From 6af775745643491879a6b8bff0bd98ccb68d38f7 Mon Sep 17 00:00:00 2001 From: Paolo Barbolini Date: Fri, 19 Aug 2022 04:00:09 +0200 Subject: [PATCH] perf(fake-tcp) let the memory allocator zero initialize the `BytesMut` memory instead of resizing immediately after allocation Co-authored-by: Datong Sun --- fake-tcp/src/lib.rs | 3 +-- fake-tcp/src/packet.rs | 3 +-- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/fake-tcp/src/lib.rs b/fake-tcp/src/lib.rs index db5534b..a5c5863 100644 --- a/fake-tcp/src/lib.rs +++ b/fake-tcp/src/lib.rs @@ -436,8 +436,7 @@ impl Stack { let mut tuples: HashMap> = HashMap::new(); loop { - let mut buf = BytesMut::with_capacity(MAX_PACKET_LEN); - buf.resize(MAX_PACKET_LEN, 0); + let mut buf = BytesMut::zeroed(MAX_PACKET_LEN); tokio::select! { size = tun.recv(&mut buf) => { diff --git a/fake-tcp/src/packet.rs b/fake-tcp/src/packet.rs index e7dd422..c2abe56 100644 --- a/fake-tcp/src/packet.rs +++ b/fake-tcp/src/packet.rs @@ -47,8 +47,7 @@ pub fn build_tcp_packet( let tcp_header_len = TCP_HEADER_LEN + if wscale { 4 } else { 0 }; // nop + wscale let tcp_total_len = tcp_header_len + payload.map_or(0, |payload| payload.len()); let total_len = ip_header_len + tcp_total_len; - let mut buf = BytesMut::with_capacity(total_len); - buf.resize(total_len, 0); + let mut buf = BytesMut::zeroed(total_len); let mut ip_buf = buf.split_to(ip_header_len); let mut tcp_buf = buf.split_to(tcp_total_len);