AmendHub

Download:

jcs

/

subtext

/

amendments

/

332

util: Turn EXPAND_TO_FIT into grow_to_fit function

This will return false if the xrealloc failed, leaving the original
pointer untouched. With the macro, the pointer would get overwritten
with NULL and not be able to be freed.

jcs made amendment 332 about 1 year ago
--- util.c Wed Mar 1 15:45:47 2023 +++ util.c Wed Mar 1 16:26:29 2023 @@ -225,6 +225,33 @@ xstrndup(const char *str, size_t maxlen) return copy; } +/* if var having used_size can't fit add, grow it by grow_amount */ +bool +grow_to_fit(void *var, size_t *var_size, size_t used_size, size_t add, + size_t grow_amount) +{ + char **p = var; + char *curp = *p; + char *newp; + size_t new_size; + + if (used_size + add < *var_size) + return true; + + new_size = *var_size; + while (new_size < used_size + add) + new_size += grow_amount; + + newp = xrealloc(curp, new_size); + if (newp == NULL) + return false; + + *var_size = new_size; + *p = newp; + + return true; +} + /* * String functions */ --- util.h Wed Mar 1 15:37:54 2023 +++ util.h Thu Mar 2 08:59:47 2023 @@ -34,20 +34,6 @@ #define MAX(a, b) ((a) > (b) ? (a) : (b)) #define BOUND(a, min, max) ((a) > (max) ? (max) : ((a) < (min) ? (min) : (a))) -/* - * If var of var_size (of which used_size is used) is not big enough to - * hold add, expand it by grow_amount (to give headroom for subsequent - * expansion). - */ -#define EXPAND_TO_FIT(var, var_size, used_size, add, grow_amount) { \ - if ((used_size) + (add) >= (var_size)) { \ - while ((used_size) + (add) >= (var_size)) { \ - (var_size) += (grow_amount); \ - } \ - (var) = xrealloc((var), (var_size)); \ - } \ -} - #define CHARS_TO_LONG(a,b,c,d) (unsigned long)(\ ((unsigned long)((unsigned char)(a)) << 24) | \ ((unsigned long)((unsigned char)(b)) << 16) | \ @@ -103,6 +89,9 @@ void * xrealloc(void *src, size_t size); void * xreallocarray(void *, size_t, size_t); char * xstrdup(const char *); char * xstrndup(const char *str, size_t maxlen); + +bool grow_to_fit(void *var, size_t *var_size, size_t used_size, size_t add, + size_t grow_amount); short getline(char *str, size_t len, char **ret); const char * ordinal(unsigned short n);