diff options
Diffstat (limited to 'odb/pgsql/endian-traits.hxx')
-rw-r--r-- | odb/pgsql/endian-traits.hxx | 169 |
1 files changed, 99 insertions, 70 deletions
diff --git a/odb/pgsql/endian-traits.hxx b/odb/pgsql/endian-traits.hxx index 07dc023..2dc79f3 100644 --- a/odb/pgsql/endian-traits.hxx +++ b/odb/pgsql/endian-traits.hxx @@ -6,103 +6,132 @@ #ifndef ODB_PGSQL_ENDIAN_TRAITS_HXX #define ODB_PGSQL_ENDIAN_TRAITS_HXX +#include <cstddef> // std::size_t #include <algorithm> // std::reverse namespace odb { namespace pgsql { - template <typename T, int S = sizeof (T)> - struct swap_endian; - - template <typename T> - struct swap_endian<T, 2> + namespace details { - static T - swap (T x) + template <typename T, std::size_t S = sizeof (T)> + struct swap_endian; + + template <typename T> + struct swap_endian<T, 2> { - union u2 + static T + swap (T x) { - T t; - char c[2]; - }; + union u2 + { + T t; + char c[2]; + }; - u2 u; - u.t = x; - std::reverse (u.c, u.c + 2); + u2 u; + u.t = x; - return u.t; - } - }; + char tmp (u.c[0]); + u.c[0] = u.c[1]; + u.c[1] = tmp; - template <typename T> - struct swap_endian<T, 4> - { - static T - swap (T x) + return u.t; + } + }; + + template <typename T> + struct swap_endian<T, 4> { - union u4 + static T + swap (T x) { - T t; - char c[4]; - }; + union u4 + { + T t; + char c[4]; + }; - u4 u; - u.t = x; - std::reverse (u.c, u.c + 4); + u4 u; + u.t = x; - return u.t; - } - }; + char tmp (u.c[0]); + u.c[0] = u.c[3]; + u.c[3] = tmp; - template <typename T> - struct swap_endian<T, 8> - { - static T - swap (T x) + tmp = u.c[1]; + u.c[1] = u.c[2]; + u.c[2] = tmp; + + return u.t; + } + }; + + template <typename T> + struct swap_endian<T, 8> { - union u8 + static T + swap (T x) { - T t; - char c[8]; - }; + union u8 + { + T t; + char c[8]; + }; - u8 u; - u.t = x; - std::reverse (u.c, u.c + 8); + u8 u; + u.t = x; - return u.t; - } - }; + char tmp (u.c[0]); + u.c[0] = u.c[7]; + u.c[7] = tmp; - class endian_traits - { - public: - enum endian - { - big_endian, - little_endian - }; + tmp = u.c[1]; + u.c[1] = u.c[6]; + u.c[6] = tmp; - public: - static const endian host_endian; + tmp = u.c[2]; + u.c[2] = u.c[5]; + u.c[5] = tmp; - public: + tmp = u.c[3]; + u.c[3] = u.c[4]; + u.c[4] = tmp; - template <typename T> - static T - hton (T x) - { - return host_endian == big_endian ? x : swap_endian<T>::swap (x); - } + return u.t; + } + }; - template <typename T> - static T - ntoh (T x) + class endian_traits { - return host_endian == big_endian ? x : swap_endian<T>::swap (x); - } - }; + public: + enum endian + { + big, + little + }; + + public: + static const endian host_endian; + + public: + + template <typename T> + static T + hton (T x) + { + return host_endian == big ? x : swap_endian<T>::swap (x); + } + + template <typename T> + static T + ntoh (T x) + { + return host_endian == big ? x : swap_endian<T>::swap (x); + } + }; + } } } |