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_ANY_WRITE_STREAM_HPP
12 : #define BOOST_CAPY_IO_ANY_WRITE_STREAM_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/buffer_array.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/await_context.hpp>
22 : #include <boost/capy/results.hpp>
23 :
24 : #include <concepts>
25 : #include <coroutine>
26 : #include <cstddef>
27 : #include <exception>
28 : #include <new>
29 : #include <span>
30 : #include <stop_token>
31 : #include <system_error>
32 : #include <utility>
33 :
34 : namespace boost {
35 : namespace capy {
36 :
37 : /** Dispatches `write_some` through a type-erased vtable, using preallocated awaitable storage.
38 :
39 : This class provides type erasure for any type satisfying the
40 : @ref WriteStream concept, enabling runtime polymorphism for
41 : write operations. It uses cached awaitable storage to achieve
42 : zero steady-state allocation after construction.
43 :
44 : The wrapper supports two construction modes:
45 : - **Owning**: Pass by value to transfer ownership. The wrapper
46 : allocates storage and owns the stream.
47 : - **Reference**: Pass a pointer to wrap without ownership. The
48 : pointed-to stream must outlive this wrapper.
49 :
50 : @par Awaitable Preallocation
51 : The constructor allocates the storage for the type-erased awaitable
52 : once, so operations do not allocate it piecemeal as traffic
53 : arrives.
54 :
55 : @par Immediate Completion
56 : Operations complete immediately without suspending when the
57 : buffer sequence is empty, or when the underlying stream's
58 : awaitable reports readiness via `await_ready`.
59 :
60 : @par Thread Safety
61 : Not thread-safe. Concurrent operations on the same wrapper
62 : are undefined behavior.
63 :
64 : @par Example
65 : @par !example example
66 :
67 :
68 : @see @ref any_read_stream, @ref any_stream, @ref WriteStream
69 : */
70 : class any_write_stream
71 : {
72 : struct vtable;
73 :
74 : template<WriteStream S>
75 : struct vtable_for_impl;
76 :
77 : // ordered for cache line coherence
78 : void* stream_ = nullptr;
79 : vtable const* vt_ = nullptr;
80 : void* cached_awaitable_ = nullptr;
81 : void* storage_ = nullptr;
82 : bool awaitable_active_ = false;
83 : // The flag of the awaitable whose operation is active, cleared
84 : // when the stream ends that operation itself.
85 : bool* owner_ = nullptr;
86 :
87 : void
88 HIT 208 : disown() noexcept
89 : {
90 208 : if(owner_)
91 6 : *std::exchange(owner_, nullptr) = false;
92 208 : }
93 :
94 : public:
95 : /** Destroy the wrapper.
96 :
97 : Ends any operation in flight, then destroys the owned stream
98 : (if any) and releases the cached awaitable storage.
99 : */
100 : ~any_write_stream();
101 :
102 : /** Construct a default instance.
103 :
104 : Constructs an empty wrapper. @ref has_value and `operator bool`
105 : report the empty state; calling @ref write_some before the
106 : wrapper holds a stream is undefined behavior.
107 : */
108 10 : any_write_stream() = default;
109 :
110 : /** Copy construction is disabled.
111 :
112 : The awaitable cache is per-instance and cannot be shared.
113 :
114 : @param other The wrapper that would be copied.
115 : */
116 : any_write_stream(any_write_stream const& other) = delete;
117 :
118 : /** Copy assignment is disabled.
119 :
120 : The awaitable cache is per-instance and cannot be shared.
121 :
122 : @param other The wrapper that would be assigned from.
123 :
124 : @return A reference to `*this`.
125 : */
126 : any_write_stream& operator=(any_write_stream const& other) = delete;
127 :
128 : /** Construct by moving.
129 :
130 : Transfers ownership of the wrapped stream (if owned) and
131 : cached awaitable storage from `other`. After the move, `other` is
132 : in a default-constructed state.
133 :
134 : @param other The wrapper to move from.
135 : */
136 2 : any_write_stream(any_write_stream&& other) noexcept
137 2 : : stream_(std::exchange(other.stream_, nullptr))
138 2 : , vt_(std::exchange(other.vt_, nullptr))
139 2 : , cached_awaitable_(std::exchange(other.cached_awaitable_, nullptr))
140 2 : , storage_(std::exchange(other.storage_, nullptr))
141 2 : , awaitable_active_(std::exchange(other.awaitable_active_, false))
142 : {
143 2 : other.disown();
144 2 : }
145 :
146 : /** Assign by moving.
147 :
148 : Destroys any owned stream and releases existing resources,
149 : then transfers ownership from `other`.
150 :
151 : @param other The wrapper to move from.
152 : @return Reference to this wrapper.
153 : */
154 : any_write_stream&
155 : operator=(any_write_stream&& other) noexcept;
156 :
157 : /** Construct by taking ownership of a WriteStream.
158 :
159 : Allocates storage and moves the stream into this wrapper.
160 : The wrapper owns the stream and destroys it.
161 :
162 : @par Exception Safety
163 : Strong guarantee. If an allocation throws, nothing is leaked.
164 :
165 : @throws std::bad_alloc If allocation fails.
166 : @throws Any exception thrown by moving `s`.
167 :
168 : @param s The stream to take ownership of.
169 : */
170 : template<WriteStream S>
171 : requires (!std::same_as<std::decay_t<S>, any_write_stream>)
172 : any_write_stream(S s);
173 :
174 : /** Construct by wrapping a WriteStream without ownership.
175 :
176 : Wraps the given stream by pointer. The stream must remain
177 : valid for the lifetime of this wrapper.
178 :
179 : @throws std::bad_alloc If allocating the awaitable storage fails.
180 :
181 : @param s Pointer to the stream to wrap.
182 : */
183 : template<WriteStream S>
184 : any_write_stream(S* s);
185 :
186 : /** Check if the wrapper contains a valid stream.
187 :
188 : @return `true` if wrapping a stream, `false` if default-constructed
189 : or moved-from.
190 : */
191 : bool
192 26 : has_value() const noexcept
193 : {
194 26 : return stream_ != nullptr;
195 : }
196 :
197 : /** Check if the wrapper contains a valid stream.
198 :
199 : @return `true` if wrapping a stream, `false` if default-constructed
200 : or moved-from.
201 : */
202 : explicit
203 3 : operator bool() const noexcept
204 : {
205 3 : return has_value();
206 : }
207 :
208 : /** Asynchronously write some data from the buffer sequence.
209 :
210 : Writes data from the provided buffer sequence. The operation
211 : completes when at least one byte is written, or an error
212 : occurs.
213 :
214 : @pre The wrapper must contain a valid stream (`has_value() == true`).
215 :
216 : @par Immediate Completion
217 : The operation completes immediately without suspending
218 : the calling coroutine when:
219 : @li The buffer sequence is empty, returning `{error_code{}, 0}`.
220 : @li The underlying stream's awaitable reports immediate
221 : readiness via `await_ready`.
222 :
223 : @par After an Error
224 : A subsequent call is permitted. The wrapper forwards directly
225 : to the underlying stream, imposing no stricter rule than
226 : @ref WriteStream.
227 :
228 : @note This is a partial operation and may not process the
229 : entire buffer sequence. Use the composed @ref write algorithm
230 : for guaranteed complete transfer.
231 :
232 : @param buffers The buffer sequence containing data to write.
233 : Passed by value to ensure the sequence lives in the
234 : coroutine frame across suspension points.
235 :
236 : @return An awaitable that await-returns `(error_code,std::size_t)`.
237 : */
238 : template<ConstBufferSequence CB>
239 : auto
240 : write_some(CB buffers);
241 :
242 : protected:
243 : /** End the operation in flight, if any.
244 :
245 : Destroys the wrapped stream's active operation, which may refer
246 : to the stream, so an owner must call this before destroying the
247 : stream. The awaitable that started the operation no longer ends
248 : it.
249 : */
250 : void
251 : end_operation() noexcept;
252 :
253 : /** Rebind to a new stream after move.
254 :
255 : Updates the internal pointer to reference a new stream object,
256 : for use when the stream object has moved to a new location.
257 :
258 : @param new_stream The new stream to bind to. Must be the same
259 : type as the original stream.
260 :
261 : @note Terminates if called with a stream of different type
262 : than the original.
263 : */
264 : template<WriteStream S>
265 : void
266 : rebind(S& new_stream) noexcept
267 : {
268 : if(vt_ != &vtable_for_impl<S>::value)
269 : std::terminate();
270 : stream_ = &new_stream;
271 : }
272 : };
273 :
274 : struct any_write_stream::vtable
275 : {
276 : // ordered by call frequency for cache line coherence
277 : void (*construct_awaitable)(
278 : void* stream,
279 : void* storage,
280 : std::span<const_buffer const> buffers);
281 : bool (*await_ready)(void*);
282 : std::coroutine_handle<> (*await_suspend)(void*, std::coroutine_handle<>, await_context const*);
283 : results<std::size_t> (*await_resume)(void*);
284 : void (*destroy_awaitable)(void*) noexcept;
285 : std::size_t awaitable_size;
286 : std::size_t awaitable_align;
287 : void (*destroy)(void*) noexcept;
288 : };
289 :
290 : template<WriteStream S>
291 : struct any_write_stream::vtable_for_impl
292 : {
293 : using Awaitable = decltype(std::declval<S&>().write_some(
294 : std::span<const_buffer const>{}));
295 :
296 : static void
297 3 : do_destroy_impl(void* stream) noexcept
298 : {
299 3 : static_cast<S*>(stream)->~S();
300 3 : }
301 :
302 : static void
303 86 : construct_awaitable_impl(
304 : void* stream,
305 : void* storage,
306 : std::span<const_buffer const> buffers)
307 : {
308 86 : auto& s = *static_cast<S*>(stream);
309 86 : ::new(storage) Awaitable(s.write_some(buffers));
310 86 : }
311 :
312 : static constexpr vtable value = {
313 : &construct_awaitable_impl,
314 86 : +[](void* p) {
315 86 : return static_cast<Awaitable*>(p)->await_ready();
316 : },
317 74 : +[](void* p, std::coroutine_handle<> h, await_context const* env) {
318 74 : return detail::call_await_suspend(
319 74 : static_cast<Awaitable*>(p), h, env);
320 : },
321 77 : +[](void* p) {
322 77 : return static_cast<Awaitable*>(p)->await_resume();
323 : },
324 95 : +[](void* p) noexcept {
325 12 : static_cast<Awaitable*>(p)->~Awaitable();
326 : },
327 : sizeof(Awaitable),
328 : alignof(Awaitable),
329 : &do_destroy_impl
330 : };
331 : };
332 :
333 : inline void
334 187 : any_write_stream::end_operation() noexcept
335 : {
336 187 : disown();
337 187 : if(awaitable_active_)
338 : {
339 6 : vt_->destroy_awaitable(cached_awaitable_);
340 6 : awaitable_active_ = false;
341 : }
342 187 : }
343 :
344 : inline
345 125 : any_write_stream::~any_write_stream()
346 : {
347 125 : end_operation();
348 125 : if(cached_awaitable_)
349 101 : ::operator delete(cached_awaitable_);
350 125 : if(storage_)
351 : {
352 2 : vt_->destroy(stream_);
353 2 : ::operator delete(storage_);
354 : }
355 125 : }
356 :
357 : inline any_write_stream&
358 19 : any_write_stream::operator=(any_write_stream&& other) noexcept
359 : {
360 19 : if(this != &other)
361 : {
362 19 : end_operation();
363 19 : other.disown();
364 19 : if(cached_awaitable_)
365 7 : ::operator delete(cached_awaitable_);
366 19 : if(storage_)
367 : {
368 1 : vt_->destroy(stream_);
369 1 : ::operator delete(storage_);
370 : }
371 19 : stream_ = std::exchange(other.stream_, nullptr);
372 19 : vt_ = std::exchange(other.vt_, nullptr);
373 19 : cached_awaitable_ = std::exchange(other.cached_awaitable_, nullptr);
374 19 : storage_ = std::exchange(other.storage_, nullptr);
375 19 : awaitable_active_ = std::exchange(other.awaitable_active_, false);
376 : }
377 19 : return *this;
378 : }
379 :
380 : template<WriteStream S>
381 : requires (!std::same_as<std::decay_t<S>, any_write_stream>)
382 4 : any_write_stream::any_write_stream(S s)
383 4 : : vt_(&vtable_for_impl<S>::value)
384 : {
385 : struct guard {
386 : any_write_stream* self;
387 : bool committed = false;
388 4 : ~guard() {
389 4 : if(!committed && self->storage_) {
390 1 : if(self->stream_)
391 : self->vt_->destroy(self->stream_); // LCOV_EXCL_LINE OOM rollback: only when the cached-awaitable allocation throws
392 1 : ::operator delete(self->storage_);
393 1 : self->storage_ = nullptr;
394 1 : self->stream_ = nullptr;
395 : }
396 4 : }
397 4 : } g{this};
398 :
399 4 : storage_ = ::operator new(sizeof(S));
400 4 : stream_ = ::new(storage_) S(std::move(s));
401 :
402 : // Preallocate the awaitable storage
403 3 : cached_awaitable_ = ::operator new(vt_->awaitable_size);
404 :
405 3 : g.committed = true;
406 4 : }
407 :
408 : template<WriteStream S>
409 105 : any_write_stream::any_write_stream(S* s)
410 105 : : stream_(s)
411 105 : , vt_(&vtable_for_impl<S>::value)
412 : {
413 : // Preallocate the awaitable storage
414 105 : cached_awaitable_ = ::operator new(vt_->awaitable_size);
415 105 : }
416 :
417 : template<ConstBufferSequence CB>
418 : auto
419 91 : any_write_stream::write_some(CB buffers)
420 : {
421 : struct awaitable
422 : {
423 : any_write_stream* self_;
424 : detail::const_buffer_array<detail::max_iovec_> ba_;
425 : // Set while this awaitable, not another on the same stream,
426 : // holds the stream's inner awaitable.
427 : bool owns_ = false;
428 :
429 : // A chain unwound while suspended here never reaches
430 : // await_resume, so the inner awaitable is destroyed here.
431 178 : ~awaitable()
432 : {
433 178 : if(owns_)
434 : {
435 3 : self_->vt_->destroy_awaitable(self_->cached_awaitable_);
436 3 : self_->awaitable_active_ = false;
437 3 : self_->owner_ = nullptr;
438 : }
439 178 : }
440 :
441 91 : awaitable(
442 : any_write_stream* self,
443 : CB const& buffers) noexcept
444 91 : : self_(self)
445 91 : , ba_(buffers)
446 : {
447 91 : }
448 :
449 87 : awaitable(awaitable&& other) noexcept
450 87 : : self_(std::exchange(other.self_, nullptr))
451 87 : , ba_(other.ba_)
452 87 : , owns_(std::exchange(other.owns_, false))
453 : {
454 87 : if(owns_)
455 1 : self_->owner_ = &owns_;
456 87 : }
457 :
458 : bool
459 90 : await_ready()
460 : {
461 : // An empty write never touches the underlying stream
462 90 : if(ba_.to_span().empty())
463 4 : return true;
464 :
465 86 : self_->vt_->construct_awaitable(
466 86 : self_->stream_,
467 86 : self_->cached_awaitable_,
468 86 : ba_.to_span());
469 86 : self_->awaitable_active_ = true;
470 86 : owns_ = true;
471 86 : self_->owner_ = &owns_;
472 :
473 172 : return self_->vt_->await_ready(
474 86 : self_->cached_awaitable_);
475 : }
476 :
477 : std::coroutine_handle<>
478 74 : await_suspend(std::coroutine_handle<> h, await_context const* env)
479 : {
480 74 : return self_->vt_->await_suspend(
481 74 : self_->cached_awaitable_, h, env);
482 : }
483 :
484 : [[nodiscard]] results<std::size_t>
485 81 : await_resume()
486 : {
487 81 : if(!owns_)
488 4 : return {std::error_code(), 0};
489 : struct guard {
490 : awaitable* a;
491 77 : ~guard() {
492 77 : a->self_->vt_->destroy_awaitable(
493 77 : a->self_->cached_awaitable_);
494 77 : a->self_->awaitable_active_ = false;
495 77 : a->self_->owner_ = nullptr;
496 77 : a->owns_ = false;
497 77 : }
498 77 : } g{this};
499 77 : return self_->vt_->await_resume(
500 77 : self_->cached_awaitable_);
501 77 : }
502 : };
503 91 : return awaitable{this, buffers};
504 : }
505 :
506 : } // namespace capy
507 : } // namespace boost
508 :
509 : #endif
|