xref: /freebsd/sys/contrib/zstd/examples/simple_compression.c (revision aa1a8ff2d6dbc51ef058f46f3db5a8bb77967145)
1 /*
2  * Copyright (c) Yann Collet, Facebook, Inc.
3  * All rights reserved.
4  *
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.
9  */
10 
11 #include <stdio.h>     // printf
12 #include <stdlib.h>    // free
13 #include <string.h>    // strlen, strcat, memset
14 #include <zstd.h>      // presumes zstd library is installed
15 #include "common.h"    // Helper functions, CHECK(), and CHECK_ZSTD()
16 
17 static void compress_orDie(const char* fname, const char* oname)
18 {
19     size_t fSize;
20     void* const fBuff = mallocAndLoadFile_orDie(fname, &fSize);
21     size_t const cBuffSize = ZSTD_compressBound(fSize);
22     void* const cBuff = malloc_orDie(cBuffSize);
23 
24     /* Compress.
25      * If you are doing many compressions, you may want to reuse the context.
26      * See the multiple_simple_compression.c example.
27      */
28     size_t const cSize = ZSTD_compress(cBuff, cBuffSize, fBuff, fSize, 1);
29     CHECK_ZSTD(cSize);
30 
31     saveFile_orDie(oname, cBuff, cSize);
32 
33     /* success */
34     printf("%25s : %6u -> %7u - %s \n", fname, (unsigned)fSize, (unsigned)cSize, oname);
35 
36     free(fBuff);
37     free(cBuff);
38 }
39 
40 static char* createOutFilename_orDie(const char* filename)
41 {
42     size_t const inL = strlen(filename);
43     size_t const outL = inL + 5;
44     void* const outSpace = malloc_orDie(outL);
45     memset(outSpace, 0, outL);
46     strcat(outSpace, filename);
47     strcat(outSpace, ".zst");
48     return (char*)outSpace;
49 }
50 
51 int main(int argc, const char** argv)
52 {
53     const char* const exeName = argv[0];
54 
55     if (argc!=2) {
56         printf("wrong arguments\n");
57         printf("usage:\n");
58         printf("%s FILE\n", exeName);
59         return 1;
60     }
61 
62     const char* const inFilename = argv[1];
63 
64     char* const outFilename = createOutFilename_orDie(inFilename);
65     compress_orDie(inFilename, outFilename);
66     free(outFilename);
67     return 0;
68 }
69