跳到主要内容

libraries/eosiolib/contracts/eosio/singleton.hpp

Namespaces

Name
eosio

Classes

Name
classeosio::singleton

Source code

#pragma once
#include "multi_index.hpp"
#include "system.hpp"

namespace eosio {

template<name::raw SingletonName, typename T>
class singleton
{
constexpr static uint64_t pk_value = static_cast<uint64_t>(SingletonName);

struct row {
T value;

uint64_t primary_key() const { return pk_value; }

EOSLIB_SERIALIZE( row, (value) )
};

typedef eosio::multi_index<SingletonName, row> table;

public:

singleton( name code, uint64_t scope ) : _t( code, scope ) {}

bool exists() {
return _t.find( pk_value ) != _t.end();
}

T get() {
auto itr = _t.find( pk_value );
eosio::check( itr != _t.end(), "singleton does not exist" );
return itr->value;
}

T get_or_default( const T& def = T() ) {
auto itr = _t.find( pk_value );
return itr != _t.end() ? itr->value : def;
}

T get_or_create( name bill_to_account, const T& def = T() ) {
auto itr = _t.find( pk_value );
return itr != _t.end() ? itr->value
: _t.emplace(bill_to_account, [&](row& r) { r.value = def; })->value;
}

void set( const T& value, name bill_to_account ) {
auto itr = _t.find( pk_value );
if( itr != _t.end() ) {
_t.modify(itr, bill_to_account, [&](row& r) { r.value = value; });
} else {
_t.emplace(bill_to_account, [&](row& r) { r.value = value; });
}
}

void remove( ) {
auto itr = _t.find( pk_value );
if( itr != _t.end() ) {
_t.erase(itr);
}
}

private:
table _t;
};
}

Updated on 2022-12-05 at 15:38:08 +0000