-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.c
71 lines (56 loc) · 1.18 KB
/
utils.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#include "compat.h"
#include "utils.h"
#include "progress.h"
#ifdef HAVE_SSE4_1_INSTRUCTIONS
#include "crc32-simd.h"
#define CRC32_PROCESS crc32_buffer_simd
#else
#include "crc32.h"
#define CRC32_PROCESS crc32_buffer
#endif
#define BUFSIZE 32 * 1024 * 1024
long crc32_fd(int fd, struct progress *progress)
{
unsigned char *buffer, *ptr;
unsigned int align, checksum = ~0;
int n = 0;
/*
* Align the buffer to improve performance of the SIMD
* instructions.
*/
buffer = malloc(BUFSIZE + 16);
align = (unsigned long) buffer % 16;
ptr = buffer + (16 - align);
while (1) {
n = read(fd, ptr, BUFSIZE);
if (n == -1) {
checksum = -errno;
goto out;
}
if (n == 0)
break;
checksum = CRC32_PROCESS(ptr, n, checksum);
if (progress)
progress->add(progress, n);
}
checksum = ~checksum;
out:
free(buffer);
return checksum;
}
long crc32_file(const char *filename, struct progress *progress)
{
struct stat st;
unsigned int checksum;
int fd;
if (stat(filename, &st) != 0)
return -errno;
if (S_ISDIR(st.st_mode))
return -EISDIR;
fd = open(filename, O_RDONLY);
if (fd < 0)
return -errno;
checksum = crc32_fd(fd, progress);
close(fd);
return checksum;
}