aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/blockcodecs/codecs/zstd/zstd.cpp
blob: 95299b3f6d35be1fcbee30e674968b9e2cb9bda2 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include <library/cpp/blockcodecs/core/codecs.h>
#include <library/cpp/blockcodecs/core/common.h>
#include <library/cpp/blockcodecs/core/register.h>

#define ZSTD_STATIC_LINKING_ONLY
#include <contrib/libs/zstd/include/zstd.h>

using namespace NBlockCodecs;

namespace {
    struct TZStd08Codec: public TAddLengthCodec<TZStd08Codec> {
        inline TZStd08Codec(unsigned level)
            : Level(level)
            , MyName(TStringBuf("zstd08_") + ToString(Level))
        {
        }

        static inline size_t CheckError(size_t ret, const char* what) {
            if (ZSTD_isError(ret)) {
                ythrow yexception() << what << TStringBuf(" zstd error: ") << ZSTD_getErrorName(ret);
            }

            return ret;
        }

        static inline size_t DoMaxCompressedLength(size_t l) noexcept {
            return ZSTD_compressBound(l);
        }

        inline size_t DoCompress(const TData& in, void* out) const {
            return CheckError(ZSTD_compress(out, DoMaxCompressedLength(in.size()), in.data(), in.size(), Level), "compress");
        }

        inline void DoDecompress(const TData& in, void* out, size_t dsize) const {
            const size_t res = CheckError(ZSTD_decompress(out, dsize, in.data(), in.size()), "decompress");

            if (res != dsize) {
                ythrow TDecompressError(dsize, res);
            }
        }

        TStringBuf Name() const noexcept override {
            return MyName;
        }

        const unsigned Level;
        const TString MyName;
    };

    struct TZStd08Registrar {
        TZStd08Registrar() {
            for (int i = 1; i <= ZSTD_maxCLevel(); ++i) {
                RegisterCodec(MakeHolder<TZStd08Codec>(i));
                RegisterAlias("zstd_" + ToString(i), "zstd08_" + ToString(i));
            }
        }
    };
    const TZStd08Registrar Registrar{};
}