]>
git.proxmox.com Git - ceph.git/blob - ceph/src/zstd/examples/simple_decompression.c
2 * Copyright (c) 2016-present, Yann Collet, Facebook, Inc.
5 * This source code is licensed under both the BSD-style license (found in the
6 * LICENSE file in the root directory of this source tree) and the GPLv2 (found
7 * in the COPYING file in the root directory of this source tree).
8 * You may select, at your option, one of the above-listed licenses.
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 #define ZSTD_STATIC_LINKING_ONLY // ZSTD_findDecompressedSize
17 #include <zstd.h> // presumes zstd library is installed
20 static off_t
fsize_orDie(const char *filename
)
23 if (stat(filename
, &st
) == 0) return st
.st_size
;
25 fprintf(stderr
, "stat: %s : %s \n", filename
, strerror(errno
));
29 static FILE* fopen_orDie(const char *filename
, const char *instruction
)
31 FILE* const inFile
= fopen(filename
, instruction
);
32 if (inFile
) return inFile
;
34 fprintf(stderr
, "fopen: %s : %s \n", filename
, strerror(errno
));
38 static void* malloc_orDie(size_t size
)
40 void* const buff
= malloc(size
+ !size
); /* avoid allocating size of 0 : may return NULL (implementation dependent) */
41 if (buff
) return buff
;
43 fprintf(stderr
, "malloc: %s \n", strerror(errno
));
47 static void* loadFile_orDie(const char* fileName
, size_t* size
)
49 off_t
const buffSize
= fsize_orDie(fileName
);
50 FILE* const inFile
= fopen_orDie(fileName
, "rb");
51 void* const buffer
= malloc_orDie(buffSize
);
52 size_t const readSize
= fread(buffer
, 1, buffSize
, inFile
);
53 if (readSize
!= (size_t)buffSize
) {
54 fprintf(stderr
, "fread: %s : %s \n", fileName
, strerror(errno
));
57 fclose(inFile
); /* can't fail (read only) */
63 static void decompress(const char* fname
)
66 void* const cBuff
= loadFile_orDie(fname
, &cSize
);
67 unsigned long long const rSize
= ZSTD_findDecompressedSize(cBuff
, cSize
);
68 if (rSize
==ZSTD_CONTENTSIZE_ERROR
) {
69 fprintf(stderr
, "%s : it was not compressed by zstd.\n", fname
);
71 } else if (rSize
==ZSTD_CONTENTSIZE_UNKNOWN
) {
73 "%s : original size unknown. Use streaming decompression instead.\n", fname
);
77 void* const rBuff
= malloc_orDie((size_t)rSize
);
79 size_t const dSize
= ZSTD_decompress(rBuff
, rSize
, cBuff
, cSize
);
82 fprintf(stderr
, "error decoding %s : %s \n", fname
, ZSTD_getErrorName(dSize
));
87 printf("%25s : %6u -> %7u \n", fname
, (unsigned)cSize
, (unsigned)rSize
);
94 int main(int argc
, const char** argv
)
96 const char* const exeName
= argv
[0];
99 printf("wrong arguments\n");
101 printf("%s FILE\n", exeName
);
107 printf("%s correctly decoded (in memory). \n", argv
[1]);