diff --git a/substrate/demo/executor/src/lib.rs b/substrate/demo/executor/src/lib.rs index 8781726089..4775194e65 100644 --- a/substrate/demo/executor/src/lib.rs +++ b/substrate/demo/executor/src/lib.rs @@ -42,7 +42,7 @@ mod tests { use runtime_io; use super::Executor; use substrate_executor::WasmExecutor; - use codec::{Slicable, Joiner}; + use codec::{Encode, Decode, Joiner}; use keyring::Keyring; use runtime_support::{Hashable, StorageValue, StorageMap}; use state_machine::{CodeExecutor, TestExternalities}; @@ -229,7 +229,7 @@ mod tests { UncheckedExtrinsic::new(extrinsic, signature) }).collect::>(); - let extrinsics_root = ordered_trie_root(extrinsics.iter().map(Slicable::encode)).0.into(); + let extrinsics_root = ordered_trie_root(extrinsics.iter().map(Encode::encode)).0.into(); let header = Header { parent_hash, diff --git a/substrate/demo/runtime/wasm/target/wasm32-unknown-unknown/release/demo_runtime.compact.wasm b/substrate/demo/runtime/wasm/target/wasm32-unknown-unknown/release/demo_runtime.compact.wasm index 2a2f6d8010..9c7f771263 100644 Binary files a/substrate/demo/runtime/wasm/target/wasm32-unknown-unknown/release/demo_runtime.compact.wasm and b/substrate/demo/runtime/wasm/target/wasm32-unknown-unknown/release/demo_runtime.compact.wasm differ diff --git a/substrate/demo/runtime/wasm/target/wasm32-unknown-unknown/release/demo_runtime.wasm b/substrate/demo/runtime/wasm/target/wasm32-unknown-unknown/release/demo_runtime.wasm index a80a02eb19..7d23bee2a8 100755 Binary files a/substrate/demo/runtime/wasm/target/wasm32-unknown-unknown/release/demo_runtime.wasm and b/substrate/demo/runtime/wasm/target/wasm32-unknown-unknown/release/demo_runtime.wasm differ diff --git a/substrate/polkadot/api/src/full.rs b/substrate/polkadot/api/src/full.rs index 7f340b53b6..7a5aeb31e7 100644 --- a/substrate/polkadot/api/src/full.rs +++ b/substrate/polkadot/api/src/full.rs @@ -93,7 +93,7 @@ impl> PolkadotApi for Client Result { use substrate_executor::error::ErrorKind as ExecErrorKind; - use codec::Slicable; + use codec::{Decode, Encode}; use runtime::Block as RuntimeBlock; let encoded = block.encode(); @@ -142,13 +142,13 @@ impl> PolkadotApi for Client) -> Result> { - use codec::Slicable; + use codec::{Encode, Decode}; with_runtime!(self, at, || { let extrinsics = ::runtime::inherent_extrinsics(timestamp, new_heads); extrinsics.into_iter() .map(|x| x.encode()) // get encoded representation - .map(|x| Slicable::decode(&mut &x[..])) // get byte-vec equivalent to extrinsic + .map(|x| Decode::decode(&mut &x[..])) // get byte-vec equivalent to extrinsic .map(|x| x.expect("UncheckedExtrinsic has encoded representation equivalent to Vec; qed")) .collect() }) diff --git a/substrate/polkadot/api/src/light.rs b/substrate/polkadot/api/src/light.rs index c0eb691e32..7e2015c0b7 100644 --- a/substrate/polkadot/api/src/light.rs +++ b/substrate/polkadot/api/src/light.rs @@ -19,7 +19,7 @@ use std::sync::Arc; use client::backend::{Backend, RemoteBackend}; use client::{Client, CallExecutor}; -use codec::Slicable; +use codec::Decode; use primitives::{AccountId, Block, BlockId, Hash, Index, SessionKey, Timestamp, UncheckedExtrinsic}; use runtime::Address; use primitives::parachain::{CandidateReceipt, DutyRoster, Id as ParaId}; diff --git a/substrate/polkadot/cli/src/lib.rs b/substrate/polkadot/cli/src/lib.rs index e0d9443d62..a4b1900d22 100644 --- a/substrate/polkadot/cli/src/lib.rs +++ b/substrate/polkadot/cli/src/lib.rs @@ -79,7 +79,7 @@ use std::net::SocketAddr; use std::path::{Path, PathBuf}; use substrate_telemetry::{init_telemetry, TelemetryConfig}; use polkadot_primitives::BlockId; -use codec::Slicable; +use codec::{Decode, Encode}; use client::BlockOrigin; use runtime_primitives::generic::SignedBlock; @@ -407,7 +407,7 @@ fn import_blocks(matches: &clap::ArgMatches, exit: E) -> error::Result<()> }; info!("Importing blocks"); - let count: u32 = Slicable::decode(&mut file).ok_or("Error reading file")?; + let count: u32 = Decode::decode(&mut file).ok_or("Error reading file")?; let mut block = 0; for _ in 0 .. count { if exit_recv.try_recv().is_ok() { diff --git a/substrate/polkadot/consensus/src/evaluation.rs b/substrate/polkadot/consensus/src/evaluation.rs index c7c4fe2c25..d843e79de4 100644 --- a/substrate/polkadot/consensus/src/evaluation.rs +++ b/substrate/polkadot/consensus/src/evaluation.rs @@ -18,7 +18,7 @@ use super::MAX_TRANSACTIONS_SIZE; -use codec::Slicable; +use codec::{Decode, Encode}; use polkadot_runtime::{Block as PolkadotGenericBlock, CheckedBlock}; use polkadot_primitives::{Block, Hash, BlockNumber, Timestamp}; use polkadot_primitives::parachain::Id as ParaId; @@ -78,13 +78,13 @@ pub fn evaluate_initial( ) -> Result { const MAX_TIMESTAMP_DRIFT: Timestamp = 60; - let encoded = Slicable::encode(proposal); + let encoded = Encode::encode(proposal); let proposal = PolkadotGenericBlock::decode(&mut &encoded[..]) .and_then(|b| CheckedBlock::new(b).ok()) .ok_or_else(|| ErrorKind::ProposalNotForPolkadot)?; let transactions_size = proposal.extrinsics.iter().fold(0, |a, tx| { - a + Slicable::encode(tx).len() + a + Encode::encode(tx).len() }); if transactions_size > MAX_TRANSACTIONS_SIZE { diff --git a/substrate/polkadot/consensus/src/lib.rs b/substrate/polkadot/consensus/src/lib.rs index 7edc78ea11..4ad6ba9544 100644 --- a/substrate/polkadot/consensus/src/lib.rs +++ b/substrate/polkadot/consensus/src/lib.rs @@ -65,7 +65,7 @@ use std::collections::{HashMap, HashSet}; use std::sync::Arc; use std::time::{Duration, Instant}; -use codec::Slicable; +use codec::{Decode, Encode}; use polkadot_api::PolkadotApi; use polkadot_primitives::{Hash, Block, BlockId, BlockNumber, Header, Timestamp, SessionKey}; use polkadot_primitives::parachain::{Id as ParaId, Chain, DutyRoster, BlockData, Extrinsic as ParachainExtrinsic, CandidateReceipt, CandidateSignature}; @@ -710,7 +710,7 @@ impl CreateProposal where C: PolkadotApi { .join(", ") ); - let substrate_block = Slicable::decode(&mut polkadot_block.encode().as_slice()) + let substrate_block = Decode::decode(&mut polkadot_block.encode().as_slice()) .expect("polkadot blocks defined to serialize to substrate blocks correctly; qed"); // TODO: full re-evaluation diff --git a/substrate/polkadot/network/src/lib.rs b/substrate/polkadot/network/src/lib.rs index fc143e92af..fe320eeecc 100644 --- a/substrate/polkadot/network/src/lib.rs +++ b/substrate/polkadot/network/src/lib.rs @@ -47,7 +47,7 @@ mod collator_pool; mod router; pub mod consensus; -use codec::Slicable; +use codec::{Decode, Encode}; use futures::sync::oneshot; use parking_lot::Mutex; use polkadot_consensus::{Statement, SignedStatement, GenericStatement}; @@ -81,25 +81,25 @@ pub struct Status { collating_for: Option<(AccountId, ParaId)>, } -impl Slicable for Status { - fn encode(&self) -> Vec { - let mut v = Vec::new(); +impl Encode for Status { + fn encode_to(&self, dest: &mut T) { match self.collating_for { Some(ref details) => { - v.push(1); - details.using_encoded(|s| v.extend(s)); + dest.push_byte(1); + dest.push(details); } None => { - v.push(0); + dest.push_byte(0); } } - v } +} - fn decode(input: &mut I) -> Option { +impl Decode for Status { + fn decode(input: &mut I) -> Option { let collating_for = match input.read_byte()? { 0 => None, - 1 => Some(Slicable::decode(input)?), + 1 => Some(Decode::decode(input)?), _ => return None, }; Some(Status { collating_for }) diff --git a/substrate/polkadot/network/src/tests.rs b/substrate/polkadot/network/src/tests.rs index 5e3eca4651..95c24ae071 100644 --- a/substrate/polkadot/network/src/tests.rs +++ b/substrate/polkadot/network/src/tests.rs @@ -23,7 +23,7 @@ use polkadot_consensus::GenericStatement; use polkadot_primitives::{Block, Hash, SessionKey}; use polkadot_primitives::parachain::{CandidateReceipt, HeadData, BlockData}; use substrate_primitives::H512; -use codec::Slicable; +use codec::Encode; use substrate_network::{PeerId, PeerInfo, ClientHandle, Context, message::Message as SubstrateMessage, message::Role, specialization::Specialization, generic_message::Message as GenericMessage}; use std::sync::Arc; diff --git a/substrate/polkadot/parachain/src/lib.rs b/substrate/polkadot/parachain/src/lib.rs index 2f3c064f33..7af248fdbe 100644 --- a/substrate/polkadot/parachain/src/lib.rs +++ b/substrate/polkadot/parachain/src/lib.rs @@ -61,7 +61,7 @@ extern crate error_chain; #[cfg(not(feature = "std"))] use alloc::vec::Vec; -use codec::Slicable; +use codec::{Encode, Decode, Input, Output}; #[cfg(feature = "std")] pub mod wasm; @@ -77,20 +77,18 @@ pub struct ValidationParams { pub parent_head: Vec, } -impl Slicable for ValidationParams { - fn encode(&self) -> Vec { - let mut v = Vec::new(); - - self.block_data.using_encoded(|s| v.extend(s)); - self.parent_head.using_encoded(|s| v.extend(s)); - - v +impl Encode for ValidationParams { + fn encode_to(&self, dest: &mut T) { + dest.push(&self.block_data); + dest.push(&self.parent_head); } +} - fn decode(input: &mut I) -> Option { +impl Decode for ValidationParams { + fn decode(input: &mut I) -> Option { Some(ValidationParams { - block_data: Slicable::decode(input)?, - parent_head: Slicable::decode(input)?, + block_data: Decode::decode(input)?, + parent_head: Decode::decode(input)?, }) } } @@ -104,14 +102,16 @@ pub struct ValidationResult { pub head_data: Vec } -impl Slicable for ValidationResult { - fn encode(&self) -> Vec { - self.head_data.encode() +impl Encode for ValidationResult { + fn encode_to(&self, dest: &mut T) { + dest.push(&self.head_data); } +} - fn decode(input: &mut I) -> Option { +impl Decode for ValidationResult { + fn decode(input: &mut I) -> Option { Some(ValidationResult { - head_data: Slicable::decode(input)?, + head_data: Decode::decode(input)?, }) } } diff --git a/substrate/polkadot/parachain/src/wasm.rs b/substrate/polkadot/parachain/src/wasm.rs index a16383acb9..494f176a3d 100644 --- a/substrate/polkadot/parachain/src/wasm.rs +++ b/substrate/polkadot/parachain/src/wasm.rs @@ -20,7 +20,7 @@ //! Assuming the parameters are correct, this module provides a wrapper around //! a WASM VM for re-execution of a parachain candidate. -use codec::Slicable; +use codec::{Decode, Encode}; use wasmi::{self, Module, ModuleInstance, MemoryInstance, MemoryDescriptor, MemoryRef, ModuleImportResolver}; use wasmi::{memory_units, RuntimeValue}; diff --git a/substrate/polkadot/parachain/test-chains/basic_add/src/lib.rs b/substrate/polkadot/parachain/test-chains/basic_add/src/lib.rs index 7518072a1d..ff9006c8c2 100644 --- a/substrate/polkadot/parachain/test-chains/basic_add/src/lib.rs +++ b/substrate/polkadot/parachain/test-chains/basic_add/src/lib.rs @@ -33,7 +33,7 @@ extern crate wee_alloc; extern crate tiny_keccak; extern crate pwasm_libc; -use parachain::codec::{Slicable, Input}; +use parachain::codec::{Decode, Encode, Input, Output}; #[cfg(not(feature = "std"))] mod wasm; @@ -41,9 +41,6 @@ mod wasm; #[cfg(not(feature = "std"))] pub use wasm::*; -#[cfg(not(feature = "std"))] -use alloc::vec::Vec; - // Define global allocator. #[cfg(not(feature = "std"))] #[global_allocator] @@ -60,22 +57,20 @@ struct HeadData { post_state: [u8; 32], } -impl Slicable for HeadData { - fn encode(&self) -> Vec { - let mut v = Vec::new(); - - self.number.using_encoded(|s| v.extend(s)); - self.parent_hash.using_encoded(|s| v.extend(s)); - self.post_state.using_encoded(|s| v.extend(s)); - - v +impl Encode for HeadData { + fn encode_to(&self, dest: &mut T) { + dest.push(&self.number); + dest.push(&self.parent_hash); + dest.push(&self.post_state); } +} +impl Decode for HeadData { fn decode(input: &mut I) -> Option { Some(HeadData { - number: Slicable::decode(input)?, - parent_hash: Slicable::decode(input)?, - post_state: Slicable::decode(input)?, + number: Decode::decode(input)?, + parent_hash: Decode::decode(input)?, + post_state: Decode::decode(input)?, }) } } @@ -89,20 +84,18 @@ struct BlockData { add: u64, } -impl Slicable for BlockData { - fn encode(&self) -> Vec { - let mut v = Vec::new(); - - self.state.using_encoded(|s| v.extend(s)); - self.add.using_encoded(|s| v.extend(s)); - - v +impl Encode for BlockData { + fn encode_to(&self, dest: &mut T) { + dest.push(&self.state); + dest.push(&self.add); } +} +impl Decode for BlockData { fn decode(input: &mut I) -> Option { Some(BlockData { - state: Slicable::decode(input)?, - add: Slicable::decode(input)?, + state: Decode::decode(input)?, + add: Decode::decode(input)?, }) } } diff --git a/substrate/polkadot/parachain/test-chains/basic_add/src/wasm.rs b/substrate/polkadot/parachain/test-chains/basic_add/src/wasm.rs index 38a8aa81b5..1007113188 100644 --- a/substrate/polkadot/parachain/test-chains/basic_add/src/wasm.rs +++ b/substrate/polkadot/parachain/test-chains/basic_add/src/wasm.rs @@ -18,7 +18,7 @@ use core::{intrinsics, panic, alloc}; use parachain::{self, ValidationResult}; -use parachain::codec::Slicable; +use parachain::codec::{Encode, Decode}; use super::{HeadData, BlockData}; #[panic_implementation] diff --git a/substrate/polkadot/parachain/tests/basic_add.rs b/substrate/polkadot/parachain/tests/basic_add.rs index c5fbe467a4..566a6efc3f 100644 --- a/substrate/polkadot/parachain/tests/basic_add.rs +++ b/substrate/polkadot/parachain/tests/basic_add.rs @@ -20,7 +20,7 @@ extern crate polkadot_parachain as parachain; extern crate tiny_keccak; use parachain::ValidationParams; -use parachain::codec::{Slicable, Input}; +use parachain::codec::{Decode, Encode, Input, Output}; // Head data for this parachain. #[derive(Default, Clone)] @@ -33,22 +33,20 @@ struct HeadData { post_state: [u8; 32], } -impl Slicable for HeadData { - fn encode(&self) -> Vec { - let mut v = Vec::new(); - - self.number.using_encoded(|s| v.extend(s)); - self.parent_hash.using_encoded(|s| v.extend(s)); - self.post_state.using_encoded(|s| v.extend(s)); - - v +impl Encode for HeadData { + fn encode_to(&self, dest: &mut T) { + dest.push(&self.number); + dest.push(&self.parent_hash); + dest.push(&self.post_state); } +} +impl Decode for HeadData { fn decode(input: &mut I) -> Option { Some(HeadData { - number: Slicable::decode(input)?, - parent_hash: Slicable::decode(input)?, - post_state: Slicable::decode(input)?, + number: Decode::decode(input)?, + parent_hash: Decode::decode(input)?, + post_state: Decode::decode(input)?, }) } } @@ -62,20 +60,18 @@ struct BlockData { add: u64, } -impl Slicable for BlockData { - fn encode(&self) -> Vec { - let mut v = Vec::new(); - - self.state.using_encoded(|s| v.extend(s)); - self.add.using_encoded(|s| v.extend(s)); - - v +impl Encode for BlockData { + fn encode_to(&self, dest: &mut T) { + dest.push(&self.state); + dest.push(&self.add); } +} +impl Decode for BlockData { fn decode(input: &mut I) -> Option { Some(BlockData { - state: Slicable::decode(input)?, - add: Slicable::decode(input)?, + state: Decode::decode(input)?, + add: Decode::decode(input)?, }) } } diff --git a/substrate/polkadot/primitives/src/lib.rs b/substrate/polkadot/primitives/src/lib.rs index f7861a8337..83118799bb 100644 --- a/substrate/polkadot/primitives/src/lib.rs +++ b/substrate/polkadot/primitives/src/lib.rs @@ -42,7 +42,7 @@ use primitives::bytes; use rstd::prelude::*; use runtime_primitives::traits::BlakeTwo256; use runtime_primitives::generic; -use codec::{Input, Slicable}; +use codec::{Encode, Decode, Input, Output}; pub mod parachain; @@ -109,12 +109,14 @@ pub type BlockId = generic::BlockId; #[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug))] pub struct Log(#[cfg_attr(feature = "std", serde(with="bytes"))] pub Vec); -impl Slicable for Log { +impl Decode for Log { fn decode(input: &mut I) -> Option { Vec::::decode(input).map(Log) } +} - fn using_encoded R>(&self, f: F) -> R { - self.0.using_encoded(f) +impl Encode for Log { + fn encode_to(&self, dest: &mut T) { + self.0.encode_to(dest) } } diff --git a/substrate/polkadot/primitives/src/parachain.rs b/substrate/polkadot/primitives/src/parachain.rs index bbf9591ee0..31ba646328 100644 --- a/substrate/polkadot/primitives/src/parachain.rs +++ b/substrate/polkadot/primitives/src/parachain.rs @@ -16,7 +16,7 @@ //! Polkadot parachain types. -use codec::{Slicable, Input}; +use codec::{Encode, Decode, Input, Output}; use rstd::prelude::*; use rstd::cmp::Ordering; use super::Hash; @@ -47,11 +47,13 @@ impl Id { } } -impl Slicable for Id { +impl Decode for Id { fn decode(input: &mut I) -> Option { u32::decode(input).map(Id) } +} +impl Encode for Id { fn using_encoded R>(&self, f: F) -> R { self.0.using_encoded(f) } @@ -67,30 +69,26 @@ pub enum Chain { Parachain(Id), } -impl Slicable for Chain { +impl Decode for Chain { fn decode(input: &mut I) -> Option { let disc = input.read_byte()?; match disc { 0 => Some(Chain::Relay), - 1 => Some(Chain::Parachain(Slicable::decode(input)?)), + 1 => Some(Chain::Parachain(Decode::decode(input)?)), _ => None, } } +} - fn encode(&self) -> Vec { - let mut v = Vec::new(); +impl Encode for Chain { + fn encode_to(&self, dest: &mut T) { match *self { - Chain::Relay => { v.push(0); } + Chain::Relay => { dest.push_byte(0); } Chain::Parachain(id) => { - v.push(1u8); - id.using_encoded(|s| v.extend(s)); + dest.push_byte(1u8); + dest.push(&id); } } - v - } - - fn using_encoded R>(&self, f: F) -> R { - f(&self.encode().as_slice()) } } @@ -105,25 +103,19 @@ pub struct DutyRoster { pub guarantor_duty: Vec, } -impl Slicable for DutyRoster { +impl Decode for DutyRoster { fn decode(input: &mut I) -> Option { Some(DutyRoster { - validator_duty: Slicable::decode(input)?, - guarantor_duty: Slicable::decode(input)?, + validator_duty: Decode::decode(input)?, + guarantor_duty: Decode::decode(input)?, }) } +} - fn encode(&self) -> Vec { - let mut v = Vec::new(); - - v.extend(self.validator_duty.encode()); - v.extend(self.guarantor_duty.encode()); - - v - } - - fn using_encoded R>(&self, f: F) -> R { - f(&self.encode().as_slice()) +impl Encode for DutyRoster { + fn encode_to(&self, dest: &mut T) { + dest.push(&self.validator_duty); + dest.push(&self.guarantor_duty); } } @@ -158,32 +150,30 @@ pub struct CandidateReceipt { pub block_data_hash: Hash, } -impl Slicable for CandidateReceipt { - fn encode(&self) -> Vec { - let mut v = Vec::new(); - - self.parachain_index.using_encoded(|s| v.extend(s)); - self.collator.using_encoded(|s| v.extend(s)); - self.signature.using_encoded(|s| v.extend(s)); - self.head_data.0.using_encoded(|s| v.extend(s)); - self.balance_uploads.using_encoded(|s| v.extend(s)); - self.egress_queue_roots.using_encoded(|s| v.extend(s)); - self.fees.using_encoded(|s| v.extend(s)); - self.block_data_hash.using_encoded(|s| v.extend(s)); - - v +impl Encode for CandidateReceipt { + fn encode_to(&self, dest: &mut T) { + dest.push(&self.parachain_index); + dest.push(&self.collator); + dest.push(&self.signature); + dest.push(&self.head_data.0); + dest.push(&self.balance_uploads); + dest.push(&self.egress_queue_roots); + dest.push(&self.fees); + dest.push(&self.block_data_hash); } +} +impl Decode for CandidateReceipt { fn decode(input: &mut I) -> Option { Some(CandidateReceipt { - parachain_index: Slicable::decode(input)?, - collator: Slicable::decode(input)?, - signature: Slicable::decode(input)?, - head_data: Slicable::decode(input).map(HeadData)?, - balance_uploads: Slicable::decode(input)?, - egress_queue_roots: Slicable::decode(input)?, - fees: Slicable::decode(input)?, - block_data_hash: Slicable::decode(input)?, + parachain_index: Decode::decode(input)?, + collator: Decode::decode(input)?, + signature: Decode::decode(input)?, + head_data: Decode::decode(input).map(HeadData)?, + balance_uploads: Decode::decode(input)?, + egress_queue_roots: Decode::decode(input)?, + fees: Decode::decode(input)?, + block_data_hash: Decode::decode(input)?, }) } } @@ -283,13 +273,15 @@ pub struct ValidationCode(#[cfg_attr(feature = "std", serde(with="bytes"))] pub #[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug))] pub struct Activity(#[cfg_attr(feature = "std", serde(with="bytes"))] pub Vec); -impl Slicable for Activity { +impl Decode for Activity { fn decode(input: &mut I) -> Option { Vec::::decode(input).map(Activity) } +} - fn using_encoded R>(&self, f: F) -> R { - self.0.using_encoded(f) +impl Encode for Activity { + fn encode_to(&self, dest: &mut T) { + self.0.encode_to(dest) } } diff --git a/substrate/polkadot/runtime/src/lib.rs b/substrate/polkadot/runtime/src/lib.rs index b74e5754e0..9ccafe92a9 100644 --- a/substrate/polkadot/runtime/src/lib.rs +++ b/substrate/polkadot/runtime/src/lib.rs @@ -257,7 +257,7 @@ pub mod api { mod tests { use super::*; use substrate_primitives as primitives; - use ::codec::Slicable; + use codec::{Encode, Decode}; use substrate_primitives::hexdisplay::HexDisplay; use substrate_serializer as ser; use runtime_primitives::traits::{Digest as DigestT, Header as HeaderT}; @@ -376,7 +376,7 @@ mod tests { // df0f0200 // 0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 - let v = Slicable::encode(&tx); + let v = Encode::encode(&tx); assert_eq!(&v[..], &hex!["6f000000ff0101010101010101010101010101010101010101010101010101010101010101e70300000300df0f02000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"][..]); println!("{}", HexDisplay::from(&v)); assert_eq!(UncheckedExtrinsic::decode(&mut &v[..]).unwrap(), tx); @@ -393,7 +393,7 @@ mod tests { )) ))), }; - let v = Slicable::encode(&xt); + let v = Encode::encode(&xt); assert_eq!(Extrinsic::decode(&mut &v[..]).unwrap(), xt); } diff --git a/substrate/polkadot/runtime/src/parachains.rs b/substrate/polkadot/runtime/src/parachains.rs index 809ff0396b..bd62f9895e 100644 --- a/substrate/polkadot/runtime/src/parachains.rs +++ b/substrate/polkadot/runtime/src/parachains.rs @@ -17,7 +17,7 @@ //! Main parachains logic. For now this is just the determination of which validators do what. use rstd::prelude::*; -use codec::Slicable; +use codec::Decode; use runtime_primitives::traits::{Hash, BlakeTwo256, Executable, RefInto, MaybeEmpty}; use primitives::parachain::{Id, Chain, DutyRoster, CandidateReceipt}; @@ -217,7 +217,7 @@ impl runtime_primitives::BuildStorage for GenesisConfig fn build_storage(mut self) -> ::std::result::Result { use std::collections::HashMap; use runtime_io::twox_128; - use codec::Slicable; + use codec::Encode; self.parachains.sort_unstable_by_key(|&(ref id, _)| id.clone()); self.parachains.dedup_by_key(|&mut (ref id, _)| id.clone()); diff --git a/substrate/polkadot/runtime/wasm/target/wasm32-unknown-unknown/release/polkadot_runtime.compact.wasm b/substrate/polkadot/runtime/wasm/target/wasm32-unknown-unknown/release/polkadot_runtime.compact.wasm index 37e839bedc..6ce4978078 100644 Binary files a/substrate/polkadot/runtime/wasm/target/wasm32-unknown-unknown/release/polkadot_runtime.compact.wasm and b/substrate/polkadot/runtime/wasm/target/wasm32-unknown-unknown/release/polkadot_runtime.compact.wasm differ diff --git a/substrate/polkadot/runtime/wasm/target/wasm32-unknown-unknown/release/polkadot_runtime.wasm b/substrate/polkadot/runtime/wasm/target/wasm32-unknown-unknown/release/polkadot_runtime.wasm index 2d63fb063f..6b4f396ef9 100755 Binary files a/substrate/polkadot/runtime/wasm/target/wasm32-unknown-unknown/release/polkadot_runtime.wasm and b/substrate/polkadot/runtime/wasm/target/wasm32-unknown-unknown/release/polkadot_runtime.wasm differ diff --git a/substrate/polkadot/service/src/lib.rs b/substrate/polkadot/service/src/lib.rs index 5c155a098e..a9952261a0 100644 --- a/substrate/polkadot/service/src/lib.rs +++ b/substrate/polkadot/service/src/lib.rs @@ -43,7 +43,7 @@ pub mod chain_spec; use std::sync::Arc; use std::collections::HashMap; -use codec::Slicable; +use codec::Encode; use transaction_pool::TransactionPool; use polkadot_api::{PolkadotApi, light::RemotePolkadotApiWrapper}; use polkadot_primitives::{Block, BlockId, Hash}; @@ -265,7 +265,7 @@ impl network::TransactionPool for TransactionPoolAdapter Some(*xt.hash()), diff --git a/substrate/polkadot/statement-table/src/generic.rs b/substrate/polkadot/statement-table/src/generic.rs index 8e7fa48e2e..56740288f8 100644 --- a/substrate/polkadot/statement-table/src/generic.rs +++ b/substrate/polkadot/statement-table/src/generic.rs @@ -31,7 +31,7 @@ use std::collections::hash_map::{HashMap, Entry}; use std::hash::Hash; use std::fmt::Debug; -use codec::{Slicable, Input}; +use codec::{Decode, Encode, Input, Output}; /// Context for the statement table. pub trait Context { @@ -97,44 +97,43 @@ enum StatementKind { Available = 4, } -impl Slicable for Statement { - fn encode(&self) -> Vec { - let mut v = Vec::new(); +impl Encode for Statement { + fn encode_to(&self, dest: &mut T) { match *self { Statement::Candidate(ref candidate) => { - v.push(StatementKind::Candidate as u8); - candidate.using_encoded(|s| v.extend(s)); + dest.push_byte(StatementKind::Candidate as u8); + dest.push(candidate); } Statement::Valid(ref digest) => { - v.push(StatementKind::Valid as u8); - digest.using_encoded(|s| v.extend(s)); + dest.push_byte(StatementKind::Valid as u8); + dest.push(digest); } Statement::Invalid(ref digest) => { - v.push(StatementKind::Invalid as u8); - digest.using_encoded(|s| v.extend(s)); + dest.push_byte(StatementKind::Invalid as u8); + dest.push(digest); } Statement::Available(ref digest) => { - v.push(StatementKind::Available as u8); - digest.using_encoded(|s| v.extend(s)); + dest.push_byte(StatementKind::Available as u8); + dest.push(digest); } } - - v } +} +impl Decode for Statement { fn decode(value: &mut I) -> Option { match value.read_byte() { Some(x) if x == StatementKind::Candidate as u8 => { - Slicable::decode(value).map(Statement::Candidate) + Decode::decode(value).map(Statement::Candidate) } Some(x) if x == StatementKind::Valid as u8 => { - Slicable::decode(value).map(Statement::Valid) + Decode::decode(value).map(Statement::Valid) } Some(x) if x == StatementKind::Invalid as u8 => { - Slicable::decode(value).map(Statement::Invalid) + Decode::decode(value).map(Statement::Invalid) } Some(x) if x == StatementKind::Available as u8 => { - Slicable::decode(value).map(Statement::Available) + Decode::decode(value).map(Statement::Available) } _ => None, } diff --git a/substrate/polkadot/transaction-pool/src/lib.rs b/substrate/polkadot/transaction-pool/src/lib.rs index ee0b506f6f..75a4eb0dac 100644 --- a/substrate/polkadot/transaction-pool/src/lib.rs +++ b/substrate/polkadot/transaction-pool/src/lib.rs @@ -43,7 +43,7 @@ use std::{ sync::Arc, }; -use codec::Slicable; +use codec::{Decode, Encode}; use extrinsic_pool::{Pool, Listener, txpool::{self, Readiness, scoring::{Change, Choice}}}; use extrinsic_pool::api::{ExtrinsicPool, EventStream}; use polkadot_api::PolkadotApi; @@ -75,7 +75,7 @@ impl VerifiedTransaction { /// Convert to primitive unchecked extrinsic. pub fn primitive_extrinsic(&self) -> ::primitives::UncheckedExtrinsic { - Slicable::decode(&mut self.as_transaction().encode().as_slice()) + Decode::decode(&mut self.as_transaction().encode().as_slice()) .expect("UncheckedExtrinsic shares repr with Vec; qed") } @@ -418,7 +418,7 @@ mod tests { use std::sync::{atomic::{self, AtomicBool}, Arc}; use super::TransactionPool; use substrate_keyring::Keyring::{self, *}; - use codec::Slicable; + use codec::{Decode, Encode}; use polkadot_api::{PolkadotApi, BlockBuilder, Result}; use primitives::{AccountId, AccountIndex, Block, BlockId, Hash, Index, SessionKey, Timestamp, UncheckedExtrinsic as FutureProofUncheckedExtrinsic}; diff --git a/substrate/substrate/bft/src/lib.rs b/substrate/substrate/bft/src/lib.rs index fbebc7ec3f..28c26fe21a 100644 --- a/substrate/substrate/bft/src/lib.rs +++ b/substrate/substrate/bft/src/lib.rs @@ -57,7 +57,7 @@ use std::mem; use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; -use codec::Slicable; +use codec::Encode; use ed25519::LocalizedSignature; use runtime_primitives::generic::BlockId; use runtime_primitives::traits::{Block, Header}; @@ -506,7 +506,7 @@ fn check_justification_signed_message(authorities: &[AuthorityId], message: & pub fn check_justification(authorities: &[AuthorityId], parent: B::Hash, just: UncheckedJustification) -> Result, UncheckedJustification> { - let message = Slicable::encode(&PrimitiveMessage:: { + let message = Encode::encode(&PrimitiveMessage:: { parent, action: PrimitiveAction::Commit(just.0.round_number as u32, just.0.digest.clone()), }); @@ -521,7 +521,7 @@ pub fn check_justification(authorities: &[AuthorityId], parent: B::Has pub fn check_prepare_justification(authorities: &[AuthorityId], parent: B::Hash, just: UncheckedJustification) -> Result, UncheckedJustification> { - let message = Slicable::encode(&PrimitiveMessage:: { + let message = Encode::encode(&PrimitiveMessage:: { parent, action: PrimitiveAction::Prepare(just.0.round_number as u32, just.0.digest.clone()), }); @@ -573,7 +573,7 @@ fn check_action(action: PrimitiveAction, parent_hash: &B:: action, }; - let message = Slicable::encode(&primitive); + let message = Encode::encode(&primitive); if ed25519::verify_strong(&sig.signature, &message, &sig.signer) { Ok(()) } else { @@ -591,7 +591,7 @@ pub fn sign_message(message: Message, key: &ed25519::Pair, action, }; - let to_sign = Slicable::encode(&primitive); + let to_sign = Encode::encode(&primitive); LocalizedSignature { signer: signer.clone(), signature: key.sign(&to_sign), diff --git a/substrate/substrate/client/db/src/lib.rs b/substrate/substrate/client/db/src/lib.rs index 1e043dfd63..bdfd5ce522 100644 --- a/substrate/substrate/client/db/src/lib.rs +++ b/substrate/substrate/client/db/src/lib.rs @@ -43,7 +43,7 @@ mod utils; use std::sync::Arc; use std::path::PathBuf; -use codec::Slicable; +use codec::{Decode, Encode}; use kvdb::{KeyValueDB, DBTransaction}; use memorydb::MemoryDB; use parking_lot::RwLock; @@ -187,7 +187,7 @@ impl client::blockchain::HeaderBackend for BlockchainDb client::blockchain::Backend for BlockchainDb { fn body(&self, id: BlockId) -> Result>, client::error::Error> { match read_db(&*self.db, columns::BLOCK_INDEX, columns::BODY, id)? { - Some(body) => match Slicable::decode(&mut &body[..]) { + Some(body) => match Decode::decode(&mut &body[..]) { Some(body) => Ok(Some(body)), None => return Err(client::error::ErrorKind::Backend("Error decoding body".into()).into()), } @@ -197,7 +197,7 @@ impl client::blockchain::Backend for BlockchainDb { fn justification(&self, id: BlockId) -> Result>, client::error::Error> { match read_db(&*self.db, columns::BLOCK_INDEX, columns::JUSTIFICATION, id)? { - Some(justification) => match Slicable::decode(&mut &justification[..]) { + Some(justification) => match Decode::decode(&mut &justification[..]) { Some(justification) => Ok(Some(justification)), None => return Err(client::error::ErrorKind::Backend("Error decoding justification".into()).into()), } diff --git a/substrate/substrate/client/db/src/light.rs b/substrate/substrate/client/db/src/light.rs index 8888026ed2..9ae3cefe61 100644 --- a/substrate/substrate/client/db/src/light.rs +++ b/substrate/substrate/client/db/src/light.rs @@ -25,7 +25,7 @@ use client::blockchain::{BlockStatus, HeaderBackend as BlockchainHeaderBackend, Info as BlockchainInfo}; use client::error::{ErrorKind as ClientErrorKind, Result as ClientResult}; use client::light::blockchain::Storage as LightBlockchainStorage; -use codec::Slicable; +use codec::{Decode, Encode}; use primitives::AuthorityId; use runtime_primitives::generic::BlockId; use runtime_primitives::traits::{Block as BlockT, Header as HeaderT, Hash, HashFor, Zero}; diff --git a/substrate/substrate/client/db/src/utils.rs b/substrate/substrate/client/db/src/utils.rs index defe523d95..46d2ec0973 100644 --- a/substrate/substrate/client/db/src/utils.rs +++ b/substrate/substrate/client/db/src/utils.rs @@ -23,7 +23,7 @@ use kvdb::{self, KeyValueDB, DBTransaction}; use kvdb_rocksdb::{Database, DatabaseConfig}; use client; -use codec::Slicable; +use codec::Decode; use hashdb::DBValue; use runtime_primitives::generic::BlockId; use runtime_primitives::traits::{As, Block as BlockT, Header as HeaderT, Hash, HashFor, Zero}; diff --git a/substrate/substrate/client/src/block_builder.rs b/substrate/substrate/client/src/block_builder.rs index c5695ce4e4..bb50df28fe 100644 --- a/substrate/substrate/client/src/block_builder.rs +++ b/substrate/substrate/client/src/block_builder.rs @@ -17,7 +17,7 @@ //! Utility struct to build a block. use std::vec::Vec; -use codec::Slicable; +use codec::{Decode, Encode}; use state_machine::{self, native_when_possible}; use runtime_primitives::traits::{Header as HeaderT, Hash, Block as BlockT, One, HashFor}; use runtime_primitives::generic::BlockId; @@ -103,12 +103,12 @@ impl BlockBuilder where &[], native_when_possible(), )?; - self.header = <::Header as Slicable>::decode(&mut &output[..]) + self.header = <::Header as Decode>::decode(&mut &output[..]) .expect("Header came straight out of runtime so must be valid"); debug_assert_eq!( self.header.extrinsics_root().clone(), - HashFor::::ordered_trie_root(self.extrinsics.iter().map(Slicable::encode)), + HashFor::::ordered_trie_root(self.extrinsics.iter().map(Encode::encode)), ); Ok(::new(self.header, self.extrinsics)) diff --git a/substrate/substrate/client/src/client.rs b/substrate/substrate/client/src/client.rs index 6b90c28b41..8103128008 100644 --- a/substrate/substrate/client/src/client.rs +++ b/substrate/substrate/client/src/client.rs @@ -24,7 +24,7 @@ use runtime_primitives::{bft::Justification, generic::{BlockId, SignedBlock, Blo use runtime_primitives::traits::{Block as BlockT, Header as HeaderT, Zero, One, As}; use runtime_primitives::BuildStorage; use primitives::storage::{StorageKey, StorageData}; -use codec::Slicable; +use codec::Decode; use state_machine::{Ext, OverlayedChanges, Backend as StateBackend, CodeExecutor, ExecutionStrategy, ExecutionManager}; use backend::{self, BlockImportOperation}; @@ -523,7 +523,7 @@ impl ChainHead for Client #[cfg(test)] mod tests { use super::*; - use codec::Slicable; + use codec::Encode; use keyring::Keyring; use test_client::{self, TestClient}; use test_client::client::BlockOrigin; diff --git a/substrate/substrate/client/src/genesis.rs b/substrate/substrate/client/src/genesis.rs index 9c4c8a96bd..8593357fde 100644 --- a/substrate/substrate/client/src/genesis.rs +++ b/substrate/substrate/client/src/genesis.rs @@ -42,7 +42,7 @@ pub fn construct_genesis_block< #[cfg(test)] mod tests { use super::*; - use codec::{Slicable, Joiner}; + use codec::{Encode, Decode, Joiner}; use keyring::Keyring; use executor::WasmExecutor; use state_machine::{execute, OverlayedChanges, ExecutionStrategy}; @@ -68,7 +68,7 @@ mod tests { Extrinsic { transfer: tx, signature } }).collect::>(); - let extrinsics_root = ordered_trie_root(transactions.iter().map(Slicable::encode)).0.into(); + let extrinsics_root = ordered_trie_root(transactions.iter().map(Encode::encode)).0.into(); println!("root before: {:?}", extrinsics_root); let mut header = Header { diff --git a/substrate/substrate/client/src/light/call_executor.rs b/substrate/substrate/client/src/light/call_executor.rs index 6ac064bd01..9c94d4fdb6 100644 --- a/substrate/substrate/client/src/light/call_executor.rs +++ b/substrate/substrate/client/src/light/call_executor.rs @@ -30,7 +30,7 @@ use call_executor::{CallExecutor, CallResult}; use error::{Error as ClientError, ErrorKind as ClientErrorKind, Result as ClientResult}; use light::fetcher::{Fetcher, RemoteCallRequest}; use executor::RuntimeVersion; -use codec::Slicable; +use codec::Decode; /// Call executor that executes methods on remote node, querying execution proof /// and checking proof by re-executing locally. diff --git a/substrate/substrate/codec/src/slicable.rs b/substrate/substrate/codec/src/codec.rs similarity index 70% rename from substrate/substrate/codec/src/slicable.rs rename to substrate/substrate/codec/src/codec.rs index da402c8375..9ab4ab1096 100644 --- a/substrate/substrate/codec/src/slicable.rs +++ b/substrate/substrate/codec/src/codec.rs @@ -19,9 +19,7 @@ use alloc::vec::Vec; use alloc::boxed::Box; use core::{mem, slice}; -use super::joiner::Joiner; use arrayvec::ArrayVec; - /// Trait that allows reading of data into a slice. pub trait Input { /// Read into the provided input slice. Returns the number of bytes read. @@ -55,14 +53,47 @@ impl Input for R { } } -/// Trait that allows zero-copy read/write of value-references to/from slices in LE format. -pub trait Slicable: Sized { - /// Attempt to deserialise the value from input. - fn decode(value: &mut I) -> Option; +/// Trait that allows writing of data. +pub trait Output: Sized { + /// Write to the output. + fn write(&mut self, bytes: &[u8]); + + fn push_byte(&mut self, byte: u8) { + self.write(&[byte]); + } + + fn push(&mut self, value: &V) { + value.encode_to(self); + } +} + +#[cfg(not(feature = "std"))] +impl Output for Vec { + fn write(&mut self, bytes: &[u8]) { + self.extend(bytes); + } +} + +#[cfg(feature = "std")] +impl Output for W { + fn write(&mut self, bytes: &[u8]) { + (self as &mut ::std::io::Write).write(bytes).expect("Codec outputs are infallible"); + } +} + +/// Trait that allows zero-copy write of value-references to slices in LE format. +/// Implementations should override `using_encoded` for value types and `encode_to` for allocating types. +pub trait Encode { + /// Convert self to a slice and append it to the destination. + fn encode_to(&self, dest: &mut T) { + self.using_encoded(|buf| dest.write(buf)); + } /// Convert self to an owned vector. fn encode(&self) -> Vec { - self.using_encoded(|s| s.to_vec()) + let mut r = Vec::new(); + self.encode_to(&mut r); + r } /// Convert self to a slice and then invoke the given closure with it. @@ -71,17 +102,32 @@ pub trait Slicable: Sized { } } -/// Encode a bytes slice as `Slicable` that can be decoded into a vector. -pub fn encode_slice(bytes: &[u8]) -> Vec { - let len = bytes.len(); - assert!(len <= u32::max_value() as usize, "Attempted to serialize a collection with too many elements."); - - let mut r: Vec = Vec::new().and(&(len as u32)); - r.extend_from_slice(bytes); - r +/// Trait that allows zero-copy read of value-references from slices in LE format. +pub trait Decode: Sized { + /// Attempt to deserialise the value from input. + fn decode(value: &mut I) -> Option; } -impl Slicable for Result { +/// Trait that allows zero-copy read/write of value-references to/from slices in LE format. +pub trait Codec: Decode + Encode {} +impl Codec for S {} + +impl Encode for Result { + fn encode_to(&self, dest: &mut W) { + match *self { + Ok(ref t) => { + dest.push_byte(0); + t.encode_to(dest); + } + Err(ref e) => { + dest.push_byte(1); + e.encode_to(dest); + } + } + } +} + +impl Decode for Result { fn decode(input: &mut I) -> Option { match input.read_byte()? { 0 => Some(Ok(T::decode(input)?)), @@ -89,36 +135,12 @@ impl Slicable for Result { _ => None, } } - - fn encode(&self) -> Vec { - let mut v = Vec::new(); - match *self { - Ok(ref t) => { - v.push(0); - t.using_encoded(|s| v.extend(s)); - } - Err(ref e) => { - v.push(1); - e.using_encoded(|s| v.extend(s)); - } - } - v - } } /// Shim type because we can't do a specialised implementation for `Option` directly. pub struct OptionBool(pub Option); -impl Slicable for OptionBool { - fn decode(input: &mut I) -> Option { - match input.read_byte()? { - 0 => Some(OptionBool(None)), - 1 => Some(OptionBool(Some(true))), - 2 => Some(OptionBool(Some(false))), - _ => None, - } - } - +impl Encode for OptionBool { fn using_encoded R>(&self, f: F) -> R { f(&[match *self { OptionBool(None) => 0u8, @@ -128,7 +150,30 @@ impl Slicable for OptionBool { } } -impl Slicable for Option { +impl Decode for OptionBool { + fn decode(input: &mut I) -> Option { + match input.read_byte()? { + 0 => Some(OptionBool(None)), + 1 => Some(OptionBool(Some(true))), + 2 => Some(OptionBool(Some(false))), + _ => None, + } + } +} + +impl Encode for Option { + fn encode_to(&self, dest: &mut W) { + match *self { + Some(ref t) => { + dest.push_byte(1); + t.encode_to(dest); + } + None => dest.push_byte(0), + } + } +} + +impl Decode for Option { fn decode(input: &mut I) -> Option { match input.read_byte()? { 0 => Some(None), @@ -136,23 +181,19 @@ impl Slicable for Option { _ => None, } } - - fn encode(&self) -> Vec { - let mut v = Vec::new(); - match *self { - Some(ref t) => { - v.push(1); - t.using_encoded(|s| v.extend(s)); - } - None => v.push(0), - } - v - } } macro_rules! impl_array { ( $( $n:expr )* ) => { $( - impl Slicable for [T; $n] { + impl Encode for [T; $n] { + fn encode_to(&self, dest: &mut W) { + for item in self.iter() { + item.encode_to(dest); + } + } + } + + impl Decode for [T; $n] { fn decode(input: &mut I) -> Option { let mut r = ArrayVec::new(); for _ in 0..$n { @@ -160,15 +201,6 @@ macro_rules! impl_array { } r.into_inner().ok() } - - fn encode(&self) -> Vec { - use core::iter::Extend; - let mut r = Vec::new(); - for item in self.iter() { - item.using_encoded(|e| r.extend(e)); - } - r - } } )* } } @@ -176,17 +208,34 @@ macro_rules! impl_array { impl_array!(1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 40 48 56 64 72 96 128 160 192 224 256); -impl Slicable for Box { - fn decode(input: &mut I) -> Option { - Some(Box::new(T::decode(input)?)) - } - - fn using_encoded R>(&self, f: F) -> R { - self.as_ref().using_encoded(f) +impl Encode for Box { + fn encode_to(&self, dest: &mut W) { + self.as_ref().encode_to(dest) } } -impl Slicable for Vec { +impl Decode for Box { + fn decode(input: &mut I) -> Option { + Some(Box::new(T::decode(input)?)) + } +} + +impl Encode for [u8] { + fn encode_to(&self, dest: &mut W) { + let len = self.len(); + assert!(len <= u32::max_value() as usize, "Attempted to serialize a collection with too many elements."); + (len as u32).encode_to(dest); + dest.write(self) + } +} + +impl Encode for Vec { + fn encode_to(&self, dest: &mut W) { + self.as_slice().encode_to(dest) + } +} + +impl Decode for Vec { fn decode(input: &mut I) -> Option { u32::decode(input).and_then(move |len| { let len = len as usize; @@ -198,13 +247,26 @@ impl Slicable for Vec { } }) } +} - fn encode(&self) -> Vec { - encode_slice(&self) +impl Encode for [T] { + fn encode_to(&self, dest: &mut W) { + let len = self.len(); + assert!(len <= u32::max_value() as usize, "Attempted to serialize a collection with too many elements."); + (len as u32).encode_to(dest); + for item in self { + item.encode_to(dest); + } } } -impl Slicable for Vec { +impl Encode for Vec { + fn encode_to(&self, dest: &mut W) { + self.as_slice().encode_to(dest) + } +} + +impl Decode for Vec { fn decode(input: &mut I) -> Option { u32::decode(input).and_then(move |len| { let mut r = Vec::with_capacity(len as usize); @@ -214,24 +276,10 @@ impl Slicable for Vec { Some(r) }) } - - fn encode(&self) -> Vec { - use core::iter::Extend; - - let len = self.len(); - assert!(len <= u32::max_value() as usize, "Attempted to serialize vec with too many elements."); - - let mut r: Vec = Vec::new().and(&(len as u32)); - for item in self { - item.using_encoded(|e| r.extend(e)) - } - r - } } -impl Slicable for () { - fn decode(_: &mut I) -> Option<()> { - Some(()) +impl Encode for () { + fn encode_to(&self, _dest: &mut T) { } fn using_encoded R>(&self, f: F) -> R { @@ -243,26 +291,46 @@ impl Slicable for () { } } +impl Decode for () { + fn decode(_: &mut I) -> Option<()> { + Some(()) + } +} + macro_rules! tuple_impl { ($one:ident,) => { - impl<$one: Slicable> Slicable for ($one,) { + impl<$one: Encode> Encode for ($one,) { + fn encode_to(&self, dest: &mut T) { + self.0.encode_to(dest); + } + } + + impl<$one: Decode> Decode for ($one,) { fn decode(input: &mut I) -> Option { match $one::decode(input) { None => None, Some($one) => Some(($one,)), } } + } + }; + ($first:ident, $($rest:ident,)+) => { + impl<$first: Encode, $($rest: Encode),+> + Encode for + ($first, $($rest),+) { + fn encode_to(&self, dest: &mut T) { + let ( + ref $first, + $(ref $rest),+ + ) = *self; - fn using_encoded R>(&self, f: F) -> R { - self.0.using_encoded(f) + $first.encode_to(dest); + $($rest.encode_to(dest);)+ } } - - }; - ($first:ident, $($rest:ident,)+) => { - impl<$first: Slicable, $($rest: Slicable),+> - Slicable for + impl<$first: Decode, $($rest: Decode),+> + Decode for ($first, $($rest),+) { fn decode(input: &mut INPUT) -> Option { Some(( @@ -276,22 +344,6 @@ macro_rules! tuple_impl { },)+ )) } - - fn using_encoded(&self, f: PROCESS) -> RETURN - where PROCESS: FnOnce(&[u8]) -> RETURN - { - let mut v = Vec::new(); - - let ( - ref $first, - $(ref $rest),+ - ) = *self; - - $first.using_encoded(|s| v.extend(s)); - $($rest.using_encoded(|s| v.extend(s));)+ - - f(v.as_slice()) - } } tuple_impl!($($rest,)+); @@ -300,15 +352,13 @@ macro_rules! tuple_impl { #[allow(non_snake_case)] mod inner_tuple_impl { - use alloc::vec::Vec; - - use super::{Input, Slicable}; + use super::{Input, Output, Decode, Encode}; tuple_impl!(A, B, C, D, E, F, G, H, I, J, K,); } /// Trait to allow conversion to a know endian representation when sensitive. /// Types implementing this trait must have a size > 0. -// note: the copy bound and static lifetimes are necessary for safety of `Slicable` blanket +// note: the copy bound and static lifetimes are necessary for safety of `Codec` blanket // implementation. trait EndianSensitive: Copy + 'static { fn to_le(self) -> Self { self } @@ -330,22 +380,7 @@ macro_rules! impl_endians { fn as_le_then T>(&self, f: F) -> T { let d = self.to_le(); f(&d) } } - impl Slicable for $t { - fn decode(input: &mut I) -> Option { - let size = mem::size_of::<$t>(); - assert!(size > 0, "EndianSensitive can never be implemented for a zero-sized type."); - let mut val: $t = unsafe { mem::zeroed() }; - - unsafe { - let raw: &mut [u8] = slice::from_raw_parts_mut( - &mut val as *mut $t as *mut u8, - size - ); - if input.read(raw) != size { return None } - } - Some(val.from_le()) - } - + impl Encode for $t { fn using_encoded R>(&self, f: F) -> R { self.as_le_then(|le| { let size = mem::size_of::<$t>(); @@ -362,13 +397,8 @@ macro_rules! impl_endians { }) } } - )* } -} -macro_rules! impl_non_endians { - ( $( $t:ty ),* ) => { $( - impl EndianSensitive for $t {} - impl Slicable for $t { + impl Decode for $t { fn decode(input: &mut I) -> Option { let size = mem::size_of::<$t>(); assert!(size > 0, "EndianSensitive can never be implemented for a zero-sized type."); @@ -383,7 +413,14 @@ macro_rules! impl_non_endians { } Some(val.from_le()) } + } + )* } +} +macro_rules! impl_non_endians { + ( $( $t:ty ),* ) => { $( + impl EndianSensitive for $t {} + impl Encode for $t { fn using_encoded R>(&self, f: F) -> R { self.as_le_then(|le| { let size = mem::size_of::<$t>(); @@ -400,6 +437,23 @@ macro_rules! impl_non_endians { }) } } + + impl Decode for $t { + fn decode(input: &mut I) -> Option { + let size = mem::size_of::<$t>(); + assert!(size > 0, "EndianSensitive can never be implemented for a zero-sized type."); + let mut val: $t = unsafe { mem::zeroed() }; + + unsafe { + let raw: &mut [u8] = slice::from_raw_parts_mut( + &mut val as *mut $t as *mut u8, + size + ); + if input.read(raw) != size { return None } + } + Some(val.from_le()) + } + } )* } } diff --git a/substrate/substrate/codec/src/joiner.rs b/substrate/substrate/codec/src/joiner.rs index f5775082fd..81105b060c 100644 --- a/substrate/substrate/codec/src/joiner.rs +++ b/substrate/substrate/codec/src/joiner.rs @@ -17,16 +17,16 @@ //! Trait use core::iter::Extend; -use super::slicable::Slicable; +use super::Codec; /// Trait to allow itself to be serialised into a value which can be extended /// by bytes. pub trait Joiner { - fn and(self, value: &V) -> Self; + fn and(self, value: &V) -> Self; } impl Joiner for T where T: for<'a> Extend<&'a u8> { - fn and(mut self, value: &V) -> Self { + fn and(mut self, value: &V) -> Self { value.using_encoded(|s| self.extend(s)); self } diff --git a/substrate/substrate/codec/src/keyedvec.rs b/substrate/substrate/codec/src/keyedvec.rs index 353c7ec0e9..301bdcb326 100644 --- a/substrate/substrate/codec/src/keyedvec.rs +++ b/substrate/substrate/codec/src/keyedvec.rs @@ -16,7 +16,7 @@ //! Serialiser and prepender. -use slicable::Slicable; +use Codec; use core::iter::Extend; use alloc::vec::Vec; @@ -25,7 +25,7 @@ pub trait KeyedVec { fn to_keyed_vec(&self, prepend_key: &[u8]) -> Vec; } -impl KeyedVec for T { +impl KeyedVec for T { fn to_keyed_vec(&self, prepend_key: &[u8]) -> Vec { self.using_encoded(|slice| { let mut r = prepend_key.to_vec(); diff --git a/substrate/substrate/codec/src/lib.rs b/substrate/substrate/codec/src/lib.rs index d38e3f6f72..d4a0843f0a 100644 --- a/substrate/substrate/codec/src/lib.rs +++ b/substrate/substrate/codec/src/lib.rs @@ -34,10 +34,10 @@ pub mod alloc { pub use std::vec; } -mod slicable; +mod codec; mod joiner; mod keyedvec; -pub use self::slicable::{Input, Slicable, encode_slice}; +pub use self::codec::{Input, Output, Encode, Decode, Codec}; pub use self::joiner::Joiner; pub use self::keyedvec::KeyedVec; diff --git a/substrate/substrate/executor/src/lib.rs b/substrate/substrate/executor/src/lib.rs index ddf631ba5f..f474946919 100644 --- a/substrate/substrate/executor/src/lib.rs +++ b/substrate/substrate/executor/src/lib.rs @@ -69,7 +69,7 @@ pub use wasm_executor::WasmExecutor; pub use native_executor::{with_native_environment, NativeExecutor, NativeExecutionDispatch}; pub use state_machine::Externalities; pub use runtime_version::RuntimeVersion; -pub use codec::Slicable; +pub use codec::Codec; /// Provides runtime information. pub trait RuntimeInfo { diff --git a/substrate/substrate/executor/src/native_executor.rs b/substrate/substrate/executor/src/native_executor.rs index c5cc2d8113..d08e56dd2f 100644 --- a/substrate/substrate/executor/src/native_executor.rs +++ b/substrate/substrate/executor/src/native_executor.rs @@ -20,7 +20,7 @@ use wasm_executor::WasmExecutor; use wasmi::Module as WasmModule; use runtime_version::RuntimeVersion; use std::collections::HashMap; -use codec::Slicable; +use codec::Decode; use twox_hash::XxHash; use std::hash::Hasher; use parking_lot::{Mutex, MutexGuard}; diff --git a/substrate/substrate/executor/src/sandbox.rs b/substrate/substrate/executor/src/sandbox.rs index 25da25cd3f..2557144e12 100644 --- a/substrate/substrate/executor/src/sandbox.rs +++ b/substrate/substrate/executor/src/sandbox.rs @@ -20,7 +20,7 @@ use std::collections::HashMap; use std::rc::Rc; -use codec::Slicable; +use codec::{Decode, Encode}; use primitives::sandbox as sandbox_primitives; use wasm_utils::UserError; use wasmi; diff --git a/substrate/substrate/executor/src/wasm_executor.rs b/substrate/substrate/executor/src/wasm_executor.rs index 85c501cb12..b4ed435f99 100644 --- a/substrate/substrate/executor/src/wasm_executor.rs +++ b/substrate/substrate/executor/src/wasm_executor.rs @@ -386,7 +386,7 @@ impl_function_executor!(this: FunctionExecutor<'e, E>, }, // TODO: Remove the old 'ext_sandbox_invoke' and rename this to it. ext_sandbox_invoke_poc2(instance_idx: u32, export_ptr: *const u8, export_len: usize, args_ptr: *const u8, args_len: usize, return_val_ptr: *const u8, return_val_len: usize, state: usize) -> u32 => { - use codec::Slicable; + use codec::{Decode, Encode}; trace!(target: "runtime-sandbox", "invoke, instance_idx={}", instance_idx); let export = this.memory.get(export_ptr, export_len as usize) @@ -555,7 +555,7 @@ impl CodeExecutor for WasmExecutor { mod tests { use super::*; use rustc_hex::FromHex; - use codec::Slicable; + use codec::Encode; use state_machine::TestExternalities; // TODO: move into own crate. diff --git a/substrate/substrate/executor/wasm/target/wasm32-unknown-unknown/release/runtime_test.compact.wasm b/substrate/substrate/executor/wasm/target/wasm32-unknown-unknown/release/runtime_test.compact.wasm index 536c458f2a..b6a193d3d2 100644 Binary files a/substrate/substrate/executor/wasm/target/wasm32-unknown-unknown/release/runtime_test.compact.wasm and b/substrate/substrate/executor/wasm/target/wasm32-unknown-unknown/release/runtime_test.compact.wasm differ diff --git a/substrate/substrate/executor/wasm/target/wasm32-unknown-unknown/release/runtime_test.wasm b/substrate/substrate/executor/wasm/target/wasm32-unknown-unknown/release/runtime_test.wasm index a65e241765..37fa02f424 100755 Binary files a/substrate/substrate/executor/wasm/target/wasm32-unknown-unknown/release/runtime_test.wasm and b/substrate/substrate/executor/wasm/target/wasm32-unknown-unknown/release/runtime_test.wasm differ diff --git a/substrate/substrate/misbehavior-check/src/lib.rs b/substrate/substrate/misbehavior-check/src/lib.rs index fc1e62aa40..0f2010c914 100644 --- a/substrate/substrate/misbehavior-check/src/lib.rs +++ b/substrate/substrate/misbehavior-check/src/lib.rs @@ -30,13 +30,13 @@ extern crate substrate_keyring as keyring; #[cfg(test)] extern crate rhododendron; -use codec::Slicable; +use codec::{Codec, Encode}; use primitives::{AuthorityId, Signature}; use runtime_primitives::bft::{Action, Message, MisbehaviorKind}; // check a message signature. returns true if signed by that authority. -fn check_message_sig( +fn check_message_sig( message: Message, signature: &Signature, from: &AuthorityId @@ -64,7 +64,7 @@ fn commit(parent: H, round_number: u32, hash: H) -> Message { /// Doesn't check that the header hash in question is /// valid or whether the misbehaving authority was part of /// the set at that block. -pub fn evaluate_misbehavior( +pub fn evaluate_misbehavior( misbehaved: &AuthorityId, parent_hash: H, kind: &MisbehaviorKind, diff --git a/substrate/substrate/network/src/message.rs b/substrate/substrate/network/src/message.rs index 5063e7e54c..a0f863c406 100644 --- a/substrate/substrate/network/src/message.rs +++ b/substrate/substrate/network/src/message.rs @@ -166,7 +166,7 @@ pub struct RemoteCallResponse { /// Generic types. pub mod generic { use primitives::AuthorityId; - use codec::Slicable; + use codec::{Codec, Decode, Encode}; use runtime_primitives::bft::Justification; use ed25519; use primitives::Signature; @@ -190,7 +190,7 @@ pub mod generic { Extrinsics(Vec), } - impl Body where Extrinsic: Slicable { + impl Body where Extrinsic: Codec { /// Extracts extrinsic from the body. pub fn to_extrinsics(self) -> Vec { match self { @@ -198,7 +198,7 @@ pub mod generic { Body::V1(e) => { e.into_iter().filter_map(|bytes| { let bytes = bytes.0.encode(); - Slicable::decode(&mut bytes.as_slice()) + Decode::decode(&mut bytes.as_slice()) }).collect() } } diff --git a/substrate/substrate/network/src/test/mod.rs b/substrate/substrate/network/src/test/mod.rs index 09b795e82f..343db6d1c4 100644 --- a/substrate/substrate/network/src/test/mod.rs +++ b/substrate/substrate/network/src/test/mod.rs @@ -30,7 +30,7 @@ use config::ProtocolConfig; use service::TransactionPool; use network_libp2p::{PeerId, SessionInfo, Error as NetworkError}; use keyring::Keyring; -use codec::Slicable; +use codec::Encode; use test_client::{self, TestClient}; use test_client::runtime::{Block, Hash, Transfer, Extrinsic}; use specialization::Specialization; diff --git a/substrate/substrate/primitives/src/authority_id.rs b/substrate/substrate/primitives/src/authority_id.rs index 2f54157355..f7bf815b51 100644 --- a/substrate/substrate/primitives/src/authority_id.rs +++ b/substrate/substrate/primitives/src/authority_id.rs @@ -17,7 +17,7 @@ #[cfg(feature = "std")] use serde::{Serialize, Serializer, Deserialize, Deserializer}; -use codec::Slicable; +use codec; use H256; /// An identifier for an authority in the consensus algorithm. The same size as ed25519::Public. @@ -106,12 +106,15 @@ impl<'de> Deserialize<'de> for AuthorityId { } } -impl Slicable for AuthorityId { - fn decode(input: &mut I) -> Option { - <[u8; 32] as ::codec::Slicable>::decode(input).map(AuthorityId) - } - +impl codec::Encode for AuthorityId { fn using_encoded R>(&self, f: F) -> R { self.0.using_encoded(f) } } + +impl codec::Decode for AuthorityId { + fn decode(input: &mut I) -> Option { + <[u8; 32] as codec::Decode>::decode(input).map(AuthorityId) + } +} + diff --git a/substrate/substrate/primitives/src/hash.rs b/substrate/substrate/primitives/src/hash.rs index 8556f649bb..a0dc5f4c1c 100644 --- a/substrate/substrate/primitives/src/hash.rs +++ b/substrate/substrate/primitives/src/hash.rs @@ -39,15 +39,16 @@ macro_rules! impl_rest { } } - impl ::codec::Slicable for $name { - fn decode(input: &mut I) -> Option { - <[u8; $len] as ::codec::Slicable>::decode(input).map($name) - } - + impl ::codec::Encode for $name { fn using_encoded R>(&self, f: F) -> R { self.0.using_encoded(f) } } + impl ::codec::Decode for $name { + fn decode(input: &mut I) -> Option { + <[u8; $len] as ::codec::Decode>::decode(input).map($name) + } + } } } diff --git a/substrate/substrate/primitives/src/lib.rs b/substrate/substrate/primitives/src/lib.rs index 9650cb7e7c..322590a0bf 100644 --- a/substrate/substrate/primitives/src/lib.rs +++ b/substrate/substrate/primitives/src/lib.rs @@ -101,4 +101,4 @@ impl From> for Bytes { impl Deref for Bytes { type Target = [u8]; fn deref(&self) -> &[u8] { &self.0[..] } -} \ No newline at end of file +} diff --git a/substrate/substrate/primitives/src/sandbox.rs b/substrate/substrate/primitives/src/sandbox.rs index 4dee6578df..b7e9d0cd62 100644 --- a/substrate/substrate/primitives/src/sandbox.rs +++ b/substrate/substrate/primitives/src/sandbox.rs @@ -16,18 +16,14 @@ //! Definition of a sandbox environment. -use codec::{Slicable, Input}; +use codec::{Encode, Decode, Input, Output}; use rstd::vec::Vec; /// Error error that can be returned from host function. #[cfg_attr(feature = "std", derive(Debug))] pub struct HostError; -impl Slicable for HostError { - fn decode(_: &mut I) -> Option { - Some(HostError) - } - +impl Encode for HostError { fn using_encoded R>(&self, f: F) -> R { f(&[]) } @@ -37,6 +33,12 @@ impl Slicable for HostError { } } +impl Decode for HostError { + fn decode(_: &mut I) -> Option { + Some(HostError) + } +} + #[derive(Clone, Copy, PartialEq, Eq)] #[cfg_attr(feature = "std", derive(Debug))] #[repr(i8)] @@ -101,31 +103,30 @@ impl From for ::wasmi::RuntimeValue { } } -impl Slicable for TypedValue { - fn encode(&self) -> Vec { - let mut v = Vec::new(); +impl Encode for TypedValue { + fn encode_to(&self, dest: &mut T) { match *self { TypedValue::I32(i) => { - v.push(ValueType::I32 as u8); - i.using_encoded(|s| v.extend(s)); + dest.push_byte(ValueType::I32 as u8); + dest.push(&i); } TypedValue::I64(i) => { - v.push(ValueType::I64 as u8); - i.using_encoded(|s| v.extend(s)); + dest.push_byte(ValueType::I64 as u8); + dest.push(&i); } TypedValue::F32(f_bits) => { - v.push(ValueType::F32 as u8); - f_bits.using_encoded(|s| v.extend(s)); + dest.push_byte(ValueType::F32 as u8); + dest.push(&f_bits); } TypedValue::F64(f_bits) => { - v.push(ValueType::F64 as u8); - f_bits.using_encoded(|s| v.extend(s)); + dest.push_byte(ValueType::F64 as u8); + dest.push(&f_bits); } } - - v } +} +impl Decode for TypedValue { fn decode(value: &mut I) -> Option { let typed_value = match i8::decode(value) { Some(x) if x == ValueType::I32 as i8 => TypedValue::I32(i32::decode(value)?), @@ -157,21 +158,21 @@ impl From for ReturnValue { } } -impl Slicable for ReturnValue { - fn encode(&self) -> Vec { - let mut v = Vec::new(); +impl Encode for ReturnValue { + fn encode_to(&self, dest: &mut T) { match *self { ReturnValue::Unit => { - v.push(0); + dest.push_byte(0); } ReturnValue::Value(ref val) => { - v.push(1); - val.using_encoded(|s| v.extend(s)); + dest.push_byte(1); + dest.push(val); } } - v } +} +impl Decode for ReturnValue { fn decode(value: &mut I) -> Option { match i8::decode(value) { Some(0) => Some(ReturnValue::Unit), @@ -183,7 +184,7 @@ impl Slicable for ReturnValue { impl ReturnValue { /// Maximum number of bytes `ReturnValue` might occupy when serialized with - /// `Slicable`. + /// `Codec`. /// /// Breakdown: /// 1 byte for encoding unit/value variant @@ -219,23 +220,22 @@ pub enum ExternEntity { Memory(u32), } -impl Slicable for ExternEntity { - fn encode(&self) -> Vec { - let mut v = Vec::new(); +impl Encode for ExternEntity { + fn encode_to(&self, dest: &mut T) { match *self { ExternEntity::Function(ref index) => { - v.push(ExternEntityKind::Function as u8); - index.using_encoded(|s| v.extend(s)); + dest.push_byte(ExternEntityKind::Function as u8); + dest.push(index); } ExternEntity::Memory(ref mem_id) => { - v.push(ExternEntityKind::Memory as u8); - mem_id.using_encoded(|s| v.extend(s)); + dest.push_byte(ExternEntityKind::Memory as u8); + dest.push(mem_id); } } - - v } +} +impl Decode for ExternEntity { fn decode(value: &mut I) -> Option { match i8::decode(value) { Some(x) if x == ExternEntityKind::Function as i8 => { @@ -266,16 +266,15 @@ pub struct Entry { pub entity: ExternEntity, } -impl Slicable for Entry { - fn encode(&self) -> Vec { - let mut v = Vec::new(); - self.module_name.using_encoded(|s| v.extend(s)); - self.field_name.using_encoded(|s| v.extend(s)); - self.entity.using_encoded(|s| v.extend(s)); - - v +impl Encode for Entry { + fn encode_to(&self, dest: &mut T) { + dest.push(&self.module_name); + dest.push(&self.field_name); + dest.push(&self.entity); } +} +impl Decode for Entry { fn decode(value: &mut I) -> Option { let module_name = Vec::decode(value)?; let field_name = Vec::decode(value)?; @@ -297,11 +296,13 @@ pub struct EnvironmentDefinition { pub entries: Vec, } -impl Slicable for EnvironmentDefinition { - fn encode(&self) -> Vec { - self.entries.encode() +impl Encode for EnvironmentDefinition { + fn encode_to(&self, dest: &mut T) { + self.entries.encode_to(dest) } +} +impl Decode for EnvironmentDefinition { fn decode(value: &mut I) -> Option { let entries = Vec::decode(value)?; @@ -340,8 +341,9 @@ pub const ERR_EXECUTION: u32 = -3i32 as u32; mod tests { use super::*; use std::fmt; + use codec::Codec; - fn roundtrip(s: S) { + fn roundtrip(s: S) { let encoded = s.encode(); assert_eq!(S::decode(&mut &encoded[..]).unwrap(), s); } diff --git a/substrate/substrate/rpc/src/author/mod.rs b/substrate/substrate/rpc/src/author/mod.rs index 327e67b5dc..8e130f4103 100644 --- a/substrate/substrate/rpc/src/author/mod.rs +++ b/substrate/substrate/rpc/src/author/mod.rs @@ -20,7 +20,7 @@ use std::sync::Arc; use client::{self, Client}; use extrinsic_pool::api::{Error, ExtrinsicPool}; -use codec::Slicable; +use codec::Codec; use primitives::Bytes; use runtime_primitives::{generic, traits::Block as BlockT}; @@ -65,7 +65,7 @@ impl AuthorApi for Author wh Block: BlockT + 'static, P: ExtrinsicPool, Hash>, P::Error: 'static, - Ex: Slicable, + Ex: Codec, { fn submit_extrinsic(&self, xt: Bytes) -> Result { self.submit_rich_extrinsic(Ex::decode(&mut &xt[..]).ok_or(error::Error::from(error::ErrorKind::BadFormat))?) diff --git a/substrate/substrate/rpc/src/author/tests.rs b/substrate/substrate/rpc/src/author/tests.rs index acdb320e96..caa1ffa38a 100644 --- a/substrate/substrate/rpc/src/author/tests.rs +++ b/substrate/substrate/rpc/src/author/tests.rs @@ -20,6 +20,7 @@ use std::{fmt, sync::Arc}; use extrinsic_pool::{api, txpool}; use test_client; use parking_lot::Mutex; +use codec::Encode; type Extrinsic = u64; type Hash = u64; diff --git a/substrate/substrate/runtime-io/with_std.rs b/substrate/substrate/runtime-io/with_std.rs index 93ac7cffa4..4d600ca4cb 100644 --- a/substrate/substrate/runtime-io/with_std.rs +++ b/substrate/substrate/runtime-io/with_std.rs @@ -168,13 +168,13 @@ macro_rules! impl_stubs { }; (@METHOD $data: ident $new_name: ident => $invoke:expr) => {{ let mut data = $data; - let input = match $crate::codec::Slicable::decode(&mut data) { + let input = match $crate::codec::Decode::decode(&mut data) { Some(input) => input, None => panic!("Bad input data provided to {}", stringify!($new_name)), }; let output = $invoke(input); - Some($crate::codec::Slicable::encode(&output)) + Some($crate::codec::Encode::encode(&output)) }} } diff --git a/substrate/substrate/runtime-io/without_std.rs b/substrate/substrate/runtime-io/without_std.rs index e1dd22c577..5f96ea88e7 100644 --- a/substrate/substrate/runtime-io/without_std.rs +++ b/substrate/substrate/runtime-io/without_std.rs @@ -282,13 +282,13 @@ macro_rules! impl_stubs { } }; - let input = match $crate::codec::Slicable::decode(&mut input) { + let input = match $crate::codec::Decode::decode(&mut input) { Some(input) => input, None => panic!("Bad input data provided to {}", stringify!($name)), }; let output = ($invoke)(input); - let output = $crate::codec::Slicable::encode(&output); + let output = $crate::codec::Encode::encode(&output); let res = output.as_ptr() as u64 + ((output.len() as u64) << 32); // Leak the output vector to avoid it being freed. diff --git a/substrate/substrate/runtime-sandbox/without_std.rs b/substrate/substrate/runtime-sandbox/without_std.rs index 860d24f43c..9efa282ebc 100755 --- a/substrate/substrate/runtime-sandbox/without_std.rs +++ b/substrate/substrate/runtime-sandbox/without_std.rs @@ -16,7 +16,7 @@ use rstd::prelude::*; use rstd::{slice, marker, mem}; -use codec::Slicable; +use codec::{Decode, Encode}; use primitives::sandbox as sandbox_primitives; use super::{Error, TypedValue, ReturnValue, HostFuncType}; diff --git a/substrate/substrate/runtime-support/src/dispatch.rs b/substrate/substrate/runtime-support/src/dispatch.rs index d9c33bdc4c..3bda733447 100644 --- a/substrate/substrate/runtime-support/src/dispatch.rs +++ b/substrate/substrate/runtime-support/src/dispatch.rs @@ -22,7 +22,7 @@ pub use std::fmt; pub use rstd::result; #[cfg(feature = "std")] use serde; -pub use codec::{Slicable, Input}; +pub use codec::{Codec, Decode, Encode, Input, Output}; pub type Result = result::Result<(), &'static str>; @@ -39,11 +39,11 @@ pub trait AuxDispatchable { #[cfg(feature = "std")] pub trait AuxCallable { - type Call: AuxDispatchable + Slicable + ::serde::Serialize + Clone + PartialEq + Eq; + type Call: AuxDispatchable + Codec + ::serde::Serialize + Clone + PartialEq + Eq; } #[cfg(not(feature = "std"))] pub trait AuxCallable { - type Call: AuxDispatchable + Slicable + Clone + PartialEq + Eq; + type Call: AuxDispatchable + Codec + Clone + PartialEq + Eq; } // dirty hack to work around serde_derive issue @@ -52,11 +52,11 @@ pub type AuxCallableCallFor = ::Call; #[cfg(feature = "std")] pub trait Callable { - type Call: Dispatchable + Slicable + ::serde::Serialize + Clone + PartialEq + Eq; + type Call: Dispatchable + Codec + ::serde::Serialize + Clone + PartialEq + Eq; } #[cfg(not(feature = "std"))] pub trait Callable { - type Call: Dispatchable + Slicable + Clone + PartialEq + Eq; + type Call: Dispatchable + Codec + Clone + PartialEq + Eq; } // dirty hack to work around serde_derive issue. @@ -64,16 +64,16 @@ pub trait Callable { pub type CallableCallFor = ::Call; #[cfg(feature = "std")] -pub trait Parameter: Slicable + serde::Serialize + Clone + Eq + fmt::Debug {} +pub trait Parameter: Codec + serde::Serialize + Clone + Eq + fmt::Debug {} #[cfg(feature = "std")] -impl Parameter for T where T: Slicable + serde::Serialize + Clone + Eq + fmt::Debug {} +impl Parameter for T where T: Codec + serde::Serialize + Clone + Eq + fmt::Debug {} #[cfg(not(feature = "std"))] -pub trait Parameter: Slicable + Clone + Eq {} +pub trait Parameter: Codec + Clone + Eq {} #[cfg(not(feature = "std"))] -impl Parameter for T where T: Slicable + Clone + Eq {} +impl Parameter for T where T: Codec + Clone + Eq {} /// Declare a struct for this module, then implement dispatch logic to create a pairing of several /// dispatch traits and enums. @@ -395,13 +395,13 @@ macro_rules! __decl_dispatch_module_common { } } - impl<$trait_instance: $trait_name> $crate::dispatch::Slicable for $call_type<$trait_instance> { + impl<$trait_instance: $trait_name> $crate::dispatch::Decode for $call_type<$trait_instance> { fn decode(input: &mut I) -> Option { match input.read_byte()? { $( $id => { $( - let $param_name = $crate::dispatch::Slicable::decode(input)?; + let $param_name = $crate::dispatch::Decode::decode(input)?; )* Some($call_type:: $fn_name( $( $param_name ),* )) } @@ -409,9 +409,10 @@ macro_rules! __decl_dispatch_module_common { _ => None, } } + } - fn encode(&self) -> $crate::dispatch::Vec { - let mut v = $crate::dispatch::Vec::new(); + impl<$trait_instance: $trait_name> $crate::dispatch::Encode for $call_type<$trait_instance> { + fn encode_to(&self, dest: &mut W) { match *self { $( $call_type::$fn_name( @@ -419,19 +420,14 @@ macro_rules! __decl_dispatch_module_common { ref $param_name ),* ) => { - v.push($id as u8); + dest.push_byte($id as u8); $( - $param_name.using_encoded(|s| v.extend(s)); + $param_name.encode_to(dest); )* } )* $call_type::__PhantomItem(_) => unreachable!(), } - v - } - - fn using_encoded R>(&self, f: F) -> R { - f(self.encode().as_slice()) } } @@ -536,32 +532,28 @@ macro_rules! impl_outer_dispatch_common { ( $call_type:ident, $( $camelcase:ident = $id:expr, )* ) => { - impl $crate::dispatch::Slicable for $call_type { + impl $crate::dispatch::Decode for $call_type { fn decode(input: &mut I) -> Option { match input.read_byte()? { $( $id => - Some($call_type::$camelcase( $crate::dispatch::Slicable::decode(input)? )), + Some($call_type::$camelcase( $crate::dispatch::Decode::decode(input)? )), )* _ => None, } } + } - fn encode(&self) -> $crate::dispatch::Vec { - let mut v = $crate::dispatch::Vec::new(); + impl $crate::dispatch::Encode for $call_type { + fn encode_to(&self, dest: &mut W) { match *self { $( $call_type::$camelcase( ref sub ) => { - v.push($id as u8); - sub.using_encoded(|s| v.extend(s)); + dest.push_byte($id as u8); + sub.encode_to(dest); } )* } - v - } - - fn using_encoded R>(&self, f: F) -> R { - f(self.encode().as_slice()) } } diff --git a/substrate/substrate/runtime-support/src/hashable.rs b/substrate/substrate/runtime-support/src/hashable.rs index 79a5c352b3..386f44c686 100644 --- a/substrate/substrate/runtime-support/src/hashable.rs +++ b/substrate/substrate/runtime-support/src/hashable.rs @@ -16,7 +16,7 @@ //! Hashable trait. -use codec::Slicable; +use codec::Codec; use runtime_io::{blake2_256, twox_128, twox_256}; pub trait Hashable: Sized { @@ -25,7 +25,7 @@ pub trait Hashable: Sized { fn twox_256(&self) -> [u8; 32]; } -impl Hashable for T { +impl Hashable for T { fn blake2_256(&self) -> [u8; 32] { blake2_256(&self.encode()) } diff --git a/substrate/substrate/runtime-support/src/storage/generator.rs b/substrate/substrate/runtime-support/src/storage/generator.rs index d91e860f9e..ed15dc845c 100644 --- a/substrate/substrate/runtime-support/src/storage/generator.rs +++ b/substrate/substrate/runtime-support/src/storage/generator.rs @@ -59,38 +59,38 @@ pub trait Storage { fn exists(&self, key: &[u8]) -> bool; /// Load the bytes of a key from storage. Can panic if the type is incorrect. - fn get(&self, key: &[u8]) -> Option; + fn get(&self, key: &[u8]) -> Option; /// Load the bytes of a key from storage. Can panic if the type is incorrect. Will panic if /// it's not there. - fn require(&self, key: &[u8]) -> T { self.get(key).expect("Required values must be in storage") } + fn require(&self, key: &[u8]) -> T { self.get(key).expect("Required values must be in storage") } /// Load the bytes of a key from storage. Can panic if the type is incorrect. The type's /// default is returned if it's not there. - fn get_or_default(&self, key: &[u8]) -> T { self.get(key).unwrap_or_default() } + fn get_or_default(&self, key: &[u8]) -> T { self.get(key).unwrap_or_default() } /// Put a value in under a key. - fn put(&self, key: &[u8], val: &T); + fn put(&self, key: &[u8], val: &T); /// Remove the bytes of a key from storage. fn kill(&self, key: &[u8]); /// Take a value from storage, deleting it after reading. - fn take(&self, key: &[u8]) -> Option { + fn take(&self, key: &[u8]) -> Option { let value = self.get(key); self.kill(key); value } /// Take a value from storage, deleting it after reading. - fn take_or_panic(&self, key: &[u8]) -> T { self.take(key).expect("Required values must be in storage") } + fn take_or_panic(&self, key: &[u8]) -> T { self.take(key).expect("Required values must be in storage") } /// Take a value from storage, deleting it after reading. - fn take_or_default(&self, key: &[u8]) -> T { self.take(key).unwrap_or_default() } + fn take_or_default(&self, key: &[u8]) -> T { self.take(key).unwrap_or_default() } } /// A strongly-typed value kept in storage. -pub trait StorageValue { +pub trait StorageValue { /// The type that get/take returns. type Query; @@ -120,7 +120,7 @@ pub trait StorageValue { } /// A strongly-typed list in storage. -pub trait StorageList { +pub trait StorageList { /// Get the prefix key in storage. fn prefix() -> &'static [u8]; @@ -150,7 +150,7 @@ pub trait StorageList { } /// A strongly-typed map in storage. -pub trait StorageMap { +pub trait StorageMap { /// The type that get/take returns. type Query; @@ -233,7 +233,7 @@ macro_rules! __storage_items_internal { /// Get the storage key used to fetch a value corresponding to a specific key. fn key_for(x: &$kty) -> Vec { let mut key = $prefix.to_vec(); - key.extend($crate::codec::Slicable::encode(x)); + $crate::codec::Encode::encode_to(x, &mut key); key } @@ -284,7 +284,7 @@ macro_rules! __storage_items_internal { /// Get the storage key used to fetch a value at a given index. fn key_for(index: u32) -> Vec { let mut key = $prefix.to_vec(); - key.extend($crate::codec::Slicable::encode(&index)); + $crate::codec::Encode::encode_to(&index, &mut key); key } @@ -496,7 +496,7 @@ macro_rules! __decl_storage_item { /// Get the storage key used to fetch a value corresponding to a specific key. fn key_for(x: &$kty) -> Vec { let mut key = $prefix.to_vec(); - key.extend($crate::codec::Slicable::encode(x)); + $crate::codec::Encode::encode_to(x, &mut key); key } @@ -991,7 +991,7 @@ macro_rules! __decl_storage_items { mod tests { use std::collections::HashMap; use std::cell::RefCell; - use codec::Slicable; + use codec::Codec; use super::*; impl Storage for RefCell, Vec>> { @@ -999,11 +999,11 @@ mod tests { self.borrow_mut().get(key).is_some() } - fn get(&self, key: &[u8]) -> Option { + fn get(&self, key: &[u8]) -> Option { self.borrow_mut().get(key).map(|v| T::decode(&mut &v[..]).unwrap()) } - fn put(&self, key: &[u8], val: &T) { + fn put(&self, key: &[u8], val: &T) { self.borrow_mut().insert(key.to_owned(), val.encode()); } diff --git a/substrate/substrate/runtime-support/src/storage/mod.rs b/substrate/substrate/runtime-support/src/storage/mod.rs index 2c9e2a5887..8d90fa9fbe 100644 --- a/substrate/substrate/runtime-support/src/storage/mod.rs +++ b/substrate/substrate/runtime-support/src/storage/mod.rs @@ -19,7 +19,7 @@ use rstd::prelude::*; use rstd::borrow::Borrow; use runtime_io::{self, twox_128}; -use codec::{Slicable, KeyedVec, Input}; +use codec::{Codec, Decode, KeyedVec, Input}; pub mod generator; @@ -40,42 +40,42 @@ impl<'a> Input for IncrementalInput<'a> { } /// Return the value of the item in storage under `key`, or `None` if there is no explicit entry. -pub fn get(key: &[u8]) -> Option { +pub fn get(key: &[u8]) -> Option { let key = twox_128(key); runtime_io::read_storage(&key[..], &mut [0; 0][..], 0).map(|_| { let mut input = IncrementalInput { key: &key[..], pos: 0, }; - Slicable::decode(&mut input).expect("storage is not null, therefore must be a valid type") + Decode::decode(&mut input).expect("storage is not null, therefore must be a valid type") }) } /// Return the value of the item in storage under `key`, or the type's default if there is no /// explicit entry. -pub fn get_or_default(key: &[u8]) -> T { +pub fn get_or_default(key: &[u8]) -> T { get(key).unwrap_or_else(Default::default) } /// Return the value of the item in storage under `key`, or `default_value` if there is no /// explicit entry. -pub fn get_or(key: &[u8], default_value: T) -> T { +pub fn get_or(key: &[u8], default_value: T) -> T { get(key).unwrap_or(default_value) } /// Return the value of the item in storage under `key`, or `default_value()` if there is no /// explicit entry. -pub fn get_or_else T>(key: &[u8], default_value: F) -> T { +pub fn get_or_else T>(key: &[u8], default_value: F) -> T { get(key).unwrap_or_else(default_value) } /// Put `value` in storage under `key`. -pub fn put(key: &[u8], value: &T) { +pub fn put(key: &[u8], value: &T) { value.using_encoded(|slice| runtime_io::set_storage(&twox_128(key)[..], slice)); } /// Remove `key` from storage, returning its value if it had an explicit entry or `None` otherwise. -pub fn take(key: &[u8]) -> Option { +pub fn take(key: &[u8]) -> Option { let r = get(key); if r.is_some() { kill(key); @@ -85,19 +85,19 @@ pub fn take(key: &[u8]) -> Option { /// Remove `key` from storage, returning its value, or, if there was no explicit entry in storage, /// the default for its type. -pub fn take_or_default(key: &[u8]) -> T { +pub fn take_or_default(key: &[u8]) -> T { take(key).unwrap_or_else(Default::default) } /// Return the value of the item in storage under `key`, or `default_value` if there is no /// explicit entry. Ensure there is no explicit entry on return. -pub fn take_or(key: &[u8], default_value: T) -> T { +pub fn take_or(key: &[u8], default_value: T) -> T { take(key).unwrap_or(default_value) } /// Return the value of the item in storage under `key`, or `default_value()` if there is no /// explicit entry. Ensure there is no explicit entry on return. -pub fn take_or_else T>(key: &[u8], default_value: F) -> T { +pub fn take_or_else T>(key: &[u8], default_value: F) -> T { take(key).unwrap_or_else(default_value) } @@ -131,12 +131,12 @@ impl ::GenericStorage for RuntimeStorage { } /// Load the bytes of a key from storage. Can panic if the type is incorrect. - fn get(&self, key: &[u8]) -> Option { + fn get(&self, key: &[u8]) -> Option { super::storage::get(key) } /// Put a value in under a key. - fn put(&self, key: &[u8], val: &T) { + fn put(&self, key: &[u8], val: &T) { super::storage::put(key, val) } @@ -146,13 +146,13 @@ impl ::GenericStorage for RuntimeStorage { } /// Take a value from storage, deleting it after reading. - fn take(&self, key: &[u8]) -> Option { + fn take(&self, key: &[u8]) -> Option { super::storage::take(key) } } /// A trait for working with macro-generated storage values under the substrate storage API. -pub trait StorageValue { +pub trait StorageValue { /// The type that get/take return. type Query; @@ -175,7 +175,7 @@ pub trait StorageValue { fn take() -> Self::Query; } -impl StorageValue for U where U: generator::StorageValue { +impl StorageValue for U where U: generator::StorageValue { type Query = U::Query; fn key() -> &'static [u8] { @@ -199,7 +199,7 @@ impl StorageValue for U where U: generator::StorageValue { } /// A strongly-typed list in storage. -pub trait StorageList { +pub trait StorageList { /// Get the prefix key in storage. fn prefix() -> &'static [u8]; @@ -228,7 +228,7 @@ pub trait StorageList { fn clear(); } -impl StorageList for U where U: generator::StorageList { +impl StorageList for U where U: generator::StorageList { fn prefix() -> &'static [u8] { >::prefix() } @@ -267,7 +267,7 @@ impl StorageList for U where U: generator::StorageList { } /// A strongly-typed map in storage. -pub trait StorageMap { +pub trait StorageMap { /// The type that get/take return. type Query; @@ -293,7 +293,7 @@ pub trait StorageMap { fn take>(key: KeyArg) -> Self::Query; } -impl StorageMap for U where U: generator::StorageMap { +impl StorageMap for U where U: generator::StorageMap { type Query = U::Query; fn prefix() -> &'static [u8] { @@ -327,7 +327,7 @@ impl StorageMap for U where U: generator::Sto /// A trait to conveniently store a vector of storable data. pub trait StorageVec { - type Item: Default + Sized + Slicable; + type Item: Default + Sized + Codec; const PREFIX: &'static [u8]; /// Get the current set of items. @@ -386,44 +386,44 @@ pub trait StorageVec { pub mod unhashed { use rstd::borrow::Borrow; - use super::{runtime_io, Slicable, KeyedVec, Vec, IncrementalInput}; + use super::{runtime_io, Codec, Decode, KeyedVec, Vec, IncrementalInput}; /// Return the value of the item in storage under `key`, or `None` if there is no explicit entry. - pub fn get(key: &[u8]) -> Option { + pub fn get(key: &[u8]) -> Option { runtime_io::read_storage(key, &mut [0; 0][..], 0).map(|_| { let mut input = IncrementalInput { key, pos: 0, }; - Slicable::decode(&mut input).expect("stroage is not null, therefore must be a valid type") + Decode::decode(&mut input).expect("storage is not null, therefore must be a valid type") }) } /// Return the value of the item in storage under `key`, or the type's default if there is no /// explicit entry. - pub fn get_or_default(key: &[u8]) -> T { + pub fn get_or_default(key: &[u8]) -> T { get(key).unwrap_or_else(Default::default) } /// Return the value of the item in storage under `key`, or `default_value` if there is no /// explicit entry. - pub fn get_or(key: &[u8], default_value: T) -> T { + pub fn get_or(key: &[u8], default_value: T) -> T { get(key).unwrap_or(default_value) } /// Return the value of the item in storage under `key`, or `default_value()` if there is no /// explicit entry. - pub fn get_or_else T>(key: &[u8], default_value: F) -> T { + pub fn get_or_else T>(key: &[u8], default_value: F) -> T { get(key).unwrap_or_else(default_value) } /// Put `value` in storage under `key`. - pub fn put(key: &[u8], value: &T) { + pub fn put(key: &[u8], value: &T) { value.using_encoded(|slice| runtime_io::set_storage(key, slice)); } /// Remove `key` from storage, returning its value if it had an explicit entry or `None` otherwise. - pub fn take(key: &[u8]) -> Option { + pub fn take(key: &[u8]) -> Option { let r = get(key); if r.is_some() { kill(key); @@ -433,19 +433,19 @@ pub mod unhashed { /// Remove `key` from storage, returning its value, or, if there was no explicit entry in storage, /// the default for its type. - pub fn take_or_default(key: &[u8]) -> T { + pub fn take_or_default(key: &[u8]) -> T { take(key).unwrap_or_else(Default::default) } /// Return the value of the item in storage under `key`, or `default_value` if there is no /// explicit entry. Ensure there is no explicit entry on return. - pub fn take_or(key: &[u8], default_value: T) -> T { + pub fn take_or(key: &[u8], default_value: T) -> T { take(key).unwrap_or(default_value) } /// Return the value of the item in storage under `key`, or `default_value()` if there is no /// explicit entry. Ensure there is no explicit entry on return. - pub fn take_or_else T>(key: &[u8], default_value: F) -> T { + pub fn take_or_else T>(key: &[u8], default_value: F) -> T { take(key).unwrap_or_else(default_value) } @@ -476,7 +476,7 @@ pub mod unhashed { /// A trait to conveniently store a vector of storable data. pub trait StorageVec { - type Item: Default + Sized + Slicable; + type Item: Default + Sized + Codec; const PREFIX: &'static [u8]; /// Get the current set of items. diff --git a/substrate/substrate/runtime/consensus/src/lib.rs b/substrate/substrate/runtime/consensus/src/lib.rs index cadbd9e865..13d40afe5e 100644 --- a/substrate/substrate/runtime/consensus/src/lib.rs +++ b/substrate/substrate/runtime/consensus/src/lib.rs @@ -48,8 +48,8 @@ use primitives::bft::MisbehaviorReport; pub const AUTHORITY_AT: &'static [u8] = b":auth:"; pub const AUTHORITY_COUNT: &'static [u8] = b":auth:len"; -struct AuthorityStorageVec(rstd::marker::PhantomData); -impl StorageVec for AuthorityStorageVec { +struct AuthorityStorageVec(rstd::marker::PhantomData); +impl StorageVec for AuthorityStorageVec { type Item = S; const PREFIX: &'static [u8] = AUTHORITY_AT; } @@ -147,7 +147,7 @@ impl Default for GenesisConfig { impl primitives::BuildStorage for GenesisConfig { fn build_storage(self) -> ::std::result::Result { - use codec::{Slicable, KeyedVec}; + use codec::{Encode, KeyedVec}; let auth_count = self.authorities.len() as u32; let mut r: runtime_io::TestExternalities = self.authorities.into_iter().enumerate().map(|(i, v)| ((i as u32).to_keyed_vec(AUTHORITY_AT), v.encode()) diff --git a/substrate/substrate/runtime/contract/src/lib.rs b/substrate/substrate/runtime/contract/src/lib.rs index bc51673fd4..9215644466 100644 --- a/substrate/substrate/runtime/contract/src/lib.rs +++ b/substrate/substrate/runtime/contract/src/lib.rs @@ -37,7 +37,7 @@ extern crate assert_matches; extern crate wabt; use rstd::prelude::*; -use codec::Slicable; +use codec::{Codec, Decode}; use parity_wasm::elements::{self, External, MemoryType}; use pwasm_utils::rules; @@ -49,9 +49,9 @@ use pwasm_utils::rules; /// operations are implicitly performed on that account. pub trait Ext { /// The indentifier of an account. - type AccountId: Slicable + Clone; + type AccountId: Codec + Clone; /// The balance of an account. - type Balance: Slicable; + type Balance: Codec; /// Returns the storage entry of the executing account by the given key. fn get_storage(&self, key: &[u8]) -> Option>; diff --git a/substrate/substrate/runtime/council/src/lib.rs b/substrate/substrate/runtime/council/src/lib.rs index e6c3c9b416..3c27021b6b 100644 --- a/substrate/substrate/runtime/council/src/lib.rs +++ b/substrate/substrate/runtime/council/src/lib.rs @@ -591,7 +591,7 @@ impl Default for GenesisConfig { impl primitives::BuildStorage for GenesisConfig { fn build_storage(self) -> ::std::result::Result { - use codec::Slicable; + use codec::Encode; use runtime_io::twox_128; Ok(map![ diff --git a/substrate/substrate/runtime/democracy/src/lib.rs b/substrate/substrate/runtime/democracy/src/lib.rs index c20d60d2de..3b256793ac 100644 --- a/substrate/substrate/runtime/democracy/src/lib.rs +++ b/substrate/substrate/runtime/democracy/src/lib.rs @@ -339,7 +339,7 @@ impl Default for GenesisConfig { impl primitives::BuildStorage for GenesisConfig { fn build_storage(self) -> ::std::result::Result { - use codec::Slicable; + use codec::Encode; use runtime_io::twox_128; Ok(map![ diff --git a/substrate/substrate/runtime/democracy/src/vote_threshold.rs b/substrate/substrate/runtime/democracy/src/vote_threshold.rs index 8512417b03..b9976d3642 100644 --- a/substrate/substrate/runtime/democracy/src/vote_threshold.rs +++ b/substrate/substrate/runtime/democracy/src/vote_threshold.rs @@ -17,7 +17,7 @@ //! Voting thresholds. use primitives::traits::{Zero, IntegerSquareRoot}; -use codec::{Input, Slicable}; +use codec::{Decode, Encode, Input}; use rstd::ops::{Add, Mul, Div, Rem}; /// A means of determining if a vote is past pass threshold. @@ -32,7 +32,7 @@ pub enum VoteThreshold { SimpleMajority, } -impl Slicable for VoteThreshold { +impl Decode for VoteThreshold { fn decode(input: &mut I) -> Option { input.read_byte().and_then(|v| match v { 0 => Some(VoteThreshold::SuperMajorityApprove), @@ -41,7 +41,9 @@ impl Slicable for VoteThreshold { _ => None, }) } +} +impl Encode for VoteThreshold { fn using_encoded R>(&self, f: F) -> R { f(&[match *self { VoteThreshold::SuperMajorityApprove => 0u8, diff --git a/substrate/substrate/runtime/executive/src/lib.rs b/substrate/substrate/runtime/executive/src/lib.rs index 8551580df7..3d30618a4a 100644 --- a/substrate/substrate/runtime/executive/src/lib.rs +++ b/substrate/substrate/runtime/executive/src/lib.rs @@ -55,7 +55,7 @@ use rstd::result; use runtime_support::StorageValue; use primitives::traits::{self, Header, Zero, One, Checkable, Applyable, CheckEqual, Executable, MakePayment, Hash, AuxLookup}; -use codec::Slicable; +use codec::{Codec, Encode}; use system::extrinsics_root; use primitives::{ApplyOutcome, ApplyError}; @@ -89,7 +89,7 @@ impl< Payment: MakePayment, Finalisation: Executable, > Executive where - Block::Extrinsic: Checkable Result> + Slicable, + Block::Extrinsic: Checkable Result> + Codec, Result>>::Checked: Applyable { /// Start the execution of a particular block. diff --git a/substrate/substrate/runtime/primitives/src/bft.rs b/substrate/substrate/runtime/primitives/src/bft.rs index 111c265233..12c8c141ca 100644 --- a/substrate/substrate/runtime/primitives/src/bft.rs +++ b/substrate/substrate/runtime/primitives/src/bft.rs @@ -17,7 +17,7 @@ //! Message formats for the BFT consensus layer. use rstd::prelude::*; -use codec::{Slicable, Input}; +use codec::{Decode, Encode, Input, Output}; use substrate_primitives::{AuthorityId, Signature}; #[derive(Clone, Copy, PartialEq, Eq)] @@ -51,59 +51,58 @@ pub enum Action { AdvanceRound(u32), } -impl Slicable for Action { - fn encode(&self) -> Vec { - let mut v = Vec::new(); +impl Encode for Action { + fn encode_to(&self, dest: &mut T) { match *self { Action::Propose(ref round, ref block) => { - v.push(ActionKind::Propose as u8); - round.using_encoded(|s| v.extend(s)); - block.using_encoded(|s| v.extend(s)); + dest.push_byte(ActionKind::Propose as u8); + dest.push(round); + dest.push(block); } Action::ProposeHeader(ref round, ref hash) => { - v.push(ActionKind::ProposeHeader as u8); - round.using_encoded(|s| v.extend(s)); - hash.using_encoded(|s| v.extend(s)); + dest.push_byte(ActionKind::ProposeHeader as u8); + dest.push(round); + dest.push(hash); } Action::Prepare(ref round, ref hash) => { - v.push(ActionKind::Prepare as u8); - round.using_encoded(|s| v.extend(s)); - hash.using_encoded(|s| v.extend(s)); + dest.push_byte(ActionKind::Prepare as u8); + dest.push(round); + dest.push(hash); } Action::Commit(ref round, ref hash) => { - v.push(ActionKind::Commit as u8); - round.using_encoded(|s| v.extend(s)); - hash.using_encoded(|s| v.extend(s)); + dest.push_byte(ActionKind::Commit as u8); + dest.push(round); + dest.push(hash); } Action::AdvanceRound(ref round) => { - v.push(ActionKind::AdvanceRound as u8); - round.using_encoded(|s| v.extend(s)); + dest.push_byte(ActionKind::AdvanceRound as u8); + dest.push(round); } } - - v } +} +impl Decode for Action { fn decode(value: &mut I) -> Option { match i8::decode(value) { Some(x) if x == ActionKind::Propose as i8 => { - let (round, block) = Slicable::decode(value)?; + let (round, block) = Decode::decode(value)?; Some(Action::Propose(round, block)) } Some(x) if x == ActionKind::ProposeHeader as i8 => { - let (round, hash) = Slicable::decode(value)?; + let (round, hash) = Decode::decode(value)?; Some(Action::ProposeHeader(round, hash)) } Some(x) if x == ActionKind::Prepare as i8 => { - let (round, hash) = Slicable::decode(value)?; + let (round, hash) = Decode::decode(value)?; Some(Action::Prepare(round, hash)) } Some(x) if x == ActionKind::Commit as i8 => { - let (round, hash) = Slicable::decode(value)?; + let (round, hash) = Decode::decode(value)?; Some(Action::Commit(round, hash)) } Some(x) if x == ActionKind::AdvanceRound as i8 => { - Slicable::decode(value).map(Action::AdvanceRound) + Decode::decode(value).map(Action::AdvanceRound) } _ => None, } @@ -123,17 +122,18 @@ pub struct Message { pub action: Action, } -impl Slicable for Message { - fn encode(&self) -> Vec { - let mut v = self.parent.encode(); - self.action.using_encoded(|s| v.extend(s)); - v +impl Encode for Message { + fn encode_to(&self, dest: &mut T) { + dest.push(&self.parent); + dest.push(&self.action); } +} +impl Decode for Message { fn decode(value: &mut I) -> Option { Some(Message { - parent: Slicable::decode(value)?, - action: Slicable::decode(value)?, + parent: Decode::decode(value)?, + action: Decode::decode(value)?, }) } } @@ -150,22 +150,20 @@ pub struct Justification { pub signatures: Vec<(AuthorityId, Signature)> } -impl Slicable for Justification { - fn encode(&self) -> Vec { - let mut v = Vec::new(); - - self.round_number.using_encoded(|s| v.extend(s)); - self.hash.using_encoded(|s| v.extend(s)); - self.signatures.using_encoded(|s| v.extend(s)); - - v +impl Encode for Justification { + fn encode_to(&self, dest: &mut T) { + dest.push(&self.round_number); + dest.push(&self.hash); + dest.push(&self.signatures); } +} +impl Decode for Justification { fn decode(value: &mut I) -> Option { Some(Justification { - round_number: Slicable::decode(value)?, - hash: Slicable::decode(value)?, - signatures: Slicable::decode(value)?, + round_number: Decode::decode(value)?, + hash: Decode::decode(value)?, + signatures: Decode::decode(value)?, }) } } @@ -213,35 +211,34 @@ pub struct MisbehaviorReport { pub misbehavior: MisbehaviorKind, } -impl Slicable for MisbehaviorReport { - fn encode(&self) -> Vec { - let mut v = Vec::new(); - self.parent_hash.using_encoded(|s| v.extend(s)); - self.parent_number.using_encoded(|s| v.extend(s)); - self.target.using_encoded(|s| v.extend(s)); +impl Encode for MisbehaviorReport { + fn encode_to(&self, dest: &mut T) { + dest.push(&self.parent_hash); + dest.push(&self.parent_number); + dest.push(&self.target); match self.misbehavior { MisbehaviorKind::BftDoublePrepare(ref round, (ref h_a, ref s_a), (ref h_b, ref s_b)) => { - (MisbehaviorCode::BftDoublePrepare as i8).using_encoded(|s| v.extend(s)); - round.using_encoded(|s| v.extend(s)); - h_a.using_encoded(|s| v.extend(s)); - s_a.using_encoded(|s| v.extend(s)); - h_b.using_encoded(|s| v.extend(s)); - s_b.using_encoded(|s| v.extend(s)); + dest.push(&(MisbehaviorCode::BftDoublePrepare as i8)); + dest.push(round); + dest.push(h_a); + dest.push(s_a); + dest.push(h_b); + dest.push(s_b); } MisbehaviorKind::BftDoubleCommit(ref round, (ref h_a, ref s_a), (ref h_b, ref s_b)) => { - (MisbehaviorCode::BftDoubleCommit as i8).using_encoded(|s| v.extend(s)); - round.using_encoded(|s| v.extend(s)); - h_a.using_encoded(|s| v.extend(s)); - s_a.using_encoded(|s| v.extend(s)); - h_b.using_encoded(|s| v.extend(s)); - s_b.using_encoded(|s| v.extend(s)); + dest.push(&(MisbehaviorCode::BftDoubleCommit as i8)); + dest.push(round); + dest.push(h_a); + dest.push(s_a); + dest.push(h_b); + dest.push(s_b); } } - - v } +} +impl Decode for MisbehaviorReport { fn decode(input: &mut I) -> Option { let parent_hash = Hash::decode(input)?; let parent_number = Number::decode(input)?; diff --git a/substrate/substrate/runtime/primitives/src/generic.rs b/substrate/substrate/runtime/primitives/src/generic.rs index 863dfb7735..1f466e2e9c 100644 --- a/substrate/substrate/runtime/primitives/src/generic.rs +++ b/substrate/substrate/runtime/primitives/src/generic.rs @@ -23,7 +23,7 @@ use std::fmt; use serde::{Deserialize, Deserializer}; use rstd::prelude::*; -use codec::{Slicable, Input}; +use codec::{Decode, Encode, Codec, Input, Output}; use runtime_support::AuxDispatchable; use traits::{self, Member, SimpleArithmetic, SimpleBitOps, MaybeDisplay, Block as BlockT, Header as HeaderT, Hash as HashT}; @@ -42,27 +42,29 @@ pub struct Extrinsic { pub function: Call, } -impl Slicable for Extrinsic where - Address: Member + Slicable + MaybeDisplay, - Index: Member + Slicable + MaybeDisplay + SimpleArithmetic, - Call: Member + Slicable +impl Decode for Extrinsic where + Address: Decode, + Index: Decode, + Call: Decode, { fn decode(input: &mut I) -> Option { Some(Extrinsic { - signed: Slicable::decode(input)?, - index: Slicable::decode(input)?, - function: Slicable::decode(input)?, + signed: Decode::decode(input)?, + index: Decode::decode(input)?, + function: Decode::decode(input)?, }) } +} - fn encode(&self) -> Vec { - let mut v = Vec::new(); - - self.signed.using_encoded(|s| v.extend(s)); - self.index.using_encoded(|s| v.extend(s)); - self.function.using_encoded(|s| v.extend(s)); - - v +impl Encode for Extrinsic where + Address: Encode, + Index: Encode, + Call: Encode, +{ + fn encode_to(&self, dest: &mut T) { + dest.push(&self.signed); + dest.push(&self.index); + dest.push(&self.function); } } @@ -105,7 +107,7 @@ where Signature: traits::Verify + Eq + Default, AccountId: Member + Default + MaybeDisplay, ::MaybeUnsigned: Member, - Extrinsic: Slicable, + Extrinsic: Codec, ThisLookup: FnOnce(Address) -> Result, { type Checked = CheckedExtrinsic; @@ -133,23 +135,32 @@ where } } -impl Slicable for UncheckedExtrinsic where - Signature: Slicable, - Extrinsic: Slicable, +impl Decode + for UncheckedExtrinsic +where + Signature: Decode, + Extrinsic: Decode, { fn decode(input: &mut I) -> Option { // This is a little more complicated than usual since the binary format must be compatible // with substrate's generic `Vec` type. Basically this just means accepting that there // will be a prefix of u32, which has the total number of bytes following (we don't need // to use this). - let _length_do_not_remove_me_see_above: u32 = Slicable::decode(input)?; + let _length_do_not_remove_me_see_above: u32 = Decode::decode(input)?; Some(UncheckedExtrinsic::new( - Slicable::decode(input)?, - Slicable::decode(input)? + Decode::decode(input)?, + Decode::decode(input)? )) } +} +impl Encode + for UncheckedExtrinsic +where + Signature: Encode, + Extrinsic: Encode, +{ fn encode(&self) -> Vec { let mut v = Vec::new(); @@ -157,9 +168,8 @@ impl Slicable for UncheckedExtrinsic. we'll make room for it here, then overwrite once we know the length. v.extend(&[0u8; 4]); - self.extrinsic.using_encoded(|s| v.extend(s)); - - self.signature.using_encoded(|s| v.extend(s)); + self.extrinsic.encode_to(&mut v); + self.signature.encode_to(&mut v); let length = (v.len() - 4) as u32; length.using_encoded(|s| v[0..4].copy_from_slice(s)); @@ -230,18 +240,20 @@ pub struct Digest { pub logs: Vec, } -impl Slicable for Digest where - Item: Member + Default + Slicable -{ +impl Decode for Digest { fn decode(input: &mut I) -> Option { - Some(Digest { logs: Slicable::decode(input)? }) - } - fn using_encoded R>(&self, f: F) -> R { - self.logs.using_encoded(f) + Some(Digest { logs: Decode::decode(input)? }) } } + +impl Encode for Digest { + fn encode_to(&self, dest: &mut T) { + self.logs.encode_to(dest) + } +} + impl traits::Digest for Digest where - Item: Member + Default + Slicable + Item: Member + Default + Codec { type Item = Item; fn push(&mut self, item: Self::Item) { @@ -307,38 +319,43 @@ impl<'a, Number: 'a, Hash: 'a + HashT, DigestItem: 'a> Deserialize<'a> for Heade } } -impl Slicable for Header where - Number: Member + Slicable + MaybeDisplay + SimpleArithmetic + Slicable, +impl Decode for Header where + Number: Decode, Hash: HashT, - DigestItem: Member + Default + Slicable, - Hash::Output: Default + Member + MaybeDisplay + SimpleBitOps + Slicable, + Hash::Output: Decode, + DigestItem: Decode, { fn decode(input: &mut I) -> Option { Some(Header { - parent_hash: Slicable::decode(input)?, - number: Slicable::decode(input)?, - state_root: Slicable::decode(input)?, - extrinsics_root: Slicable::decode(input)?, - digest: Slicable::decode(input)?, + parent_hash: Decode::decode(input)?, + number: Decode::decode(input)?, + state_root: Decode::decode(input)?, + extrinsics_root: Decode::decode(input)?, + digest: Decode::decode(input)?, }) } +} - fn encode(&self) -> Vec { - let mut v = Vec::new(); - self.parent_hash.using_encoded(|s| v.extend(s)); - self.number.using_encoded(|s| v.extend(s)); - self.state_root.using_encoded(|s| v.extend(s)); - self.extrinsics_root.using_encoded(|s| v.extend(s)); - self.digest.using_encoded(|s| v.extend(s)); - v +impl Encode for Header where + Number: Encode, + Hash: HashT, + Hash::Output: Encode, + DigestItem: Encode, +{ + fn encode_to(&self, dest: &mut T) { + dest.push(&self.parent_hash); + dest.push(&self.number); + dest.push(&self.state_root); + dest.push(&self.extrinsics_root); + dest.push(&self.digest); } } impl traits::Header for Header where - Number: Member + ::rstd::hash::Hash + Copy + Slicable + MaybeDisplay + SimpleArithmetic + Slicable, + Number: Member + ::rstd::hash::Hash + Copy + Codec + MaybeDisplay + SimpleArithmetic + Codec, Hash: HashT, - DigestItem: Member + Default + Slicable, - Hash::Output: Default + ::rstd::hash::Hash + Copy + Member + MaybeDisplay + SimpleBitOps + Slicable, + DigestItem: Member + Default + Codec, + Hash::Output: Default + ::rstd::hash::Hash + Copy + Member + MaybeDisplay + SimpleBitOps + Codec, { type Number = Number; type Hash = ::Output; @@ -374,10 +391,10 @@ impl traits::Header for Header Header where - Number: Member + ::rstd::hash::Hash + Copy + Slicable + MaybeDisplay + SimpleArithmetic + Slicable, + Number: Member + ::rstd::hash::Hash + Copy + Codec + MaybeDisplay + SimpleArithmetic + Codec, Hash: HashT, - DigestItem: Member + Default + Slicable, - Hash::Output: Default + ::rstd::hash::Hash + Copy + Member + MaybeDisplay + SimpleBitOps + Slicable, + DigestItem: Member + Default + Codec, + Hash::Output: Default + ::rstd::hash::Hash + Copy + Member + MaybeDisplay + SimpleBitOps + Codec, { /// Convenience helper for computing the hash of the header without having /// to import the trait. @@ -431,26 +448,26 @@ pub struct Block { pub extrinsics: Vec, } -impl Slicable for Block { +impl Decode for Block { fn decode(input: &mut I) -> Option { Some(Block { - header: Slicable::decode(input)?, - extrinsics: Slicable::decode(input)?, + header: Decode::decode(input)?, + extrinsics: Decode::decode(input)?, }) } +} - fn encode(&self) -> Vec { - let mut v: Vec = Vec::new(); - v.extend(self.header.encode()); - v.extend(self.extrinsics.encode()); - v +impl Encode for Block { + fn encode_to(&self, dest: &mut T) { + dest.push(&self.header); + dest.push(&self.extrinsics); } } impl traits::Block for Block where Header: HeaderT, - Extrinsic: Member + Slicable, + Extrinsic: Member + Codec, { type Extrinsic = Extrinsic; type Header = Header; @@ -482,25 +499,29 @@ pub struct SignedBlock { pub justification: Justification, } -impl Slicable for SignedBlock { +impl Decode + for SignedBlock +{ fn decode(input: &mut I) -> Option { Some(SignedBlock { - block: Slicable::decode(input)?, - justification: Slicable::decode(input)?, + block: Decode::decode(input)?, + justification: Decode::decode(input)?, }) } +} - fn encode(&self) -> Vec { - let mut v: Vec = Vec::new(); - v.extend(self.block.encode()); - v.extend(self.justification.encode()); - v +impl Encode + for SignedBlock +{ + fn encode_to(&self, dest: &mut T) { + dest.push(&self.block); + dest.push(&self.justification); } } #[cfg(test)] mod tests { - use codec::Slicable; + use codec::{Decode, Encode}; use substrate_primitives::{H256, H512}; use super::{Digest, Header, UncheckedExtrinsic, Extrinsic}; diff --git a/substrate/substrate/runtime/primitives/src/lib.rs b/substrate/substrate/runtime/primitives/src/lib.rs index f073dc7280..2a67b4764b 100644 --- a/substrate/substrate/runtime/primitives/src/lib.rs +++ b/substrate/substrate/runtime/primitives/src/lib.rs @@ -81,9 +81,16 @@ impl Verify for Ed25519Signature { } } -impl codec::Slicable for Ed25519Signature { - fn decode(input: &mut I) -> Option { Some(Ed25519Signature(codec::Slicable::decode(input)?,)) } - fn using_encoded R>(&self, f: F) -> R { self.0.using_encoded(f) } +impl codec::Decode for Ed25519Signature { + fn decode(input: &mut I) -> Option { + Some(Ed25519Signature(codec::Decode::decode(input)?,)) + } +} + +impl codec::Encode for Ed25519Signature { + fn using_encoded R>(&self, f: F) -> R { + self.0.using_encoded(f) + } } impl From for Ed25519Signature { @@ -102,7 +109,7 @@ pub enum ApplyOutcome { /// Failed application (extrinsic was probably a no-op other than fees). Fail = 1, } -impl codec::Slicable for ApplyOutcome { +impl codec::Decode for ApplyOutcome { fn decode(input: &mut I) -> Option { match input.read_byte()? { x if x == ApplyOutcome::Success as u8 => Some(ApplyOutcome::Success), @@ -110,6 +117,8 @@ impl codec::Slicable for ApplyOutcome { _ => None, } } +} +impl codec::Encode for ApplyOutcome { fn using_encoded R>(&self, f: F) -> R { f(&[*self as u8]) } @@ -129,7 +138,8 @@ pub enum ApplyError { /// Sending account had too low a balance. CantPay = 3, } -impl codec::Slicable for ApplyError { + +impl codec::Decode for ApplyError { fn decode(input: &mut I) -> Option { match input.read_byte()? { x if x == ApplyError::BadSignature as u8 => Some(ApplyError::BadSignature), @@ -139,6 +149,9 @@ impl codec::Slicable for ApplyError { _ => None, } } +} + +impl codec::Encode for ApplyError { fn using_encoded R>(&self, f: F) -> R { f(&[*self as u8]) } @@ -179,9 +192,16 @@ impl Verify for MaybeUnsigned where } } -impl codec::Slicable for MaybeUnsigned { - fn decode(input: &mut I) -> Option { Some(MaybeUnsigned(codec::Slicable::decode(input)?)) } - fn using_encoded R>(&self, f: F) -> R { self.0.using_encoded(f) } +impl codec::Decode for MaybeUnsigned { + fn decode(input: &mut I) -> Option { + Some(MaybeUnsigned(codec::Decode::decode(input)?)) + } +} + +impl codec::Encode for MaybeUnsigned { + fn encode_to(&self, dest: &mut W) { + self.0.encode_to(dest) + } } impl From for MaybeUnsigned { @@ -192,7 +212,7 @@ impl From for MaybeUnsigned { /// Verify a signature on an encoded value in a lazy manner. This can be /// an optimization if the signature scheme has an "unsigned" escape hash. -pub fn verify_encoded_lazy(sig: &V, item: &T, signer: &V::Signer) -> bool { +pub fn verify_encoded_lazy(sig: &V, item: &T, signer: &V::Signer) -> bool { // The `Lazy` trait expresses something like `X: FnMut &'a T>`. // unfortunately this is a lifetime relationship that can't // be expressed without generic associated types, better unification of HRTBs in type position, diff --git a/substrate/substrate/runtime/primitives/src/testing.rs b/substrate/substrate/runtime/primitives/src/testing.rs index 12e347e1e3..6ad72eb5fb 100644 --- a/substrate/substrate/runtime/primitives/src/testing.rs +++ b/substrate/substrate/runtime/primitives/src/testing.rs @@ -18,7 +18,7 @@ use serde::{Serialize, de::DeserializeOwned}; use std::fmt::Debug; -use codec::{Slicable, Input}; +use codec::{Decode, Encode, Codec, Input, Output}; use runtime_support::AuxDispatchable; use traits::{self, Checkable, Applyable, BlakeTwo256}; @@ -28,14 +28,19 @@ pub use substrate_primitives::H256; pub struct Digest { pub logs: Vec, } -impl Slicable for Digest { + +impl Decode for Digest { fn decode(input: &mut I) -> Option { Vec::::decode(input).map(|logs| Digest { logs }) } +} + +impl Encode for Digest { fn using_encoded R>(&self, f: F) -> R { self.logs.using_encoded(f) } } + impl traits::Digest for Digest { type Item = u64; fn push(&mut self, item: Self::Item) { @@ -53,27 +58,29 @@ pub struct Header { pub extrinsics_root: H256, pub digest: Digest, } -impl Slicable for Header { + +impl Decode for Header { fn decode(input: &mut I) -> Option { Some(Header { - parent_hash: Slicable::decode(input)?, - number: Slicable::decode(input)?, - state_root: Slicable::decode(input)?, - extrinsics_root: Slicable::decode(input)?, - digest: Slicable::decode(input)?, + parent_hash: Decode::decode(input)?, + number: Decode::decode(input)?, + state_root: Decode::decode(input)?, + extrinsics_root: Decode::decode(input)?, + digest: Decode::decode(input)?, }) } +} - fn encode(&self) -> Vec { - let mut v = Vec::new(); - self.parent_hash.using_encoded(|s| v.extend(s)); - self.number.using_encoded(|s| v.extend(s)); - self.state_root.using_encoded(|s| v.extend(s)); - self.extrinsics_root.using_encoded(|s| v.extend(s)); - self.digest.using_encoded(|s| v.extend(s)); - v +impl Encode for Header { + fn encode_to(&self, dest: &mut T) { + dest.push(&self.parent_hash); + dest.push(&self.number); + dest.push(&self.state_root); + dest.push(&self.extrinsics_root); + dest.push(&self.digest); } } + impl traits::Header for Header { type Number = u64; type Hashing = BlakeTwo256; @@ -109,25 +116,25 @@ impl traits::Header for Header { } #[derive(PartialEq, Eq, Clone, Serialize, Deserialize, Debug)] -pub struct Block { +pub struct Block { pub header: Header, pub extrinsics: Vec, } -impl Slicable for Block { +impl Decode for Block { fn decode(input: &mut I) -> Option { Some(Block { - header: Slicable::decode(input)?, - extrinsics: Slicable::decode(input)?, + header: Decode::decode(input)?, + extrinsics: Decode::decode(input)?, }) } - fn encode(&self) -> Vec { - let mut v: Vec = Vec::new(); - v.extend(self.header.encode()); - v.extend(self.extrinsics.encode()); - v +} +impl Encode for Block { + fn encode_to(&self, dest: &mut T) { + dest.push(&self.header); + dest.push(&self.extrinsics); } } -impl traits::Block for Block { +impl traits::Block for Block { type Extrinsic = Xt; type Header = Header; type Hash =
::Hash; @@ -147,21 +154,25 @@ impl(pub (u64, u64, Call)); +pub struct TestXt(pub (u64, u64, Call)); -impl Slicable for TestXt { +impl Decode for TestXt { fn decode(input: &mut I) -> Option { - Some(TestXt(Slicable::decode(input)?)) - } - fn encode(&self) -> Vec { - self.0.encode() + Some(TestXt(Decode::decode(input)?)) } } -impl Checkable for TestXt { + +impl Encode for TestXt { + fn encode_to(&self, dest: &mut T) { + self.0.encode_to(dest) + } +} + +impl Checkable for TestXt { type Checked = Self; fn check_with(self, _: Context) -> Result { Ok(self) } } -impl + Slicable + Sized + Send + Sync + Serialize + DeserializeOwned + Clone + Eq + Debug> Applyable for TestXt { +impl + Codec + Sized + Send + Sync + Serialize + DeserializeOwned + Clone + Eq + Debug> Applyable for TestXt { type AccountId = u64; type Index = u64; fn sender(&self) -> &u64 { &(self.0).0 } diff --git a/substrate/substrate/runtime/primitives/src/traits.rs b/substrate/substrate/runtime/primitives/src/traits.rs index 289e10a388..f6fd79077f 100644 --- a/substrate/substrate/runtime/primitives/src/traits.rs +++ b/substrate/substrate/runtime/primitives/src/traits.rs @@ -22,7 +22,7 @@ use runtime_io; #[cfg(feature = "std")] use std::fmt::{Debug, Display}; #[cfg(feature = "std")] use serde::{Serialize, de::DeserializeOwned}; use substrate_primitives; -use codec::Slicable; +use codec::{Codec, Encode}; pub use integer_sqrt::IntegerSquareRoot; pub use num_traits::{Zero, One, Bounded}; use rstd::ops::{Add, Sub, Mul, Div, Rem, AddAssign, SubAssign, MulAssign, DivAssign, RemAssign}; @@ -194,8 +194,8 @@ pub trait Hash: 'static + MaybeSerializeDebug + Clone + Eq + PartialEq { // Stup fn hash(s: &[u8]) -> Self::Output; /// Produce the hash of some codec-encodable value. - fn hash_of(s: &S) -> Self::Output { - Slicable::using_encoded(s, Self::hash) + fn hash_of(s: &S) -> Self::Output { + Encode::using_encoded(s, Self::hash) } /// Produce the patricia-trie root of a mapping from indices to byte slices. @@ -307,7 +307,7 @@ pub trait Member: Send + Sync + Sized + MaybeSerializeDebug + Eq + PartialEq + C impl Member for T {} /// Something that acts like a `Digest` - it can have `Log`s `push`ed onto it and these `Log`s are -/// each `Slicable`. +/// each `Codec`. pub trait Digest { type Item: Member; fn push(&mut self, item: Self::Item); @@ -318,9 +318,9 @@ pub trait Digest { /// `parent_hash`, as well as a `digest` and a block `number`. /// /// You can also create a `new` one from those fields. -pub trait Header: Clone + Send + Sync + Slicable + Eq + MaybeSerializeDebug + 'static { - type Number: Member + ::rstd::hash::Hash + Copy + MaybeDisplay + SimpleArithmetic + Slicable; - type Hash: Member + ::rstd::hash::Hash + Copy + MaybeDisplay + Default + SimpleBitOps + Slicable + AsRef<[u8]>; +pub trait Header: Clone + Send + Sync + Codec + Eq + MaybeSerializeDebug + 'static { + type Number: Member + ::rstd::hash::Hash + Copy + MaybeDisplay + SimpleArithmetic + Codec; + type Hash: Member + ::rstd::hash::Hash + Copy + MaybeDisplay + Default + SimpleBitOps + Codec + AsRef<[u8]>; type Hashing: Hash; type Digest: Member + Default; @@ -356,10 +356,10 @@ pub trait Header: Clone + Send + Sync + Slicable + Eq + MaybeSerializeDebug + 's /// `Extrinsic` piece of information as well as a `Header`. /// /// You can get an iterator over each of the `extrinsics` and retrieve the `header`. -pub trait Block: Clone + Send + Sync + Slicable + Eq + MaybeSerializeDebug + 'static { - type Extrinsic: Member + Slicable; +pub trait Block: Clone + Send + Sync + Codec + Eq + MaybeSerializeDebug + 'static { + type Extrinsic: Member + Codec; type Header: Header; - type Hash: Member + ::rstd::hash::Hash + Copy + MaybeDisplay + Default + SimpleBitOps + Slicable + AsRef<[u8]>; + type Hash: Member + ::rstd::hash::Hash + Copy + MaybeDisplay + Default + SimpleBitOps + Codec + AsRef<[u8]>; fn header(&self) -> &Self::Header; fn extrinsics(&self) -> &[Self::Extrinsic]; diff --git a/substrate/substrate/runtime/session/src/lib.rs b/substrate/substrate/runtime/session/src/lib.rs index 74debe5a84..c9ede52408 100644 --- a/substrate/substrate/runtime/session/src/lib.rs +++ b/substrate/substrate/runtime/session/src/lib.rs @@ -246,7 +246,7 @@ impl primitives::BuildStorage for GenesisConfig { fn build_storage(self) -> ::std::result::Result { use runtime_io::twox_128; - use codec::Slicable; + use codec::Encode; use primitives::traits::As; Ok(map![ twox_128(>::key()).to_vec() => self.session_length.encode(), diff --git a/substrate/substrate/runtime/staking/src/address.rs b/substrate/substrate/runtime/staking/src/address.rs index dc0769e4ad..249e0b20db 100644 --- a/substrate/substrate/runtime/staking/src/address.rs +++ b/substrate/substrate/runtime/staking/src/address.rs @@ -16,10 +16,9 @@ //! Address type that is union of index and id for an account. -use rstd::prelude::*; #[cfg(feature = "std")] use std::fmt; -use super::{Member, Slicable, As, Input}; +use super::{Member, Decode, Encode, As, Input, Output}; /// A vetted and verified extrinsic from the external world. #[derive(PartialEq, Eq, Clone)] @@ -59,45 +58,46 @@ fn need_more_than(a: T, b: T) -> Option { if a < b { Some(a) } else { None } } -impl Slicable for Address where - AccountId: Member + Slicable, - AccountIndex: Member + Slicable + PartialOrd + Ord + As + As + As + Copy, +impl Decode for Address where + AccountId: Member + Decode, + AccountIndex: Member + Decode + PartialOrd + Ord + As + As + As + Copy, { fn decode(input: &mut I) -> Option { Some(match input.read_byte()? { x @ 0x00...0xef => Address::Index(As::sa(x)), 0xfc => Address::Index(As::sa(need_more_than(0xef, u16::decode(input)?)?)), 0xfd => Address::Index(As::sa(need_more_than(0xffff, u32::decode(input)?)?)), - 0xfe => Address::Index(need_more_than(As::sa(0xffffffffu32), Slicable::decode(input)?)?), - 0xff => Address::Id(Slicable::decode(input)?), + 0xfe => Address::Index(need_more_than(As::sa(0xffffffffu32), Decode::decode(input)?)?), + 0xff => Address::Id(Decode::decode(input)?), _ => return None, }) } +} - fn encode(&self) -> Vec { - let mut v = Vec::new(); - +impl Encode for Address where + AccountId: Member + Encode, + AccountIndex: Member + Encode + PartialOrd + Ord + As + As + As + Copy, +{ + fn encode_to(&self, dest: &mut T) { match *self { Address::Id(ref i) => { - v.push(255); - i.using_encoded(|s| v.extend(s)); + dest.push_byte(255); + dest.push(i); } Address::Index(i) if i > As::sa(0xffffffffu32) => { - v.push(254); - i.using_encoded(|s| v.extend(s)); + dest.push_byte(254); + dest.push(&i); } Address::Index(i) if i > As::sa(0xffffu32) => { - v.push(253); - As::::as_(i).using_encoded(|s| v.extend(s)); + dest.push_byte(253); + dest.push(&As::::as_(i)); } Address::Index(i) if i >= As::sa(0xf0u32) => { - v.push(252); - As::::as_(i).using_encoded(|s| v.extend(s)); + dest.push_byte(252); + dest.push(&As::::as_(i)); } - Address::Index(i) => v.push(As::::as_(i)), + Address::Index(i) => dest.push_byte(As::::as_(i)), } - - v } } diff --git a/substrate/substrate/runtime/staking/src/double_map.rs b/substrate/substrate/runtime/staking/src/double_map.rs index 36c4be98d5..7c4db02f35 100644 --- a/substrate/substrate/runtime/staking/src/double_map.rs +++ b/substrate/substrate/runtime/staking/src/double_map.rs @@ -19,7 +19,7 @@ //! This implementation is somewhat specialized to the tracking of the storage of accounts. use rstd::prelude::*; -use codec::Slicable; +use codec::{Codec, Encode}; use runtime_support::storage::unhashed; use runtime_io::{blake2_256, twox_128}; @@ -29,7 +29,7 @@ use runtime_io::{blake2_256, twox_128}; fn first_part_of_key(k1: M::Key1) -> [u8; 16] { let mut raw_prefix = Vec::new(); raw_prefix.extend(M::PREFIX); - raw_prefix.extend(Slicable::encode(&k1)); + raw_prefix.extend(Encode::encode(&k1)); twox_128(&raw_prefix) } @@ -38,7 +38,7 @@ fn first_part_of_key(k1: M::Key1) -> [u8; 16] { /// The first part is hased by XX and then concatenated with a blake2 hash of `k2`. fn full_key(k1: M::Key1, k2: M::Key2) -> Vec { let first_part = first_part_of_key::(k1); - let second_part = blake2_256(&Slicable::encode(&k2)); + let second_part = blake2_256(&Encode::encode(&k2)); let mut k = Vec::new(); k.extend(&first_part); @@ -60,9 +60,9 @@ fn full_key(k1: M::Key1, k2: M::Key2) -> Vec { /// Blake2 is used for `Key2` is because it will be used as a for a key for contract's storage and /// thus will be susceptible for a untrusted input. pub trait StorageDoubleMap { - type Key1: Slicable; - type Key2: Slicable; - type Value: Slicable + Default; + type Key1: Codec; + type Key2: Codec; + type Value: Codec + Default; const PREFIX: &'static [u8]; diff --git a/substrate/substrate/runtime/staking/src/genesis_config.rs b/substrate/substrate/runtime/staking/src/genesis_config.rs index 9d29ab13a0..53d6f87c1b 100644 --- a/substrate/substrate/runtime/staking/src/genesis_config.rs +++ b/substrate/substrate/runtime/staking/src/genesis_config.rs @@ -20,7 +20,7 @@ use rstd::prelude::*; use runtime_io::twox_128; -use codec::Slicable; +use codec::Encode; use runtime_support::{StorageValue, StorageMap}; use primitives::traits::{Zero, As}; use {runtime_io, primitives}; diff --git a/substrate/substrate/runtime/staking/src/lib.rs b/substrate/substrate/runtime/staking/src/lib.rs index 5ad43f048c..4ae6f817cf 100644 --- a/substrate/substrate/runtime/staking/src/lib.rs +++ b/substrate/substrate/runtime/staking/src/lib.rs @@ -50,7 +50,7 @@ use account_db::State; use rstd::prelude::*; use rstd::{cmp, result}; use rstd::collections::btree_map::BTreeMap; -use codec::{Input, Slicable}; +use codec::{Encode, Decode, Codec, Input, Output}; use runtime_support::{StorageValue, StorageMap, Parameter}; use runtime_support::dispatch::Result; use session::OnSessionChange; @@ -110,8 +110,8 @@ impl ContractAddressFor for DummyContractAddressFor { impl ContractAddressFor for Hash where Hash: HashT, - AccountId: Sized + Slicable + From, - Hash::Output: Slicable + AccountId: Sized + Codec + From, + Hash::Output: Codec { fn contract_address_for(code: &[u8], origin: &AccountId) -> AccountId { let mut dest_pre = Hash::hash(code).encode(); @@ -122,12 +122,12 @@ impl ContractAddressFor for Hash where pub trait Trait: system::Trait + session::Trait { /// The balance of an account. - type Balance: Parameter + SimpleArithmetic + Slicable + Default + Copy + As + As + As; + type Balance: Parameter + SimpleArithmetic + Codec + Default + Copy + As + As + As; /// Function type to get the contract address given the creator. type DetermineContractAddress: ContractAddressFor; /// Type used for storing an account's index; implies the maximum number of accounts the system /// can hold. - type AccountIndex: Parameter + Member + Slicable + SimpleArithmetic + As + As + As + As + As + Copy; + type AccountIndex: Parameter + Member + Codec + SimpleArithmetic + As + As + As + As + As + Copy; } decl_module! { diff --git a/substrate/substrate/runtime/system/src/lib.rs b/substrate/substrate/runtime/system/src/lib.rs index e0c0f94a65..928a53212f 100644 --- a/substrate/substrate/runtime/system/src/lib.rs +++ b/substrate/substrate/runtime/system/src/lib.rs @@ -46,14 +46,14 @@ use safe_mix::TripletMix; #[cfg(any(feature = "std", test))] use rstd::marker::PhantomData; #[cfg(any(feature = "std", test))] -use codec::Slicable; +use codec::Encode; #[cfg(any(feature = "std", test))] use runtime_io::{twox_128, TestExternalities}; /// Compute the extrinsics root of a list of extrinsics. -pub fn extrinsics_root(extrinsics: &[E]) -> H::Output { - extrinsics_data_root::(extrinsics.iter().map(codec::Slicable::encode).collect()) +pub fn extrinsics_root(extrinsics: &[E]) -> H::Output { + extrinsics_data_root::(extrinsics.iter().map(codec::Encode::encode).collect()) } /// Compute the extrinsics root of a list of extrinsics. @@ -209,7 +209,7 @@ impl primitives::BuildStorage for GenesisConfig { fn build_storage(self) -> Result { use runtime_io::twox_128; - use codec::Slicable; + use codec::Encode; Ok(map![ twox_128(&>::key_for(T::BlockNumber::zero())).to_vec() => [69u8; 32].encode(), diff --git a/substrate/substrate/runtime/timestamp/src/lib.rs b/substrate/substrate/runtime/timestamp/src/lib.rs index f541e0a11f..ccb95e2b4d 100644 --- a/substrate/substrate/runtime/timestamp/src/lib.rs +++ b/substrate/substrate/runtime/timestamp/src/lib.rs @@ -128,7 +128,7 @@ impl runtime_primitives::BuildStorage for GenesisConfig { fn build_storage(self) -> ::std::result::Result { use runtime_io::twox_128; - use codec::Slicable; + use codec::Encode; Ok(map![ twox_128(>::key()).to_vec() => self.period.encode(), twox_128(>::key()).to_vec() => T::Moment::sa(0).encode() diff --git a/substrate/substrate/runtime/version/src/lib.rs b/substrate/substrate/runtime/version/src/lib.rs index c1bb43db81..4f4031220f 100644 --- a/substrate/substrate/runtime/version/src/lib.rs +++ b/substrate/substrate/runtime/version/src/lib.rs @@ -35,7 +35,9 @@ extern crate substrate_runtime_support as runtime_support; extern crate substrate_codec as codec; use rstd::prelude::*; -use codec::Slicable; +use codec::{Encode, Output}; +#[cfg(feature = "std")] +use codec::{Decode, Input}; #[cfg(feature = "std")] use std::borrow::Cow; @@ -134,30 +136,25 @@ impl RuntimeVersion { } } -impl Slicable for RuntimeVersion { - fn encode(&self) -> Vec { - let mut v = Vec::new(); - v.extend(codec::encode_slice(self.spec_name.as_bytes())); - v.extend(codec::encode_slice(self.impl_name.as_bytes())); - self.authoring_version.using_encoded(|s| v.extend(s)); - self.spec_version.using_encoded(|s| v.extend(s)); - self.impl_version.using_encoded(|s| v.extend(s)); - v +impl Encode for RuntimeVersion { + fn encode_to(&self, dest: &mut T) { + dest.push(self.spec_name.as_bytes()); + dest.push(self.impl_name.as_bytes()); + dest.push(&self.authoring_version); + dest.push(&self.spec_version); + dest.push(&self.impl_version); } +} - #[cfg(not(feature = "std"))] - fn decode(_value: &mut I) -> Option { - unreachable!() - } - - #[cfg(feature = "std")] - fn decode(value: &mut I) -> Option { +#[cfg(feature = "std")] +impl Decode for RuntimeVersion { + fn decode(value: &mut I) -> Option { Some(RuntimeVersion { spec_name: Cow::Owned(String::from_utf8_lossy(&Vec::decode(value)?).into()), impl_name: Cow::Owned(String::from_utf8_lossy(&Vec::decode(value)?).into()), - authoring_version: Slicable::decode(value)?, - spec_version: Slicable::decode(value)?, - impl_version: Slicable::decode(value)?, + authoring_version: Decode::decode(value)?, + spec_version: Decode::decode(value)?, + impl_version: Decode::decode(value)?, }) } } diff --git a/substrate/substrate/state-db/src/lib.rs b/substrate/substrate/state-db/src/lib.rs index 8e4e330333..f3bcc645bf 100644 --- a/substrate/substrate/state-db/src/lib.rs +++ b/substrate/substrate/state-db/src/lib.rs @@ -41,7 +41,7 @@ mod pruning; use std::fmt; use parking_lot::RwLock; -use codec::Slicable; +use codec::Codec; use std::collections::HashSet; use unfinalized::UnfinalizedOverlay; use pruning::RefWindow; @@ -50,8 +50,8 @@ use pruning::RefWindow; pub type DBValue = Vec; /// Basic set of requirements for the Block hash and node key types. -pub trait Hash: Send + Sync + Sized + Eq + PartialEq + Clone + Default + fmt::Debug + Slicable + std::hash::Hash + 'static {} -impl Hash for T {} +pub trait Hash: Send + Sync + Sized + Eq + PartialEq + Clone + Default + fmt::Debug + Codec + std::hash::Hash + 'static {} +impl Hash for T {} /// Backend database trait. Read-only. pub trait MetaDb { @@ -76,7 +76,7 @@ pub trait HashDb { pub enum Error { /// Database backend error. Db(E), - /// `Slicable` decoding error. + /// `Codec` decoding error. Decoding, } @@ -138,7 +138,7 @@ impl PruningMode { } } -fn to_meta_key(suffix: &[u8], data: &S) -> Vec { +fn to_meta_key(suffix: &[u8], data: &S) -> Vec { let mut buffer = data.encode(); buffer.extend(suffix); buffer diff --git a/substrate/substrate/state-db/src/pruning.rs b/substrate/substrate/state-db/src/pruning.rs index b5fbb553d9..afe3f8bad1 100644 --- a/substrate/substrate/state-db/src/pruning.rs +++ b/substrate/substrate/state-db/src/pruning.rs @@ -23,7 +23,7 @@ //! The changes are journaled in the DB. use std::collections::{HashMap, HashSet, VecDeque}; -use codec::{Slicable, self}; +use codec::{Decode, Encode, self}; use {CommitSet, Error, MetaDb, to_meta_key, Hash}; const LAST_PRUNED: &[u8] = b"last_pruned"; @@ -49,20 +49,20 @@ struct JournalRecord { deleted: Vec, } -impl Slicable for JournalRecord { - fn encode(&self) -> Vec { - let mut v = Vec::with_capacity(4096); - self.hash.using_encoded(|s| v.extend(s)); - self.inserted.using_encoded(|s| v.extend(s)); - self.deleted.using_encoded(|s| v.extend(s)); - v +impl Encode for JournalRecord { + fn encode_to(&self, dest: &mut T) { + dest.push(&self.hash); + dest.push(&self.inserted); + dest.push(&self.deleted); } +} +impl Decode for JournalRecord { fn decode(input: &mut I) -> Option { Some(JournalRecord { - hash: Slicable::decode(input)?, - inserted: Slicable::decode(input)?, - deleted: Slicable::decode(input)?, + hash: Decode::decode(input)?, + inserted: Decode::decode(input)?, + deleted: Decode::decode(input)?, }) } } @@ -91,7 +91,7 @@ impl RefWindow { let journal_key = to_journal_key(block); match db.get_meta(&journal_key).map_err(|e| Error::Db(e))? { Some(record) => { - let record: JournalRecord = Slicable::decode(&mut record.as_slice()).ok_or(Error::Decoding)?; + let record: JournalRecord = Decode::decode(&mut record.as_slice()).ok_or(Error::Decoding)?; trace!(target: "state-db", "Pruning journal entry {} ({} inserted, {} deleted)", block, record.inserted.len(), record.deleted.len()); pruning.import(&record.hash, journal_key, record.inserted.into_iter(), record.deleted); }, diff --git a/substrate/substrate/state-db/src/unfinalized.rs b/substrate/substrate/state-db/src/unfinalized.rs index e4cd5aa278..a6c5ceeb03 100644 --- a/substrate/substrate/state-db/src/unfinalized.rs +++ b/substrate/substrate/state-db/src/unfinalized.rs @@ -19,7 +19,7 @@ use std::collections::{HashMap, VecDeque}; use super::{Error, DBValue, ChangeSet, CommitSet, MetaDb, Hash, to_meta_key}; -use codec::{self, Slicable}; +use codec::{self, Decode, Encode}; const UNFINALIZED_JOURNAL: &[u8] = b"unfinalized_journal"; const LAST_FINALIZED: &[u8] = b"last_finalized"; @@ -38,22 +38,22 @@ struct JournalRecord { deleted: Vec, } -impl Slicable for JournalRecord { - fn encode(&self) -> Vec { - let mut v = Vec::with_capacity(4096); - self.hash.using_encoded(|s| v.extend(s)); - self.parent_hash.using_encoded(|s| v.extend(s)); - self.inserted.using_encoded(|s| v.extend(s)); - self.deleted.using_encoded(|s| v.extend(s)); - v +impl Encode for JournalRecord { + fn encode_to(&self, dest: &mut T) { + dest.push(&self.hash); + dest.push(&self.parent_hash); + dest.push(&self.inserted); + dest.push(&self.deleted); } +} +impl Decode for JournalRecord { fn decode(input: &mut I) -> Option { Some(JournalRecord { - hash: Slicable::decode(input)?, - parent_hash: Slicable::decode(input)?, - inserted: Slicable::decode(input)?, - deleted: Slicable::decode(input)?, + hash: Decode::decode(input)?, + parent_hash: Decode::decode(input)?, + inserted: Decode::decode(input)?, + deleted: Decode::decode(input)?, }) } } @@ -93,7 +93,7 @@ impl UnfinalizedOverlay { let journal_key = to_journal_key(block, index); match db.get_meta(&journal_key).map_err(|e| Error::Db(e))? { Some(record) => { - let record: JournalRecord = Slicable::decode(&mut record.as_slice()).ok_or(Error::Decoding)?; + let record: JournalRecord = Decode::decode(&mut record.as_slice()).ok_or(Error::Decoding)?; let overlay = BlockOverlay { hash: record.hash.clone(), journal_key, diff --git a/substrate/substrate/test-runtime/src/lib.rs b/substrate/substrate/test-runtime/src/lib.rs index ee4357aaee..6865ad4e28 100644 --- a/substrate/substrate/test-runtime/src/lib.rs +++ b/substrate/substrate/test-runtime/src/lib.rs @@ -51,7 +51,7 @@ extern crate substrate_runtime_version as runtime_version; pub mod system; use rstd::prelude::*; -use codec::Slicable; +use codec::{Encode, Decode}; use runtime_primitives::traits::{BlindCheckable, BlakeTwo256}; use runtime_primitives::Ed25519Signature; @@ -81,18 +81,18 @@ pub struct Transfer { pub nonce: u64, } -impl Slicable for Transfer { - fn encode(&self) -> Vec { - let mut v = Vec::new(); - self.from.using_encoded(|s| v.extend(s)); - self.to.using_encoded(|s| v.extend(s)); - self.amount.using_encoded(|s| v.extend(s)); - self.nonce.using_encoded(|s| v.extend(s)); - v +impl Encode for Transfer { + fn encode_to(&self, dest: &mut T) { + self.from.encode_to(dest); + self.to.encode_to(dest); + self.amount.encode_to(dest); + self.nonce.encode_to(dest); } +} +impl Decode for Transfer { fn decode(input: &mut I) -> Option { - Slicable::decode(input).map(|(from, to, amount, nonce)| Transfer { from, to, amount, nonce }) + Decode::decode(input).map(|(from, to, amount, nonce)| Transfer { from, to, amount, nonce }) } } @@ -104,16 +104,16 @@ pub struct Extrinsic { pub signature: Ed25519Signature, } -impl Slicable for Extrinsic { - fn encode(&self) -> Vec { - let mut v = Vec::new(); - self.transfer.using_encoded(|s| v.extend(s)); - self.signature.using_encoded(|s| v.extend(s)); - v +impl Encode for Extrinsic { + fn encode_to(&self, dest: &mut T) { + self.transfer.encode_to(dest); + self.signature.encode_to(dest); } +} +impl Decode for Extrinsic { fn decode(input: &mut I) -> Option { - Slicable::decode(input).map(|(transfer, signature)| Extrinsic { transfer, signature }) + Decode::decode(input).map(|(transfer, signature)| Extrinsic { transfer, signature }) } } @@ -151,7 +151,7 @@ pub fn run_tests(mut input: &[u8]) -> Vec { print("run_tests..."); let block = Block::decode(&mut input).unwrap(); print("deserialised block."); - let stxs = block.extrinsics.iter().map(Slicable::encode).collect::>(); + let stxs = block.extrinsics.iter().map(Encode::encode).collect::>(); print("reserialised transactions."); [stxs.len() as u8].encode() } diff --git a/substrate/substrate/test-runtime/src/system.rs b/substrate/substrate/test-runtime/src/system.rs index 6b080a25b8..df582a4624 100644 --- a/substrate/substrate/test-runtime/src/system.rs +++ b/substrate/substrate/test-runtime/src/system.rs @@ -21,7 +21,7 @@ use rstd::prelude::*; use runtime_io::{storage_root, enumerated_trie_root}; use runtime_support::storage::{self, StorageValue, StorageMap}; use runtime_primitives::traits::{Hash as HashT, BlakeTwo256}; -use codec::{KeyedVec, Slicable}; +use codec::{KeyedVec, Encode}; use super::{AccountId, BlockNumber, Extrinsic, H256 as Hash, Block, Header}; const NONCE_OF: &[u8] = b"nonce:"; @@ -65,7 +65,7 @@ pub fn execute_block(block: Block) { let ref header = block.header; // check transaction trie root represents the transactions. - let txs = block.extrinsics.iter().map(Slicable::encode).collect::>(); + let txs = block.extrinsics.iter().map(Encode::encode).collect::>(); let txs = txs.iter().map(Vec::as_slice).collect::>(); let txs_root = enumerated_trie_root(&txs).into(); info_expect_equal_hash(&header.extrinsics_root, &txs_root); diff --git a/substrate/substrate/test-runtime/wasm/target/wasm32-unknown-unknown/release/substrate_test_runtime.compact.wasm b/substrate/substrate/test-runtime/wasm/target/wasm32-unknown-unknown/release/substrate_test_runtime.compact.wasm index 9d8638f0cc..f8fcab7aac 100644 Binary files a/substrate/substrate/test-runtime/wasm/target/wasm32-unknown-unknown/release/substrate_test_runtime.compact.wasm and b/substrate/substrate/test-runtime/wasm/target/wasm32-unknown-unknown/release/substrate_test_runtime.compact.wasm differ diff --git a/substrate/substrate/test-runtime/wasm/target/wasm32-unknown-unknown/release/substrate_test_runtime.wasm b/substrate/substrate/test-runtime/wasm/target/wasm32-unknown-unknown/release/substrate_test_runtime.wasm index 7fe929ecea..cef1bdc4b2 100755 Binary files a/substrate/substrate/test-runtime/wasm/target/wasm32-unknown-unknown/release/substrate_test_runtime.wasm and b/substrate/substrate/test-runtime/wasm/target/wasm32-unknown-unknown/release/substrate_test_runtime.wasm differ