Line data Source code
1 : //
2 : // Copyright (c) 2025 Vinnie Falco (vinnie dot falco at gmail dot com)
3 : //
4 : // Distributed under the Boost Software License, Version 1.0. (See accompanying
5 : // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
6 : //
7 : // Official repository: https://github.com/cppalliance/capy
8 : //
9 :
10 : #ifndef BOOST_CAPY_WRITE_HPP
11 : #define BOOST_CAPY_WRITE_HPP
12 :
13 : #include <boost/capy/detail/config.hpp>
14 : #include <boost/capy/io_result.hpp>
15 : #include <boost/capy/task.hpp>
16 : #include <boost/capy/buffers.hpp>
17 : #include <boost/capy/buffers/consuming_buffers.hpp>
18 : #include <boost/capy/concept/write_stream.hpp>
19 : #include <boost/system/error_code.hpp>
20 :
21 : #include <cstddef>
22 :
23 : namespace boost {
24 : namespace capy {
25 :
26 : /** Write data until the buffer sequence is empty or an error occurs.
27 :
28 : This function writes data from the buffer sequence to the stream
29 : until either the entire buffer sequence is written or an error
30 : occurs.
31 :
32 : @tparam Stream The stream type, must satisfy @ref WriteStream.
33 : @tparam CB The buffer sequence type, must satisfy
34 : @ref ConstBufferSequence.
35 :
36 : @param stream The stream to write to.
37 : @param buffers The buffer sequence to write from.
38 :
39 : @return A task that yields `(system::error_code, std::size_t)`.
40 : On success, `ec` is default-constructed (no error) and `n` is
41 : `buffer_size(buffers)`. On error, `ec` contains the error code
42 : and `n` is the total number of bytes written before the error.
43 :
44 : @par Example
45 : @code
46 : task<void> example(WriteStream auto& stream)
47 : {
48 : std::string data = "Hello, World!";
49 : auto [ec, n] = co_await write(stream, const_buffer(data.data(), data.size()));
50 : if (ec)
51 : {
52 : // Handle error
53 : }
54 : // n bytes were written (n == data.size() on success)
55 : }
56 : @endcode
57 :
58 : @see WriteStream, ConstBufferSequence
59 : */
60 : auto
61 8 : write(
62 : WriteStream auto& stream,
63 : ConstBufferSequence auto const& buffers) ->
64 : task<io_result<std::size_t>>
65 : {
66 : consuming_buffers consuming(buffers);
67 : std::size_t const total_size = buffer_size(buffers);
68 : std::size_t total_written = 0;
69 :
70 : while(total_written < total_size)
71 : {
72 : auto [ec, n] = co_await stream.write_some(consuming);
73 : if(ec)
74 : co_return {ec, total_written};
75 : consuming.consume(n);
76 : total_written += n;
77 : }
78 :
79 : co_return {{}, total_written};
80 16 : }
81 :
82 : } // namespace capy
83 : } // namespace boost
84 :
85 : #endif
|