Updated Catalan translation.
[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   if (base == 1 || base > 36)
654     {
655       errno = EINVAL;
656       return 0;
657     }
658   
659   save = s = nptr;
660   
661   /* Skip white space.  */
662   while (ISSPACE (*s))
663     ++s;
664
665   if (G_UNLIKELY (!*s))
666     goto noconv;
667   
668   /* Check for a sign.  */
669   *negative = FALSE;
670   if (*s == '-')
671     {
672       *negative = TRUE;
673       ++s;
674     }
675   else if (*s == '+')
676     ++s;
677   
678   /* Recognize number prefix and if BASE is zero, figure it out ourselves.  */
679   if (*s == '0')
680     {
681       if ((base == 0 || base == 16) && TOUPPER (s[1]) == 'X')
682         {
683           s += 2;
684           base = 16;
685         }
686       else if (base == 0)
687         base = 8;
688     }
689   else if (base == 0)
690     base = 10;
691   
692   /* Save the pointer so we can check later if anything happened.  */
693   save = s;
694   cutoff = G_MAXUINT64 / base;
695   cutlim = G_MAXUINT64 % base;
696   
697   overflow = FALSE;
698   ui64 = 0;
699   c = *s;
700   for (; c; c = *++s)
701     {
702       if (c >= '0' && c <= '9')
703         c -= '0';
704       else if (ISALPHA (c))
705         c = TOUPPER (c) - 'A' + 10;
706       else
707         break;
708       if (c >= base)
709         break;
710       /* Check for overflow.  */
711       if (ui64 > cutoff || (ui64 == cutoff && c > cutlim))
712         overflow = TRUE;
713       else
714         {
715           ui64 *= base;
716           ui64 += c;
717         }
718     }
719   
720   /* Check if anything actually happened.  */
721   if (s == save)
722     goto noconv;
723   
724   /* Store in ENDPTR the address of one character
725      past the last character we converted.  */
726   if (endptr)
727     *endptr = (gchar*) s;
728   
729   if (G_UNLIKELY (overflow))
730     {
731       errno = ERANGE;
732       return G_MAXUINT64;
733     }
734
735   return ui64;
736   
737  noconv:
738   /* We must handle a special case here: the base is 0 or 16 and the
739      first two characters are '0' and 'x', but the rest are no
740      hexadecimal digits.  This is no error case.  We return 0 and
741      ENDPTR points to the `x`.  */
742   if (endptr)
743     {
744       if (save - nptr >= 2 && TOUPPER (save[-1]) == 'X'
745           && save[-2] == '0')
746         *endptr = (gchar*) &save[-1];
747       else
748         /*  There was no number to convert.  */
749         *endptr = (gchar*) nptr;
750     }
751   return 0;
752 }
753
754 /**
755  * g_ascii_strtoull:
756  * @nptr:    the string to convert to a numeric value.
757  * @endptr:  if non-%NULL, it returns the character after
758  *           the last character used in the conversion.
759  * @base:    to be used for the conversion, 2..36 or 0
760  *
761  * Converts a string to a #guint64 value.
762  * This function behaves like the standard strtoull() function
763  * does in the C locale. It does this without actually
764  * changing the current locale, since that would not be
765  * thread-safe.
766  *
767  * This function is typically used when reading configuration
768  * files or other non-user input that should be locale independent.
769  * To handle input from the user you should normally use the
770  * locale-sensitive system strtoull() function.
771  *
772  * If the correct value would cause overflow, %G_MAXUINT64
773  * is returned, and %ERANGE is stored in %errno.  If the base is
774  * outside the valid range, zero is returned, and %EINVAL is stored
775  * in %errno.  If the string conversion fails, zero is returned, and
776  * @endptr returns @nptr (if @endptr is non-%NULL).
777  *
778  * Return value: the #guint64 value or zero on error.
779  *
780  * Since: 2.2
781  **/
782 guint64
783 g_ascii_strtoull (const gchar *nptr,
784                   gchar      **endptr,
785                   guint        base)
786 {
787   gboolean negative;
788   guint64 result;
789
790   result = g_parse_long_long (nptr, endptr, base, &negative);
791
792   /* Return the result of the appropriate sign.  */
793   return negative ? -result : result;
794 }
795
796 /**
797  * g_ascii_strtoll:
798  * @nptr:    the string to convert to a numeric value.
799  * @endptr:  if non-%NULL, it returns the character after
800  *           the last character used in the conversion.
801  * @base:    to be used for the conversion, 2..36 or 0
802  *
803  * Converts a string to a #gint64 value.
804  * This function behaves like the standard strtoll() function
805  * does in the C locale. It does this without actually
806  * changing the current locale, since that would not be
807  * thread-safe.
808  *
809  * This function is typically used when reading configuration
810  * files or other non-user input that should be locale independent.
811  * To handle input from the user you should normally use the
812  * locale-sensitive system strtoll() function.
813  *
814  * If the correct value would cause overflow, %G_MAXINT64 or %G_MININT64
815  * is returned, and %ERANGE is stored in %errno.  If the base is
816  * outside the valid range, zero is returned, and %EINVAL is stored
817  * in %errno.  If the string conversion fails, zero is returned, and
818  * @endptr returns @nptr (if @endptr is non-%NULL).
819  *
820  * Return value: the #gint64 value or zero on error.
821  *
822  * Since: 2.12
823  **/
824 gint64 
825 g_ascii_strtoll (const gchar *nptr,
826                  gchar      **endptr,
827                  guint        base)
828 {
829   gboolean negative;
830   guint64 result;
831
832   result = g_parse_long_long (nptr, endptr, base, &negative);
833
834   if (negative && result > (guint64) G_MININT64)
835     {
836       errno = ERANGE;
837       return G_MININT64;
838     }
839   else if (!negative && result > (guint64) G_MAXINT64)
840     {
841       errno = ERANGE;
842       return G_MAXINT64;
843     }
844   else if (negative)
845     return - (gint64) result;
846   else
847     return (gint64) result;
848 }
849
850 G_CONST_RETURN gchar*
851 g_strerror (gint errnum)
852 {
853   static GStaticPrivate msg_private = G_STATIC_PRIVATE_INIT;
854   char *msg;
855   int saved_errno = errno;
856
857 #ifdef HAVE_STRERROR
858   const char *msg_locale;
859
860   msg_locale = strerror (errnum);
861   if (g_get_charset (NULL))
862     {
863       errno = saved_errno;
864       return msg_locale;
865     }
866   else
867     {
868       gchar *msg_utf8 = g_locale_to_utf8 (msg_locale, -1, NULL, NULL, NULL);
869       if (msg_utf8)
870         {
871           /* Stick in the quark table so that we can return a static result
872            */
873           GQuark msg_quark = g_quark_from_string (msg_utf8);
874           g_free (msg_utf8);
875           
876           msg_utf8 = (gchar *) g_quark_to_string (msg_quark);
877           errno = saved_errno;
878           return msg_utf8;
879         }
880     }
881 #elif NO_SYS_ERRLIST
882   switch (errnum)
883     {
884 #ifdef E2BIG
885     case E2BIG: return "argument list too long";
886 #endif
887 #ifdef EACCES
888     case EACCES: return "permission denied";
889 #endif
890 #ifdef EADDRINUSE
891     case EADDRINUSE: return "address already in use";
892 #endif
893 #ifdef EADDRNOTAVAIL
894     case EADDRNOTAVAIL: return "can't assign requested address";
895 #endif
896 #ifdef EADV
897     case EADV: return "advertise error";
898 #endif
899 #ifdef EAFNOSUPPORT
900     case EAFNOSUPPORT: return "address family not supported by protocol family";
901 #endif
902 #ifdef EAGAIN
903     case EAGAIN: return "try again";
904 #endif
905 #ifdef EALIGN
906     case EALIGN: return "EALIGN";
907 #endif
908 #ifdef EALREADY
909     case EALREADY: return "operation already in progress";
910 #endif
911 #ifdef EBADE
912     case EBADE: return "bad exchange descriptor";
913 #endif
914 #ifdef EBADF
915     case EBADF: return "bad file number";
916 #endif
917 #ifdef EBADFD
918     case EBADFD: return "file descriptor in bad state";
919 #endif
920 #ifdef EBADMSG
921     case EBADMSG: return "not a data message";
922 #endif
923 #ifdef EBADR
924     case EBADR: return "bad request descriptor";
925 #endif
926 #ifdef EBADRPC
927     case EBADRPC: return "RPC structure is bad";
928 #endif
929 #ifdef EBADRQC
930     case EBADRQC: return "bad request code";
931 #endif
932 #ifdef EBADSLT
933     case EBADSLT: return "invalid slot";
934 #endif
935 #ifdef EBFONT
936     case EBFONT: return "bad font file format";
937 #endif
938 #ifdef EBUSY
939     case EBUSY: return "mount device busy";
940 #endif
941 #ifdef ECHILD
942     case ECHILD: return "no children";
943 #endif
944 #ifdef ECHRNG
945     case ECHRNG: return "channel number out of range";
946 #endif
947 #ifdef ECOMM
948     case ECOMM: return "communication error on send";
949 #endif
950 #ifdef ECONNABORTED
951     case ECONNABORTED: return "software caused connection abort";
952 #endif
953 #ifdef ECONNREFUSED
954     case ECONNREFUSED: return "connection refused";
955 #endif
956 #ifdef ECONNRESET
957     case ECONNRESET: return "connection reset by peer";
958 #endif
959 #if defined(EDEADLK) && (!defined(EWOULDBLOCK) || (EDEADLK != EWOULDBLOCK))
960     case EDEADLK: return "resource deadlock avoided";
961 #endif
962 #ifdef EDEADLOCK
963     case EDEADLOCK: return "resource deadlock avoided";
964 #endif
965 #ifdef EDESTADDRREQ
966     case EDESTADDRREQ: return "destination address required";
967 #endif
968 #ifdef EDIRTY
969     case EDIRTY: return "mounting a dirty fs w/o force";
970 #endif
971 #ifdef EDOM
972     case EDOM: return "math argument out of range";
973 #endif
974 #ifdef EDOTDOT
975     case EDOTDOT: return "cross mount point";
976 #endif
977 #ifdef EDQUOT
978     case EDQUOT: return "disk quota exceeded";
979 #endif
980 #ifdef EDUPPKG
981     case EDUPPKG: return "duplicate package name";
982 #endif
983 #ifdef EEXIST
984     case EEXIST: return "file already exists";
985 #endif
986 #ifdef EFAULT
987     case EFAULT: return "bad address in system call argument";
988 #endif
989 #ifdef EFBIG
990     case EFBIG: return "file too large";
991 #endif
992 #ifdef EHOSTDOWN
993     case EHOSTDOWN: return "host is down";
994 #endif
995 #ifdef EHOSTUNREACH
996     case EHOSTUNREACH: return "host is unreachable";
997 #endif
998 #ifdef EIDRM
999     case EIDRM: return "identifier removed";
1000 #endif
1001 #ifdef EINIT
1002     case EINIT: return "initialization error";
1003 #endif
1004 #ifdef EINPROGRESS
1005     case EINPROGRESS: return "operation now in progress";
1006 #endif
1007 #ifdef EINTR
1008     case EINTR: return "interrupted system call";
1009 #endif
1010 #ifdef EINVAL
1011     case EINVAL: return "invalid argument";
1012 #endif
1013 #ifdef EIO
1014     case EIO: return "I/O error";
1015 #endif
1016 #ifdef EISCONN
1017     case EISCONN: return "socket is already connected";
1018 #endif
1019 #ifdef EISDIR
1020     case EISDIR: return "is a directory";
1021 #endif
1022 #ifdef EISNAME
1023     case EISNAM: return "is a name file";
1024 #endif
1025 #ifdef ELBIN
1026     case ELBIN: return "ELBIN";
1027 #endif
1028 #ifdef EL2HLT
1029     case EL2HLT: return "level 2 halted";
1030 #endif
1031 #ifdef EL2NSYNC
1032     case EL2NSYNC: return "level 2 not synchronized";
1033 #endif
1034 #ifdef EL3HLT
1035     case EL3HLT: return "level 3 halted";
1036 #endif
1037 #ifdef EL3RST
1038     case EL3RST: return "level 3 reset";
1039 #endif
1040 #ifdef ELIBACC
1041     case ELIBACC: return "can not access a needed shared library";
1042 #endif
1043 #ifdef ELIBBAD
1044     case ELIBBAD: return "accessing a corrupted shared library";
1045 #endif
1046 #ifdef ELIBEXEC
1047     case ELIBEXEC: return "can not exec a shared library directly";
1048 #endif
1049 #ifdef ELIBMAX
1050     case ELIBMAX: return "attempting to link in more shared libraries than system limit";
1051 #endif
1052 #ifdef ELIBSCN
1053     case ELIBSCN: return ".lib section in a.out corrupted";
1054 #endif
1055 #ifdef ELNRNG
1056     case ELNRNG: return "link number out of range";
1057 #endif
1058 #ifdef ELOOP
1059     case ELOOP: return "too many levels of symbolic links";
1060 #endif
1061 #ifdef EMFILE
1062     case EMFILE: return "too many open files";
1063 #endif
1064 #ifdef EMLINK
1065     case EMLINK: return "too many links";
1066 #endif
1067 #ifdef EMSGSIZE
1068     case EMSGSIZE: return "message too long";
1069 #endif
1070 #ifdef EMULTIHOP
1071     case EMULTIHOP: return "multihop attempted";
1072 #endif
1073 #ifdef ENAMETOOLONG
1074     case ENAMETOOLONG: return "file name too long";
1075 #endif
1076 #ifdef ENAVAIL
1077     case ENAVAIL: return "not available";
1078 #endif
1079 #ifdef ENET
1080     case ENET: return "ENET";
1081 #endif
1082 #ifdef ENETDOWN
1083     case ENETDOWN: return "network is down";
1084 #endif
1085 #ifdef ENETRESET
1086     case ENETRESET: return "network dropped connection on reset";
1087 #endif
1088 #ifdef ENETUNREACH
1089     case ENETUNREACH: return "network is unreachable";
1090 #endif
1091 #ifdef ENFILE
1092     case ENFILE: return "file table overflow";
1093 #endif
1094 #ifdef ENOANO
1095     case ENOANO: return "anode table overflow";
1096 #endif
1097 #if defined(ENOBUFS) && (!defined(ENOSR) || (ENOBUFS != ENOSR))
1098     case ENOBUFS: return "no buffer space available";
1099 #endif
1100 #ifdef ENOCSI
1101     case ENOCSI: return "no CSI structure available";
1102 #endif
1103 #ifdef ENODATA
1104     case ENODATA: return "no data available";
1105 #endif
1106 #ifdef ENODEV
1107     case ENODEV: return "no such device";
1108 #endif
1109 #ifdef ENOENT
1110     case ENOENT: return "no such file or directory";
1111 #endif
1112 #ifdef ENOEXEC
1113     case ENOEXEC: return "exec format error";
1114 #endif
1115 #ifdef ENOLCK
1116     case ENOLCK: return "no locks available";
1117 #endif
1118 #ifdef ENOLINK
1119     case ENOLINK: return "link has be severed";
1120 #endif
1121 #ifdef ENOMEM
1122     case ENOMEM: return "not enough memory";
1123 #endif
1124 #ifdef ENOMSG
1125     case ENOMSG: return "no message of desired type";
1126 #endif
1127 #ifdef ENONET
1128     case ENONET: return "machine is not on the network";
1129 #endif
1130 #ifdef ENOPKG
1131     case ENOPKG: return "package not installed";
1132 #endif
1133 #ifdef ENOPROTOOPT
1134     case ENOPROTOOPT: return "bad proocol option";
1135 #endif
1136 #ifdef ENOSPC
1137     case ENOSPC: return "no space left on device";
1138 #endif
1139 #ifdef ENOSR
1140     case ENOSR: return "out of stream resources";
1141 #endif
1142 #ifdef ENOSTR
1143     case ENOSTR: return "not a stream device";
1144 #endif
1145 #ifdef ENOSYM
1146     case ENOSYM: return "unresolved symbol name";
1147 #endif
1148 #ifdef ENOSYS
1149     case ENOSYS: return "function not implemented";
1150 #endif
1151 #ifdef ENOTBLK
1152     case ENOTBLK: return "block device required";
1153 #endif
1154 #ifdef ENOTCONN
1155     case ENOTCONN: return "socket is not connected";
1156 #endif
1157 #ifdef ENOTDIR
1158     case ENOTDIR: return "not a directory";
1159 #endif
1160 #ifdef ENOTEMPTY
1161     case ENOTEMPTY: return "directory not empty";
1162 #endif
1163 #ifdef ENOTNAM
1164     case ENOTNAM: return "not a name file";
1165 #endif
1166 #ifdef ENOTSOCK
1167     case ENOTSOCK: return "socket operation on non-socket";
1168 #endif
1169 #ifdef ENOTTY
1170     case ENOTTY: return "inappropriate device for ioctl";
1171 #endif
1172 #ifdef ENOTUNIQ
1173     case ENOTUNIQ: return "name not unique on network";
1174 #endif
1175 #ifdef ENXIO
1176     case ENXIO: return "no such device or address";
1177 #endif
1178 #ifdef EOPNOTSUPP
1179     case EOPNOTSUPP: return "operation not supported on socket";
1180 #endif
1181 #ifdef EPERM
1182     case EPERM: return "not owner";
1183 #endif
1184 #ifdef EPFNOSUPPORT
1185     case EPFNOSUPPORT: return "protocol family not supported";
1186 #endif
1187 #ifdef EPIPE
1188     case EPIPE: return "broken pipe";
1189 #endif
1190 #ifdef EPROCLIM
1191     case EPROCLIM: return "too many processes";
1192 #endif
1193 #ifdef EPROCUNAVAIL
1194     case EPROCUNAVAIL: return "bad procedure for program";
1195 #endif
1196 #ifdef EPROGMISMATCH
1197     case EPROGMISMATCH: return "program version wrong";
1198 #endif
1199 #ifdef EPROGUNAVAIL
1200     case EPROGUNAVAIL: return "RPC program not available";
1201 #endif
1202 #ifdef EPROTO
1203     case EPROTO: return "protocol error";
1204 #endif
1205 #ifdef EPROTONOSUPPORT
1206     case EPROTONOSUPPORT: return "protocol not suppored";
1207 #endif
1208 #ifdef EPROTOTYPE
1209     case EPROTOTYPE: return "protocol wrong type for socket";
1210 #endif
1211 #ifdef ERANGE
1212     case ERANGE: return "math result unrepresentable";
1213 #endif
1214 #if defined(EREFUSED) && (!defined(ECONNREFUSED) || (EREFUSED != ECONNREFUSED))
1215     case EREFUSED: return "EREFUSED";
1216 #endif
1217 #ifdef EREMCHG
1218     case EREMCHG: return "remote address changed";
1219 #endif
1220 #ifdef EREMDEV
1221     case EREMDEV: return "remote device";
1222 #endif
1223 #ifdef EREMOTE
1224     case EREMOTE: return "pathname hit remote file system";
1225 #endif
1226 #ifdef EREMOTEIO
1227     case EREMOTEIO: return "remote i/o error";
1228 #endif
1229 #ifdef EREMOTERELEASE
1230     case EREMOTERELEASE: return "EREMOTERELEASE";
1231 #endif
1232 #ifdef EROFS
1233     case EROFS: return "read-only file system";
1234 #endif
1235 #ifdef ERPCMISMATCH
1236     case ERPCMISMATCH: return "RPC version is wrong";
1237 #endif
1238 #ifdef ERREMOTE
1239     case ERREMOTE: return "object is remote";
1240 #endif
1241 #ifdef ESHUTDOWN
1242     case ESHUTDOWN: return "can't send afer socket shutdown";
1243 #endif
1244 #ifdef ESOCKTNOSUPPORT
1245     case ESOCKTNOSUPPORT: return "socket type not supported";
1246 #endif
1247 #ifdef ESPIPE
1248     case ESPIPE: return "invalid seek";
1249 #endif
1250 #ifdef ESRCH
1251     case ESRCH: return "no such process";
1252 #endif
1253 #ifdef ESRMNT
1254     case ESRMNT: return "srmount error";
1255 #endif
1256 #ifdef ESTALE
1257     case ESTALE: return "stale remote file handle";
1258 #endif
1259 #ifdef ESUCCESS
1260     case ESUCCESS: return "Error 0";
1261 #endif
1262 #ifdef ETIME
1263     case ETIME: return "timer expired";
1264 #endif
1265 #ifdef ETIMEDOUT
1266     case ETIMEDOUT: return "connection timed out";
1267 #endif
1268 #ifdef ETOOMANYREFS
1269     case ETOOMANYREFS: return "too many references: can't splice";
1270 #endif
1271 #ifdef ETXTBSY
1272     case ETXTBSY: return "text file or pseudo-device busy";
1273 #endif
1274 #ifdef EUCLEAN
1275     case EUCLEAN: return "structure needs cleaning";
1276 #endif
1277 #ifdef EUNATCH
1278     case EUNATCH: return "protocol driver not attached";
1279 #endif
1280 #ifdef EUSERS
1281     case EUSERS: return "too many users";
1282 #endif
1283 #ifdef EVERSION
1284     case EVERSION: return "version mismatch";
1285 #endif
1286 #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
1287     case EWOULDBLOCK: return "operation would block";
1288 #endif
1289 #ifdef EXDEV
1290     case EXDEV: return "cross-domain link";
1291 #endif
1292 #ifdef EXFULL
1293     case EXFULL: return "message tables full";
1294 #endif
1295     }
1296 #else /* NO_SYS_ERRLIST */
1297   extern int sys_nerr;
1298   extern char *sys_errlist[];
1299
1300   if ((errnum > 0) && (errnum <= sys_nerr))
1301     return sys_errlist [errnum];
1302 #endif /* NO_SYS_ERRLIST */
1303
1304   msg = g_static_private_get (&msg_private);
1305   if (!msg)
1306     {
1307       msg = g_new (gchar, 64);
1308       g_static_private_set (&msg_private, msg, g_free);
1309     }
1310
1311   _g_sprintf (msg, "unknown error (%d)", errnum);
1312
1313   errno = saved_errno;
1314   return msg;
1315 }
1316
1317 G_CONST_RETURN gchar*
1318 g_strsignal (gint signum)
1319 {
1320   static GStaticPrivate msg_private = G_STATIC_PRIVATE_INIT;
1321   char *msg;
1322
1323 #ifdef HAVE_STRSIGNAL
1324   const char *msg_locale;
1325   
1326 #if defined(G_OS_BEOS) || defined(G_WITH_CYGWIN)
1327 extern const char *strsignal(int);
1328 #else
1329   /* this is declared differently (const) in string.h on BeOS */
1330   extern char *strsignal (int sig);
1331 #endif /* !G_OS_BEOS && !G_WITH_CYGWIN */
1332   msg_locale = strsignal (signum);
1333   if (g_get_charset (NULL))
1334     return msg_locale;
1335   else
1336     {
1337       gchar *msg_utf8 = g_locale_to_utf8 (msg_locale, -1, NULL, NULL, NULL);
1338       if (msg_utf8)
1339         {
1340           /* Stick in the quark table so that we can return a static result
1341            */
1342           GQuark msg_quark = g_quark_from_string (msg_utf8);
1343           g_free (msg_utf8);
1344           
1345           return g_quark_to_string (msg_quark);
1346         }
1347     }
1348 #elif NO_SYS_SIGLIST
1349   switch (signum)
1350     {
1351 #ifdef SIGHUP
1352     case SIGHUP: return "Hangup";
1353 #endif
1354 #ifdef SIGINT
1355     case SIGINT: return "Interrupt";
1356 #endif
1357 #ifdef SIGQUIT
1358     case SIGQUIT: return "Quit";
1359 #endif
1360 #ifdef SIGILL
1361     case SIGILL: return "Illegal instruction";
1362 #endif
1363 #ifdef SIGTRAP
1364     case SIGTRAP: return "Trace/breakpoint trap";
1365 #endif
1366 #ifdef SIGABRT
1367     case SIGABRT: return "IOT trap/Abort";
1368 #endif
1369 #ifdef SIGBUS
1370     case SIGBUS: return "Bus error";
1371 #endif
1372 #ifdef SIGFPE
1373     case SIGFPE: return "Floating point exception";
1374 #endif
1375 #ifdef SIGKILL
1376     case SIGKILL: return "Killed";
1377 #endif
1378 #ifdef SIGUSR1
1379     case SIGUSR1: return "User defined signal 1";
1380 #endif
1381 #ifdef SIGSEGV
1382     case SIGSEGV: return "Segmentation fault";
1383 #endif
1384 #ifdef SIGUSR2
1385     case SIGUSR2: return "User defined signal 2";
1386 #endif
1387 #ifdef SIGPIPE
1388     case SIGPIPE: return "Broken pipe";
1389 #endif
1390 #ifdef SIGALRM
1391     case SIGALRM: return "Alarm clock";
1392 #endif
1393 #ifdef SIGTERM
1394     case SIGTERM: return "Terminated";
1395 #endif
1396 #ifdef SIGSTKFLT
1397     case SIGSTKFLT: return "Stack fault";
1398 #endif
1399 #ifdef SIGCHLD
1400     case SIGCHLD: return "Child exited";
1401 #endif
1402 #ifdef SIGCONT
1403     case SIGCONT: return "Continued";
1404 #endif
1405 #ifdef SIGSTOP
1406     case SIGSTOP: return "Stopped (signal)";
1407 #endif
1408 #ifdef SIGTSTP
1409     case SIGTSTP: return "Stopped";
1410 #endif
1411 #ifdef SIGTTIN
1412     case SIGTTIN: return "Stopped (tty input)";
1413 #endif
1414 #ifdef SIGTTOU
1415     case SIGTTOU: return "Stopped (tty output)";
1416 #endif
1417 #ifdef SIGURG
1418     case SIGURG: return "Urgent condition";
1419 #endif
1420 #ifdef SIGXCPU
1421     case SIGXCPU: return "CPU time limit exceeded";
1422 #endif
1423 #ifdef SIGXFSZ
1424     case SIGXFSZ: return "File size limit exceeded";
1425 #endif
1426 #ifdef SIGVTALRM
1427     case SIGVTALRM: return "Virtual time alarm";
1428 #endif
1429 #ifdef SIGPROF
1430     case SIGPROF: return "Profile signal";
1431 #endif
1432 #ifdef SIGWINCH
1433     case SIGWINCH: return "Window size changed";
1434 #endif
1435 #ifdef SIGIO
1436     case SIGIO: return "Possible I/O";
1437 #endif
1438 #ifdef SIGPWR
1439     case SIGPWR: return "Power failure";
1440 #endif
1441 #ifdef SIGUNUSED
1442     case SIGUNUSED: return "Unused signal";
1443 #endif
1444     }
1445 #else /* NO_SYS_SIGLIST */
1446
1447 #ifdef NO_SYS_SIGLIST_DECL
1448   extern char *sys_siglist[];   /*(see Tue Jan 19 00:44:24 1999 in changelog)*/
1449 #endif
1450
1451   return (char*) /* this function should return const --josh */ sys_siglist [signum];
1452 #endif /* NO_SYS_SIGLIST */
1453
1454   msg = g_static_private_get (&msg_private);
1455   if (!msg)
1456     {
1457       msg = g_new (gchar, 64);
1458       g_static_private_set (&msg_private, msg, g_free);
1459     }
1460
1461   _g_sprintf (msg, "unknown signal (%d)", signum);
1462   
1463   return msg;
1464 }
1465
1466 /* Functions g_strlcpy and g_strlcat were originally developed by
1467  * Todd C. Miller <Todd.Miller@courtesan.com> to simplify writing secure code.
1468  * See ftp://ftp.openbsd.org/pub/OpenBSD/src/lib/libc/string/strlcpy.3
1469  * for more information.
1470  */
1471
1472 #ifdef HAVE_STRLCPY
1473 /* Use the native ones, if available; they might be implemented in assembly */
1474 gsize
1475 g_strlcpy (gchar       *dest,
1476            const gchar *src,
1477            gsize        dest_size)
1478 {
1479   g_return_val_if_fail (dest != NULL, 0);
1480   g_return_val_if_fail (src  != NULL, 0);
1481   
1482   return strlcpy (dest, src, dest_size);
1483 }
1484
1485 gsize
1486 g_strlcat (gchar       *dest,
1487            const gchar *src,
1488            gsize        dest_size)
1489 {
1490   g_return_val_if_fail (dest != NULL, 0);
1491   g_return_val_if_fail (src  != NULL, 0);
1492   
1493   return strlcat (dest, src, dest_size);
1494 }
1495
1496 #else /* ! HAVE_STRLCPY */
1497 /* g_strlcpy
1498  *
1499  * Copy string src to buffer dest (of buffer size dest_size).  At most
1500  * dest_size-1 characters will be copied.  Always NUL terminates
1501  * (unless dest_size == 0).  This function does NOT allocate memory.
1502  * Unlike strncpy, this function doesn't pad dest (so it's often faster).
1503  * Returns size of attempted result, strlen(src),
1504  * so if retval >= dest_size, truncation occurred.
1505  */
1506 gsize
1507 g_strlcpy (gchar       *dest,
1508            const gchar *src,
1509            gsize        dest_size)
1510 {
1511   register gchar *d = dest;
1512   register const gchar *s = src;
1513   register gsize n = dest_size;
1514   
1515   g_return_val_if_fail (dest != NULL, 0);
1516   g_return_val_if_fail (src  != NULL, 0);
1517   
1518   /* Copy as many bytes as will fit */
1519   if (n != 0 && --n != 0)
1520     do
1521       {
1522         register gchar c = *s++;
1523         
1524         *d++ = c;
1525         if (c == 0)
1526           break;
1527       }
1528     while (--n != 0);
1529   
1530   /* If not enough room in dest, add NUL and traverse rest of src */
1531   if (n == 0)
1532     {
1533       if (dest_size != 0)
1534         *d = 0;
1535       while (*s++)
1536         ;
1537     }
1538   
1539   return s - src - 1;  /* count does not include NUL */
1540 }
1541
1542 /* g_strlcat
1543  *
1544  * Appends string src to buffer dest (of buffer size dest_size).
1545  * At most dest_size-1 characters will be copied.
1546  * Unlike strncat, dest_size is the full size of dest, not the space left over.
1547  * This function does NOT allocate memory.
1548  * This always NUL terminates (unless siz == 0 or there were no NUL characters
1549  * in the dest_size characters of dest to start with).
1550  * Returns size of attempted result, which is
1551  * MIN (dest_size, strlen (original dest)) + strlen (src),
1552  * so if retval >= dest_size, truncation occurred.
1553  */
1554 gsize
1555 g_strlcat (gchar       *dest,
1556            const gchar *src,
1557            gsize        dest_size)
1558 {
1559   register gchar *d = dest;
1560   register const gchar *s = src;
1561   register gsize bytes_left = dest_size;
1562   gsize dlength;  /* Logically, MIN (strlen (d), dest_size) */
1563   
1564   g_return_val_if_fail (dest != NULL, 0);
1565   g_return_val_if_fail (src  != NULL, 0);
1566   
1567   /* Find the end of dst and adjust bytes left but don't go past end */
1568   while (*d != 0 && bytes_left-- != 0)
1569     d++;
1570   dlength = d - dest;
1571   bytes_left = dest_size - dlength;
1572   
1573   if (bytes_left == 0)
1574     return dlength + strlen (s);
1575   
1576   while (*s != 0)
1577     {
1578       if (bytes_left != 1)
1579         {
1580           *d++ = *s;
1581           bytes_left--;
1582         }
1583       s++;
1584     }
1585   *d = 0;
1586   
1587   return dlength + (s - src);  /* count does not include NUL */
1588 }
1589 #endif /* ! HAVE_STRLCPY */
1590
1591 /**
1592  * g_ascii_strdown:
1593  * @str: a string.
1594  * @len: length of @str in bytes, or -1 if @str is nul-terminated.
1595  * 
1596  * Converts all upper case ASCII letters to lower case ASCII letters.
1597  * 
1598  * Return value: a newly-allocated string, with all the upper case
1599  *               characters in @str converted to lower case, with
1600  *               semantics that exactly match g_ascii_tolower(). (Note
1601  *               that this is unlike the old g_strdown(), which modified
1602  *               the string in place.)
1603  **/
1604 gchar*
1605 g_ascii_strdown (const gchar *str,
1606                  gssize       len)
1607 {
1608   gchar *result, *s;
1609   
1610   g_return_val_if_fail (str != NULL, NULL);
1611
1612   if (len < 0)
1613     len = strlen (str);
1614
1615   result = g_strndup (str, len);
1616   for (s = result; *s; s++)
1617     *s = g_ascii_tolower (*s);
1618   
1619   return result;
1620 }
1621
1622 /**
1623  * g_ascii_strup:
1624  * @str: a string.
1625  * @len: length of @str in bytes, or -1 if @str is nul-terminated.
1626  * 
1627  * Converts all lower case ASCII letters to upper case ASCII letters.
1628  * 
1629  * Return value: a newly allocated string, with all the lower case
1630  *               characters in @str converted to upper case, with
1631  *               semantics that exactly match g_ascii_toupper(). (Note
1632  *               that this is unlike the old g_strup(), which modified
1633  *               the string in place.)
1634  **/
1635 gchar*
1636 g_ascii_strup (const gchar *str,
1637                gssize       len)
1638 {
1639   gchar *result, *s;
1640
1641   g_return_val_if_fail (str != NULL, NULL);
1642
1643   if (len < 0)
1644     len = strlen (str);
1645
1646   result = g_strndup (str, len);
1647   for (s = result; *s; s++)
1648     *s = g_ascii_toupper (*s);
1649
1650   return result;
1651 }
1652
1653 /**
1654  * g_strdown:
1655  * @string: the string to convert.
1656  * 
1657  * Converts a string to lower case.  
1658  * 
1659  * Return value: the string 
1660  *
1661  * Deprecated:2.2: This function is totally broken for the reasons discussed 
1662  * in the g_strncasecmp() docs - use g_ascii_strdown() or g_utf8_strdown() 
1663  * instead.
1664  **/
1665 gchar*
1666 g_strdown (gchar *string)
1667 {
1668   register guchar *s;
1669   
1670   g_return_val_if_fail (string != NULL, NULL);
1671   
1672   s = (guchar *) string;
1673   
1674   while (*s)
1675     {
1676       if (isupper (*s))
1677         *s = tolower (*s);
1678       s++;
1679     }
1680   
1681   return (gchar *) string;
1682 }
1683
1684 /**
1685  * g_strup:
1686  * @string: the string to convert.
1687  * 
1688  * Converts a string to upper case. 
1689  * 
1690  * Return value: the string
1691  *
1692  * Deprecated:2.2: This function is totally broken for the reasons discussed 
1693  * in the g_strncasecmp() docs - use g_ascii_strup() or g_utf8_strup() instead.
1694  **/
1695 gchar*
1696 g_strup (gchar *string)
1697 {
1698   register guchar *s;
1699
1700   g_return_val_if_fail (string != NULL, NULL);
1701
1702   s = (guchar *) string;
1703
1704   while (*s)
1705     {
1706       if (islower (*s))
1707         *s = toupper (*s);
1708       s++;
1709     }
1710
1711   return (gchar *) string;
1712 }
1713
1714 gchar*
1715 g_strreverse (gchar *string)
1716 {
1717   g_return_val_if_fail (string != NULL, NULL);
1718
1719   if (*string)
1720     {
1721       register gchar *h, *t;
1722
1723       h = string;
1724       t = string + strlen (string) - 1;
1725
1726       while (h < t)
1727         {
1728           register gchar c;
1729
1730           c = *h;
1731           *h = *t;
1732           h++;
1733           *t = c;
1734           t--;
1735         }
1736     }
1737
1738   return string;
1739 }
1740
1741 /**
1742  * g_ascii_tolower:
1743  * @c: any character.
1744  * 
1745  * Convert a character to ASCII lower case.
1746  *
1747  * Unlike the standard C library tolower() function, this only
1748  * recognizes standard ASCII letters and ignores the locale, returning
1749  * all non-ASCII characters unchanged, even if they are lower case
1750  * letters in a particular character set. Also unlike the standard
1751  * library function, this takes and returns a char, not an int, so
1752  * don't call it on %EOF but no need to worry about casting to #guchar
1753  * before passing a possibly non-ASCII character in.
1754  * 
1755  * Return value: the result of converting @c to lower case.
1756  *               If @c is not an ASCII upper case letter,
1757  *               @c is returned unchanged.
1758  **/
1759 gchar
1760 g_ascii_tolower (gchar c)
1761 {
1762   return g_ascii_isupper (c) ? c - 'A' + 'a' : c;
1763 }
1764
1765 /**
1766  * g_ascii_toupper:
1767  * @c: any character.
1768  * 
1769  * Convert a character to ASCII upper case.
1770  *
1771  * Unlike the standard C library toupper() function, this only
1772  * recognizes standard ASCII letters and ignores the locale, returning
1773  * all non-ASCII characters unchanged, even if they are upper case
1774  * letters in a particular character set. Also unlike the standard
1775  * library function, this takes and returns a char, not an int, so
1776  * don't call it on %EOF but no need to worry about casting to #guchar
1777  * before passing a possibly non-ASCII character in.
1778  * 
1779  * Return value: the result of converting @c to upper case.
1780  *               If @c is not an ASCII lower case letter,
1781  *               @c is returned unchanged.
1782  **/
1783 gchar
1784 g_ascii_toupper (gchar c)
1785 {
1786   return g_ascii_islower (c) ? c - 'a' + 'A' : c;
1787 }
1788
1789 /**
1790  * g_ascii_digit_value:
1791  * @c: an ASCII character.
1792  *
1793  * Determines the numeric value of a character as a decimal
1794  * digit. Differs from g_unichar_digit_value() because it takes
1795  * a char, so there's no worry about sign extension if characters
1796  * are signed.
1797  *
1798  * Return value: If @c is a decimal digit (according to
1799  * g_ascii_isdigit()), its numeric value. Otherwise, -1.
1800  **/
1801 int
1802 g_ascii_digit_value (gchar c)
1803 {
1804   if (g_ascii_isdigit (c))
1805     return c - '0';
1806   return -1;
1807 }
1808
1809 /**
1810  * g_ascii_xdigit_value:
1811  * @c: an ASCII character.
1812  *
1813  * Determines the numeric value of a character as a hexidecimal
1814  * digit. Differs from g_unichar_xdigit_value() because it takes
1815  * a char, so there's no worry about sign extension if characters
1816  * are signed.
1817  *
1818  * Return value: If @c is a hex digit (according to
1819  * g_ascii_isxdigit()), its numeric value. Otherwise, -1.
1820  **/
1821 int
1822 g_ascii_xdigit_value (gchar c)
1823 {
1824   if (c >= 'A' && c <= 'F')
1825     return c - 'A' + 10;
1826   if (c >= 'a' && c <= 'f')
1827     return c - 'a' + 10;
1828   return g_ascii_digit_value (c);
1829 }
1830
1831 /**
1832  * g_ascii_strcasecmp:
1833  * @s1: string to compare with @s2.
1834  * @s2: string to compare with @s1.
1835  * 
1836  * Compare two strings, ignoring the case of ASCII characters.
1837  *
1838  * Unlike the BSD strcasecmp() function, this only recognizes standard
1839  * ASCII letters and ignores the locale, treating all non-ASCII
1840  * bytes as if they are not letters.
1841  *
1842  * This function should be used only on strings that are known to be
1843  * in encodings where the bytes corresponding to ASCII letters always
1844  * represent themselves. This includes UTF-8 and the ISO-8859-*
1845  * charsets, but not for instance double-byte encodings like the
1846  * Windows Codepage 932, where the trailing bytes of double-byte
1847  * characters include all ASCII letters. If you compare two CP932
1848  * strings using this function, you will get false matches.
1849  *
1850  * Return value: 0 if the strings match, a negative value if @s1 &lt; @s2, 
1851  *   or a positive value if @s1 &gt; @s2.
1852  **/
1853 gint
1854 g_ascii_strcasecmp (const gchar *s1,
1855                     const gchar *s2)
1856 {
1857   gint c1, c2;
1858
1859   g_return_val_if_fail (s1 != NULL, 0);
1860   g_return_val_if_fail (s2 != NULL, 0);
1861
1862   while (*s1 && *s2)
1863     {
1864       c1 = (gint)(guchar) TOLOWER (*s1);
1865       c2 = (gint)(guchar) TOLOWER (*s2);
1866       if (c1 != c2)
1867         return (c1 - c2);
1868       s1++; s2++;
1869     }
1870
1871   return (((gint)(guchar) *s1) - ((gint)(guchar) *s2));
1872 }
1873
1874 /**
1875  * g_ascii_strncasecmp:
1876  * @s1: string to compare with @s2.
1877  * @s2: string to compare with @s1.
1878  * @n:  number of characters to compare.
1879  * 
1880  * Compare @s1 and @s2, ignoring the case of ASCII characters and any
1881  * characters after the first @n in each string.
1882  *
1883  * Unlike the BSD strcasecmp() function, this only recognizes standard
1884  * ASCII letters and ignores the locale, treating all non-ASCII
1885  * characters as if they are not letters.
1886  * 
1887  * The same warning as in g_ascii_strcasecmp() applies: Use this
1888  * function only on strings known to be in encodings where bytes
1889  * corresponding to ASCII letters always represent themselves.
1890  *
1891  * Return value: 0 if the strings match, a negative value if @s1 &lt; @s2, 
1892  *   or a positive value if @s1 &gt; @s2.
1893  **/
1894 gint
1895 g_ascii_strncasecmp (const gchar *s1,
1896                      const gchar *s2,
1897                      gsize n)
1898 {
1899   gint c1, c2;
1900
1901   g_return_val_if_fail (s1 != NULL, 0);
1902   g_return_val_if_fail (s2 != NULL, 0);
1903
1904   while (n && *s1 && *s2)
1905     {
1906       n -= 1;
1907       c1 = (gint)(guchar) TOLOWER (*s1);
1908       c2 = (gint)(guchar) TOLOWER (*s2);
1909       if (c1 != c2)
1910         return (c1 - c2);
1911       s1++; s2++;
1912     }
1913
1914   if (n)
1915     return (((gint) (guchar) *s1) - ((gint) (guchar) *s2));
1916   else
1917     return 0;
1918 }
1919
1920 /**
1921  * g_strcasecmp:
1922  * @s1: a string.
1923  * @s2: a string to compare with @s1.
1924  * 
1925  * A case-insensitive string comparison, corresponding to the standard
1926  * strcasecmp() function on platforms which support it.
1927  *
1928  * Return value: 0 if the strings match, a negative value if @s1 &lt; @s2, 
1929  *   or a positive value if @s1 &gt; @s2.
1930  *
1931  * Deprecated:2.2: See g_strncasecmp() for a discussion of why this function 
1932  *   is deprecated and how to replace it.
1933  **/
1934 gint
1935 g_strcasecmp (const gchar *s1,
1936               const gchar *s2)
1937 {
1938 #ifdef HAVE_STRCASECMP
1939   g_return_val_if_fail (s1 != NULL, 0);
1940   g_return_val_if_fail (s2 != NULL, 0);
1941
1942   return strcasecmp (s1, s2);
1943 #else
1944   gint c1, c2;
1945
1946   g_return_val_if_fail (s1 != NULL, 0);
1947   g_return_val_if_fail (s2 != NULL, 0);
1948
1949   while (*s1 && *s2)
1950     {
1951       /* According to A. Cox, some platforms have islower's that
1952        * don't work right on non-uppercase
1953        */
1954       c1 = isupper ((guchar)*s1) ? tolower ((guchar)*s1) : *s1;
1955       c2 = isupper ((guchar)*s2) ? tolower ((guchar)*s2) : *s2;
1956       if (c1 != c2)
1957         return (c1 - c2);
1958       s1++; s2++;
1959     }
1960
1961   return (((gint)(guchar) *s1) - ((gint)(guchar) *s2));
1962 #endif
1963 }
1964
1965 /**
1966  * g_strncasecmp:
1967  * @s1: a string.
1968  * @s2: a string to compare with @s1.
1969  * @n: the maximum number of characters to compare.
1970  * 
1971  * A case-insensitive string comparison, corresponding to the standard
1972  * strncasecmp() function on platforms which support it.
1973  * It is similar to g_strcasecmp() except it only compares the first @n 
1974  * characters of the strings.
1975  * 
1976  * Return value: 0 if the strings match, a negative value if @s1 &lt; @s2, 
1977  *   or a positive value if @s1 &gt; @s2.
1978  *
1979  * Deprecated:2.2: The problem with g_strncasecmp() is that it does the 
1980  * comparison by calling toupper()/tolower(). These functions are
1981  * locale-specific and operate on single bytes. However, it is impossible
1982  * to handle things correctly from an I18N standpoint by operating on
1983  * bytes, since characters may be multibyte. Thus g_strncasecmp() is
1984  * broken if your string is guaranteed to be ASCII, since it's
1985  * locale-sensitive, and it's broken if your string is localized, since
1986  * it doesn't work on many encodings at all, including UTF-8, EUC-JP,
1987  * etc.
1988  *
1989  * There are therefore two replacement functions: g_ascii_strncasecmp(),
1990  * which only works on ASCII and is not locale-sensitive, and
1991  * g_utf8_casefold(), which is good for case-insensitive sorting of UTF-8.
1992  **/
1993 gint
1994 g_strncasecmp (const gchar *s1,
1995                const gchar *s2,
1996                guint n)     
1997 {
1998 #ifdef HAVE_STRNCASECMP
1999   return strncasecmp (s1, s2, n);
2000 #else
2001   gint c1, c2;
2002
2003   g_return_val_if_fail (s1 != NULL, 0);
2004   g_return_val_if_fail (s2 != NULL, 0);
2005
2006   while (n && *s1 && *s2)
2007     {
2008       n -= 1;
2009       /* According to A. Cox, some platforms have islower's that
2010        * don't work right on non-uppercase
2011        */
2012       c1 = isupper ((guchar)*s1) ? tolower ((guchar)*s1) : *s1;
2013       c2 = isupper ((guchar)*s2) ? tolower ((guchar)*s2) : *s2;
2014       if (c1 != c2)
2015         return (c1 - c2);
2016       s1++; s2++;
2017     }
2018
2019   if (n)
2020     return (((gint) (guchar) *s1) - ((gint) (guchar) *s2));
2021   else
2022     return 0;
2023 #endif
2024 }
2025
2026 gchar*
2027 g_strdelimit (gchar       *string,
2028               const gchar *delimiters,
2029               gchar        new_delim)
2030 {
2031   register gchar *c;
2032
2033   g_return_val_if_fail (string != NULL, NULL);
2034
2035   if (!delimiters)
2036     delimiters = G_STR_DELIMITERS;
2037
2038   for (c = string; *c; c++)
2039     {
2040       if (strchr (delimiters, *c))
2041         *c = new_delim;
2042     }
2043
2044   return string;
2045 }
2046
2047 gchar*
2048 g_strcanon (gchar       *string,
2049             const gchar *valid_chars,
2050             gchar        substitutor)
2051 {
2052   register gchar *c;
2053
2054   g_return_val_if_fail (string != NULL, NULL);
2055   g_return_val_if_fail (valid_chars != NULL, NULL);
2056
2057   for (c = string; *c; c++)
2058     {
2059       if (!strchr (valid_chars, *c))
2060         *c = substitutor;
2061     }
2062
2063   return string;
2064 }
2065
2066 gchar*
2067 g_strcompress (const gchar *source)
2068 {
2069   const gchar *p = source, *octal;
2070   gchar *dest = g_malloc (strlen (source) + 1);
2071   gchar *q = dest;
2072   
2073   while (*p)
2074     {
2075       if (*p == '\\')
2076         {
2077           p++;
2078           switch (*p)
2079             {
2080             case '\0':
2081               g_warning ("g_strcompress: trailing \\");
2082               goto out;
2083             case '0':  case '1':  case '2':  case '3':  case '4':
2084             case '5':  case '6':  case '7':
2085               *q = 0;
2086               octal = p;
2087               while ((p < octal + 3) && (*p >= '0') && (*p <= '7'))
2088                 {
2089                   *q = (*q * 8) + (*p - '0');
2090                   p++;
2091                 }
2092               q++;
2093               p--;
2094               break;
2095             case 'b':
2096               *q++ = '\b';
2097               break;
2098             case 'f':
2099               *q++ = '\f';
2100               break;
2101             case 'n':
2102               *q++ = '\n';
2103               break;
2104             case 'r':
2105               *q++ = '\r';
2106               break;
2107             case 't':
2108               *q++ = '\t';
2109               break;
2110             default:            /* Also handles \" and \\ */
2111               *q++ = *p;
2112               break;
2113             }
2114         }
2115       else
2116         *q++ = *p;
2117       p++;
2118     }
2119 out:
2120   *q = 0;
2121   
2122   return dest;
2123 }
2124
2125 gchar *
2126 g_strescape (const gchar *source,
2127              const gchar *exceptions)
2128 {
2129   const guchar *p;
2130   gchar *dest;
2131   gchar *q;
2132   guchar excmap[256];
2133   
2134   g_return_val_if_fail (source != NULL, NULL);
2135
2136   p = (guchar *) source;
2137   /* Each source byte needs maximally four destination chars (\777) */
2138   q = dest = g_malloc (strlen (source) * 4 + 1);
2139
2140   memset (excmap, 0, 256);
2141   if (exceptions)
2142     {
2143       guchar *e = (guchar *) exceptions;
2144
2145       while (*e)
2146         {
2147           excmap[*e] = 1;
2148           e++;
2149         }
2150     }
2151
2152   while (*p)
2153     {
2154       if (excmap[*p])
2155         *q++ = *p;
2156       else
2157         {
2158           switch (*p)
2159             {
2160             case '\b':
2161               *q++ = '\\';
2162               *q++ = 'b';
2163               break;
2164             case '\f':
2165               *q++ = '\\';
2166               *q++ = 'f';
2167               break;
2168             case '\n':
2169               *q++ = '\\';
2170               *q++ = 'n';
2171               break;
2172             case '\r':
2173               *q++ = '\\';
2174               *q++ = 'r';
2175               break;
2176             case '\t':
2177               *q++ = '\\';
2178               *q++ = 't';
2179               break;
2180             case '\\':
2181               *q++ = '\\';
2182               *q++ = '\\';
2183               break;
2184             case '"':
2185               *q++ = '\\';
2186               *q++ = '"';
2187               break;
2188             default:
2189               if ((*p < ' ') || (*p >= 0177))
2190                 {
2191                   *q++ = '\\';
2192                   *q++ = '0' + (((*p) >> 6) & 07);
2193                   *q++ = '0' + (((*p) >> 3) & 07);
2194                   *q++ = '0' + ((*p) & 07);
2195                 }
2196               else
2197                 *q++ = *p;
2198               break;
2199             }
2200         }
2201       p++;
2202     }
2203   *q = 0;
2204   return dest;
2205 }
2206
2207 gchar*
2208 g_strchug (gchar *string)
2209 {
2210   guchar *start;
2211
2212   g_return_val_if_fail (string != NULL, NULL);
2213
2214   for (start = (guchar*) string; *start && g_ascii_isspace (*start); start++)
2215     ;
2216
2217   g_memmove (string, start, strlen ((gchar *) start) + 1);
2218
2219   return string;
2220 }
2221
2222 gchar*
2223 g_strchomp (gchar *string)
2224 {
2225   gsize len;
2226
2227   g_return_val_if_fail (string != NULL, NULL);
2228
2229   len = strlen (string);
2230   while (len--)
2231     {
2232       if (g_ascii_isspace ((guchar) string[len]))
2233         string[len] = '\0';
2234       else
2235         break;
2236     }
2237
2238   return string;
2239 }
2240
2241 /**
2242  * g_strsplit:
2243  * @string: a string to split.
2244  * @delimiter: a string which specifies the places at which to split the string.
2245  *     The delimiter is not included in any of the resulting strings, unless
2246  *     @max_tokens is reached.
2247  * @max_tokens: the maximum number of pieces to split @string into. If this is
2248  *              less than 1, the string is split completely.
2249  * 
2250  * Splits a string into a maximum of @max_tokens pieces, using the given
2251  * @delimiter. If @max_tokens is reached, the remainder of @string is appended
2252  * to the last token. 
2253  *
2254  * As a special case, the result of splitting the empty string "" is an empty
2255  * vector, not a vector containing a single string. The reason for this
2256  * special case is that being able to represent a empty vector is typically
2257  * more useful than consistent handling of empty elements. If you do need
2258  * to represent empty elements, you'll need to check for the empty string
2259  * before calling g_strsplit().
2260  * 
2261  * Return value: a newly-allocated %NULL-terminated array of strings. Use 
2262  *    g_strfreev() to free it.
2263  **/
2264 gchar**
2265 g_strsplit (const gchar *string,
2266             const gchar *delimiter,
2267             gint         max_tokens)
2268 {
2269   GSList *string_list = NULL, *slist;
2270   gchar **str_array, *s;
2271   guint n = 0;
2272   const gchar *remainder;
2273
2274   g_return_val_if_fail (string != NULL, NULL);
2275   g_return_val_if_fail (delimiter != NULL, NULL);
2276   g_return_val_if_fail (delimiter[0] != '\0', NULL);
2277
2278   if (max_tokens < 1)
2279     max_tokens = G_MAXINT;
2280
2281   remainder = string;
2282   s = strstr (remainder, delimiter);
2283   if (s)
2284     {
2285       gsize delimiter_len = strlen (delimiter);   
2286
2287       while (--max_tokens && s)
2288         {
2289           gsize len;     
2290
2291           len = s - remainder;
2292           string_list = g_slist_prepend (string_list,
2293                                          g_strndup (remainder, len));
2294           n++;
2295           remainder = s + delimiter_len;
2296           s = strstr (remainder, delimiter);
2297         }
2298     }
2299   if (*string)
2300     {
2301       n++;
2302       string_list = g_slist_prepend (string_list, g_strdup (remainder));
2303     }
2304
2305   str_array = g_new (gchar*, n + 1);
2306
2307   str_array[n--] = NULL;
2308   for (slist = string_list; slist; slist = slist->next)
2309     str_array[n--] = slist->data;
2310
2311   g_slist_free (string_list);
2312
2313   return str_array;
2314 }
2315
2316 /**
2317  * g_strsplit_set:
2318  * @string: The string to be tokenized
2319  * @delimiters: A nul-terminated string containing bytes that are used
2320  *              to split the string.
2321  * @max_tokens: The maximum number of tokens to split @string into. 
2322  *              If this is less than 1, the string is split completely
2323  * 
2324  * Splits @string into a number of tokens not containing any of the characters
2325  * in @delimiter. A token is the (possibly empty) longest string that does not
2326  * contain any of the characters in @delimiters. If @max_tokens is reached, the
2327  * remainder is appended to the last token.
2328  *
2329  * For example the result of g_strsplit_set ("abc:def/ghi", ":/", -1) is a
2330  * %NULL-terminated vector containing the three strings "abc", "def", 
2331  * and "ghi".
2332  *
2333  * The result if g_strsplit_set (":def/ghi:", ":/", -1) is a %NULL-terminated
2334  * vector containing the four strings "", "def", "ghi", and "".
2335  * 
2336  * As a special case, the result of splitting the empty string "" is an empty
2337  * vector, not a vector containing a single string. The reason for this
2338  * special case is that being able to represent a empty vector is typically
2339  * more useful than consistent handling of empty elements. If you do need
2340  * to represent empty elements, you'll need to check for the empty string
2341  * before calling g_strsplit_set().
2342  *
2343  * Note that this function works on bytes not characters, so it can't be used 
2344  * to delimit UTF-8 strings for anything but ASCII characters.
2345  * 
2346  * Return value: a newly-allocated %NULL-terminated array of strings. Use 
2347  *    g_strfreev() to free it.
2348  * 
2349  * Since: 2.4
2350  **/
2351 gchar **
2352 g_strsplit_set (const gchar *string,
2353                 const gchar *delimiters,
2354                 gint         max_tokens)
2355 {
2356   gboolean delim_table[256];
2357   GSList *tokens, *list;
2358   gint n_tokens;
2359   const gchar *s;
2360   const gchar *current;
2361   gchar *token;
2362   gchar **result;
2363   
2364   g_return_val_if_fail (string != NULL, NULL);
2365   g_return_val_if_fail (delimiters != NULL, NULL);
2366
2367   if (max_tokens < 1)
2368     max_tokens = G_MAXINT;
2369
2370   if (*string == '\0')
2371     {
2372       result = g_new (char *, 1);
2373       result[0] = NULL;
2374       return result;
2375     }
2376   
2377   memset (delim_table, FALSE, sizeof (delim_table));
2378   for (s = delimiters; *s != '\0'; ++s)
2379     delim_table[*(guchar *)s] = TRUE;
2380
2381   tokens = NULL;
2382   n_tokens = 0;
2383
2384   s = current = string;
2385   while (*s != '\0')
2386     {
2387       if (delim_table[*(guchar *)s] && n_tokens + 1 < max_tokens)
2388         {
2389           gchar *token;
2390
2391           token = g_strndup (current, s - current);
2392           tokens = g_slist_prepend (tokens, token);
2393           ++n_tokens;
2394
2395           current = s + 1;
2396         }
2397       
2398       ++s;
2399     }
2400
2401   token = g_strndup (current, s - current);
2402   tokens = g_slist_prepend (tokens, token);
2403   ++n_tokens;
2404
2405   result = g_new (gchar *, n_tokens + 1);
2406
2407   result[n_tokens] = NULL;
2408   for (list = tokens; list != NULL; list = list->next)
2409     result[--n_tokens] = list->data;
2410
2411   g_slist_free (tokens);
2412   
2413   return result;
2414 }
2415
2416 /**
2417  * g_strfreev:
2418  * @str_array: a %NULL-terminated array of strings to free.
2419
2420  * Frees a %NULL-terminated array of strings, and the array itself.
2421  * If called on a %NULL value, g_strfreev() simply returns. 
2422  **/
2423 void
2424 g_strfreev (gchar **str_array)
2425 {
2426   if (str_array)
2427     {
2428       int i;
2429
2430       for (i = 0; str_array[i] != NULL; i++)
2431         g_free (str_array[i]);
2432
2433       g_free (str_array);
2434     }
2435 }
2436
2437 /**
2438  * g_strdupv:
2439  * @str_array: %NULL-terminated array of strings.
2440  * 
2441  * Copies %NULL-terminated array of strings. The copy is a deep copy;
2442  * the new array should be freed by first freeing each string, then
2443  * the array itself. g_strfreev() does this for you. If called
2444  * on a %NULL value, g_strdupv() simply returns %NULL.
2445  * 
2446  * Return value: a new %NULL-terminated array of strings.
2447  **/
2448 gchar**
2449 g_strdupv (gchar **str_array)
2450 {
2451   if (str_array)
2452     {
2453       gint i;
2454       gchar **retval;
2455
2456       i = 0;
2457       while (str_array[i])
2458         ++i;
2459           
2460       retval = g_new (gchar*, i + 1);
2461
2462       i = 0;
2463       while (str_array[i])
2464         {
2465           retval[i] = g_strdup (str_array[i]);
2466           ++i;
2467         }
2468       retval[i] = NULL;
2469
2470       return retval;
2471     }
2472   else
2473     return NULL;
2474 }
2475
2476 gchar*
2477 g_strjoinv (const gchar  *separator,
2478             gchar       **str_array)
2479 {
2480   gchar *string;
2481   gchar *ptr;
2482
2483   g_return_val_if_fail (str_array != NULL, NULL);
2484
2485   if (separator == NULL)
2486     separator = "";
2487
2488   if (*str_array)
2489     {
2490       gint i;
2491       gsize len;
2492       gsize separator_len;     
2493
2494       separator_len = strlen (separator);
2495       /* First part, getting length */
2496       len = 1 + strlen (str_array[0]);
2497       for (i = 1; str_array[i] != NULL; i++)
2498         len += strlen (str_array[i]);
2499       len += separator_len * (i - 1);
2500
2501       /* Second part, building string */
2502       string = g_new (gchar, len);
2503       ptr = g_stpcpy (string, *str_array);
2504       for (i = 1; str_array[i] != NULL; i++)
2505         {
2506           ptr = g_stpcpy (ptr, separator);
2507           ptr = g_stpcpy (ptr, str_array[i]);
2508         }
2509       }
2510   else
2511     string = g_strdup ("");
2512
2513   return string;
2514 }
2515
2516 gchar*
2517 g_strjoin (const gchar  *separator,
2518            ...)
2519 {
2520   gchar *string, *s;
2521   va_list args;
2522   gsize len;               
2523   gsize separator_len;     
2524   gchar *ptr;
2525
2526   if (separator == NULL)
2527     separator = "";
2528
2529   separator_len = strlen (separator);
2530
2531   va_start (args, separator);
2532
2533   s = va_arg (args, gchar*);
2534
2535   if (s)
2536     {
2537       /* First part, getting length */
2538       len = 1 + strlen (s);
2539
2540       s = va_arg (args, gchar*);
2541       while (s)
2542         {
2543           len += separator_len + strlen (s);
2544           s = va_arg (args, gchar*);
2545         }
2546       va_end (args);
2547
2548       /* Second part, building string */
2549       string = g_new (gchar, len);
2550
2551       va_start (args, separator);
2552
2553       s = va_arg (args, gchar*);
2554       ptr = g_stpcpy (string, s);
2555
2556       s = va_arg (args, gchar*);
2557       while (s)
2558         {
2559           ptr = g_stpcpy (ptr, separator);
2560           ptr = g_stpcpy (ptr, s);
2561           s = va_arg (args, gchar*);
2562         }
2563     }
2564   else
2565     string = g_strdup ("");
2566
2567   va_end (args);
2568
2569   return string;
2570 }
2571
2572
2573 /**
2574  * g_strstr_len:
2575  * @haystack: a string.
2576  * @haystack_len: the maximum length of @haystack.
2577  * @needle: the string to search for.
2578  *
2579  * Searches the string @haystack for the first occurrence
2580  * of the string @needle, limiting the length of the search
2581  * to @haystack_len. 
2582  *
2583  * Return value: a pointer to the found occurrence, or
2584  *    %NULL if not found.
2585  **/
2586 gchar *
2587 g_strstr_len (const gchar *haystack,
2588               gssize       haystack_len,
2589               const gchar *needle)
2590 {
2591   g_return_val_if_fail (haystack != NULL, NULL);
2592   g_return_val_if_fail (needle != NULL, NULL);
2593   
2594   if (haystack_len < 0)
2595     return strstr (haystack, needle);
2596   else
2597     {
2598       const gchar *p = haystack;
2599       gsize needle_len = strlen (needle);
2600       const gchar *end;
2601       gsize i;
2602
2603       if (needle_len == 0)
2604         return (gchar *)haystack;
2605
2606       if (haystack_len < needle_len)
2607         return NULL;
2608       
2609       end = haystack + haystack_len - needle_len;
2610       
2611       while (*p && p <= end)
2612         {
2613           for (i = 0; i < needle_len; i++)
2614             if (p[i] != needle[i])
2615               goto next;
2616           
2617           return (gchar *)p;
2618           
2619         next:
2620           p++;
2621         }
2622       
2623       return NULL;
2624     }
2625 }
2626
2627 /**
2628  * g_strrstr:
2629  * @haystack: a nul-terminated string.
2630  * @needle: the nul-terminated string to search for.
2631  *
2632  * Searches the string @haystack for the last occurrence
2633  * of the string @needle.
2634  *
2635  * Return value: a pointer to the found occurrence, or
2636  *    %NULL if not found.
2637  **/
2638 gchar *
2639 g_strrstr (const gchar *haystack,
2640            const gchar *needle)
2641 {
2642   gsize i;
2643   gsize needle_len;
2644   gsize haystack_len;
2645   const gchar *p;
2646       
2647   g_return_val_if_fail (haystack != NULL, NULL);
2648   g_return_val_if_fail (needle != NULL, NULL);
2649
2650   needle_len = strlen (needle);
2651   haystack_len = strlen (haystack);
2652
2653   if (needle_len == 0)
2654     return (gchar *)haystack;
2655
2656   if (haystack_len < needle_len)
2657     return NULL;
2658   
2659   p = haystack + haystack_len - needle_len;
2660
2661   while (p >= haystack)
2662     {
2663       for (i = 0; i < needle_len; i++)
2664         if (p[i] != needle[i])
2665           goto next;
2666       
2667       return (gchar *)p;
2668       
2669     next:
2670       p--;
2671     }
2672   
2673   return NULL;
2674 }
2675
2676 /**
2677  * g_strrstr_len:
2678  * @haystack: a nul-terminated string.
2679  * @haystack_len: the maximum length of @haystack.
2680  * @needle: the nul-terminated string to search for.
2681  *
2682  * Searches the string @haystack for the last occurrence
2683  * of the string @needle, limiting the length of the search
2684  * to @haystack_len. 
2685  *
2686  * Return value: a pointer to the found occurrence, or
2687  *    %NULL if not found.
2688  **/
2689 gchar *
2690 g_strrstr_len (const gchar *haystack,
2691                gssize        haystack_len,
2692                const gchar *needle)
2693 {
2694   g_return_val_if_fail (haystack != NULL, NULL);
2695   g_return_val_if_fail (needle != NULL, NULL);
2696   
2697   if (haystack_len < 0)
2698     return g_strrstr (haystack, needle);
2699   else
2700     {
2701       gsize needle_len = strlen (needle);
2702       const gchar *haystack_max = haystack + haystack_len;
2703       const gchar *p = haystack;
2704       gsize i;
2705
2706       while (p < haystack_max && *p)
2707         p++;
2708
2709       if (p < haystack + needle_len)
2710         return NULL;
2711         
2712       p -= needle_len;
2713
2714       while (p >= haystack)
2715         {
2716           for (i = 0; i < needle_len; i++)
2717             if (p[i] != needle[i])
2718               goto next;
2719           
2720           return (gchar *)p;
2721           
2722         next:
2723           p--;
2724         }
2725
2726       return NULL;
2727     }
2728 }
2729
2730
2731 /**
2732  * g_str_has_suffix:
2733  * @str: a nul-terminated string.
2734  * @suffix: the nul-terminated suffix to look for.
2735  *
2736  * Looks whether the string @str ends with @suffix.
2737  *
2738  * Return value: %TRUE if @str end with @suffix, %FALSE otherwise.
2739  *
2740  * Since: 2.2
2741  **/
2742 gboolean
2743 g_str_has_suffix (const gchar  *str,
2744                   const gchar  *suffix)
2745 {
2746   int str_len;
2747   int suffix_len;
2748   
2749   g_return_val_if_fail (str != NULL, FALSE);
2750   g_return_val_if_fail (suffix != NULL, FALSE);
2751
2752   str_len = strlen (str);
2753   suffix_len = strlen (suffix);
2754
2755   if (str_len < suffix_len)
2756     return FALSE;
2757
2758   return strcmp (str + str_len - suffix_len, suffix) == 0;
2759 }
2760
2761 /**
2762  * g_str_has_prefix:
2763  * @str: a nul-terminated string.
2764  * @prefix: the nul-terminated prefix to look for.
2765  *
2766  * Looks whether the string @str begins with @prefix.
2767  *
2768  * Return value: %TRUE if @str begins with @prefix, %FALSE otherwise.
2769  *
2770  * Since: 2.2
2771  **/
2772 gboolean
2773 g_str_has_prefix (const gchar  *str,
2774                   const gchar  *prefix)
2775 {
2776   int str_len;
2777   int prefix_len;
2778   
2779   g_return_val_if_fail (str != NULL, FALSE);
2780   g_return_val_if_fail (prefix != NULL, FALSE);
2781
2782   str_len = strlen (str);
2783   prefix_len = strlen (prefix);
2784
2785   if (str_len < prefix_len)
2786     return FALSE;
2787   
2788   return strncmp (str, prefix, prefix_len) == 0;
2789 }
2790
2791
2792 /**
2793  * g_strip_context:
2794  * @msgid: a string
2795  * @msgval: another string
2796  * 
2797  * An auxiliary function for gettext() support (see Q_()).
2798  * 
2799  * Return value: @msgval, unless @msgval is identical to @msgid and contains
2800  *   a '|' character, in which case a pointer to the substring of msgid after
2801  *   the first '|' character is returned. 
2802  *
2803  * Since: 2.4
2804  **/
2805 G_CONST_RETURN gchar *
2806 g_strip_context  (const gchar *msgid, 
2807                   const gchar *msgval)
2808 {
2809   if (msgval == msgid)
2810     {
2811       const char *c = strchr (msgid, '|');
2812       if (c != NULL)
2813         return c + 1;
2814     }
2815   
2816   return msgval;
2817 }
2818
2819
2820 /**
2821  * g_strv_length:
2822  * @str_array: a %NULL-terminated array of strings.
2823  * 
2824  * Returns the length of the given %NULL-terminated 
2825  * string array @str_array.
2826  * 
2827  * Return value: length of @str_array.
2828  *
2829  * Since: 2.6
2830  **/
2831 guint
2832 g_strv_length (gchar **str_array)
2833 {
2834   guint i = 0;
2835
2836   g_return_val_if_fail (str_array != NULL, 0);
2837
2838   while (str_array[i])
2839     ++i;
2840
2841   return i;
2842 }
2843
2844 #define __G_STRFUNCS_C__
2845 #include "galiasdef.c"