Skip to content

Instantly share code, notes, and snippets.

@tjade273
Last active December 13, 2016 21:22
Show Gist options
  • Save tjade273/a5203a2dff4d60fe525139c1d2ecd207 to your computer and use it in GitHub Desktop.
Save tjade273/a5203a2dff4d60fe525139c1d2ecd207 to your computer and use it in GitHub Desktop.
contract StringStore {
mapping(uint => string) public myStrings;
function storeString(string str, uint i) public {
myStrings[i] = str;
}
}
contract GetString {
function getString(address store, uint i) constant returns (string s, uint l){
bytes4 sig = bytes4(sha3("myStrings(uint256)"));
bool success; // This will be false if either call OOGs
assembly{
let m := mload(0x40) //Free memory pointer
mstore(m,sig)
mstore(add(m,4),i) // Write arguments to memory- align directly after function sig.
success := call( //Fetch string size
sub(gas,8000), // g
store, // a
0, // v
m, // in
0x24, // insize: 4 byte sig + 32 byte uint
add(m,0x24), // Out pointer: don't overwrite the call data, we need it again
0x40 // Only fetch the first 64 bytes of the string data.
)
l := mload(add(m,0x44)) // returned data stats at 0x24, length is stored in the second 32-byte slot
success := and(success,call(sub(gas,4000),store, 0,
m, // Reuse the same argument data
0x24,
m, // We can overwrite the calldata now to save space
add(l,0x40) // The length of the returned data will be 64 bytes of metadata + string length
))
s := add(m, mload(m)) // First slot points to the start o the string (will almost always be m+0x20)
mstore(0x40, add(m,add(l,0x40))) //Move free memory pointer so string doesn't get overwritten
}
if(!success) throw;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment