Skip to content
This repository has been archived by the owner on Nov 15, 2023. It is now read-only.

Use EncodeLike for storages traits #3676

Merged
merged 21 commits into from
Oct 1, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
196 changes: 98 additions & 98 deletions Cargo.lock

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion core/primitives/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ rustc-hex = { version = "2.0", default-features = false }
serde = { version = "1.0", optional = true, features = ["derive"] }
twox-hash = { version = "1.2.0", optional = true }
byteorder = { version = "1.3.1", default-features = false }
primitive-types = { version = "0.5.0", default-features = false, features = ["codec"] }
primitive-types = { version = "0.5.1", default-features = false, features = ["codec"] }
impl-serde = { version = "0.1", optional = true }
log = { version = "0.4", optional = true }
wasmi = { version = "0.5.0", optional = true }
Expand Down
2 changes: 1 addition & 1 deletion core/sr-primitives/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ impl-trait-for-tuples = "0.1.1"

[dev-dependencies]
serde_json = "1.0"
primitive-types = "0.5.0"
primitive-types = "0.5.1"
rand = "0.7.2"

[features]
Expand Down
17 changes: 16 additions & 1 deletion core/sr-primitives/src/generic/unchecked_extrinsic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ use std::fmt;

use rstd::prelude::*;
use runtime_io::blake2_256;
use codec::{Decode, Encode, Input, Error};
use codec::{Decode, Encode, EncodeLike, Input, Error};
use crate::{
traits::{self, Member, MaybeDisplay, SignedExtension, Checkable, Extrinsic},
generic::CheckedExtrinsic, transaction_validity::{TransactionValidityError, InvalidTransaction},
Expand Down Expand Up @@ -185,6 +185,12 @@ impl<Call, Extra> Encode for SignedPayload<Call, Extra> where
}
}

impl<Call, Extra> EncodeLike for SignedPayload<Call, Extra>
where
Call: Encode,
Extra: SignedExtension,
{}

impl<Address, Call, Signature, Extra> Decode
for UncheckedExtrinsic<Address, Call, Signature, Extra>
where
Expand Down Expand Up @@ -240,6 +246,15 @@ where
}
}

impl<Address, Call, Signature, Extra> EncodeLike
for UncheckedExtrinsic<Address, Call, Signature, Extra>
where
Address: Encode,
Signature: Encode,
Call: Encode,
Extra: SignedExtension,
{}

#[cfg(feature = "std")]
impl<Address: Encode, Signature: Encode, Call: Encode, Extra: SignedExtension> serde::Serialize
for UncheckedExtrinsic<Address, Call, Signature, Extra>
Expand Down
2 changes: 1 addition & 1 deletion node/runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ pub const VERSION: RuntimeVersion = RuntimeVersion {
// implementation changes and behavior does not, then leave spec_version as
// is and increment impl_version.
spec_version: 168,
impl_version: 168,
impl_version: 169,
apis: RUNTIME_API_VERSIONS,
};

Expand Down
4 changes: 2 additions & 2 deletions srml/assets/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ decl_module! {
let id = Self::next_asset_id();
<NextAssetId<T>>::mutate(|id| *id += One::one());

<Balances<T>>::insert((id, origin.clone()), total);
<Balances<T>>::insert((id, &origin), total);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

cc @shawntabrizi in v2 for kitties tutorial: the original issue of the PR references the v2 tutorial. If keys of type tuple are still around they can be refactored now

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

awesome!

<TotalSupply<T>>::insert(id, total);

Self::deposit_event(RawEvent::Issued(id, origin, total));
Expand All @@ -186,7 +186,7 @@ decl_module! {
/// Destroy any assets of `id` owned by `origin`.
fn destroy(origin, #[compact] id: T::AssetId) {
let origin = ensure_signed(origin)?;
let balance = <Balances<T>>::take((id, origin.clone()));
let balance = <Balances<T>>::take((id, &origin));
ensure!(!balance.is_zero(), "origin balance should be non-zero");

<TotalSupply<T>>::mutate(id, |total_supply| *total_supply -= balance);
Expand Down
2 changes: 1 addition & 1 deletion srml/aura/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ impl<T: Trait> Module<T> {
fn initialize_authorities(authorities: &[T::AuthorityId]) {
if !authorities.is_empty() {
assert!(<Authorities<T>>::get().is_empty(), "Authorities are already initialized!");
<Authorities<T>>::put_ref(authorities);
<Authorities<T>>::put(authorities);
}
}
}
Expand Down
6 changes: 3 additions & 3 deletions srml/authority-discovery/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,13 @@
#![cfg_attr(not(feature = "std"), no_std)]

use app_crypto::RuntimeAppPublic;
use codec::{Decode, Encode};
use codec::FullCodec;
use rstd::prelude::*;
use support::{decl_module, decl_storage};

/// The module's config trait.
pub trait Trait: system::Trait + session::Trait {
type AuthorityId: RuntimeAppPublic + Default + Decode + Encode + PartialEq;
type AuthorityId: RuntimeAppPublic + Default + FullCodec + PartialEq;
}

decl_storage! {
Expand Down Expand Up @@ -102,7 +102,7 @@ impl<T: Trait> Module<T> {
fn initialize_keys(keys: &[T::AuthorityId]) {
if !keys.is_empty() {
assert!(Keys::<T>::get().is_empty(), "Keys are already initialized!");
Keys::<T>::put_ref(keys);
Keys::<T>::put(keys);
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions srml/babe/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -358,7 +358,7 @@ impl<T: Trait> Module<T> {
} else {
// move onto the next segment and update the index.
let segment_idx = segment_idx + 1;
<UnderConstruction>::insert(&segment_idx, vec![*vrf_output].as_ref());
<UnderConstruction>::insert(&segment_idx, &vec![*vrf_output]);
<SegmentIndex>::put(&segment_idx);
}
}
Expand Down Expand Up @@ -438,7 +438,7 @@ impl<T: Trait> Module<T> {
fn initialize_authorities(authorities: &[(AuthorityId, BabeAuthorityWeight)]) {
if !authorities.is_empty() {
assert!(Authorities::get().is_empty(), "Authorities are already initialized!");
Authorities::put_ref(authorities);
Authorities::put(authorities);
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions srml/collective/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -281,15 +281,15 @@ impl<T: Trait<I>, I: Instance> ChangeMembers<T::AccountId> for Module<T, I> {
}
);
}
<Members<T, I>>::put_ref(new);
<Members<T, I>>::put(new);
}
}

impl<T: Trait<I>, I: Instance> InitializeMembers<T::AccountId> for Module<T, I> {
fn initialize_members(members: &[T::AccountId]) {
if !members.is_empty() {
assert!(<Members<T, I>>::get().is_empty(), "Members are already initialized!");
<Members<T, I>>::put_ref(members);
<Members<T, I>>::put(members);
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion srml/contracts/src/wasm/code_cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ pub fn load<T: Trait>(
let original_code =
<PristineCode<T>>::get(code_hash).ok_or_else(|| "pristine code is not found")?;
prefab_module = prepare::prepare_contract::<Env>(&original_code, schedule)?;
<CodeStorage<T>>::insert(code_hash, prefab_module.clone());
<CodeStorage<T>>::insert(&code_hash, &prefab_module);
}
Ok(prefab_module)
}
18 changes: 9 additions & 9 deletions srml/democracy/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ use sr_primitives::{
traits::{Zero, Bounded, CheckedMul, CheckedDiv, EnsureOrigin, Hash, Dispatchable},
weights::SimpleDispatchInfo,
};
use codec::{Encode, Decode, Input, Output, Error};
use codec::{Ref, Encode, Decode, Input, Output, Error};
use support::{
decl_module, decl_storage, decl_event, ensure,
Parameter,
Expand Down Expand Up @@ -377,10 +377,10 @@ decl_module! {

let index = Self::public_prop_count();
PublicPropCount::put(index + 1);
<DepositOf<T>>::insert(index, (value, vec![who.clone()]));
<DepositOf<T>>::insert(index, (value, &[&who][..]));

let new_prop = (index, (*proposal).clone(), who);
<PublicProps<T>>::append_or_put([new_prop].into_iter());
let new_prop = (index, proposal, who);
<PublicProps<T>>::append_or_put(&[Ref::from(&new_prop)][..]);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If can be refactored and you think it is worth it, would be good to have a small issue for it after the PR is merged 👍

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ref from inside srml-support/storage/generator like in the implementation of linkedmap and map.
here it is legit. no super beautiful indeed.


Self::deposit_event(RawEvent::Proposed(index, value));
}
Expand Down Expand Up @@ -609,7 +609,7 @@ decl_module! {
#[weight = SimpleDispatchInfo::FixedNormal(500_000)]
pub fn delegate(origin, to: T::AccountId, conviction: Conviction) {
let who = ensure_signed(origin)?;
<Delegations<T>>::insert(who.clone(), (to.clone(), conviction));
<Delegations<T>>::insert(&who, (&to, conviction));
// Currency is locked indefinitely as long as it's delegated.
T::Currency::extend_lock(
DEMOCRACY_ID,
Expand Down Expand Up @@ -788,10 +788,10 @@ impl<T: Trait> Module<T> {
/// Actually enact a vote, if legit.
fn do_vote(who: T::AccountId, ref_index: ReferendumIndex, vote: Vote) -> Result {
ensure!(Self::is_active_referendum(ref_index), "vote given for invalid referendum.");
if !<VoteOf<T>>::exists(&(ref_index, who.clone())) {
<VotersFor<T>>::append_or_insert(ref_index, [who.clone()].into_iter());
if !<VoteOf<T>>::exists((ref_index, &who)) {
<VotersFor<T>>::append_or_insert(ref_index, &[&who][..]);
}
<VoteOf<T>>::insert(&(ref_index, who), vote);
<VoteOf<T>>::insert((ref_index, &who), vote);
Ok(())
}

Expand Down Expand Up @@ -929,7 +929,7 @@ impl<T: Trait> Module<T> {
} else {
<DispatchQueue<T>>::append_or_insert(
now + info.delay,
[Some((info.proposal, index))].into_iter()
&[Some((info.proposal, index))][..]
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think that makes no real difference, but okay.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

no it will compile with something like:

the trait bound `Iter<'_, std::option::Option<(<T as Trait>::Proposal, u32)>>: EncodeLike<std::vec::Vec<std::option::Option<(<T as Trait>::Proposal, u32)>>>` is not satisfied

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hmm at some point we should derive EncodeLike for standard iterator structures.

);
}
} else {
Expand Down
2 changes: 1 addition & 1 deletion srml/elections-phragmen/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -539,7 +539,7 @@ impl<T: Trait> Module<T> {

// sort and save the members.
new_members.sort();
<Members<T>>::put(new_members.clone());
<Members<T>>::put(&new_members);

// save the runners as-is
<RunnersUp<T>>::put(runners_up);
Expand Down
6 changes: 3 additions & 3 deletions srml/elections/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -816,7 +816,7 @@ impl<T: Trait> Module<T> {
if set_len + 1 == VOTER_SET_SIZE {
NextVoterSet::put(next + 1);
}
<Voters<T>>::append_or_insert(next, [Some(who.clone())].into_iter())
<Voters<T>>::append_or_insert(next, &[Some(who.clone())][..])
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You are still cloning.

Copy link
Contributor Author

@gui1117 gui1117 Oct 1, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes because satisfying both iterator constrained and EncodeLike<Vec<T>> is hard.

}
}

Expand Down Expand Up @@ -862,7 +862,7 @@ impl<T: Trait> Module<T> {

// initialize leaderboard.
let leaderboard_size = empty_seats + T::CarryCount::get() as usize;
<Leaderboard<T>>::put(vec![(Zero::zero(), T::AccountId::default()); leaderboard_size]);
<Leaderboard<T>>::put(vec![(BalanceOf::<T>::zero(), T::AccountId::default()); leaderboard_size]);

Self::deposit_event(RawEvent::TallyStarted(empty_seats as u32));
}
Expand Down Expand Up @@ -1027,7 +1027,7 @@ impl<T: Trait> Module<T> {
.chunks(APPROVAL_SET_SIZE)
.enumerate()
.for_each(|(index, slice)| <ApprovalsOf<T>>::insert(
(who.clone(), index as SetIndex), slice.to_vec())
(&who, index as SetIndex), slice)
);
}

Expand Down
2 changes: 1 addition & 1 deletion srml/grandpa/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -333,7 +333,7 @@ impl<T: Trait> Module<T> {
fn initialize_authorities(authorities: &[(AuthorityId, AuthorityWeight)]) {
if !authorities.is_empty() {
assert!(Authorities::get().is_empty(), "Authorities are already initialized!");
Authorities::put_ref(authorities);
Authorities::put(authorities);
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion srml/im-online/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -418,7 +418,7 @@ impl<T: Trait> Module<T> {
fn initialize_keys(keys: &[T::AuthorityId]) {
if !keys.is_empty() {
assert!(Keys::<T>::get().is_empty(), "Keys are already initialized!");
Keys::<T>::put_ref(keys);
Keys::<T>::put(keys);
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions srml/scored-pool/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ mod mock;
#[cfg(test)]
mod tests;

use codec::{Encode, Decode};
use codec::FullCodec;
use rstd::prelude::*;
use support::{
StorageValue, StorageMap, decl_module, decl_storage, decl_event, ensure,
Expand Down Expand Up @@ -117,7 +117,7 @@ pub trait Trait<I=DefaultInstance>: system::Trait {
type Currency: Currency<Self::AccountId> + ReservableCurrency<Self::AccountId>;

/// The score attributed to a member or candidate.
type Score: SimpleArithmetic + Clone + Copy + Default + Encode + Decode + MaybeSerializeDebug;
type Score: SimpleArithmetic + Clone + Copy + Default + FullCodec + MaybeSerializeDebug;

/// The overarching event type.
type Event: From<Event<Self, I>> + Into<<Self as system::Trait>::Event>;
Expand Down
6 changes: 3 additions & 3 deletions srml/session/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -640,15 +640,15 @@ impl<T: Trait> Module<T> {
}

fn key_owner(id: KeyTypeId, key_data: &[u8]) -> Option<T::ValidatorId> {
<KeyOwner<T>>::get(DEDUP_KEY_PREFIX, &(id, key_data.to_vec()))
<KeyOwner<T>>::get(DEDUP_KEY_PREFIX, (id, key_data))
}

fn put_key_owner(id: KeyTypeId, key_data: &[u8], v: &T::ValidatorId) {
<KeyOwner<T>>::insert(DEDUP_KEY_PREFIX, &(id, key_data.to_vec()), v)
<KeyOwner<T>>::insert(DEDUP_KEY_PREFIX, (id, key_data), v)
}

fn clear_key_owner(id: KeyTypeId, key_data: &[u8]) {
<KeyOwner<T>>::remove(DEDUP_KEY_PREFIX, &(id, key_data.to_vec()));
<KeyOwner<T>>::remove(DEDUP_KEY_PREFIX, (id, key_data));
}
}

Expand Down
4 changes: 2 additions & 2 deletions srml/staking/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -722,7 +722,7 @@ decl_module! {

// You're auto-bonded forever, here. We might improve this by only bonding when
// you actually validate/nominate and remove once you unbond __everything__.
<Bonded<T>>::insert(&stash, controller.clone());
<Bonded<T>>::insert(&stash, &controller);
<Payee<T>>::insert(&stash, payee);

let stash_balance = T::Currency::free_balance(&stash);
Expand Down Expand Up @@ -1339,7 +1339,7 @@ impl<T: Trait> Module<T> {
if exposure.total < slot_stake {
slot_stake = exposure.total;
}
<Stakers<T>>::insert(c.clone(), exposure.clone());
<Stakers<T>>::insert(&c, exposure.clone());
}

// Update slot stake.
Expand Down
2 changes: 1 addition & 1 deletion srml/support/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ edition = "2018"

[dependencies]
serde = { version = "1.0", optional = true, features = ["derive"] }
codec = { package = "parity-scale-codec", version = "1.0.5", default-features = false, features = ["derive"] }
codec = { package = "parity-scale-codec", version = "1.0.6", default-features = false, features = ["derive"] }
srml-metadata = { path = "../metadata", default-features = false }
rstd = { package = "sr-std", path = "../../core/sr-std", default-features = false }
runtime-io ={ package = "sr-io", path = "../../core/sr-io", default-features = false }
Expand Down
18 changes: 8 additions & 10 deletions srml/support/procedural/src/storage/transformation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -338,7 +338,7 @@ fn decl_store_extra_genesis(
<
#name<#struct_trait #instance> as
#scrate::storage::StorageValue<#typ>
>::put(&v);
>::put::<#typ>(v);
}}
},
DeclStorageTypeInfosKind::Map { key_type, is_linked, .. } => {
Expand All @@ -363,7 +363,7 @@ fn decl_store_extra_genesis(
<
#name<#struct_trait #instance> as
#scrate::storage::#map<#key_type, #typ>
>::insert(&k, &v);
>::insert::<#key_type, #typ>(k, v);
});
}}
},
Expand All @@ -384,7 +384,7 @@ fn decl_store_extra_genesis(
<
#name<#struct_trait #instance> as
#scrate::storage::StorageDoubleMap<#key1_type, #key2_type, #typ>
>::insert(&k1, &k2, &v);
>::insert::<#key1_type, #key2_type, #typ>(k1, k2, v);
});
}}
},
Expand Down Expand Up @@ -927,11 +927,11 @@ fn impl_store_fns(

quote!{
#( #[ #attrs ] )*
pub fn #get_fn<K: #scrate::rstd::borrow::Borrow<#key_type>>(key: K) -> #value_type {
pub fn #get_fn<K: #scrate::codec::EncodeLike<#key_type>>(key: K) -> #value_type {
<
#name<#struct_trait #instance> as
#scrate::storage::#map<#key_type, #typ>
>::get(key.borrow())
>::get(key)
}
}
}
Expand All @@ -946,12 +946,10 @@ fn impl_store_fns(
};

quote!{
pub fn #get_fn<KArg1, KArg2>(k1: &KArg1, k2: &KArg2) -> #value_type
pub fn #get_fn<KArg1, KArg2>(k1: KArg1, k2: KArg2) -> #value_type
where
#key1_type: #scrate::rstd::borrow::Borrow<KArg1>,
#key2_type: #scrate::rstd::borrow::Borrow<KArg2>,
KArg1: ?Sized + #scrate::codec::Encode,
KArg2: ?Sized + #scrate::codec::Encode,
KArg1: #scrate::codec::EncodeLike<#key1_type>,
KArg2: #scrate::codec::EncodeLike<#key2_type>,
{
<
#name<#struct_trait #instance> as
Expand Down
Loading