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. 4 5 #include "base/files/file_path.h" 6 #include "base/files/file_util.h" 7 #include "base/strings/string_util.h" 8 #include "base/strings/stringprintf.h" 9 #include "mojo/public/cpp/bindings/lib/message_builder.h" 10 #include "mojo/public/cpp/bindings/lib/message_internal.h" 11 #include "mojo/public/cpp/bindings/message.h" 12 13 // This file is used to generate various files corresponding to mojo 14 // messages. The various binding implementations can parse these to verify they 15 // correctly decode messages. 16 // 17 // The output consists of each byte of the message encoded in a hex string with 18 // a newline after it. 19 namespace mojo { 20 namespace { 21 22 std::string BinaryToHex(const base::StringPiece& piece) { 23 std::string result("// File generated by mojo_message_generator.\n");; 24 result.reserve(result.size() + (piece.size() * 5)); 25 for (size_t i = 0; i < piece.size(); ++i) 26 base::StringAppendF(&result, "0X%.2X\n", static_cast<int>(piece.data()[i])); 27 return result; 28 } 29 30 void WriteMessageToFile(const Message& message, const base::FilePath& path) { 31 const std::string hex_message(BinaryToHex( 32 base::StringPiece(reinterpret_cast<const char*>(message.data()), 33 message.data_num_bytes()))); 34 CHECK_EQ(static_cast<int>(hex_message.size()), 35 base::WriteFile(path, hex_message.data(), 36 static_cast<int>(hex_message.size()))); 37 } 38 39 // Generates a message of type MessageData. The message uses the name 21, 40 // with 4 bytes of payload: 0x9, 0x8, 0x7, 0x6. 41 void GenerateMessageDataMessage() { 42 internal::MessageBuilder builder(static_cast<uint32_t>(21), 43 static_cast<size_t>(4)); 44 char* data = static_cast<char*>(builder.buffer()->Allocate(4)); 45 DCHECK(data); 46 data[0] = 9; 47 data[1] = 8; 48 data[2] = 7; 49 data[3] = 6; 50 51 Message message; 52 builder.Finish(&message); 53 WriteMessageToFile(message, 54 base::FilePath(FILE_PATH_LITERAL("message_data"))); 55 } 56 57 } // namespace 58 } // namespace mojo 59 60 int main(int argc, char** argv) { 61 mojo::GenerateMessageDataMessage(); 62 return 0; 63 } 64