Don't leave out parameters uninitialized. (#490061, Benjamin Otte)
[platform/upstream/glib.git] / glib / gstrfuncs.c
1 /* GLIB - Library of useful routines for C programming
2  * Copyright (C) 1995-1997  Peter Mattis, Spencer Kimball and Josh MacDonald
3  *
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.
8  *
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.
13  *
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.
18  */
19
20 /*
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/. 
25  */
26
27 /*
28  * MT safe
29  */
30
31 #include "config.h"
32
33 #define _GNU_SOURCE             /* For stpcpy */
34
35 #include <stdarg.h>
36 #include <stdio.h>
37 #include <stdlib.h>
38 #include <string.h>
39 #include <locale.h>
40 #include <errno.h>
41 #include <ctype.h>              /* For tolower() */
42 #if !defined (HAVE_STRSIGNAL) || !defined(NO_SYS_SIGLIST_DECL)
43 #include <signal.h>
44 #endif
45
46 #include "glib.h"
47 #include "gprintf.h"
48 #include "gprintfint.h"
49
50 #include "galias.h"
51
52 #ifdef G_OS_WIN32
53 #include <windows.h>
54 #endif
55
56 /* do not include <unistd.h> in this place since it
57  * interferes with g_strsignal() on some OSes
58  */
59
60 static const guint16 ascii_table_data[256] = {
61   0x004, 0x004, 0x004, 0x004, 0x004, 0x004, 0x004, 0x004,
62   0x004, 0x104, 0x104, 0x004, 0x104, 0x104, 0x004, 0x004,
63   0x004, 0x004, 0x004, 0x004, 0x004, 0x004, 0x004, 0x004,
64   0x004, 0x004, 0x004, 0x004, 0x004, 0x004, 0x004, 0x004,
65   0x140, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0,
66   0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0,
67   0x459, 0x459, 0x459, 0x459, 0x459, 0x459, 0x459, 0x459,
68   0x459, 0x459, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0,
69   0x0d0, 0x653, 0x653, 0x653, 0x653, 0x653, 0x653, 0x253,
70   0x253, 0x253, 0x253, 0x253, 0x253, 0x253, 0x253, 0x253,
71   0x253, 0x253, 0x253, 0x253, 0x253, 0x253, 0x253, 0x253,
72   0x253, 0x253, 0x253, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0,
73   0x0d0, 0x473, 0x473, 0x473, 0x473, 0x473, 0x473, 0x073,
74   0x073, 0x073, 0x073, 0x073, 0x073, 0x073, 0x073, 0x073,
75   0x073, 0x073, 0x073, 0x073, 0x073, 0x073, 0x073, 0x073,
76   0x073, 0x073, 0x073, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x004
77   /* the upper 128 are all zeroes */
78 };
79
80 const guint16 * const g_ascii_table = ascii_table_data;
81
82 gchar*
83 g_strdup (const gchar *str)
84 {
85   gchar *new_str;
86   gsize length;
87
88   if (str)
89     {
90       length = strlen (str) + 1;
91       new_str = g_new (char, length);
92       memcpy (new_str, str, length);
93     }
94   else
95     new_str = NULL;
96
97   return new_str;
98 }
99
100 gpointer
101 g_memdup (gconstpointer mem,
102           guint         byte_size)
103 {
104   gpointer new_mem;
105
106   if (mem)
107     {
108       new_mem = g_malloc (byte_size);
109       memcpy (new_mem, mem, byte_size);
110     }
111   else
112     new_mem = NULL;
113
114   return new_mem;
115 }
116
117 /**
118  * g_strndup:
119  * @str: the string to duplicate
120  * @n: the maximum number of bytes to copy from @str
121  *
122  * Duplicates the first @n bytes of a string, returning a newly-allocated
123  * buffer @n + 1 bytes long which will always be nul-terminated.
124  * If @str is less than @n bytes long the buffer is padded with nuls.
125  * If @str is %NULL it returns %NULL.
126  * The returned value should be freed when no longer needed.
127  * 
128  * <note><para>
129  * To copy a number of characters from a UTF-8 encoded string, use
130  * g_utf8_strncpy() instead.
131  * </para></note>
132  * 
133  * Returns: a newly-allocated buffer containing the first @n bytes 
134  *          of @str, nul-terminated 
135  */
136 gchar*
137 g_strndup (const gchar *str,
138            gsize        n)    
139 {
140   gchar *new_str;
141
142   if (str)
143     {
144       new_str = g_new (gchar, n + 1);
145       strncpy (new_str, str, n);
146       new_str[n] = '\0';
147     }
148   else
149     new_str = NULL;
150
151   return new_str;
152 }
153
154 /**
155  * g_strnfill:
156  * @length: the length of the new string
157  * @fill_char: the byte to fill the string with
158  *
159  * Creates a new string @length bytes long filled with @fill_char.
160  * The returned string should be freed when no longer needed.
161  * 
162  * Returns: a newly-allocated string filled the @fill_char
163  */
164 gchar*
165 g_strnfill (gsize length,     
166             gchar fill_char)
167 {
168   gchar *str;
169
170   str = g_new (gchar, length + 1);
171   memset (str, (guchar)fill_char, length);
172   str[length] = '\0';
173
174   return str;
175 }
176
177 /**
178  * g_stpcpy:
179  * @dest: destination buffer.
180  * @src: source string.
181  * 
182  * Copies a nul-terminated string into the dest buffer, include the
183  * trailing nul, and return a pointer to the trailing nul byte.
184  * This is useful for concatenating multiple strings together
185  * without having to repeatedly scan for the end.
186  * 
187  * Return value: a pointer to trailing nul byte.
188  **/
189 gchar *
190 g_stpcpy (gchar       *dest,
191           const gchar *src)
192 {
193 #ifdef HAVE_STPCPY
194   g_return_val_if_fail (dest != NULL, NULL);
195   g_return_val_if_fail (src != NULL, NULL);
196   return stpcpy (dest, src);
197 #else
198   register gchar *d = dest;
199   register const gchar *s = src;
200
201   g_return_val_if_fail (dest != NULL, NULL);
202   g_return_val_if_fail (src != NULL, NULL);
203   do
204     *d++ = *s;
205   while (*s++ != '\0');
206
207   return d - 1;
208 #endif
209 }
210
211 gchar*
212 g_strdup_vprintf (const gchar *format,
213                   va_list      args)
214 {
215   gchar *string = NULL;
216
217   g_vasprintf (&string, format, args);
218
219   return string;
220 }
221
222 gchar*
223 g_strdup_printf (const gchar *format,
224                  ...)
225 {
226   gchar *buffer;
227   va_list args;
228
229   va_start (args, format);
230   buffer = g_strdup_vprintf (format, args);
231   va_end (args);
232
233   return buffer;
234 }
235
236 gchar*
237 g_strconcat (const gchar *string1, ...)
238 {
239   gsize   l;     
240   va_list args;
241   gchar   *s;
242   gchar   *concat;
243   gchar   *ptr;
244
245   if (!string1)
246     return NULL;
247
248   l = 1 + strlen (string1);
249   va_start (args, string1);
250   s = va_arg (args, gchar*);
251   while (s)
252     {
253       l += strlen (s);
254       s = va_arg (args, gchar*);
255     }
256   va_end (args);
257
258   concat = g_new (gchar, l);
259   ptr = concat;
260
261   ptr = g_stpcpy (ptr, string1);
262   va_start (args, string1);
263   s = va_arg (args, gchar*);
264   while (s)
265     {
266       ptr = g_stpcpy (ptr, s);
267       s = va_arg (args, gchar*);
268     }
269   va_end (args);
270
271   return concat;
272 }
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
508 /**
509  * g_ascii_dtostr:
510  * @buffer: A buffer to place the resulting string in
511  * @buf_len: The length of the buffer.
512  * @d: The #gdouble to convert
513  *
514  * Converts a #gdouble to a string, using the '.' as
515  * decimal point. 
516  * 
517  * This functions generates enough precision that converting
518  * the string back using g_ascii_strtod() gives the same machine-number
519  * (on machines with IEEE compatible 64bit doubles). It is
520  * guaranteed that the size of the resulting string will never
521  * be larger than @G_ASCII_DTOSTR_BUF_SIZE bytes.
522  *
523  * Return value: The pointer to the buffer with the converted string.
524  **/
525 gchar *
526 g_ascii_dtostr (gchar       *buffer,
527                 gint         buf_len,
528                 gdouble      d)
529 {
530   return g_ascii_formatd (buffer, buf_len, "%.17g", d);
531 }
532
533 /**
534  * g_ascii_formatd:
535  * @buffer: A buffer to place the resulting string in
536  * @buf_len: The length of the buffer.
537  * @format: The printf()-style format to use for the
538  *          code to use for converting. 
539  * @d: The #gdouble to convert
540  *
541  * Converts a #gdouble to a string, using the '.' as
542  * decimal point. To format the number you pass in
543  * a printf()-style format string. Allowed conversion
544  * specifiers are 'e', 'E', 'f', 'F', 'g' and 'G'. 
545  * 
546  * If you just want to want to serialize the value into a
547  * string, use g_ascii_dtostr().
548  *
549  * Return value: The pointer to the buffer with the converted string.
550  **/
551 gchar *
552 g_ascii_formatd (gchar       *buffer,
553                  gint         buf_len,
554                  const gchar *format,
555                  gdouble      d)
556 {
557   struct lconv *locale_data;
558   const char *decimal_point;
559   int decimal_point_len;
560   gchar *p;
561   int rest_len;
562   gchar format_char;
563
564   g_return_val_if_fail (buffer != NULL, NULL);
565   g_return_val_if_fail (format[0] == '%', NULL);
566   g_return_val_if_fail (strpbrk (format + 1, "'l%") == NULL, NULL);
567  
568   format_char = format[strlen (format) - 1];
569   
570   g_return_val_if_fail (format_char == 'e' || format_char == 'E' ||
571                         format_char == 'f' || format_char == 'F' ||
572                         format_char == 'g' || format_char == 'G',
573                         NULL);
574
575   if (format[0] != '%')
576     return NULL;
577
578   if (strpbrk (format + 1, "'l%"))
579     return NULL;
580
581   if (!(format_char == 'e' || format_char == 'E' ||
582         format_char == 'f' || format_char == 'F' ||
583         format_char == 'g' || format_char == 'G'))
584     return NULL;
585
586       
587   _g_snprintf (buffer, buf_len, format, d);
588
589   locale_data = localeconv ();
590   decimal_point = locale_data->decimal_point;
591   decimal_point_len = strlen (decimal_point);
592
593   g_assert (decimal_point_len != 0);
594
595   if (decimal_point[0] != '.' ||
596       decimal_point[1] != 0)
597     {
598       p = buffer;
599
600       while (g_ascii_isspace (*p))
601         p++;
602
603       if (*p == '+' || *p == '-')
604         p++;
605
606       while (isdigit ((guchar)*p))
607         p++;
608
609       if (strncmp (p, decimal_point, decimal_point_len) == 0)
610         {
611           *p = '.';
612           p++;
613           if (decimal_point_len > 1) 
614             {
615               rest_len = strlen (p + (decimal_point_len-1));
616               memmove (p, p + (decimal_point_len-1), rest_len);
617               p[rest_len] = 0;
618             }
619         }
620     }
621   
622   return buffer;
623 }
624
625 static guint64
626 g_parse_long_long (const gchar *nptr,
627                    gchar      **endptr,
628                    guint        base,
629                    gboolean    *negative)
630 {
631   /* this code is based on on the strtol(3) code from GNU libc released under
632    * the GNU Lesser General Public License.
633    *
634    * Copyright (C) 1991,92,94,95,96,97,98,99,2000,01,02
635    *        Free Software Foundation, Inc.
636    */
637 #define ISSPACE(c)              ((c) == ' ' || (c) == '\f' || (c) == '\n' || \
638                                  (c) == '\r' || (c) == '\t' || (c) == '\v')
639 #define ISUPPER(c)              ((c) >= 'A' && (c) <= 'Z')
640 #define ISLOWER(c)              ((c) >= 'a' && (c) <= 'z')
641 #define ISALPHA(c)              (ISUPPER (c) || ISLOWER (c))
642 #define TOUPPER(c)              (ISLOWER (c) ? (c) - 'a' + 'A' : (c))
643 #define TOLOWER(c)              (ISUPPER (c) ? (c) - 'A' + 'a' : (c))
644   gboolean overflow;
645   guint64 cutoff;
646   guint64 cutlim;
647   guint64 ui64;
648   const gchar *s, *save;
649   guchar c;
650   
651   g_return_val_if_fail (nptr != NULL, 0);
652   
653   *negative = FALSE;
654   if (base == 1 || base > 36)
655     {
656       errno = EINVAL;
657       if (endptr)
658         *endptr = nptr;
659       return 0;
660     }
661   
662   save = s = nptr;
663   
664   /* Skip white space.  */
665   while (ISSPACE (*s))
666     ++s;
667
668   if (G_UNLIKELY (!*s))
669     goto noconv;
670   
671   /* Check for a sign.  */
672   if (*s == '-')
673     {
674       *negative = TRUE;
675       ++s;
676     }
677   else if (*s == '+')
678     ++s;
679   
680   /* Recognize number prefix and if BASE is zero, figure it out ourselves.  */
681   if (*s == '0')
682     {
683       if ((base == 0 || base == 16) && TOUPPER (s[1]) == 'X')
684         {
685           s += 2;
686           base = 16;
687         }
688       else if (base == 0)
689         base = 8;
690     }
691   else if (base == 0)
692     base = 10;
693   
694   /* Save the pointer so we can check later if anything happened.  */
695   save = s;
696   cutoff = G_MAXUINT64 / base;
697   cutlim = G_MAXUINT64 % base;
698   
699   overflow = FALSE;
700   ui64 = 0;
701   c = *s;
702   for (; c; c = *++s)
703     {
704       if (c >= '0' && c <= '9')
705         c -= '0';
706       else if (ISALPHA (c))
707         c = TOUPPER (c) - 'A' + 10;
708       else
709         break;
710       if (c >= base)
711         break;
712       /* Check for overflow.  */
713       if (ui64 > cutoff || (ui64 == cutoff && c > cutlim))
714         overflow = TRUE;
715       else
716         {
717           ui64 *= base;
718           ui64 += c;
719         }
720     }
721   
722   /* Check if anything actually happened.  */
723   if (s == save)
724     goto noconv;
725   
726   /* Store in ENDPTR the address of one character
727      past the last character we converted.  */
728   if (endptr)
729     *endptr = (gchar*) s;
730   
731   if (G_UNLIKELY (overflow))
732     {
733       errno = ERANGE;
734       return G_MAXUINT64;
735     }
736
737   return ui64;
738   
739  noconv:
740   /* We must handle a special case here: the base is 0 or 16 and the
741      first two characters are '0' and 'x', but the rest are no
742      hexadecimal digits.  This is no error case.  We return 0 and
743      ENDPTR points to the `x`.  */
744   if (endptr)
745     {
746       if (save - nptr >= 2 && TOUPPER (save[-1]) == 'X'
747           && save[-2] == '0')
748         *endptr = (gchar*) &save[-1];
749       else
750         /*  There was no number to convert.  */
751         *endptr = (gchar*) nptr;
752     }
753   return 0;
754 }
755
756 /**
757  * g_ascii_strtoull:
758  * @nptr:    the string to convert to a numeric value.
759  * @endptr:  if non-%NULL, it returns the character after
760  *           the last character used in the conversion.
761  * @base:    to be used for the conversion, 2..36 or 0
762  *
763  * Converts a string to a #guint64 value.
764  * This function behaves like the standard strtoull() function
765  * does in the C locale. It does this without actually
766  * changing the current locale, since that would not be
767  * thread-safe.
768  *
769  * This function is typically used when reading configuration
770  * files or other non-user input that should be locale independent.
771  * To handle input from the user you should normally use the
772  * locale-sensitive system strtoull() function.
773  *
774  * If the correct value would cause overflow, %G_MAXUINT64
775  * is returned, and %ERANGE is stored in %errno.  If the base is
776  * outside the valid range, zero is returned, and %EINVAL is stored
777  * in %errno.  If the string conversion fails, zero is returned, and
778  * @endptr returns @nptr (if @endptr is non-%NULL).
779  *
780  * Return value: the #guint64 value or zero on error.
781  *
782  * Since: 2.2
783  **/
784 guint64
785 g_ascii_strtoull (const gchar *nptr,
786                   gchar      **endptr,
787                   guint        base)
788 {
789   gboolean negative;
790   guint64 result;
791
792   result = g_parse_long_long (nptr, endptr, base, &negative);
793
794   /* Return the result of the appropriate sign.  */
795   return negative ? -result : result;
796 }
797
798 /**
799  * g_ascii_strtoll:
800  * @nptr:    the string to convert to a numeric value.
801  * @endptr:  if non-%NULL, it returns the character after
802  *           the last character used in the conversion.
803  * @base:    to be used for the conversion, 2..36 or 0
804  *
805  * Converts a string to a #gint64 value.
806  * This function behaves like the standard strtoll() function
807  * does in the C locale. It does this without actually
808  * changing the current locale, since that would not be
809  * thread-safe.
810  *
811  * This function is typically used when reading configuration
812  * files or other non-user input that should be locale independent.
813  * To handle input from the user you should normally use the
814  * locale-sensitive system strtoll() function.
815  *
816  * If the correct value would cause overflow, %G_MAXINT64 or %G_MININT64
817  * is returned, and %ERANGE is stored in %errno.  If the base is
818  * outside the valid range, zero is returned, and %EINVAL is stored
819  * in %errno.  If the string conversion fails, zero is returned, and
820  * @endptr returns @nptr (if @endptr is non-%NULL).
821  *
822  * Return value: the #gint64 value or zero on error.
823  *
824  * Since: 2.12
825  **/
826 gint64 
827 g_ascii_strtoll (const gchar *nptr,
828                  gchar      **endptr,
829                  guint        base)
830 {
831   gboolean negative;
832   guint64 result;
833
834   result = g_parse_long_long (nptr, endptr, base, &negative);
835
836   if (negative && result > (guint64) G_MININT64)
837     {
838       errno = ERANGE;
839       return G_MININT64;
840     }
841   else if (!negative && result > (guint64) G_MAXINT64)
842     {
843       errno = ERANGE;
844       return G_MAXINT64;
845     }
846   else if (negative)
847     return - (gint64) result;
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 /**
1625  * g_ascii_strup:
1626  * @str: a string.
1627  * @len: length of @str in bytes, or -1 if @str is nul-terminated.
1628  * 
1629  * Converts all lower case ASCII letters to upper case ASCII letters.
1630  * 
1631  * Return value: a newly allocated string, with all the lower case
1632  *               characters in @str converted to upper case, with
1633  *               semantics that exactly match g_ascii_toupper(). (Note
1634  *               that this is unlike the old g_strup(), which modified
1635  *               the string in place.)
1636  **/
1637 gchar*
1638 g_ascii_strup (const gchar *str,
1639                gssize       len)
1640 {
1641   gchar *result, *s;
1642
1643   g_return_val_if_fail (str != NULL, NULL);
1644
1645   if (len < 0)
1646     len = strlen (str);
1647
1648   result = g_strndup (str, len);
1649   for (s = result; *s; s++)
1650     *s = g_ascii_toupper (*s);
1651
1652   return result;
1653 }
1654
1655 /**
1656  * g_strdown:
1657  * @string: the string to convert.
1658  * 
1659  * Converts a string to lower case.  
1660  * 
1661  * Return value: the string 
1662  *
1663  * Deprecated:2.2: This function is totally broken for the reasons discussed 
1664  * in the g_strncasecmp() docs - use g_ascii_strdown() or g_utf8_strdown() 
1665  * instead.
1666  **/
1667 gchar*
1668 g_strdown (gchar *string)
1669 {
1670   register guchar *s;
1671   
1672   g_return_val_if_fail (string != NULL, NULL);
1673   
1674   s = (guchar *) string;
1675   
1676   while (*s)
1677     {
1678       if (isupper (*s))
1679         *s = tolower (*s);
1680       s++;
1681     }
1682   
1683   return (gchar *) string;
1684 }
1685
1686 /**
1687  * g_strup:
1688  * @string: the string to convert.
1689  * 
1690  * Converts a string to upper case. 
1691  * 
1692  * Return value: the string
1693  *
1694  * Deprecated:2.2: This function is totally broken for the reasons discussed 
1695  * in the g_strncasecmp() docs - use g_ascii_strup() or g_utf8_strup() instead.
1696  **/
1697 gchar*
1698 g_strup (gchar *string)
1699 {
1700   register guchar *s;
1701
1702   g_return_val_if_fail (string != NULL, NULL);
1703
1704   s = (guchar *) string;
1705
1706   while (*s)
1707     {
1708       if (islower (*s))
1709         *s = toupper (*s);
1710       s++;
1711     }
1712
1713   return (gchar *) string;
1714 }
1715
1716 gchar*
1717 g_strreverse (gchar *string)
1718 {
1719   g_return_val_if_fail (string != NULL, NULL);
1720
1721   if (*string)
1722     {
1723       register gchar *h, *t;
1724
1725       h = string;
1726       t = string + strlen (string) - 1;
1727
1728       while (h < t)
1729         {
1730           register gchar c;
1731
1732           c = *h;
1733           *h = *t;
1734           h++;
1735           *t = c;
1736           t--;
1737         }
1738     }
1739
1740   return string;
1741 }
1742
1743 /**
1744  * g_ascii_tolower:
1745  * @c: any character.
1746  * 
1747  * Convert a character to ASCII lower case.
1748  *
1749  * Unlike the standard C library tolower() function, this only
1750  * recognizes standard ASCII letters and ignores the locale, returning
1751  * all non-ASCII characters unchanged, even if they are lower case
1752  * letters in a particular character set. Also unlike the standard
1753  * library function, this takes and returns a char, not an int, so
1754  * don't call it on %EOF but no need to worry about casting to #guchar
1755  * before passing a possibly non-ASCII character in.
1756  * 
1757  * Return value: the result of converting @c to lower case.
1758  *               If @c is not an ASCII upper case letter,
1759  *               @c is returned unchanged.
1760  **/
1761 gchar
1762 g_ascii_tolower (gchar c)
1763 {
1764   return g_ascii_isupper (c) ? c - 'A' + 'a' : c;
1765 }
1766
1767 /**
1768  * g_ascii_toupper:
1769  * @c: any character.
1770  * 
1771  * Convert a character to ASCII upper case.
1772  *
1773  * Unlike the standard C library toupper() function, this only
1774  * recognizes standard ASCII letters and ignores the locale, returning
1775  * all non-ASCII characters unchanged, even if they are upper case
1776  * letters in a particular character set. Also unlike the standard
1777  * library function, this takes and returns a char, not an int, so
1778  * don't call it on %EOF but no need to worry about casting to #guchar
1779  * before passing a possibly non-ASCII character in.
1780  * 
1781  * Return value: the result of converting @c to upper case.
1782  *               If @c is not an ASCII lower case letter,
1783  *               @c is returned unchanged.
1784  **/
1785 gchar
1786 g_ascii_toupper (gchar c)
1787 {
1788   return g_ascii_islower (c) ? c - 'a' + 'A' : c;
1789 }
1790
1791 /**
1792  * g_ascii_digit_value:
1793  * @c: an ASCII character.
1794  *
1795  * Determines the numeric value of a character as a decimal
1796  * digit. Differs from g_unichar_digit_value() because it takes
1797  * a char, so there's no worry about sign extension if characters
1798  * are signed.
1799  *
1800  * Return value: If @c is a decimal digit (according to
1801  * g_ascii_isdigit()), its numeric value. Otherwise, -1.
1802  **/
1803 int
1804 g_ascii_digit_value (gchar c)
1805 {
1806   if (g_ascii_isdigit (c))
1807     return c - '0';
1808   return -1;
1809 }
1810
1811 /**
1812  * g_ascii_xdigit_value:
1813  * @c: an ASCII character.
1814  *
1815  * Determines the numeric value of a character as a hexidecimal
1816  * digit. Differs from g_unichar_xdigit_value() because it takes
1817  * a char, so there's no worry about sign extension if characters
1818  * are signed.
1819  *
1820  * Return value: If @c is a hex digit (according to
1821  * g_ascii_isxdigit()), its numeric value. Otherwise, -1.
1822  **/
1823 int
1824 g_ascii_xdigit_value (gchar c)
1825 {
1826   if (c >= 'A' && c <= 'F')
1827     return c - 'A' + 10;
1828   if (c >= 'a' && c <= 'f')
1829     return c - 'a' + 10;
1830   return g_ascii_digit_value (c);
1831 }
1832
1833 /**
1834  * g_ascii_strcasecmp:
1835  * @s1: string to compare with @s2.
1836  * @s2: string to compare with @s1.
1837  * 
1838  * Compare two strings, ignoring the case of ASCII characters.
1839  *
1840  * Unlike the BSD strcasecmp() function, this only recognizes standard
1841  * ASCII letters and ignores the locale, treating all non-ASCII
1842  * bytes as if they are not letters.
1843  *
1844  * This function should be used only on strings that are known to be
1845  * in encodings where the bytes corresponding to ASCII letters always
1846  * represent themselves. This includes UTF-8 and the ISO-8859-*
1847  * charsets, but not for instance double-byte encodings like the
1848  * Windows Codepage 932, where the trailing bytes of double-byte
1849  * characters include all ASCII letters. If you compare two CP932
1850  * strings using this function, you will get false matches.
1851  *
1852  * Return value: 0 if the strings match, a negative value if @s1 &lt; @s2, 
1853  *   or a positive value if @s1 &gt; @s2.
1854  **/
1855 gint
1856 g_ascii_strcasecmp (const gchar *s1,
1857                     const gchar *s2)
1858 {
1859   gint c1, c2;
1860
1861   g_return_val_if_fail (s1 != NULL, 0);
1862   g_return_val_if_fail (s2 != NULL, 0);
1863
1864   while (*s1 && *s2)
1865     {
1866       c1 = (gint)(guchar) TOLOWER (*s1);
1867       c2 = (gint)(guchar) TOLOWER (*s2);
1868       if (c1 != c2)
1869         return (c1 - c2);
1870       s1++; s2++;
1871     }
1872
1873   return (((gint)(guchar) *s1) - ((gint)(guchar) *s2));
1874 }
1875
1876 /**
1877  * g_ascii_strncasecmp:
1878  * @s1: string to compare with @s2.
1879  * @s2: string to compare with @s1.
1880  * @n:  number of characters to compare.
1881  * 
1882  * Compare @s1 and @s2, ignoring the case of ASCII characters and any
1883  * characters after the first @n in each string.
1884  *
1885  * Unlike the BSD strcasecmp() function, this only recognizes standard
1886  * ASCII letters and ignores the locale, treating all non-ASCII
1887  * characters as if they are not letters.
1888  * 
1889  * The same warning as in g_ascii_strcasecmp() applies: Use this
1890  * function only on strings known to be in encodings where bytes
1891  * corresponding to ASCII letters always represent themselves.
1892  *
1893  * Return value: 0 if the strings match, a negative value if @s1 &lt; @s2, 
1894  *   or a positive value if @s1 &gt; @s2.
1895  **/
1896 gint
1897 g_ascii_strncasecmp (const gchar *s1,
1898                      const gchar *s2,
1899                      gsize n)
1900 {
1901   gint c1, c2;
1902
1903   g_return_val_if_fail (s1 != NULL, 0);
1904   g_return_val_if_fail (s2 != NULL, 0);
1905
1906   while (n && *s1 && *s2)
1907     {
1908       n -= 1;
1909       c1 = (gint)(guchar) TOLOWER (*s1);
1910       c2 = (gint)(guchar) TOLOWER (*s2);
1911       if (c1 != c2)
1912         return (c1 - c2);
1913       s1++; s2++;
1914     }
1915
1916   if (n)
1917     return (((gint) (guchar) *s1) - ((gint) (guchar) *s2));
1918   else
1919     return 0;
1920 }
1921
1922 /**
1923  * g_strcasecmp:
1924  * @s1: a string.
1925  * @s2: a string to compare with @s1.
1926  * 
1927  * A case-insensitive string comparison, corresponding to the standard
1928  * strcasecmp() function on platforms which support it.
1929  *
1930  * Return value: 0 if the strings match, a negative value if @s1 &lt; @s2, 
1931  *   or a positive value if @s1 &gt; @s2.
1932  *
1933  * Deprecated:2.2: See g_strncasecmp() for a discussion of why this function 
1934  *   is deprecated and how to replace it.
1935  **/
1936 gint
1937 g_strcasecmp (const gchar *s1,
1938               const gchar *s2)
1939 {
1940 #ifdef HAVE_STRCASECMP
1941   g_return_val_if_fail (s1 != NULL, 0);
1942   g_return_val_if_fail (s2 != NULL, 0);
1943
1944   return strcasecmp (s1, s2);
1945 #else
1946   gint c1, c2;
1947
1948   g_return_val_if_fail (s1 != NULL, 0);
1949   g_return_val_if_fail (s2 != NULL, 0);
1950
1951   while (*s1 && *s2)
1952     {
1953       /* According to A. Cox, some platforms have islower's that
1954        * don't work right on non-uppercase
1955        */
1956       c1 = isupper ((guchar)*s1) ? tolower ((guchar)*s1) : *s1;
1957       c2 = isupper ((guchar)*s2) ? tolower ((guchar)*s2) : *s2;
1958       if (c1 != c2)
1959         return (c1 - c2);
1960       s1++; s2++;
1961     }
1962
1963   return (((gint)(guchar) *s1) - ((gint)(guchar) *s2));
1964 #endif
1965 }
1966
1967 /**
1968  * g_strncasecmp:
1969  * @s1: a string.
1970  * @s2: a string to compare with @s1.
1971  * @n: the maximum number of characters to compare.
1972  * 
1973  * A case-insensitive string comparison, corresponding to the standard
1974  * strncasecmp() function on platforms which support it.
1975  * It is similar to g_strcasecmp() except it only compares the first @n 
1976  * characters of the strings.
1977  * 
1978  * Return value: 0 if the strings match, a negative value if @s1 &lt; @s2, 
1979  *   or a positive value if @s1 &gt; @s2.
1980  *
1981  * Deprecated:2.2: The problem with g_strncasecmp() is that it does the 
1982  * comparison by calling toupper()/tolower(). These functions are
1983  * locale-specific and operate on single bytes. However, it is impossible
1984  * to handle things correctly from an I18N standpoint by operating on
1985  * bytes, since characters may be multibyte. Thus g_strncasecmp() is
1986  * broken if your string is guaranteed to be ASCII, since it's
1987  * locale-sensitive, and it's broken if your string is localized, since
1988  * it doesn't work on many encodings at all, including UTF-8, EUC-JP,
1989  * etc.
1990  *
1991  * There are therefore two replacement functions: g_ascii_strncasecmp(),
1992  * which only works on ASCII and is not locale-sensitive, and
1993  * g_utf8_casefold(), which is good for case-insensitive sorting of UTF-8.
1994  **/
1995 gint
1996 g_strncasecmp (const gchar *s1,
1997                const gchar *s2,
1998                guint n)     
1999 {
2000 #ifdef HAVE_STRNCASECMP
2001   return strncasecmp (s1, s2, n);
2002 #else
2003   gint c1, c2;
2004
2005   g_return_val_if_fail (s1 != NULL, 0);
2006   g_return_val_if_fail (s2 != NULL, 0);
2007
2008   while (n && *s1 && *s2)
2009     {
2010       n -= 1;
2011       /* According to A. Cox, some platforms have islower's that
2012        * don't work right on non-uppercase
2013        */
2014       c1 = isupper ((guchar)*s1) ? tolower ((guchar)*s1) : *s1;
2015       c2 = isupper ((guchar)*s2) ? tolower ((guchar)*s2) : *s2;
2016       if (c1 != c2)
2017         return (c1 - c2);
2018       s1++; s2++;
2019     }
2020
2021   if (n)
2022     return (((gint) (guchar) *s1) - ((gint) (guchar) *s2));
2023   else
2024     return 0;
2025 #endif
2026 }
2027
2028 gchar*
2029 g_strdelimit (gchar       *string,
2030               const gchar *delimiters,
2031               gchar        new_delim)
2032 {
2033   register gchar *c;
2034
2035   g_return_val_if_fail (string != NULL, NULL);
2036
2037   if (!delimiters)
2038     delimiters = G_STR_DELIMITERS;
2039
2040   for (c = string; *c; c++)
2041     {
2042       if (strchr (delimiters, *c))
2043         *c = new_delim;
2044     }
2045
2046   return string;
2047 }
2048
2049 gchar*
2050 g_strcanon (gchar       *string,
2051             const gchar *valid_chars,
2052             gchar        substitutor)
2053 {
2054   register gchar *c;
2055
2056   g_return_val_if_fail (string != NULL, NULL);
2057   g_return_val_if_fail (valid_chars != NULL, NULL);
2058
2059   for (c = string; *c; c++)
2060     {
2061       if (!strchr (valid_chars, *c))
2062         *c = substitutor;
2063     }
2064
2065   return string;
2066 }
2067
2068 gchar*
2069 g_strcompress (const gchar *source)
2070 {
2071   const gchar *p = source, *octal;
2072   gchar *dest = g_malloc (strlen (source) + 1);
2073   gchar *q = dest;
2074   
2075   while (*p)
2076     {
2077       if (*p == '\\')
2078         {
2079           p++;
2080           switch (*p)
2081             {
2082             case '\0':
2083               g_warning ("g_strcompress: trailing \\");
2084               goto out;
2085             case '0':  case '1':  case '2':  case '3':  case '4':
2086             case '5':  case '6':  case '7':
2087               *q = 0;
2088               octal = p;
2089               while ((p < octal + 3) && (*p >= '0') && (*p <= '7'))
2090                 {
2091                   *q = (*q * 8) + (*p - '0');
2092                   p++;
2093                 }
2094               q++;
2095               p--;
2096               break;
2097             case 'b':
2098               *q++ = '\b';
2099               break;
2100             case 'f':
2101               *q++ = '\f';
2102               break;
2103             case 'n':
2104               *q++ = '\n';
2105               break;
2106             case 'r':
2107               *q++ = '\r';
2108               break;
2109             case 't':
2110               *q++ = '\t';
2111               break;
2112             default:            /* Also handles \" and \\ */
2113               *q++ = *p;
2114               break;
2115             }
2116         }
2117       else
2118         *q++ = *p;
2119       p++;
2120     }
2121 out:
2122   *q = 0;
2123   
2124   return dest;
2125 }
2126
2127 gchar *
2128 g_strescape (const gchar *source,
2129              const gchar *exceptions)
2130 {
2131   const guchar *p;
2132   gchar *dest;
2133   gchar *q;
2134   guchar excmap[256];
2135   
2136   g_return_val_if_fail (source != NULL, NULL);
2137
2138   p = (guchar *) source;
2139   /* Each source byte needs maximally four destination chars (\777) */
2140   q = dest = g_malloc (strlen (source) * 4 + 1);
2141
2142   memset (excmap, 0, 256);
2143   if (exceptions)
2144     {
2145       guchar *e = (guchar *) exceptions;
2146
2147       while (*e)
2148         {
2149           excmap[*e] = 1;
2150           e++;
2151         }
2152     }
2153
2154   while (*p)
2155     {
2156       if (excmap[*p])
2157         *q++ = *p;
2158       else
2159         {
2160           switch (*p)
2161             {
2162             case '\b':
2163               *q++ = '\\';
2164               *q++ = 'b';
2165               break;
2166             case '\f':
2167               *q++ = '\\';
2168               *q++ = 'f';
2169               break;
2170             case '\n':
2171               *q++ = '\\';
2172               *q++ = 'n';
2173               break;
2174             case '\r':
2175               *q++ = '\\';
2176               *q++ = 'r';
2177               break;
2178             case '\t':
2179               *q++ = '\\';
2180               *q++ = 't';
2181               break;
2182             case '\\':
2183               *q++ = '\\';
2184               *q++ = '\\';
2185               break;
2186             case '"':
2187               *q++ = '\\';
2188               *q++ = '"';
2189               break;
2190             default:
2191               if ((*p < ' ') || (*p >= 0177))
2192                 {
2193                   *q++ = '\\';
2194                   *q++ = '0' + (((*p) >> 6) & 07);
2195                   *q++ = '0' + (((*p) >> 3) & 07);
2196                   *q++ = '0' + ((*p) & 07);
2197                 }
2198               else
2199                 *q++ = *p;
2200               break;
2201             }
2202         }
2203       p++;
2204     }
2205   *q = 0;
2206   return dest;
2207 }
2208
2209 gchar*
2210 g_strchug (gchar *string)
2211 {
2212   guchar *start;
2213
2214   g_return_val_if_fail (string != NULL, NULL);
2215
2216   for (start = (guchar*) string; *start && g_ascii_isspace (*start); start++)
2217     ;
2218
2219   g_memmove (string, start, strlen ((gchar *) start) + 1);
2220
2221   return string;
2222 }
2223
2224 gchar*
2225 g_strchomp (gchar *string)
2226 {
2227   gsize len;
2228
2229   g_return_val_if_fail (string != NULL, NULL);
2230
2231   len = strlen (string);
2232   while (len--)
2233     {
2234       if (g_ascii_isspace ((guchar) string[len]))
2235         string[len] = '\0';
2236       else
2237         break;
2238     }
2239
2240   return string;
2241 }
2242
2243 /**
2244  * g_strsplit:
2245  * @string: a string to split.
2246  * @delimiter: a string which specifies the places at which to split the string.
2247  *     The delimiter is not included in any of the resulting strings, unless
2248  *     @max_tokens is reached.
2249  * @max_tokens: the maximum number of pieces to split @string into. If this is
2250  *              less than 1, the string is split completely.
2251  * 
2252  * Splits a string into a maximum of @max_tokens pieces, using the given
2253  * @delimiter. If @max_tokens is reached, the remainder of @string is appended
2254  * to the last token. 
2255  *
2256  * As a special case, the result of splitting the empty string "" is an empty
2257  * vector, not a vector containing a single string. The reason for this
2258  * special case is that being able to represent a empty vector is typically
2259  * more useful than consistent handling of empty elements. If you do need
2260  * to represent empty elements, you'll need to check for the empty string
2261  * before calling g_strsplit().
2262  * 
2263  * Return value: a newly-allocated %NULL-terminated array of strings. Use 
2264  *    g_strfreev() to free it.
2265  **/
2266 gchar**
2267 g_strsplit (const gchar *string,
2268             const gchar *delimiter,
2269             gint         max_tokens)
2270 {
2271   GSList *string_list = NULL, *slist;
2272   gchar **str_array, *s;
2273   guint n = 0;
2274   const gchar *remainder;
2275
2276   g_return_val_if_fail (string != NULL, NULL);
2277   g_return_val_if_fail (delimiter != NULL, NULL);
2278   g_return_val_if_fail (delimiter[0] != '\0', NULL);
2279
2280   if (max_tokens < 1)
2281     max_tokens = G_MAXINT;
2282
2283   remainder = string;
2284   s = strstr (remainder, delimiter);
2285   if (s)
2286     {
2287       gsize delimiter_len = strlen (delimiter);   
2288
2289       while (--max_tokens && s)
2290         {
2291           gsize len;     
2292
2293           len = s - remainder;
2294           string_list = g_slist_prepend (string_list,
2295                                          g_strndup (remainder, len));
2296           n++;
2297           remainder = s + delimiter_len;
2298           s = strstr (remainder, delimiter);
2299         }
2300     }
2301   if (*string)
2302     {
2303       n++;
2304       string_list = g_slist_prepend (string_list, g_strdup (remainder));
2305     }
2306
2307   str_array = g_new (gchar*, n + 1);
2308
2309   str_array[n--] = NULL;
2310   for (slist = string_list; slist; slist = slist->next)
2311     str_array[n--] = slist->data;
2312
2313   g_slist_free (string_list);
2314
2315   return str_array;
2316 }
2317
2318 /**
2319  * g_strsplit_set:
2320  * @string: The string to be tokenized
2321  * @delimiters: A nul-terminated string containing bytes that are used
2322  *              to split the string.
2323  * @max_tokens: The maximum number of tokens to split @string into. 
2324  *              If this is less than 1, the string is split completely
2325  * 
2326  * Splits @string into a number of tokens not containing any of the characters
2327  * in @delimiter. A token is the (possibly empty) longest string that does not
2328  * contain any of the characters in @delimiters. If @max_tokens is reached, the
2329  * remainder is appended to the last token.
2330  *
2331  * For example the result of g_strsplit_set ("abc:def/ghi", ":/", -1) is a
2332  * %NULL-terminated vector containing the three strings "abc", "def", 
2333  * and "ghi".
2334  *
2335  * The result if g_strsplit_set (":def/ghi:", ":/", -1) is a %NULL-terminated
2336  * vector containing the four strings "", "def", "ghi", and "".
2337  * 
2338  * As a special case, the result of splitting the empty string "" is an empty
2339  * vector, not a vector containing a single string. The reason for this
2340  * special case is that being able to represent a empty vector is typically
2341  * more useful than consistent handling of empty elements. If you do need
2342  * to represent empty elements, you'll need to check for the empty string
2343  * before calling g_strsplit_set().
2344  *
2345  * Note that this function works on bytes not characters, so it can't be used 
2346  * to delimit UTF-8 strings for anything but ASCII characters.
2347  * 
2348  * Return value: a newly-allocated %NULL-terminated array of strings. Use 
2349  *    g_strfreev() to free it.
2350  * 
2351  * Since: 2.4
2352  **/
2353 gchar **
2354 g_strsplit_set (const gchar *string,
2355                 const gchar *delimiters,
2356                 gint         max_tokens)
2357 {
2358   gboolean delim_table[256];
2359   GSList *tokens, *list;
2360   gint n_tokens;
2361   const gchar *s;
2362   const gchar *current;
2363   gchar *token;
2364   gchar **result;
2365   
2366   g_return_val_if_fail (string != NULL, NULL);
2367   g_return_val_if_fail (delimiters != NULL, NULL);
2368
2369   if (max_tokens < 1)
2370     max_tokens = G_MAXINT;
2371
2372   if (*string == '\0')
2373     {
2374       result = g_new (char *, 1);
2375       result[0] = NULL;
2376       return result;
2377     }
2378   
2379   memset (delim_table, FALSE, sizeof (delim_table));
2380   for (s = delimiters; *s != '\0'; ++s)
2381     delim_table[*(guchar *)s] = TRUE;
2382
2383   tokens = NULL;
2384   n_tokens = 0;
2385
2386   s = current = string;
2387   while (*s != '\0')
2388     {
2389       if (delim_table[*(guchar *)s] && n_tokens + 1 < max_tokens)
2390         {
2391           gchar *token;
2392
2393           token = g_strndup (current, s - current);
2394           tokens = g_slist_prepend (tokens, token);
2395           ++n_tokens;
2396
2397           current = s + 1;
2398         }
2399       
2400       ++s;
2401     }
2402
2403   token = g_strndup (current, s - current);
2404   tokens = g_slist_prepend (tokens, token);
2405   ++n_tokens;
2406
2407   result = g_new (gchar *, n_tokens + 1);
2408
2409   result[n_tokens] = NULL;
2410   for (list = tokens; list != NULL; list = list->next)
2411     result[--n_tokens] = list->data;
2412
2413   g_slist_free (tokens);
2414   
2415   return result;
2416 }
2417
2418 /**
2419  * g_strfreev:
2420  * @str_array: a %NULL-terminated array of strings to free.
2421
2422  * Frees a %NULL-terminated array of strings, and the array itself.
2423  * If called on a %NULL value, g_strfreev() simply returns. 
2424  **/
2425 void
2426 g_strfreev (gchar **str_array)
2427 {
2428   if (str_array)
2429     {
2430       int i;
2431
2432       for (i = 0; str_array[i] != NULL; i++)
2433         g_free (str_array[i]);
2434
2435       g_free (str_array);
2436     }
2437 }
2438
2439 /**
2440  * g_strdupv:
2441  * @str_array: %NULL-terminated array of strings.
2442  * 
2443  * Copies %NULL-terminated array of strings. The copy is a deep copy;
2444  * the new array should be freed by first freeing each string, then
2445  * the array itself. g_strfreev() does this for you. If called
2446  * on a %NULL value, g_strdupv() simply returns %NULL.
2447  * 
2448  * Return value: a new %NULL-terminated array of strings.
2449  **/
2450 gchar**
2451 g_strdupv (gchar **str_array)
2452 {
2453   if (str_array)
2454     {
2455       gint i;
2456       gchar **retval;
2457
2458       i = 0;
2459       while (str_array[i])
2460         ++i;
2461           
2462       retval = g_new (gchar*, i + 1);
2463
2464       i = 0;
2465       while (str_array[i])
2466         {
2467           retval[i] = g_strdup (str_array[i]);
2468           ++i;
2469         }
2470       retval[i] = NULL;
2471
2472       return retval;
2473     }
2474   else
2475     return NULL;
2476 }
2477
2478 gchar*
2479 g_strjoinv (const gchar  *separator,
2480             gchar       **str_array)
2481 {
2482   gchar *string;
2483   gchar *ptr;
2484
2485   g_return_val_if_fail (str_array != NULL, NULL);
2486
2487   if (separator == NULL)
2488     separator = "";
2489
2490   if (*str_array)
2491     {
2492       gint i;
2493       gsize len;
2494       gsize separator_len;     
2495
2496       separator_len = strlen (separator);
2497       /* First part, getting length */
2498       len = 1 + strlen (str_array[0]);
2499       for (i = 1; str_array[i] != NULL; i++)
2500         len += strlen (str_array[i]);
2501       len += separator_len * (i - 1);
2502
2503       /* Second part, building string */
2504       string = g_new (gchar, len);
2505       ptr = g_stpcpy (string, *str_array);
2506       for (i = 1; str_array[i] != NULL; i++)
2507         {
2508           ptr = g_stpcpy (ptr, separator);
2509           ptr = g_stpcpy (ptr, str_array[i]);
2510         }
2511       }
2512   else
2513     string = g_strdup ("");
2514
2515   return string;
2516 }
2517
2518 gchar*
2519 g_strjoin (const gchar  *separator,
2520            ...)
2521 {
2522   gchar *string, *s;
2523   va_list args;
2524   gsize len;               
2525   gsize separator_len;     
2526   gchar *ptr;
2527
2528   if (separator == NULL)
2529     separator = "";
2530
2531   separator_len = strlen (separator);
2532
2533   va_start (args, separator);
2534
2535   s = va_arg (args, gchar*);
2536
2537   if (s)
2538     {
2539       /* First part, getting length */
2540       len = 1 + strlen (s);
2541
2542       s = va_arg (args, gchar*);
2543       while (s)
2544         {
2545           len += separator_len + strlen (s);
2546           s = va_arg (args, gchar*);
2547         }
2548       va_end (args);
2549
2550       /* Second part, building string */
2551       string = g_new (gchar, len);
2552
2553       va_start (args, separator);
2554
2555       s = va_arg (args, gchar*);
2556       ptr = g_stpcpy (string, s);
2557
2558       s = va_arg (args, gchar*);
2559       while (s)
2560         {
2561           ptr = g_stpcpy (ptr, separator);
2562           ptr = g_stpcpy (ptr, s);
2563           s = va_arg (args, gchar*);
2564         }
2565     }
2566   else
2567     string = g_strdup ("");
2568
2569   va_end (args);
2570
2571   return string;
2572 }
2573
2574
2575 /**
2576  * g_strstr_len:
2577  * @haystack: a string.
2578  * @haystack_len: the maximum length of @haystack.
2579  * @needle: the string to search for.
2580  *
2581  * Searches the string @haystack for the first occurrence
2582  * of the string @needle, limiting the length of the search
2583  * to @haystack_len. 
2584  *
2585  * Return value: a pointer to the found occurrence, or
2586  *    %NULL if not found.
2587  **/
2588 gchar *
2589 g_strstr_len (const gchar *haystack,
2590               gssize       haystack_len,
2591               const gchar *needle)
2592 {
2593   g_return_val_if_fail (haystack != NULL, NULL);
2594   g_return_val_if_fail (needle != NULL, NULL);
2595   
2596   if (haystack_len < 0)
2597     return strstr (haystack, needle);
2598   else
2599     {
2600       const gchar *p = haystack;
2601       gsize needle_len = strlen (needle);
2602       const gchar *end;
2603       gsize i;
2604
2605       if (needle_len == 0)
2606         return (gchar *)haystack;
2607
2608       if (haystack_len < needle_len)
2609         return NULL;
2610       
2611       end = haystack + haystack_len - needle_len;
2612       
2613       while (*p && p <= end)
2614         {
2615           for (i = 0; i < needle_len; i++)
2616             if (p[i] != needle[i])
2617               goto next;
2618           
2619           return (gchar *)p;
2620           
2621         next:
2622           p++;
2623         }
2624       
2625       return NULL;
2626     }
2627 }
2628
2629 /**
2630  * g_strrstr:
2631  * @haystack: a nul-terminated string.
2632  * @needle: the nul-terminated string to search for.
2633  *
2634  * Searches the string @haystack for the last occurrence
2635  * of the string @needle.
2636  *
2637  * Return value: a pointer to the found occurrence, or
2638  *    %NULL if not found.
2639  **/
2640 gchar *
2641 g_strrstr (const gchar *haystack,
2642            const gchar *needle)
2643 {
2644   gsize i;
2645   gsize needle_len;
2646   gsize haystack_len;
2647   const gchar *p;
2648       
2649   g_return_val_if_fail (haystack != NULL, NULL);
2650   g_return_val_if_fail (needle != NULL, NULL);
2651
2652   needle_len = strlen (needle);
2653   haystack_len = strlen (haystack);
2654
2655   if (needle_len == 0)
2656     return (gchar *)haystack;
2657
2658   if (haystack_len < needle_len)
2659     return NULL;
2660   
2661   p = haystack + haystack_len - needle_len;
2662
2663   while (p >= haystack)
2664     {
2665       for (i = 0; i < needle_len; i++)
2666         if (p[i] != needle[i])
2667           goto next;
2668       
2669       return (gchar *)p;
2670       
2671     next:
2672       p--;
2673     }
2674   
2675   return NULL;
2676 }
2677
2678 /**
2679  * g_strrstr_len:
2680  * @haystack: a nul-terminated string.
2681  * @haystack_len: the maximum length of @haystack.
2682  * @needle: the nul-terminated string to search for.
2683  *
2684  * Searches the string @haystack for the last occurrence
2685  * of the string @needle, limiting the length of the search
2686  * to @haystack_len. 
2687  *
2688  * Return value: a pointer to the found occurrence, or
2689  *    %NULL if not found.
2690  **/
2691 gchar *
2692 g_strrstr_len (const gchar *haystack,
2693                gssize        haystack_len,
2694                const gchar *needle)
2695 {
2696   g_return_val_if_fail (haystack != NULL, NULL);
2697   g_return_val_if_fail (needle != NULL, NULL);
2698   
2699   if (haystack_len < 0)
2700     return g_strrstr (haystack, needle);
2701   else
2702     {
2703       gsize needle_len = strlen (needle);
2704       const gchar *haystack_max = haystack + haystack_len;
2705       const gchar *p = haystack;
2706       gsize i;
2707
2708       while (p < haystack_max && *p)
2709         p++;
2710
2711       if (p < haystack + needle_len)
2712         return NULL;
2713         
2714       p -= needle_len;
2715
2716       while (p >= haystack)
2717         {
2718           for (i = 0; i < needle_len; i++)
2719             if (p[i] != needle[i])
2720               goto next;
2721           
2722           return (gchar *)p;
2723           
2724         next:
2725           p--;
2726         }
2727
2728       return NULL;
2729     }
2730 }
2731
2732
2733 /**
2734  * g_str_has_suffix:
2735  * @str: a nul-terminated string.
2736  * @suffix: the nul-terminated suffix to look for.
2737  *
2738  * Looks whether the string @str ends with @suffix.
2739  *
2740  * Return value: %TRUE if @str end with @suffix, %FALSE otherwise.
2741  *
2742  * Since: 2.2
2743  **/
2744 gboolean
2745 g_str_has_suffix (const gchar  *str,
2746                   const gchar  *suffix)
2747 {
2748   int str_len;
2749   int suffix_len;
2750   
2751   g_return_val_if_fail (str != NULL, FALSE);
2752   g_return_val_if_fail (suffix != NULL, FALSE);
2753
2754   str_len = strlen (str);
2755   suffix_len = strlen (suffix);
2756
2757   if (str_len < suffix_len)
2758     return FALSE;
2759
2760   return strcmp (str + str_len - suffix_len, suffix) == 0;
2761 }
2762
2763 /**
2764  * g_str_has_prefix:
2765  * @str: a nul-terminated string.
2766  * @prefix: the nul-terminated prefix to look for.
2767  *
2768  * Looks whether the string @str begins with @prefix.
2769  *
2770  * Return value: %TRUE if @str begins with @prefix, %FALSE otherwise.
2771  *
2772  * Since: 2.2
2773  **/
2774 gboolean
2775 g_str_has_prefix (const gchar  *str,
2776                   const gchar  *prefix)
2777 {
2778   int str_len;
2779   int prefix_len;
2780   
2781   g_return_val_if_fail (str != NULL, FALSE);
2782   g_return_val_if_fail (prefix != NULL, FALSE);
2783
2784   str_len = strlen (str);
2785   prefix_len = strlen (prefix);
2786
2787   if (str_len < prefix_len)
2788     return FALSE;
2789   
2790   return strncmp (str, prefix, prefix_len) == 0;
2791 }
2792
2793
2794 /**
2795  * g_strip_context:
2796  * @msgid: a string
2797  * @msgval: another string
2798  * 
2799  * An auxiliary function for gettext() support (see Q_()).
2800  * 
2801  * Return value: @msgval, unless @msgval is identical to @msgid and contains
2802  *   a '|' character, in which case a pointer to the substring of msgid after
2803  *   the first '|' character is returned. 
2804  *
2805  * Since: 2.4
2806  **/
2807 G_CONST_RETURN gchar *
2808 g_strip_context  (const gchar *msgid, 
2809                   const gchar *msgval)
2810 {
2811   if (msgval == msgid)
2812     {
2813       const char *c = strchr (msgid, '|');
2814       if (c != NULL)
2815         return c + 1;
2816     }
2817   
2818   return msgval;
2819 }
2820
2821
2822 /**
2823  * g_strv_length:
2824  * @str_array: a %NULL-terminated array of strings.
2825  * 
2826  * Returns the length of the given %NULL-terminated 
2827  * string array @str_array.
2828  * 
2829  * Return value: length of @str_array.
2830  *
2831  * Since: 2.6
2832  **/
2833 guint
2834 g_strv_length (gchar **str_array)
2835 {
2836   guint i = 0;
2837
2838   g_return_val_if_fail (str_array != NULL, 0);
2839
2840   while (str_array[i])
2841     ++i;
2842
2843   return i;
2844 }
2845
2846 #define __G_STRFUNCS_C__
2847 #include "galiasdef.c"