Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add a new function recv_at_least() to socket stream #224

Merged
merged 4 commits into from
Oct 30, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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