From b81270211502cd758dd0fe839c3d0f8801ea8764 Mon Sep 17 00:00:00 2001 From: speedie Date: Wed, 19 Jul 2023 01:06:38 +0200 Subject: [PATCH] Speed up and simplify reading of standard input --- libs/stream.c | 71 ++++++++++++++++++++++++--------------------------- 1 file changed, 33 insertions(+), 38 deletions(-) diff --git a/libs/stream.c b/libs/stream.c index b30085a..3c03f5c 100644 --- a/libs/stream.c +++ b/libs/stream.c @@ -1,65 +1,58 @@ /* See LICENSE file for copyright and license details. */ void readstdin(void) { - char buf[sizeof tx.text], *p; - size_t i, itemsiz = 0; - unsigned int tmpmax = 0; + char *line = NULL; + size_t i, junk, size = 0; + ssize_t len; +#if USEIMAGE + int oneitem = 0; +#endif - if (passwd) { + if (passwd) { // -P: No items should be displayed sp.inputw = lines = 0; return; } - if (listfile) { + if (listfile) { // -lf: List file is used so no need to read stdin readfile(); return; } - int o = 0; - - // read each line from stdin and add it to the item list - for (i = 0; fgets(buf, sizeof buf, stdin); i++) { - if (i + 1 >= itemsiz) { - itemsiz += 256; - if (!(items = realloc(items, itemsiz * sizeof(*items)))) - die("spmenu: cannot realloc %zu bytes:", itemsiz * sizeof(*items)); - } - if ((p = strchr(buf, '\n'))) - *p = '\0'; - if (!(items[i].text = strdup(buf))) - die("spmenu: cannot strdup %u bytes:", strlen(buf) + 1); - items[i].hp = arrayhas(hpitems, hplength, items[i].text); - draw_font_getexts(draw->font, buf, strlen(buf), &tmpmax, NULL, True); - if (tmpmax > sp.inputw) { - sp.inputw = tmpmax; - } + /* read each line from stdin and add it to the item list */ + for (i = 0; (len = getline(&line, &junk, stdin)) != -1; i++, line = NULL) { + if (i + 1 >= size / sizeof *items) + if (!(items = realloc(items, (size += BUFSIZ)))) + die("cannot realloc %zu bytes:", size); + if (line[len - 1] == '\n') + line[len - 1] = '\0'; + items[i].text = line; items[i].index = i; + items[i].hp = arrayhas(hpitems, hplength, items[i].text); if (parsemarkup(i)) { - o = 1; - } - -#if !USEIMAGE - if (o) { - ; - } -#endif - } - #if USEIMAGE - if (!o) img.longestedge = img.imagegaps = 0; + oneitem = 1; #endif + } - // clean - if (items) { - items[i].text = NULL; + } + free(line); + + if (items) { + items[i].text = NULL; #if USEIMAGE items[i].image = NULL; #endif } - lines = MIN(lines, i); +#if USEIMAGE + if (oneitem) { + img.longestedge = img.imagegaps = 0; + } +#endif + + lines = MIN(lines, i); } void readfile(void) { @@ -200,5 +193,7 @@ int parsemarkup(int index) { items[index].text += strlen("img://")+strlen(data)+1; } } + + return 0; #endif }