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