veriblock-pop-cpp
C++11 Libraries for leveraging VeriBlock Proof-Of-Proof blockchain technology.
write_stream.hpp
1// Copyright (c) 2019-2022 Xenios SEZC
2// https://www.veriblock.org
3// Distributed under the MIT software license, see the accompanying
4// file LICENSE or http://www.opensource.org/licenses/mit-license.php.
5
6#ifndef ALT_INTEGRATION_VERIBLOCK_WRITE_STREAM_HPP
7#define ALT_INTEGRATION_VERIBLOCK_WRITE_STREAM_HPP
8
9#include <cstdint>
10#include <string>
11#include <vector>
12
13#include "assert.hpp"
14
15namespace altintegration {
16
21 public:
22 WriteStream() = default;
23
24 using storage_t = std::vector<uint8_t>;
25
26 explicit WriteStream(size_t size);
27
28 // movable
29 explicit WriteStream(WriteStream &&) = default;
30 WriteStream &operator=(WriteStream &&) = default;
31
32 void write(const void *buf, size_t size);
33
34 template <typename T,
35 typename = typename std::enable_if<sizeof(typename T::value_type) ==
36 1>::type>
37 void write(const T &t) {
38 write(t.data(), t.size());
39 }
40
41 template <
42 typename T,
43 typename = typename std::enable_if<std::is_integral<T>::value>::type>
44 void writeBE(T num, size_t bytes = sizeof(T)) {
45 VBK_ASSERT(bytes <= sizeof(T));
46
47 for (size_t i = 0, shift = (sizeof(T) - 1) * 8; i < sizeof(T);
48 i++, shift -= 8) {
49 // skip first bytes
50 if (i < (sizeof(T) - bytes)) {
51 continue;
52 }
53 m_data.push_back((num >> shift) & 0xffu);
54 }
55 }
56
57 template <
58 typename T,
59 typename = typename std::enable_if<std::is_integral<T>::value>::type>
60 void writeLE(T num) {
61 for (size_t i = 0, shift = 0; i < sizeof(T); i++, shift += 8) {
62 m_data.push_back((num >> shift) & 0xffu);
63 }
64 }
65
66 uint32_t getVersion() const noexcept;
67
68 void setVersion(uint32_t version) noexcept;
69
70 const storage_t &data() const noexcept;
71
72 std::string hex() const noexcept;
73
74 private:
75 // publicly non-copyable
76 WriteStream(const WriteStream &) = default;
77 WriteStream &operator=(const WriteStream &) = default;
78
79 private:
80 uint32_t m_version{0};
81 storage_t m_data;
82};
83
84} // namespace altintegration
85
86#endif // ALT_INTEGRATION_WRITE_STREAM_HPP
Binary writer that is useful for binary serialization.
Defines logging helpers.
Definition: block.hpp:14