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