Skip to content

Commit

Permalink
Specialize single-element writes to buffer
Browse files Browse the repository at this point in the history
copy_from_slice generally falls back to memcpy/memmove, which is much more expensive
than we need to write a single element in.

This saves 0.26% instructions on the diesel benchmark.
  • Loading branch information
Mark-Simulacrum committed May 29, 2021
1 parent 9f75dbf commit 299ac75
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 1 deletion.
15 changes: 15 additions & 0 deletions library/proc_macro/src/bridge/buffer.rs
Expand Up @@ -91,6 +91,21 @@ impl<T: Copy> Buffer<T> {
let b = self.take();
*self = (b.extend_from_slice)(b, Slice::from(xs));
}

pub(super) fn push(&mut self, v: T) {
// Fast path to avoid going through an FFI call.
if let Some(final_len) = self.len.checked_add(1) {
if final_len <= self.capacity {
unsafe {
*self.data.add(self.len) = v;
}
self.len = final_len;
return;
}
}
let b = self.take();
*self = (b.extend_from_slice)(b, Slice::from(std::slice::from_ref(&v)));
}
}

impl Write for Buffer<u8> {
Expand Down
2 changes: 1 addition & 1 deletion library/proc_macro/src/bridge/rpc.rs
Expand Up @@ -114,7 +114,7 @@ impl<S> DecodeMut<'_, '_, S> for () {

impl<S> Encode<S> for u8 {
fn encode(self, w: &mut Writer, _: &mut S) {
w.write_all(&[self]).unwrap();
w.push(self);
}
}

Expand Down

0 comments on commit 299ac75

Please sign in to comment.