forked from lksj/einstein-puzzle
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathbuffer.cpp
More file actions
124 lines (94 loc) · 2.5 KB
/
buffer.cpp
File metadata and controls
124 lines (94 loc) · 2.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
// This file is part of Einstein Puzzle
// Einstein Puzzle
// Copyright (C) 2003-2005 Flowix Games
// Einstein Puzzle is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
// Einstein Puzzle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
#include "buffer.h"
#include "exceptions.h"
#include "unicode.h"
#include <cstring>
Buffer::Buffer(int sz, int alloc)
: size(sz), allocated(alloc), data(nullptr), currentPos(0)
{
if (size > allocated)
allocated = size;
if (allocated < 1024)
allocated = 1024;
data = malloc(allocated);
if (! data)
throw Exception(L"Error allocating memory for Buffer");
}
Buffer::~Buffer()
{
free(data);
}
void Buffer::setSize(size_t sz)
{
if (sz > allocated) {
int newAl = allocated + sz + 1024;
void *d = realloc(data, newAl);
if (! d)
throw Exception(L"Error expanding buffer memory");
data = d;
allocated = newAl;
}
size = sz;
}
size_t Buffer::getSize()
{
return size;
}
size_t Buffer::getAllocated()
{
return allocated;
}
void* Buffer::getData()
{
return data;
}
void Buffer::gotoPos(int offset)
{
currentPos = offset;
}
size_t Buffer::putData(const unsigned char *d, size_t length)
{
if (size < currentPos + length)
setSize(currentPos + length);
memcpy((unsigned char*)data + currentPos, d, length);
currentPos += length;
return length;
}
size_t Buffer::putInteger(int v)
{
unsigned char b[4];
for (unsigned char& i : b)
{
const int ib = v & 0xFF;
v = v >> 8;
i = ib;
}
return putData(b, 4);
}
size_t Buffer::putUtf8(const std::wstring &string)
{
std::string s(toUtf8(string));
putInteger(s.length());
putData((const unsigned char*)s.c_str(), s.length());
return 4 + s.length();
}
size_t Buffer::putByte(unsigned char value)
{
if (size < (size_t)currentPos + 1)
setSize(currentPos + 1);
((unsigned char*)data)[currentPos] = value;
currentPos++;
return 1;
}