1
1
mirror of https://github.com/systemd/systemd-stable.git synced 2025-01-12 09:17:44 +03:00

percent-util: clamp percent range before converting to 2^32 scale

Let#s better be safe than sorry and clamp the input, so that we don't
hit overflow issues.
This commit is contained in:
Lennart Poettering 2021-10-29 14:33:37 +02:00 committed by Yu Watanabe
parent 4768cc450d
commit 2f2cdd7250

View File

@ -19,15 +19,16 @@ int parse_permyriad(const char *p);
* a value relative to 100% == 2^32-1. Rounds to closest. */
static inline uint32_t UINT32_SCALE_FROM_PERCENT(int percent) {
assert_cc(INT_MAX <= UINT32_MAX);
return (uint32_t) (((uint64_t) percent * UINT32_MAX + 50) / 100U);
return (uint32_t) (((uint64_t) CLAMP(percent, 0, 100) * UINT32_MAX + 50) / 100U);
}
static inline uint32_t UINT32_SCALE_FROM_PERMILLE(int permille) {
return (uint32_t) (((uint64_t) permille * UINT32_MAX + 500) / 1000U);
return (uint32_t) (((uint64_t) CLAMP(permille, 0, 1000) * UINT32_MAX + 500) / 1000U);
}
static inline uint32_t UINT32_SCALE_FROM_PERMYRIAD(int permyriad) {
return (uint32_t) (((uint64_t) permyriad * UINT32_MAX + 5000) / 10000U);
return (uint32_t) (((uint64_t) CLAMP(permyriad, 0, 10000) * UINT32_MAX + 5000) / 10000U);
}
static inline int UINT32_SCALE_TO_PERCENT(uint32_t scale) {