Skip to content

Commit

Permalink
Less slices (paritytech#9176)
Browse files Browse the repository at this point in the history
* Less slices

Co-authored-by: Bastian Köcher <[email protected]>
  • Loading branch information
gilescope and bkchr authored Jun 23, 2021
1 parent e6cd6b1 commit 7dc2534
Show file tree
Hide file tree
Showing 11 changed files with 41 additions and 46 deletions.
8 changes: 4 additions & 4 deletions client/executor/common/src/sandbox.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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();
Expand Down
20 changes: 9 additions & 11 deletions client/executor/src/wasm_runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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.
Expand Down Expand Up @@ -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(
Expand All @@ -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())
)
Expand All @@ -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>>()
Expand All @@ -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.
Expand Down
4 changes: 2 additions & 2 deletions client/executor/wasmi/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -185,15 +185,15 @@ 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,
) -> WResult<u32> {
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)
Expand Down
5 changes: 1 addition & 4 deletions primitives/io/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,6 @@

use sp_std::vec::Vec;

#[cfg(feature = "std")]
use sp_std::ops::Deref;

#[cfg(feature = "std")]
use tracing;

Expand Down Expand Up @@ -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,
)
}
Expand Down
2 changes: 1 addition & 1 deletion primitives/runtime/src/generic/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
2 changes: 1 addition & 1 deletion primitives/state-machine/src/backend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
22 changes: 11 additions & 11 deletions primitives/state-machine/src/changes_trie/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});
}
Expand All @@ -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);
});
}
Expand Down
6 changes: 3 additions & 3 deletions primitives/state-machine/src/changes_trie/prune.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
4 changes: 2 additions & 2 deletions primitives/state-machine/src/ext.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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!(
Expand All @@ -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: {}",
Expand Down
8 changes: 4 additions & 4 deletions primitives/trie/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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.
Expand Down Expand Up @@ -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.
Expand All @@ -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
Expand Down
6 changes: 3 additions & 3 deletions primitives/trie/src/node_codec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

Expand All @@ -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 {
Expand Down

0 comments on commit 7dc2534

Please sign in to comment.