15df09a9cem/*
25df09a9cem * Copyright (c) 2016-present, Yann Collet, Facebook, Inc.
35df09a9cem * All rights reserved.
45df09a9cem *
55df09a9cem * This source code is licensed under both the BSD-style license (found in the
65df09a9cem * LICENSE file in the root directory of this source tree) and the GPLv2 (found
75df09a9cem * in the COPYING file in the root directory of this source tree).
85df09a9cem * You may select, at your option, one of the above-listed licenses.
95df09a9cem */
105df09a9cem
115df09a9cem#include <stdio.h>     // printf
125df09a9cem#include <stdlib.h>    // free
135df09a9cem#include <string.h>    // strlen, strcat, memset
145df09a9cem#include <zstd.h>      // presumes zstd library is installed
155df09a9cem#include "common.h"    // Helper functions, CHECK(), and CHECK_ZSTD()
165df09a9cem
175df09a9cemstatic void compress_orDie(const char* fname, const char* oname)
185df09a9cem{
195df09a9cem    size_t fSize;
205df09a9cem    void* const fBuff = mallocAndLoadFile_orDie(fname, &fSize);
215df09a9cem    size_t const cBuffSize = ZSTD_compressBound(fSize);
225df09a9cem    void* const cBuff = malloc_orDie(cBuffSize);
235df09a9cem
245df09a9cem    /* Compress.
255df09a9cem     * If you are doing many compressions, you may want to reuse the context.
265df09a9cem     * See the multiple_simple_compression.c example.
275df09a9cem     */
285df09a9cem    size_t const cSize = ZSTD_compress(cBuff, cBuffSize, fBuff, fSize, 1);
295df09a9cem    CHECK_ZSTD(cSize);
305df09a9cem
315df09a9cem    saveFile_orDie(oname, cBuff, cSize);
325df09a9cem
335df09a9cem    /* success */
345df09a9cem    printf("%25s : %6u -> %7u - %s \n", fname, (unsigned)fSize, (unsigned)cSize, oname);
355df09a9cem
365df09a9cem    free(fBuff);
375df09a9cem    free(cBuff);
385df09a9cem}
395df09a9cem
405df09a9cemstatic char* createOutFilename_orDie(const char* filename)
415df09a9cem{
425df09a9cem    size_t const inL = strlen(filename);
435df09a9cem    size_t const outL = inL + 5;
445df09a9cem    void* const outSpace = malloc_orDie(outL);
455df09a9cem    memset(outSpace, 0, outL);
465df09a9cem    strcat(outSpace, filename);
475df09a9cem    strcat(outSpace, ".zst");
485df09a9cem    return (char*)outSpace;
495df09a9cem}
505df09a9cem
515df09a9cemint main(int argc, const char** argv)
525df09a9cem{
535df09a9cem    const char* const exeName = argv[0];
545df09a9cem
555df09a9cem    if (argc!=2) {
565df09a9cem        printf("wrong arguments\n");
575df09a9cem        printf("usage:\n");
585df09a9cem        printf("%s FILE\n", exeName);
595df09a9cem        return 1;
605df09a9cem    }
615df09a9cem
625df09a9cem    const char* const inFilename = argv[1];
635df09a9cem
645df09a9cem    char* const outFilename = createOutFilename_orDie(inFilename);
655df09a9cem    compress_orDie(inFilename, outFilename);
665df09a9cem    free(outFilename);
675df09a9cem    return 0;
685df09a9cem}
69