forked from storm-ptr/bark
-
Notifications
You must be signed in to change notification settings - Fork 0
/
blob.hpp
99 lines (81 loc) · 2.25 KB
/
blob.hpp
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
// Andrew Naplavkov
#ifndef BARK_BLOB_HPP
#define BARK_BLOB_HPP
#include <bark/detail/utility.hpp>
#include <iomanip>
#include <vector>
namespace bark {
/// Read-only binary view
struct blob_view : std::basic_string_view<std::byte> {
using std::basic_string_view<std::byte>::basic_string_view;
blob_view(const std::byte*) = delete;
};
/// Binary Large OBject (BLOB) is a contiguous byte storage
struct blob : std::vector<std::byte> {
using std::vector<std::byte>::vector;
operator blob_view() const noexcept { return {data(), size()}; }
};
template <class T>
if_arithmetic_t<T, const T*> read(blob_view& src, size_t count)
{
auto res = reinterpret_cast<const T*>(src.data());
src.remove_prefix(count * sizeof(T));
return res;
}
template <class T>
if_arithmetic_t<T, T> read(blob_view& src)
{
return *read<T>(src, 1);
}
template <class T, class Size = typename T::size_type>
T read(blob_view& src)
{
Size count = *read<Size>(src, 1);
return {read<typename T::value_type>(src, count), count};
}
template <class T>
if_arithmetic_t<T> write(const T* src, size_t count, blob& dest)
{
auto first = reinterpret_cast<const std::byte*>(src);
auto last = first + count * sizeof(T);
dest.insert(dest.end(), first, last);
}
template <class T>
if_arithmetic_t<T> write(const T& src, blob& dest)
{
write(&src, 1, dest);
}
template <class T, class Size = typename T::size_type>
void write(const T& src, blob& dest)
{
Size count = src.size();
write(&count, 1, dest);
write(src.data(), count, dest);
}
template <class T>
blob_view& operator>>(blob_view& src, T& dest)
{
dest = read<T>(src);
return src;
}
template <class T>
blob& operator<<(blob& dest, const T& src)
{
write(src, dest);
return dest;
}
/// I/O manipulator.
/// Bytes inserted into the stream are expressed in hexadecimal base (radix 16)
struct hex {
blob_view data;
friend std::ostream& operator<<(std::ostream& dest, const hex& src)
{
std::ostringstream os;
os << std::uppercase << std::hex << std::setfill('0');
for (auto byte : src.data)
os << std::setw(2) << static_cast<unsigned>(byte);
return dest << os.str(); // call stream once
}
};
} // namespace bark
#endif // BARK_BLOB_HPP