ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/deliantra/server/server/dynbuf.C
Revision: 1.4
Committed: Sat Sep 2 16:37:58 2006 UTC (17 years, 9 months ago) by root
Content type: text/plain
Branch: MAIN
Changes since 1.3: +23 -14 lines
Log Message:
never, ever optimise if you don't need to

File Contents

# Content
1 #define __STDC_CONSTANT_MACROS
2 #include <stdint.h>
3
4 #ifndef UINT64_C
5 # error missing c99 support, define UINT64_C yourself
6 # define UINT64_C(c) c ## LL
7 #endif
8
9 #include "global.h"
10
11 #include <cstdio>
12
13 dynbuf::dynbuf (int initial, int extend)
14 {
15 _size = 0;
16 ext = extend;
17 first = last = (chunk *)new char [sizeof (chunk) + initial];
18 first->next = 0;
19 room = initial;
20 ptr = first->data;
21 }
22
23 dynbuf::~dynbuf ()
24 {
25 clear ();
26 }
27
28 void dynbuf::clear ()
29 {
30 while (first)
31 {
32 chunk *next = first->next;
33 delete [] (char *)first;
34 first = next;
35 }
36 }
37
38 void dynbuf::finish ()
39 {
40 // finalise current chunk
41 _size += last->size = ptr - last->data;
42 }
43
44 void dynbuf::_reserve (int size)
45 {
46 finish ();
47
48 do
49 {
50 ext += ext >> 1;
51 ext = (ext + 15) & ~15;
52 }
53 while (ext < size);
54
55 chunk *add = (chunk *)new char [sizeof (chunk) + ext];
56 add->next = 0;
57
58 last->next = add;
59 last = add;
60
61 room = ext;
62 ptr = last->data;
63 }
64
65 void dynbuf::linearise (void *data)
66 {
67 char *p = (char *)data;
68
69 last->size = ptr - last->data;
70
71 for (chunk *c = first; c; c = c->next)
72 {
73 memcpy (p, c->data, c->size);
74 p += c->size;
75 }
76 }
77
78 char *dynbuf::linearise ()
79 {
80 if (first->next)
81 {
82 finish ();
83
84 chunk *add = (chunk *)new char [sizeof (chunk) + _size];
85
86 add->next = 0;
87 linearise ((void *)add->data);
88 clear ();
89
90 first = last = add;
91 ptr = last->data + _size;
92 _size = 0;
93 room = 0;
94 }
95
96 return first->data;
97 }
98
99 void dynbuf::add (sint32 i)
100 {
101 char buf [max_sint32_size];
102 char *p = buf + sizeof (buf);
103 char neg;
104
105 uint32 val;
106
107 if (i < 0)
108 {
109 neg = '-';
110 val = -i;
111 }
112 else
113 {
114 neg = 0;
115 val = i;
116 }
117
118 do
119 {
120 uint32 div = val / 10;
121 *--p = '0' + char (val - div * 10);
122 val = div;
123 }
124 while (val);
125
126 if (neg)
127 *--p = neg;
128
129 add ((void *)p, buf + sizeof (buf) - p);
130 }
131
132 void dynbuf::add (sint64 i)
133 {
134 if (i > -10000000 && i < 10000000)
135 {
136 add (sint32 (i));
137 return;
138 }
139
140 char buf [max_sint64_size];
141 char *p = buf + sizeof (buf);
142 char neg;
143
144 uint64 val;
145
146 if (i < 0)
147 {
148 neg = '-';
149 val = -i;
150 }
151 else
152 {
153 neg = 0;
154 val = i;
155 }
156
157 do
158 {
159 uint64 div = val / 10;
160 *--p = '0' + char (val - div * 10);
161 val = div;
162 }
163 while (val);
164
165 if (neg)
166 *--p = neg;
167
168 add ((void *)p, buf + sizeof (buf) - p);
169 }
170