util: add some helpers for converting percent/permille/permyriad to parts of 2^32-1

At various places we accept values scaled to the range 0…2^32-1 which
are exposed to the user as percentages/permille/permyriad. Let's add
some helper macros (actually: typesafe macro-like functions) that help
with converting our internal encoding to the external encodings.

benefits: some of the previous code rounded up, some down. let's always
round to nearest, to ensure that our conversions are reversible. Also,
check for overflows correctly.

This also adds a test that makes sure that for the full
percent/permille/permyriad ranges we can convert forth and back without
loss of accuracy.
This commit is contained in:
Lennart Poettering
2021-02-18 22:36:34 +01:00
parent 38d0c27006
commit 3b6e71ad03
2 changed files with 97 additions and 0 deletions
+50
View File
@@ -1,6 +1,11 @@
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <errno.h>
#include <inttypes.h>
#include "macro.h"
int parse_percent_unbounded(const char *p);
int parse_percent(const char *p);
@@ -9,3 +14,48 @@ int parse_permille(const char *p);
int parse_permyriad_unbounded(const char *p);
int parse_permyriad(const char *p);
/* Some macro-like helpers that convert a percent/permille/permyriad value (as parsed by parse_percent()) to
* 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);
}
static inline uint32_t UINT32_SCALE_FROM_PERMILLE(int permille) {
return (uint32_t) (((uint64_t) permille * UINT32_MAX + 500) / 1000U);
}
static inline uint32_t UINT32_SCALE_FROM_PERMYRIAD(int permyriad) {
return (uint32_t) (((uint64_t) permyriad * UINT32_MAX + 5000) / 10000U);
}
static inline int UINT32_SCALE_TO_PERCENT(uint32_t scale) {
uint32_t u;
u = (uint32_t) ((((uint64_t) scale) * 100U + UINT32_MAX/2) / UINT32_MAX);
if (u > INT_MAX)
return -ERANGE;
return (int) u;
}
static inline int UINT32_SCALE_TO_PERMILLE(uint32_t scale) {
uint32_t u;
u = (uint32_t) ((((uint64_t) scale) * 1000U + UINT32_MAX/2) / UINT32_MAX);
if (u > INT_MAX)
return -ERANGE;
return (int) u;
}
static inline int UINT32_SCALE_TO_PERMYRIAD(uint32_t scale) {
uint32_t u;
u = (uint32_t) ((((uint64_t) scale) * 10000U + UINT32_MAX/2) / UINT32_MAX);
if (u > INT_MAX)
return -ERANGE;
return (int) u;
}