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/.
35 #define _GNU_SOURCE /* For stpcpy */
43 #include <ctype.h> /* For tolower() */
44 #if !defined (HAVE_STRSIGNAL) || !defined(NO_SYS_SIGLIST_DECL)
53 /* do not include <unistd.h> in this place since it
54 * inteferes with g_strsignal() on some OSes
57 static const guint16 ascii_table_data[256] = {
58 0x004, 0x004, 0x004, 0x004, 0x004, 0x004, 0x004, 0x004,
59 0x004, 0x104, 0x104, 0x004, 0x104, 0x104, 0x004, 0x004,
60 0x004, 0x004, 0x004, 0x004, 0x004, 0x004, 0x004, 0x004,
61 0x004, 0x004, 0x004, 0x004, 0x004, 0x004, 0x004, 0x004,
62 0x140, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0,
63 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0,
64 0x459, 0x459, 0x459, 0x459, 0x459, 0x459, 0x459, 0x459,
65 0x459, 0x459, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0,
66 0x0d0, 0x653, 0x653, 0x653, 0x653, 0x653, 0x653, 0x253,
67 0x253, 0x253, 0x253, 0x253, 0x253, 0x253, 0x253, 0x253,
68 0x253, 0x253, 0x253, 0x253, 0x253, 0x253, 0x253, 0x253,
69 0x253, 0x253, 0x253, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0,
70 0x0d0, 0x473, 0x473, 0x473, 0x473, 0x473, 0x473, 0x073,
71 0x073, 0x073, 0x073, 0x073, 0x073, 0x073, 0x073, 0x073,
72 0x073, 0x073, 0x073, 0x073, 0x073, 0x073, 0x073, 0x073,
73 0x073, 0x073, 0x073, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x004
74 /* the upper 128 are all zeroes */
77 #if defined(G_PLATFORM_WIN32) && defined(__GNUC__)
80 const guint16 * const g_ascii_table = ascii_table_data;
83 g_strdup (const gchar *str)
89 new_str = g_new (char, strlen (str) + 1);
90 strcpy (new_str, str);
99 g_memdup (gconstpointer mem,
106 new_mem = g_malloc (byte_size);
107 memcpy (new_mem, mem, byte_size);
116 g_strndup (const gchar *str,
123 new_str = g_new (gchar, n + 1);
124 strncpy (new_str, str, n);
134 g_strnfill (gsize length,
139 str = g_new (gchar, length + 1);
140 memset (str, (guchar)fill_char, length);
148 * @dest: destination buffer.
149 * @src: source string.
151 * Copies a nul-terminated string into the dest buffer, include the
152 * trailing nul, and return a pointer to the trailing nul byte.
153 * This is useful for concatenating multiple strings together
154 * without having to repeatedly scan for the end.
156 * Return value: a pointer to trailing nul byte.
159 g_stpcpy (gchar *dest,
163 g_return_val_if_fail (dest != NULL, NULL);
164 g_return_val_if_fail (src != NULL, NULL);
165 return stpcpy (dest, src);
167 register gchar *d = dest;
168 register const gchar *s = src;
170 g_return_val_if_fail (dest != NULL, NULL);
171 g_return_val_if_fail (src != NULL, NULL);
174 while (*s++ != '\0');
181 g_strdup_vprintf (const gchar *format,
185 #ifdef HAVE_VASPRINTF
186 if (vasprintf (&buffer, format, args1) < 0)
188 else if (!g_mem_is_system_malloc ())
190 gchar *buffer1 = g_strdup (buffer);
197 G_VA_COPY (args2, args1);
199 buffer = g_new (gchar, g_printf_string_upper_bound (format, args1));
201 vsprintf (buffer, format, args2);
208 g_strdup_printf (const gchar *format,
214 va_start (args, format);
215 buffer = g_strdup_vprintf (format, args);
222 g_strconcat (const gchar *string1, ...)
230 g_return_val_if_fail (string1 != NULL, NULL);
232 l = 1 + strlen (string1);
233 va_start (args, string1);
234 s = va_arg (args, gchar*);
238 s = va_arg (args, gchar*);
242 concat = g_new (gchar, l);
245 ptr = g_stpcpy (ptr, string1);
246 va_start (args, string1);
247 s = va_arg (args, gchar*);
250 ptr = g_stpcpy (ptr, s);
251 s = va_arg (args, gchar*);
260 * @nptr: the string to convert to a numeric value.
261 * @endptr: if non-%NULL, it returns the character after
262 * the last character used in the conversion.
264 * Converts a string to a #gdouble value.
265 * It calls the standard strtod() function to handle the conversion, but
266 * if the string is not completely converted it attempts the conversion
267 * again with g_ascii_strtod(), and returns the best match.
269 * This function should seldomly be used. The normal situation when reading
270 * numbers not for human consumption is to use g_ascii_strtod(). Only when
271 * you know that you must expect both locale formatted and C formatted numbers
272 * should you use this. Make sure that you don't pass strings such as comma
273 * separated lists of values, since the commas may be interpreted as a decimal
274 * point in some locales, causing unexpected results.
276 * Return value: the #gdouble value.
279 g_strtod (const gchar *nptr,
287 g_return_val_if_fail (nptr != NULL, 0);
292 val_1 = strtod (nptr, &fail_pos_1);
294 if (fail_pos_1 && fail_pos_1[0] != 0)
295 val_2 = g_ascii_strtod (nptr, &fail_pos_2);
297 if (!fail_pos_1 || fail_pos_1[0] == 0 || fail_pos_1 >= fail_pos_2)
300 *endptr = fail_pos_1;
306 *endptr = fail_pos_2;
313 * @nptr: the string to convert to a numeric value.
314 * @endptr: if non-%NULL, it returns the character after
315 * the last character used in the conversion.
317 * Converts a string to a #gdouble value.
318 * This function behaves like the standard strtod() function
319 * does in the C locale. It does this without actually
320 * changing the current locale, since that would not be
323 * This function is typically used when reading configuration
324 * files or other non-user input that should be locale dependent.
325 * To handle input from the user you should normally use the
326 * locale-sensitive system strtod() function.
328 * To convert from a string to #gdouble in a locale-insensitive
329 * way, use g_ascii_dtostr().
331 * If the correct value would cause overflow, plus or minus %HUGE_VAL
332 * is returned (according to the sign of the value), and %ERANGE is
333 * stored in %errno. If the correct value would cause underflow,
334 * zero is returned and %ERANGE is stored in %errno.
336 * This function resets %errno before calling strtod() so that
337 * you can reliably detect overflow and underflow.
339 * Return value: the #gdouble value.
342 g_ascii_strtod (const gchar *nptr,
347 struct lconv *locale_data;
348 const char *decimal_point;
349 int decimal_point_len;
350 const char *p, *decimal_point_pos;
351 const char *end = NULL; /* Silence gcc */
353 g_return_val_if_fail (nptr != NULL, 0);
357 locale_data = localeconv ();
358 decimal_point = locale_data->decimal_point;
359 decimal_point_len = strlen (decimal_point);
361 g_assert (decimal_point_len != 0);
363 decimal_point_pos = NULL;
364 if (decimal_point[0] != '.' ||
365 decimal_point[1] != 0)
368 /* Skip leading space */
369 while (g_ascii_isspace (*p))
372 /* Skip leading optional sign */
373 if (*p == '+' || *p == '-')
377 (p[1] == 'x' || p[1] == 'X'))
380 /* HEX - find the (optional) decimal point */
382 while (g_ascii_isxdigit (*p))
387 decimal_point_pos = p++;
389 while (g_ascii_isxdigit (*p))
392 if (*p == 'p' || *p == 'P')
394 if (*p == '+' || *p == '-')
396 while (g_ascii_isdigit (*p))
403 while (g_ascii_isdigit (*p))
408 decimal_point_pos = p++;
410 while (g_ascii_isdigit (*p))
413 if (*p == 'e' || *p == 'E')
415 if (*p == '+' || *p == '-')
417 while (g_ascii_isdigit (*p))
422 /* For the other cases, we need not convert the decimal point */
425 /* Set errno to zero, so that we can distinguish zero results
429 if (decimal_point_pos)
433 /* We need to convert the '.' to the locale specific decimal point */
434 copy = g_malloc (end - nptr + 1 + decimal_point_len);
437 memcpy (c, nptr, decimal_point_pos - nptr);
438 c += decimal_point_pos - nptr;
439 memcpy (c, decimal_point, decimal_point_len);
440 c += decimal_point_len;
441 memcpy (c, decimal_point_pos + 1, end - (decimal_point_pos + 1));
442 c += end - (decimal_point_pos + 1);
445 val = strtod (copy, &fail_pos);
449 if (fail_pos > decimal_point_pos)
450 fail_pos = (char *)nptr + (fail_pos - copy) - (decimal_point_len - 1);
452 fail_pos = (char *)nptr + (fail_pos - copy);
459 val = strtod (nptr, &fail_pos);
469 * @buffer: A buffer to place the resulting string in
470 * @buf_len: The length of the buffer.
471 * @d: The #gdouble to convert
473 * Converts a #gdouble to a string, using the '.' as
476 * This functions generates enough precision that converting
477 * the string back using g_strtod() gives the same machine-number
478 * (on machines with IEEE compatible 64bit doubles). It is
479 * guaranteed that the size of the resulting string will never
480 * be larger than @G_ASCII_DTOSTR_BUF_SIZE bytes.
482 * Return value: The pointer to the buffer with the converted string.
485 g_ascii_dtostr (gchar *buffer,
489 return g_ascii_formatd (buffer, buf_len, "%.17g", d);
494 * @buffer: A buffer to place the resulting string in
495 * @buf_len: The length of the buffer.
496 * @format: The printf-style format to use for the
497 * code to use for converting.
498 * @d: The #gdouble to convert
500 * Converts a #gdouble to a string, using the '.' as
501 * decimal point. To format the number you pass in
502 * a printf-style formating string. Allowed conversion
503 * specifiers are 'e', 'E', 'f', 'F', 'g' and 'G'.
505 * If you just want to want to serialize the value into a
506 * string, use g_ascii_dtostr().
508 * Return value: The pointer to the buffer with the converted string.
511 g_ascii_formatd (gchar *buffer,
516 struct lconv *locale_data;
517 const char *decimal_point;
518 int decimal_point_len;
523 g_return_val_if_fail (buffer != NULL, NULL);
524 g_return_val_if_fail (format[0] == '%', NULL);
525 g_return_val_if_fail (strpbrk (format + 1, "'l%") == NULL, NULL);
527 format_char = format[strlen (format) - 1];
529 g_return_val_if_fail (format_char == 'e' || format_char == 'E' ||
530 format_char == 'f' || format_char == 'F' ||
531 format_char == 'g' || format_char == 'G',
534 if (format[0] != '%')
537 if (strpbrk (format + 1, "'l%"))
540 if (!(format_char == 'e' || format_char == 'E' ||
541 format_char == 'f' || format_char == 'F' ||
542 format_char == 'g' || format_char == 'G'))
546 g_snprintf (buffer, buf_len, format, d);
548 locale_data = localeconv ();
549 decimal_point = locale_data->decimal_point;
550 decimal_point_len = strlen (decimal_point);
552 g_assert (decimal_point_len != 0);
554 if (decimal_point[0] != '.' ||
555 decimal_point[1] != 0)
559 if (*p == '+' || *p == '-')
562 while (isdigit ((guchar)*p))
565 if (strncmp (p, decimal_point, decimal_point_len) == 0)
569 if (decimal_point_len > 1) {
570 rest_len = strlen (p + (decimal_point_len-1));
571 memmove (p, p + (decimal_point_len-1),
583 G_CONST_RETURN gchar*
584 g_strerror (gint errnum)
586 static GStaticPrivate msg_private = G_STATIC_PRIVATE_INIT;
590 const char *msg_locale;
592 msg_locale = strerror (errnum);
593 if (g_get_charset (NULL))
597 gchar *msg_utf8 = g_locale_to_utf8 (msg_locale, -1, NULL, NULL, NULL);
600 /* Stick in the quark table so that we can return a static result
602 GQuark msg_quark = g_quark_from_string (msg_utf8);
605 return g_quark_to_string (msg_quark);
612 case E2BIG: return "argument list too long";
615 case EACCES: return "permission denied";
618 case EADDRINUSE: return "address already in use";
621 case EADDRNOTAVAIL: return "can't assign requested address";
624 case EADV: return "advertise error";
627 case EAFNOSUPPORT: return "address family not supported by protocol family";
630 case EAGAIN: return "try again";
633 case EALIGN: return "EALIGN";
636 case EALREADY: return "operation already in progress";
639 case EBADE: return "bad exchange descriptor";
642 case EBADF: return "bad file number";
645 case EBADFD: return "file descriptor in bad state";
648 case EBADMSG: return "not a data message";
651 case EBADR: return "bad request descriptor";
654 case EBADRPC: return "RPC structure is bad";
657 case EBADRQC: return "bad request code";
660 case EBADSLT: return "invalid slot";
663 case EBFONT: return "bad font file format";
666 case EBUSY: return "mount device busy";
669 case ECHILD: return "no children";
672 case ECHRNG: return "channel number out of range";
675 case ECOMM: return "communication error on send";
678 case ECONNABORTED: return "software caused connection abort";
681 case ECONNREFUSED: return "connection refused";
684 case ECONNRESET: return "connection reset by peer";
686 #if defined(EDEADLK) && (!defined(EWOULDBLOCK) || (EDEADLK != EWOULDBLOCK))
687 case EDEADLK: return "resource deadlock avoided";
690 case EDEADLOCK: return "resource deadlock avoided";
693 case EDESTADDRREQ: return "destination address required";
696 case EDIRTY: return "mounting a dirty fs w/o force";
699 case EDOM: return "math argument out of range";
702 case EDOTDOT: return "cross mount point";
705 case EDQUOT: return "disk quota exceeded";
708 case EDUPPKG: return "duplicate package name";
711 case EEXIST: return "file already exists";
714 case EFAULT: return "bad address in system call argument";
717 case EFBIG: return "file too large";
720 case EHOSTDOWN: return "host is down";
723 case EHOSTUNREACH: return "host is unreachable";
726 case EIDRM: return "identifier removed";
729 case EINIT: return "initialization error";
732 case EINPROGRESS: return "operation now in progress";
735 case EINTR: return "interrupted system call";
738 case EINVAL: return "invalid argument";
741 case EIO: return "I/O error";
744 case EISCONN: return "socket is already connected";
747 case EISDIR: return "is a directory";
750 case EISNAM: return "is a name file";
753 case ELBIN: return "ELBIN";
756 case EL2HLT: return "level 2 halted";
759 case EL2NSYNC: return "level 2 not synchronized";
762 case EL3HLT: return "level 3 halted";
765 case EL3RST: return "level 3 reset";
768 case ELIBACC: return "can not access a needed shared library";
771 case ELIBBAD: return "accessing a corrupted shared library";
774 case ELIBEXEC: return "can not exec a shared library directly";
777 case ELIBMAX: return "attempting to link in more shared libraries than system limit";
780 case ELIBSCN: return ".lib section in a.out corrupted";
783 case ELNRNG: return "link number out of range";
786 case ELOOP: return "too many levels of symbolic links";
789 case EMFILE: return "too many open files";
792 case EMLINK: return "too many links";
795 case EMSGSIZE: return "message too long";
798 case EMULTIHOP: return "multihop attempted";
801 case ENAMETOOLONG: return "file name too long";
804 case ENAVAIL: return "not available";
807 case ENET: return "ENET";
810 case ENETDOWN: return "network is down";
813 case ENETRESET: return "network dropped connection on reset";
816 case ENETUNREACH: return "network is unreachable";
819 case ENFILE: return "file table overflow";
822 case ENOANO: return "anode table overflow";
824 #if defined(ENOBUFS) && (!defined(ENOSR) || (ENOBUFS != ENOSR))
825 case ENOBUFS: return "no buffer space available";
828 case ENOCSI: return "no CSI structure available";
831 case ENODATA: return "no data available";
834 case ENODEV: return "no such device";
837 case ENOENT: return "no such file or directory";
840 case ENOEXEC: return "exec format error";
843 case ENOLCK: return "no locks available";
846 case ENOLINK: return "link has be severed";
849 case ENOMEM: return "not enough memory";
852 case ENOMSG: return "no message of desired type";
855 case ENONET: return "machine is not on the network";
858 case ENOPKG: return "package not installed";
861 case ENOPROTOOPT: return "bad proocol option";
864 case ENOSPC: return "no space left on device";
867 case ENOSR: return "out of stream resources";
870 case ENOSTR: return "not a stream device";
873 case ENOSYM: return "unresolved symbol name";
876 case ENOSYS: return "function not implemented";
879 case ENOTBLK: return "block device required";
882 case ENOTCONN: return "socket is not connected";
885 case ENOTDIR: return "not a directory";
888 case ENOTEMPTY: return "directory not empty";
891 case ENOTNAM: return "not a name file";
894 case ENOTSOCK: return "socket operation on non-socket";
897 case ENOTTY: return "inappropriate device for ioctl";
900 case ENOTUNIQ: return "name not unique on network";
903 case ENXIO: return "no such device or address";
906 case EOPNOTSUPP: return "operation not supported on socket";
909 case EPERM: return "not owner";
912 case EPFNOSUPPORT: return "protocol family not supported";
915 case EPIPE: return "broken pipe";
918 case EPROCLIM: return "too many processes";
921 case EPROCUNAVAIL: return "bad procedure for program";
924 case EPROGMISMATCH: return "program version wrong";
927 case EPROGUNAVAIL: return "RPC program not available";
930 case EPROTO: return "protocol error";
932 #ifdef EPROTONOSUPPORT
933 case EPROTONOSUPPORT: return "protocol not suppored";
936 case EPROTOTYPE: return "protocol wrong type for socket";
939 case ERANGE: return "math result unrepresentable";
941 #if defined(EREFUSED) && (!defined(ECONNREFUSED) || (EREFUSED != ECONNREFUSED))
942 case EREFUSED: return "EREFUSED";
945 case EREMCHG: return "remote address changed";
948 case EREMDEV: return "remote device";
951 case EREMOTE: return "pathname hit remote file system";
954 case EREMOTEIO: return "remote i/o error";
956 #ifdef EREMOTERELEASE
957 case EREMOTERELEASE: return "EREMOTERELEASE";
960 case EROFS: return "read-only file system";
963 case ERPCMISMATCH: return "RPC version is wrong";
966 case ERREMOTE: return "object is remote";
969 case ESHUTDOWN: return "can't send afer socket shutdown";
971 #ifdef ESOCKTNOSUPPORT
972 case ESOCKTNOSUPPORT: return "socket type not supported";
975 case ESPIPE: return "invalid seek";
978 case ESRCH: return "no such process";
981 case ESRMNT: return "srmount error";
984 case ESTALE: return "stale remote file handle";
987 case ESUCCESS: return "Error 0";
990 case ETIME: return "timer expired";
993 case ETIMEDOUT: return "connection timed out";
996 case ETOOMANYREFS: return "too many references: can't splice";
999 case ETXTBSY: return "text file or pseudo-device busy";
1002 case EUCLEAN: return "structure needs cleaning";
1005 case EUNATCH: return "protocol driver not attached";
1008 case EUSERS: return "too many users";
1011 case EVERSION: return "version mismatch";
1013 #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
1014 case EWOULDBLOCK: return "operation would block";
1017 case EXDEV: return "cross-domain link";
1020 case EXFULL: return "message tables full";
1023 #else /* NO_SYS_ERRLIST */
1024 extern int sys_nerr;
1025 extern char *sys_errlist[];
1027 if ((errnum > 0) && (errnum <= sys_nerr))
1028 return sys_errlist [errnum];
1029 #endif /* NO_SYS_ERRLIST */
1031 msg = g_static_private_get (&msg_private);
1034 msg = g_new (gchar, 64);
1035 g_static_private_set (&msg_private, msg, g_free);
1038 sprintf (msg, "unknown error (%d)", errnum);
1043 G_CONST_RETURN gchar*
1044 g_strsignal (gint signum)
1046 static GStaticPrivate msg_private = G_STATIC_PRIVATE_INIT;
1049 #ifdef HAVE_STRSIGNAL
1050 const char *msg_locale;
1052 #if defined(G_OS_BEOS) || defined(G_WITH_CYGWIN)
1053 extern const char *strsignal(int);
1055 /* this is declared differently (const) in string.h on BeOS */
1056 extern char *strsignal (int sig);
1057 #endif /* !G_OS_BEOS && !G_WITH_CYGWIN */
1058 msg_locale = strsignal (signum);
1059 if (g_get_charset (NULL))
1063 gchar *msg_utf8 = g_locale_to_utf8 (msg_locale, -1, NULL, NULL, NULL);
1066 /* Stick in the quark table so that we can return a static result
1068 GQuark msg_quark = g_quark_from_string (msg_utf8);
1071 return g_quark_to_string (msg_quark);
1074 #elif NO_SYS_SIGLIST
1078 case SIGHUP: return "Hangup";
1081 case SIGINT: return "Interrupt";
1084 case SIGQUIT: return "Quit";
1087 case SIGILL: return "Illegal instruction";
1090 case SIGTRAP: return "Trace/breakpoint trap";
1093 case SIGABRT: return "IOT trap/Abort";
1096 case SIGBUS: return "Bus error";
1099 case SIGFPE: return "Floating point exception";
1102 case SIGKILL: return "Killed";
1105 case SIGUSR1: return "User defined signal 1";
1108 case SIGSEGV: return "Segmentation fault";
1111 case SIGUSR2: return "User defined signal 2";
1114 case SIGPIPE: return "Broken pipe";
1117 case SIGALRM: return "Alarm clock";
1120 case SIGTERM: return "Terminated";
1123 case SIGSTKFLT: return "Stack fault";
1126 case SIGCHLD: return "Child exited";
1129 case SIGCONT: return "Continued";
1132 case SIGSTOP: return "Stopped (signal)";
1135 case SIGTSTP: return "Stopped";
1138 case SIGTTIN: return "Stopped (tty input)";
1141 case SIGTTOU: return "Stopped (tty output)";
1144 case SIGURG: return "Urgent condition";
1147 case SIGXCPU: return "CPU time limit exceeded";
1150 case SIGXFSZ: return "File size limit exceeded";
1153 case SIGVTALRM: return "Virtual time alarm";
1156 case SIGPROF: return "Profile signal";
1159 case SIGWINCH: return "Window size changed";
1162 case SIGIO: return "Possible I/O";
1165 case SIGPWR: return "Power failure";
1168 case SIGUNUSED: return "Unused signal";
1171 #else /* NO_SYS_SIGLIST */
1173 #ifdef NO_SYS_SIGLIST_DECL
1174 extern char *sys_siglist[]; /*(see Tue Jan 19 00:44:24 1999 in changelog)*/
1177 return (char*) /* this function should return const --josh */ sys_siglist [signum];
1178 #endif /* NO_SYS_SIGLIST */
1180 msg = g_static_private_get (&msg_private);
1183 msg = g_new (gchar, 64);
1184 g_static_private_set (&msg_private, msg, g_free);
1187 sprintf (msg, "unknown signal (%d)", signum);
1192 /* Functions g_strlcpy and g_strlcat were originally developed by
1193 * Todd C. Miller <Todd.Miller@courtesan.com> to simplify writing secure code.
1194 * See ftp://ftp.openbsd.org/pub/OpenBSD/src/lib/libc/string/strlcpy.3
1195 * for more information.
1199 /* Use the native ones, if available; they might be implemented in assembly */
1201 g_strlcpy (gchar *dest,
1205 g_return_val_if_fail (dest != NULL, 0);
1206 g_return_val_if_fail (src != NULL, 0);
1208 return strlcpy (dest, src, dest_size);
1212 g_strlcat (gchar *dest,
1216 g_return_val_if_fail (dest != NULL, 0);
1217 g_return_val_if_fail (src != NULL, 0);
1219 return strlcat (dest, src, dest_size);
1222 #else /* ! HAVE_STRLCPY */
1225 * Copy string src to buffer dest (of buffer size dest_size). At most
1226 * dest_size-1 characters will be copied. Always NUL terminates
1227 * (unless dest_size == 0). This function does NOT allocate memory.
1228 * Unlike strncpy, this function doesn't pad dest (so it's often faster).
1229 * Returns size of attempted result, strlen(src),
1230 * so if retval >= dest_size, truncation occurred.
1233 g_strlcpy (gchar *dest,
1237 register gchar *d = dest;
1238 register const gchar *s = src;
1239 register gsize n = dest_size;
1241 g_return_val_if_fail (dest != NULL, 0);
1242 g_return_val_if_fail (src != NULL, 0);
1244 /* Copy as many bytes as will fit */
1245 if (n != 0 && --n != 0)
1248 register gchar c = *s++;
1256 /* If not enough room in dest, add NUL and traverse rest of src */
1265 return s - src - 1; /* count does not include NUL */
1270 * Appends string src to buffer dest (of buffer size dest_size).
1271 * At most dest_size-1 characters will be copied.
1272 * Unlike strncat, dest_size is the full size of dest, not the space left over.
1273 * This function does NOT allocate memory.
1274 * This always NUL terminates (unless siz == 0 or there were no NUL characters
1275 * in the dest_size characters of dest to start with).
1276 * Returns size of attempted result, which is
1277 * MIN (dest_size, strlen (original dest)) + strlen (src),
1278 * so if retval >= dest_size, truncation occurred.
1281 g_strlcat (gchar *dest,
1285 register gchar *d = dest;
1286 register const gchar *s = src;
1287 register gsize bytes_left = dest_size;
1288 gsize dlength; /* Logically, MIN (strlen (d), dest_size) */
1290 g_return_val_if_fail (dest != NULL, 0);
1291 g_return_val_if_fail (src != NULL, 0);
1293 /* Find the end of dst and adjust bytes left but don't go past end */
1294 while (*d != 0 && bytes_left-- != 0)
1297 bytes_left = dest_size - dlength;
1299 if (bytes_left == 0)
1300 return dlength + strlen (s);
1304 if (bytes_left != 1)
1313 return dlength + (s - src); /* count does not include NUL */
1315 #endif /* ! HAVE_STRLCPY */
1320 * @len: length of @str in bytes, or -1 if @str is nul-terminated.
1322 * Converts all upper case ASCII letters to lower case ASCII letters.
1324 * Return value: a newly-allocated string, with all the upper case
1325 * characters in @str converted to lower case, with
1326 * semantics that exactly match g_ascii_tolower(). (Note
1327 * that this is unlike the old g_strdown(), which modified
1328 * the string in place.)
1331 g_ascii_strdown (const gchar *str,
1336 g_return_val_if_fail (str != NULL, NULL);
1341 result = g_strndup (str, len);
1342 for (s = result; *s; s++)
1343 *s = g_ascii_tolower (*s);
1351 * @len: length of @str in bytes, or -1 if @str is nul-terminated.
1353 * Converts all lower case ASCII letters to upper case ASCII letters.
1355 * Return value: a newly allocated string, with all the lower case
1356 * characters in @str converted to upper case, with
1357 * semantics that exactly match g_ascii_toupper(). (Note
1358 * that this is unlike the old g_strup(), which modified
1359 * the string in place.)
1362 g_ascii_strup (const gchar *str,
1367 g_return_val_if_fail (str != NULL, NULL);
1372 result = g_strndup (str, len);
1373 for (s = result; *s; s++)
1374 *s = g_ascii_toupper (*s);
1380 g_strdown (gchar *string)
1384 g_return_val_if_fail (string != NULL, NULL);
1386 s = (guchar *) string;
1395 return (gchar *) string;
1399 g_strup (gchar *string)
1403 g_return_val_if_fail (string != NULL, NULL);
1405 s = (guchar *) string;
1414 return (gchar *) string;
1418 g_strreverse (gchar *string)
1420 g_return_val_if_fail (string != NULL, NULL);
1424 register gchar *h, *t;
1427 t = string + strlen (string) - 1;
1446 * @c: any character.
1448 * Convert a character to ASCII lower case.
1450 * Unlike the standard C library tolower() function, this only
1451 * recognizes standard ASCII letters and ignores the locale, returning
1452 * all non-ASCII characters unchanged, even if they are lower case
1453 * letters in a particular character set. Also unlike the standard
1454 * library function, this takes and returns a char, not an int, so
1455 * don't call it on %EOF but no need to worry about casting to #guchar
1456 * before passing a possibly non-ASCII character in.
1458 * Return value: the result of converting @c to lower case.
1459 * If @c is not an ASCII upper case letter,
1460 * @c is returned unchanged.
1463 g_ascii_tolower (gchar c)
1465 return g_ascii_isupper (c) ? c - 'A' + 'a' : c;
1470 * @c: any character.
1472 * Convert a character to ASCII upper case.
1474 * Unlike the standard C library toupper() function, this only
1475 * recognizes standard ASCII letters and ignores the locale, returning
1476 * all non-ASCII characters unchanged, even if they are upper case
1477 * letters in a particular character set. Also unlike the standard
1478 * library function, this takes and returns a char, not an int, so
1479 * don't call it on %EOF but no need to worry about casting to #guchar
1480 * before passing a possibly non-ASCII character in.
1482 * Return value: the result of converting @c to upper case.
1483 * If @c is not an ASCII lower case letter,
1484 * @c is returned unchanged.
1487 g_ascii_toupper (gchar c)
1489 return g_ascii_islower (c) ? c - 'a' + 'A' : c;
1493 * g_ascii_digit_value:
1494 * @c: an ASCII character.
1496 * Determines the numeric value of a character as a decimal
1497 * digit. Differs from g_unichar_digit_value() because it takes
1498 * a char, so there's no worry about sign extension if characters
1501 * Return value: If @c is a decimal digit (according to
1502 * g_ascii_isdigit()), its numeric value. Otherwise, -1.
1505 g_ascii_digit_value (gchar c)
1507 if (g_ascii_isdigit (c))
1513 * g_ascii_xdigit_value:
1514 * @c: an ASCII character.
1516 * Determines the numeric value of a character as a hexidecimal
1517 * digit. Differs from g_unichar_xdigit_value() because it takes
1518 * a char, so there's no worry about sign extension if characters
1521 * Return value: If @c is a hex digit (according to
1522 * g_ascii_isxdigit()), its numeric value. Otherwise, -1.
1525 g_ascii_xdigit_value (gchar c)
1527 if (c >= 'A' && c <= 'F')
1528 return c - 'A' + 10;
1529 if (c >= 'a' && c <= 'f')
1530 return c - 'a' + 10;
1531 return g_ascii_digit_value (c);
1535 * g_ascii_strcasecmp:
1536 * @s1: string to compare with @s2.
1537 * @s2: string to compare with @s1.
1539 * Compare two strings, ignoring the case of ASCII characters.
1541 * Unlike the BSD strcasecmp() function, this only recognizes standard
1542 * ASCII letters and ignores the locale, treating all non-ASCII
1543 * characters as if they are not letters.
1545 * Return value: an integer less than, equal to, or greater than
1546 * zero if @s1 is found, respectively, to be less than,
1547 * to match, or to be greater than @s2.
1550 g_ascii_strcasecmp (const gchar *s1,
1555 g_return_val_if_fail (s1 != NULL, 0);
1556 g_return_val_if_fail (s2 != NULL, 0);
1560 c1 = (gint)(guchar) g_ascii_tolower (*s1);
1561 c2 = (gint)(guchar) g_ascii_tolower (*s2);
1567 return (((gint)(guchar) *s1) - ((gint)(guchar) *s2));
1571 * g_ascii_strncasecmp:
1572 * @s1: string to compare with @s2.
1573 * @s2: string to compare with @s1.
1574 * @n: number of characters to compare.
1576 * Compare @s1 and @s2, ignoring the case of ASCII characters and any
1577 * characters after the first @n in each string.
1579 * Unlike the BSD strcasecmp() function, this only recognizes standard
1580 * ASCII letters and ignores the locale, treating all non-ASCII
1581 * characters as if they are not letters.
1583 * Return value: an integer less than, equal to, or greater than zero
1584 * if the first @n bytes of @s1 is found, respectively,
1585 * to be less than, to match, or to be greater than the
1586 * first @n bytes of @s2.
1589 g_ascii_strncasecmp (const gchar *s1,
1595 g_return_val_if_fail (s1 != NULL, 0);
1596 g_return_val_if_fail (s2 != NULL, 0);
1598 while (n && *s1 && *s2)
1601 c1 = (gint)(guchar) g_ascii_tolower (*s1);
1602 c2 = (gint)(guchar) g_ascii_tolower (*s2);
1609 return (((gint) (guchar) *s1) - ((gint) (guchar) *s2));
1615 g_strcasecmp (const gchar *s1,
1618 #ifdef HAVE_STRCASECMP
1619 g_return_val_if_fail (s1 != NULL, 0);
1620 g_return_val_if_fail (s2 != NULL, 0);
1622 return strcasecmp (s1, s2);
1626 g_return_val_if_fail (s1 != NULL, 0);
1627 g_return_val_if_fail (s2 != NULL, 0);
1631 /* According to A. Cox, some platforms have islower's that
1632 * don't work right on non-uppercase
1634 c1 = isupper ((guchar)*s1) ? tolower ((guchar)*s1) : *s1;
1635 c2 = isupper ((guchar)*s2) ? tolower ((guchar)*s2) : *s2;
1641 return (((gint)(guchar) *s1) - ((gint)(guchar) *s2));
1646 g_strncasecmp (const gchar *s1,
1650 #ifdef HAVE_STRNCASECMP
1651 return strncasecmp (s1, s2, n);
1655 g_return_val_if_fail (s1 != NULL, 0);
1656 g_return_val_if_fail (s2 != NULL, 0);
1658 while (n && *s1 && *s2)
1661 /* According to A. Cox, some platforms have islower's that
1662 * don't work right on non-uppercase
1664 c1 = isupper ((guchar)*s1) ? tolower ((guchar)*s1) : *s1;
1665 c2 = isupper ((guchar)*s2) ? tolower ((guchar)*s2) : *s2;
1672 return (((gint) (guchar) *s1) - ((gint) (guchar) *s2));
1679 g_strdelimit (gchar *string,
1680 const gchar *delimiters,
1685 g_return_val_if_fail (string != NULL, NULL);
1688 delimiters = G_STR_DELIMITERS;
1690 for (c = string; *c; c++)
1692 if (strchr (delimiters, *c))
1700 g_strcanon (gchar *string,
1701 const gchar *valid_chars,
1706 g_return_val_if_fail (string != NULL, NULL);
1707 g_return_val_if_fail (valid_chars != NULL, NULL);
1709 for (c = string; *c; c++)
1711 if (!strchr (valid_chars, *c))
1719 g_strcompress (const gchar *source)
1721 const gchar *p = source, *octal;
1722 gchar *dest = g_malloc (strlen (source) + 1);
1732 case '0': case '1': case '2': case '3': case '4':
1733 case '5': case '6': case '7':
1736 while ((p < octal + 3) && (*p >= '0') && (*p <= '7'))
1738 *q = (*q * 8) + (*p - '0');
1759 default: /* Also handles \" and \\ */
1774 g_strescape (const gchar *source,
1775 const gchar *exceptions)
1782 g_return_val_if_fail (source != NULL, NULL);
1784 p = (guchar *) source;
1785 /* Each source byte needs maximally four destination chars (\777) */
1786 q = dest = g_malloc (strlen (source) * 4 + 1);
1788 memset (excmap, 0, 256);
1791 guchar *e = (guchar *) exceptions;
1837 if ((*p < ' ') || (*p >= 0177))
1840 *q++ = '0' + (((*p) >> 6) & 07);
1841 *q++ = '0' + (((*p) >> 3) & 07);
1842 *q++ = '0' + ((*p) & 07);
1856 g_strchug (gchar *string)
1860 g_return_val_if_fail (string != NULL, NULL);
1862 for (start = (guchar*) string; *start && g_ascii_isspace (*start); start++)
1865 g_memmove (string, start, strlen ((gchar *) start) + 1);
1871 g_strchomp (gchar *string)
1875 g_return_val_if_fail (string != NULL, NULL);
1880 for (s = string + strlen (string) - 1; s >= string && g_ascii_isspace ((guchar)*s);
1889 * @string: a string to split.
1890 * @delimiter: a string which specifies the places at which to split the string.
1891 * The delimiter is not included in any of the resulting strings, unless
1892 * @max_tokens is reached.
1893 * @max_tokens: the maximum number of pieces to split @string into. If this is
1894 * less than 1, the string is split completely.
1896 * Splits a string into a maximum of @max_tokens pieces, using the given
1897 * @delimiter. If @max_tokens is reached, the remainder of @string is appended
1898 * to the last token.
1900 * As a special case, the result of splitting the empty string "" is an empty
1901 * vector, not a vector containing a single string. The reason for this
1902 * special case is that being able to represent a empty vector is typically
1903 * more useful than consistent handling of empty elements. If you do need
1904 * to represent empty elements, you'll need to check for the empty string
1905 * before calling g_strsplit().
1907 * Return value: a newly-allocated %NULL-terminated array of strings. Use
1908 * g_strfreev() to free it.
1911 g_strsplit (const gchar *string,
1912 const gchar *delimiter,
1915 GSList *string_list = NULL, *slist;
1916 gchar **str_array, *s;
1918 const gchar *remainder;
1920 g_return_val_if_fail (string != NULL, NULL);
1921 g_return_val_if_fail (delimiter != NULL, NULL);
1922 g_return_val_if_fail (delimiter[0] != '\0', NULL);
1925 max_tokens = G_MAXINT;
1928 s = strstr (remainder, delimiter);
1931 gsize delimiter_len = strlen (delimiter);
1933 while (--max_tokens && s)
1938 len = s - remainder;
1939 new_string = g_new (gchar, len + 1);
1940 strncpy (new_string, remainder, len);
1941 new_string[len] = 0;
1942 string_list = g_slist_prepend (string_list, new_string);
1944 remainder = s + delimiter_len;
1945 s = strstr (remainder, delimiter);
1951 string_list = g_slist_prepend (string_list, g_strdup (remainder));
1954 str_array = g_new (gchar*, n + 1);
1956 str_array[n--] = NULL;
1957 for (slist = string_list; slist; slist = slist->next)
1958 str_array[n--] = slist->data;
1960 g_slist_free (string_list);
1966 g_strfreev (gchar **str_array)
1972 for(i = 0; str_array[i] != NULL; i++)
1973 g_free(str_array[i]);
1981 * @str_array: %NULL-terminated array of strings.
1983 * Copies %NULL-terminated array of strings. The copy is a deep copy;
1984 * the new array should be freed by first freeing each string, then
1985 * the array itself. g_strfreev() does this for you. If called
1986 * on a %NULL value, g_strdupv() simply returns %NULL.
1988 * Return value: a new %NULL-terminated array of strings.
1991 g_strdupv (gchar **str_array)
1999 while (str_array[i])
2002 retval = g_new (gchar*, i + 1);
2005 while (str_array[i])
2007 retval[i] = g_strdup (str_array[i]);
2019 g_strjoinv (const gchar *separator,
2025 g_return_val_if_fail (str_array != NULL, NULL);
2027 if (separator == NULL)
2034 gsize separator_len;
2036 separator_len = strlen (separator);
2037 /* First part, getting length */
2038 len = 1 + strlen (str_array[0]);
2039 for (i = 1; str_array[i] != NULL; i++)
2040 len += strlen (str_array[i]);
2041 len += separator_len * (i - 1);
2043 /* Second part, building string */
2044 string = g_new (gchar, len);
2045 ptr = g_stpcpy (string, *str_array);
2046 for (i = 1; str_array[i] != NULL; i++)
2048 ptr = g_stpcpy (ptr, separator);
2049 ptr = g_stpcpy (ptr, str_array[i]);
2053 string = g_strdup ("");
2059 g_strjoin (const gchar *separator,
2065 gsize separator_len;
2068 if (separator == NULL)
2071 separator_len = strlen (separator);
2073 va_start (args, separator);
2075 s = va_arg (args, gchar*);
2079 /* First part, getting length */
2080 len = 1 + strlen (s);
2082 s = va_arg (args, gchar*);
2085 len += separator_len + strlen (s);
2086 s = va_arg (args, gchar*);
2090 /* Second part, building string */
2091 string = g_new (gchar, len);
2093 va_start (args, separator);
2095 s = va_arg (args, gchar*);
2096 ptr = g_stpcpy (string, s);
2098 s = va_arg (args, gchar*);
2101 ptr = g_stpcpy (ptr, separator);
2102 ptr = g_stpcpy (ptr, s);
2103 s = va_arg (args, gchar*);
2107 string = g_strdup ("");
2117 * @haystack: a string.
2118 * @haystack_len: the maximum length of @haystack.
2119 * @needle: the string to search for.
2121 * Searches the string @haystack for the first occurrence
2122 * of the string @needle, limiting the length of the search
2125 * Return value: a pointer to the found occurrence, or
2126 * %NULL if not found.
2129 g_strstr_len (const gchar *haystack,
2130 gssize haystack_len,
2131 const gchar *needle)
2133 g_return_val_if_fail (haystack != NULL, NULL);
2134 g_return_val_if_fail (needle != NULL, NULL);
2136 if (haystack_len < 0)
2137 return strstr (haystack, needle);
2140 const gchar *p = haystack;
2141 gsize needle_len = strlen (needle);
2145 if (needle_len == 0)
2146 return (gchar *)haystack;
2148 if (haystack_len < needle_len)
2151 end = haystack + haystack_len - needle_len;
2153 while (*p && p <= end)
2155 for (i = 0; i < needle_len; i++)
2156 if (p[i] != needle[i])
2171 * @haystack: a nul-terminated string.
2172 * @needle: the nul-terminated string to search for.
2174 * Searches the string @haystack for the last occurrence
2175 * of the string @needle.
2177 * Return value: a pointer to the found occurrence, or
2178 * %NULL if not found.
2181 g_strrstr (const gchar *haystack,
2182 const gchar *needle)
2189 g_return_val_if_fail (haystack != NULL, NULL);
2190 g_return_val_if_fail (needle != NULL, NULL);
2192 needle_len = strlen (needle);
2193 haystack_len = strlen (haystack);
2195 if (needle_len == 0)
2196 return (gchar *)haystack;
2198 if (haystack_len < needle_len)
2201 p = haystack + haystack_len - needle_len;
2203 while (p >= haystack)
2205 for (i = 0; i < needle_len; i++)
2206 if (p[i] != needle[i])
2220 * @haystack: a nul-terminated string.
2221 * @haystack_len: the maximum length of @haystack.
2222 * @needle: the nul-terminated string to search for.
2224 * Searches the string @haystack for the last occurrence
2225 * of the string @needle, limiting the length of the search
2228 * Return value: a pointer to the found occurrence, or
2229 * %NULL if not found.
2232 g_strrstr_len (const gchar *haystack,
2233 gssize haystack_len,
2234 const gchar *needle)
2236 g_return_val_if_fail (haystack != NULL, NULL);
2237 g_return_val_if_fail (needle != NULL, NULL);
2239 if (haystack_len < 0)
2240 return g_strrstr (haystack, needle);
2243 gsize needle_len = strlen (needle);
2244 const gchar *haystack_max = haystack + haystack_len;
2245 const gchar *p = haystack;
2248 while (p < haystack_max && *p)
2251 if (p < haystack + needle_len)
2256 while (p >= haystack)
2258 for (i = 0; i < needle_len; i++)
2259 if (p[i] != needle[i])
2275 * @str: a nul-terminated string.
2276 * @suffix: the nul-terminated suffix to look for.
2278 * Looks whether the string @str ends with @suffix.
2280 * Return value: TRUE if @str end with @suffix, FALSE otherwise.
2283 g_str_has_suffix (const gchar *str,
2284 const gchar *suffix)
2289 g_return_val_if_fail (str != NULL, FALSE);
2290 g_return_val_if_fail (suffix != NULL, FALSE);
2292 str_len = strlen (str);
2293 suffix_len = strlen (suffix);
2295 if (str_len < suffix_len)
2298 return strcmp (str + str_len - suffix_len, suffix) == 0;
2303 * @str: a nul-terminated string.
2304 * @prefix: the nul-terminated prefix to look for.
2306 * Looks whether the string @str begins with @prefix.
2308 * Return value: TRUE if @str begins with @prefix, FALSE otherwise.
2311 g_str_has_prefix (const gchar *str,
2312 const gchar *prefix)
2317 g_return_val_if_fail (str != NULL, FALSE);
2318 g_return_val_if_fail (prefix != NULL, FALSE);
2320 str_len = strlen (str);
2321 prefix_len = strlen (prefix);
2323 if (str_len < prefix_len)
2326 return strncmp (str, prefix, prefix_len) == 0;