Kagome
Polkadot Runtime Engine in C++17
scale_message_read_writer.hpp
Go to the documentation of this file.
1 
6 #ifndef KAGOME_SCALE_MESSAGE_READ_WRITER_HPP
7 #define KAGOME_SCALE_MESSAGE_READ_WRITER_HPP
8 
9 #include <functional>
10 #include <memory>
11 
12 #include <libp2p/basic/message_read_writer_uvarint.hpp>
13 #include <outcome/outcome.hpp>
14 
15 #include "scale/scale.hpp"
16 
17 namespace kagome::network {
22  : public std::enable_shared_from_this<ScaleMessageReadWriter> {
23  template <typename MsgType>
24  using ReadCallback = std::function<void(outcome::result<MsgType>)>;
25 
26  public:
27  explicit ScaleMessageReadWriter(
28  std::shared_ptr<libp2p::basic::MessageReadWriter> read_writer);
29  explicit ScaleMessageReadWriter(
30  const std::shared_ptr<libp2p::basic::ReadWriter> &read_writer);
31 
37  template <typename MsgType>
38  void read(ReadCallback<MsgType> cb) const {
39  read_writer_->read(
40  [self{shared_from_this()}, cb = std::move(cb)](auto &&read_res) {
41  if (!read_res) {
42  return cb(read_res.error());
43  }
44 
45  if (read_res.value()) {
46  auto msg_res = scale::decode<MsgType>(*read_res.value());
47  if (!msg_res) {
48  return cb(msg_res.error());
49  }
50  return cb(std::move(msg_res.value()));
51  }
52  return cb(MsgType{});
53  });
54  }
55 
62  template <typename MsgType>
63  void write(const MsgType &msg,
64  libp2p::basic::Writer::WriteCallbackFunc cb) const {
65  auto encoded_msg_res = scale::encode(msg);
66  if (!encoded_msg_res) {
67  return cb(encoded_msg_res.error());
68  }
69  auto msg_ptr = std::make_shared<std::vector<uint8_t>>(
70  std::move(encoded_msg_res.value()));
71 
72  read_writer_->write(*msg_ptr,
73  [self{shared_from_this()},
74  msg_ptr,
75  cb = std::move(cb)](auto &&write_res) {
76  if (!write_res) {
77  return cb(write_res.error());
78  }
79  cb(outcome::success());
80  });
81  }
82 
83  private:
84  std::shared_ptr<libp2p::basic::MessageReadWriter> read_writer_;
85  };
86 } // namespace kagome::network
87 
88 #endif // KAGOME_SCALE_MESSAGE_READ_WRITER_HPP
std::function< void(outcome::result< MsgType >)> ReadCallback
ScaleMessageReadWriter(std::shared_ptr< libp2p::basic::MessageReadWriter > read_writer)
void read(ReadCallback< MsgType > cb) const
void write(const MsgType &msg, libp2p::basic::Writer::WriteCallbackFunc cb) const
std::shared_ptr< libp2p::basic::MessageReadWriter > read_writer_