]> git.lizzy.rs Git - minetest.git/blob - src/util/serialize.h
f2b0dab2f3faec39bc97939edfc5a9224176ce6f
[minetest.git] / src / util / serialize.h
1 /*
2 Minetest
3 Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #pragma once
21
22 #include "../irrlichttypes_bloated.h"
23 #include "../exceptions.h" // for SerializationError
24 #include "../debug.h" // for assert
25
26 #include "config.h"
27 #if HAVE_ENDIAN_H
28         #ifdef _WIN32
29                 #define __BYTE_ORDER 0
30                 #define __LITTLE_ENDIAN 0
31                 #define __BIG_ENDIAN 1
32         #elif defined(__MACH__) && defined(__APPLE__)
33                 #include <machine/endian.h>
34         #elif defined(__FreeBSD__)
35                 #include <sys/endian.h>
36         #else
37                 #include <endian.h>
38         #endif
39 #endif
40 #include <cstring> // for memcpy
41 #include <iostream>
42 #include <string>
43 #include <vector>
44
45 #define FIXEDPOINT_FACTOR 1000.0f
46
47 // 0x7FFFFFFF / 1000.0f is not serializable.
48 // The limited float precision at this magnitude may cause the result to round
49 // to a greater value than can be represented by a 32 bit integer when increased
50 // by a factor of FIXEDPOINT_FACTOR.  As a result, [F1000_MIN..F1000_MAX] does
51 // not represent the full range, but rather the largest safe range, of values on
52 // all supported architectures.  Note: This definition makes assumptions on
53 // platform float-to-int conversion behavior.
54 #define F1000_MIN ((float)(s32)((-0x7FFFFFFF - 1) / FIXEDPOINT_FACTOR))
55 #define F1000_MAX ((float)(s32)((0x7FFFFFFF) / FIXEDPOINT_FACTOR))
56
57 #define STRING_MAX_LEN 0xFFFF
58 #define WIDE_STRING_MAX_LEN 0xFFFF
59 // 64 MB ought to be enough for anybody - Billy G.
60 #define LONG_STRING_MAX_LEN (64 * 1024 * 1024)
61
62
63 #if HAVE_ENDIAN_H
64 // use machine native byte swapping routines
65 // Note: memcpy below is optimized out by modern compilers
66
67 inline u16 readU16(const u8 *data)
68 {
69         u16 val;
70         memcpy(&val, data, 2);
71         return be16toh(val);
72 }
73
74 inline u32 readU32(const u8 *data)
75 {
76         u32 val;
77         memcpy(&val, data, 4);
78         return be32toh(val);
79 }
80
81 inline u64 readU64(const u8 *data)
82 {
83         u64 val;
84         memcpy(&val, data, 8);
85         return be64toh(val);
86 }
87
88 inline void writeU16(u8 *data, u16 i)
89 {
90         u16 val = htobe16(i);
91         memcpy(data, &val, 2);
92 }
93
94 inline void writeU32(u8 *data, u32 i)
95 {
96         u32 val = htobe32(i);
97         memcpy(data, &val, 4);
98 }
99
100 inline void writeU64(u8 *data, u64 i)
101 {
102         u64 val = htobe64(i);
103         memcpy(data, &val, 8);
104 }
105
106 #else
107 // generic byte-swapping implementation
108
109 inline u16 readU16(const u8 *data)
110 {
111         return
112                 ((u16)data[0] << 8) | ((u16)data[1] << 0);
113 }
114
115 inline u32 readU32(const u8 *data)
116 {
117         return
118                 ((u32)data[0] << 24) | ((u32)data[1] << 16) |
119                 ((u32)data[2] <<  8) | ((u32)data[3] <<  0);
120 }
121
122 inline u64 readU64(const u8 *data)
123 {
124         return
125                 ((u64)data[0] << 56) | ((u64)data[1] << 48) |
126                 ((u64)data[2] << 40) | ((u64)data[3] << 32) |
127                 ((u64)data[4] << 24) | ((u64)data[5] << 16) |
128                 ((u64)data[6] <<  8) | ((u64)data[7] << 0);
129 }
130
131 inline void writeU16(u8 *data, u16 i)
132 {
133         data[0] = (i >> 8) & 0xFF;
134         data[1] = (i >> 0) & 0xFF;
135 }
136
137 inline void writeU32(u8 *data, u32 i)
138 {
139         data[0] = (i >> 24) & 0xFF;
140         data[1] = (i >> 16) & 0xFF;
141         data[2] = (i >>  8) & 0xFF;
142         data[3] = (i >>  0) & 0xFF;
143 }
144
145 inline void writeU64(u8 *data, u64 i)
146 {
147         data[0] = (i >> 56) & 0xFF;
148         data[1] = (i >> 48) & 0xFF;
149         data[2] = (i >> 40) & 0xFF;
150         data[3] = (i >> 32) & 0xFF;
151         data[4] = (i >> 24) & 0xFF;
152         data[5] = (i >> 16) & 0xFF;
153         data[6] = (i >>  8) & 0xFF;
154         data[7] = (i >>  0) & 0xFF;
155 }
156
157 #endif // HAVE_ENDIAN_H
158
159 //////////////// read routines ////////////////
160
161 inline u8 readU8(const u8 *data)
162 {
163         return ((u8)data[0] << 0);
164 }
165
166 inline s8 readS8(const u8 *data)
167 {
168         return (s8)readU8(data);
169 }
170
171 inline s16 readS16(const u8 *data)
172 {
173         return (s16)readU16(data);
174 }
175
176 inline s32 readS32(const u8 *data)
177 {
178         return (s32)readU32(data);
179 }
180
181 inline s64 readS64(const u8 *data)
182 {
183         return (s64)readU64(data);
184 }
185
186 inline f32 readF1000(const u8 *data)
187 {
188         return (f32)readS32(data) / FIXEDPOINT_FACTOR;
189 }
190
191 inline video::SColor readARGB8(const u8 *data)
192 {
193         video::SColor p(readU32(data));
194         return p;
195 }
196
197 inline v2s16 readV2S16(const u8 *data)
198 {
199         v2s16 p;
200         p.X = readS16(&data[0]);
201         p.Y = readS16(&data[2]);
202         return p;
203 }
204
205 inline v3s16 readV3S16(const u8 *data)
206 {
207         v3s16 p;
208         p.X = readS16(&data[0]);
209         p.Y = readS16(&data[2]);
210         p.Z = readS16(&data[4]);
211         return p;
212 }
213
214 inline v2s32 readV2S32(const u8 *data)
215 {
216         v2s32 p;
217         p.X = readS32(&data[0]);
218         p.Y = readS32(&data[4]);
219         return p;
220 }
221
222 inline v3s32 readV3S32(const u8 *data)
223 {
224         v3s32 p;
225         p.X = readS32(&data[0]);
226         p.Y = readS32(&data[4]);
227         p.Z = readS32(&data[8]);
228         return p;
229 }
230
231 inline v2f readV2F1000(const u8 *data)
232 {
233         v2f p;
234         p.X = (float)readF1000(&data[0]);
235         p.Y = (float)readF1000(&data[4]);
236         return p;
237 }
238
239 inline v3f readV3F1000(const u8 *data)
240 {
241         v3f p;
242         p.X = (float)readF1000(&data[0]);
243         p.Y = (float)readF1000(&data[4]);
244         p.Z = (float)readF1000(&data[8]);
245         return p;
246 }
247
248 /////////////// write routines ////////////////
249
250 inline void writeU8(u8 *data, u8 i)
251 {
252         data[0] = (i >> 0) & 0xFF;
253 }
254
255 inline void writeS8(u8 *data, s8 i)
256 {
257         writeU8(data, (u8)i);
258 }
259
260 inline void writeS16(u8 *data, s16 i)
261 {
262         writeU16(data, (u16)i);
263 }
264
265 inline void writeS32(u8 *data, s32 i)
266 {
267         writeU32(data, (u32)i);
268 }
269
270 inline void writeS64(u8 *data, s64 i)
271 {
272         writeU64(data, (u64)i);
273 }
274
275 inline void writeF1000(u8 *data, f32 i)
276 {
277         assert(i >= F1000_MIN && i <= F1000_MAX);
278         writeS32(data, i * FIXEDPOINT_FACTOR);
279 }
280
281 inline void writeARGB8(u8 *data, video::SColor p)
282 {
283         writeU32(data, p.color);
284 }
285
286 inline void writeV2S16(u8 *data, v2s16 p)
287 {
288         writeS16(&data[0], p.X);
289         writeS16(&data[2], p.Y);
290 }
291
292 inline void writeV3S16(u8 *data, v3s16 p)
293 {
294         writeS16(&data[0], p.X);
295         writeS16(&data[2], p.Y);
296         writeS16(&data[4], p.Z);
297 }
298
299 inline void writeV2S32(u8 *data, v2s32 p)
300 {
301         writeS32(&data[0], p.X);
302         writeS32(&data[4], p.Y);
303 }
304
305 inline void writeV3S32(u8 *data, v3s32 p)
306 {
307         writeS32(&data[0], p.X);
308         writeS32(&data[4], p.Y);
309         writeS32(&data[8], p.Z);
310 }
311
312 inline void writeV2F1000(u8 *data, v2f p)
313 {
314         writeF1000(&data[0], p.X);
315         writeF1000(&data[4], p.Y);
316 }
317
318 inline void writeV3F1000(u8 *data, v3f p)
319 {
320         writeF1000(&data[0], p.X);
321         writeF1000(&data[4], p.Y);
322         writeF1000(&data[8], p.Z);
323 }
324
325 ////
326 //// Iostream wrapper for data read/write
327 ////
328
329 #define MAKE_STREAM_READ_FXN(T, N, S)    \
330         inline T read ## N(std::istream &is) \
331         {                                    \
332                 char buf[S] = {0};               \
333                 is.read(buf, sizeof(buf));       \
334                 return read ## N((u8 *)buf);     \
335         }
336
337 #define MAKE_STREAM_WRITE_FXN(T, N, S)              \
338         inline void write ## N(std::ostream &os, T val) \
339         {                                               \
340                 char buf[S];                                \
341                 write ## N((u8 *)buf, val);                 \
342                 os.write(buf, sizeof(buf));                 \
343         }
344
345 MAKE_STREAM_READ_FXN(u8,    U8,       1);
346 MAKE_STREAM_READ_FXN(u16,   U16,      2);
347 MAKE_STREAM_READ_FXN(u32,   U32,      4);
348 MAKE_STREAM_READ_FXN(u64,   U64,      8);
349 MAKE_STREAM_READ_FXN(s8,    S8,       1);
350 MAKE_STREAM_READ_FXN(s16,   S16,      2);
351 MAKE_STREAM_READ_FXN(s32,   S32,      4);
352 MAKE_STREAM_READ_FXN(s64,   S64,      8);
353 MAKE_STREAM_READ_FXN(f32,   F1000,    4);
354 MAKE_STREAM_READ_FXN(v2s16, V2S16,    4);
355 MAKE_STREAM_READ_FXN(v3s16, V3S16,    6);
356 MAKE_STREAM_READ_FXN(v2s32, V2S32,    8);
357 MAKE_STREAM_READ_FXN(v3s32, V3S32,   12);
358 MAKE_STREAM_READ_FXN(v2f,   V2F1000,  8);
359 MAKE_STREAM_READ_FXN(v3f,   V3F1000, 12);
360 MAKE_STREAM_READ_FXN(video::SColor, ARGB8, 4);
361
362 MAKE_STREAM_WRITE_FXN(u8,    U8,       1);
363 MAKE_STREAM_WRITE_FXN(u16,   U16,      2);
364 MAKE_STREAM_WRITE_FXN(u32,   U32,      4);
365 MAKE_STREAM_WRITE_FXN(u64,   U64,      8);
366 MAKE_STREAM_WRITE_FXN(s8,    S8,       1);
367 MAKE_STREAM_WRITE_FXN(s16,   S16,      2);
368 MAKE_STREAM_WRITE_FXN(s32,   S32,      4);
369 MAKE_STREAM_WRITE_FXN(s64,   S64,      8);
370 MAKE_STREAM_WRITE_FXN(f32,   F1000,    4);
371 MAKE_STREAM_WRITE_FXN(v2s16, V2S16,    4);
372 MAKE_STREAM_WRITE_FXN(v3s16, V3S16,    6);
373 MAKE_STREAM_WRITE_FXN(v2s32, V2S32,    8);
374 MAKE_STREAM_WRITE_FXN(v3s32, V3S32,   12);
375 MAKE_STREAM_WRITE_FXN(v2f,   V2F1000,  8);
376 MAKE_STREAM_WRITE_FXN(v3f,   V3F1000, 12);
377 MAKE_STREAM_WRITE_FXN(video::SColor, ARGB8, 4);
378
379 ////
380 //// More serialization stuff
381 ////
382
383 // Creates a string with the length as the first two bytes
384 std::string serializeString(const std::string &plain);
385
386 // Creates a string with the length as the first two bytes from wide string
387 std::string serializeWideString(const std::wstring &plain);
388
389 // Reads a string with the length as the first two bytes
390 std::string deSerializeString(std::istream &is);
391
392 // Reads a wide string with the length as the first two bytes
393 std::wstring deSerializeWideString(std::istream &is);
394
395 // Creates a string with the length as the first four bytes
396 std::string serializeLongString(const std::string &plain);
397
398 // Reads a string with the length as the first four bytes
399 std::string deSerializeLongString(std::istream &is);
400
401 // Creates a string encoded in JSON format (almost equivalent to a C string literal)
402 std::string serializeJsonString(const std::string &plain);
403
404 // Reads a string encoded in JSON format
405 std::string deSerializeJsonString(std::istream &is);
406
407 // If the string contains spaces, quotes or control characters, encodes as JSON.
408 // Else returns the string unmodified.
409 std::string serializeJsonStringIfNeeded(const std::string &s);
410
411 // Parses a string serialized by serializeJsonStringIfNeeded.
412 std::string deSerializeJsonStringIfNeeded(std::istream &is);
413
414 // Creates a string consisting of the hexadecimal representation of `data`
415 std::string serializeHexString(const std::string &data, bool insert_spaces=false);
416
417 // Creates a string containing comma delimited values of a struct whose layout is
418 // described by the parameter format
419 bool serializeStructToString(std::string *out,
420         std::string format, void *value);
421
422 // Reads a comma delimited string of values into a struct whose layout is
423 // decribed by the parameter format
424 bool deSerializeStringToStruct(std::string valstr,
425         std::string format, void *out, size_t olen);
426
427 ////
428 //// BufReader
429 ////
430
431 #define MAKE_BUFREADER_GETNOEX_FXN(T, N, S) \
432         inline bool get ## N ## NoEx(T *val)    \
433         {                                       \
434                 if (pos + S > size)                 \
435                         return false;                   \
436                 *val = read ## N(data + pos);       \
437                 pos += S;                           \
438                 return true;                        \
439         }
440
441 #define MAKE_BUFREADER_GET_FXN(T, N) \
442         inline T get ## N()              \
443         {                                \
444                 T val;                       \
445                 if (!get ## N ## NoEx(&val)) \
446                         throw SerializationError("Attempted read past end of data"); \
447                 return val;                  \
448         }
449
450 class BufReader {
451 public:
452         BufReader(const u8 *data_, size_t size_) :
453                 data(data_),
454                 size(size_)
455         {
456         }
457
458         MAKE_BUFREADER_GETNOEX_FXN(u8,    U8,       1);
459         MAKE_BUFREADER_GETNOEX_FXN(u16,   U16,      2);
460         MAKE_BUFREADER_GETNOEX_FXN(u32,   U32,      4);
461         MAKE_BUFREADER_GETNOEX_FXN(u64,   U64,      8);
462         MAKE_BUFREADER_GETNOEX_FXN(s8,    S8,       1);
463         MAKE_BUFREADER_GETNOEX_FXN(s16,   S16,      2);
464         MAKE_BUFREADER_GETNOEX_FXN(s32,   S32,      4);
465         MAKE_BUFREADER_GETNOEX_FXN(s64,   S64,      8);
466         MAKE_BUFREADER_GETNOEX_FXN(f32,   F1000,    4);
467         MAKE_BUFREADER_GETNOEX_FXN(v2s16, V2S16,    4);
468         MAKE_BUFREADER_GETNOEX_FXN(v3s16, V3S16,    6);
469         MAKE_BUFREADER_GETNOEX_FXN(v2s32, V2S32,    8);
470         MAKE_BUFREADER_GETNOEX_FXN(v3s32, V3S32,   12);
471         MAKE_BUFREADER_GETNOEX_FXN(v2f,   V2F1000,  8);
472         MAKE_BUFREADER_GETNOEX_FXN(v3f,   V3F1000, 12);
473         MAKE_BUFREADER_GETNOEX_FXN(video::SColor, ARGB8, 4);
474
475         bool getStringNoEx(std::string *val);
476         bool getWideStringNoEx(std::wstring *val);
477         bool getLongStringNoEx(std::string *val);
478         bool getRawDataNoEx(void *data, size_t len);
479
480         MAKE_BUFREADER_GET_FXN(u8,            U8);
481         MAKE_BUFREADER_GET_FXN(u16,           U16);
482         MAKE_BUFREADER_GET_FXN(u32,           U32);
483         MAKE_BUFREADER_GET_FXN(u64,           U64);
484         MAKE_BUFREADER_GET_FXN(s8,            S8);
485         MAKE_BUFREADER_GET_FXN(s16,           S16);
486         MAKE_BUFREADER_GET_FXN(s32,           S32);
487         MAKE_BUFREADER_GET_FXN(s64,           S64);
488         MAKE_BUFREADER_GET_FXN(f32,           F1000);
489         MAKE_BUFREADER_GET_FXN(v2s16,         V2S16);
490         MAKE_BUFREADER_GET_FXN(v3s16,         V3S16);
491         MAKE_BUFREADER_GET_FXN(v2s32,         V2S32);
492         MAKE_BUFREADER_GET_FXN(v3s32,         V3S32);
493         MAKE_BUFREADER_GET_FXN(v2f,           V2F1000);
494         MAKE_BUFREADER_GET_FXN(v3f,           V3F1000);
495         MAKE_BUFREADER_GET_FXN(video::SColor, ARGB8);
496         MAKE_BUFREADER_GET_FXN(std::string,   String);
497         MAKE_BUFREADER_GET_FXN(std::wstring,  WideString);
498         MAKE_BUFREADER_GET_FXN(std::string,   LongString);
499
500         inline void getRawData(void *val, size_t len)
501         {
502                 if (!getRawDataNoEx(val, len))
503                         throw SerializationError("Attempted read past end of data");
504         }
505
506         inline size_t remaining()
507         {
508                 assert(pos <= size);
509                 return size - pos;
510         }
511
512         const u8 *data;
513         size_t size;
514         size_t pos = 0;
515 };
516
517 #undef MAKE_BUFREADER_GET_FXN
518 #undef MAKE_BUFREADER_GETNOEX_FXN
519
520
521 ////
522 //// Vector-based write routines
523 ////
524
525 inline void putU8(std::vector<u8> *dest, u8 val)
526 {
527         dest->push_back((val >> 0) & 0xFF);
528 }
529
530 inline void putU16(std::vector<u8> *dest, u16 val)
531 {
532         dest->push_back((val >> 8) & 0xFF);
533         dest->push_back((val >> 0) & 0xFF);
534 }
535
536 inline void putU32(std::vector<u8> *dest, u32 val)
537 {
538         dest->push_back((val >> 24) & 0xFF);
539         dest->push_back((val >> 16) & 0xFF);
540         dest->push_back((val >>  8) & 0xFF);
541         dest->push_back((val >>  0) & 0xFF);
542 }
543
544 inline void putU64(std::vector<u8> *dest, u64 val)
545 {
546         dest->push_back((val >> 56) & 0xFF);
547         dest->push_back((val >> 48) & 0xFF);
548         dest->push_back((val >> 40) & 0xFF);
549         dest->push_back((val >> 32) & 0xFF);
550         dest->push_back((val >> 24) & 0xFF);
551         dest->push_back((val >> 16) & 0xFF);
552         dest->push_back((val >>  8) & 0xFF);
553         dest->push_back((val >>  0) & 0xFF);
554 }
555
556 inline void putS8(std::vector<u8> *dest, s8 val)
557 {
558         putU8(dest, val);
559 }
560
561 inline void putS16(std::vector<u8> *dest, s16 val)
562 {
563         putU16(dest, val);
564 }
565
566 inline void putS32(std::vector<u8> *dest, s32 val)
567 {
568         putU32(dest, val);
569 }
570
571 inline void putS64(std::vector<u8> *dest, s64 val)
572 {
573         putU64(dest, val);
574 }
575
576 inline void putF1000(std::vector<u8> *dest, f32 val)
577 {
578         putS32(dest, val * FIXEDPOINT_FACTOR);
579 }
580
581 inline void putV2S16(std::vector<u8> *dest, v2s16 val)
582 {
583         putS16(dest, val.X);
584         putS16(dest, val.Y);
585 }
586
587 inline void putV3S16(std::vector<u8> *dest, v3s16 val)
588 {
589         putS16(dest, val.X);
590         putS16(dest, val.Y);
591         putS16(dest, val.Z);
592 }
593
594 inline void putV2S32(std::vector<u8> *dest, v2s32 val)
595 {
596         putS32(dest, val.X);
597         putS32(dest, val.Y);
598 }
599
600 inline void putV3S32(std::vector<u8> *dest, v3s32 val)
601 {
602         putS32(dest, val.X);
603         putS32(dest, val.Y);
604         putS32(dest, val.Z);
605 }
606
607 inline void putV2F1000(std::vector<u8> *dest, v2f val)
608 {
609         putF1000(dest, val.X);
610         putF1000(dest, val.Y);
611 }
612
613 inline void putV3F1000(std::vector<u8> *dest, v3f val)
614 {
615         putF1000(dest, val.X);
616         putF1000(dest, val.Y);
617         putF1000(dest, val.Z);
618 }
619
620 inline void putARGB8(std::vector<u8> *dest, video::SColor val)
621 {
622         putU32(dest, val.color);
623 }
624
625 inline void putString(std::vector<u8> *dest, const std::string &val)
626 {
627         if (val.size() > STRING_MAX_LEN)
628                 throw SerializationError("String too long");
629
630         putU16(dest, val.size());
631         dest->insert(dest->end(), val.begin(), val.end());
632 }
633
634 inline void putWideString(std::vector<u8> *dest, const std::wstring &val)
635 {
636         if (val.size() > WIDE_STRING_MAX_LEN)
637                 throw SerializationError("String too long");
638
639         putU16(dest, val.size());
640         for (size_t i = 0; i != val.size(); i++)
641                 putU16(dest, val[i]);
642 }
643
644 inline void putLongString(std::vector<u8> *dest, const std::string &val)
645 {
646         if (val.size() > LONG_STRING_MAX_LEN)
647                 throw SerializationError("String too long");
648
649         putU32(dest, val.size());
650         dest->insert(dest->end(), val.begin(), val.end());
651 }
652
653 inline void putRawData(std::vector<u8> *dest, const void *src, size_t len)
654 {
655         dest->insert(dest->end(), (u8 *)src, (u8 *)src + len);
656 }