From 225df20f9ed5b029c1e4c2b25b023d2a4563473a Mon Sep 17 00:00:00 2001 From: Matthew Fernandez Date: Sat, 10 Sep 2022 13:04:34 -0700 Subject: [PATCH] cgraph agxbuf: abstract calculation of the capacity of a backing store This looks a bit like overkill. However, an upcoming commit will make how we determine this capacity conditional. Gitlab: #2302 --- lib/cgraph/agxbuf.h | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/lib/cgraph/agxbuf.h b/lib/cgraph/agxbuf.h index fa1d2b6a9..6ff51f5da 100644 --- a/lib/cgraph/agxbuf.h +++ b/lib/cgraph/agxbuf.h @@ -64,6 +64,15 @@ static inline void agxbfree(agxbuf *xb) { */ static inline size_t agxblen(const agxbuf *xb) { return xb->size; } +/// get the capacity of the backing memory of a buffer +/// +/// In contrast to \p agxblen, this is the total number of usable bytes in the +/// backing store, not the total number of currently stored bytes. +/// +/// \param xb Buffer to operate on +/// \return Number of usable bytes in the backing store +static inline size_t agxbsizeof(const agxbuf *xb) { return xb->capacity; } + /* agxbpop: * Removes last character added, if any. */ @@ -87,7 +96,7 @@ static inline void agxbmore(agxbuf *xb, size_t ssz) { size_t nsize = 0; // new buffer size char *nbuf; // new buffer - size = xb->capacity; + size = agxbsizeof(xb); nsize = size == 0 ? BUFSIZ : (2 * size); if (size + ssz > nsize) nsize = size + ssz; @@ -137,7 +146,7 @@ static inline PRINTF_LIKE(2, 3) int agxbprint(agxbuf *xb, const char *fmt, // do we need to expand the buffer? { - size_t unused_space = xb->capacity - xb->size; + size_t unused_space = agxbsizeof(xb) - agxblen(xb); if (unused_space < size) { size_t extra = size - unused_space; agxbmore(xb, extra); @@ -164,7 +173,7 @@ static inline size_t agxbput_n(agxbuf *xb, const char *s, size_t ssz) { if (ssz == 0) { return 0; } - if (ssz > xb->capacity - xb->size) + if (ssz > agxbsizeof(xb) - agxblen(xb)) agxbmore(xb, ssz); memcpy(&xb->buf[xb->size], s, ssz); xb->size += ssz; @@ -185,7 +194,7 @@ static inline size_t agxbput(agxbuf *xb, const char *s) { * int agxbputc(agxbuf*, char) */ static inline int agxbputc(agxbuf *xb, char c) { - if (xb->size >= xb->capacity) { + if (agxblen(xb) >= agxbsizeof(xb)) { agxbmore(xb, 1); } xb->buf[xb->size] = c; -- 2.40.0