Code has been added to clipboard!
Solidity Libraries Example 1
Example
pragma solidity ^0.4.11;
library SetLib {
// This will define a whole new struct data type which is going
// to be used for holding its data inside the calling contract.
struct LibData { mapping(uint => bool) flagsMapping; }
// Notice how the first parameter's type is "storage
// reference" therefore it is only its storage address instead of
// its contents being passed along with the call. That is the
// Library functions' special feature. Calling the first
// parameter "selfStore" is idiomatic, if it happens so that the
// function can be seen as that object's.
function insertData(LibData storage selfStore, uint value)
returns (bool)
{
if (selfStore.flagsMapping[value])
return false; // is already there
selfStore.flagsMapping[value] = true;
return true;
}
function removeData(LibData storage selfStore, uint value)
returns (bool)
{
if (!selfStore.flagsMapping[value])
return false; // is not there
selfStore.flagsMapping[value] = false;
return true;
}
function contains(LibData storage selfStore, uint value)
returns (bool)
{
return selfStore.flagsMapping[value];
}
}
contract Cont {
SetLib.LibData valuesKnown;
function registerData(uint value) {
// The functions of the library may be called without a
// certain instance of the library, because the
// "instance" is going to be the current contract.
require(SetLib.insertData(valuesKnown, value));
}
// Inside this contract, it's possible to directly access valuesKnown.flagsMapping too, in case we want.
}