1 | #ifndef DYNBUF_H__ |
1 | #ifndef DYNBUF_H__ |
2 | #define DYNBUF_H__ |
2 | #define DYNBUF_H__ |
3 | |
3 | |
4 | #include <cstring> |
4 | #include <cstring> |
5 | #include <cassert> |
5 | #include <cassert> |
|
|
6 | |
|
|
7 | #include "shstr.h" |
6 | |
8 | |
7 | // this is a "buffer" that can grow fast |
9 | // this is a "buffer" that can grow fast |
8 | // and is still somewhat space-efficient. |
10 | // and is still somewhat space-efficient. |
9 | // unlike obstacks or other data structures, |
11 | // unlike obstacks or other data structures, |
10 | // it never moves data around. basically, |
12 | // it never moves data around. basically, |
11 | // this is a fast strstream without the overhead. |
13 | // this is a fast strstream without the overhead. |
12 | |
14 | |
13 | class dynbuf |
15 | struct dynbuf |
14 | { |
16 | { |
|
|
17 | protected: |
15 | struct chunk |
18 | struct chunk |
16 | { |
19 | { |
17 | chunk *next; |
20 | chunk *next; |
|
|
21 | int alloc; |
18 | int size; |
22 | int size; |
19 | char data[0]; |
23 | char data[0]; |
20 | }; |
24 | }; |
21 | |
25 | |
22 | char *ptr; |
26 | char *ptr; |
… | |
… | |
74 | void add (const char *s) |
78 | void add (const char *s) |
75 | { |
79 | { |
76 | add (s, strlen (s)); |
80 | add (s, strlen (s)); |
77 | } |
81 | } |
78 | |
82 | |
79 | static const int max_sint32_size = 11; |
83 | void add (const shstr &s) |
80 | static const int max_sint64_size = 20; |
84 | { |
81 | |
85 | add (s.s, s.length ()); |
82 | void add (sint32 i); |
86 | } |
83 | void add (sint64 i); |
|
|
84 | |
87 | |
85 | //TODO |
88 | //TODO |
86 | //void add_destructive (dynbuf &buf); |
89 | //void add_destructive (dynbuf &buf); |
87 | |
90 | |
88 | dynbuf &operator << (char c) { add (c); return *this; } |
91 | dynbuf &operator << (char c) { add (c); return *this; } |
89 | dynbuf &operator << (unsigned char c) { return *this << char (c); } |
92 | dynbuf &operator << (unsigned char c) { return *this << char (c); } |
90 | dynbuf &operator << (const char *s) { add (s); return *this; } |
93 | dynbuf &operator << (const char *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, ...); |
91 | }; |
114 | }; |
92 | |
115 | |
93 | #endif |
116 | #endif |