Skip to content

Serialize into a buffer

Write a value into a std::byte buffer, know how many bytes it took, and compose several values back to back.

Source: example/howto/serialize.cpp, CMake target howto_serialize.

A buffer of the right size

rbe::wire_size_of<T>() is a constant expression, so a fixed buffer can be sized exactly.

// wire_size_of<T>() is a constant expression: size the buffer exactly
std::array<std::byte, rbe::wire_size_of<Order>()> buffer {};

std::size_t written = rbe::serialize(buffer, Order {.order_id = 1, .quantity = 100, .price = 2500});

Any contiguous range of bytes

The call takes a std::span<std::byte>; std::vector, std::array and C arrays convert to it.

// Any contiguous range of std::byte converts to the std::span<std::byte> the call takes
std::vector<std::byte> buffer(rbe::wire_size_of<Header>() + rbe::wire_size_of<Order>());

std::size_t written = rbe::serialize(buffer, Header {.length = 19, .type = 1});

Check the buffer first

rbe::serialize assumes the buffer is big enough and has undefined behavior otherwise. rbe::try_serialize checks and reports instead.

std::array<std::byte, 8> too_small {};

// serialize() assumes the buffer is big enough; try_serialize() checks and reports
std::optional<std::size_t> written = rbe::try_serialize(too_small, Order {});
if (not written) {
  // the buffer holds 8 bytes and Order needs 16: nothing was written
}

Several values back to back

Each call writes at the start of the span it is given and returns how far it got. Advance the span by that much to write the next part.

// A header followed by its payload: write each part where the previous one ended
std::vector<std::byte> datagram(rbe::wire_size_of<Header>() + rbe::wire_size_of<Order>());
std::span<std::byte>   out = datagram;

out = out.subspan(rbe::serialize(out, Header {.length = static_cast<std::uint16_t>(datagram.size()), .type = 1}));
out = out.subspan(rbe::serialize(out, Order {.order_id = 1, .quantity = 100, .price = 2500}));

This is how a frame is written today: header, then payload. See the frames reference for the serializer that is planned.

See also: Serialization reference.