git/write_or_die.c
Linus Torvalds d34cf19b89 Clean up write_in_full() users
With the new-and-improved write_in_full() semantics, where a partial write
simply always returns a real error (and always sets 'errno' when that
happens, including for the disk full case), a lot of the callers of
write_in_full() were just unnecessarily complex.

In particular, there's no reason to ever check for a zero length or
return: if the length was zero, we'll return zero, otherwise, if a disk
full resulted in the actual write() system call returning zero the
write_in_full() logic would have correctly turned that into a negative
return value, with 'errno' set to ENOSPC.

I really wish every "write_in_full()" user would just check against "<0"
now, but this fixes the nasty and stupid ones.

Signed-off-by: Linus Torvalds <torvalds@osdl.org>
Signed-off-by: Junio C Hamano <junkio@cox.net>
2007-01-11 21:02:58 -08:00

91 lines
1.5 KiB
C

#include "cache.h"
int read_in_full(int fd, void *buf, size_t count)
{
char *p = buf;
ssize_t total = 0;
ssize_t loaded = 0;
while (count > 0) {
loaded = xread(fd, p, count);
if (loaded <= 0) {
if (total)
return total;
else
return loaded;
}
count -= loaded;
p += loaded;
total += loaded;
}
return total;
}
void read_or_die(int fd, void *buf, size_t count)
{
ssize_t loaded;
if (!count)
return;
loaded = read_in_full(fd, buf, count);
if (loaded == 0)
die("unexpected end of file");
else if (loaded < 0)
die("read error (%s)", strerror(errno));
}
int write_in_full(int fd, const void *buf, size_t count)
{
const char *p = buf;
ssize_t total = 0;
while (count > 0) {
size_t written = xwrite(fd, p, count);
if (written < 0)
return -1;
if (!written) {
errno = ENOSPC;
return -1;
}
count -= written;
p += written;
total += written;
}
return total;
}
void write_or_die(int fd, const void *buf, size_t count)
{
if (write_in_full(fd, buf, count) < 0) {
if (errno == EPIPE)
exit(0);
die("write error (%s)", strerror(errno));
}
}
int write_or_whine_pipe(int fd, const void *buf, size_t count, const char *msg)
{
if (write_in_full(fd, buf, count) < 0) {
if (errno == EPIPE)
exit(0);
fprintf(stderr, "%s: write error (%s)\n",
msg, strerror(errno));
return 0;
}
return 1;
}
int write_or_whine(int fd, const void *buf, size_t count, const char *msg)
{
if (write_in_full(fd, buf, count) < 0) {
fprintf(stderr, "%s: write error (%s)\n",
msg, strerror(errno));
return 0;
}
return 1;
}