Skip to content

Instantly share code, notes, and snippets.

@axic
Last active July 10, 2019 00:10
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save axic/ce82bdd1763c04ef8138c2b905985dab to your computer and use it in GitHub Desktop.
Save axic/ce82bdd1763c04ef8138c2b905985dab 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))
}
}
}
@amilano
Copy link

amilano commented Aug 30, 2017

Thanks for this solution, but can you explain how is this applied? for what I understand this solution propose to declare the mapping like this(?): mapping (bytes32 => uint) public a;, is that right?

so to access the mapping one should do like this: a[convert("some_key")];

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