snac2

Fork of https://codeberg.org/grunfink/snac2
git clone https://git.inz.fi/snac2
Log | Files | Refs | README | LICENSE

commit d5b86e4e68c1121d0375544a4c389a88075cce30
parent 4b355fb2c96af2565c48bd47b87f51ab72192085
Author: Santtu Lakkala <santtu.lakkala@unikie.com>
Date:   Sat,  8 Feb 2025 12:28:15 +0200

Optimise xs_readline

Diffstat:
Mxs_io.h | 24+++++++++++-------------
1 file changed, 11 insertions(+), 13 deletions(-)

diff --git a/xs_io.h b/xs_io.h @@ -14,24 +14,22 @@ xs_val *xs_readall(FILE *f); xs_str *xs_readline(FILE *f) /* reads a line from a file */ { - xs_str *s = xs_str_new(NULL); + size_t sz = 128; + size_t i = 0; + char *s = xs_realloc(NULL, sz); + int c; errno = 0; /* don't even try on eof */ - if (!feof(f)) { - int c; - - while ((c = fgetc(f)) != EOF) { - unsigned char rc = c; - - if (xs_is_string((char *)&rc)) - s = xs_append_m(s, (char *)&rc, 1); - - if (c == '\n') - break; - } + while ((c = fgetc(f)) != EOF && c != '\n') { + if (!xs_is_string(&(char){ c })) + continue; + if (i == sz - 1) + s = xs_realloc(s, sz *= 2); + s[i++] = c; } + s[i] = '\0'; return s; }