1
1
mirror of https://github.com/systemd/systemd-stable.git synced 2024-12-23 17:34:00 +03:00

Add saturate_add() that generalizes size_add()

This commit is contained in:
Zbigniew Jędrzejewski-Szmek 2022-05-12 16:29:48 +02:00
parent d1b8e56a62
commit 8b0c43475a
2 changed files with 17 additions and 1 deletions

View File

@ -457,8 +457,15 @@ static inline int __coverity_check_and_return__(int condition) {
_copy; \
})
#define saturate_add(x, y, limit) \
({ \
typeof(limit) _x = (x); \
typeof(limit) _y = (y); \
_x > (limit) || _y >= (limit) - _x ? (limit) : _x + _y; \
})
static inline size_t size_add(size_t x, size_t y) {
return y >= SIZE_MAX - x ? SIZE_MAX : x + y;
return saturate_add(x, y, SIZE_MAX);
}
typedef struct {

View File

@ -6,6 +6,15 @@
#include "macro.h"
#include "tests.h"
TEST(saturate_add) {
assert_se(saturate_add(1, 2, UINT8_MAX) == 3);
assert_se(saturate_add(1, UINT8_MAX-2, UINT8_MAX) == UINT8_MAX-1);
assert_se(saturate_add(1, UINT8_MAX-1, UINT8_MAX) == UINT8_MAX);
assert_se(saturate_add(1, UINT8_MAX, UINT8_MAX) == UINT8_MAX);
assert_se(saturate_add(2, UINT8_MAX, UINT8_MAX) == UINT8_MAX);
assert_se(saturate_add(60, 60, 50) == 50);
}
TEST(align_power2) {
unsigned long i, p2;