From 921fac512eed138109b0f66b9897cd3030ad5191 Mon Sep 17 00:00:00 2001 From: Aaron Ball Date: Tue, 1 Jun 2021 09:50:23 -0600 Subject: Fix printbar and add a lot more tests Previously printbar wasn't correctly calculating data width. The fill of bars included the surrounding brackets (so a width of 10 was actually 8 + 2 brackets). This makes the fill width the defined with, +2 extra chars for the square bracket. This makes the fill calculations accurate now. --- src/common.c | 19 +++++++++---------- tests/test_common.c | 17 +++++++++++++++++ 2 files changed, 26 insertions(+), 10 deletions(-) diff --git a/src/common.c b/src/common.c index e1bfaaf..812431a 100644 --- a/src/common.c +++ b/src/common.c @@ -47,27 +47,26 @@ char* trim(char* str) { } void print_bar(int width, float percent, char* buf) { - double fill = width * percent; + int fill_maj = width * percent; + int fill_min = (width * percent - fill_maj) * 10; int i = 1; - int remainder = 0; buf[0] = '['; - while(i < fill) { + while(i <= fill_maj) { buf[i] = ':'; i++; } - remainder = (fill + 1 - i) * 10; - if(i > fill && remainder >= 5.0) { - buf[i] = ':'; - i++; - } else if(i > fill && remainder < 5.0 && remainder > 0) { - buf[i] = '.'; + if(fill_maj > 0 && fill_min > 0) { + if(fill_min >= 5) + buf[i] = ':'; + else + buf[i] = '.'; i++; } - while(i < width) { + while(i <= width) { buf[i] = ' '; i++; } diff --git a/tests/test_common.c b/tests/test_common.c index e08c0ee..42acf48 100644 --- a/tests/test_common.c +++ b/tests/test_common.c @@ -41,6 +41,23 @@ void test_bar() { print_bar(10, 0, buf); assert_strncmp(buf, "[ ", 3); + print_bar(8, 0, buf); + assert_strcmp(buf, "[ ]"); + + print_bar(8, 1, buf); + assert_strcmp(buf, "[::::::::]"); + + print_bar(8, .42, buf); + assert_strcmp(buf, "[:::. ]"); + + // Fill is 0, so no colons or periods + print_bar(10, .13, buf); + assert_strcmp(buf, "[:. ]"); + + // Fill is 0, so no colons or periods + print_bar(10, .17, buf); + assert_strncmp(buf, "[:: ", 4); + // Fill is 2, +.5, so three colons print_bar(10, .25, buf); assert_strncmp(buf, "[::: ", 5); -- cgit v1.2.3