soc/intel/xeon_sp: Align resources to 4K
[coreboot2.git] / util / cbfstool / compress.c
blob96df1a74991f58e796d73f3f1aa70278417ae513
1 /* compression handling for cbfstool */
2 /* SPDX-License-Identifier: GPL-2.0-only */
4 #include <string.h>
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include "common.h"
8 #include "lz4/lib/lz4frame.h"
9 #include <commonlib/bsd/compression.h>
11 static int lz4_compress(char *in, int in_len, char *out, int *out_len)
13 LZ4F_preferences_t prefs = {
14 .compressionLevel = 20,
15 .frameInfo = {
16 .blockSizeID = max4MB,
17 .blockMode = blockIndependent,
18 .contentChecksumFlag = noContentChecksum,
21 size_t worst_size = LZ4F_compressFrameBound(in_len, &prefs);
22 void *bounce = malloc(worst_size);
23 if (!bounce)
24 return -1;
25 *out_len = LZ4F_compressFrame(bounce, worst_size, in, in_len, &prefs);
26 if (LZ4F_isError(*out_len) || *out_len >= in_len) {
27 free(bounce);
28 return -1;
30 memcpy(out, bounce, *out_len);
31 free(bounce);
32 return 0;
35 static int lz4_decompress(char *in, int in_len, char *out, int out_len,
36 size_t *actual_size)
38 size_t result = ulz4fn(in, in_len, out, out_len);
39 if (result == 0)
40 return -1;
41 if (actual_size != NULL)
42 *actual_size = result;
43 return 0;
46 static int lzma_compress(char *in, int in_len, char *out, int *out_len)
48 return do_lzma_compress(in, in_len, out, out_len);
51 static int lzma_decompress(char *in, int in_len, char *out, unused int out_len,
52 size_t *actual_size)
54 return do_lzma_uncompress(out, out_len, in, in_len, actual_size);
56 static int none_compress(char *in, int in_len, char *out, int *out_len)
58 memcpy(out, in, in_len);
59 *out_len = in_len;
60 return 0;
63 static int none_decompress(char *in, int in_len, char *out, unused int out_len,
64 size_t *actual_size)
66 memcpy(out, in, in_len);
67 if (actual_size != NULL)
68 *actual_size = in_len;
69 return 0;
72 comp_func_ptr compression_function(enum cbfs_compression algo)
74 comp_func_ptr compress;
75 switch (algo) {
76 case CBFS_COMPRESS_NONE:
77 compress = none_compress;
78 break;
79 case CBFS_COMPRESS_LZMA:
80 compress = lzma_compress;
81 break;
82 case CBFS_COMPRESS_LZ4:
83 compress = lz4_compress;
84 break;
85 default:
86 ERROR("Unknown compression algorithm %d!\n", algo);
87 return NULL;
89 return compress;
92 decomp_func_ptr decompression_function(enum cbfs_compression algo)
94 decomp_func_ptr decompress;
95 switch (algo) {
96 case CBFS_COMPRESS_NONE:
97 decompress = none_decompress;
98 break;
99 case CBFS_COMPRESS_LZMA:
100 decompress = lzma_decompress;
101 break;
102 case CBFS_COMPRESS_LZ4:
103 decompress = lz4_decompress;
104 break;
105 default:
106 ERROR("Unknown compression algorithm %d!\n", algo);
107 return NULL;
109 return decompress;