@@ -76,48 +76,42 @@ namespace libp2p::transport {
76
76
});
77
77
}
78
78
79
+ template <typename Callback>
80
+ auto closeOnError (TcpConnection &conn, Callback &&cb) {
81
+ return [cb{std::move (cb)}, conn{conn.shared_from_this ()}](auto &&ec,
82
+ auto &&result) {
83
+ if (ec == boost::asio::error::broken_pipe) {
84
+ std::ignore = conn->close ();
85
+ }
86
+ if (ec) {
87
+ return cb (std::forward<decltype (ec)>(ec));
88
+ }
89
+ cb (result);
90
+ };
91
+ }
92
+
79
93
void TcpConnection::read (gsl::span<uint8_t > out, size_t bytes,
80
94
TcpConnection::ReadCallbackFunc cb) {
81
95
boost::asio::async_read (socket_, detail::makeBuffer (out, bytes),
82
- [cb = std::move (cb)](auto &&ec, auto &&read) {
83
- if (ec) {
84
- return cb (std::forward<decltype (ec)>(ec));
85
- }
86
- return cb (read);
87
- });
96
+ closeOnError (*this , cb));
88
97
}
89
98
90
99
void TcpConnection::readSome (gsl::span<uint8_t > out, size_t bytes,
91
100
TcpConnection::ReadCallbackFunc cb) {
92
101
socket_.async_read_some (detail::makeBuffer (out, bytes),
93
- [cb = std::move (cb)](auto &&ec, auto &&read) {
94
- if (ec) {
95
- return cb (std::forward<decltype (ec)>(ec));
96
- }
97
- return cb (read);
98
- });
102
+ closeOnError (*this , cb));
99
103
}
100
104
101
105
void TcpConnection::write (gsl::span<const uint8_t > in, size_t bytes,
102
106
TcpConnection::WriteCallbackFunc cb) {
103
107
boost::asio::async_write (socket_, detail::makeBuffer (in, bytes),
104
- [cb = std::move (cb)](auto &&ec, auto &&written) {
105
- if (ec) {
106
- return cb (std::forward<decltype (ec)>(ec));
107
- }
108
- return cb (written);
109
- });
108
+ closeOnError (*this , cb));
110
109
}
111
110
112
111
void TcpConnection::writeSome (gsl::span<const uint8_t > in, size_t bytes,
113
112
TcpConnection::WriteCallbackFunc cb) {
114
113
socket_.async_write_some (detail::makeBuffer (in, bytes),
115
- [cb = std::move (cb)](auto &&ec, auto &&written) {
116
- if (ec) {
117
- return cb (std::forward<decltype (ec)>(ec));
118
- }
119
- return cb (written);
120
- });
114
+ closeOnError (*this , cb));
121
115
}
122
116
123
117
} // namespace libp2p::transport
0 commit comments