gcc config
[prop.git] / prop-src / textbuf.cc
blobadfa6a248f8700013a01c399eb055e24a1564e4b
1 ///////////////////////////////////////////////////////////////////////////////
2 //
3 // Text buffer class
4 //
5 ///////////////////////////////////////////////////////////////////////////////
6 #include <stdlib.h>
7 #include <string.h>
8 #include "textbuf.h"
10 ///////////////////////////////////////////////////////////////////////////////
12 // Constructor and destructor
14 ///////////////////////////////////////////////////////////////////////////////
15 TextBuffer::TextBuffer() : buffer(0), limit(0), cursor(0) {}
16 TextBuffer::~TextBuffer() { if (buffer) free (buffer); }
18 ///////////////////////////////////////////////////////////////////////////////
20 // Transfer text from one buffer to another.
22 ///////////////////////////////////////////////////////////////////////////////
23 TextBuffer::TextBuffer (const TextBuffer& b)
24 { TextBuffer * B = (TextBuffer *)&b;
25 buffer = B->buffer;
26 limit = B->limit;
27 cursor = B->cursor;
28 B->buffer = 0;
29 B->limit = 0;
30 B->cursor = 0;
33 ///////////////////////////////////////////////////////////////////////////////
35 // Transfer text from one buffer to another.
37 ///////////////////////////////////////////////////////////////////////////////
38 void TextBuffer::operator = (const TextBuffer& b)
39 { if (&b == this) return;
40 if (buffer) free (buffer); // kill self
41 TextBuffer * B = (TextBuffer *)&b;
42 buffer = B->buffer;
43 limit = B->limit;
44 cursor = B->cursor;
45 B->buffer = 0;
46 B->limit = 0;
47 B->cursor = 0;
50 ///////////////////////////////////////////////////////////////////////////////
52 // Emit a string
54 ///////////////////////////////////////////////////////////////////////////////
55 void TextBuffer::emit (const char * text, long len)
56 { if (len < 0) len = strlen(text);
57 if (cursor + len >= limit) grow(len);
58 memcpy(cursor, text, len);
59 cursor += len;
62 ///////////////////////////////////////////////////////////////////////////////
64 // Emit a character
66 ///////////////////////////////////////////////////////////////////////////////
67 void TextBuffer::emit (char c)
68 { if (cursor + 1 >= limit) grow(256);
69 *cursor++ = c;
72 ///////////////////////////////////////////////////////////////////////////////
74 // Method to expand the buffer
76 ///////////////////////////////////////////////////////////////////////////////
77 void TextBuffer::grow (size_t growth)
78 { size_t old_size = cursor - buffer;
79 size_t new_size = (limit - buffer) * 2 + growth;
80 if (buffer)
81 buffer = (char *)realloc(buffer, new_size);
82 else
83 buffer = (char *)malloc(new_size);
84 cursor = buffer + old_size;
85 limit = buffer + new_size;