raw
keksum_genesis_3        1 /* Minimalist POSIX I/O (unbuffered, dies on error)
keksum_genesis_3 2 * J. Welsh, May 2019
keksum_genesis_3 3 */
keksum_genesis_3 4
keksum_genesis_3 5 #include <errno.h>
keksum_genesis_3 6 #include <signal.h>
keksum_genesis_3 7 #include <string.h>
keksum_genesis_3 8 #include <unistd.h>
keksum_genesis_3 9 #include "io.h"
keksum_genesis_3 10
keksum_genesis_3 11 void write_all(int fd, char const *buf, size_t len) {
keksum_genesis_3 12 while (len) {
keksum_genesis_3 13 ssize_t n = write(fd,buf,len);
keksum_genesis_3 14 if (n < 0) {
keksum_genesis_3 15 if (errno == EINTR) continue;
keksum_genesis_3 16 if (fd != 2) /* prevent loop */
keksum_genesis_3 17 perr("write_all");
keksum_genesis_3 18 _exit(errno);
keksum_genesis_3 19 }
keksum_genesis_3 20 buf += n;
keksum_genesis_3 21 len -= n;
keksum_genesis_3 22 }
keksum_genesis_3 23 }
keksum_genesis_3 24
keksum_genesis_3 25 size_t read_all(int fd, unsigned char *buf, size_t len) {
keksum_genesis_3 26 size_t olen = len;
keksum_genesis_3 27 while (len) {
keksum_genesis_3 28 ssize_t n = read(fd,buf,len);
keksum_genesis_3 29 if (n <= 0) {
keksum_genesis_3 30 if (n) {
keksum_genesis_3 31 if (errno == EINTR) continue;
keksum_genesis_3 32 perr("read_all");
keksum_genesis_3 33 _exit(errno);
keksum_genesis_3 34 }
keksum_genesis_3 35 break;
keksum_genesis_3 36 }
keksum_genesis_3 37 buf += n;
keksum_genesis_3 38 len -= n;
keksum_genesis_3 39 }
keksum_genesis_3 40 return olen - len;
keksum_genesis_3 41 }
keksum_genesis_3 42
keksum_genesis_3 43 void write_str(int fd, char const *s) {
keksum_genesis_3 44 write_all(fd,s,strlen(s));
keksum_genesis_3 45 }
keksum_genesis_3 46
keksum_genesis_3 47 void newline(int fd) {
keksum_genesis_3 48 write_all(fd,"\n",1);
keksum_genesis_3 49 }
keksum_genesis_3 50
keksum_genesis_3 51 void write_line(int fd, char const *s) {
keksum_genesis_3 52 write_str(fd,s);
keksum_genesis_3 53 newline(fd);
keksum_genesis_3 54 }
keksum_genesis_3 55
keksum_genesis_3 56 void assert_fail(char const *expr) {
keksum_genesis_3 57 write_str(2,"Assertion failed: ");
keksum_genesis_3 58 write_line(2,expr);
keksum_genesis_3 59 raise(SIGABRT);
keksum_genesis_3 60 _exit(1);
keksum_genesis_3 61 }
keksum_genesis_3 62
keksum_genesis_3 63 void perr(char const *context) {
keksum_genesis_3 64 write_str(2,context);
keksum_genesis_3 65 write_str(2,": ");
keksum_genesis_3 66 write_line(2,strerror(errno));
keksum_genesis_3 67 }
keksum_genesis_3 68
keksum_genesis_3 69 int chkp(char const *context, int ret) {
keksum_genesis_3 70 if (ret == -1) {
keksum_genesis_3 71 perr(context);
keksum_genesis_3 72 _exit(errno);
keksum_genesis_3 73 }
keksum_genesis_3 74 return ret;
keksum_genesis_3 75 }