2020-12-27 16:02:35 +03:00
|
|
|
# CRC32c function
|
|
|
|
|
|
|
|
- Same code from : https://stackoverflow.com/a/17646775
|
|
|
|
- Fixed some alignment issues, replaced asm code with compiler intrinsics
|
|
|
|
|
2021-02-03 08:09:50 +03:00
|
|
|
- Compile time switch to hardware version if supported
|
|
|
|
(crc32c instruction on x64), fallback to software version if not available
|
2021-02-05 20:46:59 +03:00
|
|
|
- See CmakeLists.txt, it checks "-msse4.2" flag. Stackoverflow answer has
|
2020-12-27 16:02:35 +03:00
|
|
|
runtime dispatch between hardware and software versions if you'd like that.
|
|
|
|
|
|
|
|
|
|
|
|
- This is Crc32<b>c</b> algorithm, not Crc32
|
|
|
|
|
2021-02-03 08:09:50 +03:00
|
|
|
```cmake
|
2020-12-27 16:02:35 +03:00
|
|
|
## Cmake
|
|
|
|
|
2021-02-05 20:46:59 +03:00
|
|
|
# Needs HAVE_CRC32C definition to enable CPU instruction usage.
|
|
|
|
|
2020-12-27 16:02:35 +03:00
|
|
|
## Only use hardware version in 64 bit architectures.
|
2021-02-03 08:09:50 +03:00
|
|
|
include(CheckCCompilerFlag)
|
|
|
|
|
2020-12-27 16:02:35 +03:00
|
|
|
if("${CMAKE_SIZEOF_VOID_P}" EQUAL "8")
|
|
|
|
check_c_compiler_flag(-msse4.2 HAVE_CRC32_HARDWARE)
|
|
|
|
if (${HAVE_CRC32_HARDWARE})
|
2021-02-05 20:46:59 +03:00
|
|
|
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -msse4.2 -DHAVE_CRC32C")
|
2020-12-27 16:02:35 +03:00
|
|
|
endif ()
|
|
|
|
endif()
|
|
|
|
```
|
|
|
|
|
|
|
|
```c
|
|
|
|
|
2021-02-03 08:09:50 +03:00
|
|
|
#include "sc_crc32.h"
|
2020-12-27 16:02:35 +03:00
|
|
|
|
2021-02-03 08:09:50 +03:00
|
|
|
#include <stdio.h>
|
2020-12-27 16:02:35 +03:00
|
|
|
|
2021-02-03 08:09:50 +03:00
|
|
|
int main(int argc, char *argv[])
|
|
|
|
{
|
|
|
|
uint32_t crc;
|
|
|
|
const uint8_t buf[100] = {0};
|
2020-12-27 16:02:35 +03:00
|
|
|
|
2021-02-03 08:09:50 +03:00
|
|
|
sc_crc32_init();
|
2020-12-27 16:02:35 +03:00
|
|
|
|
2021-02-03 08:09:50 +03:00
|
|
|
// Partial calculation example
|
|
|
|
crc = sc_crc32(0, buf, 10);
|
|
|
|
crc = sc_crc32(crc, buf + 10, sizeof(buf) - 10);
|
|
|
|
printf("crc : %u \n", crc);
|
2020-12-27 16:02:35 +03:00
|
|
|
|
2021-02-03 08:09:50 +03:00
|
|
|
// Calculate at once
|
|
|
|
crc = sc_crc32(0, buf, sizeof(buf));
|
|
|
|
printf("crc : %u \n", crc);
|
2020-12-27 16:02:35 +03:00
|
|
|
|
2021-02-03 08:09:50 +03:00
|
|
|
return 0;
|
|
|
|
}
|
2020-12-27 16:02:35 +03:00
|
|
|
|
|
|
|
```
|