forked from rui314/mold
-
Notifications
You must be signed in to change notification settings - Fork 0
/
byteorder.h
75 lines (59 loc) · 1.37 KB
/
byteorder.h
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#pragma once
#include <cstdint>
namespace mold {
template <typename T>
class BigEndian {
public:
BigEndian() : BigEndian(0) {}
BigEndian(T x) {
*this = x;
}
operator T() const {
// We don't need to optimize this code because compilers are
// usually smart enough to compile this loop into a single
// byte-swap instruction such as x86's bswap.
T ret = 0;
for (int i = 0; i < sizeof(T); i++)
ret = (ret << 8) | val[i];
return ret;
}
BigEndian &operator=(T x) {
for (int i = 0; i < sizeof(T); i++)
val[sizeof(T) - 1 - i] = x >> (i * 8);
return *this;
}
BigEndian &operator++() {
return *this = *this + 1;
}
BigEndian operator++(int) {
T ret = *this;
*this = *this + 1;
return ret;
}
BigEndian &operator--() {
return *this = *this - 1;
}
BigEndian operator--(int) {
T ret = *this;
*this = *this - 1;
return ret;
}
BigEndian &operator+=(T x) {
return *this = *this + x;
}
BigEndian &operator&=(T x) {
return *this = *this & x;
}
BigEndian &operator|=(T x) {
return *this = *this | x;
}
private:
uint8_t val[sizeof(T)];
};
using ibig16 = BigEndian<int16_t>;
using ibig32 = BigEndian<int32_t>;
using ibig64 = BigEndian<int64_t>;
using ubig16 = BigEndian<uint16_t>;
using ubig32 = BigEndian<uint32_t>;
using ubig64 = BigEndian<uint64_t>;
} // namespace mold