]> granicus.if.org Git - graphviz/commitdiff
cgraph: rename 'agxbuf.dyna' and flip its polarity
authorMatthew Fernandez <matthew.fernandez@gmail.com>
Sat, 30 Jul 2022 00:24:05 +0000 (17:24 -0700)
committerMatthew Fernandez <matthew.fernandez@gmail.com>
Mon, 8 Aug 2022 14:59:41 +0000 (07:59 -0700)
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.

lib/cgraph/agxbuf.h

index 7412114bdb11ac961684b7cebd0c9a549efac771..9272f510f80a511d0e605732a35f3e9a1ebf1cc2 100644 (file)
@@ -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:
 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;
 }