tonic icon indicating copy to clipboard operation
tonic copied to clipboard

Support Zero-Copy `Codec`s

Open fee1-dead opened this issue 4 years ago • 5 comments

Feature Request

Motivation

There are times we don't have owned buffers but only have references to them. However the current Codec trait has a 'static bound on the items being encoded and decoded.

Proposal

Remove the 'static bound on Codec::Encode and Codec::Decode. The bound on Codec::Encode would be pretty easy to remove I think, but Codec::Decode might not be as easy and there can be other gotchas. This does not need a semver major bump.

Alternatives

One could allocate and copy the borrowed content to an owned Vec, but this has a significant performance problem.

fee1-dead avatar Oct 07 '21 06:10 fee1-dead

While I agree that API is ideal I think its quite hard now with current futures infrastructure. Is there a reason you can't get to something like Arc<[u8]>?

LucioFranco avatar Oct 07 '21 20:10 LucioFranco

Arc<[u8]> still needs to have an owned buffer. That means you need to copy from &[u8] to Arc<[u8]>

fee1-dead avatar Oct 08 '21 06:10 fee1-dead

This does look like a fundamental issue with the current infrastructure. I do think this is possible, by adding lifetime parameters everywhere, starting from BoxBody and BoxService. This would be a breaking change, and a lot of crates will need to change as well, but there is benefit to this, it can improve performance by avoid copying to an owned buffer.

fee1-dead avatar Oct 09 '21 04:10 fee1-dead

So I think doing it by ref will be quite hard like you said. For now having an owned buffer is really the right way to go imo. Its likely that tonic won't support something like this and you may need to implement a custom client/server if you want true zero-copy.

LucioFranco avatar Oct 19 '21 15:10 LucioFranco

So currently I have opted to a solution where I do accept references but serialize them beforehand to one buffer (Vec<u8>). This at least avoids unnecessary cloning to owned structs and copying again to a serialization buffer.

fee1-dead avatar Oct 19 '21 16:10 fee1-dead