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 vasprintf (&buffer, format, args1);
187 if (!g_mem_is_system_malloc ())
189 gchar *buffer1 = g_strdup (buffer);
196 G_VA_COPY (args2, args1);
198 buffer = g_new (gchar, g_printf_string_upper_bound (format, args1));
200 vsprintf (buffer, format, args2);
207 g_strdup_printf (const gchar *format,
213 va_start (args, format);
214 buffer = g_strdup_vprintf (format, args);
221 g_strconcat (const gchar *string1, ...)
229 g_return_val_if_fail (string1 != NULL, NULL);
231 l = 1 + strlen (string1);
232 va_start (args, string1);
233 s = va_arg (args, gchar*);
237 s = va_arg (args, gchar*);
241 concat = g_new (gchar, l);
244 ptr = g_stpcpy (ptr, string1);
245 va_start (args, string1);
246 s = va_arg (args, gchar*);
249 ptr = g_stpcpy (ptr, s);
250 s = va_arg (args, gchar*);
259 * @nptr: the string to convert to a numeric value.
260 * @endptr: if non-%NULL, it returns the character after
261 * the last character used in the conversion.
263 * Converts a string to a #gdouble value.
264 * It calls the standard strtod() function to handle the conversion, but
265 * if the string is not completely converted it attempts the conversion
266 * again with g_ascii_strtod(), and returns the best match.
268 * This function should seldomly be used. The normal situation when reading
269 * numbers not for human consumption is to use g_ascii_strtod(). Only when
270 * you know that you must expect both locale formatted and C formatted numbers
271 * should you use this. Make sure that you don't pass strings such as comma
272 * separated lists of values, since the commas may be interpreted as a decimal
273 * point in some locales, causing unexpected results.
275 * Return value: the #gdouble value.
278 g_strtod (const gchar *nptr,
286 g_return_val_if_fail (nptr != NULL, 0);
291 val_1 = strtod (nptr, &fail_pos_1);
293 if (fail_pos_1 && fail_pos_1[0] != 0)
294 val_2 = g_ascii_strtod (nptr, &fail_pos_2);
296 if (!fail_pos_1 || fail_pos_1[0] == 0 || fail_pos_1 >= fail_pos_2)
299 *endptr = fail_pos_1;
305 *endptr = fail_pos_2;
312 * @nptr: the string to convert to a numeric value.
313 * @endptr: if non-%NULL, it returns the character after
314 * the last character used in the conversion.
316 * Converts a string to a #gdouble value.
317 * This function behaves like the standard strtod() function
318 * does in the C locale. It does this without actually
319 * changing the current locale, since that would not be
322 * This function is typically used when reading configuration
323 * files or other non-user input that should be locale dependent.
324 * To handle input from the user you should normally use the
325 * locale-sensitive system strtod() function.
327 * To convert from a string to #gdouble in a locale-insensitive
328 * way, use g_ascii_dtostr().
330 * If the correct value would cause overflow, plus or minus %HUGE_VAL
331 * is returned (according to the sign of the value), and %ERANGE is
332 * stored in %errno. If the correct value would cause underflow,
333 * zero is returned and %ERANGE is stored in %errno.
335 * This function resets %errno before calling strtod() so that
336 * you can reliably detect overflow and underflow.
338 * Return value: the #gdouble value.
341 g_ascii_strtod (const gchar *nptr,
346 struct lconv *locale_data;
347 const char *decimal_point;
348 int decimal_point_len;
349 const char *p, *decimal_point_pos;
350 const char *end = NULL; /* Silence gcc */
352 g_return_val_if_fail (nptr != NULL, 0);
356 locale_data = localeconv ();
357 decimal_point = locale_data->decimal_point;
358 decimal_point_len = strlen (decimal_point);
360 g_assert (decimal_point_len != 0);
362 decimal_point_pos = NULL;
363 if (decimal_point[0] != '.' ||
364 decimal_point[1] != 0)
367 /* Skip leading space */
368 while (g_ascii_isspace (*p))
371 /* Skip leading optional sign */
372 if (*p == '+' || *p == '-')
376 (p[1] == 'x' || p[1] == 'X'))
379 /* HEX - find the (optional) decimal point */
381 while (g_ascii_isxdigit (*p))
386 decimal_point_pos = p++;
388 while (g_ascii_isxdigit (*p))
391 if (*p == 'p' || *p == 'P')
393 if (*p == '+' || *p == '-')
395 while (g_ascii_isdigit (*p))
402 while (g_ascii_isdigit (*p))
407 decimal_point_pos = p++;
409 while (g_ascii_isdigit (*p))
412 if (*p == 'e' || *p == 'E')
414 if (*p == '+' || *p == '-')
416 while (g_ascii_isdigit (*p))
421 /* For the other cases, we need not convert the decimal point */
424 /* Set errno to zero, so that we can distinguish zero results
428 if (decimal_point_pos)
432 /* We need to convert the '.' to the locale specific decimal point */
433 copy = g_malloc (end - nptr + 1 + decimal_point_len);
436 memcpy (c, nptr, decimal_point_pos - nptr);
437 c += decimal_point_pos - nptr;
438 memcpy (c, decimal_point, decimal_point_len);
439 c += decimal_point_len;
440 memcpy (c, decimal_point_pos + 1, end - (decimal_point_pos + 1));
441 c += end - (decimal_point_pos + 1);
444 val = strtod (copy, &fail_pos);
448 if (fail_pos > decimal_point_pos)
449 fail_pos = (char *)nptr + (fail_pos - copy) - (decimal_point_len - 1);
451 fail_pos = (char *)nptr + (fail_pos - copy);
458 val = strtod (nptr, &fail_pos);
468 * @buffer: A buffer to place the resulting string in
469 * @buf_len: The length of the buffer.
470 * @d: The #gdouble to convert
472 * Converts a #gdouble to a string, using the '.' as
475 * This functions generates enough precision that converting
476 * the string back using g_strtod() gives the same machine-number
477 * (on machines with IEEE compatible 64bit doubles). It is
478 * guaranteed that the size of the resulting string will never
479 * be larger than @G_ASCII_DTOSTR_BUF_SIZE bytes.
481 * Return value: The pointer to the buffer with the converted string.
484 g_ascii_dtostr (gchar *buffer,
488 return g_ascii_formatd (buffer, buf_len, "%.17g", d);
493 * @buffer: A buffer to place the resulting string in
494 * @buf_len: The length of the buffer.
495 * @format: The printf-style format to use for the
496 * code to use for converting.
497 * @d: The #gdouble to convert
499 * Converts a #gdouble to a string, using the '.' as
500 * decimal point. To format the number you pass in
501 * a printf-style formating string. Allowed conversion
502 * specifiers are 'e', 'E', 'f', 'F', 'g' and 'G'.
504 * If you just want to want to serialize the value into a
505 * string, use g_ascii_dtostr().
507 * Return value: The pointer to the buffer with the converted string.
510 g_ascii_formatd (gchar *buffer,
515 struct lconv *locale_data;
516 const char *decimal_point;
517 int decimal_point_len;
522 g_return_val_if_fail (buffer != NULL, NULL);
523 g_return_val_if_fail (format[0] == '%', NULL);
524 g_return_val_if_fail (strpbrk (format + 1, "'l%") == NULL, NULL);
526 format_char = format[strlen (format) - 1];
528 g_return_val_if_fail (format_char == 'e' || format_char == 'E' ||
529 format_char == 'f' || format_char == 'F' ||
530 format_char == 'g' || format_char == 'G',
533 if (format[0] != '%')
536 if (strpbrk (format + 1, "'l%"))
539 if (!(format_char == 'e' || format_char == 'E' ||
540 format_char == 'f' || format_char == 'F' ||
541 format_char == 'g' || format_char == 'G'))
545 g_snprintf (buffer, buf_len, format, d);
547 locale_data = localeconv ();
548 decimal_point = locale_data->decimal_point;
549 decimal_point_len = strlen (decimal_point);
551 g_assert (decimal_point_len != 0);
553 if (decimal_point[0] != '.' ||
554 decimal_point[1] != 0)
558 if (*p == '+' || *p == '-')
561 while (isdigit ((guchar)*p))
564 if (strncmp (p, decimal_point, decimal_point_len) == 0)
568 if (decimal_point_len > 1) {
569 rest_len = strlen (p + (decimal_point_len-1));
570 memmove (p, p + (decimal_point_len-1),
582 G_CONST_RETURN gchar*
583 g_strerror (gint errnum)
585 static GStaticPrivate msg_private = G_STATIC_PRIVATE_INIT;
589 const char *msg_locale;
591 msg_locale = strerror (errnum);
592 if (g_get_charset (NULL))
596 gchar *msg_utf8 = g_locale_to_utf8 (msg_locale, -1, NULL, NULL, NULL);
599 /* Stick in the quark table so that we can return a static result
601 GQuark msg_quark = g_quark_from_string (msg_utf8);
604 return g_quark_to_string (msg_quark);
611 case E2BIG: return "argument list too long";
614 case EACCES: return "permission denied";
617 case EADDRINUSE: return "address already in use";
620 case EADDRNOTAVAIL: return "can't assign requested address";
623 case EADV: return "advertise error";
626 case EAFNOSUPPORT: return "address family not supported by protocol family";
629 case EAGAIN: return "try again";
632 case EALIGN: return "EALIGN";
635 case EALREADY: return "operation already in progress";
638 case EBADE: return "bad exchange descriptor";
641 case EBADF: return "bad file number";
644 case EBADFD: return "file descriptor in bad state";
647 case EBADMSG: return "not a data message";
650 case EBADR: return "bad request descriptor";
653 case EBADRPC: return "RPC structure is bad";
656 case EBADRQC: return "bad request code";
659 case EBADSLT: return "invalid slot";
662 case EBFONT: return "bad font file format";
665 case EBUSY: return "mount device busy";
668 case ECHILD: return "no children";
671 case ECHRNG: return "channel number out of range";
674 case ECOMM: return "communication error on send";
677 case ECONNABORTED: return "software caused connection abort";
680 case ECONNREFUSED: return "connection refused";
683 case ECONNRESET: return "connection reset by peer";
685 #if defined(EDEADLK) && (!defined(EWOULDBLOCK) || (EDEADLK != EWOULDBLOCK))
686 case EDEADLK: return "resource deadlock avoided";
689 case EDEADLOCK: return "resource deadlock avoided";
692 case EDESTADDRREQ: return "destination address required";
695 case EDIRTY: return "mounting a dirty fs w/o force";
698 case EDOM: return "math argument out of range";
701 case EDOTDOT: return "cross mount point";
704 case EDQUOT: return "disk quota exceeded";
707 case EDUPPKG: return "duplicate package name";
710 case EEXIST: return "file already exists";
713 case EFAULT: return "bad address in system call argument";
716 case EFBIG: return "file too large";
719 case EHOSTDOWN: return "host is down";
722 case EHOSTUNREACH: return "host is unreachable";
725 case EIDRM: return "identifier removed";
728 case EINIT: return "initialization error";
731 case EINPROGRESS: return "operation now in progress";
734 case EINTR: return "interrupted system call";
737 case EINVAL: return "invalid argument";
740 case EIO: return "I/O error";
743 case EISCONN: return "socket is already connected";
746 case EISDIR: return "is a directory";
749 case EISNAM: return "is a name file";
752 case ELBIN: return "ELBIN";
755 case EL2HLT: return "level 2 halted";
758 case EL2NSYNC: return "level 2 not synchronized";
761 case EL3HLT: return "level 3 halted";
764 case EL3RST: return "level 3 reset";
767 case ELIBACC: return "can not access a needed shared library";
770 case ELIBBAD: return "accessing a corrupted shared library";
773 case ELIBEXEC: return "can not exec a shared library directly";
776 case ELIBMAX: return "attempting to link in more shared libraries than system limit";
779 case ELIBSCN: return ".lib section in a.out corrupted";
782 case ELNRNG: return "link number out of range";
785 case ELOOP: return "too many levels of symbolic links";
788 case EMFILE: return "too many open files";
791 case EMLINK: return "too many links";
794 case EMSGSIZE: return "message too long";
797 case EMULTIHOP: return "multihop attempted";
800 case ENAMETOOLONG: return "file name too long";
803 case ENAVAIL: return "not available";
806 case ENET: return "ENET";
809 case ENETDOWN: return "network is down";
812 case ENETRESET: return "network dropped connection on reset";
815 case ENETUNREACH: return "network is unreachable";
818 case ENFILE: return "file table overflow";
821 case ENOANO: return "anode table overflow";
823 #if defined(ENOBUFS) && (!defined(ENOSR) || (ENOBUFS != ENOSR))
824 case ENOBUFS: return "no buffer space available";
827 case ENOCSI: return "no CSI structure available";
830 case ENODATA: return "no data available";
833 case ENODEV: return "no such device";
836 case ENOENT: return "no such file or directory";
839 case ENOEXEC: return "exec format error";
842 case ENOLCK: return "no locks available";
845 case ENOLINK: return "link has be severed";
848 case ENOMEM: return "not enough memory";
851 case ENOMSG: return "no message of desired type";
854 case ENONET: return "machine is not on the network";
857 case ENOPKG: return "package not installed";
860 case ENOPROTOOPT: return "bad proocol option";
863 case ENOSPC: return "no space left on device";
866 case ENOSR: return "out of stream resources";
869 case ENOSTR: return "not a stream device";
872 case ENOSYM: return "unresolved symbol name";
875 case ENOSYS: return "function not implemented";
878 case ENOTBLK: return "block device required";
881 case ENOTCONN: return "socket is not connected";
884 case ENOTDIR: return "not a directory";
887 case ENOTEMPTY: return "directory not empty";
890 case ENOTNAM: return "not a name file";
893 case ENOTSOCK: return "socket operation on non-socket";
896 case ENOTTY: return "inappropriate device for ioctl";
899 case ENOTUNIQ: return "name not unique on network";
902 case ENXIO: return "no such device or address";
905 case EOPNOTSUPP: return "operation not supported on socket";
908 case EPERM: return "not owner";
911 case EPFNOSUPPORT: return "protocol family not supported";
914 case EPIPE: return "broken pipe";
917 case EPROCLIM: return "too many processes";
920 case EPROCUNAVAIL: return "bad procedure for program";
923 case EPROGMISMATCH: return "program version wrong";
926 case EPROGUNAVAIL: return "RPC program not available";
929 case EPROTO: return "protocol error";
931 #ifdef EPROTONOSUPPORT
932 case EPROTONOSUPPORT: return "protocol not suppored";
935 case EPROTOTYPE: return "protocol wrong type for socket";
938 case ERANGE: return "math result unrepresentable";
940 #if defined(EREFUSED) && (!defined(ECONNREFUSED) || (EREFUSED != ECONNREFUSED))
941 case EREFUSED: return "EREFUSED";
944 case EREMCHG: return "remote address changed";
947 case EREMDEV: return "remote device";
950 case EREMOTE: return "pathname hit remote file system";
953 case EREMOTEIO: return "remote i/o error";
955 #ifdef EREMOTERELEASE
956 case EREMOTERELEASE: return "EREMOTERELEASE";
959 case EROFS: return "read-only file system";
962 case ERPCMISMATCH: return "RPC version is wrong";
965 case ERREMOTE: return "object is remote";
968 case ESHUTDOWN: return "can't send afer socket shutdown";
970 #ifdef ESOCKTNOSUPPORT
971 case ESOCKTNOSUPPORT: return "socket type not supported";
974 case ESPIPE: return "invalid seek";
977 case ESRCH: return "no such process";
980 case ESRMNT: return "srmount error";
983 case ESTALE: return "stale remote file handle";
986 case ESUCCESS: return "Error 0";
989 case ETIME: return "timer expired";
992 case ETIMEDOUT: return "connection timed out";
995 case ETOOMANYREFS: return "too many references: can't splice";
998 case ETXTBSY: return "text file or pseudo-device busy";
1001 case EUCLEAN: return "structure needs cleaning";
1004 case EUNATCH: return "protocol driver not attached";
1007 case EUSERS: return "too many users";
1010 case EVERSION: return "version mismatch";
1012 #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
1013 case EWOULDBLOCK: return "operation would block";
1016 case EXDEV: return "cross-domain link";
1019 case EXFULL: return "message tables full";
1022 #else /* NO_SYS_ERRLIST */
1023 extern int sys_nerr;
1024 extern char *sys_errlist[];
1026 if ((errnum > 0) && (errnum <= sys_nerr))
1027 return sys_errlist [errnum];
1028 #endif /* NO_SYS_ERRLIST */
1030 msg = g_static_private_get (&msg_private);
1033 msg = g_new (gchar, 64);
1034 g_static_private_set (&msg_private, msg, g_free);
1037 sprintf (msg, "unknown error (%d)", errnum);
1042 G_CONST_RETURN gchar*
1043 g_strsignal (gint signum)
1045 static GStaticPrivate msg_private = G_STATIC_PRIVATE_INIT;
1048 #ifdef HAVE_STRSIGNAL
1049 const char *msg_locale;
1051 #if defined(G_OS_BEOS) || defined(G_WITH_CYGWIN)
1052 extern const char *strsignal(int);
1054 /* this is declared differently (const) in string.h on BeOS */
1055 extern char *strsignal (int sig);
1056 #endif /* !G_OS_BEOS && !G_WITH_CYGWIN */
1057 msg_locale = strsignal (signum);
1058 if (g_get_charset (NULL))
1062 gchar *msg_utf8 = g_locale_to_utf8 (msg_locale, -1, NULL, NULL, NULL);
1065 /* Stick in the quark table so that we can return a static result
1067 GQuark msg_quark = g_quark_from_string (msg_utf8);
1070 return g_quark_to_string (msg_quark);
1073 #elif NO_SYS_SIGLIST
1077 case SIGHUP: return "Hangup";
1080 case SIGINT: return "Interrupt";
1083 case SIGQUIT: return "Quit";
1086 case SIGILL: return "Illegal instruction";
1089 case SIGTRAP: return "Trace/breakpoint trap";
1092 case SIGABRT: return "IOT trap/Abort";
1095 case SIGBUS: return "Bus error";
1098 case SIGFPE: return "Floating point exception";
1101 case SIGKILL: return "Killed";
1104 case SIGUSR1: return "User defined signal 1";
1107 case SIGSEGV: return "Segmentation fault";
1110 case SIGUSR2: return "User defined signal 2";
1113 case SIGPIPE: return "Broken pipe";
1116 case SIGALRM: return "Alarm clock";
1119 case SIGTERM: return "Terminated";
1122 case SIGSTKFLT: return "Stack fault";
1125 case SIGCHLD: return "Child exited";
1128 case SIGCONT: return "Continued";
1131 case SIGSTOP: return "Stopped (signal)";
1134 case SIGTSTP: return "Stopped";
1137 case SIGTTIN: return "Stopped (tty input)";
1140 case SIGTTOU: return "Stopped (tty output)";
1143 case SIGURG: return "Urgent condition";
1146 case SIGXCPU: return "CPU time limit exceeded";
1149 case SIGXFSZ: return "File size limit exceeded";
1152 case SIGVTALRM: return "Virtual time alarm";
1155 case SIGPROF: return "Profile signal";
1158 case SIGWINCH: return "Window size changed";
1161 case SIGIO: return "Possible I/O";
1164 case SIGPWR: return "Power failure";
1167 case SIGUNUSED: return "Unused signal";
1170 #else /* NO_SYS_SIGLIST */
1172 #ifdef NO_SYS_SIGLIST_DECL
1173 extern char *sys_siglist[]; /*(see Tue Jan 19 00:44:24 1999 in changelog)*/
1176 return (char*) /* this function should return const --josh */ sys_siglist [signum];
1177 #endif /* NO_SYS_SIGLIST */
1179 msg = g_static_private_get (&msg_private);
1182 msg = g_new (gchar, 64);
1183 g_static_private_set (&msg_private, msg, g_free);
1186 sprintf (msg, "unknown signal (%d)", signum);
1191 /* Functions g_strlcpy and g_strlcat were originally developed by
1192 * Todd C. Miller <Todd.Miller@courtesan.com> to simplify writing secure code.
1193 * See ftp://ftp.openbsd.org/pub/OpenBSD/src/lib/libc/string/strlcpy.3
1194 * for more information.
1198 /* Use the native ones, if available; they might be implemented in assembly */
1200 g_strlcpy (gchar *dest,
1204 g_return_val_if_fail (dest != NULL, 0);
1205 g_return_val_if_fail (src != NULL, 0);
1207 return strlcpy (dest, src, dest_size);
1211 g_strlcat (gchar *dest,
1215 g_return_val_if_fail (dest != NULL, 0);
1216 g_return_val_if_fail (src != NULL, 0);
1218 return strlcat (dest, src, dest_size);
1221 #else /* ! HAVE_STRLCPY */
1224 * Copy string src to buffer dest (of buffer size dest_size). At most
1225 * dest_size-1 characters will be copied. Always NUL terminates
1226 * (unless dest_size == 0). This function does NOT allocate memory.
1227 * Unlike strncpy, this function doesn't pad dest (so it's often faster).
1228 * Returns size of attempted result, strlen(src),
1229 * so if retval >= dest_size, truncation occurred.
1232 g_strlcpy (gchar *dest,
1236 register gchar *d = dest;
1237 register const gchar *s = src;
1238 register gsize n = dest_size;
1240 g_return_val_if_fail (dest != NULL, 0);
1241 g_return_val_if_fail (src != NULL, 0);
1243 /* Copy as many bytes as will fit */
1244 if (n != 0 && --n != 0)
1247 register gchar c = *s++;
1255 /* If not enough room in dest, add NUL and traverse rest of src */
1264 return s - src - 1; /* count does not include NUL */
1269 * Appends string src to buffer dest (of buffer size dest_size).
1270 * At most dest_size-1 characters will be copied.
1271 * Unlike strncat, dest_size is the full size of dest, not the space left over.
1272 * This function does NOT allocate memory.
1273 * This always NUL terminates (unless siz == 0 or there were no NUL characters
1274 * in the dest_size characters of dest to start with).
1275 * Returns size of attempted result, which is
1276 * MIN (dest_size, strlen (original dest)) + strlen (src),
1277 * so if retval >= dest_size, truncation occurred.
1280 g_strlcat (gchar *dest,
1284 register gchar *d = dest;
1285 register const gchar *s = src;
1286 register gsize bytes_left = dest_size;
1287 gsize dlength; /* Logically, MIN (strlen (d), dest_size) */
1289 g_return_val_if_fail (dest != NULL, 0);
1290 g_return_val_if_fail (src != NULL, 0);
1292 /* Find the end of dst and adjust bytes left but don't go past end */
1293 while (*d != 0 && bytes_left-- != 0)
1296 bytes_left = dest_size - dlength;
1298 if (bytes_left == 0)
1299 return dlength + strlen (s);
1303 if (bytes_left != 1)
1312 return dlength + (s - src); /* count does not include NUL */
1314 #endif /* ! HAVE_STRLCPY */
1319 * @len: length of @str in bytes, or -1 if @str is nul-terminated.
1321 * Converts all upper case ASCII letters to lower case ASCII letters.
1323 * Return value: a newly-allocated string, with all the upper case
1324 * characters in @str converted to lower case, with
1325 * semantics that exactly match g_ascii_tolower(). (Note
1326 * that this is unlike the old g_strdown(), which modified
1327 * the string in place.)
1330 g_ascii_strdown (const gchar *str,
1335 g_return_val_if_fail (str != NULL, NULL);
1340 result = g_strndup (str, len);
1341 for (s = result; *s; s++)
1342 *s = g_ascii_tolower (*s);
1350 * @len: length of @str in bytes, or -1 if @str is nul-terminated.
1352 * Converts all lower case ASCII letters to upper case ASCII letters.
1354 * Return value: a newly allocated string, with all the lower case
1355 * characters in @str converted to upper case, with
1356 * semantics that exactly match g_ascii_toupper(). (Note
1357 * that this is unlike the old g_strup(), which modified
1358 * the string in place.)
1361 g_ascii_strup (const gchar *str,
1366 g_return_val_if_fail (str != NULL, NULL);
1371 result = g_strndup (str, len);
1372 for (s = result; *s; s++)
1373 *s = g_ascii_toupper (*s);
1379 g_strdown (gchar *string)
1383 g_return_val_if_fail (string != NULL, NULL);
1385 s = (guchar *) string;
1394 return (gchar *) string;
1398 g_strup (gchar *string)
1402 g_return_val_if_fail (string != NULL, NULL);
1404 s = (guchar *) string;
1413 return (gchar *) string;
1417 g_strreverse (gchar *string)
1419 g_return_val_if_fail (string != NULL, NULL);
1423 register gchar *h, *t;
1426 t = string + strlen (string) - 1;
1445 * @c: any character.
1447 * Convert a character to ASCII lower case.
1449 * Unlike the standard C library tolower() function, this only
1450 * recognizes standard ASCII letters and ignores the locale, returning
1451 * all non-ASCII characters unchanged, even if they are lower case
1452 * letters in a particular character set. Also unlike the standard
1453 * library function, this takes and returns a char, not an int, so
1454 * don't call it on %EOF but no need to worry about casting to #guchar
1455 * before passing a possibly non-ASCII character in.
1457 * Return value: the result of converting @c to lower case.
1458 * If @c is not an ASCII upper case letter,
1459 * @c is returned unchanged.
1462 g_ascii_tolower (gchar c)
1464 return g_ascii_isupper (c) ? c - 'A' + 'a' : c;
1469 * @c: any character.
1471 * Convert a character to ASCII upper case.
1473 * Unlike the standard C library toupper() function, this only
1474 * recognizes standard ASCII letters and ignores the locale, returning
1475 * all non-ASCII characters unchanged, even if they are upper case
1476 * letters in a particular character set. Also unlike the standard
1477 * library function, this takes and returns a char, not an int, so
1478 * don't call it on %EOF but no need to worry about casting to #guchar
1479 * before passing a possibly non-ASCII character in.
1481 * Return value: the result of converting @c to upper case.
1482 * If @c is not an ASCII lower case letter,
1483 * @c is returned unchanged.
1486 g_ascii_toupper (gchar c)
1488 return g_ascii_islower (c) ? c - 'a' + 'A' : c;
1492 * g_ascii_digit_value:
1493 * @c: an ASCII character.
1495 * Determines the numeric value of a character as a decimal
1496 * digit. Differs from g_unichar_digit_value() because it takes
1497 * a char, so there's no worry about sign extension if characters
1500 * Return value: If @c is a decimal digit (according to
1501 * g_ascii_isdigit()), its numeric value. Otherwise, -1.
1504 g_ascii_digit_value (gchar c)
1506 if (g_ascii_isdigit (c))
1512 * g_ascii_xdigit_value:
1513 * @c: an ASCII character.
1515 * Determines the numeric value of a character as a hexidecimal
1516 * digit. Differs from g_unichar_xdigit_value() because it takes
1517 * a char, so there's no worry about sign extension if characters
1520 * Return value: If @c is a hex digit (according to
1521 * g_ascii_isxdigit()), its numeric value. Otherwise, -1.
1524 g_ascii_xdigit_value (gchar c)
1526 if (c >= 'A' && c <= 'F')
1527 return c - 'A' + 10;
1528 if (c >= 'a' && c <= 'f')
1529 return c - 'a' + 10;
1530 return g_ascii_digit_value (c);
1534 * g_ascii_strcasecmp:
1535 * @s1: string to compare with @s2.
1536 * @s2: string to compare with @s1.
1538 * Compare two strings, ignoring the case of ASCII characters.
1540 * Unlike the BSD strcasecmp() function, this only recognizes standard
1541 * ASCII letters and ignores the locale, treating all non-ASCII
1542 * characters as if they are not letters.
1544 * Return value: an integer less than, equal to, or greater than
1545 * zero if @s1 is found, respectively, to be less than,
1546 * to match, or to be greater than @s2.
1549 g_ascii_strcasecmp (const gchar *s1,
1554 g_return_val_if_fail (s1 != NULL, 0);
1555 g_return_val_if_fail (s2 != NULL, 0);
1559 c1 = (gint)(guchar) g_ascii_tolower (*s1);
1560 c2 = (gint)(guchar) g_ascii_tolower (*s2);
1566 return (((gint)(guchar) *s1) - ((gint)(guchar) *s2));
1570 * g_ascii_strncasecmp:
1571 * @s1: string to compare with @s2.
1572 * @s2: string to compare with @s1.
1573 * @n: number of characters to compare.
1575 * Compare @s1 and @s2, ignoring the case of ASCII characters and any
1576 * characters after the first @n in each string.
1578 * Unlike the BSD strcasecmp() function, this only recognizes standard
1579 * ASCII letters and ignores the locale, treating all non-ASCII
1580 * characters as if they are not letters.
1582 * Return value: an integer less than, equal to, or greater than zero
1583 * if the first @n bytes of @s1 is found, respectively,
1584 * to be less than, to match, or to be greater than the
1585 * first @n bytes of @s2.
1588 g_ascii_strncasecmp (const gchar *s1,
1594 g_return_val_if_fail (s1 != NULL, 0);
1595 g_return_val_if_fail (s2 != NULL, 0);
1597 while (n && *s1 && *s2)
1600 c1 = (gint)(guchar) g_ascii_tolower (*s1);
1601 c2 = (gint)(guchar) g_ascii_tolower (*s2);
1608 return (((gint) (guchar) *s1) - ((gint) (guchar) *s2));
1614 g_strcasecmp (const gchar *s1,
1617 #ifdef HAVE_STRCASECMP
1618 g_return_val_if_fail (s1 != NULL, 0);
1619 g_return_val_if_fail (s2 != NULL, 0);
1621 return strcasecmp (s1, s2);
1625 g_return_val_if_fail (s1 != NULL, 0);
1626 g_return_val_if_fail (s2 != NULL, 0);
1630 /* According to A. Cox, some platforms have islower's that
1631 * don't work right on non-uppercase
1633 c1 = isupper ((guchar)*s1) ? tolower ((guchar)*s1) : *s1;
1634 c2 = isupper ((guchar)*s2) ? tolower ((guchar)*s2) : *s2;
1640 return (((gint)(guchar) *s1) - ((gint)(guchar) *s2));
1645 g_strncasecmp (const gchar *s1,
1649 #ifdef HAVE_STRNCASECMP
1650 return strncasecmp (s1, s2, n);
1654 g_return_val_if_fail (s1 != NULL, 0);
1655 g_return_val_if_fail (s2 != NULL, 0);
1657 while (n && *s1 && *s2)
1660 /* According to A. Cox, some platforms have islower's that
1661 * don't work right on non-uppercase
1663 c1 = isupper ((guchar)*s1) ? tolower ((guchar)*s1) : *s1;
1664 c2 = isupper ((guchar)*s2) ? tolower ((guchar)*s2) : *s2;
1671 return (((gint) (guchar) *s1) - ((gint) (guchar) *s2));
1678 g_strdelimit (gchar *string,
1679 const gchar *delimiters,
1684 g_return_val_if_fail (string != NULL, NULL);
1687 delimiters = G_STR_DELIMITERS;
1689 for (c = string; *c; c++)
1691 if (strchr (delimiters, *c))
1699 g_strcanon (gchar *string,
1700 const gchar *valid_chars,
1705 g_return_val_if_fail (string != NULL, NULL);
1706 g_return_val_if_fail (valid_chars != NULL, NULL);
1708 for (c = string; *c; c++)
1710 if (!strchr (valid_chars, *c))
1718 g_strcompress (const gchar *source)
1720 const gchar *p = source, *octal;
1721 gchar *dest = g_malloc (strlen (source) + 1);
1731 case '0': case '1': case '2': case '3': case '4':
1732 case '5': case '6': case '7':
1735 while ((p < octal + 3) && (*p >= '0') && (*p <= '7'))
1737 *q = (*q * 8) + (*p - '0');
1758 default: /* Also handles \" and \\ */
1773 g_strescape (const gchar *source,
1774 const gchar *exceptions)
1781 g_return_val_if_fail (source != NULL, NULL);
1783 p = (guchar *) source;
1784 /* Each source byte needs maximally four destination chars (\777) */
1785 q = dest = g_malloc (strlen (source) * 4 + 1);
1787 memset (excmap, 0, 256);
1790 guchar *e = (guchar *) exceptions;
1836 if ((*p < ' ') || (*p >= 0177))
1839 *q++ = '0' + (((*p) >> 6) & 07);
1840 *q++ = '0' + (((*p) >> 3) & 07);
1841 *q++ = '0' + ((*p) & 07);
1855 g_strchug (gchar *string)
1859 g_return_val_if_fail (string != NULL, NULL);
1861 for (start = (guchar*) string; *start && g_ascii_isspace (*start); start++)
1864 g_memmove (string, start, strlen ((gchar *) start) + 1);
1870 g_strchomp (gchar *string)
1874 g_return_val_if_fail (string != NULL, NULL);
1879 for (s = string + strlen (string) - 1; s >= string && g_ascii_isspace ((guchar)*s);
1888 * @string: a string to split.
1889 * @delimiter: a string which specifies the places at which to split the string.
1890 * The delimiter is not included in any of the resulting strings, unless
1891 * @max_tokens is reached.
1892 * @max_tokens: the maximum number of pieces to split @string into. If this is
1893 * less than 1, the string is split completely.
1895 * Splits a string into a maximum of @max_tokens pieces, using the given
1896 * @delimiter. If @max_tokens is reached, the remainder of @string is appended
1897 * to the last token.
1899 * As a special case, the result of splitting the empty string "" is an empty
1900 * vector, not a vector containing a single string. The reason for this
1901 * special case is that being able to represent a empty vector is typically
1902 * more useful than consistent handling of empty elements. If you do need
1903 * to represent empty elements, you'll need to check for the empty string
1904 * before calling g_strsplit().
1906 * Return value: a newly-allocated %NULL-terminated array of strings. Use
1907 * g_strfreev() to free it.
1910 g_strsplit (const gchar *string,
1911 const gchar *delimiter,
1914 GSList *string_list = NULL, *slist;
1915 gchar **str_array, *s;
1917 const gchar *remainder;
1919 g_return_val_if_fail (string != NULL, NULL);
1920 g_return_val_if_fail (delimiter != NULL, NULL);
1921 g_return_val_if_fail (delimiter[0] != '\0', NULL);
1924 max_tokens = G_MAXINT;
1927 s = strstr (remainder, delimiter);
1930 gsize delimiter_len = strlen (delimiter);
1932 while (--max_tokens && s)
1937 len = s - remainder;
1938 new_string = g_new (gchar, len + 1);
1939 strncpy (new_string, remainder, len);
1940 new_string[len] = 0;
1941 string_list = g_slist_prepend (string_list, new_string);
1943 remainder = s + delimiter_len;
1944 s = strstr (remainder, delimiter);
1950 string_list = g_slist_prepend (string_list, g_strdup (remainder));
1953 str_array = g_new (gchar*, n + 1);
1955 str_array[n--] = NULL;
1956 for (slist = string_list; slist; slist = slist->next)
1957 str_array[n--] = slist->data;
1959 g_slist_free (string_list);
1965 g_strfreev (gchar **str_array)
1971 for(i = 0; str_array[i] != NULL; i++)
1972 g_free(str_array[i]);
1980 * @str_array: %NULL-terminated array of strings.
1982 * Copies %NULL-terminated array of strings. The copy is a deep copy;
1983 * the new array should be freed by first freeing each string, then
1984 * the array itself. g_strfreev() does this for you. If called
1985 * on a %NULL value, g_strdupv() simply returns %NULL.
1987 * Return value: a new %NULL-terminated array of strings.
1990 g_strdupv (gchar **str_array)
1998 while (str_array[i])
2001 retval = g_new (gchar*, i + 1);
2004 while (str_array[i])
2006 retval[i] = g_strdup (str_array[i]);
2018 g_strjoinv (const gchar *separator,
2024 g_return_val_if_fail (str_array != NULL, NULL);
2026 if (separator == NULL)
2033 gsize separator_len;
2035 separator_len = strlen (separator);
2036 /* First part, getting length */
2037 len = 1 + strlen (str_array[0]);
2038 for (i = 1; str_array[i] != NULL; i++)
2039 len += strlen (str_array[i]);
2040 len += separator_len * (i - 1);
2042 /* Second part, building string */
2043 string = g_new (gchar, len);
2044 ptr = g_stpcpy (string, *str_array);
2045 for (i = 1; str_array[i] != NULL; i++)
2047 ptr = g_stpcpy (ptr, separator);
2048 ptr = g_stpcpy (ptr, str_array[i]);
2052 string = g_strdup ("");
2058 g_strjoin (const gchar *separator,
2064 gsize separator_len;
2067 if (separator == NULL)
2070 separator_len = strlen (separator);
2072 va_start (args, separator);
2074 s = va_arg (args, gchar*);
2078 /* First part, getting length */
2079 len = 1 + strlen (s);
2081 s = va_arg (args, gchar*);
2084 len += separator_len + strlen (s);
2085 s = va_arg (args, gchar*);
2089 /* Second part, building string */
2090 string = g_new (gchar, len);
2092 va_start (args, separator);
2094 s = va_arg (args, gchar*);
2095 ptr = g_stpcpy (string, s);
2097 s = va_arg (args, gchar*);
2100 ptr = g_stpcpy (ptr, separator);
2101 ptr = g_stpcpy (ptr, s);
2102 s = va_arg (args, gchar*);
2106 string = g_strdup ("");
2116 * @haystack: a string.
2117 * @haystack_len: the maximum length of @haystack.
2118 * @needle: the string to search for.
2120 * Searches the string @haystack for the first occurrence
2121 * of the string @needle, limiting the length of the search
2124 * Return value: a pointer to the found occurrence, or
2125 * %NULL if not found.
2128 g_strstr_len (const gchar *haystack,
2129 gssize haystack_len,
2130 const gchar *needle)
2132 g_return_val_if_fail (haystack != NULL, NULL);
2133 g_return_val_if_fail (needle != NULL, NULL);
2135 if (haystack_len < 0)
2136 return strstr (haystack, needle);
2139 const gchar *p = haystack;
2140 gsize needle_len = strlen (needle);
2144 if (needle_len == 0)
2145 return (gchar *)haystack;
2147 if (haystack_len < needle_len)
2150 end = haystack + haystack_len - needle_len;
2152 while (*p && p <= end)
2154 for (i = 0; i < needle_len; i++)
2155 if (p[i] != needle[i])
2170 * @haystack: a nul-terminated string.
2171 * @needle: the nul-terminated string to search for.
2173 * Searches the string @haystack for the last occurrence
2174 * of the string @needle.
2176 * Return value: a pointer to the found occurrence, or
2177 * %NULL if not found.
2180 g_strrstr (const gchar *haystack,
2181 const gchar *needle)
2188 g_return_val_if_fail (haystack != NULL, NULL);
2189 g_return_val_if_fail (needle != NULL, NULL);
2191 needle_len = strlen (needle);
2192 haystack_len = strlen (haystack);
2194 if (needle_len == 0)
2195 return (gchar *)haystack;
2197 if (haystack_len < needle_len)
2200 p = haystack + haystack_len - needle_len;
2202 while (p >= haystack)
2204 for (i = 0; i < needle_len; i++)
2205 if (p[i] != needle[i])
2219 * @haystack: a nul-terminated string.
2220 * @haystack_len: the maximum length of @haystack.
2221 * @needle: the nul-terminated string to search for.
2223 * Searches the string @haystack for the last occurrence
2224 * of the string @needle, limiting the length of the search
2227 * Return value: a pointer to the found occurrence, or
2228 * %NULL if not found.
2231 g_strrstr_len (const gchar *haystack,
2232 gssize haystack_len,
2233 const gchar *needle)
2235 g_return_val_if_fail (haystack != NULL, NULL);
2236 g_return_val_if_fail (needle != NULL, NULL);
2238 if (haystack_len < 0)
2239 return g_strrstr (haystack, needle);
2242 gsize needle_len = strlen (needle);
2243 const gchar *haystack_max = haystack + haystack_len;
2244 const gchar *p = haystack;
2247 while (p < haystack_max && *p)
2250 if (p < haystack + needle_len)
2255 while (p >= haystack)
2257 for (i = 0; i < needle_len; i++)
2258 if (p[i] != needle[i])