Merge pull request #6825 from ethereum/style-fixes-assembly

[DOCS] Bring code examples inline with style guide in assembly doc
This commit is contained in:
chriseth 2019-05-27 17:28:12 +02:00 committed by GitHub
commit dc0fac5dfd
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -104,27 +104,28 @@ efficient code, for example:
pragma solidity >=0.4.16 <0.7.0;
library VectorSum {
// This function is less efficient because the optimizer currently fails to
// remove the bounds checks in array access.
function sumSolidity(uint[] memory _data) public pure returns (uint o_sum) {
function sumSolidity(uint[] memory _data) public pure returns (uint sum) {
for (uint i = 0; i < _data.length; ++i)
o_sum += _data[i];
sum += _data[i];
}
// We know that we only access the array in bounds, so we can avoid the check.
// 0x20 needs to be added to an array because the first slot contains the
// array length.
function sumAsm(uint[] memory _data) public pure returns (uint o_sum) {
function sumAsm(uint[] memory _data) public pure returns (uint sum) {
for (uint i = 0; i < _data.length; ++i) {
assembly {
o_sum := add(o_sum, mload(add(add(_data, 0x20), mul(i, 0x20))))
sum := add(sum, mload(add(add(_data, 0x20), mul(i, 0x20))))
}
}
}
// Same as above, but accomplish the entire code within inline assembly.
function sumPureAsm(uint[] memory _data) public pure returns (uint o_sum) {
function sumPureAsm(uint[] memory _data) public pure returns (uint sum) {
assembly {
// Load the length (first 32 bytes)
let len := mload(_data)
@ -143,7 +144,7 @@ efficient code, for example:
lt(data, end)
{ data := add(data, 0x20) }
{
o_sum := add(o_sum, mload(data))
sum := add(sum, mload(data))
}
}
}
@ -693,6 +694,7 @@ We consider the runtime bytecode of the following Solidity program::
pragma solidity >=0.4.16 <0.7.0;
contract C {
function f(uint x) public pure returns (uint y) {
y = 1;