From fa16a96443f4b3a7b62ca05338e88d0ce13a849f Mon Sep 17 00:00:00 2001 From: Dan Goodliffe Date: Sun, 8 Oct 2023 18:59:35 +0100 Subject: Move valueAs to BinaryColumn, implement with std::byteswap Removes the need to cast to/from BSD endian supported types. --- libpqpp/pq-binarycolumn.cpp | 19 ++++++++++++++++--- libpqpp/pq-binarycolumn.h | 3 +++ libpqpp/pq-column.h | 9 --------- 3 files changed, 19 insertions(+), 12 deletions(-) (limited to 'libpqpp') diff --git a/libpqpp/pq-binarycolumn.cpp b/libpqpp/pq-binarycolumn.cpp index 514a145..761bf0b 100644 --- a/libpqpp/pq-binarycolumn.cpp +++ b/libpqpp/pq-binarycolumn.cpp @@ -2,6 +2,7 @@ #include "column.h" #include "dbTypes.h" #include "pq-column.h" +#include #include #include #include @@ -9,6 +10,18 @@ PQ::BinaryColumn::BinaryColumn(const PQ::SelectBase * s, unsigned int f) : PQ::Column(s, f) { } +template +inline T +PQ::BinaryColumn::valueAs() const +{ + T v {}; + std::memcpy(&v, value(), sizeof(T)); + if constexpr (std::endian::native != std::endian::big && sizeof(T) > 1) { + return std::byteswap(v); + } + return v; +} + void PQ::BinaryColumn::apply(DB::HandleField & h) const { @@ -27,13 +40,13 @@ PQ::BinaryColumn::apply(DB::HandleField & h) const h.boolean(valueAs()); break; case INT2OID: - h.integer(static_cast(be16toh(valueAs()))); + h.integer(valueAs()); break; case INT4OID: - h.integer(static_cast(be32toh(valueAs()))); + h.integer(valueAs()); break; case INT8OID: - h.integer(static_cast(be64toh(valueAs()))); + h.integer(valueAs()); break; case BYTEAOID: h.blob(DB::Blob(value(), length())); diff --git a/libpqpp/pq-binarycolumn.h b/libpqpp/pq-binarycolumn.h index e2a8044..e44d7e2 100644 --- a/libpqpp/pq-binarycolumn.h +++ b/libpqpp/pq-binarycolumn.h @@ -15,6 +15,9 @@ namespace PQ { BinaryColumn(const SelectBase *, unsigned int field); void apply(DB::HandleField &) const override; + + private: + template [[nodiscard]] inline T valueAs() const; }; } diff --git a/libpqpp/pq-column.h b/libpqpp/pq-column.h index 6bf2669..fa4a78a 100644 --- a/libpqpp/pq-column.h +++ b/libpqpp/pq-column.h @@ -17,15 +17,6 @@ namespace PQ { void apply(DB::HandleField &) const override; protected: - template - inline T - valueAs() const - { - T v {}; - std::memcpy(&v, value(), sizeof(T)); - return v; - } - const char * value() const; std::size_t length() const; -- cgit v1.2.3