@@ -79,6 +79,11 @@ template<typename Stream> inline void ser_writedata16(Stream &s, uint16_t obj)
79
79
obj = htole16 (obj);
80
80
s.write ((char *)&obj, 2 );
81
81
}
82
+ template <typename Stream> inline void ser_writedata16be (Stream &s, uint16_t obj)
83
+ {
84
+ obj = htobe16 (obj);
85
+ s.write ((char *)&obj, 2 );
86
+ }
82
87
template <typename Stream> inline void ser_writedata32 (Stream &s, uint32_t obj)
83
88
{
84
89
obj = htole32 (obj);
@@ -101,6 +106,12 @@ template<typename Stream> inline uint16_t ser_readdata16(Stream &s)
101
106
s.read ((char *)&obj, 2 );
102
107
return le16toh (obj);
103
108
}
109
+ template <typename Stream> inline uint16_t ser_readdata16be (Stream &s)
110
+ {
111
+ uint16_t obj;
112
+ s.read ((char *)&obj, 2 );
113
+ return be16toh (obj);
114
+ }
104
115
template <typename Stream> inline uint32_t ser_readdata32 (Stream &s)
105
116
{
106
117
uint32_t obj;
@@ -411,6 +422,40 @@ class CVarInt
411
422
}
412
423
};
413
424
425
+ /* * Serialization wrapper class for big-endian integers.
426
+ *
427
+ * Use this wrapper around integer types that are stored in memory in native
428
+ * byte order, but serialized in big endian notation. This is only intended
429
+ * to implement serializers that are compatible with existing formats, and
430
+ * its use is not recommended for new data structures.
431
+ *
432
+ * Only 16-bit types are supported for now.
433
+ */
434
+ template <typename I>
435
+ class BigEndian
436
+ {
437
+ protected:
438
+ I& m_val;
439
+ public:
440
+ explicit BigEndian (I& val) : m_val(val)
441
+ {
442
+ static_assert (std::is_unsigned<I>::value, " BigEndian type must be unsigned integer" );
443
+ static_assert (sizeof (I) == 2 && std::numeric_limits<I>::min () == 0 && std::numeric_limits<I>::max () == std::numeric_limits<uint16_t >::max (), " Unsupported BigEndian size" );
444
+ }
445
+
446
+ template <typename Stream>
447
+ void Serialize (Stream& s) const
448
+ {
449
+ ser_writedata16be (s, m_val);
450
+ }
451
+
452
+ template <typename Stream>
453
+ void Unserialize (Stream& s)
454
+ {
455
+ m_val = ser_readdata16be (s);
456
+ }
457
+ };
458
+
414
459
class CCompactSize
415
460
{
416
461
protected:
@@ -461,6 +506,9 @@ class LimitedString
461
506
template <VarIntMode Mode=VarIntMode::DEFAULT, typename I>
462
507
CVarInt<Mode, I> WrapVarInt (I& n) { return CVarInt<Mode, I>{n}; }
463
508
509
+ template <typename I>
510
+ BigEndian<I> WrapBigEndian (I& n) { return BigEndian<I>(n); }
511
+
464
512
/* *
465
513
* Forward declarations
466
514
*/
0 commit comments