Skip to content

Commit a865959

Browse files
H. Peter AnvinJames Bottomley
H. Peter Anvin
authored and
James Bottomley
committed
[SCSI] lib: string_get_size(): don't hang on zero; no decimals on exact
We would hang forever when passing a zero to string_get_size(). Furthermore, string_get_size() would produce decimals on a value small enough to be exact. Finally, a few formatting issues are inconsistent with standard SI style guidelines. - If the value is less than the divisor, skip the entire rounding step. This prints out all small values including zero as integers, without decimals. - Add a space between the value and the symbol for the unit, consistent with standard SI practice. - Lower case k in kB since we are talking about powers of 10. - Finally, change "int" to "unsigned int" in one place to shut up a gcc warning when compiling the code out-of-kernel for testing. Signed-off-by: H. Peter Anvin <[email protected]> Signed-off-by: James Bottomley <[email protected]>
1 parent 3fe68cc commit a865959

File tree

1 file changed

+19
-15
lines changed

1 file changed

+19
-15
lines changed

lib/string_helpers.c

+19-15
Original file line numberDiff line numberDiff line change
@@ -23,15 +23,15 @@
2323
int string_get_size(u64 size, const enum string_size_units units,
2424
char *buf, int len)
2525
{
26-
const char *units_10[] = { "B", "KB", "MB", "GB", "TB", "PB",
26+
const char *units_10[] = { "B", "kB", "MB", "GB", "TB", "PB",
2727
"EB", "ZB", "YB", NULL};
2828
const char *units_2[] = {"B", "KiB", "MiB", "GiB", "TiB", "PiB",
2929
"EiB", "ZiB", "YiB", NULL };
3030
const char **units_str[] = {
3131
[STRING_UNITS_10] = units_10,
3232
[STRING_UNITS_2] = units_2,
3333
};
34-
const int divisor[] = {
34+
const unsigned int divisor[] = {
3535
[STRING_UNITS_10] = 1000,
3636
[STRING_UNITS_2] = 1024,
3737
};
@@ -40,23 +40,27 @@ int string_get_size(u64 size, const enum string_size_units units,
4040
char tmp[8];
4141

4242
tmp[0] = '\0';
43+
i = 0;
44+
if (size >= divisor[units]) {
45+
while (size >= divisor[units] && units_str[units][i]) {
46+
remainder = do_div(size, divisor[units]);
47+
i++;
48+
}
4349

44-
for (i = 0; size > divisor[units] && units_str[units][i]; i++)
45-
remainder = do_div(size, divisor[units]);
50+
sf_cap = size;
51+
for (j = 0; sf_cap*10 < 1000; j++)
52+
sf_cap *= 10;
4653

47-
sf_cap = size;
48-
for (j = 0; sf_cap*10 < 1000; j++)
49-
sf_cap *= 10;
50-
51-
if (j) {
52-
remainder *= 1000;
53-
do_div(remainder, divisor[units]);
54-
snprintf(tmp, sizeof(tmp), ".%03lld",
55-
(unsigned long long)remainder);
56-
tmp[j+1] = '\0';
54+
if (j) {
55+
remainder *= 1000;
56+
do_div(remainder, divisor[units]);
57+
snprintf(tmp, sizeof(tmp), ".%03lld",
58+
(unsigned long long)remainder);
59+
tmp[j+1] = '\0';
60+
}
5761
}
5862

59-
snprintf(buf, len, "%lld%s%s", (unsigned long long)size,
63+
snprintf(buf, len, "%lld%s %s", (unsigned long long)size,
6064
tmp, units_str[units][i]);
6165

6266
return 0;

0 commit comments

Comments
 (0)