protobuf_http_stream_parser.h 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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 REMOTING_BASE_PROTOBUF_HTTP_STREAM_PARSER_H_
  5. #define REMOTING_BASE_PROTOBUF_HTTP_STREAM_PARSER_H_
  6. #include "base/callback.h"
  7. #include "base/memory/scoped_refptr.h"
  8. #include "base/memory/weak_ptr.h"
  9. #include "base/strings/string_piece_forward.h"
  10. namespace google {
  11. namespace protobuf {
  12. namespace io {
  13. class CodedInputStream;
  14. } // namespace io
  15. } // namespace protobuf
  16. } // namespace google
  17. namespace net {
  18. class GrowableIOBuffer;
  19. } // namespace net
  20. namespace remoting {
  21. class ProtobufHttpStatus;
  22. // Class to parse incoming stream data wrapped with a StreamBody protobuf
  23. // message.
  24. class ProtobufHttpStreamParser final {
  25. public:
  26. using MessageCallback = base::RepeatingCallback<void(const std::string&)>;
  27. using StreamClosedCallback =
  28. base::OnceCallback<void(const ProtobufHttpStatus&)>;
  29. ProtobufHttpStreamParser(const MessageCallback& message_callback,
  30. StreamClosedCallback stream_closed_callback);
  31. ~ProtobufHttpStreamParser();
  32. ProtobufHttpStreamParser(const ProtobufHttpStreamParser&) = delete;
  33. ProtobufHttpStreamParser& operator=(const ProtobufHttpStreamParser&) = delete;
  34. // Appends the stream data (which should be the partial or full serialized
  35. // StreamBody) and runs callbacks if there is something decodable.
  36. void Append(base::StringPiece data);
  37. // Indicates whether the parser has pending data that needs more input to
  38. // complete a StreamBody message.
  39. bool HasPendingData() const;
  40. private:
  41. void ParseStreamIfAvailable();
  42. bool ParseOneField(google::protobuf::io::CodedInputStream* input_stream);
  43. MessageCallback message_callback_;
  44. StreamClosedCallback stream_closed_callback_;
  45. scoped_refptr<net::GrowableIOBuffer> read_buffer_;
  46. base::WeakPtrFactory<ProtobufHttpStreamParser> weak_factory_{this};
  47. };
  48. } // namespace remoting
  49. #endif // REMOTING_BASE_PROTOBUF_HTTP_STREAM_PARSER_H_