From 57ca46cdd74fd1004a3b0476c136e1f26fcf002d Mon Sep 17 00:00:00 2001
From: David Oberhollenzer <david.oberhollenzer@sigma-star.at>
Date: Sun, 4 Jun 2023 23:25:05 +0200
Subject: libio: istream_get_line: minor cleanup

Remove redundant initializations, reduce variable scope. At exist of
the function, try to shrink the buffer to the actual size if it got
trimmed.

Signed-off-by: David Oberhollenzer <david.oberhollenzer@sigma-star.at>
---
 lib/io/src/get_line.c | 34 ++++++++++++++++------------------
 1 file changed, 16 insertions(+), 18 deletions(-)

(limited to 'lib/io/src')

diff --git a/lib/io/src/get_line.c b/lib/io/src/get_line.c
index e23383c..c764d04 100644
--- a/lib/io/src/get_line.c
+++ b/lib/io/src/get_line.c
@@ -41,13 +41,13 @@ static size_t trim(char *buffer, int flags)
 int istream_get_line(istream_t *strm, char **out,
 		     size_t *line_num, int flags)
 {
-	size_t i, count, line_len = 0;
 	char *line = NULL, *new;
-	bool have_line = false;
-
-	*out = NULL;
+	size_t line_len = 0;
 
 	for (;;) {
+		bool have_line = false;
+		size_t i, count;
+
 		if (istream_precache(strm))
 			goto fail_free;
 
@@ -56,12 +56,10 @@ int istream_get_line(istream_t *strm, char **out,
 				goto out_eof;
 
 			line_len = trim(line, flags);
+			if (line_len > 0 ||!(flags & ISTREAM_LINE_SKIP_EMPTY))
+				break;
 
-			if (line_len == 0 &&
-			    (flags & ISTREAM_LINE_SKIP_EMPTY)) {
-				goto out_eof;
-			}
-			break;
+			goto out_eof;
 		}
 
 		for (i = 0; i < strm->buffer_used; ++i) {
@@ -93,19 +91,19 @@ int istream_get_line(istream_t *strm, char **out,
 				line[--line_len] = '\0';
 
 			line_len = trim(line, flags);
+			if (line_len > 0 || !(flags & ISTREAM_LINE_SKIP_EMPTY))
+				break;
 
-			if (line_len == 0 &&
-			    (flags & ISTREAM_LINE_SKIP_EMPTY)) {
-				free(line);
-				line = NULL;
-				have_line = false;
-				*line_num += 1;
-				continue;
-			}
-			break;
+			free(line);
+			line = NULL;
+			*line_num += 1;
 		}
 	}
 
+	new = realloc(line, line_len + 1);
+	if (new != NULL)
+		line = new;
+
 	*out = line;
 	return 0;
 fail_errno:
-- 
cgit v1.2.3