4 * Copyright (C) 2005 Linus Torvalds
6 * Simple file write infrastructure for writing SHA1-summed
7 * files. Useful when you write a file that you want to be
8 * able to verify hasn't been messed with afterwards.
12 #include "csum-file.h"
14 static void sha1flush(struct sha1file *f, void *buf, unsigned int count)
17 int ret = xwrite(f->fd, buf, count);
20 display_throughput(f->tp, f->total);
21 buf = (char *) buf + ret;
28 die("sha1 file '%s' write error. Out of diskspace", f->name);
29 die("sha1 file '%s' write error (%s)", f->name, strerror(errno));
33 int sha1close(struct sha1file *f, unsigned char *result, unsigned int flags)
36 unsigned offset = f->offset;
39 git_SHA1_Update(&f->ctx, f->buffer, offset);
40 sha1flush(f, f->buffer, offset);
43 git_SHA1_Final(f->buffer, &f->ctx);
45 hashcpy(result, f->buffer);
46 if (flags & (CSUM_CLOSE | CSUM_FSYNC)) {
47 /* write checksum and close fd */
48 sha1flush(f, f->buffer, 20);
49 if (flags & CSUM_FSYNC)
50 fsync_or_die(f->fd, f->name);
52 die("%s: sha1 file error on close (%s)",
53 f->name, strerror(errno));
61 int sha1write(struct sha1file *f, void *buf, unsigned int count)
64 unsigned offset = f->offset;
65 unsigned left = sizeof(f->buffer) - offset;
66 unsigned nr = count > left ? left : count;
70 f->crc32 = crc32(f->crc32, buf, nr);
72 if (nr == sizeof(f->buffer)) {
73 /* process full buffer directly without copy */
76 memcpy(f->buffer + offset, buf, nr);
82 buf = (char *) buf + nr;
85 git_SHA1_Update(&f->ctx, data, offset);
86 sha1flush(f, data, offset);
94 struct sha1file *sha1fd(int fd, const char *name)
96 return sha1fd_throughput(fd, name, NULL);
99 struct sha1file *sha1fd_throughput(int fd, const char *name, struct progress *tp)
101 struct sha1file *f = xmalloc(sizeof(*f));
108 git_SHA1_Init(&f->ctx);
112 void crc32_begin(struct sha1file *f)
114 f->crc32 = crc32(0, Z_NULL, 0);
118 uint32_t crc32_end(struct sha1file *f)