boat
C++23 geospatial library
Loading...
Searching...
No Matches
blob.hpp
Go to the documentation of this file.
1// Andrew Naplavkov
2
3#ifndef BOAT_BLOB_HPP
4#define BOAT_BLOB_HPP
5
6#include <boat/detail/utility.hpp>
7#include <cstring>
8#include <iomanip>
9#include <ios>
10
11namespace boat {
12
13struct blob_view : std::basic_string_view<std::byte> {
14 using std::basic_string_view<std::byte>::basic_string_view;
15 blob_view(std::byte const*) = delete;
16};
17
18struct blob : std::basic_string<std::byte> {
19 using std::basic_string<std::byte>::basic_string;
20 blob(std::byte const*) = delete;
21 operator blob_view() const { return {data(), size()}; }
22};
23
25template <class I, class O>
26 requires std::same_as<std::remove_reference_t<I>, blob_view>
27decltype(auto) operator>>(I && in, O & out)
28{
29 if constexpr (arithmetic<O>) {
30 check(in.size() >= sizeof out, "out of blob");
31 std::memcpy(&out, in.data(), sizeof out);
32 in.remove_prefix(sizeof out);
33 }
34 else
35 static_cast<blob_view&>(in) >> out;
36 return std::forward<I>(in);
37}
38
40template <class O, class I>
41 requires std::same_as<std::remove_reference_t<O>, blob>
42decltype(auto) operator<<(O && out, I const& in)
43{
44 if constexpr (arithmetic<I>)
45 out.append_range(std::as_bytes(as_span(in)));
46 else
47 static_cast<blob&>(out) << in;
48 return std::forward<O>(out);
49}
50
51template <class T>
53 requires requires(T out) { in >> out; }
54{
55 T ret;
56 in >> ret;
57 return ret;
58}
59
60template <arithmetic T>
61T get(blob_view& in, std::endian e)
62 requires(!mixed(std::endian::native))
63{
64 check(!mixed(e), "mixed endian");
65 T ret;
66 in >> ret;
67 if (std::endian::native != e)
68 ret = byteswap(ret);
69 return ret;
70}
71
72struct hex {
74
75 friend auto& operator<<(ostream auto& out, hex const& in)
76 {
77 using char_t = std::remove_cvref_t<decltype(out)>::char_type;
78 auto os = std::basic_ostringstream<char_t>{};
79 os << std::uppercase << std::hex << std::setfill<char_t>('0');
80 for (auto byte : in.bytes)
81 os << std::setw(2) << static_cast<unsigned>(byte);
82 return out << os.view(); //< output once
83 }
84};
85
86} // namespace boat
87
88#endif // BOAT_BLOB_HPP
Definition blob.hpp:11
T get(blob_view &in)
Definition blob.hpp:52
Definition blob.hpp:13
blob_view(std::byte const *)=delete
Definition blob.hpp:18
blob(std::byte const *)=delete
Definition blob.hpp:72
blob_view bytes
Definition blob.hpp:73
friend auto & operator<<(ostream auto &out, hex const &in)
Definition blob.hpp:75