Skip to content

Commit 32e6407

Browse files
committed
make pretty_size() more precise
1 parent 5b38c73 commit 32e6407

File tree

1 file changed

+27
-30
lines changed

1 file changed

+27
-30
lines changed

src/show.c

+27-30
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@
1616

1717
#include "utils/json.h"
1818

19+
#define half_rounded(x) (((x) + ((x) < 0 ? 0 : 1)) / 2)
20+
1921
/* struct to align fields printed in plain format */
2022
typedef struct ShowBackendRow
2123
{
@@ -141,7 +143,8 @@ do_show(const char *instance_name, time_t requested_backup_id, bool show_archive
141143
void
142144
pretty_size(int64 size, char *buf, size_t len)
143145
{
144-
int exp = 0;
146+
int64 limit = 10 * 1024;
147+
int64 limit2 = limit * 2 - 1;
145148

146149
/* minus means the size is invalid */
147150
if (size < 0)
@@ -150,36 +153,30 @@ pretty_size(int64 size, char *buf, size_t len)
150153
return;
151154
}
152155

153-
/* determine postfix */
154-
while (size > 9999)
155-
{
156-
++exp;
157-
size /= 1000;
158-
}
159-
160-
switch (exp)
156+
if (Abs(size) < limit)
157+
snprintf(buf, len, "%dB", (int) size);
158+
else
161159
{
162-
case 0:
163-
snprintf(buf, len, "%dB", (int) size);
164-
break;
165-
case 1:
166-
snprintf(buf, len, "%dkB", (int) size);
167-
break;
168-
case 2:
169-
snprintf(buf, len, "%dMB", (int) size);
170-
break;
171-
case 3:
172-
snprintf(buf, len, "%dGB", (int) size);
173-
break;
174-
case 4:
175-
snprintf(buf, len, "%dTB", (int) size);
176-
break;
177-
case 5:
178-
snprintf(buf, len, "%dPB", (int) size);
179-
break;
180-
default:
181-
strncpy(buf, "***", len);
182-
break;
160+
size >>= 9;
161+
if (Abs(size) < limit2)
162+
snprintf(buf, len, "%dkB", (int) half_rounded(size));
163+
else
164+
{
165+
size >>= 10;
166+
if (Abs(size) < limit2)
167+
snprintf(buf, len, "%dMB", (int) half_rounded(size));
168+
else
169+
{
170+
size >>= 10;
171+
if (Abs(size) < limit2)
172+
snprintf(buf, len, "%dGB", (int) half_rounded(size));
173+
else
174+
{
175+
size >>= 10;
176+
snprintf(buf, len, "%dTB", (int) half_rounded(size));
177+
}
178+
}
179+
}
183180
}
184181
}
185182

0 commit comments

Comments
 (0)