1 // Copyright 2013 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 "mojo/public/cpp/bindings/lib/message_builder.h"
6
7 #include "mojo/public/cpp/bindings/lib/array_internal.h"
8 #include "mojo/public/cpp/bindings/lib/bindings_internal.h"
9 #include "mojo/public/cpp/bindings/lib/buffer.h"
10 #include "mojo/public/cpp/bindings/lib/message_internal.h"
11
12 namespace mojo {
13 namespace internal {
14
15 template <typename Header>
Allocate(Buffer * buf,Header ** header)16 void Allocate(Buffer* buf, Header** header) {
17 *header = static_cast<Header*>(buf->Allocate(sizeof(Header)));
18 (*header)->num_bytes = sizeof(Header);
19 }
20
MessageBuilder(uint32_t name,uint32_t flags,size_t payload_size,size_t payload_interface_id_count)21 MessageBuilder::MessageBuilder(uint32_t name,
22 uint32_t flags,
23 size_t payload_size,
24 size_t payload_interface_id_count) {
25 if (payload_interface_id_count > 0) {
26 // Version 2
27 InitializeMessage(
28 sizeof(MessageHeaderV2) + Align(payload_size) +
29 ArrayDataTraits<uint32_t>::GetStorageSize(
30 static_cast<uint32_t>(payload_interface_id_count)));
31
32 MessageHeaderV2* header;
33 Allocate(message_.buffer(), &header);
34 header->version = 2;
35 header->name = name;
36 header->flags = flags;
37 // The payload immediately follows the header.
38 header->payload.Set(header + 1);
39 } else if (flags &
40 (Message::kFlagExpectsResponse | Message::kFlagIsResponse)) {
41 // Version 1
42 InitializeMessage(sizeof(MessageHeaderV1) + payload_size);
43
44 MessageHeaderV1* header;
45 Allocate(message_.buffer(), &header);
46 header->version = 1;
47 header->name = name;
48 header->flags = flags;
49 } else {
50 InitializeMessage(sizeof(MessageHeader) + payload_size);
51
52 MessageHeader* header;
53 Allocate(message_.buffer(), &header);
54 header->version = 0;
55 header->name = name;
56 header->flags = flags;
57 }
58 }
59
~MessageBuilder()60 MessageBuilder::~MessageBuilder() {
61 }
62
InitializeMessage(size_t size)63 void MessageBuilder::InitializeMessage(size_t size) {
64 message_.Initialize(static_cast<uint32_t>(Align(size)),
65 true /* zero_initialized */);
66 }
67
68 } // namespace internal
69 } // namespace mojo
70