-
Notifications
You must be signed in to change notification settings - Fork 1
/
Bytes32Set.sol
70 lines (63 loc) · 2.22 KB
/
Bytes32Set.sol
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
pragma solidity 0.5.12;
// SPDX-License-Identifier: Unlicensed
// https://github.com/rob-Hitchens/SetTypes/blob/master/contracts/Bytes32Set.sol
library Bytes32Set {
struct Set {
mapping(bytes32 => uint256) keyPointers;
bytes32[] keyList;
}
/**
* @notice insert a key.
* @dev duplicate keys are not permitted.
* @param self storage pointer to a Set.
* @param key value to insert.
*/
function insert(Set storage self, bytes32 key) internal {
require(!exists(self, key), "Bytes32Set: key already exists in the set.");
self.keyPointers[key] = self.keyList.length;
self.keyList.push(key);
}
/**
* @notice remove a key.
* @dev key to remove must exist.
* @param self storage pointer to a Set.
* @param key value to remove.
*/
function remove(Set storage self, bytes32 key) internal {
require(exists(self, key), "Bytes32Set: key does not exist in the set.");
uint256 last = count(self) - 1;
uint256 rowToReplace = self.keyPointers[key];
if (rowToReplace != last) {
bytes32 keyToMove = self.keyList[last];
self.keyPointers[keyToMove] = rowToReplace;
self.keyList[rowToReplace] = keyToMove;
}
delete self.keyPointers[key];
self.keyList.pop();
}
/**
* @notice count the keys.
* @param self storage pointer to a Set.
*/
function count(Set storage self) internal view returns (uint256) {
return (self.keyList.length);
}
/**
* @notice check if a key is in the Set.
* @param self storage pointer to a Set.
* @param key value to check.
* @return bool true: Set member, false: not a Set member.
*/
function exists(Set storage self, bytes32 key) internal view returns (bool) {
if (self.keyList.length == 0) return false;
return self.keyList[self.keyPointers[key]] == key;
}
/**
* @notice fetch a key by row (enumerate).
* @param self storage pointer to a Set.
* @param index row to enumerate. Must be < count() - 1.
*/
function keyAtIndex(Set storage self, uint256 index) internal view returns (bytes32) {
return self.keyList[index];
}
}