Add g_strtod & co.
[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 (isspace ((guchar)*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 (isxdigit ((guchar)*p))
382             p++;
383           
384           if (*p == '.')
385             {
386               decimal_point_pos = p++;
387               
388               while (isxdigit ((guchar)*p))
389                 p++;
390               
391               if (*p == 'p' || *p == 'P')
392                 p++;
393               if (*p == '+' || *p == '-')
394                 p++;
395               while (isdigit ((guchar)*p))
396                 p++;
397               end = p;
398             }
399         }
400       else
401         {
402           while (isdigit ((guchar)*p))
403             p++;
404           
405           if (*p == '.')
406             {
407               decimal_point_pos = p++;
408               
409               while (isdigit ((guchar)*p))
410                 p++;
411               
412               if (*p == 'e' || *p == 'E')
413                 p++;
414               if (*p == '+' || *p == '-')
415                 p++;
416               while (isdigit ((guchar)*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   return strerror (errnum);
590 #elif NO_SYS_ERRLIST
591   switch (errnum)
592     {
593 #ifdef E2BIG
594     case E2BIG: return "argument list too long";
595 #endif
596 #ifdef EACCES
597     case EACCES: return "permission denied";
598 #endif
599 #ifdef EADDRINUSE
600     case EADDRINUSE: return "address already in use";
601 #endif
602 #ifdef EADDRNOTAVAIL
603     case EADDRNOTAVAIL: return "can't assign requested address";
604 #endif
605 #ifdef EADV
606     case EADV: return "advertise error";
607 #endif
608 #ifdef EAFNOSUPPORT
609     case EAFNOSUPPORT: return "address family not supported by protocol family";
610 #endif
611 #ifdef EAGAIN
612     case EAGAIN: return "try again";
613 #endif
614 #ifdef EALIGN
615     case EALIGN: return "EALIGN";
616 #endif
617 #ifdef EALREADY
618     case EALREADY: return "operation already in progress";
619 #endif
620 #ifdef EBADE
621     case EBADE: return "bad exchange descriptor";
622 #endif
623 #ifdef EBADF
624     case EBADF: return "bad file number";
625 #endif
626 #ifdef EBADFD
627     case EBADFD: return "file descriptor in bad state";
628 #endif
629 #ifdef EBADMSG
630     case EBADMSG: return "not a data message";
631 #endif
632 #ifdef EBADR
633     case EBADR: return "bad request descriptor";
634 #endif
635 #ifdef EBADRPC
636     case EBADRPC: return "RPC structure is bad";
637 #endif
638 #ifdef EBADRQC
639     case EBADRQC: return "bad request code";
640 #endif
641 #ifdef EBADSLT
642     case EBADSLT: return "invalid slot";
643 #endif
644 #ifdef EBFONT
645     case EBFONT: return "bad font file format";
646 #endif
647 #ifdef EBUSY
648     case EBUSY: return "mount device busy";
649 #endif
650 #ifdef ECHILD
651     case ECHILD: return "no children";
652 #endif
653 #ifdef ECHRNG
654     case ECHRNG: return "channel number out of range";
655 #endif
656 #ifdef ECOMM
657     case ECOMM: return "communication error on send";
658 #endif
659 #ifdef ECONNABORTED
660     case ECONNABORTED: return "software caused connection abort";
661 #endif
662 #ifdef ECONNREFUSED
663     case ECONNREFUSED: return "connection refused";
664 #endif
665 #ifdef ECONNRESET
666     case ECONNRESET: return "connection reset by peer";
667 #endif
668 #if defined(EDEADLK) && (!defined(EWOULDBLOCK) || (EDEADLK != EWOULDBLOCK))
669     case EDEADLK: return "resource deadlock avoided";
670 #endif
671 #ifdef EDEADLOCK
672     case EDEADLOCK: return "resource deadlock avoided";
673 #endif
674 #ifdef EDESTADDRREQ
675     case EDESTADDRREQ: return "destination address required";
676 #endif
677 #ifdef EDIRTY
678     case EDIRTY: return "mounting a dirty fs w/o force";
679 #endif
680 #ifdef EDOM
681     case EDOM: return "math argument out of range";
682 #endif
683 #ifdef EDOTDOT
684     case EDOTDOT: return "cross mount point";
685 #endif
686 #ifdef EDQUOT
687     case EDQUOT: return "disk quota exceeded";
688 #endif
689 #ifdef EDUPPKG
690     case EDUPPKG: return "duplicate package name";
691 #endif
692 #ifdef EEXIST
693     case EEXIST: return "file already exists";
694 #endif
695 #ifdef EFAULT
696     case EFAULT: return "bad address in system call argument";
697 #endif
698 #ifdef EFBIG
699     case EFBIG: return "file too large";
700 #endif
701 #ifdef EHOSTDOWN
702     case EHOSTDOWN: return "host is down";
703 #endif
704 #ifdef EHOSTUNREACH
705     case EHOSTUNREACH: return "host is unreachable";
706 #endif
707 #ifdef EIDRM
708     case EIDRM: return "identifier removed";
709 #endif
710 #ifdef EINIT
711     case EINIT: return "initialization error";
712 #endif
713 #ifdef EINPROGRESS
714     case EINPROGRESS: return "operation now in progress";
715 #endif
716 #ifdef EINTR
717     case EINTR: return "interrupted system call";
718 #endif
719 #ifdef EINVAL
720     case EINVAL: return "invalid argument";
721 #endif
722 #ifdef EIO
723     case EIO: return "I/O error";
724 #endif
725 #ifdef EISCONN
726     case EISCONN: return "socket is already connected";
727 #endif
728 #ifdef EISDIR
729     case EISDIR: return "is a directory";
730 #endif
731 #ifdef EISNAME
732     case EISNAM: return "is a name file";
733 #endif
734 #ifdef ELBIN
735     case ELBIN: return "ELBIN";
736 #endif
737 #ifdef EL2HLT
738     case EL2HLT: return "level 2 halted";
739 #endif
740 #ifdef EL2NSYNC
741     case EL2NSYNC: return "level 2 not synchronized";
742 #endif
743 #ifdef EL3HLT
744     case EL3HLT: return "level 3 halted";
745 #endif
746 #ifdef EL3RST
747     case EL3RST: return "level 3 reset";
748 #endif
749 #ifdef ELIBACC
750     case ELIBACC: return "can not access a needed shared library";
751 #endif
752 #ifdef ELIBBAD
753     case ELIBBAD: return "accessing a corrupted shared library";
754 #endif
755 #ifdef ELIBEXEC
756     case ELIBEXEC: return "can not exec a shared library directly";
757 #endif
758 #ifdef ELIBMAX
759     case ELIBMAX: return "attempting to link in more shared libraries than system limit";
760 #endif
761 #ifdef ELIBSCN
762     case ELIBSCN: return ".lib section in a.out corrupted";
763 #endif
764 #ifdef ELNRNG
765     case ELNRNG: return "link number out of range";
766 #endif
767 #ifdef ELOOP
768     case ELOOP: return "too many levels of symbolic links";
769 #endif
770 #ifdef EMFILE
771     case EMFILE: return "too many open files";
772 #endif
773 #ifdef EMLINK
774     case EMLINK: return "too many links";
775 #endif
776 #ifdef EMSGSIZE
777     case EMSGSIZE: return "message too long";
778 #endif
779 #ifdef EMULTIHOP
780     case EMULTIHOP: return "multihop attempted";
781 #endif
782 #ifdef ENAMETOOLONG
783     case ENAMETOOLONG: return "file name too long";
784 #endif
785 #ifdef ENAVAIL
786     case ENAVAIL: return "not available";
787 #endif
788 #ifdef ENET
789     case ENET: return "ENET";
790 #endif
791 #ifdef ENETDOWN
792     case ENETDOWN: return "network is down";
793 #endif
794 #ifdef ENETRESET
795     case ENETRESET: return "network dropped connection on reset";
796 #endif
797 #ifdef ENETUNREACH
798     case ENETUNREACH: return "network is unreachable";
799 #endif
800 #ifdef ENFILE
801     case ENFILE: return "file table overflow";
802 #endif
803 #ifdef ENOANO
804     case ENOANO: return "anode table overflow";
805 #endif
806 #if defined(ENOBUFS) && (!defined(ENOSR) || (ENOBUFS != ENOSR))
807     case ENOBUFS: return "no buffer space available";
808 #endif
809 #ifdef ENOCSI
810     case ENOCSI: return "no CSI structure available";
811 #endif
812 #ifdef ENODATA
813     case ENODATA: return "no data available";
814 #endif
815 #ifdef ENODEV
816     case ENODEV: return "no such device";
817 #endif
818 #ifdef ENOENT
819     case ENOENT: return "no such file or directory";
820 #endif
821 #ifdef ENOEXEC
822     case ENOEXEC: return "exec format error";
823 #endif
824 #ifdef ENOLCK
825     case ENOLCK: return "no locks available";
826 #endif
827 #ifdef ENOLINK
828     case ENOLINK: return "link has be severed";
829 #endif
830 #ifdef ENOMEM
831     case ENOMEM: return "not enough memory";
832 #endif
833 #ifdef ENOMSG
834     case ENOMSG: return "no message of desired type";
835 #endif
836 #ifdef ENONET
837     case ENONET: return "machine is not on the network";
838 #endif
839 #ifdef ENOPKG
840     case ENOPKG: return "package not installed";
841 #endif
842 #ifdef ENOPROTOOPT
843     case ENOPROTOOPT: return "bad proocol option";
844 #endif
845 #ifdef ENOSPC
846     case ENOSPC: return "no space left on device";
847 #endif
848 #ifdef ENOSR
849     case ENOSR: return "out of stream resources";
850 #endif
851 #ifdef ENOSTR
852     case ENOSTR: return "not a stream device";
853 #endif
854 #ifdef ENOSYM
855     case ENOSYM: return "unresolved symbol name";
856 #endif
857 #ifdef ENOSYS
858     case ENOSYS: return "function not implemented";
859 #endif
860 #ifdef ENOTBLK
861     case ENOTBLK: return "block device required";
862 #endif
863 #ifdef ENOTCONN
864     case ENOTCONN: return "socket is not connected";
865 #endif
866 #ifdef ENOTDIR
867     case ENOTDIR: return "not a directory";
868 #endif
869 #ifdef ENOTEMPTY
870     case ENOTEMPTY: return "directory not empty";
871 #endif
872 #ifdef ENOTNAM
873     case ENOTNAM: return "not a name file";
874 #endif
875 #ifdef ENOTSOCK
876     case ENOTSOCK: return "socket operation on non-socket";
877 #endif
878 #ifdef ENOTTY
879     case ENOTTY: return "inappropriate device for ioctl";
880 #endif
881 #ifdef ENOTUNIQ
882     case ENOTUNIQ: return "name not unique on network";
883 #endif
884 #ifdef ENXIO
885     case ENXIO: return "no such device or address";
886 #endif
887 #ifdef EOPNOTSUPP
888     case EOPNOTSUPP: return "operation not supported on socket";
889 #endif
890 #ifdef EPERM
891     case EPERM: return "not owner";
892 #endif
893 #ifdef EPFNOSUPPORT
894     case EPFNOSUPPORT: return "protocol family not supported";
895 #endif
896 #ifdef EPIPE
897     case EPIPE: return "broken pipe";
898 #endif
899 #ifdef EPROCLIM
900     case EPROCLIM: return "too many processes";
901 #endif
902 #ifdef EPROCUNAVAIL
903     case EPROCUNAVAIL: return "bad procedure for program";
904 #endif
905 #ifdef EPROGMISMATCH
906     case EPROGMISMATCH: return "program version wrong";
907 #endif
908 #ifdef EPROGUNAVAIL
909     case EPROGUNAVAIL: return "RPC program not available";
910 #endif
911 #ifdef EPROTO
912     case EPROTO: return "protocol error";
913 #endif
914 #ifdef EPROTONOSUPPORT
915     case EPROTONOSUPPORT: return "protocol not suppored";
916 #endif
917 #ifdef EPROTOTYPE
918     case EPROTOTYPE: return "protocol wrong type for socket";
919 #endif
920 #ifdef ERANGE
921     case ERANGE: return "math result unrepresentable";
922 #endif
923 #if defined(EREFUSED) && (!defined(ECONNREFUSED) || (EREFUSED != ECONNREFUSED))
924     case EREFUSED: return "EREFUSED";
925 #endif
926 #ifdef EREMCHG
927     case EREMCHG: return "remote address changed";
928 #endif
929 #ifdef EREMDEV
930     case EREMDEV: return "remote device";
931 #endif
932 #ifdef EREMOTE
933     case EREMOTE: return "pathname hit remote file system";
934 #endif
935 #ifdef EREMOTEIO
936     case EREMOTEIO: return "remote i/o error";
937 #endif
938 #ifdef EREMOTERELEASE
939     case EREMOTERELEASE: return "EREMOTERELEASE";
940 #endif
941 #ifdef EROFS
942     case EROFS: return "read-only file system";
943 #endif
944 #ifdef ERPCMISMATCH
945     case ERPCMISMATCH: return "RPC version is wrong";
946 #endif
947 #ifdef ERREMOTE
948     case ERREMOTE: return "object is remote";
949 #endif
950 #ifdef ESHUTDOWN
951     case ESHUTDOWN: return "can't send afer socket shutdown";
952 #endif
953 #ifdef ESOCKTNOSUPPORT
954     case ESOCKTNOSUPPORT: return "socket type not supported";
955 #endif
956 #ifdef ESPIPE
957     case ESPIPE: return "invalid seek";
958 #endif
959 #ifdef ESRCH
960     case ESRCH: return "no such process";
961 #endif
962 #ifdef ESRMNT
963     case ESRMNT: return "srmount error";
964 #endif
965 #ifdef ESTALE
966     case ESTALE: return "stale remote file handle";
967 #endif
968 #ifdef ESUCCESS
969     case ESUCCESS: return "Error 0";
970 #endif
971 #ifdef ETIME
972     case ETIME: return "timer expired";
973 #endif
974 #ifdef ETIMEDOUT
975     case ETIMEDOUT: return "connection timed out";
976 #endif
977 #ifdef ETOOMANYREFS
978     case ETOOMANYREFS: return "too many references: can't splice";
979 #endif
980 #ifdef ETXTBSY
981     case ETXTBSY: return "text file or pseudo-device busy";
982 #endif
983 #ifdef EUCLEAN
984     case EUCLEAN: return "structure needs cleaning";
985 #endif
986 #ifdef EUNATCH
987     case EUNATCH: return "protocol driver not attached";
988 #endif
989 #ifdef EUSERS
990     case EUSERS: return "too many users";
991 #endif
992 #ifdef EVERSION
993     case EVERSION: return "version mismatch";
994 #endif
995 #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
996     case EWOULDBLOCK: return "operation would block";
997 #endif
998 #ifdef EXDEV
999     case EXDEV: return "cross-domain link";
1000 #endif
1001 #ifdef EXFULL
1002     case EXFULL: return "message tables full";
1003 #endif
1004     }
1005 #else /* NO_SYS_ERRLIST */
1006   extern int sys_nerr;
1007   extern char *sys_errlist[];
1008
1009   if ((errnum > 0) && (errnum <= sys_nerr))
1010     return sys_errlist [errnum];
1011 #endif /* NO_SYS_ERRLIST */
1012
1013   msg = g_static_private_get (&msg_private);
1014   if (!msg)
1015     {
1016       msg = g_new (gchar, 64);
1017       g_static_private_set (&msg_private, msg, g_free);
1018     }
1019
1020   sprintf (msg, "unknown error (%d)", errnum);
1021
1022   return msg;
1023 }
1024
1025 G_CONST_RETURN gchar*
1026 g_strsignal (gint signum)
1027 {
1028   static GStaticPrivate msg_private = G_STATIC_PRIVATE_INIT;
1029   char *msg;
1030
1031 #ifdef HAVE_STRSIGNAL
1032 #if defined(G_OS_BEOS) || defined(G_WITH_CYGWIN)
1033 extern const char *strsignal(int);
1034 #else
1035   /* this is declared differently (const) in string.h on BeOS */
1036   extern char *strsignal (int sig);
1037 #endif /* !G_OS_BEOS && !G_WITH_CYGWIN */
1038   return strsignal (signum);
1039 #elif NO_SYS_SIGLIST
1040   switch (signum)
1041     {
1042 #ifdef SIGHUP
1043     case SIGHUP: return "Hangup";
1044 #endif
1045 #ifdef SIGINT
1046     case SIGINT: return "Interrupt";
1047 #endif
1048 #ifdef SIGQUIT
1049     case SIGQUIT: return "Quit";
1050 #endif
1051 #ifdef SIGILL
1052     case SIGILL: return "Illegal instruction";
1053 #endif
1054 #ifdef SIGTRAP
1055     case SIGTRAP: return "Trace/breakpoint trap";
1056 #endif
1057 #ifdef SIGABRT
1058     case SIGABRT: return "IOT trap/Abort";
1059 #endif
1060 #ifdef SIGBUS
1061     case SIGBUS: return "Bus error";
1062 #endif
1063 #ifdef SIGFPE
1064     case SIGFPE: return "Floating point exception";
1065 #endif
1066 #ifdef SIGKILL
1067     case SIGKILL: return "Killed";
1068 #endif
1069 #ifdef SIGUSR1
1070     case SIGUSR1: return "User defined signal 1";
1071 #endif
1072 #ifdef SIGSEGV
1073     case SIGSEGV: return "Segmentation fault";
1074 #endif
1075 #ifdef SIGUSR2
1076     case SIGUSR2: return "User defined signal 2";
1077 #endif
1078 #ifdef SIGPIPE
1079     case SIGPIPE: return "Broken pipe";
1080 #endif
1081 #ifdef SIGALRM
1082     case SIGALRM: return "Alarm clock";
1083 #endif
1084 #ifdef SIGTERM
1085     case SIGTERM: return "Terminated";
1086 #endif
1087 #ifdef SIGSTKFLT
1088     case SIGSTKFLT: return "Stack fault";
1089 #endif
1090 #ifdef SIGCHLD
1091     case SIGCHLD: return "Child exited";
1092 #endif
1093 #ifdef SIGCONT
1094     case SIGCONT: return "Continued";
1095 #endif
1096 #ifdef SIGSTOP
1097     case SIGSTOP: return "Stopped (signal)";
1098 #endif
1099 #ifdef SIGTSTP
1100     case SIGTSTP: return "Stopped";
1101 #endif
1102 #ifdef SIGTTIN
1103     case SIGTTIN: return "Stopped (tty input)";
1104 #endif
1105 #ifdef SIGTTOU
1106     case SIGTTOU: return "Stopped (tty output)";
1107 #endif
1108 #ifdef SIGURG
1109     case SIGURG: return "Urgent condition";
1110 #endif
1111 #ifdef SIGXCPU
1112     case SIGXCPU: return "CPU time limit exceeded";
1113 #endif
1114 #ifdef SIGXFSZ
1115     case SIGXFSZ: return "File size limit exceeded";
1116 #endif
1117 #ifdef SIGVTALRM
1118     case SIGVTALRM: return "Virtual time alarm";
1119 #endif
1120 #ifdef SIGPROF
1121     case SIGPROF: return "Profile signal";
1122 #endif
1123 #ifdef SIGWINCH
1124     case SIGWINCH: return "Window size changed";
1125 #endif
1126 #ifdef SIGIO
1127     case SIGIO: return "Possible I/O";
1128 #endif
1129 #ifdef SIGPWR
1130     case SIGPWR: return "Power failure";
1131 #endif
1132 #ifdef SIGUNUSED
1133     case SIGUNUSED: return "Unused signal";
1134 #endif
1135     }
1136 #else /* NO_SYS_SIGLIST */
1137
1138 #ifdef NO_SYS_SIGLIST_DECL
1139   extern char *sys_siglist[];   /*(see Tue Jan 19 00:44:24 1999 in changelog)*/
1140 #endif
1141
1142   return (char*) /* this function should return const --josh */ sys_siglist [signum];
1143 #endif /* NO_SYS_SIGLIST */
1144
1145   msg = g_static_private_get (&msg_private);
1146   if (!msg)
1147     {
1148       msg = g_new (gchar, 64);
1149       g_static_private_set (&msg_private, msg, g_free);
1150     }
1151
1152   sprintf (msg, "unknown signal (%d)", signum);
1153   
1154   return msg;
1155 }
1156
1157 /* Functions g_strlcpy and g_strlcat were originally developed by
1158  * Todd C. Miller <Todd.Miller@courtesan.com> to simplify writing secure code.
1159  * See ftp://ftp.openbsd.org/pub/OpenBSD/src/lib/libc/string/strlcpy.3
1160  * for more information.
1161  */
1162
1163 #ifdef HAVE_STRLCPY
1164 /* Use the native ones, if available; they might be implemented in assembly */
1165 gsize
1166 g_strlcpy (gchar       *dest,
1167            const gchar *src,
1168            gsize        dest_size)
1169 {
1170   g_return_val_if_fail (dest != NULL, 0);
1171   g_return_val_if_fail (src  != NULL, 0);
1172   
1173   return strlcpy (dest, src, dest_size);
1174 }
1175
1176 gsize
1177 g_strlcat (gchar       *dest,
1178            const gchar *src,
1179            gsize        dest_size)
1180 {
1181   g_return_val_if_fail (dest != NULL, 0);
1182   g_return_val_if_fail (src  != NULL, 0);
1183   
1184   return strlcat (dest, src, dest_size);
1185 }
1186
1187 #else /* ! HAVE_STRLCPY */
1188 /* g_strlcpy
1189  *
1190  * Copy string src to buffer dest (of buffer size dest_size).  At most
1191  * dest_size-1 characters will be copied.  Always NUL terminates
1192  * (unless dest_size == 0).  This function does NOT allocate memory.
1193  * Unlike strncpy, this function doesn't pad dest (so it's often faster).
1194  * Returns size of attempted result, strlen(src),
1195  * so if retval >= dest_size, truncation occurred.
1196  */
1197 gsize
1198 g_strlcpy (gchar       *dest,
1199            const gchar *src,
1200            gsize        dest_size)
1201 {
1202   register gchar *d = dest;
1203   register const gchar *s = src;
1204   register gsize n = dest_size;
1205   
1206   g_return_val_if_fail (dest != NULL, 0);
1207   g_return_val_if_fail (src  != NULL, 0);
1208   
1209   /* Copy as many bytes as will fit */
1210   if (n != 0 && --n != 0)
1211     do
1212       {
1213         register gchar c = *s++;
1214         
1215         *d++ = c;
1216         if (c == 0)
1217           break;
1218       }
1219     while (--n != 0);
1220   
1221   /* If not enough room in dest, add NUL and traverse rest of src */
1222   if (n == 0)
1223     {
1224       if (dest_size != 0)
1225         *d = 0;
1226       while (*s++)
1227         ;
1228     }
1229   
1230   return s - src - 1;  /* count does not include NUL */
1231 }
1232
1233 /* g_strlcat
1234  *
1235  * Appends string src to buffer dest (of buffer size dest_size).
1236  * At most dest_size-1 characters will be copied.
1237  * Unlike strncat, dest_size is the full size of dest, not the space left over.
1238  * This function does NOT allocate memory.
1239  * This always NUL terminates (unless siz == 0 or there were no NUL characters
1240  * in the dest_size characters of dest to start with).
1241  * Returns size of attempted result, which is
1242  * MIN (dest_size, strlen (original dest)) + strlen (src),
1243  * so if retval >= dest_size, truncation occurred.
1244  */
1245 gsize
1246 g_strlcat (gchar       *dest,
1247            const gchar *src,
1248            gsize        dest_size)
1249 {
1250   register gchar *d = dest;
1251   register const gchar *s = src;
1252   register gsize bytes_left = dest_size;
1253   gsize dlength;  /* Logically, MIN (strlen (d), dest_size) */
1254   
1255   g_return_val_if_fail (dest != NULL, 0);
1256   g_return_val_if_fail (src  != NULL, 0);
1257   
1258   /* Find the end of dst and adjust bytes left but don't go past end */
1259   while (*d != 0 && bytes_left-- != 0)
1260     d++;
1261   dlength = d - dest;
1262   bytes_left = dest_size - dlength;
1263   
1264   if (bytes_left == 0)
1265     return dlength + strlen (s);
1266   
1267   while (*s != 0)
1268     {
1269       if (bytes_left != 1)
1270         {
1271           *d++ = *s;
1272           bytes_left--;
1273         }
1274       s++;
1275     }
1276   *d = 0;
1277   
1278   return dlength + (s - src);  /* count does not include NUL */
1279 }
1280 #endif /* ! HAVE_STRLCPY */
1281
1282 /**
1283  * g_ascii_strdown:
1284  * @str: a string.
1285  * @len: length of @str in bytes, or -1 if @str is nul-terminated.
1286  * 
1287  * Converts all upper case ASCII letters to lower case ASCII letters.
1288  * 
1289  * Return value: a newly-allocated string, with all the upper case
1290  *               characters in @str converted to lower case, with
1291  *               semantics that exactly match g_ascii_tolower(). (Note
1292  *               that this is unlike the old g_strdown(), which modified
1293  *               the string in place.)
1294  **/
1295 gchar*
1296 g_ascii_strdown (const gchar *str,
1297                  gssize       len)
1298 {
1299   gchar *result, *s;
1300   
1301   g_return_val_if_fail (str != NULL, NULL);
1302
1303   if (len < 0)
1304     len = strlen (str);
1305
1306   result = g_strndup (str, len);
1307   for (s = result; *s; s++)
1308     *s = g_ascii_tolower (*s);
1309   
1310   return result;
1311 }
1312
1313 /**
1314  * g_ascii_strup:
1315  * @str: a string.
1316  * @len: length of @str in bytes, or -1 if @str is nul-terminated.
1317  * 
1318  * Converts all lower case ASCII letters to upper case ASCII letters.
1319  * 
1320  * Return value: a newly allocated string, with all the lower case
1321  *               characters in @str converted to upper case, with
1322  *               semantics that exactly match g_ascii_toupper(). (Note
1323  *               that this is unlike the old g_strup(), which modified
1324  *               the string in place.)
1325  **/
1326 gchar*
1327 g_ascii_strup (const gchar *str,
1328                gssize       len)
1329 {
1330   gchar *result, *s;
1331
1332   g_return_val_if_fail (str != NULL, NULL);
1333
1334   if (len < 0)
1335     len = strlen (str);
1336
1337   result = g_strndup (str, len);
1338   for (s = result; *s; s++)
1339     *s = g_ascii_toupper (*s);
1340
1341   return result;
1342 }
1343
1344 gchar*
1345 g_strdown (gchar *string)
1346 {
1347   register guchar *s;
1348   
1349   g_return_val_if_fail (string != NULL, NULL);
1350   
1351   s = (guchar *) string;
1352   
1353   while (*s)
1354     {
1355       if (isupper (*s))
1356         *s = tolower (*s);
1357       s++;
1358     }
1359   
1360   return (gchar *) string;
1361 }
1362
1363 gchar*
1364 g_strup (gchar *string)
1365 {
1366   register guchar *s;
1367
1368   g_return_val_if_fail (string != NULL, NULL);
1369
1370   s = (guchar *) string;
1371
1372   while (*s)
1373     {
1374       if (islower (*s))
1375         *s = toupper (*s);
1376       s++;
1377     }
1378
1379   return (gchar *) string;
1380 }
1381
1382 gchar*
1383 g_strreverse (gchar *string)
1384 {
1385   g_return_val_if_fail (string != NULL, NULL);
1386
1387   if (*string)
1388     {
1389       register gchar *h, *t;
1390
1391       h = string;
1392       t = string + strlen (string) - 1;
1393
1394       while (h < t)
1395         {
1396           register gchar c;
1397
1398           c = *h;
1399           *h = *t;
1400           h++;
1401           *t = c;
1402           t--;
1403         }
1404     }
1405
1406   return string;
1407 }
1408
1409 /**
1410  * g_ascii_tolower:
1411  * @c: any character.
1412  * 
1413  * Convert a character to ASCII lower case.
1414  *
1415  * Unlike the standard C library tolower() function, this only
1416  * recognizes standard ASCII letters and ignores the locale, returning
1417  * all non-ASCII characters unchanged, even if they are lower case
1418  * letters in a particular character set. Also unlike the standard
1419  * library function, this takes and returns a char, not an int, so
1420  * don't call it on %EOF but no need to worry about casting to #guchar
1421  * before passing a possibly non-ASCII character in.
1422  * 
1423  * Return value: the result of converting @c to lower case.
1424  *               If @c is not an ASCII upper case letter,
1425  *               @c is returned unchanged.
1426  **/
1427 gchar
1428 g_ascii_tolower (gchar c)
1429 {
1430   return g_ascii_isupper (c) ? c - 'A' + 'a' : c;
1431 }
1432
1433 /**
1434  * g_ascii_toupper:
1435  * @c: any character.
1436  * 
1437  * Convert a character to ASCII upper case.
1438  *
1439  * Unlike the standard C library toupper() function, this only
1440  * recognizes standard ASCII letters and ignores the locale, returning
1441  * all non-ASCII characters unchanged, even if they are upper case
1442  * letters in a particular character set. Also unlike the standard
1443  * library function, this takes and returns a char, not an int, so
1444  * don't call it on %EOF but no need to worry about casting to #guchar
1445  * before passing a possibly non-ASCII character in.
1446  * 
1447  * Return value: the result of converting @c to upper case.
1448  *               If @c is not an ASCII lower case letter,
1449  *               @c is returned unchanged.
1450  **/
1451 gchar
1452 g_ascii_toupper (gchar c)
1453 {
1454   return g_ascii_islower (c) ? c - 'a' + 'A' : c;
1455 }
1456
1457 /**
1458  * g_ascii_digit_value:
1459  * @c: an ASCII character.
1460  *
1461  * Determines the numeric value of a character as a decimal
1462  * digit. Differs from g_unichar_digit_value() because it takes
1463  * a char, so there's no worry about sign extension if characters
1464  * are signed.
1465  *
1466  * Return value: If @c is a decimal digit (according to
1467  * g_ascii_isdigit()), its numeric value. Otherwise, -1.
1468  **/
1469 int
1470 g_ascii_digit_value (gchar c)
1471 {
1472   if (g_ascii_isdigit (c))
1473     return c - '0';
1474   return -1;
1475 }
1476
1477 /**
1478  * g_ascii_xdigit_value:
1479  * @c: an ASCII character.
1480  *
1481  * Determines the numeric value of a character as a hexidecimal
1482  * digit. Differs from g_unichar_xdigit_value() because it takes
1483  * a char, so there's no worry about sign extension if characters
1484  * are signed.
1485  *
1486  * Return value: If @c is a hex digit (according to
1487  * g_ascii_isxdigit()), its numeric value. Otherwise, -1.
1488  **/
1489 int
1490 g_ascii_xdigit_value (gchar c)
1491 {
1492   if (c >= 'A' && c <= 'F')
1493     return c - 'A' + 10;
1494   if (c >= 'a' && c <= 'f')
1495     return c - 'a' + 10;
1496   return g_ascii_digit_value (c);
1497 }
1498
1499 /**
1500  * g_ascii_strcasecmp:
1501  * @s1: string to compare with @s2.
1502  * @s2: string to compare with @s1.
1503  * 
1504  * Compare two strings, ignoring the case of ASCII characters.
1505  *
1506  * Unlike the BSD strcasecmp() function, this only recognizes standard
1507  * ASCII letters and ignores the locale, treating all non-ASCII
1508  * characters as if they are not letters.
1509  * 
1510  * Return value: an integer less than, equal to, or greater than
1511  *               zero if @s1 is found, respectively, to be less than,
1512  *               to match, or to be greater than @s2.
1513  **/
1514 gint
1515 g_ascii_strcasecmp (const gchar *s1,
1516                     const gchar *s2)
1517 {
1518   gint c1, c2;
1519
1520   g_return_val_if_fail (s1 != NULL, 0);
1521   g_return_val_if_fail (s2 != NULL, 0);
1522
1523   while (*s1 && *s2)
1524     {
1525       c1 = (gint)(guchar) g_ascii_tolower (*s1);
1526       c2 = (gint)(guchar) g_ascii_tolower (*s2);
1527       if (c1 != c2)
1528         return (c1 - c2);
1529       s1++; s2++;
1530     }
1531
1532   return (((gint)(guchar) *s1) - ((gint)(guchar) *s2));
1533 }
1534
1535 /**
1536  * g_ascii_strncasecmp:
1537  * @s1: string to compare with @s2.
1538  * @s2: string to compare with @s1.
1539  * @n:  number of characters to compare.
1540  * 
1541  * Compare @s1 and @s2, ignoring the case of ASCII characters and any
1542  * characters after the first @n in each string.
1543  *
1544  * Unlike the BSD strcasecmp() function, this only recognizes standard
1545  * ASCII letters and ignores the locale, treating all non-ASCII
1546  * characters as if they are not letters.
1547  * 
1548  * Return value: an integer less than, equal to, or greater than zero
1549  *               if the first @n bytes of @s1 is found, respectively,
1550  *               to be less than, to match, or to be greater than the
1551  *               first @n bytes of @s2.
1552  **/
1553 gint
1554 g_ascii_strncasecmp (const gchar *s1,
1555                      const gchar *s2,
1556                      gsize n)
1557 {
1558   gint c1, c2;
1559
1560   g_return_val_if_fail (s1 != NULL, 0);
1561   g_return_val_if_fail (s2 != NULL, 0);
1562
1563   while (n && *s1 && *s2)
1564     {
1565       n -= 1;
1566       c1 = (gint)(guchar) g_ascii_tolower (*s1);
1567       c2 = (gint)(guchar) g_ascii_tolower (*s2);
1568       if (c1 != c2)
1569         return (c1 - c2);
1570       s1++; s2++;
1571     }
1572
1573   if (n)
1574     return (((gint) (guchar) *s1) - ((gint) (guchar) *s2));
1575   else
1576     return 0;
1577 }
1578
1579 gint
1580 g_strcasecmp (const gchar *s1,
1581               const gchar *s2)
1582 {
1583 #ifdef HAVE_STRCASECMP
1584   g_return_val_if_fail (s1 != NULL, 0);
1585   g_return_val_if_fail (s2 != NULL, 0);
1586
1587   return strcasecmp (s1, s2);
1588 #else
1589   gint c1, c2;
1590
1591   g_return_val_if_fail (s1 != NULL, 0);
1592   g_return_val_if_fail (s2 != NULL, 0);
1593
1594   while (*s1 && *s2)
1595     {
1596       /* According to A. Cox, some platforms have islower's that
1597        * don't work right on non-uppercase
1598        */
1599       c1 = isupper ((guchar)*s1) ? tolower ((guchar)*s1) : *s1;
1600       c2 = isupper ((guchar)*s2) ? tolower ((guchar)*s2) : *s2;
1601       if (c1 != c2)
1602         return (c1 - c2);
1603       s1++; s2++;
1604     }
1605
1606   return (((gint)(guchar) *s1) - ((gint)(guchar) *s2));
1607 #endif
1608 }
1609
1610 gint
1611 g_strncasecmp (const gchar *s1,
1612                const gchar *s2,
1613                gsize n)     
1614 {
1615 #ifdef HAVE_STRNCASECMP
1616   return strncasecmp (s1, s2, n);
1617 #else
1618   gint c1, c2;
1619
1620   g_return_val_if_fail (s1 != NULL, 0);
1621   g_return_val_if_fail (s2 != NULL, 0);
1622
1623   while (n && *s1 && *s2)
1624     {
1625       n -= 1;
1626       /* According to A. Cox, some platforms have islower's that
1627        * don't work right on non-uppercase
1628        */
1629       c1 = isupper ((guchar)*s1) ? tolower ((guchar)*s1) : *s1;
1630       c2 = isupper ((guchar)*s2) ? tolower ((guchar)*s2) : *s2;
1631       if (c1 != c2)
1632         return (c1 - c2);
1633       s1++; s2++;
1634     }
1635
1636   if (n)
1637     return (((gint) (guchar) *s1) - ((gint) (guchar) *s2));
1638   else
1639     return 0;
1640 #endif
1641 }
1642
1643 gchar*
1644 g_strdelimit (gchar       *string,
1645               const gchar *delimiters,
1646               gchar        new_delim)
1647 {
1648   register gchar *c;
1649
1650   g_return_val_if_fail (string != NULL, NULL);
1651
1652   if (!delimiters)
1653     delimiters = G_STR_DELIMITERS;
1654
1655   for (c = string; *c; c++)
1656     {
1657       if (strchr (delimiters, *c))
1658         *c = new_delim;
1659     }
1660
1661   return string;
1662 }
1663
1664 gchar*
1665 g_strcanon (gchar       *string,
1666             const gchar *valid_chars,
1667             gchar        substitutor)
1668 {
1669   register gchar *c;
1670
1671   g_return_val_if_fail (string != NULL, NULL);
1672   g_return_val_if_fail (valid_chars != NULL, NULL);
1673
1674   for (c = string; *c; c++)
1675     {
1676       if (!strchr (valid_chars, *c))
1677         *c = substitutor;
1678     }
1679
1680   return string;
1681 }
1682
1683 gchar*
1684 g_strcompress (const gchar *source)
1685 {
1686   const gchar *p = source, *octal;
1687   gchar *dest = g_malloc (strlen (source) + 1);
1688   gchar *q = dest;
1689   
1690   while (*p)
1691     {
1692       if (*p == '\\')
1693         {
1694           p++;
1695           switch (*p)
1696             {
1697             case '0':  case '1':  case '2':  case '3':  case '4':
1698             case '5':  case '6':  case '7':
1699               *q = 0;
1700               octal = p;
1701               while ((p < octal + 3) && (*p >= '0') && (*p <= '7'))
1702                 {
1703                   *q = (*q * 8) + (*p - '0');
1704                   p++;
1705                 }
1706               q++;
1707               p--;
1708               break;
1709             case 'b':
1710               *q++ = '\b';
1711               break;
1712             case 'f':
1713               *q++ = '\f';
1714               break;
1715             case 'n':
1716               *q++ = '\n';
1717               break;
1718             case 'r':
1719               *q++ = '\r';
1720               break;
1721             case 't':
1722               *q++ = '\t';
1723               break;
1724             default:            /* Also handles \" and \\ */
1725               *q++ = *p;
1726               break;
1727             }
1728         }
1729       else
1730         *q++ = *p;
1731       p++;
1732     }
1733   *q = 0;
1734   
1735   return dest;
1736 }
1737
1738 gchar *
1739 g_strescape (const gchar *source,
1740              const gchar *exceptions)
1741 {
1742   const guchar *p;
1743   gchar *dest;
1744   gchar *q;
1745   guchar excmap[256];
1746   
1747   g_return_val_if_fail (source != NULL, NULL);
1748
1749   p = (guchar *) source;
1750   /* Each source byte needs maximally four destination chars (\777) */
1751   q = dest = g_malloc (strlen (source) * 4 + 1);
1752
1753   memset (excmap, 0, 256);
1754   if (exceptions)
1755     {
1756       guchar *e = (guchar *) exceptions;
1757
1758       while (*e)
1759         {
1760           excmap[*e] = 1;
1761           e++;
1762         }
1763     }
1764
1765   while (*p)
1766     {
1767       if (excmap[*p])
1768         *q++ = *p;
1769       else
1770         {
1771           switch (*p)
1772             {
1773             case '\b':
1774               *q++ = '\\';
1775               *q++ = 'b';
1776               break;
1777             case '\f':
1778               *q++ = '\\';
1779               *q++ = 'f';
1780               break;
1781             case '\n':
1782               *q++ = '\\';
1783               *q++ = 'n';
1784               break;
1785             case '\r':
1786               *q++ = '\\';
1787               *q++ = 'r';
1788               break;
1789             case '\t':
1790               *q++ = '\\';
1791               *q++ = 't';
1792               break;
1793             case '\\':
1794               *q++ = '\\';
1795               *q++ = '\\';
1796               break;
1797             case '"':
1798               *q++ = '\\';
1799               *q++ = '"';
1800               break;
1801             default:
1802               if ((*p < ' ') || (*p >= 0177))
1803                 {
1804                   *q++ = '\\';
1805                   *q++ = '0' + (((*p) >> 6) & 07);
1806                   *q++ = '0' + (((*p) >> 3) & 07);
1807                   *q++ = '0' + ((*p) & 07);
1808                 }
1809               else
1810                 *q++ = *p;
1811               break;
1812             }
1813         }
1814       p++;
1815     }
1816   *q = 0;
1817   return dest;
1818 }
1819
1820 gchar*
1821 g_strchug (gchar *string)
1822 {
1823   guchar *start;
1824
1825   g_return_val_if_fail (string != NULL, NULL);
1826
1827   for (start = (guchar*) string; *start && g_ascii_isspace (*start); start++)
1828     ;
1829
1830   g_memmove (string, start, strlen ((gchar *) start) + 1);
1831
1832   return string;
1833 }
1834
1835 gchar*
1836 g_strchomp (gchar *string)
1837 {
1838   gchar *s;
1839
1840   g_return_val_if_fail (string != NULL, NULL);
1841
1842   if (!*string)
1843     return string;
1844
1845   for (s = string + strlen (string) - 1; s >= string && g_ascii_isspace ((guchar)*s); 
1846        s--)
1847     *s = '\0';
1848
1849   return string;
1850 }
1851
1852 /**
1853  * g_strsplit:
1854  * @string: a string to split.
1855  * @delimiter: a string which specifies the places at which to split the string.
1856  *     The delimiter is not included in any of the resulting strings, unless
1857  *     @max_tokens is reached.
1858  * @max_tokens: the maximum number of pieces to split @string into. If this is
1859  *              less than 1, the string is split completely.
1860  * 
1861  * Splits a string into a maximum of @max_tokens pieces, using the given
1862  * @delimiter. If @max_tokens is reached, the remainder of @string is appended
1863  * to the last token. 
1864  *
1865  * As a special case, the result of splitting the empty string "" is an empty
1866  * vector, not a vector containing a single string. The reason for this
1867  * special case is that being able to represent a empty vector is typically
1868  * more useful than consistent handling of empty elements. If you do need
1869  * to represent empty elements, you'll need to check for the empty string
1870  * before calling g_strsplit().
1871  * 
1872  * Return value: a newly-allocated %NULL-terminated array of strings. Use 
1873  *    g_strfreev() to free it.
1874  **/
1875 gchar**
1876 g_strsplit (const gchar *string,
1877             const gchar *delimiter,
1878             gint         max_tokens)
1879 {
1880   GSList *string_list = NULL, *slist;
1881   gchar **str_array, *s;
1882   guint n = 0;
1883   const gchar *remainder;
1884
1885   g_return_val_if_fail (string != NULL, NULL);
1886   g_return_val_if_fail (delimiter != NULL, NULL);
1887   g_return_val_if_fail (delimiter[0] != '\0', NULL);
1888
1889   if (max_tokens < 1)
1890     max_tokens = G_MAXINT;
1891   else
1892     --max_tokens;
1893
1894   remainder = string;
1895   s = strstr (remainder, delimiter);
1896   if (s)
1897     {
1898       gsize delimiter_len = strlen (delimiter);   
1899
1900       do
1901         {
1902           gsize len;     
1903           gchar *new_string;
1904
1905           len = s - remainder;
1906           new_string = g_new (gchar, len + 1);
1907           strncpy (new_string, remainder, len);
1908           new_string[len] = 0;
1909           string_list = g_slist_prepend (string_list, new_string);
1910           n++;
1911           remainder = s + delimiter_len;
1912           s = strstr (remainder, delimiter);
1913         }
1914       while (--max_tokens && s);
1915     }
1916   if (*string)
1917     {
1918       n++;
1919       string_list = g_slist_prepend (string_list, g_strdup (remainder));
1920     }
1921
1922   str_array = g_new (gchar*, n + 1);
1923
1924   str_array[n--] = NULL;
1925   for (slist = string_list; slist; slist = slist->next)
1926     str_array[n--] = slist->data;
1927
1928   g_slist_free (string_list);
1929
1930   return str_array;
1931 }
1932
1933 void
1934 g_strfreev (gchar **str_array)
1935 {
1936   if (str_array)
1937     {
1938       int i;
1939
1940       for(i = 0; str_array[i] != NULL; i++)
1941         g_free(str_array[i]);
1942
1943       g_free (str_array);
1944     }
1945 }
1946
1947 /**
1948  * g_strdupv:
1949  * @str_array: %NULL-terminated array of strings.
1950  * 
1951  * Copies %NULL-terminated array of strings. The copy is a deep copy;
1952  * the new array should be freed by first freeing each string, then
1953  * the array itself. g_strfreev() does this for you. If called
1954  * on a %NULL value, g_strdupv() simply returns %NULL.
1955  * 
1956  * Return value: a new %NULL-terminated array of strings.
1957  **/
1958 gchar**
1959 g_strdupv (gchar **str_array)
1960 {
1961   if (str_array)
1962     {
1963       gint i;
1964       gchar **retval;
1965
1966       i = 0;
1967       while (str_array[i])
1968         ++i;
1969           
1970       retval = g_new (gchar*, i + 1);
1971
1972       i = 0;
1973       while (str_array[i])
1974         {
1975           retval[i] = g_strdup (str_array[i]);
1976           ++i;
1977         }
1978       retval[i] = NULL;
1979
1980       return retval;
1981     }
1982   else
1983     return NULL;
1984 }
1985
1986 gchar*
1987 g_strjoinv (const gchar  *separator,
1988             gchar       **str_array)
1989 {
1990   gchar *string;
1991   gchar *ptr;
1992
1993   g_return_val_if_fail (str_array != NULL, NULL);
1994
1995   if (separator == NULL)
1996     separator = "";
1997
1998   if (*str_array)
1999     {
2000       gint i;
2001       gsize len;
2002       gsize separator_len;     
2003
2004       separator_len = strlen (separator);
2005       /* First part, getting length */
2006       len = 1 + strlen (str_array[0]);
2007       for (i = 1; str_array[i] != NULL; i++)
2008         len += strlen (str_array[i]);
2009       len += separator_len * (i - 1);
2010
2011       /* Second part, building string */
2012       string = g_new (gchar, len);
2013       ptr = g_stpcpy (string, *str_array);
2014       for (i = 1; str_array[i] != NULL; i++)
2015         {
2016           ptr = g_stpcpy (ptr, separator);
2017           ptr = g_stpcpy (ptr, str_array[i]);
2018         }
2019       }
2020   else
2021     string = g_strdup ("");
2022
2023   return string;
2024 }
2025
2026 gchar*
2027 g_strjoin (const gchar  *separator,
2028            ...)
2029 {
2030   gchar *string, *s;
2031   va_list args;
2032   gsize len;               
2033   gsize separator_len;     
2034   gchar *ptr;
2035
2036   if (separator == NULL)
2037     separator = "";
2038
2039   separator_len = strlen (separator);
2040
2041   va_start (args, separator);
2042
2043   s = va_arg (args, gchar*);
2044
2045   if (s)
2046     {
2047       /* First part, getting length */
2048       len = 1 + strlen (s);
2049
2050       s = va_arg (args, gchar*);
2051       while (s)
2052         {
2053           len += separator_len + strlen (s);
2054           s = va_arg (args, gchar*);
2055         }
2056       va_end (args);
2057
2058       /* Second part, building string */
2059       string = g_new (gchar, len);
2060
2061       va_start (args, separator);
2062
2063       s = va_arg (args, gchar*);
2064       ptr = g_stpcpy (string, s);
2065
2066       s = va_arg (args, gchar*);
2067       while (s)
2068         {
2069           ptr = g_stpcpy (ptr, separator);
2070           ptr = g_stpcpy (ptr, s);
2071           s = va_arg (args, gchar*);
2072         }
2073     }
2074   else
2075     string = g_strdup ("");
2076
2077   va_end (args);
2078
2079   return string;
2080 }
2081
2082
2083 /**
2084  * g_strstr_len:
2085  * @haystack: a string.
2086  * @haystack_len: the maximum length of @haystack.
2087  * @needle: the string to search for.
2088  *
2089  * Searches the string @haystack for the first occurrence
2090  * of the string @needle, limiting the length of the search
2091  * to @haystack_len. 
2092  *
2093  * Return value: a pointer to the found occurrence, or
2094  *    %NULL if not found.
2095  **/
2096 gchar *
2097 g_strstr_len (const gchar *haystack,
2098               gssize       haystack_len,
2099               const gchar *needle)
2100 {
2101   g_return_val_if_fail (haystack != NULL, NULL);
2102   g_return_val_if_fail (needle != NULL, NULL);
2103   
2104   if (haystack_len < 0)
2105     return strstr (haystack, needle);
2106   else
2107     {
2108       const gchar *p = haystack;
2109       gsize needle_len = strlen (needle);
2110       const gchar *end;
2111       gsize i;
2112
2113       if (needle_len == 0)
2114         return (gchar *)haystack;
2115
2116       if (haystack_len < needle_len)
2117         return NULL;
2118       
2119       end = haystack + haystack_len - needle_len;
2120       
2121       while (*p && p <= end)
2122         {
2123           for (i = 0; i < needle_len; i++)
2124             if (p[i] != needle[i])
2125               goto next;
2126           
2127           return (gchar *)p;
2128           
2129         next:
2130           p++;
2131         }
2132       
2133       return NULL;
2134     }
2135 }
2136
2137 /**
2138  * g_strrstr:
2139  * @haystack: a nul-terminated string.
2140  * @needle: the nul-terminated string to search for.
2141  *
2142  * Searches the string @haystack for the last occurrence
2143  * of the string @needle.
2144  *
2145  * Return value: a pointer to the found occurrence, or
2146  *    %NULL if not found.
2147  **/
2148 gchar *
2149 g_strrstr (const gchar *haystack,
2150            const gchar *needle)
2151 {
2152   gsize i;
2153   gsize needle_len;
2154   gsize haystack_len;
2155   const gchar *p;
2156       
2157   g_return_val_if_fail (haystack != NULL, NULL);
2158   g_return_val_if_fail (needle != NULL, NULL);
2159
2160   needle_len = strlen (needle);
2161   haystack_len = strlen (haystack);
2162
2163   if (needle_len == 0)
2164     return (gchar *)haystack;
2165
2166   if (haystack_len < needle_len)
2167     return NULL;
2168   
2169   p = haystack + haystack_len - needle_len;
2170
2171   while (p >= haystack)
2172     {
2173       for (i = 0; i < needle_len; i++)
2174         if (p[i] != needle[i])
2175           goto next;
2176       
2177       return (gchar *)p;
2178       
2179     next:
2180       p--;
2181     }
2182   
2183   return NULL;
2184 }
2185
2186 /**
2187  * g_strrstr_len:
2188  * @haystack: a nul-terminated string.
2189  * @haystack_len: the maximum length of @haystack.
2190  * @needle: the nul-terminated string to search for.
2191  *
2192  * Searches the string @haystack for the last occurrence
2193  * of the string @needle, limiting the length of the search
2194  * to @haystack_len. 
2195  *
2196  * Return value: a pointer to the found occurrence, or
2197  *    %NULL if not found.
2198  **/
2199 gchar *
2200 g_strrstr_len (const gchar *haystack,
2201                gssize        haystack_len,
2202                const gchar *needle)
2203 {
2204   g_return_val_if_fail (haystack != NULL, NULL);
2205   g_return_val_if_fail (needle != NULL, NULL);
2206   
2207   if (haystack_len < 0)
2208     return g_strrstr (haystack, needle);
2209   else
2210     {
2211       gsize needle_len = strlen (needle);
2212       const gchar *haystack_max = haystack + haystack_len;
2213       const gchar *p = haystack;
2214       gsize i;
2215
2216       while (p < haystack_max && *p)
2217         p++;
2218
2219       if (p < haystack + needle_len)
2220         return NULL;
2221         
2222       p -= needle_len;
2223
2224       while (p >= haystack)
2225         {
2226           for (i = 0; i < needle_len; i++)
2227             if (p[i] != needle[i])
2228               goto next;
2229           
2230           return (gchar *)p;
2231           
2232         next:
2233           p--;
2234         }
2235
2236       return NULL;
2237     }
2238 }
2239
2240