diff --git a/src/netaddress.h b/src/netaddress.h index b7381c1eb4..53d9c52a52 100644 --- a/src/netaddress.h +++ b/src/netaddress.h @@ -176,7 +176,7 @@ class CService : public CNetAddr template inline void SerializationOp(Stream& s, Operation ser_action) { READWRITE(ip); - READWRITE(WrapBigEndian(port)); + READWRITE(Using>(port)); } }; diff --git a/src/serialize.h b/src/serialize.h index 5045cb3c7f..7ee9556dc1 100644 --- a/src/serialize.h +++ b/src/serialize.h @@ -518,7 +518,7 @@ struct VarIntFormatter } }; -template +template struct CustomUintFormatter { static_assert(Bytes > 0 && Bytes <= 8, "CustomUintFormatter Bytes out of range"); @@ -527,52 +527,30 @@ struct CustomUintFormatter template void Ser(Stream& s, I v) { if (v < 0 || v > MAX) throw std::ios_base::failure("CustomUintFormatter value out of range"); - uint64_t raw = htole64(v); - s.write((const char*)&raw, Bytes); + if (BigEndian) { + uint64_t raw = htobe64(v); + s.write(((const char*)&raw) + 8 - Bytes, Bytes); + } else { + uint64_t raw = htole64(v); + s.write((const char*)&raw, Bytes); + } } template void Unser(Stream& s, I& v) { static_assert(std::numeric_limits::max() >= MAX && std::numeric_limits::min() <= 0, "CustomUintFormatter type too small"); uint64_t raw = 0; - s.read((char*)&raw, Bytes); - v = le64toh(raw); + if (BigEndian) { + s.read(((char*)&raw) + 8 - Bytes, Bytes); + v = be64toh(raw); + } else { + s.read((char*)&raw, Bytes); + v = le64toh(raw); + } } }; -/** Serialization wrapper class for big-endian integers. - * - * Use this wrapper around integer types that are stored in memory in native - * byte order, but serialized in big endian notation. This is only intended - * to implement serializers that are compatible with existing formats, and - * its use is not recommended for new data structures. - * - * Only 16-bit types are supported for now. - */ -template -class BigEndian -{ -protected: - I& m_val; -public: - explicit BigEndian(I& val) : m_val(val) - { - static_assert(std::is_unsigned::value, "BigEndian type must be unsigned integer"); - static_assert(sizeof(I) == 2 && std::numeric_limits::min() == 0 && std::numeric_limits::max() == std::numeric_limits::max(), "Unsupported BigEndian size"); - } - - template - void Serialize(Stream& s) const - { - ser_writedata16be(s, m_val); - } - - template - void Unserialize(Stream& s) - { - m_val = ser_readdata16be(s); - } -}; +template using BigEndianFormatter = CustomUintFormatter; /** Formatter for integers in CompactSize format. */ struct CompactSizeFormatter @@ -626,9 +604,6 @@ public: } }; -template -BigEndian WrapBigEndian(I& n) { return BigEndian(n); } - /** Formatter to serialize/deserialize vector elements using another formatter * * Example: