1 // Copyright 2020 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_SOCKET_READ_BUFFERING_STREAM_SOCKET_H_ 6 #define NET_SOCKET_READ_BUFFERING_STREAM_SOCKET_H_ 7 8 #include <memory> 9 10 #include "net/base/completion_once_callback.h" 11 #include "net/socket/socket_test_util.h" 12 13 namespace net { 14 15 class GrowableIOBuffer; 16 17 // Wraps an existing StreamSocket that will ensure a certain amount of data is 18 // internally buffered before satisfying a Read() request, regardless of how 19 // quickly the OS receives them from the peer. 20 class ReadBufferingStreamSocket : public WrappedStreamSocket { 21 public: 22 explicit ReadBufferingStreamSocket(std::unique_ptr<StreamSocket> transport); 23 ~ReadBufferingStreamSocket() override; 24 25 // Socket implementation: 26 int Read(IOBuffer* buf, 27 int buf_len, 28 CompletionOnceCallback callback) override; 29 30 int ReadIfReady(IOBuffer* buf, 31 int buf_len, 32 CompletionOnceCallback callback) override; 33 34 // Causes the next Read() or ReadIfReady() call to not return data until it 35 // has internally been buffered up to |size| bytes. Once the buffer has been 36 // consumed, the buffering is disabled. If the next read requests fewer than 37 // |size| bytes, it will not return until 0 38 void BufferNextRead(int size); 39 40 private: 41 enum State { 42 STATE_NONE, 43 STATE_READ, 44 STATE_READ_COMPLETE, 45 }; 46 47 int DoLoop(int result); 48 int DoRead(); 49 int DoReadComplete(int result); 50 void OnReadCompleted(int result); 51 int CopyToCaller(IOBuffer* buf, int buf_len); 52 53 State state_ = STATE_NONE; 54 55 // The buffer that must be filled to capacity before data is released out of 56 // Read() or ReadIfReady(). If buffering is disabled, this is zero. 57 scoped_refptr<GrowableIOBuffer> read_buffer_; 58 // True if |read_buffer_| has been filled, in which case 59 // |read_buffer_->offset()| is how much data has been released to the caller. 60 // If false, the offset is how much data has been written. 61 bool buffer_full_ = false; 62 63 scoped_refptr<IOBuffer> user_read_buf_; 64 int user_read_buf_len_; 65 CompletionOnceCallback user_read_callback_; 66 }; 67 68 } // namespace net 69 70 #endif // NET_SOCKET_READ_BUFFERING_STREAM_SOCKET_H_ 71