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