Change LGPL-2.1+ to LGPL-2.1-or-later
[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  * SPDX-License-Identifier: LGPL-2.1-or-later
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, see <http://www.gnu.org/licenses/>.
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 #include <stdarg.h>
34 #include <stdlib.h>
35 #include <stdio.h>
36 #include <string.h>
37 #include <ctype.h>
38
39 #include "gstring.h"
40 #include "guriprivate.h"
41 #include "gprintf.h"
42 #include "gutilsprivate.h"
43
44
45 /**
46  * SECTION:strings
47  * @title: Strings
48  * @short_description: text buffers which grow automatically
49  *     as text is added
50  *
51  * A #GString is an object that handles the memory management of a C
52  * string for you.  The emphasis of #GString is on text, typically
53  * UTF-8.  Crucially, the "str" member of a #GString is guaranteed to
54  * have a trailing nul character, and it is therefore always safe to
55  * call functions such as strchr() or g_strdup() on it.
56  *
57  * However, a #GString can also hold arbitrary binary data, because it
58  * has a "len" member, which includes any possible embedded nul
59  * characters in the data.  Conceptually then, #GString is like a
60  * #GByteArray with the addition of many convenience methods for text,
61  * and a guaranteed nul terminator.
62  */
63
64 /**
65  * GString:
66  * @str: points to the character data. It may move as text is added.
67  *   The @str field is null-terminated and so
68  *   can be used as an ordinary C string.
69  * @len: contains the length of the string, not including the
70  *   terminating nul byte.
71  * @allocated_len: the number of bytes that can be stored in the
72  *   string before it needs to be reallocated. May be larger than @len.
73  *
74  * The GString struct contains the public fields of a GString.
75  */
76
77 static void
78 g_string_expand (GString *string,
79                  gsize    len)
80 {
81   /* Detect potential overflow */
82   if G_UNLIKELY ((G_MAXSIZE - string->len - 1) < len)
83     g_error ("adding %" G_GSIZE_FORMAT " to string would overflow", len);
84
85   string->allocated_len = g_nearest_pow (string->len + len + 1);
86   /* If the new size is bigger than G_MAXSIZE / 2, only allocate enough
87    * memory for this string and don't over-allocate.
88    */
89   if (string->allocated_len == 0)
90     string->allocated_len = string->len + len + 1;
91
92   string->str = g_realloc (string->str, string->allocated_len);
93 }
94
95 static inline void
96 g_string_maybe_expand (GString *string,
97                        gsize    len)
98 {
99   if (G_UNLIKELY (string->len + len >= string->allocated_len))
100     g_string_expand (string, len);
101 }
102
103 /**
104  * g_string_sized_new: (constructor)
105  * @dfl_size: the default size of the space allocated to hold the string
106  *
107  * Creates a new #GString, with enough space for @dfl_size
108  * bytes. This is useful if you are going to add a lot of
109  * text to the string and don't want it to be reallocated
110  * too often.
111  *
112  * Returns: (transfer full): the new #GString
113  */
114 GString *
115 g_string_sized_new (gsize dfl_size)
116 {
117   GString *string = g_slice_new (GString);
118
119   string->allocated_len = 0;
120   string->len   = 0;
121   string->str   = NULL;
122
123   g_string_expand (string, MAX (dfl_size, 64));
124   string->str[0] = 0;
125
126   return string;
127 }
128
129 /**
130  * g_string_new: (constructor)
131  * @init: (nullable): the initial text to copy into the string, or %NULL to
132  *   start with an empty string
133  *
134  * Creates a new #GString, initialized with the given string.
135  *
136  * Returns: (transfer full): the new #GString
137  */
138 GString *
139 g_string_new (const gchar *init)
140 {
141   GString *string;
142
143   if (init == NULL || *init == '\0')
144     string = g_string_sized_new (2);
145   else
146     {
147       gint len;
148
149       len = strlen (init);
150       string = g_string_sized_new (len + 2);
151
152       g_string_append_len (string, init, len);
153     }
154
155   return string;
156 }
157
158 /**
159  * g_string_new_take: (constructor)
160  * @init: (nullable) (transfer full): initial text used as the string.
161  *     Ownership of the string is transferred to the #GString.
162  *     Passing %NULL creates an empty string.
163  *
164  * Creates a new #GString, initialized with the given string.
165  *
166  * After this call, @init belongs to the #GString and may no longer be
167  * modified by the caller. The memory of @data has to be dynamically
168  * allocated and will eventually be freed with g_free().
169  *
170  * Returns: (transfer full): the new #GString
171  *
172  * Since: 2.78
173  */
174 GString *
175 g_string_new_take (gchar *init)
176 {
177   GString *string;
178
179   if (init == NULL)
180     {
181       return g_string_new (NULL);
182     }
183
184   string = g_slice_new (GString);
185
186   string->str = init;
187   string->len = strlen (string->str);
188   string->allocated_len = string->len + 1;
189
190   return string;
191 }
192
193 /**
194  * g_string_new_len: (constructor)
195  * @init: initial contents of the string
196  * @len: length of @init to use
197  *
198  * Creates a new #GString with @len bytes of the @init buffer.
199  * Because a length is provided, @init need not be nul-terminated,
200  * and can contain embedded nul bytes.
201  *
202  * Since this function does not stop at nul bytes, it is the caller's
203  * responsibility to ensure that @init has at least @len addressable
204  * bytes.
205  *
206  * Returns: (transfer full): a new #GString
207  */
208 GString *
209 g_string_new_len (const gchar *init,
210                   gssize       len)
211 {
212   GString *string;
213
214   if (len < 0)
215     return g_string_new (init);
216   else
217     {
218       string = g_string_sized_new (len);
219
220       if (init)
221         g_string_append_len (string, init, len);
222
223       return string;
224     }
225 }
226
227 /**
228  * g_string_free:
229  * @string: (transfer full): a #GString
230  * @free_segment: if %TRUE, the actual character data is freed as well
231  *
232  * Frees the memory allocated for the #GString.
233  * If @free_segment is %TRUE it also frees the character data.  If
234  * it's %FALSE, the caller gains ownership of the buffer and must
235  * free it after use with g_free().
236  *
237  * Instead of passing %FALSE to this function, consider using
238  * g_string_free_and_steal().
239  *
240  * Returns: (nullable): the character data of @string
241  *          (i.e. %NULL if @free_segment is %TRUE)
242  */
243 gchar *
244 (g_string_free) (GString  *string,
245                  gboolean  free_segment)
246 {
247   gchar *segment;
248
249   g_return_val_if_fail (string != NULL, NULL);
250
251   if (free_segment)
252     {
253       g_free (string->str);
254       segment = NULL;
255     }
256   else
257     segment = string->str;
258
259   g_slice_free (GString, string);
260
261   return segment;
262 }
263
264 /**
265  * g_string_free_and_steal:
266  * @string: (transfer full): a #GString
267  *
268  * Frees the memory allocated for the #GString.
269  *
270  * The caller gains ownership of the buffer and
271  * must free it after use with g_free().
272  *
273  * Returns: (transfer full): the character data of @string
274  *
275  * Since: 2.76
276  */
277 gchar *
278 g_string_free_and_steal (GString *string)
279 {
280   return (g_string_free) (string, FALSE);
281 }
282
283 /**
284  * g_string_free_to_bytes:
285  * @string: (transfer full): a #GString
286  *
287  * Transfers ownership of the contents of @string to a newly allocated
288  * #GBytes.  The #GString structure itself is deallocated, and it is
289  * therefore invalid to use @string after invoking this function.
290  *
291  * Note that while #GString ensures that its buffer always has a
292  * trailing nul character (not reflected in its "len"), the returned
293  * #GBytes does not include this extra nul; i.e. it has length exactly
294  * equal to the "len" member.
295  *
296  * Returns: (transfer full): A newly allocated #GBytes containing contents of @string; @string itself is freed
297  * Since: 2.34
298  */
299 GBytes*
300 g_string_free_to_bytes (GString *string)
301 {
302   gsize len;
303   gchar *buf;
304
305   g_return_val_if_fail (string != NULL, NULL);
306
307   len = string->len;
308
309   buf = g_string_free (string, FALSE);
310
311   return g_bytes_new_take (buf, len);
312 }
313
314 /**
315  * g_string_equal:
316  * @v: a #GString
317  * @v2: another #GString
318  *
319  * Compares two strings for equality, returning %TRUE if they are equal.
320  * For use with #GHashTable.
321  *
322  * Returns: %TRUE if the strings are the same length and contain the
323  *     same bytes
324  */
325 gboolean
326 g_string_equal (const GString *v,
327                 const GString *v2)
328 {
329   gchar *p, *q;
330   GString *string1 = (GString *) v;
331   GString *string2 = (GString *) v2;
332   gsize i = string1->len;
333
334   if (i != string2->len)
335     return FALSE;
336
337   p = string1->str;
338   q = string2->str;
339   while (i)
340     {
341       if (*p != *q)
342         return FALSE;
343       p++;
344       q++;
345       i--;
346     }
347   return TRUE;
348 }
349
350 /**
351  * g_string_hash:
352  * @str: a string to hash
353  *
354  * Creates a hash code for @str; for use with #GHashTable.
355  *
356  * Returns: hash code for @str
357  */
358 guint
359 g_string_hash (const GString *str)
360 {
361   const gchar *p = str->str;
362   gsize n = str->len;
363   guint h = 0;
364
365   /* 31 bit hash function */
366   while (n--)
367     {
368       h = (h << 5) - h + *p;
369       p++;
370     }
371
372   return h;
373 }
374
375 /**
376  * g_string_assign:
377  * @string: the destination #GString. Its current contents
378  *          are destroyed.
379  * @rval: the string to copy into @string
380  *
381  * Copies the bytes from a string into a #GString,
382  * destroying any previous contents. It is rather like
383  * the standard strcpy() function, except that you do not
384  * have to worry about having enough space to copy the string.
385  *
386  * Returns: (transfer none): @string
387  */
388 GString *
389 g_string_assign (GString     *string,
390                  const gchar *rval)
391 {
392   g_return_val_if_fail (string != NULL, NULL);
393   g_return_val_if_fail (rval != NULL, string);
394
395   /* Make sure assigning to itself doesn't corrupt the string. */
396   if (string->str != rval)
397     {
398       /* Assigning from substring should be ok, since
399        * g_string_truncate() does not reallocate.
400        */
401       g_string_truncate (string, 0);
402       g_string_append (string, rval);
403     }
404
405   return string;
406 }
407
408 /**
409  * g_string_truncate:
410  * @string: a #GString
411  * @len: the new size of @string
412  *
413  * Cuts off the end of the GString, leaving the first @len bytes.
414  *
415  * Returns: (transfer none): @string
416  */
417 GString *
418 (g_string_truncate) (GString *string,
419                      gsize    len)
420 {
421   g_return_val_if_fail (string != NULL, NULL);
422
423   string->len = MIN (len, string->len);
424   string->str[string->len] = 0;
425
426   return string;
427 }
428
429 /**
430  * g_string_set_size:
431  * @string: a #GString
432  * @len: the new length
433  *
434  * Sets the length of a #GString. If the length is less than
435  * the current length, the string will be truncated. If the
436  * length is greater than the current length, the contents
437  * of the newly added area are undefined. (However, as
438  * always, string->str[string->len] will be a nul byte.)
439  *
440  * Returns: (transfer none): @string
441  */
442 GString *
443 g_string_set_size (GString *string,
444                    gsize    len)
445 {
446   g_return_val_if_fail (string != NULL, NULL);
447
448   if (len >= string->allocated_len)
449     g_string_maybe_expand (string, len - string->len);
450
451   string->len = len;
452   string->str[len] = 0;
453
454   return string;
455 }
456
457 /**
458  * g_string_insert_len:
459  * @string: a #GString
460  * @pos: position in @string where insertion should
461  *       happen, or -1 for at the end
462  * @val: bytes to insert
463  * @len: number of bytes of @val to insert, or -1 for all of @val
464  *
465  * Inserts @len bytes of @val into @string at @pos.
466  *
467  * If @len is positive, @val may contain embedded nuls and need
468  * not be nul-terminated. It is the caller's responsibility to
469  * ensure that @val has at least @len addressable bytes.
470  *
471  * If @len is negative, @val must be nul-terminated and @len
472  * is considered to request the entire string length.
473  *
474  * If @pos is -1, bytes are inserted at the end of the string.
475  *
476  * Returns: (transfer none): @string
477  */
478 GString *
479 g_string_insert_len (GString     *string,
480                      gssize       pos,
481                      const gchar *val,
482                      gssize       len)
483 {
484   gsize len_unsigned, pos_unsigned;
485
486   g_return_val_if_fail (string != NULL, NULL);
487   g_return_val_if_fail (len == 0 || val != NULL, string);
488
489   if (len == 0)
490     return string;
491
492   if (len < 0)
493     len = strlen (val);
494   len_unsigned = len;
495
496   if (pos < 0)
497     pos_unsigned = string->len;
498   else
499     {
500       pos_unsigned = pos;
501       g_return_val_if_fail (pos_unsigned <= string->len, string);
502     }
503
504   /* Check whether val represents a substring of string.
505    * This test probably violates chapter and verse of the C standards,
506    * since ">=" and "<=" are only valid when val really is a substring.
507    * In practice, it will work on modern archs.
508    */
509   if (G_UNLIKELY (val >= string->str && val <= string->str + string->len))
510     {
511       gsize offset = val - string->str;
512       gsize precount = 0;
513
514       g_string_maybe_expand (string, len_unsigned);
515       val = string->str + offset;
516       /* At this point, val is valid again.  */
517
518       /* Open up space where we are going to insert.  */
519       if (pos_unsigned < string->len)
520         memmove (string->str + pos_unsigned + len_unsigned,
521                  string->str + pos_unsigned, string->len - pos_unsigned);
522
523       /* Move the source part before the gap, if any.  */
524       if (offset < pos_unsigned)
525         {
526           precount = MIN (len_unsigned, pos_unsigned - offset);
527           memcpy (string->str + pos_unsigned, val, precount);
528         }
529
530       /* Move the source part after the gap, if any.  */
531       if (len_unsigned > precount)
532         memcpy (string->str + pos_unsigned + precount,
533                 val + /* Already moved: */ precount +
534                       /* Space opened up: */ len_unsigned,
535                 len_unsigned - precount);
536     }
537   else
538     {
539       g_string_maybe_expand (string, len_unsigned);
540
541       /* If we aren't appending at the end, move a hunk
542        * of the old string to the end, opening up space
543        */
544       if (pos_unsigned < string->len)
545         memmove (string->str + pos_unsigned + len_unsigned,
546                  string->str + pos_unsigned, string->len - pos_unsigned);
547
548       /* insert the new string */
549       if (len_unsigned == 1)
550         string->str[pos_unsigned] = *val;
551       else
552         memcpy (string->str + pos_unsigned, val, len_unsigned);
553     }
554
555   string->len += len_unsigned;
556
557   string->str[string->len] = 0;
558
559   return string;
560 }
561
562 /**
563  * g_string_append_uri_escaped:
564  * @string: a #GString
565  * @unescaped: a string
566  * @reserved_chars_allowed: a string of reserved characters allowed
567  *     to be used, or %NULL
568  * @allow_utf8: set %TRUE if the escaped string may include UTF8 characters
569  *
570  * Appends @unescaped to @string, escaping any characters that
571  * are reserved in URIs using URI-style escape sequences.
572  *
573  * Returns: (transfer none): @string
574  *
575  * Since: 2.16
576  */
577 GString *
578 g_string_append_uri_escaped (GString     *string,
579                              const gchar *unescaped,
580                              const gchar *reserved_chars_allowed,
581                              gboolean     allow_utf8)
582 {
583   _uri_encoder (string, (const guchar *) unescaped, strlen (unescaped),
584                 reserved_chars_allowed, allow_utf8);
585   return string;
586 }
587
588 /**
589  * g_string_append:
590  * @string: a #GString
591  * @val: the string to append onto the end of @string
592  *
593  * Adds a string onto the end of a #GString, expanding
594  * it if necessary.
595  *
596  * Returns: (transfer none): @string
597  */
598 GString *
599 (g_string_append) (GString     *string,
600                    const gchar *val)
601 {
602   return g_string_insert_len (string, -1, val, -1);
603 }
604
605 /**
606  * g_string_append_len:
607  * @string: a #GString
608  * @val: bytes to append
609  * @len: number of bytes of @val to use, or -1 for all of @val
610  *
611  * Appends @len bytes of @val to @string.
612  *
613  * If @len is positive, @val may contain embedded nuls and need
614  * not be nul-terminated. It is the caller's responsibility to
615  * ensure that @val has at least @len addressable bytes.
616  *
617  * If @len is negative, @val must be nul-terminated and @len
618  * is considered to request the entire string length. This
619  * makes g_string_append_len() equivalent to g_string_append().
620  *
621  * Returns: (transfer none): @string
622  */
623 GString *
624 (g_string_append_len) (GString     *string,
625                        const gchar *val,
626                        gssize       len)
627 {
628   return g_string_insert_len (string, -1, val, len);
629 }
630
631 /**
632  * g_string_append_c:
633  * @string: a #GString
634  * @c: the byte to append onto the end of @string
635  *
636  * Adds a byte onto the end of a #GString, expanding
637  * it if necessary.
638  *
639  * Returns: (transfer none): @string
640  */
641 GString *
642 (g_string_append_c) (GString *string,
643                      gchar    c)
644 {
645   g_return_val_if_fail (string != NULL, NULL);
646
647   return g_string_insert_c (string, -1, c);
648 }
649
650 /**
651  * g_string_append_unichar:
652  * @string: a #GString
653  * @wc: a Unicode character
654  *
655  * Converts a Unicode character into UTF-8, and appends it
656  * to the string.
657  *
658  * Returns: (transfer none): @string
659  */
660 GString *
661 g_string_append_unichar (GString  *string,
662                          gunichar  wc)
663 {
664   g_return_val_if_fail (string != NULL, NULL);
665
666   return g_string_insert_unichar (string, -1, wc);
667 }
668
669 /**
670  * g_string_prepend:
671  * @string: a #GString
672  * @val: the string to prepend on the start of @string
673  *
674  * Adds a string on to the start of a #GString,
675  * expanding it if necessary.
676  *
677  * Returns: (transfer none): @string
678  */
679 GString *
680 g_string_prepend (GString     *string,
681                   const gchar *val)
682 {
683   return g_string_insert_len (string, 0, val, -1);
684 }
685
686 /**
687  * g_string_prepend_len:
688  * @string: a #GString
689  * @val: bytes to prepend
690  * @len: number of bytes in @val to prepend, or -1 for all of @val
691  *
692  * Prepends @len bytes of @val to @string.
693  *
694  * If @len is positive, @val may contain embedded nuls and need
695  * not be nul-terminated. It is the caller's responsibility to
696  * ensure that @val has at least @len addressable bytes.
697  *
698  * If @len is negative, @val must be nul-terminated and @len
699  * is considered to request the entire string length. This
700  * makes g_string_prepend_len() equivalent to g_string_prepend().
701  *
702  * Returns: (transfer none): @string
703  */
704 GString *
705 g_string_prepend_len (GString     *string,
706                       const gchar *val,
707                       gssize       len)
708 {
709   return g_string_insert_len (string, 0, val, len);
710 }
711
712 /**
713  * g_string_prepend_c:
714  * @string: a #GString
715  * @c: the byte to prepend on the start of the #GString
716  *
717  * Adds a byte onto the start of a #GString,
718  * expanding it if necessary.
719  *
720  * Returns: (transfer none): @string
721  */
722 GString *
723 g_string_prepend_c (GString *string,
724                     gchar    c)
725 {
726   g_return_val_if_fail (string != NULL, NULL);
727
728   return g_string_insert_c (string, 0, c);
729 }
730
731 /**
732  * g_string_prepend_unichar:
733  * @string: a #GString
734  * @wc: a Unicode character
735  *
736  * Converts a Unicode character into UTF-8, and prepends it
737  * to the string.
738  *
739  * Returns: (transfer none): @string
740  */
741 GString *
742 g_string_prepend_unichar (GString  *string,
743                           gunichar  wc)
744 {
745   g_return_val_if_fail (string != NULL, NULL);
746
747   return g_string_insert_unichar (string, 0, wc);
748 }
749
750 /**
751  * g_string_insert:
752  * @string: a #GString
753  * @pos: the position to insert the copy of the string
754  * @val: the string to insert
755  *
756  * Inserts a copy of a string into a #GString,
757  * expanding it if necessary.
758  *
759  * Returns: (transfer none): @string
760  */
761 GString *
762 g_string_insert (GString     *string,
763                  gssize       pos,
764                  const gchar *val)
765 {
766   return g_string_insert_len (string, pos, val, -1);
767 }
768
769 /**
770  * g_string_insert_c:
771  * @string: a #GString
772  * @pos: the position to insert the byte
773  * @c: the byte to insert
774  *
775  * Inserts a byte into a #GString, expanding it if necessary.
776  *
777  * Returns: (transfer none): @string
778  */
779 GString *
780 g_string_insert_c (GString *string,
781                    gssize   pos,
782                    gchar    c)
783 {
784   gsize pos_unsigned;
785
786   g_return_val_if_fail (string != NULL, NULL);
787
788   g_string_maybe_expand (string, 1);
789
790   if (pos < 0)
791     pos = string->len;
792   else
793     g_return_val_if_fail ((gsize) pos <= string->len, string);
794   pos_unsigned = pos;
795
796   /* If not just an append, move the old stuff */
797   if (pos_unsigned < string->len)
798     memmove (string->str + pos_unsigned + 1,
799              string->str + pos_unsigned, string->len - pos_unsigned);
800
801   string->str[pos_unsigned] = c;
802
803   string->len += 1;
804
805   string->str[string->len] = 0;
806
807   return string;
808 }
809
810 /**
811  * g_string_insert_unichar:
812  * @string: a #GString
813  * @pos: the position at which to insert character, or -1
814  *     to append at the end of the string
815  * @wc: a Unicode character
816  *
817  * Converts a Unicode character into UTF-8, and insert it
818  * into the string at the given position.
819  *
820  * Returns: (transfer none): @string
821  */
822 GString *
823 g_string_insert_unichar (GString  *string,
824                          gssize    pos,
825                          gunichar  wc)
826 {
827   gint charlen, first, i;
828   gchar *dest;
829
830   g_return_val_if_fail (string != NULL, NULL);
831
832   /* Code copied from g_unichar_to_utf() */
833   if (wc < 0x80)
834     {
835       first = 0;
836       charlen = 1;
837     }
838   else if (wc < 0x800)
839     {
840       first = 0xc0;
841       charlen = 2;
842     }
843   else if (wc < 0x10000)
844     {
845       first = 0xe0;
846       charlen = 3;
847     }
848    else if (wc < 0x200000)
849     {
850       first = 0xf0;
851       charlen = 4;
852     }
853   else if (wc < 0x4000000)
854     {
855       first = 0xf8;
856       charlen = 5;
857     }
858   else
859     {
860       first = 0xfc;
861       charlen = 6;
862     }
863   /* End of copied code */
864
865   g_string_maybe_expand (string, charlen);
866
867   if (pos < 0)
868     pos = string->len;
869   else
870     g_return_val_if_fail ((gsize) pos <= string->len, string);
871
872   /* If not just an append, move the old stuff */
873   if ((gsize) pos < string->len)
874     memmove (string->str + pos + charlen, string->str + pos, string->len - pos);
875
876   dest = string->str + pos;
877   /* Code copied from g_unichar_to_utf() */
878   for (i = charlen - 1; i > 0; --i)
879     {
880       dest[i] = (wc & 0x3f) | 0x80;
881       wc >>= 6;
882     }
883   dest[0] = wc | first;
884   /* End of copied code */
885
886   string->len += charlen;
887
888   string->str[string->len] = 0;
889
890   return string;
891 }
892
893 /**
894  * g_string_overwrite:
895  * @string: a #GString
896  * @pos: the position at which to start overwriting
897  * @val: the string that will overwrite the @string starting at @pos
898  *
899  * Overwrites part of a string, lengthening it if necessary.
900  *
901  * Returns: (transfer none): @string
902  *
903  * Since: 2.14
904  */
905 GString *
906 g_string_overwrite (GString     *string,
907                     gsize        pos,
908                     const gchar *val)
909 {
910   g_return_val_if_fail (val != NULL, string);
911   return g_string_overwrite_len (string, pos, val, strlen (val));
912 }
913
914 /**
915  * g_string_overwrite_len:
916  * @string: a #GString
917  * @pos: the position at which to start overwriting
918  * @val: the string that will overwrite the @string starting at @pos
919  * @len: the number of bytes to write from @val
920  *
921  * Overwrites part of a string, lengthening it if necessary.
922  * This function will work with embedded nuls.
923  *
924  * Returns: (transfer none): @string
925  *
926  * Since: 2.14
927  */
928 GString *
929 g_string_overwrite_len (GString     *string,
930                         gsize        pos,
931                         const gchar *val,
932                         gssize       len)
933 {
934   gsize end;
935
936   g_return_val_if_fail (string != NULL, NULL);
937
938   if (!len)
939     return string;
940
941   g_return_val_if_fail (val != NULL, string);
942   g_return_val_if_fail (pos <= string->len, string);
943
944   if (len < 0)
945     len = strlen (val);
946
947   end = pos + len;
948
949   if (end > string->len)
950     g_string_maybe_expand (string, end - string->len);
951
952   memcpy (string->str + pos, val, len);
953
954   if (end > string->len)
955     {
956       string->str[end] = '\0';
957       string->len = end;
958     }
959
960   return string;
961 }
962
963 /**
964  * g_string_erase:
965  * @string: a #GString
966  * @pos: the position of the content to remove
967  * @len: the number of bytes to remove, or -1 to remove all
968  *       following bytes
969  *
970  * Removes @len bytes from a #GString, starting at position @pos.
971  * The rest of the #GString is shifted down to fill the gap.
972  *
973  * Returns: (transfer none): @string
974  */
975 GString *
976 g_string_erase (GString *string,
977                 gssize   pos,
978                 gssize   len)
979 {
980   gsize len_unsigned, pos_unsigned;
981
982   g_return_val_if_fail (string != NULL, NULL);
983   g_return_val_if_fail (pos >= 0, string);
984   pos_unsigned = pos;
985
986   g_return_val_if_fail (pos_unsigned <= string->len, string);
987
988   if (len < 0)
989     len_unsigned = string->len - pos_unsigned;
990   else
991     {
992       len_unsigned = len;
993       g_return_val_if_fail (pos_unsigned + len_unsigned <= string->len, string);
994
995       if (pos_unsigned + len_unsigned < string->len)
996         memmove (string->str + pos_unsigned,
997                  string->str + pos_unsigned + len_unsigned,
998                  string->len - (pos_unsigned + len_unsigned));
999     }
1000
1001   string->len -= len_unsigned;
1002
1003   string->str[string->len] = 0;
1004
1005   return string;
1006 }
1007
1008 /**
1009  * g_string_replace:
1010  * @string: a #GString
1011  * @find: the string to find in @string
1012  * @replace: the string to insert in place of @find
1013  * @limit: the maximum instances of @find to replace with @replace, or `0` for
1014  * no limit
1015  *
1016  * Replaces the string @find with the string @replace in a #GString up to
1017  * @limit times. If the number of instances of @find in the #GString is
1018  * less than @limit, all instances are replaced. If @limit is `0`,
1019  * all instances of @find are replaced.
1020  *
1021  * If @find is the empty string, since versions 2.69.1 and 2.68.4 the
1022  * replacement will be inserted no more than once per possible position
1023  * (beginning of string, end of string and between characters). This did
1024  * not work correctly in earlier versions.
1025  *
1026  * Returns: the number of find and replace operations performed.
1027  *
1028  * Since: 2.68
1029  */
1030 guint
1031 g_string_replace (GString     *string,
1032                   const gchar *find,
1033                   const gchar *replace,
1034                   guint        limit)
1035 {
1036   gsize f_len, r_len, pos;
1037   gchar *cur, *next;
1038   guint n = 0;
1039
1040   g_return_val_if_fail (string != NULL, 0);
1041   g_return_val_if_fail (find != NULL, 0);
1042   g_return_val_if_fail (replace != NULL, 0);
1043
1044   f_len = strlen (find);
1045   r_len = strlen (replace);
1046   cur = string->str;
1047
1048   while ((next = strstr (cur, find)) != NULL)
1049     {
1050       pos = next - string->str;
1051       g_string_erase (string, pos, f_len);
1052       g_string_insert (string, pos, replace);
1053       cur = string->str + pos + r_len;
1054       n++;
1055       /* Only match the empty string once at any given position, to
1056        * avoid infinite loops */
1057       if (f_len == 0)
1058         {
1059           if (cur[0] == '\0')
1060             break;
1061           else
1062             cur++;
1063         }
1064       if (n == limit)
1065         break;
1066     }
1067
1068   return n;
1069 }
1070
1071 /**
1072  * g_string_ascii_down:
1073  * @string: a GString
1074  *
1075  * Converts all uppercase ASCII letters to lowercase ASCII letters.
1076  *
1077  * Returns: (transfer none): passed-in @string pointer, with all the
1078  *     uppercase characters converted to lowercase in place,
1079  *     with semantics that exactly match g_ascii_tolower().
1080  */
1081 GString *
1082 g_string_ascii_down (GString *string)
1083 {
1084   gchar *s;
1085   gint n;
1086
1087   g_return_val_if_fail (string != NULL, NULL);
1088
1089   n = string->len;
1090   s = string->str;
1091
1092   while (n)
1093     {
1094       *s = g_ascii_tolower (*s);
1095       s++;
1096       n--;
1097     }
1098
1099   return string;
1100 }
1101
1102 /**
1103  * g_string_ascii_up:
1104  * @string: a GString
1105  *
1106  * Converts all lowercase ASCII letters to uppercase ASCII letters.
1107  *
1108  * Returns: (transfer none): passed-in @string pointer, with all the
1109  *     lowercase characters converted to uppercase in place,
1110  *     with semantics that exactly match g_ascii_toupper().
1111  */
1112 GString *
1113 g_string_ascii_up (GString *string)
1114 {
1115   gchar *s;
1116   gint n;
1117
1118   g_return_val_if_fail (string != NULL, NULL);
1119
1120   n = string->len;
1121   s = string->str;
1122
1123   while (n)
1124     {
1125       *s = g_ascii_toupper (*s);
1126       s++;
1127       n--;
1128     }
1129
1130   return string;
1131 }
1132
1133 /**
1134  * g_string_down:
1135  * @string: a #GString
1136  *
1137  * Converts a #GString to lowercase.
1138  *
1139  * Returns: (transfer none): the #GString
1140  *
1141  * Deprecated:2.2: This function uses the locale-specific
1142  *     tolower() function, which is almost never the right thing.
1143  *     Use g_string_ascii_down() or g_utf8_strdown() instead.
1144  */
1145 GString *
1146 g_string_down (GString *string)
1147 {
1148   guchar *s;
1149   glong n;
1150
1151   g_return_val_if_fail (string != NULL, NULL);
1152
1153   n = string->len;
1154   s = (guchar *) string->str;
1155
1156   while (n)
1157     {
1158       if (isupper (*s))
1159         *s = tolower (*s);
1160       s++;
1161       n--;
1162     }
1163
1164   return string;
1165 }
1166
1167 /**
1168  * g_string_up:
1169  * @string: a #GString
1170  *
1171  * Converts a #GString to uppercase.
1172  *
1173  * Returns: (transfer none): @string
1174  *
1175  * Deprecated:2.2: This function uses the locale-specific
1176  *     toupper() function, which is almost never the right thing.
1177  *     Use g_string_ascii_up() or g_utf8_strup() instead.
1178  */
1179 GString *
1180 g_string_up (GString *string)
1181 {
1182   guchar *s;
1183   glong n;
1184
1185   g_return_val_if_fail (string != NULL, NULL);
1186
1187   n = string->len;
1188   s = (guchar *) string->str;
1189
1190   while (n)
1191     {
1192       if (islower (*s))
1193         *s = toupper (*s);
1194       s++;
1195       n--;
1196     }
1197
1198   return string;
1199 }
1200
1201 /**
1202  * g_string_append_vprintf:
1203  * @string: a #GString
1204  * @format: (not nullable): the string format. See the printf() documentation
1205  * @args: the list of arguments to insert in the output
1206  *
1207  * Appends a formatted string onto the end of a #GString.
1208  * This function is similar to g_string_append_printf()
1209  * except that the arguments to the format string are passed
1210  * as a va_list.
1211  *
1212  * Since: 2.14
1213  */
1214 void
1215 g_string_append_vprintf (GString     *string,
1216                          const gchar *format,
1217                          va_list      args)
1218 {
1219   gchar *buf;
1220   gint len;
1221
1222   g_return_if_fail (string != NULL);
1223   g_return_if_fail (format != NULL);
1224
1225   len = g_vasprintf (&buf, format, args);
1226
1227   if (len >= 0)
1228     {
1229       g_string_maybe_expand (string, len);
1230       memcpy (string->str + string->len, buf, len + 1);
1231       string->len += len;
1232       g_free (buf);
1233     }
1234 }
1235
1236 /**
1237  * g_string_vprintf:
1238  * @string: a #GString
1239  * @format: (not nullable): the string format. See the printf() documentation
1240  * @args: the parameters to insert into the format string
1241  *
1242  * Writes a formatted string into a #GString.
1243  * This function is similar to g_string_printf() except that
1244  * the arguments to the format string are passed as a va_list.
1245  *
1246  * Since: 2.14
1247  */
1248 void
1249 g_string_vprintf (GString     *string,
1250                   const gchar *format,
1251                   va_list      args)
1252 {
1253   g_string_truncate (string, 0);
1254   g_string_append_vprintf (string, format, args);
1255 }
1256
1257 /**
1258  * g_string_sprintf:
1259  * @string: a #GString
1260  * @format: the string format. See the sprintf() documentation
1261  * @...: the parameters to insert into the format string
1262  *
1263  * Writes a formatted string into a #GString.
1264  * This is similar to the standard sprintf() function,
1265  * except that the #GString buffer automatically expands
1266  * to contain the results. The previous contents of the
1267  * #GString are destroyed.
1268  *
1269  * Deprecated: This function has been renamed to g_string_printf().
1270  */
1271
1272 /**
1273  * g_string_printf:
1274  * @string: a #GString
1275  * @format: the string format. See the printf() documentation
1276  * @...: the parameters to insert into the format string
1277  *
1278  * Writes a formatted string into a #GString.
1279  * This is similar to the standard sprintf() function,
1280  * except that the #GString buffer automatically expands
1281  * to contain the results. The previous contents of the
1282  * #GString are destroyed.
1283  */
1284 void
1285 g_string_printf (GString     *string,
1286                  const gchar *format,
1287                  ...)
1288 {
1289   va_list args;
1290
1291   g_string_truncate (string, 0);
1292
1293   va_start (args, format);
1294   g_string_append_vprintf (string, format, args);
1295   va_end (args);
1296 }
1297
1298 /**
1299  * g_string_sprintfa:
1300  * @string: a #GString
1301  * @format: the string format. See the sprintf() documentation
1302  * @...: the parameters to insert into the format string
1303  *
1304  * Appends a formatted string onto the end of a #GString.
1305  * This function is similar to g_string_sprintf() except that
1306  * the text is appended to the #GString.
1307  *
1308  * Deprecated: This function has been renamed to g_string_append_printf()
1309  */
1310
1311 /**
1312  * g_string_append_printf:
1313  * @string: a #GString
1314  * @format: the string format. See the printf() documentation
1315  * @...: the parameters to insert into the format string
1316  *
1317  * Appends a formatted string onto the end of a #GString.
1318  * This function is similar to g_string_printf() except
1319  * that the text is appended to the #GString.
1320  */
1321 void
1322 g_string_append_printf (GString     *string,
1323                         const gchar *format,
1324                         ...)
1325 {
1326   va_list args;
1327
1328   va_start (args, format);
1329   g_string_append_vprintf (string, format, args);
1330   va_end (args);
1331 }