zlib_source.h
1 // Copyright 2013, Beeri 15. All rights reserved.
2 // Author: Roman Gershman (romange@gmail.com)
3 //
4 #pragma once
5 
6 
7 #include <zlib.h>
8 
9 #include "base/macros.h"
10 #include "util/sinksource.h"
11 
12 namespace util {
13 
14 class ZlibSource : public Source {
15  public:
16  // Format key for constructor
17  enum Format {
18  // zlib will autodetect gzip header or deflate stream
19  AUTO = 0,
20 
21  // GZIP streams have some extra header data for file attributes.
22  GZIP = 1,
23 
24  // Simpler zlib stream format.
25  ZLIB = 2,
26  };
27 
28 
29  // buffer_size and format may be -1 for default of 64kB and GZIP format.
30  explicit ZlibSource(Source* sub_source, Format format = AUTO);
31  ~ZlibSource();
32 
33  static bool IsZlibSource(Source* source);
34 
35  private:
36 
37  StatusObject<size_t> ReadInternal(const strings::MutableByteRange& range) override;
38 
39  Source* sub_stream_;
40 
41  Format format_;
42  z_stream zcontext_;
43  std::unique_ptr<uint8_t[]> buf_;
44 
45  int Inflate();
46 
47  bool RefillInternal();
48 
49  DISALLOW_EVIL_CONSTRUCTORS(ZlibSource);
50 };
51 
52 class ZlibSink : public Sink {
53  public:
54  // Takes ownership over sub-sink.
55  explicit ZlibSink(Sink* sub, unsigned level = 0, size_t buf_size = 1 << 16);
56  ~ZlibSink() final;
57 
58  Status Append(const strings::ByteRange& slice) final;
59  Status Flush() final;
60 
61  private:
62  std::unique_ptr<Sink> sub_;
63  std::unique_ptr<uint8_t[]> buf_;
64  size_t buf_size_;
65  z_stream zcontext_;
66 };
67 
68 } // namespace util
69