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