diff options
author | Lennart Poettering <lennart@poettering.net> | 2019-12-09 18:26:10 +0100 |
---|---|---|
committer | Lennart Poettering <lennart@poettering.net> | 2019-12-09 18:35:10 +0100 |
commit | e49e4c33dc965b09d8d4cb95780f79de6d1d5eb5 (patch) | |
tree | 6cbbb30bdc7d6b28621438bec1bcb84ace425646 | |
parent | 85c267afa7ce4697a1231649de815b2556b3950f (diff) | |
download | systemd-e49e4c33dc965b09d8d4cb95780f79de6d1d5eb5.tar.gz |
macro: introduce new GREEDY_ALLOC_ROUND_UP() helper
-rw-r--r-- | src/basic/macro.h | 23 |
1 files changed, 23 insertions, 0 deletions
diff --git a/src/basic/macro.h b/src/basic/macro.h index 712bb422b1..5aa7f59c0b 100644 --- a/src/basic/macro.h +++ b/src/basic/macro.h @@ -179,6 +179,29 @@ static inline unsigned long ALIGN_POWER2(unsigned long u) { return 1UL << (sizeof(u) * 8 - __builtin_clzl(u - 1UL)); } +static inline size_t GREEDY_ALLOC_ROUND_UP(size_t l) { + size_t m; + + /* Round up allocation sizes a bit to some reasonable, likely larger value. This is supposed to be + * used for cases which are likely called in an allocation loop of some form, i.e. that repetitively + * grow stuff, for example strv_extend() and suchlike. + * + * Note the difference to GREEDY_REALLOC() here, as this helper operates on a single size value only, + * and rounds up to next multiple of 2, needing no further counter. + * + * Note the benefits of direct ALIGN_POWER2() usage: type-safety for size_t, sane handling for very + * small (i.e. <= 2) and safe handling for very large (i.e. > SSIZE_MAX) values. */ + + if (l <= 2) + return 2; /* Never allocate less than 2 of something. */ + + m = ALIGN_POWER2(l); + if (m == 0) /* overflow? */ + return l; + + return m; +} + #ifndef __COVERITY__ # define VOID_0 ((void)0) #else |