]> git.proxmox.com Git - ceph.git/blob - ceph/src/zstd/examples/simple_decompression.c
add subtree-ish sources for 12.0.3
[ceph.git] / ceph / src / zstd / examples / simple_decompression.c
1 /**
2 * Copyright 2016-present, Yann Collet, Facebook, Inc.
3 * All rights reserved.
4 *
5 * This source code is licensed under the license found in the
6 * LICENSE-examples file in the root directory of this source tree.
7 */
8
9
10
11 #include <stdlib.h> // malloc, exit
12 #include <stdio.h> // printf
13 #include <string.h> // strerror
14 #include <errno.h> // errno
15 #include <sys/stat.h> // stat
16 #include <zstd.h> // presumes zstd library is installed
17
18
19 static off_t fsize_X(const char *filename)
20 {
21 struct stat st;
22 if (stat(filename, &st) == 0) return st.st_size;
23 /* error */
24 printf("stat: %s : %s \n", filename, strerror(errno));
25 exit(1);
26 }
27
28 static FILE* fopen_X(const char *filename, const char *instruction)
29 {
30 FILE* const inFile = fopen(filename, instruction);
31 if (inFile) return inFile;
32 /* error */
33 printf("fopen: %s : %s \n", filename, strerror(errno));
34 exit(2);
35 }
36
37 static void* malloc_X(size_t size)
38 {
39 void* const buff = malloc(size);
40 if (buff) return buff;
41 /* error */
42 printf("malloc: %s \n", strerror(errno));
43 exit(3);
44 }
45
46 static void* loadFile_X(const char* fileName, size_t* size)
47 {
48 off_t const buffSize = fsize_X(fileName);
49 FILE* const inFile = fopen_X(fileName, "rb");
50 void* const buffer = malloc_X(buffSize);
51 size_t const readSize = fread(buffer, 1, buffSize, inFile);
52 if (readSize != (size_t)buffSize) {
53 printf("fread: %s : %s \n", fileName, strerror(errno));
54 exit(4);
55 }
56 fclose(inFile); /* can't fail (read only) */
57 *size = buffSize;
58 return buffer;
59 }
60
61
62 static void decompress(const char* fname)
63 {
64 size_t cSize;
65 void* const cBuff = loadFile_X(fname, &cSize);
66 unsigned long long const rSize = ZSTD_getDecompressedSize(cBuff, cSize);
67 if (rSize==0) {
68 printf("%s : original size unknown. Use streaming decompression instead. \n", fname);
69 exit(5);
70 }
71 void* const rBuff = malloc_X((size_t)rSize);
72
73 size_t const dSize = ZSTD_decompress(rBuff, rSize, cBuff, cSize);
74
75 if (dSize != rSize) {
76 printf("error decoding %s : %s \n", fname, ZSTD_getErrorName(dSize));
77 exit(7);
78 }
79
80 /* success */
81 printf("%25s : %6u -> %7u \n", fname, (unsigned)cSize, (unsigned)rSize);
82
83 free(rBuff);
84 free(cBuff);
85 }
86
87
88 int main(int argc, const char** argv)
89 {
90 const char* const exeName = argv[0];
91
92 if (argc!=2) {
93 printf("wrong arguments\n");
94 printf("usage:\n");
95 printf("%s FILE\n", exeName);
96 return 1;
97 }
98
99 decompress(argv[1]);
100
101 printf("%s correctly decoded (in memory). \n", argv[1]);
102
103 return 0;
104 }