1 | #ifndef _SINGULAR_LIBTHREAD_BYTEBUFFER_H |
---|
2 | #define _SINGULAR_LIBTHREAD_BYTEBUFFER_H |
---|
3 | |
---|
4 | #include <cstddef> |
---|
5 | #include <cstdlib> |
---|
6 | #include <cstring> |
---|
7 | |
---|
8 | namespace LibThread { |
---|
9 | |
---|
10 | using namespace std; |
---|
11 | |
---|
12 | char *allocate_space (size_t n); |
---|
13 | void free_space(size_t n, char *p); |
---|
14 | |
---|
15 | class ByteBuf { |
---|
16 | private: |
---|
17 | size_t count; |
---|
18 | size_t cap; |
---|
19 | size_t pos; |
---|
20 | char *buf; |
---|
21 | public: |
---|
22 | ByteBuf() : pos(0), count(0), cap(0) { } |
---|
23 | ByteBuf(const ByteBuf &other) : |
---|
24 | count(other.count), cap(other.cap), pos(0) |
---|
25 | { |
---|
26 | buf = allocate_space(cap); |
---|
27 | memcpy(buf, other.buf, count); |
---|
28 | } |
---|
29 | ByteBuf &operator=(const ByteBuf &other) { |
---|
30 | count = other.count; |
---|
31 | cap = other.cap; |
---|
32 | pos = 0; |
---|
33 | buf = allocate_space(cap); |
---|
34 | memcpy(buf, other.buf, count); |
---|
35 | } |
---|
36 | ~ByteBuf() { |
---|
37 | free_space(cap, buf); |
---|
38 | } |
---|
39 | size_t size() { return count; } |
---|
40 | void write_bytes(char *p, size_t n) { |
---|
41 | if (pos + n >= cap) { |
---|
42 | char *newbuf = allocate_space(2 * cap); |
---|
43 | memcpy(newbuf, buf, count); |
---|
44 | free_space(cap, buf); |
---|
45 | cap *= 2; |
---|
46 | } |
---|
47 | memcpy(buf+pos, p, n); |
---|
48 | pos += n; |
---|
49 | if (pos >= count) |
---|
50 | count = pos; |
---|
51 | } |
---|
52 | void read_bytes(char *p, size_t n) { |
---|
53 | memcpy(p, buf+pos, n); |
---|
54 | pos += n; |
---|
55 | } |
---|
56 | template <typename T> |
---|
57 | void write(T &value) { |
---|
58 | write_bytes((char *)&value, sizeof(T)); |
---|
59 | } |
---|
60 | template <typename T> |
---|
61 | void read(T &value) { |
---|
62 | read_bytes((char *)&value, sizeof(T)); |
---|
63 | } |
---|
64 | void seek(size_t p) { |
---|
65 | pos = p; |
---|
66 | } |
---|
67 | }; |
---|
68 | |
---|
69 | } |
---|
70 | |
---|
71 | #endif // _SINGULAR_LIBTHREAD_BYTEBUFFER_H |
---|