99.39% Lines (163/164) 100.00% Functions (26/26)
TLA Baseline Branch
Line Hits Code Line Hits Code
1   // 1   //
2   // Copyright (c) 2025 Vinnie Falco (vinnie.falco@gmail.com) 2   // Copyright (c) 2025 Vinnie Falco (vinnie.falco@gmail.com)
3   // Copyright (c) 2026 Michael Vandeberg 3   // Copyright (c) 2026 Michael Vandeberg
4   // 4   //
5   // Distributed under the Boost Software License, Version 1.0. (See accompanying 5   // Distributed under the Boost Software License, Version 1.0. (See accompanying
6   // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) 6   // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
7   // 7   //
8   // Official repository: https://github.com/cppalliance/capy 8   // Official repository: https://github.com/cppalliance/capy
9   // 9   //
10   10  
11   #ifndef BOOST_CAPY_TEST_STREAM_HPP 11   #ifndef BOOST_CAPY_TEST_STREAM_HPP
12   #define BOOST_CAPY_TEST_STREAM_HPP 12   #define BOOST_CAPY_TEST_STREAM_HPP
13   13  
14   #include <boost/capy/detail/config.hpp> 14   #include <boost/capy/detail/config.hpp>
15   #include <boost/capy/buffers.hpp> 15   #include <boost/capy/buffers.hpp>
16   #include <boost/capy/buffers/buffer_copy.hpp> 16   #include <boost/capy/buffers/buffer_copy.hpp>
17   #include <boost/capy/buffers/make_buffer.hpp> 17   #include <boost/capy/buffers/make_buffer.hpp>
18   #include <boost/capy/continuation.hpp> 18   #include <boost/capy/continuation.hpp>
19   #include <coroutine> 19   #include <coroutine>
20   #include <boost/capy/ex/await_context.hpp> 20   #include <boost/capy/ex/await_context.hpp>
21   #include <boost/capy/results.hpp> 21   #include <boost/capy/results.hpp>
22   #include <boost/capy/error.hpp> 22   #include <boost/capy/error.hpp>
23   #include <boost/capy/read.hpp> 23   #include <boost/capy/read.hpp>
24   #include <boost/capy/task.hpp> 24   #include <boost/capy/task.hpp>
25   #include <boost/capy/test/fuse.hpp> 25   #include <boost/capy/test/fuse.hpp>
26   #include <boost/capy/test/run_blocking.hpp> 26   #include <boost/capy/test/run_blocking.hpp>
27   27  
28   #include <atomic> 28   #include <atomic>
29   #include <memory> 29   #include <memory>
30   #include <new> 30   #include <new>
31   #include <stop_token> 31   #include <stop_token>
32   #include <string> 32   #include <string>
33   #include <string_view> 33   #include <string_view>
34   #include <utility> 34   #include <utility>
35   35  
36   namespace boost { 36   namespace boost {
37   namespace capy { 37   namespace capy {
38   namespace test { 38   namespace test {
39   39  
40   /** Suspends a reader until its paired end writes, or the shared fuse injects an error. 40   /** Suspends a reader until its paired end writes, or the shared fuse injects an error.
41   41  
42   Streams are created in pairs via @ref make_stream_pair. 42   Streams are created in pairs via @ref make_stream_pair.
43   Data written to one end becomes available for reading on 43   Data written to one end becomes available for reading on
44   the other. If no data is available when @ref read_some 44   the other. If no data is available when @ref read_some
45   is called, the calling coroutine suspends until the peer 45   is called, the calling coroutine suspends until the peer
46   calls @ref write_some. The shared @ref fuse enables error 46   calls @ref write_some. The shared @ref fuse enables error
47   injection at controlled points in both directions. 47   injection at controlled points in both directions.
48   48  
49   When the fuse injects an error or throws on one end, the 49   When the fuse injects an error or throws on one end, the
50   pair is automatically closed. Any suspended reader on 50   pair is automatically closed. Any suspended reader on
51   either end is resumed with `error::eof`, and subsequent 51   either end is resumed with `error::eof`, and subsequent
52   operations on both ends return `error::eof`. Calling 52   operations on both ends return `error::eof`. Calling
53   @ref close on one end signals eof to the peer's reads 53   @ref close on one end signals eof to the peer's reads
54   after draining any buffered data, while the peer may 54   after draining any buffered data, while the peer may
55   still write. 55   still write.
56   56  
57   @par Thread Safety 57   @par Thread Safety
58   Single-threaded only. Both ends of the pair must be 58   Single-threaded only. Both ends of the pair must be
59   accessed from the same thread. Concurrent access is 59   accessed from the same thread. Concurrent access is
60 - undefined behavior. 60 + undefined behavior. The exception is a stop request on the
  61 + stop token of a suspended read. That request may come from
  62 + another thread, and the read resumes through its executor.
61   63  
62   @par Example 64   @par Example
63   @par !example example 65   @par !example example
64   66  
65   67  
66   @see @ref make_stream_pair, @ref fuse 68   @see @ref make_stream_pair, @ref fuse
67   */ 69   */
68   class stream 70   class stream
69   { 71   {
70   // Single-threaded only. No concurrent access to either 72   // Single-threaded only. No concurrent access to either
71   // end of the pair. Both streams and all operations must 73   // end of the pair. Both streams and all operations must
72   // run on the same thread. 74   // run on the same thread.
73   75  
74   struct half 76   struct half
75   { 77   {
76   std::string buf; 78   std::string buf;
77   std::size_t max_read_size = std::size_t(-1); 79   std::size_t max_read_size = std::size_t(-1);
78   // The parked read's own continuation: an executor may queue it 80   // The parked read's own continuation: an executor may queue it
79   // in place, so it is never copied or changed once posted. 81   // in place, so it is never copied or changed once posted.
80   continuation* pending_cont_ = nullptr; 82   continuation* pending_cont_ = nullptr;
81   executor_ref pending_ex; 83   executor_ref pending_ex;
82   // Points at the suspended reader's claim flag (owned by the 84   // Points at the suspended reader's claim flag (owned by the
83   // read awaitable). Lets a peer wake coordinate with a stop 85   // read awaitable). Lets a peer wake coordinate with a stop
84   // callback so the parked read is resumed exactly once. 86   // callback so the parked read is resumed exactly once.
85   std::atomic<bool>* pending_claimed = nullptr; 87   std::atomic<bool>* pending_claimed = nullptr;
86   bool eof = false; 88   bool eof = false;
87   }; 89   };
88   90  
89   struct state 91   struct state
90   { 92   {
91   fuse f; 93   fuse f;
92   bool closed = false; 94   bool closed = false;
93   half sides[2]; 95   half sides[2];
94   96  
HITCBC 95   303 explicit state(fuse f_) noexcept 97   321 explicit state(fuse f_) noexcept
HITCBC 96   909 : f(std::move(f_)) 98   963 : f(std::move(f_))
97   { 99   {
HITCBC 98   303 } 100   321 }
99   101  
100   // Resume a suspended reader on this side, if any. Claims the 102   // Resume a suspended reader on this side, if any. Claims the
101   // reader's atomic so it is never double-resumed by a racing 103   // reader's atomic so it is never double-resumed by a racing
102   // stop callback; the loser of the race skips the post. 104   // stop callback; the loser of the race skips the post.
HITCBC 103   689 static void wake(half& side) 105   741 static void wake(half& side)
104   { 106   {
HITCBC 105   689 auto* c = std::exchange(side.pending_cont_, nullptr); 107   741 auto* c = std::exchange(side.pending_cont_, nullptr);
HITCBC 106   689 if(! c) 108   741 if(! c)
HITCBC 107   663 return; 109   698 return;
HITCBC 108   26 auto ex = std::exchange(side.pending_ex, {}); 110   43 auto ex = std::exchange(side.pending_ex, {});
HITCBC 109   26 auto* claimed = std::exchange(side.pending_claimed, nullptr); 111   43 auto* claimed = std::exchange(side.pending_claimed, nullptr);
HITCBC 110   52 if(! claimed || 112   86 if(! claimed ||
HITCBC 111   26 ! claimed->exchange(true, std::memory_order_acq_rel)) 113   43 ! claimed->exchange(true, std::memory_order_acq_rel))
112   { 114   {
HITCBC 113   26 ex.post(*c); 115   43 ex.post(*c);
114   } 116   }
115   } 117   }
116   118  
117   // Set closed and resume any suspended readers 119   // Set closed and resume any suspended readers
118   // with eof on both sides. 120   // with eof on both sides.
HITCBC 119   214 void close() 121   214 void close()
120   { 122   {
HITCBC 121   214 closed = true; 123   214 closed = true;
HITCBC 122   642 for(auto& side : sides) 124   642 for(auto& side : sides)
HITCBC 123   428 wake(side); 125   428 wake(side);
HITCBC 124   214 } 126   214 }
125   }; 127   };
126   128  
127   // Wraps the maybe_fail() call. If the guard is 129   // Wraps the maybe_fail() call. If the guard is
128   // not disarmed before destruction (fuse returned 130   // not disarmed before destruction (fuse returned
129   // an error, or threw an exception), closes both 131   // an error, or threw an exception), closes both
130   // ends so any suspended peer gets eof. 132   // ends so any suspended peer gets eof.
131   struct close_guard 133   struct close_guard
132   { 134   {
133   state* st; 135   state* st;
134   bool armed = true; 136   bool armed = true;
HITCBC 135   314 void disarm() noexcept { armed = false; } 137   363 void disarm() noexcept { armed = false; }
HITCBC 136   528 ~close_guard() noexcept(false) { if(armed) st->close(); } 138   577 ~close_guard() noexcept(false) { if(armed) st->close(); }
137   }; 139   };
138   140  
139   std::shared_ptr<state> state_; 141   std::shared_ptr<state> state_;
140   int index_; 142   int index_;
141   143  
HITCBC 142   606 stream( 144   642 stream(
143   std::shared_ptr<state> sp, 145   std::shared_ptr<state> sp,
144   int index) noexcept 146   int index) noexcept
HITCBC 145   606 : state_(std::move(sp)) 147   642 : state_(std::move(sp))
HITCBC 146   606 , index_(index) 148   642 , index_(index)
147   { 149   {
HITCBC 148   606 } 150   642 }
149   151  
150   friend std::pair<stream, stream> 152   friend std::pair<stream, stream>
151   make_stream_pair(fuse); 153   make_stream_pair(fuse);
152   154  
153   public: 155   public:
154   /** Copy construction is disabled; a stream end is move-only. 156   /** Copy construction is disabled; a stream end is move-only.
155   157  
156   @param other The stream end that would be copied. 158   @param other The stream end that would be copied.
157   */ 159   */
158   stream(stream const& other) = delete; 160   stream(stream const& other) = delete;
159   161  
160   /** Copy assignment is disabled; a stream end is move-only. 162   /** Copy assignment is disabled; a stream end is move-only.
161   163  
162   @param other The stream end that would be assigned from. 164   @param other The stream end that would be assigned from.
163   165  
164   @return A reference to `*this`. 166   @return A reference to `*this`.
165   */ 167   */
166   stream& operator=(stream const& other) = delete; 168   stream& operator=(stream const& other) = delete;
167   169  
168 - /** Move constructor. 170 + /** Construct by moving from another stream end.
169   171  
170   @param other The stream end to move from. 172   @param other The stream end to move from.
171   */ 173   */
HITCBC 172   708 stream(stream&& other) = default; 174   744 stream(stream&& other) = default;
173   175  
174 - /** Move assignment. 176 + /** Assign by moving from another stream end.
175   177  
176   @param other The stream end to move from. 178   @param other The stream end to move from.
177   179  
178   @return A reference to `*this`. 180   @return A reference to `*this`.
179   */ 181   */
180   stream& operator=(stream&& other) = default; 182   stream& operator=(stream&& other) = default;
181   183  
182   /** Signal end-of-stream to the peer. 184   /** Signal end-of-stream to the peer.
183   185  
184   Marks the peer's read direction as closed. 186   Marks the peer's read direction as closed.
185   If the peer is suspended in @ref read_some, 187   If the peer is suspended in @ref read_some,
186   it is resumed. The peer drains any buffered 188   it is resumed. The peer drains any buffered
187   data before receiving `error::eof`. Writes 189   data before receiving `error::eof`. Writes
188   from the peer are unaffected. 190   from the peer are unaffected.
189   */ 191   */
190   void 192   void
HITCBC 191   6 close() 193   24 close()
192   { 194   {
HITCBC 193   6 int peer = 1 - index_; 195   24 int peer = 1 - index_;
HITCBC 194   6 auto& side = state_->sides[peer]; 196   24 auto& side = state_->sides[peer];
HITCBC 195   6 side.eof = true; 197   24 side.eof = true;
HITCBC 196   6 state::wake(side); 198   24 state::wake(side);
HITCBC 197   6 } 199   24 }
198   200  
199   /** Set the maximum bytes returned per read. 201   /** Set the maximum bytes returned per read.
200   202  
201   Limits how many bytes @ref read_some returns in 203   Limits how many bytes @ref read_some returns in
202   a single call, simulating chunked network delivery. 204   a single call, simulating chunked network delivery.
203   The default is unlimited. 205   The default is unlimited.
204   206  
205   @param n Maximum bytes per read. 207   @param n Maximum bytes per read.
206   */ 208   */
207   void 209   void
HITCBC 208   54 set_max_read_size(std::size_t n) noexcept 210   54 set_max_read_size(std::size_t n) noexcept
209   { 211   {
HITCBC 210   54 state_->sides[index_].max_read_size = n; 212   54 state_->sides[index_].max_read_size = n;
HITCBC 211   54 } 213   54 }
212   214  
213   /** Asynchronously read data from the stream. 215   /** Asynchronously read data from the stream.
214   216  
215   Transfers up to `buffer_size(buffers)` bytes from 217   Transfers up to `buffer_size(buffers)` bytes from
216   data written by the peer. If no data is available, 218   data written by the peer. If no data is available,
217   the calling coroutine suspends until the peer calls 219   the calling coroutine suspends until the peer calls
218 - @ref write_some. Before every read, the attached 220 + @ref write_some. Before transferring data, the attached
219   @ref fuse is consulted to possibly inject an error. 221   @ref fuse is consulted to possibly inject an error.
220   If the fuse fires, the pair is automatically closed. 222   If the fuse fires, the pair is automatically closed.
221   If the stream is closed, returns `error::eof`. 223   If the stream is closed, returns `error::eof`.
222   The returned `std::size_t` is the number of bytes 224   The returned `std::size_t` is the number of bytes
223   transferred. 225   transferred.
224   226  
225 - @param buffers The mutable buffer sequence to receive data. 227 + The fuse is not consulted for an empty buffer sequence, a
226 - 228 + canceled read, a closed pair, or a read after the peer
227 - @return An awaitable that await-returns `(error_code,std::size_t)`. 229 + called @ref close.
228   230  
229   @par Cancellation 231   @par Cancellation
230   Cancellation applies only to a read that would otherwise suspend. 232   Cancellation applies only to a read that would otherwise suspend.
231   If no data is available and the environment's stop token is 233   If no data is available and the environment's stop token is
232   requested, before or during the wait, the read resumes with 234   requested, before or during the wait, the read resumes with
233   `error::canceled`. A read that can complete immediately from 235   `error::canceled`. A read that can complete immediately from
234   buffered data is unaffected by the stop token. 236   buffered data is unaffected by the stop token.
235   237  
  238 + @par Exception Safety
  239 + Injected I/O conditions are reported via the `error_code`
  240 + component of the result. Throws `std::system_error` when the
  241 + attached @ref fuse is in exception mode and reaches its failure
  242 + point. The pair is closed before the exception propagates.
  243 +
  244 + @throws std::system_error When the attached @ref fuse is in
  245 + exception mode and reaches its failure point.
  246 +
  247 + @param buffers The mutable buffer sequence to receive data.
  248 +
  249 + @return An awaitable that await-returns `(error_code,std::size_t)`.
  250 +
236   @see @ref fuse, @ref close 251   @see @ref fuse, @ref close
237   */ 252   */
238   template<MutableBufferSequence MB> 253   template<MutableBufferSequence MB>
239   auto 254   auto
HITCBC 240   294 read_some(MB buffers) 255   345 read_some(MB buffers)
241   { 256   {
242   // The read suspends when no data is available, parking its 257   // The read suspends when no data is available, parking its
243   // continuation on the side until the peer writes/closes. To 258   // continuation on the side until the peer writes/closes. To
244   // support cancellation it follows the same pattern as 259   // support cancellation it follows the same pattern as
245   // async_waker::wait_awaiter: a stop callback claims the resume 260   // async_waker::wait_awaiter: a stop callback claims the resume
246   // (racing the peer wake via an atomic) and posts the continuation 261   // (racing the peer wake via an atomic) and posts the continuation
247   // through the executor. Because it owns a std::atomic and a 262   // through the executor. Because it owns a std::atomic and a
248   // std::stop_callback, the awaitable needs explicit move and 263   // std::stop_callback, the awaitable needs explicit move and
249   // destruction (the task promise moves it into its 264   // destruction (the task promise moves it into its
250   // context_awaiter before awaiting). 265   // context_awaiter before awaiting).
251   struct awaitable 266   struct awaitable
252   { 267   {
253   stream* self_; 268   stream* self_;
254   MB buffers_; 269   MB buffers_;
255   270  
256   // Declared before stop_cb_buf_: the stop callback reads 271   // Declared before stop_cb_buf_: the stop callback reads
257   // these, so they must outlive a blocking stop_cb_ destructor. 272   // these, so they must outlive a blocking stop_cb_ destructor.
258   continuation cont_; 273   continuation cont_;
259   executor_ref ex_; 274   executor_ref ex_;
260   half* side_ = nullptr; 275   half* side_ = nullptr;
261   std::atomic<bool> claimed_{false}; 276   std::atomic<bool> claimed_{false};
262   bool canceled_ = false; 277   bool canceled_ = false;
263   bool stop_cb_active_ = false; 278   bool stop_cb_active_ = false;
264   279  
265   struct cancel_fn 280   struct cancel_fn
266   { 281   {
267   awaitable* self_; 282   awaitable* self_;
268   283  
HITCBC 269   14 void operator()() const noexcept 284   14 void operator()() const noexcept
270   { 285   {
HITCBC 271   14 if(! self_->claimed_.exchange( 286   14 if(! self_->claimed_.exchange(
272   true, std::memory_order_acq_rel)) 287   true, std::memory_order_acq_rel))
273   { 288   {
HITCBC 274   2 self_->canceled_ = true; 289   2 self_->canceled_ = true;
HITCBC 275   2 self_->ex_.post(self_->cont_); 290   2 self_->ex_.post(self_->cont_);
276   } 291   }
HITCBC 277   14 } 292   14 }
278   }; 293   };
279   294  
280   using stop_cb_t = std::stop_callback<cancel_fn>; 295   using stop_cb_t = std::stop_callback<cancel_fn>;
281   296  
282   // Declared last: its destructor may block while the callback 297   // Declared last: its destructor may block while the callback
283   // accesses the members above. A union gives correct alignment 298   // accesses the members above. A union gives correct alignment
284   // for stop_cb_t without an alignas specifier, which avoids 299   // for stop_cb_t without an alignas specifier, which avoids
285   // MSVC's C4324 padding warning on this function-local class 300   // MSVC's C4324 padding warning on this function-local class
286   // (the member-level pragma used by async_waker::wait_awaiter 301   // (the member-level pragma used by async_waker::wait_awaiter
287   // does not suppress it here). Lifetime is managed manually: 302   // does not suppress it here). Lifetime is managed manually:
288   // placement new in await_suspend, explicit destruction once done. 303   // placement new in await_suspend, explicit destruction once done.
289   union { stop_cb_t stop_cb_; }; 304   union { stop_cb_t stop_cb_; };
290   305  
HITCBC 291   294 awaitable(stream* self, MB buffers) noexcept 306   345 awaitable(stream* self, MB buffers) noexcept
HITCBC 292   294 : self_(self) 307   345 : self_(self)
HITCBC 293   294 , buffers_(buffers) 308   345 , buffers_(buffers)
294   { 309   {
HITCBC 295   294 } 310   345 }
296   311  
297   /// @pre Not yet awaited (no active stop callback). 312   /// @pre Not yet awaited (no active stop callback).
HITCBC 298   288 awaitable(awaitable&& o) noexcept 313   339 awaitable(awaitable&& o) noexcept
HITCBC 299   288 : self_(o.self_) 314   339 : self_(o.self_)
HITCBC 300   288 , buffers_(o.buffers_) 315   339 , buffers_(o.buffers_)
HITCBC 301   288 , cont_(o.cont_) 316   339 , cont_(o.cont_)
HITCBC 302   288 , ex_(o.ex_) 317   339 , ex_(o.ex_)
HITCBC 303   288 , side_(o.side_) 318   339 , side_(o.side_)
HITCBC 304   288 , claimed_(o.claimed_.load(std::memory_order_relaxed)) 319   339 , claimed_(o.claimed_.load(std::memory_order_relaxed))
HITCBC 305   288 , canceled_(o.canceled_) 320   339 , canceled_(o.canceled_)
HITCBC 306   288 , stop_cb_active_(std::exchange(o.stop_cb_active_, false)) 321   339 , stop_cb_active_(std::exchange(o.stop_cb_active_, false))
307   { 322   {
HITCBC 308   288 } 323   339 }
309   324  
HITCBC 310   582 ~awaitable() 325   684 ~awaitable()
311   { 326   {
HITCBC 312   582 if(stop_cb_active_) 327   684 if(stop_cb_active_)
HITCBC 313   1 stop_cb_.~stop_cb_t(); 328   1 stop_cb_.~stop_cb_t();
314   // Unlink from the side if still parked (e.g. the 329   // Unlink from the side if still parked (e.g. the
315   // coroutine was destroyed while suspended), so a later 330   // coroutine was destroyed while suspended), so a later
316   // peer wake does not dereference a freed claim flag. 331   // peer wake does not dereference a freed claim flag.
HITCBC 317   582 if(side_ && side_->pending_claimed == &claimed_) 332   684 if(side_ && side_->pending_claimed == &claimed_)
318   { 333   {
HITCBC 319   1 side_->pending_cont_ = nullptr; 334   1 side_->pending_cont_ = nullptr;
HITCBC 320   1 side_->pending_ex = {}; 335   1 side_->pending_ex = {};
HITCBC 321   1 side_->pending_claimed = nullptr; 336   1 side_->pending_claimed = nullptr;
322   } 337   }
HITCBC 323   582 } 338   684 }
324   339  
325   awaitable(awaitable const&) = delete; 340   awaitable(awaitable const&) = delete;
326   awaitable& operator=(awaitable const&) = delete; 341   awaitable& operator=(awaitable const&) = delete;
327   awaitable& operator=(awaitable&&) = delete; 342   awaitable& operator=(awaitable&&) = delete;
328   343  
HITCBC 329   294 bool await_ready() const noexcept 344   345 bool await_ready() const noexcept
330   { 345   {
HITCBC 331   294 if(buffers_empty(buffers_)) 346   345 if(buffers_empty(buffers_))
HITCBC 332   8 return true; 347   8 return true;
HITCBC 333   286 auto* st = self_->state_.get(); 348   337 auto* st = self_->state_.get();
HITCBC 334   286 auto& side = st->sides[self_->index_]; 349   337 auto& side = st->sides[self_->index_];
HITCBC 335   564 return st->closed || side.eof || 350   648 return st->closed || side.eof ||
HITCBC 336   564 !side.buf.empty(); 351   648 !side.buf.empty();
337   } 352   }
338   353  
HITCBC 339   31 bool await_suspend( 354   48 bool await_suspend(
340   std::coroutine_handle<> h, 355   std::coroutine_handle<> h,
341   await_context const* env) noexcept 356   await_context const* env) noexcept
342   { 357   {
343   // A callback registered after stop was requested would 358   // A callback registered after stop was requested would
344   // fire inline and post this coroutine, which could then be 359   // fire inline and post this coroutine, which could then be
345   // resumed and finished before the registration returns. 360   // resumed and finished before the registration returns.
HITCBC 346   31 if(env->stop_token.stop_requested()) 361   48 if(env->stop_token.stop_requested())
347   { 362   {
HITCBC 348   2 canceled_ = true; 363   2 canceled_ = true;
HITCBC 349   2 return false; 364   2 return false;
350   } 365   }
HITCBC 351   29 auto& side = self_->state_->sides[ 366   46 auto& side = self_->state_->sides[
HITCBC 352   29 self_->index_]; 367   46 self_->index_];
HITCBC 353   29 cont_.h = h; 368   46 cont_.h = h;
HITCBC 354   29 cont_.owner = env->owner; 369   46 cont_.owner = env->owner;
HITCBC 355   29 ex_ = env->executor; 370   46 ex_ = env->executor;
HITCBC 356   29 side_ = &side; 371   46 side_ = &side;
HITCBC 357   29 side.pending_cont_ = &cont_; 372   46 side.pending_cont_ = &cont_;
HITCBC 358   29 side.pending_ex = env->executor; 373   46 side.pending_ex = env->executor;
HITCBC 359   29 side.pending_claimed = &claimed_; 374   46 side.pending_claimed = &claimed_;
360   375  
HITCBC 361   29 ::new(static_cast<void*>(&stop_cb_)) stop_cb_t( 376   46 ::new(static_cast<void*>(&stop_cb_)) stop_cb_t(
HITCBC 362   29 env->stop_token, cancel_fn{this}); 377   46 env->stop_token, cancel_fn{this});
HITCBC 363   29 stop_cb_active_ = true; 378   46 stop_cb_active_ = true;
364   379  
HITCBC 365   29 return true; 380   46 return true;
366   } 381   }
367   382  
368   [[nodiscard]] results<std::size_t> 383   [[nodiscard]] results<std::size_t>
HITCBC 369   293 await_resume() 384   344 await_resume()
370   { 385   {
HITCBC 371   293 if(stop_cb_active_) 386   344 if(stop_cb_active_)
372   { 387   {
HITCBC 373   28 stop_cb_.~stop_cb_t(); 388   45 stop_cb_.~stop_cb_t();
HITCBC 374   28 stop_cb_active_ = false; 389   45 stop_cb_active_ = false;
375   } 390   }
376   391  
HITCBC 377   293 if(buffers_empty(buffers_)) 392   344 if(buffers_empty(buffers_))
HITCBC 378   8 return {std::error_code(), 0}; 393   8 return {std::error_code(), 0};
379   394  
HITCBC 380   285 if(canceled_) 395   336 if(canceled_)
381   { 396   {
382   // The stop callback posted us but left the side 397   // The stop callback posted us but left the side
383   // untouched; unlink if a peer wake has not already. 398   // untouched; unlink if a peer wake has not already.
HITCBC 384   4 if(side_ && side_->pending_claimed == &claimed_) 399   4 if(side_ && side_->pending_claimed == &claimed_)
385   { 400   {
HITCBC 386   2 side_->pending_cont_ = nullptr; 401   2 side_->pending_cont_ = nullptr;
HITCBC 387   2 side_->pending_ex = {}; 402   2 side_->pending_ex = {};
HITCBC 388   2 side_->pending_claimed = nullptr; 403   2 side_->pending_claimed = nullptr;
389   } 404   }
HITCBC 390   4 return {error::canceled, 0}; 405   4 return {error::canceled, 0};
391   } 406   }
392   407  
HITCBC 393   281 auto* st = self_->state_.get(); 408   332 auto* st = self_->state_.get();
HITCBC 394   281 auto& side = st->sides[ 409   332 auto& side = st->sides[
HITCBC 395   281 self_->index_]; 410   332 self_->index_];
396   411  
HITCBC 397   281 if(st->closed) 412   332 if(st->closed)
HITCBC 398   12 return {error::eof, 0}; 413   12 return {error::eof, 0};
399   414  
HITCBC 400   269 if(side.eof && side.buf.empty()) 415   320 if(side.eof && side.buf.empty())
HITCBC 401   6 return {error::eof, 0}; 416   24 return {error::eof, 0};
402   417  
HITCBC 403   263 if(!side.eof) 418   296 if(!side.eof)
404   { 419   {
HITCBC 405   260 close_guard g{st}; 420   276 close_guard g{st};
HITCBC 406   260 auto ec = st->f.maybe_fail(); 421   276 auto ec = st->f.maybe_fail();
HITCBC 407   206 if(ec) 422   222 if(ec)
HITCBC 408   54 return {ec, 0}; 423   54 return {ec, 0};
HITCBC 409   152 g.disarm(); 424   168 g.disarm();
HITCBC 410   260 } 425   276 }
411   426  
HITCBC 412   465 std::size_t const n = buffer_copy( 427   564 std::size_t const n = buffer_copy(
HITCBC 413   155 buffers_, make_buffer(side.buf), 428   188 buffers_, make_buffer(side.buf),
414   side.max_read_size); 429   side.max_read_size);
HITCBC 415   155 side.buf.erase(0, n); 430   188 side.buf.erase(0, n);
HITCBC 416   155 return {std::error_code(), n}; 431   188 return {std::error_code(), n};
417   } 432   }
418   }; 433   };
HITCBC 419   294 return awaitable{this, buffers}; 434   345 return awaitable{this, buffers};
420   } 435   }
421   436  
422   /** Asynchronously write data to the stream. 437   /** Asynchronously write data to the stream.
423   438  
424   Transfers up to `buffer_size(buffers)` bytes to the 439   Transfers up to `buffer_size(buffers)` bytes to the
425   peer's incoming buffer. If the peer is suspended in 440   peer's incoming buffer. If the peer is suspended in
426 - @ref read_some, it is resumed. Before every write, 441 + @ref read_some, it is resumed. Before transferring data,
427   the attached @ref fuse is consulted to possibly inject 442   the attached @ref fuse is consulted to possibly inject
428   an error. If the fuse fires, the pair is automatically 443   an error. If the fuse fires, the pair is automatically
429   closed. If the stream is closed, returns `error::eof`. 444   closed. If the stream is closed, returns `error::eof`.
430   The returned `std::size_t` is the number of bytes 445   The returned `std::size_t` is the number of bytes
431   transferred. 446   transferred.
432   447  
433 - @param buffers The const buffer sequence containing 448 + The fuse is not consulted for an empty buffer sequence, a
434 - data to write. 449 + canceled write, or a closed pair.
435 -  
436 - @return An awaitable that await-returns `(error_code,std::size_t)`.  
437   450  
438   @par Cancellation 451   @par Cancellation
439   If the environment's stop token is requested, the write 452   If the environment's stop token is requested, the write
440   completes immediately with `error::canceled` and transfers no 453   completes immediately with `error::canceled` and transfers no
441   data. An empty buffer sequence is a no-op that completes 454   data. An empty buffer sequence is a no-op that completes
442   successfully regardless of the stop token. 455   successfully regardless of the stop token.
443   456  
  457 + @par Exception Safety
  458 + Injected I/O conditions are reported via the `error_code`
  459 + component of the result. Throws `std::system_error` when the
  460 + attached @ref fuse is in exception mode and reaches its failure
  461 + point. The pair is closed before the exception propagates.
  462 +
  463 + @throws std::system_error When the attached @ref fuse is in
  464 + exception mode and reaches its failure point.
  465 +
  466 + @param buffers The const buffer sequence containing
  467 + data to write.
  468 +
  469 + @return An awaitable that await-returns `(error_code,std::size_t)`.
  470 +
444   @see @ref fuse, @ref close 471   @see @ref fuse, @ref close
445   */ 472   */
446   template<ConstBufferSequence CB> 473   template<ConstBufferSequence CB>
447   auto 474   auto
HITCBC 448   273 write_some(CB buffers) 475   306 write_some(CB buffers)
449   { 476   {
450   struct awaitable 477   struct awaitable
451   { 478   {
452   stream* self_; 479   stream* self_;
453   CB buffers_; 480   CB buffers_;
454   bool canceled_ = false; 481   bool canceled_ = false;
455   482  
HITCBC 456   273 bool await_ready() const noexcept { return false; } 483   306 bool await_ready() const noexcept { return false; }
457   484  
458   // The write completes synchronously; await_suspend is only 485   // The write completes synchronously; await_suspend is only
459   // used to observe the environment's stop token. Returning 486   // used to observe the environment's stop token. Returning
460   // false means the coroutine does not actually suspend. 487   // false means the coroutine does not actually suspend.
461   bool 488   bool
HITCBC 462   273 await_suspend( 489   306 await_suspend(
463   std::coroutine_handle<>, 490   std::coroutine_handle<>,
464   await_context const* env) noexcept 491   await_context const* env) noexcept
465   { 492   {
HITCBC 466   273 canceled_ = env->stop_token.stop_requested(); 493   306 canceled_ = env->stop_token.stop_requested();
HITCBC 467   273 return false; 494   306 return false;
468   } 495   }
469   496  
470   [[nodiscard]] results<std::size_t> 497   [[nodiscard]] results<std::size_t>
HITCBC 471   273 await_resume() 498   306 await_resume()
472   { 499   {
HITCBC 473   273 std::size_t n = buffer_size(buffers_); 500   306 std::size_t n = buffer_size(buffers_);
HITCBC 474   273 if(n == 0) 501   306 if(n == 0)
HITCBC 475   4 return {std::error_code(), 0}; 502   4 return {std::error_code(), 0};
476   503  
HITCBC 477   269 if(canceled_) 504   302 if(canceled_)
HITCBC 478   1 return {error::canceled, 0}; 505   1 return {error::canceled, 0};
479   506  
HITCBC 480   268 auto* st = self_->state_.get(); 507   301 auto* st = self_->state_.get();
481   508  
HITCBC 482   268 if(st->closed) 509   301 if(st->closed)
MISUBC 483   ✗ return {error::eof, 0}; 510   ✗ return {error::eof, 0};
484   511  
HITCBC 485   268 close_guard g{st}; 512   301 close_guard g{st};
HITCBC 486   268 auto ec = st->f.maybe_fail(); 513   301 auto ec = st->f.maybe_fail();
HITCBC 487   215 if(ec) 514   248 if(ec)
HITCBC 488   53 return {ec, 0}; 515   53 return {ec, 0};
HITCBC 489   162 g.disarm(); 516   195 g.disarm();
490   517  
HITCBC 491   162 int peer = 1 - self_->index_; 518   195 int peer = 1 - self_->index_;
HITCBC 492   162 auto& side = st->sides[peer]; 519   195 auto& side = st->sides[peer];
493   520  
HITCBC 494   162 std::size_t const old_size = side.buf.size(); 521   195 std::size_t const old_size = side.buf.size();
HITCBC 495   162 side.buf.resize(old_size + n); 522   195 side.buf.resize(old_size + n);
HITCBC 496   162 buffer_copy(make_buffer( 523   195 buffer_copy(make_buffer(
HITCBC 497   162 side.buf.data() + old_size, n), 524   195 side.buf.data() + old_size, n),
HITCBC 498   162 buffers_, n); 525   195 buffers_, n);
499   526  
HITCBC 500   162 state::wake(side); 527   195 state::wake(side);
501   528  
HITCBC 502   162 return {std::error_code(), n}; 529   195 return {std::error_code(), n};
HITCBC 503   268 } 530   301 }
504   }; 531   };
HITCBC 505   273 return awaitable{this, buffers}; 532   306 return awaitable{this, buffers};
506   } 533   }
507   534  
508   /** Inject data into this stream's peer for reading. 535   /** Inject data into this stream's peer for reading.
509   536  
510   Appends data directly to the peer's incoming buffer, 537   Appends data directly to the peer's incoming buffer,
511   bypassing the fuse. If the peer is suspended in 538   bypassing the fuse. If the peer is suspended in
512   @ref read_some, it is resumed. This is test setup, 539   @ref read_some, it is resumed. This is test setup,
513   not an operation under test. 540   not an operation under test.
514   541  
515   @param sv The data to inject. 542   @param sv The data to inject.
516   543  
517   @see @ref make_stream_pair 544   @see @ref make_stream_pair
518   */ 545   */
519   void 546   void
HITCBC 520   93 provide(std::string_view sv) 547   94 provide(std::string_view sv)
521   { 548   {
HITCBC 522   93 int peer = 1 - index_; 549   94 int peer = 1 - index_;
HITCBC 523   93 auto& side = state_->sides[peer]; 550   94 auto& side = state_->sides[peer];
HITCBC 524   93 side.buf.append(sv); 551   94 side.buf.append(sv);
HITCBC 525   93 state::wake(side); 552   94 state::wake(side);
HITCBC 526   93 } 553   94 }
527   554  
528   /** Read from this stream and verify the content. 555   /** Read from this stream and verify the content.
529   556  
530   Reads exactly `expected.size()` bytes from the stream 557   Reads exactly `expected.size()` bytes from the stream
531   and compares against the expected string. The read goes 558   and compares against the expected string. The read goes
532 - through the normal path including the fuse. 559 + through the normal path including the fuse. The call
  560 + blocks the calling thread until the read completes.
  561 +
  562 + The error code is set if a read error occurs, for example
  563 + a fuse injection. The bool is true if the data matches.
  564 +
  565 + @pre At least `expected.size()` bytes are buffered, or the
  566 + pair is closed, or the peer called @ref close. Otherwise
  567 + the read waits for a write that cannot happen on the
  568 + blocked thread, and the call never returns.
  569 +
  570 + @throws std::system_error When the attached @ref fuse is in
  571 + exception mode and reaches its failure point.
533   572  
534   @param expected The expected content. 573   @param expected The expected content.
535   574  
536 - @return A pair of `(error_code, bool)`. The error_code 575 + @return A pair of `(error_code, bool)`.
537 - is set if a read error occurs (e.g. fuse injection).  
538 - The bool is true if the data matches.  
539   576  
540   @see @ref provide 577   @see @ref provide
541   */ 578   */
542   std::pair<std::error_code, bool> 579   std::pair<std::error_code, bool>
HITCBC 543   38 expect(std::string_view expected) 580   38 expect(std::string_view expected)
544   { 581   {
HITCBC 545   38 std::error_code result; 582   38 std::error_code result;
HITCBC 546   38 bool match = false; 583   38 bool match = false;
HITCBC 547   141 run_blocking()([]( 584   141 run_blocking()([](
548   stream& self, 585   stream& self,
549   std::string_view expected, 586   std::string_view expected,
550   std::error_code& result, 587   std::error_code& result,
551   bool& match) -> task<> 588   bool& match) -> task<>
552   { 589   {
553   std::string buf(expected.size(), '\0'); 590   std::string buf(expected.size(), '\0');
554   auto [ec, n] = co_await read( 591   auto [ec, n] = co_await read(
555   self, mutable_buffer( 592   self, mutable_buffer(
556   buf.data(), buf.size())); 593   buf.data(), buf.size()));
557   if(ec) 594   if(ec)
558   { 595   {
559   result = ec; 596   result = ec;
560   co_return; 597   co_return;
561   } 598   }
562   match = (std::string_view( 599   match = (std::string_view(
563   buf.data(), n) == expected); 600   buf.data(), n) == expected);
HITCBC 564   161 }(*this, expected, result, match)); 601   161 }(*this, expected, result, match));
HITCBC 565   58 return {result, match}; 602   58 return {result, match};
566   } 603   }
567   604  
568   /** Return the stream's pending read data. 605   /** Return the stream's pending read data.
569   606  
570   Returns a view of the data waiting to be read 607   Returns a view of the data waiting to be read
571   from this stream. This is a direct peek at the 608   from this stream. This is a direct peek at the
572   internal buffer, bypassing the fuse. 609   internal buffer, bypassing the fuse.
573   610  
574   @return A view of the pending data. 611   @return A view of the pending data.
575   612  
576   @see @ref provide, @ref expect 613   @see @ref provide, @ref expect
577   */ 614   */
578   std::string_view 615   std::string_view
HITCBC 579   3 data() const noexcept 616   4 data() const noexcept
580   { 617   {
HITCBC 581   3 return state_->sides[index_].buf; 618   4 return state_->sides[index_].buf;
582   } 619   }
583   }; 620   };
584   621  
585   /** Create a connected pair of test streams. 622   /** Create a connected pair of test streams.
586   623  
587   Data written to one stream becomes readable on the other. 624   Data written to one stream becomes readable on the other.
588   If a coroutine calls @ref stream::read_some when no data 625   If a coroutine calls @ref stream::read_some when no data
589   is available, it suspends until the peer writes. Before 626   is available, it suspends until the peer writes. Before
590 - every read or write, the @ref fuse is consulted to 627 + a read or write transfers data, the @ref fuse is consulted
591 - possibly inject an error for testing fault scenarios. 628 + to possibly inject an error for testing fault scenarios.
592   When the fuse fires, the pair is automatically closed. 629   When the fuse fires, the pair is automatically closed.
  630 + Empty, canceled and closed-pair operations, and reads after
  631 + the peer called @ref stream::close, skip the fuse.
593   632  
594   @param f The fuse used to inject errors during operations. 633   @param f The fuse used to inject errors during operations.
595   634  
596   @return A pair of connected streams. 635   @return A pair of connected streams.
597   636  
598   @see @ref stream, @ref fuse 637   @see @ref stream, @ref fuse
599   */ 638   */
600   inline std::pair<stream, stream> 639   inline std::pair<stream, stream>
HITCBC 601   303 make_stream_pair(fuse f = {}) 640   321 make_stream_pair(fuse f = {})
602   { 641   {
HITCBC 603   303 auto sp = std::make_shared<stream::state>(std::move(f)); 642   321 auto sp = std::make_shared<stream::state>(std::move(f));
HITCBC 604   606 return {stream(sp, 0), stream(sp, 1)}; 643   642 return {stream(sp, 0), stream(sp, 1)};
HITCBC 605   303 } 644   321 }
606   645  
607   } // test 646   } // test
608   } // capy 647   } // capy
609   } // boost 648   } // boost
610   649  
611   #endif 650   #endif