Move docs inline, and improve wording. (#372598, Behdad Esfahbod)
[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             rest_len = strlen (p + (decimal_point_len-1));
615             memmove (p, p + (decimal_point_len-1),
616                      rest_len);
617             p[rest_len] = 0;
618             
619           }
620         }
621     }
622   
623   return buffer;
624 }
625
626 static guint64
627 g_parse_long_long (const gchar *nptr,
628                    gchar      **endptr,
629                    guint        base,
630                    gboolean    *negative)
631 {
632   /* this code is based on on the strtol(3) code from GNU libc released under
633    * the GNU Lesser General Public License.
634    *
635    * Copyright (C) 1991,92,94,95,96,97,98,99,2000,01,02
636    *        Free Software Foundation, Inc.
637    */
638 #define ISSPACE(c)              ((c) == ' ' || (c) == '\f' || (c) == '\n' || \
639                                  (c) == '\r' || (c) == '\t' || (c) == '\v')
640 #define ISUPPER(c)              ((c) >= 'A' && (c) <= 'Z')
641 #define ISLOWER(c)              ((c) >= 'a' && (c) <= 'z')
642 #define ISALPHA(c)              (ISUPPER (c) || ISLOWER (c))
643 #define TOUPPER(c)              (ISLOWER (c) ? (c) - 'a' + 'A' : (c))
644 #define TOLOWER(c)              (ISUPPER (c) ? (c) - 'A' + 'a' : (c))
645   gboolean overflow;
646   guint64 cutoff;
647   guint64 cutlim;
648   guint64 ui64;
649   const gchar *s, *save;
650   guchar c;
651   
652   g_return_val_if_fail (nptr != NULL, 0);
653   
654   if (base == 1 || base > 36)
655     {
656       errno = EINVAL;
657       return 0;
658     }
659   
660   save = s = nptr;
661   
662   /* Skip white space.  */
663   while (ISSPACE (*s))
664     ++s;
665
666   if (G_UNLIKELY (!*s))
667     goto noconv;
668   
669   /* Check for a sign.  */
670   *negative = FALSE;
671   if (*s == '-')
672     {
673       *negative = TRUE;
674       ++s;
675     }
676   else if (*s == '+')
677     ++s;
678   
679   /* Recognize number prefix and if BASE is zero, figure it out ourselves.  */
680   if (*s == '0')
681     {
682       if ((base == 0 || base == 16) && TOUPPER (s[1]) == 'X')
683         {
684           s += 2;
685           base = 16;
686         }
687       else if (base == 0)
688         base = 8;
689     }
690   else if (base == 0)
691     base = 10;
692   
693   /* Save the pointer so we can check later if anything happened.  */
694   save = s;
695   cutoff = G_MAXUINT64 / base;
696   cutlim = G_MAXUINT64 % base;
697   
698   overflow = FALSE;
699   ui64 = 0;
700   c = *s;
701   for (; c; c = *++s)
702     {
703       if (c >= '0' && c <= '9')
704         c -= '0';
705       else if (ISALPHA (c))
706         c = TOUPPER (c) - 'A' + 10;
707       else
708         break;
709       if (c >= base)
710         break;
711       /* Check for overflow.  */
712       if (ui64 > cutoff || (ui64 == cutoff && c > cutlim))
713         overflow = TRUE;
714       else
715         {
716           ui64 *= base;
717           ui64 += c;
718         }
719     }
720   
721   /* Check if anything actually happened.  */
722   if (s == save)
723     goto noconv;
724   
725   /* Store in ENDPTR the address of one character
726      past the last character we converted.  */
727   if (endptr)
728     *endptr = (gchar*) s;
729   
730   if (G_UNLIKELY (overflow))
731     {
732       errno = ERANGE;
733       return G_MAXUINT64;
734     }
735
736   return ui64;
737   
738  noconv:
739   /* We must handle a special case here: the base is 0 or 16 and the
740      first two characters are '0' and 'x', but the rest are no
741      hexadecimal digits.  This is no error case.  We return 0 and
742      ENDPTR points to the `x`.  */
743   if (endptr)
744     {
745       if (save - nptr >= 2 && TOUPPER (save[-1]) == 'X'
746           && save[-2] == '0')
747         *endptr = (gchar*) &save[-1];
748       else
749         /*  There was no number to convert.  */
750         *endptr = (gchar*) nptr;
751     }
752   return 0;
753 }
754
755 /**
756  * g_ascii_strtoull:
757  * @nptr:    the string to convert to a numeric value.
758  * @endptr:  if non-%NULL, it returns the character after
759  *           the last character used in the conversion.
760  * @base:    to be used for the conversion, 2..36 or 0
761  *
762  * Converts a string to a #guint64 value.
763  * This function behaves like the standard strtoull() function
764  * does in the C locale. It does this without actually
765  * changing the current locale, since that would not be
766  * thread-safe.
767  *
768  * This function is typically used when reading configuration
769  * files or other non-user input that should be locale independent.
770  * To handle input from the user you should normally use the
771  * locale-sensitive system strtoull() function.
772  *
773  * If the correct value would cause overflow, %G_MAXUINT64
774  * is returned, and %ERANGE is stored in %errno.  If the base is
775  * outside the valid range, zero is returned, and %EINVAL is stored
776  * in %errno.  If the string conversion fails, zero is returned, and
777  * @endptr returns @nptr (if @endptr is non-%NULL).
778  *
779  * Return value: the #guint64 value or zero on error.
780  *
781  * Since: 2.2
782  **/
783 guint64
784 g_ascii_strtoull (const gchar *nptr,
785                   gchar      **endptr,
786                   guint        base)
787 {
788   gboolean negative;
789   guint64 result;
790
791   result = g_parse_long_long (nptr, endptr, base, &negative);
792
793   /* Return the result of the appropriate sign.  */
794   return negative ? -result : result;
795 }
796
797 /**
798  * g_ascii_strtoll:
799  * @nptr:    the string to convert to a numeric value.
800  * @endptr:  if non-%NULL, it returns the character after
801  *           the last character used in the conversion.
802  * @base:    to be used for the conversion, 2..36 or 0
803  *
804  * Converts a string to a #gint64 value.
805  * This function behaves like the standard strtoll() function
806  * does in the C locale. It does this without actually
807  * changing the current locale, since that would not be
808  * thread-safe.
809  *
810  * This function is typically used when reading configuration
811  * files or other non-user input that should be locale independent.
812  * To handle input from the user you should normally use the
813  * locale-sensitive system strtoll() function.
814  *
815  * If the correct value would cause overflow, %G_MAXINT64 or %G_MININT64
816  * is returned, and %ERANGE is stored in %errno.  If the base is
817  * outside the valid range, zero is returned, and %EINVAL is stored
818  * in %errno.  If the string conversion fails, zero is returned, and
819  * @endptr returns @nptr (if @endptr is non-%NULL).
820  *
821  * Return value: the #gint64 value or zero on error.
822  *
823  * Since: 2.12
824  **/
825 gint64 
826 g_ascii_strtoll (const gchar *nptr,
827                  gchar      **endptr,
828                  guint        base)
829 {
830   gboolean negative;
831   guint64 result;
832
833   result = g_parse_long_long (nptr, endptr, base, &negative);
834
835   if (negative && result > (guint64) G_MININT64)
836     {
837       errno = ERANGE;
838       return G_MININT64;
839     }
840   else if (!negative && result > (guint64) G_MAXINT64)
841     {
842       errno = ERANGE;
843       return G_MAXINT64;
844     }
845   else
846     return (gint64) result;
847 }
848
849 G_CONST_RETURN gchar*
850 g_strerror (gint errnum)
851 {
852   static GStaticPrivate msg_private = G_STATIC_PRIVATE_INIT;
853   char *msg;
854   int saved_errno = errno;
855
856 #ifdef HAVE_STRERROR
857   const char *msg_locale;
858
859   msg_locale = strerror (errnum);
860   if (g_get_charset (NULL))
861     {
862       errno = saved_errno;
863       return msg_locale;
864     }
865   else
866     {
867       gchar *msg_utf8 = g_locale_to_utf8 (msg_locale, -1, NULL, NULL, NULL);
868       if (msg_utf8)
869         {
870           /* Stick in the quark table so that we can return a static result
871            */
872           GQuark msg_quark = g_quark_from_string (msg_utf8);
873           g_free (msg_utf8);
874           
875           msg_utf8 = (gchar *) g_quark_to_string (msg_quark);
876           errno = saved_errno;
877           return msg_utf8;
878         }
879     }
880 #elif NO_SYS_ERRLIST
881   switch (errnum)
882     {
883 #ifdef E2BIG
884     case E2BIG: return "argument list too long";
885 #endif
886 #ifdef EACCES
887     case EACCES: return "permission denied";
888 #endif
889 #ifdef EADDRINUSE
890     case EADDRINUSE: return "address already in use";
891 #endif
892 #ifdef EADDRNOTAVAIL
893     case EADDRNOTAVAIL: return "can't assign requested address";
894 #endif
895 #ifdef EADV
896     case EADV: return "advertise error";
897 #endif
898 #ifdef EAFNOSUPPORT
899     case EAFNOSUPPORT: return "address family not supported by protocol family";
900 #endif
901 #ifdef EAGAIN
902     case EAGAIN: return "try again";
903 #endif
904 #ifdef EALIGN
905     case EALIGN: return "EALIGN";
906 #endif
907 #ifdef EALREADY
908     case EALREADY: return "operation already in progress";
909 #endif
910 #ifdef EBADE
911     case EBADE: return "bad exchange descriptor";
912 #endif
913 #ifdef EBADF
914     case EBADF: return "bad file number";
915 #endif
916 #ifdef EBADFD
917     case EBADFD: return "file descriptor in bad state";
918 #endif
919 #ifdef EBADMSG
920     case EBADMSG: return "not a data message";
921 #endif
922 #ifdef EBADR
923     case EBADR: return "bad request descriptor";
924 #endif
925 #ifdef EBADRPC
926     case EBADRPC: return "RPC structure is bad";
927 #endif
928 #ifdef EBADRQC
929     case EBADRQC: return "bad request code";
930 #endif
931 #ifdef EBADSLT
932     case EBADSLT: return "invalid slot";
933 #endif
934 #ifdef EBFONT
935     case EBFONT: return "bad font file format";
936 #endif
937 #ifdef EBUSY
938     case EBUSY: return "mount device busy";
939 #endif
940 #ifdef ECHILD
941     case ECHILD: return "no children";
942 #endif
943 #ifdef ECHRNG
944     case ECHRNG: return "channel number out of range";
945 #endif
946 #ifdef ECOMM
947     case ECOMM: return "communication error on send";
948 #endif
949 #ifdef ECONNABORTED
950     case ECONNABORTED: return "software caused connection abort";
951 #endif
952 #ifdef ECONNREFUSED
953     case ECONNREFUSED: return "connection refused";
954 #endif
955 #ifdef ECONNRESET
956     case ECONNRESET: return "connection reset by peer";
957 #endif
958 #if defined(EDEADLK) && (!defined(EWOULDBLOCK) || (EDEADLK != EWOULDBLOCK))
959     case EDEADLK: return "resource deadlock avoided";
960 #endif
961 #ifdef EDEADLOCK
962     case EDEADLOCK: return "resource deadlock avoided";
963 #endif
964 #ifdef EDESTADDRREQ
965     case EDESTADDRREQ: return "destination address required";
966 #endif
967 #ifdef EDIRTY
968     case EDIRTY: return "mounting a dirty fs w/o force";
969 #endif
970 #ifdef EDOM
971     case EDOM: return "math argument out of range";
972 #endif
973 #ifdef EDOTDOT
974     case EDOTDOT: return "cross mount point";
975 #endif
976 #ifdef EDQUOT
977     case EDQUOT: return "disk quota exceeded";
978 #endif
979 #ifdef EDUPPKG
980     case EDUPPKG: return "duplicate package name";
981 #endif
982 #ifdef EEXIST
983     case EEXIST: return "file already exists";
984 #endif
985 #ifdef EFAULT
986     case EFAULT: return "bad address in system call argument";
987 #endif
988 #ifdef EFBIG
989     case EFBIG: return "file too large";
990 #endif
991 #ifdef EHOSTDOWN
992     case EHOSTDOWN: return "host is down";
993 #endif
994 #ifdef EHOSTUNREACH
995     case EHOSTUNREACH: return "host is unreachable";
996 #endif
997 #ifdef EIDRM
998     case EIDRM: return "identifier removed";
999 #endif
1000 #ifdef EINIT
1001     case EINIT: return "initialization error";
1002 #endif
1003 #ifdef EINPROGRESS
1004     case EINPROGRESS: return "operation now in progress";
1005 #endif
1006 #ifdef EINTR
1007     case EINTR: return "interrupted system call";
1008 #endif
1009 #ifdef EINVAL
1010     case EINVAL: return "invalid argument";
1011 #endif
1012 #ifdef EIO
1013     case EIO: return "I/O error";
1014 #endif
1015 #ifdef EISCONN
1016     case EISCONN: return "socket is already connected";
1017 #endif
1018 #ifdef EISDIR
1019     case EISDIR: return "is a directory";
1020 #endif
1021 #ifdef EISNAME
1022     case EISNAM: return "is a name file";
1023 #endif
1024 #ifdef ELBIN
1025     case ELBIN: return "ELBIN";
1026 #endif
1027 #ifdef EL2HLT
1028     case EL2HLT: return "level 2 halted";
1029 #endif
1030 #ifdef EL2NSYNC
1031     case EL2NSYNC: return "level 2 not synchronized";
1032 #endif
1033 #ifdef EL3HLT
1034     case EL3HLT: return "level 3 halted";
1035 #endif
1036 #ifdef EL3RST
1037     case EL3RST: return "level 3 reset";
1038 #endif
1039 #ifdef ELIBACC
1040     case ELIBACC: return "can not access a needed shared library";
1041 #endif
1042 #ifdef ELIBBAD
1043     case ELIBBAD: return "accessing a corrupted shared library";
1044 #endif
1045 #ifdef ELIBEXEC
1046     case ELIBEXEC: return "can not exec a shared library directly";
1047 #endif
1048 #ifdef ELIBMAX
1049     case ELIBMAX: return "attempting to link in more shared libraries than system limit";
1050 #endif
1051 #ifdef ELIBSCN
1052     case ELIBSCN: return ".lib section in a.out corrupted";
1053 #endif
1054 #ifdef ELNRNG
1055     case ELNRNG: return "link number out of range";
1056 #endif
1057 #ifdef ELOOP
1058     case ELOOP: return "too many levels of symbolic links";
1059 #endif
1060 #ifdef EMFILE
1061     case EMFILE: return "too many open files";
1062 #endif
1063 #ifdef EMLINK
1064     case EMLINK: return "too many links";
1065 #endif
1066 #ifdef EMSGSIZE
1067     case EMSGSIZE: return "message too long";
1068 #endif
1069 #ifdef EMULTIHOP
1070     case EMULTIHOP: return "multihop attempted";
1071 #endif
1072 #ifdef ENAMETOOLONG
1073     case ENAMETOOLONG: return "file name too long";
1074 #endif
1075 #ifdef ENAVAIL
1076     case ENAVAIL: return "not available";
1077 #endif
1078 #ifdef ENET
1079     case ENET: return "ENET";
1080 #endif
1081 #ifdef ENETDOWN
1082     case ENETDOWN: return "network is down";
1083 #endif
1084 #ifdef ENETRESET
1085     case ENETRESET: return "network dropped connection on reset";
1086 #endif
1087 #ifdef ENETUNREACH
1088     case ENETUNREACH: return "network is unreachable";
1089 #endif
1090 #ifdef ENFILE
1091     case ENFILE: return "file table overflow";
1092 #endif
1093 #ifdef ENOANO
1094     case ENOANO: return "anode table overflow";
1095 #endif
1096 #if defined(ENOBUFS) && (!defined(ENOSR) || (ENOBUFS != ENOSR))
1097     case ENOBUFS: return "no buffer space available";
1098 #endif
1099 #ifdef ENOCSI
1100     case ENOCSI: return "no CSI structure available";
1101 #endif
1102 #ifdef ENODATA
1103     case ENODATA: return "no data available";
1104 #endif
1105 #ifdef ENODEV
1106     case ENODEV: return "no such device";
1107 #endif
1108 #ifdef ENOENT
1109     case ENOENT: return "no such file or directory";
1110 #endif
1111 #ifdef ENOEXEC
1112     case ENOEXEC: return "exec format error";
1113 #endif
1114 #ifdef ENOLCK
1115     case ENOLCK: return "no locks available";
1116 #endif
1117 #ifdef ENOLINK
1118     case ENOLINK: return "link has be severed";
1119 #endif
1120 #ifdef ENOMEM
1121     case ENOMEM: return "not enough memory";
1122 #endif
1123 #ifdef ENOMSG
1124     case ENOMSG: return "no message of desired type";
1125 #endif
1126 #ifdef ENONET
1127     case ENONET: return "machine is not on the network";
1128 #endif
1129 #ifdef ENOPKG
1130     case ENOPKG: return "package not installed";
1131 #endif
1132 #ifdef ENOPROTOOPT
1133     case ENOPROTOOPT: return "bad proocol option";
1134 #endif
1135 #ifdef ENOSPC
1136     case ENOSPC: return "no space left on device";
1137 #endif
1138 #ifdef ENOSR
1139     case ENOSR: return "out of stream resources";
1140 #endif
1141 #ifdef ENOSTR
1142     case ENOSTR: return "not a stream device";
1143 #endif
1144 #ifdef ENOSYM
1145     case ENOSYM: return "unresolved symbol name";
1146 #endif
1147 #ifdef ENOSYS
1148     case ENOSYS: return "function not implemented";
1149 #endif
1150 #ifdef ENOTBLK
1151     case ENOTBLK: return "block device required";
1152 #endif
1153 #ifdef ENOTCONN
1154     case ENOTCONN: return "socket is not connected";
1155 #endif
1156 #ifdef ENOTDIR
1157     case ENOTDIR: return "not a directory";
1158 #endif
1159 #ifdef ENOTEMPTY
1160     case ENOTEMPTY: return "directory not empty";
1161 #endif
1162 #ifdef ENOTNAM
1163     case ENOTNAM: return "not a name file";
1164 #endif
1165 #ifdef ENOTSOCK
1166     case ENOTSOCK: return "socket operation on non-socket";
1167 #endif
1168 #ifdef ENOTTY
1169     case ENOTTY: return "inappropriate device for ioctl";
1170 #endif
1171 #ifdef ENOTUNIQ
1172     case ENOTUNIQ: return "name not unique on network";
1173 #endif
1174 #ifdef ENXIO
1175     case ENXIO: return "no such device or address";
1176 #endif
1177 #ifdef EOPNOTSUPP
1178     case EOPNOTSUPP: return "operation not supported on socket";
1179 #endif
1180 #ifdef EPERM
1181     case EPERM: return "not owner";
1182 #endif
1183 #ifdef EPFNOSUPPORT
1184     case EPFNOSUPPORT: return "protocol family not supported";
1185 #endif
1186 #ifdef EPIPE
1187     case EPIPE: return "broken pipe";
1188 #endif
1189 #ifdef EPROCLIM
1190     case EPROCLIM: return "too many processes";
1191 #endif
1192 #ifdef EPROCUNAVAIL
1193     case EPROCUNAVAIL: return "bad procedure for program";
1194 #endif
1195 #ifdef EPROGMISMATCH
1196     case EPROGMISMATCH: return "program version wrong";
1197 #endif
1198 #ifdef EPROGUNAVAIL
1199     case EPROGUNAVAIL: return "RPC program not available";
1200 #endif
1201 #ifdef EPROTO
1202     case EPROTO: return "protocol error";
1203 #endif
1204 #ifdef EPROTONOSUPPORT
1205     case EPROTONOSUPPORT: return "protocol not suppored";
1206 #endif
1207 #ifdef EPROTOTYPE
1208     case EPROTOTYPE: return "protocol wrong type for socket";
1209 #endif
1210 #ifdef ERANGE
1211     case ERANGE: return "math result unrepresentable";
1212 #endif
1213 #if defined(EREFUSED) && (!defined(ECONNREFUSED) || (EREFUSED != ECONNREFUSED))
1214     case EREFUSED: return "EREFUSED";
1215 #endif
1216 #ifdef EREMCHG
1217     case EREMCHG: return "remote address changed";
1218 #endif
1219 #ifdef EREMDEV
1220     case EREMDEV: return "remote device";
1221 #endif
1222 #ifdef EREMOTE
1223     case EREMOTE: return "pathname hit remote file system";
1224 #endif
1225 #ifdef EREMOTEIO
1226     case EREMOTEIO: return "remote i/o error";
1227 #endif
1228 #ifdef EREMOTERELEASE
1229     case EREMOTERELEASE: return "EREMOTERELEASE";
1230 #endif
1231 #ifdef EROFS
1232     case EROFS: return "read-only file system";
1233 #endif
1234 #ifdef ERPCMISMATCH
1235     case ERPCMISMATCH: return "RPC version is wrong";
1236 #endif
1237 #ifdef ERREMOTE
1238     case ERREMOTE: return "object is remote";
1239 #endif
1240 #ifdef ESHUTDOWN
1241     case ESHUTDOWN: return "can't send afer socket shutdown";
1242 #endif
1243 #ifdef ESOCKTNOSUPPORT
1244     case ESOCKTNOSUPPORT: return "socket type not supported";
1245 #endif
1246 #ifdef ESPIPE
1247     case ESPIPE: return "invalid seek";
1248 #endif
1249 #ifdef ESRCH
1250     case ESRCH: return "no such process";
1251 #endif
1252 #ifdef ESRMNT
1253     case ESRMNT: return "srmount error";
1254 #endif
1255 #ifdef ESTALE
1256     case ESTALE: return "stale remote file handle";
1257 #endif
1258 #ifdef ESUCCESS
1259     case ESUCCESS: return "Error 0";
1260 #endif
1261 #ifdef ETIME
1262     case ETIME: return "timer expired";
1263 #endif
1264 #ifdef ETIMEDOUT
1265     case ETIMEDOUT: return "connection timed out";
1266 #endif
1267 #ifdef ETOOMANYREFS
1268     case ETOOMANYREFS: return "too many references: can't splice";
1269 #endif
1270 #ifdef ETXTBSY
1271     case ETXTBSY: return "text file or pseudo-device busy";
1272 #endif
1273 #ifdef EUCLEAN
1274     case EUCLEAN: return "structure needs cleaning";
1275 #endif
1276 #ifdef EUNATCH
1277     case EUNATCH: return "protocol driver not attached";
1278 #endif
1279 #ifdef EUSERS
1280     case EUSERS: return "too many users";
1281 #endif
1282 #ifdef EVERSION
1283     case EVERSION: return "version mismatch";
1284 #endif
1285 #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
1286     case EWOULDBLOCK: return "operation would block";
1287 #endif
1288 #ifdef EXDEV
1289     case EXDEV: return "cross-domain link";
1290 #endif
1291 #ifdef EXFULL
1292     case EXFULL: return "message tables full";
1293 #endif
1294     }
1295 #else /* NO_SYS_ERRLIST */
1296   extern int sys_nerr;
1297   extern char *sys_errlist[];
1298
1299   if ((errnum > 0) && (errnum <= sys_nerr))
1300     return sys_errlist [errnum];
1301 #endif /* NO_SYS_ERRLIST */
1302
1303   msg = g_static_private_get (&msg_private);
1304   if (!msg)
1305     {
1306       msg = g_new (gchar, 64);
1307       g_static_private_set (&msg_private, msg, g_free);
1308     }
1309
1310   _g_sprintf (msg, "unknown error (%d)", errnum);
1311
1312   errno = saved_errno;
1313   return msg;
1314 }
1315
1316 G_CONST_RETURN gchar*
1317 g_strsignal (gint signum)
1318 {
1319   static GStaticPrivate msg_private = G_STATIC_PRIVATE_INIT;
1320   char *msg;
1321
1322 #ifdef HAVE_STRSIGNAL
1323   const char *msg_locale;
1324   
1325 #if defined(G_OS_BEOS) || defined(G_WITH_CYGWIN)
1326 extern const char *strsignal(int);
1327 #else
1328   /* this is declared differently (const) in string.h on BeOS */
1329   extern char *strsignal (int sig);
1330 #endif /* !G_OS_BEOS && !G_WITH_CYGWIN */
1331   msg_locale = strsignal (signum);
1332   if (g_get_charset (NULL))
1333     return msg_locale;
1334   else
1335     {
1336       gchar *msg_utf8 = g_locale_to_utf8 (msg_locale, -1, NULL, NULL, NULL);
1337       if (msg_utf8)
1338         {
1339           /* Stick in the quark table so that we can return a static result
1340            */
1341           GQuark msg_quark = g_quark_from_string (msg_utf8);
1342           g_free (msg_utf8);
1343           
1344           return g_quark_to_string (msg_quark);
1345         }
1346     }
1347 #elif NO_SYS_SIGLIST
1348   switch (signum)
1349     {
1350 #ifdef SIGHUP
1351     case SIGHUP: return "Hangup";
1352 #endif
1353 #ifdef SIGINT
1354     case SIGINT: return "Interrupt";
1355 #endif
1356 #ifdef SIGQUIT
1357     case SIGQUIT: return "Quit";
1358 #endif
1359 #ifdef SIGILL
1360     case SIGILL: return "Illegal instruction";
1361 #endif
1362 #ifdef SIGTRAP
1363     case SIGTRAP: return "Trace/breakpoint trap";
1364 #endif
1365 #ifdef SIGABRT
1366     case SIGABRT: return "IOT trap/Abort";
1367 #endif
1368 #ifdef SIGBUS
1369     case SIGBUS: return "Bus error";
1370 #endif
1371 #ifdef SIGFPE
1372     case SIGFPE: return "Floating point exception";
1373 #endif
1374 #ifdef SIGKILL
1375     case SIGKILL: return "Killed";
1376 #endif
1377 #ifdef SIGUSR1
1378     case SIGUSR1: return "User defined signal 1";
1379 #endif
1380 #ifdef SIGSEGV
1381     case SIGSEGV: return "Segmentation fault";
1382 #endif
1383 #ifdef SIGUSR2
1384     case SIGUSR2: return "User defined signal 2";
1385 #endif
1386 #ifdef SIGPIPE
1387     case SIGPIPE: return "Broken pipe";
1388 #endif
1389 #ifdef SIGALRM
1390     case SIGALRM: return "Alarm clock";
1391 #endif
1392 #ifdef SIGTERM
1393     case SIGTERM: return "Terminated";
1394 #endif
1395 #ifdef SIGSTKFLT
1396     case SIGSTKFLT: return "Stack fault";
1397 #endif
1398 #ifdef SIGCHLD
1399     case SIGCHLD: return "Child exited";
1400 #endif
1401 #ifdef SIGCONT
1402     case SIGCONT: return "Continued";
1403 #endif
1404 #ifdef SIGSTOP
1405     case SIGSTOP: return "Stopped (signal)";
1406 #endif
1407 #ifdef SIGTSTP
1408     case SIGTSTP: return "Stopped";
1409 #endif
1410 #ifdef SIGTTIN
1411     case SIGTTIN: return "Stopped (tty input)";
1412 #endif
1413 #ifdef SIGTTOU
1414     case SIGTTOU: return "Stopped (tty output)";
1415 #endif
1416 #ifdef SIGURG
1417     case SIGURG: return "Urgent condition";
1418 #endif
1419 #ifdef SIGXCPU
1420     case SIGXCPU: return "CPU time limit exceeded";
1421 #endif
1422 #ifdef SIGXFSZ
1423     case SIGXFSZ: return "File size limit exceeded";
1424 #endif
1425 #ifdef SIGVTALRM
1426     case SIGVTALRM: return "Virtual time alarm";
1427 #endif
1428 #ifdef SIGPROF
1429     case SIGPROF: return "Profile signal";
1430 #endif
1431 #ifdef SIGWINCH
1432     case SIGWINCH: return "Window size changed";
1433 #endif
1434 #ifdef SIGIO
1435     case SIGIO: return "Possible I/O";
1436 #endif
1437 #ifdef SIGPWR
1438     case SIGPWR: return "Power failure";
1439 #endif
1440 #ifdef SIGUNUSED
1441     case SIGUNUSED: return "Unused signal";
1442 #endif
1443     }
1444 #else /* NO_SYS_SIGLIST */
1445
1446 #ifdef NO_SYS_SIGLIST_DECL
1447   extern char *sys_siglist[];   /*(see Tue Jan 19 00:44:24 1999 in changelog)*/
1448 #endif
1449
1450   return (char*) /* this function should return const --josh */ sys_siglist [signum];
1451 #endif /* NO_SYS_SIGLIST */
1452
1453   msg = g_static_private_get (&msg_private);
1454   if (!msg)
1455     {
1456       msg = g_new (gchar, 64);
1457       g_static_private_set (&msg_private, msg, g_free);
1458     }
1459
1460   _g_sprintf (msg, "unknown signal (%d)", signum);
1461   
1462   return msg;
1463 }
1464
1465 /* Functions g_strlcpy and g_strlcat were originally developed by
1466  * Todd C. Miller <Todd.Miller@courtesan.com> to simplify writing secure code.
1467  * See ftp://ftp.openbsd.org/pub/OpenBSD/src/lib/libc/string/strlcpy.3
1468  * for more information.
1469  */
1470
1471 #ifdef HAVE_STRLCPY
1472 /* Use the native ones, if available; they might be implemented in assembly */
1473 gsize
1474 g_strlcpy (gchar       *dest,
1475            const gchar *src,
1476            gsize        dest_size)
1477 {
1478   g_return_val_if_fail (dest != NULL, 0);
1479   g_return_val_if_fail (src  != NULL, 0);
1480   
1481   return strlcpy (dest, src, dest_size);
1482 }
1483
1484 gsize
1485 g_strlcat (gchar       *dest,
1486            const gchar *src,
1487            gsize        dest_size)
1488 {
1489   g_return_val_if_fail (dest != NULL, 0);
1490   g_return_val_if_fail (src  != NULL, 0);
1491   
1492   return strlcat (dest, src, dest_size);
1493 }
1494
1495 #else /* ! HAVE_STRLCPY */
1496 /* g_strlcpy
1497  *
1498  * Copy string src to buffer dest (of buffer size dest_size).  At most
1499  * dest_size-1 characters will be copied.  Always NUL terminates
1500  * (unless dest_size == 0).  This function does NOT allocate memory.
1501  * Unlike strncpy, this function doesn't pad dest (so it's often faster).
1502  * Returns size of attempted result, strlen(src),
1503  * so if retval >= dest_size, truncation occurred.
1504  */
1505 gsize
1506 g_strlcpy (gchar       *dest,
1507            const gchar *src,
1508            gsize        dest_size)
1509 {
1510   register gchar *d = dest;
1511   register const gchar *s = src;
1512   register gsize n = dest_size;
1513   
1514   g_return_val_if_fail (dest != NULL, 0);
1515   g_return_val_if_fail (src  != NULL, 0);
1516   
1517   /* Copy as many bytes as will fit */
1518   if (n != 0 && --n != 0)
1519     do
1520       {
1521         register gchar c = *s++;
1522         
1523         *d++ = c;
1524         if (c == 0)
1525           break;
1526       }
1527     while (--n != 0);
1528   
1529   /* If not enough room in dest, add NUL and traverse rest of src */
1530   if (n == 0)
1531     {
1532       if (dest_size != 0)
1533         *d = 0;
1534       while (*s++)
1535         ;
1536     }
1537   
1538   return s - src - 1;  /* count does not include NUL */
1539 }
1540
1541 /* g_strlcat
1542  *
1543  * Appends string src to buffer dest (of buffer size dest_size).
1544  * At most dest_size-1 characters will be copied.
1545  * Unlike strncat, dest_size is the full size of dest, not the space left over.
1546  * This function does NOT allocate memory.
1547  * This always NUL terminates (unless siz == 0 or there were no NUL characters
1548  * in the dest_size characters of dest to start with).
1549  * Returns size of attempted result, which is
1550  * MIN (dest_size, strlen (original dest)) + strlen (src),
1551  * so if retval >= dest_size, truncation occurred.
1552  */
1553 gsize
1554 g_strlcat (gchar       *dest,
1555            const gchar *src,
1556            gsize        dest_size)
1557 {
1558   register gchar *d = dest;
1559   register const gchar *s = src;
1560   register gsize bytes_left = dest_size;
1561   gsize dlength;  /* Logically, MIN (strlen (d), dest_size) */
1562   
1563   g_return_val_if_fail (dest != NULL, 0);
1564   g_return_val_if_fail (src  != NULL, 0);
1565   
1566   /* Find the end of dst and adjust bytes left but don't go past end */
1567   while (*d != 0 && bytes_left-- != 0)
1568     d++;
1569   dlength = d - dest;
1570   bytes_left = dest_size - dlength;
1571   
1572   if (bytes_left == 0)
1573     return dlength + strlen (s);
1574   
1575   while (*s != 0)
1576     {
1577       if (bytes_left != 1)
1578         {
1579           *d++ = *s;
1580           bytes_left--;
1581         }
1582       s++;
1583     }
1584   *d = 0;
1585   
1586   return dlength + (s - src);  /* count does not include NUL */
1587 }
1588 #endif /* ! HAVE_STRLCPY */
1589
1590 /**
1591  * g_ascii_strdown:
1592  * @str: a string.
1593  * @len: length of @str in bytes, or -1 if @str is nul-terminated.
1594  * 
1595  * Converts all upper case ASCII letters to lower case ASCII letters.
1596  * 
1597  * Return value: a newly-allocated string, with all the upper case
1598  *               characters in @str converted to lower case, with
1599  *               semantics that exactly match g_ascii_tolower(). (Note
1600  *               that this is unlike the old g_strdown(), which modified
1601  *               the string in place.)
1602  **/
1603 gchar*
1604 g_ascii_strdown (const gchar *str,
1605                  gssize       len)
1606 {
1607   gchar *result, *s;
1608   
1609   g_return_val_if_fail (str != NULL, NULL);
1610
1611   if (len < 0)
1612     len = strlen (str);
1613
1614   result = g_strndup (str, len);
1615   for (s = result; *s; s++)
1616     *s = g_ascii_tolower (*s);
1617   
1618   return result;
1619 }
1620
1621 /**
1622  * g_ascii_strup:
1623  * @str: a string.
1624  * @len: length of @str in bytes, or -1 if @str is nul-terminated.
1625  * 
1626  * Converts all lower case ASCII letters to upper case ASCII letters.
1627  * 
1628  * Return value: a newly allocated string, with all the lower case
1629  *               characters in @str converted to upper case, with
1630  *               semantics that exactly match g_ascii_toupper(). (Note
1631  *               that this is unlike the old g_strup(), which modified
1632  *               the string in place.)
1633  **/
1634 gchar*
1635 g_ascii_strup (const gchar *str,
1636                gssize       len)
1637 {
1638   gchar *result, *s;
1639
1640   g_return_val_if_fail (str != NULL, NULL);
1641
1642   if (len < 0)
1643     len = strlen (str);
1644
1645   result = g_strndup (str, len);
1646   for (s = result; *s; s++)
1647     *s = g_ascii_toupper (*s);
1648
1649   return result;
1650 }
1651
1652 /**
1653  * g_strdown:
1654  * @string: the string to convert.
1655  * 
1656  * Converts a string to lower case.  
1657  * 
1658  * Return value: the string 
1659  *
1660  * Deprecated:2.2: This function is totally broken for the reasons discussed 
1661  * in the g_strncasecmp() docs - use g_ascii_strdown() or g_utf8_strdown() 
1662  * instead.
1663  **/
1664 gchar*
1665 g_strdown (gchar *string)
1666 {
1667   register guchar *s;
1668   
1669   g_return_val_if_fail (string != NULL, NULL);
1670   
1671   s = (guchar *) string;
1672   
1673   while (*s)
1674     {
1675       if (isupper (*s))
1676         *s = tolower (*s);
1677       s++;
1678     }
1679   
1680   return (gchar *) string;
1681 }
1682
1683 /**
1684  * g_strup:
1685  * @string: the string to convert.
1686  * 
1687  * Converts a string to upper case. 
1688  * 
1689  * Return value: the string
1690  *
1691  * Deprecated:2.2: This function is totally broken for the reasons discussed 
1692  * in the g_strncasecmp() docs - use g_ascii_strup() or g_utf8_strup() instead.
1693  **/
1694 gchar*
1695 g_strup (gchar *string)
1696 {
1697   register guchar *s;
1698
1699   g_return_val_if_fail (string != NULL, NULL);
1700
1701   s = (guchar *) string;
1702
1703   while (*s)
1704     {
1705       if (islower (*s))
1706         *s = toupper (*s);
1707       s++;
1708     }
1709
1710   return (gchar *) string;
1711 }
1712
1713 gchar*
1714 g_strreverse (gchar *string)
1715 {
1716   g_return_val_if_fail (string != NULL, NULL);
1717
1718   if (*string)
1719     {
1720       register gchar *h, *t;
1721
1722       h = string;
1723       t = string + strlen (string) - 1;
1724
1725       while (h < t)
1726         {
1727           register gchar c;
1728
1729           c = *h;
1730           *h = *t;
1731           h++;
1732           *t = c;
1733           t--;
1734         }
1735     }
1736
1737   return string;
1738 }
1739
1740 /**
1741  * g_ascii_tolower:
1742  * @c: any character.
1743  * 
1744  * Convert a character to ASCII lower case.
1745  *
1746  * Unlike the standard C library tolower() function, this only
1747  * recognizes standard ASCII letters and ignores the locale, returning
1748  * all non-ASCII characters unchanged, even if they are lower case
1749  * letters in a particular character set. Also unlike the standard
1750  * library function, this takes and returns a char, not an int, so
1751  * don't call it on %EOF but no need to worry about casting to #guchar
1752  * before passing a possibly non-ASCII character in.
1753  * 
1754  * Return value: the result of converting @c to lower case.
1755  *               If @c is not an ASCII upper case letter,
1756  *               @c is returned unchanged.
1757  **/
1758 gchar
1759 g_ascii_tolower (gchar c)
1760 {
1761   return g_ascii_isupper (c) ? c - 'A' + 'a' : c;
1762 }
1763
1764 /**
1765  * g_ascii_toupper:
1766  * @c: any character.
1767  * 
1768  * Convert a character to ASCII upper case.
1769  *
1770  * Unlike the standard C library toupper() function, this only
1771  * recognizes standard ASCII letters and ignores the locale, returning
1772  * all non-ASCII characters unchanged, even if they are upper case
1773  * letters in a particular character set. Also unlike the standard
1774  * library function, this takes and returns a char, not an int, so
1775  * don't call it on %EOF but no need to worry about casting to #guchar
1776  * before passing a possibly non-ASCII character in.
1777  * 
1778  * Return value: the result of converting @c to upper case.
1779  *               If @c is not an ASCII lower case letter,
1780  *               @c is returned unchanged.
1781  **/
1782 gchar
1783 g_ascii_toupper (gchar c)
1784 {
1785   return g_ascii_islower (c) ? c - 'a' + 'A' : c;
1786 }
1787
1788 /**
1789  * g_ascii_digit_value:
1790  * @c: an ASCII character.
1791  *
1792  * Determines the numeric value of a character as a decimal
1793  * digit. Differs from g_unichar_digit_value() because it takes
1794  * a char, so there's no worry about sign extension if characters
1795  * are signed.
1796  *
1797  * Return value: If @c is a decimal digit (according to
1798  * g_ascii_isdigit()), its numeric value. Otherwise, -1.
1799  **/
1800 int
1801 g_ascii_digit_value (gchar c)
1802 {
1803   if (g_ascii_isdigit (c))
1804     return c - '0';
1805   return -1;
1806 }
1807
1808 /**
1809  * g_ascii_xdigit_value:
1810  * @c: an ASCII character.
1811  *
1812  * Determines the numeric value of a character as a hexidecimal
1813  * digit. Differs from g_unichar_xdigit_value() because it takes
1814  * a char, so there's no worry about sign extension if characters
1815  * are signed.
1816  *
1817  * Return value: If @c is a hex digit (according to
1818  * g_ascii_isxdigit()), its numeric value. Otherwise, -1.
1819  **/
1820 int
1821 g_ascii_xdigit_value (gchar c)
1822 {
1823   if (c >= 'A' && c <= 'F')
1824     return c - 'A' + 10;
1825   if (c >= 'a' && c <= 'f')
1826     return c - 'a' + 10;
1827   return g_ascii_digit_value (c);
1828 }
1829
1830 /**
1831  * g_ascii_strcasecmp:
1832  * @s1: string to compare with @s2.
1833  * @s2: string to compare with @s1.
1834  * 
1835  * Compare two strings, ignoring the case of ASCII characters.
1836  *
1837  * Unlike the BSD strcasecmp() function, this only recognizes standard
1838  * ASCII letters and ignores the locale, treating all non-ASCII
1839  * bytes as if they are not letters.
1840  *
1841  * This function should be used only on strings that are known to be
1842  * in encodings where the bytes corresponding to ASCII letters always
1843  * represent themselves. This includes UTF-8 and the ISO-8859-*
1844  * charsets, but not for instance double-byte encodings like the
1845  * Windows Codepage 932, where the trailing bytes of double-byte
1846  * characters include all ASCII letters. If you compare two CP932
1847  * strings using this function, you will get false matches.
1848  *
1849  * Return value: 0 if the strings match, a negative value if @s1 &lt; @s2, 
1850  *   or a positive value if @s1 &gt; @s2.
1851  **/
1852 gint
1853 g_ascii_strcasecmp (const gchar *s1,
1854                     const gchar *s2)
1855 {
1856   gint c1, c2;
1857
1858   g_return_val_if_fail (s1 != NULL, 0);
1859   g_return_val_if_fail (s2 != NULL, 0);
1860
1861   while (*s1 && *s2)
1862     {
1863       c1 = (gint)(guchar) TOLOWER (*s1);
1864       c2 = (gint)(guchar) TOLOWER (*s2);
1865       if (c1 != c2)
1866         return (c1 - c2);
1867       s1++; s2++;
1868     }
1869
1870   return (((gint)(guchar) *s1) - ((gint)(guchar) *s2));
1871 }
1872
1873 /**
1874  * g_ascii_strncasecmp:
1875  * @s1: string to compare with @s2.
1876  * @s2: string to compare with @s1.
1877  * @n:  number of characters to compare.
1878  * 
1879  * Compare @s1 and @s2, ignoring the case of ASCII characters and any
1880  * characters after the first @n in each string.
1881  *
1882  * Unlike the BSD strcasecmp() function, this only recognizes standard
1883  * ASCII letters and ignores the locale, treating all non-ASCII
1884  * characters as if they are not letters.
1885  * 
1886  * The same warning as in g_ascii_strcasecmp() applies: Use this
1887  * function only on strings known to be in encodings where bytes
1888  * corresponding to ASCII letters always represent themselves.
1889  *
1890  * Return value: 0 if the strings match, a negative value if @s1 &lt; @s2, 
1891  *   or a positive value if @s1 &gt; @s2.
1892  **/
1893 gint
1894 g_ascii_strncasecmp (const gchar *s1,
1895                      const gchar *s2,
1896                      gsize n)
1897 {
1898   gint c1, c2;
1899
1900   g_return_val_if_fail (s1 != NULL, 0);
1901   g_return_val_if_fail (s2 != NULL, 0);
1902
1903   while (n && *s1 && *s2)
1904     {
1905       n -= 1;
1906       c1 = (gint)(guchar) TOLOWER (*s1);
1907       c2 = (gint)(guchar) TOLOWER (*s2);
1908       if (c1 != c2)
1909         return (c1 - c2);
1910       s1++; s2++;
1911     }
1912
1913   if (n)
1914     return (((gint) (guchar) *s1) - ((gint) (guchar) *s2));
1915   else
1916     return 0;
1917 }
1918
1919 /**
1920  * g_strcasecmp:
1921  * @s1: a string.
1922  * @s2: a string to compare with @s1.
1923  * 
1924  * A case-insensitive string comparison, corresponding to the standard
1925  * strcasecmp() function on platforms which support it.
1926  *
1927  * Return value: 0 if the strings match, a negative value if @s1 &lt; @s2, 
1928  *   or a positive value if @s1 &gt; @s2.
1929  *
1930  * Deprecated:2.2: See g_strncasecmp() for a discussion of why this function 
1931  *   is deprecated and how to replace it.
1932  **/
1933 gint
1934 g_strcasecmp (const gchar *s1,
1935               const gchar *s2)
1936 {
1937 #ifdef HAVE_STRCASECMP
1938   g_return_val_if_fail (s1 != NULL, 0);
1939   g_return_val_if_fail (s2 != NULL, 0);
1940
1941   return strcasecmp (s1, s2);
1942 #else
1943   gint c1, c2;
1944
1945   g_return_val_if_fail (s1 != NULL, 0);
1946   g_return_val_if_fail (s2 != NULL, 0);
1947
1948   while (*s1 && *s2)
1949     {
1950       /* According to A. Cox, some platforms have islower's that
1951        * don't work right on non-uppercase
1952        */
1953       c1 = isupper ((guchar)*s1) ? tolower ((guchar)*s1) : *s1;
1954       c2 = isupper ((guchar)*s2) ? tolower ((guchar)*s2) : *s2;
1955       if (c1 != c2)
1956         return (c1 - c2);
1957       s1++; s2++;
1958     }
1959
1960   return (((gint)(guchar) *s1) - ((gint)(guchar) *s2));
1961 #endif
1962 }
1963
1964 /**
1965  * g_strncasecmp:
1966  * @s1: a string.
1967  * @s2: a string to compare with @s1.
1968  * @n: the maximum number of characters to compare.
1969  * 
1970  * A case-insensitive string comparison, corresponding to the standard
1971  * strncasecmp() function on platforms which support it.
1972  * It is similar to g_strcasecmp() except it only compares the first @n 
1973  * characters of the strings.
1974  * 
1975  * Return value: 0 if the strings match, a negative value if @s1 &lt; @s2, 
1976  *   or a positive value if @s1 &gt; @s2.
1977  *
1978  * Deprecated:2.2: The problem with g_strncasecmp() is that it does the 
1979  * comparison by calling toupper()/tolower(). These functions are
1980  * locale-specific and operate on single bytes. However, it is impossible
1981  * to handle things correctly from an I18N standpoint by operating on
1982  * bytes, since characters may be multibyte. Thus g_strncasecmp() is
1983  * broken if your string is guaranteed to be ASCII, since it's
1984  * locale-sensitive, and it's broken if your string is localized, since
1985  * it doesn't work on many encodings at all, including UTF-8, EUC-JP,
1986  * etc.
1987  *
1988  * There are therefore two replacement functions: g_ascii_strncasecmp(),
1989  * which only works on ASCII and is not locale-sensitive, and
1990  * g_utf8_casefold(), which is good for case-insensitive sorting of UTF-8.
1991  **/
1992 gint
1993 g_strncasecmp (const gchar *s1,
1994                const gchar *s2,
1995                guint n)     
1996 {
1997 #ifdef HAVE_STRNCASECMP
1998   return strncasecmp (s1, s2, n);
1999 #else
2000   gint c1, c2;
2001
2002   g_return_val_if_fail (s1 != NULL, 0);
2003   g_return_val_if_fail (s2 != NULL, 0);
2004
2005   while (n && *s1 && *s2)
2006     {
2007       n -= 1;
2008       /* According to A. Cox, some platforms have islower's that
2009        * don't work right on non-uppercase
2010        */
2011       c1 = isupper ((guchar)*s1) ? tolower ((guchar)*s1) : *s1;
2012       c2 = isupper ((guchar)*s2) ? tolower ((guchar)*s2) : *s2;
2013       if (c1 != c2)
2014         return (c1 - c2);
2015       s1++; s2++;
2016     }
2017
2018   if (n)
2019     return (((gint) (guchar) *s1) - ((gint) (guchar) *s2));
2020   else
2021     return 0;
2022 #endif
2023 }
2024
2025 gchar*
2026 g_strdelimit (gchar       *string,
2027               const gchar *delimiters,
2028               gchar        new_delim)
2029 {
2030   register gchar *c;
2031
2032   g_return_val_if_fail (string != NULL, NULL);
2033
2034   if (!delimiters)
2035     delimiters = G_STR_DELIMITERS;
2036
2037   for (c = string; *c; c++)
2038     {
2039       if (strchr (delimiters, *c))
2040         *c = new_delim;
2041     }
2042
2043   return string;
2044 }
2045
2046 gchar*
2047 g_strcanon (gchar       *string,
2048             const gchar *valid_chars,
2049             gchar        substitutor)
2050 {
2051   register gchar *c;
2052
2053   g_return_val_if_fail (string != NULL, NULL);
2054   g_return_val_if_fail (valid_chars != NULL, NULL);
2055
2056   for (c = string; *c; c++)
2057     {
2058       if (!strchr (valid_chars, *c))
2059         *c = substitutor;
2060     }
2061
2062   return string;
2063 }
2064
2065 gchar*
2066 g_strcompress (const gchar *source)
2067 {
2068   const gchar *p = source, *octal;
2069   gchar *dest = g_malloc (strlen (source) + 1);
2070   gchar *q = dest;
2071   
2072   while (*p)
2073     {
2074       if (*p == '\\')
2075         {
2076           p++;
2077           switch (*p)
2078             {
2079             case '\0':
2080               g_warning ("g_strcompress: trailing \\");
2081               goto out;
2082             case '0':  case '1':  case '2':  case '3':  case '4':
2083             case '5':  case '6':  case '7':
2084               *q = 0;
2085               octal = p;
2086               while ((p < octal + 3) && (*p >= '0') && (*p <= '7'))
2087                 {
2088                   *q = (*q * 8) + (*p - '0');
2089                   p++;
2090                 }
2091               q++;
2092               p--;
2093               break;
2094             case 'b':
2095               *q++ = '\b';
2096               break;
2097             case 'f':
2098               *q++ = '\f';
2099               break;
2100             case 'n':
2101               *q++ = '\n';
2102               break;
2103             case 'r':
2104               *q++ = '\r';
2105               break;
2106             case 't':
2107               *q++ = '\t';
2108               break;
2109             default:            /* Also handles \" and \\ */
2110               *q++ = *p;
2111               break;
2112             }
2113         }
2114       else
2115         *q++ = *p;
2116       p++;
2117     }
2118 out:
2119   *q = 0;
2120   
2121   return dest;
2122 }
2123
2124 gchar *
2125 g_strescape (const gchar *source,
2126              const gchar *exceptions)
2127 {
2128   const guchar *p;
2129   gchar *dest;
2130   gchar *q;
2131   guchar excmap[256];
2132   
2133   g_return_val_if_fail (source != NULL, NULL);
2134
2135   p = (guchar *) source;
2136   /* Each source byte needs maximally four destination chars (\777) */
2137   q = dest = g_malloc (strlen (source) * 4 + 1);
2138
2139   memset (excmap, 0, 256);
2140   if (exceptions)
2141     {
2142       guchar *e = (guchar *) exceptions;
2143
2144       while (*e)
2145         {
2146           excmap[*e] = 1;
2147           e++;
2148         }
2149     }
2150
2151   while (*p)
2152     {
2153       if (excmap[*p])
2154         *q++ = *p;
2155       else
2156         {
2157           switch (*p)
2158             {
2159             case '\b':
2160               *q++ = '\\';
2161               *q++ = 'b';
2162               break;
2163             case '\f':
2164               *q++ = '\\';
2165               *q++ = 'f';
2166               break;
2167             case '\n':
2168               *q++ = '\\';
2169               *q++ = 'n';
2170               break;
2171             case '\r':
2172               *q++ = '\\';
2173               *q++ = 'r';
2174               break;
2175             case '\t':
2176               *q++ = '\\';
2177               *q++ = 't';
2178               break;
2179             case '\\':
2180               *q++ = '\\';
2181               *q++ = '\\';
2182               break;
2183             case '"':
2184               *q++ = '\\';
2185               *q++ = '"';
2186               break;
2187             default:
2188               if ((*p < ' ') || (*p >= 0177))
2189                 {
2190                   *q++ = '\\';
2191                   *q++ = '0' + (((*p) >> 6) & 07);
2192                   *q++ = '0' + (((*p) >> 3) & 07);
2193                   *q++ = '0' + ((*p) & 07);
2194                 }
2195               else
2196                 *q++ = *p;
2197               break;
2198             }
2199         }
2200       p++;
2201     }
2202   *q = 0;
2203   return dest;
2204 }
2205
2206 gchar*
2207 g_strchug (gchar *string)
2208 {
2209   guchar *start;
2210
2211   g_return_val_if_fail (string != NULL, NULL);
2212
2213   for (start = (guchar*) string; *start && g_ascii_isspace (*start); start++)
2214     ;
2215
2216   g_memmove (string, start, strlen ((gchar *) start) + 1);
2217
2218   return string;
2219 }
2220
2221 gchar*
2222 g_strchomp (gchar *string)
2223 {
2224   gsize len;
2225
2226   g_return_val_if_fail (string != NULL, NULL);
2227
2228   len = strlen (string);
2229   while (len--)
2230     {
2231       if (g_ascii_isspace ((guchar) string[len]))
2232         string[len] = '\0';
2233       else
2234         break;
2235     }
2236
2237   return string;
2238 }
2239
2240 /**
2241  * g_strsplit:
2242  * @string: a string to split.
2243  * @delimiter: a string which specifies the places at which to split the string.
2244  *     The delimiter is not included in any of the resulting strings, unless
2245  *     @max_tokens is reached.
2246  * @max_tokens: the maximum number of pieces to split @string into. If this is
2247  *              less than 1, the string is split completely.
2248  * 
2249  * Splits a string into a maximum of @max_tokens pieces, using the given
2250  * @delimiter. If @max_tokens is reached, the remainder of @string is appended
2251  * to the last token. 
2252  *
2253  * As a special case, the result of splitting the empty string "" is an empty
2254  * vector, not a vector containing a single string. The reason for this
2255  * special case is that being able to represent a empty vector is typically
2256  * more useful than consistent handling of empty elements. If you do need
2257  * to represent empty elements, you'll need to check for the empty string
2258  * before calling g_strsplit().
2259  * 
2260  * Return value: a newly-allocated %NULL-terminated array of strings. Use 
2261  *    g_strfreev() to free it.
2262  **/
2263 gchar**
2264 g_strsplit (const gchar *string,
2265             const gchar *delimiter,
2266             gint         max_tokens)
2267 {
2268   GSList *string_list = NULL, *slist;
2269   gchar **str_array, *s;
2270   guint n = 0;
2271   const gchar *remainder;
2272
2273   g_return_val_if_fail (string != NULL, NULL);
2274   g_return_val_if_fail (delimiter != NULL, NULL);
2275   g_return_val_if_fail (delimiter[0] != '\0', NULL);
2276
2277   if (max_tokens < 1)
2278     max_tokens = G_MAXINT;
2279
2280   remainder = string;
2281   s = strstr (remainder, delimiter);
2282   if (s)
2283     {
2284       gsize delimiter_len = strlen (delimiter);   
2285
2286       while (--max_tokens && s)
2287         {
2288           gsize len;     
2289           gchar *new_string;
2290
2291           len = s - remainder;
2292           new_string = g_new (gchar, len + 1);
2293           strncpy (new_string, remainder, len);
2294           new_string[len] = 0;
2295           string_list = g_slist_prepend (string_list, new_string);
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"