aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/blockcodecs/codecs/zlib/zlib.cpp
blob: 8e23269f6d2e84b38723102f9067d5ffccf0cd05 (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
60
61
62
63
64
#include <library/cpp/blockcodecs/core/codecs.h>
#include <library/cpp/blockcodecs/core/common.h>
#include <library/cpp/blockcodecs/core/register.h>

#include <contrib/libs/zlib/zlib.h>

using namespace NBlockCodecs;

namespace {
    struct TZLibCodec: public TAddLengthCodec<TZLibCodec> {
        inline TZLibCodec(int level)
            : MyName("zlib-" + ToString(level))
            , Level(level)
        {
        }

        static inline size_t DoMaxCompressedLength(size_t in) noexcept {
            return compressBound(in);
        }

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

        inline size_t DoCompress(const TData& in, void* buf) const {
            //TRASH detected
            uLong ret = Max<unsigned int>();

            int cres = compress2((Bytef*)buf, &ret, (const Bytef*)in.data(), in.size(), Level);

            if (cres != Z_OK) {
                ythrow TCompressError(cres);
            }

            return ret;
        }

        inline void DoDecompress(const TData& in, void* out, size_t len) const {
            uLong ret = len;

            int uncres = uncompress((Bytef*)out, &ret, (const Bytef*)in.data(), in.size());
            if (uncres != Z_OK) {
                ythrow TDecompressError(uncres);
            }

            if (ret != len) {
                ythrow TDecompressError(len, ret);
            }
        }

        const TString MyName;
        const int Level;
    };

    struct TZLibRegistrar {
        TZLibRegistrar() {
            for (int i = 0; i < 10; ++i) {
                RegisterCodec(MakeHolder<TZLibCodec>(i));
            }
            RegisterAlias("zlib", "zlib-6");
        }
    };
    const TZLibRegistrar Registrar{}; 
}