1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677 |
- /***********************************************
- File Name: peer.h
- Author: Abby Cin
- Mail: abbytsing@gmail.com
- Created Time: 10/24/20 2:42 PM
- ***********************************************/
-
- #ifndef _CONET_PEER_H_
- #define _CONET_PEER_H_
-
- class peer
- {
- public:
- peer(context& ctx, int fd) : ctx_{ctx}, fd_{fd} {}
- peer(peer&& r) noexcept : ctx_{r.ctx_}, fd_{r.fd_} { r.fd_ = -1; }
- ~peer() { this->close(); }
-
- auto read_some(char* data, int n)
- {
- struct awaiter
- {
- context& ctx_;
- int fd_;
- char* data_;
- int n_;
- awaiter(context& ctx, int f, char* data, int n) : ctx_{ctx}, fd_{f}, data_{data}, n_{n} {}
-
- bool await_ready() { return false; }
-
- bool await_suspend(handle_t co)
- {
- ctx_.push(fd_, co);
- return true; // same to `void await_suspend()`, immediately back to caller
- }
-
- int await_resume() { return ::read(fd_, data_, n_); }
- };
- return awaiter{ctx_, fd_, data, n};
- }
-
- // no guarantee that all data will be sent
- auto write_some(char* data, int n)
- {
- struct awaiter
- {
- peer* p_;
- int fd_;
- char* data_;
- int n_;
- int res_{0};
- awaiter(peer* p, int f, char* data, int n) : p_{p}, fd_{f}, data_{data}, n_{n} {}
-
- bool await_ready() { return false; }
-
- void await_suspend(handle_t) { res_ = ::write(fd_, data_, n_); }
-
- int await_resume() { return res_; }
- };
- return awaiter{this, fd_, data, n};
- }
-
- void close()
- {
- if(fd_ > 0)
- {
- ctx_.pop(fd_);
- ::close(fd_);
- fd_ = -1;
- }
- }
-
- private:
- context& ctx_;
- int fd_;
- };
-
- #endif //_CONET_PEER_H_
|