Debian Codegraph @

src/engine/serialize.h

raw symbols SCIP
1 /***************************************************************************
2 * fheroes2: https://github.com/ihhub/fheroes2 *
3 * Copyright (C) 2019 - 2025 *
4 * *
5 * Free Heroes2 Engine: http://sourceforge.net/projects/fheroes2 *
6 * Copyright (C) 2012 by Andrey Afletdinov <[email protected]> *
7 * *
8 * This program is free software; you can redistribute it and/or modify *
9 * it under the terms of the GNU General Public License as published by *
10 * the Free Software Foundation; either version 2 of the License, or *
11 * (at your option) any later version. *
12 * *
13 * This program is distributed in the hope that it will be useful, *
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
16 * GNU General Public License for more details. *
17 * *
18 * You should have received a copy of the GNU General Public License *
19 * along with this program; if not, write to the *
20 * Free Software Foundation, Inc., *
21 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
22 ***************************************************************************/
23
24 #pragma once
25
26 #include <algorithm>
27 #include <array>
28 #include <cassert>
29 #include <cstdint>
30 #include <cstdio>
31 #include <iterator>
32 #include <list>
33 #include <map>
34 #include <memory>
35 #include <optional>
36 #include <string>
37 #include <string_view>
38 #include <type_traits>
39 #include <utility>
40 #include <vector>
41
42 #if defined( __FreeBSD__ ) || defined( __OpenBSD__ )
43 #include <sys/endian.h>
44
45 #elif defined( _WIN32 )
46 #include <cstdlib>
47
48 #define BIG_ENDIAN 4321
49 #define LITTLE_ENDIAN 1234
50 #define BYTE_ORDER LITTLE_ENDIAN
51
52 #define htobe16( x ) _byteswap_ushort( x )
53 #define htole16( x ) ( x )
54 #define be16toh( x ) _byteswap_ushort( x )
55 #define le16toh( x ) ( x )
56 #define htobe32( x ) _byteswap_ulong( x )
57 #define htole32( x ) ( x )
58 #define be32toh( x ) _byteswap_ulong( x )
59 #define le32toh( x ) ( x )
60
61 #elif defined( __APPLE__ )
62 #include <libkern/OSByteOrder.h>
63 #define htobe16( x ) OSSwapHostToBigInt16( x )
64 #define htole16( x ) OSSwapHostToLittleInt16( x )
65 #define be16toh( x ) OSSwapBigToHostInt16( x )
66 #define le16toh( x ) OSSwapLittleToHostInt16( x )
67 #define htobe32( x ) OSSwapHostToBigInt32( x )
68 #define htole32( x ) OSSwapHostToLittleInt32( x )
69 #define be32toh( x ) OSSwapBigToHostInt32( x )
70 #define le32toh( x ) OSSwapLittleToHostInt32( x )
71
72 #elif defined( TARGET_PS_VITA )
73 #define BIG_ENDIAN 4321
74 #define LITTLE_ENDIAN 1234
75 #define BYTE_ORDER LITTLE_ENDIAN
76
77 #define htobe16( x ) __builtin_bswap16( x )
78 #define htole16( x ) ( x )
79 #define be16toh( x ) __builtin_bswap16( x )
80 #define le16toh( x ) ( x )
81 #define htobe32( x ) __builtin_bswap32( x )
82 #define htole32( x ) ( x )
83 #define be32toh( x ) __builtin_bswap32( x )
84 #define le32toh( x ) ( x )
85
86 #elif defined( TARGET_NINTENDO_SWITCH )
87 #include <machine/endian.h>
88 #define LITTLE_ENDIAN _LITTLE_ENDIAN
89 #define BIG_ENDIAN _BIG_ENDIAN
90 #define BYTE_ORDER _BYTE_ORDER
91 #define htobe16( x ) __bswap16( x )
92 #define htole16( x ) ( x )
93 #define be16toh( x ) __bswap16( x )
94 #define le16toh( x ) ( x )
95 #define htobe32( x ) __bswap32( x )
96 #define htole32( x ) ( x )
97 #define be32toh( x ) __bswap32( x )
98 #define le32toh( x ) ( x )
99
100 #else
101 // POSIX 1003.1-2024
102 // https://pubs.opengroup.org/onlinepubs/9799919799/basedefs/endian.h.html
103 #include <endian.h>
104
105 #endif
106
107 #include "math_base.h"
108
109 #define IS_BIGENDIAN ( BYTE_ORDER == BIG_ENDIAN )
110
111 // Base class for all I/O facilities
112 class StreamBase
113 {
114 public:
115 StreamBase( const StreamBase & ) = delete;
116
117 virtual ~StreamBase() = default;
118
119 StreamBase & operator=( const StreamBase & ) = delete;
120
121 void setFail()
122 {
123 setFail( true );
124 }
125
126 void setBigendian( bool f );
127
128 bool fail() const
129 {
130 return ( _flags & FAILURE ) != 0;
131 }
132
133 bool bigendian() const
134 {
135 return ( _flags & BIGENDIAN ) != 0;
136 }
137
138 protected:
139 StreamBase() = default;
140
141 void setFail( bool f );
142
143 private:
144 enum : uint32_t
145 {
146 FAILURE = 0x00000001,
147 BIGENDIAN = 0x00000002
148 };
149
150 uint32_t _flags{ 0 };
151 };
152
153 // Interface that declares the methods needed to read from a stream
154 class IStreamBase : virtual public StreamBase
155 {
156 public:
157 IStreamBase( const IStreamBase & ) = delete;
158
159 ~IStreamBase() override = default;
160
161 IStreamBase & operator=( const IStreamBase & ) = delete;
162
163 virtual void skip( size_t ) = 0;
164
165 virtual uint16_t getBE16() = 0;
166 virtual uint16_t getLE16() = 0;
167 virtual uint32_t getBE32() = 0;
168 virtual uint32_t getLE32() = 0;
169
170 // If a zero size is specified, then all still unread data is returned
171 virtual std::vector<uint8_t> getRaw( size_t ) = 0;
172
173 uint16_t get16();
174 uint32_t get32();
175
176 uint8_t get()
177 {
178 return get8();
179 }
180
181 IStreamBase & operator>>( bool & v );
182 IStreamBase & operator>>( char & v );
183 IStreamBase & operator>>( int8_t & v );
184 IStreamBase & operator>>( uint8_t & v );
185 IStreamBase & operator>>( int16_t & v );
186 IStreamBase & operator>>( uint16_t & v );
187 IStreamBase & operator>>( int32_t & v );
188 IStreamBase & operator>>( uint32_t & v );
189 IStreamBase & operator>>( std::string & v );
190
191 IStreamBase & operator>>( fheroes2::Point & v );
192
193 template <typename Type, std::enable_if_t<std::is_enum_v<Type>, bool> = true>
194 IStreamBase & operator>>( Type & v )
195 {
196 std::underlying_type_t<Type> temp{};
197 *this >> temp;
198
199 v = static_cast<Type>( temp );
200
201 return *this;
202 }
203
204 template <class Type1, class Type2>
205 IStreamBase & operator>>( std::pair<Type1, Type2> & v )
206 {
207 return *this >> v.first >> v.second;
208 }
209
210 template <class Type>
211 IStreamBase & operator>>( std::optional<Type> & v )
212 {
213 bool hasValue{};
214 *this >> hasValue;
215
216 if ( hasValue ) {
217 Type temp{};
218 *this >> temp;
219
220 v = std::move( temp );
221 }
222 else {
223 v = {};
224 }
225
226 return *this;
227 }
228
229 template <class Type>
230 IStreamBase & operator>>( std::vector<Type> & v )
231 {
232 v.resize( get32() );
233
234 std::for_each( v.begin(), v.end(), [this]( auto & item ) { *this >> item; } );
235
236 return *this;
237 }
238
239 template <class Type>
240 IStreamBase & operator>>( std::list<Type> & v )
241 {
242 v.resize( get32() );
243
244 std::for_each( v.begin(), v.end(), [this]( auto & item ) { *this >> item; } );
245
246 return *this;
247 }
248
249 template <class Type1, class Type2>
250 IStreamBase & operator>>( std::map<Type1, Type2> & v )
251 {
252 const uint32_t size = get32();
253
254 v.clear();
255
256 for ( uint32_t i = 0; i < size; ++i ) {
257 std::pair<Type1, Type2> temp{};
258
259 *this >> temp;
260
261 v.emplace( std::move( temp ) );
262 }
263
264 return *this;
265 }
266
267 template <class Type, size_t Count>
268 IStreamBase & operator>>( std::array<Type, Count> & v )
269 {
270 const uint32_t size = get32();
271 if ( size != v.size() ) {
272 setFail();
273
274 v = {};
275
276 return *this;
277 }
278
279 std::for_each( v.begin(), v.end(), [this]( auto & item ) { *this >> item; } );
280
281 return *this;
282 }
283
284 protected:
285 IStreamBase() = default;
286
287 virtual uint8_t get8() = 0;
288 };
289
290 // Interface that declares the methods needed to write to a stream
291 class OStreamBase : virtual public StreamBase
292 {
293 public:
294 OStreamBase( const OStreamBase & ) = delete;
295
296 ~OStreamBase() override = default;
297
298 OStreamBase & operator=( const OStreamBase & ) = delete;
299
300 virtual void putBE16( uint16_t ) = 0;
301 virtual void putLE16( uint16_t ) = 0;
302 virtual void putBE32( uint32_t ) = 0;
303 virtual void putLE32( uint32_t ) = 0;
304
305 virtual void putRaw( const void *, size_t ) = 0;
306
307 void put16( uint16_t );
308 void put32( uint32_t );
309
310 void put( const uint8_t ch )
311 {
312 put8( ch );
313 }
314
315 OStreamBase & operator<<( const bool v );
316 OStreamBase & operator<<( const char v );
317 OStreamBase & operator<<( const int8_t v );
318 OStreamBase & operator<<( const uint8_t v );
319 OStreamBase & operator<<( const int16_t v );
320 OStreamBase & operator<<( const uint16_t v );
321 OStreamBase & operator<<( const int32_t v );
322 OStreamBase & operator<<( const uint32_t v );
323 OStreamBase & operator<<( const std::string_view v );
324
325 OStreamBase & operator<<( const fheroes2::Point & v );
326
327 template <typename Type, std::enable_if_t<std::is_enum_v<Type>, bool> = true>
328 OStreamBase & operator<<( const Type v )
329 {
330 return *this << static_cast<std::underlying_type_t<Type>>( v );
331 }
332
333 template <class Type1, class Type2>
334 OStreamBase & operator<<( const std::pair<Type1, Type2> & v )
335 {
336 return *this << v.first << v.second;
337 }
338
339 template <class Type>
340 OStreamBase & operator<<( const std::optional<Type> & v )
341 {
342 const bool hasValue = v.has_value();
343 *this << hasValue;
344
345 if ( hasValue ) {
346 *this << *v;
347 }
348
349 return *this;
350 }
351
352 template <class Type>
353 OStreamBase & operator<<( const std::vector<Type> & v )
354 {
355 put32( static_cast<uint32_t>( v.size() ) );
356
357 std::for_each( v.begin(), v.end(), [this]( const auto & item ) { *this << item; } );
358
359 return *this;
360 }
361
362 template <class Type>
363 OStreamBase & operator<<( const std::list<Type> & v )
364 {
365 put32( static_cast<uint32_t>( v.size() ) );
366
367 std::for_each( v.begin(), v.end(), [this]( const auto & item ) { *this << item; } );
368
369 return *this;
370 }
371
372 template <class Type1, class Type2>
373 OStreamBase & operator<<( const std::map<Type1, Type2> & v )
374 {
375 put32( static_cast<uint32_t>( v.size() ) );
376
377 std::for_each( v.begin(), v.end(), [this]( const auto & item ) { *this << item; } );
378
379 return *this;
380 }
381
382 template <class Type, size_t Count>
383 OStreamBase & operator<<( const std::array<Type, Count> & v )
384 {
385 put32( static_cast<uint32_t>( v.size() ) );
386
387 std::for_each( v.begin(), v.end(), [this]( const auto & item ) { *this << item; } );
388
389 return *this;
390 }
391
392 protected:
393 OStreamBase() = default;
394
395 virtual void put8( const uint8_t ) = 0;
396 };
397
398 // Interface that declares a stream with an in-memory storage backend that can be read from
399 class IStreamBuf : public IStreamBase
400 {
401 public:
402 virtual const uint8_t * data() const = 0;
403 virtual size_t size() const = 0;
404
405 protected:
406 IStreamBuf() = default;
407 };
408
409 // Class template for a stream with an in-memory storage backend that can store either const or non-const data as desired
410 template <typename T, std::enable_if_t<std::is_same_v<T, uint8_t> || std::is_same_v<T, const uint8_t>, bool> = true>
411 class StreamBufTmpl : public IStreamBuf
412 {
413 public:
414 StreamBufTmpl( const StreamBufTmpl & ) = delete;
415
416 ~StreamBufTmpl() override = default;
417
418 StreamBufTmpl & operator=( const StreamBufTmpl & ) = delete;
419
420 const uint8_t * data() const override
421 {
422 return _itget;
423 }
424
425 size_t size() const override
426 {
427 return sizeg();
428 }
429
430 size_t tell() const
431 {
432 return tellg();
433 }
434
435 void seek( const size_t pos )
436 {
437 assert( _itbeg <= _itput );
438
439 const size_t putPos = _itput - _itbeg;
440
441 _itget = ( pos < putPos ? _itbeg + pos : _itput );
442 }
443
444 void skip( size_t size ) override
445 {
446 _itget += ( size < sizeg() ? size : sizeg() );
447 }
448
449 uint16_t getBE16() override
450 {
451 uint16_t v = ( static_cast<uint16_t>( get8() ) << 8 );
452
453 v |= get8();
454
455 return v;
456 }
457
458 uint16_t getLE16() override
459 {
460 uint16_t v = get8();
461
462 v |= ( static_cast<uint16_t>( get8() ) << 8 );
463
464 return v;
465 }
466
467 uint32_t getBE32() override
468 {
469 uint32_t v = ( static_cast<uint32_t>( get8() ) << 24 );
470
471 v |= ( static_cast<uint32_t>( get8() ) << 16 );
472 v |= ( static_cast<uint32_t>( get8() ) << 8 );
473 v |= get8();
474
475 return v;
476 }
477
478 uint32_t getLE32() override
479 {
480 uint32_t v = get8();
481
482 v |= ( static_cast<uint32_t>( get8() ) << 8 );
483 v |= ( static_cast<uint32_t>( get8() ) << 16 );
484 v |= ( static_cast<uint32_t>( get8() ) << 24 );
485
486 return v;
487 }
488
489 // If a zero size is specified, then all still unread data is returned
490 std::vector<uint8_t> getRaw( size_t size ) override
491 {
492 const size_t remainSize = sizeg();
493 const size_t resultSize = size > 0 ? size : remainSize;
494 const size_t sizeToCopy = std::min( resultSize, remainSize );
495
496 std::vector<uint8_t> v( resultSize, 0 );
497
498 std::copy( _itget, _itget + sizeToCopy, v.data() );
499
500 _itget += sizeToCopy;
501
502 return v;
503 }
504
505 // Reads no more than 'size' bytes of data (if a zero size is specified, then all still unread data
506 // is read), forms a string that ends with the first null character found in this data (or includes
507 // all data if this data does not contain null characters), and returns this string
508 std::string getString( const size_t size = 0 )
509 {
510 const size_t remainSize = sizeg();
511 const size_t sizeToSkip = size > 0 ? std::min( size, remainSize ) : remainSize;
512
513 T * strBeg = _itget;
514 _itget += sizeToSkip;
515
516 return { strBeg, std::find( strBeg, _itget, 0 ) };
517 }
518
519 protected:
520 StreamBufTmpl() = default;
521
522 size_t sizeg() const
523 {
524 assert( _itget <= _itput );
525
526 return _itput - _itget;
527 }
528
529 size_t tellg() const
530 {
531 assert( _itbeg <= _itget );
532
533 return _itget - _itbeg;
534 }
535
536 uint8_t get8() override
537 {
538 if ( sizeg() > 0 ) {
539 return *( _itget++ );
540 }
541
542 setFail();
543
544 return 0;
545 }
546
547 size_t capacity() const
548 {
549 assert( _itbeg <= _itend );
550
551 return _itend - _itbeg;
552 }
553
554 T * _itbeg{ nullptr };
555 T * _itget{ nullptr };
556 T * _itput{ nullptr };
557 T * _itend{ nullptr };
558 };
559
560 // Stream with a dynamically-sized in-memory storage backend that supports both reading and writing
561 class RWStreamBuf final : public StreamBufTmpl<uint8_t>, public OStreamBase
562 {
563 public:
564 RWStreamBuf()
565 : RWStreamBuf( 0 )
566 {}
567
568 explicit RWStreamBuf( const size_t size );
569
570 RWStreamBuf( const RWStreamBuf & ) = delete;
571
572 ~RWStreamBuf() override = default;
573
574 RWStreamBuf & operator=( const RWStreamBuf & ) = delete;
575
576 void putBE32( uint32_t v ) override;
577 void putLE32( uint32_t v ) override;
578 void putBE16( uint16_t v ) override;
579 void putLE16( uint16_t v ) override;
580
581 void putRaw( const void * ptr, size_t size ) override;
582
583 private:
584 void put8( const uint8_t v ) override;
585
586 size_t sizep() const;
587 size_t tellp() const;
588
589 void reallocBuf( size_t size );
590
591 std::unique_ptr<uint8_t[]> _buf;
592 };
593
594 // Stream with read-only in-memory storage backed by a const vector instance (either internal or external, depending on the constructor used)
595 class ROStreamBuf final : public StreamBufTmpl<const uint8_t>
596 {
597 public:
598 // Creates a non-owning stream on top of an external buffer ("view mode")
599 explicit ROStreamBuf( const std::vector<uint8_t> & buf );
600 // Takes ownership of the given buffer (through the move operation) and creates a stream on top of it
601 explicit ROStreamBuf( std::vector<uint8_t> && buf );
602
603 ROStreamBuf( const ROStreamBuf & ) = delete;
604
605 ~ROStreamBuf() override = default;
606
607 ROStreamBuf & operator=( const ROStreamBuf & ) = delete;
608
609 // If a zero size is specified, then a view of all still unread data is returned
610 std::pair<const uint8_t *, size_t> getRawView( const size_t size = 0 );
611
612 // Returns a string view of no more than 'size' bytes of data ending with the first null character found in
613 // this data (or of all the data in the corresponding range if this data does not contain null characters).
614 // If a zero size is specified, then the entire unread amount of data is considered. Advances the cursor
615 // intended for reading data forward by the full amount of the data used (regardless of the presence of null
616 // characters in this data).
617 std::string_view getStringView( const size_t size = 0 );
618
619 private:
620 // Buffer to which the transfer of ownership of the external buffer takes place. This buffer is not used in
621 // the non-owning ("view") mode.
622 const std::vector<uint8_t> _buf;
623 };
624
625 // Stream with a file storage backend that supports both reading and writing
626 class StreamFile final : public IStreamBase, public OStreamBase
627 {
628 public:
629 StreamFile() = default;
630
631 StreamFile( const StreamFile & ) = delete;
632
633 ~StreamFile() override = default;
634
635 StreamFile & operator=( const StreamFile & ) = delete;
636
637 size_t size();
638 size_t tell();
639
640 bool open( const std::string & fn, const std::string & mode );
641 void close();
642
643 // If a zero size is specified, then all still unread data is returned
644 ROStreamBuf getStreamBuf( const size_t size = 0 );
645
646 void seek( const size_t pos );
647 void skip( size_t size ) override;
648
649 uint16_t getBE16() override;
650 uint16_t getLE16() override;
651 uint32_t getBE32() override;
652 uint32_t getLE32() override;
653
654 void putBE16( uint16_t v ) override;
655 void putLE16( uint16_t v ) override;
656 void putBE32( uint32_t v ) override;
657 void putLE32( uint32_t v ) override;
658
659 // If a zero size is specified, then all still unread data is returned
660 std::vector<uint8_t> getRaw( const size_t size ) override;
661
662 void putRaw( const void * ptr, size_t size ) override;
663
664 // Reads no more than 'size' bytes of data (if a zero size is specified, then all still unread data
665 // is read), forms a string that ends with the first null character found in this data (or includes
666 // all data if this data does not contain null characters), and returns this string
667 std::string getString( const size_t size = 0 );
668
669 private:
670 size_t sizeg();
671
672 uint8_t get8() override;
673 void put8( const uint8_t v ) override;
674
675 template <typename T>
676 T getUint()
677 {
678 if ( !_file ) {
679 return 0;
680 }
681
682 T v;
683
684 if ( std::fread( &v, sizeof( T ), 1, _file.get() ) != 1 ) {
685 setFail();
686
687 return 0;
688 }
689
690 return v;
691 }
692
693 template <typename T>
694 void putUint( const T v )
695 {
696 if ( !_file ) {
697 return;
698 }
699
700 if ( std::fwrite( &v, sizeof( T ), 1, _file.get() ) != 1 ) {
701 setFail();
702 }
703 }
704
705 static int closeFile( std::FILE * f );
706
707 std::unique_ptr<std::FILE, int ( * )( std::FILE * )> _file{ nullptr, closeFile };
708 };
709
710 namespace fheroes2
711 {
712 // Get a value of type T in the system byte order from the buffer in which it was originally stored in the little-endian byte order
713 template <typename T, std::enable_if_t<std::is_integral_v<T> || std::is_floating_point_v<T>, bool> = true>
714 T getLEValue( const char * data, const size_t base, const size_t offset = 0 )
715 {
716 const char * begin = data + base + offset * sizeof( T );
717 const char * end = begin + sizeof( T );
718
719 T v;
720
721 #if defined( BYTE_ORDER ) && defined( LITTLE_ENDIAN ) && BYTE_ORDER == LITTLE_ENDIAN
722 std::copy( begin, end, reinterpret_cast<char *>( &v ) );
723 #elif defined( BYTE_ORDER ) && defined( BIG_ENDIAN ) && BYTE_ORDER == BIG_ENDIAN
724 std::reverse_copy( begin, end, reinterpret_cast<char *>( &v ) );
725 #else
726 #error "Unknown byte order"
727 #endif
728
729 return v;
730 }
731 }