• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2013 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifndef NET_WEBSOCKETS_WEBSOCKET_DEFLATER_H_
6 #define NET_WEBSOCKETS_WEBSOCKET_DEFLATER_H_
7 
8 #include <stddef.h>
9 
10 #include <memory>
11 #include <vector>
12 
13 #include "base/containers/circular_deque.h"
14 #include "base/memory/scoped_refptr.h"
15 #include "net/base/net_export.h"
16 
17 extern "C" struct z_stream_s;
18 
19 namespace net {
20 
21 class IOBufferWithSize;
22 
23 class NET_EXPORT_PRIVATE WebSocketDeflater {
24  public:
25   enum ContextTakeOverMode {
26     DO_NOT_TAKE_OVER_CONTEXT,
27     TAKE_OVER_CONTEXT,
28     NUM_CONTEXT_TAKEOVER_MODE_TYPES,
29   };
30 
31   explicit WebSocketDeflater(ContextTakeOverMode mode);
32 
33   WebSocketDeflater(const WebSocketDeflater&) = delete;
34   WebSocketDeflater& operator=(const WebSocketDeflater&) = delete;
35 
36   ~WebSocketDeflater();
37 
38   // Returns true if there is no error and false otherwise.
39   // This function must be called exactly once before calling any of
40   // following methods.
41   // |window_bits| must be between 8 and 15 (both inclusive).
42   bool Initialize(int window_bits);
43 
44   // Adds bytes to |stream_|.
45   // Returns true if there is no error and false otherwise.
46   bool AddBytes(const char* data, size_t size);
47 
48   // Flushes the current processing data.
49   // Returns true if there is no error and false otherwise.
50   bool Finish();
51 
52   // Pushes "\x00\x00\xff\xff" to the end of the buffer.
53   void PushSyncMark();
54 
55   // Returns the current deflated output.
56   // If the current output is larger than |size| bytes,
57   // returns the first |size| bytes of the current output.
58   // The returned bytes will be dropped from the current output and never be
59   // returned thereafter.
60   scoped_refptr<IOBufferWithSize> GetOutput(size_t size);
61 
62   // Returns the size of the current deflated output.
CurrentOutputSize()63   size_t CurrentOutputSize() const { return buffer_.size(); }
64 
65  private:
66   void ResetContext();
67   int Deflate(int flush);
68 
69   std::unique_ptr<z_stream_s> stream_;
70   ContextTakeOverMode mode_;
71   base::circular_deque<char> buffer_;
72   std::vector<char> fixed_buffer_;
73   // true if bytes were added after last Finish().
74   bool are_bytes_added_ = false;
75 };
76 
77 }  // namespace net
78 
79 #endif  // NET_WEBSOCKETS_WEBSOCKET_DEFLATER_H_
80