Module Name:    src
Committed By:   rillig
Date:           Fri Nov 26 15:08:48 UTC 2021

Modified Files:
        src/usr.bin/indent: io.c

Log Message:
indent: replace inp_enlarge with inp_add

Previously, inbuf.inp.s was only updated at the very end of reading a
line from the input file, which meant that during debugging, it pointed
to invalid memory. Updating all fields in inbuf.inp after every
reallocation makes the code less tricky to understand.

No functional change.


To generate a diff of this commit:
cvs rdiff -u -r1.137 -r1.138 src/usr.bin/indent/io.c

Please note that diffs are not public domain; they are subject to the
copyright notices on the relevant files.

Modified files:

Index: src/usr.bin/indent/io.c
diff -u src/usr.bin/indent/io.c:1.137 src/usr.bin/indent/io.c:1.138
--- src/usr.bin/indent/io.c:1.137	Fri Nov 26 14:48:03 2021
+++ src/usr.bin/indent/io.c	Fri Nov 26 15:08:48 2021
@@ -1,4 +1,4 @@
-/*	$NetBSD: io.c,v 1.137 2021/11/26 14:48:03 rillig Exp $	*/
+/*	$NetBSD: io.c,v 1.138 2021/11/26 15:08:48 rillig Exp $	*/
 
 /*-
  * SPDX-License-Identifier: BSD-4-Clause
@@ -43,7 +43,7 @@ static char sccsid[] = "@(#)io.c	8.1 (Be
 
 #include <sys/cdefs.h>
 #if defined(__NetBSD__)
-__RCSID("$NetBSD: io.c,v 1.137 2021/11/26 14:48:03 rillig Exp $");
+__RCSID("$NetBSD: io.c,v 1.138 2021/11/26 15:08:48 rillig Exp $");
 #elif defined(__FreeBSD__)
 __FBSDID("$FreeBSD: head/usr.bin/indent/io.c 334927 2018-06-10 16:44:18Z pstef $");
 #endif
@@ -306,43 +306,42 @@ inp_comment_insert_lbrace(void)
     inbuf.save_com_s[0] = '{';
 }
 
-static char *
-inp_enlarge(char *p)
+static void
+inp_add(char ch)
 {
-    size_t new_size = (size_t)(inbuf.inp.l - inbuf.inp.buf) * 2 + 10;
-    size_t offset = (size_t)(p - inbuf.inp.buf);
-    inbuf.inp.buf = xrealloc(inbuf.inp.buf, new_size);
-    inbuf.inp.l = inbuf.inp.buf + new_size - 2;
-    return inbuf.inp.buf + offset;
+    if (inbuf.inp.e >= inbuf.inp.l) {
+	size_t new_size = (size_t)(inbuf.inp.l - inbuf.inp.buf) * 2 + 10;
+	size_t offset = (size_t)(inbuf.inp.e - inbuf.inp.buf);
+	inbuf.inp.buf = xrealloc(inbuf.inp.buf, new_size);
+	inbuf.inp.s = inbuf.inp.buf;
+	inbuf.inp.e = inbuf.inp.buf + offset;
+	inbuf.inp.l = inbuf.inp.buf + new_size - 2;
+    }
+    *inbuf.inp.e++ = ch;
 }
 
 static void
 inp_read_next_line(FILE *f)
 {
-    char *p;
-    int ch;
-
-    for (p = inbuf.inp.buf;;) {
-	if (p >= inbuf.inp.l)
-	    p = inp_enlarge(p);
+    inbuf.inp.s = inbuf.inp.buf;
+    inbuf.inp.e = inbuf.inp.buf;
 
-	if ((ch = getc(f)) == EOF) {
+    for (;;) {
+	int ch = getc(f);
+	if (ch == EOF) {
 	    if (!inhibit_formatting) {
-		*p++ = ' ';
-		*p++ = '\n';
+		inp_add(' ');
+		inp_add('\n');
 	    }
 	    had_eof = true;
 	    break;
 	}
 
 	if (ch != '\0')
-	    *p++ = (char)ch;
+	    inp_add((char)ch);
 	if (ch == '\n')
 	    break;
     }
-
-    inbuf.inp.s = inbuf.inp.buf;
-    inbuf.inp.e = p;
 }
 
 static void

Reply via email to