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