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 <boost/functional/hash.hpp>
8#include <cstring>
9#include <iomanip>
10#include <ios>
11
12namespace boat {
13
14struct blob_view : std::basic_string_view<std::byte> {
15 using std::basic_string_view<std::byte>::basic_string_view;
16 blob_view(std::byte const*) = delete;
17};
18
19struct blob : std::basic_string<std::byte> {
20 using std::basic_string<std::byte>::basic_string;
21 blob(std::byte const*) = delete;
22 operator blob_view() const { return {data(), size()}; }
23 friend auto hash_value(blob const& v) { return boost::hash_value(v); }
24};
25
27template <class I, class O>
28 requires std::same_as<std::remove_reference_t<I>, blob_view>
29decltype(auto) operator>>(I && in, O & out)
30{
31 if constexpr (arithmetic<O>) {
32 check(in.size() >= sizeof out, "out of blob");
33 std::memcpy(&out, in.data(), sizeof out);
34 in.remove_prefix(sizeof out);
35 }
36 else
37 static_cast<blob_view&>(in) >> out;
38 return std::forward<I>(in);
39}
40
42template <class O, class I>
43 requires std::same_as<std::remove_reference_t<O>, blob>
44decltype(auto) operator<<(O && out, I const& in)
45{
46 if constexpr (arithmetic<I>)
47 out.append_range(std::as_bytes(as_span(in)));
48 else
49 static_cast<blob&>(out) << in;
50 return std::forward<O>(out);
51}
52
53template <class T>
55 requires requires(T out) { in >> out; }
56{
57 T ret;
58 in >> ret;
59 return ret;
60}
61
62template <arithmetic T>
63T get(blob_view& in, std::endian e)
64 requires(!mixed(std::endian::native))
65{
66 check(!mixed(e), "mixed endian");
67 T ret;
68 in >> ret;
69 if (std::endian::native != e)
70 ret = byteswap(ret);
71 return ret;
72}
73
75struct hex {
77
78 friend auto& operator<<(ostream auto& out, hex const& in)
79 {
80 using char_t = std::remove_cvref_t<decltype(out)>::char_type;
81 auto os = std::basic_ostringstream<char_t>{};
82 os << std::uppercase << std::hex << std::setfill<char_t>('0');
83 for (auto byte : in.bytes)
84 os << std::setw(2) << static_cast<unsigned>(byte);
85 return out << os.view(); //< output once
86 }
87};
88
89} // namespace boat
90
91template <>
92struct std::hash<boat::blob> {
93 static auto operator()(boat::blob const& v) { return hash_value(v); }
94};
95
96#endif // BOAT_BLOB_HPP
Definition blob.hpp:12
T get(blob_view &in)
Definition blob.hpp:54
Definition blob.hpp:14
blob_view(std::byte const *)=delete
Definition blob.hpp:19
friend auto hash_value(blob const &v)
Definition blob.hpp:23
blob(std::byte const *)=delete
Formats bytes as uppercase hex, two digits per byte.
Definition blob.hpp:75
blob_view bytes
Definition blob.hpp:76
friend auto & operator<<(ostream auto &out, hex const &in)
Definition blob.hpp:78
static auto operator()(boat::blob const &v)
Definition blob.hpp:93