Less slices (#9176)

* Less slices

Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>
This commit is contained in:
Squirrel
2021-06-23 13:33:48 +01:00
committed by GitHub
parent 7b50bbb9bf
commit 07449840bd
11 changed files with 41 additions and 46 deletions
@@ -187,10 +187,10 @@ fn trap(msg: &'static str) -> Trap {
TrapKind::Host(Box::new(Error::Other(msg.into()))).into() 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 self::sandbox_primitives::HostError;
use sp_wasm_interface::ReturnValue; 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!"))?; .map_err(|_| trap("Decoding Result<ReturnValue, HostError> failed!"))?;
match result_val { match result_val {
@@ -379,10 +379,10 @@ pub enum InstantiationError {
} }
fn decode_environment_definition( fn decode_environment_definition(
raw_env_def: &[u8], mut raw_env_def: &[u8],
memories: &[Option<MemoryRef>], memories: &[Option<MemoryRef>],
) -> std::result::Result<(Imports, GuestToSupervisorFunctionMapping), InstantiationError> { ) -> 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)?; .map_err(|_| InstantiationError::EnvironmentDefinitionCorrupted)?;
let mut func_map = HashMap::new(); let mut func_map = HashMap::new();
+9 -11
View File
@@ -177,7 +177,7 @@ impl RuntimeCache {
/// Prepares a WASM module instance and executes given function for it. /// 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 /// # Parameters
/// ///
/// `code` - Provides external code or tells the executor to fetch it from storage. /// `code` - Provides external code or tells the executor to fetch it from storage.
@@ -196,7 +196,7 @@ impl RuntimeCache {
/// ///
/// `f` - Function to execute. /// `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: /// In case of failure one of two errors can be returned:
/// ///
/// `Err::InvalidCode` is returned for runtime code issues. /// `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[..]) let v: RuntimeVersion = sp_api::OldRuntimeVersion::decode(&mut &version[..])
.map_err(|_| .map_err(|_|
WasmError::Instantiation( 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"); let core_api_id = sp_core::hashing::blake2_64(b"Core");
if v.has_api_with(&core_api_id, |v| v >= 3) { 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(|_| .map_err(|_|
WasmError::Instantiation("failed to decode \"Core_version\" result".into()) 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) <[u8; RUNTIME_API_INFO_SIZE]>::try_from(chunk)
.map(sp_api::deserialize_runtime_api_info) .map(sp_api::deserialize_runtime_api_info)
.map_err(|_| { .map_err(|_| {
WasmError::Other(format!( WasmError::Other("a clipped runtime api info declaration".to_owned())
"a clipped runtime api info declaration"
))
}) })
}) })
.collect::<Result<Vec<_>, WasmError>>() .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( pub fn read_embedded_version(
blob: &RuntimeBlob, blob: &RuntimeBlob,
) -> Result<Option<RuntimeVersion>, WasmError> { ) -> 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 // 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 // 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 // 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 structure found in the `runtime_version` always contain an empty `apis` field. Therefore
// the version read will be mistakingly treated as an legacy one. // the version read will be mistakenly treated as an legacy one.
let mut decoded_version = sp_api::RuntimeVersion::decode(&mut &version_section[..]) let mut decoded_version = sp_api::RuntimeVersion::decode(&mut version_section)
.map_err(|_| .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. // Don't stop on this and check if there is a special section that encodes all runtime APIs.
+2 -2
View File
@@ -185,7 +185,7 @@ impl<'a> Sandbox for FunctionExecutor<'a> {
&mut self, &mut self,
instance_id: u32, instance_id: u32,
export_name: &str, export_name: &str,
args: &[u8], mut args: &[u8],
return_val: Pointer<u8>, return_val: Pointer<u8>,
return_val_len: WordSize, return_val_len: WordSize,
state: u32, state: u32,
@@ -193,7 +193,7 @@ impl<'a> Sandbox for FunctionExecutor<'a> {
trace!(target: "sp-sandbox", "invoke, instance_idx={}", instance_id); trace!(target: "sp-sandbox", "invoke, instance_idx={}", instance_id);
// Deserialize arguments and convert them into wasmi types. // 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")? .map_err(|_| "Can't decode serialized arguments for the invocation")?
.into_iter() .into_iter()
.map(Into::into) .map(Into::into)
+1 -4
View File
@@ -29,9 +29,6 @@
use sp_std::vec::Vec; use sp_std::vec::Vec;
#[cfg(feature = "std")]
use sp_std::ops::Deref;
#[cfg(feature = "std")] #[cfg(feature = "std")]
use tracing; use tracing;
@@ -990,7 +987,7 @@ pub trait Offchain {
.local_storage_compare_and_set( .local_storage_compare_and_set(
kind, kind,
key, key,
old_value.as_ref().map(|v| v.deref()), old_value.as_deref(),
new_value, new_value,
) )
} }
@@ -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 size = ::sp_std::mem::size_of::<T>();
let reserve = match size { let reserve = match size {
0..=0b00111111 => 1, 0..=0b00111111 => 1,
0..=0b00111111_11111111 => 2, 0b01000000..=0b00111111_11111111 => 2,
_ => 4, _ => 4,
}; };
let mut v = Vec::with_capacity(reserve + size); let mut v = Vec::with_capacity(reserve + size);
@@ -207,7 +207,7 @@ pub trait Backend<H: Hasher>: sp_std::fmt::Debug {
} }
} }
let (root, parent_txs) = self.storage_root(delta 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( .chain(
child_roots child_roots
.iter() .iter()
@@ -279,22 +279,22 @@ fn prepare_digest_input<'a, H, Number>(
trie_root, trie_root,
); );
trie_storage.for_key_values_with_prefix(&child_prefix, |key, 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(InputKey::ChildIndex::<Number>(trie_key)) = Decode::decode(&mut key) {
if let Ok(value) = <Vec<u8>>::decode(&mut &value[..]) { if let Ok(value) = <Vec<u8>>::decode(&mut value) {
let mut trie_root = <H as Hasher>::Out::default(); let mut trie_root = <H as Hasher>::Out::default();
trie_root.as_mut().copy_from_slice(&value[..]); trie_root.as_mut().copy_from_slice(&value[..]);
children_roots.insert(trie_key.storage_key, trie_root); children_roots.insert(trie_key.storage_key, trie_root);
} }
}); });
trie_storage.for_keys_with_prefix(&extrinsic_prefix, |key| trie_storage.for_keys_with_prefix(&extrinsic_prefix, |mut key|
if let Ok(InputKey::ExtrinsicIndex::<Number>(trie_key)) = Decode::decode(&mut &key[..]) { if let Ok(InputKey::ExtrinsicIndex::<Number>(trie_key)) = Decode::decode(&mut key) {
insert_to_map(&mut map, trie_key.key); insert_to_map(&mut map, trie_key.key);
}); });
trie_storage.for_keys_with_prefix(&digest_prefix, |key| trie_storage.for_keys_with_prefix(&digest_prefix, |mut key|
if let Ok(InputKey::DigestIndex::<Number>(trie_key)) = Decode::decode(&mut &key[..]) { if let Ok(InputKey::DigestIndex::<Number>(trie_key)) = Decode::decode(&mut key) {
insert_to_map(&mut map, trie_key.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), crate::changes_trie::TrieBackendStorageAdapter(storage),
trie_root, trie_root,
); );
trie_storage.for_keys_with_prefix(&extrinsic_prefix, |key| trie_storage.for_keys_with_prefix(&extrinsic_prefix, |mut key|
if let Ok(InputKey::ExtrinsicIndex::<Number>(trie_key)) = Decode::decode(&mut &key[..]) { if let Ok(InputKey::ExtrinsicIndex::<Number>(trie_key)) = Decode::decode(&mut key) {
insert_to_map(&mut map, trie_key.key); insert_to_map(&mut map, trie_key.key);
}); });
trie_storage.for_keys_with_prefix(&digest_prefix, |key| trie_storage.for_keys_with_prefix(&digest_prefix, |mut key|
if let Ok(InputKey::DigestIndex::<Number>(trie_key)) = Decode::decode(&mut &key[..]) { if let Ok(InputKey::DigestIndex::<Number>(trie_key)) = Decode::decode(&mut key) {
insert_to_map(&mut map, trie_key.key); insert_to_map(&mut map, trie_key.key);
}); });
} }
@@ -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 child_prefix = ChildIndex::key_neutral_prefix(block.clone());
let mut children_roots = Vec::new(); let mut children_roots = Vec::new();
trie_storage.for_key_values_with_prefix(&child_prefix, |key, 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(InputKey::ChildIndex::<Number>(_trie_key)) = Decode::decode(&mut key) {
if let Ok(value) = <Vec<u8>>::decode(&mut &value[..]) { if let Ok(value) = <Vec<u8>>::decode(&mut value) {
let mut trie_root = <H as Hasher>::Out::default(); let mut trie_root = <H as Hasher>::Out::default();
trie_root.as_mut().copy_from_slice(&value[..]); trie_root.as_mut().copy_from_slice(&value[..]);
children_roots.push(trie_root); children_roots.push(trie_root);
@@ -637,7 +637,7 @@ where
} }
#[cfg(feature = "std")] #[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(); let _guard = guard();
if let Some(ref root) = self.storage_transaction_cache.changes_trie_transaction_storage_root { if let Some(ref root) = self.storage_transaction_cache.changes_trie_transaction_storage_root {
trace!( trace!(
@@ -653,7 +653,7 @@ where
let root = self.overlay.changes_trie_root( let root = self.overlay.changes_trie_root(
self.backend, self.backend,
self.changes_trie_state.as_ref(), self.changes_trie_state.as_ref(),
Decode::decode(&mut &parent_hash[..]).map_err(|e| Decode::decode(&mut parent_hash).map_err(|e|
trace!( trace!(
target: "state", target: "state",
"Failed to decode changes root parent hash: {}", "Failed to decode changes root parent hash: {}",
+4 -4
View File
@@ -211,7 +211,7 @@ pub fn read_trie_value<L: TrieConfiguration, DB: hash_db::HashDBRef<L::Hash, tri
root: &TrieHash<L>, root: &TrieHash<L>,
key: &[u8] key: &[u8]
) -> Result<Option<Vec<u8>>, Box<TrieError<L>>> { ) -> 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. /// Read a value from the trie with given Query.
@@ -225,7 +225,7 @@ pub fn read_trie_value_with<
key: &[u8], key: &[u8],
query: Q query: Q
) -> Result<Option<Vec<u8>>, Box<TrieError<L>>> { ) -> 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. /// 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); root.as_mut().copy_from_slice(root_slice);
let db = KeySpacedDB::new(&*db, keyspace); 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. /// 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); root.as_mut().copy_from_slice(root_slice);
let db = KeySpacedDB::new(&*db, keyspace); 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 /// `HashDB` implementation that append a encoded prefix (unique id bytes) in addition to the
+3 -3
View File
@@ -259,7 +259,7 @@ fn partial_encode(partial: Partial, node_kind: NodeKind) -> Vec<u8> {
if number_nibble_encoded > 0 { if number_nibble_encoded > 0 {
output.push(nibble_ops::pad_right((partial.0).1)); output.push(nibble_ops::pad_right((partial.0).1));
} }
output.extend_from_slice(&partial.1[..]); output.extend_from_slice(partial.1);
output output
} }
@@ -272,8 +272,8 @@ const BITMAP_LENGTH: usize = 2;
pub(crate) struct Bitmap(u16); pub(crate) struct Bitmap(u16);
impl Bitmap { impl Bitmap {
pub fn decode(data: &[u8]) -> Result<Self, Error> { pub fn decode(mut data: &[u8]) -> Result<Self, Error> {
Ok(Bitmap(u16::decode(&mut &data[..])?)) Ok(Bitmap(u16::decode(&mut data)?))
} }
pub fn value_at(&self, i: usize) -> bool { pub fn value_at(&self, i: usize) -> bool {