forked from aclements/libelfin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommon.hh
109 lines (90 loc) · 2.41 KB
/
common.hh
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
// Copyright (c) 2013 Austin T. Clements. All rights reserved.
// Use of this source code is governed by an MIT license
// that can be found in the LICENSE file.
#ifndef _ELFPP_COMMON_HH_
#define _ELFPP_COMMON_HH_
#define ELFPP_BEGIN_NAMESPACE namespace elf {
#define ELFPP_END_NAMESPACE }
#define ELFPP_BEGIN_INTERNAL namespace internal {
#define ELFPP_END_INTERNAL }
#include <cstdint>
ELFPP_BEGIN_NAMESPACE
/**
* A byte ordering.
*/
enum class byte_order
{
native,
lsb,
msb
};
/**
* Return either byte_order::lsb or byte_order::msb. If the argument
* is byte_order::native, it will be resolved to whatever the native
* byte order is.
*/
static inline byte_order
resolve_order(byte_order o)
{
static const union
{
int i;
char c[sizeof(int)];
} test = {1};
if (o == byte_order::native)
return test.c[0] == 1 ? byte_order::lsb : byte_order::msb;
return o;
}
/**
* Return v converted from one byte order to another.
*/
template<typename T>
T
swizzle(T v, byte_order from, byte_order to)
{
static_assert(sizeof(T) == 1 ||
sizeof(T) == 2 ||
sizeof(T) == 4 ||
sizeof(T) == 8,
"cannot swizzle type");
from = resolve_order(from);
to = resolve_order(to);
if (from == to)
return v;
switch (sizeof(T)) {
case 1:
return v;
case 2: {
std::uint16_t x = (std::uint16_t)v;
return (T)(((x&0xFF) << 8) | (x >> 8));
}
case 4:
return (T)__builtin_bswap32((std::uint32_t)v);
case 8:
return (T)__builtin_bswap64((std::uint64_t)v);
}
}
ELFPP_BEGIN_INTERNAL
/**
* OrderPick selects between Native, LSB, and MSB based on ord.
*/
template<byte_order ord, typename Native, typename LSB, typename MSB>
struct OrderPick;
template<typename Native, typename LSB, typename MSB>
struct OrderPick<byte_order::native, Native, LSB, MSB>
{
typedef Native T;
};
template<typename Native, typename LSB, typename MSB>
struct OrderPick<byte_order::lsb, Native, LSB, MSB>
{
typedef LSB T;
};
template<typename Native, typename LSB, typename MSB>
struct OrderPick<byte_order::msb, Native, LSB, MSB>
{
typedef MSB T;
};
ELFPP_END_INTERNAL
ELFPP_END_NAMESPACE
#endif