Skip to content

Commit 4f79346

Browse files
committed
human-readable: calculate numbers in a loop
This drops a lot of `else if` blocks and extends units by "E", "Z" & "Y".
1 parent 797e17f commit 4f79346

2 files changed

Lines changed: 19 additions & 21 deletions

File tree

lib/compat.c

Lines changed: 16 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -181,26 +181,24 @@ char *do_big_num(int64 num, int human_flag, const char *fract)
181181

182182
if (human_flag > 1) {
183183
int mult = human_flag == 2 ? 1000 : 1024;
184+
184185
if (num >= mult || num <= -mult) {
185-
double dnum = (double)num / mult;
186-
char units;
187-
if (num < 0)
188-
dnum = -dnum;
189-
if (dnum < mult)
190-
units = 'K';
191-
else if ((dnum /= mult) < mult)
192-
units = 'M';
193-
else if ((dnum /= mult) < mult)
194-
units = 'G';
195-
else if ((dnum /= mult) < mult)
196-
units = 'T';
197-
else {
198-
dnum /= mult;
199-
units = 'P';
186+
const char* units = " KMGTPEZY";
187+
int64 powi = 1;
188+
189+
for (;;) {
190+
if (labs(num / mult) < powi)
191+
break;
192+
193+
if (units[1] == '\0')
194+
break;
195+
196+
powi *= mult;
197+
++units;
200198
}
201-
if (num < 0)
202-
dnum = -dnum;
203-
snprintf(bufs[n], sizeof bufs[0], "%.2f%c", dnum, units);
199+
200+
snprintf(bufs[n], sizeof bufs[0], "%.2f%c",
201+
(double) num / powi, *units);
204202
return bufs[n];
205203
}
206204
}

rsync.1.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3326,9 +3326,9 @@ expand it.
33263326
digits) by specifying the `--no-human-readable` (`--no-h`) option.
33273327

33283328
The unit letters that are appended in levels 2 and 3 are: `K` (kilo), `M`
3329-
(mega), `G` (giga), `T` (tera), or `P` (peta). For example, a 1234567-byte
3330-
file would output as 1.23M in level-2 (assuming that a period is your local
3331-
decimal point).
3329+
(mega), `G` (giga), `T` (tera), `P` (peta), `E` (exa), `Z` (zetta) or `Y`
3330+
(yotta). For example, a 1234567-byte file would output as 1.23M in level-2
3331+
(assuming that a period is your local decimal point).
33323332

33333333
Backward compatibility note: versions of rsync prior to 3.1.0 do not
33343334
support human-readable level 1, and they default to level 0. Thus,

0 commit comments

Comments
 (0)