summaryrefslogtreecommitdiff
path: root/src/serialization.cpp
blob: c324ca0fdb13ef38deb917ce93a595d8914305af (plain)
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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
/*
Minetest-c55
Copyright (C) 2010 celeron55, Perttu Ahola <celeron55@gmail.com>

This program 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.

This program 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, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/

#include "serialization.h"
#include "utility.h"
#ifdef _WIN32
	#define ZLIB_WINAPI
#endif
#include "zlib.h"

/* report a zlib or i/o error */
void zerr(int ret)
{   
    fputs("zerr: ", stderr);
    switch (ret) {
    case Z_ERRNO:
        if (ferror(stdin))
            fputs("error reading stdin\n", stderr);
        if (ferror(stdout))
            fputs("error writing stdout\n", stderr);
        break;
    case Z_STREAM_ERROR:
        fputs("invalid compression level\n", stderr);
        break;
    case Z_DATA_ERROR:
        fputs("invalid or incomplete deflate data\n", stderr);
        break;
    case Z_MEM_ERROR:
        fputs("out of memory\n", stderr);
        break;
    case Z_VERSION_ERROR:
        fputs("zlib version mismatch!\n", stderr);
		break;
	default:
		dstream<<"return value = "<<ret<<"\n";
    }
}

void compressZlib(SharedBuffer<u8> data, std::ostream &os)
{
	z_stream z;
	const s32 bufsize = 16384;
	//char input_buffer[bufsize];
	char output_buffer[bufsize];
	int input_i = 0;
	int status = 0;
	int ret;

	z.zalloc = Z_NULL;
	z.zfree = Z_NULL;
	z.opaque = Z_NULL;

	ret = deflateInit(&z, -1);
	if(ret != Z_OK)
		throw SerializationError("compressZlib: deflateInit failed");
	
	z.avail_in = 0;
	
	for(;;)
	{
		int flush = Z_NO_FLUSH;
		z.next_out = (Bytef*)output_buffer;
		z.avail_out = bufsize;

		if(z.avail_in == 0)
		{
			//z.next_in = (char*)&data[input_i];
			z.next_in = (Bytef*)&data[input_i];
			z.avail_in = data.getSize() - input_i;
			input_i += z.avail_in;
			if(input_i == (int)data.getSize())
				flush = Z_FINISH;
		}
		if(z.avail_in == 0)
			break;
		status = deflate(&z, flush);
		if(status == Z_NEED_DICT || status == Z_DATA_ERROR
				|| status == Z_MEM_ERROR)
		{
			zerr(status);
			throw SerializationError("compressZlib: deflate failed");
		}
		int count = bufsize - z.avail_out;
		if(count)
			os.write(output_buffer, count);
	}

	deflateEnd(&z);

}

void decompressZlib(std::istream &is, std::ostream &os)
{
	z_stream z;
	const s32 bufsize = 16384;
	char input_buffer[bufsize];
	char output_buffer[bufsize];
	int status = 0;
	int ret;
	int bytes_read = 0;
	int input_buffer_len = 0;

	z.zalloc = Z_NULL;
	z.zfree = Z_NULL;
	z.opaque = Z_NULL;

	ret = inflateInit(&z);
	if(ret != Z_OK)
		throw SerializationError("compressZlib: inflateInit failed");
	
	z.avail_in = 0;
	
	//dstream<<"initial fail="<<is.fail()<<" bad="<<is.bad()<<std::endl;

	for(;;)
	{
		z.next_out = (Bytef*)output_buffer;
		z.avail_out = bufsize;

		if(z.avail_in == 0)
		{
			z.next_in = (Bytef*)input_buffer;
			input_buffer_len = is.readsome(input_buffer, bufsize);
			z.avail_in = input_buffer_len;
			//dstream<<"read fail="<<is.fail()<<" bad="<<is.bad()<<std::endl;
		}
		if(z.avail_in == 0)
		{
			//dstream<<"z.avail_in == 0"<<std::endl;
			break;
		}
			
		//dstream<<"1 z.avail_in="<<z.avail_in<<std::endl;
		status = inflate(&z, Z_NO_FLUSH);
		//dstream<<"2 z.avail_in="<<z.avail_in<<std::endl;
		bytes_read += is.gcount() - z.avail_in;
		//dstream<<"bytes_read="<<bytes_read<<std::endl;

		if(status == Z_NEED_DICT || status == Z_DATA_ERROR
				|| status == Z_MEM_ERROR)
		{
			zerr(status);
			throw SerializationError("compressZlib: inflate failed");
		}
		int count = bufsize - z.avail_out;
		//dstream<<"count="<<count<<std::endl;
		if(count)
			os.write(output_buffer, count);
		if(status == Z_STREAM_END)
		{
			//dstream<<"Z_STREAM_END"<<std::endl;
			
			//dstream<<"z.avail_in="<<z.avail_in<<std::endl;
			//dstream<<"fail="<<is.fail()<<" bad="<<is.bad()<<std::endl;
			// Unget all the data that inflate didn't take
			for(u32 i=0; i < z.avail_in; i++)
			{
				is.unget();
				if(is.fail() || is.bad())
				{
					dstream<<"unget #"<<i<<" failed"<<std::endl;
					dstream<<"fail="<<is.fail()<<" bad="<<is.bad()<<std::endl;
					throw SerializationError("compressZlib: unget failed");
				}
			}
			
			break;
		}
	}

	inflateEnd(&z);
}

void compress(SharedBuffer<u8> data, std::ostream &os, u8 version)
{
	if(version >= 11)
	{
		compressZlib(data, os);
		return;
	}

	if(data.getSize() == 0)
		return;
	
	// Write length (u32)

	u8 tmp[4];
	writeU32(tmp, data.getSize());
	os.write((char*)tmp, 4);
	
	// We will be writing 8-bit pairs of more_count and byte
	u8 more_count = 0;
	u8 current_byte = data[0];
	for(u32 i=1; i<data.getSize(); i++)
	{
		if(
			data[i] != current_byte
			|| more_count == 255
		)
		{
			// write count and byte
			os.write((char*)&more_count, 1);
			os.write((char*)&current_byte, 1);
			more_count = 0;
			current_byte = data[i];
		}
		else
		{
			more_count++;
		}
	}
	// write count and byte
	os.write((char*)&more_count, 1);
	os.write((char*)&current_byte, 1);
}

void decompress(std::istream &is, std::ostream &os, u8 version)
{
	if(version >= 11)
	{
		decompressZlib(is, os);
		return;
	}

	// Read length (u32)

	u8 tmp[4];
	is.read((char*)tmp, 4);
	u32 len = readU32(tmp);
	
	// We will be reading 8-bit pairs of more_count and byte
	u32 count = 0;
	for(;;)
	{
		u8 more_count=0;
		u8 byte=0;

		is.read((char*)&more_count, 1);
		
		is.read((char*)&byte, 1);

		if(is.eof())
			throw SerializationError("decompress: stream ended halfway");

		for(s32 i=0; i<(u16)more_count+1; i++)
			os.write((char*)&byte, 1);

		count += (u16)more_count+1;

		if(count == len)
			break;
	}
}


ass="hl com">/* Now we are an inventory item containing the serialization string of an object that contains the serialization string of an inventory item. Fuck this. */ //assert(0); dstream<<__FUNCTION_NAME<<": WARNING: Ignoring ItemObj " <<"because an item-object should never be inside " <<"an object-item."<<std::endl; return NULL; } else { return NULL; } } /* Inventory */ InventoryList::InventoryList(std::string name, u32 size) { m_name = name; m_size = size; clearItems(); } InventoryList::~InventoryList() { for(u32 i=0; i<m_items.size(); i++) { if(m_items[i]) delete m_items[i]; } } void InventoryList::clearItems() { for(u32 i=0; i<m_items.size(); i++) { if(m_items[i]) delete m_items[i]; } m_items.clear(); for(u32 i=0; i<m_size; i++) { m_items.push_back(NULL); } } void InventoryList::serialize(std::ostream &os) { //os.imbue(std::locale("C")); for(u32 i=0; i<m_items.size(); i++) { InventoryItem *item = m_items[i]; if(item != NULL) { os<<"Item "; item->serialize(os); } else { os<<"Empty"; } os<<"\n"; } os<<"end\n"; } void InventoryList::deSerialize(std::istream &is) { //is.imbue(std::locale("C")); clearItems(); u32 item_i = 0; for(;;) { std::string line; std::getline(is, line, '\n'); std::istringstream iss(line); //iss.imbue(std::locale("C")); std::string name; std::getline(iss, name, ' '); if(name == "end") { break; } else if(name == "Item") { if(item_i > getSize() - 1) throw SerializationError("too many items"); InventoryItem *item = InventoryItem::deSerialize(iss); m_items[item_i++] = item; } else if(name == "Empty") { if(item_i > getSize() - 1) throw SerializationError("too many items"); m_items[item_i++] = NULL; } else { throw SerializationError("Unknown inventory identifier"); } } } InventoryList::InventoryList(const InventoryList &other) { /* Do this so that the items get cloned. Otherwise the pointers in the array will just get copied. */ *this = other; } InventoryList & InventoryList::operator = (const InventoryList &other) { m_name = other.m_name; m_size = other.m_size; clearItems(); for(u32 i=0; i<other.m_items.size(); i++) { InventoryItem *item = other.m_items[i]; if(item != NULL) { m_items[i] = item->clone(); } } return *this; } std::string InventoryList::getName() { return m_name; } u32 InventoryList::getSize() { return m_items.size(); } u32 InventoryList::getUsedSlots() { u32 num = 0; for(u32 i=0; i<m_items.size(); i++) { InventoryItem *item = m_items[i]; if(item != NULL) num++; } return num; } InventoryItem * InventoryList::getItem(u32 i) { if(i > m_items.size() - 1) return NULL; return m_items[i]; } InventoryItem * InventoryList::changeItem(u32 i, InventoryItem *newitem) { assert(i < m_items.size()); InventoryItem *olditem = m_items[i]; m_items[i] = newitem; return olditem; } void InventoryList::deleteItem(u32 i) { assert(i < m_items.size()); InventoryItem *item = changeItem(i, NULL); if(item) delete item; } InventoryItem * InventoryList::addItem(InventoryItem *newitem) { /* First try to find if it could be added to some existing items */ for(u32 i=0; i<m_items.size(); i++) { // Ignore empty slots if(m_items[i] == NULL) continue; // Try adding newitem = addItem(i, newitem); if(newitem == NULL) return NULL; // All was eaten } /* Then try to add it to empty slots */ for(u32 i=0; i<m_items.size(); i++) { // Ignore unempty slots if(m_items[i] != NULL) continue; // Try adding newitem = addItem(i, newitem); if(newitem == NULL) return NULL; // All was eaten } // Return leftover return newitem; } InventoryItem * InventoryList::addItem(u32 i, InventoryItem *newitem) { // If it is an empty position, it's an easy job. InventoryItem *to_item = m_items[i]; if(to_item == NULL) { m_items[i] = newitem; return NULL; } // If not addable, return the item if(newitem->addableTo(to_item) == false) return newitem; // If the item fits fully in the slot, add counter and delete it if(newitem->getCount() <= to_item->freeSpace()) { to_item->add(newitem->getCount()); delete newitem; return NULL; } // Else the item does not fit fully. Add all that fits and return // the rest. else { u16 freespace = to_item->freeSpace(); to_item->add(freespace); newitem->remove(freespace); return newitem; } } InventoryItem * InventoryList::takeItem(u32 i, u32 count) { if(count == 0) return NULL; InventoryItem *item = m_items[i]; // If it is an empty position, return NULL if(item == NULL) return NULL; if(count >= item->getCount()) { // Get the item by swapping NULL to its place return changeItem(i, NULL); } else { InventoryItem *item2 = item->clone(); item->remove(count); item2->setCount(count); return item2; } return false; } void InventoryList::decrementMaterials(u16 count) { for(u32 i=0; i<m_items.size(); i++) { InventoryItem *item = takeItem(i, count); if(item) delete item; } } void InventoryList::print(std::ostream &o) { o<<"InventoryList:"<<std::endl; for(u32 i=0; i<m_items.size(); i++) { InventoryItem *item = m_items[i]; if(item != NULL) { o<<i<<": "; item->serialize(o); o<<"\n"; } } } /* Inventory */ Inventory::~Inventory() { clear(); } void Inventory::clear() { for(u32 i=0; i<m_lists.size(); i++) { delete m_lists[i]; } m_lists.clear(); } Inventory::Inventory() { } Inventory::Inventory(const Inventory &other) { *this = other; } Inventory & Inventory::operator = (const Inventory &other) { clear(); for(u32 i=0; i<other.m_lists.size(); i++) { m_lists.push_back(new InventoryList(*other.m_lists[i])); } return *this; } void Inventory::serialize(std::ostream &os) { for(u32 i=0; i<m_lists.size(); i++) { InventoryList *list = m_lists[i]; os<<"List "<<list->getName()<<" "<<list->getSize()<<"\n"; list->serialize(os); } os<<"end\n"; } void Inventory::deSerialize(std::istream &is) { clear(); for(;;) { std::string line; std::getline(is, line, '\n'); std::istringstream iss(line); std::string name; std::getline(iss, name, ' '); if(name == "end") { break; } else if(name == "List") { std::string listname; u32 listsize; std::getline(iss, listname, ' '); iss>>listsize; InventoryList *list = new InventoryList(listname, listsize); list->deSerialize(is); m_lists.push_back(list); } else { throw SerializationError("Unknown inventory identifier"); } } } InventoryList * Inventory::addList(const std::string &name, u32 size) { s32 i = getListIndex(name); if(i != -1) { if(m_lists[i]->getSize() != size) { delete m_lists[i]; m_lists[i] = new InventoryList(name, size); } return m_lists[i]; } else { m_lists.push_back(new InventoryList(name, size)); return m_lists.getLast(); } } InventoryList * Inventory::getList(const std::string &name) { s32 i = getListIndex(name); if(i == -1) return NULL; return m_lists[i]; } s32 Inventory::getListIndex(const std::string &name) { for(u32 i=0; i<m_lists.size(); i++) { if(m_lists[i]->getName() == name) return i; } return -1; } /* InventoryAction */ InventoryAction * InventoryAction::deSerialize(std::istream &is) { std::string type; std::getline(is, type, ' '); InventoryAction *a = NULL; if(type == "Move") { a = new IMoveAction(is); } return a; } void IMoveAction::apply(Inventory *inventory) {