Botan  2.9.0
Crypto and TLS for C++11
bzip2.cpp
Go to the documentation of this file.
1 /*
2 * Bzip2 Compressor
3 * (C) 2001 Peter J Jones
4 * 2001-2007,2014 Jack Lloyd
5 * 2006 Matt Johnston
6 *
7 * Botan is released under the Simplified BSD License (see license.txt)
8 */
9 
10 #include <botan/bzip2.h>
11 #include <botan/exceptn.h>
12 #include <botan/internal/compress_utils.h>
13 
14 #define BZ_NO_STDIO
15 #include <bzlib.h>
16 
17 namespace Botan {
18 
19 namespace {
20 
21 class Bzip2_Stream : public Zlib_Style_Stream<bz_stream, char>
22  {
23  public:
24  Bzip2_Stream()
25  {
26  streamp()->opaque = alloc();
27  streamp()->bzalloc = Compression_Alloc_Info::malloc<int>;
28  streamp()->bzfree = Compression_Alloc_Info::free;
29  }
30 
31  uint32_t run_flag() const override { return BZ_RUN; }
32  uint32_t flush_flag() const override { return BZ_FLUSH; }
33  uint32_t finish_flag() const override { return BZ_FINISH; }
34  };
35 
36 class Bzip2_Compression_Stream final : public Bzip2_Stream
37  {
38  public:
39  explicit Bzip2_Compression_Stream(size_t block_size)
40  {
41  /*
42  * Defaults to 900k blocks as the computation cost of
43  * compression is not overly affected by the size, though
44  * more memory is required.
45  */
46  if(block_size == 0 || block_size >= 9)
47  block_size = 9;
48 
49  int rc = BZ2_bzCompressInit(streamp(), block_size, 0, 0);
50 
51  if(rc != BZ_OK)
52  throw Compression_Error("BZ2_bzCompressInit", ErrorType::Bzip2Error, rc);
53  }
54 
55  ~Bzip2_Compression_Stream()
56  {
57  BZ2_bzCompressEnd(streamp());
58  }
59 
60  bool run(uint32_t flags) override
61  {
62  int rc = BZ2_bzCompress(streamp(), flags);
63 
64  if(rc < 0)
65  throw Compression_Error("BZ2_bzCompress", ErrorType::Bzip2Error, rc);
66 
67  return (rc == BZ_STREAM_END);
68  }
69  };
70 
71 class Bzip2_Decompression_Stream final : public Bzip2_Stream
72  {
73  public:
74  Bzip2_Decompression_Stream()
75  {
76  int rc = BZ2_bzDecompressInit(streamp(), 0, 0);
77 
78  if(rc != BZ_OK)
79  throw Compression_Error("BZ2_bzDecompressInit", ErrorType::Bzip2Error, rc);
80  }
81 
82  ~Bzip2_Decompression_Stream()
83  {
84  BZ2_bzDecompressEnd(streamp());
85  }
86 
87  bool run(uint32_t) override
88  {
89  int rc = BZ2_bzDecompress(streamp());
90 
91  if(rc != BZ_OK && rc != BZ_STREAM_END)
92  throw Compression_Error("BZ2_bzDecompress", ErrorType::Bzip2Error, rc);
93 
94  return (rc == BZ_STREAM_END);
95  }
96  };
97 
98 }
99 
100 Compression_Stream* Bzip2_Compression::make_stream(size_t comp_level) const
101  {
102  return new Bzip2_Compression_Stream(comp_level);
103  }
104 
105 Compression_Stream* Bzip2_Decompression::make_stream() const
106  {
107  return new Bzip2_Decompression_Stream;
108  }
109 
110 }
static void free(void *self, void *ptr)
int(* final)(unsigned char *, CTX *)
Flags flags(Flag flags)
Definition: p11.h:858
Definition: alg_id.cpp:13