Kagome
Polkadot Runtime Engine in C++17
protobuf_message_read_writer.hpp
Go to the documentation of this file.
1 
6 #ifndef KAGOME_PROTOBUF_MESSAGE_READ_WRITER_HPP
7 #define KAGOME_PROTOBUF_MESSAGE_READ_WRITER_HPP
8 
9 #include <functional>
10 #include <memory>
11 
12 #include <libp2p/basic/message_read_writer_uvarint.hpp>
13 #include <libp2p/basic/protobuf_message_read_writer.hpp>
14 #include <outcome/outcome.hpp>
15 
19 #include "scale/scale.hpp"
20 
21 namespace kagome::network {
26  : public std::enable_shared_from_this<ProtobufMessageReadWriter> {
27  template <typename MsgType>
28  using ReadCallback = std::function<void(outcome::result<MsgType>)>;
29 
30  std::shared_ptr<libp2p::basic::MessageReadWriter> read_writer_;
31 
32  public:
34  const std::shared_ptr<libp2p::basic::ReadWriter> &read_writer)
35  : read_writer_(
36  std::make_shared<libp2p::basic::MessageReadWriterUvarint>(
37  read_writer)) {}
38 
44  template <typename MsgType>
45  void read(ReadCallback<MsgType> &&cb) const {
46  read_writer_->read(
47  [self{shared_from_this()}, cb = std::move(cb)](auto &&read_res) {
48  if (!read_res) {
49  return cb(read_res.error());
50  }
51 
52  using ProtobufRW =
54 
55  MsgType msg;
56  if (read_res.value()) {
57  if (auto msg_res = ProtobufRW::read(
58  msg, *read_res.value(), read_res.value()->begin());
59  !msg_res) {
60  return cb(msg_res.error());
61  }
62  }
63  return cb(std::move(msg));
64  });
65  }
66 
73  template <typename MsgType>
74  void write(const MsgType &msg,
75  libp2p::basic::Writer::WriteCallbackFunc &&cb) const {
76  using ProtobufRW =
78 
79  // TODO(iceseer): PRE-523 cache this vector
80  std::vector<uint8_t> out;
81  auto it = ProtobufRW::write(msg, out);
82 
83  gsl::span<uint8_t> data(it.base(),
84  out.size() - std::distance(out.begin(), it));
85 
86  read_writer_->write(data,
87  [self{shared_from_this()},
88  out{std::move(out)},
89  cb = std::move(cb)](auto &&write_res) {
90  if (!write_res) {
91  return cb(write_res.error());
92  }
93  cb(outcome::success());
94  });
95  }
96  };
97 
98 } // namespace kagome::network
99 
100 #endif // KAGOME_PROTOBUF_MESSAGE_READ_WRITER_HPP
STL namespace.
std::shared_ptr< libp2p::basic::MessageReadWriter > read_writer_
std::function< void(outcome::result< MsgType >)> ReadCallback
void read(ReadCallback< MsgType > &&cb) const
void write(const MsgType &msg, libp2p::basic::Writer::WriteCallbackFunc &&cb) const
ProtobufMessageReadWriter(const std::shared_ptr< libp2p::basic::ReadWriter > &read_writer)