TLA Line data Source code
1 : //
2 : // Copyright (c) 2025 Vinnie Falco (vinnie.falco@gmail.com)
3 : // Copyright (c) 2026 Michael Vandeberg
4 : //
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)
7 : //
8 : // Official repository: https://github.com/cppalliance/capy
9 : //
10 :
11 : #ifndef BOOST_CAPY_IO_WRITE_NOW_HPP
12 : #define BOOST_CAPY_IO_WRITE_NOW_HPP
13 :
14 : #include <boost/capy/detail/config.hpp>
15 : #include <boost/capy/detail/await_suspend_helper.hpp>
16 : #include <boost/capy/buffers.hpp>
17 : #include <boost/capy/detail/consuming_buffers.hpp>
18 : #include <boost/capy/concept/context_awaitable.hpp>
19 : #include <boost/capy/concept/write_stream.hpp>
20 : #include <coroutine>
21 : #include <boost/capy/ex/executor_ref.hpp>
22 : #include <boost/capy/ex/frame_allocator.hpp>
23 : #include <boost/capy/ex/abandon.hpp>
24 : #include <boost/capy/ex/await_context.hpp>
25 : #include <boost/capy/results.hpp>
26 :
27 : #include <cstddef>
28 : #include <exception>
29 : #include <new>
30 : #include <stop_token>
31 : #include <utility>
32 :
33 : #ifndef BOOST_CAPY_WRITE_NOW_WORKAROUND
34 : # if defined(__GNUC__) && !defined(__clang__)
35 : # define BOOST_CAPY_WRITE_NOW_WORKAROUND 1
36 : # else
37 : # define BOOST_CAPY_WRITE_NOW_WORKAROUND 0
38 : # endif
39 : #endif
40 :
41 : namespace boost {
42 : namespace capy {
43 :
44 : /** Eagerly writes complete buffer sequences with frame caching.
45 :
46 : This class wraps a @ref WriteStream and provides an `operator()`
47 : that writes an entire buffer sequence, attempting to complete
48 : synchronously. If every `write_some` completes without suspending,
49 : the entire operation finishes in `await_ready` with no coroutine
50 : suspension.
51 :
52 : The class maintains a one-element coroutine frame cache. After
53 : the first call, subsequent calls reuse the cached frame memory,
54 : avoiding repeated allocation for the internal coroutine.
55 :
56 : @pre Only one operation may be outstanding at a time. A new call to
57 : `operator()` must not be made until the previous operation has
58 : completed (i.e., the returned awaitable is fully consumed).
59 :
60 : Destroying the returned operation object while it is being awaited
61 : calls `std::terminate`, except while its chain is unwound after an
62 : @ref abandon.
63 :
64 : @par Thread Safety
65 : Distinct objects: Safe.
66 : Shared objects: Unsafe.
67 :
68 : @note With `BOOST_CAPY_WRITE_NOW_WORKAROUND` (the default on GCC)
69 : the caller always suspends. When every `write_some` is ready, the
70 : operation still completes inline without an executor hop.
71 :
72 : @par Example
73 :
74 : @code
75 : template< WriteStream Stream >
76 : task<> send_messages( Stream& stream )
77 : {
78 : write_now wn( stream );
79 : auto [ec1, n1] = co_await wn( make_buffer( std::string_view( "hello" ) ) );
80 : if( ec1 )
81 : throw std::system_error( ec1 );
82 : auto [ec2, n2] = co_await wn( make_buffer( std::string_view( "world" ) ) );
83 : if( ec2 )
84 : throw std::system_error( ec2 );
85 : }
86 : @endcode
87 :
88 : @tparam Stream The stream type, must satisfy @ref WriteStream.
89 :
90 : @see @ref write, @ref write_some, @ref WriteStream, @ref ConstBufferSequence
91 : */
92 : template<class Stream>
93 : requires WriteStream<Stream>
94 : class write_now
95 : {
96 : Stream& stream_;
97 : void* cached_frame_ = nullptr;
98 : std::size_t cached_size_ = 0;
99 :
100 : struct [[nodiscard]] BOOST_CAPY_CORO_AWAIT_ELIDABLE
101 : op_type
102 : {
103 : struct promise_type
104 : {
105 : results<std::size_t> result_;
106 : std::exception_ptr ep_;
107 : std::coroutine_handle<> cont_{nullptr};
108 : await_context const* env_ = nullptr;
109 : bool done_ = false;
110 :
111 : // The awaiting op_type while a parent awaits this frame.
112 : op_type* owner_ = nullptr;
113 :
114 HIT 77 : op_type get_return_object()
115 : {
116 : return op_type{
117 : std::coroutine_handle<
118 77 : promise_type>::from_promise(*this)};
119 : }
120 :
121 77 : auto initial_suspend() noexcept
122 : {
123 : #if BOOST_CAPY_WRITE_NOW_WORKAROUND
124 77 : return std::suspend_always{};
125 : #else
126 : return std::suspend_never{};
127 : #endif
128 : }
129 :
130 73 : auto final_suspend() noexcept
131 : {
132 : struct awaiter
133 : {
134 : promise_type* p_;
135 :
136 73 : bool await_ready() const noexcept
137 : {
138 73 : return false;
139 : }
140 :
141 73 : std::coroutine_handle<> await_suspend(std::coroutine_handle<>) const noexcept
142 : {
143 73 : p_->done_ = true;
144 73 : if(!p_->cont_)
145 : return std::noop_coroutine(); // LCOV_EXCL_LINE cont_ always set on this (suspend_always) path
146 73 : return p_->cont_;
147 : }
148 :
149 : void await_resume() const noexcept {} // LCOV_EXCL_LINE final_suspend awaiter, never resumed
150 : };
151 73 : return awaiter{this};
152 : }
153 :
154 50 : void return_value(
155 : results<std::size_t> r) noexcept
156 : {
157 50 : result_ = r;
158 50 : }
159 :
160 23 : void unhandled_exception()
161 : {
162 23 : ep_ = std::current_exception();
163 23 : }
164 :
165 : std::suspend_always yield_value(int) noexcept
166 : {
167 : return {};
168 : }
169 :
170 : template<class A>
171 94 : auto await_transform(A&& a)
172 : {
173 : using decayed = std::decay_t<A>;
174 : if constexpr (ContextAwaitable<decayed>)
175 : {
176 : // Not context_awaiter: an exception from the
177 : // stream's await_suspend is the caller's to handle.
178 : struct wrapper
179 : {
180 : decayed inner_;
181 : promise_type* p_;
182 :
183 94 : bool await_ready()
184 : {
185 94 : return inner_.await_ready();
186 : }
187 :
188 : // The inner operation may resume or destroy this
189 : // frame on another thread before control returns
190 : // here, so the handle must not round-trip through
191 : // the frame.
192 94 : auto await_suspend(std::coroutine_handle<> h)
193 : {
194 93 : return detail::symmetric_transfer(
195 : detail::call_await_suspend(
196 : &inner_, h,
197 187 : p_->env_));
198 : }
199 :
200 91 : decltype(auto) await_resume()
201 : {
202 : // The resumption may arrive on another thread.
203 91 : set_current_frame_allocator(
204 91 : p_->env_->frame_allocator);
205 91 : return inner_.await_resume();
206 : }
207 : };
208 : return wrapper{
209 94 : std::forward<A>(a), this};
210 : }
211 : else
212 : {
213 : return std::forward<A>(a);
214 : }
215 : }
216 :
217 : static void*
218 77 : operator new(
219 : std::size_t size,
220 : write_now& self,
221 : auto&)
222 : {
223 77 : if(self.cached_frame_ &&
224 6 : self.cached_size_ >= size)
225 5 : return self.cached_frame_;
226 72 : void* p = ::operator new(size);
227 72 : if(self.cached_frame_)
228 1 : ::operator delete(self.cached_frame_);
229 72 : self.cached_frame_ = p;
230 72 : self.cached_size_ = size;
231 72 : return p;
232 : }
233 :
234 : static void
235 77 : operator delete(void*, std::size_t) noexcept
236 : {
237 77 : }
238 : };
239 :
240 : std::coroutine_handle<promise_type> h_;
241 :
242 152 : ~op_type()
243 : {
244 152 : if(h_)
245 : {
246 : // Only the unwind of an abandoned chain destroys a frame
247 : // that is still awaited.
248 77 : auto& p = h_.promise();
249 79 : if(!p.done_ && p.owner_ &&
250 2 : !(p.env_->owner && p.env_->owner->abandoned()))
251 : std::terminate(); // LCOV_EXCL_LINE reached only in a death test's child process
252 77 : h_.destroy();
253 : }
254 152 : }
255 :
256 : op_type(op_type const&) = delete;
257 : op_type& operator=(op_type const&) = delete;
258 :
259 75 : op_type(op_type&& other) noexcept
260 75 : : h_(std::exchange(other.h_, nullptr))
261 : {
262 75 : }
263 :
264 : op_type& operator=(op_type&&) = delete;
265 :
266 75 : bool await_ready() const noexcept
267 : {
268 75 : return h_.promise().done_;
269 : }
270 :
271 75 : std::coroutine_handle<> await_suspend(
272 : std::coroutine_handle<> cont,
273 : await_context const* env)
274 : {
275 75 : auto& p = h_.promise();
276 75 : p.cont_ = cont;
277 75 : p.env_ = env;
278 75 : p.owner_ = this;
279 75 : return h_;
280 : }
281 :
282 73 : [[nodiscard]] results<std::size_t> await_resume()
283 : {
284 73 : auto& p = h_.promise();
285 73 : p.owner_ = nullptr;
286 73 : if(p.ep_)
287 23 : std::rethrow_exception(p.ep_);
288 50 : return p.result_;
289 : }
290 :
291 : private:
292 77 : explicit op_type(
293 : std::coroutine_handle<promise_type> h)
294 77 : : h_(h)
295 : {
296 77 : }
297 : };
298 :
299 : public:
300 : /// Destroy the object, freeing the cached coroutine frame.
301 71 : ~write_now()
302 : {
303 71 : if(cached_frame_)
304 71 : ::operator delete(cached_frame_);
305 71 : }
306 :
307 : /** Construct from a stream reference.
308 :
309 : @param s The stream to write to. Must outlive this object.
310 : */
311 : explicit
312 71 : write_now(Stream& s) noexcept
313 71 : : stream_(s)
314 : {
315 71 : }
316 :
317 : /// Copy construction is disabled. The frame cache is per-instance.
318 : write_now(write_now const&) = delete;
319 :
320 : /// Copy assignment is disabled. The frame cache is per-instance.
321 : write_now& operator=(write_now const&) = delete;
322 :
323 : /** Eagerly write the entire buffer sequence.
324 :
325 : Writes data to the stream by calling `write_some` repeatedly
326 : until the entire buffer sequence is written or an error
327 : occurs. The operation attempts to complete synchronously:
328 : if every `write_some` completes without suspending, the
329 : entire operation finishes in `await_ready`.
330 :
331 : When the fast path cannot complete, the coroutine suspends
332 : and continues asynchronously. The internal coroutine frame
333 : is cached and reused across calls.
334 :
335 : On success, `n` equals `buffer_size(buffers)`. On error, `n`
336 : counts the bytes written before the error. Compare error
337 : codes to conditions:
338 : @li `cond::canceled`: the operation was cancelled.
339 : @li `std::errc::broken_pipe`: the peer closed the connection.
340 :
341 : @pre This object outlives the returned awaitable, including
342 : its destruction. The awaitable uses this object's cached frame.
343 :
344 : @throws std::bad_alloc If allocating the coroutine frame fails.
345 : @throws Any exception thrown by the stream's `write_some`.
346 :
347 : @note With `BOOST_CAPY_WRITE_NOW_WORKAROUND` (the default on GCC)
348 : the caller always suspends. See the class documentation. When the
349 : workaround is off and a `write_some` fails without suspending,
350 : `n` excludes any bytes that failing call reported.
351 :
352 : @par Example
353 :
354 : @code
355 : write_now wn( stream );
356 : auto [ec, n] = co_await wn( make_buffer( body ) );
357 : if( ec )
358 : throw std::system_error( ec );
359 : @endcode
360 :
361 : @param buffers The buffer sequence to write. Passed by
362 : value to ensure the sequence lives in the coroutine
363 : frame across suspension points. The memory it refers to
364 : is not copied and must remain valid until the operation
365 : completes.
366 :
367 : @return An awaitable that await-returns `(error_code,std::size_t)`.
368 :
369 : @see @ref write, @ref write_some, @ref WriteStream
370 : */
371 : // GCC falsely warns that the coroutine promise's
372 : // placement operator new(size_t, write_now&, auto&)
373 : // mismatches operator delete(void*, size_t). Per the
374 : // standard, coroutine deallocation lookup is separate.
375 : #if defined(__GNUC__) && !defined(__clang__)
376 : #pragma GCC diagnostic push
377 : #pragma GCC diagnostic ignored "-Wmismatched-new-delete"
378 : #endif
379 :
380 : #if BOOST_CAPY_WRITE_NOW_WORKAROUND
381 : template<ConstBufferSequence Buffers>
382 : op_type
383 77 : operator()(Buffers buffers)
384 : {
385 : std::size_t const total_size = buffer_size(buffers);
386 : std::size_t total_written = 0;
387 : detail::consuming_buffers cb(buffers);
388 : while(total_written < total_size)
389 : {
390 : auto r =
391 : co_await stream_.write_some(cb.data());
392 : cb.consume(std::get<1>(r));
393 : total_written += std::get<1>(r);
394 : if(std::get<0>(r))
395 : co_return results<std::size_t>{
396 : std::get<0>(r), total_written};
397 : }
398 : co_return results<std::size_t>{
399 : std::error_code(), total_written};
400 154 : }
401 : #else
402 : template<ConstBufferSequence Buffers>
403 : op_type
404 : operator()(Buffers buffers)
405 : {
406 : std::size_t const total_size = buffer_size(buffers);
407 : std::size_t total_written = 0;
408 :
409 : // GCC ICE in expand_expr_real_1 (expr.cc:11376)
410 : // when the buffer slice spans a co_yield, so
411 : // the GCC path uses a separate simple coroutine.
412 : detail::consuming_buffers cb(buffers);
413 : while(total_written < total_size)
414 : {
415 : auto inner = stream_.write_some(cb.data());
416 : if(!inner.await_ready())
417 : break;
418 : auto r = inner.await_resume();
419 : if(std::get<0>(r))
420 : co_return results<std::size_t>{
421 : std::get<0>(r), total_written};
422 : cb.consume(std::get<1>(r));
423 : total_written += std::get<1>(r);
424 : }
425 :
426 : if(total_written >= total_size)
427 : co_return results<std::size_t>{
428 : std::error_code(), total_written};
429 :
430 : co_yield 0;
431 :
432 : while(total_written < total_size)
433 : {
434 : auto r =
435 : co_await stream_.write_some(cb.data());
436 : cb.consume(std::get<1>(r));
437 : total_written += std::get<1>(r);
438 : if(std::get<0>(r))
439 : co_return results<std::size_t>{
440 : std::get<0>(r), total_written};
441 : }
442 : co_return results<std::size_t>{
443 : std::error_code(), total_written};
444 : }
445 : #endif
446 :
447 : #if defined(__GNUC__) && !defined(__clang__)
448 : #pragma GCC diagnostic pop
449 : #endif
450 : };
451 :
452 : template<WriteStream S>
453 : write_now(S&) -> write_now<S>;
454 :
455 : } // namespace capy
456 : } // namespace boost
457 :
458 : #endif
|