Split code into modules, handle USR1, minor fixes.
[reservoir_sample] / buf.h
diff --git a/buf.h b/buf.h
new file mode 100644 (file)
index 0000000..a47f3ba
--- /dev/null
+++ b/buf.h
@@ -0,0 +1,73 @@
+#ifndef BUF_H_B87OZOFU
+#define BUF_H_B87OZOFU
+
+#include <stdlib.h>
+
+#ifndef NDEBUG
+#include "notify.h"
+#endif /* NDEBUG */
+
+/* A simple sliding-window byte buffer. */
+
+typedef struct buf_ {
+       size_t buf_sz;
+       size_t buf_start;
+       size_t buf_used;
+       unsigned char buf[];
+} *buf_t;
+#define BUF_ROOM(__b__) ( (__b__)->buf_sz - ( (__b__)->buf_start + (__b__)->buf_used ) )
+
+#ifndef NDEBUG
+#define D_BUF(__pre__,__b__,...) do {\
+       if ( (__b__) == NULL )\
+               NOTIFY_DEBUG(__pre__ "buf:%p", ## __VA_ARGS__, (__b__));\
+       else {\
+               NOTIFY_DEBUG(__pre__ "buf:%p sz:%zu start:%zu used:%zu free:%zu '%.*s'",\
+                            ## __VA_ARGS__,\
+                            (__b__),\
+                            (__b__)->buf_sz,\
+                            (__b__)->buf_start,\
+                            (__b__)->buf_used,\
+                            BUF_ROOM((__b__)),\
+                            (int)(__b__)->buf_used, (__b__)->buf + (__b__)->buf_start);\
+               assert( (__b__)->buf_sz >= (__b__)->buf_start + (__b__)->buf_used );\
+       }\
+} while (0)
+#else /* NDEBUG */
+#define D_BUF(...)
+#endif /* NDEBUG */
+
+/*  buf_new
+       Allocate and return a new buf_t capable of holding #sz bytes.
+*/
+buf_t buf_new(size_t sz);
+
+/*  buf_rebase
+       Reclaim any free space from the start of #buf, preserving active content.
+*/
+void buf_rebase(buf_t buf);
+
+/* buf_makeroom
+               Assures that the buf pointed to by #pbuf has at space to hold #roomfor more
+       bytes.
+*/
+int buf_makeroom(buf_t *pbuf, size_t roomfor);
+
+/*  buf_range_dup_or_append
+               Starting at the #src_offset byte of #src, appends the following #n bytes to
+       the buffer pointed to by #dstp, which will be re/allocated if needed.
+*/
+int buf_range_dup_or_append(buf_t src, size_t src_offset, size_t n, buf_t *pdst);
+
+/*  buf_flense
+               Starting after #src_offset characters, scan through the buffer pointed
+       to by #psrc, stopping at the first byte matching #delimiter, whereupon, if
+       #pdst is not NULL, all the bytes previous to #delimiter are appended onto
+       the buffer pointed to by *#pdst.  The buffer pointed to by #psrc is then
+       trimmed to only contain the bytes following #delimiter.  The delimiter byte
+       is discarded.
+               Returns the number of characters flensed from #src.
+*/
+ssize_t buf_flense(buf_t *psrc, size_t src_offset, int delimiter, buf_t *pdst);
+
+#endif /* BUF_H_B87OZOFU */