1 /*
2  * \file roundtrip.c
3  * In this example we include \c zstd.h and compile separately the amalgamated
4  * \c zstd.c:
5  * \code
6  *	cc -Wall -Wextra -Werror -I. -Os -g0 zstd.c examples/roundtrip.c
7  * \endcode
8  *
9  * \author Carl Woffenden, Numfum GmbH (released under a CC0 license)
10  */
11 
12 #include <stddef.h>
13 #include <stdint.h>
14 #include <stdio.h>
15 #include <stdlib.h>
16 #include <string.h>
17 
18 #include "zstd.h"
19 
20 //************************** Test Data (DXT texture) **************************/
21 
22 /**
23  * Raw test data (borrowed from the Emscripten example).
24  * \n
25  * See \c testcard.png for the original.
26  */
27 static uint8_t const rawData[] = {
28 #include "testcard-dxt1.inl"
29 };
30 
31 #ifndef ZSTD_VERSION_MAJOR
32 /*
33  * For the case where the decompression library hasn't been included we add
34  * dummy functions to fake the process and stop the buffers being optimised out.
35  */
ZSTD_compressBound(size_t maxSrc)36 size_t ZSTD_compressBound(size_t maxSrc) {
37 	return maxSrc + 32;
38 }
ZSTD_maxCLevel(void)39 int ZSTD_maxCLevel(void) {
40 	return 20;
41 }
ZSTD_compress(void * dst,size_t dstLen,const void * src,size_t srcLen,int level)42 size_t ZSTD_compress(void* dst, size_t dstLen, const void* src, size_t srcLen, int level) {
43 	return (memcmp(dst, src, (srcLen < dstLen) ? srcLen : dstLen)) ? level : dstLen;
44 }
ZSTD_isError(size_t code)45 unsigned ZSTD_isError(size_t code) {
46 	return ((int) code) < 0;
47 }
ZSTD_decompress(void * dst,size_t dstLen,const void * src,size_t srcLen)48 size_t ZSTD_decompress(void* dst, size_t dstLen, const void* src, size_t srcLen) {
49 	return (memcmp(dst, src, (srcLen < dstLen) ? srcLen : dstLen)) ? 0 : dstLen;
50 }
51 #endif
52 
53 //*****************************************************************************/
54 
55 /**
56  * Simple single-file test to compress \c rawData, decompress the result, then
57  * compare the decompressed version with the original.
58  */
main()59 int main() {
60 	size_t bounds = ZSTD_compressBound(sizeof rawData);
61 	void* compBuf = malloc(bounds);
62 	void* testBuf = malloc(sizeof rawData);
63 	int compare   = -1;
64 	if (compBuf && testBuf) {
65 		size_t compSize = ZSTD_compress(compBuf, bounds, rawData, sizeof rawData, ZSTD_maxCLevel());
66 		if (!ZSTD_isError(compSize)) {
67 			printf("Compression: PASSED (size: %lu, uncompressed: %lu)\n", (unsigned long) compSize, (unsigned long) (sizeof rawData));
68 			size_t decSize = ZSTD_decompress(testBuf, sizeof rawData, compBuf, compSize);
69 			if (!ZSTD_isError(decSize)) {
70 				printf("Decompression: PASSED\n");
71 				compare = memcmp(rawData, testBuf, decSize);
72 				printf("Byte comparison: %s\n", (compare == 0) ? "PASSED" : "FAILED");
73 			} else {
74 				printf("Decompression: FAILED\n");
75 			}
76 		} else {
77 			printf("Compression: FAILED\n");
78 		}
79 		free(compBuf);
80 		free(testBuf);
81 	}
82 	return (compare == 0) ? EXIT_SUCCESS : EXIT_FAILURE;
83 }
84