blob: ea35084bed4ab34c8b6ee3e2ebdc4b2cc85137c0 [file] [log] [blame]
David Ghandehari00be30f2017-04-27 21:30:48 -07001// Copyright 2017 Google Inc. All Rights Reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#ifndef COBALT_WEBSOCKET_BUFFERED_AMOUNT_TRACKER_H_
16#define COBALT_WEBSOCKET_BUFFERED_AMOUNT_TRACKER_H_
17
18#include <deque>
19
20namespace cobalt {
21namespace websocket {
22
23// This class is helper class for implementing the |bufferedAmount| attribute in
24// the Websockets API at:
25// https://www.w3.org/TR/websockets/#dom-websocket-bufferedamount.
26class BufferedAmountTracker {
27 public:
28 BufferedAmountTracker() : total_payload_inflight_(0) {}
29
30 // The payload in this context only applies to user messages.
31 // So even though a close message might have a "payload", for the purposes
32 // of the tracker, the |is_user_payload| will be false.
33 void Add(const bool is_user_payload, const std::size_t message_size) {
34 if (is_user_payload) {
35 total_payload_inflight_ += message_size;
36 }
37 entries_.push_back(Entry(is_user_payload, message_size));
38 }
39
40 // Returns the number of user payload bytes popped, these are bytes that were
41 // added with |is_user_payload| set to true.
42 std::size_t Pop(const std::size_t number_bytes_to_pop);
43
44 std::size_t GetTotalBytesInflight() const { return total_payload_inflight_; }
45
46 private:
47 struct Entry {
48 Entry(const bool is_user_payload, const std::size_t message_size)
49 : is_user_payload_(is_user_payload), message_size_(message_size) {}
50
51 bool is_user_payload_;
52 std::size_t message_size_;
53 };
54
55 typedef std::deque<Entry> Entries;
56
57 std::size_t total_payload_inflight_;
58 Entries entries_;
59};
60
61} // namespace websocket
62} // namespace cobalt
63
64#endif // COBALT_WEBSOCKET_BUFFERED_AMOUNT_TRACKER_H_