You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
55 lines
1.5 KiB
55 lines
1.5 KiB
5 years ago
|
pragma solidity >=0.4.9 <0.6.0;
|
||
7 years ago
|
|
||
5 years ago
|
library Set {
|
||
7 years ago
|
// We define a new struct datatype that will be used to
|
||
|
// hold its data in the calling contract.
|
||
5 years ago
|
struct Data { mapping(uint => bool) flags; }
|
||
7 years ago
|
|
||
|
// Note that the first parameter is of type "storage
|
||
|
// reference" and thus only its storage address and not
|
||
|
// its contents is passed as part of the call. This is a
|
||
|
// special feature of library functions. It is idiomatic
|
||
|
// to call the first parameter 'self', if the function can
|
||
|
// be seen as a method of that object.
|
||
5 years ago
|
function insert(Data storage self, uint value) public
|
||
|
returns (bool)
|
||
|
{
|
||
|
if (self.flags[value])
|
||
|
return false; // already there
|
||
|
self.flags[value] = true;
|
||
7 years ago
|
|
||
5 years ago
|
return true;
|
||
|
}
|
||
7 years ago
|
|
||
5 years ago
|
function remove(Data storage self, uint value) public
|
||
|
returns (bool)
|
||
|
{
|
||
|
if (!self.flags[value])
|
||
|
return false; // not there
|
||
|
self.flags[value] = false;
|
||
|
return true;
|
||
|
}
|
||
7 years ago
|
|
||
5 years ago
|
function contains(Data storage self, uint value) public
|
||
|
returns (bool)
|
||
7 years ago
|
{
|
||
5 years ago
|
return self.flags[value];
|
||
7 years ago
|
}
|
||
|
}
|
||
|
|
||
|
|
||
|
contract C {
|
||
5 years ago
|
Set.Data knownValues;
|
||
7 years ago
|
|
||
6 years ago
|
function register(uint value) public {
|
||
7 years ago
|
// The library functions can be called without a
|
||
|
// specific instance of the library, since the
|
||
|
// "instance" will be the current contract.
|
||
6 years ago
|
address payable a;
|
||
7 years ago
|
a.send(10 wei);
|
||
5 years ago
|
if (!Set.insert(knownValues, value))
|
||
|
revert();
|
||
5 years ago
|
}
|
||
5 years ago
|
|
||
7 years ago
|
// In this contract, we can also directly access knownValues.flags, if we want.
|
||
|
}
|