]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/percent-util.h
mkosi: update arch commit reference
[thirdparty/systemd.git] / src / basic / percent-util.h
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2 #pragma once
3
4 #include <errno.h>
5 #include <inttypes.h>
6
7 #include "macro.h"
8
9 int parse_percent_unbounded(const char *p);
10 int parse_percent(const char *p);
11
12 int parse_permille_unbounded(const char *p);
13 int parse_permille(const char *p);
14
15 int parse_permyriad_unbounded(const char *p);
16 int parse_permyriad(const char *p);
17
18 /* Some macro-like helpers that convert a percent/permille/permyriad value (as parsed by parse_percent()) to
19 * a value relative to 100% == 2^32-1. Rounds to closest. */
20 static inline uint32_t UINT32_SCALE_FROM_PERCENT(int percent) {
21 assert_cc(INT_MAX <= UINT32_MAX);
22
23 return (uint32_t) (((uint64_t) CLAMP(percent, 0, 100) * UINT32_MAX + 50) / 100U);
24 }
25
26 static inline uint32_t UINT32_SCALE_FROM_PERMILLE(int permille) {
27 return (uint32_t) (((uint64_t) CLAMP(permille, 0, 1000) * UINT32_MAX + 500) / 1000U);
28 }
29
30 static inline uint32_t UINT32_SCALE_FROM_PERMYRIAD(int permyriad) {
31 return (uint32_t) (((uint64_t) CLAMP(permyriad, 0, 10000) * UINT32_MAX + 5000) / 10000U);
32 }
33
34 static inline int UINT32_SCALE_TO_PERCENT(uint32_t scale) {
35 uint32_t u;
36
37 u = (uint32_t) ((((uint64_t) scale) * 100U + UINT32_MAX/2) / UINT32_MAX);
38 if (u > INT_MAX)
39 return -ERANGE;
40
41 return (int) u;
42 }
43
44 static inline int UINT32_SCALE_TO_PERMILLE(uint32_t scale) {
45 uint32_t u;
46
47 u = (uint32_t) ((((uint64_t) scale) * 1000U + UINT32_MAX/2) / UINT32_MAX);
48 if (u > INT_MAX)
49 return -ERANGE;
50
51 return (int) u;
52 }
53
54 static inline int UINT32_SCALE_TO_PERMYRIAD(uint32_t scale) {
55 uint32_t u;
56
57 u = (uint32_t) ((((uint64_t) scale) * 10000U + UINT32_MAX/2) / UINT32_MAX);
58 if (u > INT_MAX)
59 return -ERANGE;
60
61 return (int) u;
62 }
63
64 #define PERMYRIAD_AS_PERCENT_FORMAT_STR "%i.%02i%%"
65 #define PERMYRIAD_AS_PERCENT_FORMAT_VAL(x) ((x)/100), ((x)%100)