-
Notifications
You must be signed in to change notification settings - Fork 5
/
test.cpp
105 lines (88 loc) · 2.59 KB
/
test.cpp
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
#include "endian.hpp"
#include <cassert>
#include <cstdio>
#include <typeinfo>
namespace test {
template<endian::order Order> void read1()
{
char buffer[4];
const int32_t num = 21344;
endian::write<Order>(num, buffer);
const int32_t res = endian::read<Order, int32_t>(buffer);
assert(res == num);
}
template<endian::order Order> void read2()
{
int32_t buffer;
const int32_t num = 21344;
endian::write<Order>(num, reinterpret_cast<char*>(&buffer));
const int32_t res = endian::read<Order, int32_t>(
reinterpret_cast<char*>(&buffer));
assert(res == num);
}
template<endian::order Order> void read3()
{
// Buffer size doesn't matter as long as it's at least N large. (N = 3)
char buffer[8];
const int32_t num = 0x00ffaabb;
endian::write<Order, 3>(num, buffer);
// NOTE: don't start reading from the beginning of the buffer as buffer
// contains a 4 byte value and we want 3 bytes.
const int32_t res = endian::read<Order, 3>(buffer);
std::printf("expected: 0x%x actual: 0x%x\n", num, res);
assert(res == num);
}
template<endian::order Order> void read4()
{
char buffer[4];
const int32_t num = 0x0000a01f;
endian::write<Order, 3>(num, buffer);
const int32_t res = endian::read<Order, 3>(buffer);
assert(res == num);
}
void reverse()
{
const uint32_t orig = 1234;
const uint32_t conv = endian::reverse(endian::reverse(orig));
assert(conv == orig);
}
void host_network_conv()
{
const uint32_t orig = 1234;
const uint32_t conv = endian::network_to_host(endian::host_to_network(orig));
assert(conv == orig);
}
void typedefs()
{
char buffer[4];
const int32_t num = 0x0000a01f;
endian::write_le(num, buffer);
auto res1 = endian::read_le<4>(buffer);
assert(res1 == num);
res1 = endian::read_le<int32_t>(buffer);
assert(res1 == num);
endian::write_be(num, buffer);
auto res2 = endian::read_be<4>(buffer);
assert(res2 == num);
res2 = endian::read_be<int32_t>(buffer);
assert(res2 == num);
}
} // test
int main()
{
test::read1<endian::order::big>();
test::read1<endian::order::little>();
test::read2<endian::order::big>();
test::read2<endian::order::little>();
test::read3<endian::order::big>();
test::read3<endian::order::little>();
test::read4<endian::order::big>();
test::read4<endian::order::little>();
test::typedefs();
test::reverse();
test::host_network_conv();
if(endian::order::host == endian::order::little)
std::printf("host is little endian\n");
else
std::printf("host is big endian\n");
}