A plain stream, permitting reading, writing, and closing.
Read available data (up to maxSize bytes) from stream. Returns std::nullopt on EOF or closed handle (close()).
Throws UvcoException on error.
NOTE: Consider using read(std::span<char>) for better performance.
NOTE: only one reader is allowed to be active at a time. If a read is started while another is still active, uvco will abort the process (in Debug mode), or ignore the first read (in Release mode).
105 {
106
107 std::string buf(maxSize, '\0');
109 const size_t nRead = co_await awaiter;
110 if (nRead == 0) {
111
112 co_return std::nullopt;
113 }
114 buf.resize(nRead);
115 co_return buf;
116}
| Promise< void > uvco::StreamBase::write |
( |
std::string | buf | ) |
|
|
nodiscard |
Write a buffer to the stream. A copy of buf is taken because it is undetermined when the actual write will occur. Await the result if the status is important; the write will be executed even without awaiting (as long as the process keeps running).
NOTE: only one writer is allowed to be active at a time. If two writes are started simultaneously, the process will be aborted in Debug mode, or the first write() coroutine will not return in Release mode.
WARNING: due to the interactions with libuv, writes cannot be cancelled. That's why write() always takes ownership of a buffer to avoid use-after-free issues. The safety comes at the cost of increased allocations, obviously.
123 {
125 std::array<uv_buf_t, 1> bufs{};
126 bufs[0] = uv_buf_init(const_cast<char *>(awaiter.write_->buffer.data()),
127 awaiter.write_->buffer.size());
128
130 const OnExit _onExit{[
write = awaiter.write_.get(), &awaiter] {
131
132
133 if (awaiter.handle_) {
135 }
136 }};
137
139 uv_write((uv_write_t *)(awaiter.write_.release()), &
stream(), bufs.data(),
141 if (status < 0) {
142 throw UvcoException{status,
143 "StreamBase::write() encountered error in uv_write"};
144 }
145 const uv_status completionStatus =
co_await awaiter;
146
147 if (completionStatus < 0) {
148 throw UvcoException{
149 status, "StreamBase::write() encountered error while awaiting write"};
150 }
151 co_return;
152}
Promise< void > write(std::string buf)
Definition stream.cc:123
static void onOutStreamWrite(uv_write_t *write, uv_status status)
Definition stream.cc:315