commit 74f1f9366c25d65b15a435fe872cb3f9baf0810f
parent 79a944325f45499e3bf4e150c0b7375664af205f
Author: Robert Russell <robertrussell.72001@gmail.com>
Date: Sat, 7 Jan 2023 19:03:09 -0800
Document and improve read_all and write_all
The improvement is that the n parameter is optional.
Diffstat:
2 files changed, 20 insertions(+), 10 deletions(-)
diff --git a/inc/rcx/unix.h b/inc/rcx/unix.h
@@ -2,5 +2,14 @@
#include "rcx/def.h"
+/* Read exactly len bytes from fd into buf and return 0 on success. On failure,
+ * return -1 and set errno in the same manner as read(2). In either case, if
+ * n is not NULL, set *n to the number of bytes actually read (which is less
+ * than len if and only if an error occurred). */
int r_read_all(usize *n, int fd, void *buf, usize len);
+
+/* Write exactly len bytes from buf to fd and return 0 on success. On failure,
+ * return -1 and set errno in the same manner as write(2). In either case, if
+ * n is not NULL, set *n to the number of bytes actually written (which is less
+ * than len if and only if an error occurred). */
int r_write_all(usize *n, int fd, void *buf, usize len);
diff --git a/src/unix.c b/src/unix.c
@@ -6,21 +6,22 @@
typedef isize (*IoOp)(int, void *, usize);
static int
-perform_io(usize *n_, IoOp op, int fd, void *buf, usize len) {
- usize n = 0;
+perform_io(usize *n, IoOp op, int fd, void *buf, usize len) {
+ usize i = 0;
+
do {
- isize ret = op(fd, (char *)buf + n, len - n);
+ isize ret = op(fd, (char *)buf + i, len - i);
if (ret < 0) {
if (errno == EINTR)
continue;
- *n_ = n;
- return -1;
+ break;
}
- n += ret;
- } while (n < len);
+ i += ret;
+ } while (i < len);
- *n_ = n;
- return 0;
+ if (n)
+ *n = i;
+ return i == len ? 0 : -1;
}
int
@@ -30,6 +31,6 @@ r_read_all(usize *n, int fd, void *buf, usize len) {
int
r_write_all(usize *n, int fd, void *buf, usize len) {
- /* Cast off const-ness from write. */
+ /* Cast off const-ness of buf argument from write. */
return perform_io(n, (IoOp)write, fd, buf, len);
}