Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove unnecessary allocations in message serialization #1858

Open
joshua-spacetime opened this issue Oct 15, 2024 · 0 comments
Open

Remove unnecessary allocations in message serialization #1858

joshua-spacetime opened this issue Oct 15, 2024 · 0 comments

Comments

@joshua-spacetime
Copy link
Collaborator

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()
}
}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant