Skip to content

Instantly share code, notes, and snippets.

@D-Nice
Forked from axic/stringaskey.sol
Created August 20, 2016 18:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save D-Nice/f25d907ead094274f3def7943320abd2 to your computer and use it in GitHub Desktop.
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
//
// 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