From: Matthew Fernandez Date: Sat, 30 Jul 2022 00:24:05 +0000 (-0700) Subject: cgraph: rename 'agxbuf.dyna' and flip its polarity X-Git-Tag: 5.0.1~16^2~1 X-Git-Url: https://granicus.if.org/sourcecode?a=commitdiff_plain;h=04a248348798a4a32fc9ac7e5d860a84ab5ee49f;p=graphviz cgraph: rename 'agxbuf.dyna' and flip its polarity On the surface, this change looks a little odd – why care about what bit means what in an internal field of a data structure? But this has an interesting side effect. After this change, the zeroed state of an agxbuf is a valid 0-sized dynamically allocated buffer, the same as the end state after `agxbdisown`. In other words, C99 zero initialization (`agxbuf xb = {0}`) now defines a reasonably “default” agxbuf state. This gives you all the benefits of the previous “I don’t know how long my data will be so I’ll just use `BUFSIZ` as a hint” approach with less typing and less hard coding. The next commit will roll this out for some simplification in agxbuf usage. --- diff --git a/lib/cgraph/agxbuf.h b/lib/cgraph/agxbuf.h index 7412114bd..9272f510f 100644 --- a/lib/cgraph/agxbuf.h +++ b/lib/cgraph/agxbuf.h @@ -23,7 +23,7 @@ char *buf; /* start of buffer */ char *ptr; /* next place to write */ char *eptr; /* end of buffer */ - int dyna; /* true if buffer is malloc'ed */ + int stack_allocated; // false if buffer is malloc'ed } agxbuf; /* agxbinit: @@ -33,12 +33,12 @@ static inline void agxbinit(agxbuf *xb, unsigned int hint, char *init) { if (init != NULL) { xb->buf = init; - xb->dyna = 0; + xb->stack_allocated = 1; } else { if (hint == 0) { hint = BUFSIZ; } - xb->dyna = 1; + xb->stack_allocated = 0; xb->buf = (char *)gv_calloc(hint, sizeof(char)); } xb->eptr = xb->buf + hint; @@ -50,7 +50,7 @@ static inline void agxbinit(agxbuf *xb, unsigned int hint, char *init) { * Free any malloced resources. */ static inline void agxbfree(agxbuf *xb) { - if (xb->dyna) + if (!xb->stack_allocated) free(xb->buf); } @@ -80,12 +80,12 @@ static inline void agxbmore(agxbuf *xb, size_t ssz) { if (size + ssz > nsize) nsize = size + ssz; cnt = (size_t)(xb->ptr - xb->buf); - if (xb->dyna) { + if (!xb->stack_allocated) { nbuf = (char *)gv_recalloc(xb->buf, size, nsize, sizeof(char)); } else { nbuf = (char *)gv_calloc(nsize, sizeof(char)); memcpy(nbuf, xb->buf, cnt); - xb->dyna = 1; + xb->stack_allocated = 0; } xb->buf = nbuf; xb->ptr = xb->buf + cnt; @@ -229,7 +229,7 @@ static inline char *agxbdisown(agxbuf *xb) { // terminate the existing string agxbputc(xb, '\0'); - if (!xb->dyna) { + if (xb->stack_allocated) { // the buffer is not dynamically allocated, so we need to copy its contents // to heap memory @@ -245,7 +245,7 @@ static inline char *agxbdisown(agxbuf *xb) { // reset xb to a state where it is usable xb->buf = xb->ptr = xb->eptr = NULL; - xb->dyna = 1; + xb->stack_allocated = 0; return buf; }