Clean up g_thread_yield implementation
[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.  If 
501  * it's %FALSE, the caller gains ownership of the buffer and must
502  * free it after use with g_free().
503  *
504  * Returns: the character data of @string 
505  *          (i.e. %NULL if @free_segment is %TRUE)
506  */
507 gchar*
508 g_string_free (GString *string,
509                gboolean free_segment)
510 {
511   gchar *segment;
512
513   g_return_val_if_fail (string != NULL, NULL);
514
515   if (free_segment)
516     {
517       g_free (string->str);
518       segment = NULL;
519     }
520   else
521     segment = string->str;
522
523   g_slice_free (GString, string);
524
525   return segment;
526 }
527
528 /**
529  * g_string_equal:
530  * @v: a #GString
531  * @v2: another #GString
532  *
533  * Compares two strings for equality, returning %TRUE if they are equal. 
534  * For use with #GHashTable.
535  *
536  * Returns: %TRUE if they strings are the same length and contain the 
537  *   same bytes
538  */
539 gboolean
540 g_string_equal (const GString *v,
541                 const GString *v2)
542 {
543   gchar *p, *q;
544   GString *string1 = (GString *) v;
545   GString *string2 = (GString *) v2;
546   gsize i = string1->len;    
547
548   if (i != string2->len)
549     return FALSE;
550
551   p = string1->str;
552   q = string2->str;
553   while (i)
554     {
555       if (*p != *q)
556         return FALSE;
557       p++;
558       q++;
559       i--;
560     }
561   return TRUE;
562 }
563
564 /**
565  * g_string_hash:
566  * @str: a string to hash
567  *
568  * Creates a hash code for @str; for use with #GHashTable.
569  *
570  * Returns: hash code for @str
571  */
572 /* 31 bit hash function */
573 guint
574 g_string_hash (const GString *str)
575 {
576   const gchar *p = str->str;
577   gsize n = str->len;    
578   guint h = 0;
579
580   while (n--)
581     {
582       h = (h << 5) - h + *p;
583       p++;
584     }
585
586   return h;
587 }
588
589 /**
590  * g_string_assign:
591  * @string: the destination #GString. Its current contents 
592  *          are destroyed.
593  * @rval: the string to copy into @string
594  *
595  * Copies the bytes from a string into a #GString, 
596  * destroying any previous contents. It is rather like 
597  * the standard strcpy() function, except that you do not 
598  * have to worry about having enough space to copy the string.
599  *
600  * Returns: @string
601  */
602 GString*
603 g_string_assign (GString     *string,
604                  const gchar *rval)
605 {
606   g_return_val_if_fail (string != NULL, NULL);
607   g_return_val_if_fail (rval != NULL, string);
608
609   /* Make sure assigning to itself doesn't corrupt the string.  */
610   if (string->str != rval)
611     {
612       /* Assigning from substring should be ok since g_string_truncate
613          does not realloc.  */
614       g_string_truncate (string, 0);
615       g_string_append (string, rval);
616     }
617
618   return string;
619 }
620
621 /**
622  * g_string_truncate:
623  * @string: a #GString
624  * @len: the new size of @string
625  *
626  * Cuts off the end of the GString, leaving the first @len bytes. 
627  *
628  * Returns: @string
629  */
630 GString*
631 g_string_truncate (GString *string,
632                    gsize    len)    
633 {
634   g_return_val_if_fail (string != NULL, NULL);
635
636   string->len = MIN (len, string->len);
637   string->str[string->len] = 0;
638
639   return string;
640 }
641
642 /**
643  * g_string_set_size:
644  * @string: a #GString
645  * @len: the new length
646  * 
647  * Sets the length of a #GString. If the length is less than
648  * the current length, the string will be truncated. If the
649  * length is greater than the current length, the contents
650  * of the newly added area are undefined. (However, as
651  * always, string->str[string->len] will be a nul byte.) 
652  * 
653  * Return value: @string
654  **/
655 GString*
656 g_string_set_size (GString *string,
657                    gsize    len)    
658 {
659   g_return_val_if_fail (string != NULL, NULL);
660
661   if (len >= string->allocated_len)
662     g_string_maybe_expand (string, len - string->len);
663   
664   string->len = len;
665   string->str[len] = 0;
666
667   return string;
668 }
669
670 /**
671  * g_string_insert_len:
672  * @string: a #GString
673  * @pos: position in @string where insertion should
674  *       happen, or -1 for at the end
675  * @val: bytes to insert
676  * @len: number of bytes of @val to insert
677  *
678  * Inserts @len bytes of @val into @string at @pos.
679  * Because @len is provided, @val may contain embedded
680  * nuls and need not be nul-terminated. If @pos is -1,
681  * bytes are inserted at the end of the string.
682  *
683  * Since this function does not stop at nul bytes, it is
684  * the caller's responsibility to ensure that @val has at
685  * least @len addressable bytes.
686  *
687  * Returns: @string
688  */
689 GString*
690 g_string_insert_len (GString     *string,
691                      gssize       pos,
692                      const gchar *val,
693                      gssize       len)
694 {
695   g_return_val_if_fail (string != NULL, NULL);
696   g_return_val_if_fail (len == 0 || val != NULL, string);
697
698   if (len == 0)
699     return string;
700
701   if (len < 0)
702     len = strlen (val);
703
704   if (pos < 0)
705     pos = string->len;
706   else
707     g_return_val_if_fail (pos <= string->len, string);
708
709   /* Check whether val represents a substring of string.  This test
710      probably violates chapter and verse of the C standards, since
711      ">=" and "<=" are only valid when val really is a substring.
712      In practice, it will work on modern archs.  */
713   if (val >= string->str && val <= string->str + string->len)
714     {
715       gsize offset = val - string->str;
716       gsize precount = 0;
717
718       g_string_maybe_expand (string, len);
719       val = string->str + offset;
720       /* At this point, val is valid again.  */
721
722       /* Open up space where we are going to insert.  */
723       if (pos < string->len)
724         g_memmove (string->str + pos + len, string->str + pos, string->len - pos);
725
726       /* Move the source part before the gap, if any.  */
727       if (offset < pos)
728         {
729           precount = MIN (len, pos - offset);
730           memcpy (string->str + pos, val, precount);
731         }
732
733       /* Move the source part after the gap, if any.  */
734       if (len > precount)
735         memcpy (string->str + pos + precount,
736                 val + /* Already moved: */ precount + /* Space opened up: */ len,
737                 len - precount);
738     }
739   else
740     {
741       g_string_maybe_expand (string, len);
742
743       /* If we aren't appending at the end, move a hunk
744        * of the old string to the end, opening up space
745        */
746       if (pos < string->len)
747         g_memmove (string->str + pos + len, string->str + pos, string->len - pos);
748
749       /* insert the new string */
750       if (len == 1)
751         string->str[pos] = *val;
752       else
753         memcpy (string->str + pos, val, len);
754     }
755
756   string->len += len;
757
758   string->str[string->len] = 0;
759
760   return string;
761 }
762
763 #define SUB_DELIM_CHARS  "!$&'()*+,;="
764
765 static gboolean
766 is_valid (char c, const char *reserved_chars_allowed)
767 {
768   if (g_ascii_isalnum (c) ||
769       c == '-' ||
770       c == '.' ||
771       c == '_' ||
772       c == '~')
773     return TRUE;
774
775   if (reserved_chars_allowed &&
776       strchr (reserved_chars_allowed, c) != NULL)
777     return TRUE;
778   
779   return FALSE;
780 }
781
782 static gboolean 
783 gunichar_ok (gunichar c)
784 {
785   return
786     (c != (gunichar) -2) &&
787     (c != (gunichar) -1);
788 }
789
790 /**
791  * g_string_append_uri_escaped:
792  * @string: a #GString
793  * @unescaped: a string
794  * @reserved_chars_allowed: a string of reserved characters allowed to be used, or %NULL
795  * @allow_utf8: set %TRUE if the escaped string may include UTF8 characters
796  * 
797  * Appends @unescaped to @string, escaped any characters that
798  * are reserved in URIs using URI-style escape sequences.
799  * 
800  * Returns: @string
801  *
802  * Since: 2.16
803  **/
804 GString *
805 g_string_append_uri_escaped (GString *string,
806                              const char *unescaped,
807                              const char *reserved_chars_allowed,
808                              gboolean allow_utf8)
809 {
810   unsigned char c;
811   const char *end;
812   static const gchar hex[16] = "0123456789ABCDEF";
813
814   g_return_val_if_fail (string != NULL, NULL);
815   g_return_val_if_fail (unescaped != NULL, NULL);
816
817   end = unescaped + strlen (unescaped);
818   
819   while ((c = *unescaped) != 0)
820     {
821       if (c >= 0x80 && allow_utf8 &&
822           gunichar_ok (g_utf8_get_char_validated (unescaped, end - unescaped)))
823         {
824           int len = g_utf8_skip [c];
825           g_string_append_len (string, unescaped, len);
826           unescaped += len;
827         }
828       else if (is_valid (c, reserved_chars_allowed))
829         {
830           g_string_append_c (string, c);
831           unescaped++;
832         }
833       else
834         {
835           g_string_append_c (string, '%');
836           g_string_append_c (string, hex[((guchar)c) >> 4]);
837           g_string_append_c (string, hex[((guchar)c) & 0xf]);
838           unescaped++;
839         }
840     }
841
842   return string;
843 }
844
845 /**
846  * g_string_append:
847  * @string: a #GString
848  * @val: the string to append onto the end of @string
849  * 
850  * Adds a string onto the end of a #GString, expanding 
851  * it if necessary.
852  *
853  * Returns: @string
854  */
855 GString*
856 g_string_append (GString     *string,
857                  const gchar *val)
858 {  
859   g_return_val_if_fail (string != NULL, NULL);
860   g_return_val_if_fail (val != NULL, string);
861
862   return g_string_insert_len (string, -1, val, -1);
863 }
864
865 /**
866  * g_string_append_len:
867  * @string: a #GString
868  * @val: bytes to append
869  * @len: number of bytes of @val to use
870  * 
871  * Appends @len bytes of @val to @string. Because @len is 
872  * provided, @val may contain embedded nuls and need not 
873  * be nul-terminated.
874  * 
875  * Since this function does not stop at nul bytes, it is 
876  * the caller's responsibility to ensure that @val has at 
877  * least @len addressable bytes.
878  *
879  * Returns: @string
880  */
881 GString*
882 g_string_append_len (GString     *string,
883                      const gchar *val,
884                      gssize       len)    
885 {
886   g_return_val_if_fail (string != NULL, NULL);
887   g_return_val_if_fail (len == 0 || val != NULL, string);
888
889   return g_string_insert_len (string, -1, val, len);
890 }
891
892 /**
893  * g_string_append_c:
894  * @string: a #GString
895  * @c: the byte to append onto the end of @string
896  *
897  * Adds a byte onto the end of a #GString, expanding 
898  * it if necessary.
899  * 
900  * Returns: @string
901  */
902 #undef g_string_append_c
903 GString*
904 g_string_append_c (GString *string,
905                    gchar    c)
906 {
907   g_return_val_if_fail (string != NULL, NULL);
908
909   return g_string_insert_c (string, -1, c);
910 }
911
912 /**
913  * g_string_append_unichar:
914  * @string: a #GString
915  * @wc: a Unicode character
916  * 
917  * Converts a Unicode character into UTF-8, and appends it
918  * to the string.
919  * 
920  * Return value: @string
921  **/
922 GString*
923 g_string_append_unichar (GString  *string,
924                          gunichar  wc)
925 {  
926   g_return_val_if_fail (string != NULL, NULL);
927   
928   return g_string_insert_unichar (string, -1, wc);
929 }
930
931 /**
932  * g_string_prepend:
933  * @string: a #GString
934  * @val: the string to prepend on the start of @string
935  *
936  * Adds a string on to the start of a #GString, 
937  * expanding it if necessary.
938  *
939  * Returns: @string
940  */
941 GString*
942 g_string_prepend (GString     *string,
943                   const gchar *val)
944 {
945   g_return_val_if_fail (string != NULL, NULL);
946   g_return_val_if_fail (val != NULL, string);
947   
948   return g_string_insert_len (string, 0, val, -1);
949 }
950
951 /**
952  * g_string_prepend_len:
953  * @string: a #GString
954  * @val: bytes to prepend
955  * @len: number of bytes in @val to prepend
956  *
957  * Prepends @len bytes of @val to @string. 
958  * Because @len is provided, @val may contain 
959  * embedded nuls and need not be nul-terminated.
960  *
961  * Since this function does not stop at nul bytes, 
962  * it is the caller's responsibility to ensure that 
963  * @val has at least @len addressable bytes.
964  *
965  * Returns: @string
966  */
967 GString*
968 g_string_prepend_len (GString     *string,
969                       const gchar *val,
970                       gssize       len)    
971 {
972   g_return_val_if_fail (string != NULL, NULL);
973   g_return_val_if_fail (val != NULL, string);
974
975   return g_string_insert_len (string, 0, val, len);
976 }
977
978 /**
979  * g_string_prepend_c:
980  * @string: a #GString
981  * @c: the byte to prepend on the start of the #GString
982  *
983  * Adds a byte onto the start of a #GString, 
984  * expanding it if necessary.
985  *
986  * Returns: @string
987  */
988 GString*
989 g_string_prepend_c (GString *string,
990                     gchar    c)
991 {  
992   g_return_val_if_fail (string != NULL, NULL);
993   
994   return g_string_insert_c (string, 0, c);
995 }
996
997 /**
998  * g_string_prepend_unichar:
999  * @string: a #GString
1000  * @wc: a Unicode character
1001  * 
1002  * Converts a Unicode character into UTF-8, and prepends it
1003  * to the string.
1004  * 
1005  * Return value: @string
1006  **/
1007 GString*
1008 g_string_prepend_unichar (GString  *string,
1009                           gunichar  wc)
1010 {  
1011   g_return_val_if_fail (string != NULL, NULL);
1012   
1013   return g_string_insert_unichar (string, 0, wc);
1014 }
1015
1016 /**
1017  * g_string_insert:
1018  * @string: a #GString
1019  * @pos: the position to insert the copy of the string
1020  * @val: the string to insert
1021  *
1022  * Inserts a copy of a string into a #GString, 
1023  * expanding it if necessary.
1024  *
1025  * Returns: @string
1026  */
1027 GString*
1028 g_string_insert (GString     *string,
1029                  gssize       pos,    
1030                  const gchar *val)
1031 {
1032   g_return_val_if_fail (string != NULL, NULL);
1033   g_return_val_if_fail (val != NULL, string);
1034   if (pos >= 0)
1035     g_return_val_if_fail (pos <= string->len, string);
1036   
1037   return g_string_insert_len (string, pos, val, -1);
1038 }
1039
1040 /**
1041  * g_string_insert_c:
1042  * @string: a #GString
1043  * @pos: the position to insert the byte
1044  * @c: the byte to insert
1045  *
1046  * Inserts a byte into a #GString, expanding it if necessary.
1047  * 
1048  * Returns: @string
1049  */
1050 GString*
1051 g_string_insert_c (GString *string,
1052                    gssize   pos,    
1053                    gchar    c)
1054 {
1055   g_return_val_if_fail (string != NULL, NULL);
1056
1057   g_string_maybe_expand (string, 1);
1058
1059   if (pos < 0)
1060     pos = string->len;
1061   else
1062     g_return_val_if_fail (pos <= string->len, string);
1063   
1064   /* If not just an append, move the old stuff */
1065   if (pos < string->len)
1066     g_memmove (string->str + pos + 1, string->str + pos, string->len - pos);
1067
1068   string->str[pos] = c;
1069
1070   string->len += 1;
1071
1072   string->str[string->len] = 0;
1073
1074   return string;
1075 }
1076
1077 /**
1078  * g_string_insert_unichar:
1079  * @string: a #GString
1080  * @pos: the position at which to insert character, or -1 to
1081  *       append at the end of the string
1082  * @wc: a Unicode character
1083  * 
1084  * Converts a Unicode character into UTF-8, and insert it
1085  * into the string at the given position.
1086  * 
1087  * Return value: @string
1088  **/
1089 GString*
1090 g_string_insert_unichar (GString *string,
1091                          gssize   pos,    
1092                          gunichar wc)
1093 {
1094   gint charlen, first, i;
1095   gchar *dest;
1096
1097   g_return_val_if_fail (string != NULL, NULL);
1098
1099   /* Code copied from g_unichar_to_utf() */
1100   if (wc < 0x80)
1101     {
1102       first = 0;
1103       charlen = 1;
1104     }
1105   else if (wc < 0x800)
1106     {
1107       first = 0xc0;
1108       charlen = 2;
1109     }
1110   else if (wc < 0x10000)
1111     {
1112       first = 0xe0;
1113       charlen = 3;
1114     }
1115    else if (wc < 0x200000)
1116     {
1117       first = 0xf0;
1118       charlen = 4;
1119     }
1120   else if (wc < 0x4000000)
1121     {
1122       first = 0xf8;
1123       charlen = 5;
1124     }
1125   else
1126     {
1127       first = 0xfc;
1128       charlen = 6;
1129     }
1130   /* End of copied code */
1131
1132   g_string_maybe_expand (string, charlen);
1133
1134   if (pos < 0)
1135     pos = string->len;
1136   else
1137     g_return_val_if_fail (pos <= string->len, string);
1138
1139   /* If not just an append, move the old stuff */
1140   if (pos < string->len)
1141     g_memmove (string->str + pos + charlen, string->str + pos, string->len - pos);
1142
1143   dest = string->str + pos;
1144   /* Code copied from g_unichar_to_utf() */
1145   for (i = charlen - 1; i > 0; --i)
1146     {
1147       dest[i] = (wc & 0x3f) | 0x80;
1148       wc >>= 6;
1149     }
1150   dest[0] = wc | first;
1151   /* End of copied code */
1152   
1153   string->len += charlen;
1154
1155   string->str[string->len] = 0;
1156
1157   return string;
1158 }
1159
1160 /**
1161  * g_string_overwrite:
1162  * @string: a #GString
1163  * @pos: the position at which to start overwriting
1164  * @val: the string that will overwrite the @string starting at @pos
1165  * 
1166  * Overwrites part of a string, lengthening it if necessary.
1167  * 
1168  * Return value: @string
1169  *
1170  * Since: 2.14
1171  **/
1172 GString *
1173 g_string_overwrite (GString     *string,
1174                     gsize        pos,
1175                     const gchar *val)
1176 {
1177   g_return_val_if_fail (val != NULL, string);
1178   return g_string_overwrite_len (string, pos, val, strlen (val));
1179 }
1180
1181 /**
1182  * g_string_overwrite_len:
1183  * @string: a #GString
1184  * @pos: the position at which to start overwriting
1185  * @val: the string that will overwrite the @string starting at @pos
1186  * @len: the number of bytes to write from @val
1187  * 
1188  * Overwrites part of a string, lengthening it if necessary. 
1189  * This function will work with embedded nuls.
1190  * 
1191  * Return value: @string
1192  *
1193  * Since: 2.14
1194  **/
1195 GString *
1196 g_string_overwrite_len (GString     *string,
1197                         gsize        pos,
1198                         const gchar *val,
1199                         gssize       len)
1200 {
1201   gsize end;
1202
1203   g_return_val_if_fail (string != NULL, NULL);
1204
1205   if (!len)
1206     return string;
1207
1208   g_return_val_if_fail (val != NULL, string);
1209   g_return_val_if_fail (pos <= string->len, string);
1210
1211   if (len < 0)
1212     len = strlen (val);
1213
1214   end = pos + len;
1215
1216   if (end > string->len)
1217     g_string_maybe_expand (string, end - string->len);
1218
1219   memcpy (string->str + pos, val, len);
1220
1221   if (end > string->len)
1222     {
1223       string->str[end] = '\0';
1224       string->len = end;
1225     }
1226
1227   return string;
1228 }
1229
1230 /**
1231  * g_string_erase:
1232  * @string: a #GString
1233  * @pos: the position of the content to remove
1234  * @len: the number of bytes to remove, or -1 to remove all
1235  *       following bytes
1236  *
1237  * Removes @len bytes from a #GString, starting at position @pos.
1238  * The rest of the #GString is shifted down to fill the gap.
1239  *
1240  * Returns: @string
1241  */
1242 GString*
1243 g_string_erase (GString *string,
1244                 gssize   pos,
1245                 gssize   len)
1246 {
1247   g_return_val_if_fail (string != NULL, NULL);
1248   g_return_val_if_fail (pos >= 0, string);
1249   g_return_val_if_fail (pos <= string->len, string);
1250
1251   if (len < 0)
1252     len = string->len - pos;
1253   else
1254     {
1255       g_return_val_if_fail (pos + len <= string->len, string);
1256
1257       if (pos + len < string->len)
1258         g_memmove (string->str + pos, string->str + pos + len, string->len - (pos + len));
1259     }
1260
1261   string->len -= len;
1262   
1263   string->str[string->len] = 0;
1264
1265   return string;
1266 }
1267
1268 /**
1269  * g_string_ascii_down:
1270  * @string: a GString
1271  * 
1272  * Converts all upper case ASCII letters to lower case ASCII letters.
1273  * 
1274  * Return value: passed-in @string pointer, with all the upper case
1275  *               characters converted to lower case in place, with
1276  *               semantics that exactly match g_ascii_tolower().
1277  **/
1278 GString*
1279 g_string_ascii_down (GString *string)
1280 {
1281   gchar *s;
1282   gint n;
1283
1284   g_return_val_if_fail (string != NULL, NULL);
1285
1286   n = string->len;
1287   s = string->str;
1288
1289   while (n)
1290     {
1291       *s = g_ascii_tolower (*s);
1292       s++;
1293       n--;
1294     }
1295
1296   return string;
1297 }
1298
1299 /**
1300  * g_string_ascii_up:
1301  * @string: a GString
1302  * 
1303  * Converts all lower case ASCII letters to upper case ASCII letters.
1304  * 
1305  * Return value: passed-in @string pointer, with all the lower case
1306  *               characters converted to upper case in place, with
1307  *               semantics that exactly match g_ascii_toupper().
1308  **/
1309 GString*
1310 g_string_ascii_up (GString *string)
1311 {
1312   gchar *s;
1313   gint n;
1314
1315   g_return_val_if_fail (string != NULL, NULL);
1316
1317   n = string->len;
1318   s = string->str;
1319
1320   while (n)
1321     {
1322       *s = g_ascii_toupper (*s);
1323       s++;
1324       n--;
1325     }
1326
1327   return string;
1328 }
1329
1330 /**
1331  * g_string_down:
1332  * @string: a #GString
1333  *  
1334  * Converts a #GString to lowercase.
1335  *
1336  * Returns: the #GString.
1337  *
1338  * Deprecated:2.2: This function uses the locale-specific 
1339  *   tolower() function, which is almost never the right thing. 
1340  *   Use g_string_ascii_down() or g_utf8_strdown() instead.
1341  */
1342 GString*
1343 g_string_down (GString *string)
1344 {
1345   guchar *s;
1346   glong n;
1347
1348   g_return_val_if_fail (string != NULL, NULL);
1349
1350   n = string->len;    
1351   s = (guchar *) string->str;
1352
1353   while (n)
1354     {
1355       if (isupper (*s))
1356         *s = tolower (*s);
1357       s++;
1358       n--;
1359     }
1360
1361   return string;
1362 }
1363
1364 /**
1365  * g_string_up:
1366  * @string: a #GString 
1367  * 
1368  * Converts a #GString to uppercase.
1369  * 
1370  * Return value: @string
1371  *
1372  * Deprecated:2.2: This function uses the locale-specific 
1373  *   toupper() function, which is almost never the right thing. 
1374  *   Use g_string_ascii_up() or g_utf8_strup() instead.
1375  **/
1376 GString*
1377 g_string_up (GString *string)
1378 {
1379   guchar *s;
1380   glong n;
1381
1382   g_return_val_if_fail (string != NULL, NULL);
1383
1384   n = string->len;
1385   s = (guchar *) string->str;
1386
1387   while (n)
1388     {
1389       if (islower (*s))
1390         *s = toupper (*s);
1391       s++;
1392       n--;
1393     }
1394
1395   return string;
1396 }
1397
1398 /**
1399  * g_string_append_vprintf:
1400  * @string: a #GString
1401  * @format: the string format. See the printf() documentation
1402  * @args: the list of arguments to insert in the output
1403  *
1404  * Appends a formatted string onto the end of a #GString.
1405  * This function is similar to g_string_append_printf()
1406  * except that the arguments to the format string are passed
1407  * as a va_list.
1408  *
1409  * Since: 2.14
1410  */
1411 void
1412 g_string_append_vprintf (GString     *string,
1413                          const gchar *format,
1414                          va_list      args)
1415 {
1416   gchar *buf;
1417   gint len;
1418   
1419   g_return_if_fail (string != NULL);
1420   g_return_if_fail (format != NULL);
1421
1422   len = g_vasprintf (&buf, format, args);
1423
1424   if (len >= 0)
1425     {
1426       g_string_maybe_expand (string, len);
1427       memcpy (string->str + string->len, buf, len + 1);
1428       string->len += len;
1429       g_free (buf);
1430     }
1431 }
1432
1433 /**
1434  * g_string_vprintf:
1435  * @string: a #GString
1436  * @format: the string format. See the printf() documentation
1437  * @args: the parameters to insert into the format string
1438  *
1439  * Writes a formatted string into a #GString. 
1440  * This function is similar to g_string_printf() except that 
1441  * the arguments to the format string are passed as a va_list.
1442  *
1443  * Since: 2.14
1444  */
1445 void
1446 g_string_vprintf (GString     *string,
1447                   const gchar *format,
1448                   va_list      args)
1449 {
1450   g_string_truncate (string, 0);
1451   g_string_append_vprintf (string, format, args);
1452 }
1453
1454 /**
1455  * g_string_sprintf:
1456  * @string: a #GString
1457  * @format: the string format. See the sprintf() documentation
1458  * @...: the parameters to insert into the format string
1459  *
1460  * Writes a formatted string into a #GString.
1461  * This is similar to the standard sprintf() function,
1462  * except that the #GString buffer automatically expands 
1463  * to contain the results. The previous contents of the 
1464  * #GString are destroyed. 
1465  *
1466  * Deprecated: This function has been renamed to g_string_printf().
1467  */
1468
1469 /**
1470  * g_string_printf:
1471  * @string: a #GString
1472  * @format: the string format. See the printf() documentation
1473  * @...: the parameters to insert into the format string
1474  *
1475  * Writes a formatted string into a #GString.
1476  * This is similar to the standard sprintf() function,
1477  * except that the #GString buffer automatically expands 
1478  * to contain the results. The previous contents of the 
1479  * #GString are destroyed.
1480  */
1481 void
1482 g_string_printf (GString     *string,
1483                  const gchar *format,
1484                  ...)
1485 {
1486   va_list args;
1487
1488   g_string_truncate (string, 0);
1489
1490   va_start (args, format);
1491   g_string_append_vprintf (string, format, args);
1492   va_end (args);
1493 }
1494
1495 /**
1496  * g_string_sprintfa:
1497  * @string: a #GString
1498  * @format: the string format. See the sprintf() documentation
1499  * @...: the parameters to insert into the format string
1500  *
1501  * Appends a formatted string onto the end of a #GString.
1502  * This function is similar to g_string_sprintf() except that
1503  * the text is appended to the #GString. 
1504  *
1505  * Deprecated: This function has been renamed to g_string_append_printf()
1506  */
1507
1508 /**
1509  * g_string_append_printf:
1510  * @string: a #GString
1511  * @format: the string format. See the printf() documentation
1512  * @...: the parameters to insert into the format string
1513  *
1514  * Appends a formatted string onto the end of a #GString.
1515  * This function is similar to g_string_printf() except 
1516  * that the text is appended to the #GString.
1517  */
1518 void
1519 g_string_append_printf (GString     *string,
1520                         const gchar *format,
1521                         ...)
1522 {
1523   va_list args;
1524
1525   va_start (args, format);
1526   g_string_append_vprintf (string, format, args);
1527   va_end (args);
1528 }