summaryrefslogtreecommitdiff
path: root/libs/tdlib/td/tdutils/td/utils/Gzip.h
blob: dd5fba5bf57e929957f137c6ad80d7eaaf9ce4ce (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
95
96
97
98
99
100
101
102
103
104
//
// Copyright Aliaksei Levin (levlam@telegram.org), Arseny Smirnov (arseny30@gmail.com) 2014-2018
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#pragma once

#include "td/utils/common.h"

#if TD_HAVE_ZLIB
#include "td/utils/buffer.h"
#include "td/utils/Slice.h"
#include "td/utils/Status.h"

namespace td {

class Gzip {
 public:
  Gzip();
  Gzip(const Gzip &) = delete;
  Gzip &operator=(const Gzip &) = delete;
  Gzip(Gzip &&other);
  Gzip &operator=(Gzip &&other);
  ~Gzip();

  enum Mode { Empty, Encode, Decode };
  Status init(Mode mode) TD_WARN_UNUSED_RESULT {
    if (mode == Encode) {
      return init_encode();
    } else if (mode == Decode) {
      return init_decode();
    }
    clear();
    return Status::OK();
  }

  Status init_encode() TD_WARN_UNUSED_RESULT;

  Status init_decode() TD_WARN_UNUSED_RESULT;

  void set_input(Slice input);

  void set_output(MutableSlice output);

  void close_input() {
    close_input_flag_ = true;
  }

  bool need_input() const {
    return left_input() == 0;
  }

  bool need_output() const {
    return left_output() == 0;
  }

  size_t left_input() const;

  size_t left_output() const;

  size_t used_input() const {
    return input_size_ - left_input();
  }

  size_t used_output() const {
    return output_size_ - left_output();
  }

  size_t flush_input() {
    auto res = used_input();
    input_size_ = left_input();
    return res;
  }

  size_t flush_output() {
    auto res = used_output();
    output_size_ = left_output();
    return res;
  }

  enum State { Running, Done };
  Result<State> run() TD_WARN_UNUSED_RESULT;

 private:
  class Impl;
  unique_ptr<Impl> impl_;

  size_t input_size_ = 0;
  size_t output_size_ = 0;
  bool close_input_flag_ = false;
  Mode mode_ = Empty;

  void init_common();
  void clear();
};

BufferSlice gzdecode(Slice s);

BufferSlice gzencode(Slice s, double k = 0.9);

}  // namespace td

#endif