-
Notifications
You must be signed in to change notification settings - Fork 0
/
fast_endianless.hpp
61 lines (46 loc) · 1.59 KB
/
fast_endianless.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#pragma once
#include <arpa/inet.h>
#if defined(__APPLE__)
#include <libkern/OSByteOrder.h>
// Source: https://gist.github.com/pavel-odintsov/d13684600423d1c5e64e
#define be64toh(x) OSSwapBigToHostInt64(x)
#define htobe64(x) OSSwapHostToBigInt64(x)
#endif
// For be64toh and htobe64
#if defined(__FreeBSD__) || defined(__DragonFly__)
#include <sys/endian.h>
#endif
// Linux standard functions for endian conversions are ugly because there are no checks about arguments length
// And you could accidentally use ntohs (suitable only for 16 bit) for 32 or 64 bit value and nobody will warning you
// With this wrapper functions it's pretty complicated to use them for incorrect length type! :)
// Type safe versions of ntohl, ntohs with type control
inline uint16_t fast_ntoh(uint16_t value) {
return ntohs(value);
}
inline uint32_t fast_ntoh(uint32_t value) {
return ntohl(value);
}
inline int32_t fast_ntoh(int32_t value) {
return ntohl(value);
}
// network (big endian) byte order to host byte order
inline uint64_t fast_ntoh(uint64_t value) {
return be64toh(value);
}
// Type safe version of htonl, htons
inline uint16_t fast_hton(uint16_t value) {
return htons(value);
}
inline uint32_t fast_hton(uint32_t value) {
return htonl(value);
}
inline int32_t fast_hton(int32_t value) {
return htonl(value);
}
inline uint64_t fast_hton(uint64_t value) {
// host to big endian (network byte order)
return htobe64(value);
}
// Explicitly remove all other types to avoid implicit conversion
template <class T> void fast_ntoh(T) = delete;
template <class T> void fast_hton(T) = delete;