Last active
October 14, 2017 21:35
-
-
Save willitscale/6d472ddb1fd7e9a3aa20f26310372061 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
pragma solidity ^0.4.0; | |
contract Array { | |
uint[] arr; | |
function setup() internal { | |
arr.push(1); | |
arr.push(3); | |
arr.push(2); | |
arr.push(4); | |
} | |
function returnBytes() returns(uint[]) { | |
setup(); | |
return bytesToArray(toBytes(arr)); | |
} | |
function returnArray() returns(uint[]) { | |
setup(); | |
return toArray(arr); | |
} | |
function bytesToArray(bytes _bytes) | |
internal | |
returns (uint[]) { | |
assembly { | |
let len := mload(add(_bytes, 0x40)) | |
let _ptr := msize() | |
mstore(_ptr, 0x20) | |
mstore(add(_ptr, 0x20), len) | |
let idx := 0 | |
loop: | |
jumpi(end, eq(len, idx)) | |
mstore(add(_ptr, add(mul(idx,0x20),0x40)), mload(add(_bytes, add(0x40, mul(idx, 0x20))))) | |
idx := add(idx, 1) | |
jump(loop) | |
end: | |
return(_ptr, add(mul(len, 0x20), 0x20)) | |
} | |
} | |
function toBytes(uint[] _arr) | |
internal | |
returns (bytes) { | |
assembly { | |
let len := mload(_arr) | |
let _ptr := msize() | |
mstore(_ptr, mul(add(len, 2), 0x20)) | |
mstore(add(_ptr, 0x20), 0x20) | |
mstore(add(_ptr, 0x40), len) | |
let idx := 0 | |
loop: | |
jumpi(end, eq(len, idx)) | |
mstore(add(_ptr, add(mul(idx,0x20),0x60)), mload(add(_arr, add(0x20, mul(idx, 0x20))))) | |
idx := add(idx, 1) | |
jump(loop) | |
end: | |
return(_ptr, add(mul(len, 0x20), 0x60)) | |
} | |
} | |
function toArray(uint[] _arr) | |
internal | |
returns (uint[]) { | |
assembly { | |
let len := mload(_arr) | |
let _ptr := msize() | |
mstore(_ptr, 0x20) | |
mstore(add(_ptr, 0x20), len) | |
let idx := 0 | |
loop: | |
jumpi(end, eq(len, idx)) | |
mstore(add(_ptr, add(mul(idx,0x20),0x40)), mload(add(_arr, add(0x20, mul(idx, 0x20))))) | |
idx := add(idx, 1) | |
jump(loop) | |
end: | |
return(_ptr, add(mul(len, 0x20), 0x40)) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment