a47f3ba154d38ec7958fe0f70905f19fb91c8257
[reservoir_sample] / buf.h
1 #ifndef BUF_H_B87OZOFU
2 #define BUF_H_B87OZOFU
3
4 #include <stdlib.h>
5
6 #ifndef NDEBUG
7 #include "notify.h"
8 #endif /* NDEBUG */
9
10 /* A simple sliding-window byte buffer. */
11
12 typedef struct buf_ {
13 size_t buf_sz;
14 size_t buf_start;
15 size_t buf_used;
16 unsigned char buf[];
17 } *buf_t;
18 #define BUF_ROOM(__b__) ( (__b__)->buf_sz - ( (__b__)->buf_start + (__b__)->buf_used ) )
19
20 #ifndef NDEBUG
21 #define D_BUF(__pre__,__b__,...) do {\
22 if ( (__b__) == NULL )\
23 NOTIFY_DEBUG(__pre__ "buf:%p", ## __VA_ARGS__, (__b__));\
24 else {\
25 NOTIFY_DEBUG(__pre__ "buf:%p sz:%zu start:%zu used:%zu free:%zu '%.*s'",\
26 ## __VA_ARGS__,\
27 (__b__),\
28 (__b__)->buf_sz,\
29 (__b__)->buf_start,\
30 (__b__)->buf_used,\
31 BUF_ROOM((__b__)),\
32 (int)(__b__)->buf_used, (__b__)->buf + (__b__)->buf_start);\
33 assert( (__b__)->buf_sz >= (__b__)->buf_start + (__b__)->buf_used );\
34 }\
35 } while (0)
36 #else /* NDEBUG */
37 #define D_BUF(...)
38 #endif /* NDEBUG */
39
40 /* buf_new
41 Allocate and return a new buf_t capable of holding #sz bytes.
42 */
43 buf_t buf_new(size_t sz);
44
45 /* buf_rebase
46 Reclaim any free space from the start of #buf, preserving active content.
47 */
48 void buf_rebase(buf_t buf);
49
50 /* buf_makeroom
51 Assures that the buf pointed to by #pbuf has at space to hold #roomfor more
52 bytes.
53 */
54 int buf_makeroom(buf_t *pbuf, size_t roomfor);
55
56 /* buf_range_dup_or_append
57 Starting at the #src_offset byte of #src, appends the following #n bytes to
58 the buffer pointed to by #dstp, which will be re/allocated if needed.
59 */
60 int buf_range_dup_or_append(buf_t src, size_t src_offset, size_t n, buf_t *pdst);
61
62 /* buf_flense
63 Starting after #src_offset characters, scan through the buffer pointed
64 to by #psrc, stopping at the first byte matching #delimiter, whereupon, if
65 #pdst is not NULL, all the bytes previous to #delimiter are appended onto
66 the buffer pointed to by *#pdst. The buffer pointed to by #psrc is then
67 trimmed to only contain the bytes following #delimiter. The delimiter byte
68 is discarded.
69 Returns the number of characters flensed from #src.
70 */
71 ssize_t buf_flense(buf_t *psrc, size_t src_offset, int delimiter, buf_t *pdst);
72
73 #endif /* BUF_H_B87OZOFU */