Corelink CPP Client
Corelink C++ client library
 
Loading...
Searching...
No Matches
system.hpp
Go to the documentation of this file.
1#pragma once
2
6
7namespace corelink
8{
9 namespace utils
10 {
11 namespace system
12 {
13 namespace _internals
14 {
15 template<typename t, size_t sz = sizeof(t)>
16 union CORELINK_EXPORT pun
17 {
18 static_assert(std::is_arithmetic<t>::value, "Non-numeric values are not supported");
19 t val;
20 std::array<uint8_t, sz> bytes;
21 };
22 }
23
30 CORELINK_EXPORT enum class endianness
31 {
33 };
34
39 CORELINK_EXPORT inline endianness sys_endianness()
40 {
41 _internals::pun<int32_t> _{0x01020304};
42 switch (_.bytes[0])
43 {
44 case 1:
45 return endianness::big;
46 case 4:
47 return endianness::little;
48 default:
50 }
51 }
52
64 template<typename num_typ,
65 size_t sz = sizeof(num_typ),
67 CORELINK_EXPORT inline std::vector<uint8_t> to_bytes(num_typ val)
68 {
69 // if system endianness and required endianness are same, we already
70 // have the data in the buffer in the required endianness order.
71 // if not, we just reverse the buffer order
72 const auto sys_endian = sys_endianness();
73 if (sys_endian == endianness::unknown || e == endianness::unknown) return {};
74
76 auto bytes = std::vector<uint8_t>(std::make_move_iterator(_.bytes.begin()),
77 std::make_move_iterator(_.bytes.end()));
78 if (sys_endian != e) std::reverse(bytes.begin(), bytes.end());
79 return bytes;
80 }
81
92 template<typename num_typ, endianness e = endianness::little>
93 CORELINK_EXPORT inline num_typ from_bytes(std::vector<uint8_t> bytes, num_typ default_val = num_typ())
94 {
95 // if the system endianness is the same as the required endianness,
96 // we can just pun the bytes as the final value
97 // however, if they are not the same, we reverse the bytes to get the desired
98 // value
99 const auto sys_endian = sys_endianness();
100 if (sys_endian == endianness::unknown || e == endianness::unknown) return default_val;
101
102 if (e != sys_endian) std::reverse(bytes.begin(), bytes.end());
103 _internals::pun<num_typ> _{*reinterpret_cast<num_typ *>(bytes.data())};
104 return _.val;
105 }
106 }
107 }
108}