]> git.lizzy.rs Git - dragonfireclient.git/blob - src/util/serialize.h
C++ modernize: Pragma once (#6264)
[dragonfireclient.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 <string.h> // 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 extern SerializationError eof_ser_err;
432
433 #define MAKE_BUFREADER_GETNOEX_FXN(T, N, S) \
434         inline bool get ## N ## NoEx(T *val)    \
435         {                                       \
436                 if (pos + S > size)                 \
437                         return false;                   \
438                 *val = read ## N(data + pos);       \
439                 pos += S;                           \
440                 return true;                        \
441         }
442
443 #define MAKE_BUFREADER_GET_FXN(T, N) \
444         inline T get ## N()              \
445         {                                \
446                 T val;                       \
447                 if (!get ## N ## NoEx(&val)) \
448                         throw eof_ser_err;       \
449                 return val;                  \
450         }
451
452 class BufReader {
453 public:
454         BufReader(const u8 *data_, size_t size_) :
455                 data(data_),
456                 size(size_)
457         {
458         }
459
460         MAKE_BUFREADER_GETNOEX_FXN(u8,    U8,       1);
461         MAKE_BUFREADER_GETNOEX_FXN(u16,   U16,      2);
462         MAKE_BUFREADER_GETNOEX_FXN(u32,   U32,      4);
463         MAKE_BUFREADER_GETNOEX_FXN(u64,   U64,      8);
464         MAKE_BUFREADER_GETNOEX_FXN(s8,    S8,       1);
465         MAKE_BUFREADER_GETNOEX_FXN(s16,   S16,      2);
466         MAKE_BUFREADER_GETNOEX_FXN(s32,   S32,      4);
467         MAKE_BUFREADER_GETNOEX_FXN(s64,   S64,      8);
468         MAKE_BUFREADER_GETNOEX_FXN(f32,   F1000,    4);
469         MAKE_BUFREADER_GETNOEX_FXN(v2s16, V2S16,    4);
470         MAKE_BUFREADER_GETNOEX_FXN(v3s16, V3S16,    6);
471         MAKE_BUFREADER_GETNOEX_FXN(v2s32, V2S32,    8);
472         MAKE_BUFREADER_GETNOEX_FXN(v3s32, V3S32,   12);
473         MAKE_BUFREADER_GETNOEX_FXN(v2f,   V2F1000,  8);
474         MAKE_BUFREADER_GETNOEX_FXN(v3f,   V3F1000, 12);
475         MAKE_BUFREADER_GETNOEX_FXN(video::SColor, ARGB8, 4);
476
477         bool getStringNoEx(std::string *val);
478         bool getWideStringNoEx(std::wstring *val);
479         bool getLongStringNoEx(std::string *val);
480         bool getRawDataNoEx(void *data, size_t len);
481
482         MAKE_BUFREADER_GET_FXN(u8,            U8);
483         MAKE_BUFREADER_GET_FXN(u16,           U16);
484         MAKE_BUFREADER_GET_FXN(u32,           U32);
485         MAKE_BUFREADER_GET_FXN(u64,           U64);
486         MAKE_BUFREADER_GET_FXN(s8,            S8);
487         MAKE_BUFREADER_GET_FXN(s16,           S16);
488         MAKE_BUFREADER_GET_FXN(s32,           S32);
489         MAKE_BUFREADER_GET_FXN(s64,           S64);
490         MAKE_BUFREADER_GET_FXN(f32,           F1000);
491         MAKE_BUFREADER_GET_FXN(v2s16,         V2S16);
492         MAKE_BUFREADER_GET_FXN(v3s16,         V3S16);
493         MAKE_BUFREADER_GET_FXN(v2s32,         V2S32);
494         MAKE_BUFREADER_GET_FXN(v3s32,         V3S32);
495         MAKE_BUFREADER_GET_FXN(v2f,           V2F1000);
496         MAKE_BUFREADER_GET_FXN(v3f,           V3F1000);
497         MAKE_BUFREADER_GET_FXN(video::SColor, ARGB8);
498         MAKE_BUFREADER_GET_FXN(std::string,   String);
499         MAKE_BUFREADER_GET_FXN(std::wstring,  WideString);
500         MAKE_BUFREADER_GET_FXN(std::string,   LongString);
501
502         inline void getRawData(void *val, size_t len)
503         {
504                 if (!getRawDataNoEx(val, len))
505                         throw eof_ser_err;
506         }
507
508         inline size_t remaining()
509         {
510                 assert(pos <= size);
511                 return size - pos;
512         }
513
514         const u8 *data;
515         size_t size;
516         size_t pos = 0;
517 };
518
519 #undef MAKE_BUFREADER_GET_FXN
520 #undef MAKE_BUFREADER_GETNOEX_FXN
521
522
523 ////
524 //// Vector-based write routines
525 ////
526
527 inline void putU8(std::vector<u8> *dest, u8 val)
528 {
529         dest->push_back((val >> 0) & 0xFF);
530 }
531
532 inline void putU16(std::vector<u8> *dest, u16 val)
533 {
534         dest->push_back((val >> 8) & 0xFF);
535         dest->push_back((val >> 0) & 0xFF);
536 }
537
538 inline void putU32(std::vector<u8> *dest, u32 val)
539 {
540         dest->push_back((val >> 24) & 0xFF);
541         dest->push_back((val >> 16) & 0xFF);
542         dest->push_back((val >>  8) & 0xFF);
543         dest->push_back((val >>  0) & 0xFF);
544 }
545
546 inline void putU64(std::vector<u8> *dest, u64 val)
547 {
548         dest->push_back((val >> 56) & 0xFF);
549         dest->push_back((val >> 48) & 0xFF);
550         dest->push_back((val >> 40) & 0xFF);
551         dest->push_back((val >> 32) & 0xFF);
552         dest->push_back((val >> 24) & 0xFF);
553         dest->push_back((val >> 16) & 0xFF);
554         dest->push_back((val >>  8) & 0xFF);
555         dest->push_back((val >>  0) & 0xFF);
556 }
557
558 inline void putS8(std::vector<u8> *dest, s8 val)
559 {
560         putU8(dest, val);
561 }
562
563 inline void putS16(std::vector<u8> *dest, s16 val)
564 {
565         putU16(dest, val);
566 }
567
568 inline void putS32(std::vector<u8> *dest, s32 val)
569 {
570         putU32(dest, val);
571 }
572
573 inline void putS64(std::vector<u8> *dest, s64 val)
574 {
575         putU64(dest, val);
576 }
577
578 inline void putF1000(std::vector<u8> *dest, f32 val)
579 {
580         putS32(dest, val * FIXEDPOINT_FACTOR);
581 }
582
583 inline void putV2S16(std::vector<u8> *dest, v2s16 val)
584 {
585         putS16(dest, val.X);
586         putS16(dest, val.Y);
587 }
588
589 inline void putV3S16(std::vector<u8> *dest, v3s16 val)
590 {
591         putS16(dest, val.X);
592         putS16(dest, val.Y);
593         putS16(dest, val.Z);
594 }
595
596 inline void putV2S32(std::vector<u8> *dest, v2s32 val)
597 {
598         putS32(dest, val.X);
599         putS32(dest, val.Y);
600 }
601
602 inline void putV3S32(std::vector<u8> *dest, v3s32 val)
603 {
604         putS32(dest, val.X);
605         putS32(dest, val.Y);
606         putS32(dest, val.Z);
607 }
608
609 inline void putV2F1000(std::vector<u8> *dest, v2f val)
610 {
611         putF1000(dest, val.X);
612         putF1000(dest, val.Y);
613 }
614
615 inline void putV3F1000(std::vector<u8> *dest, v3f val)
616 {
617         putF1000(dest, val.X);
618         putF1000(dest, val.Y);
619         putF1000(dest, val.Z);
620 }
621
622 inline void putARGB8(std::vector<u8> *dest, video::SColor val)
623 {
624         putU32(dest, val.color);
625 }
626
627 inline void putString(std::vector<u8> *dest, const std::string &val)
628 {
629         if (val.size() > STRING_MAX_LEN)
630                 throw SerializationError("String too long");
631
632         putU16(dest, val.size());
633         dest->insert(dest->end(), val.begin(), val.end());
634 }
635
636 inline void putWideString(std::vector<u8> *dest, const std::wstring &val)
637 {
638         if (val.size() > WIDE_STRING_MAX_LEN)
639                 throw SerializationError("String too long");
640
641         putU16(dest, val.size());
642         for (size_t i = 0; i != val.size(); i++)
643                 putU16(dest, val[i]);
644 }
645
646 inline void putLongString(std::vector<u8> *dest, const std::string &val)
647 {
648         if (val.size() > LONG_STRING_MAX_LEN)
649                 throw SerializationError("String too long");
650
651         putU32(dest, val.size());
652         dest->insert(dest->end(), val.begin(), val.end());
653 }
654
655 inline void putRawData(std::vector<u8> *dest, const void *src, size_t len)
656 {
657         dest->insert(dest->end(), (u8 *)src, (u8 *)src + len);
658 }