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
Changes from 1 commit
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
17 changes: 17 additions & 0 deletions net/socket.h
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,23 @@ namespace net {
// may block once at most, when there's no data yet in the socket;
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;
virtual ssize_t recv_mutable(struct iovec *iov, int iovcnt, int flags = 0) {
return recv(iov, iovcnt, flags);
}
Copy link
Collaborator

@beef9999 beef9999 Oct 28, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Any chance we need to modify the iovec pointer?

Copy link
Collaborator Author

@lihuiba lihuiba Oct 28, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Because const iovec* is a convention, just like readv/preadv/writev/pwritev ...

Obeying the convention can avoid unnecessary errors.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Using another function name is also for obeying the convention, despite C++ has function overloading.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, I made a mistake. In fact recv/send usually makes a single I/O action that doesn't need to modify the iovec[]. Only recv_at_least needs so.


// recv at `least` bytes to buffer (`buf`, `count`)
ssize_t recv_at_least(void* buf, size_t count, size_t least, int flags = 0) {
size_t n = 0;
if (least > count) least = count;
while (true) {
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;
}
return n;
}

// read count bytes and drop them
// return true/false for success/failure
Expand Down
Loading