1 // Copyright 2018 The Fuchsia 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 #ifndef LIB_FIDL_CPP_MESSAGE_BUILDER_H_
6 #define LIB_FIDL_CPP_MESSAGE_BUILDER_H_
7 
8 #include <stdint.h>
9 
10 #include <lib/fidl/cpp/builder.h>
11 #include <lib/fidl/cpp/message_buffer.h>
12 #include <lib/fidl/cpp/message.h>
13 #include <zircon/fidl.h>
14 #include <zircon/types.h>
15 
16 namespace fidl {
17 
18 // A builder for FIDL messages that owns the memory for the message.
19 //
20 // A |MessageBuilder| is a |Builder| that uses the heap to back the memory for
21 // the message. If you wish to manage the memory yourself, you can use |Builder|
22 // and |Message| directly.
23 //
24 // Upon creation, the |MessageBuilder| creates a FIDL message header, which you
25 // can modify using |header()|.
26 class MessageBuilder : public Builder {
27 public:
28     // Creates a |MessageBuilder| for the given |type| that allocates buffers
29     // for message of the given capacities.
30     //
31     // The bytes buffer is initialied by adding a |fidl_message_header_t|
32     // header.
33     //
34     // The buffers are freed when the |MessageBuilder| is destructed.
35     explicit MessageBuilder(
36         const fidl_type_t* type,
37         uint32_t bytes_capacity = ZX_CHANNEL_MAX_MSG_BYTES,
38         uint32_t handles_capacity = ZX_CHANNEL_MAX_MSG_HANDLES);
39 
40     // The memory that backs the message is freed by this destructor.
41     ~MessageBuilder();
42 
43     // The type of the message payload this object is building.
type()44     const fidl_type_t* type() const { return type_; }
45 
46     // The header for the message.
47     //
48     // The message header is allocated by the |MessageBuilder| itself.
header()49     fidl_message_header_t* header() const {
50         return reinterpret_cast<fidl_message_header_t*>(buffer());
51     }
52 
53     // Encodes a message of the given |type|.
54     //
55     // The memory that backs the message returned by this function is owned by
56     // the |MessageBuilder|, which means the |MessageBuilder| must remain alive
57     // as long as the |Message| object is in use.
58     //
59     // The |message| parameter might be modified even if this method returns an
60     // error.
61     zx_status_t Encode(Message* message_out, const char** error_msg_out);
62 
63     // Resets all the data in the |MessageBuffer|.
64     //
65     // The underlying buffer is retained and reused. The next object will be
66     // allocated at the start of the buffer.
67     void Reset();
68 
69 private:
70     const fidl_type_t* type_;
71     MessageBuffer buffer_;
72 };
73 
74 } // namespace fidl
75 
76 #endif // LIB_FIDL_CPP_MESSAGE_BUILDER_H_
77