Revert of Revert of Roll android_tools f6e2370:2a860d8 (patchset #1 id:1 of https...
[chromium-blink-merge.git] / remoting / protocol / protobuf_message_parser.h
blob68840b1fc6d3722a9ca4a556a39b5c89262353a6
1 // Copyright 2014 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.
5 #ifndef REMOTING_PROTOCOL_PROTOBUF_MESSAGE_PARSER_H_
6 #define REMOTING_PROTOCOL_PROTOBUF_MESSAGE_PARSER_H_
8 #include "base/bind.h"
9 #include "base/callback.h"
10 #include "base/memory/scoped_ptr.h"
11 #include "remoting/base/compound_buffer.h"
12 #include "remoting/protocol/message_reader.h"
14 namespace remoting {
15 namespace protocol {
17 // Version of MessageReader for protocol buffer messages, that parses
18 // each incoming message.
19 template <class T>
20 class ProtobufMessageParser {
21 public:
22 // The callback that is called when a new message is received. |done_task|
23 // must be called by the callback when it's done processing the |message|.
24 typedef typename base::Callback<void(scoped_ptr<T> message,
25 const base::Closure& done_task)>
26 MessageReceivedCallback;
28 // |message_reader| must outlive ProtobufMessageParser.
29 ProtobufMessageParser(const MessageReceivedCallback& callback,
30 MessageReader* message_reader)
31 : message_reader_(message_reader),
32 message_received_callback_(callback) {
33 message_reader->SetMessageReceivedCallback(base::Bind(
34 &ProtobufMessageParser<T>::OnNewData, base::Unretained(this)));
36 ~ProtobufMessageParser() {
37 message_reader_->SetMessageReceivedCallback(
38 MessageReader::MessageReceivedCallback());
41 private:
42 void OnNewData(scoped_ptr<CompoundBuffer> buffer,
43 const base::Closure& done_task) {
44 scoped_ptr<T> message(new T());
45 CompoundBufferInputStream stream(buffer.get());
46 bool ret = message->ParseFromZeroCopyStream(&stream);
47 if (!ret) {
48 LOG(WARNING) << "Received message that is not a valid protocol buffer.";
49 } else {
50 DCHECK_EQ(stream.position(), buffer->total_bytes());
51 message_received_callback_.Run(message.Pass(), done_task);
55 MessageReader* message_reader_;
56 MessageReceivedCallback message_received_callback_;
59 } // namespace protocol
60 } // namespace remoting
62 #endif // REMOTING_PROTOCOL_PROTOBUF_MESSAGE_PARSER_H_