aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/blockcodecs/codecs/lzma/lzma.cpp
blob: ab3a2466f58513ddef16ee42b54b63f86bd9ab27 (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
65
66
67
68
69
70
71
72
73
74
#include <library/cpp/blockcodecs/core/codecs.h>
#include <library/cpp/blockcodecs/core/common.h>
#include <library/cpp/blockcodecs/core/register.h>

#include <contrib/libs/lzmasdk/LzmaLib.h>

using namespace NBlockCodecs;

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

        static inline size_t DoMaxCompressedLength(size_t in) noexcept {
            return Max<size_t>(in + in / 20, 128) + LZMA_PROPS_SIZE;
        }

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

        inline size_t DoCompress(const TData& in, void* buf) const {
            unsigned char* props = (unsigned char*)buf;
            unsigned char* data = props + LZMA_PROPS_SIZE;
            size_t destLen = Max<size_t>();
            size_t outPropsSize = LZMA_PROPS_SIZE;

            const int ret = LzmaCompress(data, &destLen, (const unsigned char*)in.data(), in.size(), props, &outPropsSize, Level, 0, -1, -1, -1, -1, -1);

            if (ret != SZ_OK) {
                ythrow TCompressError(ret);
            }

            return destLen + LZMA_PROPS_SIZE;
        }

        inline void DoDecompress(const TData& in, void* out, size_t len) const {
            if (in.size() <= LZMA_PROPS_SIZE) {
                ythrow TDataError() << TStringBuf("broken lzma stream");
            }

            const unsigned char* props = (const unsigned char*)in.data();
            const unsigned char* data = props + LZMA_PROPS_SIZE;
            size_t destLen = len;
            SizeT srcLen = in.size() - LZMA_PROPS_SIZE;

            const int res = LzmaUncompress((unsigned char*)out, &destLen, data, &srcLen, props, LZMA_PROPS_SIZE);

            if (res != SZ_OK) {
                ythrow TDecompressError(res);
            }

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

        const int Level;
        const TString MyName;
    };

    struct TLzmaRegistrar {
        TLzmaRegistrar() {
            for (int i = 0; i < 10; ++i) {
                RegisterCodec(MakeHolder<TLzmaCodec>(i)); 
            }
            RegisterAlias("lzma", "lzma-5");
        }
    };
    const TLzmaRegistrar Registrar{};
}