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