From 07449840bdcd9bc1c55dcb47dfe41f1befa0f20b Mon Sep 17 00:00:00 2001
From: Squirrel <gilescope@gmail.com>
Date: Wed, 23 Jun 2021 13:33:48 +0100
Subject: [PATCH] Less slices (#9176)
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

* Less slices

Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>
---
 .../client/executor/common/src/sandbox.rs     |  8 +++----
 substrate/client/executor/src/wasm_runtime.rs | 20 ++++++++---------
 substrate/client/executor/wasmi/src/lib.rs    |  4 ++--
 substrate/primitives/io/src/lib.rs            |  5 +----
 .../primitives/runtime/src/generic/mod.rs     |  2 +-
 .../primitives/state-machine/src/backend.rs   |  2 +-
 .../state-machine/src/changes_trie/build.rs   | 22 +++++++++----------
 .../state-machine/src/changes_trie/prune.rs   |  6 ++---
 substrate/primitives/state-machine/src/ext.rs |  4 ++--
 substrate/primitives/trie/src/lib.rs          |  8 +++----
 substrate/primitives/trie/src/node_codec.rs   |  6 ++---
 11 files changed, 41 insertions(+), 46 deletions(-)

diff --git a/substrate/client/executor/common/src/sandbox.rs b/substrate/client/executor/common/src/sandbox.rs
index 8ed294bb839..b7838aab7f3 100644
--- a/substrate/client/executor/common/src/sandbox.rs
+++ b/substrate/client/executor/common/src/sandbox.rs
@@ -187,10 +187,10 @@ fn trap(msg: &'static str) -> Trap {
 	TrapKind::Host(Box::new(Error::Other(msg.into()))).into()
 }
 
-fn deserialize_result(serialized_result: &[u8]) -> std::result::Result<Option<RuntimeValue>, Trap> {
+fn deserialize_result(mut serialized_result: &[u8]) -> std::result::Result<Option<RuntimeValue>, Trap> {
 	use self::sandbox_primitives::HostError;
 	use sp_wasm_interface::ReturnValue;
-	let result_val = std::result::Result::<ReturnValue, HostError>::decode(&mut &serialized_result[..])
+	let result_val = std::result::Result::<ReturnValue, HostError>::decode(&mut serialized_result)
 		.map_err(|_| trap("Decoding Result<ReturnValue, HostError> failed!"))?;
 
 	match result_val {
@@ -379,10 +379,10 @@ pub enum InstantiationError {
 }
 
 fn decode_environment_definition(
-	raw_env_def: &[u8],
+	mut raw_env_def: &[u8],
 	memories: &[Option<MemoryRef>],
 ) -> std::result::Result<(Imports, GuestToSupervisorFunctionMapping), InstantiationError> {
-	let env_def = sandbox_primitives::EnvironmentDefinition::decode(&mut &raw_env_def[..])
+	let env_def = sandbox_primitives::EnvironmentDefinition::decode(&mut raw_env_def)
 		.map_err(|_| InstantiationError::EnvironmentDefinitionCorrupted)?;
 
 	let mut func_map = HashMap::new();
diff --git a/substrate/client/executor/src/wasm_runtime.rs b/substrate/client/executor/src/wasm_runtime.rs
index d721f36e8a9..d01132da180 100644
--- a/substrate/client/executor/src/wasm_runtime.rs
+++ b/substrate/client/executor/src/wasm_runtime.rs
@@ -177,7 +177,7 @@ impl RuntimeCache {
 
 	/// Prepares a WASM module instance and executes given function for it.
 	///
-	/// This uses internal cache to find avaiable instance or create a new one.
+	/// This uses internal cache to find available instance or create a new one.
 	/// # Parameters
 	///
 	/// `code` - Provides external code or tells the executor to fetch it from storage.
@@ -196,7 +196,7 @@ impl RuntimeCache {
 	///
 	/// `f` - Function to execute.
 	///
-	/// # Returns result of `f` wrapped in an additonal result.
+	/// # Returns result of `f` wrapped in an additional result.
 	/// In case of failure one of two errors can be returned:
 	///
 	/// `Err::InvalidCode` is returned for runtime code issues.
@@ -337,7 +337,7 @@ pub fn create_wasm_runtime_with_code(
 	}
 }
 
-fn decode_version(version: &[u8]) -> Result<RuntimeVersion, WasmError> {
+fn decode_version(mut version: &[u8]) -> Result<RuntimeVersion, WasmError> {
 	let v: RuntimeVersion = sp_api::OldRuntimeVersion::decode(&mut &version[..])
 		.map_err(|_|
 				 WasmError::Instantiation(
@@ -347,7 +347,7 @@ fn decode_version(version: &[u8]) -> Result<RuntimeVersion, WasmError> {
 
 	let core_api_id = sp_core::hashing::blake2_64(b"Core");
 	if v.has_api_with(&core_api_id, |v| v >= 3) {
-		sp_api::RuntimeVersion::decode(&mut &version[..])
+		sp_api::RuntimeVersion::decode(&mut version)
 			.map_err(|_|
 				WasmError::Instantiation("failed to decode \"Core_version\" result".into())
 			)
@@ -367,9 +367,7 @@ fn decode_runtime_apis(apis: &[u8]) -> Result<Vec<([u8; 8], u32)>, WasmError> {
 			<[u8; RUNTIME_API_INFO_SIZE]>::try_from(chunk)
 				.map(sp_api::deserialize_runtime_api_info)
 				.map_err(|_| {
-					WasmError::Other(format!(
-						"a clipped runtime api info declaration"
-					))
+					WasmError::Other("a clipped runtime api info declaration".to_owned())
 				})
 		})
 		.collect::<Result<Vec<_>, WasmError>>()
@@ -383,15 +381,15 @@ fn decode_runtime_apis(apis: &[u8]) -> Result<Vec<([u8; 8], u32)>, WasmError> {
 pub fn read_embedded_version(
 	blob: &RuntimeBlob,
 ) -> Result<Option<RuntimeVersion>, WasmError> {
-	if let Some(version_section) = blob.custom_section_contents("runtime_version") {
+	if let Some(mut version_section) = blob.custom_section_contents("runtime_version") {
 		// We do not use `decode_version` here because the runtime_version section is not supposed
 		// to ever contain a legacy version. Apart from that `decode_version` relies on presence
 		// of a special API in the `apis` field to treat the input as a non-legacy version. However
 		// the structure found in the `runtime_version` always contain an empty `apis` field. Therefore
-		// the version read will be mistakingly treated as an legacy one.
-		let mut decoded_version = sp_api::RuntimeVersion::decode(&mut &version_section[..])
+		// the version read will be mistakenly treated as an legacy one.
+		let mut decoded_version = sp_api::RuntimeVersion::decode(&mut version_section)
 			.map_err(|_|
-				WasmError::Instantiation("failed to decode verison section".into())
+				WasmError::Instantiation("failed to decode version section".into())
 			)?;
 
 		// Don't stop on this and check if there is a special section that encodes all runtime APIs.
diff --git a/substrate/client/executor/wasmi/src/lib.rs b/substrate/client/executor/wasmi/src/lib.rs
index 953c5e5178a..d4c9f4dc2e8 100644
--- a/substrate/client/executor/wasmi/src/lib.rs
+++ b/substrate/client/executor/wasmi/src/lib.rs
@@ -185,7 +185,7 @@ impl<'a> Sandbox for FunctionExecutor<'a> {
 		&mut self,
 		instance_id: u32,
 		export_name: &str,
-		args: &[u8],
+		mut args: &[u8],
 		return_val: Pointer<u8>,
 		return_val_len: WordSize,
 		state: u32,
@@ -193,7 +193,7 @@ impl<'a> Sandbox for FunctionExecutor<'a> {
 		trace!(target: "sp-sandbox", "invoke, instance_idx={}", instance_id);
 
 		// Deserialize arguments and convert them into wasmi types.
-		let args = Vec::<sp_wasm_interface::Value>::decode(&mut &args[..])
+		let args = Vec::<sp_wasm_interface::Value>::decode(&mut args)
 			.map_err(|_| "Can't decode serialized arguments for the invocation")?
 			.into_iter()
 			.map(Into::into)
diff --git a/substrate/primitives/io/src/lib.rs b/substrate/primitives/io/src/lib.rs
index 12cbf09e865..6fb25df3d02 100644
--- a/substrate/primitives/io/src/lib.rs
+++ b/substrate/primitives/io/src/lib.rs
@@ -29,9 +29,6 @@
 
 use sp_std::vec::Vec;
 
-#[cfg(feature = "std")]
-use sp_std::ops::Deref;
-
 #[cfg(feature = "std")]
 use tracing;
 
@@ -990,7 +987,7 @@ pub trait Offchain {
 			.local_storage_compare_and_set(
 				kind,
 				key,
-				old_value.as_ref().map(|v| v.deref()),
+				old_value.as_deref(),
 				new_value,
 			)
 	}
diff --git a/substrate/primitives/runtime/src/generic/mod.rs b/substrate/primitives/runtime/src/generic/mod.rs
index f5087eccab0..c4b28a06c90 100644
--- a/substrate/primitives/runtime/src/generic/mod.rs
+++ b/substrate/primitives/runtime/src/generic/mod.rs
@@ -44,7 +44,7 @@ fn encode_with_vec_prefix<T: Encode, F: Fn(&mut Vec<u8>)>(encoder: F) -> Vec<u8>
 	let size = ::sp_std::mem::size_of::<T>();
 	let reserve = match size {
 		0..=0b00111111 => 1,
-		0..=0b00111111_11111111 => 2,
+		0b01000000..=0b00111111_11111111 => 2,
 		_ => 4,
 	};
 	let mut v = Vec::with_capacity(reserve + size);
diff --git a/substrate/primitives/state-machine/src/backend.rs b/substrate/primitives/state-machine/src/backend.rs
index 9b995371303..5b1f901a3ea 100644
--- a/substrate/primitives/state-machine/src/backend.rs
+++ b/substrate/primitives/state-machine/src/backend.rs
@@ -207,7 +207,7 @@ pub trait Backend<H: Hasher>: sp_std::fmt::Debug {
 			}
 		}
 		let (root, parent_txs) = self.storage_root(delta
-			.map(|(k, v)| (&k[..], v.as_ref().map(|v| &v[..])))
+			.map(|(k, v)| (k, v.as_ref().map(|v| &v[..])))
 			.chain(
 				child_roots
 					.iter()
diff --git a/substrate/primitives/state-machine/src/changes_trie/build.rs b/substrate/primitives/state-machine/src/changes_trie/build.rs
index 1e0fc5c4d6c..38d1ab714e7 100644
--- a/substrate/primitives/state-machine/src/changes_trie/build.rs
+++ b/substrate/primitives/state-machine/src/changes_trie/build.rs
@@ -279,22 +279,22 @@ fn prepare_digest_input<'a, H, Number>(
 					trie_root,
 				);
 
-				trie_storage.for_key_values_with_prefix(&child_prefix, |key, value|
-					if let Ok(InputKey::ChildIndex::<Number>(trie_key)) = Decode::decode(&mut &key[..]) {
-						if let Ok(value) = <Vec<u8>>::decode(&mut &value[..]) {
+				trie_storage.for_key_values_with_prefix(&child_prefix, |mut key, mut value|
+					if let Ok(InputKey::ChildIndex::<Number>(trie_key)) = Decode::decode(&mut key) {
+						if let Ok(value) = <Vec<u8>>::decode(&mut value) {
 							let mut trie_root = <H as Hasher>::Out::default();
 							trie_root.as_mut().copy_from_slice(&value[..]);
 							children_roots.insert(trie_key.storage_key, trie_root);
 						}
 					});
 
-				trie_storage.for_keys_with_prefix(&extrinsic_prefix, |key|
-					if let Ok(InputKey::ExtrinsicIndex::<Number>(trie_key)) = Decode::decode(&mut &key[..]) {
+				trie_storage.for_keys_with_prefix(&extrinsic_prefix, |mut key|
+					if let Ok(InputKey::ExtrinsicIndex::<Number>(trie_key)) = Decode::decode(&mut key) {
 						insert_to_map(&mut map, trie_key.key);
 					});
 
-				trie_storage.for_keys_with_prefix(&digest_prefix, |key|
-					if let Ok(InputKey::DigestIndex::<Number>(trie_key)) = Decode::decode(&mut &key[..]) {
+				trie_storage.for_keys_with_prefix(&digest_prefix, |mut key|
+					if let Ok(InputKey::DigestIndex::<Number>(trie_key)) = Decode::decode(&mut key) {
 						insert_to_map(&mut map, trie_key.key);
 					});
 			}
@@ -310,13 +310,13 @@ fn prepare_digest_input<'a, H, Number>(
 					crate::changes_trie::TrieBackendStorageAdapter(storage),
 					trie_root,
 				);
-				trie_storage.for_keys_with_prefix(&extrinsic_prefix, |key|
-					if let Ok(InputKey::ExtrinsicIndex::<Number>(trie_key)) = Decode::decode(&mut &key[..]) {
+				trie_storage.for_keys_with_prefix(&extrinsic_prefix, |mut key|
+					if let Ok(InputKey::ExtrinsicIndex::<Number>(trie_key)) = Decode::decode(&mut key) {
 						insert_to_map(&mut map, trie_key.key);
 					});
 
-				trie_storage.for_keys_with_prefix(&digest_prefix, |key|
-					if let Ok(InputKey::DigestIndex::<Number>(trie_key)) = Decode::decode(&mut &key[..]) {
+				trie_storage.for_keys_with_prefix(&digest_prefix, |mut key|
+					if let Ok(InputKey::DigestIndex::<Number>(trie_key)) = Decode::decode(&mut key) {
 						insert_to_map(&mut map, trie_key.key);
 					});
 			}
diff --git a/substrate/primitives/state-machine/src/changes_trie/prune.rs b/substrate/primitives/state-machine/src/changes_trie/prune.rs
index a741b814a5c..754e3893f96 100644
--- a/substrate/primitives/state-machine/src/changes_trie/prune.rs
+++ b/substrate/primitives/state-machine/src/changes_trie/prune.rs
@@ -66,9 +66,9 @@ pub fn prune<H: Hasher, Number: BlockNumber, F: FnMut(H::Out)>(
 			);
 			let child_prefix = ChildIndex::key_neutral_prefix(block.clone());
 			let mut children_roots = Vec::new();
-			trie_storage.for_key_values_with_prefix(&child_prefix, |key, value| {
-				if let Ok(InputKey::ChildIndex::<Number>(_trie_key)) = Decode::decode(&mut &key[..]) {
-					if let Ok(value) = <Vec<u8>>::decode(&mut &value[..]) {
+			trie_storage.for_key_values_with_prefix(&child_prefix, |mut key, mut value| {
+				if let Ok(InputKey::ChildIndex::<Number>(_trie_key)) = Decode::decode(&mut key) {
+					if let Ok(value) = <Vec<u8>>::decode(&mut value) {
 						let mut trie_root = <H as Hasher>::Out::default();
 						trie_root.as_mut().copy_from_slice(&value[..]);
 						children_roots.push(trie_root);
diff --git a/substrate/primitives/state-machine/src/ext.rs b/substrate/primitives/state-machine/src/ext.rs
index e66664647d9..d1d636cb656 100644
--- a/substrate/primitives/state-machine/src/ext.rs
+++ b/substrate/primitives/state-machine/src/ext.rs
@@ -637,7 +637,7 @@ where
 	}
 
 	#[cfg(feature = "std")]
-	fn storage_changes_root(&mut self, parent_hash: &[u8]) -> Result<Option<Vec<u8>>, ()> {
+	fn storage_changes_root(&mut self, mut parent_hash: &[u8]) -> Result<Option<Vec<u8>>, ()> {
 		let _guard = guard();
 		if let Some(ref root) = self.storage_transaction_cache.changes_trie_transaction_storage_root {
 			trace!(
@@ -653,7 +653,7 @@ where
 			let root = self.overlay.changes_trie_root(
 				self.backend,
 				self.changes_trie_state.as_ref(),
-				Decode::decode(&mut &parent_hash[..]).map_err(|e|
+				Decode::decode(&mut parent_hash).map_err(|e|
 					trace!(
 						target: "state",
 						"Failed to decode changes root parent hash: {}",
diff --git a/substrate/primitives/trie/src/lib.rs b/substrate/primitives/trie/src/lib.rs
index f815d2af44a..4cfe3623812 100644
--- a/substrate/primitives/trie/src/lib.rs
+++ b/substrate/primitives/trie/src/lib.rs
@@ -211,7 +211,7 @@ pub fn read_trie_value<L: TrieConfiguration, DB: hash_db::HashDBRef<L::Hash, tri
 	root: &TrieHash<L>,
 	key: &[u8]
 ) -> Result<Option<Vec<u8>>, Box<TrieError<L>>> {
-	Ok(TrieDB::<L>::new(&*db, root)?.get(key).map(|x| x.map(|val| val.to_vec()))?)
+	TrieDB::<L>::new(&*db, root)?.get(key).map(|x| x.map(|val| val.to_vec()))
 }
 
 /// Read a value from the trie with given Query.
@@ -225,7 +225,7 @@ pub fn read_trie_value_with<
 	key: &[u8],
 	query: Q
 ) -> Result<Option<Vec<u8>>, Box<TrieError<L>>> {
-	Ok(TrieDB::<L>::new(&*db, root)?.get_with(key, query).map(|x| x.map(|val| val.to_vec()))?)
+	TrieDB::<L>::new(&*db, root)?.get_with(key, query).map(|x| x.map(|val| val.to_vec()))
 }
 
 /// Determine the empty trie root.
@@ -317,7 +317,7 @@ pub fn read_child_trie_value<L: TrieConfiguration, DB>(
 	root.as_mut().copy_from_slice(root_slice);
 
 	let db = KeySpacedDB::new(&*db, keyspace);
-	Ok(TrieDB::<L>::new(&db, &root)?.get(key).map(|x| x.map(|val| val.to_vec()))?)
+	TrieDB::<L>::new(&db, &root)?.get(key).map(|x| x.map(|val| val.to_vec()))
 }
 
 /// Read a value from the child trie with given query.
@@ -336,7 +336,7 @@ pub fn read_child_trie_value_with<L: TrieConfiguration, Q: Query<L::Hash, Item=D
 	root.as_mut().copy_from_slice(root_slice);
 
 	let db = KeySpacedDB::new(&*db, keyspace);
-	Ok(TrieDB::<L>::new(&db, &root)?.get_with(key, query).map(|x| x.map(|val| val.to_vec()))?)
+	TrieDB::<L>::new(&db, &root)?.get_with(key, query).map(|x| x.map(|val| val.to_vec()))
 }
 
 /// `HashDB` implementation that append a encoded prefix (unique id bytes) in addition to the
diff --git a/substrate/primitives/trie/src/node_codec.rs b/substrate/primitives/trie/src/node_codec.rs
index 0c923ff024c..296f03972c7 100644
--- a/substrate/primitives/trie/src/node_codec.rs
+++ b/substrate/primitives/trie/src/node_codec.rs
@@ -259,7 +259,7 @@ fn partial_encode(partial: Partial, node_kind: NodeKind) -> Vec<u8> {
 	if number_nibble_encoded > 0 {
 		output.push(nibble_ops::pad_right((partial.0).1));
 	}
-	output.extend_from_slice(&partial.1[..]);
+	output.extend_from_slice(partial.1);
 	output
 }
 
@@ -272,8 +272,8 @@ const BITMAP_LENGTH: usize = 2;
 pub(crate) struct Bitmap(u16);
 
 impl Bitmap {
-	pub fn decode(data: &[u8]) -> Result<Self, Error> {
-		Ok(Bitmap(u16::decode(&mut &data[..])?))
+	pub fn decode(mut data: &[u8]) -> Result<Self, Error> {
+		Ok(Bitmap(u16::decode(&mut data)?))
 	}
 
 	pub fn value_at(&self, i: usize) -> bool {
-- 
GitLab