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

* Run cargo fmt on the whole code base

* Second run

* Add CI check

* Fix compilation

* More unnecessary braces

* Handle weights

* Use --all

* Use correct attributes...

* Fix UI tests

* AHHHHHHHHH

* 🤦

* Docs

* Fix compilation

* 🤷

* Please stop

* 🤦 x 2

* More

* make rustfmt.toml consistent with polkadot

Co-authored-by: André Silva <andrerfosilva@gmail.com>
This commit is contained in:
Bastian Köcher
2021-07-21 16:32:32 +02:00
committed by GitHub
parent d451c38c1c
commit 7b56ab15b4
1010 changed files with 53339 additions and 51208 deletions
@@ -48,17 +48,15 @@
//! assert_eq!(body.error(), &None);
//! ```
use sp_std::str;
use sp_std::prelude::Vec;
use sp_core::{
offchain::{
HttpError, HttpRequestId as RequestId, HttpRequestStatus as RequestStatus, Timestamp,
},
RuntimeDebug,
};
#[cfg(not(feature = "std"))]
use sp_std::prelude::vec;
use sp_core::RuntimeDebug;
use sp_core::offchain::{
Timestamp,
HttpRequestId as RequestId,
HttpRequestStatus as RequestStatus,
HttpError,
};
use sp_std::{prelude::Vec, str};
/// Request method (HTTP verb)
#[derive(Clone, PartialEq, Eq, RuntimeDebug)]
@@ -103,10 +101,7 @@ mod header {
impl Header {
/// Creates new header given it's name and value.
pub fn new(name: &str, value: &str) -> Self {
Header {
name: name.as_bytes().to_vec(),
value: value.as_bytes().to_vec(),
}
Header { name: name.as_bytes().to_vec(), value: value.as_bytes().to_vec() }
}
/// Returns the name of this header.
@@ -166,13 +161,7 @@ impl<'a, T> Request<'a, T> {
pub fn post(url: &'a str, body: T) -> Self {
let req: Request = Request::default();
Request {
url,
body,
method: Method::Post,
headers: req.headers,
deadline: req.deadline,
}
Request { url, body, method: Method::Post, headers: req.headers, deadline: req.deadline }
}
}
@@ -213,7 +202,7 @@ impl<'a, T: Default> Request<'a, T> {
}
}
impl<'a, I: AsRef<[u8]>, T: IntoIterator<Item=I>> Request<'a, T> {
impl<'a, I: AsRef<[u8]>, T: IntoIterator<Item = I>> Request<'a, T> {
/// Send the request and return a handle.
///
/// Err is returned in case the deadline is reached
@@ -222,19 +211,13 @@ impl<'a, I: AsRef<[u8]>, T: IntoIterator<Item=I>> Request<'a, T> {
let meta = &[];
// start an http request.
let id = sp_io::offchain::http_request_start(
self.method.as_ref(),
self.url,
meta,
).map_err(|_| HttpError::IoError)?;
let id = sp_io::offchain::http_request_start(self.method.as_ref(), self.url, meta)
.map_err(|_| HttpError::IoError)?;
// add custom headers
for header in &self.headers {
sp_io::offchain::http_request_add_header(
id,
header.name(),
header.value(),
).map_err(|_| HttpError::IoError)?
sp_io::offchain::http_request_add_header(id, header.name(), header.value())
.map_err(|_| HttpError::IoError)?
}
// write body
@@ -245,9 +228,7 @@ impl<'a, I: AsRef<[u8]>, T: IntoIterator<Item=I>> Request<'a, T> {
// finalize the request
sp_io::offchain::http_request_write_body(id, &[], self.deadline)?;
Ok(PendingRequest {
id,
})
Ok(PendingRequest { id })
}
}
@@ -285,8 +266,13 @@ impl PendingRequest {
/// Attempts to wait for the request to finish,
/// but will return `Err` in case the deadline is reached.
pub fn try_wait(self, deadline: impl Into<Option<Timestamp>>) -> Result<HttpResult, PendingRequest> {
Self::try_wait_all(vec![self], deadline).pop().expect("One request passed, one status received; qed")
pub fn try_wait(
self,
deadline: impl Into<Option<Timestamp>>,
) -> Result<HttpResult, PendingRequest> {
Self::try_wait_all(vec![self], deadline)
.pop()
.expect("One request passed, one status received; qed")
}
/// Wait for all provided requests.
@@ -305,7 +291,7 @@ impl PendingRequest {
/// Requests that are complete will resolve to an `Ok` others will return a `DeadlineReached` error.
pub fn try_wait_all(
requests: Vec<PendingRequest>,
deadline: impl Into<Option<Timestamp>>
deadline: impl Into<Option<Timestamp>>,
) -> Vec<Result<HttpResult, PendingRequest>> {
let ids = requests.iter().map(|r| r.id).collect::<Vec<_>>();
let statuses = sp_io::offchain::http_response_wait(&ids, deadline.into());
@@ -336,19 +322,13 @@ pub struct Response {
impl Response {
fn new(id: RequestId, code: u16) -> Self {
Self {
id,
code,
headers: None,
}
Self { id, code, headers: None }
}
/// Retrieve the headers for this response.
pub fn headers(&mut self) -> &Headers {
if self.headers.is_none() {
self.headers = Some(
Headers { raw: sp_io::offchain::http_response_headers(self.id) },
);
self.headers = Some(Headers { raw: sp_io::offchain::http_response_headers(self.id) });
}
self.headers.as_ref().expect("Headers were just set; qed")
}
@@ -363,7 +343,7 @@ impl Response {
///
/// Note that reading the body may return `None` in following cases:
/// 1. Either the deadline you've set is reached (check via `#error`;
/// In such case you can resume the reader by setting a new deadline)
/// In such case you can resume the reader by setting a new deadline)
/// 2. Or because of IOError. In such case the reader is not resumable and will keep
/// returning `None`.
/// 3. The body has been returned. The reader will keep returning `None`.
@@ -423,32 +403,28 @@ impl Iterator for ResponseBody {
fn next(&mut self) -> Option<Self::Item> {
if self.error.is_some() {
return None;
return None
}
if self.filled_up_to.is_none() {
let result = sp_io::offchain::http_response_read_body(
self.id,
&mut self.buffer,
self.deadline);
let result =
sp_io::offchain::http_response_read_body(self.id, &mut self.buffer, self.deadline);
match result {
Err(e) => {
self.error = Some(e);
return None;
}
Ok(0) => {
return None;
}
return None
},
Ok(0) => return None,
Ok(size) => {
self.position = 0;
self.filled_up_to = Some(size as usize);
}
},
}
}
if Some(self.position) == self.filled_up_to {
self.filled_up_to = None;
return self.next();
return self.next()
}
let result = self.buffer[self.position];
@@ -508,7 +484,8 @@ impl<'a> HeadersIterator<'a> {
///
/// Note that you have to call `next` prior to calling this
pub fn current(&self) -> Option<(&str, &str)> {
self.collection.get(self.index?)
self.collection
.get(self.index?)
.map(|val| (str::from_utf8(&val.0).unwrap_or(""), str::from_utf8(&val.1).unwrap_or("")))
}
}
@@ -516,11 +493,8 @@ impl<'a> HeadersIterator<'a> {
#[cfg(test)]
mod tests {
use super::*;
use sp_core::offchain::{testing, OffchainWorkerExt};
use sp_io::TestExternalities;
use sp_core::offchain::{
OffchainWorkerExt,
testing,
};
#[test]
fn should_send_a_basic_request_and_get_response() {
@@ -530,10 +504,7 @@ mod tests {
t.execute_with(|| {
let request: Request = Request::get("http://localhost:1234");
let pending = request
.add_header("X-Auth", "hunter2")
.send()
.unwrap();
let pending = request.add_header("X-Auth", "hunter2").send().unwrap();
// make sure it's sent correctly
state.write().fulfill_pending_request(
0,
@@ -44,7 +44,7 @@ pub enum MutateStorageError<T, E> {
/// The function given to us to create the value to be stored failed.
/// May be used to signal that having looked at the existing value,
/// they don't want to mutate it.
ValueFunctionFailed(E)
ValueFunctionFailed(E),
}
impl<'a> StorageValueRef<'a> {
@@ -64,9 +64,7 @@ impl<'a> StorageValueRef<'a> {
/// if you happen to write a `get-check-set` pattern you should most likely
/// be using `mutate` instead.
pub fn set(&self, value: &impl codec::Encode) {
value.using_encoded(|val| {
sp_io::offchain::local_storage_set(self.kind, self.key, val)
})
value.using_encoded(|val| sp_io::offchain::local_storage_set(self.kind, self.key, val))
}
/// Remove the associated value from the storage.
@@ -83,8 +81,7 @@ impl<'a> StorageValueRef<'a> {
/// Returns an error if the value could not be decoded.
pub fn get<T: codec::Decode>(&self) -> Result<Option<T>, StorageRetrievalError> {
sp_io::offchain::local_storage_get(self.kind, self.key)
.map(|val| T::decode(&mut &*val)
.map_err(|_| StorageRetrievalError::Undecodable))
.map(|val| T::decode(&mut &*val).map_err(|_| StorageRetrievalError::Undecodable))
.transpose()
}
@@ -98,26 +95,22 @@ impl<'a> StorageValueRef<'a> {
/// 2. `Err(MutateStorageError::ConcurrentModification(T))` in case the value was calculated
/// by the passed closure `mutate_val`, but it could not be stored.
/// 3. `Err(MutateStorageError::ValueFunctionFailed(_))` in case `mutate_val` returns an error.
pub fn mutate<T, E, F>(&self, mutate_val: F) -> Result<T, MutateStorageError<T,E>> where
pub fn mutate<T, E, F>(&self, mutate_val: F) -> Result<T, MutateStorageError<T, E>>
where
T: codec::Codec,
F: FnOnce(Result<Option<T>, StorageRetrievalError>) -> Result<T, E>
F: FnOnce(Result<Option<T>, StorageRetrievalError>) -> Result<T, E>,
{
let value = sp_io::offchain::local_storage_get(self.kind, self.key);
let decoded = value.as_deref()
.map(|mut bytes| {
T::decode(&mut bytes)
.map_err(|_| StorageRetrievalError::Undecodable)
}).transpose();
let decoded = value
.as_deref()
.map(|mut bytes| T::decode(&mut bytes).map_err(|_| StorageRetrievalError::Undecodable))
.transpose();
let val = mutate_val(decoded).map_err(|err| MutateStorageError::ValueFunctionFailed(err))?;
let val =
mutate_val(decoded).map_err(|err| MutateStorageError::ValueFunctionFailed(err))?;
let set = val.using_encoded(|new_val| {
sp_io::offchain::local_storage_compare_and_set(
self.kind,
self.key,
value,
new_val,
)
sp_io::offchain::local_storage_compare_and_set(self.kind, self.key, value, new_val)
});
if set {
Ok(val)
@@ -130,11 +123,8 @@ impl<'a> StorageValueRef<'a> {
#[cfg(test)]
mod tests {
use super::*;
use sp_core::offchain::{testing, OffchainDbExt};
use sp_io::TestExternalities;
use sp_core::offchain::{
OffchainDbExt,
testing,
};
#[test]
fn should_set_and_get() {
@@ -151,10 +141,7 @@ mod tests {
assert_eq!(val.get::<u32>(), Ok(Some(15_u32)));
assert_eq!(val.get::<Vec<u8>>(), Err(StorageRetrievalError::Undecodable));
assert_eq!(
state.read().persistent_storage.get(b"testval"),
Some(vec![15_u8, 0, 0, 0])
);
assert_eq!(state.read().persistent_storage.get(b"testval"), Some(vec![15_u8, 0, 0, 0]));
})
}
@@ -174,10 +161,7 @@ mod tests {
});
assert_eq!(result, Ok(16_u32));
assert_eq!(val.get::<u32>(), Ok(Some(16_u32)));
assert_eq!(
state.read().persistent_storage.get(b"testval"),
Some(vec![16_u8, 0, 0, 0])
);
assert_eq!(state.read().persistent_storage.get(b"testval"), Some(vec![16_u8, 0, 0, 0]));
// mutate again, but this time early-exit.
let res = val.mutate::<u32, (), _>(|val| {
@@ -38,8 +38,8 @@
//! # use codec::{Decode, Encode, Codec};
//! // in your off-chain worker code
//! use sp_runtime::offchain::{
//! storage::StorageValueRef,
//! storage_lock::{StorageLock, Time},
//! storage::StorageValueRef,
//! storage_lock::{StorageLock, Time},
//! };
//!
//! fn append_to_in_storage_vec<'a, T>(key: &'a [u8], _: T) where T: Codec {
@@ -61,8 +61,10 @@
//! }
//! ```
use crate::offchain::storage::{StorageRetrievalError, MutateStorageError, StorageValueRef};
use crate::traits::BlockNumberProvider;
use crate::{
offchain::storage::{MutateStorageError, StorageRetrievalError, StorageValueRef},
traits::BlockNumberProvider,
};
use codec::{Codec, Decode, Encode};
use sp_core::offchain::{Duration, Timestamp};
use sp_io::offchain;
@@ -115,9 +117,7 @@ pub struct Time {
impl Default for Time {
fn default() -> Self {
Self {
expiration_duration: STORAGE_LOCK_DEFAULT_EXPIRY_DURATION,
}
Self { expiration_duration: STORAGE_LOCK_DEFAULT_EXPIRY_DURATION }
}
}
@@ -157,10 +157,7 @@ pub struct BlockAndTimeDeadline<B: BlockNumberProvider> {
impl<B: BlockNumberProvider> Clone for BlockAndTimeDeadline<B> {
fn clone(&self) -> Self {
Self {
block_number: self.block_number.clone(),
timestamp: self.timestamp,
}
Self { block_number: self.block_number.clone(), timestamp: self.timestamp }
}
}
@@ -175,7 +172,8 @@ impl<B: BlockNumberProvider> Default for BlockAndTimeDeadline<B> {
}
impl<B: BlockNumberProvider> fmt::Debug for BlockAndTimeDeadline<B>
where <B as BlockNumberProvider>::BlockNumber: fmt::Debug
where
<B as BlockNumberProvider>::BlockNumber: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("BlockAndTimeDeadline")
@@ -225,8 +223,8 @@ impl<B: BlockNumberProvider> Lockable for BlockAndTime<B> {
type Deadline = BlockAndTimeDeadline<B>;
fn deadline(&self) -> Self::Deadline {
let block_number = <B as BlockNumberProvider>::current_block_number()
+ self.expiration_block_number_offset.into();
let block_number = <B as BlockNumberProvider>::current_block_number() +
self.expiration_block_number_offset.into();
BlockAndTimeDeadline {
timestamp: offchain::timestamp().add(self.expiration_duration),
block_number,
@@ -234,8 +232,8 @@ impl<B: BlockNumberProvider> Lockable for BlockAndTime<B> {
}
fn has_expired(deadline: &Self::Deadline) -> bool {
offchain::timestamp() > deadline.timestamp
&& <B as BlockNumberProvider>::current_block_number() > deadline.block_number
offchain::timestamp() > deadline.timestamp &&
<B as BlockNumberProvider>::current_block_number() > deadline.block_number
}
fn snooze(deadline: &Self::Deadline) {
@@ -271,10 +269,7 @@ impl<'a, L: Lockable + Default> StorageLock<'a, L> {
impl<'a, L: Lockable> StorageLock<'a, L> {
/// Create a new storage lock with an explicit instance of a lockable `L`.
pub fn with_lockable(key: &'a [u8], lockable: L) -> Self {
Self {
value_ref: StorageValueRef::<'a>::persistent(key),
lockable,
}
Self { value_ref: StorageValueRef::<'a>::persistent(key), lockable }
}
/// Extend active lock's deadline
@@ -398,9 +393,7 @@ impl<'a> StorageLock<'a, Time> {
pub fn with_deadline(key: &'a [u8], expiration_duration: Duration) -> Self {
Self {
value_ref: StorageValueRef::<'a>::persistent(key),
lockable: Time {
expiration_duration,
},
lockable: Time { expiration_duration },
}
}
}
@@ -443,7 +436,7 @@ where
#[cfg(test)]
mod tests {
use super::*;
use sp_core::offchain::{testing, OffchainWorkerExt, OffchainDbExt};
use sp_core::offchain::{testing, OffchainDbExt, OffchainWorkerExt};
use sp_io::TestExternalities;
const VAL_1: u32 = 0u32;