Runtime logging. (#3821)

* Implement Printable for tuples.

* Add debugging function.

* Add debug 1.

* Implement  for everything.

* RuntimeDebug derive.

* Introduce RuntimeDebug.

* Add some dummy logging.

* Replace RuntimeDebug with Debug.

* Revert "Replace RuntimeDebug with Debug."

This reverts commit bc47070a8cb30241b2b590b2fa29fd195088162f.

* Working on Debug for all.

* Fix bounds.

* Add debug utils.

* Implement runtime logging.

* Add some docs and clean up.

* Clean up derives.

* Fix custom derive impl.

* Bump runtime.

* Fix long lines.

* Fix doc test.

* Use CARGO_CFG_STD.

* Revert "Use CARGO_CFG_STD."

This reverts commit ea429566de18ed0fa052571b359eb9826a64a9f4.

* Use parse_macro_input

* Update lockfile.

* Apply review suggestions.

* Remove stray re-export.

* Add no-std impl.

* Update lockfile.
This commit is contained in:
Tomasz Drwięga
2019-10-22 14:13:44 +02:00
committed by Bastian Köcher
parent 934d7aac1c
commit 20a3989785
86 changed files with 1266 additions and 469 deletions
+4 -2
View File
@@ -8,12 +8,12 @@ edition = "2018"
rstd = { package = "sr-std", path = "../sr-std", default-features = false }
codec = { package = "parity-scale-codec", version = "1.0.0", default-features = false, features = ["derive"] }
rustc-hex = { version = "2.0.1", default-features = false }
log = { version = "0.4.8", default-features = false }
serde = { version = "1.0.101", optional = true, features = ["derive"] }
twox-hash = { version = "1.5.0", optional = true }
byteorder = { version = "1.3.2", default-features = false }
primitive-types = { version = "0.5.1", default-features = false, features = ["codec"] }
impl-serde = { version = "0.2.1", optional = true }
log = { version = "0.4.8", optional = true }
wasmi = { version = "0.5.1", optional = true }
hash-db = { version = "0.15.2", default-features = false }
hash256-std-hasher = { version = "0.15.2", default-features = false }
@@ -31,6 +31,7 @@ num-traits = { version = "0.2.8", default-features = false }
zeroize = "0.10.1"
lazy_static = { version = "1.4.0", optional = true }
parking_lot = { version = "0.9.0", optional = true }
substrate-debug-derive = { version = "2.0.0", path = "./debug-derive" }
externalities = { package = "substrate-externalities", path = "../externalities", optional = true }
primitives-storage = { package = "substrate-primitives-storage", path = "storage", default-features = false }
@@ -51,7 +52,7 @@ bench = false
[features]
default = ["std"]
std = [
"log",
"log/std",
"wasmi",
"lazy_static",
"parking_lot",
@@ -81,6 +82,7 @@ std = [
"schnorrkel",
"regex",
"num-traits/std",
"substrate-debug-derive/std",
"externalities",
"primitives-storage/std",
]
@@ -0,0 +1,19 @@
[package]
name = "substrate-debug-derive"
version = "2.0.0"
authors = ["Parity Technologies <admin@parity.io>"]
edition = "2018"
[lib]
proc-macro = true
[dependencies]
quote = "1.0.2"
syn = "1.0.5"
proc-macro2 = "1.0"
[features]
std = []
[dev-dependencies]
@@ -0,0 +1,217 @@
// Copyright 2019 Parity Technologies (UK) Ltd.
// This file is part of Substrate.
// Substrate is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Substrate is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
use quote::quote;
use proc_macro2::TokenStream;
use syn::{Data, DeriveInput, parse_quote};
pub fn debug_derive(ast: DeriveInput) -> proc_macro::TokenStream {
let name_str = ast.ident.to_string();
let implementation = implementation::derive(&name_str, &ast.data);
let name = &ast.ident;
let mut generics = ast.generics.clone();
let (impl_generics, ty_generics, where_clause) = {
let wh = generics.make_where_clause();
for t in ast.generics.type_params() {
let name = &t.ident;
wh.predicates.push(parse_quote!{ #name : core::fmt::Debug });
}
generics.split_for_impl()
};
let gen = quote!{
impl #impl_generics core::fmt::Debug for #name #ty_generics #where_clause {
fn fmt(&self, fmt: &mut core::fmt::Formatter) -> core::fmt::Result {
#implementation
}
}
};
gen.into()
}
#[cfg(not(feature = "std"))]
mod implementation {
use super::*;
/// Derive the inner implementation of `Debug::fmt` function.
///
/// Non-std environment. We do nothing to prevent bloating the size of runtime.
/// Implement `Printable` if you need to print the details.
pub fn derive(_name_str: &str, _data: &Data) -> TokenStream {
quote! {
fmt.write_str("<wasm:stripped>")
}
}
}
#[cfg(feature = "std")]
mod implementation {
use super::*;
use proc_macro2::Span;
use syn::{Ident, Index, token::SelfValue};
/// Derive the inner implementation of `Debug::fmt` function.
pub fn derive(name_str: &str, data: &Data) -> TokenStream {
match *data {
Data::Struct(ref s) => derive_struct(&name_str, &s.fields),
Data::Union(ref u) => derive_fields(&name_str, Fields::new(u.fields.named.iter(), None)),
Data::Enum(ref e) => derive_enum(&name_str, &e),
}
}
enum Fields {
Indexed {
indices: Vec<Index>,
},
Unnamed {
vars: Vec<Ident>,
},
Named {
names: Vec<Ident>,
this: Option<SelfValue>,
},
}
impl Fields {
fn new<'a>(fields: impl Iterator<Item=&'a syn::Field>, this: Option<SelfValue>) -> Self {
let mut indices = vec![];
let mut names = vec![];
for (i, f) in fields.enumerate() {
if let Some(ident) = f.ident.clone() {
names.push(ident);
} else {
indices.push(Index::from(i));
}
}
if names.is_empty() {
Self::Indexed {
indices,
}
} else {
Self::Named {
names,
this,
}
}
}
}
fn derive_fields<'a>(
name_str: &str,
fields: Fields,
) -> TokenStream {
match fields {
Fields::Named { names, this } => {
let names_str: Vec<_> = names.iter()
.map(|x| x.to_string())
.collect();
let fields = match this {
None => quote! { #( .field(#names_str, #names) )* },
Some(this) => quote! { #( .field(#names_str, &#this.#names) )* },
};
quote! {
fmt.debug_struct(#name_str)
#fields
.finish()
}
},
Fields::Indexed { indices } => {
quote! {
fmt.debug_tuple(#name_str)
#( .field(&self.#indices) )*
.finish()
}
},
Fields::Unnamed { vars } => {
quote! {
fmt.debug_tuple(#name_str)
#( .field(#vars) )*
.finish()
}
},
}
}
fn derive_enum(
name: &str,
e: &syn::DataEnum,
) -> TokenStream {
let v = e.variants
.iter()
.map(|v| {
let name = format!("{}::{}", name, v.ident);
let ident = &v.ident;
match v.fields {
syn::Fields::Named(ref f) => {
let names: Vec<_> = f.named.iter().flat_map(|f| f.ident.clone()).collect();
let fields_impl = derive_fields(&name, Fields::Named {
names: names.clone(),
this: None,
});
(ident, (quote!{ { #( ref #names ),* } }, fields_impl))
},
syn::Fields::Unnamed(ref f) => {
let names = f.unnamed.iter()
.enumerate()
.map(|(id, _)| Ident::new(&format!("a{}", id), Span::call_site()))
.collect::<Vec<_>>();
let fields_impl = derive_fields(&name, Fields::Unnamed { vars: names.clone() });
(ident, (quote! { ( #( ref #names ),* ) }, fields_impl))
},
syn::Fields::Unit => {
let fields_impl = derive_fields(&name, Fields::Indexed { indices: vec![] });
(ident, (quote! { }, fields_impl))
},
}
});
type Vecs<A, B> = (Vec<A>, Vec<B>);
let (variants, others): Vecs<_, _> = v.unzip();
let (match_fields, variants_impl): Vecs<_, _> = others.into_iter().unzip();
quote! {
match self {
#( Self::#variants #match_fields => #variants_impl, )*
_ => Ok(()),
}
}
}
fn derive_struct(
name_str: &str,
fields: &syn::Fields,
) -> TokenStream {
match *fields {
syn::Fields::Named(ref f) => derive_fields(
name_str,
Fields::new(f.named.iter(), Some(syn::Token!(self)(Span::call_site()))),
),
syn::Fields::Unnamed(ref f) => derive_fields(
name_str,
Fields::new(f.unnamed.iter(), None),
),
syn::Fields::Unit => derive_fields(
name_str,
Fields::Indexed { indices: vec![] },
),
}
}
}
@@ -0,0 +1,44 @@
// Copyright 2019 Parity Technologies (UK) Ltd.
// This file is part of Substrate.
// Substrate is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Substrate is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
//! Macros to derive runtime debug implementation.
//!
//! This custom derive implements a `core::fmt::Debug` trait,
//! but in case the `std` feature is enabled the implementation
//! will actually print out the structure as regular `derive(Debug)`
//! would do. If `std` is disabled the implementation will be empty.
//!
//! This behaviour is useful to prevent bloating the runtime WASM
//! blob from unneeded code.
//!
//! ```rust
//! #[derive(substrate_debug_derive::RuntimeDebug)]
//! struct MyStruct;
//!
//! assert_eq!(format!("{:?}", MyStruct), "MyStruct");
//! ```
extern crate proc_macro;
mod impls;
use proc_macro::TokenStream;
#[proc_macro_derive(RuntimeDebug)]
pub fn debug_derive(input: TokenStream) -> TokenStream {
impls::debug_derive(syn::parse_macro_input!(input))
}
@@ -0,0 +1,63 @@
// Copyright 2019 Parity Technologies (UK) Ltd.
// This file is part of Substrate.
// Substrate is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Substrate is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
use substrate_debug_derive::RuntimeDebug;
#[derive(RuntimeDebug)]
struct Unnamed(u64, String);
#[derive(RuntimeDebug)]
struct Named {
a: u64,
b: String,
}
#[derive(RuntimeDebug)]
enum EnumLongName<A> {
A,
B(A, String),
VariantLongName {
a: A,
b: String,
},
}
#[test]
fn should_display_proper_debug() {
use self::EnumLongName as Enum;
assert_eq!(
format!("{:?}", Unnamed(1, "abc".into())),
"Unnamed(1, \"abc\")"
);
assert_eq!(
format!("{:?}", Named { a: 1, b: "abc".into() }),
"Named { a: 1, b: \"abc\" }"
);
assert_eq!(
format!("{:?}", Enum::<u64>::A),
"EnumLongName::A"
);
assert_eq!(
format!("{:?}", Enum::B(1, "abc".into())),
"EnumLongName::B(1, \"abc\")"
);
assert_eq!(
format!("{:?}", Enum::VariantLongName { a: 1, b: "abc".into() }),
"EnumLongName::VariantLongName { a: 1, b: \"abc\" }"
);
}
+2 -2
View File
@@ -43,7 +43,7 @@ pub const DEV_PHRASE: &str = "bottom drive obey lake curtain smoke basket hold r
pub const DEV_ADDRESS: &str = "5DfhGyQdFobKM8NsWvEeAKk5EQQgYe9AydgJ7rMB6E1EqRzV";
/// The infallible type.
#[derive(Debug)]
#[derive(crate::RuntimeDebug)]
pub enum Infallible {}
/// The length of the junction identifier. Note that this is also referred to as the
@@ -743,7 +743,7 @@ pub trait CryptoType {
/// Values whose first character is `_` are reserved for private use and won't conflict with any
/// public modules.
#[derive(Copy, Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Encode, Decode)]
#[cfg_attr(feature = "std", derive(Debug))]
#[derive(crate::RuntimeDebug)]
pub struct KeyTypeId(pub [u8; 4]);
impl From<u32> for KeyTypeId {
+16 -6
View File
@@ -130,12 +130,17 @@ impl std::fmt::Display for Public {
}
}
#[cfg(feature = "std")]
impl std::fmt::Debug for Public {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
impl rstd::fmt::Debug for Public {
#[cfg(feature = "std")]
fn fmt(&self, f: &mut rstd::fmt::Formatter) -> rstd::fmt::Result {
let s = self.to_ss58check();
write!(f, "{} ({}...)", crate::hexdisplay::HexDisplay::from(&self.0), &s[0..8])
}
#[cfg(not(feature = "std"))]
fn fmt(&self, _: &mut rstd::fmt::Formatter) -> rstd::fmt::Result {
Ok(())
}
}
#[cfg(feature = "std")]
@@ -223,11 +228,16 @@ impl AsMut<[u8]> for Signature {
}
}
#[cfg(feature = "std")]
impl std::fmt::Debug for Signature {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
impl rstd::fmt::Debug for Signature {
#[cfg(feature = "std")]
fn fmt(&self, f: &mut rstd::fmt::Formatter) -> rstd::fmt::Result {
write!(f, "{}", crate::hexdisplay::HexDisplay::from(&self.0))
}
#[cfg(not(feature = "std"))]
fn fmt(&self, _: &mut rstd::fmt::Formatter) -> rstd::fmt::Result {
Ok(())
}
}
#[cfg(feature = "std")]
+4 -4
View File
@@ -24,8 +24,8 @@ impl<'a> HexDisplay<'a> {
pub fn from<R: AsBytesRef>(d: &'a R) -> Self { HexDisplay(d.as_bytes_ref()) }
}
impl<'a> ::core::fmt::Display for HexDisplay<'a> {
fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
impl<'a> rstd::fmt::Display for HexDisplay<'a> {
fn fmt(&self, f: &mut rstd::fmt::Formatter) -> Result<(), rstd::fmt::Error> {
if self.0.len() < 1027 {
for byte in self.0 {
f.write_fmt(format_args!("{:02x}", byte))?;
@@ -43,8 +43,8 @@ impl<'a> ::core::fmt::Display for HexDisplay<'a> {
}
}
impl<'a> core::fmt::Debug for HexDisplay<'a> {
fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
impl<'a> rstd::fmt::Debug for HexDisplay<'a> {
fn fmt(&self, f: &mut rstd::fmt::Formatter) -> Result<(), rstd::fmt::Error> {
for byte in self.0 {
f.write_fmt(format_args!("{:02x}", byte))?;
}
+61 -4
View File
@@ -42,6 +42,8 @@ pub use serde;// << for macro
#[doc(hidden)]
pub use codec::{Encode, Decode};// << for macro
pub use substrate_debug_derive::RuntimeDebug;
#[cfg(feature = "std")]
pub use impl_serde::serialize as bytes;
@@ -116,8 +118,8 @@ impl ExecutionContext {
}
/// Hex-serialized shim for `Vec<u8>`.
#[derive(PartialEq, Eq, Clone)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug, Hash, PartialOrd, Ord))]
#[derive(PartialEq, Eq, Clone, RuntimeDebug)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Hash, PartialOrd, Ord))]
pub struct Bytes(#[cfg_attr(feature = "std", serde(with="bytes"))] pub Vec<u8>);
impl From<Vec<u8>> for Bytes {
@@ -162,8 +164,8 @@ pub enum NativeOrEncoded<R> {
}
#[cfg(feature = "std")]
impl<R: codec::Encode> ::std::fmt::Debug for NativeOrEncoded<R> {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
impl<R: codec::Encode> rstd::fmt::Debug for NativeOrEncoded<R> {
fn fmt(&self, f: &mut rstd::fmt::Formatter) -> rstd::fmt::Result {
hexdisplay::HexDisplay::from(&self.as_encoded().as_ref()).fmt(f)
}
}
@@ -229,3 +231,58 @@ pub trait TypeId {
/// Simple 4 byte identifier.
const TYPE_ID: [u8; 4];
}
/// A log level matching the one from `log` crate.
///
/// Used internally by `runtime_io::log` method.
#[repr(u32)]
pub enum LogLevel {
/// `Error` log level.
Error = 1,
/// `Warn` log level.
Warn = 2,
/// `Info` log level.
Info = 3,
/// `Debug` log level.
Debug = 4,
/// `Trace` log level.
Trace = 5,
}
impl From<u32> for LogLevel {
fn from(val: u32) -> Self {
match val {
x if x == LogLevel::Warn as u32 => LogLevel::Warn,
x if x == LogLevel::Info as u32 => LogLevel::Info,
x if x == LogLevel::Debug as u32 => LogLevel::Debug,
x if x == LogLevel::Trace as u32 => LogLevel::Trace,
_ => LogLevel::Error,
}
}
}
impl From<log::Level> for LogLevel {
fn from(l: log::Level) -> Self {
use log::Level::*;
match l {
Error => Self::Error,
Warn => Self::Warn,
Info => Self::Info,
Debug => Self::Debug,
Trace => Self::Trace,
}
}
}
impl From<LogLevel> for log::Level {
fn from(l: LogLevel) -> Self {
use self::LogLevel::*;
match l {
Error => Self::Error,
Warn => Self::Warn,
Info => Self::Info,
Debug => Self::Debug,
Trace => Self::Trace,
}
}
}
+11 -18
View File
@@ -18,12 +18,12 @@
use codec::{Encode, Decode};
use rstd::{prelude::{Vec, Box}, convert::TryFrom};
use crate::RuntimeDebug;
pub use crate::crypto::KeyTypeId;
/// A type of supported crypto.
#[derive(Clone, Copy, PartialEq, Eq, Encode, Decode)]
#[cfg_attr(feature = "std", derive(Debug))]
#[derive(Clone, Copy, PartialEq, Eq, Encode, Decode, RuntimeDebug)]
#[repr(C)]
pub enum StorageKind {
/// Persistent storage is non-revertible and not fork-aware. It means that any value
@@ -59,8 +59,8 @@ impl From<StorageKind> for u32 {
}
/// Opaque type for offchain http requests.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
#[cfg_attr(feature = "std", derive(Debug, Hash))]
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, RuntimeDebug)]
#[cfg_attr(feature = "std", derive(Hash))]
pub struct HttpRequestId(pub u16);
impl From<HttpRequestId> for u32 {
@@ -70,8 +70,7 @@ impl From<HttpRequestId> for u32 {
}
/// An error enum returned by some http methods.
#[derive(Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "std", derive(Debug))]
#[derive(Clone, Copy, PartialEq, Eq, RuntimeDebug)]
#[repr(C)]
pub enum HttpError {
/// The requested action couldn't been completed within a deadline.
@@ -102,8 +101,7 @@ impl From<HttpError> for u32 {
}
/// Status of the HTTP request
#[derive(Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "std", derive(Debug))]
#[derive(Clone, Copy, PartialEq, Eq, RuntimeDebug)]
pub enum HttpRequestStatus {
/// Deadline was reached while we waited for this request to finish.
///
@@ -149,8 +147,7 @@ impl TryFrom<u32> for HttpRequestStatus {
/// A blob to hold information about the local node's network state
/// without committing to its format.
#[derive(Clone, Eq, PartialEq, Encode, Decode)]
#[cfg_attr(feature = "std", derive(Debug))]
#[derive(Clone, Eq, PartialEq, Encode, Decode, RuntimeDebug)]
pub struct OpaqueNetworkState {
/// PeerId of the local node.
pub peer_id: OpaquePeerId,
@@ -159,8 +156,7 @@ pub struct OpaqueNetworkState {
}
/// Simple blob to hold a `PeerId` without committing to its format.
#[derive(Default, Clone, Eq, PartialEq, Encode, Decode)]
#[cfg_attr(feature = "std", derive(Debug))]
#[derive(Default, Clone, Eq, PartialEq, Encode, Decode, RuntimeDebug)]
pub struct OpaquePeerId(pub Vec<u8>);
impl OpaquePeerId {
@@ -171,8 +167,7 @@ impl OpaquePeerId {
}
/// Simple blob to hold a `Multiaddr` without committing to its format.
#[derive(Clone, Eq, PartialEq, Encode, Decode)]
#[cfg_attr(feature = "std", derive(Debug))]
#[derive(Clone, Eq, PartialEq, Encode, Decode, RuntimeDebug)]
pub struct OpaqueMultiaddr(pub Vec<u8>);
impl OpaqueMultiaddr {
@@ -183,13 +178,11 @@ impl OpaqueMultiaddr {
}
/// Opaque timestamp type
#[derive(Clone, Copy, PartialEq, Eq, Ord, PartialOrd, Default)]
#[cfg_attr(feature = "std", derive(Debug))]
#[derive(Clone, Copy, PartialEq, Eq, Ord, PartialOrd, Default, RuntimeDebug)]
pub struct Timestamp(u64);
/// Duration type
#[derive(Clone, Copy, PartialEq, Eq, Ord, PartialOrd, Default)]
#[cfg_attr(feature = "std", derive(Debug))]
#[derive(Clone, Copy, PartialEq, Eq, Ord, PartialOrd, Default, RuntimeDebug)]
pub struct Duration(u64);
impl Duration {
+6 -6
View File
@@ -21,12 +21,12 @@ use rstd::vec::Vec;
/// Error error that can be returned from host function.
#[derive(Encode, Decode)]
#[cfg_attr(feature = "std", derive(Debug))]
#[derive(crate::RuntimeDebug)]
pub struct HostError;
/// Representation of a typed wasm value.
#[derive(Clone, Copy, PartialEq, Encode, Decode)]
#[cfg_attr(feature = "std", derive(Debug))]
#[derive(crate::RuntimeDebug)]
pub enum TypedValue {
/// Value of 32-bit signed or unsigned integer.
#[codec(index = "1")]
@@ -86,7 +86,7 @@ impl From<TypedValue> for ::wasmi::RuntimeValue {
///
/// Basically a `TypedValue` plus `Unit`, for functions which return nothing.
#[derive(Clone, Copy, PartialEq, Encode, Decode)]
#[cfg_attr(feature = "std", derive(Debug))]
#[derive(crate::RuntimeDebug)]
pub enum ReturnValue {
/// For returning nothing.
Unit,
@@ -119,7 +119,7 @@ fn return_value_encoded_max_size() {
/// Describes an entity to define or import into the environment.
#[derive(Clone, PartialEq, Eq, Encode, Decode)]
#[cfg_attr(feature = "std", derive(Debug))]
#[derive(crate::RuntimeDebug)]
pub enum ExternEntity {
/// Function that is specified by an index in a default table of
/// a module that creates the sandbox.
@@ -137,7 +137,7 @@ pub enum ExternEntity {
/// Each entry has a two-level name and description of an entity
/// being defined.
#[derive(Clone, PartialEq, Eq, Encode, Decode)]
#[cfg_attr(feature = "std", derive(Debug))]
#[derive(crate::RuntimeDebug)]
pub struct Entry {
/// Module name of which corresponding entity being defined.
pub module_name: Vec<u8>,
@@ -149,7 +149,7 @@ pub struct Entry {
/// Definition of runtime that could be used by sandboxed code.
#[derive(Clone, PartialEq, Eq, Encode, Decode)]
#[cfg_attr(feature = "std", derive(Debug))]
#[derive(crate::RuntimeDebug)]
pub struct EnvironmentDefinition {
/// Vector of all entries in the environment definition.
pub entries: Vec<Entry>,
+19 -6
View File
@@ -129,12 +129,20 @@ impl std::fmt::Display for Public {
}
}
#[cfg(feature = "std")]
impl std::fmt::Debug for Public {
fn fmt(&self, f: &mut std::fmt::Formatter) -> ::std::fmt::Result {
#[cfg(not(feature = "std"))]
use core as std;
impl rstd::fmt::Debug for Public {
#[cfg(feature = "std")]
fn fmt(&self, f: &mut rstd::fmt::Formatter) -> rstd::fmt::Result {
let s = self.to_ss58check();
write!(f, "{} ({}...)", crate::hexdisplay::HexDisplay::from(&self.0), &s[0..8])
}
#[cfg(not(feature = "std"))]
fn fmt(&self, _: &mut rstd::fmt::Formatter) -> rstd::fmt::Result {
Ok(())
}
}
#[cfg(feature = "std")]
@@ -231,11 +239,16 @@ impl From<schnorrkel::Signature> for Signature {
}
}
#[cfg(feature = "std")]
impl std::fmt::Debug for Signature {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
impl rstd::fmt::Debug for Signature {
#[cfg(feature = "std")]
fn fmt(&self, f: &mut rstd::fmt::Formatter) -> rstd::fmt::Result {
write!(f, "{}", crate::hexdisplay::HexDisplay::from(&self.0))
}
#[cfg(not(feature = "std"))]
fn fmt(&self, _: &mut rstd::fmt::Formatter) -> rstd::fmt::Result {
Ok(())
}
}
#[cfg(feature = "std")]
@@ -9,6 +9,7 @@ description = "Storage related primitives"
rstd = { package = "sr-std", path = "../../sr-std", default-features = false }
serde = { version = "1.0.101", optional = true, features = ["derive"] }
impl-serde = { version = "0.2.1", optional = true }
substrate-debug-derive = { version = "2.0.0", path = "../debug-derive" }
[features]
default = [ "std" ]
+7 -5
View File
@@ -20,27 +20,29 @@
#[cfg(feature = "std")]
use serde::{Serialize, Deserialize};
use substrate_debug_derive::RuntimeDebug;
use rstd::{vec::Vec, borrow::Cow};
/// Storage key.
#[derive(PartialEq, Eq)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug, Hash, PartialOrd, Ord, Clone))]
#[derive(PartialEq, Eq, RuntimeDebug)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Hash, PartialOrd, Ord, Clone))]
pub struct StorageKey(
#[cfg_attr(feature = "std", serde(with="impl_serde::serialize"))]
pub Vec<u8>,
);
/// Storage data associated to a [`StorageKey`].
#[derive(PartialEq, Eq)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug, Hash, PartialOrd, Ord, Clone))]
#[derive(PartialEq, Eq, RuntimeDebug)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Hash, PartialOrd, Ord, Clone))]
pub struct StorageData(
#[cfg_attr(feature = "std", serde(with="impl_serde::serialize"))]
pub Vec<u8>,
);
/// Storage change set
#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug, PartialEq, Eq))]
#[derive(RuntimeDebug)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize, PartialEq, Eq))]
#[cfg_attr(feature = "std", serde(rename_all = "camelCase"))]
pub struct StorageChangeSet<Hash> {
/// Block hash