xref: /plan9/sys/src/libflate/crc.c (revision 80ee5cbfe36716af62da8896207e9763b8e3d760)
1 #include <u.h>
2 #include <libc.h>
3 #include <flate.h>
4 
5 ulong*
mkcrctab(ulong poly)6 mkcrctab(ulong poly)
7 {
8 	ulong *crctab;
9 	ulong crc;
10 	int i, j;
11 
12 	crctab = malloc(256 * sizeof(ulong));
13 	if(crctab == nil)
14 		return nil;
15 
16 	for(i = 0; i < 256; i++){
17 		crc = i;
18 		for(j = 0; j < 8; j++){
19 			if(crc & 1)
20 				crc = (crc >> 1) ^ poly;
21 			else
22 				crc >>= 1;
23 		}
24 		crctab[i] = crc;
25 	}
26 	return crctab;
27 }
28 
29 ulong
blockcrc(ulong * crctab,ulong crc,void * vbuf,int n)30 blockcrc(ulong *crctab, ulong crc, void *vbuf, int n)
31 {
32 	uchar *buf, *ebuf;
33 
34 	crc ^= 0xffffffff;
35 	buf = vbuf;
36 	ebuf = buf + n;
37 	while(buf < ebuf)
38 		crc = crctab[(crc & 0xff) ^ *buf++] ^ (crc >> 8);
39 	return crc ^ 0xffffffff;
40 }
41