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