Botan 2.1.0 Crypto and TLS for C++11

- Main Page
- Namespaces
- Classes
- Files

- File List
- File Members

lzma.cpp
Go to the documentation of this file.
1 /*
2 * Lzma Compressor
3 * (C) 2001 Peter J Jones
4 * 2001-2007,2014 Jack Lloyd
5 * 2006 Matt Johnston
6 * 2012 Vojtech Kral
7 *
8 * Botan is released under the Simplified BSD License (see license.txt)
9 */
10
11 #include <botan/lzma.h>
12 #include <botan/internal/compress_utils.h>
13 #include <botan/exceptn.h>
14 #include <lzma.h>
15
16 namespace Botan {
17
18 namespace {
19
20 class LZMA_Stream : public Zlib_Style_Stream<lzma_stream, uint8_t>
21 {
22 public:
23 LZMA_Stream()
24 {
25 auto a = new ::lzma_allocator;
26 a->opaque = alloc();
27 a->alloc = Compression_Alloc_Info::malloc<size_t>;
28 a->free = Compression_Alloc_Info::free;
29 streamp()->allocator = a;
30 }
31
32 ~LZMA_Stream()
33 {
34 ::lzma_end(streamp());
35 delete streamp()->allocator;
36 }
37
38 bool run(uint32_t flags) override
39 {
40 lzma_ret rc = ::lzma_code(streamp(), static_cast<lzma_action>(flags));
41
42 if(rc == LZMA_MEM_ERROR)
43 throw Exception("lzma memory allocation failed");
44 else if (rc != LZMA_OK && rc != LZMA_STREAM_END)
45 throw Exception("Lzma error");
46
47 return (rc == LZMA_STREAM_END);
48 }
49
50 uint32_t run_flag() const override { return LZMA_RUN; }
51 uint32_t flush_flag() const override { return LZMA_FULL_FLUSH; }
52 uint32_t finish_flag() const override { return LZMA_FINISH; }
53 };
54
55 class LZMA_Compression_Stream : public LZMA_Stream
56 {
57 public:
58 explicit LZMA_Compression_Stream(size_t level)
59 {
60 if(level == 0)
61 level = 6; // default
62 else if(level > 9)
63 level = 9; // clamp to maximum allowed value
64
65 lzma_ret rc = ::lzma_easy_encoder(streamp(), level, LZMA_CHECK_CRC64);
66
67 if(rc == LZMA_MEM_ERROR)
68 throw Exception("lzma memory allocation failed");
69 else if(rc != LZMA_OK)
70 throw Exception("lzma compress initialization failed");
71 }
72 };
73
74 class LZMA_Decompression_Stream : public LZMA_Stream
75 {
76 public:
77 LZMA_Decompression_Stream()
78 {
79 lzma_ret rc = ::lzma_stream_decoder(streamp(), UINT64_MAX,
80 LZMA_TELL_UNSUPPORTED_CHECK);
81
82 if(rc == LZMA_MEM_ERROR)
83 throw Exception("lzma memory allocation failed");
84 else if(rc != LZMA_OK)
85 throw Exception("Bad setting in lzma_stream_decoder");
86 }
87 };
88
89 }
90
91 Compression_Stream* LZMA_Compression::make_stream(size_t level) const
92 {
93 return new LZMA_Compression_Stream(level);
94 }
95
96 Compression_Stream* LZMA_Decompression::make_stream() const
97 {
98 return new LZMA_Decompression_Stream;
99 }
100
101 }
Botan::Compression_Alloc_Info::free
static void free(void *self, void *ptr)
Definition: compress_utils.h:29
Botan::PKCS11::flags
Flags flags(Flag flags)
Definition: p11.h:858
lzma.h
Botan
Definition: alg_id.cpp:13