|
| 1 | +// |
| 2 | +// Created by netcan on 2021/11/30. |
| 3 | +// |
| 4 | + |
| 5 | +#ifndef ASYNCIO_STREAM_H |
| 6 | +#define ASYNCIO_STREAM_H |
| 7 | +#include <asyncio/asyncio_ns.h> |
| 8 | +#include <asyncio/noncopyable.h> |
| 9 | +#include <asyncio/task.h> |
| 10 | +#include <utility> |
| 11 | +#include <vector> |
| 12 | +#include <unistd.h> |
| 13 | + |
| 14 | +ASYNCIO_NS_BEGIN |
| 15 | +struct Stream: NonCopyable { |
| 16 | + using Buffer = std::vector<char>; |
| 17 | + Stream(int fd): fd_(fd) {} |
| 18 | + Stream(Stream&& other): fd_{std::exchange(other.fd_, -1) } {} |
| 19 | + ~Stream() { close(); } |
| 20 | + |
| 21 | + void close() { |
| 22 | + if (fd_ > 0) { ::close(fd_); } |
| 23 | + fd_ = -1; |
| 24 | + } |
| 25 | + |
| 26 | + Task<Buffer> read(ssize_t sz = -1) { |
| 27 | + if (sz < 0) { co_return co_await read_until_eof(); } |
| 28 | + |
| 29 | + Buffer result(sz, 0); |
| 30 | + Event ev { .fd = fd_, .events = EPOLLIN }; |
| 31 | + auto& loop = get_event_loop(); |
| 32 | + co_await loop.wait_event(ev); |
| 33 | + sz = ::read(fd_, result.data(), result.size()); |
| 34 | + if (sz == -1) { |
| 35 | + throw std::system_error(std::make_error_code(static_cast<std::errc>(errno))); |
| 36 | + } |
| 37 | + result.resize(sz); |
| 38 | + co_return result; |
| 39 | + } |
| 40 | + |
| 41 | + Task<> write(const Buffer& buf) { |
| 42 | + Event ev { .fd = fd_, .events = EPOLLOUT }; |
| 43 | + auto& loop = get_event_loop(); |
| 44 | + ssize_t total_write = 0; |
| 45 | + while (total_write < buf.size()) { |
| 46 | + co_await loop.wait_event(ev); |
| 47 | + ssize_t sz = ::write(fd_, buf.data() + total_write, buf.size() - total_write); |
| 48 | + if (sz == -1) { |
| 49 | + throw std::system_error(std::make_error_code(static_cast<std::errc>(errno))); |
| 50 | + } |
| 51 | + total_write += sz; |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | +private: |
| 56 | + Task<Buffer> read_until_eof() { |
| 57 | + auto& loop = get_event_loop(); |
| 58 | + |
| 59 | + Buffer result(chunk_size, 0); |
| 60 | + Event ev { .fd = fd_, .events = EPOLLIN }; |
| 61 | + int current_read = 0; |
| 62 | + int total_read = 0; |
| 63 | + do { |
| 64 | + co_await loop.wait_event(ev); |
| 65 | + current_read = ::read(fd_, result.data() + total_read, chunk_size); |
| 66 | + if (current_read == -1) { |
| 67 | + throw std::system_error(std::make_error_code(static_cast<std::errc>(errno))); |
| 68 | + } |
| 69 | + if (current_read < chunk_size) { result.resize(total_read + current_read); } |
| 70 | + total_read += current_read; |
| 71 | + result.resize(total_read + chunk_size); |
| 72 | + } while (current_read > 0); |
| 73 | + co_return result; |
| 74 | + } |
| 75 | +private: |
| 76 | + int fd_{-1}; |
| 77 | + constexpr static size_t chunk_size = 4096; |
| 78 | +}; |
| 79 | +ASYNCIO_NS_END |
| 80 | +#endif // ASYNCIO_STREAM_H |
0 commit comments