From 184b0ee2c950355f9ba70ca2e0aa5896872c1031 Mon Sep 17 00:00:00 2001 From: Mosolov Sergey Date: Thu, 27 Jan 2022 21:03:50 +0400 Subject: [PATCH] Preallocate vector with exact size when possible https://doc.rust-lang.org/std/vec/struct.Vec.html#capacity-and-reallocation --- src/codec/mod.rs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/codec/mod.rs b/src/codec/mod.rs index c75afb5f..23315622 100644 --- a/src/codec/mod.rs +++ b/src/codec/mod.rs @@ -179,7 +179,7 @@ impl TryFrom for Request { if bytes.len() < (6 + byte_count as usize) { return Err(Error::new(ErrorKind::InvalidData, "Invalid byte count")); } - let mut data = vec![]; + let mut data = Vec::with_capacity(quantity as usize); for _ in 0..quantity { data.push(rdr.read_u16::()?); } @@ -191,10 +191,10 @@ impl TryFrom for Request { let write_address = rdr.read_u16::()?; let write_quantity = rdr.read_u16::()?; let write_count = rdr.read_u8()? as usize; - let mut data = vec![]; if bytes.len() < (10 + write_count as usize) { return Err(Error::new(ErrorKind::InvalidData, "Invalid byte count")); } + let mut data = Vec::with_capacity(write_quantity as usize); for _ in 0..write_quantity { data.push(rdr.read_u16::()?); } @@ -253,7 +253,7 @@ impl TryFrom for Response { 0x04 => { let byte_count = rdr.read_u8()?; let quantity = byte_count / 2; - let mut data = vec![]; + let mut data = Vec::with_capacity(quantity as usize); for _ in 0..quantity { data.push(rdr.read_u16::()?); } @@ -262,7 +262,7 @@ impl TryFrom for Response { 0x03 => { let byte_count = rdr.read_u8()?; let quantity = byte_count / 2; - let mut data = vec![]; + let mut data = Vec::with_capacity(quantity as usize); for _ in 0..quantity { data.push(rdr.read_u16::()?); } @@ -276,7 +276,7 @@ impl TryFrom for Response { 0x17 => { let byte_count = rdr.read_u8()?; let quantity = byte_count / 2; - let mut data = vec![]; + let mut data = Vec::with_capacity(quantity as usize); for _ in 0..quantity { data.push(rdr.read_u16::()?); }