1#include "cache.h"
2
3int read_in_full(int fd, void *buf, size_t count)
4{
5 char *p = buf;
6 ssize_t total = 0;
7 ssize_t loaded = 0;
8
9 while (count > 0) {
10 loaded = xread(fd, p, count);
11 if (loaded <= 0) {
12 if (total)
13 return total;
14 else
15 return loaded;
16 }
17 count -= loaded;
18 p += loaded;
19 total += loaded;
20 }
21
22 return total;
23}
24
25void read_or_die(int fd, void *buf, size_t count)
26{
27 ssize_t loaded;
28
29 if (!count)
30 return;
31 loaded = read_in_full(fd, buf, count);
32 if (loaded == 0)
33 die("unexpected end of file");
34 else if (loaded < 0)
35 die("read error (%s)", strerror(errno));
36}
37
38int write_in_full(int fd, const void *buf, size_t count)
39{
40 const char *p = buf;
41 ssize_t total = 0;
42
43 while (count > 0) {
44 size_t written = xwrite(fd, p, count);
45 if (written < 0)
46 return -1;
47 if (!written) {
48 errno = ENOSPC;
49 return -1;
50 }
51 count -= written;
52 p += written;
53 total += written;
54 }
55
56 return total;
57}
58
59void write_or_die(int fd, const void *buf, size_t count)
60{
61 if (write_in_full(fd, buf, count) < 0) {
62 if (errno == EPIPE)
63 exit(0);
64 die("write error (%s)", strerror(errno));
65 }
66}
67
68int write_or_whine_pipe(int fd, const void *buf, size_t count, const char *msg)
69{
70 if (write_in_full(fd, buf, count) < 0) {
71 if (errno == EPIPE)
72 exit(0);
73 fprintf(stderr, "%s: write error (%s)\n",
74 msg, strerror(errno));
75 return 0;
76 }
77
78 return 1;
79}
80
81int write_or_whine(int fd, const void *buf, size_t count, const char *msg)
82{
83 if (write_in_full(fd, buf, count) < 0) {
84 fprintf(stderr, "%s: write error (%s)\n",
85 msg, strerror(errno));
86 return 0;
87 }
88
89 return 1;
90}