RelNotes draft for 1.5.3 update.
[git/builtin-gsoc.git] / csum-file.c
blob9ab997120d04c5be0aa9d3ff3ba090ba12b7bec8
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 "csum-file.h"
13 static void sha1flush(struct sha1file *f, unsigned int count)
15 void *buf = f->buffer;
17 for (;;) {
18 int ret = xwrite(f->fd, buf, count);
19 if (ret > 0) {
20 buf = (char *) buf + ret;
21 count -= ret;
22 if (count)
23 continue;
24 return;
26 if (!ret)
27 die("sha1 file '%s' write error. Out of diskspace", f->name);
28 die("sha1 file '%s' write error (%s)", f->name, strerror(errno));
32 int sha1close(struct sha1file *f, unsigned char *result, int final)
34 unsigned offset = f->offset;
35 if (offset) {
36 SHA1_Update(&f->ctx, f->buffer, offset);
37 sha1flush(f, offset);
38 f->offset = 0;
40 if (!final)
41 return 0; /* only want to flush (no checksum write, no close) */
42 SHA1_Final(f->buffer, &f->ctx);
43 if (result)
44 hashcpy(result, f->buffer);
45 sha1flush(f, 20);
46 if (close(f->fd))
47 die("%s: sha1 file error on close (%s)", f->name, strerror(errno));
48 free(f);
49 return 0;
52 int sha1write(struct sha1file *f, void *buf, unsigned int count)
54 if (f->do_crc)
55 f->crc32 = crc32(f->crc32, buf, count);
56 while (count) {
57 unsigned offset = f->offset;
58 unsigned left = sizeof(f->buffer) - offset;
59 unsigned nr = count > left ? left : count;
61 memcpy(f->buffer + offset, buf, nr);
62 count -= nr;
63 offset += nr;
64 buf = (char *) buf + nr;
65 left -= nr;
66 if (!left) {
67 SHA1_Update(&f->ctx, f->buffer, offset);
68 sha1flush(f, offset);
69 offset = 0;
71 f->offset = offset;
73 return 0;
76 struct sha1file *sha1fd(int fd, const char *name)
78 struct sha1file *f;
79 unsigned len;
81 f = xmalloc(sizeof(*f));
83 len = strlen(name);
84 if (len >= PATH_MAX)
85 die("you wascally wabbit, you");
86 f->namelen = len;
87 memcpy(f->name, name, len+1);
89 f->fd = fd;
90 f->error = 0;
91 f->offset = 0;
92 f->do_crc = 0;
93 SHA1_Init(&f->ctx);
94 return f;
97 void crc32_begin(struct sha1file *f)
99 f->crc32 = crc32(0, Z_NULL, 0);
100 f->do_crc = 1;
103 uint32_t crc32_end(struct sha1file *f)
105 f->do_crc = 0;
106 return f->crc32;