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