diff options
author | Treeki <treeki@gmail.com> | 2014-01-16 20:19:00 +0100 |
---|---|---|
committer | Treeki <treeki@gmail.com> | 2014-01-16 20:19:00 +0100 |
commit | a47ea91881c3cca4c8e3bdd3ea13d09886cafa94 (patch) | |
tree | 91e9e6ebcbe08044f9594a577b9ad83b186d7868 /buffer.h | |
download | bounce4-a47ea91881c3cca4c8e3bdd3ea13d09886cafa94.tar.gz bounce4-a47ea91881c3cca4c8e3bdd3ea13d09886cafa94.zip |
initial commit of stuff
Diffstat (limited to '')
-rw-r--r-- | buffer.h | 103 |
1 files changed, 103 insertions, 0 deletions
diff --git a/buffer.h b/buffer.h new file mode 100644 index 0000000..ef6d027 --- /dev/null +++ b/buffer.h @@ -0,0 +1,103 @@ +#ifndef BUFFER_H +#define BUFFER_H + +#include <string.h> +#include <stdint.h> + +class Buffer { +private: + char *m_data; + bool m_freeBuffer; + int m_size; + int m_capacity; + char m_preAllocBuffer[0x200]; + +public: + Buffer() { + m_data = m_preAllocBuffer; + m_freeBuffer = false; + m_size = 0; + m_capacity = sizeof(m_preAllocBuffer); + } + + ~Buffer() { + if ((m_data != NULL) && m_freeBuffer) { + delete[] m_data; + m_data = NULL; + } + } + + char *data() const { return m_data; } + int size() const { return m_size; } + int capacity() const { return m_capacity; } + + void setCapacity(int capacity) { + if (capacity == m_capacity) + return; + + // Trim the size down if it's too big to fit + if (m_size > capacity) + m_size = capacity; + + char *newBuf = new char[capacity]; + + if (m_data != NULL) { + memcpy(newBuf, m_data, m_size); + if (m_freeBuffer) + delete[] m_data; + } + + m_data = newBuf; + m_capacity = capacity; + m_freeBuffer = true; + } + + void clear() { + m_size = 0; + } + void append(const char *data, int size) { + if (size <= 0) + return; + + int requiredSize = m_size + size; + if (requiredSize > m_capacity) + setCapacity(requiredSize + 0x100); + + memcpy(&m_data[m_size], data, size); + m_size += size; + } + void resize(int size) { + if (size > m_capacity) + setCapacity(size + 0x100); + m_size = size; + } + + void trimFromStart(int amount) { + if (amount <= 0) + return; + if (amount >= m_size) { + clear(); + return; + } + + memmove(m_data, &m_data[amount], m_size - amount); + m_size -= amount; + } + + + void writeU32(uint32_t v) { append((const char *)&v, 4); } + void writeU16(uint32_t v) { append((const char *)&v, 2); } + void writeU8(uint32_t v) { append((const char *)&v, 1); } + void writeS32(uint32_t v) { append((const char *)&v, 4); } + void writeS16(uint32_t v) { append((const char *)&v, 2); } + void writeS8(uint32_t v) { append((const char *)&v, 1); } + + void writeStr(const char *data, int size = -1) { + if (size == -1) + size = strlen(data); + writeU32(size); + append(data, size); + } +}; + +#endif /* BUFFER_H */ |