diff: use extended regexp to find hunk headers
[git/dkf.git] / csum-file.c
blob28389541a32454f2d988bb02e4268ffe12755bbc
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, unsigned int flags)
37 int fd;
38 unsigned offset = f->offset;
40 if (offset) {
41 SHA1_Update(&f->ctx, f->buffer, offset);
42 sha1flush(f, offset);
43 f->offset = 0;
45 SHA1_Final(f->buffer, &f->ctx);
46 if (result)
47 hashcpy(result, f->buffer);
48 if (flags & (CSUM_CLOSE | CSUM_FSYNC)) {
49 /* write checksum and close fd */
50 sha1flush(f, 20);
51 if (flags & CSUM_FSYNC)
52 fsync_or_die(f->fd, f->name);
53 if (close(f->fd))
54 die("%s: sha1 file error on close (%s)",
55 f->name, strerror(errno));
56 fd = 0;
57 } else
58 fd = f->fd;
59 free(f);
60 return fd;
63 int sha1write(struct sha1file *f, void *buf, unsigned int count)
65 if (f->do_crc)
66 f->crc32 = crc32(f->crc32, buf, count);
67 while (count) {
68 unsigned offset = f->offset;
69 unsigned left = sizeof(f->buffer) - offset;
70 unsigned nr = count > left ? left : count;
72 memcpy(f->buffer + offset, buf, nr);
73 count -= nr;
74 offset += nr;
75 buf = (char *) buf + nr;
76 left -= nr;
77 if (!left) {
78 SHA1_Update(&f->ctx, f->buffer, offset);
79 sha1flush(f, offset);
80 offset = 0;
82 f->offset = offset;
84 return 0;
87 struct sha1file *sha1fd(int fd, const char *name)
89 return sha1fd_throughput(fd, name, NULL);
92 struct sha1file *sha1fd_throughput(int fd, const char *name, struct progress *tp)
94 struct sha1file *f = xmalloc(sizeof(*f));
95 f->fd = fd;
96 f->offset = 0;
97 f->total = 0;
98 f->tp = tp;
99 f->name = name;
100 f->do_crc = 0;
101 SHA1_Init(&f->ctx);
102 return f;
105 void crc32_begin(struct sha1file *f)
107 f->crc32 = crc32(0, Z_NULL, 0);
108 f->do_crc = 1;
111 uint32_t crc32_end(struct sha1file *f)
113 f->do_crc = 0;
114 return f->crc32;