1 /* GLIB - Library of useful routines for C programming
2 * Copyright (C) 2006-2019 Free Software Foundation, Inc.
3 *
4 * This file is not part of the GNU gettext program, but is used with
5 * GNU gettext.
6 *
7 * The original copyright notice is as follows:
8 */
9
10 /* GLIB - Library of useful routines for C programming
11 * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
12 *
13 * This library is free software; you can redistribute it and/or
14 * modify it under the terms of the GNU Lesser General Public
15 * License as published by the Free Software Foundation; either
16 * version 2 of the License, or (at your option) any later version.
17 *
18 * This library is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
21 * Lesser General Public License for more details.
22 *
23 * You should have received a copy of the GNU Lesser General Public
24 * License along with this library; if not, write to the
25 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
26 * Boston, MA 02111-1307, USA.
27 */
28
29 /*
30 * Modified by the GLib Team and others 1997-2000. See the AUTHORS
31 * file for a list of people on the GLib Team. See the ChangeLog
32 * files for a list of changes. These files are distributed with
33 * GLib at ftp://ftp.gtk.org/pub/gtk/.
34 */
35
36 /*
37 * Modified by Bruno Haible for use as a gnulib module.
38 */
39
40 /*
41 * MT safe
42 */
43
44 #include "config.h"
45
46 #if 0
47 #define _GNU_SOURCE /* For stpcpy */
48 #endif
49
50 #include <stdarg.h>
51 #include <stdio.h>
52 #include <stdlib.h>
53 #include <string.h>
54 #include <locale.h>
55 #include <errno.h>
56 #include <ctype.h> /* For tolower() */
57 #if !defined (HAVE_STRSIGNAL) || !defined(NO_SYS_SIGLIST_DECL)
58 #include <signal.h>
59 #endif
60
61 #include "glib.h"
62 #if 0
63 #include "gprintf.h"
64 #endif
65 #include "gprintfint.h"
66
67 #if 0
68 #include "galias.h"
69
70 #ifdef G_OS_WIN32
71 #include <windows.h>
72 #endif
73 #endif
74
75 /* do not include <unistd.h> in this place since it
76 * interferes with g_strsignal() on some OSes
77 */
78
79 static const guint16 ascii_table_data[256] = {
80 0x004, 0x004, 0x004, 0x004, 0x004, 0x004, 0x004, 0x004,
81 0x004, 0x104, 0x104, 0x004, 0x104, 0x104, 0x004, 0x004,
82 0x004, 0x004, 0x004, 0x004, 0x004, 0x004, 0x004, 0x004,
83 0x004, 0x004, 0x004, 0x004, 0x004, 0x004, 0x004, 0x004,
84 0x140, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0,
85 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0,
86 0x459, 0x459, 0x459, 0x459, 0x459, 0x459, 0x459, 0x459,
87 0x459, 0x459, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0,
88 0x0d0, 0x653, 0x653, 0x653, 0x653, 0x653, 0x653, 0x253,
89 0x253, 0x253, 0x253, 0x253, 0x253, 0x253, 0x253, 0x253,
90 0x253, 0x253, 0x253, 0x253, 0x253, 0x253, 0x253, 0x253,
91 0x253, 0x253, 0x253, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0,
92 0x0d0, 0x473, 0x473, 0x473, 0x473, 0x473, 0x473, 0x073,
93 0x073, 0x073, 0x073, 0x073, 0x073, 0x073, 0x073, 0x073,
94 0x073, 0x073, 0x073, 0x073, 0x073, 0x073, 0x073, 0x073,
95 0x073, 0x073, 0x073, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x004
96 /* the upper 128 are all zeroes */
97 };
98
99 const guint16 * const g_ascii_table = ascii_table_data;
100
101 gchar*
g_strdup(const gchar * str)102 g_strdup (const gchar *str)
103 {
104 gchar *new_str;
105 gsize length;
106
107 if (str)
108 {
109 length = strlen (str) + 1;
110 new_str = g_new (char, length);
111 memcpy (new_str, str, length);
112 }
113 else
114 new_str = NULL;
115
116 return new_str;
117 }
118
119 #if 0
120
121 gpointer
122 g_memdup (gconstpointer mem,
123 guint byte_size)
124 {
125 gpointer new_mem;
126
127 if (mem)
128 {
129 new_mem = g_malloc (byte_size);
130 memcpy (new_mem, mem, byte_size);
131 }
132 else
133 new_mem = NULL;
134
135 return new_mem;
136 }
137
138 #endif
139
140 gchar*
g_strndup(const gchar * str,gsize n)141 g_strndup (const gchar *str,
142 gsize n)
143 {
144 gchar *new_str;
145
146 if (str)
147 {
148 new_str = g_new (gchar, n + 1);
149 strncpy (new_str, str, n);
150 new_str[n] = '\0';
151 }
152 else
153 new_str = NULL;
154
155 return new_str;
156 }
157
158 #if 0
159
160 gchar*
161 g_strnfill (gsize length,
162 gchar fill_char)
163 {
164 gchar *str;
165
166 str = g_new (gchar, length + 1);
167 memset (str, (guchar)fill_char, length);
168 str[length] = '\0';
169
170 return str;
171 }
172
173 #endif
174
175 /**
176 * g_stpcpy:
177 * @dest: destination buffer.
178 * @src: source string.
179 *
180 * Copies a nul-terminated string into the dest buffer, include the
181 * trailing nul, and return a pointer to the trailing nul byte.
182 * This is useful for concatenating multiple strings together
183 * without having to repeatedly scan for the end.
184 *
185 * Return value: a pointer to trailing nul byte.
186 **/
187 gchar *
g_stpcpy(gchar * dest,const gchar * src)188 g_stpcpy (gchar *dest,
189 const gchar *src)
190 {
191 #ifdef HAVE_STPCPY
192 g_return_val_if_fail (dest != NULL, NULL);
193 g_return_val_if_fail (src != NULL, NULL);
194 return stpcpy (dest, src);
195 #else
196 register gchar *d = dest;
197 register const gchar *s = src;
198
199 g_return_val_if_fail (dest != NULL, NULL);
200 g_return_val_if_fail (src != NULL, NULL);
201 do
202 *d++ = *s;
203 while (*s++ != '\0');
204
205 return d - 1;
206 #endif
207 }
208
209 gchar*
g_strdup_vprintf(const gchar * format,va_list args)210 g_strdup_vprintf (const gchar *format,
211 va_list args)
212 {
213 gchar *string = NULL;
214
215 g_vasprintf (&string, format, args);
216
217 return string;
218 }
219
220 gchar*
g_strdup_printf(const gchar * format,...)221 g_strdup_printf (const gchar *format,
222 ...)
223 {
224 gchar *buffer;
225 va_list args;
226
227 va_start (args, format);
228 buffer = g_strdup_vprintf (format, args);
229 va_end (args);
230
231 return buffer;
232 }
233
234 gchar*
g_strconcat(const gchar * string1,...)235 g_strconcat (const gchar *string1, ...)
236 {
237 gsize l;
238 va_list args;
239 gchar *s;
240 gchar *concat;
241 gchar *ptr;
242
243 if (!string1)
244 return NULL;
245
246 l = 1 + strlen (string1);
247 va_start (args, string1);
248 s = va_arg (args, gchar*);
249 while (s)
250 {
251 l += strlen (s);
252 s = va_arg (args, gchar*);
253 }
254 va_end (args);
255
256 concat = g_new (gchar, l);
257 ptr = concat;
258
259 ptr = g_stpcpy (ptr, string1);
260 va_start (args, string1);
261 s = va_arg (args, gchar*);
262 while (s)
263 {
264 ptr = g_stpcpy (ptr, s);
265 s = va_arg (args, gchar*);
266 }
267 va_end (args);
268
269 return concat;
270 }
271
272 #if 0
273
274 /**
275 * g_strtod:
276 * @nptr: the string to convert to a numeric value.
277 * @endptr: if non-%NULL, it returns the character after
278 * the last character used in the conversion.
279 *
280 * Converts a string to a #gdouble value.
281 * It calls the standard strtod() function to handle the conversion, but
282 * if the string is not completely converted it attempts the conversion
283 * again with g_ascii_strtod(), and returns the best match.
284 *
285 * This function should seldomly be used. The normal situation when reading
286 * numbers not for human consumption is to use g_ascii_strtod(). Only when
287 * you know that you must expect both locale formatted and C formatted numbers
288 * should you use this. Make sure that you don't pass strings such as comma
289 * separated lists of values, since the commas may be interpreted as a decimal
290 * point in some locales, causing unexpected results.
291 *
292 * Return value: the #gdouble value.
293 **/
294 gdouble
295 g_strtod (const gchar *nptr,
296 gchar **endptr)
297 {
298 gchar *fail_pos_1;
299 gchar *fail_pos_2;
300 gdouble val_1;
301 gdouble val_2 = 0;
302
303 g_return_val_if_fail (nptr != NULL, 0);
304
305 fail_pos_1 = NULL;
306 fail_pos_2 = NULL;
307
308 val_1 = strtod (nptr, &fail_pos_1);
309
310 if (fail_pos_1 && fail_pos_1[0] != 0)
311 val_2 = g_ascii_strtod (nptr, &fail_pos_2);
312
313 if (!fail_pos_1 || fail_pos_1[0] == 0 || fail_pos_1 >= fail_pos_2)
314 {
315 if (endptr)
316 *endptr = fail_pos_1;
317 return val_1;
318 }
319 else
320 {
321 if (endptr)
322 *endptr = fail_pos_2;
323 return val_2;
324 }
325 }
326
327 /**
328 * g_ascii_strtod:
329 * @nptr: the string to convert to a numeric value.
330 * @endptr: if non-%NULL, it returns the character after
331 * the last character used in the conversion.
332 *
333 * Converts a string to a #gdouble value.
334 * This function behaves like the standard strtod() function
335 * does in the C locale. It does this without actually
336 * changing the current locale, since that would not be
337 * thread-safe.
338 *
339 * This function is typically used when reading configuration
340 * files or other non-user input that should be locale independent.
341 * To handle input from the user you should normally use the
342 * locale-sensitive system strtod() function.
343 *
344 * To convert from a #gdouble to a string in a locale-insensitive
345 * way, use g_ascii_dtostr().
346 *
347 * If the correct value would cause overflow, plus or minus %HUGE_VAL
348 * is returned (according to the sign of the value), and %ERANGE is
349 * stored in %errno. If the correct value would cause underflow,
350 * zero is returned and %ERANGE is stored in %errno.
351 *
352 * This function resets %errno before calling strtod() so that
353 * you can reliably detect overflow and underflow.
354 *
355 * Return value: the #gdouble value.
356 **/
357 gdouble
358 g_ascii_strtod (const gchar *nptr,
359 gchar **endptr)
360 {
361 gchar *fail_pos;
362 gdouble val;
363 struct lconv *locale_data;
364 const char *decimal_point;
365 int decimal_point_len;
366 const char *p, *decimal_point_pos;
367 const char *end = NULL; /* Silence gcc */
368 int strtod_errno;
369
370 g_return_val_if_fail (nptr != NULL, 0);
371
372 fail_pos = NULL;
373
374 locale_data = localeconv ();
375 decimal_point = locale_data->decimal_point;
376 decimal_point_len = strlen (decimal_point);
377
378 g_assert (decimal_point_len != 0);
379
380 decimal_point_pos = NULL;
381 end = NULL;
382
383 if (decimal_point[0] != '.' ||
384 decimal_point[1] != 0)
385 {
386 p = nptr;
387 /* Skip leading space */
388 while (g_ascii_isspace (*p))
389 p++;
390
391 /* Skip leading optional sign */
392 if (*p == '+' || *p == '-')
393 p++;
394
395 if (p[0] == '0' &&
396 (p[1] == 'x' || p[1] == 'X'))
397 {
398 p += 2;
399 /* HEX - find the (optional) decimal point */
400
401 while (g_ascii_isxdigit (*p))
402 p++;
403
404 if (*p == '.')
405 decimal_point_pos = p++;
406
407 while (g_ascii_isxdigit (*p))
408 p++;
409
410 if (*p == 'p' || *p == 'P')
411 p++;
412 if (*p == '+' || *p == '-')
413 p++;
414 while (g_ascii_isdigit (*p))
415 p++;
416
417 end = p;
418 }
419 else if (g_ascii_isdigit (*p) || *p == '.')
420 {
421 while (g_ascii_isdigit (*p))
422 p++;
423
424 if (*p == '.')
425 decimal_point_pos = p++;
426
427 while (g_ascii_isdigit (*p))
428 p++;
429
430 if (*p == 'e' || *p == 'E')
431 p++;
432 if (*p == '+' || *p == '-')
433 p++;
434 while (g_ascii_isdigit (*p))
435 p++;
436
437 end = p;
438 }
439 /* For the other cases, we need not convert the decimal point */
440 }
441
442 if (decimal_point_pos)
443 {
444 char *copy, *c;
445
446 /* We need to convert the '.' to the locale specific decimal point */
447 copy = g_malloc (end - nptr + 1 + decimal_point_len);
448
449 c = copy;
450 memcpy (c, nptr, decimal_point_pos - nptr);
451 c += decimal_point_pos - nptr;
452 memcpy (c, decimal_point, decimal_point_len);
453 c += decimal_point_len;
454 memcpy (c, decimal_point_pos + 1, end - (decimal_point_pos + 1));
455 c += end - (decimal_point_pos + 1);
456 *c = 0;
457
458 errno = 0;
459 val = strtod (copy, &fail_pos);
460 strtod_errno = errno;
461
462 if (fail_pos)
463 {
464 if (fail_pos - copy > decimal_point_pos - nptr)
465 fail_pos = (char *)nptr + (fail_pos - copy) - (decimal_point_len - 1);
466 else
467 fail_pos = (char *)nptr + (fail_pos - copy);
468 }
469
470 g_free (copy);
471
472 }
473 else if (end)
474 {
475 char *copy;
476
477 copy = g_malloc (end - (char *)nptr + 1);
478 memcpy (copy, nptr, end - nptr);
479 *(copy + (end - (char *)nptr)) = 0;
480
481 errno = 0;
482 val = strtod (copy, &fail_pos);
483 strtod_errno = errno;
484
485 if (fail_pos)
486 {
487 fail_pos = (char *)nptr + (fail_pos - copy);
488 }
489
490 g_free (copy);
491 }
492 else
493 {
494 errno = 0;
495 val = strtod (nptr, &fail_pos);
496 strtod_errno = errno;
497 }
498
499 if (endptr)
500 *endptr = fail_pos;
501
502 errno = strtod_errno;
503
504 return val;
505 }
506
507 #endif
508
509 /**
510 * g_ascii_dtostr:
511 * @buffer: A buffer to place the resulting string in
512 * @buf_len: The length of the buffer.
513 * @d: The #gdouble to convert
514 *
515 * Converts a #gdouble to a string, using the '.' as
516 * decimal point.
517 *
518 * This functions generates enough precision that converting
519 * the string back using g_ascii_strtod() gives the same machine-number
520 * (on machines with IEEE compatible 64bit doubles). It is
521 * guaranteed that the size of the resulting string will never
522 * be larger than @G_ASCII_DTOSTR_BUF_SIZE bytes.
523 *
524 * Return value: The pointer to the buffer with the converted string.
525 **/
526 gchar *
g_ascii_dtostr(gchar * buffer,gint buf_len,gdouble d)527 g_ascii_dtostr (gchar *buffer,
528 gint buf_len,
529 gdouble d)
530 {
531 return g_ascii_formatd (buffer, buf_len, "%.17g", d);
532 }
533
534 /**
535 * g_ascii_formatd:
536 * @buffer: A buffer to place the resulting string in
537 * @buf_len: The length of the buffer.
538 * @format: The printf()-style format to use for the
539 * code to use for converting.
540 * @d: The #gdouble to convert
541 *
542 * Converts a #gdouble to a string, using the '.' as
543 * decimal point. To format the number you pass in
544 * a printf()-style format string. Allowed conversion
545 * specifiers are 'e', 'E', 'f', 'F', 'g' and 'G'.
546 *
547 * If you just want to want to serialize the value into a
548 * string, use g_ascii_dtostr().
549 *
550 * Return value: The pointer to the buffer with the converted string.
551 **/
552 gchar *
g_ascii_formatd(gchar * buffer,gint buf_len,const gchar * format,gdouble d)553 g_ascii_formatd (gchar *buffer,
554 gint buf_len,
555 const gchar *format,
556 gdouble d)
557 {
558 struct lconv *locale_data;
559 const char *decimal_point;
560 int decimal_point_len;
561 gchar *p;
562 int rest_len;
563 gchar format_char;
564
565 g_return_val_if_fail (buffer != NULL, NULL);
566 g_return_val_if_fail (format[0] == '%', NULL);
567 g_return_val_if_fail (strpbrk (format + 1, "'l%") == NULL, NULL);
568
569 format_char = format[strlen (format) - 1];
570
571 g_return_val_if_fail (format_char == 'e' || format_char == 'E' ||
572 format_char == 'f' || format_char == 'F' ||
573 format_char == 'g' || format_char == 'G',
574 NULL);
575
576 if (format[0] != '%')
577 return NULL;
578
579 if (strpbrk (format + 1, "'l%"))
580 return NULL;
581
582 if (!(format_char == 'e' || format_char == 'E' ||
583 format_char == 'f' || format_char == 'F' ||
584 format_char == 'g' || format_char == 'G'))
585 return NULL;
586
587
588 _g_snprintf (buffer, buf_len, format, d);
589
590 locale_data = localeconv ();
591 decimal_point = locale_data->decimal_point;
592 decimal_point_len = strlen (decimal_point);
593
594 g_assert (decimal_point_len != 0);
595
596 if (decimal_point[0] != '.' ||
597 decimal_point[1] != 0)
598 {
599 p = buffer;
600
601 while (g_ascii_isspace (*p))
602 p++;
603
604 if (*p == '+' || *p == '-')
605 p++;
606
607 while (isdigit ((guchar)*p))
608 p++;
609
610 if (strncmp (p, decimal_point, decimal_point_len) == 0)
611 {
612 *p = '.';
613 p++;
614 if (decimal_point_len > 1) {
615 rest_len = strlen (p + (decimal_point_len-1));
616 memmove (p, p + (decimal_point_len-1),
617 rest_len);
618 p[rest_len] = 0;
619
620 }
621 }
622 }
623
624 return buffer;
625 }
626
627 #define ISSPACE(c) ((c) == ' ' || (c) == '\f' || (c) == '\n' || \
628 (c) == '\r' || (c) == '\t' || (c) == '\v')
629 #define ISUPPER(c) ((c) >= 'A' && (c) <= 'Z')
630 #define ISLOWER(c) ((c) >= 'a' && (c) <= 'z')
631 #define ISALPHA(c) (ISUPPER (c) || ISLOWER (c))
632 #define TOUPPER(c) (ISLOWER (c) ? (c) - 'a' + 'A' : (c))
633 #define TOLOWER(c) (ISUPPER (c) ? (c) - 'A' + 'a' : (c))
634
635 #if 0
636
637 static guint64
638 g_parse_long_long (const gchar *nptr,
639 gchar **endptr,
640 guint base,
641 gboolean *negative)
642 {
643 /* this code is based on on the strtol(3) code from GNU libc released under
644 * the GNU Lesser General Public License.
645 *
646 * Copyright (C) 1991-1992, 1994-2002 Free Software Foundation, Inc.
647 */
648 gboolean overflow;
649 guint64 cutoff;
650 guint64 cutlim;
651 guint64 ui64;
652 const gchar *s, *save;
653 guchar c;
654
655 g_return_val_if_fail (nptr != NULL, 0);
656
657 if (base == 1 || base > 36)
658 {
659 errno = EINVAL;
660 return 0;
661 }
662
663 save = s = nptr;
664
665 /* Skip white space. */
666 while (ISSPACE (*s))
667 ++s;
668
669 if (G_UNLIKELY (!*s))
670 goto noconv;
671
672 /* Check for a sign. */
673 *negative = FALSE;
674 if (*s == '-')
675 {
676 *negative = TRUE;
677 ++s;
678 }
679 else if (*s == '+')
680 ++s;
681
682 /* Recognize number prefix and if BASE is zero, figure it out ourselves. */
683 if (*s == '0')
684 {
685 if ((base == 0 || base == 16) && TOUPPER (s[1]) == 'X')
686 {
687 s += 2;
688 base = 16;
689 }
690 else if (base == 0)
691 base = 8;
692 }
693 else if (base == 0)
694 base = 10;
695
696 /* Save the pointer so we can check later if anything happened. */
697 save = s;
698 cutoff = G_MAXUINT64 / base;
699 cutlim = G_MAXUINT64 % base;
700
701 overflow = FALSE;
702 ui64 = 0;
703 c = *s;
704 for (; c; c = *++s)
705 {
706 if (c >= '0' && c <= '9')
707 c -= '0';
708 else if (ISALPHA (c))
709 c = TOUPPER (c) - 'A' + 10;
710 else
711 break;
712 if (c >= base)
713 break;
714 /* Check for overflow. */
715 if (ui64 > cutoff || (ui64 == cutoff && c > cutlim))
716 overflow = TRUE;
717 else
718 {
719 ui64 *= base;
720 ui64 += c;
721 }
722 }
723
724 /* Check if anything actually happened. */
725 if (s == save)
726 goto noconv;
727
728 /* Store in ENDPTR the address of one character
729 past the last character we converted. */
730 if (endptr)
731 *endptr = (gchar*) s;
732
733 if (G_UNLIKELY (overflow))
734 {
735 errno = ERANGE;
736 return G_MAXUINT64;
737 }
738
739 return ui64;
740
741 noconv:
742 /* We must handle a special case here: the base is 0 or 16 and the
743 first two characters are '0' and 'x', but the rest are no
744 hexadecimal digits. This is no error case. We return 0 and
745 ENDPTR points to the `x`. */
746 if (endptr)
747 {
748 if (save - nptr >= 2 && TOUPPER (save[-1]) == 'X'
749 && save[-2] == '0')
750 *endptr = (gchar*) &save[-1];
751 else
752 /* There was no number to convert. */
753 *endptr = (gchar*) nptr;
754 }
755 return 0;
756 }
757
758 /**
759 * g_ascii_strtoull:
760 * @nptr: the string to convert to a numeric value.
761 * @endptr: if non-%NULL, it returns the character after
762 * the last character used in the conversion.
763 * @base: to be used for the conversion, 2..36 or 0
764 *
765 * Converts a string to a #guint64 value.
766 * This function behaves like the standard strtoull() function
767 * does in the C locale. It does this without actually
768 * changing the current locale, since that would not be
769 * thread-safe.
770 *
771 * This function is typically used when reading configuration
772 * files or other non-user input that should be locale independent.
773 * To handle input from the user you should normally use the
774 * locale-sensitive system strtoull() function.
775 *
776 * If the correct value would cause overflow, %G_MAXUINT64
777 * is returned, and %ERANGE is stored in %errno. If the base is
778 * outside the valid range, zero is returned, and %EINVAL is stored
779 * in %errno. If the string conversion fails, zero is returned, and
780 * @endptr returns @nptr (if @endptr is non-%NULL).
781 *
782 * Return value: the #guint64 value or zero on error.
783 *
784 * Since: 2.2
785 **/
786 guint64
787 g_ascii_strtoull (const gchar *nptr,
788 gchar **endptr,
789 guint base)
790 {
791 gboolean negative;
792 guint64 result;
793
794 result = g_parse_long_long (nptr, endptr, base, &negative);
795
796 /* Return the result of the appropriate sign. */
797 return negative ? -result : result;
798 }
799
800 /**
801 * g_ascii_strtoll:
802 * @nptr: the string to convert to a numeric value.
803 * @endptr: if non-%NULL, it returns the character after
804 * the last character used in the conversion.
805 * @base: to be used for the conversion, 2..36 or 0
806 *
807 * Converts a string to a #gint64 value.
808 * This function behaves like the standard strtoll() function
809 * does in the C locale. It does this without actually
810 * changing the current locale, since that would not be
811 * thread-safe.
812 *
813 * This function is typically used when reading configuration
814 * files or other non-user input that should be locale independent.
815 * To handle input from the user you should normally use the
816 * locale-sensitive system strtoll() function.
817 *
818 * If the correct value would cause overflow, %G_MAXINT64 or %G_MININT64
819 * is returned, and %ERANGE is stored in %errno. If the base is
820 * outside the valid range, zero is returned, and %EINVAL is stored
821 * in %errno. If the string conversion fails, zero is returned, and
822 * @endptr returns @nptr (if @endptr is non-%NULL).
823 *
824 * Return value: the #gint64 value or zero on error.
825 *
826 * Since: 2.12
827 **/
828 gint64
829 g_ascii_strtoll (const gchar *nptr,
830 gchar **endptr,
831 guint base)
832 {
833 gboolean negative;
834 guint64 result;
835
836 result = g_parse_long_long (nptr, endptr, base, &negative);
837
838 if (negative && result > (guint64) G_MININT64)
839 {
840 errno = ERANGE;
841 return G_MININT64;
842 }
843 else if (!negative && result > (guint64) G_MAXINT64)
844 {
845 errno = ERANGE;
846 return G_MAXINT64;
847 }
848 else
849 return (gint64) result;
850 }
851
852 G_CONST_RETURN gchar*
853 g_strerror (gint errnum)
854 {
855 static GStaticPrivate msg_private = G_STATIC_PRIVATE_INIT;
856 char *msg;
857 int saved_errno = errno;
858
859 #ifdef HAVE_STRERROR
860 const char *msg_locale;
861
862 msg_locale = strerror (errnum);
863 if (g_get_charset (NULL))
864 {
865 errno = saved_errno;
866 return msg_locale;
867 }
868 else
869 {
870 gchar *msg_utf8 = g_locale_to_utf8 (msg_locale, -1, NULL, NULL, NULL);
871 if (msg_utf8)
872 {
873 /* Stick in the quark table so that we can return a static result
874 */
875 GQuark msg_quark = g_quark_from_string (msg_utf8);
876 g_free (msg_utf8);
877
878 msg_utf8 = (gchar *) g_quark_to_string (msg_quark);
879 errno = saved_errno;
880 return msg_utf8;
881 }
882 }
883 #elif NO_SYS_ERRLIST
884 switch (errnum)
885 {
886 #ifdef E2BIG
887 case E2BIG: return "argument list too long";
888 #endif
889 #ifdef EACCES
890 case EACCES: return "permission denied";
891 #endif
892 #ifdef EADDRINUSE
893 case EADDRINUSE: return "address already in use";
894 #endif
895 #ifdef EADDRNOTAVAIL
896 case EADDRNOTAVAIL: return "can't assign requested address";
897 #endif
898 #ifdef EADV
899 case EADV: return "advertise error";
900 #endif
901 #ifdef EAFNOSUPPORT
902 case EAFNOSUPPORT: return "address family not supported by protocol family";
903 #endif
904 #ifdef EAGAIN
905 case EAGAIN: return "try again";
906 #endif
907 #ifdef EALIGN
908 case EALIGN: return "EALIGN";
909 #endif
910 #ifdef EALREADY
911 case EALREADY: return "operation already in progress";
912 #endif
913 #ifdef EBADE
914 case EBADE: return "bad exchange descriptor";
915 #endif
916 #ifdef EBADF
917 case EBADF: return "bad file number";
918 #endif
919 #ifdef EBADFD
920 case EBADFD: return "file descriptor in bad state";
921 #endif
922 #ifdef EBADMSG
923 case EBADMSG: return "not a data message";
924 #endif
925 #ifdef EBADR
926 case EBADR: return "bad request descriptor";
927 #endif
928 #ifdef EBADRPC
929 case EBADRPC: return "RPC structure is bad";
930 #endif
931 #ifdef EBADRQC
932 case EBADRQC: return "bad request code";
933 #endif
934 #ifdef EBADSLT
935 case EBADSLT: return "invalid slot";
936 #endif
937 #ifdef EBFONT
938 case EBFONT: return "bad font file format";
939 #endif
940 #ifdef EBUSY
941 case EBUSY: return "mount device busy";
942 #endif
943 #ifdef ECHILD
944 case ECHILD: return "no children";
945 #endif
946 #ifdef ECHRNG
947 case ECHRNG: return "channel number out of range";
948 #endif
949 #ifdef ECOMM
950 case ECOMM: return "communication error on send";
951 #endif
952 #ifdef ECONNABORTED
953 case ECONNABORTED: return "software caused connection abort";
954 #endif
955 #ifdef ECONNREFUSED
956 case ECONNREFUSED: return "connection refused";
957 #endif
958 #ifdef ECONNRESET
959 case ECONNRESET: return "connection reset by peer";
960 #endif
961 #if defined(EDEADLK) && (!defined(EWOULDBLOCK) || (EDEADLK != EWOULDBLOCK))
962 case EDEADLK: return "resource deadlock avoided";
963 #endif
964 #ifdef EDEADLOCK
965 case EDEADLOCK: return "resource deadlock avoided";
966 #endif
967 #ifdef EDESTADDRREQ
968 case EDESTADDRREQ: return "destination address required";
969 #endif
970 #ifdef EDIRTY
971 case EDIRTY: return "mounting a dirty fs w/o force";
972 #endif
973 #ifdef EDOM
974 case EDOM: return "math argument out of range";
975 #endif
976 #ifdef EDOTDOT
977 case EDOTDOT: return "cross mount point";
978 #endif
979 #ifdef EDQUOT
980 case EDQUOT: return "disk quota exceeded";
981 #endif
982 #ifdef EDUPPKG
983 case EDUPPKG: return "duplicate package name";
984 #endif
985 #ifdef EEXIST
986 case EEXIST: return "file already exists";
987 #endif
988 #ifdef EFAULT
989 case EFAULT: return "bad address in system call argument";
990 #endif
991 #ifdef EFBIG
992 case EFBIG: return "file too large";
993 #endif
994 #ifdef EHOSTDOWN
995 case EHOSTDOWN: return "host is down";
996 #endif
997 #ifdef EHOSTUNREACH
998 case EHOSTUNREACH: return "host is unreachable";
999 #endif
1000 #ifdef EIDRM
1001 case EIDRM: return "identifier removed";
1002 #endif
1003 #ifdef EINIT
1004 case EINIT: return "initialization error";
1005 #endif
1006 #ifdef EINPROGRESS
1007 case EINPROGRESS: return "operation now in progress";
1008 #endif
1009 #ifdef EINTR
1010 case EINTR: return "interrupted system call";
1011 #endif
1012 #ifdef EINVAL
1013 case EINVAL: return "invalid argument";
1014 #endif
1015 #ifdef EIO
1016 case EIO: return "I/O error";
1017 #endif
1018 #ifdef EISCONN
1019 case EISCONN: return "socket is already connected";
1020 #endif
1021 #ifdef EISDIR
1022 case EISDIR: return "is a directory";
1023 #endif
1024 #ifdef EISNAME
1025 case EISNAM: return "is a name file";
1026 #endif
1027 #ifdef ELBIN
1028 case ELBIN: return "ELBIN";
1029 #endif
1030 #ifdef EL2HLT
1031 case EL2HLT: return "level 2 halted";
1032 #endif
1033 #ifdef EL2NSYNC
1034 case EL2NSYNC: return "level 2 not synchronized";
1035 #endif
1036 #ifdef EL3HLT
1037 case EL3HLT: return "level 3 halted";
1038 #endif
1039 #ifdef EL3RST
1040 case EL3RST: return "level 3 reset";
1041 #endif
1042 #ifdef ELIBACC
1043 case ELIBACC: return "can not access a needed shared library";
1044 #endif
1045 #ifdef ELIBBAD
1046 case ELIBBAD: return "accessing a corrupted shared library";
1047 #endif
1048 #ifdef ELIBEXEC
1049 case ELIBEXEC: return "can not exec a shared library directly";
1050 #endif
1051 #ifdef ELIBMAX
1052 case ELIBMAX: return "attempting to link in more shared libraries than system limit";
1053 #endif
1054 #ifdef ELIBSCN
1055 case ELIBSCN: return ".lib section in a.out corrupted";
1056 #endif
1057 #ifdef ELNRNG
1058 case ELNRNG: return "link number out of range";
1059 #endif
1060 #ifdef ELOOP
1061 case ELOOP: return "too many levels of symbolic links";
1062 #endif
1063 #ifdef EMFILE
1064 case EMFILE: return "too many open files";
1065 #endif
1066 #ifdef EMLINK
1067 case EMLINK: return "too many links";
1068 #endif
1069 #ifdef EMSGSIZE
1070 case EMSGSIZE: return "message too long";
1071 #endif
1072 #ifdef EMULTIHOP
1073 case EMULTIHOP: return "multihop attempted";
1074 #endif
1075 #ifdef ENAMETOOLONG
1076 case ENAMETOOLONG: return "file name too long";
1077 #endif
1078 #ifdef ENAVAIL
1079 case ENAVAIL: return "not available";
1080 #endif
1081 #ifdef ENET
1082 case ENET: return "ENET";
1083 #endif
1084 #ifdef ENETDOWN
1085 case ENETDOWN: return "network is down";
1086 #endif
1087 #ifdef ENETRESET
1088 case ENETRESET: return "network dropped connection on reset";
1089 #endif
1090 #ifdef ENETUNREACH
1091 case ENETUNREACH: return "network is unreachable";
1092 #endif
1093 #ifdef ENFILE
1094 case ENFILE: return "file table overflow";
1095 #endif
1096 #ifdef ENOANO
1097 case ENOANO: return "anode table overflow";
1098 #endif
1099 #if defined(ENOBUFS) && (!defined(ENOSR) || (ENOBUFS != ENOSR))
1100 case ENOBUFS: return "no buffer space available";
1101 #endif
1102 #ifdef ENOCSI
1103 case ENOCSI: return "no CSI structure available";
1104 #endif
1105 #ifdef ENODATA
1106 case ENODATA: return "no data available";
1107 #endif
1108 #ifdef ENODEV
1109 case ENODEV: return "no such device";
1110 #endif
1111 #ifdef ENOENT
1112 case ENOENT: return "no such file or directory";
1113 #endif
1114 #ifdef ENOEXEC
1115 case ENOEXEC: return "exec format error";
1116 #endif
1117 #ifdef ENOLCK
1118 case ENOLCK: return "no locks available";
1119 #endif
1120 #ifdef ENOLINK
1121 case ENOLINK: return "link has be severed";
1122 #endif
1123 #ifdef ENOMEM
1124 case ENOMEM: return "not enough memory";
1125 #endif
1126 #ifdef ENOMSG
1127 case ENOMSG: return "no message of desired type";
1128 #endif
1129 #ifdef ENONET
1130 case ENONET: return "machine is not on the network";
1131 #endif
1132 #ifdef ENOPKG
1133 case ENOPKG: return "package not installed";
1134 #endif
1135 #ifdef ENOPROTOOPT
1136 case ENOPROTOOPT: return "bad proocol option";
1137 #endif
1138 #ifdef ENOSPC
1139 case ENOSPC: return "no space left on device";
1140 #endif
1141 #ifdef ENOSR
1142 case ENOSR: return "out of stream resources";
1143 #endif
1144 #ifdef ENOSTR
1145 case ENOSTR: return "not a stream device";
1146 #endif
1147 #ifdef ENOSYM
1148 case ENOSYM: return "unresolved symbol name";
1149 #endif
1150 #ifdef ENOSYS
1151 case ENOSYS: return "function not implemented";
1152 #endif
1153 #ifdef ENOTBLK
1154 case ENOTBLK: return "block device required";
1155 #endif
1156 #ifdef ENOTCONN
1157 case ENOTCONN: return "socket is not connected";
1158 #endif
1159 #ifdef ENOTDIR
1160 case ENOTDIR: return "not a directory";
1161 #endif
1162 #ifdef ENOTEMPTY
1163 case ENOTEMPTY: return "directory not empty";
1164 #endif
1165 #ifdef ENOTNAM
1166 case ENOTNAM: return "not a name file";
1167 #endif
1168 #ifdef ENOTSOCK
1169 case ENOTSOCK: return "socket operation on non-socket";
1170 #endif
1171 #ifdef ENOTTY
1172 case ENOTTY: return "inappropriate device for ioctl";
1173 #endif
1174 #ifdef ENOTUNIQ
1175 case ENOTUNIQ: return "name not unique on network";
1176 #endif
1177 #ifdef ENXIO
1178 case ENXIO: return "no such device or address";
1179 #endif
1180 #ifdef EOPNOTSUPP
1181 case EOPNOTSUPP: return "operation not supported on socket";
1182 #endif
1183 #ifdef EPERM
1184 case EPERM: return "not owner";
1185 #endif
1186 #ifdef EPFNOSUPPORT
1187 case EPFNOSUPPORT: return "protocol family not supported";
1188 #endif
1189 #ifdef EPIPE
1190 case EPIPE: return "broken pipe";
1191 #endif
1192 #ifdef EPROCLIM
1193 case EPROCLIM: return "too many processes";
1194 #endif
1195 #ifdef EPROCUNAVAIL
1196 case EPROCUNAVAIL: return "bad procedure for program";
1197 #endif
1198 #ifdef EPROGMISMATCH
1199 case EPROGMISMATCH: return "program version wrong";
1200 #endif
1201 #ifdef EPROGUNAVAIL
1202 case EPROGUNAVAIL: return "RPC program not available";
1203 #endif
1204 #ifdef EPROTO
1205 case EPROTO: return "protocol error";
1206 #endif
1207 #ifdef EPROTONOSUPPORT
1208 case EPROTONOSUPPORT: return "protocol not suppored";
1209 #endif
1210 #ifdef EPROTOTYPE
1211 case EPROTOTYPE: return "protocol wrong type for socket";
1212 #endif
1213 #ifdef ERANGE
1214 case ERANGE: return "math result unrepresentable";
1215 #endif
1216 #if defined(EREFUSED) && (!defined(ECONNREFUSED) || (EREFUSED != ECONNREFUSED))
1217 case EREFUSED: return "EREFUSED";
1218 #endif
1219 #ifdef EREMCHG
1220 case EREMCHG: return "remote address changed";
1221 #endif
1222 #ifdef EREMDEV
1223 case EREMDEV: return "remote device";
1224 #endif
1225 #ifdef EREMOTE
1226 case EREMOTE: return "pathname hit remote file system";
1227 #endif
1228 #ifdef EREMOTEIO
1229 case EREMOTEIO: return "remote i/o error";
1230 #endif
1231 #ifdef EREMOTERELEASE
1232 case EREMOTERELEASE: return "EREMOTERELEASE";
1233 #endif
1234 #ifdef EROFS
1235 case EROFS: return "read-only file system";
1236 #endif
1237 #ifdef ERPCMISMATCH
1238 case ERPCMISMATCH: return "RPC version is wrong";
1239 #endif
1240 #ifdef ERREMOTE
1241 case ERREMOTE: return "object is remote";
1242 #endif
1243 #ifdef ESHUTDOWN
1244 case ESHUTDOWN: return "can't send afer socket shutdown";
1245 #endif
1246 #ifdef ESOCKTNOSUPPORT
1247 case ESOCKTNOSUPPORT: return "socket type not supported";
1248 #endif
1249 #ifdef ESPIPE
1250 case ESPIPE: return "invalid seek";
1251 #endif
1252 #ifdef ESRCH
1253 case ESRCH: return "no such process";
1254 #endif
1255 #ifdef ESRMNT
1256 case ESRMNT: return "srmount error";
1257 #endif
1258 #ifdef ESTALE
1259 case ESTALE: return "stale remote file handle";
1260 #endif
1261 #ifdef ESUCCESS
1262 case ESUCCESS: return "Error 0";
1263 #endif
1264 #ifdef ETIME
1265 case ETIME: return "timer expired";
1266 #endif
1267 #ifdef ETIMEDOUT
1268 case ETIMEDOUT: return "connection timed out";
1269 #endif
1270 #ifdef ETOOMANYREFS
1271 case ETOOMANYREFS: return "too many references: can't splice";
1272 #endif
1273 #ifdef ETXTBSY
1274 case ETXTBSY: return "text file or pseudo-device busy";
1275 #endif
1276 #ifdef EUCLEAN
1277 case EUCLEAN: return "structure needs cleaning";
1278 #endif
1279 #ifdef EUNATCH
1280 case EUNATCH: return "protocol driver not attached";
1281 #endif
1282 #ifdef EUSERS
1283 case EUSERS: return "too many users";
1284 #endif
1285 #ifdef EVERSION
1286 case EVERSION: return "version mismatch";
1287 #endif
1288 #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
1289 case EWOULDBLOCK: return "operation would block";
1290 #endif
1291 #ifdef EXDEV
1292 case EXDEV: return "cross-domain link";
1293 #endif
1294 #ifdef EXFULL
1295 case EXFULL: return "message tables full";
1296 #endif
1297 }
1298 #else /* NO_SYS_ERRLIST */
1299 extern int sys_nerr;
1300 extern char *sys_errlist[];
1301
1302 if ((errnum > 0) && (errnum <= sys_nerr))
1303 return sys_errlist [errnum];
1304 #endif /* NO_SYS_ERRLIST */
1305
1306 msg = g_static_private_get (&msg_private);
1307 if (!msg)
1308 {
1309 msg = g_new (gchar, 64);
1310 g_static_private_set (&msg_private, msg, g_free);
1311 }
1312
1313 _g_sprintf (msg, "unknown error (%d)", errnum);
1314
1315 errno = saved_errno;
1316 return msg;
1317 }
1318
1319 G_CONST_RETURN gchar*
1320 g_strsignal (gint signum)
1321 {
1322 static GStaticPrivate msg_private = G_STATIC_PRIVATE_INIT;
1323 char *msg;
1324
1325 #ifdef HAVE_STRSIGNAL
1326 const char *msg_locale;
1327
1328 #if defined(G_OS_BEOS) || defined(G_WITH_CYGWIN)
1329 extern const char *strsignal(int);
1330 #else
1331 /* this is declared differently (const) in string.h on BeOS */
1332 extern char *strsignal (int sig);
1333 #endif /* !G_OS_BEOS && !G_WITH_CYGWIN */
1334 msg_locale = strsignal (signum);
1335 if (g_get_charset (NULL))
1336 return msg_locale;
1337 else
1338 {
1339 gchar *msg_utf8 = g_locale_to_utf8 (msg_locale, -1, NULL, NULL, NULL);
1340 if (msg_utf8)
1341 {
1342 /* Stick in the quark table so that we can return a static result
1343 */
1344 GQuark msg_quark = g_quark_from_string (msg_utf8);
1345 g_free (msg_utf8);
1346
1347 return g_quark_to_string (msg_quark);
1348 }
1349 }
1350 #elif NO_SYS_SIGLIST
1351 switch (signum)
1352 {
1353 #ifdef SIGHUP
1354 case SIGHUP: return "Hangup";
1355 #endif
1356 #ifdef SIGINT
1357 case SIGINT: return "Interrupt";
1358 #endif
1359 #ifdef SIGQUIT
1360 case SIGQUIT: return "Quit";
1361 #endif
1362 #ifdef SIGILL
1363 case SIGILL: return "Illegal instruction";
1364 #endif
1365 #ifdef SIGTRAP
1366 case SIGTRAP: return "Trace/breakpoint trap";
1367 #endif
1368 #ifdef SIGABRT
1369 case SIGABRT: return "IOT trap/Abort";
1370 #endif
1371 #ifdef SIGBUS
1372 case SIGBUS: return "Bus error";
1373 #endif
1374 #ifdef SIGFPE
1375 case SIGFPE: return "Floating point exception";
1376 #endif
1377 #ifdef SIGKILL
1378 case SIGKILL: return "Killed";
1379 #endif
1380 #ifdef SIGUSR1
1381 case SIGUSR1: return "User defined signal 1";
1382 #endif
1383 #ifdef SIGSEGV
1384 case SIGSEGV: return "Segmentation fault";
1385 #endif
1386 #ifdef SIGUSR2
1387 case SIGUSR2: return "User defined signal 2";
1388 #endif
1389 #ifdef SIGPIPE
1390 case SIGPIPE: return "Broken pipe";
1391 #endif
1392 #ifdef SIGALRM
1393 case SIGALRM: return "Alarm clock";
1394 #endif
1395 #ifdef SIGTERM
1396 case SIGTERM: return "Terminated";
1397 #endif
1398 #ifdef SIGSTKFLT
1399 case SIGSTKFLT: return "Stack fault";
1400 #endif
1401 #ifdef SIGCHLD
1402 case SIGCHLD: return "Child exited";
1403 #endif
1404 #ifdef SIGCONT
1405 case SIGCONT: return "Continued";
1406 #endif
1407 #ifdef SIGSTOP
1408 case SIGSTOP: return "Stopped (signal)";
1409 #endif
1410 #ifdef SIGTSTP
1411 case SIGTSTP: return "Stopped";
1412 #endif
1413 #ifdef SIGTTIN
1414 case SIGTTIN: return "Stopped (tty input)";
1415 #endif
1416 #ifdef SIGTTOU
1417 case SIGTTOU: return "Stopped (tty output)";
1418 #endif
1419 #ifdef SIGURG
1420 case SIGURG: return "Urgent condition";
1421 #endif
1422 #ifdef SIGXCPU
1423 case SIGXCPU: return "CPU time limit exceeded";
1424 #endif
1425 #ifdef SIGXFSZ
1426 case SIGXFSZ: return "File size limit exceeded";
1427 #endif
1428 #ifdef SIGVTALRM
1429 case SIGVTALRM: return "Virtual time alarm";
1430 #endif
1431 #ifdef SIGPROF
1432 case SIGPROF: return "Profile signal";
1433 #endif
1434 #ifdef SIGWINCH
1435 case SIGWINCH: return "Window size changed";
1436 #endif
1437 #ifdef SIGIO
1438 case SIGIO: return "Possible I/O";
1439 #endif
1440 #ifdef SIGPWR
1441 case SIGPWR: return "Power failure";
1442 #endif
1443 #ifdef SIGUNUSED
1444 case SIGUNUSED: return "Unused signal";
1445 #endif
1446 }
1447 #else /* NO_SYS_SIGLIST */
1448
1449 #ifdef NO_SYS_SIGLIST_DECL
1450 extern char *sys_siglist[]; /*(see Tue Jan 19 00:44:24 1999 in changelog)*/
1451 #endif
1452
1453 return (char*) /* this function should return const --josh */ sys_siglist [signum];
1454 #endif /* NO_SYS_SIGLIST */
1455
1456 msg = g_static_private_get (&msg_private);
1457 if (!msg)
1458 {
1459 msg = g_new (gchar, 64);
1460 g_static_private_set (&msg_private, msg, g_free);
1461 }
1462
1463 _g_sprintf (msg, "unknown signal (%d)", signum);
1464
1465 return msg;
1466 }
1467
1468 /* Functions g_strlcpy and g_strlcat were originally developed by
1469 * Todd C. Miller <Todd.Miller@courtesan.com> to simplify writing secure code.
1470 * See ftp://ftp.openbsd.org/pub/OpenBSD/src/lib/libc/string/strlcpy.3
1471 * for more information.
1472 */
1473
1474 #ifdef HAVE_STRLCPY
1475 /* Use the native ones, if available; they might be implemented in assembly */
1476 gsize
1477 g_strlcpy (gchar *dest,
1478 const gchar *src,
1479 gsize dest_size)
1480 {
1481 g_return_val_if_fail (dest != NULL, 0);
1482 g_return_val_if_fail (src != NULL, 0);
1483
1484 return strlcpy (dest, src, dest_size);
1485 }
1486
1487 gsize
1488 g_strlcat (gchar *dest,
1489 const gchar *src,
1490 gsize dest_size)
1491 {
1492 g_return_val_if_fail (dest != NULL, 0);
1493 g_return_val_if_fail (src != NULL, 0);
1494
1495 return strlcat (dest, src, dest_size);
1496 }
1497
1498 #else /* ! HAVE_STRLCPY */
1499 /* g_strlcpy
1500 *
1501 * Copy string src to buffer dest (of buffer size dest_size). At most
1502 * dest_size-1 characters will be copied. Always NUL terminates
1503 * (unless dest_size == 0). This function does NOT allocate memory.
1504 * Unlike strncpy, this function doesn't pad dest (so it's often faster).
1505 * Returns size of attempted result, strlen(src),
1506 * so if retval >= dest_size, truncation occurred.
1507 */
1508 gsize
1509 g_strlcpy (gchar *dest,
1510 const gchar *src,
1511 gsize dest_size)
1512 {
1513 register gchar *d = dest;
1514 register const gchar *s = src;
1515 register gsize n = dest_size;
1516
1517 g_return_val_if_fail (dest != NULL, 0);
1518 g_return_val_if_fail (src != NULL, 0);
1519
1520 /* Copy as many bytes as will fit */
1521 if (n != 0 && --n != 0)
1522 do
1523 {
1524 register gchar c = *s++;
1525
1526 *d++ = c;
1527 if (c == 0)
1528 break;
1529 }
1530 while (--n != 0);
1531
1532 /* If not enough room in dest, add NUL and traverse rest of src */
1533 if (n == 0)
1534 {
1535 if (dest_size != 0)
1536 *d = 0;
1537 while (*s++)
1538 ;
1539 }
1540
1541 return s - src - 1; /* count does not include NUL */
1542 }
1543
1544 /* g_strlcat
1545 *
1546 * Appends string src to buffer dest (of buffer size dest_size).
1547 * At most dest_size-1 characters will be copied.
1548 * Unlike strncat, dest_size is the full size of dest, not the space left over.
1549 * This function does NOT allocate memory.
1550 * This always NUL terminates (unless siz == 0 or there were no NUL characters
1551 * in the dest_size characters of dest to start with).
1552 * Returns size of attempted result, which is
1553 * MIN (dest_size, strlen (original dest)) + strlen (src),
1554 * so if retval >= dest_size, truncation occurred.
1555 */
1556 gsize
1557 g_strlcat (gchar *dest,
1558 const gchar *src,
1559 gsize dest_size)
1560 {
1561 register gchar *d = dest;
1562 register const gchar *s = src;
1563 register gsize bytes_left = dest_size;
1564 gsize dlength; /* Logically, MIN (strlen (d), dest_size) */
1565
1566 g_return_val_if_fail (dest != NULL, 0);
1567 g_return_val_if_fail (src != NULL, 0);
1568
1569 /* Find the end of dst and adjust bytes left but don't go past end */
1570 while (*d != 0 && bytes_left-- != 0)
1571 d++;
1572 dlength = d - dest;
1573 bytes_left = dest_size - dlength;
1574
1575 if (bytes_left == 0)
1576 return dlength + strlen (s);
1577
1578 while (*s != 0)
1579 {
1580 if (bytes_left != 1)
1581 {
1582 *d++ = *s;
1583 bytes_left--;
1584 }
1585 s++;
1586 }
1587 *d = 0;
1588
1589 return dlength + (s - src); /* count does not include NUL */
1590 }
1591 #endif /* ! HAVE_STRLCPY */
1592
1593 /**
1594 * g_ascii_strdown:
1595 * @str: a string.
1596 * @len: length of @str in bytes, or -1 if @str is nul-terminated.
1597 *
1598 * Converts all upper case ASCII letters to lower case ASCII letters.
1599 *
1600 * Return value: a newly-allocated string, with all the upper case
1601 * characters in @str converted to lower case, with
1602 * semantics that exactly match g_ascii_tolower(). (Note
1603 * that this is unlike the old g_strdown(), which modified
1604 * the string in place.)
1605 **/
1606 gchar*
1607 g_ascii_strdown (const gchar *str,
1608 gssize len)
1609 {
1610 gchar *result, *s;
1611
1612 g_return_val_if_fail (str != NULL, NULL);
1613
1614 if (len < 0)
1615 len = strlen (str);
1616
1617 result = g_strndup (str, len);
1618 for (s = result; *s; s++)
1619 *s = g_ascii_tolower (*s);
1620
1621 return result;
1622 }
1623
1624 #endif
1625
1626 /**
1627 * g_ascii_strup:
1628 * @str: a string.
1629 * @len: length of @str in bytes, or -1 if @str is nul-terminated.
1630 *
1631 * Converts all lower case ASCII letters to upper case ASCII letters.
1632 *
1633 * Return value: a newly allocated string, with all the lower case
1634 * characters in @str converted to upper case, with
1635 * semantics that exactly match g_ascii_toupper(). (Note
1636 * that this is unlike the old g_strup(), which modified
1637 * the string in place.)
1638 **/
1639 gchar*
g_ascii_strup(const gchar * str,gssize len)1640 g_ascii_strup (const gchar *str,
1641 gssize len)
1642 {
1643 gchar *result, *s;
1644
1645 g_return_val_if_fail (str != NULL, NULL);
1646
1647 if (len < 0)
1648 len = strlen (str);
1649
1650 result = g_strndup (str, len);
1651 for (s = result; *s; s++)
1652 *s = g_ascii_toupper (*s);
1653
1654 return result;
1655 }
1656
1657 #if 0
1658
1659 /**
1660 * g_strdown:
1661 * @string: the string to convert.
1662 *
1663 * Converts a string to lower case.
1664 *
1665 * Return value: the string
1666 *
1667 * Deprecated:2.2: This function is totally broken for the reasons discussed
1668 * in the g_strncasecmp() docs - use g_ascii_strdown() or g_utf8_strdown()
1669 * instead.
1670 **/
1671 gchar*
1672 g_strdown (gchar *string)
1673 {
1674 register guchar *s;
1675
1676 g_return_val_if_fail (string != NULL, NULL);
1677
1678 s = (guchar *) string;
1679
1680 while (*s)
1681 {
1682 if (isupper (*s))
1683 *s = tolower (*s);
1684 s++;
1685 }
1686
1687 return (gchar *) string;
1688 }
1689
1690 /**
1691 * g_strup:
1692 * @string: the string to convert.
1693 *
1694 * Converts a string to upper case.
1695 *
1696 * Return value: the string
1697 *
1698 * Deprecated:2.2: This function is totally broken for the reasons discussed
1699 * in the g_strncasecmp() docs - use g_ascii_strup() or g_utf8_strup() instead.
1700 **/
1701 gchar*
1702 g_strup (gchar *string)
1703 {
1704 register guchar *s;
1705
1706 g_return_val_if_fail (string != NULL, NULL);
1707
1708 s = (guchar *) string;
1709
1710 while (*s)
1711 {
1712 if (islower (*s))
1713 *s = toupper (*s);
1714 s++;
1715 }
1716
1717 return (gchar *) string;
1718 }
1719
1720 gchar*
1721 g_strreverse (gchar *string)
1722 {
1723 g_return_val_if_fail (string != NULL, NULL);
1724
1725 if (*string)
1726 {
1727 register gchar *h, *t;
1728
1729 h = string;
1730 t = string + strlen (string) - 1;
1731
1732 while (h < t)
1733 {
1734 register gchar c;
1735
1736 c = *h;
1737 *h = *t;
1738 h++;
1739 *t = c;
1740 t--;
1741 }
1742 }
1743
1744 return string;
1745 }
1746
1747 /**
1748 * g_ascii_tolower:
1749 * @c: any character.
1750 *
1751 * Convert a character to ASCII lower case.
1752 *
1753 * Unlike the standard C library tolower() function, this only
1754 * recognizes standard ASCII letters and ignores the locale, returning
1755 * all non-ASCII characters unchanged, even if they are lower case
1756 * letters in a particular character set. Also unlike the standard
1757 * library function, this takes and returns a char, not an int, so
1758 * don't call it on %EOF but no need to worry about casting to #guchar
1759 * before passing a possibly non-ASCII character in.
1760 *
1761 * Return value: the result of converting @c to lower case.
1762 * If @c is not an ASCII upper case letter,
1763 * @c is returned unchanged.
1764 **/
1765 gchar
1766 g_ascii_tolower (gchar c)
1767 {
1768 return g_ascii_isupper (c) ? c - 'A' + 'a' : c;
1769 }
1770
1771 #endif
1772
1773 /**
1774 * g_ascii_toupper:
1775 * @c: any character.
1776 *
1777 * Convert a character to ASCII upper case.
1778 *
1779 * Unlike the standard C library toupper() function, this only
1780 * recognizes standard ASCII letters and ignores the locale, returning
1781 * all non-ASCII characters unchanged, even if they are upper case
1782 * letters in a particular character set. Also unlike the standard
1783 * library function, this takes and returns a char, not an int, so
1784 * don't call it on %EOF but no need to worry about casting to #guchar
1785 * before passing a possibly non-ASCII character in.
1786 *
1787 * Return value: the result of converting @c to upper case.
1788 * If @c is not an ASCII lower case letter,
1789 * @c is returned unchanged.
1790 **/
1791 gchar
g_ascii_toupper(gchar c)1792 g_ascii_toupper (gchar c)
1793 {
1794 return g_ascii_islower (c) ? c - 'a' + 'A' : c;
1795 }
1796
1797 #if 0
1798
1799 /**
1800 * g_ascii_digit_value:
1801 * @c: an ASCII character.
1802 *
1803 * Determines the numeric value of a character as a decimal
1804 * digit. Differs from g_unichar_digit_value() because it takes
1805 * a char, so there's no worry about sign extension if characters
1806 * are signed.
1807 *
1808 * Return value: If @c is a decimal digit (according to
1809 * g_ascii_isdigit()), its numeric value. Otherwise, -1.
1810 **/
1811 int
1812 g_ascii_digit_value (gchar c)
1813 {
1814 if (g_ascii_isdigit (c))
1815 return c - '0';
1816 return -1;
1817 }
1818
1819 /**
1820 * g_ascii_xdigit_value:
1821 * @c: an ASCII character.
1822 *
1823 * Determines the numeric value of a character as a hexidecimal
1824 * digit. Differs from g_unichar_xdigit_value() because it takes
1825 * a char, so there's no worry about sign extension if characters
1826 * are signed.
1827 *
1828 * Return value: If @c is a hex digit (according to
1829 * g_ascii_isxdigit()), its numeric value. Otherwise, -1.
1830 **/
1831 int
1832 g_ascii_xdigit_value (gchar c)
1833 {
1834 if (c >= 'A' && c <= 'F')
1835 return c - 'A' + 10;
1836 if (c >= 'a' && c <= 'f')
1837 return c - 'a' + 10;
1838 return g_ascii_digit_value (c);
1839 }
1840
1841 #endif
1842
1843 /**
1844 * g_ascii_strcasecmp:
1845 * @s1: string to compare with @s2.
1846 * @s2: string to compare with @s1.
1847 *
1848 * Compare two strings, ignoring the case of ASCII characters.
1849 *
1850 * Unlike the BSD strcasecmp() function, this only recognizes standard
1851 * ASCII letters and ignores the locale, treating all non-ASCII
1852 * bytes as if they are not letters.
1853 *
1854 * This function should be used only on strings that are known to be
1855 * in encodings where the bytes corresponding to ASCII letters always
1856 * represent themselves. This includes UTF-8 and the ISO-8859-*
1857 * charsets, but not for instance double-byte encodings like the
1858 * Windows Codepage 932, where the trailing bytes of double-byte
1859 * characters include all ASCII letters. If you compare two CP932
1860 * strings using this function, you will get false matches.
1861 *
1862 * Return value: 0 if the strings match, a negative value if @s1 < @s2,
1863 * or a positive value if @s1 > @s2.
1864 **/
1865 gint
g_ascii_strcasecmp(const gchar * s1,const gchar * s2)1866 g_ascii_strcasecmp (const gchar *s1,
1867 const gchar *s2)
1868 {
1869 gint c1, c2;
1870
1871 g_return_val_if_fail (s1 != NULL, 0);
1872 g_return_val_if_fail (s2 != NULL, 0);
1873
1874 while (*s1 && *s2)
1875 {
1876 c1 = (gint)(guchar) TOLOWER (*s1);
1877 c2 = (gint)(guchar) TOLOWER (*s2);
1878 if (c1 != c2)
1879 return (c1 - c2);
1880 s1++; s2++;
1881 }
1882
1883 return (((gint)(guchar) *s1) - ((gint)(guchar) *s2));
1884 }
1885
1886 #if 0
1887
1888 /**
1889 * g_ascii_strncasecmp:
1890 * @s1: string to compare with @s2.
1891 * @s2: string to compare with @s1.
1892 * @n: number of characters to compare.
1893 *
1894 * Compare @s1 and @s2, ignoring the case of ASCII characters and any
1895 * characters after the first @n in each string.
1896 *
1897 * Unlike the BSD strcasecmp() function, this only recognizes standard
1898 * ASCII letters and ignores the locale, treating all non-ASCII
1899 * characters as if they are not letters.
1900 *
1901 * The same warning as in g_ascii_strcasecmp() applies: Use this
1902 * function only on strings known to be in encodings where bytes
1903 * corresponding to ASCII letters always represent themselves.
1904 *
1905 * Return value: 0 if the strings match, a negative value if @s1 < @s2,
1906 * or a positive value if @s1 > @s2.
1907 **/
1908 gint
1909 g_ascii_strncasecmp (const gchar *s1,
1910 const gchar *s2,
1911 gsize n)
1912 {
1913 gint c1, c2;
1914
1915 g_return_val_if_fail (s1 != NULL, 0);
1916 g_return_val_if_fail (s2 != NULL, 0);
1917
1918 while (n && *s1 && *s2)
1919 {
1920 n -= 1;
1921 c1 = (gint)(guchar) TOLOWER (*s1);
1922 c2 = (gint)(guchar) TOLOWER (*s2);
1923 if (c1 != c2)
1924 return (c1 - c2);
1925 s1++; s2++;
1926 }
1927
1928 if (n)
1929 return (((gint) (guchar) *s1) - ((gint) (guchar) *s2));
1930 else
1931 return 0;
1932 }
1933
1934 /**
1935 * g_strcasecmp:
1936 * @s1: a string.
1937 * @s2: a string to compare with @s1.
1938 *
1939 * A case-insensitive string comparison, corresponding to the standard
1940 * strcasecmp() function on platforms which support it.
1941 *
1942 * Return value: 0 if the strings match, a negative value if @s1 < @s2,
1943 * or a positive value if @s1 > @s2.
1944 *
1945 * Deprecated:2.2: See g_strncasecmp() for a discussion of why this function
1946 * is deprecated and how to replace it.
1947 **/
1948 gint
1949 g_strcasecmp (const gchar *s1,
1950 const gchar *s2)
1951 {
1952 #ifdef HAVE_STRCASECMP
1953 g_return_val_if_fail (s1 != NULL, 0);
1954 g_return_val_if_fail (s2 != NULL, 0);
1955
1956 return strcasecmp (s1, s2);
1957 #else
1958 gint c1, c2;
1959
1960 g_return_val_if_fail (s1 != NULL, 0);
1961 g_return_val_if_fail (s2 != NULL, 0);
1962
1963 while (*s1 && *s2)
1964 {
1965 /* According to A. Cox, some platforms have islower's that
1966 * don't work right on non-uppercase
1967 */
1968 c1 = isupper ((guchar)*s1) ? tolower ((guchar)*s1) : *s1;
1969 c2 = isupper ((guchar)*s2) ? tolower ((guchar)*s2) : *s2;
1970 if (c1 != c2)
1971 return (c1 - c2);
1972 s1++; s2++;
1973 }
1974
1975 return (((gint)(guchar) *s1) - ((gint)(guchar) *s2));
1976 #endif
1977 }
1978
1979 /**
1980 * g_strncasecmp:
1981 * @s1: a string.
1982 * @s2: a string to compare with @s1.
1983 * @n: the maximum number of characters to compare.
1984 *
1985 * A case-insensitive string comparison, corresponding to the standard
1986 * strncasecmp() function on platforms which support it.
1987 * It is similar to g_strcasecmp() except it only compares the first @n
1988 * characters of the strings.
1989 *
1990 * Return value: 0 if the strings match, a negative value if @s1 < @s2,
1991 * or a positive value if @s1 > @s2.
1992 *
1993 * Deprecated:2.2: The problem with g_strncasecmp() is that it does the
1994 * comparison by calling toupper()/tolower(). These functions are
1995 * locale-specific and operate on single bytes. However, it is impossible
1996 * to handle things correctly from an I18N standpoint by operating on
1997 * bytes, since characters may be multibyte. Thus g_strncasecmp() is
1998 * broken if your string is guaranteed to be ASCII, since it's
1999 * locale-sensitive, and it's broken if your string is localized, since
2000 * it doesn't work on many encodings at all, including UTF-8, EUC-JP,
2001 * etc.
2002 *
2003 * There are therefore two replacement functions: g_ascii_strncasecmp(),
2004 * which only works on ASCII and is not locale-sensitive, and
2005 * g_utf8_casefold(), which is good for case-insensitive sorting of UTF-8.
2006 **/
2007 gint
2008 g_strncasecmp (const gchar *s1,
2009 const gchar *s2,
2010 guint n)
2011 {
2012 #ifdef HAVE_STRNCASECMP
2013 return strncasecmp (s1, s2, n);
2014 #else
2015 gint c1, c2;
2016
2017 g_return_val_if_fail (s1 != NULL, 0);
2018 g_return_val_if_fail (s2 != NULL, 0);
2019
2020 while (n && *s1 && *s2)
2021 {
2022 n -= 1;
2023 /* According to A. Cox, some platforms have islower's that
2024 * don't work right on non-uppercase
2025 */
2026 c1 = isupper ((guchar)*s1) ? tolower ((guchar)*s1) : *s1;
2027 c2 = isupper ((guchar)*s2) ? tolower ((guchar)*s2) : *s2;
2028 if (c1 != c2)
2029 return (c1 - c2);
2030 s1++; s2++;
2031 }
2032
2033 if (n)
2034 return (((gint) (guchar) *s1) - ((gint) (guchar) *s2));
2035 else
2036 return 0;
2037 #endif
2038 }
2039
2040 gchar*
2041 g_strdelimit (gchar *string,
2042 const gchar *delimiters,
2043 gchar new_delim)
2044 {
2045 register gchar *c;
2046
2047 g_return_val_if_fail (string != NULL, NULL);
2048
2049 if (!delimiters)
2050 delimiters = G_STR_DELIMITERS;
2051
2052 for (c = string; *c; c++)
2053 {
2054 if (strchr (delimiters, *c))
2055 *c = new_delim;
2056 }
2057
2058 return string;
2059 }
2060
2061 gchar*
2062 g_strcanon (gchar *string,
2063 const gchar *valid_chars,
2064 gchar substitutor)
2065 {
2066 register gchar *c;
2067
2068 g_return_val_if_fail (string != NULL, NULL);
2069 g_return_val_if_fail (valid_chars != NULL, NULL);
2070
2071 for (c = string; *c; c++)
2072 {
2073 if (!strchr (valid_chars, *c))
2074 *c = substitutor;
2075 }
2076
2077 return string;
2078 }
2079
2080 gchar*
2081 g_strcompress (const gchar *source)
2082 {
2083 const gchar *p = source, *octal;
2084 gchar *dest = g_malloc (strlen (source) + 1);
2085 gchar *q = dest;
2086
2087 while (*p)
2088 {
2089 if (*p == '\\')
2090 {
2091 p++;
2092 switch (*p)
2093 {
2094 case '\0':
2095 g_warning ("g_strcompress: trailing \\");
2096 goto out;
2097 case '0': case '1': case '2': case '3': case '4':
2098 case '5': case '6': case '7':
2099 *q = 0;
2100 octal = p;
2101 while ((p < octal + 3) && (*p >= '0') && (*p <= '7'))
2102 {
2103 *q = (*q * 8) + (*p - '0');
2104 p++;
2105 }
2106 q++;
2107 p--;
2108 break;
2109 case 'b':
2110 *q++ = '\b';
2111 break;
2112 case 'f':
2113 *q++ = '\f';
2114 break;
2115 case 'n':
2116 *q++ = '\n';
2117 break;
2118 case 'r':
2119 *q++ = '\r';
2120 break;
2121 case 't':
2122 *q++ = '\t';
2123 break;
2124 default: /* Also handles \" and \\ */
2125 *q++ = *p;
2126 break;
2127 }
2128 }
2129 else
2130 *q++ = *p;
2131 p++;
2132 }
2133 out:
2134 *q = 0;
2135
2136 return dest;
2137 }
2138
2139 gchar *
2140 g_strescape (const gchar *source,
2141 const gchar *exceptions)
2142 {
2143 const guchar *p;
2144 gchar *dest;
2145 gchar *q;
2146 guchar excmap[256];
2147
2148 g_return_val_if_fail (source != NULL, NULL);
2149
2150 p = (guchar *) source;
2151 /* Each source byte needs maximally four destination chars (\777) */
2152 q = dest = g_malloc (strlen (source) * 4 + 1);
2153
2154 memset (excmap, 0, 256);
2155 if (exceptions)
2156 {
2157 guchar *e = (guchar *) exceptions;
2158
2159 while (*e)
2160 {
2161 excmap[*e] = 1;
2162 e++;
2163 }
2164 }
2165
2166 while (*p)
2167 {
2168 if (excmap[*p])
2169 *q++ = *p;
2170 else
2171 {
2172 switch (*p)
2173 {
2174 case '\b':
2175 *q++ = '\\';
2176 *q++ = 'b';
2177 break;
2178 case '\f':
2179 *q++ = '\\';
2180 *q++ = 'f';
2181 break;
2182 case '\n':
2183 *q++ = '\\';
2184 *q++ = 'n';
2185 break;
2186 case '\r':
2187 *q++ = '\\';
2188 *q++ = 'r';
2189 break;
2190 case '\t':
2191 *q++ = '\\';
2192 *q++ = 't';
2193 break;
2194 case '\\':
2195 *q++ = '\\';
2196 *q++ = '\\';
2197 break;
2198 case '"':
2199 *q++ = '\\';
2200 *q++ = '"';
2201 break;
2202 default:
2203 if ((*p < ' ') || (*p >= 0177))
2204 {
2205 *q++ = '\\';
2206 *q++ = '0' + (((*p) >> 6) & 07);
2207 *q++ = '0' + (((*p) >> 3) & 07);
2208 *q++ = '0' + ((*p) & 07);
2209 }
2210 else
2211 *q++ = *p;
2212 break;
2213 }
2214 }
2215 p++;
2216 }
2217 *q = 0;
2218 return dest;
2219 }
2220
2221 gchar*
2222 g_strchug (gchar *string)
2223 {
2224 guchar *start;
2225
2226 g_return_val_if_fail (string != NULL, NULL);
2227
2228 for (start = (guchar*) string; *start && g_ascii_isspace (*start); start++)
2229 ;
2230
2231 g_memmove (string, start, strlen ((gchar *) start) + 1);
2232
2233 return string;
2234 }
2235
2236 gchar*
2237 g_strchomp (gchar *string)
2238 {
2239 gsize len;
2240
2241 g_return_val_if_fail (string != NULL, NULL);
2242
2243 len = strlen (string);
2244 while (len--)
2245 {
2246 if (g_ascii_isspace ((guchar) string[len]))
2247 string[len] = '\0';
2248 else
2249 break;
2250 }
2251
2252 return string;
2253 }
2254
2255 /**
2256 * g_strsplit:
2257 * @string: a string to split.
2258 * @delimiter: a string which specifies the places at which to split the string.
2259 * The delimiter is not included in any of the resulting strings, unless
2260 * @max_tokens is reached.
2261 * @max_tokens: the maximum number of pieces to split @string into. If this is
2262 * less than 1, the string is split completely.
2263 *
2264 * Splits a string into a maximum of @max_tokens pieces, using the given
2265 * @delimiter. If @max_tokens is reached, the remainder of @string is appended
2266 * to the last token.
2267 *
2268 * As a special case, the result of splitting the empty string "" is an empty
2269 * vector, not a vector containing a single string. The reason for this
2270 * special case is that being able to represent a empty vector is typically
2271 * more useful than consistent handling of empty elements. If you do need
2272 * to represent empty elements, you'll need to check for the empty string
2273 * before calling g_strsplit().
2274 *
2275 * Return value: a newly-allocated %NULL-terminated array of strings. Use
2276 * g_strfreev() to free it.
2277 **/
2278 gchar**
2279 g_strsplit (const gchar *string,
2280 const gchar *delimiter,
2281 gint max_tokens)
2282 {
2283 GSList *string_list = NULL, *slist;
2284 gchar **str_array, *s;
2285 guint n = 0;
2286 const gchar *remainder;
2287
2288 g_return_val_if_fail (string != NULL, NULL);
2289 g_return_val_if_fail (delimiter != NULL, NULL);
2290 g_return_val_if_fail (delimiter[0] != '\0', NULL);
2291
2292 if (max_tokens < 1)
2293 max_tokens = G_MAXINT;
2294
2295 remainder = string;
2296 s = strstr (remainder, delimiter);
2297 if (s)
2298 {
2299 gsize delimiter_len = strlen (delimiter);
2300
2301 while (--max_tokens && s)
2302 {
2303 gsize len;
2304 gchar *new_string;
2305
2306 len = s - remainder;
2307 new_string = g_new (gchar, len + 1);
2308 strncpy (new_string, remainder, len);
2309 new_string[len] = 0;
2310 string_list = g_slist_prepend (string_list, new_string);
2311 n++;
2312 remainder = s + delimiter_len;
2313 s = strstr (remainder, delimiter);
2314 }
2315 }
2316 if (*string)
2317 {
2318 n++;
2319 string_list = g_slist_prepend (string_list, g_strdup (remainder));
2320 }
2321
2322 str_array = g_new (gchar*, n + 1);
2323
2324 str_array[n--] = NULL;
2325 for (slist = string_list; slist; slist = slist->next)
2326 str_array[n--] = slist->data;
2327
2328 g_slist_free (string_list);
2329
2330 return str_array;
2331 }
2332
2333 /**
2334 * g_strsplit_set:
2335 * @string: The string to be tokenized
2336 * @delimiters: A nul-terminated string containing bytes that are used
2337 * to split the string.
2338 * @max_tokens: The maximum number of tokens to split @string into.
2339 * If this is less than 1, the string is split completely
2340 *
2341 * Splits @string into a number of tokens not containing any of the characters
2342 * in @delimiter. A token is the (possibly empty) longest string that does not
2343 * contain any of the characters in @delimiters. If @max_tokens is reached, the
2344 * remainder is appended to the last token.
2345 *
2346 * For example the result of g_strsplit_set ("abc:def/ghi", ":/", -1) is a
2347 * %NULL-terminated vector containing the three strings "abc", "def",
2348 * and "ghi".
2349 *
2350 * The result if g_strsplit_set (":def/ghi:", ":/", -1) is a %NULL-terminated
2351 * vector containing the four strings "", "def", "ghi", and "".
2352 *
2353 * As a special case, the result of splitting the empty string "" is an empty
2354 * vector, not a vector containing a single string. The reason for this
2355 * special case is that being able to represent a empty vector is typically
2356 * more useful than consistent handling of empty elements. If you do need
2357 * to represent empty elements, you'll need to check for the empty string
2358 * before calling g_strsplit_set().
2359 *
2360 * Note that this function works on bytes not characters, so it can't be used
2361 * to delimit UTF-8 strings for anything but ASCII characters.
2362 *
2363 * Return value: a newly-allocated %NULL-terminated array of strings. Use
2364 * g_strfreev() to free it.
2365 *
2366 * Since: 2.4
2367 **/
2368 gchar **
2369 g_strsplit_set (const gchar *string,
2370 const gchar *delimiters,
2371 gint max_tokens)
2372 {
2373 gboolean delim_table[256];
2374 GSList *tokens, *list;
2375 gint n_tokens;
2376 const gchar *s;
2377 const gchar *current;
2378 gchar *token;
2379 gchar **result;
2380
2381 g_return_val_if_fail (string != NULL, NULL);
2382 g_return_val_if_fail (delimiters != NULL, NULL);
2383
2384 if (max_tokens < 1)
2385 max_tokens = G_MAXINT;
2386
2387 if (*string == '\0')
2388 {
2389 result = g_new (char *, 1);
2390 result[0] = NULL;
2391 return result;
2392 }
2393
2394 memset (delim_table, FALSE, sizeof (delim_table));
2395 for (s = delimiters; *s != '\0'; ++s)
2396 delim_table[*(guchar *)s] = TRUE;
2397
2398 tokens = NULL;
2399 n_tokens = 0;
2400
2401 s = current = string;
2402 while (*s != '\0')
2403 {
2404 if (delim_table[*(guchar *)s] && n_tokens + 1 < max_tokens)
2405 {
2406 gchar *token;
2407
2408 token = g_strndup (current, s - current);
2409 tokens = g_slist_prepend (tokens, token);
2410 ++n_tokens;
2411
2412 current = s + 1;
2413 }
2414
2415 ++s;
2416 }
2417
2418 token = g_strndup (current, s - current);
2419 tokens = g_slist_prepend (tokens, token);
2420 ++n_tokens;
2421
2422 result = g_new (gchar *, n_tokens + 1);
2423
2424 result[n_tokens] = NULL;
2425 for (list = tokens; list != NULL; list = list->next)
2426 result[--n_tokens] = list->data;
2427
2428 g_slist_free (tokens);
2429
2430 return result;
2431 }
2432
2433 /**
2434 * g_strfreev:
2435 * @str_array: a %NULL-terminated array of strings to free.
2436
2437 * Frees a %NULL-terminated array of strings, and the array itself.
2438 * If called on a %NULL value, g_strfreev() simply returns.
2439 **/
2440 void
2441 g_strfreev (gchar **str_array)
2442 {
2443 if (str_array)
2444 {
2445 int i;
2446
2447 for(i = 0; str_array[i] != NULL; i++)
2448 g_free(str_array[i]);
2449
2450 g_free (str_array);
2451 }
2452 }
2453
2454 /**
2455 * g_strdupv:
2456 * @str_array: %NULL-terminated array of strings.
2457 *
2458 * Copies %NULL-terminated array of strings. The copy is a deep copy;
2459 * the new array should be freed by first freeing each string, then
2460 * the array itself. g_strfreev() does this for you. If called
2461 * on a %NULL value, g_strdupv() simply returns %NULL.
2462 *
2463 * Return value: a new %NULL-terminated array of strings.
2464 **/
2465 gchar**
2466 g_strdupv (gchar **str_array)
2467 {
2468 if (str_array)
2469 {
2470 gint i;
2471 gchar **retval;
2472
2473 i = 0;
2474 while (str_array[i])
2475 ++i;
2476
2477 retval = g_new (gchar*, i + 1);
2478
2479 i = 0;
2480 while (str_array[i])
2481 {
2482 retval[i] = g_strdup (str_array[i]);
2483 ++i;
2484 }
2485 retval[i] = NULL;
2486
2487 return retval;
2488 }
2489 else
2490 return NULL;
2491 }
2492
2493 gchar*
2494 g_strjoinv (const gchar *separator,
2495 gchar **str_array)
2496 {
2497 gchar *string;
2498 gchar *ptr;
2499
2500 g_return_val_if_fail (str_array != NULL, NULL);
2501
2502 if (separator == NULL)
2503 separator = "";
2504
2505 if (*str_array)
2506 {
2507 gint i;
2508 gsize len;
2509 gsize separator_len;
2510
2511 separator_len = strlen (separator);
2512 /* First part, getting length */
2513 len = 1 + strlen (str_array[0]);
2514 for (i = 1; str_array[i] != NULL; i++)
2515 len += strlen (str_array[i]);
2516 len += separator_len * (i - 1);
2517
2518 /* Second part, building string */
2519 string = g_new (gchar, len);
2520 ptr = g_stpcpy (string, *str_array);
2521 for (i = 1; str_array[i] != NULL; i++)
2522 {
2523 ptr = g_stpcpy (ptr, separator);
2524 ptr = g_stpcpy (ptr, str_array[i]);
2525 }
2526 }
2527 else
2528 string = g_strdup ("");
2529
2530 return string;
2531 }
2532
2533 gchar*
2534 g_strjoin (const gchar *separator,
2535 ...)
2536 {
2537 gchar *string, *s;
2538 va_list args;
2539 gsize len;
2540 gsize separator_len;
2541 gchar *ptr;
2542
2543 if (separator == NULL)
2544 separator = "";
2545
2546 separator_len = strlen (separator);
2547
2548 va_start (args, separator);
2549
2550 s = va_arg (args, gchar*);
2551
2552 if (s)
2553 {
2554 /* First part, getting length */
2555 len = 1 + strlen (s);
2556
2557 s = va_arg (args, gchar*);
2558 while (s)
2559 {
2560 len += separator_len + strlen (s);
2561 s = va_arg (args, gchar*);
2562 }
2563 va_end (args);
2564
2565 /* Second part, building string */
2566 string = g_new (gchar, len);
2567
2568 va_start (args, separator);
2569
2570 s = va_arg (args, gchar*);
2571 ptr = g_stpcpy (string, s);
2572
2573 s = va_arg (args, gchar*);
2574 while (s)
2575 {
2576 ptr = g_stpcpy (ptr, separator);
2577 ptr = g_stpcpy (ptr, s);
2578 s = va_arg (args, gchar*);
2579 }
2580 }
2581 else
2582 string = g_strdup ("");
2583
2584 va_end (args);
2585
2586 return string;
2587 }
2588
2589 #endif
2590
2591 /**
2592 * g_strstr_len:
2593 * @haystack: a string.
2594 * @haystack_len: the maximum length of @haystack.
2595 * @needle: the string to search for.
2596 *
2597 * Searches the string @haystack for the first occurrence
2598 * of the string @needle, limiting the length of the search
2599 * to @haystack_len.
2600 *
2601 * Return value: a pointer to the found occurrence, or
2602 * %NULL if not found.
2603 **/
2604 gchar *
g_strstr_len(const gchar * haystack,gssize haystack_len,const gchar * needle)2605 g_strstr_len (const gchar *haystack,
2606 gssize haystack_len,
2607 const gchar *needle)
2608 {
2609 g_return_val_if_fail (haystack != NULL, NULL);
2610 g_return_val_if_fail (needle != NULL, NULL);
2611
2612 if (haystack_len < 0)
2613 return strstr (haystack, needle);
2614 else
2615 {
2616 const gchar *p = haystack;
2617 gsize needle_len = strlen (needle);
2618 const gchar *end;
2619 gsize i;
2620
2621 if (needle_len == 0)
2622 return (gchar *)haystack;
2623
2624 if (haystack_len < needle_len)
2625 return NULL;
2626
2627 end = haystack + haystack_len - needle_len;
2628
2629 while (*p && p <= end)
2630 {
2631 for (i = 0; i < needle_len; i++)
2632 if (p[i] != needle[i])
2633 goto next;
2634
2635 return (gchar *)p;
2636
2637 next:
2638 p++;
2639 }
2640
2641 return NULL;
2642 }
2643 }
2644
2645 #if 0
2646
2647 /**
2648 * g_strrstr:
2649 * @haystack: a nul-terminated string.
2650 * @needle: the nul-terminated string to search for.
2651 *
2652 * Searches the string @haystack for the last occurrence
2653 * of the string @needle.
2654 *
2655 * Return value: a pointer to the found occurrence, or
2656 * %NULL if not found.
2657 **/
2658 gchar *
2659 g_strrstr (const gchar *haystack,
2660 const gchar *needle)
2661 {
2662 gsize i;
2663 gsize needle_len;
2664 gsize haystack_len;
2665 const gchar *p;
2666
2667 g_return_val_if_fail (haystack != NULL, NULL);
2668 g_return_val_if_fail (needle != NULL, NULL);
2669
2670 needle_len = strlen (needle);
2671 haystack_len = strlen (haystack);
2672
2673 if (needle_len == 0)
2674 return (gchar *)haystack;
2675
2676 if (haystack_len < needle_len)
2677 return NULL;
2678
2679 p = haystack + haystack_len - needle_len;
2680
2681 while (p >= haystack)
2682 {
2683 for (i = 0; i < needle_len; i++)
2684 if (p[i] != needle[i])
2685 goto next;
2686
2687 return (gchar *)p;
2688
2689 next:
2690 p--;
2691 }
2692
2693 return NULL;
2694 }
2695
2696 /**
2697 * g_strrstr_len:
2698 * @haystack: a nul-terminated string.
2699 * @haystack_len: the maximum length of @haystack.
2700 * @needle: the nul-terminated string to search for.
2701 *
2702 * Searches the string @haystack for the last occurrence
2703 * of the string @needle, limiting the length of the search
2704 * to @haystack_len.
2705 *
2706 * Return value: a pointer to the found occurrence, or
2707 * %NULL if not found.
2708 **/
2709 gchar *
2710 g_strrstr_len (const gchar *haystack,
2711 gssize haystack_len,
2712 const gchar *needle)
2713 {
2714 g_return_val_if_fail (haystack != NULL, NULL);
2715 g_return_val_if_fail (needle != NULL, NULL);
2716
2717 if (haystack_len < 0)
2718 return g_strrstr (haystack, needle);
2719 else
2720 {
2721 gsize needle_len = strlen (needle);
2722 const gchar *haystack_max = haystack + haystack_len;
2723 const gchar *p = haystack;
2724 gsize i;
2725
2726 while (p < haystack_max && *p)
2727 p++;
2728
2729 if (p < haystack + needle_len)
2730 return NULL;
2731
2732 p -= needle_len;
2733
2734 while (p >= haystack)
2735 {
2736 for (i = 0; i < needle_len; i++)
2737 if (p[i] != needle[i])
2738 goto next;
2739
2740 return (gchar *)p;
2741
2742 next:
2743 p--;
2744 }
2745
2746 return NULL;
2747 }
2748 }
2749
2750
2751 /**
2752 * g_str_has_suffix:
2753 * @str: a nul-terminated string.
2754 * @suffix: the nul-terminated suffix to look for.
2755 *
2756 * Looks whether the string @str ends with @suffix.
2757 *
2758 * Return value: %TRUE if @str end with @suffix, %FALSE otherwise.
2759 *
2760 * Since: 2.2
2761 **/
2762 gboolean
2763 g_str_has_suffix (const gchar *str,
2764 const gchar *suffix)
2765 {
2766 int str_len;
2767 int suffix_len;
2768
2769 g_return_val_if_fail (str != NULL, FALSE);
2770 g_return_val_if_fail (suffix != NULL, FALSE);
2771
2772 str_len = strlen (str);
2773 suffix_len = strlen (suffix);
2774
2775 if (str_len < suffix_len)
2776 return FALSE;
2777
2778 return strcmp (str + str_len - suffix_len, suffix) == 0;
2779 }
2780
2781 /**
2782 * g_str_has_prefix:
2783 * @str: a nul-terminated string.
2784 * @prefix: the nul-terminated prefix to look for.
2785 *
2786 * Looks whether the string @str begins with @prefix.
2787 *
2788 * Return value: %TRUE if @str begins with @prefix, %FALSE otherwise.
2789 *
2790 * Since: 2.2
2791 **/
2792 gboolean
2793 g_str_has_prefix (const gchar *str,
2794 const gchar *prefix)
2795 {
2796 int str_len;
2797 int prefix_len;
2798
2799 g_return_val_if_fail (str != NULL, FALSE);
2800 g_return_val_if_fail (prefix != NULL, FALSE);
2801
2802 str_len = strlen (str);
2803 prefix_len = strlen (prefix);
2804
2805 if (str_len < prefix_len)
2806 return FALSE;
2807
2808 return strncmp (str, prefix, prefix_len) == 0;
2809 }
2810
2811
2812 /**
2813 * g_strip_context:
2814 * @msgid: a string
2815 * @msgval: another string
2816 *
2817 * An auxiliary function for gettext() support (see Q_()).
2818 *
2819 * Return value: @msgval, unless @msgval is identical to @msgid and contains
2820 * a '|' character, in which case a pointer to the substring of msgid after
2821 * the first '|' character is returned.
2822 *
2823 * Since: 2.4
2824 **/
2825 G_CONST_RETURN gchar *
2826 g_strip_context (const gchar *msgid,
2827 const gchar *msgval)
2828 {
2829 if (msgval == msgid)
2830 {
2831 const char *c = strchr (msgid, '|');
2832 if (c != NULL)
2833 return c + 1;
2834 }
2835
2836 return msgval;
2837 }
2838
2839
2840 /**
2841 * g_strv_length:
2842 * @str_array: a %NULL-terminated array of strings.
2843 *
2844 * Returns the length of the given %NULL-terminated
2845 * string array @str_array.
2846 *
2847 * Return value: length of @str_array.
2848 *
2849 * Since: 2.6
2850 **/
2851 guint
2852 g_strv_length (gchar **str_array)
2853 {
2854 guint i = 0;
2855
2856 g_return_val_if_fail (str_array != NULL, 0);
2857
2858 while (str_array[i])
2859 ++i;
2860
2861 return i;
2862 }
2863
2864 #define __G_STRFUNCS_C__
2865 #include "galiasdef.c"
2866 #endif
2867