This source file includes following definitions.
- WriteUntilComplete
- fail_
- WriteMessage
#include "remoting/host/native_messaging/native_messaging_writer.h"
#include <string>
#include "base/basictypes.h"
#include "base/json/json_writer.h"
namespace {
typedef uint32 MessageLengthType;
const int kMessageHeaderSize = sizeof(MessageLengthType);
const size_t kMaximumMessageSize = 1024 * 1024;
int WriteUntilComplete(net::FileStream* out,
const char* buffer, int buffer_length) {
int written = 0;
while (written < buffer_length) {
int result = out->WriteSync(buffer + written, buffer_length - written);
if (result <= 0) {
return result;
}
DCHECK_LE(result, buffer_length - written);
written += result;
}
return written;
}
}
namespace remoting {
NativeMessagingWriter::NativeMessagingWriter(base::PlatformFile handle)
: write_stream_(handle, base::PLATFORM_FILE_WRITE, NULL),
fail_(false) {
}
NativeMessagingWriter::~NativeMessagingWriter() {
}
bool NativeMessagingWriter::WriteMessage(const base::Value& message) {
if (fail_) {
LOG(ERROR) << "Stream marked as corrupt.";
return false;
}
std::string message_json;
base::JSONWriter::Write(&message, &message_json);
CHECK_LE(message_json.length(), kMaximumMessageSize);
MessageLengthType message_length =
static_cast<MessageLengthType>(message_json.length());
int result = WriteUntilComplete(
&write_stream_, reinterpret_cast<char*>(&message_length),
kMessageHeaderSize);
if (result != kMessageHeaderSize) {
LOG(ERROR) << "Failed to send message header, write returned " << result;
fail_ = true;
return false;
}
int message_length_as_int = message_length;
CHECK(!message_json.empty());
result = WriteUntilComplete(&write_stream_, message_json.data(),
message_length_as_int);
if (result != message_length_as_int) {
LOG(ERROR) << "Failed to send message body, write returned " << result;
fail_ = true;
return false;
}
return true;
}
}