]> granicus.if.org Git - graphviz/commitdiff
cgraph agxbuf: make inline strings the default
authorMatthew Fernandez <matthew.fernandez@gmail.com>
Sat, 10 Sep 2022 21:32:15 +0000 (14:32 -0700)
committerMatthew Fernandez <matthew.fernandez@gmail.com>
Sat, 10 Sep 2022 22:28:25 +0000 (15:28 -0700)
This change switches both `agxbinit` and zero-initialization (`agxbuf xb = {0}`)
to result in a buffer with `AGXBUF_INLINE` set. This means string data is
written inline until it becomes too large to store within the `agxbuf` struct
itself, when it is then relocated to the heap.

This is an optimization. Short dynamic strings can now be written completely
without heap allocation. For example, stringifying a number
(`agxbprint(&xb, "%d", i)`) will fit fully within the inline buffer.

lib/cgraph/agxbuf.h

index c7b89acd8e2496b8e85ac1e5ca4551ead035dd1a..77348a4f5b0499738f401944d3717e8e97cb1c5c 100644 (file)
@@ -19,9 +19,9 @@
 
 /// a description of where a buffer is located
 typedef enum {
-  AGXBUF_ON_HEAP = 0, ///< buffer is dynamically allocated
-  AGXBUF_ON_STACK,    ///< buffer is statically allocated
-  AGXBUF_INLINE       ///< buffer is _within_ the containing agxbuf
+  AGXBUF_INLINE = 0, ///< buffer is _within_ the containing agxbuf
+  AGXBUF_ON_HEAP,    ///< buffer is dynamically allocated
+  AGXBUF_ON_STACK    ///< buffer is statically allocated
 } agxbuf_loc_t;
 
 /// extensible buffer
@@ -64,11 +64,9 @@ static inline void agxbinit(agxbuf *xb, unsigned int hint, char *init) {
     xb->buf = init;
     xb->located = AGXBUF_ON_STACK;
   } else {
-    if (hint == 0) {
-      hint = BUFSIZ;
-    }
-    xb->located = AGXBUF_ON_HEAP;
-    xb->buf = (char *)gv_calloc(hint, sizeof(char));
+    memset(xb->store, 0, sizeof(xb->store));
+    xb->located = AGXBUF_INLINE;
+    return;
   }
   xb->eptr = xb->buf + hint;
   xb->ptr = xb->buf;
@@ -362,8 +360,7 @@ static inline char *agxbdisown(agxbuf *xb) {
   }
 
   // reset xb to a state where it is usable
-  xb->buf = xb->ptr = xb->eptr = NULL;
-  xb->located = AGXBUF_ON_HEAP;
+  agxbinit(xb, 0, NULL);
 
   return buf;
 }