Created
December 19, 2015 08:59
-
-
Save androlo/25392c8db5a3077f2117 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| contract AddressMapper { | |
| struct IAMElement { | |
| uint keyIndex; | |
| bool value; | |
| } | |
| struct IAMap | |
| { | |
| mapping(address => IAMElement) data; | |
| address[] keys; | |
| uint size; | |
| } | |
| function _insert(IAMap storage map, address key, bool value) internal returns (bool added) | |
| { | |
| var exists = map.data[key].value; | |
| if (exists){ | |
| return false; | |
| } else { | |
| var keyIndex = map.keys.length++; | |
| map.data[key] = IAMElement(keyIndex, value); | |
| map.keys[keyIndex] = key; | |
| map.size++; | |
| return true; | |
| } | |
| } | |
| function _remove(IAMap storage map, address key) internal returns (bool removed) | |
| { | |
| var elem = map.data[key]; | |
| var exists = elem.value; | |
| if (!exists){ | |
| return false; | |
| } | |
| var keyIndex = elem.keyIndex; | |
| delete map.data[key]; | |
| var len = map.keys.length; | |
| if(keyIndex != len - 1){ | |
| var swap = map.keys[len - 1]; | |
| map.keys[keyIndex] = swap; | |
| map.data[swap].keyIndex = keyIndex; | |
| } | |
| map.keys.length--; | |
| map.size--; | |
| return true; | |
| } | |
| function _removeAll(IAMap storage map) internal returns (uint numRemoved){ | |
| var l = map.keys.length; | |
| for(uint i = 0; i < l; i++){ | |
| delete map.data[map.keys[i]]; | |
| } | |
| delete map.keys; | |
| map.size = 0; | |
| return l; | |
| } | |
| function _hasKey(IAMap storage map, address key) internal constant returns (bool has){ | |
| return map.data[key].value; | |
| } | |
| function _keyIndex(IAMap storage map, address key) internal constant returns (int index){ | |
| var elem = map.data[key]; | |
| if(!elem.value){ | |
| return -1; | |
| } | |
| return int(elem.keyIndex); | |
| } | |
| function _keyFromIndex(IAMap storage map, uint index) internal constant returns (address key){ | |
| if(index >= map.keys.length){ | |
| return 0; | |
| } | |
| return map.keys[index]; | |
| } | |
| function _size(IAMap storage map) internal constant returns (uint size){ | |
| return map.size; | |
| } | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment