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