Skip to content

Commit

Permalink
use internal buffer's Buf impl for codec buffers (#1695)
Browse files Browse the repository at this point in the history
* use internal buffer's Buf impl for codec buffers

The internal buffers within the codec EncodeBuf/DecodeBuf
implementations contain slightly-more-optimized implementations of Buf,
which we can take advantage of.

* run cargo fmt
  • Loading branch information
ClementTsang committed May 24, 2024
1 parent 9e9bc59 commit a0159d3
Showing 1 changed file with 26 additions and 1 deletion.
27 changes: 26 additions & 1 deletion tonic/src/codec/buffer.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use bytes::buf::UninitSlice;
use bytes::{Buf, BufMut, BytesMut};
use bytes::{Buf, BufMut, Bytes, BytesMut};

/// A specialized buffer to decode gRPC messages from.
#[derive(Debug)]
Expand Down Expand Up @@ -43,6 +43,13 @@ impl Buf for DecodeBuf<'_> {
self.buf.advance(cnt);
self.len -= cnt;
}

#[inline]
fn copy_to_bytes(&mut self, len: usize) -> Bytes {
assert!(len <= self.len);
self.len -= len;
self.buf.copy_to_bytes(len)
}
}

impl<'a> EncodeBuf<'a> {
Expand Down Expand Up @@ -78,6 +85,24 @@ unsafe impl BufMut for EncodeBuf<'_> {
fn chunk_mut(&mut self) -> &mut UninitSlice {
self.buf.chunk_mut()
}

#[inline]
fn put<T: Buf>(&mut self, src: T)
where
Self: Sized,
{
self.buf.put(src)
}

#[inline]
fn put_slice(&mut self, src: &[u8]) {
self.buf.put_slice(src)
}

#[inline]
fn put_bytes(&mut self, val: u8, cnt: usize) {
self.buf.put_bytes(val, cnt);
}
}

#[cfg(test)]
Expand Down

0 comments on commit a0159d3

Please sign in to comment.