Merge pull request #22734 from poettering/decimal-str-width-test

DECIMAL_STR_WIDTH() + DECIMAL_STR_MAX() tweaks
This commit is contained in:
Lennart Poettering
2022-03-14 23:07:59 +01:00
committed by GitHub
3 changed files with 72 additions and 15 deletions
+18 -9
View File
@@ -309,22 +309,31 @@ static inline int __coverity_check_and_return__(int condition) {
#define sizeof_field(struct_type, member) sizeof(((struct_type *) 0)->member)
/* Returns the number of chars needed to format variables of the
* specified type as a decimal string. Adds in extra space for a
* negative '-' prefix (hence works correctly on signed
* types). Includes space for the trailing NUL. */
/* Returns the number of chars needed to format variables of the specified type as a decimal string. Adds in
* extra space for a negative '-' prefix for signed types. Includes space for the trailing NUL. */
#define DECIMAL_STR_MAX(type) \
(2U+(sizeof(type) <= 1 ? 3U : \
((size_t) IS_SIGNED_INTEGER_TYPE(type) + 1U + \
(sizeof(type) <= 1 ? 3U : \
sizeof(type) <= 2 ? 5U : \
sizeof(type) <= 4 ? 10U : \
sizeof(type) <= 8 ? 20U : sizeof(int[-2*(sizeof(type) > 8)])))
sizeof(type) <= 8 ? (IS_SIGNED_INTEGER_TYPE(type) ? 19U : 20U) : sizeof(int[-2*(sizeof(type) > 8)])))
/* Returns the number of chars needed to format the specified integer value. It's hence more specific than
* DECIMAL_STR_MAX() which answers the same question for all possible values of the specified type. Does
* *not* include space for a trailing NUL. (If you wonder why we special case _x_ == 0 here: it's to trick
* out gcc's -Wtype-limits, which would complain on comparing an unsigned type with < 0, otherwise. By
* special-casing == 0 here first, we can use <= 0 instead of < 0 to trick out gcc.) */
#define DECIMAL_STR_WIDTH(x) \
({ \
typeof(x) _x_ = (x); \
size_t ans = IS_SIGNED_INTEGER_TYPE(_x_) ? 2 : 1; \
while ((_x_ /= 10) != 0) \
ans++; \
size_t ans; \
if (_x_ == 0) \
ans = 1; \
else { \
ans = _x_ <= 0 ? 2 : 1; \
while ((_x_ /= 10) != 0) \
ans++; \
} \
ans; \
})