index-pack: write-or-die instead of unchecked write-in-full.
[git/gitweb.git] / write_or_die.c
blob7f99a22aed43afd8ca06d3eafef8d3e836b15107
1 #include "cache.h"
3 int read_in_full(int fd, void *buf, size_t count)
5 char *p = buf;
6 ssize_t total = 0;
7 ssize_t loaded = 0;
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;
17 count -= loaded;
18 p += loaded;
19 total += loaded;
22 return total;
25 void read_or_die(int fd, void *buf, size_t count)
27 ssize_t loaded;
29 loaded = read_in_full(fd, buf, count);
30 if (loaded == 0)
31 die("unexpected end of file");
32 else if (loaded < 0)
33 die("read error (%s)", strerror(errno));
36 int write_in_full(int fd, const void *buf, size_t count)
38 const char *p = buf;
39 ssize_t total = 0;
41 while (count > 0) {
42 size_t written = xwrite(fd, p, count);
43 if (written < 0)
44 return -1;
45 if (!written) {
46 errno = ENOSPC;
47 return -1;
49 count -= written;
50 p += written;
51 total += written;
54 return total;
57 void write_or_die(int fd, const void *buf, size_t count)
59 ssize_t written;
61 written = write_in_full(fd, buf, count);
62 if (written == 0)
63 die("disk full?");
64 else if (written < 0) {
65 if (errno == EPIPE)
66 exit(0);
67 die("write error (%s)", strerror(errno));
71 int write_or_whine_pipe(int fd, const void *buf, size_t count, const char *msg)
73 ssize_t written;
75 written = write_in_full(fd, buf, count);
76 if (written == 0) {
77 fprintf(stderr, "%s: disk full?\n", msg);
78 return 0;
80 else if (written < 0) {
81 if (errno == EPIPE)
82 exit(0);
83 fprintf(stderr, "%s: write error (%s)\n",
84 msg, strerror(errno));
85 return 0;
88 return 1;
91 int write_or_whine(int fd, const void *buf, size_t count, const char *msg)
93 ssize_t written;
95 written = write_in_full(fd, buf, count);
96 if (written == 0) {
97 fprintf(stderr, "%s: disk full?\n", msg);
98 return 0;
100 else if (written < 0) {
101 fprintf(stderr, "%s: write error (%s)\n",
102 msg, strerror(errno));
103 return 0;
106 return 1;