Skip to content

Instantly share code, notes, and snippets.

@come-maiz
Last active August 13, 2019 01:31
Show Gist options
  • Save come-maiz/37794464c01522237eb47ad7a2a9fb7c to your computer and use it in GitHub Desktop.
Save come-maiz/37794464c01522237eb47ad7a2a9fb7c to your computer and use it in GitHub Desktop.
pragma solidity ^0.5.10;
contract AssemblyArrays {
bytes testArray;
function getLength() public view returns (uint256) {
return testArray.length;
}
function getElement(uint256 index) public view returns (bytes1) {
return testArray[index];
}
function pushElement(bytes1 value) public {
testArray.push(value);
}
function updateElement(bytes1 value, uint256 index) public {
testArray[index] = value;
}
}
pragma solidity ^0.5.10;
contract AssemblyArrays {
bytes testArray;
function getLength() public view returns (uint256) {
bytes memory memoryTestArray = testArray;
uint256 result;
assembly {
result := mload(memoryTestArray)
}
return result;
}
function getElement(uint256 index) public view returns (bytes1) {
return testArray[index];
}
function pushElement(bytes1 value) public {
testArray.push(value);
}
function updateElement(bytes1 value, uint256 index) public {
testArray[index] = value;
}
}
pragma solidity ^0.5.10;
contract AssemblyArrays {
bytes testArray;
function getLength() public view returns (uint256) {
bytes memory memoryTestArray = testArray;
uint256 result;
assembly {
result := mload(memoryTestArray)
}
return result;
}
function getElement(uint256 index) public view returns (bytes1) {
uint256 length = getLength();
require(index < length);
bytes memory memoryTestArray = testArray;
bytes1 result;
assembly {
let wordIndex := div(index, 32)
let initialElement := add(memoryTestArray, 32)
let resultWord := mload(add(initialElement, mul(wordIndex, 32)))
let indexInWord := mod(index, 32)
result := shl(mul(indexInWord, 8), resultWord)
}
return result;
}
function pushElement(bytes1 value) public {
testArray.push(value);
}
function updateElement(bytes1 value, uint256 index) public {
testArray[index] = value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment