@@ -547,7 +547,7 @@ struct VarIntFormatter
547547 }
548548};
549549
550- template <int Bytes>
550+ template <int Bytes, bool BigEndian = false >
551551struct CustomUintFormatter
552552{
553553 static_assert (Bytes > 0 && Bytes <= 8 , " CustomUintFormatter Bytes out of range" );
@@ -556,52 +556,30 @@ struct CustomUintFormatter
556556 template <typename Stream, typename I> void Ser (Stream& s, I v)
557557 {
558558 if (v < 0 || v > MAX) throw std::ios_base::failure (" CustomUintFormatter value out of range" );
559- uint64_t raw = htole64 (v);
560- s.write ((const char *)&raw, Bytes);
559+ if (BigEndian) {
560+ uint64_t raw = htobe64 (v);
561+ s.write (((const char *)&raw) + 8 - Bytes, Bytes);
562+ } else {
563+ uint64_t raw = htole64 (v);
564+ s.write ((const char *)&raw, Bytes);
565+ }
561566 }
562567
563568 template <typename Stream, typename I> void Unser (Stream& s, I& v)
564569 {
565570 static_assert (std::numeric_limits<I>::max () >= MAX && std::numeric_limits<I>::min () <= 0 , " CustomUintFormatter type too small" );
566571 uint64_t raw = 0 ;
567- s.read ((char *)&raw, Bytes);
568- v = le64toh (raw);
572+ if (BigEndian) {
573+ s.read (((char *)&raw) + 8 - Bytes, Bytes);
574+ v = be64toh (raw);
575+ } else {
576+ s.read ((char *)&raw, Bytes);
577+ v = le64toh (raw);
578+ }
569579 }
570580};
571581
572- /* * Serialization wrapper class for big-endian integers.
573- *
574- * Use this wrapper around integer types that are stored in memory in native
575- * byte order, but serialized in big endian notation. This is only intended
576- * to implement serializers that are compatible with existing formats, and
577- * its use is not recommended for new data structures.
578- *
579- * Only 16-bit types are supported for now.
580- */
581- template <typename I>
582- class BigEndian
583- {
584- protected:
585- I& m_val;
586- public:
587- explicit BigEndian (I& val) : m_val(val)
588- {
589- static_assert (std::is_unsigned<I>::value, " BigEndian type must be unsigned integer" );
590- 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" );
591- }
592-
593- template <typename Stream>
594- void Serialize (Stream& s) const
595- {
596- ser_writedata16be (s, m_val);
597- }
598-
599- template <typename Stream>
600- void Unserialize (Stream& s)
601- {
602- m_val = ser_readdata16be (s);
603- }
604- };
582+ template <int Bytes> using BigEndianFormatter = CustomUintFormatter<Bytes, true >;
605583
606584/* * Formatter for integers in CompactSize format. */
607585struct CompactSizeFormatter
@@ -656,9 +634,6 @@ class LimitedString
656634 }
657635};
658636
659- template <typename I>
660- BigEndian<I> WrapBigEndian (I& n) { return BigEndian<I>(n); }
661-
662637/* * Formatter to serialize/deserialize vector elements using another formatter
663638 *
664639 * Example:
0 commit comments