|
| 1 | +/** |
| 2 | + * Copyright Soramitsu Co., Ltd. All Rights Reserved. |
| 3 | + * SPDX-License-Identifier: Apache-2.0 |
| 4 | + */ |
| 5 | + |
| 6 | +#ifndef LIBP2P_BASIC_READ_HPP |
| 7 | +#define LIBP2P_BASIC_READ_HPP |
| 8 | + |
| 9 | +#include <libp2p/basic/reader.hpp> |
| 10 | +#include <libp2p/common/span_size.hpp> |
| 11 | +#include <memory> |
| 12 | + |
| 13 | +namespace libp2p { |
| 14 | + /// Read exactly `out.size()` bytes |
| 15 | + inline void read(const std::shared_ptr<basic::Reader> &reader, |
| 16 | + gsl::span<uint8_t> out, |
| 17 | + std::function<void(outcome::result<void>)> cb) { |
| 18 | + auto post_cb = [](decltype(reader) reader, decltype(cb) &&cb, |
| 19 | + outcome::result<size_t> r) { |
| 20 | + reader->deferReadCallback(r, |
| 21 | + [cb{std::move(cb)}](outcome::result<size_t> r) { |
| 22 | + if (r.has_error()) { |
| 23 | + cb(r.error()); |
| 24 | + } else { |
| 25 | + cb(outcome::success()); |
| 26 | + } |
| 27 | + }); |
| 28 | + }; |
| 29 | + if (out.empty()) { |
| 30 | + return post_cb(reader, std::move(cb), outcome::success()); |
| 31 | + } |
| 32 | + // read some bytes |
| 33 | + reader->readSome( |
| 34 | + out, spanSize(out), |
| 35 | + [weak{std::weak_ptr{reader}}, out, cb{std::move(cb)}, |
| 36 | + post_cb](outcome::result<size_t> n_res) mutable { |
| 37 | + auto reader = weak.lock(); |
| 38 | + if (not reader) { |
| 39 | + return; |
| 40 | + } |
| 41 | + if (n_res.has_error()) { |
| 42 | + return post_cb(reader, std::move(cb), n_res.error()); |
| 43 | + } |
| 44 | + auto n = n_res.value(); |
| 45 | + if (n == 0) { |
| 46 | + throw std::logic_error{"libp2p::read zero bytes read"}; |
| 47 | + } |
| 48 | + if (n > spanSize(out)) { |
| 49 | + throw std::logic_error{"libp2p::read too much bytes read"}; |
| 50 | + } |
| 51 | + if (n == spanSize(out)) { |
| 52 | + // successfully read last bytes |
| 53 | + return post_cb(reader, std::move(cb), outcome::success()); |
| 54 | + } |
| 55 | + // read remaining bytes |
| 56 | + read(reader, out.subspan(n), std::move(cb)); |
| 57 | + }); |
| 58 | + } |
| 59 | +} // namespace libp2p |
| 60 | + |
| 61 | +#endif // LIBP2P_BASIC_READ_HPP |
0 commit comments