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