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; |
18 | int size; |
21 | int size; |
19 | char data[0]; |
22 | char data[0]; |
… | |
… | |
74 | void add (const char *s) |
77 | void add (const char *s) |
75 | { |
78 | { |
76 | add (s, strlen (s)); |
79 | add (s, strlen (s)); |
77 | } |
80 | } |
78 | |
81 | |
79 | static const int max_sint32_size = 11; |
82 | void add (const shstr &s) |
80 | static const int max_sint64_size = 20; |
83 | { |
81 | |
84 | add (s.s, s.length ()); |
82 | void add (sint32 i); |
85 | } |
83 | void add (sint64 i); |
|
|
84 | |
86 | |
85 | //TODO |
87 | //TODO |
86 | //void add_destructive (dynbuf &buf); |
88 | //void add_destructive (dynbuf &buf); |
87 | |
89 | |
88 | dynbuf &operator << (char c) { add (c); return *this; } |
90 | dynbuf &operator << (char c) { add (c); return *this; } |
89 | dynbuf &operator << (unsigned char c) { return *this << char (c); } |
91 | dynbuf &operator << (unsigned char c) { return *this << char (c); } |
90 | dynbuf &operator << (const char *s) { add (s); return *this; } |
92 | dynbuf &operator << (const char *s) { add (s); return *this; } |
|
|
93 | dynbuf &operator << (const std::string &s) { add (s.data(), s.size ()); return *this; } |
|
|
94 | |
|
|
95 | operator std::string (); |
|
|
96 | }; |
|
|
97 | |
|
|
98 | struct dynbuf_text : dynbuf |
|
|
99 | { |
|
|
100 | dynbuf_text (int initial = 4096, int extend = 16384) |
|
|
101 | : dynbuf (initial, extend) |
|
|
102 | { } |
|
|
103 | |
|
|
104 | using dynbuf::add; |
|
|
105 | |
|
|
106 | static const int max_sint32_size = 11; |
|
|
107 | static const int max_sint64_size = 20; |
|
|
108 | |
|
|
109 | void add (sint32 i); |
|
|
110 | void add (sint64 i); |
|
|
111 | |
|
|
112 | void printf (const char *format, ...); |
91 | }; |
113 | }; |
92 | |
114 | |
93 | #endif |
115 | #endif |