]> mj.ucw.cz Git - libucw.git/commitdiff
added a simple source-code for resizable buffers, I am going to need it at
authorRobert Spalek <robert@ucw.cz>
Mon, 28 Jun 2004 09:30:52 +0000 (09:30 +0000)
committerRobert Spalek <robert@ucw.cz>
Mon, 28 Jun 2004 09:30:52 +0000 (09:30 +0000)
3 places, so let us separate it

lib/gbuf.h [new file with mode: 0644]

diff --git a/lib/gbuf.h b/lib/gbuf.h
new file mode 100644 (file)
index 0000000..c56cb79
--- /dev/null
@@ -0,0 +1,58 @@
+/*
+ *     A simple growing buffer
+ *
+ *     (c) 2004, Robert Spalek <robert@ucw.cz>
+ *
+ *     Define the following macros:
+ *
+ *     GBUF_TYPE       data type of records stored in the buffer
+ *     GBUF_PREFIX(x)  add a name prefix to all global symbols
+ */
+
+#define        BUF_T   GBUF_PREFIX(t)
+
+typedef struct
+{
+  uns len;
+  GBUF_TYPE *ptr;
+}
+BUF_T;
+
+static inline void
+GBUF_PREFIX(init)(BUF_T *b)
+{
+  b->ptr = NULL;
+  b->len = 0;
+}
+
+static inline void
+GBUF_PREFIX(done)(BUF_T *b)
+{
+  if (b->ptr)
+    xfree(b->ptr);
+  b->ptr = NULL;
+  b->len = 0;
+}
+
+static inline void
+GBUF_PREFIX(realloc)(BUF_T *b, uns len)
+{
+  b->len = len;
+  if (b->ptr)
+    b->ptr = xrealloc(b->ptr, len * sizeof(GBUF_TYPE));
+  else
+    b->ptr = xmalloc(len * sizeof(GBUF_TYPE));
+}
+
+static inline void
+GBUF_PREFIX(grow)(BUF_T *b, uns len)
+{
+  if (len <= b->len)
+    return;
+  if (len < 2*b->len)                  // to ensure logarithmic cost
+    len = 2*b->len;
+  GBUF_PREFIX(realloc)(b, len);
+}
+
+#undef GBUF_TYPE
+#undef GBUF_PREFIX