From d77de798c443efa010a7c3d1627233944fb3d9ab Mon Sep 17 00:00:00 2001 From: FRex Date: Sat, 7 Nov 2020 19:42:18 +0100 Subject: [PATCH] speed up by buffering the word and fputing once --- colors.c | 29 ++++++++++++++++++++--------- 1 file changed, 20 insertions(+), 9 deletions(-) diff --git a/colors.c b/colors.c index 5d3d333..44be2aa 100644 --- a/colors.c +++ b/colors.c @@ -81,11 +81,6 @@ const char * const kColors[] = { const int kColorCount = sizeof(kColors) / sizeof(kColors[0]); -static void resetColor(void) -{ - fputs("\033[0m", stdout); /* is this correct? */ -} - /* 32-bit fnv1, not 1a */ static unsigned fnv(const char * str) { @@ -100,12 +95,28 @@ static unsigned fnv(const char * str) return ret; } +#define COLOR_RESET_STRING "\033[0m" + static void printColoredByHash(const char * str) { + char buff[1024]; const int idx = fnv(str) % kColorCount; - fputs(kColors[idx], stdout); - fputs(str, stdout); /* not puts to not get a newline */ - resetColor(); + + if(strlen(str) > 1000) + { + /* too long, print 3 times */ + fputs(kColors[idx], stdout); + fputs(str, stdout); /* not puts to not get a newline */ + fputs(COLOR_RESET_STRING, stdout); + } + else + { + /* prepare the word and color and reset, then print it out */ + strcpy(buff, kColors[idx]); + strcat(buff, str); + strcat(buff, COLOR_RESET_STRING); + fputs(buff, stdout); + } } static int mygetline(char * buff, int len, int * toomuch) @@ -198,7 +209,7 @@ static int printhelp(const char * argv0) puts(c + 1); /* skip the ESC char to not interpret this as control sequence */ } /* for each color */ - resetColor(); + fputs(COLOR_RESET_STRING, stdout); return 0; }