Ratan Gupta | 37a7a07 | 2016-12-14 00:51:23 +0530 | [diff] [blame] | 1 | #pragma once |
| 2 | |
| 3 | #include <endian.h> |
| 4 | #include <stdint.h> |
| 5 | |
| 6 | namespace endian |
| 7 | { |
| 8 | namespace details |
| 9 | { |
| 10 | template <typename T> |
| 11 | struct convert |
| 12 | { |
| 13 | static T to_network(T) = delete; |
| 14 | static T from_network(T) = delete; |
| 15 | }; |
| 16 | |
Patrick Venture | 537ff14 | 2018-11-01 16:37:09 -0700 | [diff] [blame] | 17 | template <> |
| 18 | struct convert<uint16_t> |
Ratan Gupta | 37a7a07 | 2016-12-14 00:51:23 +0530 | [diff] [blame] | 19 | { |
| 20 | static uint16_t to_network(uint16_t i) |
| 21 | { |
| 22 | return htobe16(i); |
| 23 | }; |
| 24 | static uint16_t from_network(uint16_t i) |
| 25 | { |
| 26 | return be16toh(i); |
| 27 | }; |
| 28 | }; |
| 29 | |
Patrick Venture | 537ff14 | 2018-11-01 16:37:09 -0700 | [diff] [blame] | 30 | template <> |
| 31 | struct convert<uint32_t> |
Ratan Gupta | 37a7a07 | 2016-12-14 00:51:23 +0530 | [diff] [blame] | 32 | { |
| 33 | static uint32_t to_network(uint32_t i) |
| 34 | { |
| 35 | return htobe32(i); |
| 36 | }; |
| 37 | static uint32_t from_network(uint32_t i) |
| 38 | { |
| 39 | return be32toh(i); |
| 40 | }; |
| 41 | }; |
Patrick Venture | 537ff14 | 2018-11-01 16:37:09 -0700 | [diff] [blame] | 42 | } // namespace details |
| 43 | template <typename T> |
| 44 | T to_network(T i) |
Ratan Gupta | 37a7a07 | 2016-12-14 00:51:23 +0530 | [diff] [blame] | 45 | { |
| 46 | return details::convert<T>::to_network(i); |
| 47 | } |
Patrick Venture | 537ff14 | 2018-11-01 16:37:09 -0700 | [diff] [blame] | 48 | template <typename T> |
| 49 | T from_network(T i) |
Ratan Gupta | 37a7a07 | 2016-12-14 00:51:23 +0530 | [diff] [blame] | 50 | { |
| 51 | return details::convert<T>::from_network(i); |
| 52 | } |
Patrick Venture | 537ff14 | 2018-11-01 16:37:09 -0700 | [diff] [blame] | 53 | } // namespace endian |