From 236684f6deb3178043fe72a8e2faca538fa2aae1 Mon Sep 17 00:00:00 2001
From: Sergey Poznyakoff <gray@gnu.org>
Date: Wed, 18 Aug 2021 09:41:39 +0300
Subject: [PATCH 13/13] Fix dynamic string reallocations

* src/dstring.c (ds_resize): Take additional argument: number of
bytes to leave available after ds_idx.  All uses changed.
---
 src/dstring.c | 18 ++++++++----------
 1 file changed, 8 insertions(+), 10 deletions(-)

diff --git a/src/dstring.c b/src/dstring.c
index b7e0bb5..fd4e030 100644
--- a/src/dstring.c
+++ b/src/dstring.c
@@ -49,9 +49,9 @@ ds_free (dynamic_string *string)
 /* Expand dynamic string STRING, if necessary.  */
 
 void
-ds_resize (dynamic_string *string)
+ds_resize (dynamic_string *string, size_t len)
 {
-  if (string->ds_idx == string->ds_size)
+  while (len + string->ds_idx >= string->ds_size)
     {
       string->ds_string = x2nrealloc (string->ds_string, &string->ds_size,
 				      1);
@@ -63,8 +63,7 @@ ds_resize (dynamic_string *string)
 void
 ds_reset (dynamic_string *s, size_t len)
 {
-  while (len > s->ds_size)
-    s->ds_string = x2nrealloc (s->ds_string, &s->ds_size, 1);
+  ds_resize (s, len);
   s->ds_idx = len;
 }
 
@@ -86,10 +85,10 @@ ds_fgetstr (FILE *f, dynamic_string *s, char eos)
   /* Read the input string.  */
   while ((next_ch = getc (f)) != eos && next_ch != EOF)
     {
-      ds_resize (s);
+      ds_resize (s, 0);
       s->ds_string[s->ds_idx++] = next_ch;
     }
-  ds_resize (s);
+  ds_resize (s, 0);
   s->ds_string[s->ds_idx] = '\0';
 
   if (s->ds_idx == 0 && next_ch == EOF)
@@ -101,12 +100,12 @@ ds_fgetstr (FILE *f, dynamic_string *s, char eos)
 void
 ds_append (dynamic_string *s, int c)
 {
-  ds_resize (s);
+  ds_resize (s, 0);
   s->ds_string[s->ds_idx] = c;
   if (c)
     {
       s->ds_idx++;
-      ds_resize (s);
+      ds_resize (s, 0);
       s->ds_string[s->ds_idx] = 0;
     }      
 }
@@ -115,8 +114,7 @@ void
 ds_concat (dynamic_string *s, char const *str)
 {
   size_t len = strlen (str);
-  while (len + 1 > s->ds_size)
-    s->ds_string = x2nrealloc (s->ds_string, &s->ds_size, 1);
+  ds_resize (s, len);
   memcpy (s->ds_string + s->ds_idx, str, len);
   s->ds_idx += len;
   s->ds_string[s->ds_idx] = 0;
-- 
1.8.3.1

