Skip to content

Remove unnecessary allocations in message serialization #1858

@joshua-spacetime

Description

@joshua-spacetime

I.e. address the following TODO left by @Centril.

/// Serialize `msg` into a [`DataMessage`] containing a [`ws::ServerMessage`].
///
/// If `protocol` is [`Protocol::Binary`],
/// the message will be conditionally compressed by this method according to `compression`.
pub fn serialize(
msg: impl ToProtocol<Encoded = SwitchedServerMessage>,
protocol: Protocol,
compression: Compression,
) -> DataMessage {
// TODO(centril, perf): here we are allocating buffers only to throw them away eventually.
// Consider pooling these allocations so that we reuse them.
match msg.to_protocol(protocol) {
FormatSwitch::Json(msg) => serde_json::to_string(&SerializeWrapper::new(msg)).unwrap().into(),
FormatSwitch::Bsatn(msg) => {
// First write the tag so that we avoid shifting the entire message at the end.
let mut msg_bytes = vec![SERVER_MSG_COMPRESSION_TAG_NONE];
bsatn::to_writer(&mut msg_bytes, &msg).unwrap();
// Conditionally compress the message.
let srv_msg = &msg_bytes[1..];
let msg_bytes = match ws::decide_compression(srv_msg.len(), compression) {
Compression::None => msg_bytes,
Compression::Brotli => {
let mut out = vec![SERVER_MSG_COMPRESSION_TAG_BROTLI];
ws::brotli_compress(srv_msg, &mut out);
out
}
Compression::Gzip => {
let mut out = vec![SERVER_MSG_COMPRESSION_TAG_GZIP];
ws::gzip_compress(srv_msg, &mut out);
out
}
};
msg_bytes.into()
}
}
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions