Memory Example
function getData(uint value) public view returns (bytes32 output) {
assembly {
function allocate(length) -> pos {
let freePointer := 0x40
pos := mload(freePointer)
mstore(freePointer, add(pos,length))
}
let dataSize := 0x20 // 32 bytes
let offset := allocate(dataSize)
mstore(offset, value)
return(offset, dataSize)
}
}
Calldata demo
// return calldata as bytes output
function getData(uint input) public view returns (bytes memory output) {
assembly {
let base := mload(0x40)
mstore(add(base, 0x00), 0x20) // pointer to data
mstore(add(base, 0x20), 36) // data length
calldatacopy(add(base, 0x40), 0, 36) // data from byte 0
return(base, 0x80)
}
}
Storage demo
uint8 data1 = 1;
uint8 data2 = 2;
uint8 data3 = 3;
uint8 data4 = 4;
// get data3 and return it as ouput
function getData() public view returns(bytes32){
assembly {
let data := sload(data3_slot)
let result := and(shr(shl(3,data3.offset), data), 0xff)
mstore(0, result)
return(0,32)
}
}