Merge branch 'maint'
[git.git] / csum-file.c
blob2ddb12a0b70da87afe6fa8a33dce08c6c8ae7f71
1 /*
2 * csum-file.c
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.
9 */
10 #include "cache.h"
11 #include "progress.h"
12 #include "csum-file.h"
14 static void flush(struct sha1file *f, void * buf, unsigned int count)
16 for (;;) {
17 int ret = xwrite(f->fd, buf, count);
18 if (ret > 0) {
19 f->total += ret;
20 display_throughput(f->tp, f->total);
21 buf = (char *) buf + ret;
22 count -= ret;
23 if (count)
24 continue;
25 return;
27 if (!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 void sha1flush(struct sha1file *f)
35 unsigned offset = f->offset;
37 if (offset) {
38 git_SHA1_Update(&f->ctx, f->buffer, offset);
39 flush(f, f->buffer, offset);
40 f->offset = 0;
44 int sha1close(struct sha1file *f, unsigned char *result, unsigned int flags)
46 int fd;
48 sha1flush(f);
49 git_SHA1_Final(f->buffer, &f->ctx);
50 if (result)
51 hashcpy(result, f->buffer);
52 if (flags & (CSUM_CLOSE | CSUM_FSYNC)) {
53 /* write checksum and close fd */
54 flush(f, f->buffer, 20);
55 if (flags & CSUM_FSYNC)
56 fsync_or_die(f->fd, f->name);
57 if (close(f->fd))
58 die("%s: sha1 file error on close (%s)",
59 f->name, strerror(errno));
60 fd = 0;
61 } else
62 fd = f->fd;
63 free(f);
64 return fd;
67 int sha1write(struct sha1file *f, void *buf, unsigned int count)
69 while (count) {
70 unsigned offset = f->offset;
71 unsigned left = sizeof(f->buffer) - offset;
72 unsigned nr = count > left ? left : count;
73 void *data;
75 if (f->do_crc)
76 f->crc32 = crc32(f->crc32, buf, nr);
78 if (nr == sizeof(f->buffer)) {
79 /* process full buffer directly without copy */
80 data = buf;
81 } else {
82 memcpy(f->buffer + offset, buf, nr);
83 data = f->buffer;
86 count -= nr;
87 offset += nr;
88 buf = (char *) buf + nr;
89 left -= nr;
90 if (!left) {
91 git_SHA1_Update(&f->ctx, data, offset);
92 flush(f, data, offset);
93 offset = 0;
95 f->offset = offset;
97 return 0;
100 struct sha1file *sha1fd(int fd, const char *name)
102 return sha1fd_throughput(fd, name, NULL);
105 struct sha1file *sha1fd_throughput(int fd, const char *name, struct progress *tp)
107 struct sha1file *f = xmalloc(sizeof(*f));
108 f->fd = fd;
109 f->offset = 0;
110 f->total = 0;
111 f->tp = tp;
112 f->name = name;
113 f->do_crc = 0;
114 git_SHA1_Init(&f->ctx);
115 return f;
118 void crc32_begin(struct sha1file *f)
120 f->crc32 = crc32(0, Z_NULL, 0);
121 f->do_crc = 1;
124 uint32_t crc32_end(struct sha1file *f)
126 f->do_crc = 0;
127 return f->crc32;