buf.h (934B)
1 #ifndef KIT_BUF_H 2 #define KIT_BUF_H 3 4 #include "core/core.h" 5 #include "core/heap.h" 6 7 #define BUF_CHUNK 65536 8 9 typedef struct BufChunk BufChunk; 10 struct BufChunk { 11 BufChunk* next; 12 u32 used; 13 u32 cap; /* usable size of data[] */ 14 u8 data[]; 15 }; 16 17 typedef struct Buf { 18 Heap* heap; 19 BufChunk* head; 20 BufChunk* tail; 21 u32 total; /* sum of used across all chunks */ 22 } Buf; 23 24 void buf_init(Buf*, Heap*); 25 void buf_fini(Buf*); 26 27 void buf_write(Buf*, const void* data, size_t n); 28 u8* buf_reserve(Buf*, 29 size_t n); /* contiguous; spills to a fresh chunk if needed */ 30 u32 buf_pos(const Buf*); 31 void buf_patch(Buf*, u32 ofs, const void* data, 32 size_t n); /* must lie within written range */ 33 void buf_read(const Buf*, u32 ofs, void* dst, 34 size_t n); /* must lie within written range */ 35 36 void buf_flatten(const Buf*, 37 u8* dst); /* copy entire contents out, dst >= total bytes */ 38 39 #endif