Skip to content

Commit

Permalink
add a new function recv_at_least() to socket stream (alibaba#224)
Browse files Browse the repository at this point in the history
add new functions recv_at_least() and recv_at_least_mutable() to socket stream
  • Loading branch information
lihuiba authored and beef9999 committed Nov 2, 2023
1 parent 71bbe46 commit 31ae464
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
27 changes: 27 additions & 0 deletions net/basic_socket.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -262,6 +262,33 @@ bool ISocketStream::skip_read(size_t count) {
return true;
}

ssize_t ISocketStream::recv_at_least(void* buf, size_t count, size_t least, int flags) {
size_t n = 0;
do {
ssize_t ret = this->recv(buf, count, flags);
if (ret < 0) return ret;
if (ret == 0) break; // EOF
if ((n += ret) >= least) break;
count -= ret;
} while (count);
return n;
}

ssize_t ISocketStream::recv_at_least_mutable(struct iovec *iov, int iovcnt,
size_t least, int flags /*=0*/) {
size_t n = 0;
iovector_view v(iov, iovcnt);
do {
ssize_t ret = this->recv(v.iov, v.iovcnt, flags);
if (ret < 0) return ret;
if (ret == 0) break; // EOF
if ((n += ret) >= least) break;
auto r = v.extract_front(ret);
assert(r == ret); (void)r;
} while (v.iovcnt && v.iov->iov_len);
return n;
}

int do_get_name(int fd, Getter getter, EndPoint& addr) {
sockaddr_storage storage;
socklen_t len = storage.get_max_socklen();
Expand Down
4 changes: 4 additions & 0 deletions net/socket.h
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,10 @@ namespace net {
virtual ssize_t recv(void *buf, size_t count, int flags = 0) = 0;
virtual ssize_t recv(const struct iovec *iov, int iovcnt, int flags = 0) = 0;

// recv at `least` bytes to buffer (`buf`, `count`)
ssize_t recv_at_least(void* buf, size_t count, size_t least, int flags = 0);
ssize_t recv_at_least_mutable(struct iovec *iov, int iovcnt, size_t least, int flags = 0);

// read count bytes and drop them
// return true/false for success/failure
bool skip_read(size_t count);
Expand Down

0 comments on commit 31ae464

Please sign in to comment.