Oxygen Engine
Modern C++ 3D Engine using OpenGL
Loading...
Searching...
No Matches
byte_array.h
1#ifndef OE_UTIL_BYTE_ARRAY_H
2#define OE_UTIL_BYTE_ARRAY_H
3
4#include "../common.h"
5
6#include <cstdint>
7#include <vector>
8#include <algorithm>
9#include <string>
10#include <cstddef>
11#include <span>
12
13namespace oe
14{
15 typedef std::vector<std::byte> ByteArray;
16 typedef std::span<const std::byte> ByteSpan;
17};
18
19namespace oe::util
20{
26 inline ByteArray convertUint8VectorToByteArray(const std::vector<uint8_t>& input)
27 {
28 ByteArray result(input.size());
29
30 std::ranges::transform(input, result.begin(),
31 [] (const uint8_t& c) { return std::byte(c); }
32 );
33
34 return result;
35 }
36
42 inline std::vector<uint8_t> convertByteArrayToUint8Vector(ByteSpan input)
43 {
44 std::vector<uint8_t> result(input.size());
45
46 std::ranges::transform(input, result.begin(),
47 [] (const std::byte& c) { return std::to_integer<char>(c); }
48 );
49
50 return result;
51 }
52
53 template <typename T>
54 inline T convertFromByteArray(ByteSpan input)
55 {
56 return *reinterpret_cast<const T*>(input.data());
57 }
58
59 template <typename T>
60 inline ByteArray convertToByteArray(const T& input)
61 {
62 ByteArray result;
63
64 constexpr const size_t size = sizeof(T);
65
66 result.reserve(size);
67
68 auto ptr = reinterpret_cast<const uint8_t*>(&input);
69 for (std::size_t i=0; i<size; ++i)
70 {
71 result.push_back(std::byte(ptr[i]));
72 }
73
74 return result;
75 }
76
80 inline std::string bytesToStr(ByteSpan input)
81 {
82 if (input.size() == 0)
83 {
84 return "";
85 }
86
87 return {reinterpret_cast<const char*>(input.data()), input.size()};
88 }
89
93 inline ByteArray strToBytes(std::string_view input)
94 {
95 ByteArray result(input.size());
96
97 std::ranges::transform(input, result.begin(),
98 [] (char c) { return std::byte(c); }
99 );
100
101 return result;
102 }
103
107 std::string bytesToHex(ByteSpan input, bool uppercase = false);
108
112 ByteArray hexToBytes(const std::string& input);
113};
114
115#endif
Various utilities.
Definition byte_array.h:20
std::string bytesToStr(ByteSpan input)
Definition byte_array.h:80
std::string bytesToHex(ByteSpan input, bool uppercase=false)
ByteArray convertUint8VectorToByteArray(const std::vector< uint8_t > &input)
Convert a vector of uint8_t to ByteArray.
Definition byte_array.h:26
ByteArray hexToBytes(const std::string &input)
std::vector< uint8_t > convertByteArrayToUint8Vector(ByteSpan input)
Convert a Byte Span to vector of uint8_t.
Definition byte_array.h:42
ByteArray strToBytes(std::string_view input)
Definition byte_array.h:93
Oxygen Engine common namespace.
Definition cursor.h:8