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