read_buffering_stream_socket.h 2.2 KB

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