g_str_hash: switch to using DJB hash
[platform/upstream/glib.git] / glib / gstring.c
1 /* GLIB - Library of useful routines for C programming
2  * Copyright (C) 1995-1997  Peter Mattis, Spencer Kimball and Josh MacDonald
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17  * Boston, MA 02111-1307, USA.
18  */
19
20 /*
21  * Modified by the GLib Team and others 1997-2000.  See the AUTHORS
22  * file for a list of people on the GLib Team.  See the ChangeLog
23  * files for a list of changes.  These files are distributed with
24  * GLib at ftp://ftp.gtk.org/pub/gtk/.
25  */
26
27 /*
28  * MT safe
29  */
30
31 #include "config.h"
32
33 #ifdef HAVE_UNISTD_H
34 #include <unistd.h>
35 #endif
36 #include <stdarg.h>
37 #include <stdlib.h>
38 #include <stdio.h>
39 #include <string.h>
40 #include <ctype.h>
41
42 #include "gstring.h"
43
44 #include "gprintf.h"
45
46
47 /**
48  * SECTION: string_chunks
49  * @title: String Chunks
50  * @short_description: efficient storage of groups of strings
51  *
52  * String chunks are used to store groups of strings. Memory is
53  * allocated in blocks, and as strings are added to the #GStringChunk
54  * they are copied into the next free position in a block. When a block
55  * is full a new block is allocated.
56  *
57  * When storing a large number of strings, string chunks are more
58  * efficient than using g_strdup() since fewer calls to malloc() are
59  * needed, and less memory is wasted in memory allocation overheads.
60  *
61  * By adding strings with g_string_chunk_insert_const() it is also
62  * possible to remove duplicates.
63  *
64  * To create a new #GStringChunk use g_string_chunk_new().
65  *
66  * To add strings to a #GStringChunk use g_string_chunk_insert().
67  *
68  * To add strings to a #GStringChunk, but without duplicating strings
69  * which are already in the #GStringChunk, use
70  * g_string_chunk_insert_const().
71  *
72  * To free the entire #GStringChunk use g_string_chunk_free(). It is
73  * not possible to free individual strings.
74  **/
75
76 /**
77  * GStringChunk:
78  *
79  * An opaque data structure representing String Chunks. It should only
80  * be accessed by using the following functions.
81  **/
82 struct _GStringChunk
83 {
84   GHashTable *const_table;
85   GSList     *storage_list;
86   gsize       storage_next;    
87   gsize       this_size;       
88   gsize       default_size;    
89 };
90
91 /* Hash Functions.
92  */
93
94 /**
95  * g_str_equal:
96  * @v1: a key
97  * @v2: a key to compare with @v1
98  *
99  * Compares two strings for byte-by-byte equality and returns %TRUE
100  * if they are equal. It can be passed to g_hash_table_new() as the
101  * @key_equal_func parameter, when using strings as keys in a #GHashTable.
102  *
103  * Note that this function is primarily meant as a hash table comparison
104  * function. For a general-purpose, %NULL-safe string comparison function,
105  * see g_strcmp0().
106  *
107  * Returns: %TRUE if the two keys match
108  */
109 gboolean
110 g_str_equal (gconstpointer v1,
111              gconstpointer v2)
112 {
113   const gchar *string1 = v1;
114   const gchar *string2 = v2;
115   
116   return strcmp (string1, string2) == 0;
117 }
118
119 /**
120  * g_str_hash:
121  * @v: a string key
122  *
123  * Converts a string to a hash value.
124  *
125  * This function implements the widely used "djb" hash apparently posted
126  * by Daniel Bernstein to comp.lang.c some time ago.  The 32 bit
127  * unsigned hash value starts at 5381 and for each byte 'c' in the
128  * string, is updated: <literal>hash = hash * 33 + c</literal>.  This
129  * function uses the signed value of each byte.
130  *
131  * It can be passed to g_hash_table_new() as the @hash_func parameter,
132  * when using strings as keys in a #GHashTable.
133  *
134  * Returns: a hash value corresponding to the key
135  **/
136 guint
137 g_str_hash (gconstpointer v)
138 {
139   const signed char *p;
140   guint32 h = 5381;
141
142   for (p = v; *p != '\0'; p++)
143     h = (h << 5) + h + *p;
144
145   return h;
146 }
147
148 #define MY_MAXSIZE ((gsize)-1)
149
150 static inline gsize
151 nearest_power (gsize base, gsize num)    
152 {
153   if (num > MY_MAXSIZE / 2)
154     {
155       return MY_MAXSIZE;
156     }
157   else
158     {
159       gsize n = base;
160
161       while (n < num)
162         n <<= 1;
163       
164       return n;
165     }
166 }
167
168 /* String Chunks.
169  */
170
171 /**
172  * g_string_chunk_new:
173  * @size: the default size of the blocks of memory which are 
174  *        allocated to store the strings. If a particular string 
175  *        is larger than this default size, a larger block of 
176  *        memory will be allocated for it.
177  * 
178  * Creates a new #GStringChunk. 
179  * 
180  * Returns: a new #GStringChunk
181  */
182 GStringChunk*
183 g_string_chunk_new (gsize size)    
184 {
185   GStringChunk *new_chunk = g_new (GStringChunk, 1);
186   gsize actual_size = 1;    
187
188   actual_size = nearest_power (1, size);
189
190   new_chunk->const_table       = NULL;
191   new_chunk->storage_list      = NULL;
192   new_chunk->storage_next      = actual_size;
193   new_chunk->default_size      = actual_size;
194   new_chunk->this_size         = actual_size;
195
196   return new_chunk;
197 }
198
199 /**
200  * g_string_chunk_free:
201  * @chunk: a #GStringChunk 
202  * 
203  * Frees all memory allocated by the #GStringChunk.
204  * After calling g_string_chunk_free() it is not safe to
205  * access any of the strings which were contained within it.
206  */
207 void
208 g_string_chunk_free (GStringChunk *chunk)
209 {
210   GSList *tmp_list;
211
212   g_return_if_fail (chunk != NULL);
213
214   if (chunk->storage_list)
215     {
216       for (tmp_list = chunk->storage_list; tmp_list; tmp_list = tmp_list->next)
217         g_free (tmp_list->data);
218
219       g_slist_free (chunk->storage_list);
220     }
221
222   if (chunk->const_table)
223     g_hash_table_destroy (chunk->const_table);
224
225   g_free (chunk);
226 }
227
228 /**
229  * g_string_chunk_clear:
230  * @chunk: a #GStringChunk
231  *
232  * Frees all strings contained within the #GStringChunk.
233  * After calling g_string_chunk_clear() it is not safe to
234  * access any of the strings which were contained within it.
235  *
236  * Since: 2.14
237  */
238 void
239 g_string_chunk_clear (GStringChunk *chunk)
240 {
241   GSList *tmp_list;
242
243   g_return_if_fail (chunk != NULL);
244
245   if (chunk->storage_list)
246     {
247       for (tmp_list = chunk->storage_list; tmp_list; tmp_list = tmp_list->next)
248         g_free (tmp_list->data);
249
250       g_slist_free (chunk->storage_list);
251
252       chunk->storage_list       = NULL;
253       chunk->storage_next       = chunk->default_size;
254       chunk->this_size          = chunk->default_size;
255     }
256
257   if (chunk->const_table)
258       g_hash_table_remove_all (chunk->const_table);
259 }
260
261 /**
262  * g_string_chunk_insert:
263  * @chunk: a #GStringChunk
264  * @string: the string to add
265  * 
266  * Adds a copy of @string to the #GStringChunk.
267  * It returns a pointer to the new copy of the string 
268  * in the #GStringChunk. The characters in the string 
269  * can be changed, if necessary, though you should not 
270  * change anything after the end of the string.
271  *
272  * Unlike g_string_chunk_insert_const(), this function 
273  * does not check for duplicates. Also strings added 
274  * with g_string_chunk_insert() will not be searched 
275  * by g_string_chunk_insert_const() when looking for 
276  * duplicates.
277  * 
278  * Returns: a pointer to the copy of @string within 
279  *          the #GStringChunk
280  */
281 gchar*
282 g_string_chunk_insert (GStringChunk *chunk,
283                        const gchar  *string)
284 {
285   g_return_val_if_fail (chunk != NULL, NULL);
286
287   return g_string_chunk_insert_len (chunk, string, -1);
288 }
289
290 /**
291  * g_string_chunk_insert_const:
292  * @chunk: a #GStringChunk
293  * @string: the string to add
294  *
295  * Adds a copy of @string to the #GStringChunk, unless the same
296  * string has already been added to the #GStringChunk with
297  * g_string_chunk_insert_const().
298  *
299  * This function is useful if you need to copy a large number
300  * of strings but do not want to waste space storing duplicates.
301  * But you must remember that there may be several pointers to
302  * the same string, and so any changes made to the strings
303  * should be done very carefully.
304  *
305  * Note that g_string_chunk_insert_const() will not return a
306  * pointer to a string added with g_string_chunk_insert(), even
307  * if they do match.
308  *
309  * Returns: a pointer to the new or existing copy of @string
310  *          within the #GStringChunk
311  */
312 gchar*
313 g_string_chunk_insert_const (GStringChunk *chunk,
314                              const gchar  *string)
315 {
316   char* lookup;
317
318   g_return_val_if_fail (chunk != NULL, NULL);
319
320   if (!chunk->const_table)
321     chunk->const_table = g_hash_table_new (g_str_hash, g_str_equal);
322
323   lookup = (char*) g_hash_table_lookup (chunk->const_table, (gchar *)string);
324
325   if (!lookup)
326     {
327       lookup = g_string_chunk_insert (chunk, string);
328       g_hash_table_insert (chunk->const_table, lookup, lookup);
329     }
330
331   return lookup;
332 }
333
334 /**
335  * g_string_chunk_insert_len:
336  * @chunk: a #GStringChunk
337  * @string: bytes to insert
338  * @len: number of bytes of @string to insert, or -1 to insert a
339  *     nul-terminated string
340  *
341  * Adds a copy of the first @len bytes of @string to the #GStringChunk.
342  * The copy is nul-terminated.
343  *
344  * Since this function does not stop at nul bytes, it is the caller's
345  * responsibility to ensure that @string has at least @len addressable
346  * bytes.
347  *
348  * The characters in the returned string can be changed, if necessary,
349  * though you should not change anything after the end of the string.
350  *
351  * Return value: a pointer to the copy of @string within the #GStringChunk
352  *
353  * Since: 2.4
354  */
355 gchar*
356 g_string_chunk_insert_len (GStringChunk *chunk,
357                            const gchar  *string,
358                            gssize        len)
359 {
360   gssize size;
361   gchar* pos;
362
363   g_return_val_if_fail (chunk != NULL, NULL);
364
365   if (len < 0)
366     size = strlen (string);
367   else
368     size = len;
369
370   if ((chunk->storage_next + size + 1) > chunk->this_size)
371     {
372       gsize new_size = nearest_power (chunk->default_size, size + 1);
373
374       chunk->storage_list = g_slist_prepend (chunk->storage_list,
375                                              g_new (gchar, new_size));
376
377       chunk->this_size = new_size;
378       chunk->storage_next = 0;
379     }
380
381   pos = ((gchar *) chunk->storage_list->data) + chunk->storage_next;
382
383   *(pos + size) = '\0';
384
385   memcpy (pos, string, size);
386
387   chunk->storage_next += size + 1;
388
389   return pos;
390 }
391
392 /* Strings.
393  */
394 static void
395 g_string_maybe_expand (GString* string,
396                        gsize    len) 
397 {
398   if (string->len + len >= string->allocated_len)
399     {
400       string->allocated_len = nearest_power (1, string->len + len + 1);
401       string->str = g_realloc (string->str, string->allocated_len);
402     }
403 }
404
405 /**
406  * g_string_sized_new:
407  * @dfl_size: the default size of the space allocated to 
408  *            hold the string
409  *
410  * Creates a new #GString, with enough space for @dfl_size 
411  * bytes. This is useful if you are going to add a lot of 
412  * text to the string and don't want it to be reallocated 
413  * too often.
414  *
415  * Returns: the new #GString
416  */
417 GString*
418 g_string_sized_new (gsize dfl_size)    
419 {
420   GString *string = g_slice_new (GString);
421
422   string->allocated_len = 0;
423   string->len   = 0;
424   string->str   = NULL;
425
426   g_string_maybe_expand (string, MAX (dfl_size, 2));
427   string->str[0] = 0;
428
429   return string;
430 }
431
432 /**
433  * g_string_new:
434  * @init: the initial text to copy into the string
435  * 
436  * Creates a new #GString, initialized with the given string.
437  *
438  * Returns: the new #GString
439  */
440 GString*
441 g_string_new (const gchar *init)
442 {
443   GString *string;
444
445   if (init == NULL || *init == '\0')
446     string = g_string_sized_new (2);
447   else 
448     {
449       gint len;
450
451       len = strlen (init);
452       string = g_string_sized_new (len + 2);
453
454       g_string_append_len (string, init, len);
455     }
456
457   return string;
458 }
459
460 /**
461  * g_string_new_len:
462  * @init: initial contents of the string
463  * @len: length of @init to use
464  *
465  * Creates a new #GString with @len bytes of the @init buffer.  
466  * Because a length is provided, @init need not be nul-terminated,
467  * and can contain embedded nul bytes.
468  *
469  * Since this function does not stop at nul bytes, it is the caller's
470  * responsibility to ensure that @init has at least @len addressable 
471  * bytes.
472  *
473  * Returns: a new #GString
474  */
475 GString*
476 g_string_new_len (const gchar *init,
477                   gssize       len)    
478 {
479   GString *string;
480
481   if (len < 0)
482     return g_string_new (init);
483   else
484     {
485       string = g_string_sized_new (len);
486       
487       if (init)
488         g_string_append_len (string, init, len);
489       
490       return string;
491     }
492 }
493
494 /**
495  * g_string_free:
496  * @string: a #GString
497  * @free_segment: if %TRUE the actual character data is freed as well
498  *
499  * Frees the memory allocated for the #GString.
500  * If @free_segment is %TRUE it also frees the character data.
501  *
502  * Returns: the character data of @string 
503  *          (i.e. %NULL if @free_segment is %TRUE)
504  */
505 gchar*
506 g_string_free (GString *string,
507                gboolean free_segment)
508 {
509   gchar *segment;
510
511   g_return_val_if_fail (string != NULL, NULL);
512
513   if (free_segment)
514     {
515       g_free (string->str);
516       segment = NULL;
517     }
518   else
519     segment = string->str;
520
521   g_slice_free (GString, string);
522
523   return segment;
524 }
525
526 /**
527  * g_string_equal:
528  * @v: a #GString
529  * @v2: another #GString
530  *
531  * Compares two strings for equality, returning %TRUE if they are equal. 
532  * For use with #GHashTable.
533  *
534  * Returns: %TRUE if they strings are the same length and contain the 
535  *   same bytes
536  */
537 gboolean
538 g_string_equal (const GString *v,
539                 const GString *v2)
540 {
541   gchar *p, *q;
542   GString *string1 = (GString *) v;
543   GString *string2 = (GString *) v2;
544   gsize i = string1->len;    
545
546   if (i != string2->len)
547     return FALSE;
548
549   p = string1->str;
550   q = string2->str;
551   while (i)
552     {
553       if (*p != *q)
554         return FALSE;
555       p++;
556       q++;
557       i--;
558     }
559   return TRUE;
560 }
561
562 /**
563  * g_string_hash:
564  * @str: a string to hash
565  *
566  * Creates a hash code for @str; for use with #GHashTable.
567  *
568  * Returns: hash code for @str
569  */
570 /* 31 bit hash function */
571 guint
572 g_string_hash (const GString *str)
573 {
574   const gchar *p = str->str;
575   gsize n = str->len;    
576   guint h = 0;
577
578   while (n--)
579     {
580       h = (h << 5) - h + *p;
581       p++;
582     }
583
584   return h;
585 }
586
587 /**
588  * g_string_assign:
589  * @string: the destination #GString. Its current contents 
590  *          are destroyed.
591  * @rval: the string to copy into @string
592  *
593  * Copies the bytes from a string into a #GString, 
594  * destroying any previous contents. It is rather like 
595  * the standard strcpy() function, except that you do not 
596  * have to worry about having enough space to copy the string.
597  *
598  * Returns: @string
599  */
600 GString*
601 g_string_assign (GString     *string,
602                  const gchar *rval)
603 {
604   g_return_val_if_fail (string != NULL, NULL);
605   g_return_val_if_fail (rval != NULL, string);
606
607   /* Make sure assigning to itself doesn't corrupt the string.  */
608   if (string->str != rval)
609     {
610       /* Assigning from substring should be ok since g_string_truncate
611          does not realloc.  */
612       g_string_truncate (string, 0);
613       g_string_append (string, rval);
614     }
615
616   return string;
617 }
618
619 /**
620  * g_string_truncate:
621  * @string: a #GString
622  * @len: the new size of @string
623  *
624  * Cuts off the end of the GString, leaving the first @len bytes. 
625  *
626  * Returns: @string
627  */
628 GString*
629 g_string_truncate (GString *string,
630                    gsize    len)    
631 {
632   g_return_val_if_fail (string != NULL, NULL);
633
634   string->len = MIN (len, string->len);
635   string->str[string->len] = 0;
636
637   return string;
638 }
639
640 /**
641  * g_string_set_size:
642  * @string: a #GString
643  * @len: the new length
644  * 
645  * Sets the length of a #GString. If the length is less than
646  * the current length, the string will be truncated. If the
647  * length is greater than the current length, the contents
648  * of the newly added area are undefined. (However, as
649  * always, string->str[string->len] will be a nul byte.) 
650  * 
651  * Return value: @string
652  **/
653 GString*
654 g_string_set_size (GString *string,
655                    gsize    len)    
656 {
657   g_return_val_if_fail (string != NULL, NULL);
658
659   if (len >= string->allocated_len)
660     g_string_maybe_expand (string, len - string->len);
661   
662   string->len = len;
663   string->str[len] = 0;
664
665   return string;
666 }
667
668 /**
669  * g_string_insert_len:
670  * @string: a #GString
671  * @pos: position in @string where insertion should
672  *       happen, or -1 for at the end
673  * @val: bytes to insert
674  * @len: number of bytes of @val to insert
675  *
676  * Inserts @len bytes of @val into @string at @pos.
677  * Because @len is provided, @val may contain embedded
678  * nuls and need not be nul-terminated. If @pos is -1,
679  * bytes are inserted at the end of the string.
680  *
681  * Since this function does not stop at nul bytes, it is
682  * the caller's responsibility to ensure that @val has at
683  * least @len addressable bytes.
684  *
685  * Returns: @string
686  */
687 GString*
688 g_string_insert_len (GString     *string,
689                      gssize       pos,
690                      const gchar *val,
691                      gssize       len)
692 {
693   g_return_val_if_fail (string != NULL, NULL);
694   g_return_val_if_fail (len == 0 || val != NULL, string);
695
696   if (len == 0)
697     return string;
698
699   if (len < 0)
700     len = strlen (val);
701
702   if (pos < 0)
703     pos = string->len;
704   else
705     g_return_val_if_fail (pos <= string->len, string);
706
707   /* Check whether val represents a substring of string.  This test
708      probably violates chapter and verse of the C standards, since
709      ">=" and "<=" are only valid when val really is a substring.
710      In practice, it will work on modern archs.  */
711   if (val >= string->str && val <= string->str + string->len)
712     {
713       gsize offset = val - string->str;
714       gsize precount = 0;
715
716       g_string_maybe_expand (string, len);
717       val = string->str + offset;
718       /* At this point, val is valid again.  */
719
720       /* Open up space where we are going to insert.  */
721       if (pos < string->len)
722         g_memmove (string->str + pos + len, string->str + pos, string->len - pos);
723
724       /* Move the source part before the gap, if any.  */
725       if (offset < pos)
726         {
727           precount = MIN (len, pos - offset);
728           memcpy (string->str + pos, val, precount);
729         }
730
731       /* Move the source part after the gap, if any.  */
732       if (len > precount)
733         memcpy (string->str + pos + precount,
734                 val + /* Already moved: */ precount + /* Space opened up: */ len,
735                 len - precount);
736     }
737   else
738     {
739       g_string_maybe_expand (string, len);
740
741       /* If we aren't appending at the end, move a hunk
742        * of the old string to the end, opening up space
743        */
744       if (pos < string->len)
745         g_memmove (string->str + pos + len, string->str + pos, string->len - pos);
746
747       /* insert the new string */
748       if (len == 1)
749         string->str[pos] = *val;
750       else
751         memcpy (string->str + pos, val, len);
752     }
753
754   string->len += len;
755
756   string->str[string->len] = 0;
757
758   return string;
759 }
760
761 #define SUB_DELIM_CHARS  "!$&'()*+,;="
762
763 static gboolean
764 is_valid (char c, const char *reserved_chars_allowed)
765 {
766   if (g_ascii_isalnum (c) ||
767       c == '-' ||
768       c == '.' ||
769       c == '_' ||
770       c == '~')
771     return TRUE;
772
773   if (reserved_chars_allowed &&
774       strchr (reserved_chars_allowed, c) != NULL)
775     return TRUE;
776   
777   return FALSE;
778 }
779
780 static gboolean 
781 gunichar_ok (gunichar c)
782 {
783   return
784     (c != (gunichar) -2) &&
785     (c != (gunichar) -1);
786 }
787
788 /**
789  * g_string_append_uri_escaped:
790  * @string: a #GString
791  * @unescaped: a string
792  * @reserved_chars_allowed: a string of reserved characters allowed to be used, or %NULL
793  * @allow_utf8: set %TRUE if the escaped string may include UTF8 characters
794  * 
795  * Appends @unescaped to @string, escaped any characters that
796  * are reserved in URIs using URI-style escape sequences.
797  * 
798  * Returns: @string
799  *
800  * Since: 2.16
801  **/
802 GString *
803 g_string_append_uri_escaped (GString *string,
804                              const char *unescaped,
805                              const char *reserved_chars_allowed,
806                              gboolean allow_utf8)
807 {
808   unsigned char c;
809   const char *end;
810   static const gchar hex[16] = "0123456789ABCDEF";
811
812   g_return_val_if_fail (string != NULL, NULL);
813   g_return_val_if_fail (unescaped != NULL, NULL);
814
815   end = unescaped + strlen (unescaped);
816   
817   while ((c = *unescaped) != 0)
818     {
819       if (c >= 0x80 && allow_utf8 &&
820           gunichar_ok (g_utf8_get_char_validated (unescaped, end - unescaped)))
821         {
822           int len = g_utf8_skip [c];
823           g_string_append_len (string, unescaped, len);
824           unescaped += len;
825         }
826       else if (is_valid (c, reserved_chars_allowed))
827         {
828           g_string_append_c (string, c);
829           unescaped++;
830         }
831       else
832         {
833           g_string_append_c (string, '%');
834           g_string_append_c (string, hex[((guchar)c) >> 4]);
835           g_string_append_c (string, hex[((guchar)c) & 0xf]);
836           unescaped++;
837         }
838     }
839
840   return string;
841 }
842
843 /**
844  * g_string_append:
845  * @string: a #GString
846  * @val: the string to append onto the end of @string
847  * 
848  * Adds a string onto the end of a #GString, expanding 
849  * it if necessary.
850  *
851  * Returns: @string
852  */
853 GString*
854 g_string_append (GString     *string,
855                  const gchar *val)
856 {  
857   g_return_val_if_fail (string != NULL, NULL);
858   g_return_val_if_fail (val != NULL, string);
859
860   return g_string_insert_len (string, -1, val, -1);
861 }
862
863 /**
864  * g_string_append_len:
865  * @string: a #GString
866  * @val: bytes to append
867  * @len: number of bytes of @val to use
868  * 
869  * Appends @len bytes of @val to @string. Because @len is 
870  * provided, @val may contain embedded nuls and need not 
871  * be nul-terminated.
872  * 
873  * Since this function does not stop at nul bytes, it is 
874  * the caller's responsibility to ensure that @val has at 
875  * least @len addressable bytes.
876  *
877  * Returns: @string
878  */
879 GString*
880 g_string_append_len (GString     *string,
881                      const gchar *val,
882                      gssize       len)    
883 {
884   g_return_val_if_fail (string != NULL, NULL);
885   g_return_val_if_fail (len == 0 || val != NULL, string);
886
887   return g_string_insert_len (string, -1, val, len);
888 }
889
890 /**
891  * g_string_append_c:
892  * @string: a #GString
893  * @c: the byte to append onto the end of @string
894  *
895  * Adds a byte onto the end of a #GString, expanding 
896  * it if necessary.
897  * 
898  * Returns: @string
899  */
900 #undef g_string_append_c
901 GString*
902 g_string_append_c (GString *string,
903                    gchar    c)
904 {
905   g_return_val_if_fail (string != NULL, NULL);
906
907   return g_string_insert_c (string, -1, c);
908 }
909
910 /**
911  * g_string_append_unichar:
912  * @string: a #GString
913  * @wc: a Unicode character
914  * 
915  * Converts a Unicode character into UTF-8, and appends it
916  * to the string.
917  * 
918  * Return value: @string
919  **/
920 GString*
921 g_string_append_unichar (GString  *string,
922                          gunichar  wc)
923 {  
924   g_return_val_if_fail (string != NULL, NULL);
925   
926   return g_string_insert_unichar (string, -1, wc);
927 }
928
929 /**
930  * g_string_prepend:
931  * @string: a #GString
932  * @val: the string to prepend on the start of @string
933  *
934  * Adds a string on to the start of a #GString, 
935  * expanding it if necessary.
936  *
937  * Returns: @string
938  */
939 GString*
940 g_string_prepend (GString     *string,
941                   const gchar *val)
942 {
943   g_return_val_if_fail (string != NULL, NULL);
944   g_return_val_if_fail (val != NULL, string);
945   
946   return g_string_insert_len (string, 0, val, -1);
947 }
948
949 /**
950  * g_string_prepend_len:
951  * @string: a #GString
952  * @val: bytes to prepend
953  * @len: number of bytes in @val to prepend
954  *
955  * Prepends @len bytes of @val to @string. 
956  * Because @len is provided, @val may contain 
957  * embedded nuls and need not be nul-terminated.
958  *
959  * Since this function does not stop at nul bytes, 
960  * it is the caller's responsibility to ensure that 
961  * @val has at least @len addressable bytes.
962  *
963  * Returns: @string
964  */
965 GString*
966 g_string_prepend_len (GString     *string,
967                       const gchar *val,
968                       gssize       len)    
969 {
970   g_return_val_if_fail (string != NULL, NULL);
971   g_return_val_if_fail (val != NULL, string);
972
973   return g_string_insert_len (string, 0, val, len);
974 }
975
976 /**
977  * g_string_prepend_c:
978  * @string: a #GString
979  * @c: the byte to prepend on the start of the #GString
980  *
981  * Adds a byte onto the start of a #GString, 
982  * expanding it if necessary.
983  *
984  * Returns: @string
985  */
986 GString*
987 g_string_prepend_c (GString *string,
988                     gchar    c)
989 {  
990   g_return_val_if_fail (string != NULL, NULL);
991   
992   return g_string_insert_c (string, 0, c);
993 }
994
995 /**
996  * g_string_prepend_unichar:
997  * @string: a #GString
998  * @wc: a Unicode character
999  * 
1000  * Converts a Unicode character into UTF-8, and prepends it
1001  * to the string.
1002  * 
1003  * Return value: @string
1004  **/
1005 GString*
1006 g_string_prepend_unichar (GString  *string,
1007                           gunichar  wc)
1008 {  
1009   g_return_val_if_fail (string != NULL, NULL);
1010   
1011   return g_string_insert_unichar (string, 0, wc);
1012 }
1013
1014 /**
1015  * g_string_insert:
1016  * @string: a #GString
1017  * @pos: the position to insert the copy of the string
1018  * @val: the string to insert
1019  *
1020  * Inserts a copy of a string into a #GString, 
1021  * expanding it if necessary.
1022  *
1023  * Returns: @string
1024  */
1025 GString*
1026 g_string_insert (GString     *string,
1027                  gssize       pos,    
1028                  const gchar *val)
1029 {
1030   g_return_val_if_fail (string != NULL, NULL);
1031   g_return_val_if_fail (val != NULL, string);
1032   if (pos >= 0)
1033     g_return_val_if_fail (pos <= string->len, string);
1034   
1035   return g_string_insert_len (string, pos, val, -1);
1036 }
1037
1038 /**
1039  * g_string_insert_c:
1040  * @string: a #GString
1041  * @pos: the position to insert the byte
1042  * @c: the byte to insert
1043  *
1044  * Inserts a byte into a #GString, expanding it if necessary.
1045  * 
1046  * Returns: @string
1047  */
1048 GString*
1049 g_string_insert_c (GString *string,
1050                    gssize   pos,    
1051                    gchar    c)
1052 {
1053   g_return_val_if_fail (string != NULL, NULL);
1054
1055   g_string_maybe_expand (string, 1);
1056
1057   if (pos < 0)
1058     pos = string->len;
1059   else
1060     g_return_val_if_fail (pos <= string->len, string);
1061   
1062   /* If not just an append, move the old stuff */
1063   if (pos < string->len)
1064     g_memmove (string->str + pos + 1, string->str + pos, string->len - pos);
1065
1066   string->str[pos] = c;
1067
1068   string->len += 1;
1069
1070   string->str[string->len] = 0;
1071
1072   return string;
1073 }
1074
1075 /**
1076  * g_string_insert_unichar:
1077  * @string: a #GString
1078  * @pos: the position at which to insert character, or -1 to
1079  *       append at the end of the string
1080  * @wc: a Unicode character
1081  * 
1082  * Converts a Unicode character into UTF-8, and insert it
1083  * into the string at the given position.
1084  * 
1085  * Return value: @string
1086  **/
1087 GString*
1088 g_string_insert_unichar (GString *string,
1089                          gssize   pos,    
1090                          gunichar wc)
1091 {
1092   gint charlen, first, i;
1093   gchar *dest;
1094
1095   g_return_val_if_fail (string != NULL, NULL);
1096
1097   /* Code copied from g_unichar_to_utf() */
1098   if (wc < 0x80)
1099     {
1100       first = 0;
1101       charlen = 1;
1102     }
1103   else if (wc < 0x800)
1104     {
1105       first = 0xc0;
1106       charlen = 2;
1107     }
1108   else if (wc < 0x10000)
1109     {
1110       first = 0xe0;
1111       charlen = 3;
1112     }
1113    else if (wc < 0x200000)
1114     {
1115       first = 0xf0;
1116       charlen = 4;
1117     }
1118   else if (wc < 0x4000000)
1119     {
1120       first = 0xf8;
1121       charlen = 5;
1122     }
1123   else
1124     {
1125       first = 0xfc;
1126       charlen = 6;
1127     }
1128   /* End of copied code */
1129
1130   g_string_maybe_expand (string, charlen);
1131
1132   if (pos < 0)
1133     pos = string->len;
1134   else
1135     g_return_val_if_fail (pos <= string->len, string);
1136
1137   /* If not just an append, move the old stuff */
1138   if (pos < string->len)
1139     g_memmove (string->str + pos + charlen, string->str + pos, string->len - pos);
1140
1141   dest = string->str + pos;
1142   /* Code copied from g_unichar_to_utf() */
1143   for (i = charlen - 1; i > 0; --i)
1144     {
1145       dest[i] = (wc & 0x3f) | 0x80;
1146       wc >>= 6;
1147     }
1148   dest[0] = wc | first;
1149   /* End of copied code */
1150   
1151   string->len += charlen;
1152
1153   string->str[string->len] = 0;
1154
1155   return string;
1156 }
1157
1158 /**
1159  * g_string_overwrite:
1160  * @string: a #GString
1161  * @pos: the position at which to start overwriting
1162  * @val: the string that will overwrite the @string starting at @pos
1163  * 
1164  * Overwrites part of a string, lengthening it if necessary.
1165  * 
1166  * Return value: @string
1167  *
1168  * Since: 2.14
1169  **/
1170 GString *
1171 g_string_overwrite (GString     *string,
1172                     gsize        pos,
1173                     const gchar *val)
1174 {
1175   g_return_val_if_fail (val != NULL, string);
1176   return g_string_overwrite_len (string, pos, val, strlen (val));
1177 }
1178
1179 /**
1180  * g_string_overwrite_len:
1181  * @string: a #GString
1182  * @pos: the position at which to start overwriting
1183  * @val: the string that will overwrite the @string starting at @pos
1184  * @len: the number of bytes to write from @val
1185  * 
1186  * Overwrites part of a string, lengthening it if necessary. 
1187  * This function will work with embedded nuls.
1188  * 
1189  * Return value: @string
1190  *
1191  * Since: 2.14
1192  **/
1193 GString *
1194 g_string_overwrite_len (GString     *string,
1195                         gsize        pos,
1196                         const gchar *val,
1197                         gssize       len)
1198 {
1199   gsize end;
1200
1201   g_return_val_if_fail (string != NULL, NULL);
1202
1203   if (!len)
1204     return string;
1205
1206   g_return_val_if_fail (val != NULL, string);
1207   g_return_val_if_fail (pos <= string->len, string);
1208
1209   if (len < 0)
1210     len = strlen (val);
1211
1212   end = pos + len;
1213
1214   if (end > string->len)
1215     g_string_maybe_expand (string, end - string->len);
1216
1217   memcpy (string->str + pos, val, len);
1218
1219   if (end > string->len)
1220     {
1221       string->str[end] = '\0';
1222       string->len = end;
1223     }
1224
1225   return string;
1226 }
1227
1228 /**
1229  * g_string_erase:
1230  * @string: a #GString
1231  * @pos: the position of the content to remove
1232  * @len: the number of bytes to remove, or -1 to remove all
1233  *       following bytes
1234  *
1235  * Removes @len bytes from a #GString, starting at position @pos.
1236  * The rest of the #GString is shifted down to fill the gap.
1237  *
1238  * Returns: @string
1239  */
1240 GString*
1241 g_string_erase (GString *string,
1242                 gssize   pos,
1243                 gssize   len)
1244 {
1245   g_return_val_if_fail (string != NULL, NULL);
1246   g_return_val_if_fail (pos >= 0, string);
1247   g_return_val_if_fail (pos <= string->len, string);
1248
1249   if (len < 0)
1250     len = string->len - pos;
1251   else
1252     {
1253       g_return_val_if_fail (pos + len <= string->len, string);
1254
1255       if (pos + len < string->len)
1256         g_memmove (string->str + pos, string->str + pos + len, string->len - (pos + len));
1257     }
1258
1259   string->len -= len;
1260   
1261   string->str[string->len] = 0;
1262
1263   return string;
1264 }
1265
1266 /**
1267  * g_string_ascii_down:
1268  * @string: a GString
1269  * 
1270  * Converts all upper case ASCII letters to lower case ASCII letters.
1271  * 
1272  * Return value: passed-in @string pointer, with all the upper case
1273  *               characters converted to lower case in place, with
1274  *               semantics that exactly match g_ascii_tolower().
1275  **/
1276 GString*
1277 g_string_ascii_down (GString *string)
1278 {
1279   gchar *s;
1280   gint n;
1281
1282   g_return_val_if_fail (string != NULL, NULL);
1283
1284   n = string->len;
1285   s = string->str;
1286
1287   while (n)
1288     {
1289       *s = g_ascii_tolower (*s);
1290       s++;
1291       n--;
1292     }
1293
1294   return string;
1295 }
1296
1297 /**
1298  * g_string_ascii_up:
1299  * @string: a GString
1300  * 
1301  * Converts all lower case ASCII letters to upper case ASCII letters.
1302  * 
1303  * Return value: passed-in @string pointer, with all the lower case
1304  *               characters converted to upper case in place, with
1305  *               semantics that exactly match g_ascii_toupper().
1306  **/
1307 GString*
1308 g_string_ascii_up (GString *string)
1309 {
1310   gchar *s;
1311   gint n;
1312
1313   g_return_val_if_fail (string != NULL, NULL);
1314
1315   n = string->len;
1316   s = string->str;
1317
1318   while (n)
1319     {
1320       *s = g_ascii_toupper (*s);
1321       s++;
1322       n--;
1323     }
1324
1325   return string;
1326 }
1327
1328 /**
1329  * g_string_down:
1330  * @string: a #GString
1331  *  
1332  * Converts a #GString to lowercase.
1333  *
1334  * Returns: the #GString.
1335  *
1336  * Deprecated:2.2: This function uses the locale-specific 
1337  *   tolower() function, which is almost never the right thing. 
1338  *   Use g_string_ascii_down() or g_utf8_strdown() instead.
1339  */
1340 GString*
1341 g_string_down (GString *string)
1342 {
1343   guchar *s;
1344   glong n;
1345
1346   g_return_val_if_fail (string != NULL, NULL);
1347
1348   n = string->len;    
1349   s = (guchar *) string->str;
1350
1351   while (n)
1352     {
1353       if (isupper (*s))
1354         *s = tolower (*s);
1355       s++;
1356       n--;
1357     }
1358
1359   return string;
1360 }
1361
1362 /**
1363  * g_string_up:
1364  * @string: a #GString 
1365  * 
1366  * Converts a #GString to uppercase.
1367  * 
1368  * Return value: @string
1369  *
1370  * Deprecated:2.2: This function uses the locale-specific 
1371  *   toupper() function, which is almost never the right thing. 
1372  *   Use g_string_ascii_up() or g_utf8_strup() instead.
1373  **/
1374 GString*
1375 g_string_up (GString *string)
1376 {
1377   guchar *s;
1378   glong n;
1379
1380   g_return_val_if_fail (string != NULL, NULL);
1381
1382   n = string->len;
1383   s = (guchar *) string->str;
1384
1385   while (n)
1386     {
1387       if (islower (*s))
1388         *s = toupper (*s);
1389       s++;
1390       n--;
1391     }
1392
1393   return string;
1394 }
1395
1396 /**
1397  * g_string_append_vprintf:
1398  * @string: a #GString
1399  * @format: the string format. See the printf() documentation
1400  * @args: the list of arguments to insert in the output
1401  *
1402  * Appends a formatted string onto the end of a #GString.
1403  * This function is similar to g_string_append_printf()
1404  * except that the arguments to the format string are passed
1405  * as a va_list.
1406  *
1407  * Since: 2.14
1408  */
1409 void
1410 g_string_append_vprintf (GString     *string,
1411                          const gchar *format,
1412                          va_list      args)
1413 {
1414   gchar *buf;
1415   gint len;
1416   
1417   g_return_if_fail (string != NULL);
1418   g_return_if_fail (format != NULL);
1419
1420   len = g_vasprintf (&buf, format, args);
1421
1422   if (len >= 0)
1423     {
1424       g_string_maybe_expand (string, len);
1425       memcpy (string->str + string->len, buf, len + 1);
1426       string->len += len;
1427       g_free (buf);
1428     }
1429 }
1430
1431 /**
1432  * g_string_vprintf:
1433  * @string: a #GString
1434  * @format: the string format. See the printf() documentation
1435  * @args: the parameters to insert into the format string
1436  *
1437  * Writes a formatted string into a #GString. 
1438  * This function is similar to g_string_printf() except that 
1439  * the arguments to the format string are passed as a va_list.
1440  *
1441  * Since: 2.14
1442  */
1443 void
1444 g_string_vprintf (GString     *string,
1445                   const gchar *format,
1446                   va_list      args)
1447 {
1448   g_string_truncate (string, 0);
1449   g_string_append_vprintf (string, format, args);
1450 }
1451
1452 /**
1453  * g_string_sprintf:
1454  * @string: a #GString
1455  * @format: the string format. See the sprintf() documentation
1456  * @Varargs: the parameters to insert into the format string
1457  *
1458  * Writes a formatted string into a #GString.
1459  * This is similar to the standard sprintf() function,
1460  * except that the #GString buffer automatically expands 
1461  * to contain the results. The previous contents of the 
1462  * #GString are destroyed. 
1463  *
1464  * Deprecated: This function has been renamed to g_string_printf().
1465  */
1466
1467 /**
1468  * g_string_printf:
1469  * @string: a #GString
1470  * @format: the string format. See the printf() documentation
1471  * @Varargs: the parameters to insert into the format string
1472  *
1473  * Writes a formatted string into a #GString.
1474  * This is similar to the standard sprintf() function,
1475  * except that the #GString buffer automatically expands 
1476  * to contain the results. The previous contents of the 
1477  * #GString are destroyed.
1478  */
1479 void
1480 g_string_printf (GString     *string,
1481                  const gchar *format,
1482                  ...)
1483 {
1484   va_list args;
1485
1486   g_string_truncate (string, 0);
1487
1488   va_start (args, format);
1489   g_string_append_vprintf (string, format, args);
1490   va_end (args);
1491 }
1492
1493 /**
1494  * g_string_sprintfa:
1495  * @string: a #GString
1496  * @format: the string format. See the sprintf() documentation
1497  * @Varargs: the parameters to insert into the format string
1498  *
1499  * Appends a formatted string onto the end of a #GString.
1500  * This function is similar to g_string_sprintf() except that
1501  * the text is appended to the #GString. 
1502  *
1503  * Deprecated: This function has been renamed to g_string_append_printf()
1504  */
1505
1506 /**
1507  * g_string_append_printf:
1508  * @string: a #GString
1509  * @format: the string format. See the printf() documentation
1510  * @Varargs: the parameters to insert into the format string
1511  *
1512  * Appends a formatted string onto the end of a #GString.
1513  * This function is similar to g_string_printf() except 
1514  * that the text is appended to the #GString.
1515  */
1516 void
1517 g_string_append_printf (GString     *string,
1518                         const gchar *format,
1519                         ...)
1520 {
1521   va_list args;
1522
1523   va_start (args, format);
1524   g_string_append_vprintf (string, format, args);
1525   va_end (args);
1526 }