-
-
Save brianonn/ec7cc6367997093e475632daa81f4027 to your computer and use it in GitHub Desktop.
pragma solidity ^0.4.17; | |
contract StringMap { | |
mapping(bytes32 => string) map; | |
function add(string key, string value, bool overwrite) public returns (bool) { | |
bytes32 hash = keccak256(key); | |
// overwrite existing entries only if the overwrite flag is set | |
// or if a lookup returns length 0 at that location. | |
if (overwrite || bytes(map[hash]).length == 0) { | |
map[hash] = value; | |
return true; | |
} | |
return false; | |
} | |
function addByHash(bytes32 hash, string value, bool overwrite) public returns (bool) { | |
if (overwrite || bytes(map[hash]).length == 0) { | |
map[hash] = value; | |
return true; | |
} | |
return false; | |
} | |
function get(string key) public view returns (string) { | |
bytes32 hash = keccak256(key); | |
return map[hash]; | |
} | |
function getHash(string key) public pure returns (bytes32) { | |
return keccak256(key); | |
} | |
} |
smart, thanks!
so cant directlly use string in mapping ?
@Javadyakuza That code is maybe 4 to 5 years old. In the version of Solidity listed there, 0.4.17, it was not possible to make a public mapping string to string, only private or internal visibility worked. However, this has since been fixed in current Solidity and it's now possible to map string to string with either public, private or internal visibility. When doing so, Solidity will use the keccak256 hash behind the scenes for string typed keys. So all is good today with Solidity 0.8.x
Having said that, back when this code was necessary, it would have been cheaper in gas costs to use a fixed size bytes32 hash for the key, especially with larger strings, since the majority of gas cost of a transaction comes from SSTORE operations and reducing the number of SSTOREs is always good.
Solidity mapping string to string using a hashmap.