1 /*
2  * Copyright (c) 2020 Linumiz
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <stdio.h>
8 #include <zephyr/kernel.h>
9 #include <zephyr/misc/lorem_ipsum.h>
10 #include <string.h>
11 #include <stdlib.h>
12 #include "lz4.h"
13 
main(void)14 int main(void)
15 {
16 	static const char *src = LOREM_IPSUM;
17 
18 	const int src_size = (int)(strlen(src) + 1);
19 	const int max_dst_size = LZ4_compressBound(src_size);
20 
21 	char *compressed_data = malloc((size_t)max_dst_size);
22 
23 	if (compressed_data == NULL) {
24 		printk("Failed to allocate memory for compressed data\n");
25 		return 0;
26 	}
27 
28 	const int compressed_data_size = LZ4_compress_default(src,
29 					compressed_data, src_size,
30 					max_dst_size);
31 	if (compressed_data_size <= 0) {
32 		printk("Failed to compress the data\n");
33 		return 0;
34 	}
35 
36 	printk("Original Data size: %d\n", src_size);
37 	printk("Compressed Data size : %d\n", compressed_data_size);
38 
39 	compressed_data = (char *)realloc(compressed_data,
40 					  (size_t)compressed_data_size);
41 	if (compressed_data == NULL) {
42 		printk("Failed to re-alloc memory for compressed data\n");
43 		return 0;
44 	}
45 
46 	char * const decompressed_data = malloc(src_size);
47 
48 	if (decompressed_data == NULL) {
49 		printk("Failed to allocate memory to decompress data\n");
50 		return 0;
51 	}
52 
53 	const int decompressed_size = LZ4_decompress_safe(compressed_data,
54 				      decompressed_data, compressed_data_size,
55 				      src_size);
56 	if (decompressed_size < 0) {
57 		printk("Failed to decompress the data\n");
58 		return 0;
59 	}
60 
61 	free(compressed_data);
62 
63 	if (decompressed_size >= 0) {
64 		printk("Successfully decompressed some data\n");
65 	}
66 
67 	if (decompressed_size != src_size) {
68 		printk("Decompressed data is different from original\n");
69 		return 0;
70 	}
71 
72 	if (memcmp(src, decompressed_data, src_size) != 0) {
73 		printk("Validation failed.\n");
74 		printk("*src and *new_src are not identical\n");
75 		return 0;
76 	}
77 
78 	printk("Validation done. The string we ended up with is:\n%s\n",
79 			decompressed_data);
80 	return 0;
81 }
82