From ea7b73aac55177d1d556d0c9dba04b0870d3aaf6 Mon Sep 17 00:00:00 2001 From: pommicket Date: Tue, 16 Sep 2025 20:49:49 -0400 Subject: Allow short reads from read_func --- examples/all_functions.c | 23 +++++++++-------------- 1 file changed, 9 insertions(+), 14 deletions(-) (limited to 'examples/all_functions.c') diff --git a/examples/all_functions.c b/examples/all_functions.c index 413d114..ee960b3 100644 --- a/examples/all_functions.c +++ b/examples/all_functions.c @@ -10,21 +10,16 @@ static size_t custom_read(void *udata, char *buf, size_t size) { int fd = (int)(intptr_t)udata; - size_t total_read = 0; - while (true) { - // must call read in a loop to fill buf up as much as possible! - // (read isn't guaranteed to read len bytes even if it could) - ssize_t ret = read(fd, buf, size); - if (ret <= 0) { - // read error/end-of-file - break; - } else { - total_read += ret; - buf += ret; - size -= ret; - } + // only read up to 4 bytes at a time. why not! + // it's much slower, but it is allowed. + ssize_t ret = read(fd, buf, size < 4 ? size : 4); + if (ret < 0) { + // read error occured. + // we could store an error away somewhere if we wanted to + // (read errors are unusual anyways.) + ret = 0; } - return total_read; + return ret; } int main(void) { -- cgit v1.2.3