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