Fix num2str() output when maxlen <= strlen(tmp)
authorTomohiro Kusumi <tkusumi@tuxera.com>
Tue, 4 Apr 2017 20:22:17 +0000 (23:22 +0300)
committerJens Axboe <axboe@fb.com>
Sat, 8 Apr 2017 17:04:21 +0000 (11:04 -0600)
commite5a415c889251928dd256738a8022f1eab91c73b
tree0a360f340598ea9230077d4a19954855bc7583b6
parent5e7468209ad6956c3d7393110c379dd7d316dd7e
Fix num2str() output when maxlen <= strlen(tmp)

Since a local variable decimals is unsigned int, this conditional
 if (decimals <= 1)
needs cast as shown below.
 if ((int)decimals <= 1)

Otherwise it results in showing some garbage in case of maxlen == 0,

 # cat ./test0.c
 #include <stdio.h>
 #include "lib/num2str.h"
 int main(void) {
         printf("%s\n", num2str(123, 3, 1, 1, N2S_BYTE));
         printf("%s\n", num2str(123, 2, 1, 1, N2S_BYTE));
         printf("%s\n", num2str(123, 1, 1, 1, N2S_BYTE));
         printf("%s\n", num2str(123, 0, 1, 1, N2S_BYTE));
         return 0;
 }
 # gcc -Wall -g -DCONFIG_STATIC_ASSERT ./test0.c ./lib/num2str.c
 # ./a.out
 123B
 0KiB
 0KiB
 0.0?$-JB
 # ./a.out
 123B
 0KiB
 0KiB
 0.0#;bB
 # ./a.out
 123B
 0KiB
 0KiB
 0.0|B

whereas with this commit it prints "0B".

 # gcc -Wall -g -DCONFIG_STATIC_ASSERT ./test0.c ./lib/num2str.c
 # ./a.out
 123B
 0KiB
 0KiB
 0B

Signed-off-by: Tomohiro Kusumi <tkusumi@tuxera.com>
Signed-off-by: Jens Axboe <axboe@fb.com>
lib/num2str.c