Add a function for clearing a GStringChunk. (#364608, Matt Barnes)
[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 #include "galias.h"
46
47 struct _GStringChunk
48 {
49   GHashTable *const_table;
50   GSList     *storage_list;
51   gsize       storage_next;    
52   gsize       this_size;       
53   gsize       default_size;    
54 };
55
56 /* Hash Functions.
57  */
58
59 /**
60  * g_str_equal:
61  * @v1: a key. 
62  * @v2: a key to compare with @v1.
63  * 
64  * Compares two strings and returns %TRUE if they are equal.
65  * It can be passed to g_hash_table_new() as the @key_equal_func
66  * parameter, when using strings as keys in a #GHashTable.
67  *
68  * Returns: %TRUE if the two keys match.
69  */
70 gboolean
71 g_str_equal (gconstpointer v1,
72              gconstpointer v2)
73 {
74   const gchar *string1 = v1;
75   const gchar *string2 = v2;
76   
77   return strcmp (string1, string2) == 0;
78 }
79
80 /**
81  * g_str_hash:
82  * @v: a string key.
83  *
84  * Converts a string to a hash value.
85  * It can be passed to g_hash_table_new() as the @hash_func parameter, 
86  * when using strings as keys in a #GHashTable.
87  *
88  * Returns: a hash value corresponding to the key.
89  */
90 guint
91 g_str_hash (gconstpointer v)
92 {
93   /* 31 bit hash function */
94   const signed char *p = v;
95   guint32 h = *p;
96
97   if (h)
98     for (p += 1; *p != '\0'; p++)
99       h = (h << 5) - h + *p;
100
101   return h;
102 }
103
104 #define MY_MAXSIZE ((gsize)-1)
105
106 static inline gsize
107 nearest_power (gsize base, gsize num)    
108 {
109   if (num > MY_MAXSIZE / 2)
110     {
111       return MY_MAXSIZE;
112     }
113   else
114     {
115       gsize n = base;
116
117       while (n < num)
118         n <<= 1;
119       
120       return n;
121     }
122 }
123
124 /* String Chunks.
125  */
126
127 GStringChunk*
128 g_string_chunk_new (gsize default_size)    
129 {
130   GStringChunk *new_chunk = g_new (GStringChunk, 1);
131   gsize size = 1;    
132
133   size = nearest_power (1, default_size);
134
135   new_chunk->const_table       = NULL;
136   new_chunk->storage_list      = NULL;
137   new_chunk->storage_next      = size;
138   new_chunk->default_size      = size;
139   new_chunk->this_size         = size;
140
141   return new_chunk;
142 }
143
144 void
145 g_string_chunk_free (GStringChunk *chunk)
146 {
147   GSList *tmp_list;
148
149   g_return_if_fail (chunk != NULL);
150
151   if (chunk->storage_list)
152     {
153       for (tmp_list = chunk->storage_list; tmp_list; tmp_list = tmp_list->next)
154         g_free (tmp_list->data);
155
156       g_slist_free (chunk->storage_list);
157     }
158
159   if (chunk->const_table)
160     g_hash_table_destroy (chunk->const_table);
161
162   g_free (chunk);
163 }
164
165 /**
166  * g_string_chunk_clear:
167  * @chunk: a #GStringChunk
168  *
169  * Frees all strings contained within the #GStringChunk.
170  * After calling g_string_chunk_clear() it is not safe to
171  * access any of the strings which were contained within it.
172  *
173  * Since: 2.14
174  */
175 void
176 g_string_chunk_clear (GStringChunk *chunk)
177 {
178   GSList *tmp_list;
179
180   g_return_if_fail (chunk != NULL);
181
182   if (chunk->storage_list)
183     {
184       for (tmp_list = chunk->storage_list; tmp_list; tmp_list = tmp_list->next)
185         g_free (tmp_list->data);
186
187       g_slist_free (chunk->storage_list);
188
189       chunk->storage_list       = NULL;
190       chunk->storage_next       = chunk->default_size;
191       chunk->this_size          = chunk->default_size;
192     }
193
194   if (chunk->const_table)
195       g_hash_table_remove_all (chunk->const_table);
196 }
197
198 gchar*
199 g_string_chunk_insert (GStringChunk *chunk,
200                        const gchar  *string)
201 {
202   g_return_val_if_fail (chunk != NULL, NULL);
203
204   return g_string_chunk_insert_len (chunk, string, -1);
205 }
206
207 gchar*
208 g_string_chunk_insert_const (GStringChunk *chunk,
209                              const gchar  *string)
210 {
211   char* lookup;
212
213   g_return_val_if_fail (chunk != NULL, NULL);
214
215   if (!chunk->const_table)
216     chunk->const_table = g_hash_table_new (g_str_hash, g_str_equal);
217
218   lookup = (char*) g_hash_table_lookup (chunk->const_table, (gchar *)string);
219
220   if (!lookup)
221     {
222       lookup = g_string_chunk_insert (chunk, string);
223       g_hash_table_insert (chunk->const_table, lookup, lookup);
224     }
225
226   return lookup;
227 }
228
229 /**
230  * g_string_chunk_insert_len:
231  * @chunk: a #GStringChunk
232  * @string: bytes to insert
233  * @len: number of bytes of @string to insert, or -1 to insert a 
234  *     nul-terminated string. 
235  * 
236  * Adds a copy of the first @len bytes of @string to the #GStringChunk. The
237  * copy is nul-terminated.
238  * 
239  * The characters in the string can be changed, if necessary, though you
240  * should not change anything after the end of the string.
241  * 
242  * Return value: a pointer to the copy of @string within the #GStringChunk
243  * 
244  * Since: 2.4
245  **/
246 gchar*
247 g_string_chunk_insert_len (GStringChunk *chunk,
248                            const gchar  *string, 
249                            gssize        len)
250 {
251   gssize size;
252   gchar* pos;
253
254   g_return_val_if_fail (chunk != NULL, NULL);
255
256   if (len < 0)
257     size = strlen (string);
258   else
259     size = len;
260   
261   if ((chunk->storage_next + size + 1) > chunk->this_size)
262     {
263       gsize new_size = nearest_power (chunk->default_size, size + 1);
264
265       chunk->storage_list = g_slist_prepend (chunk->storage_list,
266                                              g_new (gchar, new_size));
267
268       chunk->this_size = new_size;
269       chunk->storage_next = 0;
270     }
271
272   pos = ((gchar *) chunk->storage_list->data) + chunk->storage_next;
273
274   *(pos + size) = '\0';
275
276   strncpy (pos, string, size);
277   if (len > 0)
278     size = strlen (pos);
279
280   chunk->storage_next += size + 1;
281
282   return pos;
283 }
284
285 /* Strings.
286  */
287 static void
288 g_string_maybe_expand (GString* string,
289                        gsize    len) 
290 {
291   if (string->len + len >= string->allocated_len)
292     {
293       string->allocated_len = nearest_power (1, string->len + len + 1);
294       string->str = g_realloc (string->str, string->allocated_len);
295     }
296 }
297
298 GString*
299 g_string_sized_new (gsize dfl_size)    
300 {
301   GString *string = g_slice_new (GString);
302
303   string->allocated_len = 0;
304   string->len   = 0;
305   string->str   = NULL;
306
307   g_string_maybe_expand (string, MAX (dfl_size, 2));
308   string->str[0] = 0;
309
310   return string;
311 }
312
313 GString*
314 g_string_new (const gchar *init)
315 {
316   GString *string;
317
318   if (init == NULL || *init == '\0')
319     string = g_string_sized_new (2);
320   else 
321     {
322       gint len;
323
324       len = strlen (init);
325       string = g_string_sized_new (len + 2);
326
327       g_string_append_len (string, init, len);
328     }
329
330   return string;
331 }
332
333 GString*
334 g_string_new_len (const gchar *init,
335                   gssize       len)    
336 {
337   GString *string;
338
339   if (len < 0)
340     return g_string_new (init);
341   else
342     {
343       string = g_string_sized_new (len);
344       
345       if (init)
346         g_string_append_len (string, init, len);
347       
348       return string;
349     }
350 }
351
352 gchar*
353 g_string_free (GString *string,
354                gboolean free_segment)
355 {
356   gchar *segment;
357
358   g_return_val_if_fail (string != NULL, NULL);
359
360   if (free_segment)
361     {
362       g_free (string->str);
363       segment = NULL;
364     }
365   else
366     segment = string->str;
367
368   g_slice_free (GString, string);
369
370   return segment;
371 }
372
373 gboolean
374 g_string_equal (const GString *v,
375                 const GString *v2)
376 {
377   gchar *p, *q;
378   GString *string1 = (GString *) v;
379   GString *string2 = (GString *) v2;
380   gsize i = string1->len;    
381
382   if (i != string2->len)
383     return FALSE;
384
385   p = string1->str;
386   q = string2->str;
387   while (i)
388     {
389       if (*p != *q)
390         return FALSE;
391       p++;
392       q++;
393       i--;
394     }
395   return TRUE;
396 }
397
398 /* 31 bit hash function */
399 guint
400 g_string_hash (const GString *str)
401 {
402   const gchar *p = str->str;
403   gsize n = str->len;    
404   guint h = 0;
405
406   while (n--)
407     {
408       h = (h << 5) - h + *p;
409       p++;
410     }
411
412   return h;
413 }
414
415 GString*
416 g_string_assign (GString     *string,
417                  const gchar *rval)
418 {
419   g_return_val_if_fail (string != NULL, NULL);
420   g_return_val_if_fail (rval != NULL, string);
421
422   /* Make sure assigning to itself doesn't corrupt the string.  */
423   if (string->str != rval)
424     {
425       /* Assigning from substring should be ok since g_string_truncate
426          does not realloc.  */
427       g_string_truncate (string, 0);
428       g_string_append (string, rval);
429     }
430
431   return string;
432 }
433
434 GString*
435 g_string_truncate (GString *string,
436                    gsize    len)    
437 {
438   g_return_val_if_fail (string != NULL, NULL);
439
440   string->len = MIN (len, string->len);
441   string->str[string->len] = 0;
442
443   return string;
444 }
445
446 /**
447  * g_string_set_size:
448  * @string: a #GString
449  * @len: the new length
450  * 
451  * Sets the length of a #GString. If the length is less than
452  * the current length, the string will be truncated. If the
453  * length is greater than the current length, the contents
454  * of the newly added area are undefined. (However, as
455  * always, string->str[string->len] will be a nul byte.) 
456  * 
457  * Return value: @string
458  **/
459 GString*
460 g_string_set_size (GString *string,
461                    gsize    len)    
462 {
463   g_return_val_if_fail (string != NULL, NULL);
464
465   if (len >= string->allocated_len)
466     g_string_maybe_expand (string, len - string->len);
467   
468   string->len = len;
469   string->str[len] = 0;
470
471   return string;
472 }
473
474 GString*
475 g_string_insert_len (GString     *string,
476                      gssize       pos,    
477                      const gchar *val,
478                      gssize       len)    
479 {
480   g_return_val_if_fail (string != NULL, NULL);
481   g_return_val_if_fail (val != NULL, string);
482
483   if (len < 0)
484     len = strlen (val);
485
486   if (pos < 0)
487     pos = string->len;
488   else
489     g_return_val_if_fail (pos <= string->len, string);
490
491   /* Check whether val represents a substring of string.  This test
492      probably violates chapter and verse of the C standards, since
493      ">=" and "<=" are only valid when val really is a substring.
494      In practice, it will work on modern archs.  */
495   if (val >= string->str && val <= string->str + string->len)
496     {
497       gsize offset = val - string->str;
498       gsize precount = 0;
499
500       g_string_maybe_expand (string, len);
501       val = string->str + offset;
502       /* At this point, val is valid again.  */
503
504       /* Open up space where we are going to insert.  */
505       if (pos < string->len)
506         g_memmove (string->str + pos + len, string->str + pos, string->len - pos);
507
508       /* Move the source part before the gap, if any.  */
509       if (offset < pos)
510         {
511           precount = MIN (len, pos - offset);
512           memcpy (string->str + pos, val, precount);
513         }
514
515       /* Move the source part after the gap, if any.  */
516       if (len > precount)
517         memcpy (string->str + pos + precount,
518                 val + /* Already moved: */ precount + /* Space opened up: */ len,
519                 len - precount);
520     }
521   else
522     {
523       g_string_maybe_expand (string, len);
524
525       /* If we aren't appending at the end, move a hunk
526        * of the old string to the end, opening up space
527        */
528       if (pos < string->len)
529         g_memmove (string->str + pos + len, string->str + pos, string->len - pos);
530
531       /* insert the new string */
532       if (len == 1)
533         string->str[pos] = *val;
534       else
535         memcpy (string->str + pos, val, len);
536     }
537
538   string->len += len;
539
540   string->str[string->len] = 0;
541
542   return string;
543 }
544
545 GString*
546 g_string_append (GString     *string,
547                  const gchar *val)
548 {  
549   g_return_val_if_fail (string != NULL, NULL);
550   g_return_val_if_fail (val != NULL, string);
551
552   return g_string_insert_len (string, -1, val, -1);
553 }
554
555 GString*
556 g_string_append_len (GString     *string,
557                      const gchar *val,
558                      gssize       len)    
559 {
560   g_return_val_if_fail (string != NULL, NULL);
561   g_return_val_if_fail (val != NULL, string);
562
563   return g_string_insert_len (string, -1, val, len);
564 }
565
566 #undef g_string_append_c
567 GString*
568 g_string_append_c (GString *string,
569                    gchar    c)
570 {
571   g_return_val_if_fail (string != NULL, NULL);
572
573   return g_string_insert_c (string, -1, c);
574 }
575
576 /**
577  * g_string_append_unichar:
578  * @string: a #GString
579  * @wc: a Unicode character
580  * 
581  * Converts a Unicode character into UTF-8, and appends it
582  * to the string.
583  * 
584  * Return value: @string
585  **/
586 GString*
587 g_string_append_unichar (GString  *string,
588                          gunichar  wc)
589 {  
590   g_return_val_if_fail (string != NULL, NULL);
591   
592   return g_string_insert_unichar (string, -1, wc);
593 }
594
595 GString*
596 g_string_prepend (GString     *string,
597                   const gchar *val)
598 {
599   g_return_val_if_fail (string != NULL, NULL);
600   g_return_val_if_fail (val != NULL, string);
601   
602   return g_string_insert_len (string, 0, val, -1);
603 }
604
605 GString*
606 g_string_prepend_len (GString     *string,
607                       const gchar *val,
608                       gssize       len)    
609 {
610   g_return_val_if_fail (string != NULL, NULL);
611   g_return_val_if_fail (val != NULL, string);
612
613   return g_string_insert_len (string, 0, val, len);
614 }
615
616 GString*
617 g_string_prepend_c (GString *string,
618                     gchar    c)
619 {  
620   g_return_val_if_fail (string != NULL, NULL);
621   
622   return g_string_insert_c (string, 0, c);
623 }
624
625 /**
626  * g_string_prepend_unichar:
627  * @string: a #GString.
628  * @wc: a Unicode character.
629  * 
630  * Converts a Unicode character into UTF-8, and prepends it
631  * to the string.
632  * 
633  * Return value: @string.
634  **/
635 GString*
636 g_string_prepend_unichar (GString  *string,
637                           gunichar  wc)
638 {  
639   g_return_val_if_fail (string != NULL, NULL);
640   
641   return g_string_insert_unichar (string, 0, wc);
642 }
643
644 GString*
645 g_string_insert (GString     *string,
646                  gssize       pos,    
647                  const gchar *val)
648 {
649   g_return_val_if_fail (string != NULL, NULL);
650   g_return_val_if_fail (val != NULL, string);
651   if (pos >= 0)
652     g_return_val_if_fail (pos <= string->len, string);
653   
654   return g_string_insert_len (string, pos, val, -1);
655 }
656
657 GString*
658 g_string_insert_c (GString *string,
659                    gssize   pos,    
660                    gchar    c)
661 {
662   g_return_val_if_fail (string != NULL, NULL);
663
664   g_string_maybe_expand (string, 1);
665
666   if (pos < 0)
667     pos = string->len;
668   else
669     g_return_val_if_fail (pos <= string->len, string);
670   
671   /* If not just an append, move the old stuff */
672   if (pos < string->len)
673     g_memmove (string->str + pos + 1, string->str + pos, string->len - pos);
674
675   string->str[pos] = c;
676
677   string->len += 1;
678
679   string->str[string->len] = 0;
680
681   return string;
682 }
683
684 /**
685  * g_string_insert_unichar:
686  * @string: a #GString
687  * @pos: the position at which to insert character, or -1 to
688  *       append at the end of the string.
689  * @wc: a Unicode character
690  * 
691  * Converts a Unicode character into UTF-8, and insert it
692  * into the string at the given position.
693  * 
694  * Return value: @string
695  **/
696 GString*
697 g_string_insert_unichar (GString *string,
698                          gssize   pos,    
699                          gunichar wc)
700 {
701   gint charlen, first, i;
702   gchar *dest;
703
704   g_return_val_if_fail (string != NULL, NULL);
705
706   /* Code copied from g_unichar_to_utf() */
707   if (wc < 0x80)
708     {
709       first = 0;
710       charlen = 1;
711     }
712   else if (wc < 0x800)
713     {
714       first = 0xc0;
715       charlen = 2;
716     }
717   else if (wc < 0x10000)
718     {
719       first = 0xe0;
720       charlen = 3;
721     }
722    else if (wc < 0x200000)
723     {
724       first = 0xf0;
725       charlen = 4;
726     }
727   else if (wc < 0x4000000)
728     {
729       first = 0xf8;
730       charlen = 5;
731     }
732   else
733     {
734       first = 0xfc;
735       charlen = 6;
736     }
737   /* End of copied code */
738
739   g_string_maybe_expand (string, charlen);
740
741   if (pos < 0)
742     pos = string->len;
743   else
744     g_return_val_if_fail (pos <= string->len, string);
745
746   /* If not just an append, move the old stuff */
747   if (pos < string->len)
748     g_memmove (string->str + pos + charlen, string->str + pos, string->len - pos);
749
750   dest = string->str + pos;
751   /* Code copied from g_unichar_to_utf() */
752   for (i = charlen - 1; i > 0; --i)
753     {
754       dest[i] = (wc & 0x3f) | 0x80;
755       wc >>= 6;
756     }
757   dest[0] = wc | first;
758   /* End of copied code */
759   
760   string->len += charlen;
761
762   string->str[string->len] = 0;
763
764   return string;
765 }
766
767 GString*
768 g_string_erase (GString *string,
769                 gssize   pos,
770                 gssize   len)
771 {
772   g_return_val_if_fail (string != NULL, NULL);
773   g_return_val_if_fail (pos >= 0, string);
774   g_return_val_if_fail (pos <= string->len, string);
775
776   if (len < 0)
777     len = string->len - pos;
778   else
779     {
780       g_return_val_if_fail (pos + len <= string->len, string);
781
782       if (pos + len < string->len)
783         g_memmove (string->str + pos, string->str + pos + len, string->len - (pos + len));
784     }
785
786   string->len -= len;
787   
788   string->str[string->len] = 0;
789
790   return string;
791 }
792
793 /**
794  * g_string_ascii_down:
795  * @string: a GString
796  * 
797  * Converts all upper case ASCII letters to lower case ASCII letters.
798  * 
799  * Return value: passed-in @string pointer, with all the upper case
800  *               characters converted to lower case in place, with
801  *               semantics that exactly match g_ascii_tolower.
802  **/
803 GString*
804 g_string_ascii_down (GString *string)
805 {
806   gchar *s;
807   gint n;
808
809   g_return_val_if_fail (string != NULL, NULL);
810
811   n = string->len;
812   s = string->str;
813
814   while (n)
815     {
816       *s = g_ascii_tolower (*s);
817       s++;
818       n--;
819     }
820
821   return string;
822 }
823
824 /**
825  * g_string_ascii_up:
826  * @string: a GString
827  * 
828  * Converts all lower case ASCII letters to upper case ASCII letters.
829  * 
830  * Return value: passed-in @string pointer, with all the lower case
831  *               characters converted to upper case in place, with
832  *               semantics that exactly match g_ascii_toupper.
833  **/
834 GString*
835 g_string_ascii_up (GString *string)
836 {
837   gchar *s;
838   gint n;
839
840   g_return_val_if_fail (string != NULL, NULL);
841
842   n = string->len;
843   s = string->str;
844
845   while (n)
846     {
847       *s = g_ascii_toupper (*s);
848       s++;
849       n--;
850     }
851
852   return string;
853 }
854
855 /**
856  * g_string_down:
857  * @string: a #GString
858  *  
859  * Converts a #GString to lowercase.
860  *
861  * Returns: the #GString.
862  *
863  * Deprecated:2.2: This function uses the locale-specific tolower() function, 
864  * which is almost never the right thing. Use g_string_ascii_down() or 
865  * g_utf8_strdown() instead.
866  */
867 GString*
868 g_string_down (GString *string)
869 {
870   guchar *s;
871   glong n;
872
873   g_return_val_if_fail (string != NULL, NULL);
874
875   n = string->len;    
876   s = (guchar *) string->str;
877
878   while (n)
879     {
880       if (isupper (*s))
881         *s = tolower (*s);
882       s++;
883       n--;
884     }
885
886   return string;
887 }
888
889 /**
890  * g_string_up:
891  * @string: a #GString 
892  * 
893  * Converts a #GString to uppercase.
894  * 
895  * Return value: the #GString
896  *
897  * Deprecated:2.2: This function uses the locale-specific toupper() function, 
898  * which is almost never the right thing. Use g_string_ascii_up() or 
899  * g_utf8_strup() instead.
900  **/
901 GString*
902 g_string_up (GString *string)
903 {
904   guchar *s;
905   glong n;
906
907   g_return_val_if_fail (string != NULL, NULL);
908
909   n = string->len;
910   s = (guchar *) string->str;
911
912   while (n)
913     {
914       if (islower (*s))
915         *s = toupper (*s);
916       s++;
917       n--;
918     }
919
920   return string;
921 }
922
923 static void
924 g_string_append_printf_internal (GString     *string,
925                                  const gchar *fmt,
926                                  va_list      args)
927 {
928   gchar *buffer;
929   gint length;
930   
931   length = g_vasprintf (&buffer, fmt, args);
932   g_string_append_len (string, buffer, length);
933   g_free (buffer);
934 }
935
936 void
937 g_string_printf (GString *string,
938                  const gchar *fmt,
939                  ...)
940 {
941   va_list args;
942
943   g_string_truncate (string, 0);
944
945   va_start (args, fmt);
946   g_string_append_printf_internal (string, fmt, args);
947   va_end (args);
948 }
949
950 void
951 g_string_append_printf (GString *string,
952                         const gchar *fmt,
953                         ...)
954 {
955   va_list args;
956
957   va_start (args, fmt);
958   g_string_append_printf_internal (string, fmt, args);
959   va_end (args);
960 }
961
962 #define __G_STRING_C__
963 #include "galiasdef.c"