1  
//
1  
//
2  
// Copyright (c) 2025 Vinnie Falco (vinnie.falco@gmail.com)
2  
// Copyright (c) 2025 Vinnie Falco (vinnie.falco@gmail.com)
3  
//
3  
//
4  
// Distributed under the Boost Software License, Version 1.0. (See accompanying
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)
5  
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
6  
//
6  
//
7  
// Official repository: https://github.com/cppalliance/capy
7  
// Official repository: https://github.com/cppalliance/capy
8  
//
8  
//
9  

9  

10  
#ifndef BOOST_CAPY_TEST_WRITE_STREAM_HPP
10  
#ifndef BOOST_CAPY_TEST_WRITE_STREAM_HPP
11  
#define BOOST_CAPY_TEST_WRITE_STREAM_HPP
11  
#define BOOST_CAPY_TEST_WRITE_STREAM_HPP
12  

12  

13  
#include <boost/capy/detail/config.hpp>
13  
#include <boost/capy/detail/config.hpp>
14  
#include <boost/capy/buffers.hpp>
14  
#include <boost/capy/buffers.hpp>
15  
#include <boost/capy/buffers/buffer_copy.hpp>
15  
#include <boost/capy/buffers/buffer_copy.hpp>
16  
#include <boost/capy/buffers/make_buffer.hpp>
16  
#include <boost/capy/buffers/make_buffer.hpp>
17  
#include <boost/capy/coro.hpp>
17  
#include <boost/capy/coro.hpp>
18  
#include <boost/capy/ex/executor_ref.hpp>
18  
#include <boost/capy/ex/executor_ref.hpp>
19  
#include <boost/capy/io_result.hpp>
19  
#include <boost/capy/io_result.hpp>
20  
#include <boost/capy/error.hpp>
20  
#include <boost/capy/error.hpp>
21  
#include <boost/capy/test/fuse.hpp>
21  
#include <boost/capy/test/fuse.hpp>
22  

22  

23  
#include <algorithm>
23  
#include <algorithm>
24  
#include <stop_token>
24  
#include <stop_token>
25  
#include <string>
25  
#include <string>
26  
#include <string_view>
26  
#include <string_view>
27  

27  

28  
namespace boost {
28  
namespace boost {
29  
namespace capy {
29  
namespace capy {
30  
namespace test {
30  
namespace test {
31  

31  

32  
/** A mock stream for testing write operations.
32  
/** A mock stream for testing write operations.
33  

33  

34  
    Use this to verify code that performs writes without needing
34  
    Use this to verify code that performs writes without needing
35 -
    real I/O. Call @ref write_some to write data, then @ref str
35 +
    real I/O. Call @ref write_some to write data, then @ref data
36 -
    or @ref data to retrieve what was written. The associated
36 +
    to retrieve what was written. The associated @ref fuse enables
37 -
    @ref fuse enables error injection at controlled points. An
37 +
    error injection at controlled points. An optional
38 -
    optional `max_write_size` constructor parameter limits bytes
38 +
    `max_write_size` constructor parameter limits bytes per write
39 -
    per write to simulate chunked delivery.
39 +
    to simulate chunked delivery.
 
40 +

 
41 +
    This class satisfies the @ref WriteStream concept.
40  

42  

41  
    @par Thread Safety
43  
    @par Thread Safety
42  
    Not thread-safe.
44  
    Not thread-safe.
43  

45  

44  
    @par Example
46  
    @par Example
45  
    @code
47  
    @code
46  
    fuse f;
48  
    fuse f;
47  
    write_stream ws( f );
49  
    write_stream ws( f );
48  

50  

49  
    auto r = f.armed( [&]( fuse& ) -> task<void> {
51  
    auto r = f.armed( [&]( fuse& ) -> task<void> {
50  
        auto [ec, n] = co_await ws.write_some(
52  
        auto [ec, n] = co_await ws.write_some(
51  
            const_buffer( "Hello", 5 ) );
53  
            const_buffer( "Hello", 5 ) );
52  
        if( ec )
54  
        if( ec )
53  
            co_return;
55  
            co_return;
54 -
        // ws.str() returns "Hello"
56 +
        // ws.data() returns "Hello"
55  
    } );
57  
    } );
56  
    @endcode
58  
    @endcode
57  

59  

58 -
    @see fuse
60 +
    @see fuse, WriteStream
59  
*/
61  
*/
60  
class write_stream
62  
class write_stream
61  
{
63  
{
62 -
    fuse* f_;
64 +
    fuse f_;
63  
    std::string data_;
65  
    std::string data_;
64  
    std::string expect_;
66  
    std::string expect_;
65  
    std::size_t max_write_size_;
67  
    std::size_t max_write_size_;
66  

68  

67  
    std::error_code
69  
    std::error_code
68  
    consume_match_() noexcept
70  
    consume_match_() noexcept
69  
    {
71  
    {
70  
        if(data_.empty() || expect_.empty())
72  
        if(data_.empty() || expect_.empty())
71  
            return {};
73  
            return {};
72  
        std::size_t const n = (std::min)(data_.size(), expect_.size());
74  
        std::size_t const n = (std::min)(data_.size(), expect_.size());
73  
        if(std::string_view(data_.data(), n) !=
75  
        if(std::string_view(data_.data(), n) !=
74  
            std::string_view(expect_.data(), n))
76  
            std::string_view(expect_.data(), n))
75  
            return error::test_failure;
77  
            return error::test_failure;
76  
        data_.erase(0, n);
78  
        data_.erase(0, n);
77  
        expect_.erase(0, n);
79  
        expect_.erase(0, n);
78  
        return {};
80  
        return {};
79  
    }
81  
    }
80  

82  

81  
public:
83  
public:
82  
    /** Construct a write stream.
84  
    /** Construct a write stream.
83  

85  

84  
        @param f The fuse used to inject errors during writes.
86  
        @param f The fuse used to inject errors during writes.
85  

87  

86  
        @param max_write_size Maximum bytes transferred per write.
88  
        @param max_write_size Maximum bytes transferred per write.
87  
        Use to simulate chunked network delivery.
89  
        Use to simulate chunked network delivery.
88  
    */
90  
    */
89  
    explicit write_stream(
91  
    explicit write_stream(
90 -
        fuse& f,
92 +
        fuse f = {},
91  
        std::size_t max_write_size = std::size_t(-1)) noexcept
93  
        std::size_t max_write_size = std::size_t(-1)) noexcept
92 -
        : f_(&f)
94 +
        : f_(std::move(f))
93  
        , max_write_size_(max_write_size)
95  
        , max_write_size_(max_write_size)
94  
    {
96  
    {
95  
    }
97  
    }
96  

98  

97  
    /// Return the written data as a string view.
99  
    /// Return the written data as a string view.
98  
    std::string_view
100  
    std::string_view
99  
    data() const noexcept
101  
    data() const noexcept
100  
    {
102  
    {
101  
        return data_;
103  
        return data_;
102  
    }
104  
    }
103  

105  

104  
    /** Set the expected data for subsequent writes.
106  
    /** Set the expected data for subsequent writes.
105  

107  

106  
        Stores the expected data and immediately tries to match
108  
        Stores the expected data and immediately tries to match
107  
        against any data already written. Matched data is consumed
109  
        against any data already written. Matched data is consumed
108  
        from both buffers.
110  
        from both buffers.
109  

111  

110  
        @param sv The expected data.
112  
        @param sv The expected data.
111  

113  

112  
        @return An error if existing data does not match.
114  
        @return An error if existing data does not match.
113  
    */
115  
    */
114  
    std::error_code
116  
    std::error_code
115  
    expect(std::string_view sv)
117  
    expect(std::string_view sv)
116  
    {
118  
    {
117  
        expect_.assign(sv);
119  
        expect_.assign(sv);
118  
        return consume_match_();
120  
        return consume_match_();
119  
    }
121  
    }
120  

122  

121  
    /// Return the number of bytes written.
123  
    /// Return the number of bytes written.
122  
    std::size_t
124  
    std::size_t
123  
    size() const noexcept
125  
    size() const noexcept
124  
    {
126  
    {
125  
        return data_.size();
127  
        return data_.size();
126  
    }
128  
    }
127  

129  

128  
    /** Asynchronously write data to the stream.
130  
    /** Asynchronously write data to the stream.
129  

131  

130  
        Transfers up to `buffer_size( buffers )` bytes from the provided
132  
        Transfers up to `buffer_size( buffers )` bytes from the provided
131  
        const buffer sequence to the internal buffer. Before every write,
133  
        const buffer sequence to the internal buffer. Before every write,
132  
        the attached @ref fuse is consulted to possibly inject an error
134  
        the attached @ref fuse is consulted to possibly inject an error
133  
        for testing fault scenarios. The returned `std::size_t` is the
135  
        for testing fault scenarios. The returned `std::size_t` is the
134  
        number of bytes transferred.
136  
        number of bytes transferred.
135  

137  

136  
        @par Effects
138  
        @par Effects
137  
        On success, appends the written bytes to the internal buffer.
139  
        On success, appends the written bytes to the internal buffer.
138  
        If an error is injected by the fuse, the internal buffer remains
140  
        If an error is injected by the fuse, the internal buffer remains
139  
        unchanged.
141  
        unchanged.
140  

142  

141  
        @par Exception Safety
143  
        @par Exception Safety
142  
        No-throw guarantee.
144  
        No-throw guarantee.
143  

145  

144  
        @param buffers The const buffer sequence containing data to write.
146  
        @param buffers The const buffer sequence containing data to write.
145  

147  

146  
        @return An awaitable yielding `(error_code,std::size_t)`.
148  
        @return An awaitable yielding `(error_code,std::size_t)`.
147  

149  

148  
        @see fuse
150  
        @see fuse
149  
    */
151  
    */
150  
    template<ConstBufferSequence CB>
152  
    template<ConstBufferSequence CB>
151  
    auto
153  
    auto
152  
    write_some(CB buffers)
154  
    write_some(CB buffers)
153  
    {
155  
    {
154  
        struct awaitable
156  
        struct awaitable
155  
        {
157  
        {
156  
            write_stream* self_;
158  
            write_stream* self_;
157  
            CB buffers_;
159  
            CB buffers_;
158  

160  

159  
            bool await_ready() const noexcept { return true; }
161  
            bool await_ready() const noexcept { return true; }
160  

162  

161  
            // This method is required to satisfy Capy's IoAwaitable concept,
163  
            // This method is required to satisfy Capy's IoAwaitable concept,
162  
            // but is never called because await_ready() returns true.
164  
            // but is never called because await_ready() returns true.
163  
            //
165  
            //
164  
            // Capy uses a two-layer awaitable system: the promise's
166  
            // Capy uses a two-layer awaitable system: the promise's
165  
            // await_transform wraps awaitables in a transform_awaiter whose
167  
            // await_transform wraps awaitables in a transform_awaiter whose
166  
            // standard await_suspend(coroutine_handle) calls this custom
168  
            // standard await_suspend(coroutine_handle) calls this custom
167  
            // 3-argument overload, passing the executor and stop_token from
169  
            // 3-argument overload, passing the executor and stop_token from
168  
            // the coroutine's context. For synchronous test awaitables like
170  
            // the coroutine's context. For synchronous test awaitables like
169  
            // this one, the coroutine never suspends, so this is not invoked.
171  
            // this one, the coroutine never suspends, so this is not invoked.
170  
            // The signature exists to allow the same awaitable type to work
172  
            // The signature exists to allow the same awaitable type to work
171  
            // with both synchronous (test) and asynchronous (real I/O) code.
173  
            // with both synchronous (test) and asynchronous (real I/O) code.
172  
            void await_suspend(
174  
            void await_suspend(
173  
                coro,
175  
                coro,
174  
                executor_ref,
176  
                executor_ref,
175  
                std::stop_token) const noexcept
177  
                std::stop_token) const noexcept
176  
            {
178  
            {
177  
            }
179  
            }
178  

180  

179  
            io_result<std::size_t>
181  
            io_result<std::size_t>
180  
            await_resume()
182  
            await_resume()
181  
            {
183  
            {
182 -
                auto ec = self_->f_->maybe_fail();
184 +
                if(buffer_empty(buffers_))
 
185 +
                    return {{}, 0};
 
186 +

 
187 +
                auto ec = self_->f_.maybe_fail();
183  
                if(ec)
188  
                if(ec)
184  
                    return {ec, 0};
189  
                    return {ec, 0};
185  

190  

186  
                std::size_t n = buffer_size(buffers_);
191  
                std::size_t n = buffer_size(buffers_);
187 -
                if(n == 0)
 
188 -
                    return {{}, 0};
 
189  
                n = (std::min)(n, self_->max_write_size_);
192  
                n = (std::min)(n, self_->max_write_size_);
190  

193  

191  
                std::size_t const old_size = self_->data_.size();
194  
                std::size_t const old_size = self_->data_.size();
192  
                self_->data_.resize(old_size + n);
195  
                self_->data_.resize(old_size + n);
193  
                buffer_copy(make_buffer(
196  
                buffer_copy(make_buffer(
194  
                    self_->data_.data() + old_size, n), buffers_, n);
197  
                    self_->data_.data() + old_size, n), buffers_, n);
195  

198  

196  
                ec = self_->consume_match_();
199  
                ec = self_->consume_match_();
197  
                if(ec)
200  
                if(ec)
198 -
                    return {ec, n};
201 +
                {
 
202 +
                    self_->data_.resize(old_size);
 
203 +
                    return {ec, 0};
 
204 +
                }
199  

205  

200  
                return {{}, n};
206  
                return {{}, n};
201  
            }
207  
            }
202  
        };
208  
        };
203  
        return awaitable{this, buffers};
209  
        return awaitable{this, buffers};
204  
    }
210  
    }
205  
};
211  
};
206  

212  

207  
} // test
213  
} // test
208  
} // capy
214  
} // capy
209  
} // boost
215  
} // boost
210  

216  

211  
#endif
217  
#endif