logo

utils-extra

Collection of extra tools for Unixes git clone https://anongit.hacktivis.me/git/utils-extra.git/
commit: ea7360c37dd40b1aca6456566cf4c32ba03c2bf9
parent 3286a659856e9a63391f2a74e5581b40c9332e84
Author: Haelwenn (lanodan) Monnier <contact@hacktivis.me>
Date:   Thu, 17 Apr 2025 01:11:35 +0200

cmd/humanize: fix off-by-one for max prefix

Diffstat:

Mcmd/humanize.c5+++--
Mtest-cmd/humanize13+++++++++++++
2 files changed, 16 insertions(+), 2 deletions(-)

diff --git a/cmd/humanize.c b/cmd/humanize.c @@ -22,13 +22,14 @@ human_num(long double num, bool iec) char **prefixes = iec ? iec_prefixes : si_prefixes; unsigned quotient = 0; - while(num > div && quotient < PFX) + while(num > div && quotient < (PFX - 1)) { num /= div; quotient += 1; } - printf("%Lg %s\n", num, prefixes[quotient]); + // %g to avoid decimal separator when possible, %f to avoid %e exponent form + printf((num > div ? "%Lf %s\n" : "%Lg %s\n"), num, prefixes[quotient]); } static void diff --git a/test-cmd/humanize b/test-cmd/humanize @@ -66,6 +66,17 @@ badflag_body() { atf_check -s exit:1 -e "inline:humanize: Error: Unrecognised option: '-f'\n"'Usage: humanize [-bdt] number\n' ../cmd/humanize -f 123 } +atf_test_case pfx_limit +pfx_limit_body() { + atf_check -o "inline:1024 RiB\n" ../cmd/humanize -b "$(echo 1024^10 | bc -l)" + atf_check -o "inline:1024 QiB\n" ../cmd/humanize -b "$(echo 1024^11 | bc -l)" + atf_check -o "inline:1048576.000000 QiB\n" ../cmd/humanize -b "$(echo 1024^12 | bc -l)" + + atf_check -o "inline:1000 R\n" ../cmd/humanize "$(echo 1000^10 | bc -l)" + atf_check -o "inline:1000 Q\n" ../cmd/humanize "$(echo 1000^11 | bc -l)" + atf_check -o "inline:1000000.000000 Q\n" ../cmd/humanize "$(echo 1000^12 | bc -l)" +} + atf_test_case duration duration_body() { atf_check -o "inline:1s\n" ../cmd/humanize -t 1 @@ -91,5 +102,7 @@ atf_init_test_cases() { atf_add_test_case six atf_add_test_case seven + atf_add_test_case pfx_limit + atf_add_test_case duration }