Message Builders

Sometimes, actors need to assemble messages incrementally and cannot provide all values at once for make_message. With message builders, CAF offers a convenient tool to collect some values for converting them to a message later.

The general work flow for message builders is calling append until all values were added and then calling move_to_message for turning the collection of values to an actual message as shown below.

Source Code

message_builder mb;
for (int32_t i = 1; i <= 8; i *= 2)
  mb.append(i);
println("result: ", mb.move_to_message());

Output

result: message(1, 2, 4, 8)

Calling move_to_message leaves the builder object in a moved-from state and we may only destroy it after this point. To leave the builder in a state where we can still add more values to it, we can call to_message instead as shown below.

Source Code

std::string hw = "hello world";
message_builder mb;
mb.append(hw.substr(0, 5));
println("result 1: ", mb.to_message());
mb.append(hw.substr(6, 5));
println("result 2: ", mb.move_to_message());

Output

result 1: message("hello")
result 2: message("hello", "world")

Using to_message means that CAF needs to copy each value into the new message instead of moving them. The builder can also copy values from another CAF message:

Source Code

auto msg = make_message("hello", "world", "goodbye");
auto vec = std::vector<int32_t>{1, 2, 3};
message_builder mb;
mb.append_from(msg, 0, 2) // starting at index 0, copying two elements
  .append(vec.begin(), vec.end());
println("result: ", mb.move_to_message());

Output

result: message("hello", "world", 1, 2, 3)

While message builders offer great flexibility, they do come with some performance overhead. Mostly due to the extra heap allocations. So we still recommend sticking to make_message whenever feasible.

Previous
Previous

Typed Message Views

Next
Next

Copy-on-write Tuples