| 1 |
/* SPDX-License-Identifier: LGPL-2.1-or-later */ |
| 2 |
#pragma once |
| 3 |
|
| 4 |
#include "basic-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 |
static inline uint32_t UINT32_SCALE_FROM_PERCENT(int percent) { |
| 18 |
assert_cc(INT_MAX <= UINT32_MAX); |
| 19 |
|
| 20 |
return (uint32_t) (((uint64_t) CLAMP(percent, 0, 100) * UINT32_MAX + 50) / 100U); |
| 21 |
} |
| 22 |
|
| 23 |
static inline uint32_t UINT32_SCALE_FROM_PERMILLE(int permille) { |
| 24 |
return (uint32_t) (((uint64_t) CLAMP(permille, 0, 1000) * UINT32_MAX + 500) / 1000U); |
| 25 |
} |
| 26 |
|
| 27 |
static inline uint32_t UINT32_SCALE_FROM_PERMYRIAD(int permyriad) { |
| 28 |
return (uint32_t) (((uint64_t) CLAMP(permyriad, 0, 10000) * UINT32_MAX + 5000) / 10000U); |
| 29 |
} |
| 30 |
|
| 31 |
static inline int UINT32_SCALE_TO_PERCENT(uint32_t scale) { |
| 32 |
uint32_t u; |
| 33 |
|
| 34 |
u = (uint32_t) ((((uint64_t) scale) * 100U + UINT32_MAX/2) / UINT32_MAX); |
| 35 |
if (u > INT_MAX) |
| 36 |
return -ERANGE; |
| 37 |
|
| 38 |
return (int) u; |
| 39 |
} |
| 40 |
|
| 41 |
static inline int UINT32_SCALE_TO_PERMILLE(uint32_t scale) { |
| 42 |
uint32_t u; |
| 43 |
|
| 44 |
u = (uint32_t) ((((uint64_t) scale) * 1000U + UINT32_MAX/2) / UINT32_MAX); |
| 45 |
if (u > INT_MAX) |
| 46 |
return -ERANGE; |
| 47 |
|
| 48 |
return (int) u; |
| 49 |
} |
| 50 |
|
| 51 |
static inline int UINT32_SCALE_TO_PERMYRIAD(uint32_t scale) { |
| 52 |
uint32_t u; |
| 53 |
|
| 54 |
u = (uint32_t) ((((uint64_t) scale) * 10000U + UINT32_MAX/2) / UINT32_MAX); |
| 55 |
if (u > INT_MAX) |
| 56 |
return -ERANGE; |
| 57 |
|
| 58 |
return (int) u; |
| 59 |
} |
| 60 |
|
| 61 |
#define PERMYRIAD_AS_PERCENT_FORMAT_STR "%i.%02i%%" |
| 62 |
#define PERMYRIAD_AS_PERCENT_FORMAT_VAL(x) ((x)/100), ((x)%100) |