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