1 // SPDX-License-Identifier: 0BSD
2 
3 ///////////////////////////////////////////////////////////////////////////////
4 //
5 /// \file       crc64_tablegen.c
6 /// \brief      Generate crc64_table_le.h and crc64_table_be.h
7 ///
8 /// Compiling: gcc -std=c99 -o crc64_tablegen crc64_tablegen.c
9 /// Add -DWORDS_BIGENDIAN to generate big endian table.
10 //
11 //  Author:     Lasse Collin
12 //
13 ///////////////////////////////////////////////////////////////////////////////
14 
15 #include <stdio.h>
16 #include "../../common/tuklib_integer.h"
17 
18 
19 static uint64_t crc64_table[4][256];
20 
21 
22 extern void
23 init_crc64_table(void)
24 {
25 	static const uint64_t poly64 = UINT64_C(0xC96C5795D7870F42);
26 
27 	for (size_t s = 0; s < 4; ++s) {
28 		for (size_t b = 0; b < 256; ++b) {
29 			uint64_t r = s == 0 ? b : crc64_table[s - 1][b];
30 
31 			for (size_t i = 0; i < 8; ++i) {
32 				if (r & 1)
33 					r = (r >> 1) ^ poly64;
34 				else
35 					r >>= 1;
36 			}
37 
38 			crc64_table[s][b] = r;
39 		}
40 	}
41 
42 #ifdef WORDS_BIGENDIAN
43 	for (size_t s = 0; s < 4; ++s)
44 		for (size_t b = 0; b < 256; ++b)
45 			crc64_table[s][b] = bswap64(crc64_table[s][b]);
46 #endif
47 
48 	return;
49 }
50 
51 
52 static void
53 print_crc64_table(void)
54 {
55 	// Split the SPDX string so that it won't accidentally match
56 	// when tools search for the string.
57 	printf("// SPDX" "-License-Identifier" ": 0BSD\n\n"
58 		"// This file has been generated by crc64_tablegen.c.\n\n"
59 		"const uint64_t lzma_crc64_table[4][256] = {\n\t{");
60 
61 	for (size_t s = 0; s < 4; ++s) {
62 		for (size_t b = 0; b < 256; ++b) {
63 			if ((b % 2) == 0)
64 				printf("\n\t\t");
65 
66 			printf("UINT64_C(0x%016" PRIX64 ")",
67 					crc64_table[s][b]);
68 
69 			if (b != 255)
70 				printf(",%s", (b+1) % 2 == 0 ? "" : " ");
71 		}
72 
73 		if (s == 3)
74 			printf("\n\t}\n};\n");
75 		else
76 			printf("\n\t}, {");
77 	}
78 
79 	return;
80 }
81 
82 
83 int
84 main(void)
85 {
86 	init_crc64_table();
87 	print_crc64_table();
88 	return 0;
89 }
90