forked from germankuber/solidity-pattern-design
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path06.indexMapPattern.sol
More file actions
56 lines (45 loc) · 1.39 KB
/
06.indexMapPattern.sol
File metadata and controls
56 lines (45 loc) · 1.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
library IndexedMapping {
struct Data {
mapping(address => bool) valueExists;
mapping(address => uint256) valueIndex;
address[] valueList;
}
function add(Data storage self, address val) internal returns (bool) {
if (exists(self, val)) return false;
self.valueExists[val] = true;
self.valueIndex[val] = self.valueList.push(val) - 1;
return true;
}
function remove(Data storage self, address val) internal returns (bool) {
uint256 index;
address lastVal;
if (!exists(self, val)) return false;
index = self.valueIndex[val];
lastVal = self.valueList[self.valueList.length - 1];
// replace value with last value
self.valueList[index] = lastVal;
self.valueIndex[lastVal] = index;
self.valueList.length--;
// remove value
delete self.valueExists[val];
delete self.valueIndex[val];
return true;
}
function exists(Data storage self, address val)
internal
view
returns (bool)
{
return self.valueExists[val];
}
function getValue(Data storage self, uint256 index)
internal
view
returns (address)
{
return self.valueList[index];
}
function getValueList(Data storage self) internal view returns (address[]) {
return self.valueList;
}
}