Run cargo fmt on the whole code base (#9394)

* Run cargo fmt on the whole code base

* Second run

* Add CI check

* Fix compilation

* More unnecessary braces

* Handle weights

* Use --all

* Use correct attributes...

* Fix UI tests

* AHHHHHHHHH

* 🤦

* Docs

* Fix compilation

* 🤷

* Please stop

* 🤦 x 2

* More

* make rustfmt.toml consistent with polkadot

Co-authored-by: André Silva <andrerfosilva@gmail.com>
This commit is contained in:
Bastian Köcher
2021-07-21 16:32:32 +02:00
committed by GitHub
parent d451c38c1c
commit 7b56ab15b4
1010 changed files with 53339 additions and 51208 deletions
@@ -20,36 +20,35 @@
mod changeset;
mod offchain;
pub use offchain::OffchainOverlayedChanges;
use crate::{
backend::Backend,
stats::StateMachineStats,
};
use sp_std::{vec::Vec, any::{TypeId, Any}, boxed::Box};
use self::changeset::OverlayedChangeSet;
use crate::{backend::Backend, stats::StateMachineStats};
pub use offchain::OffchainOverlayedChanges;
use sp_std::{
any::{Any, TypeId},
boxed::Box,
vec::Vec,
};
use crate::{changes_trie::BlockNumber, DefaultError};
#[cfg(feature = "std")]
use crate::{
changes_trie::{build_changes_trie, State as ChangesTrieState},
ChangesTrieTransaction,
changes_trie::{
build_changes_trie,
State as ChangesTrieState,
},
};
use crate::changes_trie::BlockNumber;
#[cfg(feature = "std")]
use std::collections::{HashMap as Map, hash_map::Entry as MapEntry};
use codec::{Decode, Encode};
use hash_db::Hasher;
use sp_core::{
offchain::OffchainOverlayedChange,
storage::{well_known_keys::EXTRINSIC_INDEX, ChildInfo},
};
use sp_externalities::{Extension, Extensions};
#[cfg(not(feature = "std"))]
use sp_std::collections::btree_map::{BTreeMap as Map, Entry as MapEntry};
use sp_std::collections::btree_set::BTreeSet;
use codec::{Decode, Encode};
use sp_core::storage::{well_known_keys::EXTRINSIC_INDEX, ChildInfo};
use sp_core::offchain::OffchainOverlayedChange;
use hash_db::Hasher;
use crate::DefaultError;
use sp_externalities::{Extensions, Extension};
#[cfg(feature = "std")]
use std::collections::{hash_map::Entry as MapEntry, HashMap as Map};
pub use self::changeset::{OverlayedValue, NoOpenTransaction, AlreadyInRuntime, NotInRuntime};
pub use self::changeset::{AlreadyInRuntime, NoOpenTransaction, NotInRuntime, OverlayedValue};
/// Changes that are made outside of extrinsics are marked with this index;
pub const NO_EXTRINSIC_INDEX: u32 = 0xffffffff;
@@ -129,7 +128,7 @@ pub enum IndexOperation {
extrinsic: u32,
/// Referenced index hash.
hash: Vec<u8>,
}
},
}
/// A storage changes structure that can be generated by the data collected in [`OverlayedChanges`].
@@ -169,7 +168,9 @@ pub struct StorageChanges<Transaction, H: Hasher, N: BlockNumber> {
#[cfg(feature = "std")]
impl<Transaction, H: Hasher, N: BlockNumber> StorageChanges<Transaction, H, N> {
/// Deconstruct into the inner values
pub fn into_inner(self) -> (
pub fn into_inner(
self,
) -> (
StorageCollection,
ChildStorageCollection,
OffchainChangesCollection,
@@ -216,7 +217,9 @@ impl<Transaction, H: Hasher, N: BlockNumber> StorageTransactionCache<Transaction
}
}
impl<Transaction, H: Hasher, N: BlockNumber> Default for StorageTransactionCache<Transaction, H, N> {
impl<Transaction, H: Hasher, N: BlockNumber> Default
for StorageTransactionCache<Transaction, H, N>
{
fn default() -> Self {
Self {
transaction: None,
@@ -231,7 +234,9 @@ impl<Transaction, H: Hasher, N: BlockNumber> Default for StorageTransactionCache
}
}
impl<Transaction: Default, H: Hasher, N: BlockNumber> Default for StorageChanges<Transaction, H, N> {
impl<Transaction: Default, H: Hasher, N: BlockNumber> Default
for StorageChanges<Transaction, H, N>
{
fn default() -> Self {
Self {
main_storage_changes: Default::default(),
@@ -325,12 +330,10 @@ impl OverlayedChanges {
self.stats.tally_write_overlay(size_write);
let storage_key = child_info.storage_key().to_vec();
let top = &self.top;
let (changeset, info) = self.children.entry(storage_key).or_insert_with(||
(
top.spawn_child(),
child_info.clone()
)
);
let (changeset, info) = self
.children
.entry(storage_key)
.or_insert_with(|| (top.spawn_child(), child_info.clone()));
let updatable = info.try_update(child_info);
debug_assert!(updatable);
changeset.set(key, val, extrinsic_index);
@@ -339,19 +342,14 @@ impl OverlayedChanges {
/// Clear child storage of given storage key.
///
/// Can be rolled back or committed when called inside a transaction.
pub(crate) fn clear_child_storage(
&mut self,
child_info: &ChildInfo,
) {
pub(crate) fn clear_child_storage(&mut self, child_info: &ChildInfo) {
let extrinsic_index = self.extrinsic_index();
let storage_key = child_info.storage_key().to_vec();
let top = &self.top;
let (changeset, info) = self.children.entry(storage_key).or_insert_with(||
(
top.spawn_child(),
child_info.clone()
)
);
let (changeset, info) = self
.children
.entry(storage_key)
.or_insert_with(|| (top.spawn_child(), child_info.clone()));
let updatable = info.try_update(child_info);
debug_assert!(updatable);
changeset.clear_where(|_, _| true, extrinsic_index);
@@ -367,20 +365,14 @@ impl OverlayedChanges {
/// Removes all key-value pairs which keys share the given prefix.
///
/// Can be rolled back or committed when called inside a transaction
pub(crate) fn clear_child_prefix(
&mut self,
child_info: &ChildInfo,
prefix: &[u8],
) {
pub(crate) fn clear_child_prefix(&mut self, child_info: &ChildInfo, prefix: &[u8]) {
let extrinsic_index = self.extrinsic_index();
let storage_key = child_info.storage_key().to_vec();
let top = &self.top;
let (changeset, info) = self.children.entry(storage_key).or_insert_with(||
(
top.spawn_child(),
child_info.clone()
)
);
let (changeset, info) = self
.children
.entry(storage_key)
.or_insert_with(|| (top.spawn_child(), child_info.clone()));
let updatable = info.try_update(child_info);
debug_assert!(updatable);
changeset.clear_where(|key, _| key.starts_with(prefix), extrinsic_index);
@@ -417,11 +409,14 @@ impl OverlayedChanges {
pub fn rollback_transaction(&mut self) -> Result<(), NoOpenTransaction> {
self.top.rollback_transaction()?;
retain_map(&mut self.children, |_, (changeset, _)| {
changeset.rollback_transaction()
changeset
.rollback_transaction()
.expect("Top and children changesets are started in lockstep; qed");
!changeset.is_empty()
});
self.offchain.overlay_mut().rollback_transaction()
self.offchain
.overlay_mut()
.rollback_transaction()
.expect("Top and offchain changesets are started in lockstep; qed");
Ok(())
}
@@ -433,10 +428,13 @@ impl OverlayedChanges {
pub fn commit_transaction(&mut self) -> Result<(), NoOpenTransaction> {
self.top.commit_transaction()?;
for (_, (changeset, _)) in self.children.iter_mut() {
changeset.commit_transaction()
changeset
.commit_transaction()
.expect("Top and children changesets are started in lockstep; qed");
}
self.offchain.overlay_mut().commit_transaction()
self.offchain
.overlay_mut()
.commit_transaction()
.expect("Top and offchain changesets are started in lockstep; qed");
Ok(())
}
@@ -448,10 +446,13 @@ impl OverlayedChanges {
pub fn enter_runtime(&mut self) -> Result<(), AlreadyInRuntime> {
self.top.enter_runtime()?;
for (_, (changeset, _)) in self.children.iter_mut() {
changeset.enter_runtime()
changeset
.enter_runtime()
.expect("Top and children changesets are entering runtime in lockstep; qed")
}
self.offchain.overlay_mut().enter_runtime()
self.offchain
.overlay_mut()
.enter_runtime()
.expect("Top and offchain changesets are started in lockstep; qed");
Ok(())
}
@@ -463,10 +464,13 @@ impl OverlayedChanges {
pub fn exit_runtime(&mut self) -> Result<(), NotInRuntime> {
self.top.exit_runtime()?;
for (_, (changeset, _)) in self.children.iter_mut() {
changeset.exit_runtime()
changeset
.exit_runtime()
.expect("Top and children changesets are entering runtime in lockstep; qed");
}
self.offchain.overlay_mut().exit_runtime()
self.offchain
.overlay_mut()
.exit_runtime()
.expect("Top and offchain changesets are started in lockstep; qed");
Ok(())
}
@@ -477,19 +481,23 @@ impl OverlayedChanges {
///
/// Panics:
/// Panics if `transaction_depth() > 0`
fn drain_committed(&mut self) -> (
impl Iterator<Item=(StorageKey, Option<StorageValue>)>,
impl Iterator<Item=(StorageKey, (impl Iterator<Item=(StorageKey, Option<StorageValue>)>, ChildInfo))>,
fn drain_committed(
&mut self,
) -> (
impl Iterator<Item = (StorageKey, Option<StorageValue>)>,
impl Iterator<
Item = (
StorageKey,
(impl Iterator<Item = (StorageKey, Option<StorageValue>)>, ChildInfo),
),
>,
) {
use sp_std::mem::take;
(
take(&mut self.top).drain_commited(),
take(&mut self.children).into_iter()
.map(|(key, (val, info))| (
key,
(val.drain_commited(), info)
)
),
take(&mut self.children)
.into_iter()
.map(|(key, (val, info))| (key, (val.drain_commited(), info))),
)
}
@@ -499,24 +507,29 @@ impl OverlayedChanges {
///
/// Panics:
/// Panics if `transaction_depth() > 0`
pub fn offchain_drain_committed(&mut self) -> impl Iterator<Item=((StorageKey, StorageKey), OffchainOverlayedChange)> {
pub fn offchain_drain_committed(
&mut self,
) -> impl Iterator<Item = ((StorageKey, StorageKey), OffchainOverlayedChange)> {
self.offchain.drain()
}
/// Get an iterator over all child changes as seen by the current transaction.
pub fn children(&self)
-> impl Iterator<Item=(impl Iterator<Item=(&StorageKey, &OverlayedValue)>, &ChildInfo)> {
pub fn children(
&self,
) -> impl Iterator<Item = (impl Iterator<Item = (&StorageKey, &OverlayedValue)>, &ChildInfo)> {
self.children.iter().map(|(_, v)| (v.0.changes(), &v.1))
}
/// Get an iterator over all top changes as been by the current transaction.
pub fn changes(&self) -> impl Iterator<Item=(&StorageKey, &OverlayedValue)> {
pub fn changes(&self) -> impl Iterator<Item = (&StorageKey, &OverlayedValue)> {
self.top.changes()
}
/// Get an optional iterator over all child changes stored under the supplied key.
pub fn child_changes(&self, key: &[u8])
-> Option<(impl Iterator<Item=(&StorageKey, &OverlayedValue)>, &ChildInfo)> {
pub fn child_changes(
&self,
key: &[u8],
) -> Option<(impl Iterator<Item = (&StorageKey, &OverlayedValue)>, &ChildInfo)> {
self.children.get(key).map(|(overlay, info)| (overlay.changes(), info))
}
@@ -527,16 +540,16 @@ impl OverlayedChanges {
/// Convert this instance with all changes into a [`StorageChanges`] instance.
#[cfg(feature = "std")]
pub fn into_storage_changes<
B: Backend<H>, H: Hasher, N: BlockNumber
>(
pub fn into_storage_changes<B: Backend<H>, H: Hasher, N: BlockNumber>(
mut self,
backend: &B,
changes_trie_state: Option<&ChangesTrieState<H, N>>,
parent_hash: H::Out,
mut cache: StorageTransactionCache<B::Transaction, H, N>,
) -> Result<StorageChanges<B::Transaction, H, N>, DefaultError>
where H::Out: Ord + Encode + 'static {
where
H::Out: Ord + Encode + 'static,
{
self.drain_storage_changes(backend, changes_trie_state, parent_hash, &mut cache)
}
@@ -544,35 +557,34 @@ impl OverlayedChanges {
pub fn drain_storage_changes<B: Backend<H>, H: Hasher, N: BlockNumber>(
&mut self,
backend: &B,
#[cfg(feature = "std")]
changes_trie_state: Option<&ChangesTrieState<H, N>>,
#[cfg(feature = "std")] changes_trie_state: Option<&ChangesTrieState<H, N>>,
parent_hash: H::Out,
mut cache: &mut StorageTransactionCache<B::Transaction, H, N>,
) -> Result<StorageChanges<B::Transaction, H, N>, DefaultError>
where H::Out: Ord + Encode + 'static {
where
H::Out: Ord + Encode + 'static,
{
// If the transaction does not exist, we generate it.
if cache.transaction.is_none() {
self.storage_root(backend, &mut cache);
}
let (transaction, transaction_storage_root) = cache.transaction.take()
let (transaction, transaction_storage_root) = cache
.transaction
.take()
.and_then(|t| cache.transaction_storage_root.take().map(|tr| (t, tr)))
.expect("Transaction was be generated as part of `storage_root`; qed");
// If the transaction does not exist, we generate it.
#[cfg(feature = "std")]
if cache.changes_trie_transaction.is_none() {
self.changes_trie_root(
backend,
changes_trie_state,
parent_hash,
false,
&mut cache,
).map_err(|_| "Failed to generate changes trie transaction")?;
self.changes_trie_root(backend, changes_trie_state, parent_hash, false, &mut cache)
.map_err(|_| "Failed to generate changes trie transaction")?;
}
#[cfg(feature = "std")]
let changes_trie_transaction = cache.changes_trie_transaction
let changes_trie_transaction = cache
.changes_trie_transaction
.take()
.expect("Changes trie transaction was generated by `changes_trie_root`; qed");
@@ -584,7 +596,9 @@ impl OverlayedChanges {
Ok(StorageChanges {
main_storage_changes: main_storage_changes.collect(),
child_storage_changes: child_storage_changes.map(|(sk, it)| (sk, it.0.collect())).collect(),
child_storage_changes: child_storage_changes
.map(|(sk, it)| (sk, it.0.collect()))
.collect(),
offchain_storage_changes,
transaction,
transaction_storage_root,
@@ -614,7 +628,8 @@ impl OverlayedChanges {
true => Some(
self.storage(EXTRINSIC_INDEX)
.and_then(|idx| idx.and_then(|idx| Decode::decode(&mut &*idx).ok()))
.unwrap_or(NO_EXTRINSIC_INDEX)),
.unwrap_or(NO_EXTRINSIC_INDEX),
),
false => None,
}
}
@@ -628,13 +643,13 @@ impl OverlayedChanges {
backend: &B,
cache: &mut StorageTransactionCache<B::Transaction, H, N>,
) -> H::Out
where H::Out: Ord + Encode,
where
H::Out: Ord + Encode,
{
let delta = self.changes().map(|(k, v)| (&k[..], v.value().map(|v| &v[..])));
let child_delta = self.children()
.map(|(changes, info)| (info, changes.map(
|(k, v)| (&k[..], v.value().map(|v| &v[..]))
)));
let child_delta = self.children().map(|(changes, info)| {
(info, changes.map(|(k, v)| (&k[..], v.value().map(|v| &v[..]))))
});
let (root, transaction) = backend.full_storage_root(delta, child_delta);
@@ -659,14 +674,18 @@ impl OverlayedChanges {
parent_hash: H::Out,
panic_on_storage_error: bool,
cache: &mut StorageTransactionCache<B::Transaction, H, N>,
) -> Result<Option<H::Out>, ()> where H::Out: Ord + Encode + 'static {
) -> Result<Option<H::Out>, ()>
where
H::Out: Ord + Encode + 'static,
{
build_changes_trie::<_, H, N>(
backend,
changes_trie_state,
self,
parent_hash,
panic_on_storage_error,
).map(|r| {
)
.map(|r| {
let root = r.as_ref().map(|r| r.1).clone();
cache.changes_trie_transaction = Some(r.map(|(db, _, cache)| (db, cache)));
cache.changes_trie_transaction_storage_root = Some(root);
@@ -685,7 +704,7 @@ impl OverlayedChanges {
pub fn child_iter_after(
&self,
storage_key: &[u8],
key: &[u8]
key: &[u8],
) -> impl Iterator<Item = (&[u8], &OverlayedValue)> {
self.children
.get(storage_key)
@@ -716,18 +735,18 @@ impl OverlayedChanges {
#[cfg(feature = "std")]
fn retain_map<K, V, F>(map: &mut Map<K, V>, f: F)
where
K: std::cmp::Eq + std::hash::Hash,
F: FnMut(&K, &mut V) -> bool,
where
K: std::cmp::Eq + std::hash::Hash,
F: FnMut(&K, &mut V) -> bool,
{
map.retain(f);
}
#[cfg(not(feature = "std"))]
fn retain_map<K, V, F>(map: &mut Map<K, V>, mut f: F)
where
K: Ord,
F: FnMut(&K, &mut V) -> bool,
where
K: Ord,
F: FnMut(&K, &mut V) -> bool,
{
let old = sp_std::mem::replace(map, Map::default());
for (k, mut v) in old.into_iter() {
@@ -799,18 +818,13 @@ impl<'a> OverlayedExtensions<'a> {
#[cfg(test)]
mod tests {
use hex_literal::hex;
use sp_core::{Blake2Hasher, traits::Externalities};
use crate::InMemoryBackend;
use crate::ext::Ext;
use super::*;
use crate::{ext::Ext, InMemoryBackend};
use hex_literal::hex;
use sp_core::{traits::Externalities, Blake2Hasher};
use std::collections::BTreeMap;
fn assert_extrinsics(
overlay: &OverlayedChangeSet,
key: impl AsRef<[u8]>,
expected: Vec<u32>,
) {
fn assert_extrinsics(overlay: &OverlayedChangeSet, key: impl AsRef<[u8]>, expected: Vec<u32>) {
assert_eq!(
overlay.get(key.as_ref()).unwrap().extrinsics().into_iter().collect::<Vec<_>>(),
expected
@@ -863,13 +877,16 @@ mod tests {
state.commit_transaction().unwrap();
}
let offchain_data: Vec<_> = state.offchain_drain_committed().collect();
let expected: Vec<_> = expected.into_iter().map(|(key, value)| {
let change = match value {
Some(value) => OffchainOverlayedChange::SetValue(value),
None => OffchainOverlayedChange::Remove,
};
((STORAGE_PREFIX.to_vec(), key), change)
}).collect();
let expected: Vec<_> = expected
.into_iter()
.map(|(key, value)| {
let change = match value {
Some(value) => OffchainOverlayedChange::SetValue(value),
None => OffchainOverlayedChange::Remove,
};
((STORAGE_PREFIX.to_vec(), key), change)
})
.collect();
assert_eq!(offchain_data, expected);
}
@@ -904,7 +921,6 @@ mod tests {
check_offchain_content(&overlayed, 0, vec![(key.clone(), None)]);
}
#[test]
fn overlayed_storage_root_works() {
let initial: BTreeMap<_, _> = vec![
@@ -912,7 +928,9 @@ mod tests {
(b"dog".to_vec(), b"puppyXXX".to_vec()),
(b"dogglesworth".to_vec(), b"catXXX".to_vec()),
(b"doug".to_vec(), b"notadog".to_vec()),
].into_iter().collect();
]
.into_iter()
.collect();
let backend = InMemoryBackend::<Blake2Hasher>::from(initial);
let mut overlay = OverlayedChanges::default();
overlay.set_collect_extrinsics(false);
@@ -935,7 +953,8 @@ mod tests {
crate::changes_trie::disabled_state::<_, u64>(),
None,
);
const ROOT: [u8; 32] = hex!("39245109cef3758c2eed2ccba8d9b370a917850af3824bc8348d505df2c298fa");
const ROOT: [u8; 32] =
hex!("39245109cef3758c2eed2ccba8d9b370a917850af3824bc8348d505df2c298fa");
assert_eq!(&ext.storage_root()[..], &ROOT);
}