-
-
Save Arachnid/59159497f124fdbff14bc2ca960b77ba to your computer and use it in GitHub Desktop.
library itmap { | |
struct entry { | |
// Equal to the index of the key of this item in keys, plus 1. | |
uint keyIndex; | |
uint value; | |
} | |
struct itmap { | |
mapping(uint => entry) data; | |
uint[] keys; | |
} | |
function insert(itmap storage self, uint key, uint value) internal returns (bool replaced) { | |
entry storage e = self.data[key]; | |
e.value = value; | |
if (e.keyIndex > 0) { | |
return true; | |
} else { | |
e.keyIndex = ++self.keys.length; | |
self.keys[e.keyIndex - 1] = key; | |
return false; | |
} | |
} | |
function remove(itmap storage self, uint key) internal returns (bool success) { | |
entry storage e = self.data[key]; | |
if (e.keyIndex == 0) | |
return false; | |
if (e.keyIndex < self.keys.length) { | |
// Move an existing element into the vacated key slot. | |
self.data[self.keys[self.keys.length - 1]].keyIndex = e.keyIndex; | |
self.keys[e.keyIndex - 1] = self.keys[self.keys.length - 1]; | |
self.keys.length -= 1; | |
delete self.data[key]; | |
} | |
} | |
function contains(itmap storage self, uint key) internal returns (bool exists) { | |
return self.data[key].keyIndex > 0; | |
} | |
function size(itmap storage self) internal returns (uint) { | |
return self.keys.length; | |
} | |
function get(itmap storage self, uint key) internal returns (uint value) { | |
return self.data[key].value; | |
} | |
function getKey(itmap storage self, uint idx) internal returns (uint value) { | |
return self.keys[idx]; | |
} | |
} | |
contract Test { | |
// Use itmap for all functions on the struct | |
using itmap for itmap.itmap; | |
// Declare an iterable mapping | |
itmap.itmap mymap; | |
function insert(uint key, uint value) { | |
mymap.insert(key, value); | |
} | |
function get(uint key) returns (uint value) { | |
return mymap.get(key); | |
} | |
} |
keyIndex
should be uint as it by design always ends up 0 or higher? <--- this actually is now already implemented, I had an older version
.
Clearer to make the name of the name of the return value of the function getKey
be "key" instead of "value" on line 51 https://gist.github.com/Arachnid/59159497f124fdbff14bc2ca960b77ba#file-itmap-sol-L51
Shouldn't the get
s be constant functions as they are not transactions?
Missing a return value at line 63 https://gist.github.com/Arachnid/59159497f124fdbff14bc2ca960b77ba#file-itmap-sol-L63
Hi! I've tweaked this, fixed a bug (it wasn't removing the item when there was only 1 item in map) plus added a few new type mappings.
All of it in a new repo: https://github.com/szerintedmi/solidity-itMapsLib
You don't have any license here, so I've added Apache 2.0. Please let me know if you have any issue with that license.
Suggestions about my changes are welcome too! :)
This line https://gist.github.com/Arachnid/59159497f124fdbff14bc2ca960b77ba#file-itmap-sol-L36 is missing a
return true
upon success.