gitweb: shortlog now also obeys $hash_parent
[git/ericb.git] / csum-file.c
blobbb70c75ee1ed54a11ce31d7092ef6e35cae37c04
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 sha1flush(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 int sha1close(struct sha1file *f, unsigned char *result, unsigned int flags)
35 int fd;
36 unsigned offset = f->offset;
38 if (offset) {
39 SHA1_Update(&f->ctx, f->buffer, offset);
40 sha1flush(f, f->buffer, offset);
41 f->offset = 0;
43 SHA1_Final(f->buffer, &f->ctx);
44 if (result)
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);
51 if (close(f->fd))
52 die("%s: sha1 file error on close (%s)",
53 f->name, strerror(errno));
54 fd = 0;
55 } else
56 fd = f->fd;
57 free(f);
58 return fd;
61 int sha1write(struct sha1file *f, void *buf, unsigned int count)
63 while (count) {
64 unsigned offset = f->offset;
65 unsigned left = sizeof(f->buffer) - offset;
66 unsigned nr = count > left ? left : count;
67 void *data;
69 if (f->do_crc)
70 f->crc32 = crc32(f->crc32, buf, nr);
72 if (nr == sizeof(f->buffer)) {
73 /* process full buffer directly without copy */
74 data = buf;
75 } else {
76 memcpy(f->buffer + offset, buf, nr);
77 data = f->buffer;
80 count -= nr;
81 offset += nr;
82 buf = (char *) buf + nr;
83 left -= nr;
84 if (!left) {
85 SHA1_Update(&f->ctx, data, offset);
86 sha1flush(f, data, offset);
87 offset = 0;
89 f->offset = offset;
91 return 0;
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));
102 f->fd = fd;
103 f->offset = 0;
104 f->total = 0;
105 f->tp = tp;
106 f->name = name;
107 f->do_crc = 0;
108 SHA1_Init(&f->ctx);
109 return f;
112 void crc32_begin(struct sha1file *f)
114 f->crc32 = crc32(0, Z_NULL, 0);
115 f->do_crc = 1;
118 uint32_t crc32_end(struct sha1file *f)
120 f->do_crc = 0;
121 return f->crc32;