summaryrefslogtreecommitdiff
path: root/chromium/net/websockets/websocket_deflater.h
blob: cf5b43b3b23dc1fe0a195aa687fe0fd5db1fe3f6 (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
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef NET_WEBSOCKETS_WEBSOCKET_DEFLATER_H_
#define NET_WEBSOCKETS_WEBSOCKET_DEFLATER_H_

#include <stddef.h>

#include <deque>
#include <memory>
#include <vector>

#include "base/macros.h"
#include "base/memory/ref_counted.h"
#include "net/base/net_export.h"

extern "C" struct z_stream_s;

namespace net {

class IOBufferWithSize;

class NET_EXPORT_PRIVATE WebSocketDeflater {
 public:
  // Do not reorder or remove entries of this enum. The values of them are used
  // in UMA.
  enum ContextTakeOverMode {
    DO_NOT_TAKE_OVER_CONTEXT,
    TAKE_OVER_CONTEXT,
    NUM_CONTEXT_TAKEOVER_MODE_TYPES,
  };

  explicit WebSocketDeflater(ContextTakeOverMode mode);
  ~WebSocketDeflater();

  // Returns true if there is no error and false otherwise.
  // This function must be called exactly once before calling any of
  // following methods.
  // |window_bits| must be between 8 and 15 (both inclusive).
  bool Initialize(int window_bits);

  // Adds bytes to |stream_|.
  // Returns true if there is no error and false otherwise.
  bool AddBytes(const char* data, size_t size);

  // Flushes the current processing data.
  // Returns true if there is no error and false otherwise.
  bool Finish();

  // Pushes "\x00\x00\xff\xff" to the end of the buffer.
  void PushSyncMark();

  // Returns the current deflated output.
  // If the current output is larger than |size| bytes,
  // returns the first |size| bytes of the current output.
  // The returned bytes will be dropped from the current output and never be
  // returned thereafter.
  scoped_refptr<IOBufferWithSize> GetOutput(size_t size);

  // Returns the size of the current deflated output.
  size_t CurrentOutputSize() const { return buffer_.size(); }

 private:
  void ResetContext();
  int Deflate(int flush);

  std::unique_ptr<z_stream_s> stream_;
  ContextTakeOverMode mode_;
  std::deque<char> buffer_;
  std::vector<char> fixed_buffer_;
  // true if bytes were added after last Finish().
  bool are_bytes_added_;

  DISALLOW_COPY_AND_ASSIGN(WebSocketDeflater);
};

}  // namespace net

#endif  // NET_WEBSOCKETS_WEBSOCKET_DEFLATER_H_