-
-
Save D-Nice/f25d907ead094274f3def7943320abd2 to your computer and use it in GitHub Desktop.
How to use string as a key in a mapping in Solidity aka. how to store short strings cheape
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
// | |
// In Solidity, a mapping is like a hashmap and works with `string` like this: | |
// mapping (string => uint) a; | |
// | |
// However it doesn't support accessors where string is a key: | |
// mapping (string => uint) public a; | |
// | |
// "Internal compiler error: Accessors for mapping with dynamically-sized keys not yet implemented." | |
// | |
// An accessor returns uint when called as `a(string)`. | |
// | |
// As a short term solution, until it is implemented in Solidity, use the conversion code below. It also uses half as much storage space. | |
// | |
// See more utilities soon at https://github.com/axic/density | |
// | |
library StringAsKey { | |
function convert(string key) returns (bytes32 ret) { | |
if (bytes(key).length > 32) { | |
throw; | |
} | |
assembly { | |
ret := mload(add(key, 32)) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment