Skip to content

Commit

Permalink
Introduce countDigits() function for PID and UID field widths
Browse files Browse the repository at this point in the history
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 <[email protected]>
Co-authored-by: Benny Baumann <[email protected]>
Co-authored-by: Odric Roux-Paris <[email protected]>
  • Loading branch information
3 people committed Nov 11, 2024
1 parent 7ac4ac1 commit 7d40b68
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 2 deletions.
4 changes: 2 additions & 2 deletions Row.c
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}

Expand All @@ -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);
}

Expand Down
15 changes: 15 additions & 0 deletions XUtils.c
Original file line number Diff line number Diff line change
Expand Up @@ -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[] = {
Expand Down
5 changes: 5 additions & 0 deletions XUtils.h
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down

0 comments on commit 7d40b68

Please sign in to comment.