From 7d40b6856876751f17d85422cdea45d5622fe837 Mon Sep 17 00:00:00 2001 From: Explorer09 Date: Tue, 12 Nov 2024 01:55:54 +0800 Subject: [PATCH] Introduce countDigits() function for PID and UID field widths countDigits() is designed with 64-bit integer input and may be reused for computing field widths of, for example, memory addresses. Signed-off-by: Kang-Che Sung Co-authored-by: Benny Baumann Co-authored-by: Odric Roux-Paris --- Row.c | 4 ++-- XUtils.c | 15 +++++++++++++++ XUtils.h | 5 +++++ 3 files changed, 22 insertions(+), 2 deletions(-) diff --git a/Row.c b/Row.c index d795787e6..13a1313ac 100644 --- a/Row.c +++ b/Row.c @@ -89,7 +89,7 @@ void Row_setPidColumnWidth(pid_t maxPid) { return; } - Row_pidDigits = (int)log10(maxPid) + 1; + Row_pidDigits = countDigits((size_t)maxPid, 10); assert(Row_pidDigits <= ROW_MAX_PID_DIGITS); } @@ -99,7 +99,7 @@ void Row_setUidColumnWidth(uid_t maxUid) { return; } - Row_uidDigits = (int)log10(maxUid) + 1; + Row_uidDigits = countDigits((size_t)maxUid, 10); assert(Row_uidDigits <= ROW_MAX_UID_DIGITS); } diff --git a/XUtils.c b/XUtils.c index 94a14df64..aa9c9bf7c 100644 --- a/XUtils.c +++ b/XUtils.c @@ -374,6 +374,21 @@ double sumPositiveValues(const double* array, size_t count) { return sum; } +/* Counts the number of digits needed to print "n" with a given base. + If "n" is zero, returns 1. This function is expected to called with + small numbers often, hence a O(log(n)) time algorithm is used. */ +size_t countDigits(size_t n, size_t base) { + assert(base > 1); + size_t res = 1; + for (size_t limit = base; n >= limit; limit *= base) { + res++; + if (base && limit > SIZE_MAX / base) { + break; + } + } + return res; +} + #if !defined(HAVE_BUILTIN_CTZ) // map a bit value mod 37 to its position static const uint8_t mod37BitPosition[] = { diff --git a/XUtils.h b/XUtils.h index 17576f937..2e10a57bb 100644 --- a/XUtils.h +++ b/XUtils.h @@ -141,6 +141,11 @@ int compareRealNumbers(double a, double b); ATTR_NONNULL ATTR_ACCESS3_R(1, 2) double sumPositiveValues(const double* array, size_t count); +/* Counts the number of digits needed to print "n" with a given base. + If "n" is zero, returns 1. This function is expected to called with + small numbers often, hence a O(log(n)) time algorithm is used. */ +size_t countDigits(size_t n, size_t base); + /* Returns the number of trailing zero bits */ #if defined(HAVE_BUILTIN_CTZ) static inline unsigned int countTrailingZeros(unsigned int x) {