diff options
author | Aaron Ball <nullspoon@oper.io> | 2021-06-01 09:50:23 -0600 |
---|---|---|
committer | Aaron Ball <nullspoon@oper.io> | 2021-06-01 09:50:23 -0600 |
commit | 921fac512eed138109b0f66b9897cd3030ad5191 (patch) | |
tree | 369a7bedf63b9eeebcbd0d455f42b3ac42fd04a3 | |
parent | e4438be128cb5944e106e7c5b495954e04622d82 (diff) | |
download | i3cstat-921fac512eed138109b0f66b9897cd3030ad5191.tar.gz i3cstat-921fac512eed138109b0f66b9897cd3030ad5191.tar.xz |
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.
-rw-r--r-- | src/common.c | 19 | ||||
-rw-r--r-- | 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); |