aboutsummaryrefslogtreecommitdiffstats
path: root/src/lib/compression/lzma/lzma.cpp
blob: d145ed305b65bbf25ecad6cfe696d4f0905aa0a8 (plain)
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
/*
* Lzma Compressor
* (C) 2001 Peter J Jones
*     2001-2007,2014 Jack Lloyd
*     2006 Matt Johnston
*     2012 Vojtech Kral
*
* Distributed under the terms of the Botan license
*/

#include <botan/lzma.h>
#include <botan/internal/comp_util.h>
#include <lzma.h>

namespace Botan {

namespace {

class LZMA_Stream : public Zlib_Style_Stream<lzma_stream, byte>
   {
   public:
      LZMA_Stream()
         {
         streamp()->allocator = new ::lzma_allocator;
         streamp()->allocator->opaque = alloc();
         streamp()->allocator->alloc = Compression_Alloc_Info::malloc<size_t>;
         streamp()->allocator->free = Compression_Alloc_Info::free;
         }

      ~LZMA_Stream()
         {
         ::lzma_end(streamp());
         delete streamp()->allocator;
         }

      bool run(u32bit flags) override
         {
         lzma_ret rc = ::lzma_code(streamp(), static_cast<lzma_action>(flags));

         if(rc == LZMA_MEM_ERROR)
            throw std::bad_alloc();
         else if (rc != LZMA_OK && rc != LZMA_STREAM_END)
            throw std::runtime_error("Lzma error");

         return (rc == LZMA_STREAM_END);
         }

      u32bit run_flag() const override { return LZMA_RUN; }
      u32bit flush_flag() const override { return LZMA_FULL_FLUSH; }
      u32bit finish_flag() const override { return LZMA_FINISH; }
   };

class LZMA_Compression_Stream : public LZMA_Stream
   {
   public:
      LZMA_Compression_Stream(size_t level)
         {
         lzma_ret rc = ::lzma_easy_encoder(streamp(), level, LZMA_CHECK_CRC64);

         if(rc == LZMA_MEM_ERROR)
            throw std::bad_alloc();
         else if(rc != LZMA_OK)
            throw std::runtime_error("lzma compress initialization failed");
         }
   };

class LZMA_Decompression_Stream : public LZMA_Stream
   {
   public:
      LZMA_Decompression_Stream()
         {
         lzma_ret rc = ::lzma_stream_decoder(streamp(), UINT64_MAX,
                                             LZMA_TELL_UNSUPPORTED_CHECK);

         if(rc == LZMA_MEM_ERROR)
            throw std::bad_alloc();
         else if(rc != LZMA_OK)
            throw std::runtime_error("Bad setting in lzma_stream_decoder");
         }
   };

}

Compression_Stream* LZMA_Compression::make_stream() const
   {
   return new LZMA_Compression_Stream(m_level);
   }

Compression_Stream* LZMA_Decompression::make_stream() const
   {
   return new LZMA_Decompression_Stream;
   }

}