aboutsummaryrefslogtreecommitdiff
path: root/common/serializer.h
blob: a44883683b4c0e524bfcebb6427d0bf1f33b39f1 (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
/* ScummVM - Graphic Adventure Engine
 *
 * ScummVM is the legal property of its developers, whose names
 * are too numerous to list here. Please refer to the COPYRIGHT
 * file distributed with this source distribution.
 *
 * 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.
 *
 * $URL$
 * $Id$
 *
 */

#ifndef COMMON_SERIALIZER_H
#define COMMON_SERIALIZER_H

#include "common/stream.h"
#include "common/str.h"

namespace Common {


#define SYNC_AS(SUFFIX,TYPE,SIZE) \
	template <typename T> \
	void syncAs ## SUFFIX(T &val, Version minVersion = 0, Version maxVersion = kLastVersion) { \
		if (_version < minVersion || _version > maxVersion) \
			return;	\
		if (_loadStream) \
			val = static_cast<T>(_loadStream->read ## SUFFIX()); \
		else { \
			TYPE tmp = val; \
			_saveStream->write ## SUFFIX(tmp); \
		} \
		_bytesSynced += SIZE; \
	}


/**
 * This class allows syncing / serializing data (primarily game savestates)
 * between memory and Read/WriteStreams.
 * It optionally supports versioning the serialized data (client code must
 * use the syncVersion() method for this). This makes it possible to support
 * multiple versions of a savegame format with a single codepath
 *
 * This class was heavily inspired by the save/load code in the SCUMM engine.
 *
 * @todo Maybe rename this to Synchronizer?
 *
 * @todo One feature the SCUMM code has but that is missing here: Support for
 *       syncing arrays of a given type and *fixed* size; and also support
 *       for when the array size changed between versions. Also, support for
 *       2D-arrays.
 *
 * @todo Proper error handling!
 */
class Serializer {
public:
	typedef uint32 Version;
	static const Version kLastVersion = 0xFFFFFFFF;

protected:
	Common::SeekableReadStream *_loadStream;
	Common::WriteStream *_saveStream;

	uint _bytesSynced;

	Version _version;

public:
	Serializer(Common::SeekableReadStream *in, Common::WriteStream *out)
		: _loadStream(in), _saveStream(out), _bytesSynced(0), _version(0) {
		assert(in || out);
	}
	virtual ~Serializer() {}

	inline bool isSaving() { return (_saveStream != 0); }
	inline bool isLoading() { return (_loadStream != 0); }

	/**
	 * Returns true if an I/O failure occurred.
	 * This flag is never cleared automatically. In order to clear it,
	 * client code has to call clearErr() explicitly.
	 */
	bool err() const {
		if (_saveStream)
			return _saveStream->err();
		else
			return _loadStream->err();
	}

	/**
	 * Reset the I/O error status as returned by err().
	 */
	void clearErr() {
		if (_saveStream)
			_saveStream->clearErr();
		else
			_loadStream->clearErr();
	}

	/**
	 * Sync the "version" of the savegame we are loading/creating.
	 * @param currentVersion	current format version, used when writing a new file
	 * @return true if the version of the savestate is not too new.
	 */
	bool syncVersion(Version currentVersion) {
		_version = currentVersion;
		syncAsUint32LE(_version);
		return _version <= currentVersion;
	}

	/**
	 * Return the version of the savestate being serialized. Useful if the engine
	 * needs to perform additional adjustments when loading old savestates.
	 */
	Version getVersion() const { return _version; }

	/**
	 * Sync a 'magic id' of up to 256 bytes, and return whether it matched.
	 * When saving, this will simply write out the magic id and return true.
	 * When loading, this will read the specified number of bytes, compare it
	 * to the given magic id and return true on a match, false otherwise.
	 *
	 * A typical magic id is a FOURCC like 'MAGI'.
	 *
	 * @param magic		magic id as a byte sequence
	 * @param size		length of the magic id in bytes
	 * @return true if the magic id matched, false otherwise
	 *
	 * @todo Should this have minVersion/maxVersion params, too?
	 */
	bool syncMagic(const char *magic, byte size) {
		char buf[256];
		bool match;
		if (isSaving()) {
			_saveStream->write(magic, size);
			match = true;
		} else {
			_loadStream->read(buf, size);
			match = (0 == memcmp(buf, magic, size));
		}
		_bytesSynced += size;
		return match;
	}


	/**
	 * Return the total number of bytes synced so far.
	 */
	uint bytesSynced() const { return _bytesSynced; }

	/**
	 * Skip a number of bytes in the data stream.
	 * This is useful to skip obsolete fields in old savestates.
	 */
	void skip(uint32 size, Version minVersion = 0, Version maxVersion = kLastVersion) {
		if (_version < minVersion || _version > maxVersion)
			return;	// Ignore anything which is not supposed to be present in this save game version

		_bytesSynced += size;
		if (isLoading())
			_loadStream->skip(size);
		else {
			while (size--)
				_saveStream->writeByte(0);
		}
	}

	/**
	 * Sync a block of arbitrary fixed-length data.
	 */
	void syncBytes(byte *buf, uint32 size, Version minVersion = 0, Version maxVersion = kLastVersion) {
		if (_version < minVersion || _version > maxVersion)
			return;	// Ignore anything which is not supposed to be present in this save game version

		if (isLoading())
			_loadStream->read(buf, size);
		else
			_saveStream->write(buf, size);
		_bytesSynced += size;
	}

	/**
	 * Sync a C-string, by treating it as a zero-terminated byte sequence.
	 * @todo Replace this method with a special Syncer class for Common::String
	 */
	void syncString(Common::String &str, Version minVersion = 0, Version maxVersion = kLastVersion) {
		if (_version < minVersion || _version > maxVersion)
			return;	// Ignore anything which is not supposed to be present in this save game version

		if (isLoading()) {
			char c;
			str.clear();
			while ((c = _loadStream->readByte())) {
				str += c;
				_bytesSynced++;
			}
			_bytesSynced++;
		} else {
			_saveStream->writeString(str);
			_saveStream->writeByte(0);
			_bytesSynced += str.size() + 1;
		}
	}

	SYNC_AS(Byte, byte, 1)

	SYNC_AS(Uint16LE, uint16, 2)
	SYNC_AS(Uint16BE, uint16, 2)
	SYNC_AS(Sint16LE, int16, 2)
	SYNC_AS(Sint16BE, int16, 2)

	SYNC_AS(Uint32LE, uint32, 4)
	SYNC_AS(Uint32BE, uint32, 4)
	SYNC_AS(Sint32LE, int32, 4)
	SYNC_AS(Sint32BE, int32, 4)
};

#undef SYNC_AS


// Mixin class / interface
// TODO: Maybe rename this to Syncable ?
class Serializable {
public:
	virtual ~Serializable() {}

	// Maybe rename this method to "syncWithSerializer" or "syncUsingSerializer" ?
	virtual void saveLoadWithSerializer(Serializer &ser) = 0;
};


} // end of namespace Common

#endif