From f37311a3f1652eda11f67f408e586a780b269efe Mon Sep 17 00:00:00 2001 From: Jason Volk Date: Thu, 21 Dec 2017 14:25:50 -0700 Subject: [PATCH] ircd::util: Add an endian bswap; add more data()/size() participants. --- include/ircd/util.h | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/include/ircd/util.h b/include/ircd/util.h index afc14fb79..c67c4f1c7 100644 --- a/include/ircd/util.h +++ b/include/ircd/util.h @@ -404,6 +404,13 @@ size(const std::array &buf) return SIZE; } +template +constexpr typename std::enable_if::value, size_t>::type +size(const T &val) +{ + return sizeof(T); +} + template constexpr const char * @@ -419,6 +426,20 @@ data(char (&buf)[SIZE]) return buf; } +template +constexpr typename std::enable_if::value, const uint8_t *>::type +data(const T &val) +{ + return reinterpret_cast(&val); +} + +template +constexpr typename std::enable_if::value, uint8_t *>::type +data(T &val) +{ + return reinterpret_cast(&val); +} + template auto @@ -1044,5 +1065,24 @@ is_powerof2(const long long v) } +template +T & +bswap(T *const &val) +{ + assert(val != nullptr); + std::reverse(data(*val), data(*val) + size(*val)); + return *val; +} + +template +T +bswap(const T &val) +{ + T ret; + std::reverse_copy(data(val), data(val) + size(val), data(ret)); + return ret; +} + + } // namespace util } // namespace ircd