logo

utils

~/.local/bin tools and git-hooks git clone https://hacktivis.me/git/utils.git
commit: 792c66d2246fffe3bc2f43e6b07ef64904f430c9
parent b16e98b53d15d81190a8b02ec263812d7ecdd67b
Author: Haelwenn (lanodan) Monnier <contact@hacktivis.me>
Date:   Tue, 17 Aug 2021 15:28:56 +0200

bin/humanize: Use the same precision on -b and -d

Diffstat:

Mbin/humanize.c16++++++++++++----
1 file changed, 12 insertions(+), 4 deletions(-)

diff --git a/bin/humanize.c b/bin/humanize.c @@ -25,14 +25,22 @@ main(int argc, char *argv[]) { int c; int flags = HN_NOSPACE | HN_DECIMAL; + // default to -d int divisor = HN_DIVISOR_1000; + size_t buflen = 6; while((c = getopt(argc, argv, "bd")) != -1) { switch(c) { - case 'b': divisor = ~HN_DIVISOR_1000; break; - case 'd': divisor = HN_DIVISOR_1000; break; + case 'b': + divisor = ~HN_DIVISOR_1000; + buflen = 7; // 4 digits, 3 letters for suffix, NUL byte + break; + case 'd': + divisor = HN_DIVISOR_1000; + buflen = 6; // 4 digits, 2 letters for suffix, NUL byte + break; case '?': fprintf(stderr, "Error: Unrecognised option: '-%c'\n", optopt); usage(); @@ -43,7 +51,7 @@ main(int argc, char *argv[]) for(; optind < argc; optind++) { const char *errstr = NULL; - char buffer[6] = "-"; + char buffer[7] = "-"; // 1024^(6+1) goes higher than long long; don't ask for the moon long long n = strtonum(argv[optind], LLONG_MIN, LLONG_MAX, &errstr); @@ -52,7 +60,7 @@ main(int argc, char *argv[]) errx(1, "strtonum: %s is %s", argv[optind], errstr); } - int err = humanize_number(buffer, sizeof(buffer), n, "", HN_AUTOSCALE, flags | divisor); + int err = humanize_number(buffer, buflen, n, "", HN_AUTOSCALE, flags | divisor); if(err < 0) { switch(errno)