0
0
Fork 0
mirror of https://github.com/matrix-construct/construct synced 2025-01-13 08:23:56 +01:00

ircd::util: Add specific endian bswaps e.g arpa/inet.h; minor cleanup.

This commit is contained in:
Jason Volk 2018-07-01 16:31:46 -07:00
parent c26255290b
commit d1c1fb931f

View file

@ -13,8 +13,102 @@
namespace ircd::util
{
template<class T> T &bswap(T *const &val);
template<class T> T bswap(const T &val);
template<class T> T &bswap(T *const &);
template<class T> T bswap(T);
// Host <-> network endian
template<class T> T hton(T);
template<class T> T ntoh(T);
// Convenience host to network interface for arpa/inet.h compat
uint32_t htonl(const uint32_t &);
uint16_t htons(const uint16_t &);
double htond(const double &);
float htonf(const float &);
// Convenience network to host interface for arpa/inet.h compat
uint32_t ntohl(const uint32_t &);
uint16_t ntohs(const uint16_t &);
double ntohd(const double &);
float ntohf(const float &);
}
inline float
ircd::util::ntohf(const float &a)
{
return ntoh(a);
}
inline double
ircd::util::ntohd(const double &a)
{
return ntoh(a);
}
inline uint32_t
ircd::util::ntohl(const uint32_t &a)
{
return ntoh(a);
}
inline uint16_t
ircd::util::ntohs(const uint16_t &a)
{
return ntoh(a);
}
inline float
ircd::util::htonf(const float &a)
{
return hton(a);
}
inline double
ircd::util::htond(const double &a)
{
return hton(a);
}
inline uint32_t
ircd::util::htonl(const uint32_t &a)
{
return hton(a);
}
inline uint16_t
ircd::util::htons(const uint16_t &a)
{
return hton(a);
}
template<class T>
T
ircd::util::hton(T a)
{
#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
return bswap(&a);
#else
return a;
#endif
}
template<class T>
T
ircd::util::ntoh(T a)
{
#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
return bswap(&a);
#else
return a;
#endif
}
/// Reverse endian of T returning value copy
template<class T>
T
ircd::util::bswap(T ret)
{
return bswap(&ret);
}
/// Reverse endian of data pointed to; return reference
@ -23,19 +117,11 @@ T &
ircd::util::bswap(T *const &val)
{
assert(val != nullptr);
const auto ptr{reinterpret_cast<uint8_t *>(val)};
const auto &ptr
{
reinterpret_cast<uint8_t *const &>(val)
};
std::reverse(ptr, ptr + sizeof(T));
return *val;
}
/// Reverse endian of T returning value copy
template<class T>
T
ircd::util::bswap(const T &val)
{
T ret;
const auto valptr{reinterpret_cast<const uint8_t *>(&val)};
const auto retptr{reinterpret_cast<uint8_t *>(&ret)};
std::reverse_copy(valptr, valptr + sizeof(T), retptr);
return ret;
}