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