Skip to content

Instantly share code, notes, and snippets.

@brianonn
Last active May 19, 2022 10:41
Show Gist options
  • Save brianonn/ec7cc6367997093e475632daa81f4027 to your computer and use it in GitHub Desktop.
Save brianonn/ec7cc6367997093e475632daa81f4027 to your computer and use it in GitHub Desktop.
solidity mapping string to string
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);
}
}
@brianonn
Copy link
Author

brianonn commented Mar 30, 2018

Solidity mapping string to string using a hashmap.

@snissn
Copy link

snissn commented Feb 5, 2022

smart, thanks!

@Javadyakuza
Copy link

so cant directlly use string in mapping ?

@brianonn
Copy link
Author

@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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment