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() */
41 #if !defined (HAVE_STRSIGNAL) || !defined(NO_SYS_SIGLIST_DECL)
49 /* do not include <unistd.h> here, it may interfere with g_strsignal() */
51 #include "gstrfuncs.h"
54 #include "gprintfint.h"
56 #include "gthreadprivate.h"
60 * SECTION:string_utils
61 * @title: String Utility Functions
62 * @short_description: various string-related functions
64 * This section describes a number of utility functions for creating,
65 * duplicating, and manipulating strings.
67 * Note that the functions g_printf(), g_fprintf(), g_sprintf(),
68 * g_snprintf(), g_vprintf(), g_vfprintf(), g_vsprintf() and g_vsnprintf()
69 * are declared in the header <filename>gprintf.h</filename> which is
70 * <emphasis>not</emphasis> included in <filename>glib.h</filename>
71 * (otherwise using <filename>glib.h</filename> would drag in
72 * <filename>stdio.h</filename>), so you'll have to explicitly include
73 * <literal><glib/gprintf.h></literal> in order to use the GLib
76 * <para id="string-precision">While you may use the printf() functions
77 * to format UTF-8 strings, notice that the precision of a
78 * <literal>%Ns</literal> parameter is interpreted as the
79 * number of <emphasis>bytes</emphasis>, not <emphasis>characters</emphasis>
80 * to print. On top of that, the GNU libc implementation of the printf()
81 * functions has the "feature" that it checks that the string given for
82 * the <literal>%Ns</literal> parameter consists of a whole number
83 * of characters in the current encoding. So, unless you are sure you are
84 * always going to be in an UTF-8 locale or your know your text is restricted
85 * to ASCII, avoid using <literal>%Ns</literal>. If your intention is
86 * to format strings for a certain number of columns, then
87 * <literal>%Ns</literal> is not a correct solution anyway, since it
88 * fails to take wide characters (see g_unichar_iswide()) into account.
96 * Determines whether a character is alphanumeric.
98 * Unlike the standard C library isalnum() function, this only
99 * recognizes standard ASCII letters and ignores the locale,
100 * returning %FALSE for all non-ASCII characters. Also, unlike
101 * the standard library function, this takes a <type>char</type>,
102 * not an <type>int</type>, so don't call it on %EOF, but no need to
103 * cast to #guchar before passing a possibly non-ASCII character in.
105 * Returns: %TRUE if @c is an ASCII alphanumeric character
112 * Determines whether a character is alphabetic (i.e. a letter).
114 * Unlike the standard C library isalpha() function, this only
115 * recognizes standard ASCII letters and ignores the locale,
116 * returning %FALSE for all non-ASCII characters. Also, unlike
117 * the standard library function, this takes a <type>char</type>,
118 * not an <type>int</type>, so don't call it on %EOF, but no need to
119 * cast to #guchar before passing a possibly non-ASCII character in.
121 * Returns: %TRUE if @c is an ASCII alphabetic character
128 * Determines whether a character is a control character.
130 * Unlike the standard C library iscntrl() function, this only
131 * recognizes standard ASCII control characters and ignores the
132 * locale, returning %FALSE for all non-ASCII characters. Also,
133 * unlike the standard library function, this takes a <type>char</type>,
134 * not an <type>int</type>, so don't call it on %EOF, but no need to
135 * cast to #guchar before passing a possibly non-ASCII character in.
137 * Returns: %TRUE if @c is an ASCII control character.
144 * Determines whether a character is digit (0-9).
146 * Unlike the standard C library isdigit() function, this takes
147 * a <type>char</type>, not an <type>int</type>, so don't call it
148 * on %EOF, but no need to cast to #guchar before passing a possibly
149 * non-ASCII character in.
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 <type>char</type>,
164 * not an <type>int</type>, so don't call it on %EOF, but no need
165 * to cast to #guchar before passing a possibly non-ASCII character in.
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 <type>char</type>,
180 * not an <type>int</type>, so don't call it on %EOF, but no need
181 * to worry about casting to #guchar before passing a possibly
182 * non-ASCII character in.
184 * Returns: %TRUE if @c is an ASCII lower case letter
191 * Determines whether a character is a printing character.
193 * Unlike the standard C library isprint() function, this only
194 * recognizes standard ASCII characters and ignores the locale,
195 * returning %FALSE for all non-ASCII characters. Also, unlike
196 * the standard library function, this takes a <type>char</type>,
197 * not an <type>int</type>, so don't call it on %EOF, but no need
198 * to cast to #guchar before passing a possibly non-ASCII character in.
200 * Returns: %TRUE if @c is an ASCII printing character.
207 * Determines whether a character is a punctuation character.
209 * Unlike the standard C library ispunct() function, this only
210 * recognizes standard ASCII letters and ignores the locale,
211 * returning %FALSE for all non-ASCII characters. Also, unlike
212 * the standard library function, this takes a <type>char</type>,
213 * not an <type>int</type>, so don't call it on %EOF, but no need to
214 * cast to #guchar before passing a possibly non-ASCII character in.
216 * Returns: %TRUE if @c is an ASCII punctuation character.
223 * Determines whether a character is a white-space character.
225 * Unlike the standard C library isspace() function, this only
226 * recognizes standard ASCII white-space and ignores the locale,
227 * returning %FALSE for all non-ASCII characters. Also, unlike
228 * the standard library function, this takes a <type>char</type>,
229 * not an <type>int</type>, so don't call it on %EOF, but no need to
230 * cast to #guchar before passing a possibly non-ASCII character in.
232 * Returns: %TRUE if @c is an ASCII white-space character
239 * Determines whether a character is an ASCII upper case letter.
241 * Unlike the standard C library isupper() function, this only
242 * recognizes standard ASCII letters and ignores the locale,
243 * returning %FALSE for all non-ASCII characters. Also, unlike
244 * the standard library function, this takes a <type>char</type>,
245 * not an <type>int</type>, so don't call it on %EOF, but no need to
246 * worry about casting to #guchar before passing a possibly non-ASCII
249 * Returns: %TRUE if @c is an ASCII upper case letter
256 * Determines whether a character is a hexadecimal-digit character.
258 * Unlike the standard C library isxdigit() function, this takes
259 * a <type>char</type>, not an <type>int</type>, so don't call it
260 * on %EOF, but no need to cast to #guchar before passing a
261 * possibly non-ASCII character in.
263 * Returns: %TRUE if @c is an ASCII hexadecimal-digit character.
267 * G_ASCII_DTOSTR_BUF_SIZE:
269 * A good size for a buffer to be passed into g_ascii_dtostr().
270 * It is guaranteed to be enough for all output of that function
271 * on systems with 64bit IEEE-compatible doubles.
273 * The typical usage would be something like:
275 * char buf[G_ASCII_DTOSTR_BUF_SIZE];
277 * fprintf (out, "value=%s\n", g_ascii_dtostr (buf, sizeof (buf), value));
283 * @string: a string to remove the leading and trailing whitespace from
285 * Removes leading and trailing whitespace from a string.
286 * See g_strchomp() and g_strchug().
294 * The standard delimiters, used in g_strdelimit().
297 static const guint16 ascii_table_data[256] = {
298 0x004, 0x004, 0x004, 0x004, 0x004, 0x004, 0x004, 0x004,
299 0x004, 0x104, 0x104, 0x004, 0x104, 0x104, 0x004, 0x004,
300 0x004, 0x004, 0x004, 0x004, 0x004, 0x004, 0x004, 0x004,
301 0x004, 0x004, 0x004, 0x004, 0x004, 0x004, 0x004, 0x004,
302 0x140, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0,
303 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0,
304 0x459, 0x459, 0x459, 0x459, 0x459, 0x459, 0x459, 0x459,
305 0x459, 0x459, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0,
306 0x0d0, 0x653, 0x653, 0x653, 0x653, 0x653, 0x653, 0x253,
307 0x253, 0x253, 0x253, 0x253, 0x253, 0x253, 0x253, 0x253,
308 0x253, 0x253, 0x253, 0x253, 0x253, 0x253, 0x253, 0x253,
309 0x253, 0x253, 0x253, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0,
310 0x0d0, 0x473, 0x473, 0x473, 0x473, 0x473, 0x473, 0x073,
311 0x073, 0x073, 0x073, 0x073, 0x073, 0x073, 0x073, 0x073,
312 0x073, 0x073, 0x073, 0x073, 0x073, 0x073, 0x073, 0x073,
313 0x073, 0x073, 0x073, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x004
314 /* the upper 128 are all zeroes */
317 const guint16 * const g_ascii_table = ascii_table_data;
319 #ifdef HAVE_NEWLOCALE
323 static gsize initialized = FALSE;
324 static locale_t C_locale = NULL;
326 if (g_once_init_enter (&initialized))
328 C_locale = newlocale (LC_ALL_MASK, "C", NULL);
329 g_once_init_leave (&initialized, TRUE);
338 * @str: the string to duplicate
340 * Duplicates a string. If @str is %NULL it returns %NULL.
341 * The returned string should be freed with g_free()
342 * when no longer needed.
344 * Returns: a newly-allocated copy of @str
347 g_strdup (const gchar *str)
354 length = strlen (str) + 1;
355 new_str = g_new (char, length);
356 memcpy (new_str, str, length);
366 * @mem: the memory to copy.
367 * @byte_size: the number of bytes to copy.
369 * Allocates @byte_size bytes of memory, and copies @byte_size bytes into it
370 * from @mem. If @mem is %NULL it returns %NULL.
372 * Returns: a pointer to the newly-allocated copy of the memory, or %NULL if @mem
376 g_memdup (gconstpointer mem,
383 new_mem = g_malloc (byte_size);
384 memcpy (new_mem, mem, byte_size);
394 * @str: the string to duplicate
395 * @n: the maximum number of bytes to copy from @str
397 * Duplicates the first @n bytes of a string, returning a newly-allocated
398 * buffer @n + 1 bytes long which will always be nul-terminated.
399 * If @str is less than @n bytes long the buffer is padded with nuls.
400 * If @str is %NULL it returns %NULL.
401 * The returned value should be freed when no longer needed.
404 * To copy a number of characters from a UTF-8 encoded string, use
405 * g_utf8_strncpy() instead.
408 * Returns: a newly-allocated buffer containing the first @n bytes
409 * of @str, nul-terminated
412 g_strndup (const gchar *str,
419 new_str = g_new (gchar, n + 1);
420 strncpy (new_str, str, n);
431 * @length: the length of the new string
432 * @fill_char: the byte to fill the string with
434 * Creates a new string @length bytes long filled with @fill_char.
435 * The returned string should be freed when no longer needed.
437 * Returns: a newly-allocated string filled the @fill_char
440 g_strnfill (gsize length,
445 str = g_new (gchar, length + 1);
446 memset (str, (guchar)fill_char, length);
454 * @dest: destination buffer.
455 * @src: source string.
457 * Copies a nul-terminated string into the dest buffer, include the
458 * trailing nul, and return a pointer to the trailing nul byte.
459 * This is useful for concatenating multiple strings together
460 * without having to repeatedly scan for the end.
462 * Return value: a pointer to trailing nul byte.
465 g_stpcpy (gchar *dest,
469 g_return_val_if_fail (dest != NULL, NULL);
470 g_return_val_if_fail (src != NULL, NULL);
471 return stpcpy (dest, src);
473 register gchar *d = dest;
474 register const gchar *s = src;
476 g_return_val_if_fail (dest != NULL, NULL);
477 g_return_val_if_fail (src != NULL, NULL);
480 while (*s++ != '\0');
488 * @format: a standard printf() format string, but notice
489 * <link linkend="string-precision">string precision pitfalls</link>
490 * @args: the list of parameters to insert into the format string
492 * Similar to the standard C vsprintf() function but safer, since it
493 * calculates the maximum space required and allocates memory to hold
494 * the result. The returned string should be freed with g_free() when
497 * See also g_vasprintf(), which offers the same functionality, but
498 * additionally returns the length of the allocated string.
500 * Returns: a newly-allocated string holding the result
503 g_strdup_vprintf (const gchar *format,
506 gchar *string = NULL;
508 g_vasprintf (&string, format, args);
515 * @format: a standard printf() format string, but notice
516 * <link linkend="string-precision">string precision pitfalls</link>
517 * @...: the parameters to insert into the format string
519 * Similar to the standard C sprintf() function but safer, since it
520 * calculates the maximum space required and allocates memory to hold
521 * the result. The returned string should be freed with g_free() when no
524 * Returns: a newly-allocated string holding the result
527 g_strdup_printf (const gchar *format,
533 va_start (args, format);
534 buffer = g_strdup_vprintf (format, args);
542 * @string1: the first string to add, which must not be %NULL
543 * @...: a %NULL-terminated list of strings to append to the string
545 * Concatenates all of the given strings into one long string.
546 * The returned string should be freed with g_free() when no longer needed.
548 * Note that this function is usually not the right function to use to
549 * assemble a translated message from pieces, since proper translation
550 * often requires the pieces to be reordered.
552 * <warning><para>The variable argument list <emphasis>must</emphasis> end
553 * with %NULL. If you forget the %NULL, g_strconcat() will start appending
554 * random memory junk to your string.</para></warning>
556 * Returns: a newly-allocated string containing all the string arguments
559 g_strconcat (const gchar *string1, ...)
570 l = 1 + strlen (string1);
571 va_start (args, string1);
572 s = va_arg (args, gchar*);
576 s = va_arg (args, gchar*);
580 concat = g_new (gchar, l);
583 ptr = g_stpcpy (ptr, string1);
584 va_start (args, string1);
585 s = va_arg (args, gchar*);
588 ptr = g_stpcpy (ptr, s);
589 s = va_arg (args, gchar*);
598 * @nptr: the string to convert to a numeric value.
599 * @endptr: if non-%NULL, it returns the character after
600 * the last character used in the conversion.
602 * Converts a string to a #gdouble value.
603 * It calls the standard strtod() function to handle the conversion, but
604 * if the string is not completely converted it attempts the conversion
605 * again with g_ascii_strtod(), and returns the best match.
607 * This function should seldom be used. The normal situation when reading
608 * numbers not for human consumption is to use g_ascii_strtod(). Only when
609 * you know that you must expect both locale formatted and C formatted numbers
610 * should you use this. Make sure that you don't pass strings such as comma
611 * separated lists of values, since the commas may be interpreted as a decimal
612 * point in some locales, causing unexpected results.
614 * Return value: the #gdouble value.
617 g_strtod (const gchar *nptr,
625 g_return_val_if_fail (nptr != NULL, 0);
630 val_1 = strtod (nptr, &fail_pos_1);
632 if (fail_pos_1 && fail_pos_1[0] != 0)
633 val_2 = g_ascii_strtod (nptr, &fail_pos_2);
635 if (!fail_pos_1 || fail_pos_1[0] == 0 || fail_pos_1 >= fail_pos_2)
638 *endptr = fail_pos_1;
644 *endptr = fail_pos_2;
651 * @nptr: the string to convert to a numeric value.
652 * @endptr: if non-%NULL, it returns the character after
653 * the last character used in the conversion.
655 * Converts a string to a #gdouble value.
657 * This function behaves like the standard strtod() function
658 * does in the C locale. It does this without actually changing
659 * the current locale, since that would not be thread-safe.
660 * A limitation of the implementation is that this function
661 * will still accept localized versions of infinities and NANs.
663 * This function is typically used when reading configuration
664 * files or other non-user input that should be locale independent.
665 * To handle input from the user you should normally use the
666 * locale-sensitive system strtod() function.
668 * To convert from a #gdouble to a string in a locale-insensitive
669 * way, use g_ascii_dtostr().
671 * If the correct value would cause overflow, plus or minus %HUGE_VAL
672 * is returned (according to the sign of the value), and %ERANGE is
673 * stored in %errno. If the correct value would cause underflow,
674 * zero is returned and %ERANGE is stored in %errno.
676 * This function resets %errno before calling strtod() so that
677 * you can reliably detect overflow and underflow.
679 * Return value: the #gdouble value.
682 g_ascii_strtod (const gchar *nptr,
686 return strtod_l (nptr, endptr, get_C_locale ());
690 struct lconv *locale_data;
691 const char *decimal_point;
692 int decimal_point_len;
693 const char *p, *decimal_point_pos;
694 const char *end = NULL; /* Silence gcc */
697 g_return_val_if_fail (nptr != NULL, 0);
701 locale_data = localeconv ();
702 decimal_point = locale_data->decimal_point;
703 decimal_point_len = strlen (decimal_point);
705 g_assert (decimal_point_len != 0);
707 decimal_point_pos = NULL;
710 if (decimal_point[0] != '.' ||
711 decimal_point[1] != 0)
714 /* Skip leading space */
715 while (g_ascii_isspace (*p))
718 /* Skip leading optional sign */
719 if (*p == '+' || *p == '-')
723 (p[1] == 'x' || p[1] == 'X'))
726 /* HEX - find the (optional) decimal point */
728 while (g_ascii_isxdigit (*p))
732 decimal_point_pos = p++;
734 while (g_ascii_isxdigit (*p))
737 if (*p == 'p' || *p == 'P')
739 if (*p == '+' || *p == '-')
741 while (g_ascii_isdigit (*p))
746 else if (g_ascii_isdigit (*p) || *p == '.')
748 while (g_ascii_isdigit (*p))
752 decimal_point_pos = p++;
754 while (g_ascii_isdigit (*p))
757 if (*p == 'e' || *p == 'E')
759 if (*p == '+' || *p == '-')
761 while (g_ascii_isdigit (*p))
766 /* For the other cases, we need not convert the decimal point */
769 if (decimal_point_pos)
773 /* We need to convert the '.' to the locale specific decimal point */
774 copy = g_malloc (end - nptr + 1 + decimal_point_len);
777 memcpy (c, nptr, decimal_point_pos - nptr);
778 c += decimal_point_pos - nptr;
779 memcpy (c, decimal_point, decimal_point_len);
780 c += decimal_point_len;
781 memcpy (c, decimal_point_pos + 1, end - (decimal_point_pos + 1));
782 c += end - (decimal_point_pos + 1);
786 val = strtod (copy, &fail_pos);
787 strtod_errno = errno;
791 if (fail_pos - copy > decimal_point_pos - nptr)
792 fail_pos = (char *)nptr + (fail_pos - copy) - (decimal_point_len - 1);
794 fail_pos = (char *)nptr + (fail_pos - copy);
804 copy = g_malloc (end - (char *)nptr + 1);
805 memcpy (copy, nptr, end - nptr);
806 *(copy + (end - (char *)nptr)) = 0;
809 val = strtod (copy, &fail_pos);
810 strtod_errno = errno;
814 fail_pos = (char *)nptr + (fail_pos - copy);
822 val = strtod (nptr, &fail_pos);
823 strtod_errno = errno;
829 errno = strtod_errno;
838 * @buffer: A buffer to place the resulting string in
839 * @buf_len: The length of the buffer.
840 * @d: The #gdouble to convert
842 * Converts a #gdouble to a string, using the '.' as
845 * This functions generates enough precision that converting
846 * the string back using g_ascii_strtod() gives the same machine-number
847 * (on machines with IEEE compatible 64bit doubles). It is
848 * guaranteed that the size of the resulting string will never
849 * be larger than @G_ASCII_DTOSTR_BUF_SIZE bytes.
851 * Return value: The pointer to the buffer with the converted string.
854 g_ascii_dtostr (gchar *buffer,
858 return g_ascii_formatd (buffer, buf_len, "%.17g", d);
863 * @buffer: A buffer to place the resulting string in
864 * @buf_len: The length of the buffer.
865 * @format: The printf()-style format to use for the
866 * code to use for converting.
867 * @d: The #gdouble to convert
869 * Converts a #gdouble to a string, using the '.' as
870 * decimal point. To format the number you pass in
871 * a printf()-style format string. Allowed conversion
872 * specifiers are 'e', 'E', 'f', 'F', 'g' and 'G'.
874 * If you just want to want to serialize the value into a
875 * string, use g_ascii_dtostr().
877 * Return value: The pointer to the buffer with the converted string.
880 g_ascii_formatd (gchar *buffer,
885 #ifdef HAVE_USELOCALE
888 old_locale = uselocale (get_C_locale ());
889 _g_snprintf (buffer, buf_len, format, d);
890 uselocale (old_locale);
894 struct lconv *locale_data;
895 const char *decimal_point;
896 int decimal_point_len;
901 g_return_val_if_fail (buffer != NULL, NULL);
902 g_return_val_if_fail (format[0] == '%', NULL);
903 g_return_val_if_fail (strpbrk (format + 1, "'l%") == NULL, NULL);
905 format_char = format[strlen (format) - 1];
907 g_return_val_if_fail (format_char == 'e' || format_char == 'E' ||
908 format_char == 'f' || format_char == 'F' ||
909 format_char == 'g' || format_char == 'G',
912 if (format[0] != '%')
915 if (strpbrk (format + 1, "'l%"))
918 if (!(format_char == 'e' || format_char == 'E' ||
919 format_char == 'f' || format_char == 'F' ||
920 format_char == 'g' || format_char == 'G'))
923 _g_snprintf (buffer, buf_len, format, d);
925 locale_data = localeconv ();
926 decimal_point = locale_data->decimal_point;
927 decimal_point_len = strlen (decimal_point);
929 g_assert (decimal_point_len != 0);
931 if (decimal_point[0] != '.' ||
932 decimal_point[1] != 0)
936 while (g_ascii_isspace (*p))
939 if (*p == '+' || *p == '-')
942 while (isdigit ((guchar)*p))
945 if (strncmp (p, decimal_point, decimal_point_len) == 0)
949 if (decimal_point_len > 1)
951 rest_len = strlen (p + (decimal_point_len-1));
952 memmove (p, p + (decimal_point_len-1), rest_len);
962 #define ISSPACE(c) ((c) == ' ' || (c) == '\f' || (c) == '\n' || \
963 (c) == '\r' || (c) == '\t' || (c) == '\v')
964 #define ISUPPER(c) ((c) >= 'A' && (c) <= 'Z')
965 #define ISLOWER(c) ((c) >= 'a' && (c) <= 'z')
966 #define ISALPHA(c) (ISUPPER (c) || ISLOWER (c))
967 #define TOUPPER(c) (ISLOWER (c) ? (c) - 'a' + 'A' : (c))
968 #define TOLOWER(c) (ISUPPER (c) ? (c) - 'A' + 'a' : (c))
970 #if !defined(HAVE_STRTOLL_L) || !defined(HAVE_STRTOULL_L)
973 g_parse_long_long (const gchar *nptr,
974 const gchar **endptr,
978 /* this code is based on on the strtol(3) code from GNU libc released under
979 * the GNU Lesser General Public License.
981 * Copyright (C) 1991,92,94,95,96,97,98,99,2000,01,02
982 * Free Software Foundation, Inc.
988 const gchar *s, *save;
991 g_return_val_if_fail (nptr != NULL, 0);
994 if (base == 1 || base > 36)
1004 /* Skip white space. */
1005 while (ISSPACE (*s))
1008 if (G_UNLIKELY (!*s))
1011 /* Check for a sign. */
1020 /* Recognize number prefix and if BASE is zero, figure it out ourselves. */
1023 if ((base == 0 || base == 16) && TOUPPER (s[1]) == 'X')
1034 /* Save the pointer so we can check later if anything happened. */
1036 cutoff = G_MAXUINT64 / base;
1037 cutlim = G_MAXUINT64 % base;
1044 if (c >= '0' && c <= '9')
1046 else if (ISALPHA (c))
1047 c = TOUPPER (c) - 'A' + 10;
1052 /* Check for overflow. */
1053 if (ui64 > cutoff || (ui64 == cutoff && c > cutlim))
1062 /* Check if anything actually happened. */
1066 /* Store in ENDPTR the address of one character
1067 past the last character we converted. */
1071 if (G_UNLIKELY (overflow))
1080 /* We must handle a special case here: the base is 0 or 16 and the
1081 first two characters are '0' and 'x', but the rest are no
1082 hexadecimal digits. This is no error case. We return 0 and
1083 ENDPTR points to the `x`. */
1086 if (save - nptr >= 2 && TOUPPER (save[-1]) == 'X'
1088 *endptr = &save[-1];
1090 /* There was no number to convert. */
1099 * @nptr: the string to convert to a numeric value.
1100 * @endptr: if non-%NULL, it returns the character after
1101 * the last character used in the conversion.
1102 * @base: to be used for the conversion, 2..36 or 0
1104 * Converts a string to a #guint64 value.
1105 * This function behaves like the standard strtoull() function
1106 * does in the C locale. It does this without actually
1107 * changing the current locale, since that would not be
1110 * This function is typically used when reading configuration
1111 * files or other non-user input that should be locale independent.
1112 * To handle input from the user you should normally use the
1113 * locale-sensitive system strtoull() function.
1115 * If the correct value would cause overflow, %G_MAXUINT64
1116 * is returned, and %ERANGE is stored in %errno. If the base is
1117 * outside the valid range, zero is returned, and %EINVAL is stored
1118 * in %errno. If the string conversion fails, zero is returned, and
1119 * @endptr returns @nptr (if @endptr is non-%NULL).
1121 * Return value: the #guint64 value or zero on error.
1126 g_ascii_strtoull (const gchar *nptr,
1130 #ifdef HAVE_STRTOULL_L
1131 return strtoull_l (nptr, endptr, base, get_C_locale ());
1136 result = g_parse_long_long (nptr, (const gchar **) endptr, base, &negative);
1138 /* Return the result of the appropriate sign. */
1139 return negative ? -result : result;
1145 * @nptr: the string to convert to a numeric value.
1146 * @endptr: if non-%NULL, it returns the character after
1147 * the last character used in the conversion.
1148 * @base: to be used for the conversion, 2..36 or 0
1150 * Converts a string to a #gint64 value.
1151 * This function behaves like the standard strtoll() function
1152 * does in the C locale. It does this without actually
1153 * changing the current locale, since that would not be
1156 * This function is typically used when reading configuration
1157 * files or other non-user input that should be locale independent.
1158 * To handle input from the user you should normally use the
1159 * locale-sensitive system strtoll() function.
1161 * If the correct value would cause overflow, %G_MAXINT64 or %G_MININT64
1162 * is returned, and %ERANGE is stored in %errno. If the base is
1163 * outside the valid range, zero is returned, and %EINVAL is stored
1164 * in %errno. If the string conversion fails, zero is returned, and
1165 * @endptr returns @nptr (if @endptr is non-%NULL).
1167 * Return value: the #gint64 value or zero on error.
1172 g_ascii_strtoll (const gchar *nptr,
1176 #ifdef HAVE_STRTOLL_L
1177 return strtoll_l (nptr, endptr, base, get_C_locale ());
1182 result = g_parse_long_long (nptr, (const gchar **) endptr, base, &negative);
1184 if (negative && result > (guint64) G_MININT64)
1189 else if (!negative && result > (guint64) G_MAXINT64)
1195 return - (gint64) result;
1197 return (gint64) result;
1203 * @errnum: the system error number. See the standard C %errno
1206 * Returns a string corresponding to the given error code, e.g.
1207 * "no such process". You should use this function in preference to
1208 * strerror(), because it returns a string in UTF-8 encoding, and since
1209 * not all platforms support the strerror() function.
1211 * Returns: a UTF-8 string describing the error code. If the error code
1212 * is unknown, it returns "unknown error (<code>)". The string
1213 * can only be used until the next call to g_strerror()
1216 g_strerror (gint errnum)
1218 static GStaticPrivate msg_private = G_STATIC_PRIVATE_INIT;
1220 int saved_errno = errno;
1222 #ifdef HAVE_STRERROR
1223 const char *msg_locale;
1225 msg_locale = strerror (errnum);
1226 if (g_get_charset (NULL))
1228 errno = saved_errno;
1233 gchar *msg_utf8 = g_locale_to_utf8 (msg_locale, -1, NULL, NULL, NULL);
1236 /* Stick in the quark table so that we can return a static result
1238 GQuark msg_quark = g_quark_from_string (msg_utf8);
1241 msg_utf8 = (gchar *) g_quark_to_string (msg_quark);
1242 errno = saved_errno;
1246 #elif NO_SYS_ERRLIST
1250 case E2BIG: return "argument list too long";
1253 case EACCES: return "permission denied";
1256 case EADDRINUSE: return "address already in use";
1258 #ifdef EADDRNOTAVAIL
1259 case EADDRNOTAVAIL: return "can't assign requested address";
1262 case EADV: return "advertise error";
1265 case EAFNOSUPPORT: return "address family not supported by protocol family";
1268 case EAGAIN: return "try again";
1271 case EALIGN: return "EALIGN";
1274 case EALREADY: return "operation already in progress";
1277 case EBADE: return "bad exchange descriptor";
1280 case EBADF: return "bad file number";
1283 case EBADFD: return "file descriptor in bad state";
1286 case EBADMSG: return "not a data message";
1289 case EBADR: return "bad request descriptor";
1292 case EBADRPC: return "RPC structure is bad";
1295 case EBADRQC: return "bad request code";
1298 case EBADSLT: return "invalid slot";
1301 case EBFONT: return "bad font file format";
1304 case EBUSY: return "mount device busy";
1307 case ECHILD: return "no children";
1310 case ECHRNG: return "channel number out of range";
1313 case ECOMM: return "communication error on send";
1316 case ECONNABORTED: return "software caused connection abort";
1319 case ECONNREFUSED: return "connection refused";
1322 case ECONNRESET: return "connection reset by peer";
1324 #if defined(EDEADLK) && (!defined(EWOULDBLOCK) || (EDEADLK != EWOULDBLOCK))
1325 case EDEADLK: return "resource deadlock avoided";
1327 #if defined(EDEADLOCK) && (!defined(EDEADLK) || (EDEADLOCK != EDEADLK))
1328 case EDEADLOCK: return "resource deadlock avoided";
1331 case EDESTADDRREQ: return "destination address required";
1334 case EDIRTY: return "mounting a dirty fs w/o force";
1337 case EDOM: return "math argument out of range";
1340 case EDOTDOT: return "cross mount point";
1343 case EDQUOT: return "disk quota exceeded";
1346 case EDUPPKG: return "duplicate package name";
1349 case EEXIST: return "file already exists";
1352 case EFAULT: return "bad address in system call argument";
1355 case EFBIG: return "file too large";
1358 case EHOSTDOWN: return "host is down";
1361 case EHOSTUNREACH: return "host is unreachable";
1364 case EIDRM: return "identifier removed";
1367 case EINIT: return "initialization error";
1370 case EINPROGRESS: return "operation now in progress";
1373 case EINTR: return "interrupted system call";
1376 case EINVAL: return "invalid argument";
1379 case EIO: return "I/O error";
1382 case EISCONN: return "socket is already connected";
1385 case EISDIR: return "is a directory";
1388 case EISNAM: return "is a name file";
1391 case ELBIN: return "ELBIN";
1394 case EL2HLT: return "level 2 halted";
1397 case EL2NSYNC: return "level 2 not synchronized";
1400 case EL3HLT: return "level 3 halted";
1403 case EL3RST: return "level 3 reset";
1406 case ELIBACC: return "can not access a needed shared library";
1409 case ELIBBAD: return "accessing a corrupted shared library";
1412 case ELIBEXEC: return "can not exec a shared library directly";
1415 case ELIBMAX: return "attempting to link in more shared libraries than system limit";
1418 case ELIBSCN: return ".lib section in a.out corrupted";
1421 case ELNRNG: return "link number out of range";
1424 case ELOOP: return "too many levels of symbolic links";
1427 case EMFILE: return "too many open files";
1430 case EMLINK: return "too many links";
1433 case EMSGSIZE: return "message too long";
1436 case EMULTIHOP: return "multihop attempted";
1439 case ENAMETOOLONG: return "file name too long";
1442 case ENAVAIL: return "not available";
1445 case ENET: return "ENET";
1448 case ENETDOWN: return "network is down";
1451 case ENETRESET: return "network dropped connection on reset";
1454 case ENETUNREACH: return "network is unreachable";
1457 case ENFILE: return "file table overflow";
1460 case ENOANO: return "anode table overflow";
1462 #if defined(ENOBUFS) && (!defined(ENOSR) || (ENOBUFS != ENOSR))
1463 case ENOBUFS: return "no buffer space available";
1466 case ENOCSI: return "no CSI structure available";
1469 case ENODATA: return "no data available";
1472 case ENODEV: return "no such device";
1475 case ENOENT: return "no such file or directory";
1478 case ENOEXEC: return "exec format error";
1481 case ENOLCK: return "no locks available";
1484 case ENOLINK: return "link has be severed";
1487 case ENOMEM: return "not enough memory";
1490 case ENOMSG: return "no message of desired type";
1493 case ENONET: return "machine is not on the network";
1496 case ENOPKG: return "package not installed";
1499 case ENOPROTOOPT: return "bad proocol option";
1502 case ENOSPC: return "no space left on device";
1505 case ENOSR: return "out of stream resources";
1508 case ENOSTR: return "not a stream device";
1511 case ENOSYM: return "unresolved symbol name";
1514 case ENOSYS: return "function not implemented";
1517 case ENOTBLK: return "block device required";
1520 case ENOTCONN: return "socket is not connected";
1523 case ENOTDIR: return "not a directory";
1526 case ENOTEMPTY: return "directory not empty";
1529 case ENOTNAM: return "not a name file";
1532 case ENOTSOCK: return "socket operation on non-socket";
1535 case ENOTTY: return "inappropriate device for ioctl";
1538 case ENOTUNIQ: return "name not unique on network";
1541 case ENXIO: return "no such device or address";
1544 case EOPNOTSUPP: return "operation not supported on socket";
1547 case EPERM: return "not owner";
1550 case EPFNOSUPPORT: return "protocol family not supported";
1553 case EPIPE: return "broken pipe";
1556 case EPROCLIM: return "too many processes";
1559 case EPROCUNAVAIL: return "bad procedure for program";
1561 #ifdef EPROGMISMATCH
1562 case EPROGMISMATCH: return "program version wrong";
1565 case EPROGUNAVAIL: return "RPC program not available";
1568 case EPROTO: return "protocol error";
1570 #ifdef EPROTONOSUPPORT
1571 case EPROTONOSUPPORT: return "protocol not suppored";
1574 case EPROTOTYPE: return "protocol wrong type for socket";
1577 case ERANGE: return "math result unrepresentable";
1579 #if defined(EREFUSED) && (!defined(ECONNREFUSED) || (EREFUSED != ECONNREFUSED))
1580 case EREFUSED: return "EREFUSED";
1583 case EREMCHG: return "remote address changed";
1586 case EREMDEV: return "remote device";
1589 case EREMOTE: return "pathname hit remote file system";
1592 case EREMOTEIO: return "remote i/o error";
1594 #ifdef EREMOTERELEASE
1595 case EREMOTERELEASE: return "EREMOTERELEASE";
1598 case EROFS: return "read-only file system";
1601 case ERPCMISMATCH: return "RPC version is wrong";
1604 case ERREMOTE: return "object is remote";
1607 case ESHUTDOWN: return "can't send afer socket shutdown";
1609 #ifdef ESOCKTNOSUPPORT
1610 case ESOCKTNOSUPPORT: return "socket type not supported";
1613 case ESPIPE: return "invalid seek";
1616 case ESRCH: return "no such process";
1619 case ESRMNT: return "srmount error";
1622 case ESTALE: return "stale remote file handle";
1625 case ESUCCESS: return "Error 0";
1628 case ETIME: return "timer expired";
1631 case ETIMEDOUT: return "connection timed out";
1634 case ETOOMANYREFS: return "too many references: can't splice";
1637 case ETXTBSY: return "text file or pseudo-device busy";
1640 case EUCLEAN: return "structure needs cleaning";
1643 case EUNATCH: return "protocol driver not attached";
1646 case EUSERS: return "too many users";
1649 case EVERSION: return "version mismatch";
1651 #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
1652 case EWOULDBLOCK: return "operation would block";
1655 case EXDEV: return "cross-domain link";
1658 case EXFULL: return "message tables full";
1661 #else /* NO_SYS_ERRLIST */
1662 extern int sys_nerr;
1663 extern char *sys_errlist[];
1665 if ((errnum > 0) && (errnum <= sys_nerr))
1666 return sys_errlist [errnum];
1667 #endif /* NO_SYS_ERRLIST */
1669 msg = g_static_private_get (&msg_private);
1672 msg = g_new (gchar, 64);
1673 g_static_private_set (&msg_private, msg, g_free);
1676 _g_sprintf (msg, "unknown error (%d)", errnum);
1678 errno = saved_errno;
1684 * @signum: the signal number. See the <literal>signal</literal>
1687 * Returns a string describing the given signal, e.g. "Segmentation fault".
1688 * You should use this function in preference to strsignal(), because it
1689 * returns a string in UTF-8 encoding, and since not all platforms support
1690 * the strsignal() function.
1692 * Returns: a UTF-8 string describing the signal. If the signal is unknown,
1693 * it returns "unknown signal (<signum>)". The string can only be
1694 * used until the next call to g_strsignal()
1697 g_strsignal (gint signum)
1699 static GStaticPrivate msg_private = G_STATIC_PRIVATE_INIT;
1702 #ifdef HAVE_STRSIGNAL
1703 const char *msg_locale;
1705 #if defined(G_OS_BEOS) || defined(G_WITH_CYGWIN)
1706 extern const char *strsignal(int);
1708 /* this is declared differently (const) in string.h on BeOS */
1709 extern char *strsignal (int sig);
1710 #endif /* !G_OS_BEOS && !G_WITH_CYGWIN */
1711 msg_locale = strsignal (signum);
1712 if (g_get_charset (NULL))
1716 gchar *msg_utf8 = g_locale_to_utf8 (msg_locale, -1, NULL, NULL, NULL);
1719 /* Stick in the quark table so that we can return a static result
1721 GQuark msg_quark = g_quark_from_string (msg_utf8);
1724 return g_quark_to_string (msg_quark);
1727 #elif NO_SYS_SIGLIST
1731 case SIGHUP: return "Hangup";
1734 case SIGINT: return "Interrupt";
1737 case SIGQUIT: return "Quit";
1740 case SIGILL: return "Illegal instruction";
1743 case SIGTRAP: return "Trace/breakpoint trap";
1746 case SIGABRT: return "IOT trap/Abort";
1749 case SIGBUS: return "Bus error";
1752 case SIGFPE: return "Floating point exception";
1755 case SIGKILL: return "Killed";
1758 case SIGUSR1: return "User defined signal 1";
1761 case SIGSEGV: return "Segmentation fault";
1764 case SIGUSR2: return "User defined signal 2";
1767 case SIGPIPE: return "Broken pipe";
1770 case SIGALRM: return "Alarm clock";
1773 case SIGTERM: return "Terminated";
1776 case SIGSTKFLT: return "Stack fault";
1779 case SIGCHLD: return "Child exited";
1782 case SIGCONT: return "Continued";
1785 case SIGSTOP: return "Stopped (signal)";
1788 case SIGTSTP: return "Stopped";
1791 case SIGTTIN: return "Stopped (tty input)";
1794 case SIGTTOU: return "Stopped (tty output)";
1797 case SIGURG: return "Urgent condition";
1800 case SIGXCPU: return "CPU time limit exceeded";
1803 case SIGXFSZ: return "File size limit exceeded";
1806 case SIGVTALRM: return "Virtual time alarm";
1809 case SIGPROF: return "Profile signal";
1812 case SIGWINCH: return "Window size changed";
1815 case SIGIO: return "Possible I/O";
1818 case SIGPWR: return "Power failure";
1821 case SIGUNUSED: return "Unused signal";
1824 #else /* NO_SYS_SIGLIST */
1826 #ifdef NO_SYS_SIGLIST_DECL
1827 extern char *sys_siglist[]; /*(see Tue Jan 19 00:44:24 1999 in changelog)*/
1830 return (char*) /* this function should return const --josh */ sys_siglist [signum];
1831 #endif /* NO_SYS_SIGLIST */
1833 msg = g_static_private_get (&msg_private);
1836 msg = g_new (gchar, 64);
1837 g_static_private_set (&msg_private, msg, g_free);
1840 _g_sprintf (msg, "unknown signal (%d)", signum);
1845 /* Functions g_strlcpy and g_strlcat were originally developed by
1846 * Todd C. Miller <Todd.Miller@courtesan.com> to simplify writing secure code.
1847 * See http://www.openbsd.org/cgi-bin/man.cgi?query=strlcpy
1848 * for more information.
1852 /* Use the native ones, if available; they might be implemented in assembly */
1854 g_strlcpy (gchar *dest,
1858 g_return_val_if_fail (dest != NULL, 0);
1859 g_return_val_if_fail (src != NULL, 0);
1861 return strlcpy (dest, src, dest_size);
1865 g_strlcat (gchar *dest,
1869 g_return_val_if_fail (dest != NULL, 0);
1870 g_return_val_if_fail (src != NULL, 0);
1872 return strlcat (dest, src, dest_size);
1875 #else /* ! HAVE_STRLCPY */
1878 * @dest: destination buffer
1879 * @src: source buffer
1880 * @dest_size: length of @dest in bytes
1882 * Portability wrapper that calls strlcpy() on systems which have it,
1883 * and emulates strlcpy() otherwise. Copies @src to @dest; @dest is
1884 * guaranteed to be nul-terminated; @src must be nul-terminated;
1885 * @dest_size is the buffer size, not the number of chars to copy.
1887 * At most dest_size - 1 characters will be copied. Always nul-terminates
1888 * (unless dest_size == 0). This function does <emphasis>not</emphasis>
1889 * allocate memory. Unlike strncpy(), this function doesn't pad dest (so
1890 * it's often faster). It returns the size of the attempted result,
1891 * strlen (src), so if @retval >= @dest_size, truncation occurred.
1893 * <note><para>Caveat: strlcpy() is supposedly more secure than
1894 * strcpy() or strncpy(), but if you really want to avoid screwups,
1895 * g_strdup() is an even better idea.</para></note>
1897 * Returns: length of @src
1900 g_strlcpy (gchar *dest,
1904 register gchar *d = dest;
1905 register const gchar *s = src;
1906 register gsize n = dest_size;
1908 g_return_val_if_fail (dest != NULL, 0);
1909 g_return_val_if_fail (src != NULL, 0);
1911 /* Copy as many bytes as will fit */
1912 if (n != 0 && --n != 0)
1915 register gchar c = *s++;
1923 /* If not enough room in dest, add NUL and traverse rest of src */
1932 return s - src - 1; /* count does not include NUL */
1937 * @dest: destination buffer, already containing one nul-terminated string
1938 * @src: source buffer
1939 * @dest_size: length of @dest buffer in bytes (not length of existing string
1942 * Portability wrapper that calls strlcat() on systems which have it,
1943 * and emulates it otherwise. Appends nul-terminated @src string to @dest,
1944 * guaranteeing nul-termination for @dest. The total size of @dest won't
1945 * exceed @dest_size.
1947 * At most dest_size - 1 characters will be copied.
1948 * Unlike strncat, dest_size is the full size of dest, not the space left over.
1949 * This function does NOT allocate memory.
1950 * This always NUL terminates (unless siz == 0 or there were no NUL characters
1951 * in the dest_size characters of dest to start with).
1953 * <note><para>Caveat: this is supposedly a more secure alternative to
1954 * strcat() or strncat(), but for real security g_strconcat() is harder
1955 * to mess up.</para></note>
1957 * Returns: size of attempted result, which is MIN (dest_size, strlen
1958 * (original dest)) + strlen (src), so if retval >= dest_size,
1959 * truncation occurred.
1962 g_strlcat (gchar *dest,
1966 register gchar *d = dest;
1967 register const gchar *s = src;
1968 register gsize bytes_left = dest_size;
1969 gsize dlength; /* Logically, MIN (strlen (d), dest_size) */
1971 g_return_val_if_fail (dest != NULL, 0);
1972 g_return_val_if_fail (src != NULL, 0);
1974 /* Find the end of dst and adjust bytes left but don't go past end */
1975 while (*d != 0 && bytes_left-- != 0)
1978 bytes_left = dest_size - dlength;
1980 if (bytes_left == 0)
1981 return dlength + strlen (s);
1985 if (bytes_left != 1)
1994 return dlength + (s - src); /* count does not include NUL */
1996 #endif /* ! HAVE_STRLCPY */
2001 * @len: length of @str in bytes, or -1 if @str is nul-terminated.
2003 * Converts all upper case ASCII letters to lower case ASCII letters.
2005 * Return value: a newly-allocated string, with all the upper case
2006 * characters in @str converted to lower case, with
2007 * semantics that exactly match g_ascii_tolower(). (Note
2008 * that this is unlike the old g_strdown(), which modified
2009 * the string in place.)
2012 g_ascii_strdown (const gchar *str,
2017 g_return_val_if_fail (str != NULL, NULL);
2022 result = g_strndup (str, len);
2023 for (s = result; *s; s++)
2024 *s = g_ascii_tolower (*s);
2032 * @len: length of @str in bytes, or -1 if @str is nul-terminated.
2034 * Converts all lower case ASCII letters to upper case ASCII letters.
2036 * Return value: a newly allocated string, with all the lower case
2037 * characters in @str converted to upper case, with
2038 * semantics that exactly match g_ascii_toupper(). (Note
2039 * that this is unlike the old g_strup(), which modified
2040 * the string in place.)
2043 g_ascii_strup (const gchar *str,
2048 g_return_val_if_fail (str != NULL, NULL);
2053 result = g_strndup (str, len);
2054 for (s = result; *s; s++)
2055 *s = g_ascii_toupper (*s);
2062 * @string: the string to convert.
2064 * Converts a string to lower case.
2066 * Return value: the string
2068 * Deprecated:2.2: This function is totally broken for the reasons discussed
2069 * in the g_strncasecmp() docs - use g_ascii_strdown() or g_utf8_strdown()
2073 g_strdown (gchar *string)
2077 g_return_val_if_fail (string != NULL, NULL);
2079 s = (guchar *) string;
2088 return (gchar *) string;
2093 * @string: the string to convert.
2095 * Converts a string to upper case.
2097 * Return value: the string
2099 * Deprecated:2.2: This function is totally broken for the reasons discussed
2100 * in the g_strncasecmp() docs - use g_ascii_strup() or g_utf8_strup() instead.
2103 g_strup (gchar *string)
2107 g_return_val_if_fail (string != NULL, NULL);
2109 s = (guchar *) string;
2118 return (gchar *) string;
2123 * @string: the string to reverse
2125 * Reverses all of the bytes in a string. For example,
2126 * <literal>g_strreverse ("abcdef")</literal> will result
2129 * Note that g_strreverse() doesn't work on UTF-8 strings
2130 * containing multibyte characters. For that purpose, use
2131 * g_utf8_strreverse().
2133 * Returns: the same pointer passed in as @string
2136 g_strreverse (gchar *string)
2138 g_return_val_if_fail (string != NULL, NULL);
2142 register gchar *h, *t;
2145 t = string + strlen (string) - 1;
2164 * @c: any character.
2166 * Convert a character to ASCII lower case.
2168 * Unlike the standard C library tolower() function, this only
2169 * recognizes standard ASCII letters and ignores the locale, returning
2170 * all non-ASCII characters unchanged, even if they are lower case
2171 * letters in a particular character set. Also unlike the standard
2172 * library function, this takes and returns a char, not an int, so
2173 * don't call it on %EOF but no need to worry about casting to #guchar
2174 * before passing a possibly non-ASCII character in.
2176 * Return value: the result of converting @c to lower case.
2177 * If @c is not an ASCII upper case letter,
2178 * @c is returned unchanged.
2181 g_ascii_tolower (gchar c)
2183 return g_ascii_isupper (c) ? c - 'A' + 'a' : c;
2188 * @c: any character.
2190 * Convert a character to ASCII upper case.
2192 * Unlike the standard C library toupper() function, this only
2193 * recognizes standard ASCII letters and ignores the locale, returning
2194 * all non-ASCII characters unchanged, even if they are upper case
2195 * letters in a particular character set. Also unlike the standard
2196 * library function, this takes and returns a char, not an int, so
2197 * don't call it on %EOF but no need to worry about casting to #guchar
2198 * before passing a possibly non-ASCII character in.
2200 * Return value: the result of converting @c to upper case.
2201 * If @c is not an ASCII lower case letter,
2202 * @c is returned unchanged.
2205 g_ascii_toupper (gchar c)
2207 return g_ascii_islower (c) ? c - 'a' + 'A' : c;
2211 * g_ascii_digit_value:
2212 * @c: an ASCII character.
2214 * Determines the numeric value of a character as a decimal
2215 * digit. Differs from g_unichar_digit_value() because it takes
2216 * a char, so there's no worry about sign extension if characters
2219 * Return value: If @c is a decimal digit (according to
2220 * g_ascii_isdigit()), its numeric value. Otherwise, -1.
2223 g_ascii_digit_value (gchar c)
2225 if (g_ascii_isdigit (c))
2231 * g_ascii_xdigit_value:
2232 * @c: an ASCII character.
2234 * Determines the numeric value of a character as a hexidecimal
2235 * digit. Differs from g_unichar_xdigit_value() because it takes
2236 * a char, so there's no worry about sign extension if characters
2239 * Return value: If @c is a hex digit (according to
2240 * g_ascii_isxdigit()), its numeric value. Otherwise, -1.
2243 g_ascii_xdigit_value (gchar c)
2245 if (c >= 'A' && c <= 'F')
2246 return c - 'A' + 10;
2247 if (c >= 'a' && c <= 'f')
2248 return c - 'a' + 10;
2249 return g_ascii_digit_value (c);
2253 * g_ascii_strcasecmp:
2254 * @s1: string to compare with @s2.
2255 * @s2: string to compare with @s1.
2257 * Compare two strings, ignoring the case of ASCII characters.
2259 * Unlike the BSD strcasecmp() function, this only recognizes standard
2260 * ASCII letters and ignores the locale, treating all non-ASCII
2261 * bytes as if they are not letters.
2263 * This function should be used only on strings that are known to be
2264 * in encodings where the bytes corresponding to ASCII letters always
2265 * represent themselves. This includes UTF-8 and the ISO-8859-*
2266 * charsets, but not for instance double-byte encodings like the
2267 * Windows Codepage 932, where the trailing bytes of double-byte
2268 * characters include all ASCII letters. If you compare two CP932
2269 * strings using this function, you will get false matches.
2271 * Return value: 0 if the strings match, a negative value if @s1 < @s2,
2272 * or a positive value if @s1 > @s2.
2275 g_ascii_strcasecmp (const gchar *s1,
2280 g_return_val_if_fail (s1 != NULL, 0);
2281 g_return_val_if_fail (s2 != NULL, 0);
2285 c1 = (gint)(guchar) TOLOWER (*s1);
2286 c2 = (gint)(guchar) TOLOWER (*s2);
2292 return (((gint)(guchar) *s1) - ((gint)(guchar) *s2));
2296 * g_ascii_strncasecmp:
2297 * @s1: string to compare with @s2.
2298 * @s2: string to compare with @s1.
2299 * @n: number of characters to compare.
2301 * Compare @s1 and @s2, ignoring the case of ASCII characters and any
2302 * characters after the first @n in each string.
2304 * Unlike the BSD strcasecmp() function, this only recognizes standard
2305 * ASCII letters and ignores the locale, treating all non-ASCII
2306 * characters as if they are not letters.
2308 * The same warning as in g_ascii_strcasecmp() applies: Use this
2309 * function only on strings known to be in encodings where bytes
2310 * corresponding to ASCII letters always represent themselves.
2312 * Return value: 0 if the strings match, a negative value if @s1 < @s2,
2313 * or a positive value if @s1 > @s2.
2316 g_ascii_strncasecmp (const gchar *s1,
2322 g_return_val_if_fail (s1 != NULL, 0);
2323 g_return_val_if_fail (s2 != NULL, 0);
2325 while (n && *s1 && *s2)
2328 c1 = (gint)(guchar) TOLOWER (*s1);
2329 c2 = (gint)(guchar) TOLOWER (*s2);
2336 return (((gint) (guchar) *s1) - ((gint) (guchar) *s2));
2344 * @s2: a string to compare with @s1.
2346 * A case-insensitive string comparison, corresponding to the standard
2347 * strcasecmp() function on platforms which support it.
2349 * Return value: 0 if the strings match, a negative value if @s1 < @s2,
2350 * or a positive value if @s1 > @s2.
2352 * Deprecated:2.2: See g_strncasecmp() for a discussion of why this function
2353 * is deprecated and how to replace it.
2356 g_strcasecmp (const gchar *s1,
2359 #ifdef HAVE_STRCASECMP
2360 g_return_val_if_fail (s1 != NULL, 0);
2361 g_return_val_if_fail (s2 != NULL, 0);
2363 return strcasecmp (s1, s2);
2367 g_return_val_if_fail (s1 != NULL, 0);
2368 g_return_val_if_fail (s2 != NULL, 0);
2372 /* According to A. Cox, some platforms have islower's that
2373 * don't work right on non-uppercase
2375 c1 = isupper ((guchar)*s1) ? tolower ((guchar)*s1) : *s1;
2376 c2 = isupper ((guchar)*s2) ? tolower ((guchar)*s2) : *s2;
2382 return (((gint)(guchar) *s1) - ((gint)(guchar) *s2));
2389 * @s2: a string to compare with @s1.
2390 * @n: the maximum number of characters to compare.
2392 * A case-insensitive string comparison, corresponding to the standard
2393 * strncasecmp() function on platforms which support it.
2394 * It is similar to g_strcasecmp() except it only compares the first @n
2395 * characters of the strings.
2397 * Return value: 0 if the strings match, a negative value if @s1 < @s2,
2398 * or a positive value if @s1 > @s2.
2400 * Deprecated:2.2: The problem with g_strncasecmp() is that it does the
2401 * comparison by calling toupper()/tolower(). These functions are
2402 * locale-specific and operate on single bytes. However, it is impossible
2403 * to handle things correctly from an I18N standpoint by operating on
2404 * bytes, since characters may be multibyte. Thus g_strncasecmp() is
2405 * broken if your string is guaranteed to be ASCII, since it's
2406 * locale-sensitive, and it's broken if your string is localized, since
2407 * it doesn't work on many encodings at all, including UTF-8, EUC-JP,
2410 * There are therefore two replacement functions: g_ascii_strncasecmp(),
2411 * which only works on ASCII and is not locale-sensitive, and
2412 * g_utf8_casefold(), which is good for case-insensitive sorting of UTF-8.
2415 g_strncasecmp (const gchar *s1,
2419 #ifdef HAVE_STRNCASECMP
2420 return strncasecmp (s1, s2, n);
2424 g_return_val_if_fail (s1 != NULL, 0);
2425 g_return_val_if_fail (s2 != NULL, 0);
2427 while (n && *s1 && *s2)
2430 /* According to A. Cox, some platforms have islower's that
2431 * don't work right on non-uppercase
2433 c1 = isupper ((guchar)*s1) ? tolower ((guchar)*s1) : *s1;
2434 c2 = isupper ((guchar)*s2) ? tolower ((guchar)*s2) : *s2;
2441 return (((gint) (guchar) *s1) - ((gint) (guchar) *s2));
2449 * @string: the string to convert
2450 * @delimiters: a string containing the current delimiters, or %NULL
2451 * to use the standard delimiters defined in #G_STR_DELIMITERS
2452 * @new_delimiter: the new delimiter character
2454 * Converts any delimiter characters in @string to @new_delimiter.
2455 * Any characters in @string which are found in @delimiters are
2456 * changed to the @new_delimiter character. Modifies @string in place,
2457 * and returns @string itself, not a copy. The return value is to
2458 * allow nesting such as
2460 * g_ascii_strup (g_strdelimit (str, "abc", '?'))
2466 g_strdelimit (gchar *string,
2467 const gchar *delimiters,
2472 g_return_val_if_fail (string != NULL, NULL);
2475 delimiters = G_STR_DELIMITERS;
2477 for (c = string; *c; c++)
2479 if (strchr (delimiters, *c))
2488 * @string: a nul-terminated array of bytes
2489 * @valid_chars: bytes permitted in @string
2490 * @substitutor: replacement character for disallowed bytes
2492 * For each character in @string, if the character is not in
2493 * @valid_chars, replaces the character with @substitutor.
2494 * Modifies @string in place, and return @string itself, not
2495 * a copy. The return value is to allow nesting such as
2497 * g_ascii_strup (g_strcanon (str, "abc", '?'))
2503 g_strcanon (gchar *string,
2504 const gchar *valid_chars,
2509 g_return_val_if_fail (string != NULL, NULL);
2510 g_return_val_if_fail (valid_chars != NULL, NULL);
2512 for (c = string; *c; c++)
2514 if (!strchr (valid_chars, *c))
2523 * @source: a string to compress
2525 * Replaces all escaped characters with their one byte equivalent.
2527 * This function does the reverse conversion of g_strescape().
2529 * Returns: a newly-allocated copy of @source with all escaped
2530 * character compressed
2533 g_strcompress (const gchar *source)
2535 const gchar *p = source, *octal;
2536 gchar *dest = g_malloc (strlen (source) + 1);
2547 g_warning ("g_strcompress: trailing \\");
2549 case '0': case '1': case '2': case '3': case '4':
2550 case '5': case '6': case '7':
2553 while ((p < octal + 3) && (*p >= '0') && (*p <= '7'))
2555 *q = (*q * 8) + (*p - '0');
2576 default: /* Also handles \" and \\ */
2593 * @source: a string to escape
2594 * @exceptions: a string of characters not to escape in @source
2596 * Escapes the special characters '\b', '\f', '\n', '\r', '\t', '\'
2597 * and '"' in the string @source by inserting a '\' before
2598 * them. Additionally all characters in the range 0x01-0x1F (everything
2599 * below SPACE) and in the range 0x7F-0xFF (all non-ASCII chars) are
2600 * replaced with a '\' followed by their octal representation.
2601 * Characters supplied in @exceptions are not escaped.
2603 * g_strcompress() does the reverse conversion.
2605 * Returns: a newly-allocated copy of @source with certain
2606 * characters escaped. See above.
2609 g_strescape (const gchar *source,
2610 const gchar *exceptions)
2617 g_return_val_if_fail (source != NULL, NULL);
2619 p = (guchar *) source;
2620 /* Each source byte needs maximally four destination chars (\777) */
2621 q = dest = g_malloc (strlen (source) * 4 + 1);
2623 memset (excmap, 0, 256);
2626 guchar *e = (guchar *) exceptions;
2672 if ((*p < ' ') || (*p >= 0177))
2675 *q++ = '0' + (((*p) >> 6) & 07);
2676 *q++ = '0' + (((*p) >> 3) & 07);
2677 *q++ = '0' + ((*p) & 07);
2692 * @string: a string to remove the leading whitespace from
2694 * Removes leading whitespace from a string, by moving the rest
2695 * of the characters forward.
2697 * This function doesn't allocate or reallocate any memory;
2698 * it modifies @string in place. The pointer to @string is
2699 * returned to allow the nesting of functions.
2701 * Also see g_strchomp() and g_strstrip().
2706 g_strchug (gchar *string)
2710 g_return_val_if_fail (string != NULL, NULL);
2712 for (start = (guchar*) string; *start && g_ascii_isspace (*start); start++)
2715 g_memmove (string, start, strlen ((gchar *) start) + 1);
2722 * @string: a string to remove the trailing whitespace from
2724 * Removes trailing whitespace from a string.
2726 * This function doesn't allocate or reallocate any memory;
2727 * it modifies @string in place. The pointer to @string is
2728 * returned to allow the nesting of functions.
2730 * Also see g_strchug() and g_strstrip().
2735 g_strchomp (gchar *string)
2739 g_return_val_if_fail (string != NULL, NULL);
2741 len = strlen (string);
2744 if (g_ascii_isspace ((guchar) string[len]))
2755 * @string: a string to split
2756 * @delimiter: a string which specifies the places at which to split
2757 * the string. The delimiter is not included in any of the resulting
2758 * strings, unless @max_tokens is reached.
2759 * @max_tokens: the maximum number of pieces to split @string into.
2760 * If this is less than 1, the string is split completely.
2762 * Splits a string into a maximum of @max_tokens pieces, using the given
2763 * @delimiter. If @max_tokens is reached, the remainder of @string is
2764 * appended to the last token.
2766 * As a special case, the result of splitting the empty string "" is an empty
2767 * vector, not a vector containing a single string. The reason for this
2768 * special case is that being able to represent a empty vector is typically
2769 * more useful than consistent handling of empty elements. If you do need
2770 * to represent empty elements, you'll need to check for the empty string
2771 * before calling g_strsplit().
2773 * Return value: a newly-allocated %NULL-terminated array of strings. Use
2774 * g_strfreev() to free it.
2777 g_strsplit (const gchar *string,
2778 const gchar *delimiter,
2781 GSList *string_list = NULL, *slist;
2782 gchar **str_array, *s;
2784 const gchar *remainder;
2786 g_return_val_if_fail (string != NULL, NULL);
2787 g_return_val_if_fail (delimiter != NULL, NULL);
2788 g_return_val_if_fail (delimiter[0] != '\0', NULL);
2791 max_tokens = G_MAXINT;
2794 s = strstr (remainder, delimiter);
2797 gsize delimiter_len = strlen (delimiter);
2799 while (--max_tokens && s)
2803 len = s - remainder;
2804 string_list = g_slist_prepend (string_list,
2805 g_strndup (remainder, len));
2807 remainder = s + delimiter_len;
2808 s = strstr (remainder, delimiter);
2814 string_list = g_slist_prepend (string_list, g_strdup (remainder));
2817 str_array = g_new (gchar*, n + 1);
2819 str_array[n--] = NULL;
2820 for (slist = string_list; slist; slist = slist->next)
2821 str_array[n--] = slist->data;
2823 g_slist_free (string_list);
2830 * @string: The string to be tokenized
2831 * @delimiters: A nul-terminated string containing bytes that are used
2832 * to split the string.
2833 * @max_tokens: The maximum number of tokens to split @string into.
2834 * If this is less than 1, the string is split completely
2836 * Splits @string into a number of tokens not containing any of the characters
2837 * in @delimiter. A token is the (possibly empty) longest string that does not
2838 * contain any of the characters in @delimiters. If @max_tokens is reached, the
2839 * remainder is appended to the last token.
2841 * For example the result of g_strsplit_set ("abc:def/ghi", ":/", -1) is a
2842 * %NULL-terminated vector containing the three strings "abc", "def",
2845 * The result if g_strsplit_set (":def/ghi:", ":/", -1) is a %NULL-terminated
2846 * vector containing the four strings "", "def", "ghi", and "".
2848 * As a special case, the result of splitting the empty string "" is an empty
2849 * vector, not a vector containing a single string. The reason for this
2850 * special case is that being able to represent a empty vector is typically
2851 * more useful than consistent handling of empty elements. If you do need
2852 * to represent empty elements, you'll need to check for the empty string
2853 * before calling g_strsplit_set().
2855 * Note that this function works on bytes not characters, so it can't be used
2856 * to delimit UTF-8 strings for anything but ASCII characters.
2858 * Return value: a newly-allocated %NULL-terminated array of strings. Use
2859 * g_strfreev() to free it.
2864 g_strsplit_set (const gchar *string,
2865 const gchar *delimiters,
2868 gboolean delim_table[256];
2869 GSList *tokens, *list;
2872 const gchar *current;
2876 g_return_val_if_fail (string != NULL, NULL);
2877 g_return_val_if_fail (delimiters != NULL, NULL);
2880 max_tokens = G_MAXINT;
2882 if (*string == '\0')
2884 result = g_new (char *, 1);
2889 memset (delim_table, FALSE, sizeof (delim_table));
2890 for (s = delimiters; *s != '\0'; ++s)
2891 delim_table[*(guchar *)s] = TRUE;
2896 s = current = string;
2899 if (delim_table[*(guchar *)s] && n_tokens + 1 < max_tokens)
2901 token = g_strndup (current, s - current);
2902 tokens = g_slist_prepend (tokens, token);
2911 token = g_strndup (current, s - current);
2912 tokens = g_slist_prepend (tokens, token);
2915 result = g_new (gchar *, n_tokens + 1);
2917 result[n_tokens] = NULL;
2918 for (list = tokens; list != NULL; list = list->next)
2919 result[--n_tokens] = list->data;
2921 g_slist_free (tokens);
2928 * @str_array: a %NULL-terminated array of strings to free
2930 * Frees a %NULL-terminated array of strings, and the array itself.
2931 * If called on a %NULL value, g_strfreev() simply returns.
2934 g_strfreev (gchar **str_array)
2940 for (i = 0; str_array[i] != NULL; i++)
2941 g_free (str_array[i]);
2949 * @str_array: a %NULL-terminated array of strings
2951 * Copies %NULL-terminated array of strings. The copy is a deep copy;
2952 * the new array should be freed by first freeing each string, then
2953 * the array itself. g_strfreev() does this for you. If called
2954 * on a %NULL value, g_strdupv() simply returns %NULL.
2956 * Return value: a new %NULL-terminated array of strings.
2959 g_strdupv (gchar **str_array)
2967 while (str_array[i])
2970 retval = g_new (gchar*, i + 1);
2973 while (str_array[i])
2975 retval[i] = g_strdup (str_array[i]);
2988 * @separator: a string to insert between each of the strings, or %NULL
2989 * @str_array: a %NULL-terminated array of strings to join
2991 * Joins a number of strings together to form one long string, with the
2992 * optional @separator inserted between each of them. The returned string
2993 * should be freed with g_free().
2995 * Returns: a newly-allocated string containing all of the strings joined
2996 * together, with @separator between them
2999 g_strjoinv (const gchar *separator,
3005 g_return_val_if_fail (str_array != NULL, NULL);
3007 if (separator == NULL)
3014 gsize separator_len;
3016 separator_len = strlen (separator);
3017 /* First part, getting length */
3018 len = 1 + strlen (str_array[0]);
3019 for (i = 1; str_array[i] != NULL; i++)
3020 len += strlen (str_array[i]);
3021 len += separator_len * (i - 1);
3023 /* Second part, building string */
3024 string = g_new (gchar, len);
3025 ptr = g_stpcpy (string, *str_array);
3026 for (i = 1; str_array[i] != NULL; i++)
3028 ptr = g_stpcpy (ptr, separator);
3029 ptr = g_stpcpy (ptr, str_array[i]);
3033 string = g_strdup ("");
3040 * @separator: a string to insert between each of the strings, or %NULL
3041 * @...: a %NULL-terminated list of strings to join
3043 * Joins a number of strings together to form one long string, with the
3044 * optional @separator inserted between each of them. The returned string
3045 * should be freed with g_free().
3047 * Returns: a newly-allocated string containing all of the strings joined
3048 * together, with @separator between them
3051 g_strjoin (const gchar *separator,
3057 gsize separator_len;
3060 if (separator == NULL)
3063 separator_len = strlen (separator);
3065 va_start (args, separator);
3067 s = va_arg (args, gchar*);
3071 /* First part, getting length */
3072 len = 1 + strlen (s);
3074 s = va_arg (args, gchar*);
3077 len += separator_len + strlen (s);
3078 s = va_arg (args, gchar*);
3082 /* Second part, building string */
3083 string = g_new (gchar, len);
3085 va_start (args, separator);
3087 s = va_arg (args, gchar*);
3088 ptr = g_stpcpy (string, s);
3090 s = va_arg (args, gchar*);
3093 ptr = g_stpcpy (ptr, separator);
3094 ptr = g_stpcpy (ptr, s);
3095 s = va_arg (args, gchar*);
3099 string = g_strdup ("");
3109 * @haystack: a string
3110 * @haystack_len: the maximum length of @haystack. Note that -1 is
3111 * a valid length, if @haystack is nul-terminated, meaning it will
3112 * search through the whole string.
3113 * @needle: the string to search for
3115 * Searches the string @haystack for the first occurrence
3116 * of the string @needle, limiting the length of the search
3119 * Return value: a pointer to the found occurrence, or
3120 * %NULL if not found.
3123 g_strstr_len (const gchar *haystack,
3124 gssize haystack_len,
3125 const gchar *needle)
3127 g_return_val_if_fail (haystack != NULL, NULL);
3128 g_return_val_if_fail (needle != NULL, NULL);
3130 if (haystack_len < 0)
3131 return strstr (haystack, needle);
3134 const gchar *p = haystack;
3135 gsize needle_len = strlen (needle);
3139 if (needle_len == 0)
3140 return (gchar *)haystack;
3142 if (haystack_len < needle_len)
3145 end = haystack + haystack_len - needle_len;
3147 while (p <= end && *p)
3149 for (i = 0; i < needle_len; i++)
3150 if (p[i] != needle[i])
3165 * @haystack: a nul-terminated string
3166 * @needle: the nul-terminated string to search for
3168 * Searches the string @haystack for the last occurrence
3169 * of the string @needle.
3171 * Return value: a pointer to the found occurrence, or
3172 * %NULL if not found.
3175 g_strrstr (const gchar *haystack,
3176 const gchar *needle)
3183 g_return_val_if_fail (haystack != NULL, NULL);
3184 g_return_val_if_fail (needle != NULL, NULL);
3186 needle_len = strlen (needle);
3187 haystack_len = strlen (haystack);
3189 if (needle_len == 0)
3190 return (gchar *)haystack;
3192 if (haystack_len < needle_len)
3195 p = haystack + haystack_len - needle_len;
3197 while (p >= haystack)
3199 for (i = 0; i < needle_len; i++)
3200 if (p[i] != needle[i])
3214 * @haystack: a nul-terminated string
3215 * @haystack_len: the maximum length of @haystack
3216 * @needle: the nul-terminated string to search for
3218 * Searches the string @haystack for the last occurrence
3219 * of the string @needle, limiting the length of the search
3222 * Return value: a pointer to the found occurrence, or
3223 * %NULL if not found.
3226 g_strrstr_len (const gchar *haystack,
3227 gssize haystack_len,
3228 const gchar *needle)
3230 g_return_val_if_fail (haystack != NULL, NULL);
3231 g_return_val_if_fail (needle != NULL, NULL);
3233 if (haystack_len < 0)
3234 return g_strrstr (haystack, needle);
3237 gsize needle_len = strlen (needle);
3238 const gchar *haystack_max = haystack + haystack_len;
3239 const gchar *p = haystack;
3242 while (p < haystack_max && *p)
3245 if (p < haystack + needle_len)
3250 while (p >= haystack)
3252 for (i = 0; i < needle_len; i++)
3253 if (p[i] != needle[i])
3269 * @str: a nul-terminated string
3270 * @suffix: the nul-terminated suffix to look for
3272 * Looks whether the string @str ends with @suffix.
3274 * Return value: %TRUE if @str end with @suffix, %FALSE otherwise.
3279 g_str_has_suffix (const gchar *str,
3280 const gchar *suffix)
3285 g_return_val_if_fail (str != NULL, FALSE);
3286 g_return_val_if_fail (suffix != NULL, FALSE);
3288 str_len = strlen (str);
3289 suffix_len = strlen (suffix);
3291 if (str_len < suffix_len)
3294 return strcmp (str + str_len - suffix_len, suffix) == 0;
3299 * @str: a nul-terminated string
3300 * @prefix: the nul-terminated prefix to look for
3302 * Looks whether the string @str begins with @prefix.
3304 * Return value: %TRUE if @str begins with @prefix, %FALSE otherwise.
3309 g_str_has_prefix (const gchar *str,
3310 const gchar *prefix)
3315 g_return_val_if_fail (str != NULL, FALSE);
3316 g_return_val_if_fail (prefix != NULL, FALSE);
3318 str_len = strlen (str);
3319 prefix_len = strlen (prefix);
3321 if (str_len < prefix_len)
3324 return strncmp (str, prefix, prefix_len) == 0;
3331 * @msgval: another string
3333 * An auxiliary function for gettext() support (see Q_()).
3335 * Return value: @msgval, unless @msgval is identical to @msgid and contains
3336 * a '|' character, in which case a pointer to the substring of msgid after
3337 * the first '|' character is returned.
3342 g_strip_context (const gchar *msgid,
3343 const gchar *msgval)
3345 if (msgval == msgid)
3347 const char *c = strchr (msgid, '|');
3358 * @str_array: a %NULL-terminated array of strings
3360 * Returns the length of the given %NULL-terminated
3361 * string array @str_array.
3363 * Return value: length of @str_array.
3368 g_strv_length (gchar **str_array)
3372 g_return_val_if_fail (str_array != NULL, 0);
3374 while (str_array[i])
3383 * @domain: the translation domain to use, or %NULL to use
3384 * the domain set with textdomain()
3385 * @msgctxtid: a combined message context and message id, separated
3386 * by a \004 character
3387 * @msgidoffset: the offset of the message id in @msgctxid
3389 * This function is a variant of g_dgettext() which supports
3390 * a disambiguating message context. GNU gettext uses the
3391 * '\004' character to separate the message context and
3392 * message id in @msgctxtid.
3393 * If 0 is passed as @msgidoffset, this function will fall back to
3394 * trying to use the deprecated convention of using "|" as a separation
3397 * This uses g_dgettext() internally. See that functions for differences
3398 * with dgettext() proper.
3400 * Applications should normally not use this function directly,
3401 * but use the C_() macro for translations with context.
3403 * Returns: The translated string
3408 g_dpgettext (const gchar *domain,
3409 const gchar *msgctxtid,
3412 const gchar *translation;
3415 translation = g_dgettext (domain, msgctxtid);
3417 if (translation == msgctxtid)
3419 if (msgidoffset > 0)
3420 return msgctxtid + msgidoffset;
3422 sep = strchr (msgctxtid, '|');
3426 /* try with '\004' instead of '|', in case
3427 * xgettext -kQ_:1g was used
3429 gchar *tmp = g_alloca (strlen (msgctxtid) + 1);
3430 strcpy (tmp, msgctxtid);
3431 tmp[sep - msgctxtid] = '\004';
3433 translation = g_dgettext (domain, tmp);
3435 if (translation == tmp)
3443 /* This function is taken from gettext.h
3444 * GNU gettext uses '\004' to separate context and msgid in .mo files.
3448 * @domain: the translation domain to use, or %NULL to use
3449 * the domain set with textdomain()
3450 * @context: the message context
3451 * @msgid: the message
3453 * This function is a variant of g_dgettext() which supports
3454 * a disambiguating message context. GNU gettext uses the
3455 * '\004' character to separate the message context and
3456 * message id in @msgctxtid.
3458 * This uses g_dgettext() internally. See that functions for differences
3459 * with dgettext() proper.
3461 * This function differs from C_() in that it is not a macro and
3462 * thus you may use non-string-literals as context and msgid arguments.
3464 * Returns: The translated string
3469 g_dpgettext2 (const char *domain,
3470 const char *msgctxt,
3473 size_t msgctxt_len = strlen (msgctxt) + 1;
3474 size_t msgid_len = strlen (msgid) + 1;
3475 const char *translation;
3478 msg_ctxt_id = g_alloca (msgctxt_len + msgid_len);
3480 memcpy (msg_ctxt_id, msgctxt, msgctxt_len - 1);
3481 msg_ctxt_id[msgctxt_len - 1] = '\004';
3482 memcpy (msg_ctxt_id + msgctxt_len, msgid, msgid_len);
3484 translation = g_dgettext (domain, msg_ctxt_id);
3486 if (translation == msg_ctxt_id)
3488 /* try the old way of doing message contexts, too */
3489 msg_ctxt_id[msgctxt_len - 1] = '|';
3490 translation = g_dgettext (domain, msg_ctxt_id);
3492 if (translation == msg_ctxt_id)
3500 _g_dgettext_should_translate (void)
3502 static gsize translate = 0;
3504 SHOULD_TRANSLATE = 1,
3505 SHOULD_NOT_TRANSLATE = 2
3508 if (G_UNLIKELY (g_once_init_enter (&translate)))
3510 gboolean should_translate = TRUE;
3512 const char *default_domain = textdomain (NULL);
3513 const char *translator_comment = gettext ("");
3515 const char *translate_locale = setlocale (LC_MESSAGES, NULL);
3517 const char *translate_locale = g_win32_getlocale ();
3519 /* We should NOT translate only if all the following hold:
3520 * - user has called textdomain() and set textdomain to non-default
3521 * - default domain has no translations
3522 * - locale does not start with "en_" and is not "C"
3525 * - If text domain is still the default domain, maybe user calls
3526 * it later. Continue with old behavior of translating.
3527 * - If locale starts with "en_", we can continue using the
3528 * translations even if the app doesn't have translations for
3529 * this locale. That is, en_UK and en_CA for example.
3530 * - If locale is "C", maybe user calls setlocale(LC_ALL,"") later.
3531 * Continue with old behavior of translating.
3533 if (0 != strcmp (default_domain, "messages") &&
3534 '\0' == *translator_comment &&
3535 0 != strncmp (translate_locale, "en_", 3) &&
3536 0 != strcmp (translate_locale, "C"))
3537 should_translate = FALSE;
3539 g_once_init_leave (&translate,
3542 SHOULD_NOT_TRANSLATE);
3545 return translate == SHOULD_TRANSLATE;
3550 * @domain: the translation domain to use, or %NULL to use
3551 * the domain set with textdomain()
3552 * @msgid: message to translate
3554 * This function is a wrapper of dgettext() which does not translate
3555 * the message if the default domain as set with textdomain() has no
3556 * translations for the current locale.
3558 * The advantage of using this function over dgettext() proper is that
3559 * libraries using this function (like GTK+) will not use translations
3560 * if the application using the library does not have translations for
3561 * the current locale. This results in a consistent English-only
3562 * interface instead of one having partial translations. For this
3563 * feature to work, the call to textdomain() and setlocale() should
3564 * precede any g_dgettext() invocations. For GTK+, it means calling
3565 * textdomain() before gtk_init or its variants.
3567 * This function disables translations if and only if upon its first
3568 * call all the following conditions hold:
3570 * <listitem>@domain is not %NULL</listitem>
3571 * <listitem>textdomain() has been called to set a default text domain</listitem>
3572 * <listitem>there is no translations available for the default text domain
3573 * and the current locale</listitem>
3574 * <listitem>current locale is not "C" or any English locales (those
3575 * starting with "en_")</listitem>
3578 * Note that this behavior may not be desired for example if an application
3579 * has its untranslated messages in a language other than English. In those
3580 * cases the application should call textdomain() after initializing GTK+.
3582 * Applications should normally not use this function directly,
3583 * but use the _() macro for translations.
3585 * Returns: The translated string
3590 g_dgettext (const gchar *domain,
3593 if (domain && G_UNLIKELY (!_g_dgettext_should_translate ()))
3596 return dgettext (domain, msgid);
3601 * @domain: (allow-none): the translation domain to use, or %NULL to use
3602 * the domain set with textdomain()
3603 * @msgid: message to translate
3604 * @category: a locale category
3606 * This is a variant of g_dgettext() that allows specifying a locale
3607 * category instead of always using %LC_MESSAGES. See g_dgettext() for
3608 * more information about how this functions differs from calling
3609 * dcgettext() directly.
3611 * Returns: the translated string for the given locale category
3616 g_dcgettext (const gchar *domain,
3620 if (domain && G_UNLIKELY (!_g_dgettext_should_translate ()))
3623 return dcgettext (domain, msgid, category);
3628 * @domain: the translation domain to use, or %NULL to use
3629 * the domain set with textdomain()
3630 * @msgid: message to translate
3631 * @msgid_plural: plural form of the message
3632 * @n: the quantity for which translation is needed
3634 * This function is a wrapper of dngettext() which does not translate
3635 * the message if the default domain as set with textdomain() has no
3636 * translations for the current locale.
3638 * See g_dgettext() for details of how this differs from dngettext()
3641 * Returns: The translated string
3646 g_dngettext (const gchar *domain,
3648 const gchar *msgid_plural,
3651 if (domain && G_UNLIKELY (!_g_dgettext_should_translate ()))
3652 return n == 1 ? msgid : msgid_plural;
3654 return dngettext (domain, msgid, msgid_plural, n);