Skip to content

Commit

Permalink
chore: more Vec over BytesMut (#7084)
Browse files Browse the repository at this point in the history
  • Loading branch information
mattsse committed Mar 11, 2024
1 parent 72d6e95 commit 81291ff
Show file tree
Hide file tree
Showing 14 changed files with 33 additions and 40 deletions.
4 changes: 2 additions & 2 deletions crates/net/discv4/src/proto.rs
Original file line number Diff line number Diff line change
Expand Up @@ -813,7 +813,7 @@ mod tests {
assert_eq!(pubkey.to_vec(), expected_pubkey);
assert!(enr.0.verify());

let mut encoded = BytesMut::new();
let mut encoded = Vec::new();
enr.encode(&mut encoded);
assert_eq!(&encoded[..], &valid_record[..]);

Expand Down Expand Up @@ -867,7 +867,7 @@ mod tests {
EnrWrapper::new(builder.build(&key).unwrap())
};

let mut encoded = BytesMut::new();
let mut encoded = Vec::new();
enr.encode(&mut encoded);
let mut encoded_bytes = &encoded[..];
let decoded_enr = EnrWrapper::<SecretKey>::decode(&mut encoded_bytes).unwrap();
Expand Down
10 changes: 4 additions & 6 deletions crates/net/eth-wire/src/ethstream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -215,11 +215,10 @@ where
&mut self,
item: EthBroadcastMessage,
) -> Result<(), EthStreamError> {
let mut bytes = BytesMut::new();
let mut bytes = Vec::new();
ProtocolBroadcastMessage::from(item).encode(&mut bytes);
let bytes = bytes.freeze();

self.inner.start_send_unpin(bytes)?;
self.inner.start_send_unpin(bytes.into())?;

Ok(())
}
Expand Down Expand Up @@ -297,11 +296,10 @@ where
return Err(EthStreamError::EthHandshakeError(EthHandshakeError::StatusNotInHandshake))
}

let mut bytes = BytesMut::new();
let mut bytes = Vec::new();
ProtocolMessage::from(item).encode(&mut bytes);
let bytes = bytes.freeze();

self.project().inner.start_send(bytes)?;
self.project().inner.start_send(bytes.into())?;

Ok(())
}
Expand Down
2 changes: 1 addition & 1 deletion crates/net/eth-wire/src/p2pstream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ where
trace!(?hello, "sending p2p hello to peer");

// send our hello message with the Sink
let mut raw_hello_bytes = BytesMut::new();
let mut raw_hello_bytes = Vec::with_capacity(142);
P2PMessage::Hello(hello.message()).encode(&mut raw_hello_bytes);
self.inner.send(raw_hello_bytes.into()).await?;

Expand Down
3 changes: 1 addition & 2 deletions crates/net/eth-wire/src/types/broadcast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -740,7 +740,6 @@ impl FromIterator<(TxHash, Eth68TxMetadata)> for RequestTxHashes {
#[cfg(test)]
mod tests {
use super::*;
use bytes::BytesMut;
use reth_primitives::{b256, hex};
use std::str::FromStr;

Expand All @@ -750,7 +749,7 @@ mod tests {
input: (T, &[u8]),
) {
let (expected_decoded, expected_encoded) = input;
let mut encoded = BytesMut::new();
let mut encoded = Vec::new();
expected_decoded.encode(&mut encoded);

assert_eq!(hex::encode(&encoded), hex::encode(expected_encoded));
Expand Down
6 changes: 3 additions & 3 deletions crates/node-core/src/cli/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

use alloy_rlp::Encodable;
use reth_network::protocol::IntoRlpxSubProtocol;
use reth_primitives::{Bytes, BytesMut};
use reth_primitives::Bytes;
use reth_rpc::{
eth::{cache::EthStateCacheConfig, gas_oracle::GasPriceOracleConfig},
JwtError, JwtSecret,
Expand Down Expand Up @@ -89,9 +89,9 @@ pub trait PayloadBuilderConfig {

/// Returns the rlp-encoded extradata bytes.
fn extradata_rlp_bytes(&self) -> Bytes {
let mut extradata = BytesMut::new();
let mut extradata = Vec::with_capacity(self.extradata().as_bytes().len() + 1);
self.extradata().as_bytes().encode(&mut extradata);
extradata.freeze().into()
extradata.into()
}

/// The interval at which the job should build a new payload after the last.
Expand Down
5 changes: 2 additions & 3 deletions crates/payload/basic/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ use reth_payload_builder::{
PayloadJobGenerator,
};
use reth_primitives::{
bytes::BytesMut,
constants::{EMPTY_WITHDRAWALS, ETHEREUM_BLOCK_GAS_LIMIT, RETH_CLIENT_VERSION, SLOT_DURATION},
proofs, BlockNumberOrTag, Bytes, ChainSpec, SealedBlock, Withdrawals, B256, U256,
};
Expand Down Expand Up @@ -301,10 +300,10 @@ impl BasicPayloadJobGeneratorConfig {

impl Default for BasicPayloadJobGeneratorConfig {
fn default() -> Self {
let mut extradata = BytesMut::new();
let mut extradata = Vec::with_capacity(RETH_CLIENT_VERSION.as_bytes().len() + 1);
RETH_CLIENT_VERSION.as_bytes().encode(&mut extradata);
Self {
extradata: extradata.freeze().into(),
extradata: extradata.into(),
max_gas_limit: ETHEREUM_BLOCK_GAS_LIMIT,
interval: Duration::from_secs(1),
// 12s slot time
Expand Down
3 changes: 1 addition & 2 deletions crates/primitives/src/chain/spec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1530,7 +1530,6 @@ mod tests {
use super::*;
use crate::{b256, hex, trie::TrieAccount, ChainConfig, GenesisAccount};
use alloy_rlp::Encodable;
use bytes::BytesMut;
use std::{collections::HashMap, str::FromStr};

fn test_fork_ids(spec: &ChainSpec, cases: &[(Head, ForkId)]) {
Expand Down Expand Up @@ -2601,7 +2600,7 @@ Post-merge hard forks (timestamp based):

for (key, expected_rlp) in key_rlp {
let account = chainspec.genesis.alloc.get(&key).expect("account should exist");
let mut account_rlp = BytesMut::new();
let mut account_rlp = Vec::new();
TrieAccount::from(account.clone()).encode(&mut account_rlp);
assert_eq!(account_rlp, expected_rlp)
}
Expand Down
4 changes: 2 additions & 2 deletions crates/primitives/src/header.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use crate::{
ChainSpec, GotExpected, GotExpectedBoxed, Hardfork, B256, B64, U256,
};
use alloy_rlp::{length_of_length, Decodable, Encodable};
use bytes::{BufMut, BytesMut};
use bytes::BufMut;
#[cfg(any(test, feature = "arbitrary"))]
use proptest::prelude::*;
use reth_codecs::{add_arbitrary_tests, derive_arbitrary, main_codec, Compact};
Expand Down Expand Up @@ -206,7 +206,7 @@ impl Header {
/// Heavy function that will calculate hash of data and will *not* save the change to metadata.
/// Use [`Header::seal`], [`SealedHeader`] and unlock if you need hash to be persistent.
pub fn hash_slow(&self) -> B256 {
let mut out = BytesMut::new();
let mut out = Vec::new();
self.encode(&mut out);
keccak256(&out)
}
Expand Down
12 changes: 6 additions & 6 deletions crates/primitives/src/receipt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use crate::{
logs_bloom, Bloom, Log, PruneSegmentError, TxType, B256,
};
use alloy_rlp::{length_of_length, Decodable, Encodable};
use bytes::{Buf, BufMut, BytesMut};
use bytes::{Buf, BufMut};
#[cfg(any(test, feature = "arbitrary"))]
use proptest::strategy::Strategy;
use reth_codecs::{add_arbitrary_tests, main_codec, Compact, CompactZstd};
Expand Down Expand Up @@ -485,7 +485,7 @@ impl<'a> ReceiptWithBloomEncoder<'a> {
return
}

let mut payload = BytesMut::new();
let mut payload = Vec::new();
self.encode_fields(&mut payload);

if with_header {
Expand Down Expand Up @@ -630,9 +630,9 @@ mod tests {
let receipt = ReceiptWithBloom::decode(&mut &data[..]).unwrap();
assert_eq!(receipt, expected);

let mut buf = BytesMut::default();
let mut buf = Vec::new();
receipt.encode_inner(&mut buf, false);
assert_eq!(buf.freeze(), &data[..]);
assert_eq!(buf, &data[..]);
}

#[cfg(feature = "optimism")]
Expand All @@ -656,9 +656,9 @@ mod tests {
let receipt = ReceiptWithBloom::decode(&mut &data[..]).unwrap();
assert_eq!(receipt, expected);

let mut buf = BytesMut::default();
let mut buf = Vec::new();
expected.encode_inner(&mut buf, false);
assert_eq!(buf.freeze(), &data[..]);
assert_eq!(buf, &data[..]);
}

#[test]
Expand Down
5 changes: 2 additions & 3 deletions crates/primitives/src/transaction/eip2930.rs
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,6 @@ mod tests {
Address, Bytes, Transaction, TransactionSigned, U256,
};
use alloy_rlp::{Decodable, Encodable};
use bytes::BytesMut;

#[test]
fn test_decode_create() {
Expand All @@ -211,7 +210,7 @@ mod tests {
let signature = Signature { odd_y_parity: true, r: U256::default(), s: U256::default() };
let tx = TransactionSigned::from_transaction_and_signature(request, signature);

let mut encoded = BytesMut::new();
let mut encoded = Vec::new();
tx.encode(&mut encoded);
assert_eq!(encoded.len(), tx.length());

Expand All @@ -236,7 +235,7 @@ mod tests {

let tx = TransactionSigned::from_transaction_and_signature(request, signature);

let mut encoded = BytesMut::new();
let mut encoded = Vec::new();
tx.encode(&mut encoded);
assert_eq!(encoded.len(), tx.length());

Expand Down
6 changes: 3 additions & 3 deletions crates/primitives/src/transaction/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use crate::{
use alloy_rlp::{
Decodable, Encodable, Error as RlpError, Header, EMPTY_LIST_CODE, EMPTY_STRING_CODE,
};
use bytes::{Buf, BytesMut};
use bytes::Buf;
use derive_more::{AsRef, Deref};
use once_cell::sync::Lazy;
use rayon::prelude::{IntoParallelIterator, ParallelIterator};
Expand Down Expand Up @@ -1107,9 +1107,9 @@ impl TransactionSigned {
///
/// See also [TransactionSigned::encode_enveloped]
pub fn envelope_encoded(&self) -> Bytes {
let mut buf = BytesMut::new();
let mut buf = Vec::new();
self.encode_enveloped(&mut buf);
buf.freeze().into()
buf.into()
}

/// Encodes the transaction into the "raw" format (e.g. `eth_sendRawTransaction`).
Expand Down
6 changes: 3 additions & 3 deletions crates/primitives/src/transaction/pooled.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use crate::{
EIP4844_TX_TYPE_ID,
};
use alloy_rlp::{Decodable, Encodable, Error as RlpError, Header, EMPTY_LIST_CODE};
use bytes::{Buf, BytesMut};
use bytes::Buf;
use derive_more::{AsRef, Deref};
use reth_codecs::add_arbitrary_tests;
use serde::{Deserialize, Serialize};
Expand Down Expand Up @@ -302,9 +302,9 @@ impl PooledTransactionsElement {
///
/// See also [TransactionSigned::encode_enveloped]
pub fn envelope_encoded(&self) -> Bytes {
let mut buf = BytesMut::new();
let mut buf = Vec::new();
self.encode_enveloped(&mut buf);
buf.freeze().into()
buf.into()
}

/// Encodes the transaction into the "raw" format (e.g. `eth_sendRawTransaction`).
Expand Down
5 changes: 2 additions & 3 deletions crates/rpc/rpc/src/eth/api/transactions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1271,10 +1271,9 @@ where
) -> EthResult<OptimismTxMeta> {
let Some(l1_block_info) = l1_block_info else { return Ok(OptimismTxMeta::default()) };

let mut envelope_buf = bytes::BytesMut::new();
tx.encode_enveloped(&mut envelope_buf);

let (l1_fee, l1_data_gas) = if !tx.is_deposit() {
let envelope_buf = tx.envelope_encoded();

let inner_l1_fee = l1_block_info
.l1_tx_data_fee(
&self.inner.provider.chain_spec(),
Expand Down
2 changes: 1 addition & 1 deletion crates/transaction-pool/src/maintain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -609,7 +609,7 @@ where
.collect::<Vec<_>>();

let num_txs = local_transactions.len();
let mut buf = alloy_rlp::BytesMut::new();
let mut buf = Vec::new();
alloy_rlp::encode_list(&local_transactions, &mut buf);
info!(target: "txpool", txs_file =?file_path, num_txs=%num_txs, "Saving current local transactions");
let parent_dir = file_path.parent().map(std::fs::create_dir_all).transpose();
Expand Down

0 comments on commit 81291ff

Please sign in to comment.