@@ -518,7 +518,7 @@ struct VarIntFormatter
518518 }
519519};
520520
521- template <int Bytes>
521+ template <int Bytes, bool BigEndian = false >
522522struct CustomUintFormatter
523523{
524524 static_assert (Bytes > 0 && Bytes <= 8 , " CustomUintFormatter Bytes out of range" );
@@ -527,52 +527,30 @@ struct CustomUintFormatter
527527 template <typename Stream, typename I> void Ser (Stream& s, I v)
528528 {
529529 if (v < 0 || v > MAX) throw std::ios_base::failure (" CustomUintFormatter value out of range" );
530- uint64_t raw = htole64 (v);
531- s.write ((const char *)&raw, Bytes);
530+ if (BigEndian) {
531+ uint64_t raw = htobe64 (v);
532+ s.write (((const char *)&raw) + 8 - Bytes, Bytes);
533+ } else {
534+ uint64_t raw = htole64 (v);
535+ s.write ((const char *)&raw, Bytes);
536+ }
532537 }
533538
534539 template <typename Stream, typename I> void Unser (Stream& s, I& v)
535540 {
536541 static_assert (std::numeric_limits<I>::max () >= MAX && std::numeric_limits<I>::min () <= 0 , " CustomUintFormatter type too small" );
537542 uint64_t raw = 0 ;
538- s.read ((char *)&raw, Bytes);
539- v = le64toh (raw);
543+ if (BigEndian) {
544+ s.read (((char *)&raw) + 8 - Bytes, Bytes);
545+ v = be64toh (raw);
546+ } else {
547+ s.read ((char *)&raw, Bytes);
548+ v = le64toh (raw);
549+ }
540550 }
541551};
542552
543- /* * Serialization wrapper class for big-endian integers.
544- *
545- * Use this wrapper around integer types that are stored in memory in native
546- * byte order, but serialized in big endian notation. This is only intended
547- * to implement serializers that are compatible with existing formats, and
548- * its use is not recommended for new data structures.
549- *
550- * Only 16-bit types are supported for now.
551- */
552- template <typename I>
553- class BigEndian
554- {
555- protected:
556- I& m_val;
557- public:
558- explicit BigEndian (I& val) : m_val(val)
559- {
560- static_assert (std::is_unsigned<I>::value, " BigEndian type must be unsigned integer" );
561- 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" );
562- }
563-
564- template <typename Stream>
565- void Serialize (Stream& s) const
566- {
567- ser_writedata16be (s, m_val);
568- }
569-
570- template <typename Stream>
571- void Unserialize (Stream& s)
572- {
573- m_val = ser_readdata16be (s);
574- }
575- };
553+ template <int Bytes> using BigEndianFormatter = CustomUintFormatter<Bytes, true >;
576554
577555/* * Formatter for integers in CompactSize format. */
578556struct CompactSizeFormatter
@@ -626,9 +604,6 @@ class LimitedString
626604 }
627605};
628606
629- template <typename I>
630- BigEndian<I> WrapBigEndian (I& n) { return BigEndian<I>(n); }
631-
632607/* * Formatter to serialize/deserialize vector elements using another formatter
633608 *
634609 * Example:
0 commit comments