1 |
#ifndef DYNBUF_H__ |
2 |
#define DYNBUF_H__ |
3 |
|
4 |
#include <cstring> |
5 |
#include <cassert> |
6 |
|
7 |
// this is a "buffer" that can grow fast |
8 |
// and is still somewhat space-efficient. |
9 |
// unlike obstacks or other data structures, |
10 |
// it never moves data around. basically, |
11 |
// this is a fast strstream without the overhead. |
12 |
|
13 |
class dynbuf |
14 |
{ |
15 |
struct chunk |
16 |
{ |
17 |
chunk *next; |
18 |
int size; |
19 |
char data[0]; |
20 |
}; |
21 |
|
22 |
char *ptr; |
23 |
int room; |
24 |
int ext; |
25 |
int _size; |
26 |
|
27 |
chunk *first, *last; |
28 |
|
29 |
void _reserve (int size); |
30 |
void clear (); |
31 |
void finish (); |
32 |
|
33 |
public: |
34 |
|
35 |
dynbuf (int initial = 128, int extend = 128); |
36 |
~dynbuf (); |
37 |
|
38 |
int size () { return _size + (ptr - last->data); } |
39 |
|
40 |
void linearise (void *data); |
41 |
char *linearise (); |
42 |
|
43 |
char *force (int size) |
44 |
{ |
45 |
if (room < size) |
46 |
_reserve (size); |
47 |
|
48 |
return ptr; |
49 |
} |
50 |
|
51 |
char *alloc (int size) |
52 |
{ |
53 |
char *res = force (size); |
54 |
|
55 |
room -= size; |
56 |
ptr += size; |
57 |
|
58 |
return res; |
59 |
} |
60 |
|
61 |
void fadd (char c) { --room; *ptr++ = c; } |
62 |
void fadd (unsigned char c) { fadd (char (c));; } |
63 |
|
64 |
void add (const void *p, int len) |
65 |
{ |
66 |
memcpy (alloc (len), p, len); |
67 |
} |
68 |
|
69 |
void add (char c) |
70 |
{ |
71 |
if (room < 1) |
72 |
_reserve (1); |
73 |
|
74 |
room--; |
75 |
*ptr++ = c; |
76 |
} |
77 |
|
78 |
void add (const char *s) |
79 |
{ |
80 |
add (s, strlen (s)); |
81 |
} |
82 |
|
83 |
static const int max_sint32_size = 11; |
84 |
static const int max_sint64_size = 20; |
85 |
|
86 |
void add (sint32 i); |
87 |
void add (sint64 i); |
88 |
|
89 |
//TODO |
90 |
//void add_destructive (dynbuf &buf); |
91 |
|
92 |
dynbuf &operator << (char c) { add (c); return *this; } |
93 |
dynbuf &operator << (unsigned char c) { return *this << char (c); } |
94 |
dynbuf &operator << (const char *s) { add (s); return *this; } |
95 |
}; |
96 |
|
97 |
#endif |