xref: /freebsd/sys/contrib/xz-embedded/linux/lib/xz/xz_crc32.c (revision cd3a777bca91669fc4711d1eff66c40f3f62a223)
163dab8eeSAdrian Chadd /*
263dab8eeSAdrian Chadd  * CRC32 using the polynomial from IEEE-802.3
363dab8eeSAdrian Chadd  *
463dab8eeSAdrian Chadd  * Authors: Lasse Collin <lasse.collin@tukaani.org>
5*cd3a777bSXin LI  *          Igor Pavlov <https://7-zip.org/>
663dab8eeSAdrian Chadd  *
763dab8eeSAdrian Chadd  * This file has been put into the public domain.
863dab8eeSAdrian Chadd  * You can do whatever you want with this file.
963dab8eeSAdrian Chadd  */
1063dab8eeSAdrian Chadd 
1163dab8eeSAdrian Chadd /*
1263dab8eeSAdrian Chadd  * This is not the fastest implementation, but it is pretty compact.
1363dab8eeSAdrian Chadd  * The fastest versions of xz_crc32() on modern CPUs without hardware
1463dab8eeSAdrian Chadd  * accelerated CRC instruction are 3-5 times as fast as this version,
1563dab8eeSAdrian Chadd  * but they are bigger and use more memory for the lookup table.
1663dab8eeSAdrian Chadd  */
1763dab8eeSAdrian Chadd 
1863dab8eeSAdrian Chadd #include "xz_private.h"
1963dab8eeSAdrian Chadd 
2063dab8eeSAdrian Chadd /*
2163dab8eeSAdrian Chadd  * STATIC_RW_DATA is used in the pre-boot environment on some architectures.
2263dab8eeSAdrian Chadd  * See <linux/decompress/mm.h> for details.
2363dab8eeSAdrian Chadd  */
2463dab8eeSAdrian Chadd #ifndef STATIC_RW_DATA
2563dab8eeSAdrian Chadd #	define STATIC_RW_DATA static
2663dab8eeSAdrian Chadd #endif
2763dab8eeSAdrian Chadd 
2863dab8eeSAdrian Chadd STATIC_RW_DATA uint32_t xz_crc32_table[256];
2963dab8eeSAdrian Chadd 
xz_crc32_init(void)3063dab8eeSAdrian Chadd XZ_EXTERN void xz_crc32_init(void)
3163dab8eeSAdrian Chadd {
3263dab8eeSAdrian Chadd 	const uint32_t poly = 0xEDB88320;
3363dab8eeSAdrian Chadd 
3463dab8eeSAdrian Chadd 	uint32_t i;
3563dab8eeSAdrian Chadd 	uint32_t j;
3663dab8eeSAdrian Chadd 	uint32_t r;
3763dab8eeSAdrian Chadd 
3863dab8eeSAdrian Chadd 	for (i = 0; i < 256; ++i) {
3963dab8eeSAdrian Chadd 		r = i;
4063dab8eeSAdrian Chadd 		for (j = 0; j < 8; ++j)
4163dab8eeSAdrian Chadd 			r = (r >> 1) ^ (poly & ~((r & 1) - 1));
4263dab8eeSAdrian Chadd 
4363dab8eeSAdrian Chadd 		xz_crc32_table[i] = r;
4463dab8eeSAdrian Chadd 	}
4563dab8eeSAdrian Chadd 
4663dab8eeSAdrian Chadd 	return;
4763dab8eeSAdrian Chadd }
4863dab8eeSAdrian Chadd 
xz_crc32(const uint8_t * buf,size_t size,uint32_t crc)4963dab8eeSAdrian Chadd XZ_EXTERN uint32_t xz_crc32(const uint8_t *buf, size_t size, uint32_t crc)
5063dab8eeSAdrian Chadd {
5163dab8eeSAdrian Chadd 	crc = ~crc;
5263dab8eeSAdrian Chadd 
5363dab8eeSAdrian Chadd 	while (size != 0) {
5463dab8eeSAdrian Chadd 		crc = xz_crc32_table[*buf++ ^ (crc & 0xFF)] ^ (crc >> 8);
5563dab8eeSAdrian Chadd 		--size;
5663dab8eeSAdrian Chadd 	}
5763dab8eeSAdrian Chadd 
5863dab8eeSAdrian Chadd 	return ~crc;
5963dab8eeSAdrian Chadd }
60