diff --git a/.rustfmt.toml b/.rustfmt.toml index 422da2beabf..61403ea3630 100644 --- a/.rustfmt.toml +++ b/.rustfmt.toml @@ -1,15 +1,15 @@ -max_width = 90 # changed +max_width = 90 hard_tabs = false tab_spaces = 4 newline_style = "Auto" use_small_heuristics = "Default" indent_style = "Block" -wrap_comments = false +wrap_comments = true format_code_in_doc_comments = false comment_width = 80 -normalize_comments = true # changed +normalize_comments = true normalize_doc_attributes = false -license_template_path = "FILE_HEADER" # changed +license_template_path = "FILE_HEADER" format_strings = false format_macro_matchers = false format_macro_bodies = true @@ -18,8 +18,8 @@ struct_lit_single_line = true fn_single_line = false where_single_line = false imports_indent = "Block" -imports_layout = "Vertical" # changed -imports_granularity = "Crate" # changed +imports_layout = "Vertical" +imports_granularity = "Crate" reorder_imports = true reorder_modules = true reorder_impl_items = false @@ -29,29 +29,29 @@ space_after_colon = true spaces_around_ranges = false binop_separator = "Front" remove_nested_parens = true -combine_control_expr = false # changed +combine_control_expr = false overflow_delimited_expr = false struct_field_align_threshold = 0 enum_discrim_align_threshold = 0 match_arm_blocks = true -force_multiline_blocks = true # changed +force_multiline_blocks = true fn_args_layout = "Tall" brace_style = "SameLineWhere" control_brace_style = "AlwaysSameLine" -trailing_semicolon = false # changed +trailing_semicolon = false trailing_comma = "Vertical" match_block_trailing_comma = false blank_lines_upper_bound = 1 blank_lines_lower_bound = 0 -edition = "2021" # changed +edition = "2021" version = "One" merge_derives = true -use_try_shorthand = true # changed -use_field_init_shorthand = true # changed +use_try_shorthand = true +use_field_init_shorthand = true force_explicit_abi = true condense_wildcard_suffixes = false color = "Auto" -unstable_features = true # changed +unstable_features = true disable_all_formatting = false skip_children = false hide_parse_errors = false diff --git a/crates/allocator/src/bump.rs b/crates/allocator/src/bump.rs index a5736895737..031a68b2a10 100644 --- a/crates/allocator/src/bump.rs +++ b/crates/allocator/src/bump.rs @@ -14,12 +14,14 @@ //! A simple bump allocator. //! -//! Its goal to have a much smaller footprint than the admittedly more full-featured `wee_alloc` -//! allocator which is currently being used by ink! smart contracts. +//! Its goal to have a much smaller footprint than the admittedly more +//! full-featured `wee_alloc` allocator which is currently being used by ink! +//! smart contracts. //! -//! The heap which is used by this allocator is built from pages of Wasm memory (each page is `64KiB`). -//! We will request new pages of memory as needed until we run out of memory, at which point we -//! will crash with an `OOM` error instead of freeing any memory. +//! The heap which is used by this allocator is built from pages of Wasm memory +//! (each page is `64KiB`). We will request new pages of memory as needed until +//! we run out of memory, at which point we will crash with an `OOM` error +//! instead of freeing any memory. use core::alloc::{ GlobalAlloc, @@ -45,8 +47,8 @@ unsafe impl GlobalAlloc for BumpAllocator { #[inline] unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 { - // A new page in Wasm is guaranteed to already be zero initialized, so we can just use our - // regular `alloc` call here and save a bit of work. + // A new page in Wasm is guaranteed to already be zero initialized, so we can + // just use our regular `alloc` call here and save a bit of work. // // See: https://webassembly.github.io/spec/core/exec/modules.html#growing-memories self.alloc(layout) @@ -110,10 +112,12 @@ impl InnerAlloc { } } - /// Tries to allocate enough memory on the heap for the given `Layout`. If there is not enough - /// room on the heap it'll try and grow it by a page. + /// Tries to allocate enough memory on the heap for the given `Layout`. If + /// there is not enough room on the heap it'll try and grow it by a + /// page. /// - /// Note: This implementation results in internal fragmentation when allocating across pages. + /// Note: This implementation results in internal fragmentation when + /// allocating across pages. fn alloc(&mut self, layout: Layout) -> Option { let alloc_start = self.next; @@ -137,11 +141,12 @@ impl InnerAlloc { } } -/// Calculates the number of pages of memory needed for an allocation of `size` bytes. +/// Calculates the number of pages of memory needed for an allocation of `size` +/// bytes. /// -/// This function rounds up to the next page. For example, if we have an allocation of -/// `size = PAGE_SIZE / 2` this function will indicate that one page is required to satisfy -/// the allocation. +/// This function rounds up to the next page. For example, if we have an +/// allocation of `size = PAGE_SIZE / 2` this function will indicate that one +/// page is required to satisfy the allocation. #[inline] fn required_pages(size: usize) -> Option { size.checked_add(PAGE_SIZE - 1) @@ -235,8 +240,8 @@ mod tests { let expected_limit = 2 * PAGE_SIZE; assert_eq!(inner.upper_limit, expected_limit); - // Notice that we start the allocation on the second page, instead of making use of the - // remaining byte on the first page + // Notice that we start the allocation on the second page, instead of making use + // of the remaining byte on the first page let expected_alloc_start = PAGE_SIZE + size_of::(); assert_eq!(inner.next, expected_alloc_start); } @@ -259,8 +264,8 @@ mod tests { let expected_alloc_start = size_of::(); assert_eq!(inner.next, expected_alloc_start); - // Now we want to make sure that the state of our allocator is correct for any subsequent - // allocations + // Now we want to make sure that the state of our allocator is correct for any + // subsequent allocations let layout = Layout::new::(); assert_eq!(inner.alloc(layout), Some(2 * PAGE_SIZE)); @@ -288,8 +293,8 @@ mod fuzz_tests { #[quickcheck] fn should_allocate_arbitrary_sized_bytes(n: usize) -> TestResult { - // If `n` is going to overflow we don't want to check it here (we'll check the overflow - // case in another test) + // If `n` is going to overflow we don't want to check it here (we'll check the + // overflow case in another test) if n.checked_add(PAGE_SIZE - 1).is_none() { return TestResult::discard() } @@ -323,7 +328,8 @@ mod fuzz_tests { #[quickcheck] fn should_not_allocate_arbitrary_bytes_if_they_overflow(n: usize) -> TestResult { - // In the previous test we ignored the overflow case, now we ignore the valid cases + // In the previous test we ignored the overflow case, now we ignore the valid + // cases if n.checked_add(PAGE_SIZE - 1).is_some() { return TestResult::discard() } @@ -351,8 +357,8 @@ mod fuzz_tests { let aligns = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512]; let align = aligns[align % aligns.len()]; - // If `n` is going to overflow we don't want to check it here (we'll check the overflow - // case in another test) + // If `n` is going to overflow we don't want to check it here (we'll check the + // overflow case in another test) if n.checked_add(PAGE_SIZE - 1).is_none() { return TestResult::discard() } @@ -382,15 +388,16 @@ mod fuzz_tests { TestResult::passed() } - /// The idea behind this fuzz test is to check a series of allocation sequences. For - /// example, we maybe have back to back runs as follows: + /// The idea behind this fuzz test is to check a series of allocation + /// sequences. For example, we maybe have back to back runs as follows: /// /// 1. `vec![1, 2, 3]` /// 2. `vec![4, 5, 6, 7]` /// 3. `vec![8]` /// - /// Each of the vectors represents one sequence of allocations. Within each sequence the - /// individual size of allocations will be randomly selected by `quickcheck`. + /// Each of the vectors represents one sequence of allocations. Within each + /// sequence the individual size of allocations will be randomly + /// selected by `quickcheck`. #[quickcheck] fn should_allocate_arbitrary_byte_sequences(sequence: Vec) -> TestResult { let mut inner = InnerAlloc::new(); @@ -399,8 +406,8 @@ mod fuzz_tests { return TestResult::discard() } - // We want to make sure no single allocation is going to overflow, we'll check this - // case in a different test + // We want to make sure no single allocation is going to overflow, we'll check + // this case in a different test if !sequence .iter() .all(|n| n.checked_add(PAGE_SIZE - 1).is_some()) @@ -415,8 +422,8 @@ mod fuzz_tests { .fold(0, |acc, &x| acc + required_pages(x).unwrap()); let max_pages = required_pages(usize::MAX - PAGE_SIZE + 1).unwrap(); - // We know this is going to end up overflowing, we'll check this case in a different - // test + // We know this is going to end up overflowing, we'll check this case in a + // different test if pages_required > max_pages { return TestResult::discard() } @@ -442,8 +449,8 @@ mod fuzz_tests { total_bytes_fragmented += fragmented_in_current_page; - // We expect our next allocation to be aligned to the start of the next page - // boundary + // We expect our next allocation to be aligned to the start of the next + // page boundary expected_alloc_start = inner.upper_limit; } @@ -471,11 +478,12 @@ mod fuzz_tests { TestResult::passed() } - // For this test we have sequences of allocations which will eventually overflow the maximum - // amount of pages (in practice this means our heap will be OOM). + // For this test we have sequences of allocations which will eventually overflow + // the maximum amount of pages (in practice this means our heap will be + // OOM). // - // We don't care about the allocations that succeed (those are checked in other tests), we just - // care that eventually an allocation doesn't success. + // We don't care about the allocations that succeed (those are checked in other + // tests), we just care that eventually an allocation doesn't success. #[quickcheck] fn should_not_allocate_arbitrary_byte_sequences_which_eventually_overflow( sequence: Vec, @@ -486,8 +494,8 @@ mod fuzz_tests { return TestResult::discard() } - // We want to make sure no single allocation is going to overflow, we'll check that - // case seperately + // We want to make sure no single allocation is going to overflow, we'll check + // that case seperately if !sequence .iter() .all(|n| n.checked_add(PAGE_SIZE - 1).is_some()) @@ -502,8 +510,8 @@ mod fuzz_tests { .fold(0, |acc, &x| acc + required_pages(x).unwrap()); let max_pages = required_pages(usize::MAX - PAGE_SIZE + 1).unwrap(); - // We want to explicitly test for the case where a series of allocations eventually - // runs out of pages of memory + // We want to explicitly test for the case where a series of allocations + // eventually runs out of pages of memory if !(pages_required > max_pages) { return TestResult::discard() } @@ -515,7 +523,8 @@ mod fuzz_tests { results.push(inner.alloc(layout)); } - // Ensure that at least one of the allocations ends up overflowing our calculations. + // Ensure that at least one of the allocations ends up overflowing our + // calculations. assert!( results.iter().any(|r| r.is_none()), "Expected an allocation to overflow our heap, but this didn't happen." diff --git a/crates/allocator/src/lib.rs b/crates/allocator/src/lib.rs index 7d29f91aebb..6cd9159ed52 100644 --- a/crates/allocator/src/lib.rs +++ b/crates/allocator/src/lib.rs @@ -12,17 +12,20 @@ // See the License for the specific language governing permissions and // limitations under the License. -//! Crate providing allocator support for all Wasm compilations of ink! smart contracts. +//! Crate providing allocator support for all Wasm compilations of ink! smart +//! contracts. //! -//! The default allocator is a bump allocator whose goal is to have a small size footprint. If you -//! are not concerned about the size of your final Wasm binaries you may opt into using the more -//! full-featured `wee_alloc` allocator by activating the `wee-alloc` crate feature. +//! The default allocator is a bump allocator whose goal is to have a small size +//! footprint. If you are not concerned about the size of your final Wasm +//! binaries you may opt into using the more full-featured `wee_alloc` allocator +//! by activating the `wee-alloc` crate feature. #![cfg_attr(not(feature = "std"), no_std)] #![cfg_attr(not(feature = "std"), feature(alloc_error_handler, core_intrinsics))] -// We use `wee_alloc` as the global allocator since it is optimized for binary file size -// so that contracts compiled with it as allocator do not grow too much in size. +// We use `wee_alloc` as the global allocator since it is optimized for binary +// file size so that contracts compiled with it as allocator do not grow too +// much in size. #[cfg(not(feature = "std"))] #[cfg(feature = "wee-alloc")] #[global_allocator] diff --git a/crates/engine/src/database.rs b/crates/engine/src/database.rs index 3651424c2d6..89446e9e174 100644 --- a/crates/engine/src/database.rs +++ b/crates/engine/src/database.rs @@ -73,7 +73,8 @@ impl Database { self.hmap.get(&hashed_key.to_vec()) } - /// Inserts `value` into the contract storage of `account_id` at storage key `key`. + /// Inserts `value` into the contract storage of `account_id` at storage key + /// `key`. pub fn insert_into_contract_storage( &mut self, account_id: &[u8], @@ -84,7 +85,8 @@ impl Database { self.hmap.insert(hashed_key.to_vec(), value) } - /// Removes the value at the contract storage of `account_id` at storage key `key`. + /// Removes the value at the contract storage of `account_id` at storage key + /// `key`. pub fn remove_contract_storage( &mut self, account_id: &[u8], @@ -94,8 +96,8 @@ impl Database { self.hmap.remove(&hashed_key.to_vec()) } - /// Removes a key from the storage, returning the value at the key if the key - /// was previously in storage. + /// Removes a key from the storage, returning the value at the key if the + /// key was previously in storage. pub fn remove(&mut self, key: &[u8]) -> Option> { self.hmap.remove(key) } diff --git a/crates/engine/src/exec_context.rs b/crates/engine/src/exec_context.rs index 873cfc7506a..e2a2ad5c51d 100644 --- a/crates/engine/src/exec_context.rs +++ b/crates/engine/src/exec_context.rs @@ -22,17 +22,17 @@ use super::types::{ pub struct ExecContext { /// The caller of the contract execution. Might be user or another contract. /// - /// We don't know the specifics of the AccountId ‒ like how many bytes or what - /// type of default `AccountId` makes sense ‒ they are left to be initialized - /// by the crate which uses the `engine`. Methods which require a caller might - /// panic when it has not been set. + /// We don't know the specifics of the AccountId ‒ like how many bytes or + /// what type of default `AccountId` makes sense ‒ they are left to be + /// initialized by the crate which uses the `engine`. Methods which + /// require a caller might panic when it has not been set. pub caller: Option, /// The callee of the contract execution. Might be user or another contract. /// - /// We don't know the specifics of the AccountId ‒ like how many bytes or what - /// type of default `AccountId` makes sense ‒ they are left to be initialized - /// by the crate which uses the `engine`. Methods which require a callee might - /// panic when it has not been set. + /// We don't know the specifics of the AccountId ‒ like how many bytes or + /// what type of default `AccountId` makes sense ‒ they are left to be + /// initialized by the crate which uses the `engine`. Methods which + /// require a callee might panic when it has not been set. pub callee: Option, /// The value transferred to the contract as part of the call. pub value_transferred: Balance, diff --git a/crates/engine/src/ext.rs b/crates/engine/src/ext.rs index a28957954cc..a318b509164 100644 --- a/crates/engine/src/ext.rs +++ b/crates/engine/src/ext.rs @@ -233,9 +233,9 @@ impl Engine { /// Remove the calling account and transfer remaining balance. /// - /// This function never returns. Either the termination was successful and the - /// execution of the destroyed contract is halted. Or it failed during the - /// termination which is considered fatal. + /// This function never returns. Either the termination was successful and + /// the execution of the destroyed contract is halted. Or it failed + /// during the termination which is considered fatal. pub fn terminate(&mut self, beneficiary: &[u8]) -> ! { // Send the remaining balance to the beneficiary let contract = self.get_callee(); @@ -303,13 +303,14 @@ impl Engine { /// /// # Params /// - /// - `account_id`: Encoded bytes of the `AccountId` of the to-be-restored contract. + /// - `account_id`: Encoded bytes of the `AccountId` of the to-be-restored + /// contract. /// - `code_hash`: Encoded code hash of the to-be-restored contract. /// - `rent_allowance`: The encoded rent allowance of the restored contract - /// upon successful restoration. - /// - `filtered_keys`: Storage keys that will be ignored for the tombstone hash - /// match calculation that decide whether the original contract - /// storage and the storage of the restorer contract is equal. + /// upon successful restoration. + /// - `filtered_keys`: Storage keys that will be ignored for the tombstone + /// hash match calculation that decide whether the original contract + /// storage and the storage of the restorer contract is equal. pub fn restore_to( &mut self, _account_id: &[u8], @@ -420,8 +421,8 @@ impl Engine { ); } - /// Recovers the compressed ECDSA public key for given `signature` and `message_hash`, - /// and stores the result in `output`. + /// Recovers the compressed ECDSA public key for given `signature` and + /// `message_hash`, and stores the result in `output`. pub fn ecdsa_recover( &mut self, signature: &[u8; 65], @@ -436,7 +437,8 @@ impl Engine { }; // In most implementations, the v is just 0 or 1 internally, but 27 was added - // as an arbitrary number for signing Bitcoin messages and Ethereum adopted that as well. + // as an arbitrary number for signing Bitcoin messages and Ethereum adopted that + // as well. let recovery_byte = if signature[64] > 26 { signature[64] - 27 } else { diff --git a/crates/engine/src/test_api.rs b/crates/engine/src/test_api.rs index b3dd43a5b02..b764443e700 100644 --- a/crates/engine/src/test_api.rs +++ b/crates/engine/src/test_api.rs @@ -215,7 +215,8 @@ impl Engine { self.exec_context.callee() } - /// Returns the contents of the past performed environmental `debug_message` in order. + /// Returns the contents of the past performed environmental `debug_message` + /// in order. pub fn get_emitted_debug_messages(&self) -> RecordedDebugMessages { self.debug_info.emitted_debug_messages.clone() } @@ -237,7 +238,8 @@ impl Engine { self.database.set_balance(&account_id, new_balance); } - /// Sets the value transferred from the caller to the callee as part of the call. + /// Sets the value transferred from the caller to the callee as part of the + /// call. pub fn set_value_transferred(&mut self, value: Balance) { self.exec_context.value_transferred = value; } diff --git a/crates/engine/src/types.rs b/crates/engine/src/types.rs index 5237f7a5948..66594dc8408 100644 --- a/crates/engine/src/types.rs +++ b/crates/engine/src/types.rs @@ -20,7 +20,8 @@ use derive_more::From; /// /// In the long-term this type should be `Vec` as well, as to not /// be dependent on the specific off-chain environment type, so that -/// the `engine` crate can be used with an arbitrary `Environment` configuration. +/// the `engine` crate can be used with an arbitrary `Environment` +/// configuration. pub type Balance = u128; /// The Account Id type used by this crate. diff --git a/crates/env/src/api.rs b/crates/env/src/api.rs index d9a4bcc28df..3bbdf5217f8 100644 --- a/crates/env/src/api.rs +++ b/crates/env/src/api.rs @@ -177,11 +177,12 @@ where /// /// # Parameters /// -/// - `at_refcount`: The `refcount` assumed for the returned `custom_refcount_*` fields. -/// If `None` is supplied the `custom_refcount_*` fields will also be `None`. +/// - `at_refcount`: The `refcount` assumed for the returned `custom_refcount_*` +/// fields. If `None` is supplied the `custom_refcount_*` fields will also be +/// `None`. /// -/// The `current_*` fields of `RentStatus` do **not** consider changes to the code's -/// `refcount` made during the currently running call. +/// The `current_*` fields of `RentStatus` do **not** consider changes to the +/// code's `refcount` made during the currently running call. /// /// # Errors /// @@ -262,7 +263,8 @@ where /// /// # Panics /// -/// - If the encode length of value exceeds the configured maximum value length of a storage entry. +/// - If the encode length of value exceeds the configured maximum value length +/// of a storage entry. pub fn set_contract_storage(key: &Key, value: &V) where V: scale::Encode, @@ -272,7 +274,8 @@ where }) } -/// Returns the value stored under the given key in the contract's storage if any. +/// Returns the value stored under the given key in the contract's storage if +/// any. /// /// # Errors /// @@ -298,9 +301,10 @@ pub fn clear_contract_storage(key: &Key) { /// # Note /// /// - Prefer using this over [`eval_contract`] if possible. [`invoke_contract`] -/// will generally have a better performance since it won't try to fetch any results. -/// - This is a low level way to invoke another smart contract. -/// Prefer to use the ink! guided and type safe approach to using this. +/// will generally have a better performance since it won't try to fetch any +/// results. +/// - This is a low level way to invoke another smart contract. Prefer to use +/// the ink! guided and type safe approach to using this. /// /// # Errors /// @@ -381,11 +385,11 @@ where /// /// - `account_id`: Account ID of the to-be-restored contract. /// - `code_hash`: Code hash of the to-be-restored contract. -/// - `rent_allowance`: Rent allowance of the restored contract -/// upon successful restoration. -/// - `filtered_keys`: Storage keys to be excluded when calculating the tombstone hash, -/// which is used to decide whether the original contract and the -/// to-be-restored contract have matching storage. +/// - `rent_allowance`: Rent allowance of the restored contract upon successful +/// restoration. +/// - `filtered_keys`: Storage keys to be excluded when calculating the +/// tombstone hash, which is used to decide whether the original contract and +/// the to-be-restored contract have matching storage. /// /// # Usage /// @@ -407,14 +411,15 @@ where /// The `filtered_keys` argument can be used to ignore the extraneous keys /// used by `C2` but not used by `C`. /// -/// The process of such a smart contract restoration can generally be very expensive. +/// The process of such a smart contract restoration can generally be very +/// expensive. /// /// # Note /// -/// - `filtered_keys` can be used to ignore certain storage regions -/// in the restorer contract to not influence the hash calculations. -/// - Does *not* perform restoration right away but defers it to the end of -/// the contract execution. +/// - `filtered_keys` can be used to ignore certain storage regions in the +/// restorer contract to not influence the hash calculations. +/// - Does *not* perform restoration right away but defers it to the end of the +/// contract execution. /// - Restoration is canceled if there is no tombstone in the destination /// address or if the hashes don't match. No changes are made in this case. pub fn restore_contract( @@ -447,8 +452,8 @@ pub fn restore_contract( /// # Note /// /// This function never returns. Either the termination was successful and the -/// execution of the destroyed contract is halted. Or it failed during the termination -/// which is considered fatal and results in a trap and rollback. +/// execution of the destroyed contract is halted. Or it failed during the +/// termination which is considered fatal and results in a trap and rollback. pub fn terminate_contract(beneficiary: T::AccountId) -> ! where T: Environment, @@ -484,10 +489,10 @@ where /// /// # Note /// -/// - The input is the 4-bytes selector followed by the arguments -/// of the called function in their SCALE encoded representation. -/// - No prior interaction with the environment must take place before -/// calling this procedure. +/// - The input is the 4-bytes selector followed by the arguments of the called +/// function in their SCALE encoded representation. +/// - No prior interaction with the environment must take place before calling +/// this procedure. /// /// # Usage /// @@ -526,13 +531,14 @@ where }) } -/// Returns a random hash seed and the block number since which it was determinable -/// by chain observers. +/// Returns a random hash seed and the block number since which it was +/// determinable by chain observers. /// /// # Note /// /// - The subject buffer can be used to further randomize the hash. -/// - Within the same execution returns the same random hash for the same subject. +/// - Within the same execution returns the same random hash for the same +/// subject. /// /// # Errors /// @@ -541,10 +547,10 @@ where /// # Important /// /// The returned seed should only be used to distinguish commitments made before -/// the returned block number. If the block number is too early (i.e. commitments were -/// made afterwards), then ensure no further commitments may be made and repeatedly -/// call this on later blocks until the block number returned is later than the latest -/// commitment. +/// the returned block number. If the block number is too early (i.e. +/// commitments were made afterwards), then ensure no further commitments may be +/// made and repeatedly call this on later blocks until the block number +/// returned is later than the latest commitment. pub fn random(subject: &[u8]) -> Result<(T::Hash, T::BlockNumber)> where T: Environment, @@ -561,7 +567,8 @@ pub fn debug_message(message: &str) { }) } -/// Conducts the crypto hash of the given input and stores the result in `output`. +/// Conducts the crypto hash of the given input and stores the result in +/// `output`. /// /// # Example /// @@ -580,7 +587,8 @@ where }) } -/// Conducts the crypto hash of the given encoded input and stores the result in `output`. +/// Conducts the crypto hash of the given encoded input and stores the result in +/// `output`. /// /// # Example /// @@ -605,8 +613,8 @@ where }) } -/// Recovers the compressed ECDSA public key for given `signature` and `message_hash`, -/// and stores the result in `output`. +/// Recovers the compressed ECDSA public key for given `signature` and +/// `message_hash`, and stores the result in `output`. /// /// # Example /// diff --git a/crates/env/src/arithmetic.rs b/crates/env/src/arithmetic.rs index 131cfd44aa6..57b18c4b3bf 100644 --- a/crates/env/src/arithmetic.rs +++ b/crates/env/src/arithmetic.rs @@ -127,34 +127,37 @@ impl BaseArithmetic for T where /// A meta trait for arithmetic (copied from substrate). /// -/// Arithmetic types do all the usual stuff you'd expect numbers to do. They are guaranteed to -/// be able to represent at least `u32` values without loss, hence the trait implies `From` -/// and smaller integers. All other conversions are fallible. +/// Arithmetic types do all the usual stuff you'd expect numbers to do. They are +/// guaranteed to be able to represent at least `u32` values without loss, hence +/// the trait implies `From` and smaller integers. All other conversions +/// are fallible. pub trait AtLeast32Bit: BaseArithmetic + From + From {} impl AtLeast32Bit for T where T: BaseArithmetic + From + From {} -/// A meta trait for arithmetic. Same as [`AtLeast32Bit `], but also bounded to be unsigned. +/// A meta trait for arithmetic. Same as [`AtLeast32Bit `], but also bounded to +/// be unsigned. pub trait AtLeast32BitUnsigned: AtLeast32Bit + Unsigned {} impl AtLeast32BitUnsigned for T where T: AtLeast32Bit + Unsigned {} -/// Saturating arithmetic operations, returning maximum or minimum values instead of overflowing. +/// Saturating arithmetic operations, returning maximum or minimum values +/// instead of overflowing. pub trait Saturating { - /// Saturating addition. Compute `self + rhs`, saturating at the numeric bounds instead of - /// overflowing. + /// Saturating addition. Compute `self + rhs`, saturating at the numeric + /// bounds instead of overflowing. fn saturating_add(self, rhs: Self) -> Self; - /// Saturating subtraction. Compute `self - rhs`, saturating at the numeric bounds instead of - /// overflowing. + /// Saturating subtraction. Compute `self - rhs`, saturating at the numeric + /// bounds instead of overflowing. fn saturating_sub(self, rhs: Self) -> Self; - /// Saturating multiply. Compute `self * rhs`, saturating at the numeric bounds instead of - /// overflowing. + /// Saturating multiply. Compute `self * rhs`, saturating at the numeric + /// bounds instead of overflowing. fn saturating_mul(self, rhs: Self) -> Self; - /// Saturating exponentiation. Compute `self.pow(exp)`, saturating at the numeric bounds - /// instead of overflowing. + /// Saturating exponentiation. Compute `self.pow(exp)`, saturating at the + /// numeric bounds instead of overflowing. fn saturating_pow(self, exp: usize) -> Self; } diff --git a/crates/env/src/backend.rs b/crates/env/src/backend.rs index 6c69c0bc0f6..4936c75fa88 100644 --- a/crates/env/src/backend.rs +++ b/crates/env/src/backend.rs @@ -32,7 +32,8 @@ use crate::{ }; use ink_primitives::Key; -/// The flags to indicate further information about the end of a contract execution. +/// The flags to indicate further information about the end of a contract +/// execution. #[derive(Default)] pub struct ReturnFlags { value: u32, @@ -62,7 +63,8 @@ pub trait EnvBackend { where V: scale::Encode; - /// Returns the value stored under the given key in the contract's storage if any. + /// Returns the value stored under the given key in the contract's storage + /// if any. /// /// # Errors /// @@ -74,21 +76,23 @@ pub trait EnvBackend { /// Clears the contract's storage key entry. fn clear_contract_storage(&mut self, key: &Key); - /// Returns the execution input to the executed contract and decodes it as `T`. + /// Returns the execution input to the executed contract and decodes it as + /// `T`. /// /// # Note /// - /// - The input is the 4-bytes selector followed by the arguments - /// of the called function in their SCALE encoded representation. + /// - The input is the 4-bytes selector followed by the arguments of the + /// called function in their SCALE encoded representation. /// - No prior interaction with the environment must take place before /// calling this procedure. /// /// # Usage /// /// Normally contracts define their own `enum` dispatch types respective - /// to their exported constructors and messages that implement `scale::Decode` - /// according to the constructors or messages selectors and their arguments. - /// These `enum` dispatch types are then given to this procedure as the `T`. + /// to their exported constructors and messages that implement + /// `scale::Decode` according to the constructors or messages selectors + /// and their arguments. These `enum` dispatch types are then given to + /// this procedure as the `T`. /// /// When using ink! users do not have to construct those enum dispatch types /// themselves as they are normally generated by the ink! code generation @@ -116,27 +120,31 @@ pub trait EnvBackend { /// Emit a custom debug message. /// - /// The message is appended to the debug buffer which is then supplied to the calling RPC - /// client. This buffer is also printed as a debug message to the node console if the - /// `debug` log level is enabled for the `runtime::contracts` target. + /// The message is appended to the debug buffer which is then supplied to + /// the calling RPC client. This buffer is also printed as a debug + /// message to the node console if the `debug` log level is enabled for + /// the `runtime::contracts` target. /// - /// If debug message recording is disabled in the contracts pallet, which is always the case - /// when the code is executing on-chain, then this will have no effect. + /// If debug message recording is disabled in the contracts pallet, which is + /// always the case when the code is executing on-chain, then this will + /// have no effect. fn debug_message(&mut self, content: &str); - /// Conducts the crypto hash of the given input and stores the result in `output`. + /// Conducts the crypto hash of the given input and stores the result in + /// `output`. fn hash_bytes(&mut self, input: &[u8], output: &mut ::Type) where H: CryptoHash; - /// Conducts the crypto hash of the given encoded input and stores the result in `output`. + /// Conducts the crypto hash of the given encoded input and stores the + /// result in `output`. fn hash_encoded(&mut self, input: &T, output: &mut ::Type) where H: CryptoHash, T: scale::Encode; - /// Recovers the compressed ECDSA public key for given `signature` and `message_hash`, - /// and stores the result in `output`. + /// Recovers the compressed ECDSA public key for given `signature` and + /// `message_hash`, and stores the result in `output`. fn ecdsa_recover( &mut self, signature: &[u8; 65], @@ -192,7 +200,8 @@ pub trait TypedEnvBackend: EnvBackend { /// /// # Note /// - /// For more details visit: [`transferred_balance`][`crate::transferred_balance`] + /// For more details visit: + /// [`transferred_balance`][`crate::transferred_balance`] fn transferred_balance(&mut self) -> T::Balance; /// Returns the price for the specified amount of gas. @@ -272,7 +281,8 @@ pub trait TypedEnvBackend: EnvBackend { /// /// # Note /// - /// For more details visit: [`tombstone_deposit`][`crate::tombstone_deposit`] + /// For more details visit: + /// [`tombstone_deposit`][`crate::tombstone_deposit`] fn tombstone_deposit(&mut self) -> T::Balance; /// Emits an event with the given event data. @@ -289,7 +299,8 @@ pub trait TypedEnvBackend: EnvBackend { /// /// # Note /// - /// For more details visit: [`set_rent_allowance`][`crate::set_rent_allowance`] + /// For more details visit: + /// [`set_rent_allowance`][`crate::set_rent_allowance`] fn set_rent_allowance(&mut self, new_value: T::Balance) where T: Environment; @@ -325,7 +336,8 @@ pub trait TypedEnvBackend: EnvBackend { /// /// # Note /// - /// For more details visit: [`instantiate_contract`][`crate::instantiate_contract`] + /// For more details visit: + /// [`instantiate_contract`][`crate::instantiate_contract`] fn instantiate_contract( &mut self, params: &CreateParams, @@ -353,7 +365,8 @@ pub trait TypedEnvBackend: EnvBackend { /// /// # Note /// - /// For more details visit: [`terminate_contract`][`crate::terminate_contract`] + /// For more details visit: + /// [`terminate_contract`][`crate::terminate_contract`] fn terminate_contract(&mut self, beneficiary: T::AccountId) -> ! where T: Environment; diff --git a/crates/env/src/call/call_builder.rs b/crates/env/src/call/call_builder.rs index c4e472f6ac9..fb7b6f0f515 100644 --- a/crates/env/src/call/call_builder.rs +++ b/crates/env/src/call/call_builder.rs @@ -85,7 +85,8 @@ where /// # Note /// /// Prefer [`invoke`](`Self::invoke`) over [`eval`](`Self::eval`) if the - /// called contract message does not return anything because it is more efficient. + /// called contract message does not return anything because it is more + /// efficient. pub fn invoke(&self) -> Result<(), crate::Error> { crate::invoke_contract(self) } @@ -104,19 +105,21 @@ where /// # Note /// /// Prefer [`invoke`](`Self::invoke`) over [`eval`](`Self::eval`) if the - /// called contract message does not return anything because it is more efficient. + /// called contract message does not return anything because it is more + /// efficient. pub fn eval(&self) -> Result { crate::eval_contract(self) } } -/// Returns a new [`CallBuilder`] to build up the parameters to a cross-contract call. +/// Returns a new [`CallBuilder`] to build up the parameters to a cross-contract +/// call. /// /// # Example /// -/// **Note:** The shown examples panic because there is currently no cross-calling -/// support in the off-chain testing environment. However, this code -/// should work fine in on-chain environments. +/// **Note:** The shown examples panic because there is currently no +/// cross-calling support in the off-chain testing environment. +/// However, this code should work fine in on-chain environments. /// /// ## Example 1: No Return Value /// @@ -126,10 +129,8 @@ where /// - has a selector equal to `0xDEADBEEF` /// - is provided with 5000 units of gas for its execution /// - is provided with 10 units of transferred value for the contract instance -/// - receives the following arguments in order -/// 1. an `i32` with value `42` -/// 2. a `bool` with value `true` -/// 3. an array of 32 `u8` with value `0x10` +/// - receives the following arguments in order 1. an `i32` with value `42` 2. a +/// `bool` with value `true` 3. an array of 32 `u8` with value `0x10` /// /// ```should_panic /// # use ::ink_env::{ @@ -161,10 +162,8 @@ where /// - has a selector equal to `0xDEADBEEF` /// - is provided with 5000 units of gas for its execution /// - is provided with 10 units of transferred value for the contract instance -/// - receives the following arguments in order -/// 1. an `i32` with value `42` -/// 2. a `bool` with value `true` -/// 3. an array of 32 `u8` with value `0x10` +/// - receives the following arguments in order 1. an `i32` with value `42` 2. a +/// `bool` with value `true` 3. an array of 32 `u8` with value `0x10` /// /// ```should_panic /// # use ::ink_env::{ @@ -291,7 +290,8 @@ where } mod seal { - /// Used to prevent users from implementing `IndicateReturnType` for their own types. + /// Used to prevent users from implementing `IndicateReturnType` for their + /// own types. pub trait Sealed {} impl Sealed for () {} impl Sealed for super::ReturnType {} @@ -311,9 +311,9 @@ where /// /// # Note /// - /// Either use `.returns::<()>` to signal that the call does not return a value - /// or use `.returns::>` to signal that the call returns a value of - /// type `T`. + /// Either use `.returns::<()>` to signal that the call does not return a + /// value or use `.returns::>` to signal that the call + /// returns a value of type `T`. #[inline] pub fn returns( self, diff --git a/crates/env/src/call/common.rs b/crates/env/src/call/common.rs index 1097aa835f5..ba0c0f3e997 100644 --- a/crates/env/src/call/common.rs +++ b/crates/env/src/call/common.rs @@ -18,7 +18,8 @@ use core::marker::PhantomData; /// Represents a return type. /// -/// Used as a marker type to differentiate at compile-time between invoke and evaluate. +/// Used as a marker type to differentiate at compile-time between invoke and +/// evaluate. #[derive(Debug)] pub struct ReturnType(PhantomData T>); diff --git a/crates/env/src/call/create_builder.rs b/crates/env/src/call/create_builder.rs index bd50b65fa45..8fa58c3b535 100644 --- a/crates/env/src/call/create_builder.rs +++ b/crates/env/src/call/create_builder.rs @@ -46,7 +46,8 @@ pub trait FromAccountId where T: Environment, { - /// Creates the contract instance from the account ID of the already instantiated contract. + /// Creates the contract instance from the account ID of the already + /// instantiated contract. fn from_account_id(account_id: ::AccountId) -> Self; } @@ -139,7 +140,8 @@ where return_type: ReturnType, } -/// Returns a new [`CreateBuilder`] to build up the parameters to a cross-contract instantiation. +/// Returns a new [`CreateBuilder`] to build up the parameters to a +/// cross-contract instantiation. /// /// # Example /// @@ -149,11 +151,10 @@ where /// /// - has a selector equal to `0xDEADBEEF` /// - is provided with 4000 units of gas for its execution -/// - is provided with 25 units of transferred value for the new contract instance -/// - receives the following arguments in order -/// 1. an `i32` with value `42` -/// 2. a `bool` with value `true` -/// 3. an array of 32 `u8` with value `0x10` +/// - is provided with 25 units of transferred value for the new contract +/// instance +/// - receives the following arguments in order 1. an `i32` with value `42` 2. a +/// `bool` with value `true` 3. an array of 32 `u8` with value `0x10` /// /// ```should_panic /// # use ::ink_env::{ @@ -184,9 +185,9 @@ where /// .unwrap(); /// ``` /// -/// **Note:** The shown example panics because there is currently no cross-calling -/// support in the off-chain testing environment. However, this code -/// should work fine in on-chain environments. +/// **Note:** The shown example panics because there is currently no +/// cross-calling support in the off-chain testing environment. +/// However, this code should work fine in on-chain environments. #[allow(clippy::type_complexity)] pub fn build_create() -> CreateBuilder< E, diff --git a/crates/env/src/chain_extension.rs b/crates/env/src/chain_extension.rs index 5e094d55681..2a55d5b0361 100644 --- a/crates/env/src/chain_extension.rs +++ b/crates/env/src/chain_extension.rs @@ -14,8 +14,9 @@ //! Definitions and utilities for calling chain extension methods. //! -//! Users should not use these types and definitions directly but rather use the provided -//! `#[ink::chain_extension]` procedural macro defined in the `ink_lang` crate. +//! Users should not use these types and definitions directly but rather use the +//! provided `#[ink::chain_extension]` procedural macro defined in the +//! `ink_lang` crate. use crate::{ backend::EnvBackend, @@ -32,48 +33,57 @@ use core::marker::PhantomData; /// It is the `u32` return value. /// /// The purpose of an `ErrorCode` type that implements this trait is to provide -/// more context information about the status of an ink! chain extension method call. +/// more context information about the status of an ink! chain extension method +/// call. pub trait FromStatusCode: Sized { - /// Returns `Ok` if the status code for the called chain extension method is valid. + /// Returns `Ok` if the status code for the called chain extension method is + /// valid. /// - /// Returning `Ok` will query the output buffer of the call if the chain extension - /// method definition has a return value. + /// Returning `Ok` will query the output buffer of the call if the chain + /// extension method definition has a return value. /// /// # Note /// - /// The convention is to use `0` as the only `raw` value that yields `Ok` whereas - /// every other value represents one error code. By convention this mapping should - /// never panic and therefore every `raw` value must map to either `Ok` or to a proper - /// `ErrorCode` variant. + /// The convention is to use `0` as the only `raw` value that yields `Ok` + /// whereas every other value represents one error code. By convention + /// this mapping should never panic and therefore every `raw` value must + /// map to either `Ok` or to a proper `ErrorCode` variant. fn from_status_code(status_code: u32) -> Result<(), Self>; } /// A concrete instance of a chain extension method. /// -/// This is a utility type used to drive the execution of a chain extension method call. -/// It has several specializations of its `call` method for different ways to manage -/// error handling when calling a predefined chain extension method. +/// This is a utility type used to drive the execution of a chain extension +/// method call. It has several specializations of its `call` method for +/// different ways to manage error handling when calling a predefined chain +/// extension method. /// -/// - `I` represents the input type of the chain extension method. -/// All tuple types that may act as input parameters for the chain extension method are valid. -/// Examples include `()`, `i32`, `(u8, [u8; 5], i32)`, etc. +/// - `I` represents the input type of the chain extension method. All tuple +/// types that may act as input parameters for the chain extension method are +/// valid. Examples include `()`, `i32`, `(u8, [u8; 5], i32)`, etc. /// - `O` represents the return (or output) type of the chain extension method. /// Only `Result` or `NoResult` generic types are allowed for `O`. -/// The `Result` type says that the chain extension method returns a `Result` type -/// whereas the `NoResult` type says that the chain extension method returns a non-`Result` value -/// of type `O`. -/// - `ErrorCode` represents how the chain extension method handles the chain extension's error code. -/// Only `HandleErrorCode` and `IgnoreErrorCode` types are allowed that each say to either properly -/// handle or ignore the chain extension's error code respectively. +/// The `Result` type says that the chain extension method returns a +/// `Result` type whereas the `NoResult` type says that the chain extension +/// method returns a non-`Result` value of type `O`. +/// - `ErrorCode` represents how the chain extension method handles the chain +/// extension's error code. Only `HandleErrorCode` and `IgnoreErrorCode` +/// types are allowed that each say to either properly handle or ignore the +/// chain extension's error code respectively. /// -/// The type states for type parameter `O` and `ErrorCode` represent 4 different states: +/// The type states for type parameter `O` and `ErrorCode` represent 4 different +/// states: /// -/// 1. The chain extension method makes use of the chain extension's error code: `HandleErrorCode(E)` +/// 1. The chain extension method makes use of the chain extension's error code: +/// `HandleErrorCode(E)` /// - **A:** The chain extension method returns a `Result` type. -/// - **B:** The chain extension method returns a type `T` that is not a `Result` type: `NoResult` -/// 2. The chain extension ignores the chain extension's error code: `IgnoreErrorCode` +/// - **B:** The chain extension method returns a type `T` that is not a +/// `Result` type: `NoResult` +/// 2. The chain extension ignores the chain extension's error code: +/// `IgnoreErrorCode` /// - **A:** The chain extension method returns a `Result` type. -/// - **B:** The chain extension method returns a type `T` that is not a `Result` type: `NoResult` +/// - **B:** The chain extension method returns a type `T` that is not a +/// `Result` type: `NoResult` #[derive(Debug)] pub struct ChainExtensionMethod { func_id: u32, @@ -98,8 +108,9 @@ impl ChainExtensionMethod<(), O, ErrorCode> { /// # Note /// /// `I` represents the input type of the chain extension method. - /// All tuple types that may act as input parameters for the chain extension method are valid. - /// Examples include `()`, `i32`, `(u8, [u8; 5], i32)`, etc. + /// All tuple types that may act as input parameters for the chain extension + /// method are valid. Examples include `()`, `i32`, `(u8, [u8; 5], + /// i32)`, etc. #[inline(always)] pub fn input(self) -> ChainExtensionMethod where @@ -113,11 +124,13 @@ impl ChainExtensionMethod<(), O, ErrorCode> { } impl ChainExtensionMethod { - /// Sets the output type of the chain extension method call to `Result`. + /// Sets the output type of the chain extension method call to `Result`. /// /// # Note /// - /// This indicates that the chain extension method return value might represent a failure. + /// This indicates that the chain extension method return value might + /// represent a failure. #[inline(always)] pub fn output_result(self) -> ChainExtensionMethod, ErrorCode> where @@ -151,15 +164,18 @@ impl ChainExtensionMethod { } impl ChainExtensionMethod { - /// Makes the chain extension method call assume that the returned status code is always success. + /// Makes the chain extension method call assume that the returned status + /// code is always success. /// /// # Note /// - /// This will avoid handling of failure status codes returned by the chain extension method call. - /// Use this only if you are sure that the chain extension method call will never return an error + /// This will avoid handling of failure status codes returned by the chain + /// extension method call. Use this only if you are sure that the chain + /// extension method call will never return an error /// code that represents failure. /// - /// The output of the chain extension method call is always decoded and returned in this case. + /// The output of the chain extension method call is always decoded and + /// returned in this case. #[inline(always)] pub fn ignore_error_code(self) -> ChainExtensionMethod { ChainExtensionMethod { @@ -172,8 +188,9 @@ impl ChainExtensionMethod { /// /// # Note /// - /// This will handle the returned status code and only loads and decodes the value - /// returned as the output of the chain extension method call in case of success. + /// This will handle the returned status code and only loads and decodes the + /// value returned as the output of the chain extension method call in + /// case of success. #[inline(always)] pub fn handle_error_code( self, @@ -192,19 +209,23 @@ impl ChainExtensionMethod { pub mod state { use core::marker::PhantomData; - /// Type state meaning that the chain extension method ignores the chain extension's error code. + /// Type state meaning that the chain extension method ignores the chain + /// extension's error code. #[derive(Debug)] pub enum IgnoreErrorCode {} - /// Type state meaning that the chain extension method uses the chain extension's error code. + /// Type state meaning that the chain extension method uses the chain + /// extension's error code. #[derive(Debug)] pub struct HandleErrorCode { error_code: PhantomData T>, } - /// Type state meaning that the chain extension method deliberately does not return a `Result` type. + /// Type state meaning that the chain extension method deliberately does not + /// return a `Result` type. /// - /// Additionally this is enforced by the `#[ink::chain_extension]` procedural macro when used. + /// Additionally this is enforced by the `#[ink::chain_extension]` + /// procedural macro when used. #[derive(Debug)] pub struct NoResult { no_result: PhantomData T>, @@ -225,18 +246,23 @@ where /// /// # Errors /// - /// - If the called chain extension method returns a non-successful error code. - /// - If the `Result` return value of the called chain extension represents an error. + /// - If the called chain extension method returns a non-successful error + /// code. + /// - If the `Result` return value of the called chain extension represents + /// an error. /// - If the `Result` return value cannot be SCALE decoded properly. - /// - If custom constraints specified by the called chain extension method are violated. - /// - These constraints are determined and defined by the author of the chain extension method. + /// - If custom constraints specified by the called chain extension method + /// are violated. + /// - These constraints are determined and defined by the author of the + /// chain extension method. /// /// # Example /// - /// Declares a chain extension method with the unique ID of 5 that requires a `bool` and an `i32` - /// as input parameters and returns a `Result` upon completion. - /// It will handle the shared error code from the chain extension. - /// The call is finally invoked with arguments `true` and `42` for the `bool` and `i32` input + /// Declares a chain extension method with the unique ID of 5 that requires + /// a `bool` and an `i32` as input parameters and returns a `Result` upon completion. It will handle the shared error code from + /// the chain extension. The call is finally invoked with arguments + /// `true` and `42` for the `bool` and `i32` input /// parameter respectively. /// /// ```should_panic @@ -287,18 +313,22 @@ where /// /// # Errors /// - /// - If the `Result` return value of the called chain extension represents an error. + /// - If the `Result` return value of the called chain extension represents + /// an error. /// - If the `Result` return value cannot be SCALE decoded properly. - /// - If custom constraints specified by the called chain extension method are violated. - /// - These constraints are determined and defined by the author of the chain extension method. + /// - If custom constraints specified by the called chain extension method + /// are violated. + /// - These constraints are determined and defined by the author of the + /// chain extension method. /// /// # Example /// - /// Declares a chain extension method with the unique ID of 5 that requires a `bool` and an `i32` - /// as input parameters and returns a `Result` upon completion. - /// It will ignore the shared error code from the chain extension and assumes that the call succeeds. - /// The call is finally invoked with arguments `true` and `42` for the `bool` and `i32` input - /// parameter respectively. + /// Declares a chain extension method with the unique ID of 5 that requires + /// a `bool` and an `i32` as input parameters and returns a `Result` upon completion. It will ignore the shared error code from + /// the chain extension and assumes that the call succeeds. The call is + /// finally invoked with arguments `true` and `42` for the `bool` and `i32` + /// input parameter respectively. /// /// ```should_panic /// # // Panics because the off-chain environment has not @@ -342,9 +372,12 @@ where /// /// # Errors /// - /// - If the called chain extension method returns a non-successful error code. - /// - If custom constraints specified by the called chain extension method are violated. - /// - These constraints are determined and defined by the author of the chain extension method. + /// - If the called chain extension method returns a non-successful error + /// code. + /// - If custom constraints specified by the called chain extension method + /// are violated. + /// - These constraints are determined and defined by the author of the + /// chain extension method. /// /// # Panics /// @@ -352,10 +385,11 @@ where /// /// # Example /// - /// Declares a chain extension method with the unique ID of 5 that requires a `bool` and an `i32` - /// as input parameters and returns a `Result` upon completion. - /// It will handle the shared error code from the chain extension. - /// The call is finally invoked with arguments `true` and `42` for the `bool` and `i32` input + /// Declares a chain extension method with the unique ID of 5 that requires + /// a `bool` and an `i32` as input parameters and returns a `Result` upon completion. It will handle the shared error code + /// from the chain extension. The call is finally invoked with arguments + /// `true` and `42` for the `bool` and `i32` input /// parameter respectively. /// /// ```should_panic @@ -405,11 +439,12 @@ where /// /// # Example /// - /// Declares a chain extension method with the unique ID of 5 that requires a `bool` and an `i32` - /// as input parameters and returns a `Result` upon completion. - /// It will ignore the shared error code from the chain extension and assumes that the call succeeds. - /// The call is finally invoked with arguments `true` and `42` for the `bool` and `i32` input - /// parameter respectively. + /// Declares a chain extension method with the unique ID of 5 that requires + /// a `bool` and an `i32` as input parameters and returns a `Result` upon completion. It will ignore the shared error code + /// from the chain extension and assumes that the call succeeds. + /// The call is finally invoked with arguments `true` and `42` for the + /// `bool` and `i32` input parameter respectively. /// /// ```should_panic /// # // Panics because the off-chain environment has not diff --git a/crates/env/src/engine/experimental_off_chain/impls.rs b/crates/env/src/engine/experimental_off_chain/impls.rs index f2f7ceff243..9d41c82e3b3 100644 --- a/crates/env/src/engine/experimental_off_chain/impls.rs +++ b/crates/env/src/engine/experimental_off_chain/impls.rs @@ -48,8 +48,8 @@ use ink_engine::{ use ink_primitives::Key; /// The capacity of the static buffer. -/// This is the same size as the ink! on-chain environment. We chose to use the same size -/// to be as close to the on-chain behavior as possible. +/// This is the same size as the ink! on-chain environment. We chose to use the +/// same size to be as close to the on-chain behavior as possible. const BUFFER_SIZE: usize = 1 << 14; // 16 kB impl CryptoHash for Blake2x128 { @@ -261,7 +261,8 @@ impl EnvBackend for EnvInstance { }; // In most implementations, the v is just 0 or 1 internally, but 27 was added - // as an arbitrary number for signing Bitcoin messages and Ethereum adopted that as well. + // as an arbitrary number for signing Bitcoin messages and Ethereum adopted that + // as well. let recovery_byte = if signature[64] > 26 { signature[64] - 27 } else { diff --git a/crates/env/src/engine/experimental_off_chain/test_api.rs b/crates/env/src/engine/experimental_off_chain/test_api.rs index aebdb46c7b4..7ee7d123a99 100644 --- a/crates/env/src/engine/experimental_off_chain/test_api.rs +++ b/crates/env/src/engine/experimental_off_chain/test_api.rs @@ -129,7 +129,8 @@ where unimplemented!("off-chain environment does not yet support `set_block_entropy`"); } -/// Returns the contents of the past performed environmental debug messages in order. +/// Returns the contents of the past performed environmental debug messages in +/// order. pub fn recorded_debug_messages() -> RecordedDebugMessages { ::on_instance(|instance| { instance.engine.get_emitted_debug_messages() @@ -140,8 +141,9 @@ pub fn recorded_debug_messages() -> RecordedDebugMessages { /// /// # Note /// -/// Useful for benchmarks because it ensures the initialized storage is maintained across runs, -/// because lazy storage structures automatically clear their associated cells when they are dropped. +/// Useful for benchmarks because it ensures the initialized storage is +/// maintained across runs, because lazy storage structures automatically clear +/// their associated cells when they are dropped. pub fn set_clear_storage_disabled(_disable: bool) { unimplemented!( "off-chain environment does not yet support `set_clear_storage_disabled`" @@ -208,7 +210,8 @@ where }) } -/// Sets the value transferred from the caller to the callee as part of the call. +/// Sets the value transferred from the caller to the callee as part of the +/// call. pub fn set_value_transferred(value: T::Balance) where T: Environment, // Just temporary for the MVP! @@ -324,11 +327,12 @@ pub fn recorded_events() -> impl Iterator { /// /// The arguments denote: /// -/// * `should_terminate`: A closure in which the function supposed to terminate is called. -/// * `expected_beneficiary`: The beneficiary account who should have received the -/// remaining value in the contract -/// * `expected_value_transferred_to_beneficiary`: The value which should have been transferred -/// to the `expected_beneficiary`. +/// * `should_terminate`: A closure in which the function supposed to terminate +/// is called. +/// * `expected_beneficiary`: The beneficiary account who should have received +/// the remaining value in the contract +/// * `expected_value_transferred_to_beneficiary`: The value which should have +/// been transferred to the `expected_beneficiary`. /// # Usage /// /// ```no_compile diff --git a/crates/env/src/engine/off_chain/call_data.rs b/crates/env/src/engine/off_chain/call_data.rs index b6b4dbf88a7..b3523796ff4 100644 --- a/crates/env/src/engine/off_chain/call_data.rs +++ b/crates/env/src/engine/off_chain/call_data.rs @@ -22,7 +22,8 @@ use ink_prelude::{ /// /// # Note /// -/// The first four bytes are the function selector and the rest are SCALE encoded inputs. +/// The first four bytes are the function selector and the rest are SCALE +/// encoded inputs. #[derive(Debug, Clone, PartialEq, Eq)] pub struct CallData { /// Already encoded function selector and inputs. diff --git a/crates/env/src/engine/off_chain/chain_extension.rs b/crates/env/src/engine/off_chain/chain_extension.rs index ecec775a123..22f2bbd08bb 100644 --- a/crates/env/src/engine/off_chain/chain_extension.rs +++ b/crates/env/src/engine/off_chain/chain_extension.rs @@ -26,7 +26,8 @@ use std::collections::{ pub struct ChainExtensionHandler { /// The currently registered runtime call handler. registered: HashMap>, - /// The output buffer used and reused for chain extension method call results. + /// The output buffer used and reused for chain extension method call + /// results. output: Vec, } @@ -38,7 +39,8 @@ pub struct ExtensionId(u32); /// Types implementing this trait can be used as chain extensions. /// -/// This trait is only useful for testing contract via the off-chain environment. +/// This trait is only useful for testing contract via the off-chain +/// environment. pub trait ChainExtension { /// The static function ID of the chain extension. /// @@ -49,7 +51,8 @@ pub trait ChainExtension { /// Calls the chain extension with the given input. /// - /// Returns an error code and may fill the `output` buffer with a SCALE encoded result. + /// Returns an error code and may fill the `output` buffer with a SCALE + /// encoded result. fn call(&mut self, input: &[u8], output: &mut Vec) -> u32; } @@ -79,7 +82,8 @@ impl ChainExtensionHandler { /// Evaluates the chain extension with the given parameters. /// - /// Upon success returns the values returned by the evaluated chain extension. + /// Upon success returns the values returned by the evaluated chain + /// extension. pub fn eval(&mut self, func_id: u32, input: &[u8]) -> Result<(u32, &[u8])> { self.output.clear(); let extension_id = ExtensionId::from(func_id); diff --git a/crates/env/src/engine/off_chain/db/accounts.rs b/crates/env/src/engine/off_chain/db/accounts.rs index e23f9ce474f..c6d131a33d6 100644 --- a/crates/env/src/engine/off_chain/db/accounts.rs +++ b/crates/env/src/engine/off_chain/db/accounts.rs @@ -263,7 +263,8 @@ impl Account { .and_then(|contract| contract.storage.get_storage::(at)) } - /// Returns the total number of reads and write from and to the contract's storage. + /// Returns the total number of reads and write from and to the contract's + /// storage. pub fn get_storage_rw(&self) -> Result<(usize, usize)> { self.contract_or_err().map(|contract| contract.get_rw()) } diff --git a/crates/env/src/engine/off_chain/db/block.rs b/crates/env/src/engine/off_chain/db/block.rs index 0906200d076..f7e3bba60e0 100644 --- a/crates/env/src/engine/off_chain/db/block.rs +++ b/crates/env/src/engine/off_chain/db/block.rs @@ -95,8 +95,8 @@ impl Block { /// /// - Returned hashes on the surface might appear random, however for /// testing purposes the actual implementation is quite simple and - /// computes those "random" hashes by wrapping XOR of the internal entry hash - /// with the eventually repeated sequence of the subject buffer. + /// computes those "random" hashes by wrapping XOR of the internal entry + /// hash with the eventually repeated sequence of the subject buffer. pub fn random(&self, subject: &[u8]) -> Result where T: Environment, diff --git a/crates/env/src/engine/off_chain/db/chain_spec.rs b/crates/env/src/engine/off_chain/db/chain_spec.rs index 444accff607..4d95db9228a 100644 --- a/crates/env/src/engine/off_chain/db/chain_spec.rs +++ b/crates/env/src/engine/off_chain/db/chain_spec.rs @@ -33,11 +33,13 @@ pub struct ChainSpec { tombstone_deposit: OffBalance, /// The targeted block time. block_time: OffTimestamp, - /// The balance a contract needs to deposit per storage byte to stay alive indefinitely. + /// The balance a contract needs to deposit per storage byte to stay alive + /// indefinitely. deposit_per_storage_byte: OffBalance, /// The balance every contract needs to deposit to stay alive indefinitely. deposit_per_contract: OffBalance, - /// The balance a contract needs to deposit per storage item to stay alive indefinitely. + /// The balance a contract needs to deposit per storage item to stay alive + /// indefinitely. deposit_per_storage_item: OffBalance, /// The fraction of the deposit costs that should be used as rent per block. rent_fraction: OffRentFraction, @@ -141,7 +143,8 @@ impl ChainSpec { self.block_time.decode().map_err(Into::into) } - /// The balance a contract needs to deposit per storage byte to stay alive indefinitely. + /// The balance a contract needs to deposit per storage byte to stay alive + /// indefinitely. pub fn deposit_per_storage_byte(&self) -> Result where T: Environment, @@ -157,7 +160,8 @@ impl ChainSpec { self.deposit_per_contract.decode().map_err(Into::into) } - /// The balance a contract needs to deposit per storage item to stay alive indefinitely. + /// The balance a contract needs to deposit per storage item to stay alive + /// indefinitely. pub fn deposit_per_storage_item(&self) -> Result where T: Environment, diff --git a/crates/env/src/engine/off_chain/impls.rs b/crates/env/src/engine/off_chain/impls.rs index 45d18fcf044..3d1ac12e218 100644 --- a/crates/env/src/engine/off_chain/impls.rs +++ b/crates/env/src/engine/off_chain/impls.rs @@ -209,7 +209,8 @@ impl EnvBackend for EnvInstance { }; // In most implementations, the v is just 0 or 1 internally, but 27 was added - // as an arbitrary number for signing Bitcoin messages and Ethereum adopted that as well. + // as an arbitrary number for signing Bitcoin messages and Ethereum adopted that + // as well. let recovery_byte = if signature[64] > 26 { signature[64] - 27 } else { @@ -293,8 +294,8 @@ impl EnvInstance { // Remove the calling account and transfer remaining balance. // // This function never returns. Either the termination was successful and the - // execution of the destroyed contract is halted. Or it failed during the termination - // which is considered fatal. + // execution of the destroyed contract is halted. Or it failed during the + // termination which is considered fatal. fn terminate_contract_impl(&mut self, beneficiary: T::AccountId) -> ! where T: Environment, diff --git a/crates/env/src/engine/off_chain/mod.rs b/crates/env/src/engine/off_chain/mod.rs index 6ff31e65d8b..d77f92a84ad 100644 --- a/crates/env/src/engine/off_chain/mod.rs +++ b/crates/env/src/engine/off_chain/mod.rs @@ -114,7 +114,8 @@ impl EnvInstance { !self.exec_context.is_empty() } - /// Either resets or initializes the off-chain environment to default values. + /// Either resets or initializes the off-chain environment to default + /// values. pub fn initialize_or_reset_as_default(&mut self) -> crate::Result<()> where T: Environment, diff --git a/crates/env/src/engine/off_chain/test_api.rs b/crates/env/src/engine/off_chain/test_api.rs index ff3e9c8236c..239acd5c0a8 100644 --- a/crates/env/src/engine/off_chain/test_api.rs +++ b/crates/env/src/engine/off_chain/test_api.rs @@ -215,7 +215,8 @@ where Ok(()) } -/// Returns the contents of the past performed environmental debug messages in order. +/// Returns the contents of the past performed environmental debug messages in +/// order. pub fn recorded_debug_messages() -> impl Iterator { ::on_instance(|instance| { // We return a clone of the recorded strings instead of @@ -261,8 +262,9 @@ where /// /// # Note /// -/// Useful for benchmarks because it ensures the initialized storage is maintained across runs, -/// because lazy storage structures automatically clear their associated cells when they are dropped. +/// Useful for benchmarks because it ensures the initialized storage is +/// maintained across runs, because lazy storage structures automatically clear +/// their associated cells when they are dropped. pub fn set_clear_storage_disabled(disable: bool) { ::on_instance(|instance| { instance.clear_storage_disabled = disable @@ -384,7 +386,8 @@ pub struct ContractTerminationResult where E: Environment, { - /// The beneficiary account who received the remaining value in the contract. + /// The beneficiary account who received the remaining value in the + /// contract. pub beneficiary: ::AccountId, /// The value which was transferred to the `beneficiary`. pub transferred: ::Balance, diff --git a/crates/env/src/engine/off_chain/typed_encoded.rs b/crates/env/src/engine/off_chain/typed_encoded.rs index a590b74305d..28cd357fc97 100644 --- a/crates/env/src/engine/off_chain/typed_encoded.rs +++ b/crates/env/src/engine/off_chain/typed_encoded.rs @@ -49,20 +49,20 @@ pub struct TypedEncoded { /// # Note /// /// - This should not be the typed that is actually stored as encoded - /// representation in `self.encoded` but should primarily be an - /// abstract marker type that may be used for classification. - /// - The idea behind the marker is to say that whenever two instances - /// of `TypedEncoded` share a marker they are guaranteed to also have - /// a common (but unknown) `type_id` so they can decode to the same - /// original type and thus we can allow to interoperate on them. + /// representation in `self.encoded` but should primarily be an abstract + /// marker type that may be used for classification. + /// - The idea behind the marker is to say that whenever two instances of + /// `TypedEncoded` share a marker they are guaranteed to also have a + /// common (but unknown) `type_id` so they can decode to the same original + /// type and thus we can allow to interoperate on them. /// /// # Example /// /// The `TestEnv` might use one abstract marker for every /// of the fundamental FRAME types: `Balance`, `AccountId`, `Hash`, etc. - /// With this and the explicit guarantee that two instances of `TypedEncoded` - /// with the same abstract marker also share the same (unknown) `type_id` - /// it is possible to allow them to interoperate. + /// With this and the explicit guarantee that two instances of + /// `TypedEncoded` with the same abstract marker also share the same + /// (unknown) `type_id` it is possible to allow them to interoperate. marker: PhantomData T>, } @@ -204,7 +204,8 @@ impl TypedEncoded { Ok(()) } - /// Returns `Ok` if `T` is the type represented by the typed encoded instance. + /// Returns `Ok` if `T` is the type represented by the typed encoded + /// instance. fn check_enforced_type(&self) -> Result<()> where T: 'static, diff --git a/crates/env/src/engine/on_chain/buffer.rs b/crates/env/src/engine/on_chain/buffer.rs index 0ad13729c3c..a1ad9cdd612 100644 --- a/crates/env/src/engine/on_chain/buffer.rs +++ b/crates/env/src/engine/on_chain/buffer.rs @@ -120,9 +120,11 @@ impl<'a> From<&'a mut [u8]> for ScopedBuffer<'a> { } impl<'a> ScopedBuffer<'a> { - /// Splits the scoped buffer into yet another piece to operate on it temporarily. + /// Splits the scoped buffer into yet another piece to operate on it + /// temporarily. /// - /// The split buffer will have an offset of 0 but be offset by `self`'s offset. + /// The split buffer will have an offset of 0 but be offset by `self`'s + /// offset. pub fn split(&mut self) -> ScopedBuffer { ScopedBuffer { offset: 0, @@ -169,9 +171,10 @@ impl<'a> ScopedBuffer<'a> { /// Appends the encoding of `value` to the scoped buffer. /// - /// Does not return the buffer immediately so that other values can be appended - /// afterwards. The [`take_appended`] method shall be used to return the buffer - /// that includes all appended encodings as a single buffer. + /// Does not return the buffer immediately so that other values can be + /// appended afterwards. The [`take_appended`] method shall be used to + /// return the buffer that includes all appended encodings as a single + /// buffer. pub fn append_encoded(&mut self, value: &T) where T: scale::Encode, @@ -185,8 +188,8 @@ impl<'a> ScopedBuffer<'a> { let _ = core::mem::replace(&mut self.buffer, buffer); } - /// Returns the buffer containing all encodings appended via [`append_encoded`] - /// in a single byte buffer. + /// Returns the buffer containing all encodings appended via + /// [`append_encoded`] in a single byte buffer. pub fn take_appended(&mut self) -> &'a mut [u8] { debug_assert_ne!(self.offset, 0); let offset = self.offset; diff --git a/crates/env/src/engine/on_chain/ext.rs b/crates/env/src/engine/on_chain/ext.rs index 92b2be4e0b3..daf58b0f0d3 100644 --- a/crates/env/src/engine/on_chain/ext.rs +++ b/crates/env/src/engine/on_chain/ext.rs @@ -495,13 +495,14 @@ pub fn get_storage(key: &[u8], output: &mut &mut [u8]) -> Result { /// /// # Params /// -/// - `account_id`: Encoded bytes of the `AccountId` of the to-be-restored contract. +/// - `account_id`: Encoded bytes of the `AccountId` of the to-be-restored +/// contract. /// - `code_hash`: Encoded code hash of the to-be-restored contract. -/// - `rent_allowance`: The encoded rent allowance of the restored contract -/// upon successful restoration. +/// - `rent_allowance`: The encoded rent allowance of the restored contract upon +/// successful restoration. /// - `filtered_keys`: Storage keys that will be ignored for the tombstone hash -/// match calculation that decide whether the original contract -/// storage and the storage of the restorer contract is equal. +/// match calculation that decide whether the original contract storage and +/// the storage of the restorer contract is equal. pub fn restore_to( account_id: &[u8], code_hash: &[u8], @@ -662,24 +663,26 @@ pub fn random(subject: &[u8], output: &mut &mut [u8]) { #[cfg(feature = "ink-debug")] /// Call `seal_debug_message` with the supplied UTF-8 encoded message. /// -/// If debug message recording is disabled in the contracts pallet, the first call will -/// return a `LoggingDisabled` error, and further calls will be a no-op to avoid the cost -/// of calling into the supervisor. +/// If debug message recording is disabled in the contracts pallet, the first +/// call will return a `LoggingDisabled` error, and further calls will be a +/// no-op to avoid the cost of calling into the supervisor. /// /// # Note /// /// This depends on the `seal_debug_message` interface which requires the -/// `"pallet-contracts/unstable-interface"` feature to be enabled in the target runtime. +/// `"pallet-contracts/unstable-interface"` feature to be enabled in the target +/// runtime. pub fn debug_message(message: &str) { static mut DEBUG_ENABLED: bool = false; static mut FIRST_RUN: bool = true; // SAFETY: safe because executing in a single threaded context - // We need those two variables in order to make sure that the assignment is performed - // in the "logging enabled" case. This is because during RPC execution logging might - // be enabled while it is disabled during the actual execution as part of a transaction. - // The gas estimation takes place during RPC execution. We want to overestimate instead - // of underestimate gas usage. Otherwise using this estimate could lead to a out of gas error. + // We need those two variables in order to make sure that the assignment is + // performed in the "logging enabled" case. This is because during RPC + // execution logging might be enabled while it is disabled during the actual + // execution as part of a transaction. The gas estimation takes place during + // RPC execution. We want to overestimate instead of underestimate gas + // usage. Otherwise using this estimate could lead to a out of gas error. if unsafe { DEBUG_ENABLED || FIRST_RUN } { let bytes = message.as_bytes(); let ret_code = unsafe { diff --git a/crates/env/src/engine/on_chain/impls.rs b/crates/env/src/engine/on_chain/impls.rs index fa8f4804d39..601729f563e 100644 --- a/crates/env/src/engine/on_chain/impls.rs +++ b/crates/env/src/engine/on_chain/impls.rs @@ -172,7 +172,8 @@ where } impl EnvInstance { - /// Returns a new scoped buffer for the entire scope of the static 16 kB buffer. + /// Returns a new scoped buffer for the entire scope of the static 16 kB + /// buffer. fn scoped_buffer(&mut self) -> ScopedBuffer { ScopedBuffer::from(&mut self.buffer[..]) } @@ -181,7 +182,8 @@ impl EnvInstance { /// /// # Note /// - /// This skips the potentially costly decoding step that is often equivalent to a `memcpy`. + /// This skips the potentially costly decoding step that is often equivalent + /// to a `memcpy`. fn get_property_inplace(&mut self, ext_fn: fn(output: &mut &mut [u8])) -> T where T: Default + AsMut<[u8]>, @@ -191,11 +193,13 @@ impl EnvInstance { result } - /// Returns the contract property value from its little-endian representation. + /// Returns the contract property value from its little-endian + /// representation. /// /// # Note /// - /// This skips the potentially costly decoding step that is often equivalent to a `memcpy`. + /// This skips the potentially costly decoding step that is often equivalent + /// to a `memcpy`. fn get_property_little_endian(&mut self, ext_fn: fn(output: &mut &mut [u8])) -> T where T: FromLittleEndian, diff --git a/crates/env/src/error.rs b/crates/env/src/error.rs index a6b9be65de7..b3c7a7c8d77 100644 --- a/crates/env/src/error.rs +++ b/crates/env/src/error.rs @@ -35,21 +35,25 @@ pub enum Error { /// below the subsistence threshold. BelowSubsistenceThreshold, /// Transfer failed for other not further specified reason. Most probably - /// reserved or locked balance of the sender that was preventing the transfer. + /// reserved or locked balance of the sender that was preventing the + /// transfer. TransferFailed, - /// The newly created contract is below the subsistence threshold after executing - /// its constructor so no usable contract instance will be created. + /// The newly created contract is below the subsistence threshold after + /// executing its constructor so no usable contract instance will be + /// created. NewContractNotFunded, /// No code could be found at the supplied code hash. CodeNotFound, - /// The account that was called is either no contract (e.g. user account) or is a tombstone. + /// The account that was called is either no contract (e.g. user account) or + /// is a tombstone. NotCallable, /// An unknown error has occurred. Unknown, /// The call to `seal_debug_message` had no effect because debug message /// recording was disabled. LoggingDisabled, - /// ECDSA pubkey recovery failed. Most probably wrong recovery id or signature. + /// ECDSA pubkey recovery failed. Most probably wrong recovery id or + /// signature. EcdsaRecoverFailed, } diff --git a/crates/env/src/lib.rs b/crates/env/src/lib.rs index 60cbd60335c..e07543856e9 100644 --- a/crates/env/src/lib.rs +++ b/crates/env/src/lib.rs @@ -47,12 +47,13 @@ #[allow(unused_variables)] #[panic_handler] fn panic(info: &core::panic::PanicInfo) -> ! { - // This code gets removed in release builds where the macro will expand into nothing. + // This code gets removed in release builds where the macro will expand into + // nothing. debug_print!("{}\n", info); // We only use this operation if we are guaranteed to be in Wasm32 compilation. - // This is used in order to make any panic a direct abort avoiding Rust's general - // panic infrastructure. + // This is used in order to make any panic a direct abort avoiding Rust's + // general panic infrastructure. core::arch::wasm32::unreachable(); } diff --git a/crates/env/src/topics.rs b/crates/env/src/topics.rs index 0a10412fbc1..c05290dd669 100644 --- a/crates/env/src/topics.rs +++ b/crates/env/src/topics.rs @@ -67,9 +67,11 @@ pub mod state { /// The topic builder is uninitialized and needs to be provided with the /// expected number of topics that need to be constructed. pub enum Uninit {} - /// There are some remaining topics that need to be provided with some values. + /// There are some remaining topics that need to be provided with some + /// values. pub enum HasRemainingTopics {} - /// There are no more remaining topics and the topic builder shall be finalized. + /// There are no more remaining topics and the topic builder shall be + /// finalized. pub enum NoRemainingTopics {} } @@ -78,9 +80,11 @@ where E: Environment, B: TopicsBuilderBackend, { - /// Initializes the topics builder and informs it about how many topics it must expect to serialize. + /// Initializes the topics builder and informs it about how many topics it + /// must expect to serialize. /// - /// The number of expected topics is given implicitly by the `E` type parameter. + /// The number of expected topics is given implicitly by the `E` type + /// parameter. pub fn build( mut self, ) -> TopicsBuilder<::RemainingTopics, E, B> { @@ -101,8 +105,8 @@ where { /// Pushes another event topic to be serialized through the topics builder. /// - /// Returns a topics builder that expects one less event topic for serialization - /// than before the call. + /// Returns a topics builder that expects one less event topic for + /// serialization than before the call. pub fn push_topic( mut self, value: &T, @@ -125,9 +129,9 @@ where { /// Finalizes the topics builder. /// - /// No more event topics can be serialized afterwards, but the environment will be - /// able to extract the information collected by the topics builder in order to - /// emit the serialized event. + /// No more event topics can be serialized afterwards, but the environment + /// will be able to extract the information collected by the topics + /// builder in order to emit the serialized event. pub fn finish(self) -> >::Output where B: TopicsBuilderBackend, @@ -136,7 +140,8 @@ where } } -/// Indicates that there are some remaining topics left for expected serialization. +/// Indicates that there are some remaining topics left for expected +/// serialization. #[doc(hidden)] pub trait SomeRemainingTopics { /// The type state indicating the amount of the remaining topics afterwards. @@ -185,11 +190,14 @@ impl EventTopicsAmount for state::NoRemainingTopics { const AMOUNT: usize = 0; } -/// Implemented by event types to guide the event topic serialization using the topics builder. +/// Implemented by event types to guide the event topic serialization using the +/// topics builder. /// -/// Normally this trait should be implemented automatically via the ink! codegen. +/// Normally this trait should be implemented automatically via the ink! +/// codegen. pub trait Topics { - /// Type state indicating how many event topics are to be expected by the topics builder. + /// Type state indicating how many event topics are to be expected by the + /// topics builder. type RemainingTopics: EventTopicsAmount; /// Guides event topic serialization using the given topics builder. diff --git a/crates/env/src/types.rs b/crates/env/src/types.rs index fff2d3a8868..c687d7318fe 100644 --- a/crates/env/src/types.rs +++ b/crates/env/src/types.rs @@ -14,22 +14,23 @@ //! Types for the default environment. //! -//! These are simple mirrored types from the default substrate FRAME configuration. -//! Their interfaces and functionality might not be complete. +//! These are simple mirrored types from the default substrate FRAME +//! configuration. Their interfaces and functionality might not be complete. //! //! Users are required to provide their own type definitions and `Environment` -//! implementations in order to write ink! contracts for other chain configurations. +//! implementations in order to write ink! contracts for other chain +//! configurations. //! //! # Note //! -//! When authoring a contract, the concrete `Environment` are available via aliases -//! generated by the `lang` macro. Therefore all functionality of the concrete -//! types is accessible in the contract, not constrained by the required trait -//! bounds. +//! When authoring a contract, the concrete `Environment` are available via +//! aliases generated by the `lang` macro. Therefore all functionality of the +//! concrete types is accessible in the contract, not constrained by the +//! required trait bounds. //! -//! Outside the contract and its tests (e.g. in the off-chain environment), where -//! there is no knowledge of the concrete types, the functionality is restricted to -//! the trait bounds on the `Environment` trait types. +//! Outside the contract and its tests (e.g. in the off-chain environment), +//! where there is no knowledge of the concrete types, the functionality is +//! restricted to the trait bounds on the `Environment` trait types. use super::arithmetic::AtLeast32BitUnsigned; use core::{ @@ -104,7 +105,8 @@ impl FromLittleEndian for u128 { pub trait Environment { /// The maximum number of supported event topics provided by the runtime. /// - /// The value must match the maximum number of supported event topics of the used runtime. + /// The value must match the maximum number of supported event topics of the + /// used runtime. const MAX_EVENT_TOPICS: usize; /// The address type. @@ -162,8 +164,9 @@ pub trait Environment { /// The chain extension for the environment. /// - /// This is a type that is defined through the `#[ink::chain_extension]` procedural macro. - /// For more information about usage and definition click [this][chain_extension] link. + /// This is a type that is defined through the `#[ink::chain_extension]` + /// procedural macro. For more information about usage and definition + /// click [this][chain_extension] link. /// /// [chain_extension]: https://paritytech.github.io/ink/ink_lang/attr.chain_extension.html type ChainExtension; @@ -339,58 +342,69 @@ impl Clear for Hash { } } -/// Information needed for rent calculations that can be requested by a contract. +/// Information needed for rent calculations that can be requested by a +/// contract. #[derive(scale::Decode)] #[cfg_attr(test, derive(Debug, PartialEq))] pub struct RentParams { - /// The total balance of the contract. Includes the balance transferred from the caller. + /// The total balance of the contract. Includes the balance transferred from + /// the caller. pub total_balance: T::Balance, - /// The free balance of the contract, i.e. the portion of the contract's balance - /// that is not reserved. Includes the balance transferred from the caller. + /// The free balance of the contract, i.e. the portion of the contract's + /// balance that is not reserved. Includes the balance transferred from + /// the caller. pub free_balance: T::Balance, - /// Subsistence threshold is the extension of the minimum balance (aka existential deposit) - /// by the tombstone deposit, required for leaving a tombstone. + /// Subsistence threshold is the extension of the minimum balance (aka + /// existential deposit) by the tombstone deposit, required for leaving + /// a tombstone. /// - /// Rent or any contract initiated balance transfer mechanism cannot make the balance lower - /// than the subsistence threshold in order to guarantee that a tombstone is created. + /// Rent or any contract initiated balance transfer mechanism cannot make + /// the balance lower than the subsistence threshold in order to + /// guarantee that a tombstone is created. /// - /// The only way to completely kill a contract without a tombstone is calling `seal_terminate`. + /// The only way to completely kill a contract without a tombstone is + /// calling `seal_terminate`. pub subsistence_threshold: T::Balance, /// The balance every contract needs to deposit to stay alive indefinitely. /// - /// This is different from the tombstone deposit because this only needs to be - /// deposited while the contract is alive. Costs for additional storage are added to - /// this base cost. + /// This is different from the tombstone deposit because this only needs to + /// be deposited while the contract is alive. Costs for additional + /// storage are added to this base cost. /// - /// This is a simple way to ensure that contracts with empty storage eventually get deleted by - /// making them pay rent. This creates an incentive to remove them early in order to save rent. + /// This is a simple way to ensure that contracts with empty storage + /// eventually get deleted by making them pay rent. This creates an + /// incentive to remove them early in order to save rent. pub deposit_per_contract: T::Balance, - /// The balance a contract needs to deposit per storage byte to stay alive indefinitely. + /// The balance a contract needs to deposit per storage byte to stay alive + /// indefinitely. /// - /// Let's suppose the deposit is 1,000 BU (balance units)/byte and the rent is 1 BU/byte/day, - /// then a contract with 1,000,000 BU that uses 1,000 bytes of storage would pay no rent. - /// But if the balance reduced to 500,000 BU and the storage stayed the same at 1,000, - /// then it would pay 500 BU/day. + /// Let's suppose the deposit is 1,000 BU (balance units)/byte and the rent + /// is 1 BU/byte/day, then a contract with 1,000,000 BU that uses 1,000 + /// bytes of storage would pay no rent. But if the balance reduced to + /// 500,000 BU and the storage stayed the same at 1,000, then it would + /// pay 500 BU/day. pub deposit_per_storage_byte: T::Balance, - /// The balance a contract needs to deposit per storage item to stay alive indefinitely. + /// The balance a contract needs to deposit per storage item to stay alive + /// indefinitely. /// /// It works as [`Self::deposit_per_storage_byte`] but for storage items. pub deposit_per_storage_item: T::Balance, - /// The contract's rent allowance, the rent mechanism cannot consume more than this. + /// The contract's rent allowance, the rent mechanism cannot consume more + /// than this. pub rent_allowance: T::Balance, /// The fraction of the deposit costs that should be used as rent per block. /// - /// When a contract does not have enough balance deposited to stay alive indefinitely - /// it needs to pay per block for the storage it consumes that is not covered by the - /// deposit. This determines how high this rent payment is per block as a fraction - /// of the deposit costs. + /// When a contract does not have enough balance deposited to stay alive + /// indefinitely it needs to pay per block for the storage it consumes + /// that is not covered by the deposit. This determines how high this + /// rent payment is per block as a fraction of the deposit costs. pub rent_fraction: T::RentFraction, /// The total number of bytes used by this contract. @@ -420,22 +434,26 @@ pub struct RentParams { #[derive(scale::Decode)] #[cfg_attr(test, derive(Debug, PartialEq))] pub struct RentStatus { - /// Required deposit assuming that this contract is the only user of its code. + /// Required deposit assuming that this contract is the only user of its + /// code. pub max_deposit: T::Balance, /// Required deposit assuming the code's current `refcount`. pub current_deposit: T::Balance, - /// Required deposit assuming the specified `refcount` (`None` if `0` is supplied). + /// Required deposit assuming the specified `refcount` (`None` if `0` is + /// supplied). pub custom_refcount_deposit: Option, - /// Rent that is paid assuming that the contract is the only user of its code. + /// Rent that is paid assuming that the contract is the only user of its + /// code. pub max_rent: T::Balance, /// Rent that is paid given the code's current refcount. pub current_rent: T::Balance, - /// Rent that is paid assuming the specified refcount (`None` if `0` is supplied). + /// Rent that is paid assuming the specified refcount (`None` if `0` is + /// supplied). pub custom_refcount_rent: Option, /// Reserved for backwards compatible changes to this data structure. diff --git a/crates/eth_compatibility/src/lib.rs b/crates/eth_compatibility/src/lib.rs index 827384ed3b2..dd7103ce8d5 100644 --- a/crates/eth_compatibility/src/lib.rs +++ b/crates/eth_compatibility/src/lib.rs @@ -25,8 +25,9 @@ pub struct ECDSAPublicKey([u8; 33]); impl Default for ECDSAPublicKey { fn default() -> Self { - // Default is not implemented for [u8; 33], so we can't derive it for ECDSAPublicKey - // But clippy thinks that it is possible. So it is workaround for clippy. + // Default is not implemented for [u8; 33], so we can't derive it for + // ECDSAPublicKey But clippy thinks that it is possible. So it is + // workaround for clippy. let empty = [0; 33]; Self { 0: empty } } @@ -113,8 +114,9 @@ impl ECDSAPublicKey { result } - /// Returns the default Substrate's `AccountId` from the ECDSA compressed public key. - /// It hashes the compressed public key with the blake2b256 algorithm like in substrate. + /// Returns the default Substrate's `AccountId` from the ECDSA compressed + /// public key. It hashes the compressed public key with the blake2b256 + /// algorithm like in substrate. /// /// # Example /// diff --git a/crates/lang/codegen/src/enforced_error.rs b/crates/lang/codegen/src/enforced_error.rs index ea92e2b8a51..d628dfde904 100644 --- a/crates/lang/codegen/src/enforced_error.rs +++ b/crates/lang/codegen/src/enforced_error.rs @@ -24,9 +24,10 @@ use quote::format_ident; /// when building a contract and fails if it finds markers. #[derive(scale::Encode, scale::Decode)] pub enum EnforcedErrors { - /// The below error represents calling a `&mut self` message in a context that - /// only allows for `&self` messages. This may happen under certain circumstances - /// when ink! trait implementations are involved with long-hand calling notation. + /// The below error represents calling a `&mut self` message in a context + /// that only allows for `&self` messages. This may happen under certain + /// circumstances when ink! trait implementations are involved with + /// long-hand calling notation. #[codec(index = 1)] CannotCallTraitMessage { /// The trait that defines the called message. diff --git a/crates/lang/codegen/src/generator/arg_list.rs b/crates/lang/codegen/src/generator/arg_list.rs index c239f4b2e62..300e53994e9 100644 --- a/crates/lang/codegen/src/generator/arg_list.rs +++ b/crates/lang/codegen/src/generator/arg_list.rs @@ -32,8 +32,8 @@ pub fn output_ident(message_name: &syn::Ident) -> syn::Ident { /// /// # Note /// -/// This returns `__ink_binding_N` for every message input where `N` is the number -/// of the input from first to last. +/// This returns `__ink_binding_N` for every message input where `N` is the +/// number of the input from first to last. pub fn input_bindings(inputs: ir::InputsIter) -> Vec { inputs .enumerate() @@ -69,7 +69,8 @@ pub fn input_bindings_tuple(inputs: ir::InputsIter) -> TokenStream2 { } } -/// Builds up the `ink_env::call::utils::ArgumentList` type structure for the given types. +/// Builds up the `ink_env::call::utils::ArgumentList` type structure for the +/// given types. pub fn generate_argument_list<'b, Args>(args: Args) -> TokenStream2 where Args: IntoIterator, @@ -87,12 +88,14 @@ where ) } -/// Generates code to uniquely identify a trait by its unique ID given only its identifier. +/// Generates code to uniquely identify a trait by its unique ID given only its +/// identifier. /// /// # Note /// -/// As with all Rust macros identifiers can shadow each other so the given identifier -/// needs to be valid for the scope in which the returned code is generated. +/// As with all Rust macros identifiers can shadow each other so the given +/// identifier needs to be valid for the scope in which the returned code is +/// generated. pub fn generate_reference_to_trait_info( span: Span, trait_path: &syn::Path, diff --git a/crates/lang/codegen/src/generator/as_dependency/call_builder.rs b/crates/lang/codegen/src/generator/as_dependency/call_builder.rs index 94cc3f9c9f9..1ff7c72f770 100644 --- a/crates/lang/codegen/src/generator/as_dependency/call_builder.rs +++ b/crates/lang/codegen/src/generator/as_dependency/call_builder.rs @@ -30,13 +30,14 @@ use syn::spanned::Spanned as _; /// /// The call builder is the entity that builds up calls for calling of other /// smart contract on-chain in a type safe way. -/// It implements all ink! traits that the associated ink! smart contract implements -/// so that their underlying implementation directly calls the respective ink! -/// trait implementation on-chain. +/// It implements all ink! traits that the associated ink! smart contract +/// implements so that their underlying implementation directly calls the +/// respective ink! trait implementation on-chain. /// /// The ink! call builder of a smart contract is directly used by the storage /// type of the smart contract itself as well by other entities that use the -/// smart contract via long-hand calling notation to incrementally build up calls. +/// smart contract via long-hand calling notation to incrementally build up +/// calls. #[derive(From)] pub struct CallBuilder<'a> { contract: &'a ir::Contract, @@ -137,13 +138,14 @@ impl CallBuilder<'_> { ) } - /// Generate the `TraitCallForwarder` trait implementations for the call builder - /// for every ink! trait implemented by the associated ink! smart contract. + /// Generate the `TraitCallForwarder` trait implementations for the call + /// builder for every ink! trait implemented by the associated ink! + /// smart contract. /// - /// These call forwarder trait implementations are used to dispatch to the global - /// call builder for the respective ink! trait definition that is being called. - /// The call builder only forwards the actual calls to those global call builders - /// and does not have its own calling logic. + /// These call forwarder trait implementations are used to dispatch to the + /// global call builder for the respective ink! trait definition that is + /// being called. The call builder only forwards the actual calls to + /// those global call builders and does not have its own calling logic. fn generate_call_forwarder_impls(&self) -> TokenStream2 { self.contract .module() @@ -157,8 +159,9 @@ impl CallBuilder<'_> { .collect() } - /// Generates code required by the ink! call builder of an ink! smart contract - /// for a single ink! trait definition that the contract implements. + /// Generates code required by the ink! call builder of an ink! smart + /// contract for a single ink! trait definition that the contract + /// implements. fn generate_code_for_trait_impl( &self, trait_path: &syn::Path, @@ -173,8 +176,8 @@ impl CallBuilder<'_> { } } - /// Generates code for a single ink! trait implementation to forward calls for - /// the associated ink! smart contract call builder. + /// Generates code for a single ink! trait implementation to forward calls + /// for the associated ink! smart contract call builder. fn generate_call_forwarder_for_trait_impl( &self, trait_path: &syn::Path, @@ -233,7 +236,8 @@ impl CallBuilder<'_> { ) } - /// Generates the actual ink! trait implementation for the generated call builder. + /// Generates the actual ink! trait implementation for the generated call + /// builder. fn generate_ink_trait_impl( &self, trait_path: &syn::Path, @@ -301,7 +305,8 @@ impl CallBuilder<'_> { ) } - /// Generate call builder code for all ink! inherent ink! implementation blocks. + /// Generate call builder code for all ink! inherent ink! implementation + /// blocks. /// /// # Note /// @@ -320,13 +325,15 @@ impl CallBuilder<'_> { .collect() } - /// Generate call builder code for a single inherent ink! implementation block. + /// Generate call builder code for a single inherent ink! implementation + /// block. /// /// # Note /// - /// Unlike as with ink! trait implementation blocks we do not have to generate - /// associate `*Output` types, ink! trait validating implementation blocks or - /// trait forwarder implementations. Instead we build the calls directly. + /// Unlike as with ink! trait implementation blocks we do not have to + /// generate associate `*Output` types, ink! trait validating + /// implementation blocks or trait forwarder implementations. Instead we + /// build the calls directly. fn generate_call_builder_inherent_impl( &self, impl_block: &ir::ItemImpl, diff --git a/crates/lang/codegen/src/generator/as_dependency/contract_ref.rs b/crates/lang/codegen/src/generator/as_dependency/contract_ref.rs index d9c724f716d..180a0c75218 100644 --- a/crates/lang/codegen/src/generator/as_dependency/contract_ref.rs +++ b/crates/lang/codegen/src/generator/as_dependency/contract_ref.rs @@ -32,13 +32,14 @@ use syn::spanned::Spanned as _; /// /// The call builder is the entity that builds up calls for calling of other /// smart contract on-chain in a type safe way. -/// It implements all ink! traits that the associated ink! smart contract implements -/// so that their underlying implementation directly calls the respective ink! -/// trait implementation on-chain. +/// It implements all ink! traits that the associated ink! smart contract +/// implements so that their underlying implementation directly calls the +/// respective ink! trait implementation on-chain. /// /// The ink! call builder of a smart contract is directly used by the storage /// type of the smart contract itself as well by other entities that use the -/// smart contract via long-hand calling notation to incrementally build up calls. +/// smart contract via long-hand calling notation to incrementally build up +/// calls. #[derive(From)] pub struct ContractRef<'a> { contract: &'a ir::Contract, @@ -71,8 +72,8 @@ impl ContractRef<'_> { /// /// The generated struct is the type onto which everything is implemented. /// It is also the type that is going to be used by other smart contract - /// dynamically depending on the smart contract. It mirrors the smart contract - /// API but is just a typed thin-wrapper around an `AccountId`. + /// dynamically depending on the smart contract. It mirrors the smart + /// contract API but is just a typed thin-wrapper around an `AccountId`. fn generate_struct(&self) -> TokenStream2 { let span = self.contract.module().storage().span(); let doc_attrs = self @@ -147,7 +148,8 @@ impl ContractRef<'_> { ) } - /// Generates the `CallBuilder` trait implementation for the contract reference. + /// Generates the `CallBuilder` trait implementation for the contract + /// reference. /// /// This creates the bridge between the ink! smart contract type and the /// associated call builder. @@ -174,12 +176,13 @@ impl ContractRef<'_> { ) } - /// Generates the code for all ink! trait implementations of the contract itself. + /// Generates the code for all ink! trait implementations of the contract + /// itself. /// /// # Note /// - /// The generated implementations must live outside of an artificial `const` block - /// in order to properly show their documentation using `rustdoc`. + /// The generated implementations must live outside of an artificial `const` + /// block in order to properly show their documentation using `rustdoc`. fn generate_contract_trait_impls(&self) -> TokenStream2 { self.contract .module() @@ -193,10 +196,12 @@ impl ContractRef<'_> { .collect() } - /// Generates the code for a single ink! trait implementation of the contract itself. + /// Generates the code for a single ink! trait implementation of the + /// contract itself. /// - /// The generated implementation mainly forwards the calls to the previously generated - /// associated call builder that implements each respective ink! trait. + /// The generated implementation mainly forwards the calls to the previously + /// generated associated call builder that implements each respective + /// ink! trait. fn generate_contract_trait_impl( &self, trait_path: &syn::Path, @@ -218,8 +223,8 @@ impl ContractRef<'_> { ) } - /// Generates the code for all messages of a single ink! trait implementation of - /// the ink! smart contract. + /// Generates the code for all messages of a single ink! trait + /// implementation of the ink! smart contract. fn generate_contract_trait_impl_messages( &self, trait_path: &syn::Path, @@ -233,8 +238,8 @@ impl ContractRef<'_> { .collect() } - /// Generates the code for a single message of a single ink! trait implementation - /// that is implemented by the ink! smart contract. + /// Generates the code for a single message of a single ink! trait + /// implementation that is implemented by the ink! smart contract. fn generate_contract_trait_impl_for_message( &self, trait_path: &syn::Path, @@ -275,12 +280,13 @@ impl ContractRef<'_> { ) } - /// Generates the code for all ink! inherent implementations of the contract itself. + /// Generates the code for all ink! inherent implementations of the contract + /// itself. /// /// # Note /// - /// The generated implementations must live outside of an artificial `const` block - /// in order to properly show their documentation using `rustdoc`. + /// The generated implementations must live outside of an artificial `const` + /// block in order to properly show their documentation using `rustdoc`. fn generate_contract_inherent_impls(&self) -> TokenStream2 { self.contract .module() @@ -295,12 +301,14 @@ impl ContractRef<'_> { .collect() } - /// Generates the code for a single ink! inherent implementation of the contract itself. + /// Generates the code for a single ink! inherent implementation of the + /// contract itself. /// /// # Note /// - /// This produces the short-hand calling notation for the inherent contract implementation. - /// The generated code simply forwards its calling logic to the associated call builder. + /// This produces the short-hand calling notation for the inherent contract + /// implementation. The generated code simply forwards its calling logic + /// to the associated call builder. fn generate_contract_inherent_impl(&self, impl_block: &ir::ItemImpl) -> TokenStream2 { let span = impl_block.span(); let attrs = impl_block.attrs(); @@ -320,12 +328,14 @@ impl ContractRef<'_> { ) } - /// Generates the code for a single ink! inherent message of the contract itself. + /// Generates the code for a single ink! inherent message of the contract + /// itself. /// /// # Note /// - /// This produces the short-hand calling notation for the inherent contract message. - /// The generated code simply forwards its calling logic to the associated call builder. + /// This produces the short-hand calling notation for the inherent contract + /// message. The generated code simply forwards its calling logic to the + /// associated call builder. fn generate_contract_inherent_impl_for_message( &self, message: ir::CallableWithSelector, @@ -363,13 +373,15 @@ impl ContractRef<'_> { ) } - /// Generates the code for a single ink! inherent constructor of the contract itself. + /// Generates the code for a single ink! inherent constructor of the + /// contract itself. /// /// # Note /// - /// Unlike with ink! messages this does not forward to the call builder since constructor - /// calls in ink! do not have a short-hand notation and therefore this implements the - /// long-hand calling notation code directly. + /// Unlike with ink! messages this does not forward to the call builder + /// since constructor calls in ink! do not have a short-hand notation + /// and therefore this implements the long-hand calling notation code + /// directly. fn generate_contract_inherent_impl_for_constructor( &self, constructor: ir::CallableWithSelector, diff --git a/crates/lang/codegen/src/generator/as_dependency/mod.rs b/crates/lang/codegen/src/generator/as_dependency/mod.rs index 4a6acacadbe..d8ee757665c 100644 --- a/crates/lang/codegen/src/generator/as_dependency/mod.rs +++ b/crates/lang/codegen/src/generator/as_dependency/mod.rs @@ -27,7 +27,8 @@ use derive_more::From; use proc_macro2::TokenStream as TokenStream2; use quote::quote; -/// Generates `#[cfg(..)]` code to guard against compilation under `ink-as-dependency`. +/// Generates `#[cfg(..)]` code to guard against compilation under +/// `ink-as-dependency`. #[derive(From)] pub struct NotAsDependencyCfg<'a> { contract: &'a ir::Contract, @@ -44,14 +45,17 @@ impl GenerateCode for NotAsDependencyCfg<'_> { } } -/// Generates `#[cfg(..)]` code to only allow compilation when `ink-as-dependency` is enabled. +/// Generates `#[cfg(..)]` code to only allow compilation when +/// `ink-as-dependency` is enabled. /// /// The `ink-as-dependency` can be enabled mainly by 2 different ways: /// /// - Enabling it in the associated `Cargo.toml` as crate feature. /// - Note: This can be enabled by dependencies of an ink! smart contract. -/// - Enabling it in the configuration header with `#[ink::contract(compile_as_dependency = true)]`. -/// - If set here the contract will always be compiled as it is was a dependency. +/// - Enabling it in the configuration header with +/// `#[ink::contract(compile_as_dependency = true)]`. +/// - If set here the contract will always be compiled as it is was a +/// dependency. #[derive(From)] pub struct OnlyAsDependencyCfg<'a> { contract: &'a ir::Contract, diff --git a/crates/lang/codegen/src/generator/dispatch.rs b/crates/lang/codegen/src/generator/dispatch.rs index 568e9eb1d45..944c36862d8 100644 --- a/crates/lang/codegen/src/generator/dispatch.rs +++ b/crates/lang/codegen/src/generator/dispatch.rs @@ -36,11 +36,11 @@ use syn::spanned::Spanned as _; /// This code efficiently selects the dispatched ink! constructor or message /// by inspecting the first four bytes (selector) of the given input bytes. /// -/// As this happens on every contract execution this code must be highly optimized. -/// For that purpose a so-called dispatch enum is being generated that has a -/// specialized `scale::Decode` implementation taking the first four bytes of -/// the input stream in order to identify the enum variant that it is going to -/// produce out of the rest of the input buffer. +/// As this happens on every contract execution this code must be highly +/// optimized. For that purpose a so-called dispatch enum is being generated +/// that has a specialized `scale::Decode` implementation taking the first four +/// bytes of the input stream in order to identify the enum variant that it is +/// going to produce out of the rest of the input buffer. /// /// The rest of the input buffer is then automatically decoded directly into the /// expected input types of the respective ink! constructor or message. @@ -92,7 +92,8 @@ impl GenerateCode for Dispatch<'_> { } impl Dispatch<'_> { - /// Returns the number of dispatchable ink! constructors of the ink! smart contract. + /// Returns the number of dispatchable ink! constructors of the ink! smart + /// contract. fn query_amount_constructors(&self) -> usize { self.contract .module() @@ -102,7 +103,8 @@ impl Dispatch<'_> { .count() } - /// Returns the number of dispatchable ink! messages of the ink! smart contract. + /// Returns the number of dispatchable ink! messages of the ink! smart + /// contract. /// /// This includes inherent ink! messages as well as trait ink! messages. fn query_amount_messages(&self) -> usize { @@ -114,10 +116,12 @@ impl Dispatch<'_> { .count() } - /// Generates code for the [`ink_lang::ContractDispatchables`] trait implementation. + /// Generates code for the [`ink_lang::ContractDispatchables`] trait + /// implementation. /// /// This trait implementation stores information of how many dispatchable - /// ink! messages and ink! constructors there are for the ink! smart contract. + /// ink! messages and ink! constructors there are for the ink! smart + /// contract. fn generate_contract_amount_dispatchables_trait_impl(&self) -> TokenStream2 { let span = self.contract.module().storage().span(); let storage_ident = self.contract.module().storage().ident(); @@ -131,7 +135,8 @@ impl Dispatch<'_> { ) } - /// Generates code for the [`ink_lang::ContractDispatchableMessages`] trait implementation. + /// Generates code for the [`ink_lang::ContractDispatchableMessages`] trait + /// implementation. /// /// This trait implementation stores the selector ID of each dispatchable /// ink! messages of the ink! smart contract. @@ -199,7 +204,8 @@ impl Dispatch<'_> { ) } - /// Generates code for the [`ink_lang::ContractDispatchableConstructors`] trait implementation. + /// Generates code for the [`ink_lang::ContractDispatchableConstructors`] + /// trait implementation. /// /// This trait implementation stores the selector ID of each dispatchable /// ink! constructor of the ink! smart contract. @@ -238,10 +244,11 @@ impl Dispatch<'_> { ) } - /// Generate code for the [`ink_lang::DispatchableConstructorInfo`] trait implementations. + /// Generate code for the [`ink_lang::DispatchableConstructorInfo`] trait + /// implementations. /// - /// These trait implementations store relevant dispatch information for every - /// dispatchable ink! constructor of the ink! smart contract. + /// These trait implementations store relevant dispatch information for + /// every dispatchable ink! constructor of the ink! smart contract. fn generate_dispatchable_constructor_infos(&self) -> TokenStream2 { let span = self.contract.module().storage().span(); let storage_ident = self.contract.module().storage().ident(); @@ -277,10 +284,11 @@ impl Dispatch<'_> { ) } - /// Generate code for the [`ink_lang::DispatchableConstructorInfo`] trait implementations. + /// Generate code for the [`ink_lang::DispatchableConstructorInfo`] trait + /// implementations. /// - /// These trait implementations store relevant dispatch information for every - /// dispatchable ink! constructor of the ink! smart contract. + /// These trait implementations store relevant dispatch information for + /// every dispatchable ink! constructor of the ink! smart contract. fn generate_dispatchable_message_infos(&self) -> TokenStream2 { let span = self.contract.module().storage().span(); let storage_ident = self.contract.module().storage().ident(); @@ -432,10 +440,12 @@ impl Dispatch<'_> { ) } - /// Generates code for the ink! constructor decoder type of the ink! smart contract. + /// Generates code for the ink! constructor decoder type of the ink! smart + /// contract. /// - /// This type can be used in order to decode the input bytes received by a call to `deploy` - /// into one of the available dispatchable ink! constructors and their arguments. + /// This type can be used in order to decode the input bytes received by a + /// call to `deploy` into one of the available dispatchable ink! + /// constructors and their arguments. fn generate_constructor_decoder_type( &self, constructor_spans: &[proc_macro2::Span], @@ -569,10 +579,12 @@ impl Dispatch<'_> { ) } - /// Generates code for the ink! message decoder type of the ink! smart contract. + /// Generates code for the ink! message decoder type of the ink! smart + /// contract. /// - /// This type can be used in order to decode the input bytes received by a call to `call` - /// into one of the available dispatchable ink! messages and their arguments. + /// This type can be used in order to decode the input bytes received by a + /// call to `call` into one of the available dispatchable ink! messages + /// and their arguments. fn generate_message_decoder_type( &self, message_spans: &[proc_macro2::Span], @@ -739,11 +751,12 @@ impl Dispatch<'_> { ) } - /// Generates code to express if any dispatchable ink! message accepts payment. + /// Generates code to express if any dispatchable ink! message accepts + /// payment. /// - /// This information can be used to speed-up dispatch since denying of payment - /// can be generalized to work before dispatch happens if none of the ink! messages - /// accept payment anyways. + /// This information can be used to speed-up dispatch since denying of + /// payment can be generalized to work before dispatch happens if none + /// of the ink! messages accept payment anyways. fn any_message_accepts_payment_expr( &self, message_spans: &[proc_macro2::Span], diff --git a/crates/lang/codegen/src/generator/events.rs b/crates/lang/codegen/src/generator/events.rs index 3401da156bb..d9694473351 100644 --- a/crates/lang/codegen/src/generator/events.rs +++ b/crates/lang/codegen/src/generator/events.rs @@ -53,8 +53,9 @@ impl GenerateCode for Events<'_> { } impl<'a> Events<'a> { - /// Used to allow emitting user defined events directly instead of converting - /// them first into the automatically generated base trait of the contract. + /// Used to allow emitting user defined events directly instead of + /// converting them first into the automatically generated base trait of + /// the contract. fn generate_emit_event_trait_impl(&self) -> TokenStream2 { let storage_ident = &self.contract.module().storage().ident(); quote! { @@ -75,8 +76,9 @@ impl<'a> Events<'a> { } /// Generates the base event enum that comprises all user defined events. - /// All emitted events are converted into a variant of this enum before being - /// serialized and emitted to apply their unique event discriminant (ID). + /// All emitted events are converted into a variant of this enum before + /// being serialized and emitted to apply their unique event + /// discriminant (ID). fn generate_event_base(&self) -> TokenStream2 { let storage_ident = &self.contract.module().storage().ident(); let event_idents = self @@ -163,7 +165,8 @@ impl<'a> Events<'a> { ) } - /// Generates the guard code that protects against having too many topics defined on an ink! event. + /// Generates the guard code that protects against having too many topics + /// defined on an ink! event. fn generate_topic_guards(&'a self) -> impl Iterator + 'a { self.contract.module().events().map(move |event| { let span = event.span(); @@ -174,7 +177,8 @@ impl<'a> Events<'a> { }) } - /// Generates the `Topics` trait implementations for the user defined events. + /// Generates the `Topics` trait implementations for the user defined + /// events. fn generate_topics_impls(&'a self) -> impl Iterator + 'a { let contract_ident = self.contract.module().storage().ident(); self.contract.module().events().map(move |event| { diff --git a/crates/lang/codegen/src/generator/item_impls.rs b/crates/lang/codegen/src/generator/item_impls.rs index 28fe7fb6cc7..65838c581b6 100644 --- a/crates/lang/codegen/src/generator/item_impls.rs +++ b/crates/lang/codegen/src/generator/item_impls.rs @@ -119,7 +119,8 @@ impl ItemImpls<'_> { ) } - /// Generates code to assert that ink! input and output types meet certain properties. + /// Generates code to assert that ink! input and output types meet certain + /// properties. fn generate_input_output_guards(&self) -> TokenStream2 { let storage_span = self.contract.module().storage().span(); let constructor_input_guards = self @@ -181,7 +182,8 @@ impl ItemImpls<'_> { ) } - /// Generates the code for the given ink! message within a trait implementation block. + /// Generates the code for the given ink! message within a trait + /// implementation block. fn generate_trait_message(message: &ir::Message) -> TokenStream2 { let span = message.span(); let attrs = message.attrs(); @@ -227,7 +229,8 @@ impl ItemImpls<'_> { ) } - /// Generates the code for the given ink! constructor within an inherent implementation block. + /// Generates the code for the given ink! constructor within an inherent + /// implementation block. fn generate_inherent_constructor(constructor: &ir::Constructor) -> TokenStream2 { let span = constructor.span(); let attrs = constructor.attrs(); @@ -243,7 +246,8 @@ impl ItemImpls<'_> { ) } - /// Generates the code for the given ink! message within an inherent implementation block. + /// Generates the code for the given ink! message within an inherent + /// implementation block. fn generate_inherent_message(message: &ir::Message) -> TokenStream2 { let span = message.span(); let attrs = message.attrs(); @@ -288,8 +292,8 @@ impl ItemImpls<'_> { ) } - /// Generates code to guard against ink! implementations that have not been implemented - /// for the ink! storage struct. + /// Generates code to guard against ink! implementations that have not been + /// implemented for the ink! storage struct. fn generate_item_impl_self_ty_guard(&self, item_impl: &ir::ItemImpl) -> TokenStream2 { let self_ty = item_impl.self_type(); let span = self_ty.span(); diff --git a/crates/lang/codegen/src/generator/metadata.rs b/crates/lang/codegen/src/generator/metadata.rs index 81c3a94e8aa..1cf2dd446ae 100644 --- a/crates/lang/codegen/src/generator/metadata.rs +++ b/crates/lang/codegen/src/generator/metadata.rs @@ -194,7 +194,8 @@ impl Metadata<'_> { messages } - /// Generates the ink! metadata for all inherent ink! smart contract messages. + /// Generates the ink! metadata for all inherent ink! smart contract + /// messages. fn generate_inherent_messages(&self) -> Vec { self.contract .module() @@ -235,7 +236,8 @@ impl Metadata<'_> { .collect() } - /// Generates the ink! metadata for all inherent ink! smart contract messages. + /// Generates the ink! metadata for all inherent ink! smart contract + /// messages. fn generate_trait_messages(&self) -> Vec { let storage_ident = self.contract.module().storage().ident(); self.contract @@ -333,7 +335,8 @@ impl Metadata<'_> { }) } - /// Generate ink! metadata for a single argument of an ink! event definition. + /// Generate ink! metadata for a single argument of an ink! event + /// definition. fn generate_event_args(event: &ir::Event) -> impl Iterator + '_ { event.fields().map(|event_field| { let span = event_field.span(); diff --git a/crates/lang/codegen/src/generator/storage.rs b/crates/lang/codegen/src/generator/storage.rs index c68e29824a4..3e52d597e9f 100644 --- a/crates/lang/codegen/src/generator/storage.rs +++ b/crates/lang/codegen/src/generator/storage.rs @@ -21,7 +21,8 @@ use quote::{ }; use syn::spanned::Spanned as _; -/// Generator to create the ink! storage struct and important trait implementations. +/// Generator to create the ink! storage struct and important trait +/// implementations. #[derive(From)] pub struct Storage<'a> { contract: &'a ir::Contract, @@ -35,7 +36,8 @@ impl GenerateCode for Storage<'_> { let storage_struct = self.generate_storage_struct(); let use_emit_event = self.contract.module().events().next().is_some().then(|| { - // Required to allow for `self.env().emit_event(..)` in messages and constructors. + // Required to allow for `self.env().emit_event(..)` in messages and + // constructors. quote! { use ::ink_lang::codegen::EmitEvent as _; } }); quote_spanned!(storage_span => diff --git a/crates/lang/codegen/src/generator/trait_def/call_builder.rs b/crates/lang/codegen/src/generator/trait_def/call_builder.rs index 11d484ccc72..ca915578e80 100644 --- a/crates/lang/codegen/src/generator/trait_def/call_builder.rs +++ b/crates/lang/codegen/src/generator/trait_def/call_builder.rs @@ -121,12 +121,14 @@ impl CallBuilder<'_> { ) } - /// Generates the `StorageLayout` trait implementation for the account wrapper. + /// Generates the `StorageLayout` trait implementation for the account + /// wrapper. /// /// # Note /// - /// Due to the generic parameter `E` and Rust's default rules for derive generated - /// trait bounds it is not recommended to derive the `StorageLayout` trait implementation. + /// Due to the generic parameter `E` and Rust's default rules for derive + /// generated trait bounds it is not recommended to derive the + /// `StorageLayout` trait implementation. fn generate_storage_layout_impl(&self) -> TokenStream2 { let span = self.span(); let call_builder_ident = self.ident(); @@ -155,12 +157,14 @@ impl CallBuilder<'_> { ) } - /// Generates the `SpreadLayout` trait implementation for the account wrapper. + /// Generates the `SpreadLayout` trait implementation for the account + /// wrapper. /// /// # Note /// - /// Due to the generic parameter `E` and Rust's default rules for derive generated - /// trait bounds it is not recommended to derive the `SpreadLayout` trait implementation. + /// Due to the generic parameter `E` and Rust's default rules for derive + /// generated trait bounds it is not recommended to derive the + /// `SpreadLayout` trait implementation. fn generate_spread_layout_impl(&self) -> TokenStream2 { let span = self.span(); let call_builder_ident = self.ident(); @@ -198,12 +202,14 @@ impl CallBuilder<'_> { ) } - /// Generates the `PackedLayout` trait implementation for the account wrapper. + /// Generates the `PackedLayout` trait implementation for the account + /// wrapper. /// /// # Note /// - /// Due to the generic parameter `E` and Rust's default rules for derive generated - /// trait bounds it is not recommended to derive the `PackedLayout` trait implementation. + /// Due to the generic parameter `E` and Rust's default rules for derive + /// generated trait bounds it is not recommended to derive the + /// `PackedLayout` trait implementation. fn generate_packed_layout_impl(&self) -> TokenStream2 { let span = self.span(); let call_builder_ident = self.ident(); @@ -225,7 +231,8 @@ impl CallBuilder<'_> { ) } - /// Generates trait implementations for auxiliary traits for the account wrapper. + /// Generates trait implementations for auxiliary traits for the account + /// wrapper. /// /// # Note /// @@ -266,12 +273,13 @@ impl CallBuilder<'_> { ) } - /// Generate trait implementations for `FromAccountId` and `ToAccountId` for the account wrapper. + /// Generate trait implementations for `FromAccountId` and `ToAccountId` for + /// the account wrapper. /// /// # Note /// - /// This allows user code to conveniently transform from and to `AccountId` when - /// interacting with typed contracts. + /// This allows user code to conveniently transform from and to `AccountId` + /// when interacting with typed contracts. fn generate_to_from_account_id_impls(&self) -> TokenStream2 { let span = self.span(); let call_builder_ident = self.ident(); @@ -306,8 +314,8 @@ impl CallBuilder<'_> { /// The implemented messages call the SEAL host runtime in order to dispatch /// the respective ink! trait message calls of the called smart contract /// instance. - /// The way these messages are built-up allows the caller to customize message - /// parameters such as gas limit and transferred balance. + /// The way these messages are built-up allows the caller to customize + /// message parameters such as gas limit and transferred balance. fn generate_ink_trait_impl(&self) -> TokenStream2 { let span = self.trait_def.span(); let trait_ident = self.trait_def.trait_def.item().ident(); @@ -335,7 +343,8 @@ impl CallBuilder<'_> { ) } - /// Generate the code for all ink! trait messages implemented by the trait call builder. + /// Generate the code for all ink! trait messages implemented by the trait + /// call builder. fn generate_ink_trait_impl_messages(&self) -> TokenStream2 { let messages = self.trait_def.trait_def.item().iter_items().filter_map( |(item, selector)| { @@ -349,7 +358,8 @@ impl CallBuilder<'_> { } } - /// Generate the code for a single ink! trait message implemented by the trait call builder. + /// Generate the code for a single ink! trait message implemented by the + /// trait call builder. fn generate_ink_trait_impl_for_message( &self, message: &ir::InkTraitMessage, diff --git a/crates/lang/codegen/src/generator/trait_def/call_forwarder.rs b/crates/lang/codegen/src/generator/trait_def/call_forwarder.rs index 26003527c09..b031e7ce182 100644 --- a/crates/lang/codegen/src/generator/trait_def/call_forwarder.rs +++ b/crates/lang/codegen/src/generator/trait_def/call_forwarder.rs @@ -36,9 +36,9 @@ impl<'a> TraitDefinition<'a> { /// and allows to build up contract calls that allow for customization by /// the user to provide gas limit, endowment etc. /// - The call forwarder is associated to the call builder for the same ink! - /// trait definition and handles all ink! trait calls into another contract - /// instance on-chain. For constructing custom calls it forwards to the call - /// builder. + /// trait definition and handles all ink! trait calls into another + /// contract instance on-chain. For constructing custom calls it forwards + /// to the call builder. pub fn generate_call_forwarder(&self) -> TokenStream2 { CallForwarder::from(*self).generate_code() } @@ -125,12 +125,14 @@ impl CallForwarder<'_> { ) } - /// Generates the `StorageLayout` trait implementation for the account wrapper. + /// Generates the `StorageLayout` trait implementation for the account + /// wrapper. /// /// # Note /// - /// Due to the generic parameter `E` and Rust's default rules for derive generated - /// trait bounds it is not recommended to derive the `StorageLayout` trait implementation. + /// Due to the generic parameter `E` and Rust's default rules for derive + /// generated trait bounds it is not recommended to derive the + /// `StorageLayout` trait implementation. fn generate_storage_layout_impl(&self) -> TokenStream2 { let span = self.span(); let call_forwarder_ident = self.ident(); @@ -152,12 +154,14 @@ impl CallForwarder<'_> { ) } - /// Generates the `SpreadLayout` trait implementation for the account wrapper. + /// Generates the `SpreadLayout` trait implementation for the account + /// wrapper. /// /// # Note /// - /// Due to the generic parameter `E` and Rust's default rules for derive generated - /// trait bounds it is not recommended to derive the `SpreadLayout` trait implementation. + /// Due to the generic parameter `E` and Rust's default rules for derive + /// generated trait bounds it is not recommended to derive the + /// `SpreadLayout` trait implementation. fn generate_spread_layout_impl(&self) -> TokenStream2 { let span = self.span(); let call_forwarder_ident = self.ident(); @@ -194,12 +198,14 @@ impl CallForwarder<'_> { ) } - /// Generates the `PackedLayout` trait implementation for the account wrapper. + /// Generates the `PackedLayout` trait implementation for the account + /// wrapper. /// /// # Note /// - /// Due to the generic parameter `E` and Rust's default rules for derive generated - /// trait bounds it is not recommended to derive the `PackedLayout` trait implementation. + /// Due to the generic parameter `E` and Rust's default rules for derive + /// generated trait bounds it is not recommended to derive the + /// `PackedLayout` trait implementation. fn generate_packed_layout_impl(&self) -> TokenStream2 { let span = self.span(); let call_forwarder_ident = self.ident(); @@ -220,7 +226,8 @@ impl CallForwarder<'_> { ) } - /// Generates trait implementations for auxiliary traits for the account wrapper. + /// Generates trait implementations for auxiliary traits for the account + /// wrapper. /// /// # Note /// @@ -260,12 +267,13 @@ impl CallForwarder<'_> { ) } - /// Generate trait impls for `FromAccountId` and `ToAccountId` for the account wrapper. + /// Generate trait impls for `FromAccountId` and `ToAccountId` for the + /// account wrapper. /// /// # Note /// - /// This allows user code to conveniently transform from and to `AccountId` when - /// interacting with typed contracts. + /// This allows user code to conveniently transform from and to `AccountId` + /// when interacting with typed contracts. fn generate_to_from_account_id_impls(&self) -> TokenStream2 { let span = self.span(); let call_forwarder_ident = self.ident(); @@ -295,12 +303,14 @@ impl CallForwarder<'_> { ) } - /// Generate the trait implementation for `CallBuilder` for the ink! trait call forwarder. + /// Generate the trait implementation for `CallBuilder` for the ink! trait + /// call forwarder. /// /// # Note /// /// Through the implementation of this trait it is possible to refer to the - /// ink! trait call builder that is associated to this ink! trait call forwarder. + /// ink! trait call builder that is associated to this ink! trait call + /// forwarder. fn generate_call_builder_trait_impl(&self) -> TokenStream2 { let span = self.trait_def.span(); let call_forwarder_ident = self.ident(); @@ -363,7 +373,8 @@ impl CallForwarder<'_> { ) } - /// Generate the code for all ink! trait messages implemented by the trait call forwarder. + /// Generate the code for all ink! trait messages implemented by the trait + /// call forwarder. fn generate_ink_trait_impl_messages(&self) -> TokenStream2 { let messages = self.trait_def @@ -379,7 +390,8 @@ impl CallForwarder<'_> { } } - /// Generate the code for a single ink! trait message implemented by the trait call forwarder. + /// Generate the code for a single ink! trait message implemented by the + /// trait call forwarder. fn generate_ink_trait_impl_for_message( &self, message: &ir::InkTraitMessage, diff --git a/crates/lang/codegen/src/generator/trait_def/mod.rs b/crates/lang/codegen/src/generator/trait_def/mod.rs index f9e53bec316..befe549b5a7 100644 --- a/crates/lang/codegen/src/generator/trait_def/mod.rs +++ b/crates/lang/codegen/src/generator/trait_def/mod.rs @@ -28,7 +28,8 @@ use quote::{ quote_spanned, }; -/// Generator to create the ink! storage struct and important trait implementations. +/// Generator to create the ink! storage struct and important trait +/// implementations. #[derive(From, Copy, Clone)] pub struct TraitDefinition<'a> { trait_def: &'a ir::InkTraitDefinition, diff --git a/crates/lang/codegen/src/generator/trait_def/trait_registry.rs b/crates/lang/codegen/src/generator/trait_def/trait_registry.rs index 0ddda318549..1213d56dec0 100644 --- a/crates/lang/codegen/src/generator/trait_def/trait_registry.rs +++ b/crates/lang/codegen/src/generator/trait_def/trait_registry.rs @@ -15,9 +15,9 @@ //! The global registry with which it is possible to refer back to the global //! trait call builder and call forwarder types using only the trait identifier. //! -//! This works by making the global trait registry type defined in the `ink_lang` -//! crate implement each and every ink! trait definition and defining associated -//! types for the trait's respective call builder and call forwarder. +//! This works by making the global trait registry type defined in the +//! `ink_lang` crate implement each and every ink! trait definition and defining +//! associated types for the trait's respective call builder and call forwarder. use super::TraitDefinition; use crate::{ @@ -87,17 +87,19 @@ impl TraitRegistry<'_> { /// Generates the global trait registry implementation for the ink! trait. /// /// This makes it possible to refer back to the global call forwarder and - /// call builder specific to this ink! trait from anywhere with just the Rust - /// trait identifier which allows for type safe access. + /// call builder specific to this ink! trait from anywhere with just the + /// Rust trait identifier which allows for type safe access. /// /// # Note /// - /// Through this implementation we register the previously defined ink! trait - /// call forwarder and call builder types as such for the ink! trait. + /// Through this implementation we register the previously defined ink! + /// trait call forwarder and call builder types as such for the ink! + /// trait. /// /// This is done by the fact that ink! implements all ink! traits by the - /// [`ink_lang::TraitDefinitionRegistry`] type and uses the `__ink_ConcreteImplementer` - /// associated type to refer back to the actual call forwarder and call builder types. + /// [`ink_lang::TraitDefinitionRegistry`] type and uses the + /// `__ink_ConcreteImplementer` associated type to refer back to the + /// actual call forwarder and call builder types. fn generate_registry_impl(&self) -> TokenStream2 { let span = self.span(); let name = self.trait_ident(); @@ -118,7 +120,8 @@ impl TraitRegistry<'_> { ) } - /// Generate the code for all ink! trait messages implemented by the trait registry. + /// Generate the code for all ink! trait messages implemented by the trait + /// registry. fn generate_registry_messages(&self) -> TokenStream2 { let messages = self.trait_def.trait_def.item().iter_items().filter_map( |(item, selector)| { @@ -131,7 +134,8 @@ impl TraitRegistry<'_> { } } - /// Generates code to assert that ink! input and output types meet certain properties. + /// Generates code to assert that ink! input and output types meet certain + /// properties. fn generate_inout_guards_for_message(message: &ir::InkTraitMessage) -> TokenStream2 { let message_span = message.span(); let message_inputs = message.inputs().map(|input| { @@ -157,9 +161,11 @@ impl TraitRegistry<'_> { ) } - /// Generate the code for a single ink! trait message implemented by the trait registry. + /// Generate the code for a single ink! trait message implemented by the + /// trait registry. /// - /// Generally the implementation of any ink! trait of the ink! trait registry + /// Generally the implementation of any ink! trait of the ink! trait + /// registry fn generate_registry_for_message( &self, message: &ir::InkTraitMessage, @@ -274,8 +280,8 @@ impl TraitRegistry<'_> { ) } - /// Generates the [`::ink_lang::reflect::TraitMessageInfo`] implementations for all - /// ink! messages defined by the ink! trait definition. + /// Generates the [`::ink_lang::reflect::TraitMessageInfo`] implementations + /// for all ink! messages defined by the ink! trait definition. fn generate_info_for_trait_messages(&self) -> TokenStream2 { let span = self.span(); let message_impls = self.trait_def.trait_def.item().iter_items().filter_map( @@ -290,8 +296,8 @@ impl TraitRegistry<'_> { ) } - /// Generates the [`::ink_lang::reflect::TraitMessageInfo`] implementation for a single - /// ink! message defined by the ink! trait definition. + /// Generates the [`::ink_lang::reflect::TraitMessageInfo`] implementation + /// for a single ink! message defined by the ink! trait definition. fn generate_info_for_trait_for_message( &self, message: &ir::InkTraitMessage, diff --git a/crates/lang/codegen/src/traits.rs b/crates/lang/codegen/src/traits.rs index a6c8f19ac16..60865f907aa 100644 --- a/crates/lang/codegen/src/traits.rs +++ b/crates/lang/codegen/src/traits.rs @@ -20,7 +20,8 @@ pub trait GenerateCode { fn generate_code(&self) -> TokenStream2; } -/// Types implementing this trait can forward code generation to other generators. +/// Types implementing this trait can forward code generation to other +/// generators. pub trait GenerateCodeUsing: AsRef { /// Generates code using the given codegen module. fn generate_code_using<'a, G>(&'a self) -> TokenStream2 diff --git a/crates/lang/ir/src/ast/attr_args.rs b/crates/lang/ir/src/ast/attr_args.rs index a32459ae311..43bf3e4409c 100644 --- a/crates/lang/ir/src/ast/attr_args.rs +++ b/crates/lang/ir/src/ast/attr_args.rs @@ -30,8 +30,9 @@ use syn::{ /// The attribute arguments for the configuration of an ink! smart contract. /// -/// These are the segments `env = ::my::env::Environment` and `compile_as_dependency = true` -/// in `#[ink::contract(env = ::my::env::Environment, compile_as_dependency = true`. +/// These are the segments `env = ::my::env::Environment` and +/// `compile_as_dependency = true` in `#[ink::contract(env = +/// ::my::env::Environment, compile_as_dependency = true`. #[derive(Debug, PartialEq, Eq)] pub struct AttributeArgs { args: Punctuated, diff --git a/crates/lang/ir/src/error.rs b/crates/lang/ir/src/error.rs index 4355998f645..0b1abd6af2d 100644 --- a/crates/lang/ir/src/error.rs +++ b/crates/lang/ir/src/error.rs @@ -31,15 +31,15 @@ impl ExtError for syn::Error { /// /// # Parameters /// -/// - The first argument must implement [`quote::ToTokens`] in order to -/// infer a [`Span`](`proc_macro2::Span`). +/// - The first argument must implement [`quote::ToTokens`] in order to infer a +/// [`Span`](`proc_macro2::Span`). /// - The second argument is a format string. /// - The rest are format string arguments. /// /// # Note /// -/// On stable Rust this might yield higher quality error span information to the user -/// than [`format_err`]. +/// On stable Rust this might yield higher quality error span information to the +/// user than [`format_err`]. /// - Source: /// [`syn::Error::new_spanned`](https://docs.rs/syn/1.0.33/syn/struct.Error.html#method.new_spanned) /// - Tracking issue: [`#54725`](https://github.com/rust-lang/rust/issues/54725) @@ -58,7 +58,8 @@ macro_rules! format_err_spanned { /// /// # Parameters /// -/// - The first argument must be a type that implements [`syn::spanned::Spanned`]. +/// - The first argument must be a type that implements +/// [`syn::spanned::Spanned`]. /// - The second argument is a format string. /// - The rest are format string arguments. /// diff --git a/crates/lang/ir/src/ir/attrs.rs b/crates/lang/ir/src/ir/attrs.rs index 99ba725f941..1d593a4ce14 100644 --- a/crates/lang/ir/src/ir/attrs.rs +++ b/crates/lang/ir/src/ir/attrs.rs @@ -31,7 +31,8 @@ use proc_macro2::{ use std::collections::HashMap; use syn::spanned::Spanned; -/// An extension trait for [`syn::Attribute`] in order to query for documentation. +/// An extension trait for [`syn::Attribute`] in order to query for +/// documentation. pub trait IsDocAttribute { /// Returns `true` if the attribute is a Rust documentation attribute. fn is_doc_attribute(&self) -> bool; @@ -67,12 +68,13 @@ pub enum Attribute { Ink(InkAttribute), /// Any other attribute. /// - /// This can be a known `#[derive(Debug)]` or a specific attribute of another - /// crate. + /// This can be a known `#[derive(Debug)]` or a specific attribute of + /// another crate. Other(syn::Attribute), } -/// Types implementing this trait can return a slice over their `syn` attributes. +/// Types implementing this trait can return a slice over their `syn` +/// attributes. pub trait Attrs { /// Returns the slice of attributes of an AST entity. fn attrs(&self) -> &[syn::Attribute]; @@ -212,8 +214,9 @@ impl InkAttribute { /// /// # Example /// - /// Given the input ink! attribute sequence `[ #[ink(message)], #[ink(payable)] ]` - /// this procedure returns the single attribute `#[ink(message, payable)]`. + /// Given the input ink! attribute sequence `[ #[ink(message)], + /// #[ink(payable)] ]` this procedure returns the single attribute + /// `#[ink(message, payable)]`. /// /// # Errors /// @@ -286,7 +289,8 @@ impl InkAttribute { .any(|arg| matches!(arg.kind(), AttributeArg::Anonymous)) } - /// Returns `false` if the ink! attribute contains the `handle_status = false` argument. + /// Returns `false` if the ink! attribute contains the `handle_status = + /// false` argument. /// /// Otherwise returns `true`. pub fn is_handle_status(&self) -> bool { @@ -295,7 +299,8 @@ impl InkAttribute { .any(|arg| matches!(arg.kind(), AttributeArg::HandleStatus(false))) } - /// Returns `false` if the ink! attribute contains the `returns_result = false` argument. + /// Returns `false` if the ink! attribute contains the `returns_result = + /// false` argument. /// /// Otherwise returns `true`. pub fn is_returns_result(&self) -> bool { @@ -411,16 +416,17 @@ pub enum AttributeArg { /// /// Can be applied on ink! implementation blocks in order to make ink! aware /// of them. This is useful if such an implementation block does not contain - /// any other ink! attributes, so it would be flagged by ink! as a Rust item. - /// Adding `#[ink(impl)]` on such implementation blocks makes them treated - /// as ink! implementation blocks thus allowing to access the environment - /// etc. Note that ink! messages and constructors still need to be explicitly - /// flagged as such. + /// any other ink! attributes, so it would be flagged by ink! as a Rust + /// item. Adding `#[ink(impl)]` on such implementation blocks makes them + /// treated as ink! implementation blocks thus allowing to access the + /// environment etc. Note that ink! messages and constructors still need + /// to be explicitly flagged as such. Implementation, /// `#[ink(extension = N: u32)]` /// /// Applies on ink! chain extension method to set their `func_id` parameter. - /// Every chain extension method must have exactly one ink! `extension` attribute. + /// Every chain extension method must have exactly one ink! `extension` + /// attribute. /// /// Used by the `#[ink::chain_extension]` procedural macro. Extension(ExtensionId), @@ -531,8 +537,8 @@ impl Namespace { } } -/// Returns `true` if the given iterator yields at least one attribute of the form -/// `#[ink(..)]` or `#[ink]`. +/// Returns `true` if the given iterator yields at least one attribute of the +/// form `#[ink(..)]` or `#[ink]`. /// /// # Note /// @@ -565,11 +571,13 @@ where } } -/// Partitions the given attributes into ink! specific and non-ink! specific attributes. +/// Partitions the given attributes into ink! specific and non-ink! specific +/// attributes. /// /// # Error /// -/// Returns an error if some ink! specific attributes could not be successfully parsed. +/// Returns an error if some ink! specific attributes could not be successfully +/// parsed. pub fn partition_attributes( attrs: I, ) -> Result<(Vec, Vec), syn::Error> @@ -603,9 +611,10 @@ where /// /// # Parameters /// -/// The `is_conflicting_attr` closure returns `Ok` if the attribute does not conflict, -/// returns `Err(None)` if the attribute conflicts but without providing further reasoning -/// and `Err(Some(reason))` if the attribute conflicts given additional context information. +/// The `is_conflicting_attr` closure returns `Ok` if the attribute does not +/// conflict, returns `Err(None)` if the attribute conflicts but without +/// providing further reasoning and `Err(Some(reason))` if the attribute +/// conflicts given additional context information. /// /// # Errors /// @@ -649,9 +658,10 @@ where /// /// # Parameters /// -/// The `is_conflicting_attr` closure returns `Ok` if the attribute does not conflict, -/// returns `Err(None)` if the attribute conflicts but without providing further reasoning -/// and `Err(Some(reason))` if the attribute conflicts given additional context information. +/// The `is_conflicting_attr` closure returns `Ok` if the attribute does not +/// conflict, returns `Err(None)` if the attribute conflicts but without +/// providing further reasoning and `Err(Some(reason))` if the attribute +/// conflicts given additional context information. /// /// # Errors /// @@ -754,16 +764,18 @@ impl TryFrom for InkAttribute { } impl InkAttribute { - /// Ensures that there are no conflicting ink! attribute arguments in `self`. + /// Ensures that there are no conflicting ink! attribute arguments in + /// `self`. /// /// The given `is_conflicting` describes for every ink! attribute argument /// found in `self` if it is in conflict. /// /// # Parameters /// - /// The `is_conflicting_attr` closure returns `Ok` if the attribute does not conflict, - /// returns `Err(None)` if the attribute conflicts but without providing further reasoning - /// and `Err(Some(reason))` if the attribute conflicts given additional context information. + /// The `is_conflicting_attr` closure returns `Ok` if the attribute does not + /// conflict, returns `Err(None)` if the attribute conflicts but without + /// providing further reasoning and `Err(Some(reason))` if the attribute + /// conflicts given additional context information. pub fn ensure_no_conflicts<'a, P>( &'a self, mut is_conflicting: P, diff --git a/crates/lang/ir/src/ir/blake2.rs b/crates/lang/ir/src/ir/blake2.rs index 43bd5f6b836..22c292191b0 100644 --- a/crates/lang/ir/src/ir/blake2.rs +++ b/crates/lang/ir/src/ir/blake2.rs @@ -16,7 +16,8 @@ use core::convert::TryFrom; use proc_macro2::TokenStream as TokenStream2; use syn::spanned::Spanned as _; -/// Computes the BLAKE-2b 256-bit hash for the given input and stores it in output. +/// Computes the BLAKE-2b 256-bit hash for the given input and stores it in +/// output. pub fn blake2b_256(input: &[u8], output: &mut [u8; 32]) { use ::blake2::digest::{ Update as _, diff --git a/crates/lang/ir/src/ir/chain_extension.rs b/crates/lang/ir/src/ir/chain_extension.rs index e589f547477..d0b36418046 100644 --- a/crates/lang/ir/src/ir/chain_extension.rs +++ b/crates/lang/ir/src/ir/chain_extension.rs @@ -76,24 +76,28 @@ pub struct ChainExtensionMethod { item: syn::TraitItemMethod, /// The unique identifier of the chain extension method. id: ExtensionId, - /// If `false` the `u32` status code of the chain extension method call is going to be - /// ignored and assumed to be always successful. The output buffer in this case is going - /// to be queried and decoded into the chain extension method's output type. + /// If `false` the `u32` status code of the chain extension method call is + /// going to be ignored and assumed to be always successful. The output + /// buffer in this case is going to be queried and decoded into the + /// chain extension method's output type. /// /// If `true` the returned `u32` status code `code` is queried and - /// `::from_status_code(code)` is called. - /// The call to `from_status_code` returns `Result<(), Self::ErrorCode>`. If `Ok(())` - /// the output buffer is queried and decoded as described above. - /// If `Err(Self::ErrorCode)` the `Self::ErrorCode` is converted into `E` of `Result` + /// `::from_status_code(code)` + /// is called. The call to `from_status_code` returns `Result<(), + /// Self::ErrorCode>`. If `Ok(())` the output buffer is queried and + /// decoded as described above. If `Err(Self::ErrorCode)` the + /// `Self::ErrorCode` is converted into `E` of `Result` /// if the chain extension method returns a `Result` type. - /// In case the chain extension method does _NOT_ return a `Result` type the call returns - /// `Result` where `T` is the chain extension method's return type. + /// In case the chain extension method does _NOT_ return a `Result` type the + /// call returns `Result` where `T` is the chain + /// extension method's return type. /// /// The default for this flag is `true`. handle_status: bool, - /// If `false` the procedural macro no longer tries to enforce that the returned type encoded - /// into the output buffer of the chain extension method call is of type `Result`. - /// Also `E` is no longer required to implement `From` in case `handle_status` + /// If `false` the procedural macro no longer tries to enforce that the + /// returned type encoded into the output buffer of the chain extension + /// method call is of type `Result`. Also `E` is no longer + /// required to implement `From` in case `handle_status` /// flag does not exist. /// /// The default for this flag is `true`. @@ -137,12 +141,14 @@ impl ChainExtensionMethod { } } - /// Returns `true` if the chain extension method was flagged with `#[ink(handle_status)]`. + /// Returns `true` if the chain extension method was flagged with + /// `#[ink(handle_status)]`. pub fn handle_status(&self) -> bool { self.handle_status } - /// Returns `true` if the chain extension method was flagged with `#[ink(returns_result)]`. + /// Returns `true` if the chain extension method was flagged with + /// `#[ink(returns_result)]`. pub fn returns_result(&self) -> bool { self.returns_result } @@ -176,7 +182,8 @@ impl<'a> Iterator for ChainExtensionMethodInputs<'a> { /// /// The ink! attribute `#[ink(extension = N: u32)]` for chain extension methods. /// -/// Has a `func_id` extension ID to identify the associated chain extension method. +/// Has a `func_id` extension ID to identify the associated chain extension +/// method. #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct ExtensionId { index: u32, @@ -210,7 +217,8 @@ impl TryFrom for ChainExtension { } impl ChainExtension { - /// Returns `Ok` if the trait matches all requirements for an ink! chain extension. + /// Returns `Ok` if the trait matches all requirements for an ink! chain + /// extension. pub fn new(attr: TokenStream2, input: TokenStream2) -> Result { if !attr.is_empty() { return Err(format_err_spanned!( @@ -227,7 +235,8 @@ impl ChainExtension { /// # Errors /// /// - If the input trait has been defined as `unsafe`. - /// - If the input trait is an automatically implemented trait (`auto trait`). + /// - If the input trait is an automatically implemented trait (`auto + /// trait`). /// - If the input trait is generic over some set of types. /// - If the input trait's visibility is not public (`pub`). /// - If the input trait has super-traits. @@ -265,12 +274,14 @@ impl ChainExtension { Ok(()) } - /// Checks if the associated trait item type is a proper chain extension error code. + /// Checks if the associated trait item type is a proper chain extension + /// error code. /// /// # Errors /// /// - If the associated type is not called `ErrorCode`. - /// - If the associated type is generic, has where bounds or has a default type. + /// - If the associated type is generic, has where bounds or has a default + /// type. /// - If there are multiple associated `ErrorCode` types. fn analyse_error_code( item_type: &syn::TraitItemType, @@ -318,7 +329,8 @@ impl ChainExtension { Ok(()) } - /// Returns `Ok` if all trait items respect the requirements for an ink! chain extension. + /// Returns `Ok` if all trait items respect the requirements for an ink! + /// chain extension. /// /// # Errors /// @@ -328,15 +340,18 @@ impl ChainExtension { /// - macros definitions or usages /// - unknown token sequences (`Verbatim`s) /// - methods with default implementations - /// - If the trait contains methods which do not respect the ink! trait definition requirements: + /// - If the trait contains methods which do not respect the ink! trait + /// definition requirements: /// - All trait methods must not have a `self` receiver. - /// - All trait methods must have an `#[ink(extension = N: u32)]` attribute that is the ID that - /// corresponds with the function ID of the respective chain extension call. + /// - All trait methods must have an `#[ink(extension = N: u32)]` + /// attribute that is the ID that corresponds with the function ID of + /// the respective chain extension call. /// /// # Note /// - /// The input Rust trait item is going to be replaced with a concrete chain extension type definition - /// as a result of this procedural macro invocation. + /// The input Rust trait item is going to be replaced with a concrete chain + /// extension type definition as a result of this procedural macro + /// invocation. fn analyse_items( item_trait: &syn::ItemTrait, ) -> Result<(syn::TraitItemType, Vec)> { @@ -515,7 +530,8 @@ impl ChainExtension { mod tests { use super::*; - /// Checks if the token stream in `$chain_extension` results in the expected error message. + /// Checks if the token stream in `$chain_extension` results in the expected + /// error message. macro_rules! assert_ink_chain_extension_eq_err { ( error: $err_str:literal, $($chain_extension:tt)* ) => { assert_eq!( diff --git a/crates/lang/ir/src/ir/config.rs b/crates/lang/ir/src/ir/config.rs index a6fdb6449ce..b38722b1099 100644 --- a/crates/lang/ir/src/ir/config.rs +++ b/crates/lang/ir/src/ir/config.rs @@ -170,8 +170,9 @@ impl Default for Environment { mod tests { use super::*; - /// Asserts that the given input configuration attribute argument are converted - /// into the expected ink! configuration or yields the expected error message. + /// Asserts that the given input configuration attribute argument are + /// converted into the expected ink! configuration or yields the + /// expected error message. fn assert_try_from( input: ast::AttributeArgs, expected: Result, diff --git a/crates/lang/ir/src/ir/contract.rs b/crates/lang/ir/src/ir/contract.rs index f7533a8bb7d..43bb492ff1e 100644 --- a/crates/lang/ir/src/ir/contract.rs +++ b/crates/lang/ir/src/ir/contract.rs @@ -52,8 +52,10 @@ impl Contract { /// /// # Note /// - /// - The `ink_config` token stream must properly decode into [`ir::Config`]. - /// - The `ink_module` token stream must properly decode into [`ir::ItemMod`]. + /// - The `ink_config` token stream must properly decode into + /// [`ir::Config`]. + /// - The `ink_module` token stream must properly decode into + /// [`ir::ItemMod`]. /// /// # Errors /// @@ -98,16 +100,14 @@ impl Contract { /// macro annotation itself within the `(config)` part. The available fields /// are the following: /// - /// - `types`: To specify `Environment` different from the default environment - /// types. + /// - `types`: To specify `Environment` different from the default + /// environment types. /// - `storage-alloc`: If `true` enables the dynamic storage allocator - /// facilities and code generation of the ink! smart - /// contract. Does incur some overhead. The default is - /// `true`. + /// facilities and code generation of the ink! smart contract. Does incur + /// some overhead. The default is `true`. /// - `as-dependency`: If `true` compiles this ink! smart contract always as - /// if it was a dependency of another smart contract. - /// This configuration is mainly needed for testing and - /// the default is `false`. + /// if it was a dependency of another smart contract. This configuration + /// is mainly needed for testing and the default is `false`. /// /// Note that we might add more configuration fields in the future if /// necessary. diff --git a/crates/lang/ir/src/ir/idents_lint.rs b/crates/lang/ir/src/ir/idents_lint.rs index 5306c54b470..be96025a021 100644 --- a/crates/lang/ir/src/ir/idents_lint.rs +++ b/crates/lang/ir/src/ir/idents_lint.rs @@ -12,11 +12,13 @@ // See the License for the specific language governing permissions and // limitations under the License. -/// Returns `Ok` if there are no occurrences of identifiers starting with `__ink_`. +/// Returns `Ok` if there are no occurrences of identifiers starting with +/// `__ink_`. /// /// # Errors /// -/// Returns a combined error for every instance of `__ink_` prefixed identifier found. +/// Returns a combined error for every instance of `__ink_` prefixed identifier +/// found. pub fn ensure_no_ink_identifiers(checked: &T) -> Result<(), syn::Error> where T: VisitBy, @@ -59,7 +61,8 @@ mod private { } } - /// Visitor to ensure that there are no identifiers starting with `__ink_` as prefix. + /// Visitor to ensure that there are no identifiers starting with `__ink_` + /// as prefix. /// /// # Errors /// diff --git a/crates/lang/ir/src/ir/ink_test.rs b/crates/lang/ir/src/ir/ink_test.rs index fa427bfcafa..1de09610891 100644 --- a/crates/lang/ir/src/ir/ink_test.rs +++ b/crates/lang/ir/src/ir/ink_test.rs @@ -32,7 +32,8 @@ impl TryFrom for InkTest { } impl InkTest { - /// Returns `Ok` if the trait matches all requirements for an ink! trait definition. + /// Returns `Ok` if the trait matches all requirements for an ink! trait + /// definition. pub fn new(attr: TokenStream2, input: TokenStream2) -> Result { if !attr.is_empty() { return Err(format_err_spanned!( diff --git a/crates/lang/ir/src/ir/item/mod.rs b/crates/lang/ir/src/ir/item/mod.rs index 5034a362f27..3e25018950c 100644 --- a/crates/lang/ir/src/ir/item/mod.rs +++ b/crates/lang/ir/src/ir/item/mod.rs @@ -31,7 +31,8 @@ use crate::{ use core::convert::TryFrom; use syn::spanned::Spanned as _; -/// An item in the root of the ink! module ([`ir::ItemMod`](`crate::ir::ItemMod`)). +/// An item in the root of the ink! module +/// ([`ir::ItemMod`](`crate::ir::ItemMod`)). /// /// This is either an ink! specific item or a normal Rust item. #[derive(Debug, PartialEq, Eq)] @@ -177,7 +178,8 @@ impl InkItem { /// /// # Errors /// - /// If invalid or malformed ink! attributes are encountered for the given item. + /// If invalid or malformed ink! attributes are encountered for the given + /// item. pub fn is_ink_item(item: &syn::Item) -> Result { match item { syn::Item::Struct(item_struct) => { @@ -225,7 +227,8 @@ impl InkItem { } } - /// Returns `true` if the ink! specific item is the storage struct definition. + /// Returns `true` if the ink! specific item is the storage struct + /// definition. pub fn is_storage_item(&self) -> bool { self.filter_map_storage_item().is_some() } diff --git a/crates/lang/ir/src/ir/item_impl/callable.rs b/crates/lang/ir/src/ir/item_impl/callable.rs index d7ab1bca1cb..0be32013bd1 100644 --- a/crates/lang/ir/src/ir/item_impl/callable.rs +++ b/crates/lang/ir/src/ir/item_impl/callable.rs @@ -171,7 +171,8 @@ pub trait Callable { /// Returns the span of the inputs of the ink! callable. fn inputs_span(&self) -> Span; - /// Returns a slice over shared references to the statements of the callable. + /// Returns a slice over shared references to the statements of the + /// callable. fn statements(&self) -> &[syn::Stmt]; } @@ -191,12 +192,12 @@ pub trait Callable { /// Then the selector is composed in the following way: /// /// - If `s` is given we simply return `s`. -/// - Otherwise if `T` is not `None` (trait `impl` block) we concatenate -/// `S`, `T` and `i` with `::` as separator if `T` refers to a full-path. -/// If `T` refers to a relative path or is just an identifier we only take -/// its last segment `p` (e.g. the trait's identifier) into consideration -/// and use it instead of `P` in the above concatenation. -/// In the following we refer to the resulting concatenation as `C`. +/// - Otherwise if `T` is not `None` (trait `impl` block) we concatenate `S`, +/// `T` and `i` with `::` as separator if `T` refers to a full-path. If `T` +/// refers to a relative path or is just an identifier we only take its last +/// segment `p` (e.g. the trait's identifier) into consideration and use it +/// instead of `P` in the above concatenation. In the following we refer to +/// the resulting concatenation as `C`. /// - Now we take the BLAKE-2 hash of `C` which results in 32 bytes of output /// and take the first 4 bytes that are returned in order as the composed /// selector. @@ -214,8 +215,8 @@ pub trait Callable { /// } /// ``` /// -/// ... then the selector of `my_message` is simply `0xDEADBEEF` since it overrides -/// the composed selector. +/// ... then the selector of `my_message` is simply `0xDEADBEEF` since it +/// overrides the composed selector. /// /// ## Inherent implementation block /// @@ -357,8 +358,8 @@ where /// - `const` (compile-time evaluable) /// - `async` (asynchronous WebAssembly smart contract calling is not allowed) /// - `unsafe` (caller provided assertions not yet stable) -/// - Furthermore this is `true` if the externally callable is defined for a -/// non default ABI (e.g. `extern "C"`) or does not have valid visibility. +/// - Furthermore this is `true` if the externally callable is defined for a non +/// default ABI (e.g. `extern "C"`) or does not have valid visibility. pub(super) fn ensure_callable_invariants( method_item: &syn::ImplItemMethod, kind: CallableKind, @@ -451,7 +452,8 @@ impl quote::ToTokens for Visibility { } impl Visibility { - /// Returns `true` if the visibility of the ink! message of constructor is public (`pub`). + /// Returns `true` if the visibility of the ink! message of constructor is + /// public (`pub`). /// /// # Note /// @@ -460,7 +462,8 @@ impl Visibility { matches!(self, Self::Public(_)) } - /// Returns `true` if the visibility of the ink! message of constructor is inherited. + /// Returns `true` if the visibility of the ink! message of constructor is + /// inherited. /// /// # Note /// diff --git a/crates/lang/ir/src/ir/item_impl/message.rs b/crates/lang/ir/src/ir/item_impl/message.rs index 9659531f801..4cf7e9114b8 100644 --- a/crates/lang/ir/src/ir/item_impl/message.rs +++ b/crates/lang/ir/src/ir/item_impl/message.rs @@ -283,13 +283,14 @@ impl Message { } } - /// Returns a local ID unique to the ink! message with respect to its implementation block. + /// Returns a local ID unique to the ink! message with respect to its + /// implementation block. /// /// # Note /// - /// It is a compile error if two ink! trait messages share the same local ID. - /// Although the above scenario is very unlikely since the local ID is computed - /// solely by the identifier of the ink! message. + /// It is a compile error if two ink! trait messages share the same local + /// ID. Although the above scenario is very unlikely since the local ID + /// is computed solely by the identifier of the ink! message. pub fn local_id(&self) -> u32 { utils::local_message_id(self.ident()) } diff --git a/crates/lang/ir/src/ir/item_impl/mod.rs b/crates/lang/ir/src/ir/item_impl/mod.rs index 1e7ed9acd50..0c0f8686b4c 100644 --- a/crates/lang/ir/src/ir/item_impl/mod.rs +++ b/crates/lang/ir/src/ir/item_impl/mod.rs @@ -114,8 +114,8 @@ impl quote::ToTokens for ItemImpl { } impl ItemImpl { - /// Returns `true` if the Rust implementation block is an ink! implementation - /// block. + /// Returns `true` if the Rust implementation block is an ink! + /// implementation block. /// /// # Note /// @@ -357,17 +357,20 @@ impl ItemImpl { .map(|segment| &segment.ident) } - /// Returns the namespace of the implementation block if any has been provided. + /// Returns the namespace of the implementation block if any has been + /// provided. pub fn namespace(&self) -> Option<&ir::Namespace> { self.namespace.as_ref() } - /// Returns an iterator yielding the ink! messages of the implementation block. + /// Returns an iterator yielding the ink! messages of the implementation + /// block. pub fn iter_messages(&self) -> IterMessages { IterMessages::new(self) } - /// Returns an iterator yielding the ink! messages of the implementation block. + /// Returns an iterator yielding the ink! messages of the implementation + /// block. pub fn iter_constructors(&self) -> IterConstructors { IterConstructors::new(self) } diff --git a/crates/lang/ir/src/ir/item_mod.rs b/crates/lang/ir/src/ir/item_mod.rs index 858035889df..717696ad223 100644 --- a/crates/lang/ir/src/ir/item_mod.rs +++ b/crates/lang/ir/src/ir/item_mod.rs @@ -84,7 +84,8 @@ use syn::{ /// } /// ``` /// -/// If the capabilities of an inline Rust module change we have to adjust for that. +/// If the capabilities of an inline Rust module change we have to adjust for +/// that. #[derive(Debug, PartialEq, Eq)] pub struct ItemMod { attrs: Vec, @@ -97,7 +98,8 @@ pub struct ItemMod { impl ItemMod { /// Ensures that the ink! storage struct is not missing and that there are - /// not multiple ink! storage struct definitions for the given slice of items. + /// not multiple ink! storage struct definitions for the given slice of + /// items. fn ensure_storage_struct_quantity( module_span: Span, items: &[ir::Item], @@ -121,7 +123,8 @@ impl ItemMod { Ok(()) } - /// Ensures that the given slice of items contains at least one ink! message. + /// Ensures that the given slice of items contains at least one ink! + /// message. fn ensure_contains_message( module_span: Span, items: &[ir::Item], @@ -143,7 +146,8 @@ impl ItemMod { Ok(()) } - /// Ensures that the given slice of items contains at least one ink! constructor. + /// Ensures that the given slice of items contains at least one ink! + /// constructor. fn ensure_contains_constructor( module_span: Span, items: &[ir::Item], @@ -345,7 +349,8 @@ impl ItemMod { storage } - /// Returns all (ink! and non-ink! specific) item definitions of the ink! inline module. + /// Returns all (ink! and non-ink! specific) item definitions of the ink! + /// inline module. pub fn items(&self) -> &[ir::Item] { self.items.as_slice() } diff --git a/crates/lang/ir/src/ir/selector.rs b/crates/lang/ir/src/ir/selector.rs index 59dc6615741..0574a94a192 100644 --- a/crates/lang/ir/src/ir/selector.rs +++ b/crates/lang/ir/src/ir/selector.rs @@ -23,20 +23,22 @@ use syn::spanned::Spanned as _; /// /// # Note /// -/// This is equal to the first four bytes of the SHA-3 hash of a function's name. +/// This is equal to the first four bytes of the SHA-3 hash of a function's +/// name. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Selector { bytes: [u8; 4], } -/// The trait prefix to compute a composed selector for trait implementation blocks. +/// The trait prefix to compute a composed selector for trait implementation +/// blocks. #[derive(Debug, Copy, Clone)] pub struct TraitPrefix<'a> { /// The namespace of the ink! trait definition. /// - /// By default this is equal to the `module_path!` at the ink! trait definition site. - /// It can be customized by the ink! trait definition author using `#[ink(namespace = N)]` - /// ink! attribute. + /// By default this is equal to the `module_path!` at the ink! trait + /// definition site. It can be customized by the ink! trait definition + /// author using `#[ink(namespace = N)]` ink! attribute. namespace: Option<&'a syn::LitStr>, /// The Rust identifier of the ink! trait definition. trait_ident: &'a syn::Ident, @@ -74,36 +76,38 @@ impl Selector { /// # Note /// - /// - `trait_prefix` is `None` when computing the selector of ink! constructors - /// and messages in inherent implementation blocks. - /// - `trait_prefix` is `Some` when computing the selector of ink! constructors - /// and messages in trait implementation blocks. In this case the `namespace` - /// is either the full path of the trait definition gained by Rust's - /// `module_path!` macro by default or it is customized by manual application - /// of the `#[ink(namespace = "my_namespace")]` ink! attribute. In the - /// example `my_namespace` concatenated with `::` and the identifier of the - /// trait definition would then be part of the provided `trait_prefix` parameter. + /// - `trait_prefix` is `None` when computing the selector of ink! + /// constructors and messages in inherent implementation blocks. + /// - `trait_prefix` is `Some` when computing the selector of ink! + /// constructors and messages in trait implementation blocks. In this case + /// the `namespace` is either the full path of the trait definition gained + /// by Rust's `module_path!` macro by default or it is customized by + /// manual application of the `#[ink(namespace = "my_namespace")]` ink! + /// attribute. In the example `my_namespace` concatenated with `::` and + /// the identifier of the trait definition would then be part of the + /// provided `trait_prefix` parameter. /// - `fn_ident` refers to the ink! constructor or message identifier. /// /// # Inherent Implementation Blocks /// - /// For inherent implementation blocks, when `trait_prefix` is `None` the composed - /// selector is computed as follows: + /// For inherent implementation blocks, when `trait_prefix` is `None` the + /// composed selector is computed as follows: /// - /// 1. Apply `BLAKE2` 256-bit hash `H` on the bytes of the ASCII representation of - /// the `fn_ident` identifier. + /// 1. Apply `BLAKE2` 256-bit hash `H` on the bytes of the ASCII + /// representation of the `fn_ident` identifier. /// 1. The first 4 bytes of `H` make up the selector. /// /// # Trait Implementation Blocks /// /// For trait implementation blocks, when `trait_prefix` is - /// `Some((namespace, trait_ident))` the composed selector is computed as follows: + /// `Some((namespace, trait_ident))` the composed selector is computed as + /// follows: /// /// 1. Compute the ASCII byte representation of `fn_ident` and call it `F`. /// 1. Compute the ASCII byte representation of `namespace` and call it `N`. - /// 1. Compute the ASCII byte representation of `trait_ident` and call it `T`. - /// 1. Concatenate `N`, `T` and `F` using `::` as separator and call it `C`. - /// 1. Apply the `BLAKE2` 256-bit hash `H` of `C`. + /// 1. Compute the ASCII byte representation of `trait_ident` and call it + /// `T`. 1. Concatenate `N`, `T` and `F` using `::` as separator and + /// call it `C`. 1. Apply the `BLAKE2` 256-bit hash `H` of `C`. /// 1. The first 4 bytes of `H` make up the selector. pub fn compose<'a, T>(trait_prefix: T, fn_ident: &syn::Ident) -> Self where diff --git a/crates/lang/ir/src/ir/trait_def/config.rs b/crates/lang/ir/src/ir/trait_def/config.rs index 5cd790e8baf..39c675d4a70 100644 --- a/crates/lang/ir/src/ir/trait_def/config.rs +++ b/crates/lang/ir/src/ir/trait_def/config.rs @@ -46,7 +46,8 @@ impl TraitDefinitionConfig { } } -/// Return an error to notify about duplicate ink! trait definition configuration arguments. +/// Return an error to notify about duplicate ink! trait definition +/// configuration arguments. fn duplicate_config_err(fst: F, snd: S, name: &str) -> syn::Error where F: Spanned, diff --git a/crates/lang/ir/src/ir/trait_def/item/iter.rs b/crates/lang/ir/src/ir/trait_def/item/iter.rs index 38a5acd2638..06731bfb204 100644 --- a/crates/lang/ir/src/ir/trait_def/item/iter.rs +++ b/crates/lang/ir/src/ir/trait_def/item/iter.rs @@ -27,7 +27,8 @@ pub struct IterInkTraitItemsRaw<'a> { } impl<'a> IterInkTraitItemsRaw<'a> { - /// Creates a new iterator yielding ink! trait items over the raw Rust trait definition. + /// Creates a new iterator yielding ink! trait items over the raw Rust trait + /// definition. pub(super) fn from_raw(item_trait: &'a syn::ItemTrait) -> Self { Self { iter: item_trait.items.iter(), diff --git a/crates/lang/ir/src/ir/trait_def/item/mod.rs b/crates/lang/ir/src/ir/trait_def/item/mod.rs index 69cb677a383..de22eeb8a3b 100644 --- a/crates/lang/ir/src/ir/trait_def/item/mod.rs +++ b/crates/lang/ir/src/ir/trait_def/item/mod.rs @@ -60,7 +60,8 @@ impl TryFrom for InkItemTrait { } impl InkItemTrait { - /// Creates a new ink! item trait from the given configuration and trait definition. + /// Creates a new ink! item trait from the given configuration and trait + /// definition. pub fn new( config: &TraitDefinitionConfig, item_trait: syn::ItemTrait, @@ -99,7 +100,8 @@ impl InkItemTrait { &self.item.ident } - /// Returns an iterator yielding the ink! specific items of the ink! trait definition. + /// Returns an iterator yielding the ink! specific items of the ink! trait + /// definition. pub fn iter_items(&self) -> IterInkTraitItems { IterInkTraitItems::new(self) } @@ -146,7 +148,8 @@ impl InkItemTrait { Ok(()) } - /// Returns `Ok` if all trait items respects the requirements for an ink! trait definition. + /// Returns `Ok` if all trait items respects the requirements for an ink! + /// trait definition. /// /// # Errors /// @@ -156,9 +159,11 @@ impl InkItemTrait { /// - macros definitions or usages /// - unknown token sequences (verbatim) /// - methods with default implementations - /// - If the trait contains methods which do not respect the ink! trait definition requirements: - /// - All trait methods need to be declared as either `#[ink(message)]` or `#[ink(constructor)]` - /// and need to respect their respective rules. + /// - If the trait contains methods which do not respect the ink! trait + /// definition requirements: + /// - All trait methods need to be declared as either `#[ink(message)]` + /// or `#[ink(constructor)]` and need to respect their respective + /// rules. /// /// # Note /// @@ -204,15 +209,16 @@ impl InkItemTrait { Ok(()) } - /// Analyses an ink! method that can be either an ink! message or constructor. + /// Analyses an ink! method that can be either an ink! message or + /// constructor. /// /// # Errors /// /// - If the method declared as `unsafe`, `const` or `async`. /// - If the method has some explicit API. /// - If the method is variadic or has generic parameters. - /// - If the method does not respect the properties of either an - /// ink! message or ink! constructor. + /// - If the method does not respect the properties of either an ink! + /// message or ink! constructor. fn analyse_trait_method(method: &syn::TraitItemMethod) -> Result<()> { if let Some(default_impl) = &method.default { return Err(format_err_spanned!( @@ -320,18 +326,19 @@ impl InkItemTrait { /// Extract selectors for ink! trait constructors and messages. /// - /// The composed or manually specified selectors are stored into the provided - /// hash tables for later look-up when querying ink! constructors or messages. - /// This way we are more flexible with regard to the underlying structures of the IR. + /// The composed or manually specified selectors are stored into the + /// provided hash tables for later look-up when querying ink! + /// constructors or messages. This way we are more flexible with regard + /// to the underlying structures of the IR. /// - /// In this step we assume that all sanitation checks have taken place prior so - /// instead of returning errors we simply panic upon failures. + /// In this step we assume that all sanitation checks have taken place prior + /// so instead of returning errors we simply panic upon failures. /// /// # Errors /// - /// Returns an error if there are overlapping selectors for ink! constructors - /// or ink! messages. Note that overlaps between ink! constructor and message - /// selectors are allowed. + /// Returns an error if there are overlapping selectors for ink! + /// constructors or ink! messages. Note that overlaps between ink! + /// constructor and message selectors are allowed. fn extract_selectors( config: &TraitDefinitionConfig, item_trait: &syn::ItemTrait, diff --git a/crates/lang/ir/src/ir/trait_def/item/trait_item.rs b/crates/lang/ir/src/ir/trait_def/item/trait_item.rs index 9fddf5cbd84..7c326efd3ab 100644 --- a/crates/lang/ir/src/ir/trait_def/item/trait_item.rs +++ b/crates/lang/ir/src/ir/trait_def/item/trait_item.rs @@ -72,7 +72,8 @@ impl<'a> InkTraitMessage<'a> { Self { item } } - /// Analyses and extracts the ink! and non-ink! attributes of an ink! trait message. + /// Analyses and extracts the ink! and non-ink! attributes of an ink! trait + /// message. pub(super) fn extract_attributes( span: Span, attrs: &[syn::Attribute], @@ -114,7 +115,8 @@ impl<'a> InkTraitMessage<'a> { /// Returns the `self` receiver of the ink! trait message. /// - /// Returns `Ref` for `&self` messages and `RefMut` for `&mut self` messages. + /// Returns `Ref` for `&self` messages and `RefMut` for `&mut self` + /// messages. pub fn receiver(&self) -> Receiver { match self.item.sig.inputs.iter().next() { Some(syn::FnArg::Receiver(receiver)) => { @@ -147,13 +149,14 @@ impl<'a> InkTraitMessage<'a> { &self.item.sig.ident } - /// Returns a local ID unique to the ink! trait definition of the ink! trait message. + /// Returns a local ID unique to the ink! trait definition of the ink! trait + /// message. /// /// # Note /// - /// It is a compile error if two ink! trait messages share the same local ID. - /// Although the above scenario is very unlikely since the local ID is computed - /// solely by the identifier of the ink! message. + /// It is a compile error if two ink! trait messages share the same local + /// ID. Although the above scenario is very unlikely since the local ID + /// is computed solely by the identifier of the ink! message. pub fn local_id(&self) -> u32 { utils::local_message_id(self.ident()) } diff --git a/crates/lang/ir/src/ir/trait_def/mod.rs b/crates/lang/ir/src/ir/trait_def/mod.rs index 220038af0d1..0f0c2034ac9 100644 --- a/crates/lang/ir/src/ir/trait_def/mod.rs +++ b/crates/lang/ir/src/ir/trait_def/mod.rs @@ -40,7 +40,8 @@ pub struct InkTraitDefinition { } impl InkTraitDefinition { - /// Returns `Ok` if the input matches all requirements for an ink! trait definition. + /// Returns `Ok` if the input matches all requirements for an ink! trait + /// definition. pub fn new(config: TokenStream2, input: TokenStream2) -> Result { let parsed_config = syn::parse2::(config)?; let parsed_item = syn::parse2::(input)?; diff --git a/crates/lang/ir/src/ir/trait_def/tests.rs b/crates/lang/ir/src/ir/trait_def/tests.rs index 40caa5249b9..3276d3caa4f 100644 --- a/crates/lang/ir/src/ir/trait_def/tests.rs +++ b/crates/lang/ir/src/ir/trait_def/tests.rs @@ -14,7 +14,8 @@ use super::*; -/// Checks if the token stream in `$trait_def` results in the expected error message. +/// Checks if the token stream in `$trait_def` results in the expected error +/// message. macro_rules! assert_ink_trait_eq_err { ( error: $err_str:literal, $($trait_def:tt)* ) => { assert_eq!( diff --git a/crates/lang/ir/src/ir/utils.rs b/crates/lang/ir/src/ir/utils.rs index a075f9432c9..c1d4de3b167 100644 --- a/crates/lang/ir/src/ir/utils.rs +++ b/crates/lang/ir/src/ir/utils.rs @@ -17,12 +17,13 @@ use crate::format_err; use proc_macro2::Span; use syn::spanned::Spanned as _; -/// Ensures that the given visibility is `pub` and otherwise returns an appropriate error. +/// Ensures that the given visibility is `pub` and otherwise returns an +/// appropriate error. /// /// # Note /// -/// The `name` parameter is given to improve the resulting error message. It denotes the -/// entity which cannot have non-public visibility. +/// The `name` parameter is given to improve the resulting error message. It +/// denotes the entity which cannot have non-public visibility. pub fn ensure_pub_visibility( name: &str, parent_span: Span, @@ -49,7 +50,8 @@ pub fn ensure_pub_visibility( /// # Note /// /// - The returned value is equal to the selector of the message identifier. -/// - Used from within ink! trait definitions as well as ink! trait implementation blocks. +/// - Used from within ink! trait definitions as well as ink! trait +/// implementation blocks. pub fn local_message_id(ident: &syn::Ident) -> u32 { let input = ident.to_string().into_bytes(); let selector = Selector::compute(&input); diff --git a/crates/lang/ir/src/lib.rs b/crates/lang/ir/src/lib.rs index 0be21bf5109..4b289d0e233 100644 --- a/crates/lang/ir/src/lib.rs +++ b/crates/lang/ir/src/lib.rs @@ -17,9 +17,10 @@ //! This module defines everything the ink! procedural macro needs in order to //! parse, analyze and generate code for ink! smart contracts. //! -//! The entry point for every ink! smart contract is the [`Contract`](`crate::ir::Contract`) -//! with its [`Config`](`crate::ir::Config`) provided in the initial invocation at -//! `#[ink::contract(... configuration ...)]`. +//! The entry point for every ink! smart contract is the +//! [`Contract`](`crate::ir::Contract`) with its [`Config`](`crate::ir::Config`) +//! provided in the initial invocation at `#[ink::contract(... configuration +//! ...)]`. //! //! The ink! IR tries to stay close to the original Rust syntactic structure. //! All ink! definitions of an ink! smart contract are always defined within diff --git a/crates/lang/ir/src/literal.rs b/crates/lang/ir/src/literal.rs index 7acb5e33a73..d5e0349976e 100644 --- a/crates/lang/ir/src/literal.rs +++ b/crates/lang/ir/src/literal.rs @@ -17,7 +17,8 @@ mod private { pub struct Sealed; } -/// Used to convert literal values into their hex representations for code generation. +/// Used to convert literal values into their hex representations for code +/// generation. pub trait HexLiteral { /// Shared implementation details. /// @@ -31,18 +32,22 @@ pub trait HexLiteral { sealed: private::Sealed, ) -> syn::LitInt; - /// Converts the given value into a hex represented literal with type suffix. + /// Converts the given value into a hex represented literal with type + /// suffix. fn hex_suffixed(self) -> syn::LitInt; - /// Converts the given value into a hex represented literal without type suffix. + /// Converts the given value into a hex represented literal without type + /// suffix. fn hex_unsuffixed(self) -> syn::LitInt; - /// Converts the given value into a hex represented literal with type suffix. + /// Converts the given value into a hex represented literal with type + /// suffix. /// /// The resulting hex encoded literal is padded with zeros. fn hex_padded_suffixed(self) -> syn::LitInt; - /// Converts the given value into a hex represented literal without type suffix. + /// Converts the given value into a hex represented literal without type + /// suffix. /// /// The resulting hex encoded literal is padded with zeros. fn hex_padded_unsuffixed(self) -> syn::LitInt; diff --git a/crates/lang/macro/src/lib.rs b/crates/lang/macro/src/lib.rs index 203d8ff141e..26243e1edf6 100644 --- a/crates/lang/macro/src/lib.rs +++ b/crates/lang/macro/src/lib.rs @@ -49,7 +49,8 @@ pub fn blake2x256(input: TokenStream) -> TokenStream { blake2b::generate_blake2x256_hash(input.into()).into() } -/// Computes the ink! selector of the string and expands into its `u32` representation. +/// Computes the ink! selector of the string and expands into its `u32` +/// representation. /// /// # Note /// @@ -69,7 +70,8 @@ pub fn selector_id(input: TokenStream) -> TokenStream { selector::generate_selector_id(input.into()).into() } -/// Computes the ink! selector of the string and expands into its byte representation. +/// Computes the ink! selector of the string and expands into its byte +/// representation. /// /// # Note /// @@ -94,9 +96,9 @@ pub fn selector_bytes(input: TokenStream) -> TokenStream { /// If you are a beginner trying to learn ink! we recommend you to check out /// our extensive [ink! workshop](https://docs.substrate.io/tutorials/v3/ink-workshop/pt1). /// -/// **Note:** In all below examples we will be using `ink_lang` crate aliased as just `ink`. -/// You can do this yourself by adding the following line to your code: -/// `use ink_lang as ink;` +/// **Note:** In all below examples we will be using `ink_lang` crate aliased as +/// just `ink`. You can do this yourself by adding the following line +/// to your code: `use ink_lang as ink;` /// /// # Description /// @@ -116,8 +118,8 @@ pub fn selector_bytes(input: TokenStream) -> TokenStream { /// /// ## Header Arguments /// -/// The `#[ink::contract]` macro can be provided with some additional comma-separated -/// header arguments: +/// The `#[ink::contract]` macro can be provided with some additional +/// comma-separated header arguments: /// /// - `dynamic_storage_allocator: bool` /// @@ -126,13 +128,14 @@ pub fn selector_bytes(input: TokenStream) -> TokenStream { /// - `true`: Use the dynamic storage allocator provided by ink!. /// - `false`: Do NOT use the dynamic storage allocator provided by ink!. /// -/// This feature is generally only needed for smart contracts that try to model -/// their data in a way that contains storage entities within other storage -/// entities. +/// This feature is generally only needed for smart contracts that try to +/// model their data in a way that contains storage entities within other +/// storage entities. /// -/// Contract writers should try to write smart contracts that do not depend on the -/// dynamic storage allocator since enabling it comes at a cost of increased Wasm -/// file size. Although it will enable interesting use cases. Use it with care! +/// Contract writers should try to write smart contracts that do not depend +/// on the dynamic storage allocator since enabling it comes at a cost of +/// increased Wasm file size. Although it will enable interesting use cases. +/// Use it with care! /// /// An example for this is the following type that could potentially be used /// within a contract's storage struct definition: @@ -166,17 +169,18 @@ pub fn selector_bytes(input: TokenStream) -> TokenStream { /// - `compile_as_dependency: bool` /// /// Tells the ink! code generator to **always** or **never** -/// compile the smart contract as if it was used as a dependency of another ink! -/// smart contract. +/// compile the smart contract as if it was used as a dependency of another +/// ink! smart contract. /// /// Normally this flag is only really useful for ink! developers who /// want to inspect code generation of ink! smart contracts. -/// The author is not aware of any particular practical use case for users that -/// makes use of this flag but contract writers are encouraged to disprove this. +/// The author is not aware of any particular practical use case for users +/// that makes use of this flag but contract writers are encouraged to +/// disprove this. /// /// Note that it is recommended to make use of the built-in crate feature -/// `ink-as-dependency` to flag smart contract dependencies listed in a contract's -/// `Cargo.toml` as actual dependencies to ink!. +/// `ink-as-dependency` to flag smart contract dependencies listed in a +/// contract's `Cargo.toml` as actual dependencies to ink!. /// /// **Usage Example:** /// ``` @@ -195,17 +199,20 @@ pub fn selector_bytes(input: TokenStream) -> TokenStream { /// } /// ``` /// -/// **Default value:** Depends on the crate feature propagation of `Cargo.toml`. +/// **Default value:** Depends on the crate feature propagation of +/// `Cargo.toml`. /// /// - `env: impl Environment` /// -/// Tells the ink! code generator which environment to use for the ink! smart contract. -/// The environment must implement the `Environment` (defined in `ink_env`) trait and provides -/// all the necessary fundamental type definitions for `Balance`, `AccountId` etc. +/// Tells the ink! code generator which environment to use for the ink! +/// smart contract. The environment must implement the `Environment` +/// (defined in `ink_env`) trait and provides all the necessary fundamental +/// type definitions for `Balance`, `AccountId` etc. /// -/// When using a custom `Environment` implementation for a smart contract all types -/// that it exposes to the ink! smart contract and the mirrored types used in the runtime -/// must be aligned with respect to SCALE encoding and semantics. +/// When using a custom `Environment` implementation for a smart contract +/// all types that it exposes to the ink! smart contract and the mirrored +/// types used in the runtime must be aligned with respect to SCALE encoding +/// and semantics. /// /// **Usage Example:** /// @@ -224,8 +231,8 @@ pub fn selector_bytes(input: TokenStream) -> TokenStream { /// type ChainExtension = ::ink_env::NoChainExtension; /// } /// ``` -/// A user might implement their ink! smart contract using the above custom `Environment` -/// implementation as demonstrated below: +/// A user might implement their ink! smart contract using the above custom +/// `Environment` implementation as demonstrated below: /// ``` /// # use ink_lang as ink; /// #[ink::contract(env = MyEnvironment)] @@ -266,9 +273,10 @@ pub fn selector_bytes(input: TokenStream) -> TokenStream { /// /// - There must be exactly one `#[ink(storage)]` struct. /// -/// This struct defines the layout of the storage that the ink! smart contract operates on. -/// The user is able to use a variety of built-in facilities, combine them in various ways -/// or even provide their own implementations of storage data structures. +/// This struct defines the layout of the storage that the ink! smart +/// contract operates on. The user is able to use a variety of built-in +/// facilities, combine them in various ways or even provide their own +/// implementations of storage data structures. /// /// For more information visit the `ink_storage` crate documentation. /// @@ -293,14 +301,15 @@ pub fn selector_bytes(input: TokenStream) -> TokenStream { /// /// - There must be at least one `#[ink(constructor)]` defined method. /// -/// Methods flagged with `#[ink(constructor)]` are special in that they are dispatchable -/// upon contract instantiation. A contract may define multiple such constructors which -/// allow users of the contract to instantiate a contract in multiple different ways. +/// Methods flagged with `#[ink(constructor)]` are special in that they are +/// dispatchable upon contract instantiation. A contract may define multiple +/// such constructors which allow users of the contract to instantiate a +/// contract in multiple different ways. /// /// **Example:** /// -/// Given the `Flipper` contract definition above we add an `#[ink(constructor)]` -/// as follows: +/// Given the `Flipper` contract definition above we add an +/// `#[ink(constructor)]` as follows: /// /// ``` /// # use ink_lang as ink; @@ -323,21 +332,23 @@ pub fn selector_bytes(input: TokenStream) -> TokenStream { /// /// - There must be at least one `#[ink(message)]` defined method. /// -/// Methods flagged with `#[ink(message)]` are special in that they are dispatchable -/// upon contract invocation. The set of ink! messages defined for an ink! smart contract -/// define its API surface with which users are allowed to interact. +/// Methods flagged with `#[ink(message)]` are special in that they are +/// dispatchable upon contract invocation. The set of ink! messages defined +/// for an ink! smart contract define its API surface with which users are +/// allowed to interact. /// /// An ink! smart contract can have multiple such ink! messages defined. /// /// **Note:** /// -/// - An ink! message with a `&self` receiver may only read state whereas an ink! message -/// with a `&mut self` receiver may mutate the contract's storage. +/// - An ink! message with a `&self` receiver may only read state whereas an +/// ink! message with a `&mut self` receiver may mutate the contract's +/// storage. /// /// **Example:** /// -/// Given the `Flipper` contract definition above we add some `#[ink(message)]` definitions -/// as follows: +/// Given the `Flipper` contract definition above we add some +/// `#[ink(message)]` definitions as follows: /// /// ``` /// # use ink_lang as ink; @@ -369,12 +380,12 @@ pub fn selector_bytes(input: TokenStream) -> TokenStream { /// /// **Payable Messages:** /// -/// An ink! message by default will reject calls that additional fund the smart contract. -/// Authors of ink! smart contracts can make an ink! message payable by adding the `payable` -/// flag to it. An example below: +/// An ink! message by default will reject calls that additional fund the +/// smart contract. Authors of ink! smart contracts can make an ink! message +/// payable by adding the `payable` flag to it. An example below: /// -/// Note that ink! constructors are always implicitly payable and thus cannot be flagged -/// as such. +/// Note that ink! constructors are always implicitly payable and thus +/// cannot be flagged as such. /// /// ``` /// # use ink_lang as ink; @@ -407,12 +418,14 @@ pub fn selector_bytes(input: TokenStream) -> TokenStream { /// /// **Controlling the messages selector:** /// -/// Every ink! message and ink! constructor has a unique selector with which the -/// message or constructor can be uniquely identified within the ink! smart contract. -/// These selectors are mainly used to drive the contract's dispatch upon calling it. +/// Every ink! message and ink! constructor has a unique selector with which +/// the message or constructor can be uniquely identified within the ink! +/// smart contract. These selectors are mainly used to drive the contract's +/// dispatch upon calling it. /// -/// An ink! smart contract author can control the selector of an ink! message or ink! -/// constructor using the `selector` flag. An example is shown below: +/// An ink! smart contract author can control the selector of an ink! +/// message or ink! constructor using the `selector` flag. An example is +/// shown below: /// /// ``` /// # use ink_lang as ink; @@ -431,14 +444,14 @@ pub fn selector_bytes(input: TokenStream) -> TokenStream { /// /// # /// Flips the current value. /// # #[ink(message)] -/// # #[ink(selector = 0xCAFEBABE)] // You can either specify selector out-of-line. -/// # pub fn flip(&mut self) { +/// # #[ink(selector = 0xCAFEBABE)] // You can either specify selector +/// out-of-line. # pub fn flip(&mut self) { /// # self.value = !self.value; /// # } /// # /// /// Returns the current value. -/// #[ink(message, selector = 0xFEEDBEEF)] // ... or specify selector inline. -/// pub fn get(&self) -> bool { +/// #[ink(message, selector = 0xFEEDBEEF)] // ... or specify selector +/// inline. pub fn get(&self) -> bool { /// self.value /// } /// } @@ -447,8 +460,8 @@ pub fn selector_bytes(input: TokenStream) -> TokenStream { /// /// ## Interacting with the Contract Executor /// -/// The `ink_env` crate provides facilities to interact with the contract executor that -/// connects ink! smart contracts with the outer world. +/// The `ink_env` crate provides facilities to interact with the contract +/// executor that connects ink! smart contracts with the outer world. /// /// For example it is possible to query the current call's caller via: /// ``` @@ -459,8 +472,8 @@ pub fn selector_bytes(input: TokenStream) -> TokenStream { /// # }).unwrap(); /// ``` /// -/// However, ink! provides a much simpler way to interact with the contract executor -/// via its environment accessor. An example below: +/// However, ink! provides a much simpler way to interact with the contract +/// executor via its environment accessor. An example below: /// /// ``` /// # use ink_lang as ink; @@ -492,12 +505,12 @@ pub fn selector_bytes(input: TokenStream) -> TokenStream { /// /// ## Events /// -/// An ink! smart contract may define events that it can emit during contract execution. -/// Emitting events can be used by third party tools to query information about a contract's -/// execution and state. +/// An ink! smart contract may define events that it can emit during contract +/// execution. Emitting events can be used by third party tools to query +/// information about a contract's execution and state. /// -/// The following example ink! contract shows how an event `Transferred` is defined and -/// emitted in the `#[ink(constructor)]`. +/// The following example ink! contract shows how an event `Transferred` is +/// defined and emitted in the `#[ink(constructor)]`. /// /// ``` /// # use ink_lang as ink; @@ -588,9 +601,10 @@ pub fn contract(attr: TokenStream, item: TokenStream) -> TokenStream { /// Marks trait definitions to ink! as special ink! trait definitions. /// /// There are some restrictions that apply to ink! trait definitions that -/// this macro checks. Also ink! trait definitions are required to have specialized -/// structure so that the main [`#[ink::contract]`](`macro@crate::contract`) macro can -/// properly generate code for its implementations. +/// this macro checks. Also ink! trait definitions are required to have +/// specialized structure so that the main +/// [`#[ink::contract]`](`macro@crate::contract`) macro can properly generate +/// code for its implementations. /// /// # Example: Definition /// @@ -718,18 +732,20 @@ pub fn test(attr: TokenStream, item: TokenStream) -> TokenStream { /// as well as the definition of some chain extension methods. /// /// The overall structure follows that of a simple Rust trait definition. -/// The error code is defined as an associated type definition of the trait definition. -/// The methods are defined as associated trait methods without implementation. +/// The error code is defined as an associated type definition of the trait +/// definition. The methods are defined as associated trait methods without +/// implementation. /// -/// Chain extension methods must not have a `self` receiver such as `&self` or `&mut self` -/// and must have inputs and output that implement the SCALE encoding and decoding. -/// Their return value follows specific rules that can be altered using the `handle_status` -/// and `returns_result` attributes which are described in more detail below. +/// Chain extension methods must not have a `self` receiver such as `&self` or +/// `&mut self` and must have inputs and output that implement the SCALE +/// encoding and decoding. Their return value follows specific rules that can be +/// altered using the `handle_status` and `returns_result` attributes which are +/// described in more detail below. /// /// # Usage /// -/// Usually the chain extension definition using this procedural macro is provided -/// by the author of the chain extension in a separate crate. +/// Usually the chain extension definition using this procedural macro is +/// provided by the author of the chain extension in a separate crate. /// ink! smart contracts using this chain extension simply depend on this crate /// and use its associated environment definition in order to make use of /// the methods provided by the chain extension. @@ -741,12 +757,18 @@ pub fn test(attr: TokenStream, item: TokenStream) -> TokenStream { /// /// | Attribute | Required | Default Value | Description | /// |:----------|:--------:|:--------------|:-----------:| -/// | `ink(extension = N: u32)` | Yes | - | Determines the unique function ID of the chain extension method. | -/// | `ink(handle_status = flag: bool)` | Optional | `true` | Assumes that the returned status code of the chain extension method always indicates success and therefore always loads and decodes the output buffer of the call. | -/// | `ink(returns_result = flag: bool)` | Optional | `true` | By default chain extension methods are assumed to return a `Result` in the output buffer. Using `returns_result = false` this check is disabled and the chain extension method may return any other type. | -/// -/// As with all ink! attributes multiple of them can either appear in a contiguous list: -/// ``` +/// | `ink(extension = N: u32)` | Yes | - | Determines the unique function ID of +/// the chain extension method. | | `ink(handle_status = flag: bool)` | Optional +/// | `true` | Assumes that the returned status code of the chain extension +/// method always indicates success and therefore always loads and decodes the +/// output buffer of the call. | | `ink(returns_result = flag: bool)` | Optional +/// | `true` | By default chain extension methods are assumed to return a +/// `Result` in the output buffer. Using `returns_result = false` this +/// check is disabled and the chain extension method may return any other type. +/// | +/// +/// As with all ink! attributes multiple of them can either appear in a +/// contiguous list: ``` /// # type Access = i32; /// # use ink_lang as ink; /// # #[ink::chain_extension] @@ -774,51 +796,70 @@ pub fn test(attr: TokenStream, item: TokenStream) -> TokenStream { /// /// Default value: `true` /// -/// By default all chain extension methods return a `Result` where `E: From`. -/// The `Self::ErrorCode` represents the error code of the chain extension. -/// This means that a smart contract calling such a chain extension method first queries the returned -/// status code of the chain extension method and only loads and decodes the output if the returned +/// By default all chain extension methods return a `Result` where `E: +/// From`. The `Self::ErrorCode` represents the error code of +/// the chain extension. This means that a smart contract calling such a chain +/// extension method first queries the returned status code of the chain +/// extension method and only loads and decodes the output if the returned /// status code indicates a successful call. -/// This design was chosen as it is more efficient when no output besides the error -/// code is required for a chain extension call. When designing a chain extension try to utilize the -/// error code to return errors and only use the output buffer for information that does not fit in -/// a single `u32` value. -/// -/// A chain extension method that is flagged with `handle_status = false` assumes that the returned error code -/// will always indicate success. Therefore it will always load and decode the output buffer and loses +/// This design was chosen as it is more efficient when no output besides the +/// error code is required for a chain extension call. When designing a chain +/// extension try to utilize the error code to return errors and only use the +/// output buffer for information that does not fit in a single `u32` value. +/// +/// A chain extension method that is flagged with `handle_status = false` +/// assumes that the returned error code will always indicate success. Therefore +/// it will always load and decode the output buffer and loses /// the `E: From` through the -/// output buffer. Using `returns_result = false` this check is disabled and the chain extension method may return +/// By default chain extension methods are assumed to return a value of type +/// `Result` through the output buffer. Using `returns_result = false` +/// this check is disabled and the chain extension method may return /// any other type. /// -/// Note that if a chain extension method is attributed with `returns_result = false` -/// and with `handle_status = true` it will still return a value of type `Result`. +/// Note that if a chain extension method is attributed with `returns_result = +/// false` and with `handle_status = true` it will still return a value of type +/// `Result`. /// /// ## Usage: `handle_status` and `returns_result` /// -/// Use both `handle_status = false` and `returns_result = false` for the same chain extension method -/// if a call to it may never fail and never returns a `Result` type. +/// Use both `handle_status = false` and `returns_result = false` for the same +/// chain extension method if a call to it may never fail and never returns a +/// `Result` type. /// /// # Combinations /// -/// Due to the possibility to flag a chain extension method with `handle_status` and `returns_result` -/// there are 4 different cases with slightly varying semantics: +/// Due to the possibility to flag a chain extension method with `handle_status` +/// and `returns_result` there are 4 different cases with slightly varying +/// semantics: /// /// | `handle_status` | `returns_result` | Effects | /// |:---------------:|:----------------:|:--------| -/// | `true` | `true` | The chain extension method is required to return a value of type `Result` where `E: From`. A call will always check if the returned status code indicates success and only then will load and decode the value in the output buffer. | -/// | `true` | `false` | The chain extension method may return any non-`Result` type. A call will always check if the returned status code indicates success and only then will load and decode the value in the output buffer. The actual return type of the chain extension method is still `Result` when the chain extension method was defined to return a value of type `T`. | -/// | `false` | `true` | The chain extension method is required to return a value of type `Result`. A call will always assume that the returned status code indicates success and therefore always load and decode the output buffer directly. | -/// | `false` | `false` | The chain extension method may return any non-`Result` type. A call will always assume that the returned status code indicates success and therefore always load and decode the output buffer directly. | +/// | `true` | `true` | The chain extension method is required to return a +/// value of type `Result` where `E: From`. A call will +/// always check if the returned status code indicates success and only then +/// will load and decode the value in the output buffer. | | `true` | `false` | +/// The chain extension method may return any non-`Result` type. A call will +/// always check if the returned status code indicates success and only then +/// will load and decode the value in the output buffer. The actual return type +/// of the chain extension method is still `Result` when the +/// chain extension method was defined to return a value of type `T`. | +/// | `false` | `true` | The chain extension method is required to return a +/// value of type `Result`. A call will always assume that the returned +/// status code indicates success and therefore always load and decode the +/// output buffer directly. | | `false` | `false` | The chain extension method +/// may return any non-`Result` type. A call will always assume that the +/// returned status code indicates success and therefore always load and decode +/// the output buffer directly. | /// /// # Error Code /// -/// Every chain extension defines exactly one `ErrorCode` using the following syntax: +/// Every chain extension defines exactly one `ErrorCode` using the following +/// syntax: /// /// ``` /// use ink_lang as ink; @@ -831,17 +872,18 @@ pub fn test(attr: TokenStream, item: TokenStream) -> TokenStream { /// } /// ``` /// -/// The defined `ErrorCode` must implement `FromStatusCode` which should be implemented as a -/// more or less trivial conversion from the `u32` status code to a `Result<(), Self::ErrorCode>`. -/// The `Ok(())` value indicates that the call to the chain extension method was successful. +/// The defined `ErrorCode` must implement `FromStatusCode` which should be +/// implemented as a more or less trivial conversion from the `u32` status code +/// to a `Result<(), Self::ErrorCode>`. The `Ok(())` value indicates that the +/// call to the chain extension method was successful. /// /// By convention an error code of `0` represents success. /// However, chain extension authors may use whatever suits their needs. /// /// # Example: Definition /// -/// In the below example a chain extension is defined that allows its users to read and write -/// from and to the runtime storage using access privileges: +/// In the below example a chain extension is defined that allows its users to +/// read and write from and to the runtime storage using access privileges: /// /// ``` /// use ink_lang as ink; @@ -954,17 +996,18 @@ pub fn test(attr: TokenStream, item: TokenStream) -> TokenStream { /// # } /// ``` /// -/// All the error types and other utility types used in the chain extension definition -/// above are often required to implement various traits such as SCALE's `Encode` and `Decode` -/// as well as `scale-info`'s `TypeInfo` trait. +/// All the error types and other utility types used in the chain extension +/// definition above are often required to implement various traits such as +/// SCALE's `Encode` and `Decode` as well as `scale-info`'s `TypeInfo` trait. /// /// A full example of the above chain extension definition can be seen /// [here](https://github.com/paritytech/ink/blob/017f71d60799b764425334f86b732cc7b7065fe6/crates/lang/macro/tests/ui/chain_extension/simple.rs). /// /// # Example: Environment /// -/// In order to allow ink! smart contracts to use the above defined chain extension it needs -/// to be integrated into an `Environment` definition as shown below: +/// In order to allow ink! smart contracts to use the above defined chain +/// extension it needs to be integrated into an `Environment` definition as +/// shown below: /// /// ``` /// # type RuntimeReadWrite = i32; @@ -988,18 +1031,19 @@ pub fn test(attr: TokenStream, item: TokenStream) -> TokenStream { /// } /// ``` /// -/// Above we defined the `CustomEnvironment` which defaults to ink!'s `DefaultEnvironment` -/// for all constants and types but the `ChainExtension` type which is assigned to our newly -/// defined chain extension. +/// Above we defined the `CustomEnvironment` which defaults to ink!'s +/// `DefaultEnvironment` for all constants and types but the `ChainExtension` +/// type which is assigned to our newly defined chain extension. /// /// # Example: Usage /// -/// An ink! smart contract can use the above defined chain extension through the `Environment` -/// definition defined in the last example section using the `env` macro parameter as -/// shown below. +/// An ink! smart contract can use the above defined chain extension through the +/// `Environment` definition defined in the last example section using the `env` +/// macro parameter as shown below. /// -/// Note that chain extension methods are accessible through `Self::extension()` or -/// `self.extension()`. For example as in `Self::extension().read(..)` or `self.extension().read(..)`. +/// Note that chain extension methods are accessible through `Self::extension()` +/// or `self.extension()`. For example as in `Self::extension().read(..)` or +/// `self.extension().read(..)`. /// /// ``` /// # use ink_lang as ink; @@ -1135,12 +1179,13 @@ pub fn test(attr: TokenStream, item: TokenStream) -> TokenStream { /// /// # Technical Limitations /// -/// - Due to technical limitations it is not possible to refer to the `ErrorCode` associated type -/// using `Self::ErrorCode` anywhere within the chain extension and its defined methods. -/// Instead chain extension authors should directly use the error code type when required. -/// This limitation might be lifted in future versions of ink!. -/// - It is not possible to declare other chain extension traits as super traits or super -/// chain extensions of another. +/// - Due to technical limitations it is not possible to refer to the +/// `ErrorCode` associated type using `Self::ErrorCode` anywhere within the +/// chain extension and its defined methods. Instead chain extension authors +/// should directly use the error code type when required. This limitation +/// might be lifted in future versions of ink!. +/// - It is not possible to declare other chain extension traits as super traits +/// or super chain extensions of another. #[proc_macro_attribute] pub fn chain_extension(attr: TokenStream, item: TokenStream) -> TokenStream { chain_extension::generate(attr.into(), item.into()).into() diff --git a/crates/lang/src/chain_extension.rs b/crates/lang/src/chain_extension.rs index f3432414a8d..7eebbc762e4 100644 --- a/crates/lang/src/chain_extension.rs +++ b/crates/lang/src/chain_extension.rs @@ -18,12 +18,14 @@ /// /// # Note /// -/// This trait is automatically implemented when using `#[ink::chain_extension]` procedural macro. +/// This trait is automatically implemented when using `#[ink::chain_extension]` +/// procedural macro. pub trait ChainExtensionInstance { /// The type of the chain extension instance. type Instance; - /// Creates a new instance of the chain extension to use methods with method chaining syntax. + /// Creates a new instance of the chain extension to use methods with method + /// chaining syntax. fn instantiate() -> Self::Instance; } @@ -32,7 +34,8 @@ pub trait ChainExtensionInstance { /// Every chain extension defines a set of chain extension methods /// that share a common error code type. pub trait ChainExtension { - /// The error code that determines whether a chain extension method call was successful. + /// The error code that determines whether a chain extension method call was + /// successful. type ErrorCode: ink_env::chain_extension::FromStatusCode; } @@ -55,6 +58,7 @@ impl IsResultType for Result { } mod private { - /// Seals the `IsResultType` trait so that it cannot be implemented outside this module. + /// Seals the `IsResultType` trait so that it cannot be implemented outside + /// this module. pub trait Sealed {} } diff --git a/crates/lang/src/codegen/dispatch/execution.rs b/crates/lang/src/codegen/dispatch/execution.rs index e190cd83ea0..e951c692a88 100644 --- a/crates/lang/src/codegen/dispatch/execution.rs +++ b/crates/lang/src/codegen/dispatch/execution.rs @@ -59,7 +59,8 @@ pub struct ExecuteConstructorConfig { /// /// # Note /// - /// Authors can enable it via `#[ink::contract(dynamic_storage_allocator = true)]`. + /// Authors can enable it via `#[ink::contract(dynamic_storage_allocator = + /// true)]`. pub dynamic_storage_alloc: bool, } @@ -111,7 +112,8 @@ pub struct ExecuteMessageConfig { /// /// # Note /// - /// Authors can enable it via `#[ink::contract(dynamic_storage_allocator = true)]`. + /// Authors can enable it via `#[ink::contract(dynamic_storage_allocator = + /// true)]`. pub dynamic_storage_alloc: bool, } diff --git a/crates/lang/src/env_access.rs b/crates/lang/src/env_access.rs index d3e79a345df..63d5610940a 100644 --- a/crates/lang/src/env_access.rs +++ b/crates/lang/src/env_access.rs @@ -262,9 +262,10 @@ where /// /// # Note /// - /// The Substrate default for the timestamp type is the milliseconds since the - /// Unix epoch. However, this is not guaranteed: the specific timestamp is - /// defined by the chain environment on which this contract runs. + /// The Substrate default for the timestamp type is the milliseconds since + /// the Unix epoch. However, this is not guaranteed: the specific + /// timestamp is defined by the chain environment on which this contract + /// runs. /// /// For more details visit: [`ink_env::block_timestamp`] pub fn block_timestamp(self) -> T::Timestamp { @@ -460,11 +461,12 @@ where /// /// # Parameters /// - /// - `at_refcount`: The `refcount` assumed for the returned `custom_refcount_*` fields. - /// If `None` is supplied the `custom_refcount_*` fields will also be `None`. + /// - `at_refcount`: The `refcount` assumed for the returned + /// `custom_refcount_*` fields. If `None` is supplied the + /// `custom_refcount_*` fields will also be `None`. /// - /// The `current_*` fields of `RentStatus` do **not** consider changes to the code's - /// `refcount` made during the currently running call. + /// The `current_*` fields of `RentStatus` do **not** consider changes to + /// the code's `refcount` made during the currently running call. /// /// # Note /// @@ -957,7 +959,8 @@ where output } - /// Computes the hash of the given SCALE encoded value using the cryptographic hash `H`. + /// Computes the hash of the given SCALE encoded value using the + /// cryptographic hash `H`. /// /// # Example /// @@ -988,8 +991,8 @@ where output } - /// Recovers the compressed ECDSA public key for given `signature` and `message_hash`, - /// and stores the result in `output`. + /// Recovers the compressed ECDSA public key for given `signature` and + /// `message_hash`, and stores the result in `output`. /// /// # Example /// diff --git a/crates/lang/src/reflect/contract.rs b/crates/lang/src/reflect/contract.rs index 7083f56f8b5..af4ab03abcf 100644 --- a/crates/lang/src/reflect/contract.rs +++ b/crates/lang/src/reflect/contract.rs @@ -149,11 +149,12 @@ pub trait ContractEnv { /// /// # Note /// -/// Given an ink! storage struct with identifier `Contract` the ink! codegen produces -/// the ink! root type `Contract` and the ink! reference type `ContractRef`. +/// Given an ink! storage struct with identifier `Contract` the ink! codegen +/// produces the ink! root type `Contract` and the ink! reference type +/// `ContractRef`. /// -/// This trait exists so that users can avoid using a generated identifier to refer to -/// the generated reference type of the ink! smart contract. +/// This trait exists so that users can avoid using a generated identifier to +/// refer to the generated reference type of the ink! smart contract. /// /// # Usage /// diff --git a/crates/lang/src/reflect/dispatch.rs b/crates/lang/src/reflect/dispatch.rs index 4a396f631f5..74ade66b4a1 100644 --- a/crates/lang/src/reflect/dispatch.rs +++ b/crates/lang/src/reflect/dispatch.rs @@ -14,13 +14,15 @@ use core::fmt::Display; -/// Reflects the number of dispatchable ink! messages and constructors respectively. +/// Reflects the number of dispatchable ink! messages and constructors +/// respectively. /// /// # Note /// /// - This is automatically implemented by all ink! smart contracts. -/// - All ink! constructors and ink! messages of an ink! smart contract are dispatchables. -/// This explicitly includes ink! messages from ink! trait implementations. +/// - All ink! constructors and ink! messages of an ink! smart contract are +/// dispatchables. This explicitly includes ink! messages from ink! trait +/// implementations. /// /// # Usage /// @@ -65,7 +67,8 @@ pub trait ContractAmountDispatchables { const CONSTRUCTORS: usize; } -/// Reflects the sequence of all dispatchable ink! messages of the ink! smart contract. +/// Reflects the sequence of all dispatchable ink! messages of the ink! smart +/// contract. /// /// # Note /// @@ -111,11 +114,13 @@ pub trait ContractAmountDispatchables { /// } /// ``` pub trait ContractDispatchableMessages { - /// The sequence stores selector IDs of all ink! messages dispatchable by the ink! smart contract. + /// The sequence stores selector IDs of all ink! messages dispatchable by + /// the ink! smart contract. const IDS: [u32; AMOUNT]; } -/// Reflects the sequence of all dispatchable ink! constructors of the ink! smart contract. +/// Reflects the sequence of all dispatchable ink! constructors of the ink! +/// smart contract. /// /// # Note /// @@ -161,7 +166,8 @@ pub trait ContractDispatchableMessages { /// } /// ``` pub trait ContractDispatchableConstructors { - /// The sequence stores selector IDs of all ink! constructors dispatchable by the ink! smart contract. + /// The sequence stores selector IDs of all ink! constructors dispatchable + /// by the ink! smart contract. const IDS: [u32; AMOUNT]; } @@ -244,13 +250,15 @@ pub trait DispatchableMessageInfo { /// The ink! storage struct type. type Storage; - /// The closure that can be used to dispatch into the dispatchable ink! message. + /// The closure that can be used to dispatch into the dispatchable ink! + /// message. /// /// # Note /// - /// We unify `&self` and `&mut self` ink! messages here and always take a `&mut self`. - /// This is mainly done for simplification but also because we can easily convert from - /// `&mut self` to `&self` with our current dispatch codegen architecture. + /// We unify `&self` and `&mut self` ink! messages here and always take a + /// `&mut self`. This is mainly done for simplification but also because + /// we can easily convert from `&mut self` to `&self` with our current + /// dispatch codegen architecture. const CALLABLE: fn(&mut Self::Storage, Self::Input) -> Self::Output; /// Yields `true` if the dispatchable ink! message mutates the ink! storage. @@ -336,7 +344,8 @@ pub trait DispatchableConstructorInfo { /// The ink! storage struct type. type Storage; - /// The closure that can be used to dispatch into the dispatchable ink! constructor. + /// The closure that can be used to dispatch into the dispatchable ink! + /// constructor. const CALLABLE: fn(Self::Input) -> Self::Storage; /// The selectors of the dispatchable ink! constructor. @@ -345,12 +354,14 @@ pub trait DispatchableConstructorInfo { const LABEL: &'static str; } -/// Generated type used to decode all dispatchable ink! messages of the ink! smart contract. +/// Generated type used to decode all dispatchable ink! messages of the ink! +/// smart contract. /// /// # Note /// -/// The decoder follows the ink! calling ABI where all ink! message calls start with -/// 4 bytes dedicated to the ink! message selector followed by the SCALE encoded parameters. +/// The decoder follows the ink! calling ABI where all ink! message calls start +/// with 4 bytes dedicated to the ink! message selector followed by the SCALE +/// encoded parameters. /// /// # Usage /// @@ -425,12 +436,14 @@ pub trait ContractMessageDecoder { type Type: scale::Decode + ExecuteDispatchable; } -/// Generated type used to decode all dispatchable ink! constructors of the ink! smart contract. +/// Generated type used to decode all dispatchable ink! constructors of the ink! +/// smart contract. /// /// # Note /// -/// The decoder follows the ink! calling ABI where all ink! constructor calls start with -/// 4 bytes dedicated to the ink! constructor selector followed by the SCALE encoded parameters. +/// The decoder follows the ink! calling ABI where all ink! constructor calls +/// start with 4 bytes dedicated to the ink! constructor selector followed by +/// the SCALE encoded parameters. /// /// # Usage /// @@ -557,19 +570,24 @@ impl From for scale::Error { } } -/// Decodes an ink! dispatch input into a known selector and its expected parameters. +/// Decodes an ink! dispatch input into a known selector and its expected +/// parameters. /// /// # Note /// -/// This trait is automatically implemented for ink! message and constructor decoders. +/// This trait is automatically implemented for ink! message and constructor +/// decoders. /// /// # Errors /// /// Returns an error if any of the decode steps failed: /// -/// - `InvalidSelector`: The first four bytes could not properly decoded into the selector. -/// - `UnknownSelector`: The decoded selector did not match any of the expected ones. -/// - `InvalidParameters`: Failed to decoded the parameters for the selected dispatchable. +/// - `InvalidSelector`: The first four bytes could not properly decoded into +/// the selector. +/// - `UnknownSelector`: The decoded selector did not match any of the expected +/// ones. +/// - `InvalidParameters`: Failed to decoded the parameters for the selected +/// dispatchable. /// /// The other dispatch errors are handled by other structures usually. /// diff --git a/crates/lang/src/reflect/trait_def/info.rs b/crates/lang/src/reflect/trait_def/info.rs index 8745c1b2daf..e110934b2aa 100644 --- a/crates/lang/src/reflect/trait_def/info.rs +++ b/crates/lang/src/reflect/trait_def/info.rs @@ -28,18 +28,18 @@ /// /// # Note /// -/// - The `TraitMessageInfo` is implemented by the -/// automatically generated ink! trait definition information object -/// associated to the ink! trait definition at hand. -/// - For every ink! trait message defined by the ink! trait definition -/// the associated ink! trait definition information object implements -/// this trait given the `TRAIT_LOCAL_MESSAGE_ID` of each ink! trait -/// message respectively. -/// - The local IDs uniquely identifying all the ink! trait messages -/// of the ink! trait definition are computed solely using the Rust -/// identifier of the ink! trait message which can be derived from -/// ink! implementation blocks in order to query the information -/// stored by this ink! trait information object trait implementation. +/// - The `TraitMessageInfo` is implemented by the automatically +/// generated ink! trait definition information object associated to the ink! +/// trait definition at hand. +/// - For every ink! trait message defined by the ink! trait definition the +/// associated ink! trait definition information object implements this trait +/// given the `TRAIT_LOCAL_MESSAGE_ID` of each ink! trait message +/// respectively. +/// - The local IDs uniquely identifying all the ink! trait messages of the ink! +/// trait definition are computed solely using the Rust identifier of the ink! +/// trait message which can be derived from ink! implementation blocks in +/// order to query the information stored by this ink! trait information +/// object trait implementation. /// /// # Usage /// @@ -126,7 +126,8 @@ /// } /// ``` pub trait TraitMessageInfo { - /// Is `true` if the ink! trait message has been annotated with `#[ink(payable)]`. + /// Is `true` if the ink! trait message has been annotated with + /// `#[ink(payable)]`. const PAYABLE: bool; /// The unique selector of the ink! trait message. diff --git a/crates/lang/src/reflect/trait_def/registry.rs b/crates/lang/src/reflect/trait_def/registry.rs index 5f33d2323eb..814fc67a3ad 100644 --- a/crates/lang/src/reflect/trait_def/registry.rs +++ b/crates/lang/src/reflect/trait_def/registry.rs @@ -22,17 +22,17 @@ use core::marker::PhantomData; /// /// # Codegen /// -/// - The `#[ink::trait_definition]` procedural macro generates an associated type -/// called `__ink_TraitInfo` for each ink! trait definition. +/// - The `#[ink::trait_definition]` procedural macro generates an associated +/// type called `__ink_TraitInfo` for each ink! trait definition. /// - Furthermore the ink! codegen implements the ink! trait definition for the /// `TraitDefinitionRegistry` with stub implementations for all methods that /// guarantee that they are never called. /// - For every implemented ink! trait definition an ink! trait info object type -/// is generated that is linked to the global `TraitDefinitionRegistry` through -/// the aforementioned `__ink_TraitInfo` associated type. -/// - This trait info object type itself implements various traits each providing -/// useful static reflection information to the rest of the codegen about the ink! -/// trait definition. +/// is generated that is linked to the global `TraitDefinitionRegistry` +/// through the aforementioned `__ink_TraitInfo` associated type. +/// - This trait info object type itself implements various traits each +/// providing useful static reflection information to the rest of the codegen +/// about the ink! trait definition. /// /// # Usage /// diff --git a/crates/lang/tests/unique_topics.rs b/crates/lang/tests/unique_topics.rs index f17837ba763..f1cc090cf05 100644 --- a/crates/lang/tests/unique_topics.rs +++ b/crates/lang/tests/unique_topics.rs @@ -113,8 +113,9 @@ mod my_contract { /// Finds duplicates in a given vector. /// - /// This function has complexity of `O(n * log n)` and no additional memory - /// is required, although the order of items is not preserved. + /// This function has complexity of `O(n * log n)` and no additional + /// memory is required, although the order of items is not + /// preserved. fn has_duplicates>(items: &mut Vec) -> bool { // Sort the vector items.sort_by(|a, b| Ord::cmp(a.as_ref(), b.as_ref())); diff --git a/crates/metadata/src/layout/mod.rs b/crates/metadata/src/layout/mod.rs index ab4fec5bb0a..e29d56c17b3 100644 --- a/crates/metadata/src/layout/mod.rs +++ b/crates/metadata/src/layout/mod.rs @@ -369,7 +369,8 @@ where self.len } - /// Returns the number of cells each element in the array layout consists of. + /// Returns the number of cells each element in the array layout consists + /// of. pub fn cells_per_elem(&self) -> u64 { self.cells_per_elem } @@ -552,7 +553,8 @@ impl EnumLayout where F: Form, { - /// Returns the key where the discriminant is stored to dispatch the variants. + /// Returns the key where the discriminant is stored to dispatch the + /// variants. pub fn dispatch_key(&self) -> &LayoutKey { &self.dispatch_key } diff --git a/crates/metadata/src/lib.rs b/crates/metadata/src/lib.rs index 552bd79a056..2fead8ea8d2 100644 --- a/crates/metadata/src/lib.rs +++ b/crates/metadata/src/lib.rs @@ -61,12 +61,14 @@ use serde::{ /// /// # Note /// -/// Represents the version of the serialized metadata *format*, which is distinct from the version -/// of this crate for Rust semantic versioning compatibility. +/// Represents the version of the serialized metadata *format*, which is +/// distinct from the version of this crate for Rust semantic versioning +/// compatibility. #[derive(Debug, Serialize, Deserialize)] #[allow(clippy::large_enum_variant)] pub enum MetadataVersioned { - /// Version 0 placeholder. Represents the original non-versioned metadata format. + /// Version 0 placeholder. Represents the original non-versioned metadata + /// format. V0(MetadataVersionDeprecated), /// Version 1 of the contract metadata. V1(InkProject), diff --git a/crates/metadata/src/specs.rs b/crates/metadata/src/specs.rs index 30383131f10..1d3232dfea4 100644 --- a/crates/metadata/src/specs.rs +++ b/crates/metadata/src/specs.rs @@ -394,8 +394,8 @@ pub struct MessageSpec { docs: Vec, } -/// Type state for builders to tell that some mandatory state has not yet been set -/// yet or to fail upon setting the same state multiple times. +/// Type state for builders to tell that some mandatory state has not yet been +/// set yet or to fail upon setting the same state multiple times. pub struct Missing(PhantomData S>); mod state { @@ -535,7 +535,8 @@ impl MessageSpecBuilder, M, P, R> { } impl MessageSpecBuilder, P, R> { - /// Sets if the message is mutable, thus taking `&mut self` or not thus taking `&self`. + /// Sets if the message is mutable, thus taking `&mut self` or not thus + /// taking `&self`. pub fn mutates(self, mutates: bool) -> MessageSpecBuilder { MessageSpecBuilder { spec: MessageSpec { @@ -548,7 +549,8 @@ impl MessageSpecBuilder, P, R> { } impl MessageSpecBuilder, R> { - /// Sets if the message is mutable, thus taking `&mut self` or not thus taking `&self`. + /// Sets if the message is mutable, thus taking `&mut self` or not thus + /// taking `&self`. pub fn payable( self, is_payable: bool, diff --git a/crates/prelude/src/lib.rs b/crates/prelude/src/lib.rs index def128e4b74..e72a1cf0bb3 100644 --- a/crates/prelude/src/lib.rs +++ b/crates/prelude/src/lib.rs @@ -14,11 +14,13 @@ //! Data structures to operate on contract memory during contract execution. //! -//! These definitions are useful since we are operating in a `no_std` environment -//! and should be used by all ink! crates instead of directly using `std` or `alloc` -//! crates. If needed we shall instead enhance the exposed types here. +//! These definitions are useful since we are operating in a `no_std` +//! environment and should be used by all ink! crates instead of directly using +//! `std` or `alloc` crates. If needed we shall instead enhance the exposed +//! types here. //! -//! The `ink_prelude` crate guarantees a stable interface between `std` and `no_std` mode. +//! The `ink_prelude` crate guarantees a stable interface between `std` and +//! `no_std` mode. #![cfg_attr(not(feature = "std"), no_std)] diff --git a/crates/primitives/src/key.rs b/crates/primitives/src/key.rs index 4f3c2b0a89a..158dc802227 100644 --- a/crates/primitives/src/key.rs +++ b/crates/primitives/src/key.rs @@ -35,13 +35,13 @@ use scale_info::{ /// # Note /// /// - The storage of an ink! smart contract can be viewed as a key-value store. -/// - In order to manipulate its storage an ink! smart contract is required -/// to indicate the respective cells using this primitive type. +/// - In order to manipulate its storage an ink! smart contract is required to +/// indicate the respective cells using this primitive type. /// - The `Key` type can be compared to a raw pointer and also allows operations /// similar to pointer arithmetic. -/// - Users usually should not have to deal with this low-level primitive themselves -/// and instead use the more high-level primitives provided by the `ink_storage` -/// crate. +/// - Users usually should not have to deal with this low-level primitive +/// themselves and instead use the more high-level primitives provided by the +/// `ink_storage` crate. #[derive(Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] #[repr(transparent)] pub struct Key([u8; 32]); @@ -194,13 +194,15 @@ impl Key { /// /// # Note /// - /// This implementation is heavily optimized for little-endian Wasm platforms. + /// This implementation is heavily optimized for little-endian Wasm + /// platforms. /// /// # Developer Note /// - /// Since we are operating on little-endian we can convert the underlying `[u8; 32]` - /// array to `[u64; 4]`. Since in WebAssembly `u64` is supported natively unlike `u8` - /// it is more efficient to work on chunks of `u8` represented as `u64`. + /// Since we are operating on little-endian we can convert the underlying + /// `[u8; 32]` array to `[u64; 4]`. Since in WebAssembly `u64` is + /// supported natively unlike `u8` it is more efficient to work on + /// chunks of `u8` represented as `u64`. #[cfg(target_endian = "little")] fn add_assign_u64_le(&mut self, rhs: u64) { let words = self.reinterpret_as_u64x4_mut(); @@ -218,13 +220,15 @@ impl Key { /// /// # Note /// - /// This implementation is heavily optimized for little-endian Wasm platforms. + /// This implementation is heavily optimized for little-endian Wasm + /// platforms. /// /// # Developer Note /// - /// Since we are operating on little-endian we can convert the underlying `[u8; 32]` - /// array to `[u64; 4]`. Since in WebAssembly `u64` is supported natively unlike `u8` - /// it is more efficient to work on chunks of `u8` represented as `u64`. + /// Since we are operating on little-endian we can convert the underlying + /// `[u8; 32]` array to `[u64; 4]`. Since in WebAssembly `u64` is + /// supported natively unlike `u8` it is more efficient to work on + /// chunks of `u8` represented as `u64`. #[cfg(target_endian = "little")] fn add_assign_u64_le_using(&self, rhs: u64, result: &mut Key) { let input = self.reinterpret_as_u64x4(); diff --git a/crates/primitives/src/lib.rs b/crates/primitives/src/lib.rs index 4addb36532b..df0a29a60d4 100644 --- a/crates/primitives/src/lib.rs +++ b/crates/primitives/src/lib.rs @@ -14,12 +14,15 @@ //! Utilities in use by ink!. //! -//! These are kept separate from ink core utilities to allow for more dynamic inter-crate dependencies. -//! The main problem is that today Cargo manages crate features on a per-crate basis instead of -//! a per-crate-target basis thus making dependencies from `ink_lang` (or others) to `ink_env` or `ink_storage` impossible. +//! These are kept separate from ink core utilities to allow for more dynamic +//! inter-crate dependencies. The main problem is that today Cargo manages crate +//! features on a per-crate basis instead of a per-crate-target basis thus +//! making dependencies from `ink_lang` (or others) to `ink_env` or +//! `ink_storage` impossible. //! -//! By introducing `ink_primitives` we have a way to share utility components between `ink_env` or `ink_storage` and -//! other parts of the framework, like `ink_lang`. +//! By introducing `ink_primitives` we have a way to share utility components +//! between `ink_env` or `ink_storage` and other parts of the framework, like +//! `ink_lang`. #![cfg_attr(not(feature = "std"), no_std)] diff --git a/crates/storage/benches/bench_binary_heap.rs b/crates/storage/benches/bench_binary_heap.rs index 13551d5614a..d500ca6c430 100644 --- a/crates/storage/benches/bench_binary_heap.rs +++ b/crates/storage/benches/bench_binary_heap.rs @@ -47,17 +47,19 @@ fn test_values(n: u32) -> Vec { mod binary_heap { use super::*; - /// Initialize the contract storage at the given key with the provided values. + /// Initialize the contract storage at the given key with the provided + /// values. /// - /// Use for testing lazy loading of a binary heap: an instance with an associated key which is - /// yet to load any elements from storage. This is the state a binary heap instance will be in - /// at the start of contract execution. + /// Use for testing lazy loading of a binary heap: an instance with an + /// associated key which is yet to load any elements from storage. This + /// is the state a binary heap instance will be in at the start of + /// contract execution. pub fn init_storage(root_key: Key, values: &[u32]) { let heap = from_slice(values); SpreadLayout::push_spread(&heap, &mut KeyPtr::from(root_key)); - // prevents storage for the test heap being cleared when the heap is dropped after each - // benchmark iteration + // prevents storage for the test heap being cleared when the heap is dropped + // after each benchmark iteration ink_env::test::set_clear_storage_disabled(true); } @@ -133,16 +135,16 @@ where /// Strategies for constructing a binary heap instance for a benchmark routine enum NewHeap { - /// Create a binary heap with an empty cache, values at the given key are loaded from storage - /// upon access. + /// Create a binary heap with an empty cache, values at the given key are + /// loaded from storage upon access. /// /// This simulates the state of a binary heap at the beginning of a smart /// contract's execution. Lazy(Key), /// Create a binary heap with all the values loaded into the cache. /// - /// This simulates the state of a binary heap once all elements have been accessed during smart - /// contract execution and loaded into the cache. + /// This simulates the state of a binary heap once all elements have been + /// accessed during smart contract execution and loaded into the cache. Populated(Vec), } @@ -167,7 +169,8 @@ impl NewHeap { } } -/// Define a benchmark for an operation to be run against different size binary heaps +/// Define a benchmark for an operation to be run against different size binary +/// heaps trait Benchmark { fn bench(group: &mut BenchmarkGroup, size: u32, new_heap: NewHeap); } diff --git a/crates/storage/benches/bench_bitstash.rs b/crates/storage/benches/bench_bitstash.rs index 68761b519af..5da462e4218 100644 --- a/crates/storage/benches/bench_bitstash.rs +++ b/crates/storage/benches/bench_bitstash.rs @@ -71,7 +71,8 @@ fn create_large_stash() -> BitStash { mod populated_cache { use super::*; - /// Executes `put` operations on a new `BitStash` exactly `BENCH_ALLOCATIONS` times. + /// Executes `put` operations on a new `BitStash` exactly + /// `BENCH_ALLOCATIONS` times. pub fn fill_bitstash() { let mut stash = BitStash::default(); for _ in 0..BENCH_ALLOCATIONS { @@ -92,7 +93,8 @@ fn bench_populated_cache(c: &mut Criterion) { mod empty_cache { use super::*; - /// Executes `put` operations on a new `BitStash` exactly `BENCH_ALLOCATIONS` times. + /// Executes `put` operations on a new `BitStash` exactly + /// `BENCH_ALLOCATIONS` times. pub fn fill_bitstash() { push_stash(); let mut stash = pull_stash(); @@ -102,9 +104,9 @@ mod empty_cache { } } -/// In this case we lazily instantiate a `BitStash` by first creating and storing -/// into the contract storage. We then load the stash from storage lazily in each -/// benchmark iteration. +/// In this case we lazily instantiate a `BitStash` by first creating and +/// storing into the contract storage. We then load the stash from storage +/// lazily in each benchmark iteration. fn bench_empty_cache(c: &mut Criterion) { let _ = ink_env::test::run_test::(|_| { let mut group = c.benchmark_group("Bench: empty cache"); diff --git a/crates/storage/benches/bench_stash.rs b/crates/storage/benches/bench_stash.rs index 758c2245069..10efe58ae15 100644 --- a/crates/storage/benches/bench_stash.rs +++ b/crates/storage/benches/bench_stash.rs @@ -115,9 +115,9 @@ mod empty_cache { } } -/// In this case we lazily instantiate a `StorageStash` by first `create_and_store`-ing -/// into the contract storage. We then load the stash from storage lazily in each -/// benchmark iteration. +/// In this case we lazily instantiate a `StorageStash` by first +/// `create_and_store`-ing into the contract storage. We then load the stash +/// from storage lazily in each benchmark iteration. fn bench_remove_occupied_empty_cache(c: &mut Criterion) { let _ = ink_env::test::run_test::(|_| { let mut group = c.benchmark_group( diff --git a/crates/storage/benches/bench_vec.rs b/crates/storage/benches/bench_vec.rs index 943a67541f8..67a700536f2 100644 --- a/crates/storage/benches/bench_vec.rs +++ b/crates/storage/benches/bench_vec.rs @@ -161,9 +161,9 @@ mod empty_cache { } } -/// In this case we lazily instantiate a `StorageVec` by first `create_and_store`-ing -/// into the contract storage. We then load the vec from storage lazily in each -/// benchmark iteration. +/// In this case we lazily instantiate a `StorageVec` by first +/// `create_and_store`-ing into the contract storage. We then load the vec from +/// storage lazily in each benchmark iteration. fn bench_clear_empty_cache(c: &mut Criterion) { let _ = ink_env::test::run_test::(|_| { let mut group = c.benchmark_group("Compare: `clear` and `pop_all` (empty cache)"); @@ -175,9 +175,9 @@ fn bench_clear_empty_cache(c: &mut Criterion) { .unwrap(); } -/// In this case we lazily instantiate a `StorageVec` by first `create_and_store`-ing -/// into the contract storage. We then load the vec from storage lazily in each -/// benchmark iteration. +/// In this case we lazily instantiate a `StorageVec` by first +/// `create_and_store`-ing into the contract storage. We then load the vec from +/// storage lazily in each benchmark iteration. fn bench_put_empty_cache(c: &mut Criterion) { let _ = ink_env::test::run_test::(|_| { let mut group = c.benchmark_group("Compare: `set` and `get_mut` (empty cache)"); diff --git a/crates/storage/derive/src/packed_layout.rs b/crates/storage/derive/src/packed_layout.rs index 3195735c9ab..4a20b2a3d46 100644 --- a/crates/storage/derive/src/packed_layout.rs +++ b/crates/storage/derive/src/packed_layout.rs @@ -15,7 +15,8 @@ use proc_macro2::TokenStream as TokenStream2; use quote::quote; -/// Derives `ink_storage`'s `PackedLayout` trait for the given `struct` or `enum`. +/// Derives `ink_storage`'s `PackedLayout` trait for the given `struct` or +/// `enum`. pub fn packed_layout_derive(mut s: synstructure::Structure) -> TokenStream2 { s.bind_with(|_| synstructure::BindStyle::Move) .add_bounds(synstructure::AddBounds::Generics) diff --git a/crates/storage/derive/src/spread_layout.rs b/crates/storage/derive/src/spread_layout.rs index c517027b5d8..efadd9b81d6 100644 --- a/crates/storage/derive/src/spread_layout.rs +++ b/crates/storage/derive/src/spread_layout.rs @@ -58,7 +58,8 @@ fn footprint(s: &synstructure::Structure) -> TokenStream2 { max_n(&variant_footprints[..]) } -/// Generates the tokens for the `SpreadLayout` `REQUIRES_DEEP_CLEAN_UP` constant for the given structure. +/// Generates the tokens for the `SpreadLayout` `REQUIRES_DEEP_CLEAN_UP` +/// constant for the given structure. fn requires_deep_clean_up(s: &synstructure::Structure) -> TokenStream2 { s.variants() .iter() @@ -198,7 +199,8 @@ fn spread_layout_enum_derive(s: &synstructure::Structure) -> TokenStream2 { }) } -/// Derives `ink_storage`'s `SpreadLayout` trait for the given `struct` or `enum`. +/// Derives `ink_storage`'s `SpreadLayout` trait for the given `struct` or +/// `enum`. pub fn spread_layout_derive(mut s: synstructure::Structure) -> TokenStream2 { s.bind_with(|_| synstructure::BindStyle::Move) .add_bounds(synstructure::AddBounds::Generics) diff --git a/crates/storage/src/alloc/init.rs b/crates/storage/src/alloc/init.rs index 52019562594..33e1025bce8 100644 --- a/crates/storage/src/alloc/init.rs +++ b/crates/storage/src/alloc/init.rs @@ -135,14 +135,16 @@ impl DynamicAllocatorState { } } - /// Runs the closure on the global instance for the dynamic storage allocator. + /// Runs the closure on the global instance for the dynamic storage + /// allocator. /// - /// Will automatically initialize the global allocator instance if it has not - /// yet been initialized. + /// Will automatically initialize the global allocator instance if it has + /// not yet been initialized. /// /// # Panics /// - /// If the global dynamic storage allocator instance has already been finalized. + /// If the global dynamic storage allocator instance has already been + /// finalized. pub fn on_instance(&mut self, f: F) -> R where F: FnOnce(&mut DynamicAllocator) -> R, diff --git a/crates/storage/src/alloc/mod.rs b/crates/storage/src/alloc/mod.rs index 5b0b8c1221d..06288ccda10 100644 --- a/crates/storage/src/alloc/mod.rs +++ b/crates/storage/src/alloc/mod.rs @@ -23,18 +23,18 @@ //! # Simplification //! //! The contracts pallet is using 256-bit keys for identifying storage cells. -//! This implies a storage space of `2^256` cells which is big enough to say that -//! there are probably never going to happen collisions anywhere at any time -//! if keys are chosen randomly. Using the built-in crypto hashers on unique -//! input we can be sure that there are never going to be collisions in this -//! space of `2^256` cells. +//! This implies a storage space of `2^256` cells which is big enough to say +//! that there are probably never going to happen collisions anywhere at any +//! time if keys are chosen randomly. Using the built-in crypto hashers on +//! unique input we can be sure that there are never going to be collisions in +//! this space of `2^256` cells. //! //! This way we can reduce the problem of finding another region in our storage //! that fits certain requirements (e.g. a minimum size) to the problem of //! finding another uniform slot. Since we are on 32-bit WebAssembly we have //! memory limitations that make it impractical to have more than `2^32` dynamic -//! allocated entities, so we can create another limitation for having a total of -//! `2^32` dynamic allocations at any point in time. +//! allocated entities, so we can create another limitation for having a total +//! of `2^32` dynamic allocations at any point in time. //! This enables us to have 32-bit keys instead of 256-bit keys. //! //! We can convert such 32-bit keys (represented by e.g. a `u32`) into 256-bit @@ -55,8 +55,8 @@ //! for a dynamic allocation would mean that for every 256 consecutively //! occupied dynamic allocations there was a contract storage lookup required. //! This might seem a lot but given that there could be thousands or -//! tens of thousands of dynamic allocations at any given time this might not scale -//! well. +//! tens of thousands of dynamic allocations at any given time this might not +//! scale well. //! For the reason of improving scalability we added another vector: the //! so-called `set_bits` vector. //! In this vector every `u8` element densely stores the number of set bits @@ -104,9 +104,10 @@ pub fn free(allocation: DynamicAllocation) { /// automatically being use in the correct order and way by the generated code. /// /// - The `phase` parameter describes for which execution phase the dynamic -/// storage allocator needs to be initialized since this is different -/// in contract instantiations and calls. -/// - This has to be issued before the first interaction with the global allocator. +/// storage allocator needs to be initialized since this is different in +/// contract instantiations and calls. +/// - This has to be issued before the first interaction with the global +/// allocator. /// - The actual instantiation will happen only upon the first interaction with /// the global allocator, e.g. using the `alloc` or `free` calls. Until then, /// it remains uninitialized. diff --git a/crates/storage/src/collections/binary_heap/children_vec.rs b/crates/storage/src/collections/binary_heap/children_vec.rs index d4ef8d4ac27..909a9a4a94d 100644 --- a/crates/storage/src/collections/binary_heap/children_vec.rs +++ b/crates/storage/src/collections/binary_heap/children_vec.rs @@ -44,9 +44,10 @@ where T: PackedLayout + Ord, { /// The number of elements stored in the heap. - /// We cannot use the length of the storage vector, since each entry (i.e. each - /// `Children` object) in the vector contains two child elements (except the root - /// element which occupies a `Children` object on its own. + /// We cannot use the length of the storage vector, since each entry (i.e. + /// each `Children` object) in the vector contains two child elements + /// (except the root element which occupies a `Children` object on its + /// own. len: Lazy, /// The underlying storage vec containing the `Children`. children: StorageVec>, @@ -99,7 +100,8 @@ where } } - /// Returns the number of elements in the heap, also referred to as its length. + /// Returns the number of elements in the heap, also referred to as its + /// length. #[inline] pub fn len(&self) -> u32 { *self.len @@ -168,7 +170,8 @@ where self.pop() } - /// Returns an iterator yielding shared references to all elements of the heap. + /// Returns an iterator yielding shared references to all elements of the + /// heap. /// /// # Note /// @@ -232,7 +235,8 @@ where /// Returns information about the child at the heap index if any. /// - /// The returned `ChildInfoMut` contains a mutable reference to the value `T`. + /// The returned `ChildInfoMut` contains a mutable reference to the value + /// `T`. pub(super) fn get_child_mut(&mut self, index: u32) -> Option> { let storage_index = children::get_children_storage_index(index); let child_pos = children::get_child_pos(index); @@ -278,7 +282,8 @@ where .expect("children must exist at last_index"); let popped_val = info.child.take(); if info.child_count == 1 { - // if both children are non-existent the entire `Children` object can be removed + // if both children are non-existent the entire `Children` object can be + // removed self.children.pop(); } popped_val diff --git a/crates/storage/src/collections/binary_heap/mod.rs b/crates/storage/src/collections/binary_heap/mod.rs index c8601bc4883..716a0cd24a3 100644 --- a/crates/storage/src/collections/binary_heap/mod.rs +++ b/crates/storage/src/collections/binary_heap/mod.rs @@ -63,7 +63,8 @@ where } } - /// Returns the number of elements in the heap, also referred to as its length. + /// Returns the number of elements in the heap, also referred to as its + /// length. pub fn len(&self) -> u32 { self.elements.len() } @@ -78,7 +79,8 @@ impl BinaryHeap where T: PackedLayout + Ord, { - /// Returns an iterator yielding shared references to all elements of the heap. + /// Returns an iterator yielding shared references to all elements of the + /// heap. /// /// # Note /// @@ -102,7 +104,8 @@ where /// /// # Note: /// - /// If the `PeekMut` value is leaked, the heap may be in an inconsistent state. + /// If the `PeekMut` value is leaked, the heap may be in an inconsistent + /// state. /// /// # Example /// @@ -208,11 +211,13 @@ where T: 'a + PackedLayout + Ord, { heap: &'a mut BinaryHeap, - /// If `true`, on `drop()` will sift the peeked value down the tree if after mutation it is no - /// longer the largest value, in order to keep the heap in a consistent state. + /// If `true`, on `drop()` will sift the peeked value down the tree if after + /// mutation it is no longer the largest value, in order to keep the + /// heap in a consistent state. /// - /// If the peeked value is consumed via `PeekMut::pop()` then this is set to false in order - /// to prevent a redundant reorganization which would already have happened via `BinaryHeap::pop()`. + /// If the peeked value is consumed via `PeekMut::pop()` then this is set to + /// false in order to prevent a redundant reorganization which would + /// already have happened via `BinaryHeap::pop()`. sift: bool, } diff --git a/crates/storage/src/collections/binary_heap/reverse.rs b/crates/storage/src/collections/binary_heap/reverse.rs index 1ae64edbe61..f0b57c66fea 100644 --- a/crates/storage/src/collections/binary_heap/reverse.rs +++ b/crates/storage/src/collections/binary_heap/reverse.rs @@ -12,13 +12,14 @@ // See the License for the specific language governing permissions and // limitations under the License. -//! [`BinaryHeap`](`super::BinaryHeap`) is a max-heap by default, where the *largest* element will -//! be returned by `heap.pop()`. To use a [`BinaryHeap`](`super::BinaryHeap`) as a min-heap, where -//! the *smallest* element returned by `heap.pop()`, the type `T` of the binary heap can be wrapped -//! in a `Reverse`. +//! [`BinaryHeap`](`super::BinaryHeap`) is a max-heap by default, where the +//! *largest* element will be returned by `heap.pop()`. To use a +//! [`BinaryHeap`](`super::BinaryHeap`) as a min-heap, where the *smallest* +//! element returned by `heap.pop()`, the type `T` of the binary heap can be +//! wrapped in a `Reverse`. //! -//! [`Reverse`] simply wraps [`core::cmp::Reverse`] and implements all the required traits for use -//! as a storage struct. +//! [`Reverse`] simply wraps [`core::cmp::Reverse`] and implements all the +//! required traits for use as a storage struct. use crate::traits::{ KeyPtr, @@ -28,8 +29,8 @@ use crate::traits::{ use ink_prelude::vec::Vec; use ink_primitives::Key; -/// Wrapper for [`core::cmp::Reverse`] for using a [`BinaryHeap`](`super::BinaryHeap`) as a -/// min-heap. +/// Wrapper for [`core::cmp::Reverse`] for using a +/// [`BinaryHeap`](`super::BinaryHeap`) as a min-heap. #[derive(PartialEq, Eq, Ord, PartialOrd, Debug, Copy, Clone, Default)] pub struct Reverse(core::cmp::Reverse); diff --git a/crates/storage/src/collections/binary_heap/tests.rs b/crates/storage/src/collections/binary_heap/tests.rs index 4280d657fd8..49630e54567 100644 --- a/crates/storage/src/collections/binary_heap/tests.rs +++ b/crates/storage/src/collections/binary_heap/tests.rs @@ -442,7 +442,8 @@ where #[test] fn push_largest_value_complexity_big_o_log_n() -> ink_env::Result<()> { - // 1 elements overhead (#508) + 1 elements.len + 1 heap overhead (#508) + 1 heap.len + 1 cell + // 1 elements overhead (#508) + 1 elements.len + 1 heap overhead (#508) + 1 + // heap.len + 1 cell const CONST_READS: usize = 5; // 1 elements.len + 1 cell which was pushed to diff --git a/crates/storage/src/collections/bitvec/bits256.rs b/crates/storage/src/collections/bitvec/bits256.rs index f5ef136b3b9..7457a06d4a1 100644 --- a/crates/storage/src/collections/bitvec/bits256.rs +++ b/crates/storage/src/collections/bitvec/bits256.rs @@ -116,7 +116,8 @@ impl<'a> IterMut<'a> { self.end - self.start } - /// Returns access for the given bit index with extended but valid lifetimes. + /// Returns access for the given bit index with extended but valid + /// lifetimes. fn get<'b>(&'b mut self, index: u8) -> BitRefMut<'a> { unsafe { BitRefMut::new(extend_lifetime(self.bits), index) } } @@ -182,7 +183,8 @@ impl Bits256 { Iter::new(self, len) } - /// Yields mutable accessors to the first `len` bits of the pack of 256 bits. + /// Yields mutable accessors to the first `len` bits of the pack of 256 + /// bits. pub(super) fn iter_mut(&mut self, len: u16) -> IterMut { IterMut::new(self, len) } diff --git a/crates/storage/src/collections/bitvec/mod.rs b/crates/storage/src/collections/bitvec/mod.rs index b44ab9f81fa..787757a0386 100644 --- a/crates/storage/src/collections/bitvec/mod.rs +++ b/crates/storage/src/collections/bitvec/mod.rs @@ -122,12 +122,14 @@ impl Bitvec { Bits256Iter::new(self) } - /// Returns an iterator over the mutable 256-bit chunks of the storage bit vector. + /// Returns an iterator over the mutable 256-bit chunks of the storage bit + /// vector. pub(super) fn iter_chunks_mut(&mut self) -> Bits256IterMut { Bits256IterMut::new(self) } - /// Splits the given index into a 256-bit pack index and a position index of the bit. + /// Splits the given index into a 256-bit pack index and a position index of + /// the bit. fn split_index(&self, at: Index) -> Option<(Index, Index256)> { if at >= self.len() { return None @@ -135,7 +137,8 @@ impl Bitvec { Some((at / 256, (at % 256) as u8)) } - /// Returns the immutable access pair to the underlying 256-bits pack and bit. + /// Returns the immutable access pair to the underlying 256-bits pack and + /// bit. /// /// Returns `None` if the given index is out of bounds. fn get_bits256(&self, at: Index) -> Option<(&Bits256, Index256)> { @@ -170,7 +173,8 @@ impl Bitvec { self.get_access_mut(at) } - /// Returns a shared reference to the 256-bit chunk for the bit at the given index. + /// Returns a shared reference to the 256-bit chunk for the bit at the given + /// index. pub fn get_chunk(&self, at: Index) -> Option> { if at >= self.len() { return None @@ -182,7 +186,8 @@ impl Bitvec { Some(ChunkRef::shared(bits256, chunk_len)) } - /// Returns an exclusive reference to the 256-bit chunk for the bit at the given index. + /// Returns an exclusive reference to the 256-bit chunk for the bit at the + /// given index. pub fn get_chunk_mut(&mut self, at: Index) -> Option> { if at >= self.len() { return None @@ -276,8 +281,8 @@ impl Bitvec { } // Case: The last 256-bit pack has unused bits: // - Set last bit of last 256-bit pack to the given value. - // - Opt.: Since bits are initialized as 0 we only need - // to mutate this value if `value` is `true`. + // - Opt.: Since bits are initialized as 0 we only need to mutate this value if + // `value` is `true`. *self.len += 1; if value { self.last_mut() diff --git a/crates/storage/src/collections/hashmap/fuzz_tests.rs b/crates/storage/src/collections/hashmap/fuzz_tests.rs index 52f061f4269..47dd72163a2 100644 --- a/crates/storage/src/collections/hashmap/fuzz_tests.rs +++ b/crates/storage/src/collections/hashmap/fuzz_tests.rs @@ -39,7 +39,8 @@ use std::{ /// Conducts repeated insert and remove operations into the map by iterating /// over `xs`. For each odd `x` in `xs` a defined number of insert operations /// (`inserts_each`) is executed. For each even `x` it's asserted that the -/// previously inserted elements are in the map, and they are removed subsequently. +/// previously inserted elements are in the map, and they are removed +/// subsequently. /// /// The reasoning behind this even/odd sequence is to introduce some /// randomness into when elements are inserted/removed. diff --git a/crates/storage/src/collections/hashmap/mod.rs b/crates/storage/src/collections/hashmap/mod.rs index 2ee602b8f8d..28b678e7a87 100644 --- a/crates/storage/src/collections/hashmap/mod.rs +++ b/crates/storage/src/collections/hashmap/mod.rs @@ -138,7 +138,8 @@ where K: Ord + Clone + PackedLayout, V: PackedLayout, { - /// A vacant entry that holds the index to the next and previous vacant entry. + /// A vacant entry that holds the index to the next and previous vacant + /// entry. Vacant(VacantEntry<'a, K, V>), /// An occupied entry that holds the value. Occupied(OccupiedEntry<'a, K, V>), @@ -181,8 +182,8 @@ where /// # Note /// /// - Avoid unbounded iteration over big storage hash maps. - /// - Prefer using methods like `Iterator::take` in order to limit the number - /// of yielded elements. + /// - Prefer using methods like `Iterator::take` in order to limit the + /// number of yielded elements. pub fn iter(&self) -> Iter { Iter::new(self) } @@ -193,41 +194,44 @@ where /// # Note /// /// - Avoid unbounded iteration over big storage hash maps. - /// - Prefer using methods like `Iterator::take` in order to limit the number - /// of yielded elements. + /// - Prefer using methods like `Iterator::take` in order to limit the + /// number of yielded elements. pub fn iter_mut(&mut self) -> IterMut { IterMut::new(self) } - /// Returns an iterator yielding shared references to all values of the hash map. + /// Returns an iterator yielding shared references to all values of the hash + /// map. /// /// # Note /// /// - Avoid unbounded iteration over big storage hash maps. - /// - Prefer using methods like `Iterator::take` in order to limit the number - /// of yielded elements. + /// - Prefer using methods like `Iterator::take` in order to limit the + /// number of yielded elements. pub fn values(&self) -> Values { Values::new(self) } - /// Returns an iterator yielding shared references to all values of the hash map. + /// Returns an iterator yielding shared references to all values of the hash + /// map. /// /// # Note /// /// - Avoid unbounded iteration over big storage hash maps. - /// - Prefer using methods like `Iterator::take` in order to limit the number - /// of yielded elements. + /// - Prefer using methods like `Iterator::take` in order to limit the + /// number of yielded elements. pub fn values_mut(&mut self) -> ValuesMut { ValuesMut::new(self) } - /// Returns an iterator yielding shared references to all keys of the hash map. + /// Returns an iterator yielding shared references to all keys of the hash + /// map. /// /// # Note /// /// - Avoid unbounded iteration over big storage hash maps. - /// - Prefer using methods like `Iterator::take` in order to limit the number - /// of yielded elements. + /// - Prefer using methods like `Iterator::take` in order to limit the + /// number of yielded elements. pub fn keys(&self) -> Keys { Keys::new(self) } @@ -273,9 +277,9 @@ where /// /// # Note /// - /// - If the map did have this key present, the value is updated, - /// and the old value is returned. The key is not updated, though; - /// this matters for types that can be `==` without being identical. + /// - If the map did have this key present, the value is updated, and the + /// old value is returned. The key is not updated, though; this matters + /// for types that can be `==` without being identical. pub fn insert(&mut self, key: K, new_value: V) -> Option { if let Some(occupied) = self.values.get_mut(&key) { // Update value, don't update key. @@ -301,7 +305,8 @@ where /// # Note /// /// The key may be any borrowed form of the map's key type, - /// but `Hash` and `Eq` on the borrowed form must match those for the key type. + /// but `Hash` and `Eq` on the borrowed form must match those for the key + /// type. pub fn take(&mut self, key: &Q) -> Option where K: Borrow, @@ -317,7 +322,8 @@ where /// Returns a shared reference to the value corresponding to the key. /// /// The key may be any borrowed form of the map's key type, - /// but `Hash` and `Eq` on the borrowed form must match those for the key type. + /// but `Hash` and `Eq` on the borrowed form must match those for the key + /// type. pub fn get(&self, key: &Q) -> Option<&V> where K: Borrow, @@ -329,7 +335,8 @@ where /// Returns a mutable reference to the value corresponding to the key. /// /// The key may be any borrowed form of the map's key type, - /// but `Hash` and `Eq` on the borrowed form must match those for the key type. + /// but `Hash` and `Eq` on the borrowed form must match those for the key + /// type. pub fn get_mut(&mut self, key: &Q) -> Option<&mut V> where K: Borrow, @@ -361,10 +368,11 @@ where /// /// # Note /// - /// This frees storage that is held but not necessary for the hash map to hold. - /// This operation might be expensive, especially for big `max_iteration` - /// parameters. The `max_iterations` parameter can be used to limit the - /// expensiveness for this operation and instead free up storage incrementally. + /// This frees storage that is held but not necessary for the hash map to + /// hold. This operation might be expensive, especially for big + /// `max_iteration` parameters. The `max_iterations` parameter can be + /// used to limit the expensiveness for this operation and instead free + /// up storage incrementally. pub fn defrag(&mut self, max_iterations: Option) -> u32 { // This method just defrags the underlying `storage::Stash` used to // store the keys as it can sometimes take a lot of unused storage @@ -387,7 +395,8 @@ where self.keys.defrag(Some(max_iterations), callback) } - /// Gets the given key's corresponding entry in the map for in-place manipulation. + /// Gets the given key's corresponding entry in the map for in-place + /// manipulation. pub fn entry(&mut self, key: K) -> Entry { let entry = self.values.entry(key); match entry { @@ -420,8 +429,8 @@ where } } - /// Ensures a value is in the entry by inserting the default value if empty, and returns - /// a reference to the value in the entry. + /// Ensures a value is in the entry by inserting the default value if empty, + /// and returns a reference to the value in the entry. pub fn or_default(self) -> &'a V { match self { Entry::Occupied(entry) => &mut entry.values_entry.into_mut().value, @@ -429,8 +438,8 @@ where } } - /// Ensures a value is in the entry by inserting the default if empty, and returns - /// a mutable reference to the value in the entry. + /// Ensures a value is in the entry by inserting the default if empty, and + /// returns a mutable reference to the value in the entry. pub fn or_insert(self, default: V) -> &'a mut V { match self { Entry::Occupied(entry) => &mut entry.values_entry.into_mut().value, @@ -438,8 +447,9 @@ where } } - /// Ensures a value is in the entry by inserting the result of the default function if empty, - /// and returns mutable references to the key and value in the entry. + /// Ensures a value is in the entry by inserting the result of the default + /// function if empty, and returns mutable references to the key and + /// value in the entry. pub fn or_insert_with(self, default: F) -> &'a mut V where F: FnOnce() -> V, @@ -450,9 +460,9 @@ where } } - /// Ensures a value is in the entry by inserting, if empty, the result of the default - /// function, which takes the key as its argument, and returns a mutable reference to - /// the value in the entry. + /// Ensures a value is in the entry by inserting, if empty, the result of + /// the default function, which takes the key as its argument, and + /// returns a mutable reference to the value in the entry. pub fn or_insert_with_key(self, default: F) -> &'a mut V where F: FnOnce(&K) -> V, @@ -492,7 +502,8 @@ where K: Ord + Clone + PackedLayout, V: PackedLayout, { - /// Gets a reference to the key that would be used when inserting a value through the `VacantEntry`. + /// Gets a reference to the key that would be used when inserting a value + /// through the `VacantEntry`. pub fn key(&self) -> &K { self.values_entry.key() } @@ -502,7 +513,8 @@ where self.values_entry.into_key() } - /// Sets the value of the entry with the `VacantEntry`s key, and returns a mutable reference to it. + /// Sets the value of the entry with the `VacantEntry`s key, and returns a + /// mutable reference to it. pub fn insert(self, value: V) -> &'a mut V { // At this point we know that `key` does not yet exist in the map. let key_index = self.keys.put(self.key().to_owned()); @@ -540,8 +552,8 @@ where /// Gets a mutable reference to the value in the entry. /// - /// If you need a reference to the `OccupiedEntry` which may outlive the destruction of the - /// `Entry` value, see `into_mut`. + /// If you need a reference to the `OccupiedEntry` which may outlive the + /// destruction of the `Entry` value, see `into_mut`. pub fn get_mut(&mut self) -> &mut V { &mut self.values_entry.get_mut().value } @@ -556,8 +568,8 @@ where self.remove_entry().1 } - /// Converts the `OccupiedEntry` into a mutable reference to the value in the entry - /// with a lifetime bound to the map itself. + /// Converts the `OccupiedEntry` into a mutable reference to the value in + /// the entry with a lifetime bound to the map itself. pub fn into_mut(self) -> &'a mut V { &mut self.values_entry.into_mut().value } diff --git a/crates/storage/src/collections/mod.rs b/crates/storage/src/collections/mod.rs index 07ade806f2e..8c36e89a866 100644 --- a/crates/storage/src/collections/mod.rs +++ b/crates/storage/src/collections/mod.rs @@ -39,7 +39,8 @@ pub use self::{ #[doc(inline)] pub use self::smallvec::SmallVec; -/// Extends the lifetime `'a` to the outliving lifetime `'b` for the given reference. +/// Extends the lifetime `'a` to the outliving lifetime `'b` for the given +/// reference. /// /// # Note /// diff --git a/crates/storage/src/collections/smallvec/iter.rs b/crates/storage/src/collections/smallvec/iter.rs index 3ae9c4d38be..46e1f7f32db 100644 --- a/crates/storage/src/collections/smallvec/iter.rs +++ b/crates/storage/src/collections/smallvec/iter.rs @@ -18,7 +18,8 @@ use crate::{ traits::PackedLayout, }; -/// An iterator over shared references to the elements of a small storage vector. +/// An iterator over shared references to the elements of a small storage +/// vector. #[derive(Debug, Clone, Copy)] pub struct Iter<'a, T, const N: usize> where @@ -106,7 +107,8 @@ where } } -/// An iterator over exclusive references to the elements of a small storage vector. +/// An iterator over exclusive references to the elements of a small storage +/// vector. #[derive(Debug)] pub struct IterMut<'a, T, const N: usize> where diff --git a/crates/storage/src/collections/smallvec/mod.rs b/crates/storage/src/collections/smallvec/mod.rs index e2388a27ebe..d6fb6760286 100644 --- a/crates/storage/src/collections/smallvec/mod.rs +++ b/crates/storage/src/collections/smallvec/mod.rs @@ -45,13 +45,13 @@ type Index = u32; /// /// # Note /// -/// - The `storage::SmallVec` has a very similar API compared to a `storage::Vec`. -/// The major difference between both data structures is that the `SmallVec` -/// can only contain up to a fixed amount of elements given by `N` whereas the -/// `Vec` can contain up to `2^32` elements which is the maximum for 32-bit Wasm -/// targets. -/// - The performance characteristics may be different from Rust's -/// `Vec` due to the internal differences. +/// - The `storage::SmallVec` has a very similar API compared to a +/// `storage::Vec`. The major difference between both data structures is that +/// the `SmallVec` can only contain up to a fixed amount of elements given by +/// `N` whereas the `Vec` can contain up to `2^32` elements which is the +/// maximum for 32-bit Wasm targets. +/// - The performance characteristics may be different from Rust's `Vec` due to +/// the internal differences. /// - Allows to store up to N elements. #[derive(Debug)] pub struct SmallVec @@ -85,8 +85,8 @@ where /// the contents of its associated storage region. /// /// This API is used for the `Drop` implementation of [`Vec`] as well as - /// for the [`SpreadLayout::clear_spread`][`crate::traits::SpreadLayout::clear_spread`] - /// trait implementation. + /// for the [`SpreadLayout::clear_spread`][`crate::traits::SpreadLayout:: + /// clear_spread`] trait implementation. fn clear_cells(&self) { if self.elems.key().is_none() { // We won't clear any storage if we are in lazy state since there @@ -117,7 +117,8 @@ where self.elems.capacity() } - /// Returns the number of elements in the vector, also referred to as its length. + /// Returns the number of elements in the vector, also referred to as its + /// length. #[inline] pub fn len(&self) -> u32 { *self.len @@ -139,8 +140,8 @@ where /// # Note /// /// - Avoid unbounded iteration over big storage vectors. - /// - Prefer using methods like `Iterator::take` in order to limit the number - /// of yielded elements. + /// - Prefer using methods like `Iterator::take` in order to limit the + /// number of yielded elements. pub fn iter(&self) -> Iter { Iter::new(self) } @@ -150,8 +151,8 @@ where /// # Note /// /// - Avoid unbounded iteration over big storage vectors. - /// - Prefer using methods like `Iterator::take` in order to limit the number - /// of yielded elements. + /// - Prefer using methods like `Iterator::take` in order to limit the + /// number of yielded elements. pub fn iter_mut(&mut self) -> IterMut { IterMut::new(self) } @@ -281,7 +282,8 @@ where /// Removes the indexed element from the vector and returns it. /// /// The last element of the vector is put into the indexed slot. - /// Returns `None` and does not mutate the vector if the index is out of bounds. + /// Returns `None` and does not mutate the vector if the index is out of + /// bounds. /// /// # Note /// diff --git a/crates/storage/src/collections/stash/mod.rs b/crates/storage/src/collections/stash/mod.rs index 6c94fd6ad42..ed42b32da0a 100644 --- a/crates/storage/src/collections/stash/mod.rs +++ b/crates/storage/src/collections/stash/mod.rs @@ -91,7 +91,8 @@ pub struct VacantEntry { #[derive(Debug, scale::Encode, scale::Decode)] #[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] pub enum Entry { - /// A vacant entry that holds the index to the next and previous vacant entry. + /// A vacant entry that holds the index to the next and previous vacant + /// entry. Vacant(VacantEntry), /// An occupied entry that hold the value. Occupied(T), @@ -111,7 +112,8 @@ impl Entry { !self.is_occupied() } - /// Returns the vacant entry if the entry is vacant, otherwise returns `None`. + /// Returns the vacant entry if the entry is vacant, otherwise returns + /// `None`. fn try_to_vacant(&self) -> Option { match self { Entry::Occupied(_) => None, @@ -119,7 +121,8 @@ impl Entry { } } - /// Returns the vacant entry if the entry is vacant, otherwise returns `None`. + /// Returns the vacant entry if the entry is vacant, otherwise returns + /// `None`. fn try_to_vacant_mut(&mut self) -> Option<&mut VacantEntry> { match self { Entry::Occupied(_) => None, @@ -179,7 +182,8 @@ where self.entries.key() } - /// Returns an iterator yielding shared references to all elements of the stash. + /// Returns an iterator yielding shared references to all elements of the + /// stash. /// /// # Note /// @@ -190,7 +194,8 @@ where Iter::new(self) } - /// Returns an iterator yielding exclusive references to all elements of the stash. + /// Returns an iterator yielding exclusive references to all elements of the + /// stash. /// /// # Note /// @@ -201,7 +206,8 @@ where IterMut::new(self) } - /// Returns an iterator yielding shared references to all entries of the stash. + /// Returns an iterator yielding shared references to all entries of the + /// stash. pub fn entries(&self) -> Entries { Entries::new(self) } @@ -266,8 +272,8 @@ where /// the contents of its associated storage region. /// /// This API is used for the `Drop` implementation of [`Vec`] as well as - /// for the [`SpreadLayout::clear_spread`][`crate::traits::SpreadLayout::clear_spread`] - /// trait implementation. + /// for the [`SpreadLayout::clear_spread`][`crate::traits::SpreadLayout:: + /// clear_spread`] trait implementation. fn clear_cells(&self) { if self.entries.key().is_none() { // We won't clear any storage if we are in lazy state since there @@ -291,7 +297,8 @@ impl Stash where T: PackedLayout, { - /// Rebinds the `prev` and `next` bindings of the neighbors of the vacant entry. + /// Rebinds the `prev` and `next` bindings of the neighbors of the vacant + /// entry. /// /// # Note /// @@ -419,7 +426,8 @@ where pub fn put(&mut self, new_value: T) -> Index { let new_entry = Some(Entry::Occupied(new_value)); let new_index = if let Some(index) = self.last_vacant_index() { - // Put the new element to the most recent vacant index if not all entries are occupied. + // Put the new element to the most recent vacant index if not all entries are + // occupied. let old_entry = self .entries .put_get(index, new_entry) @@ -482,20 +490,20 @@ where /// Removes the element stored at the given index if any. /// - /// This method acts similar to the take API and even still returns an Option. - /// However, it guarantees to make no contract storage reads to the indexed - /// element and will only write to its internal low-level lazy cache that the - /// element at the given index is going to be removed at the end of the contract - /// execution. + /// This method acts similar to the take API and even still returns an + /// Option. However, it guarantees to make no contract storage reads to + /// the indexed element and will only write to its internal low-level + /// lazy cache that the element at the given index is going to be + /// removed at the end of the contract execution. /// - /// Calling this method with an index out of bounds for the returns `None` and - /// does not `remove` the element, otherwise it returns `Some(())`. + /// Calling this method with an index out of bounds for the returns `None` + /// and does not `remove` the element, otherwise it returns `Some(())`. /// /// # Safety /// - /// The caller must ensure that `at` refers to an occupied index. Behavior is - /// unspecified if `at` refers to a vacant index and could seriously damage the - /// contract storage integrity. + /// The caller must ensure that `at` refers to an occupied index. Behavior + /// is unspecified if `at` refers to a vacant index and could seriously + /// damage the contract storage integrity. pub unsafe fn remove_occupied(&mut self, at: Index) -> Option<()> { // This function is written similar to [`Stash::take`], with the exception // that the caller has to ensure that `at` refers to an occupied entry whereby @@ -535,10 +543,10 @@ where /// - If `max_iterations` is `Some` concrete value it is used in order to /// bound the number of iterations and won't try to defrag until the stash /// is optimally compacted. - /// - Users are advised to call this method using `Some` concrete - /// value to keep gas costs within certain bounds. - /// - The call to the given callback takes place before the reinsertion - /// of the shifted occupied entry. + /// - Users are advised to call this method using `Some` concrete value to + /// keep gas costs within certain bounds. + /// - The call to the given callback takes place before the reinsertion of + /// the shifted occupied entry. pub fn defrag(&mut self, max_iterations: Option, mut callback: C) -> u32 where C: FnMut(Index, Index, &T), diff --git a/crates/storage/src/collections/stash/tests.rs b/crates/storage/src/collections/stash/tests.rs index 8335345e443..1206c1b90fb 100644 --- a/crates/storage/src/collections/stash/tests.rs +++ b/crates/storage/src/collections/stash/tests.rs @@ -141,8 +141,8 @@ fn remove_out_of_bounds_works() { #[test] fn remove_works_with_spread_layout_push_pull() -> ink_env::Result<()> { ink_env::test::run_test::(|_| { - // First populate some storage Stash and writes that to the contract storage using pull_spread - // and some known Key. + // First populate some storage Stash and writes that to the contract storage + // using pull_spread and some known Key. let stash = [b'A', b'B', b'C'] .iter() .copied() @@ -151,8 +151,8 @@ fn remove_works_with_spread_layout_push_pull() -> ink_env::Result<()> { SpreadLayout::push_spread(&stash, &mut KeyPtr::from(root_key)); // Then load another instance from the same key lazily and remove some of - // the known-to-be-populated entries from it. Afterwards push_spread this second instance and - // load yet another using pull_spread again. + // the known-to-be-populated entries from it. Afterwards push_spread this second + // instance and load yet another using pull_spread again. let mut stash2 = as SpreadLayout>::pull_spread(&mut KeyPtr::from(root_key)); assert_eq!(unsafe { stash2.remove_occupied(0) }, Some(())); diff --git a/crates/storage/src/collections/vec/mod.rs b/crates/storage/src/collections/vec/mod.rs index 1063ad3fde9..b0541a8ca24 100644 --- a/crates/storage/src/collections/vec/mod.rs +++ b/crates/storage/src/collections/vec/mod.rs @@ -44,9 +44,9 @@ use crate::{ /// # Note /// /// Despite the similarity to Rust's `Vec` type this storage `Vec` has many -/// differences in its internal data layout. While it stores its data in contiguous -/// storage slots this does not mean that the data is actually densely stored -/// in memory. +/// differences in its internal data layout. While it stores its data in +/// contiguous storage slots this does not mean that the data is actually +/// densely stored in memory. /// /// Also its technical performance characteristics may be different from Rust's /// `Vec` due to the differences stated above. @@ -89,7 +89,8 @@ where } } - /// Returns the number of elements in the vector, also referred to as its length. + /// Returns the number of elements in the vector, also referred to as its + /// length. pub fn len(&self) -> u32 { *self.len } @@ -112,8 +113,8 @@ where /// the contents of its associated storage region. /// /// This API is used for the `Drop` implementation of [`Vec`] as well as - /// for the [`SpreadLayout::clear_spread`][`crate::traits::SpreadLayout::clear_spread`] - /// trait implementation. + /// for the [`SpreadLayout::clear_spread`][`crate::traits::SpreadLayout:: + /// clear_spread`] trait implementation. fn clear_cells(&self) { if self.elems.key().is_none() { // We won't clear any storage if we are in lazy state since there @@ -130,7 +131,8 @@ impl Vec where T: PackedLayout, { - /// Returns an iterator yielding shared references to all elements of the vector. + /// Returns an iterator yielding shared references to all elements of the + /// vector. /// /// # Note /// @@ -141,7 +143,8 @@ where Iter::new(self) } - /// Returns an iterator yielding exclusive references to all elements of the vector. + /// Returns an iterator yielding exclusive references to all elements of the + /// vector. /// /// # Note /// @@ -450,7 +453,8 @@ where /// Removes the indexed element from the vector and returns it. /// /// The last element of the vector is put into the indexed slot. - /// Returns `None` and does not mutate the vector if the index is out of bounds. + /// Returns `None` and does not mutate the vector if the index is out of + /// bounds. /// /// # Note /// diff --git a/crates/storage/src/lazy/cache_cell.rs b/crates/storage/src/lazy/cache_cell.rs index 4910135bd3b..1429ce476d1 100644 --- a/crates/storage/src/lazy/cache_cell.rs +++ b/crates/storage/src/lazy/cache_cell.rs @@ -22,8 +22,9 @@ use core::{ /// A cache for a `T` that allow to mutate the inner `T` through `&self`. /// /// Internally this is a thin wrapper around an `UnsafeCell`. -/// The main difference to `UnsafeCell` is that this type provides an out-of-the-box -/// API to safely access the inner `T` as well for single threaded contexts. +/// The main difference to `UnsafeCell` is that this type provides an +/// out-of-the-box API to safely access the inner `T` as well for single +/// threaded contexts. pub struct CacheCell { /// The inner value that is allowed to be mutated in shared contexts. inner: UnsafeCell, diff --git a/crates/storage/src/lazy/entry.rs b/crates/storage/src/lazy/entry.rs index 9420638ce16..6b819dd072d 100644 --- a/crates/storage/src/lazy/entry.rs +++ b/crates/storage/src/lazy/entry.rs @@ -203,8 +203,8 @@ impl StorageEntry where T: SpreadLayout, { - /// Pulls the entity from the underlying associated storage as a `SpreadLayout` - /// storage layout representation. + /// Pulls the entity from the underlying associated storage as a + /// `SpreadLayout` storage layout representation. /// /// # Note /// @@ -228,7 +228,8 @@ where } } - /// Clears the underlying associated storage as `SpreadLayout` storage layout representation. + /// Clears the underlying associated storage as `SpreadLayout` storage + /// layout representation. /// /// # Note /// @@ -243,12 +244,14 @@ impl StorageEntry where T: PackedLayout, { - /// Pulls the entity from the underlying associated storage as packed representation. + /// Pulls the entity from the underlying associated storage as packed + /// representation. /// /// # Note /// /// Mainly used by lazy storage abstractions that only allow operating on - /// packed storage entities such as [`LazyIndexMap`][`crate::lazy::LazyIndexMap`] or + /// packed storage entities such as + /// [`LazyIndexMap`][`crate::lazy::LazyIndexMap`] or /// [`LazyArray`][`crate::lazy::LazyArray`]. pub fn pull_packed_root(root_key: &Key) -> Self { Self::new(pull_packed_root_opt::(root_key), EntryState::Preserved) @@ -259,7 +262,8 @@ where /// # Note /// /// Mainly used by lazy storage abstractions that only allow operating on - /// packed storage entities such as [`LazyIndexMap`][`crate::lazy::LazyIndexMap`] + /// packed storage entities such as + /// [`LazyIndexMap`][`crate::lazy::LazyIndexMap`] /// or [`LazyArray`][`crate::lazy::LazyArray`]. pub fn push_packed_root(&self, root_key: &Key) { let old_state = self.replace_state(EntryState::Preserved); @@ -273,7 +277,8 @@ where /// # Note /// /// Mainly used by lazy storage abstractions that only allow operating on - /// packed storage entities such as [`LazyIndexMap`][`crate::lazy::LazyIndexMap`] + /// packed storage entities such as + /// [`LazyIndexMap`][`crate::lazy::LazyIndexMap`] /// or [`LazyArray`][`crate::lazy::LazyArray`]. pub fn clear_packed_root(&self, root_key: &Key) { clear_packed_root::>(self.value(), root_key); diff --git a/crates/storage/src/lazy/lazy_array.rs b/crates/storage/src/lazy/lazy_array.rs index 3bac215a74d..2f53e9fee6c 100644 --- a/crates/storage/src/lazy/lazy_array.rs +++ b/crates/storage/src/lazy/lazy_array.rs @@ -45,7 +45,8 @@ pub type Index = u32; /// /// Computes operations on the underlying N storage cells in a lazy fashion. /// Due to the size constraints the `LazyArray` is generally more efficient -/// than the [`LazyMap`](`super::LazyIndexMap`) for most use cases with limited elements. +/// than the [`LazyMap`](`super::LazyIndexMap`) for most use cases with limited +/// elements. /// /// This is mainly used as low-level storage primitives by other high-level /// storage primitives in order to manage the contract storage for a whole @@ -245,7 +246,8 @@ impl EntryArray { .flatten() } - /// Inserts a new entry into the cache and returns an exclusive reference to it. + /// Inserts a new entry into the cache and returns an exclusive reference to + /// it. unsafe fn insert_entry( &self, at: Index, @@ -292,8 +294,8 @@ where let root_key = self.key_at(index).expect("cannot clear in lazy state"); if ::REQUIRES_DEEP_CLEAN_UP { // We need to load the entity before we remove its associated contract storage - // because it requires a deep clean-up which propagates clearing to its fields, - // for example in the case of `T` being a `storage::Box`. + // because it requires a deep clean-up which propagates clearing to its + // fields, for example in the case of `T` being a `storage::Box`. let entity = self.get(index).expect("cannot clear a non existing entity"); clear_packed_root::(entity, &root_key); } else { @@ -315,8 +317,9 @@ impl LazyArray { /// /// # Note /// - /// A lazy array created this way cannot be used to load from the contract storage. - /// All operations that directly or indirectly load from storage will panic. + /// A lazy array created this way cannot be used to load from the contract + /// storage. All operations that directly or indirectly load from + /// storage will panic. pub fn new() -> Self { Self { key: None, @@ -496,7 +499,8 @@ where self.load_through_cache_mut(at).value_mut().into() } - /// Puts the new value into the indexed slot and returns the old value if any. + /// Puts the new value into the indexed slot and returns the old value if + /// any. /// /// # Note /// @@ -563,7 +567,8 @@ mod tests { }; use ink_primitives::Key; - /// Asserts that the cached entries of the given `imap` is equal to the `expected` slice. + /// Asserts that the cached entries of the given `imap` is equal to the + /// `expected` slice. fn assert_cached_entries( larray: &LazyArray, expected: &[(Index, StorageEntry)], diff --git a/crates/storage/src/lazy/lazy_cell.rs b/crates/storage/src/lazy/lazy_cell.rs index 822433826f2..521b4b10111 100644 --- a/crates/storage/src/lazy/lazy_cell.rs +++ b/crates/storage/src/lazy/lazy_cell.rs @@ -38,7 +38,8 @@ use ink_primitives::Key; /// /// # Note /// -/// Use this if the storage field does not need to be loaded in some or most cases. +/// Use this if the storage field does not need to be loaded in some or most +/// cases. pub struct LazyCell where T: SpreadLayout, @@ -584,11 +585,12 @@ mod tests { // 1. Change the second `i32` value of the pair. // 2. Push the pair again to contract storage. // - // We prevent the intermediate instance from clearing the storage preemtively by wrapping - // it inside `ManuallyDrop`. The third step will clean up the same storage region afterwards. + // We prevent the intermediate instance from clearing the storage + // preemtively by wrapping it inside `ManuallyDrop`. The + // third step will clean up the same storage region afterwards. // - // We explicitly do not touch or assert the value of `pulled_pair.0` in order to trigger - // the bug. + // We explicitly do not touch or assert the value of `pulled_pair.0` in + // order to trigger the bug. let pulled_pair: (LazyCell, i32) = SpreadLayout::pull_spread(&mut KeyPtr::from(root_key)); let mut pulled_pair = core::mem::ManuallyDrop::new(pulled_pair); @@ -599,8 +601,9 @@ mod tests { { // Step 3: Pull the pair again from the storage. // - // If the bug with `Lazy` that has been fixed in PR #528 has been fixed we should be - // able to inspect the correct values for both pair entries which is: `(Some(1), 3)` + // If the bug with `Lazy` that has been fixed in PR #528 has been fixed we + // should be able to inspect the correct values for both + // pair entries which is: `(Some(1), 3)` let pulled_pair: (LazyCell, i32) = SpreadLayout::pull_spread(&mut KeyPtr::from(root_key)); assert_eq!(pulled_pair.0.get(), Some(&1i32)); @@ -631,9 +634,10 @@ mod tests { // 1. Change the first values `None` to `Some(...)`. // 2. Push the first value again to contract storage. // - // We prevent the intermediate instance from clearing the storage preemptively - // by wrapping it inside `ManuallyDrop`. The third step will clean up the same - // storage region afterwards. + // We prevent the intermediate instance from clearing the storage + // preemptively by wrapping it inside `ManuallyDrop`. The + // third step will clean up the same storage region + // afterwards. let mut ptr = KeyPtr::from(root_key); let pulled_v1: Option = SpreadLayout::pull_spread(&mut ptr); let mut pulled_v1 = core::mem::ManuallyDrop::new(pulled_v1); @@ -650,8 +654,8 @@ mod tests { { // Step 3: Pull the values again from the storage. // - // If the bug with `Option` has been fixed in PR #520 we must be able to inspect - // the correct values for both entries. + // If the bug with `Option` has been fixed in PR #520 we must be able to + // inspect the correct values for both entries. let mut ptr = KeyPtr::from(root_key); let pulled_v1: Option = SpreadLayout::pull_spread(&mut ptr); let pulled_v2: u32 = SpreadLayout::pull_spread(&mut ptr); @@ -698,7 +702,8 @@ mod tests { // the pointer will break as soon as the `Option` is changed to it's // opposite (`None` -> `Some`, `Some` -> `None`). let mut expected_post_op_ptr = KeyPtr::from(root_key); - // advance one time after the cell containing `self.is_some() as u8` has been read + // advance one time after the cell containing `self.is_some() as u8` has been + // read expected_post_op_ptr.advance_by(1); // advance another time after the cell containing the inner `Option` value // has either been skipped (in case of the previous cell being `None`) or diff --git a/crates/storage/src/lazy/lazy_hmap.rs b/crates/storage/src/lazy/lazy_hmap.rs index 11caecd2d4f..becb27b934d 100644 --- a/crates/storage/src/lazy/lazy_hmap.rs +++ b/crates/storage/src/lazy/lazy_hmap.rs @@ -12,7 +12,8 @@ // See the License for the specific language governing permissions and // limitations under the License. -//! A lazy storage mapping that stores entries under their SCALE encoded key hashes. +//! A lazy storage mapping that stores entries under their SCALE encoded key +//! hashes. use super::{ CacheCell, @@ -64,7 +65,8 @@ use ink_primitives::Key; /// [`LazyHashMap::get`]. pub type EntryMap = BTreeMap>>; -/// A lazy storage mapping that stores entries under their SCALE encoded key hashes. +/// A lazy storage mapping that stores entries under their SCALE encoded key +/// hashes. /// /// # Note /// @@ -109,7 +111,8 @@ enum EntryOrMutableValue { /// This represents the case where the key was in the cache. EntryElementWasInCache(E), /// A reference to the mutable value behind a cache entry. - /// This represents the case where the key was not in the cache, but in storage. + /// This represents the case where the key was not in the cache, but in + /// storage. MutableValueElementWasNotInCache(V), } @@ -123,8 +126,8 @@ where { /// The key stored in this entry. key: K, - /// Either the occupied `EntryMap` entry that holds the value or a mutable reference - /// to the value behind a cache entry. + /// Either the occupied `EntryMap` entry that holds the value or a mutable + /// reference to the value behind a cache entry. entry: EntryOrMutableValue, &'a mut Box>>, } @@ -136,12 +139,12 @@ where { /// The key stored in this entry. key: K, - /// The entry within the `LazyHashMap`. This entry can be either occupied or vacant. - /// In an `BTreeMapEntry::Occupied` state the entry has been marked to - /// be removed (with `None`), but we still want to expose the `VacantEntry` API - /// to the use. - /// In an `BTreeMapEntry::Vacant` state the entry is vacant, and we want to expose - /// the `VacantEntry` API. + /// The entry within the `LazyHashMap`. This entry can be either occupied or + /// vacant. In an `BTreeMapEntry::Occupied` state the entry has been + /// marked to be removed (with `None`), but we still want to expose the + /// `VacantEntry` API to the use. + /// In an `BTreeMapEntry::Vacant` state the entry is vacant, and we want to + /// expose the `VacantEntry` API. entry: BTreeMapEntry<'a, K, Box>>, } @@ -151,7 +154,8 @@ where K: Ord + Clone + PackedLayout, V: PackedLayout, { - /// A vacant entry that holds the index to the next and previous vacant entry. + /// A vacant entry that holds the index to the next and previous vacant + /// entry. Vacant(VacantEntry<'a, K, V>), /// An occupied entry that holds the value. Occupied(OccupiedEntry<'a, K, V>), @@ -175,7 +179,8 @@ where V: Debug, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - // The `hash_builder` field is not really required or needed for debugging purposes. + // The `hash_builder` field is not really required or needed for debugging + // purposes. f.debug_struct("LazyHashMap") .field("key", &self.key) .field("cached_entries", &DebugEntryMap(&self.cached_entries)) @@ -360,8 +365,9 @@ where /// /// # Note /// - /// A lazy map created this way cannot be used to load from the contract storage. - /// All operations that directly or indirectly load from storage will panic. + /// A lazy map created this way cannot be used to load from the contract + /// storage. All operations that directly or indirectly load from + /// storage will panic. pub fn new() -> Self { Self { key: None, @@ -413,8 +419,8 @@ where /// # Note /// /// - Use [`LazyHashMap::put`]`(None)` in order to remove an element. - /// - Prefer this method over [`LazyHashMap::put_get`] if you are not interested - /// in the old value of the same cell index. + /// - Prefer this method over [`LazyHashMap::put_get`] if you are not + /// interested in the old value of the same cell index. /// /// # Panics /// @@ -436,7 +442,8 @@ where H: CryptoHash, Key: From<::Type>, { - /// Gets the given key's corresponding entry in the map for in-place manipulation. + /// Gets the given key's corresponding entry in the map for in-place + /// manipulation. pub fn entry(&mut self, key: K) -> Entry { // SAFETY: We have put the whole `cached_entries` mapping into an // `UnsafeCell` because of this caching functionality. The @@ -477,8 +484,9 @@ where .unwrap_or(None); match value.is_some() { true => { - // The entry was not in the cache, but in the storage. This results in - // a problem: We only have `Vacant` here, but need to return `Occupied`, + // The entry was not in the cache, but in the storage. This + // results in a problem: We only have + // `Vacant` here, but need to return `Occupied`, // to reflect this. let v_mut = entry.insert(Box::new(StorageEntry::new( value, @@ -555,8 +563,9 @@ where /// /// # Note /// - /// Only loads a value if `key` is set and if the value has not been loaded yet. - /// Returns the freshly loaded or already loaded entry of the value. + /// Only loads a value if `key` is set and if the value has not been loaded + /// yet. Returns the freshly loaded or already loaded entry of the + /// value. /// /// # Safety /// @@ -566,10 +575,10 @@ where /// /// # Safety /// - /// This is an `unsafe` operation because it has a `&self` receiver but returns - /// a `*mut Entry` pointer that allows for exclusive access. This is safe - /// within internal use only and should never be given outside the lazy entity - /// for public `&self` methods. + /// This is an `unsafe` operation because it has a `&self` receiver but + /// returns a `*mut Entry` pointer that allows for exclusive access. + /// This is safe within internal use only and should never be given + /// outside the lazy entity for public `&self` methods. unsafe fn lazily_load(&self, key: &Q) -> NonNull> where K: Borrow, @@ -612,8 +621,9 @@ where /// /// # Note /// - /// Only loads a value if `key` is set and if the value has not been loaded yet. - /// Returns a pointer to the freshly loaded or already loaded entry of the value. + /// Only loads a value if `key` is set and if the value has not been loaded + /// yet. Returns a pointer to the freshly loaded or already loaded entry + /// of the value. /// /// # Panics /// @@ -625,9 +635,9 @@ where Q: Ord + scale::Encode + ToOwned, { // SAFETY: - // - Returning a `&mut Entry` is safe because entities inside the - // cache are stored within a `Box` to not invalidate references into - // them upon operating on the outer cache. + // - Returning a `&mut Entry` is safe because entities inside the cache are + // stored within a `Box` to not invalidate references into them upon operating + // on the outer cache. unsafe { &mut *self.lazily_load(index).as_ptr() } } @@ -650,8 +660,8 @@ where let root_key = self.key_at(index).expect("cannot clear in lazy state"); if ::REQUIRES_DEEP_CLEAN_UP { // We need to load the entity before we remove its associated contract storage - // because it requires a deep clean-up which propagates clearing to its fields, - // for example in the case of `T` being a `storage::Box`. + // because it requires a deep clean-up which propagates clearing to its + // fields, for example in the case of `T` being a `storage::Box`. let entity = self.get(index).expect("cannot clear a non existing entity"); clear_packed_root::(entity, &root_key); } else { @@ -661,7 +671,8 @@ where } } - /// Returns a shared reference to the value associated with the given key if any. + /// Returns a shared reference to the value associated with the given key if + /// any. /// /// # Panics /// @@ -678,7 +689,8 @@ where unsafe { &*self.lazily_load(index).as_ptr() }.value().into() } - /// Returns an exclusive reference to the value associated with the given key if any. + /// Returns an exclusive reference to the value associated with the given + /// key if any. /// /// # Panics /// @@ -696,8 +708,8 @@ where /// /// # Note /// - /// - Use [`LazyHashMap::put_get`]`(None)` in order to remove an element - /// and retrieve the old element back. + /// - Use [`LazyHashMap::put_get`]`(None)` in order to remove an element and + /// retrieve the old element back. /// /// # Panics /// @@ -713,7 +725,8 @@ where /// Swaps the values at entries with associated keys `x` and `y`. /// - /// This operation tries to be as efficient as possible and reuse allocations. + /// This operation tries to be as efficient as possible and reuse + /// allocations. /// /// # Panics /// @@ -764,8 +777,8 @@ where } } - /// Ensures a value is in the entry by inserting the default value if empty, and returns - /// a reference to the value in the entry. + /// Ensures a value is in the entry by inserting the default value if empty, + /// and returns a reference to the value in the entry. pub fn or_default(self) -> &'a V { match self { Entry::Occupied(entry) => entry.into_mut(), @@ -773,8 +786,8 @@ where } } - /// Ensures a value is in the entry by inserting the default if empty, and returns - /// a mutable reference to the value in the entry. + /// Ensures a value is in the entry by inserting the default if empty, and + /// returns a mutable reference to the value in the entry. pub fn or_insert(self, default: V) -> &'a mut V { match self { Entry::Occupied(entry) => entry.into_mut(), @@ -782,8 +795,9 @@ where } } - /// Ensures a value is in the entry by inserting the result of the default function if empty, - /// and returns mutable references to the key and value in the entry. + /// Ensures a value is in the entry by inserting the result of the default + /// function if empty, and returns mutable references to the key and + /// value in the entry. pub fn or_insert_with(self, default: F) -> &'a mut V where F: FnOnce() -> V, @@ -794,9 +808,9 @@ where } } - /// Ensures a value is in the entry by inserting, if empty, the result of the default - /// function, which takes the key as its argument, and returns a mutable reference to - /// the value in the entry. + /// Ensures a value is in the entry by inserting, if empty, the result of + /// the default function, which takes the key as its argument, and + /// returns a mutable reference to the value in the entry. pub fn or_insert_with_key(self, default: F) -> &'a mut V where F: FnOnce(&K) -> V, @@ -834,7 +848,8 @@ where K: Ord + Clone + PackedLayout, V: PackedLayout, { - /// Gets a reference to the key that would be used when inserting a value through the `VacantEntry`. + /// Gets a reference to the key that would be used when inserting a value + /// through the `VacantEntry`. pub fn key(&self) -> &K { &self.key } @@ -844,7 +859,8 @@ where self.key } - /// Sets the value of the entry with the `VacantEntry`s key, and returns a mutable reference to it. + /// Sets the value of the entry with the `VacantEntry`s key, and returns a + /// mutable reference to it. pub fn insert(self, value: V) -> &'a mut V { let new = Box::new(StorageEntry::new(Some(value), EntryState::Mutated)); match self.entry { @@ -918,8 +934,8 @@ where /// Gets a mutable reference to the value in the entry. /// - /// If you need a reference to the `OccupiedEntry` which may outlive the destruction of the - /// `Entry` value, see `into_mut`. + /// If you need a reference to the `OccupiedEntry` which may outlive the + /// destruction of the `Entry` value, see `into_mut`. pub fn get_mut(&mut self) -> &mut V { match &mut self.entry { EntryOrMutableValue::EntryElementWasInCache(entry) => { @@ -961,8 +977,8 @@ where self.remove_entry().1 } - /// Converts the `OccupiedEntry` into a mutable reference to the value in the entry - /// with a lifetime bound to the map itself. + /// Converts the `OccupiedEntry` into a mutable reference to the value in + /// the entry with a lifetime bound to the map itself. pub fn into_mut(self) -> &'a mut V { match self.entry { EntryOrMutableValue::EntryElementWasInCache(entry) => { @@ -999,7 +1015,8 @@ mod tests { }; use ink_primitives::Key; - /// Asserts that the cached entries of the given `imap` is equal to the `expected` slice. + /// Asserts that the cached entries of the given `imap` is equal to the + /// `expected` slice. fn assert_cached_entries( hmap: &LazyHashMap, expected: &[(i32, StorageEntry)], diff --git a/crates/storage/src/lazy/lazy_imap.rs b/crates/storage/src/lazy/lazy_imap.rs index c2a700910bf..7196357c17f 100644 --- a/crates/storage/src/lazy/lazy_imap.rs +++ b/crates/storage/src/lazy/lazy_imap.rs @@ -141,8 +141,9 @@ impl LazyIndexMap { /// /// # Note /// - /// A lazy map created this way cannot be used to load from the contract storage. - /// All operations that directly or indirectly load from storage will panic. + /// A lazy map created this way cannot be used to load from the contract + /// storage. All operations that directly or indirectly load from + /// storage will panic. pub fn new() -> Self { Self { key: None, @@ -185,8 +186,8 @@ impl LazyIndexMap { /// # Note /// /// - Use [`LazyIndexMap::put`]`(None)` in order to remove an element. - /// - Prefer this method over [`LazyIndexMap::put_get`] if you are not interested - /// in the old value of the same cell index. + /// - Prefer this method over [`LazyIndexMap::put_get`] if you are not + /// interested in the old value of the same cell index. /// /// # Panics /// @@ -294,8 +295,8 @@ where let root_key = self.key_at(index).expect("cannot clear in lazy state"); if ::REQUIRES_DEEP_CLEAN_UP { // We need to load the entity before we remove its associated contract storage - // because it requires a deep clean-up which propagates clearing to its fields, - // for example in the case of `T` being a `storage::Box`. + // because it requires a deep clean-up which propagates clearing to its + // fields, for example in the case of `T` being a `storage::Box`. let entity = self.get(index).expect("cannot clear a non existing entity"); clear_packed_root::(entity, &root_key); } else { @@ -322,8 +323,9 @@ where /// /// # Note /// - /// Only loads a value if `key` is set and if the value has not been loaded yet. - /// Returns the freshly loaded or already loaded entry of the value. + /// Only loads a value if `key` is set and if the value has not been loaded + /// yet. Returns the freshly loaded or already loaded entry of the + /// value. /// /// # Safety /// @@ -333,10 +335,10 @@ where /// /// # Safety /// - /// This is an `unsafe` operation because it has a `&self` receiver but returns - /// a `*mut Entry` pointer that allows for exclusive access. This is safe - /// within internal use only and should never be given outside the lazy entity - /// for public `&self` methods. + /// This is an `unsafe` operation because it has a `&self` receiver but + /// returns a `*mut Entry` pointer that allows for exclusive access. + /// This is safe within internal use only and should never be given + /// outside the lazy entity for public `&self` methods. unsafe fn lazily_load(&self, index: Index) -> NonNull> { // SAFETY: We have put the whole `cached_entries` mapping into an // `UnsafeCell` because of this caching functionality. The @@ -372,8 +374,9 @@ where /// /// # Note /// - /// Only loads a value if `key` is set and if the value has not been loaded yet. - /// Returns the freshly loaded or already loaded entry of the value. + /// Only loads a value if `key` is set and if the value has not been loaded + /// yet. Returns the freshly loaded or already loaded entry of the + /// value. /// /// # Panics /// @@ -381,9 +384,9 @@ where /// - If the lazy chunk is not in a state that allows lazy loading. fn lazily_load_mut(&mut self, index: Index) -> &mut StorageEntry { // SAFETY: - // - Returning a `&mut Entry` is safe because entities inside the - // cache are stored within a `Box` to not invalidate references into - // them upon operating on the outer cache. + // - Returning a `&mut Entry` is safe because entities inside the cache are + // stored within a `Box` to not invalidate references into them upon operating + // on the outer cache. unsafe { &mut *self.lazily_load(index).as_ptr() } } @@ -427,7 +430,8 @@ where /// Swaps the values at indices `x` and `y`. /// - /// This operation tries to be as efficient as possible and reuse allocations. + /// This operation tries to be as efficient as possible and reuse + /// allocations. /// /// # Panics /// @@ -476,7 +480,8 @@ mod tests { }; use ink_primitives::Key; - /// Asserts that the cached entries of the given `imap` is equal to the `expected` slice. + /// Asserts that the cached entries of the given `imap` is equal to the + /// `expected` slice. fn assert_cached_entries( imap: &LazyIndexMap, expected: &[(Index, StorageEntry)], diff --git a/crates/storage/src/lazy/mod.rs b/crates/storage/src/lazy/mod.rs index c9726a57164..1aef060dbb1 100644 --- a/crates/storage/src/lazy/mod.rs +++ b/crates/storage/src/lazy/mod.rs @@ -60,7 +60,8 @@ use ink_primitives::Key; /// /// # Note /// -/// Use this if the storage field does not need to be loaded in some or most cases. +/// Use this if the storage field does not need to be loaded in some or most +/// cases. #[derive(Debug)] pub struct Lazy where @@ -145,7 +146,8 @@ where /// /// # Note /// - /// This loads the value from the contract storage if this did not happen before. + /// This loads the value from the contract storage if this did not happen + /// before. /// /// # Panics /// @@ -159,7 +161,8 @@ where /// /// # Note /// - /// This loads the value from the contract storage if this did not happen before. + /// This loads the value from the contract storage if this did not happen + /// before. /// /// # Panics /// diff --git a/crates/storage/src/lib.rs b/crates/storage/src/lib.rs index fac4024c3c8..feb37fa6a91 100644 --- a/crates/storage/src/lib.rs +++ b/crates/storage/src/lib.rs @@ -12,7 +12,8 @@ // See the License for the specific language governing permissions and // limitations under the License. -//! The `ink_storage` utilities used to manipulate and organize contract storage. +//! The `ink_storage` utilities used to manipulate and organize contract +//! storage. //! //! Mainly provides entities to work on a contract's storage //! as well as high-level collections on top of those. diff --git a/crates/storage/src/pack.rs b/crates/storage/src/pack.rs index 73e8520a7ad..7b9a1e20390 100644 --- a/crates/storage/src/pack.rs +++ b/crates/storage/src/pack.rs @@ -40,17 +40,17 @@ use ink_primitives::Key; /// # Usage /// /// - A `Pack` instance is equivalent to `i32` in its storage occupation. -/// - A `Pack<(i32, i32)>` instance will occupy a single cell compared to -/// `(i32, i32)` which occupies a cell per `i32`. -/// - A `Lazy>` lazily loads a `Pack<[u8; 8]>` which occupies -/// a single cell whereas a `[u8; 8]` array would occupy 8 cells in total, -/// one for each `u8`. +/// - A `Pack<(i32, i32)>` instance will occupy a single cell compared to `(i32, +/// i32)` which occupies a cell per `i32`. +/// - A `Lazy>` lazily loads a `Pack<[u8; 8]>` which occupies a +/// single cell whereas a `[u8; 8]` array would occupy 8 cells in total, one +/// for each `u8`. /// - Rust collections will never use more than a single cell. So /// `Pack>` and `LinkedList` will occupy the same amount of /// cells, namely 1. -/// - Packs can be packed. So for example a -/// `Pack<(Pack<(i32, i32)>, Pack<[u8; 8]>)` uses just one cell instead of -/// two cells which is the case for `(Pack<(i32, i32)>, Pack<[u8; 8]>)`. +/// - Packs can be packed. So for example a `Pack<(Pack<(i32, i32)>, Pack<[u8; +/// 8]>)` uses just one cell instead of two cells which is the case for +/// `(Pack<(i32, i32)>, Pack<[u8; 8]>)`. /// - Not all `storage` types can be packed. Only those that are implementing /// the `PackedLayout` trait. For example `storage::Vec` does not implement /// this trait and thus cannot be packed. diff --git a/crates/storage/src/test_utils.rs b/crates/storage/src/test_utils.rs index 68cbcc46ebb..b3539178f8d 100644 --- a/crates/storage/src/test_utils.rs +++ b/crates/storage/src/test_utils.rs @@ -29,9 +29,9 @@ where } /// Creates two tests: -/// (1) Tests if an object which is `push_spread`-ed to storage results in exactly -/// the same object when it is `pull_spread`-ed again. Subsequently the object -/// undergoes the same test for `push_packed` and `pull_packed`. +/// (1) Tests if an object which is `push_spread`-ed to storage results in +/// exactly the same object when it is `pull_spread`-ed again. Subsequently +/// the object undergoes the same test for `push_packed` and `pull_packed`. /// (2) Tests if `clear_spread` removes the object properly from storage. #[macro_export] macro_rules! push_pull_works_for_primitive { @@ -92,21 +92,21 @@ pub trait FuzzCollection { /// Creates two fuzz tests. Both tests have the same flow: /// - Take two instances of the collection, generated by our fuzzer -/// - Push `instance2` to storage, pull it out and assert that what -/// is pulled out is what was pushed. -/// - Do some mutations on the `pulled` object. Here the two tests -/// behave differently: +/// - Push `instance2` to storage, pull it out and assert that what is +/// pulled out is what was pushed. +/// - Do some mutations on the `pulled` object. Here the two tests behave +/// differently: /// /// * `fuzz_ $id _mutate_some` Mutates some entries of the data /// structure based on the content of `instance2`. /// -/// * `fuzz_ $id _mutate_all` Mutates the entire data structure, -/// so that it has the same content as `instance2`. +/// * `fuzz_ $id _mutate_all` Mutates the entire data structure, so that +/// it has the same content as `instance2`. /// -/// - Push the mutated `pulled` object into storage again, pull it -/// out as `pulled2` and assert that both objects are equal. -/// - Clear the object from storage and assert that storage was -/// cleared up properly, without any leftovers. +/// - Push the mutated `pulled` object into storage again, pull it out as +/// `pulled2` and assert that both objects are equal. +/// - Clear the object from storage and assert that storage was cleared up +/// properly, without any leftovers. #[macro_export] macro_rules! fuzz_storage { ($id:literal, $collection_type:ty) => { diff --git a/crates/storage/src/traits/mod.rs b/crates/storage/src/traits/mod.rs index d812bb1ae10..3554b8a647f 100644 --- a/crates/storage/src/traits/mod.rs +++ b/crates/storage/src/traits/mod.rs @@ -19,9 +19,9 @@ //! to tell a smart contract how to load and store instances of this type //! from and to the contract's storage. //! -//! The `PackedLayout` trait can then be implemented on top of the `SpreadLayout` -//! for types that further allow to be stored in the contract storage in a more -//! compressed format to a single storage cell. +//! The `PackedLayout` trait can then be implemented on top of the +//! `SpreadLayout` for types that further allow to be stored in the contract +//! storage in a more compressed format to a single storage cell. mod impls; mod keyptr; @@ -79,8 +79,8 @@ pub use ink_storage_derive::{ /// /// # Note /// -/// - The routine assumes that the instance has previously been stored to -/// the contract storage using spread layout. +/// - The routine assumes that the instance has previously been stored to the +/// contract storage using spread layout. /// - Users should prefer using this function directly instead of using the /// trait methods on [`SpreadLayout`]. pub fn pull_spread_root(root_key: &Key) -> T @@ -98,8 +98,8 @@ where /// /// # Note /// -/// - The routine assumes that the instance has previously been stored to -/// the contract storage using spread layout. +/// - The routine assumes that the instance has previously been stored to the +/// contract storage using spread layout. /// - Users should prefer using this function directly instead of using the /// trait method on [`SpreadAllocate`]. pub fn allocate_spread_root(root_key: &Key) -> T @@ -117,8 +117,8 @@ where /// /// # Note /// -/// - The routine assumes that the instance has previously been stored to -/// the contract storage using spread layout. +/// - The routine assumes that the instance has previously been stored to the +/// contract storage using spread layout. /// - Users should prefer using this function directly instead of using the /// trait methods on [`SpreadLayout`]. pub fn clear_spread_root(entity: &T, root_key: &Key) @@ -155,8 +155,8 @@ where /// /// # Note /// -/// - The routine assumes that the instance has previously been stored to -/// the contract storage using packed layout. +/// - The routine assumes that the instance has previously been stored to the +/// contract storage using packed layout. /// - Users should prefer using this function directly instead of using the /// trait methods on [`PackedLayout`]. pub fn pull_packed_root(root_key: &Key) -> T @@ -170,15 +170,16 @@ where entity } -/// Allocates an instance of type `T` to the contract storage using packed layout. +/// Allocates an instance of type `T` to the contract storage using packed +/// layout. /// /// The root key denotes the offset into the contract storage where the /// instance of type `T` is being allocated to. /// /// # Note /// -/// - The routine assumes that the instance has previously been stored to -/// the contract storage using packed layout. +/// - The routine assumes that the instance has previously been stored to the +/// contract storage using packed layout. /// - Users should prefer using this function directly instead of using the /// trait method on [`PackedAllocate`]. pub fn allocate_packed_root(root_key: &Key) -> T @@ -216,8 +217,8 @@ where /// /// # Note /// -/// - The routine assumes that the instance has previously been stored to -/// the contract storage using packed layout. +/// - The routine assumes that the instance has previously been stored to the +/// contract storage using packed layout. /// - Users should prefer using this function directly instead of using the /// trait methods on [`PackedLayout`]. pub fn clear_packed_root(entity: &T, root_key: &Key) diff --git a/crates/storage/src/traits/packed.rs b/crates/storage/src/traits/packed.rs index f701284521c..454d865d4dc 100644 --- a/crates/storage/src/traits/packed.rs +++ b/crates/storage/src/traits/packed.rs @@ -26,7 +26,8 @@ pub trait PackedAllocate: SpreadAllocate + PackedLayout { /// /// Most types will have to implement a trivial forwarding to their fields. /// However, some types such as [`storage::Box`](`crate::Box`) - /// are required to perform some special handling upon receiving this signal. + /// are required to perform some special handling upon receiving this + /// signal. fn allocate_packed(&mut self, at: &Key); } @@ -38,7 +39,8 @@ pub trait PackedLayout: SpreadLayout + scale::Encode + scale::Decode { /// /// Most types will have to implement a trivial forwarding to their fields. /// However, some types such as [`storage::Box`](`crate::Box`) - /// are required to perform some special handling upon receiving this signal. + /// are required to perform some special handling upon receiving this + /// signal. fn pull_packed(&mut self, at: &Key); /// Indicates to `self` that it is about to be pushed to contract storage. @@ -47,15 +49,18 @@ pub trait PackedLayout: SpreadLayout + scale::Encode + scale::Decode { /// /// Most types will have to implement a trivial forwarding to their fields. /// However, some types such as [`storage::Box`](`crate::Box`) - /// are required to perform some special handling upon receiving this signal. + /// are required to perform some special handling upon receiving this + /// signal. fn push_packed(&self, at: &Key); - /// Indicates to `self` that it is about to be cleared from contract storage. + /// Indicates to `self` that it is about to be cleared from contract + /// storage. /// /// # Note /// /// Most types will have to implement a trivial forwarding to their fields. /// However, some types such as [`storage::Box`](`crate::Box`) - /// are required to perform some special handling upon receiving this signal. + /// are required to perform some special handling upon receiving this + /// signal. fn clear_packed(&self, at: &Key); } diff --git a/crates/storage/src/traits/spread.rs b/crates/storage/src/traits/spread.rs index 651aae3084c..a4821c1f579 100644 --- a/crates/storage/src/traits/spread.rs +++ b/crates/storage/src/traits/spread.rs @@ -27,8 +27,8 @@ pub trait SpreadAllocate: SpreadLayout { /// /// # Note /// - /// - The key pointer denotes the position in contract storage where - /// the instance is being allocated at. + /// - The key pointer denotes the position in contract storage where the + /// instance is being allocated at. /// - Fields of `Self` are allocated in order and construct `Self` upon /// completion. fn allocate_spread(ptr: &mut KeyPtr) -> Self; @@ -50,20 +50,22 @@ pub trait SpreadLayout { /// has a footprint of 5. const FOOTPRINT: u64; - /// Indicates whether a type requires deep clean-up of its state meaning that - /// a clean-up routine has to decode an entity into an instance in order to - /// eventually recurse upon its tear-down. - /// This is not required for the majority of primitive data types such as `i32`, - /// however types such as `storage::Box` that might want to forward the clean-up - /// procedure to their inner `T` require a deep clean-up. + /// Indicates whether a type requires deep clean-up of its state meaning + /// that a clean-up routine has to decode an entity into an instance in + /// order to eventually recurse upon its tear-down. + /// This is not required for the majority of primitive data types such as + /// `i32`, however types such as `storage::Box` that might want to + /// forward the clean-up procedure to their inner `T` require a deep + /// clean-up. /// /// # Note /// - /// The default is set to `true` in order to have correctness by default since - /// no type invariants break if a deep clean-up is performed on a type that does - /// not need it but performing a shallow clean-up for a type that requires a - /// deep clean-up would break invariants. - /// This is solely a setting to improve performance upon clean-up for some types. + /// The default is set to `true` in order to have correctness by default + /// since no type invariants break if a deep clean-up is performed on a + /// type that does not need it but performing a shallow clean-up for a + /// type that requires a deep clean-up would break invariants. + /// This is solely a setting to improve performance upon clean-up for some + /// types. const REQUIRES_DEEP_CLEAN_UP: bool = true; /// Pulls an instance of `Self` from the contract storage. @@ -80,7 +82,8 @@ pub trait SpreadLayout { /// Pushes an instance of `Self` to the contract storage. /// /// - Tries to spread `Self` to as many storage cells as possible. - /// - The key pointer denotes the position where the instance is being pushed + /// - The key pointer denotes the position where the instance is being + /// pushed /// to the contract storage. /// /// # Note @@ -91,10 +94,10 @@ pub trait SpreadLayout { /// Clears an instance of `Self` from the contract storage. /// - /// - Tries to clean `Self` from contract storage as if `self` was stored - /// in it using spread layout. - /// - The key pointer denotes the position where the instance is being cleared - /// from the contract storage. + /// - Tries to clean `Self` from contract storage as if `self` was stored in + /// it using spread layout. + /// - The key pointer denotes the position where the instance is being + /// cleared from the contract storage. /// /// # Note ///