Fix the wrong output of `git-show v1.3.0~155^2~4` in documentation.
[git/raj.git] / csum-file.c
blob9728a9954129246b96713d2f3b8dbd52541c416b
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, unsigned int count)
16 void *buf = f->buffer;
18 for (;;) {
19 int ret = xwrite(f->fd, buf, count);
20 if (ret > 0) {
21 f->total += ret;
22 display_throughput(f->tp, f->total);
23 buf = (char *) buf + ret;
24 count -= ret;
25 if (count)
26 continue;
27 return;
29 if (!ret)
30 die("sha1 file '%s' write error. Out of diskspace", f->name);
31 die("sha1 file '%s' write error (%s)", f->name, strerror(errno));
35 int sha1close(struct sha1file *f, unsigned char *result, int final)
37 int fd;
38 unsigned offset = f->offset;
39 if (offset) {
40 SHA1_Update(&f->ctx, f->buffer, offset);
41 sha1flush(f, offset);
42 f->offset = 0;
44 if (final) {
45 /* write checksum and close fd */
46 SHA1_Final(f->buffer, &f->ctx);
47 if (result)
48 hashcpy(result, f->buffer);
49 sha1flush(f, 20);
50 if (close(f->fd))
51 die("%s: sha1 file error on close (%s)",
52 f->name, strerror(errno));
53 fd = 0;
54 } else
55 fd = f->fd;
56 free(f);
57 return fd;
60 int sha1write(struct sha1file *f, void *buf, unsigned int count)
62 if (f->do_crc)
63 f->crc32 = crc32(f->crc32, buf, count);
64 while (count) {
65 unsigned offset = f->offset;
66 unsigned left = sizeof(f->buffer) - offset;
67 unsigned nr = count > left ? left : count;
69 memcpy(f->buffer + offset, buf, nr);
70 count -= nr;
71 offset += nr;
72 buf = (char *) buf + nr;
73 left -= nr;
74 if (!left) {
75 SHA1_Update(&f->ctx, f->buffer, offset);
76 sha1flush(f, offset);
77 offset = 0;
79 f->offset = offset;
81 return 0;
84 struct sha1file *sha1fd(int fd, const char *name)
86 return sha1fd_throughput(fd, name, NULL);
89 struct sha1file *sha1fd_throughput(int fd, const char *name, struct progress *tp)
91 struct sha1file *f = xmalloc(sizeof(*f));
92 f->fd = fd;
93 f->offset = 0;
94 f->total = 0;
95 f->tp = tp;
96 f->name = name;
97 f->do_crc = 0;
98 SHA1_Init(&f->ctx);
99 return f;
102 void crc32_begin(struct sha1file *f)
104 f->crc32 = crc32(0, Z_NULL, 0);
105 f->do_crc = 1;
108 uint32_t crc32_end(struct sha1file *f)
110 f->do_crc = 0;
111 return f->crc32;