tool_progress: make max5data() use an algorithm

Instead of a list of conditions. Makes a unified decimal output when the
value is less than 100. Prepares for > 64 bit data type.

Closes #18807
This commit is contained in:
Daniel Stenberg 2025-10-02 11:31:52 +02:00
parent 34dc762cef
commit e49698925c
No known key found for this signature in database
GPG key ID: 5CC908FDB71E12C2

View file

@ -31,48 +31,30 @@
Add suffix k, M, G when suitable... */ Add suffix k, M, G when suitable... */
static char *max5data(curl_off_t bytes, char *max5) static char *max5data(curl_off_t bytes, char *max5)
{ {
#define ONE_KILOBYTE (curl_off_t)1024 /* a signed 64-bit value is 8192 petabytes maximum */
#define ONE_MEGABYTE (1024 * ONE_KILOBYTE) const char unit[] = { 'k', 'M', 'G', 'T', 'P', 0 };
#define ONE_GIGABYTE (1024 * ONE_MEGABYTE) int k = 0;
#define ONE_TERABYTE (1024 * ONE_GIGABYTE)
#define ONE_PETABYTE (1024 * ONE_TERABYTE)
if(bytes < 100000) if(bytes < 100000)
msnprintf(max5, 6, "%5" CURL_FORMAT_CURL_OFF_T, bytes); msnprintf(max5, 6, "%5" CURL_FORMAT_CURL_OFF_T, bytes);
else if(bytes < 10000 * ONE_KILOBYTE) do {
msnprintf(max5, 6, "%4" CURL_FORMAT_CURL_OFF_T "k", bytes/ONE_KILOBYTE); curl_off_t nbytes = bytes / 1024;
if(nbytes < 100) {
else if(bytes < 100 * ONE_MEGABYTE) /* display with a decimal */
/* 'XX.XM' is good as long as we are less than 100 megs */ msnprintf(max5, 6, "%2" CURL_FORMAT_CURL_OFF_T ".%0"
msnprintf(max5, 6, "%2" CURL_FORMAT_CURL_OFF_T ".%0" CURL_FORMAT_CURL_OFF_T "%c", bytes/1024,
CURL_FORMAT_CURL_OFF_T "M", bytes/ONE_MEGABYTE, (bytes%1024) / (1024/10), unit[k]);
(bytes%ONE_MEGABYTE) / (ONE_MEGABYTE/10) ); break;
}
else if(bytes < 10000 * ONE_MEGABYTE) else if(nbytes < 10000) {
/* 'XXXXM' is good until we are at 10000MB or above */ /* no decimals */
msnprintf(max5, 6, "%4" CURL_FORMAT_CURL_OFF_T "M", bytes/ONE_MEGABYTE); msnprintf(max5, 6, "%4" CURL_FORMAT_CURL_OFF_T "%c", nbytes, unit[k]);
break;
else if(bytes < 100 * ONE_GIGABYTE) }
/* 10000 MB - 100 GB, we show it as XX.XG */ bytes = nbytes;
msnprintf(max5, 6, "%2" CURL_FORMAT_CURL_OFF_T ".%0" k++;
CURL_FORMAT_CURL_OFF_T "G", bytes/ONE_GIGABYTE, DEBUGASSERT(unit[k]);
(bytes%ONE_GIGABYTE) / (ONE_GIGABYTE/10) ); } while(unit[k]);
else if(bytes < 10000 * ONE_GIGABYTE)
/* up to 10000GB, display without decimal: XXXXG */
msnprintf(max5, 6, "%4" CURL_FORMAT_CURL_OFF_T "G", bytes/ONE_GIGABYTE);
else if(bytes < 10000 * ONE_TERABYTE)
/* up to 10000TB, display without decimal: XXXXT */
msnprintf(max5, 6, "%4" CURL_FORMAT_CURL_OFF_T "T", bytes/ONE_TERABYTE);
else
/* up to 10000PB, display without decimal: XXXXP */
msnprintf(max5, 6, "%4" CURL_FORMAT_CURL_OFF_T "P", bytes/ONE_PETABYTE);
/* 16384 petabytes (16 exabytes) is the maximum a 64-bit unsigned number can
hold, but our data type is signed so 8192PB will be the maximum. */
return max5; return max5;
} }