text
stringlengths 5
1.04M
|
|---|
/* Copyright (c) 2020 UATC, LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#pragma once
#include "neuropod/internal/memory_utils.hh"
#include "neuropod/internal/tensor_types.hh"
#include <memory>
#include <string>
#include <unordered_map>
#include <vector>
namespace neuropod
{
// Device types that are supported in the Neuropod configuration
typedef int NeuropodDeviceType;
namespace DeviceType
{
constexpr int CPU = 0;
constexpr int GPU = 1;
}; // namespace DeviceType
// A struct that stores the value of a dimension
struct Dimension
{
Dimension(int64_t value);
Dimension(std::string symbol);
~Dimension();
bool operator==(const Dimension &other) const;
// The value
// -1 == Any value is allowed (None/null)
// -2 == Symbol
int64_t value;
// The name of this symbol (if it is a symbol)
std::string symbol;
};
// A struct that stores a specification for a tensor
struct TensorSpec
{
TensorSpec(const std::string &name, const std::vector<Dimension> dims, const TensorType type);
~TensorSpec();
const std::string name;
const std::vector<Dimension> dims;
const TensorType type;
};
// A struct that stores the expected inputs and outputs of a model
struct ModelConfig
{
const std::string name;
const std::string platform;
// The requested versions of the platform specified as a semver range
// e.g. `1.13.1` or `> 1.13.1`
// See the following URLs for examples and more info:
// - https://semver.org/
// - https://docs.npmjs.com/misc/semver#ranges
// - https://docs.npmjs.com/misc/semver#advanced-range-syntax
const std::string platform_version_semver;
const std::vector<TensorSpec> inputs;
const std::vector<TensorSpec> outputs;
const std::vector<std::string> custom_ops;
// A map from an input tensor name to a device type
const std::unordered_map<std::string, NeuropodDeviceType> input_tensor_device;
};
std::unique_ptr<ModelConfig> load_model_config(const std::string &neuropod_path);
std::unique_ptr<ModelConfig> load_model_config(std::istream &input_stream);
} // namespace neuropod
|
/* Code generated by IfcQuery EXPRESS generator, www.ifcquery.com */
#include <sstream>
#include <limits>
#include "ifcpp/model/AttributeObject.h"
#include "ifcpp/model/BuildingException.h"
#include "ifcpp/model/BuildingGuid.h"
#include "ifcpp/reader/ReaderUtil.h"
#include "ifcpp/writer/WriterUtil.h"
#include "ifcpp/IFC4/include/IfcComplexPropertyTemplate.h"
#include "ifcpp/IFC4/include/IfcComplexPropertyTemplateTypeEnum.h"
#include "ifcpp/IFC4/include/IfcGloballyUniqueId.h"
#include "ifcpp/IFC4/include/IfcLabel.h"
#include "ifcpp/IFC4/include/IfcOwnerHistory.h"
#include "ifcpp/IFC4/include/IfcPropertySetTemplate.h"
#include "ifcpp/IFC4/include/IfcPropertyTemplate.h"
#include "ifcpp/IFC4/include/IfcRelAssociates.h"
#include "ifcpp/IFC4/include/IfcRelDeclares.h"
#include "ifcpp/IFC4/include/IfcText.h"
// ENTITY IfcComplexPropertyTemplate
IfcComplexPropertyTemplate::IfcComplexPropertyTemplate() {}
IfcComplexPropertyTemplate::IfcComplexPropertyTemplate( int id ) { m_entity_id = id; }
IfcComplexPropertyTemplate::~IfcComplexPropertyTemplate() {}
shared_ptr<BuildingObject> IfcComplexPropertyTemplate::getDeepCopy( BuildingCopyOptions& options )
{
shared_ptr<IfcComplexPropertyTemplate> copy_self( new IfcComplexPropertyTemplate() );
if( m_GlobalId )
{
if( options.create_new_IfcGloballyUniqueId ) { copy_self->m_GlobalId = shared_ptr<IfcGloballyUniqueId>(new IfcGloballyUniqueId( createBase64Uuid<wchar_t>().data() ) ); }
else { copy_self->m_GlobalId = dynamic_pointer_cast<IfcGloballyUniqueId>( m_GlobalId->getDeepCopy(options) ); }
}
if( m_OwnerHistory )
{
if( options.shallow_copy_IfcOwnerHistory ) { copy_self->m_OwnerHistory = m_OwnerHistory; }
else { copy_self->m_OwnerHistory = dynamic_pointer_cast<IfcOwnerHistory>( m_OwnerHistory->getDeepCopy(options) ); }
}
if( m_Name ) { copy_self->m_Name = dynamic_pointer_cast<IfcLabel>( m_Name->getDeepCopy(options) ); }
if( m_Description ) { copy_self->m_Description = dynamic_pointer_cast<IfcText>( m_Description->getDeepCopy(options) ); }
if( m_UsageName ) { copy_self->m_UsageName = dynamic_pointer_cast<IfcLabel>( m_UsageName->getDeepCopy(options) ); }
if( m_TemplateType ) { copy_self->m_TemplateType = dynamic_pointer_cast<IfcComplexPropertyTemplateTypeEnum>( m_TemplateType->getDeepCopy(options) ); }
for( size_t ii=0; ii<m_HasPropertyTemplates.size(); ++ii )
{
auto item_ii = m_HasPropertyTemplates[ii];
if( item_ii )
{
copy_self->m_HasPropertyTemplates.push_back( dynamic_pointer_cast<IfcPropertyTemplate>(item_ii->getDeepCopy(options) ) );
}
}
return copy_self;
}
void IfcComplexPropertyTemplate::getStepLine( std::stringstream& stream ) const
{
stream << "#" << m_entity_id << "= IFCCOMPLEXPROPERTYTEMPLATE" << "(";
if( m_GlobalId ) { m_GlobalId->getStepParameter( stream ); } else { stream << "*"; }
stream << ",";
if( m_OwnerHistory ) { stream << "#" << m_OwnerHistory->m_entity_id; } else { stream << "*"; }
stream << ",";
if( m_Name ) { m_Name->getStepParameter( stream ); } else { stream << "*"; }
stream << ",";
if( m_Description ) { m_Description->getStepParameter( stream ); } else { stream << "*"; }
stream << ",";
if( m_UsageName ) { m_UsageName->getStepParameter( stream ); } else { stream << "$"; }
stream << ",";
if( m_TemplateType ) { m_TemplateType->getStepParameter( stream ); } else { stream << "$"; }
stream << ",";
writeEntityList( stream, m_HasPropertyTemplates );
stream << ");";
}
void IfcComplexPropertyTemplate::getStepParameter( std::stringstream& stream, bool ) const { stream << "#" << m_entity_id; }
const std::wstring IfcComplexPropertyTemplate::toString() const { return L"IfcComplexPropertyTemplate"; }
void IfcComplexPropertyTemplate::readStepArguments( const std::vector<std::wstring>& args, const std::map<int,shared_ptr<BuildingEntity> >& map )
{
const size_t num_args = args.size();
if( num_args != 7 ){ std::stringstream err; err << "Wrong parameter count for entity IfcComplexPropertyTemplate, expecting 7, having " << num_args << ". Entity ID: " << m_entity_id << std::endl; throw BuildingException( err.str().c_str() ); }
m_GlobalId = IfcGloballyUniqueId::createObjectFromSTEP( args[0], map );
readEntityReference( args[1], m_OwnerHistory, map );
m_Name = IfcLabel::createObjectFromSTEP( args[2], map );
m_Description = IfcText::createObjectFromSTEP( args[3], map );
m_UsageName = IfcLabel::createObjectFromSTEP( args[4], map );
m_TemplateType = IfcComplexPropertyTemplateTypeEnum::createObjectFromSTEP( args[5], map );
readEntityReferenceList( args[6], m_HasPropertyTemplates, map );
}
void IfcComplexPropertyTemplate::getAttributes( std::vector<std::pair<std::string, shared_ptr<BuildingObject> > >& vec_attributes )
{
IfcPropertyTemplate::getAttributes( vec_attributes );
vec_attributes.push_back( std::make_pair( "UsageName", m_UsageName ) );
vec_attributes.push_back( std::make_pair( "TemplateType", m_TemplateType ) );
if( m_HasPropertyTemplates.size() > 0 )
{
shared_ptr<AttributeObjectVector> HasPropertyTemplates_vec_object( new AttributeObjectVector() );
std::copy( m_HasPropertyTemplates.begin(), m_HasPropertyTemplates.end(), std::back_inserter( HasPropertyTemplates_vec_object->m_vec ) );
vec_attributes.push_back( std::make_pair( "HasPropertyTemplates", HasPropertyTemplates_vec_object ) );
}
}
void IfcComplexPropertyTemplate::getAttributesInverse( std::vector<std::pair<std::string, shared_ptr<BuildingObject> > >& vec_attributes_inverse )
{
IfcPropertyTemplate::getAttributesInverse( vec_attributes_inverse );
}
void IfcComplexPropertyTemplate::setInverseCounterparts( shared_ptr<BuildingEntity> ptr_self_entity )
{
IfcPropertyTemplate::setInverseCounterparts( ptr_self_entity );
shared_ptr<IfcComplexPropertyTemplate> ptr_self = dynamic_pointer_cast<IfcComplexPropertyTemplate>( ptr_self_entity );
if( !ptr_self ) { throw BuildingException( "IfcComplexPropertyTemplate::setInverseCounterparts: type mismatch" ); }
for( size_t i=0; i<m_HasPropertyTemplates.size(); ++i )
{
if( m_HasPropertyTemplates[i] )
{
m_HasPropertyTemplates[i]->m_PartOfComplexTemplate_inverse.push_back( ptr_self );
}
}
}
void IfcComplexPropertyTemplate::unlinkFromInverseCounterparts()
{
IfcPropertyTemplate::unlinkFromInverseCounterparts();
for( size_t i=0; i<m_HasPropertyTemplates.size(); ++i )
{
if( m_HasPropertyTemplates[i] )
{
std::vector<weak_ptr<IfcComplexPropertyTemplate> >& PartOfComplexTemplate_inverse = m_HasPropertyTemplates[i]->m_PartOfComplexTemplate_inverse;
for( auto it_PartOfComplexTemplate_inverse = PartOfComplexTemplate_inverse.begin(); it_PartOfComplexTemplate_inverse != PartOfComplexTemplate_inverse.end(); )
{
weak_ptr<IfcComplexPropertyTemplate> self_candidate_weak = *it_PartOfComplexTemplate_inverse;
if( self_candidate_weak.expired() )
{
++it_PartOfComplexTemplate_inverse;
continue;
}
shared_ptr<IfcComplexPropertyTemplate> self_candidate( *it_PartOfComplexTemplate_inverse );
if( self_candidate.get() == this )
{
it_PartOfComplexTemplate_inverse= PartOfComplexTemplate_inverse.erase( it_PartOfComplexTemplate_inverse );
}
else
{
++it_PartOfComplexTemplate_inverse;
}
}
}
}
}
|
//----------------------------------------------------------------------
// Copyright 2004-2011 Synopsys, Inc.
// Copyright 2010 Mentor Graphics Corporation
// Copyright 2010-2011 Cadence Design Systems, Inc.
// Copyright 2013-2014 NXP B.V.
// All Rights Reserved Worldwide
//
// Licensed under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in
// compliance with the License. You may obtain a copy of
// the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in
// writing, software distributed under the License is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See
// the License for the specific language governing
// permissions and limitations under the License.
//----------------------------------------------------------------------
#include <systemc>
#include <uvm>
#include "tb_env.h"
#include "tb_test.h"
//----------------------------------------------------------------------
// This example demonstrates how to model a register containing
// read-only fields and a register containing write-only fields
// at the same physical address.
//----------------------------------------------------------------------
int sc_main(int, char*[])
{
tb_env* env;
tb_test* test;
env = new tb_env("env");
test = new tb_test("test");
uvm::uvm_root::get()->set_report_verbosity_level(uvm::UVM_FULL);
test->set_report_verbosity_level(uvm::UVM_FULL);
env->set_report_verbosity_level(uvm::UVM_FULL);
uvm::uvm_report_server::get_server()->set_max_quit_count(10);
uvm::run_test();
delete env;
delete test;
return 0;
}
|
#include <bits/stdc++.h>
using namespace std;
#define fast ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
typedef long long ll;typedef long double ld;typedef pair<int,int> pii;
#define F first
#define S second
#define PB push_back
#define MP make_pair
const ll mod = 1e9+7, N = 2e6+7, M = 2e6+7, INF = INT_MAX/10;
ll powe(ll x, ll y){ x = x%mod, y=y%(mod-1);ll ans = 1;while(y>0){if (y&1){ans = (1ll * x * ans)%mod;}y>>=1;x = (1ll * x * x)%mod;}return ans;}
//Sum Of the elements of an array
void input_of_array(int arr[],int n)
{
for (int i =0;i<n;i++)
{
cin>>arr[i];
}
}
void rotating_the_array(int arr[], int n)
{
int m;
cin>>m;
for(int i=0;i<m;i++)
{
int temp =arr[0];
for(int j=0;j<n;j++)
{
if(j==n-1)
{
arr[j]=temp;
}
else
{
arr[j]=arr[j+1];
}
}
}
for(int i=0;i<n;i++)
cout<<arr[i]<<" ";
cout<<endl;
}
void solve(){
int arr[100];
int n;
cin>>n;
input_of_array(arr,n);
rotating_the_array(arr,n);
}
signed main(){
fast;
int t = 1;
while(t--){
solve();
}
return 0;
}
|
// Copyright (c) 2011-2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <qt/recentrequeststablemodel.h>
#include <qt/bitcoinunits.h>
#include <qt/guiutil.h>
#include <qt/optionsmodel.h>
#include <algorithm>
#include <clientversion.h>
#include <streams.h>
RecentRequestsTableModel::RecentRequestsTableModel(WalletModel *parent) :
QAbstractTableModel(parent), walletModel(parent)
{
nReceiveRequestsMaxId = 0;
// Load entries from wallet
std::vector<std::string> vReceiveRequests;
parent->loadReceiveRequests(vReceiveRequests);
for (const std::string& request : vReceiveRequests)
addNewRequest(request);
/* These columns must match the indices in the ColumnIndex enumeration */
columns << tr("Date") << tr("Label") << tr("Message") << getAmountTitle();
connect(walletModel->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
}
RecentRequestsTableModel::~RecentRequestsTableModel()
{
/* Intentionally left empty */
}
int RecentRequestsTableModel::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return list.length();
}
int RecentRequestsTableModel::columnCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return columns.length();
}
QVariant RecentRequestsTableModel::data(const QModelIndex &index, int role) const
{
if(!index.isValid() || index.row() >= list.length())
return QVariant();
if(role == Qt::DisplayRole || role == Qt::EditRole)
{
const RecentRequestEntry *rec = &list[index.row()];
switch(index.column())
{
case Date:
return GUIUtil::dateTimeStr(rec->date);
case Label:
if(rec->recipient.label.isEmpty() && role == Qt::DisplayRole)
{
return tr("(no label)");
}
else
{
return rec->recipient.label;
}
case Message:
if(rec->recipient.message.isEmpty() && role == Qt::DisplayRole)
{
return tr("(no message)");
}
else
{
return rec->recipient.message;
}
case Amount:
if (rec->recipient.amount == 0 && role == Qt::DisplayRole)
return tr("(no amount requested)");
else if (role == Qt::EditRole)
return BitcoinUnits::format(walletModel->getOptionsModel()->getDisplayUnit(), rec->recipient.amount, false, BitcoinUnits::separatorNever);
else
return BitcoinUnits::format(walletModel->getOptionsModel()->getDisplayUnit(), rec->recipient.amount);
}
}
else if (role == Qt::TextAlignmentRole)
{
if (index.column() == Amount)
return (int)(Qt::AlignRight|Qt::AlignVCenter);
}
return QVariant();
}
bool RecentRequestsTableModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
return true;
}
QVariant RecentRequestsTableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if(orientation == Qt::Horizontal)
{
if(role == Qt::DisplayRole && section < columns.size())
{
return columns[section];
}
}
return QVariant();
}
/** Updates the column title to "Amount (DisplayUnit)" and emits headerDataChanged() signal for table headers to react. */
void RecentRequestsTableModel::updateAmountColumnTitle()
{
columns[Amount] = getAmountTitle();
Q_EMIT headerDataChanged(Qt::Horizontal,Amount,Amount);
}
/** Gets title for amount column including current display unit if optionsModel reference available. */
QString RecentRequestsTableModel::getAmountTitle()
{
return (this->walletModel->getOptionsModel() != nullptr) ? tr("Requested") + " ("+BitcoinUnits::shortName(this->walletModel->getOptionsModel()->getDisplayUnit()) + ")" : "";
}
QModelIndex RecentRequestsTableModel::index(int row, int column, const QModelIndex &parent) const
{
Q_UNUSED(parent);
return createIndex(row, column);
}
bool RecentRequestsTableModel::removeRows(int row, int count, const QModelIndex &parent)
{
Q_UNUSED(parent);
if(count > 0 && row >= 0 && (row+count) <= list.size())
{
for (int i = 0; i < count; ++i)
{
const RecentRequestEntry* rec = &list[row+i];
if (!walletModel->saveReceiveRequest(rec->recipient.address.toStdString(), rec->id, ""))
return false;
}
beginRemoveRows(parent, row, row + count - 1);
list.erase(list.begin() + row, list.begin() + row + count);
endRemoveRows();
return true;
} else {
return false;
}
}
Qt::ItemFlags RecentRequestsTableModel::flags(const QModelIndex &index) const
{
return Qt::ItemIsSelectable | Qt::ItemIsEnabled;
}
// called when adding a request from the GUI
void RecentRequestsTableModel::addNewRequest(const SendCoinsRecipient &recipient)
{
RecentRequestEntry newEntry;
newEntry.id = ++nReceiveRequestsMaxId;
newEntry.date = QDateTime::currentDateTime();
newEntry.recipient = recipient;
CDataStream ss(SER_DISK, CLIENT_VERSION);
ss << newEntry;
if (!walletModel->saveReceiveRequest(recipient.address.toStdString(), newEntry.id, ss.str()))
return;
addNewRequest(newEntry);
}
// called from ctor when loading from wallet
void RecentRequestsTableModel::addNewRequest(const std::string &recipient)
{
std::vector<char> data(recipient.begin(), recipient.end());
CDataStream ss(data, SER_DISK, CLIENT_VERSION);
RecentRequestEntry entry;
ss >> entry;
if (entry.id == 0) // should not happen
return;
if (entry.id > nReceiveRequestsMaxId)
nReceiveRequestsMaxId = entry.id;
addNewRequest(entry);
}
// actually add to table in GUI
void RecentRequestsTableModel::addNewRequest(RecentRequestEntry &recipient)
{
beginInsertRows(QModelIndex(), 0, 0);
list.prepend(recipient);
endInsertRows();
}
void RecentRequestsTableModel::sort(int column, Qt::SortOrder order)
{
std::sort(list.begin(), list.end(), RecentRequestEntryLessThan(column, order));
Q_EMIT dataChanged(index(0, 0, QModelIndex()), index(list.size() - 1, NUMBER_OF_COLUMNS - 1, QModelIndex()));
}
void RecentRequestsTableModel::updateDisplayUnit()
{
updateAmountColumnTitle();
}
bool RecentRequestEntryLessThan::operator()(RecentRequestEntry &left, RecentRequestEntry &right) const
{
RecentRequestEntry *pLeft = &left;
RecentRequestEntry *pRight = &right;
if (order == Qt::DescendingOrder)
std::swap(pLeft, pRight);
switch(column)
{
case RecentRequestsTableModel::Date:
return pLeft->date.toTime_t() < pRight->date.toTime_t();
case RecentRequestsTableModel::Label:
return pLeft->recipient.label < pRight->recipient.label;
case RecentRequestsTableModel::Message:
return pLeft->recipient.message < pRight->recipient.message;
case RecentRequestsTableModel::Amount:
return pLeft->recipient.amount < pRight->recipient.amount;
default:
return pLeft->id < pRight->id;
}
}
|
//HEADER_GOES_HERE
#include "../types.h"
int invflag;
void *pInvCels;
int drawsbarflag; // idb
int sgdwLastTime; // check name
const InvXY InvRect[73] =
{
{ 452, 31 }, // helmet
{ 480, 31 }, // helmet
{ 452, 59 }, // helmet
{ 480, 59 }, // helmet
{ 365, 205 }, // left ring
{ 567, 205 }, // right ring
{ 524, 59 }, // amulet
{ 337, 104 }, // left hand
{ 366, 104 }, // left hand
{ 337, 132 }, // left hand
{ 366, 132 }, // left hand
{ 337, 160 }, // left hand
{ 366, 160 }, // left hand
{ 567, 104 }, // right hand
{ 596, 104 }, // right hand
{ 567, 132 }, // right hand
{ 596, 132 }, // right hand
{ 567, 160 }, // right hand
{ 596, 160 }, // right hand
{ 452, 104 }, // chest
{ 480, 104 }, // chest
{ 452, 132 }, // chest
{ 480, 132 }, // chest
{ 452, 160 }, // chest
{ 480, 160 }, // chest
{ 337, 250 }, // inv row 1
{ 366, 250 }, // inv row 1
{ 394, 250 }, // inv row 1
{ 423, 250 }, // inv row 1
{ 451, 250 }, // inv row 1
{ 480, 250 }, // inv row 1
{ 509, 250 }, // inv row 1
{ 538, 250 }, // inv row 1
{ 567, 250 }, // inv row 1
{ 596, 250 }, // inv row 1
{ 337, 279 }, // inv row 2
{ 366, 279 }, // inv row 2
{ 394, 279 }, // inv row 2
{ 423, 279 }, // inv row 2
{ 451, 279 }, // inv row 2
{ 480, 279 }, // inv row 2
{ 509, 279 }, // inv row 2
{ 538, 279 }, // inv row 2
{ 567, 279 }, // inv row 2
{ 596, 279 }, // inv row 2
{ 337, 308 }, // inv row 3
{ 366, 308 }, // inv row 3
{ 394, 308 }, // inv row 3
{ 423, 308 }, // inv row 3
{ 451, 308 }, // inv row 3
{ 480, 308 }, // inv row 3
{ 509, 308 }, // inv row 3
{ 538, 308 }, // inv row 3
{ 567, 308 }, // inv row 3
{ 596, 308 }, // inv row 3
{ 337, 336 }, // inv row 4
{ 366, 336 }, // inv row 4
{ 394, 336 }, // inv row 4
{ 423, 336 }, // inv row 4
{ 451, 336 }, // inv row 4
{ 480, 336 }, // inv row 4
{ 509, 336 }, // inv row 4
{ 538, 336 }, // inv row 4
{ 567, 336 }, // inv row 4
{ 596, 336 }, // inv row 4
{ 205, 385 }, // belt
{ 234, 385 }, // belt
{ 263, 385 }, // belt
{ 292, 385 }, // belt
{ 321, 385 }, // belt
{ 350, 385 }, // belt
{ 379, 385 }, // belt
{ 408, 385 } // belt
};
/* data */
int AP2x2Tbl[10] = { 8, 28, 6, 26, 4, 24, 2, 22, 0, 20 }; // weak
void __cdecl FreeInvGFX()
{
void *invCels = pInvCels;
pInvCels = NULL;
mem_free_dbg(invCels);
}
void __cdecl InitInv()
{
if ( plr[myplr]._pClass == PC_WARRIOR )
{
pInvCels = LoadFileInMem("Data\\Inv\\Inv.CEL", 0);
}
else if ( plr[myplr]._pClass == PC_ROGUE )
{
pInvCels = LoadFileInMem("Data\\Inv\\Inv_rog.CEL", 0);
}
else if ( plr[myplr]._pClass == PC_SORCERER )
{
pInvCels = LoadFileInMem("Data\\Inv\\Inv_Sor.CEL", 0);
}
invflag = 0;
drawsbarflag = 0;
}
void __fastcall InvDrawSlotBack(int X, int Y, int W, int H)
{
unsigned char *v4; // edi
int v5; // edx
int v6; // ecx
unsigned char v7; // al
unsigned char v8; // al
v4 = (unsigned char *)gpBuffer + screen_y_times_768[Y] + X;
v5 = (unsigned short)H;
do
{
v6 = (unsigned short)W;
do
{
v7 = *v4;
if ( *v4 < 0xB0u )
goto LABEL_9;
if ( v7 > 0xBFu )
{
if ( v7 < 0xF0u )
goto LABEL_9;
v8 = v7 - 80;
}
else
{
v8 = v7 - 16;
}
*v4 = v8;
LABEL_9:
++v4;
--v6;
}
while ( v6 );
v4 = &v4[-(unsigned short)W - 768];
--v5;
}
while ( v5 );
}
void __cdecl DrawInv()
{
BOOL invtest[40];
CelDecodeOnly(384, 511, pInvCels, 1, 320);
if ( plr[myplr].InvBody[INVLOC_HEAD]._itype != ITYPE_NONE )
{
InvDrawSlotBack(517, 219, 2 * INV_SLOT_SIZE_PX, 2 * INV_SLOT_SIZE_PX);
int frame = plr[myplr].InvBody[INVLOC_HEAD]._iCurs + 12;
int frame_width = InvItemWidth[frame];
if ( pcursinvitem == INVITEM_HEAD )
{
int colour = 197;
if ( plr[myplr].InvBody[INVLOC_HEAD]._iMagical )
{
colour = 181;
}
if ( !plr[myplr].InvBody[INVLOC_HEAD]._iStatFlag )
{
colour = 229;
}
CelDecodeClr(colour, 517, 219, (char *)pCursCels, frame, frame_width, 0, 8);
}
if ( plr[myplr].InvBody[INVLOC_HEAD]._iStatFlag )
{
CelDrawHdrOnly(517, 219, (char *)pCursCels, frame, frame_width, 0, 8);
}
else
{
CelDrawHdrLightRed(517, 219, (char *)pCursCels, frame, frame_width, 0, 8, 1);
}
}
if ( plr[myplr].InvBody[INVLOC_RING_LEFT]._itype != ITYPE_NONE )
{
InvDrawSlotBack(432, 365, INV_SLOT_SIZE_PX, INV_SLOT_SIZE_PX);
int frame = plr[myplr].InvBody[INVLOC_RING_LEFT]._iCurs + 12;
int frame_width = InvItemWidth[frame];
if ( pcursinvitem == INVITEM_RING_LEFT )
{
int colour = 197;
if ( plr[myplr].InvBody[INVLOC_RING_LEFT]._iMagical )
{
colour = 181;
}
if ( !plr[myplr].InvBody[INVLOC_RING_LEFT]._iStatFlag )
{
colour = 229;
}
CelDecodeClr(colour, 432, 365, (char *)pCursCels, frame, frame_width, 0, 8);
}
if ( plr[myplr].InvBody[INVLOC_RING_LEFT]._iStatFlag )
{
CelDrawHdrOnly(432, 365, (char *)pCursCels, frame, frame_width, 0, 8);
}
else
{
CelDrawHdrLightRed(432, 365, (char *)pCursCels, frame, frame_width, 0, 8, 1);
}
}
if ( plr[myplr].InvBody[INVLOC_RING_RIGHT]._itype != ITYPE_NONE )
{
InvDrawSlotBack(633, 365, INV_SLOT_SIZE_PX, INV_SLOT_SIZE_PX);
int frame = plr[myplr].InvBody[INVLOC_RING_RIGHT]._iCurs + 12;
int frame_width = InvItemWidth[frame];
if ( pcursinvitem == INVITEM_RING_RIGHT )
{
int colour = 197;
if ( plr[myplr].InvBody[INVLOC_RING_RIGHT]._iMagical )
{
colour = 181;
}
if ( !plr[myplr].InvBody[INVLOC_RING_RIGHT]._iStatFlag )
{
colour = 229;
}
CelDecodeClr(colour, 633, 365, (char *)pCursCels, frame, frame_width, 0, 8);
}
if ( plr[myplr].InvBody[INVLOC_RING_RIGHT]._iStatFlag )
{
CelDrawHdrOnly(633, 365, (char *)pCursCels, frame, frame_width, 0, 8);
}
else
{
CelDrawHdrLightRed(633, 365, (char *)pCursCels, frame, frame_width, 0, 8, 1);
}
}
if ( plr[myplr].InvBody[INVLOC_AMULET]._itype != ITYPE_NONE )
{
InvDrawSlotBack(589, 220, INV_SLOT_SIZE_PX, INV_SLOT_SIZE_PX);
int frame = plr[myplr].InvBody[INVLOC_AMULET]._iCurs + 12;
int frame_width = InvItemWidth[frame];
if ( pcursinvitem == INVITEM_AMULET )
{
int colour = 197;
if ( plr[myplr].InvBody[INVLOC_AMULET]._iMagical )
{
colour = 181;
}
if ( !plr[myplr].InvBody[INVLOC_AMULET]._iStatFlag )
{
colour = 229;
}
CelDecodeClr(colour, 589, 220, (char *)pCursCels, frame, frame_width, 0, 8);
}
if ( plr[myplr].InvBody[INVLOC_AMULET]._iStatFlag )
{
CelDrawHdrOnly(589, 220, (char *)pCursCels, frame, frame_width, 0, 8);
}
else
{
CelDrawHdrLightRed(589, 220, (char *)pCursCels, frame, frame_width, 0, 8, 1);
}
}
if ( plr[myplr].InvBody[INVLOC_HAND_LEFT]._itype != ITYPE_NONE )
{
InvDrawSlotBack(401, 320, 2 * INV_SLOT_SIZE_PX, 3 * INV_SLOT_SIZE_PX);
int frame = plr[myplr].InvBody[INVLOC_HAND_LEFT]._iCurs + 12;
int frame_width = InvItemWidth[frame];
// calc item offsets for weapons smaller than 2x3 slots
int screen_x = frame_width == INV_SLOT_SIZE_PX ? 415 : 401;
int screen_y = InvItemHeight[frame] == (3 * INV_SLOT_SIZE_PX) ? 320 : 306;
if ( pcursinvitem == INVITEM_HAND_LEFT )
{
int colour = 197;
if ( plr[myplr].InvBody[INVLOC_HAND_LEFT]._iMagical )
{
colour = 181;
}
if ( !plr[myplr].InvBody[INVLOC_HAND_LEFT]._iStatFlag )
{
colour = 229;
}
CelDecodeClr(colour, screen_x, screen_y, (char *)pCursCels, frame, frame_width, 0, 8);
}
if ( plr[myplr].InvBody[INVLOC_HAND_LEFT]._iStatFlag )
{
CelDrawHdrOnly(screen_x, screen_y, (char *)pCursCels, frame, frame_width, 0, 8);
}
else
{
CelDrawHdrLightRed(screen_x, screen_y, (char *)pCursCels, frame, frame_width, 0, 8, 1);
}
if ( plr[myplr].InvBody[INVLOC_HAND_LEFT]._iLoc == ILOC_TWOHAND )
{
InvDrawSlotBack(631, 320, 2 * INV_SLOT_SIZE_PX, 3 * INV_SLOT_SIZE_PX);
light_table_index = 0;
cel_transparency_active = 1;
CelDecodeHdrLightTrans(
frame_width == INV_SLOT_SIZE_PX
? &gpBuffer->row[160].pixels[581]
: &gpBuffer->row[160].pixels[567],
(char *)pCursCels, frame, frame_width, 0, 8);
cel_transparency_active = 0;
}
}
if ( plr[myplr].InvBody[INVLOC_HAND_RIGHT]._itype != ITYPE_NONE )
{
InvDrawSlotBack(631, 320, 2 * INV_SLOT_SIZE_PX, 3 * INV_SLOT_SIZE_PX);
int frame = plr[myplr].InvBody[INVLOC_HAND_RIGHT]._iCurs + 12;
int frame_width = InvItemWidth[frame];
// calc item offsets for weapons smaller than 2x3 slots
int screen_x = frame_width == INV_SLOT_SIZE_PX ? 645 : 633;
int screen_y = InvItemHeight[frame] == 3 * INV_SLOT_SIZE_PX ? 320 : 306;
if ( pcursinvitem == INVITEM_HAND_RIGHT )
{
int colour = 197;
if ( plr[myplr].InvBody[INVLOC_HAND_RIGHT]._iMagical )
{
colour = 181;
}
if ( !plr[myplr].InvBody[INVLOC_HAND_RIGHT]._iStatFlag )
{
colour = 229;
}
CelDecodeClr(colour, screen_x, screen_y, (char *)pCursCels, frame, frame_width, 0, 8);
}
if ( plr[myplr].InvBody[INVLOC_HAND_RIGHT]._iStatFlag )
{
CelDrawHdrOnly(screen_x, screen_y, (char *)pCursCels, frame, frame_width, 0, 8);
}
else
{
CelDrawHdrLightRed(screen_x, screen_y, (char *)pCursCels, frame, frame_width, 0, 8, 1);
}
}
if ( plr[myplr].InvBody[INVLOC_CHEST]._itype != ITYPE_NONE )
{
InvDrawSlotBack(517, 320, 2 * INV_SLOT_SIZE_PX, 3 * INV_SLOT_SIZE_PX);
int frame = plr[myplr].InvBody[INVLOC_CHEST]._iCurs + 12;
int frame_width = InvItemWidth[frame];
if ( pcursinvitem == INVITEM_CHEST )
{
int colour = 197;
if ( plr[myplr].InvBody[INVLOC_CHEST]._iMagical )
{
colour = 181;
}
if ( !plr[myplr].InvBody[INVLOC_CHEST]._iStatFlag )
{
colour = 229;
}
CelDecodeClr(colour, 517, 320, (char *)pCursCels, frame, frame_width, 0, 8);
}
if ( plr[myplr].InvBody[INVLOC_CHEST]._iStatFlag )
{
CelDrawHdrOnly(517, 320, (char *)pCursCels, frame, frame_width, 0, 8);
}
else
{
CelDrawHdrLightRed(517, 320, (char *)pCursCels, frame, frame_width, 0, 8, 1);
}
}
for ( int i = 0; i < NUM_INV_GRID_ELEM; i++ )
{
if ( plr[myplr].InvGrid[i] != 0 )
{
InvDrawSlotBack(
InvRect[i + SLOTXY_INV_FIRST].X + 64,
InvRect[i + SLOTXY_INV_FIRST].Y + 159,
INV_SLOT_SIZE_PX,
INV_SLOT_SIZE_PX);
}
}
for ( int j = 0; j < NUM_INV_GRID_ELEM; j++ )
{
if ( plr[myplr].InvGrid[j] > 0 ) // first slot of an item
{
int ii = plr[myplr].InvGrid[j] - 1;
invtest[j] = TRUE;
int frame = plr[myplr].InvList[ii]._iCurs + 12;
int frame_width = InvItemWidth[frame];
if ( pcursinvitem == ii + INVITEM_INV_FIRST )
{
int colour = 197;
if ( plr[myplr].InvList[ii]._iMagical )
{
colour = 181;
}
if ( !plr[myplr].InvList[ii]._iStatFlag )
{
colour = 229;
}
CelDecodeClr(
colour,
InvRect[j + SLOTXY_INV_FIRST].X + 64,
InvRect[j + SLOTXY_INV_FIRST].Y + 159,
(char *)pCursCels, frame, frame_width, 0, 8);
}
if ( plr[myplr].InvList[ii]._iStatFlag )
{
CelDrawHdrOnly(
InvRect[j + SLOTXY_INV_FIRST].X + 64,
InvRect[j + SLOTXY_INV_FIRST].Y + 159,
(char *)pCursCels, frame, frame_width, 0, 8);
}
else
{
CelDrawHdrLightRed(
InvRect[j + SLOTXY_INV_FIRST].X + 64,
InvRect[j + SLOTXY_INV_FIRST].Y + 159,
(char *)pCursCels, frame, frame_width, 0, 8, 1);
}
}
}
}
// 4B8CB8: using guessed type char pcursinvitem;
// 69BEF8: using guessed type int light_table_index;
// 69CF94: using guessed type int cel_transparency_active;
// 41B8C4: using guessed type int var_A0[40];
void __cdecl DrawInvBelt()
{
int v0; // ebx
signed int v1; // esi
int v2; // ecx
int v3; // eax
int v4; // edi
char v5; // cl
int v6; // edx
bool v7; // zf
int v8; // ecx
int v9; // eax
unsigned char v10; // edx
signed int v11; // [esp+4h] [ebp-Ch]
int frame_width; // [esp+8h] [ebp-8h]
int v13; // [esp+Ch] [ebp-4h]
v0 = 0;
if ( !talkflag )
{
DrawPanelBox(205, 21, 0xE8u, 0x1Cu, 269, 517);
v11 = 0;
v13 = 0;
do
{
if ( *(int *)((char *)&plr[myplr].SpdList[0]._itype + v0) != -1 )
{
v1 = v11;
InvDrawSlotBack(InvRect[v11 + 65].X + 64, InvRect[v11 + 65].Y + 159, 28, 28);
v2 = myplr;
v3 = v0 + 21720 * myplr;
v4 = *(int *)((char *)&plr[0].SpdList[0]._iCurs + v3) + 12;
frame_width = InvItemWidth[v4];
if ( pcursinvitem == v11 + 47 )
{
v5 = -59;
if ( *(&plr[0].SpdList[0]._iMagical + v3) )
v5 = -75;
if ( !*(int *)((char *)&plr[0].SpdList[0]._iStatFlag + v3) )
v5 = -27;
CelDecodeClr(
v5,
InvRect[v1 + 65].X + 64,
InvRect[v1 + 65].Y + 159,
(char *)pCursCels,
v4,
frame_width,
0,
8);
v2 = myplr;
}
v0 = v13;
v6 = InvRect[v1 + 65].Y + 159;
v7 = *(int *)((char *)&plr[v2].SpdList[0]._iStatFlag + v13) == 0;
v8 = InvRect[v1 + 65].X;
if ( v7 )
CelDrawHdrLightRed(v8 + 64, v6, (char *)pCursCels, v4, frame_width, 0, 8, 1);
else
CelDrawHdrOnly(v8 + 64, v6, (char *)pCursCels, v4, frame_width, 0, 8);
v9 = v13 + 21720 * myplr;
if ( AllItemsList[*(int *)((char *)&plr[0].SpdList[0].IDidx + v9)].iUsable
&& *(int *)((char *)&plr[0].SpdList[0]._iStatFlag + v9)
&& *(int *)((char *)&plr[0].SpdList[0]._itype + v9) != 11 )
{
v10 = fontframe[fontidx[(unsigned char)(v11 + 49)]];
CPrintString(
screen_y_times_768[InvRect[v1 + 65].Y + 159]
- fontkern[v10]
+ InvRect[v1 + 65].X
+ 92,
v10,
0);
}
}
++v11;
v0 += 368;
v13 = v0;
}
while ( v11 < 8 );
}
}
// 4B8960: using guessed type int talkflag;
// 4B8CB8: using guessed type char pcursinvitem;
int __fastcall AutoPlace(int pnum, int ii, int sx, int sy, int saveflag)
{
__int64 v5; // rax
int v6; // ebx
signed int v7; // edx
signed int v8; // eax
signed int v9; // esi
int j; // edi
int v11; // eax
signed int v12; // esi
signed int v13; // ecx
int v14; // edi
char *v15; // ecx
char v16; // dl
signed int v18; // [esp+Ch] [ebp-Ch]
int p; // [esp+10h] [ebp-8h]
int v20; // [esp+14h] [ebp-4h]
int i; // [esp+14h] [ebp-4h]
p = pnum;
v5 = ii;
v6 = 1;
v18 = v5 % 10;
v7 = 10 * (unsigned __int64)(v5 / 10);
v8 = v7;
if ( v7 < 0 )
v8 = 0;
v20 = 0;
if ( sy <= 0 )
{
LABEL_16:
if ( saveflag )
{
v11 = pnum;
qmemcpy(
&plr[pnum].InvList[plr[pnum]._pNumInv],
&plr[pnum].HoldItem,
sizeof(plr[pnum].InvList[plr[pnum]._pNumInv]));
++plr[v11]._pNumInv;
v12 = v7;
if ( v7 < 0 )
v12 = 0;
for ( i = 0; i < sy; ++i )
{
v13 = v18;
if ( v18 < 0 )
v13 = 0;
v14 = 0;
if ( sx > 0 )
{
v15 = &plr[v11].InvGrid[v13 + v12];
do
{
if ( v14 || i != sy - 1 )
v16 = -_LOBYTE(plr[v11]._pNumInv);
else
v16 = plr[v11]._pNumInv;
*v15++ = v16;
++v14;
}
while ( v14 < sx );
}
v12 += 10;
}
CalcPlrScrolls(p);
}
}
else
{
while ( v6 )
{
if ( v8 >= 40 )
v6 = 0;
v9 = v18;
if ( v18 < 0 )
v9 = 0;
for ( j = 0; j < sx; ++j )
{
if ( !v6 )
break;
v6 = 0;
if ( v9 < 10 )
_LOBYTE(v6) = plr[pnum].InvGrid[v9 + v8] == 0;
++v9;
}
v8 += 10;
if ( ++v20 >= sy )
{
if ( !v6 )
return v6;
goto LABEL_16;
}
}
}
return v6;
}
int __fastcall SpecialAutoPlace(int pnum, int ii, int sx, int sy, int saveflag)
{
__int64 v5; // rax
int v6; // ebx
signed int v7; // edx
signed int v8; // eax
signed int v9; // esi
int j; // edi
signed int v11; // ecx
int *v12; // eax
int v13; // eax
signed int v14; // esi
signed int v15; // ecx
int v16; // edi
char *v17; // ecx
char v18; // dl
signed int v20; // [esp+Ch] [ebp-Ch]
int p; // [esp+10h] [ebp-8h]
int v22; // [esp+14h] [ebp-4h]
int i; // [esp+14h] [ebp-4h]
p = pnum;
v5 = ii;
v6 = 1;
v20 = v5 % 10;
v7 = 10 * (unsigned __int64)(v5 / 10);
v8 = v7;
if ( v7 < 0 )
v8 = 0;
v22 = 0;
if ( sy <= 0 )
{
LABEL_25:
if ( saveflag )
{
v13 = p;
qmemcpy(&plr[p].InvList[plr[p]._pNumInv], &plr[p].HoldItem, sizeof(plr[p].InvList[plr[p]._pNumInv]));
++plr[v13]._pNumInv;
v14 = v7;
if ( v7 < 0 )
v14 = 0;
for ( i = 0; i < sy; ++i )
{
v15 = v20;
if ( v20 < 0 )
v15 = 0;
v16 = 0;
if ( sx > 0 )
{
v17 = &plr[v13].InvGrid[v15 + v14];
do
{
if ( v16 || i != sy - 1 )
v18 = -_LOBYTE(plr[v13]._pNumInv);
else
v18 = plr[v13]._pNumInv;
*v17++ = v18;
++v16;
}
while ( v16 < sx );
}
v14 += 10;
}
CalcPlrScrolls(p);
}
return v6;
}
while ( v6 )
{
if ( v8 >= 40 )
v6 = 0;
v9 = v20;
if ( v20 < 0 )
v9 = 0;
for ( j = 0; j < sx; ++j )
{
if ( !v6 )
break;
v6 = 0;
if ( v9 < 10 )
_LOBYTE(v6) = plr[pnum].InvGrid[v9 + v8] == 0;
++v9;
}
v8 += 10;
if ( ++v22 >= sy )
{
if ( v6 )
goto LABEL_25;
break;
}
}
if ( sx <= 1 && sy <= 1 )
{
v11 = 0;
v12 = &plr[p].SpdList[0]._itype;
while ( *v12 != -1 )
{
++v11;
v12 += 92;
if ( v11 >= 8 )
goto LABEL_24;
}
v6 = 1;
goto LABEL_25;
}
v6 = 0;
LABEL_24:
if ( v6 )
goto LABEL_25;
return v6;
}
int __fastcall GoldAutoPlace(int pnum)
{
int v1; // ebp
int v2; // edi
int v3; // ecx
int *v4; // esi
int v5; // eax
int v6; // edi
int *v7; // esi
int v8; // eax
signed int v9; // ebx
char *v10; // edx
int v11; // eax
int v12; // ecx
int pnuma; // [esp+10h] [ebp-4h]
pnuma = pnum;
v1 = pnum;
v2 = 0;
v3 = 0;
if ( plr[v1]._pNumInv <= 0 )
{
LABEL_14:
v6 = 0;
if ( plr[v1]._pNumInv <= 0 )
{
LABEL_28:
v9 = 39;
do
{
if ( v3 )
break;
v10 = &plr[0].InvGrid[10 * (v9 / 10) + v1 * 21720 + v9 % 10];
if ( !*v10 )
{
v11 = v1 * 21720 + 368 * plr[v1]._pNumInv;
qmemcpy((char *)plr[0].InvList + v11, &plr[v1].HoldItem, 0x170u);
++plr[v1]._pNumInv;
*v10 = plr[v1]._pNumInv;
v12 = plr[v1].HoldItem._ivalue;
if ( v12 < 2500 )
{
if ( v12 > 1000 )
*(int *)((char *)&plr[0].InvList[0]._iCurs + v11) = 5;
else
*(int *)((char *)&plr[0].InvList[0]._iCurs + v11) = 4;
}
else
{
*(int *)((char *)&plr[0].InvList[0]._iCurs + v11) = 6;
}
plr[v1]._pGold = CalculateGold(pnuma);
v3 = 1;
}
--v9;
}
while ( v9 >= 0 );
}
else
{
v7 = &plr[v1].InvList[0]._ivalue;
while ( !v3 )
{
if ( *(v7 - 47) == 11 && *v7 < 5000 )
{
v8 = plr[v1].HoldItem._ivalue + *v7;
if ( v8 <= 5000 )
{
*v7 = v8;
if ( v8 < 2500 )
{
if ( v8 > 1000 )
*(v7 - 1) = 5;
else
*(v7 - 1) = 4;
}
else
{
*(v7 - 1) = 6;
}
plr[v1]._pGold = CalculateGold(pnuma);
v3 = 1;
}
}
++v6;
v7 += 92;
if ( v6 >= plr[v1]._pNumInv )
{
if ( v3 )
return v3;
goto LABEL_28;
}
}
}
}
else
{
v4 = &plr[v1].InvList[0]._ivalue;
while ( !v3 )
{
if ( *(v4 - 47) == 11 )
{
v5 = *v4 + plr[v1].HoldItem._ivalue;
if ( v5 <= 5000 )
{
*v4 = v5;
if ( v5 < 2500 )
{
if ( v5 > 1000 )
*(v4 - 1) = 5;
else
*(v4 - 1) = 4;
}
else
{
*(v4 - 1) = 6;
}
plr[v1]._pGold = CalculateGold(pnuma);
v3 = 1;
}
}
++v2;
v4 += 92;
if ( v2 >= plr[v1]._pNumInv )
{
if ( v3 )
return v3;
goto LABEL_14;
}
}
}
return v3;
}
int __fastcall WeaponAutoPlace(int pnum)
{
int v1; // edi
int v2; // eax
int v3; // ecx
ItemStruct *v4; // esi
ItemStruct *v5; // edi
int result; // eax
v1 = pnum;
if ( plr[pnum].HoldItem._iLoc == ILOC_TWOHAND )
{
if ( plr[v1].InvBody[4]._itype != -1 || plr[v1].InvBody[5]._itype != -1 )
return 0;
LABEL_12:
NetSendCmdChItem(1u, 4u);
v4 = &plr[v1].HoldItem;
v5 = &plr[v1].InvBody[4];
goto LABEL_13;
}
v2 = plr[v1].InvBody[4]._itype;
if ( v2 != -1 && plr[v1].InvBody[4]._iClass == 1 )
return 0;
v3 = plr[v1].InvBody[5]._itype;
if ( v3 != -1 && plr[v1].InvBody[5]._iClass == 1 )
return 0;
if ( v2 == -1 )
goto LABEL_12;
if ( v3 == -1 && plr[v1].InvBody[4]._iLoc != ILOC_TWOHAND )
{
NetSendCmdChItem(1u, 5u);
v4 = &plr[v1].HoldItem;
v5 = &plr[v1].InvBody[5];
LABEL_13:
result = 1;
qmemcpy(v5, v4, sizeof(ItemStruct));
return result;
}
return 0;
}
int __fastcall SwapItem(ItemStruct *a, ItemStruct *b)
{
int v2; // eax
ItemStruct h; // [esp+8h] [ebp-170h]
qmemcpy(&h, a, sizeof(h));
v2 = h._iCurs;
qmemcpy(a, b, sizeof(ItemStruct));
qmemcpy(b, &h, sizeof(ItemStruct));
return v2 + 12;
}
void __fastcall CheckInvPaste(int pnum, int mx, int my)
{
int v3; // ebx
int v4; // edi
int v5; // eax
int v6; // esi
signed int v7; // edi
int v8; // edx
int v9; // edx
signed int v10; // edi
char v11; // al
signed int v12; // ecx
int v13; // eax
int v14; // eax
char *v15; // edi
int v16; // esi
int v17; // ecx
int v18; // edx
char v19; // al
int v20; // ecx
int v21; // esi
ItemStruct *v22; // edi
ItemStruct *v23; // ecx
int v24; // eax
int v25; // eax
int v26; // edx
ItemStruct *v27; // esi
int v28; // eax
int v29; // ecx
int v30; // esi
int v31; // eax
int v32; // eax
int v33; // ecx
int v34; // eax
int v35; // ecx
char *v36; // eax
int v37; // edx
int v38; // ecx
int v39; // edi
int v40; // esi
int v41; // ebx
int v42; // edx
int v43; // eax
int v44; // eax
signed int v45; // ecx
int v46; // edx
char *v47; // eax
int v48; // edi
int v49; // eax
int v50; // ecx
char *v51; // esi
char v52; // cl
int v53; // ecx
int v54; // eax
int v55; // edi
int v56; // edx
int v57; // esi
int v58; // ebx
int v59; // eax
int v60; // esi
ItemStruct tempitem; // [esp+Ch] [ebp-190h]
int v62; // [esp+17Ch] [ebp-20h]
int p; // [esp+180h] [ebp-1Ch]
int v64; // [esp+184h] [ebp-18h]
int v65; // [esp+188h] [ebp-14h]
int v66; // [esp+18Ch] [ebp-10h]
int v67; // [esp+190h] [ebp-Ch]
int v68; // [esp+194h] [ebp-8h]
int v69; // [esp+198h] [ebp-4h]
int cursor_id; // [esp+1A4h] [ebp+8h]
int cursor_ida; // [esp+1A4h] [ebp+8h]
p = pnum;
v3 = pnum;
v4 = mx;
SetICursor(plr[pnum].HoldItem._iCurs + 12);
v5 = my + (icursH >> 1);
v6 = v4 + (icursW >> 1);
v64 = icursW28;
v7 = 0;
v67 = icursH28;
v68 = 0;
do
{
if ( v7 )
goto LABEL_18;
v8 = InvRect[v68].X;
if ( v6 >= v8 && v6 < v8 + 28 )
{
v9 = InvRect[v68].Y;
if ( v5 >= v9 - 29 && v5 < v9 )
{
v7 = 1;
--v68;
}
}
if ( v68 != 24 )
goto LABEL_13;
if ( !(v64 & 1) )
v6 -= 14;
if ( !(v67 & 1) )
{
v5 -= 14;
LABEL_13:
if ( v68 == 64 && !(v67 & 1) )
v5 += 14;
}
++v68;
}
while ( (unsigned int)v68 < 0x49 );
if ( !v7 )
return;
LABEL_18:
v10 = v68;
v69 = ILOC_UNEQUIPABLE;
if ( v68 >= 0 && v68 <= ILOC_ARMOR )
v69 = ILOC_HELM;
if ( v68 >= ILOC_HELM && v68 <= ILOC_RING )
v69 = ILOC_RING;
if ( v68 == ILOC_AMULET )
v69 = ILOC_AMULET;
if ( v68 >= ILOC_UNEQUIPABLE && v68 <= 18 )
v69 = ILOC_ONEHAND;
if ( v68 >= 19 && v68 <= 24 )
v69 = ILOC_ARMOR;
if ( v68 >= 65 && v68 <= 72 )
v69 = ILOC_BELT;
v11 = plr[v3].HoldItem._iLoc;
v12 = 0;
if ( (char)v11 == v69 )
v12 = 1;
if ( v69 == 1 && v11 == ILOC_TWOHAND )
{
v69 = ILOC_TWOHAND;
v12 = 1;
}
if ( v11 != 7 || v69 != ILOC_BELT )
{
LABEL_50:
if ( v69 != ILOC_UNEQUIPABLE )
goto LABEL_81;
v66 = 0;
cursor_id = 1;
v13 = (v68 - 25) / 10;
if ( plr[v3].HoldItem._itype == ITYPE_GOLD )
{
_LOBYTE(v13) = plr[0].InvGrid[10 * v13 + v3 * 21720 + (v68 - 25) % 10];
if ( !(_BYTE)v13 )
goto LABEL_93;
v13 = (char)v13;
if ( (char)v13 <= 0 )
{
v13 = -v13;
}
else if ( *(int *)((char *)&plr[0].InvBody[v13 + 6]._itype + v3 * 21720) == ITYPE_GOLD )
{
goto LABEL_93;
}
v66 = v13;
LABEL_93:
v21 = p;
if ( p == myplr )
{
PlaySFX(ItemInvSnds[ItemCAnimTbl[plr[v3].HoldItem._iCurs]]);
v10 = v68;
}
cursor_ida = 1;
switch ( v69 )
{
case ILOC_ONEHAND:
if ( v10 > 12 )
{
if ( plr[v3].InvBody[5]._itype == ITYPE_NONE )
{
v25 = plr[v3].InvBody[4]._itype;
if ( v25 == ITYPE_NONE )
goto LABEL_232;
if ( plr[v3].InvBody[4]._iLoc == ILOC_TWOHAND )
{
NetSendCmdDelItem(0, 4u);
NetSendCmdChItem(0, 5u);
SwapItem(&plr[v3].InvBody[5], &plr[v3].InvBody[4]);
v23 = &plr[v3].InvBody[5];
LABEL_99:
v24 = SwapItem(v23, &plr[v3].HoldItem);
LABEL_172:
cursor_ida = v24;
goto LABEL_226;
}
if ( v25 == ITYPE_NONE || plr[v3].InvBody[4]._iClass != plr[v3].HoldItem._iClass )
{
LABEL_232:
NetSendCmdChItem(0, 5u);
v22 = &plr[v3].InvBody[5];
LABEL_158:
qmemcpy(v22, &plr[v3].HoldItem, sizeof(ItemStruct));
goto LABEL_226;
}
}
else if ( plr[v3].InvBody[4]._itype == ITYPE_NONE
|| plr[v3].InvBody[4]._iClass != plr[v3].HoldItem._iClass )
{
goto LABEL_114;
}
}
else
{
if ( plr[v3].InvBody[4]._itype == ITYPE_NONE )
{
if ( plr[v3].InvBody[5]._itype != ITYPE_NONE
&& plr[v3].InvBody[5]._iClass == plr[v3].HoldItem._iClass )
{
LABEL_114:
NetSendCmdChItem(0, 5u);
v23 = &plr[v3].InvBody[5];
goto LABEL_99;
}
NetSendCmdChItem(0, 4u);
v22 = &plr[v3].InvBody[4];
goto LABEL_158;
}
if ( plr[v3].InvBody[5]._itype != ITYPE_NONE
&& plr[v3].InvBody[5]._iClass == plr[v3].HoldItem._iClass )
{
goto LABEL_114;
}
}
NetSendCmdChItem(0, 4u);
v23 = &plr[v3].InvBody[4];
goto LABEL_99;
case ILOC_TWOHAND:
NetSendCmdDelItem(0, 5u);
if ( plr[v3].InvBody[4]._itype == ITYPE_NONE )
goto LABEL_147;
v26 = plr[v3].InvBody[5]._itype;
if ( v26 == -1 )
goto LABEL_146;
qmemcpy(&tempitem, &plr[v3].HoldItem, sizeof(tempitem));
v27 = &plr[v3].InvBody[5];
if ( v26 != 5 )
v27 = &plr[v3].InvBody[4];
v28 = p;
qmemcpy(&plr[v3].HoldItem, v27, sizeof(plr[v3].HoldItem));
v29 = plr[v3].HoldItem._iCurs + 12;
if ( v28 == myplr )
SetCursor(v29);
else
SetICursor(v29);
v67 = 0;
v30 = 0;
do
{
if ( v67 )
break;
v31 = AutoPlace(p, v30++, icursW28, icursH28, 1);
v67 = v31;
}
while ( v30 < 40 );
v32 = p;
qmemcpy(&plr[v3].HoldItem, &tempitem, sizeof(plr[v3].HoldItem));
v33 = plr[v3].HoldItem._iCurs + 12;
if ( v32 == myplr )
SetCursor(v33);
else
SetICursor(v33);
if ( !v67 )
return;
if ( plr[v3].InvBody[5]._itype == ITYPE_SHIELD )
plr[v3].InvBody[5]._itype = ITYPE_NONE;
else
plr[v3].InvBody[4]._itype = ITYPE_NONE;
LABEL_146:
if ( plr[v3].InvBody[4]._itype != ITYPE_NONE )
goto LABEL_149;
LABEL_147:
if ( plr[v3].InvBody[5]._itype == ITYPE_NONE )
{
NetSendCmdChItem(0, 4u);
qmemcpy(&plr[v3].InvBody[4], &plr[v3].HoldItem, sizeof(plr[v3].InvBody[4]));
}
else
{
LABEL_149:
NetSendCmdChItem(0, 4u);
if ( plr[v3].InvBody[4]._itype == ITYPE_NONE )
SwapItem(&plr[v3].InvBody[4], &plr[v3].InvBody[5]);
cursor_ida = SwapItem(&plr[v3].InvBody[4], &plr[v3].HoldItem);
}
if ( plr[v3].InvBody[4]._itype == ITYPE_STAFF )
{
v34 = plr[v3].InvBody[4]._iSpell;
if ( v34 )
{
if ( plr[v3].InvBody[4]._iCharges > 0 )
{
plr[v3]._pRSpell = v34;
_LOBYTE(plr[v3]._pRSplType) = 3;
drawpanflag = 255;
}
}
}
goto LABEL_226;
case ILOC_ARMOR:
NetSendCmdChItem(0, 6u);
if ( plr[v3].InvBody[6]._itype == ITYPE_NONE )
{
v22 = &plr[v3].InvBody[6];
goto LABEL_158;
}
v23 = &plr[v3].InvBody[6];
goto LABEL_99;
case ILOC_HELM:
NetSendCmdChItem(0, 0);
if ( plr[v3].InvBody[0]._itype == ITYPE_NONE )
{
v22 = plr[v3].InvBody;
goto LABEL_158;
}
v23 = plr[v3].InvBody;
goto LABEL_99;
case ILOC_RING:
if ( v10 == 4 )
{
NetSendCmdChItem(0, 1u);
if ( plr[v3].InvBody[1]._itype == ITYPE_NONE )
{
v22 = &plr[v3].InvBody[1];
goto LABEL_158;
}
v23 = &plr[v3].InvBody[1];
}
else
{
NetSendCmdChItem(0, 2u);
if ( plr[v3].InvBody[2]._itype == ITYPE_NONE )
{
v22 = &plr[v3].InvBody[2];
goto LABEL_158;
}
v23 = &plr[v3].InvBody[2];
}
goto LABEL_99;
case ILOC_AMULET:
NetSendCmdChItem(0, 3u);
if ( plr[v3].InvBody[3]._itype == ITYPE_NONE )
{
v22 = &plr[v3].InvBody[3];
goto LABEL_158;
}
v23 = &plr[v3].InvBody[3];
goto LABEL_99;
case ILOC_UNEQUIPABLE:
v35 = plr[v3].HoldItem._itype;
if ( v35 == 11 )
{
if ( !v66 )
{
v36 = &plr[0].InvGrid[10 * ((v68 - 25) / 10) + v3 * 21720 + (v68 - 25) % 10];
if ( *v36 <= 0 )
{
v42 = 368 * plr[v3]._pNumInv + v3 * 21720;
qmemcpy((char *)plr[0].InvList + v42, &plr[v3].HoldItem, 0x170u);
++plr[v3]._pNumInv;
*v36 = plr[v3]._pNumInv;
v43 = plr[v3].HoldItem._ivalue;
plr[v3]._pGold += v43;
if ( v43 <= 5000 )
{
if ( v43 < 2500 )
{
if ( v43 > 1000 )
*(int *)((char *)&plr[0].InvList[0]._iCurs + v42) = 5;
else
*(int *)((char *)&plr[0].InvList[0]._iCurs + v42) = 4;
}
else
{
*(int *)((char *)&plr[0].InvList[0]._iCurs + v42) = 6;
}
}
goto LABEL_226;
}
v37 = plr[v3].HoldItem._ivalue;
v38 = 368 * (*v36 - 1) + v3 * 21720;
v39 = *(int *)((char *)&plr[0].InvList[0]._ivalue + v38);
v40 = v37 + v39;
if ( v37 + v39 <= 5000 )
{
*(int *)((char *)&plr[0].InvList[0]._ivalue + v38) = v40;
plr[v3]._pGold += plr[v3].HoldItem._ivalue;
if ( v40 < 2500 )
{
if ( v40 > 1000 )
*(int *)((char *)&plr[0].InvList[0]._iCurs + v38) = 5;
else
*(int *)((char *)&plr[0].InvList[0]._iCurs + v38) = 4;
}
else
{
*(int *)((char *)&plr[0].InvList[0]._iCurs + v38) = 6;
}
goto LABEL_226;
}
plr[v3]._pGold += 5000 - v39;
plr[v3].HoldItem._ivalue = v37 - (5000 - v39);
*(int *)((char *)&plr[0].InvList[0]._ivalue + v38) = 5000;
*(int *)((char *)&plr[0].InvList[0]._iCurs + v38) = 6;
v41 = plr[v3].HoldItem._ivalue;
if ( v41 >= 2500 )
{
cursor_ida = 18;
goto LABEL_226;
}
v24 = (v41 > 1000) + 16;
goto LABEL_172;
}
}
else if ( !v66 )
{
qmemcpy((char *)&plr[0].InvList[plr[v3]._pNumInv++] + v3 * 21720, &plr[v3].HoldItem, 0x170u);
v66 = plr[v3]._pNumInv;
LABEL_191:
v48 = v67;
v49 = 10 * ((v68 - 25) / 10 - ((v67 - 1) >> 1));
if ( v49 < 0 )
v49 = 0;
v65 = 0;
if ( v67 > 0 )
{
v69 = (v68 - 25) % 10 - ((v64 - 1) >> 1);
do
{
v50 = v69;
if ( v69 < 0 )
v50 = 0;
v67 = 0;
if ( v64 > 0 )
{
v51 = &plr[v3].InvGrid[v50 + v49];
do
{
if ( v67 || v65 != v48 - 1 )
v52 = -(char)v66;
else
v52 = v66;
*v51++ = v52;
++v67;
}
while ( v67 < v64 );
}
v49 += 10;
++v65;
}
while ( v65 < v48 );
}
goto LABEL_226;
}
v44 = v66 - 1;
if ( v35 == 11 )
plr[v3]._pGold += plr[v3].HoldItem._ivalue;
cursor_ida = SwapItem((ItemStruct *)((char *)&plr[0].InvList[v44] + v3 * 21720), &plr[v3].HoldItem);
if ( plr[v3].HoldItem._itype == ITYPE_GOLD )
plr[v3]._pGold = CalculateGold(v21);
v45 = 0;
v46 = -v66;
do
{
v47 = &plr[v3].InvGrid[v45];
if ( *v47 == v66 )
*v47 = 0;
if ( *v47 == v46 )
*v47 = 0;
++v45;
}
while ( v45 < 40 );
goto LABEL_191;
case ILOC_BELT:
v53 = v3 * 21720 + 368 * (v68 - 65);
if ( plr[v3].HoldItem._itype != ITYPE_GOLD )
{
if ( *(int *)((char *)&plr[0].SpdList[0]._itype + v53) == ITYPE_NONE )
{
qmemcpy((char *)plr[0].SpdList + v53, &plr[v3].HoldItem, 0x170u);
}
else
{
cursor_ida = SwapItem((ItemStruct *)((char *)plr[0].SpdList + v53), &plr[v3].HoldItem);
if ( plr[v3].HoldItem._itype == ITYPE_GOLD )
plr[v3]._pGold = CalculateGold(p);
}
goto LABEL_225;
}
v54 = *(int *)((char *)&plr[0].SpdList[0]._itype + v53);
if ( v54 != -1 )
{
if ( v54 == 11 )
{
v55 = *(int *)((char *)&plr[0].SpdList[0]._ivalue + v53);
v56 = plr[v3].HoldItem._ivalue;
v57 = v55 + v56;
if ( v55 + v56 <= 5000 )
{
*(int *)((char *)&plr[0].SpdList[0]._ivalue + v53) = v57;
plr[v3]._pGold += plr[v3].HoldItem._ivalue;
if ( v57 < 2500 )
{
if ( v57 > 1000 )
*(int *)((char *)&plr[0].SpdList[0]._iCurs + v53) = 5;
else
*(int *)((char *)&plr[0].SpdList[0]._iCurs + v53) = 4;
}
else
{
*(int *)((char *)&plr[0].SpdList[0]._iCurs + v53) = 6;
}
goto LABEL_225;
}
plr[v3]._pGold += 5000 - v55;
plr[v3].HoldItem._ivalue = v56 - (5000 - v55);
*(int *)((char *)&plr[0].SpdList[0]._ivalue + v53) = 5000;
*(int *)((char *)&plr[0].SpdList[0]._iCurs + v53) = 6;
v58 = plr[v3].HoldItem._ivalue;
if ( v58 >= 2500 )
{
cursor_ida = 18;
goto LABEL_225;
}
v59 = (v58 > 1000) + 16;
}
else
{
plr[v3]._pGold += plr[v3].HoldItem._ivalue;
v59 = SwapItem((ItemStruct *)((char *)plr[0].SpdList + v53), &plr[v3].HoldItem);
}
cursor_ida = v59;
goto LABEL_225;
}
qmemcpy((char *)plr[0].SpdList + v53, &plr[v3].HoldItem, 0x170u);
plr[v3]._pGold += plr[v3].HoldItem._ivalue;
LABEL_225:
drawsbarflag = 1;
LABEL_226:
v60 = p;
CalcPlrInv(p, 1u);
if ( v60 == myplr )
{
if ( cursor_ida == 1 )
SetCursorPos(MouseX + (cursW >> 1), MouseY + (cursH >> 1));
SetCursor(cursor_ida);
}
return;
default:
goto LABEL_226;
}
}
v62 = (v68 - 25) % 10;
v14 = 10 * (v13 - ((v67 - 1) >> 1));
if ( v14 < 0 )
v14 = 0;
v65 = 0;
if ( v67 <= 0 )
goto LABEL_93;
v15 = &plr[v3].InvGrid[v14];
while ( 1 )
{
if ( cursor_id == CURSOR_NONE )
return;
if ( v14 >= 40 )
cursor_id = 0;
v16 = v62 - ((v64 - 1) >> 1);
if ( v16 < 0 )
v16 = 0;
v17 = 0;
if ( v64 > 0 )
break;
LABEL_79:
v14 += 10;
v15 += 10;
if ( ++v65 >= v67 )
{
v12 = cursor_id;
v10 = v68;
goto LABEL_81;
}
}
while ( 1 )
{
if ( cursor_id == CURSOR_NONE )
goto LABEL_79;
if ( v16 >= 10 )
goto LABEL_233;
_LOBYTE(v18) = v15[v16];
if ( (_BYTE)v18 )
{
v18 = (char)v18;
if ( (v18 & 0x80u) != 0 )
v18 = -v18;
if ( !v66 )
{
v66 = v18;
goto LABEL_78;
}
if ( v66 != v18 )
LABEL_233:
cursor_id = 0;
}
LABEL_78:
++v16;
if ( ++v17 >= v64 )
goto LABEL_79;
}
}
if ( v64 == 1 && v67 == 1 )
{
v12 = 1;
if ( !AllItemsList[plr[v3].HoldItem.IDidx].iUsable )
v12 = 0;
if ( !plr[v3].HoldItem._iStatFlag )
v12 = 0;
if ( plr[v3].HoldItem._itype == ITYPE_GOLD )
{
v12 = 0;
goto LABEL_50;
}
}
LABEL_81:
if ( !v12 )
return;
if ( v69 == ILOC_UNEQUIPABLE || v69 == ILOC_BELT || plr[v3].HoldItem._iStatFlag )
goto LABEL_92;
v19 = plr[v3]._pClass;
if ( !v19 )
{
v20 = PS_WARR13;
goto LABEL_89;
}
if ( v19 != 1 )
{
if ( v19 != 2 )
return;
PlaySFX(PS_MAGE13);
v12 = 0;
v10 = v68;
LABEL_92:
if ( !v12 )
return;
goto LABEL_93;
}
v20 = PS_ROGUE13;
LABEL_89:
PlaySFX(v20);
}
// 4B8C9C: using guessed type int cursH;
// 4B8CB4: using guessed type int icursH;
// 4B8CBC: using guessed type int icursW;
// 52571C: using guessed type int drawpanflag;
void __fastcall CheckInvSwap(int pnum, BYTE bLoc, int idx, WORD wCI, int seed, BOOL bId)
{
RecreateItem(MAXITEMS, idx, wCI, seed, 0);
PlayerStruct *p = &plr[pnum];
p->HoldItem = item[MAXITEMS];
if ( bId )
{
p->HoldItem._iIdentified = TRUE;
}
if ( bLoc < NUM_INVLOC )
{
p->InvBody[bLoc] = p->HoldItem;
if ( bLoc == INVLOC_HAND_LEFT && p->HoldItem._iLoc == ILOC_TWOHAND )
{
p->InvBody[INVLOC_HAND_RIGHT]._itype = ITYPE_NONE;
}
else if ( bLoc == INVLOC_HAND_RIGHT && p->HoldItem._iLoc == ILOC_TWOHAND )
{
p->InvBody[INVLOC_HAND_LEFT]._itype = ITYPE_NONE;
}
}
CalcPlrInv(pnum, TRUE);
}
void __fastcall CheckInvCut(int pnum, int mx, int my)
{
if ( plr[pnum]._pmode > PM_WALK3 )
{
return;
}
if ( dropGoldFlag )
{
dropGoldFlag = 0;
dropGoldValue = 0;
}
int r;
BOOL done = FALSE;
// TODO: this loop is compiled differently (via InvRect pointers)
for ( r = 0; (DWORD)r < NUM_XY_SLOTS && !done; r++ )
{
// check which inventory rectangle the mouse is in, if any
if ( mx >= InvRect[r].X
&& mx < InvRect[r].X + (INV_SLOT_SIZE_PX + 1)
&& my >= InvRect[r].Y - (INV_SLOT_SIZE_PX + 1)
&& my < InvRect[r].Y )
{
done = TRUE;
r--;
}
}
if ( !done )
{
// not on an inventory slot rectangle
return;
}
plr[pnum].HoldItem._itype = ITYPE_NONE;
if (
r >= SLOTXY_HEAD_FIRST
&& r <= SLOTXY_HEAD_LAST
&& plr[pnum].InvBody[INVLOC_HEAD]._itype != ITYPE_NONE )
{
NetSendCmdDelItem(FALSE, INVLOC_HEAD);
plr[pnum].HoldItem = plr[pnum].InvBody[INVLOC_HEAD];
plr[pnum].InvBody[INVLOC_HEAD]._itype = ITYPE_NONE;
}
if (
r == SLOTXY_RING_LEFT
&& plr[pnum].InvBody[INVLOC_RING_LEFT]._itype != ITYPE_NONE )
{
NetSendCmdDelItem(FALSE, INVLOC_RING_LEFT);
plr[pnum].HoldItem = plr[pnum].InvBody[INVLOC_RING_LEFT];
plr[pnum].InvBody[INVLOC_RING_LEFT]._itype = ITYPE_NONE;
}
if (
r == SLOTXY_RING_RIGHT
&& plr[pnum].InvBody[INVLOC_RING_RIGHT]._itype != ITYPE_NONE )
{
NetSendCmdDelItem(FALSE, INVLOC_RING_RIGHT);
plr[pnum].HoldItem = plr[pnum].InvBody[INVLOC_RING_RIGHT];
plr[pnum].InvBody[INVLOC_RING_RIGHT]._itype = ITYPE_NONE;
}
if (
r == SLOTXY_AMULET
&& plr[pnum].InvBody[INVLOC_AMULET]._itype != ITYPE_NONE )
{
NetSendCmdDelItem(FALSE, INVLOC_AMULET);
plr[pnum].HoldItem = plr[pnum].InvBody[INVLOC_AMULET];
plr[pnum].InvBody[INVLOC_AMULET]._itype = ITYPE_NONE;
}
if (
r >= SLOTXY_HAND_LEFT_FIRST
&& r <= SLOTXY_HAND_LEFT_LAST
&& plr[pnum].InvBody[INVLOC_HAND_LEFT]._itype != ITYPE_NONE )
{
NetSendCmdDelItem(FALSE, INVLOC_HAND_LEFT);
plr[pnum].HoldItem = plr[pnum].InvBody[INVLOC_HAND_LEFT];
plr[pnum].InvBody[INVLOC_HAND_LEFT]._itype = ITYPE_NONE;
}
if (
r >= SLOTXY_HAND_RIGHT_FIRST
&& r <= SLOTXY_HAND_RIGHT_LAST
&& plr[pnum].InvBody[INVLOC_HAND_RIGHT]._itype != ITYPE_NONE )
{
NetSendCmdDelItem(FALSE, INVLOC_HAND_RIGHT);
plr[pnum].HoldItem = plr[pnum].InvBody[INVLOC_HAND_RIGHT];
plr[pnum].InvBody[INVLOC_HAND_RIGHT]._itype = ITYPE_NONE;
}
if (
r >= SLOTXY_CHEST_FIRST
&& r <= SLOTXY_CHEST_LAST
&& plr[pnum].InvBody[INVLOC_CHEST]._itype != ITYPE_NONE )
{
NetSendCmdDelItem(FALSE, INVLOC_CHEST);
plr[pnum].HoldItem = plr[pnum].InvBody[INVLOC_CHEST];
plr[pnum].InvBody[INVLOC_CHEST]._itype = ITYPE_NONE;
}
if ( r >= SLOTXY_INV_FIRST && r <= SLOTXY_INV_LAST )
{
char ii = plr[pnum].InvGrid[r - SLOTXY_INV_FIRST];
if ( ii )
{
int iv = ii;
if ( ii <= 0 )
{
iv = -ii;
}
for ( int i = 0; i < NUM_INV_GRID_ELEM; i++ )
{
if ( plr[pnum].InvGrid[i] == iv || plr[pnum].InvGrid[i] == -iv )
{
plr[pnum].InvGrid[i] = 0;
}
}
iv--;
plr[pnum].HoldItem = plr[pnum].InvList[iv];
plr[pnum]._pNumInv--;
if ( plr[pnum]._pNumInv > 0 && plr[pnum]._pNumInv != iv )
{
plr[pnum].InvList[iv] = plr[pnum].InvList[plr[pnum]._pNumInv];
for ( int j = 0; j < NUM_INV_GRID_ELEM; j++ )
{
if ( plr[pnum].InvGrid[j] == plr[pnum]._pNumInv + 1 )
{
plr[pnum].InvGrid[j] = iv + 1;
}
if ( plr[pnum].InvGrid[j] == -(plr[pnum]._pNumInv + 1) )
{
plr[pnum].InvGrid[j] = -iv - 1;
}
}
}
}
}
if ( r >= SLOTXY_BELT_FIRST )
{
int offs = r - SLOTXY_BELT_FIRST;
if ( plr[pnum].SpdList[offs]._itype != ITYPE_NONE )
{
plr[pnum].HoldItem = plr[pnum].SpdList[offs];
plr[pnum].SpdList[offs]._itype = ITYPE_NONE;
drawsbarflag = 1;
}
}
if ( plr[pnum].HoldItem._itype != ITYPE_NONE )
{
if ( plr[pnum].HoldItem._itype == ITYPE_GOLD )
{
plr[pnum]._pGold = CalculateGold(pnum);
}
CalcPlrInv(pnum, TRUE);
CheckItemStats(pnum);
if ( pnum == myplr )
{
PlaySFX(IS_IGRAB);
SetCursor(plr[pnum].HoldItem._iCurs + CURSOR_FIRSTITEM);
SetCursorPos(mx - (cursW >> 1), MouseY - (cursH >> 1));
}
}
}
void __fastcall inv_update_rem_item(int pnum, BYTE iv)
{
if ( iv < NUM_INVLOC )
{
plr[pnum].InvBody[iv]._itype = ITYPE_NONE;
}
BOOL Loadgfx = FALSE;
if ( plr[pnum]._pmode != PM_DEATH )
{
Loadgfx = TRUE;
}
CalcPlrInv(pnum, Loadgfx);
}
void __fastcall RemoveInvItem(int pnum, int iv)
{
iv++;
for ( int i = 0; i < NUM_INV_GRID_ELEM; i++ )
{
if ( plr[pnum].InvGrid[i] == iv || plr[pnum].InvGrid[i] == -iv )
{
plr[pnum].InvGrid[i] = 0;
}
}
iv--;
plr[pnum]._pNumInv--;
if ( plr[pnum]._pNumInv > 0 && plr[pnum]._pNumInv != iv )
{
plr[pnum].InvList[iv] = plr[pnum].InvList[plr[pnum]._pNumInv];
for ( int j = 0; j < NUM_INV_GRID_ELEM; j++ )
{
if ( plr[pnum].InvGrid[j] == plr[pnum]._pNumInv + 1 )
{
plr[pnum].InvGrid[j] = iv + 1;
}
if ( plr[pnum].InvGrid[j] == -(plr[pnum]._pNumInv + 1) )
{
plr[pnum].InvGrid[j] = -(iv + 1);
}
}
}
CalcPlrScrolls(pnum);
if ( plr[pnum]._pRSplType == RSPLTYPE_SCROLL )
{
if ( plr[pnum]._pRSpell != SPL_INVALID )
{
// BUGFIX: Cast the literal `1` to `UINT64` to make that bitshift 64bit
// this causes the last 4 skills to not reset correctly after use
if ( !(
plr[pnum]._pScrlSpells64
& (1 << (plr[pnum]._pRSpell - 1))) )
{
plr[pnum]._pRSpell = SPL_INVALID;
}
drawpanflag = 255;
}
}
}
void __fastcall RemoveSpdBarItem(int pnum, int iv)
{
plr[pnum].SpdList[iv]._itype = ITYPE_NONE;
CalcPlrScrolls(pnum);
if ( plr[pnum]._pRSplType == RSPLTYPE_SCROLL )
{
if ( plr[pnum]._pRSpell != SPL_INVALID )
{
// BUGFIX: Cast the literal `1` to `UINT64` to make that bitshift 64bit
// this causes the last 4 skills to not reset correctly after use
if ( !(
plr[pnum]._pScrlSpells64
& (1 << (plr[pnum]._pRSpell - 1))) )
{
plr[pnum]._pRSpell = SPL_INVALID;
}
}
}
drawpanflag = 255;
}
void __cdecl CheckInvItem()
{
if ( pcurs >= CURSOR_FIRSTITEM )
{
CheckInvPaste(myplr, MouseX, MouseY);
}
else
{
CheckInvCut(myplr, MouseX, MouseY);
}
}
void __cdecl CheckInvScrn()
{
if ( MouseX > 190 && MouseX < 437
&& MouseY > 352 && MouseY < 385 )
{
CheckInvItem();
}
}
void __fastcall CheckItemStats(int pnum)
{
PlayerStruct *p = &plr[pnum];
p->HoldItem._iStatFlag = FALSE;
if ( p->_pStrength >= p->HoldItem._iMinStr
&& p->_pMagic >= p->HoldItem._iMinMag
&& p->_pDexterity >= p->HoldItem._iMinDex )
{
p->HoldItem._iStatFlag = TRUE;
}
}
void __fastcall CheckBookLevel(int pnum)
{
int v1; // ecx
int v2; // eax
unsigned char v3; // bl
int v4; // edi
v1 = pnum;
if ( plr[v1].HoldItem._iMiscId == IMISC_BOOK )
{
v2 = plr[v1].HoldItem._iSpell;
v3 = spelldata[plr[v1].HoldItem._iSpell].sMinInt;
plr[v1].HoldItem._iMinMag = v3;
v4 = plr[0]._pSplLvl[v2 + v1 * 21720];
if ( plr[0]._pSplLvl[v2 + v1 * 21720] )
{
do
{
v3 += 20 * v3 / 100;
--v4;
if ( v3 + 20 * v3 / 100 > 255 )
{
v3 = -1;
v4 = 0;
}
}
while ( v4 );
plr[v1].HoldItem._iMinMag = v3;
}
}
}
void __fastcall CheckQuestItem(int pnum)
{
int v1; // ecx
int v2; // esi
char v3; // cl
char v4; // cl
char v5; // cl
char v6; // cl
char v7; // al
v1 = pnum;
v2 = plr[v1].HoldItem.IDidx;
if ( v2 == IDI_OPTAMULET )
quests[8]._qactive = 3;
if ( v2 == IDI_MUSHROOM && quests[1]._qactive == 2 && quests[1]._qvar1 == 3 )
{
v3 = plr[v1]._pClass;
sfxdelay = IDI_OPTAMULET;
if ( v3 )
{
if ( v3 == 1 )
{
sfxdnum = PS_ROGUE95;
}
else if ( v3 == 2 )
{
sfxdnum = PS_MAGE95;
}
}
else
{
sfxdnum = PS_WARR95;
}
quests[1]._qvar1 = 4;
}
if ( v2 == IDI_ANVIL )
{
if ( quests[10]._qactive == 1 )
{
quests[10]._qactive = 2;
quests[10]._qvar1 = 1;
}
if ( quests[10]._qlog == 1 )
{
sfxdelay = IDI_OPTAMULET;
v4 = plr[myplr]._pClass;
if ( v4 )
{
if ( v4 == 1 )
{
sfxdnum = PS_ROGUE89;
}
else if ( v4 == 2 )
{
sfxdnum = PS_MAGE89;
}
}
else
{
sfxdnum = PS_WARR89;
}
}
}
if ( v2 == IDI_GLDNELIX )
{
sfxdelay = 30;
v5 = plr[myplr]._pClass;
if ( v5 )
{
if ( v5 == 1 )
{
sfxdnum = PS_ROGUE88;
}
else if ( v5 == 2 )
{
sfxdnum = PS_MAGE88;
}
}
else
{
sfxdnum = PS_WARR88;
}
}
if ( v2 == IDI_ROCK )
{
if ( quests[0]._qactive == 1 )
{
quests[0]._qactive = 2;
quests[0]._qvar1 = 1;
}
if ( quests[0]._qlog == 1 )
{
sfxdelay = IDI_OPTAMULET;
v6 = plr[myplr]._pClass;
if ( v6 )
{
if ( v6 == 1 )
{
sfxdnum = PS_ROGUE87;
}
else if ( v6 == 2 )
{
sfxdnum = PS_MAGE87;
}
}
else
{
sfxdnum = PS_WARR87;
}
}
}
if ( v2 == IDI_ARMOFVAL )
{
quests[9]._qactive = 3;
sfxdelay = 20;
v7 = plr[myplr]._pClass;
if ( v7 )
{
if ( v7 == 1 )
{
sfxdnum = PS_ROGUE91;
}
else if ( v7 == 2 )
{
sfxdnum = PS_MAGE91;
}
}
else
{
sfxdnum = PS_WARR91;
}
}
}
// 52A554: using guessed type int sfxdelay;
void __fastcall InvGetItem(int pnum, int ii)
{
int v2; // ebp
int v3; // edx
int v4; // ecx
int v5; // ecx
int pnuma; // [esp+4h] [ebp-8h]
int v7; // [esp+8h] [ebp-4h]
v7 = ii;
pnuma = pnum;
if ( dropGoldFlag )
{
dropGoldFlag = 0;
dropGoldValue = 0;
}
v2 = ii;
if ( dItem[item[ii]._ix][item[ii]._iy] )
{
if ( myplr == pnum && pcurs >= CURSOR_FIRSTITEM )
NetSendCmdPItem(1u, CMD_SYNCPUTITEM, plr[myplr].WorldX, plr[myplr].WorldY);
_HIBYTE(item[v2]._iCreateInfo) &= 0x7Fu;
qmemcpy(&plr[pnuma].HoldItem, &item[v2], sizeof(plr[pnuma].HoldItem));
CheckQuestItem(pnuma);
CheckBookLevel(pnuma);
CheckItemStats(pnuma);
v3 = 0;
dItem[item[v2]._ix][item[v2]._iy] = 0;
while ( v3 < numitems )
{
v4 = itemactive[v3];
if ( v4 == v7 )
{
DeleteItem(v4, v3);
v3 = 0;
}
else
{
++v3;
}
}
v5 = plr[pnuma].HoldItem._iCurs;
pcursitem = -1;
SetCursor(v5 + 12);
}
}
// 4B84DC: using guessed type int dropGoldFlag;
// 4B8CC0: using guessed type char pcursitem;
void __fastcall AutoGetItem(int pnum, int ii)
{
int v2; // ebx
int v3; // ebp
int v4; // eax
int v5; // ecx
int v6; // edi
int v7; // edi
int v8; // edi
int v9; // edi
int v10; // edx
int v11; // ecx
char v12; // al
int v13; // ecx
int iia; // [esp+10h] [ebp-18h]
signed int iib; // [esp+10h] [ebp-18h]
signed int iic; // [esp+10h] [ebp-18h]
signed int iid; // [esp+10h] [ebp-18h]
signed int iie; // [esp+10h] [ebp-18h]
signed int iif; // [esp+10h] [ebp-18h]
signed int iig; // [esp+10h] [ebp-18h]
signed int iih; // [esp+10h] [ebp-18h]
signed int iii; // [esp+10h] [ebp-18h]
signed int iij; // [esp+10h] [ebp-18h]
ItemStruct *v24; // [esp+14h] [ebp-14h]
int *v25; // [esp+14h] [ebp-14h]
int v26; // [esp+18h] [ebp-10h]
int i; // [esp+1Ch] [ebp-Ch]
int v28; // [esp+20h] [ebp-8h]
int v29; // [esp+24h] [ebp-4h]
v2 = pnum;
i = ii;
if ( dropGoldFlag )
{
dropGoldFlag = 0;
dropGoldValue = 0;
}
if ( ii == 127 || dItem[item[ii]._ix][item[ii]._iy] )
{
v3 = pnum;
_HIBYTE(item[ii]._iCreateInfo) &= 0x7Fu;
v28 = ii;
qmemcpy(&plr[pnum].HoldItem, &item[ii], sizeof(plr[pnum].HoldItem));
CheckQuestItem(pnum);
CheckBookLevel(v2);
CheckItemStats(v2);
SetICursor(plr[v2].HoldItem._iCurs + 12);
if ( plr[v2].HoldItem._itype == ITYPE_GOLD )
{
v4 = GoldAutoPlace(v2);
}
else
{
v4 = 0;
if ( (!(plr[v3]._pgfxnum & 0xF) || (plr[v3]._pgfxnum & 0xF) == 1) && plr[v3]._pmode <= PM_WALK3 )
{
if ( plr[v3].HoldItem._iStatFlag )
{
if ( plr[v3].HoldItem._iClass == 1 )
{
v4 = WeaponAutoPlace(v2);
if ( v4 )
{
CalcPlrInv(v2, 1u);
goto LABEL_71;
}
}
}
}
v5 = icursW28;
v29 = icursW28;
v26 = icursH28;
if ( icursW28 == 1 )
{
if ( icursH28 == 1 )
{
if ( plr[v3].HoldItem._iStatFlag && AllItemsList[plr[v3].HoldItem.IDidx].iUsable )
{
iia = 0;
v24 = plr[v3].SpdList;
do
{
if ( v4 )
break;
if ( v24->_itype == -1 )
{
qmemcpy(v24, &plr[v3].HoldItem, sizeof(ItemStruct));
CalcPlrScrolls(v2);
v4 = 1;
drawsbarflag = 1;
}
++iia;
++v24;
}
while ( iia < 8 );
}
v6 = 30;
do
{
if ( v4 )
break;
v4 = AutoPlace(v2, v6++, 1, 1, 1);
}
while ( v6 <= 39 );
v7 = 20;
do
{
if ( v4 )
break;
v4 = AutoPlace(v2, v7++, 1, 1, 1);
}
while ( v7 <= 29 );
v8 = 10;
do
{
if ( v4 )
break;
v4 = AutoPlace(v2, v8++, 1, 1, 1);
}
while ( v8 <= 19 );
v9 = 0;
while ( !v4 )
{
v4 = AutoPlace(v2, v9++, 1, 1, 1);
if ( v9 > 9 )
goto LABEL_35;
}
goto LABEL_71;
}
LABEL_35:
if ( v26 == 2 )
{
iib = 29;
do
{
if ( v4 )
break;
v4 = AutoPlace(v2, iib--, 1, 2, 1);
}
while ( iib >= 20 );
iic = 9;
do
{
if ( v4 )
break;
v4 = AutoPlace(v2, iic--, 1, 2, 1);
}
while ( iic >= 0 );
iid = 19;
while ( !v4 )
{
v4 = AutoPlace(v2, iid--, 1, 2, 1);
if ( iid < 10 )
goto LABEL_45;
}
goto LABEL_71;
}
LABEL_45:
if ( v26 == 3 )
{
iie = 0;
while ( !v4 )
{
v4 = AutoPlace(v2, iie++, 1, 3, 1);
if ( iie >= 20 )
goto LABEL_49;
}
goto LABEL_71;
}
}
else
{
LABEL_49:
if ( v29 == 2 )
{
if ( v26 == 2 )
{
v25 = AP2x2Tbl;
do
{
if ( v4 )
break;
v4 = AutoPlace(v2, *v25, 2, 2, 1);
++v25;
}
while ( (signed int)v25 < (signed int)&AP2x2Tbl[10] );
iif = 21;
do
{
if ( v4 )
break;
v4 = AutoPlace(v2, iif, 2, 2, 1);
iif += 2;
}
while ( iif < 29 );
iig = 1;
do
{
if ( v4 )
break;
v4 = AutoPlace(v2, iig, 2, 2, 1);
iig += 2;
}
while ( iig < 9 );
iih = 10;
while ( !v4 )
{
v4 = AutoPlace(v2, iih++, 2, 2, 1);
if ( iih >= 19 )
goto LABEL_63;
}
goto LABEL_71;
}
LABEL_63:
if ( v26 == 3 )
{
iii = 0;
do
{
if ( v4 )
break;
v4 = AutoPlace(v2, iii++, 2, 3, 1);
}
while ( iii < 9 );
iij = 10;
while ( !v4 )
{
v4 = AutoPlace(v2, iij++, 2, 3, 1);
if ( iij >= 19 )
goto LABEL_70;
}
goto LABEL_71;
}
}
}
}
LABEL_70:
if ( v4 )
{
LABEL_71:
v10 = 0;
dItem[item[v28]._ix][item[v28]._iy] = 0;
while ( v10 < numitems )
{
v11 = itemactive[v10];
if ( v11 == i )
{
DeleteItem(v11, v10);
v10 = 0;
}
else
{
++v10;
}
}
return;
}
if ( v2 == myplr )
{
v12 = plr[v3]._pClass;
switch ( v12 )
{
case UI_WARRIOR:
v13 = random(0, 3) + PS_WARR14;
LABEL_84:
PlaySFX(v13);
break;
case UI_ROGUE:
v13 = random(0, 3) + PS_ROGUE14;
goto LABEL_84;
case UI_SORCERER:
v13 = random(0, 3) + PS_MAGE14;
goto LABEL_84;
}
}
qmemcpy(&plr[v3].HoldItem, &item[v28], sizeof(plr[v3].HoldItem));
RespawnItem(i, 1);
NetSendCmdPItem(1u, CMD_RESPAWNITEM, item[v28]._ix, item[v28]._iy);
plr[v3].HoldItem._itype = ITYPE_NONE;
}
}
// 48E9A8: using guessed type int AP2x2Tbl[10];
// 4B84DC: using guessed type int dropGoldFlag;
int __fastcall FindGetItem(int indx, unsigned short ci, int iseed)
{
int i; // ebx
int ii; // esi
i = 0;
if ( numitems <= 0 )
return -1;
while ( 1 )
{
ii = itemactive[i];
if ( item[ii].IDidx == indx && item[ii]._iSeed == iseed && item[ii]._iCreateInfo == ci )
break;
if ( ++i >= numitems )
return -1;
}
return ii;
}
void __fastcall SyncGetItem(int x, int y, int idx, unsigned short ci, int iseed)
{
char v5; // cl
int v6; // esi
int v7; // eax
int v8; // edx
int v9; // ecx
//int v10; // ecx
v5 = dItem[x][y];
if ( v5
&& (v6 = v5 - 1, v7 = v6, item[v7].IDidx == idx)
&& item[v7]._iSeed == iseed
&& item[v7]._iCreateInfo == ci )
{
FindGetItem(idx, ci, iseed);
}
else
{
v6 = FindGetItem(idx, ci, iseed);
}
if ( v6 != -1 )
{
v8 = 0;
dItem[item[v6]._ix][item[v6]._iy] = 0;
while ( v8 < numitems )
{
v9 = itemactive[v8];
if ( v9 == v6 )
{
DeleteItem(v9, v8);
FindGetItem(idx, ci, iseed);
FindGetItem(idx, ci, iseed); /* check idx */
v8 = 0;
}
else
{
++v8;
}
}
FindGetItem(idx, ci, iseed);
}
}
int __fastcall CanPut(int i, int j)
{
int v2; // ecx
int v3; // esi
char v4; // al
int v5; // eax
char v6; // al
bool v7; // sf
char v8; // al
char v9; // cl
v2 = i;
if ( dItem[v2][j] )
return 0;
v3 = v2 * 112 + j;
if ( nSolidTable[dPiece[0][v3]] )
return 0;
v4 = dObject[v2][j];
if ( v4 )
{
v5 = v4 <= 0 ? -1 - v4 : v4 - 1;
if ( object[v5]._oSolidFlag )
return 0;
}
v6 = dObject[v2 + 1][j + 1];
v7 = v6 < 0;
if ( v6 > 0 )
{
if ( object[v6 - 1]._oSelFlag ) /* check */
return 0;
v7 = v6 < 0;
}
if ( v7 && object[-(v6 + 1)]._oSelFlag )
return 0;
v8 = dObject[v2 + 1][j];
if ( v8 > 0 )
{
v9 = dObject[v2][j + 1];
if ( v9 > 0 && object[v8 - 1]._oSelFlag && object[v9 - 1]._oSelFlag )
return 0;
}
if ( !currlevel && (dMonster[0][v3] || dMonster[1][v3 + 1]) )
return 0;
return 1;
}
int __cdecl TryInvPut()
{
int result; // eax
int v1; // eax
char v2; // si
int v3; // edi
int v4; // ebx
int v5; // esi
if ( numitems >= 127 )
return 0;
v1 = GetDirection(plr[myplr].WorldX, plr[myplr].WorldY, cursmx, cursmy);
v2 = v1;
v3 = plr[myplr].WorldY;
v4 = plr[myplr].WorldX;
if ( CanPut(v4 + offset_x[v1], v3 + offset_y[v1])
|| (v5 = (v2 - 1) & 7, CanPut(v4 + offset_x[v5], v3 + offset_y[v5]))
|| CanPut(v4 + offset_x[((_BYTE)v5 + 2) & 7], v3 + offset_y[((_BYTE)v5 + 2) & 7]) )
{
result = 1;
}
else
{
result = CanPut(v4, v3);
}
return result;
}
void __fastcall DrawInvMsg(char *msg)
{
char *v1; // esi
int v2; // eax
v1 = msg;
v2 = GetTickCount();
if ( (unsigned int)(v2 - sgdwLastTime) >= 5000 )
{
sgdwLastTime = v2;
ErrorPlrMsg(v1);
}
}
int __fastcall InvPutItem(int pnum, int x, int y)
{
int v3; // edi
int *v4; // esi
int v5; // ebx
int v6; // esi
int v7; // eax
int v8; // edi
int v9; // esi
int v10; // esi
int v11; // eax
int v12; // edx
int v13; // esi
int v15; // eax
int *v16; // edx
int v17; // edx
ItemStruct *v18; // [esp+Ch] [ebp-1Ch]
int v19; // [esp+10h] [ebp-18h]
signed int v20; // [esp+14h] [ebp-14h]
int v21; // [esp+18h] [ebp-10h]
int v22; // [esp+1Ch] [ebp-Ch]
signed int v23; // [esp+20h] [ebp-8h]
int xa; // [esp+24h] [ebp-4h]
int ya; // [esp+30h] [ebp+8h]
int yb; // [esp+30h] [ebp+8h]
int yc; // [esp+30h] [ebp+8h]
xa = x;
if ( numitems >= 127 )
return -1;
v3 = pnum;
_LOWORD(x) = plr[pnum].HoldItem._iCreateInfo;
v4 = &plr[pnum].HoldItem._iSeed;
v18 = &plr[pnum].HoldItem;
v5 = y;
if ( FindGetItem(plr[pnum].HoldItem.IDidx, x, plr[pnum].HoldItem._iSeed) != -1 )
{
DrawInvMsg("A duplicate item has been detected. Destroying duplicate...");
SyncGetItem(xa, y, plr[v3].HoldItem.IDidx, plr[v3].HoldItem._iCreateInfo, *v4);
}
ya = GetDirection(plr[v3].WorldX, plr[v3].WorldY, xa, y);
v6 = v5 - plr[v3].WorldY;
if ( abs(xa - plr[v3].WorldX) > 1 || abs(v6) > 1 )
{
v5 = plr[v3].WorldY + offset_y[ya];
xa = plr[v3].WorldX + offset_x[ya];
}
if ( !CanPut(xa, v5) )
{
v7 = plr[v3].WorldX;
v8 = plr[v3].WorldY;
v9 = ((_BYTE)ya - 1) & 7;
v19 = v7;
v5 = v8 + offset_y[v9];
xa = v7 + offset_x[v9];
if ( !CanPut(xa, v8 + offset_y[v9]) )
{
v10 = ((_BYTE)v9 + 2) & 7;
v5 = v8 + offset_y[v10];
xa = v19 + offset_x[v10];
if ( !CanPut(xa, v8 + offset_y[v10]) )
{
v23 = 0;
v11 = -1;
yb = 1;
v20 = -1;
while ( !v23 )
{
v22 = v11;
while ( v11 <= yb && !v23 )
{
v21 = v20;
v12 = v8 + v22;
v13 = v19 + v20;
do
{
if ( v23 )
break;
if ( CanPut(v13, v12) )
{
v23 = 1;
xa = v13;
v5 = v12;
}
++v21;
++v13;
}
while ( v21 <= yb );
v11 = ++v22;
}
++yb;
v11 = v20-- - 1;
if ( v20 <= -50 )
{
if ( v23 )
break;
return -1;
}
}
}
}
}
CanPut(xa, v5);
v15 = itemavail[0];
dItem[xa][v5] = _LOBYTE(itemavail[0]) + 1;
yc = v15;
v16 = &itemavail[-numitems + 126];
itemactive[numitems] = v15;
itemavail[0] = *v16;
v17 = v15;
qmemcpy(&item[v15], v18, sizeof(ItemStruct));
item[v17]._iy = v5;
item[v17]._ix = xa;
RespawnItem(v15, 1);
++numitems;
SetCursor(CURSOR_HAND);
return yc;
}
int __fastcall SyncPutItem(int pnum, int x, int y, int idx, int icreateinfo, int iseed, int Id, int dur, int mdur, int ch, int mch, int ivalue, unsigned int ibuff)
{
int v13; // ebx
int v14; // edi
int v15; // esi
int v17; // edi
int v18; // ecx
int v19; // edi
int v20; // eax
int v21; // eax
int v22; // eax
int v23; // edx
int v25; // ecx
int *v26; // edx
int v27; // eax
int v28; // eax
int v29; // [esp+Ch] [ebp-18h]
int v30; // [esp+Ch] [ebp-18h]
signed int v31; // [esp+10h] [ebp-14h]
int v32; // [esp+14h] [ebp-10h]
int v33; // [esp+18h] [ebp-Ch]
int o1; // [esp+1Ch] [ebp-8h]
signed int v35; // [esp+20h] [ebp-4h]
int i; // [esp+2Ch] [ebp+8h]
int ia; // [esp+2Ch] [ebp+8h]
int ib; // [esp+2Ch] [ebp+8h]
int ic; // [esp+2Ch] [ebp+8h]
v13 = x;
v14 = pnum;
if ( numitems >= 127 )
return -1;
v15 = y;
if ( FindGetItem(idx, icreateinfo, iseed) != -1 )
{
DrawInvMsg("A duplicate item has been detected from another player.");
SyncGetItem(v13, y, idx, icreateinfo, iseed);
}
v17 = v14;
i = GetDirection(plr[v17].WorldX, plr[v17].WorldY, v13, y);
v29 = v15 - plr[v17].WorldY;
if ( abs(v13 - plr[v17].WorldX) > 1 || abs(v29) > 1 )
{
v13 = plr[v17].WorldX + offset_x[i];
v15 = plr[v17].WorldY + offset_y[i];
}
if ( !CanPut(v13, v15) )
{
v18 = plr[v17].WorldX;
v19 = plr[v17].WorldY;
v20 = ((_BYTE)i - 1) & 7;
v30 = v18;
ia = v20;
v20 *= 4;
v13 = v18 + *(int *)((char *)offset_x + v20);
v15 = v19 + *(int *)((char *)offset_y + v20);
if ( !CanPut(v18 + *(int *)((char *)offset_x + v20), v19 + *(int *)((char *)offset_y + v20)) )
{
v21 = ((_BYTE)ia + 2) & 7;
v13 = v30 + offset_x[v21];
v15 = v19 + offset_y[v21];
if ( !CanPut(v30 + offset_x[v21], v19 + offset_y[v21]) )
{
v35 = 0;
v22 = -1;
ib = 1;
v31 = -1;
while ( !v35 )
{
v33 = v22;
while ( v22 <= ib && !v35 )
{
v23 = v19 + v33;
v32 = v31;
o1 = v30 + v31;
do
{
if ( v35 )
break;
if ( CanPut(o1, v23) )
{
v13 = o1;
v35 = 1;
v15 = v23;
}
++v32;
++o1;
}
while ( v32 <= ib );
v22 = ++v33;
}
++ib;
v22 = v31-- - 1;
if ( v31 <= -50 )
{
if ( v35 )
break;
return -1;
}
}
}
}
}
CanPut(v13, v15);
v25 = itemavail[0];
ic = itemavail[0];
dItem[v13][v15] = _LOBYTE(itemavail[0]) + 1;
v26 = &itemavail[-numitems + 126];
itemactive[numitems] = v25;
itemavail[0] = *v26;
if ( idx == IDI_EAR )
{
RecreateEar(v25, icreateinfo, iseed, Id, dur, mdur, ch, mch, ivalue, ibuff);
}
else
{
RecreateItem(v25, idx, icreateinfo, iseed, ivalue);
if ( Id )
item[ic]._iIdentified = 1;
v27 = ic;
item[v27]._iDurability = dur;
item[v27]._iMaxDur = mdur;
item[v27]._iCharges = ch;
item[v27]._iMaxCharges = mch;
}
v28 = ic;
item[v28]._ix = v13;
item[v28]._iy = v15;
RespawnItem(ic, 1);
++numitems;
return ic;
}
int __cdecl CheckInvHLight()
{
signed int v0; // ebx
int result; // eax
ItemStruct *v2; // edi
PlayerStruct *v3; // esi
int v4; // eax
int v5; // ebx
int v6; // edi
char *v7; // eax
char v8; // al
char v9; // [esp+Fh] [ebp-1h]
v0 = 0;
do
{
result = InvRect[v0].X;
if ( MouseX >= result )
{
result += 29;
if ( MouseX < result )
{
result = InvRect[v0].Y;
if ( MouseY >= result - 29 && MouseY < result )
break;
}
}
++v0;
}
while ( (unsigned int)v0 < 0x49 );
if ( (unsigned int)v0 >= 0x49 )
goto LABEL_37;
v9 = -1;
_LOBYTE(infoclr) = 0;
v2 = 0;
v3 = &plr[myplr];
ClearPanel();
if ( v0 >= 0 && v0 <= 3 )
{
v9 = 0;
v2 = v3->InvBody;
goto LABEL_36;
}
switch ( v0 )
{
case 4:
v9 = 1;
v2 = &v3->InvBody[1];
goto LABEL_36;
case 5:
v9 = 2;
v2 = &v3->InvBody[2];
goto LABEL_36;
case 6:
v9 = 3;
v2 = &v3->InvBody[3];
goto LABEL_36;
}
if ( v0 >= 7 && v0 <= 12 )
{
v9 = 4;
v2 = &v3->InvBody[4];
goto LABEL_36;
}
if ( v0 < 13 || v0 > 18 )
{
if ( v0 >= 19 && v0 <= 24 )
{
v9 = 6;
v2 = &v3->InvBody[6];
goto LABEL_36;
}
if ( v0 < 25 || v0 > 64 )
{
if ( v0 < 65 )
goto LABEL_36;
v5 = v0 - 65;
drawsbarflag = 1;
result = 368 * v5;
v2 = &v3->SpdList[v5];
if ( v3->SpdList[v5]._itype != -1 )
{
v9 = v5 + 47;
goto LABEL_36;
}
}
else
{
result = abs(v3->InvGrid[v0 - 25]); // abs(*((char *)&v3->InvList[39]._iVAdd2 + v0 + 3)); /* find right address */
if ( result )
{
v4 = result - 1;
v9 = v4 + 7;
v2 = &v3->InvList[v4];
goto LABEL_36;
}
}
LABEL_37:
_LOBYTE(result) = -1;
return result;
}
v2 = &v3->InvBody[4];
if ( v3->InvBody[4]._itype == -1 || v3->InvBody[4]._iLoc != 2 )
{
v9 = 5;
v2 = &v3->InvBody[5];
}
else
{
v9 = 4;
}
LABEL_36:
result = v2->_itype;
if ( result == ITYPE_NONE )
goto LABEL_37;
if ( result == ITYPE_GOLD )
{
v6 = v2->_ivalue;
v7 = get_pieces_str(v6);
result = sprintf(infostr, "%i gold %s", v6, v7);
}
else
{
v8 = v2->_iMagical;
if ( v8 == 1 )
{
_LOBYTE(infoclr) = 1;
}
else if ( v8 == 2 )
{
_LOBYTE(infoclr) = 3;
}
strcpy(infostr, v2->_iName);
if ( v2->_iIdentified )
{
strcpy(infostr, v2->_iIName);
PrintItemDetails(v2);
}
else
{
PrintItemDur(v2);
}
}
_LOBYTE(result) = v9;
return result;
}
// 4B883C: using guessed type int infoclr;
void __fastcall RemoveScroll(int pnum)
{
int v1; // eax
int v2; // esi
int v3; // edx
int *v4; // ecx
int v5; // edx
int *v6; // ecx
int p; // [esp+Ch] [ebp-4h]
p = pnum;
v1 = pnum;
v2 = plr[pnum]._pNumInv;
v3 = 0;
if ( v2 <= 0 )
{
LABEL_8:
v5 = 0;
v6 = &plr[v1].SpdList[0]._iMiscId;
while ( *(v6 - 53) == -1 || *v6 != IMISC_SCROLL && *v6 != IMISC_SCROLLT || v6[1] != plr[v1]._pSpell )
{
++v5;
v6 += 92;
if ( v5 >= 8 )
return;
}
RemoveSpdBarItem(p, v5);
}
else
{
v4 = &plr[v1].InvList[0]._iMiscId;
while ( *(v4 - 53) == -1 || *v4 != IMISC_SCROLL && *v4 != IMISC_SCROLLT || v4[1] != plr[v1]._pSpell )
{
++v3;
v4 += 92;
if ( v3 >= v2 )
goto LABEL_8;
}
RemoveInvItem(p, v3);
}
CalcPlrScrolls(p);
}
bool __cdecl UseScroll()
{
int v0; // eax
int v1; // esi
int v2; // ecx
int *v3; // edx
signed int v4; // esi
int *v5; // ecx
if ( pcurs != CURSOR_HAND || leveltype == DTYPE_TOWN && !*(_DWORD *)&spelldata[plr[myplr]._pRSpell].sTownSpell )
return 0;
v0 = myplr;
v1 = 0;
v2 = plr[myplr]._pNumInv;
if ( v2 <= 0 )
{
LABEL_11:
v4 = 0;
v5 = &plr[v0].SpdList[0]._iMiscId;
while ( *(v5 - 53) == -1 || *v5 != IMISC_SCROLL && *v5 != IMISC_SCROLLT || v5[1] != plr[v0]._pRSpell )
{
++v4;
v5 += 92;
if ( v4 >= 8 )
return 0;
}
}
else
{
v3 = &plr[v0].InvList[0]._iMiscId;
while ( *(v3 - 53) == -1 || *v3 != IMISC_SCROLL && *v3 != IMISC_SCROLLT || v3[1] != plr[v0]._pRSpell )
{
++v1;
v3 += 92;
if ( v1 >= v2 )
goto LABEL_11;
}
}
return 1;
}
// 5BB1ED: using guessed type char leveltype;
void __fastcall UseStaffCharge(int pnum)
{
int v1; // eax
int *v2; // eax
v1 = pnum;
if ( plr[pnum].InvBody[4]._itype != ITYPE_NONE
&& plr[v1].InvBody[4]._iMiscId == IMISC_STAFF
&& plr[v1].InvBody[4]._iSpell == plr[v1]._pRSpell )
{
v2 = &plr[v1].InvBody[4]._iCharges;
if ( *v2 > 0 )
{
--*v2;
CalcPlrStaff(pnum);
}
}
}
bool __cdecl UseStaff()
{
int v0; // eax
bool result; // al
result = 0;
if ( pcurs == CURSOR_HAND )
{
v0 = myplr;
if ( plr[myplr].InvBody[4]._itype != ITYPE_NONE
&& plr[v0].InvBody[4]._iMiscId == IMISC_STAFF
&& plr[v0].InvBody[4]._iSpell == plr[v0]._pRSpell
&& plr[v0].InvBody[4]._iCharges > 0 )
{
result = 1;
}
}
return result;
}
void __cdecl StartGoldDrop()
{
int v0; // eax
initialDropGoldIndex = pcursinvitem;
if ( pcursinvitem > 46 )
v0 = plr[myplr].InvBody[pcursinvitem]._iMaxDur;
else
v0 = plr[myplr].InvBody[pcursinvitem]._ivalue;
dropGoldValue = 0;
initialDropGoldValue = v0;
dropGoldFlag = 1;
if ( talkflag )
control_reset_talk();
}
// 4B84DC: using guessed type int dropGoldFlag;
// 4B8960: using guessed type int talkflag;
// 4B8CB8: using guessed type char pcursinvitem;
int __fastcall UseInvItem(int pnum, int cii)
{
int v2; // esi
int result; // eax
int v4; // ebx
int v5; // ebp
_DWORD *v6; // edi
char v7; // al
int v8; // ecx
int v9; // eax
int v10; // ecx
char v11; // al
char v12; // al
int p; // [esp+10h] [ebp-8h]
signed int v14; // [esp+14h] [ebp-4h]
v2 = pnum;
p = pnum;
if ( plr[pnum]._pInvincible && !plr[v2]._pHitPoints && pnum == myplr )
return 1;
result = 1;
if ( pcurs == 1 && !stextflag )
{
if ( cii <= 5 )
return 0;
if ( cii > 46 )
{
if ( talkflag )
return result;
v4 = cii - 47;
v14 = 1;
v5 = 368 * (cii - 47) + v2 * 21720;
v6 = (_DWORD *)((char *)plr[0].SpdList + v5);
}
else
{
v4 = cii - 7;
v14 = 0;
v5 = 368 * (cii - 7) + v2 * 21720;
v6 = (_DWORD *)((char *)plr[0].InvList + v5);
}
if ( v6[90] == 17 )
{
v12 = plr[v2]._pClass;
sfxdelay = 10;
if ( v12 )
{
if ( v12 == 1 )
{
sfxdnum = PS_ROGUE95;
}
else if ( v12 == 2 )
{
sfxdnum = PS_MAGE95;
}
}
else
{
sfxdnum = PS_WARR95;
}
return 1;
}
if ( v6[90] == 19 )
{
PlaySFX(IS_IBOOK);
v11 = plr[v2]._pClass;
sfxdelay = 10;
if ( v11 )
{
if ( v11 == 1 )
{
sfxdnum = PS_ROGUE29;
}
else if ( v11 == 2 )
{
sfxdnum = PS_MAGE29;
}
}
else
{
sfxdnum = PS_WARR29;
}
return 1;
}
if ( !AllItemsList[v6[90]].iUsable )
return 0;
if ( !v6[89] )
{
v7 = plr[v2]._pClass;
if ( v7 )
{
if ( v7 == 1 )
{
v8 = PS_ROGUE13;
}
else
{
if ( v7 != 2 )
return 1;
v8 = PS_MAGE13;
}
}
else
{
v8 = PS_WARR13;
}
PlaySFX(v8);
return 1;
}
v9 = v6[55];
if ( !v9 && v6[2] == 11 )
{
StartGoldDrop();
return 1;
}
if ( dropGoldFlag )
{
dropGoldFlag = 0;
dropGoldValue = 0;
}
if ( v9 == 21 && !currlevel && !*(_DWORD *)&spelldata[v6[56]].sTownSpell
|| v9 == 22 && !currlevel && !*(_DWORD *)&spelldata[v6[56]].sTownSpell )
{
return 1;
}
if ( v9 == 24 )
{
v10 = 65;
}
else
{
if ( pnum != myplr )
goto LABEL_39;
v10 = ItemInvSnds[ItemCAnimTbl[v6[48]]];
}
PlaySFX(v10);
LABEL_39:
UseItem(p, v6[55], v6[56]);
if ( v14 )
{
RemoveSpdBarItem(p, v4);
}
else if ( *(int *)((char *)&plr[0].InvList[0]._iMiscId + v5) != IMISC_MAPOFDOOM )
{
RemoveInvItem(p, v4);
}
return 1;
}
return result;
}
// 4B84DC: using guessed type int dropGoldFlag;
// 4B8960: using guessed type int talkflag;
// 52A554: using guessed type int sfxdelay;
// 6AA705: using guessed type char stextflag;
void __cdecl DoTelekinesis()
{
if ( pcursobj != -1 )
NetSendCmdParam1(1u, CMD_OPOBJT, pcursobj);
if ( pcursitem != -1 )
NetSendCmdGItem(1u, CMD_REQUESTAGITEM, myplr, myplr, pcursitem);
if ( pcursmonst != -1 && !M_Talker(pcursmonst) && !monster[pcursmonst].mtalkmsg )
NetSendCmdParam1(1u, CMD_KNOCKBACK, pcursmonst);
SetCursor(CURSOR_HAND);
}
// 4B8CC0: using guessed type char pcursitem;
// 4B8CC1: using guessed type char pcursobj;
int __fastcall CalculateGold(int pnum)
{
int result; // eax
int v2; // ecx
int *v3; // edx
signed int v4; // esi
int v5; // edx
int *v6; // ecx
result = 0;
v2 = pnum;
v3 = &plr[v2].SpdList[0]._ivalue;
v4 = 8;
do
{
if ( *(v3 - 47) == 11 )
{
result += *v3;
drawpanflag = 255;
}
v3 += 92;
--v4;
}
while ( v4 );
v5 = plr[v2]._pNumInv;
if ( v5 > 0 )
{
v6 = &plr[v2].InvList[0]._ivalue;
do
{
if ( *(v6 - 47) == 11 )
result += *v6;
v6 += 92;
--v5;
}
while ( v5 );
}
return result;
}
// 52571C: using guessed type int drawpanflag;
int __cdecl DropItemBeforeTrig()
{
if ( !TryInvPut() )
return 0;
NetSendCmdPItem(1u, CMD_PUTITEM, cursmx, cursmy);
SetCursor(CURSOR_HAND);
return 1;
}
|
#include <boost/metaparse/one_of_c.hpp>
|
// Copyright (c) 2011-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2017 The nativecoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "bitcoinunits.h"
#include "chainparams.h"
#include "primitives/transaction.h"
#include <QSettings>
#include <QStringList>
BitcoinUnits::BitcoinUnits(QObject* parent) : QAbstractListModel(parent),
unitlist(availableUnits())
{
}
QList<BitcoinUnits::Unit> BitcoinUnits::availableUnits()
{
QList<BitcoinUnits::Unit> unitlist;
unitlist.append(N8V);
unitlist.append(mN8V);
unitlist.append(uN8V);
return unitlist;
}
bool BitcoinUnits::valid(int unit)
{
switch (unit) {
case N8V:
case mN8V:
case uN8V:
return true;
default:
return false;
}
}
QString BitcoinUnits::id(int unit)
{
switch (unit) {
case N8V:
return QString("NativeCoin");
case mN8V:
return QString("mNativeCoin");
case uN8V:
return QString::fromUtf8("uNativeCoin");
default:
return QString("???");
}
}
QString BitcoinUnits::name(int unit)
{
if (Params().NetworkID() == CBaseChainParams::MAIN) {
switch (unit) {
case N8V:
return QString("N8V");
case mN8V:
return QString("mN8V");
case uN8V:
return QString::fromUtf8("μN8V");
default:
return QString("???");
}
} else {
switch (unit) {
case N8V:
return QString("tN8V");
case mN8V:
return QString("mtN8V");
case uN8V:
return QString::fromUtf8("μtN8V");
default:
return QString("???");
}
}
}
QString BitcoinUnits::description(int unit)
{
if (Params().NetworkID() == CBaseChainParams::MAIN) {
switch (unit) {
case N8V:
return QString("N8V");
case mN8V:
return QString("Milli-N8V (1 / 1" THIN_SP_UTF8 "000)");
case uN8V:
return QString("Micro-N8V (1 / 1" THIN_SP_UTF8 "000" THIN_SP_UTF8 "000)");
default:
return QString("???");
}
} else {
switch (unit) {
case N8V:
return QString("TestN8Vs");
case mN8V:
return QString("Milli-TestN8V (1 / 1" THIN_SP_UTF8 "000)");
case uN8V:
return QString("Micro-TestN8V (1 / 1" THIN_SP_UTF8 "000" THIN_SP_UTF8 "000)");
default:
return QString("???");
}
}
}
qint64 BitcoinUnits::factor(int unit)
{
switch (unit) {
case N8V:
return 100000000;
case mN8V:
return 100000;
case uN8V:
return 100;
default:
return 100000000;
}
}
int BitcoinUnits::decimals(int unit)
{
switch (unit) {
case N8V:
return 8;
case mN8V:
return 5;
case uN8V:
return 2;
default:
return 0;
}
}
QString BitcoinUnits::format(int unit, const CAmount& nIn, bool fPlus, SeparatorStyle separators)
{
// Note: not using straight sprintf here because we do NOT want
// localized number formatting.
if (!valid(unit))
return QString(); // Refuse to format invalid unit
qint64 n = (qint64)nIn;
qint64 coin = factor(unit);
int num_decimals = decimals(unit);
qint64 n_abs = (n > 0 ? n : -n);
qint64 quotient = n_abs / coin;
qint64 remainder = n_abs % coin;
QString quotient_str = QString::number(quotient);
QString remainder_str = QString::number(remainder).rightJustified(num_decimals, '0');
// Use SI-style thin space separators as these are locale independent and can't be
// confused with the decimal marker.
QChar thin_sp(THIN_SP_CP);
int q_size = quotient_str.size();
if (separators == separatorAlways || (separators == separatorStandard && q_size > 4))
for (int i = 3; i < q_size; i += 3)
quotient_str.insert(q_size - i, thin_sp);
//-------------------------------------------------------------------------------//
if (n < 0)
quotient_str.insert(0, '-');
else if (fPlus && n > 0)
quotient_str.insert(0, '+');
if (num_decimals <= 0)
return quotient_str;
return quotient_str + QString(".") + remainder_str;
}
// TODO: Review all remaining calls to BitcoinUnits::formatWithUnit to
// TODO: determine whether the output is used in a plain text context
// TODO: or an HTML context (and replace with
// TODO: BtcoinUnits::formatHtmlWithUnit in the latter case). Hopefully
// TODO: there aren't instances where the result could be used in
// TODO: either context.
// NOTE: Using formatWithUnit in an HTML context risks wrapping
// quantities at the thousands separator. More subtly, it also results
// in a standard space rather than a thin space, due to a bug in Qt's
// XML whitespace canonicalisation
//
// Please take care to use formatHtmlWithUnit instead, when
// appropriate.
QString BitcoinUnits::formatWithUnit(int unit, const CAmount& amount, bool plussign, SeparatorStyle separators)
{
return format(unit, amount, plussign, separators) + QString(" ") + name(unit);
}
QString BitcoinUnits::formatHtmlWithUnit(int unit, const CAmount& amount, bool plussign, SeparatorStyle separators)
{
QString str(formatWithUnit(unit, amount, plussign, separators));
str.replace(QChar(THIN_SP_CP), QString(THIN_SP_HTML));
return QString("<span style='white-space: nowrap;'>%1</span>").arg(str);
}
QString BitcoinUnits::floorWithUnit(int unit, const CAmount& amount, bool plussign, SeparatorStyle separators)
{
QSettings settings;
int digits = settings.value("digits").toInt();
QString result = format(unit, amount, plussign, separators);
if (decimals(unit) > digits) result.chop(decimals(unit) - digits);
return result + QString(" ") + name(unit);
}
QString BitcoinUnits::floorHtmlWithUnit(int unit, const CAmount& amount, bool plussign, SeparatorStyle separators)
{
QString str(floorWithUnit(unit, amount, plussign, separators));
str.replace(QChar(THIN_SP_CP), QString(THIN_SP_HTML));
return QString("<span style='white-space: nowrap;'>%1</span>").arg(str);
}
bool BitcoinUnits::parse(int unit, const QString& value, CAmount* val_out)
{
if (!valid(unit) || value.isEmpty())
return false; // Refuse to parse invalid unit or empty string
int num_decimals = decimals(unit);
// Ignore spaces and thin spaces when parsing
QStringList parts = removeSpaces(value).split(".");
if (parts.size() > 2) {
return false; // More than one dot
}
QString whole = parts[0];
QString decimals;
if (parts.size() > 1) {
decimals = parts[1];
}
if (decimals.size() > num_decimals) {
return false; // Exceeds max precision
}
bool ok = false;
QString str = whole + decimals.leftJustified(num_decimals, '0');
if (str.size() > 18) {
return false; // Longer numbers will exceed 63 bits
}
CAmount retvalue(str.toLongLong(&ok));
if (val_out) {
*val_out = retvalue;
}
return ok;
}
QString BitcoinUnits::getAmountColumnTitle(int unit)
{
QString amountTitle = QObject::tr("Amount");
if (BitcoinUnits::valid(unit)) {
amountTitle += " (" + BitcoinUnits::name(unit) + ")";
}
return amountTitle;
}
int BitcoinUnits::rowCount(const QModelIndex& parent) const
{
Q_UNUSED(parent);
return unitlist.size();
}
QVariant BitcoinUnits::data(const QModelIndex& index, int role) const
{
int row = index.row();
if (row >= 0 && row < unitlist.size()) {
Unit unit = unitlist.at(row);
switch (role) {
case Qt::EditRole:
case Qt::DisplayRole:
return QVariant(name(unit));
case Qt::ToolTipRole:
return QVariant(description(unit));
case UnitRole:
return QVariant(static_cast<int>(unit));
}
}
return QVariant();
}
CAmount BitcoinUnits::maxMoney()
{
return Params().MaxMoneyOut();
}
|
/*
* This file is part of Matrix.
*
* See the COPYRIGHT file at the top-level directory of this distribution
* for details of code ownership.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include <doctest/doctest.h>
#include <Matrix/matrix.h>
TEST_SUITE_BEGIN("test_associative_multiplication");
TEST_CASE("small_ones_matrix")
{
using namespace linalg;
Matrix<int> A{5, 5, 1};
Matrix<int> B{5, 5, 1};
Matrix<int> C{5, 5, 1};
Matrix<int> D{5, 5, 25};
CHECK(isSame(D, A * B * C) == 1);
}
TEST_CASE("small_matrix")
{
using namespace linalg;
Matrix<int> A{{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}};
Matrix<int> B{{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}};
Matrix<int> C{{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}};
Matrix<int> D{{{468, 576, 684}, {1062, 1305, 1548}, {1656, 2034, 2412}}};
CHECK(isSame(D, A * B * C) == 1);
}
TEST_CASE("medium_matrix")
{
using namespace linalg;
Matrix<int> A{100, 100, 6};
Matrix<int> B{100, 100, 2};
Matrix<int> C{100, 100, 8};
Matrix<int> D{100, 100, 960000};
CHECK(isSame(D, A * B * C) == 1);
}
TEST_CASE("huge_matrix")
{
using namespace linalg;
Matrix<int> A{1000, 1000, 9};
Matrix<int> B{1000, 1000, 7};
Matrix<int> C{1000, 1000, 1};
Matrix<int> D{1000, 1000, 63000000};
CHECK(isSame(D, A * B * C) == 1);
}
TEST_SUITE_END();
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2018 The Bitcoin Core developers
// Copyright (c) 2017-2020 The Qtum Core developers
// Copyright (c) 2020 The BCS Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <util/system.h>
#include <chainparamsbase.h>
#include <random.h>
#include <serialize.h>
#include <util/strencodings.h>
#include <regex>
#include <iomanip>
#include <stdarg.h>
#if (defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__DragonFly__))
#include <pthread.h>
#include <pthread_np.h>
#endif
#ifndef WIN32
// for posix_fallocate
#ifdef __linux__
#ifdef _POSIX_C_SOURCE
#undef _POSIX_C_SOURCE
#endif
#define _POSIX_C_SOURCE 200112L
#endif // __linux__
#include <algorithm>
#include <fcntl.h>
#include <sched.h>
#include <sys/resource.h>
#include <sys/stat.h>
#else
#ifdef _MSC_VER
#pragma warning(disable:4786)
#pragma warning(disable:4804)
#pragma warning(disable:4805)
#pragma warning(disable:4717)
#endif
#ifdef _WIN32_IE
#undef _WIN32_IE
#endif
#define _WIN32_IE 0x0501
#define WIN32_LEAN_AND_MEAN 1
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <codecvt>
#include <io.h> /* for _commit */
#include <shellapi.h>
#include <shlobj.h>
#endif
#ifdef HAVE_SYS_PRCTL_H
#include <sys/prctl.h>
#endif
#ifdef HAVE_MALLOPT_ARENA_MAX
#include <malloc.h>
#endif
#include <thread>
// Application startup time (used for uptime calculation)
const int64_t nStartupTime = GetTime();
const char * const BITCOIN_CONF_FILENAME = "bcs.conf";
ArgsManager gArgs;
/** A map that contains all the currently held directory locks. After
* successful locking, these will be held here until the global destructor
* cleans them up and thus automatically unlocks them, or ReleaseDirectoryLocks
* is called.
*/
static std::map<std::string, std::unique_ptr<fsbridge::FileLock>> dir_locks;
/** Mutex to protect dir_locks. */
static std::mutex cs_dir_locks;
bool LockDirectory(const fs::path& directory, const std::string lockfile_name, bool probe_only, bool try_lock)
{
std::lock_guard<std::mutex> ulock(cs_dir_locks);
fs::path pathLockFile = directory / lockfile_name;
// If a lock for this directory already exists in the map, don't try to re-lock it
if (dir_locks.count(pathLockFile.string())) {
return true;
}
// Create empty lock file if it doesn't exist.
FILE* file = fsbridge::fopen(pathLockFile, "a");
if (file) fclose(file);
auto lock = MakeUnique<fsbridge::FileLock>(pathLockFile);
if (try_lock && !lock->TryLock()) {
return error("Error while attempting to lock directory %s: %s", directory.string(), lock->GetReason());
}
if (!probe_only) {
// Lock successful and we're not just probing, put it into the map
dir_locks.emplace(pathLockFile.string(), std::move(lock));
}
return true;
}
void UnlockDirectory(const fs::path& directory, const std::string& lockfile_name)
{
std::lock_guard<std::mutex> lock(cs_dir_locks);
dir_locks.erase((directory / lockfile_name).string());
}
void ReleaseDirectoryLocks()
{
std::lock_guard<std::mutex> ulock(cs_dir_locks);
dir_locks.clear();
}
bool DirIsWritable(const fs::path& directory)
{
fs::path tmpFile = directory / fs::unique_path();
FILE* file = fsbridge::fopen(tmpFile, "a");
if (!file) return false;
fclose(file);
remove(tmpFile);
return true;
}
/**
* Interpret a string argument as a boolean.
*
* The definition of atoi() requires that non-numeric string values like "foo",
* return 0. This means that if a user unintentionally supplies a non-integer
* argument here, the return value is always false. This means that -foo=false
* does what the user probably expects, but -foo=true is well defined but does
* not do what they probably expected.
*
* The return value of atoi() is undefined when given input not representable as
* an int. On most systems this means string value between "-2147483648" and
* "2147483647" are well defined (this method will return true). Setting
* -txindex=2147483648 on most systems, however, is probably undefined.
*
* For a more extensive discussion of this topic (and a wide range of opinions
* on the Right Way to change this code), see PR12713.
*/
static bool InterpretBool(const std::string& strValue)
{
if (strValue.empty())
return true;
return (atoi(strValue) != 0);
}
/** Internal helper functions for ArgsManager */
class ArgsManagerHelper {
public:
typedef std::map<std::string, std::vector<std::string>> MapArgs;
/** Determine whether to use config settings in the default section,
* See also comments around ArgsManager::ArgsManager() below. */
static inline bool UseDefaultSection(const ArgsManager& am, const std::string& arg) EXCLUSIVE_LOCKS_REQUIRED(am.cs_args)
{
return (am.m_network == CBaseChainParams::MAIN || am.m_network_only_args.count(arg) == 0);
}
/** Convert regular argument into the network-specific setting */
static inline std::string NetworkArg(const ArgsManager& am, const std::string& arg)
{
assert(arg.length() > 1 && arg[0] == '-');
return "-" + am.m_network + "." + arg.substr(1);
}
/** Find arguments in a map and add them to a vector */
static inline void AddArgs(std::vector<std::string>& res, const MapArgs& map_args, const std::string& arg)
{
auto it = map_args.find(arg);
if (it != map_args.end()) {
res.insert(res.end(), it->second.begin(), it->second.end());
}
}
/** Return true/false if an argument is set in a map, and also
* return the first (or last) of the possibly multiple values it has
*/
static inline std::pair<bool,std::string> GetArgHelper(const MapArgs& map_args, const std::string& arg, bool getLast = false)
{
auto it = map_args.find(arg);
if (it == map_args.end() || it->second.empty()) {
return std::make_pair(false, std::string());
}
if (getLast) {
return std::make_pair(true, it->second.back());
} else {
return std::make_pair(true, it->second.front());
}
}
/* Get the string value of an argument, returning a pair of a boolean
* indicating the argument was found, and the value for the argument
* if it was found (or the empty string if not found).
*/
static inline std::pair<bool,std::string> GetArg(const ArgsManager &am, const std::string& arg)
{
LOCK(am.cs_args);
std::pair<bool,std::string> found_result(false, std::string());
// We pass "true" to GetArgHelper in order to return the last
// argument value seen from the command line (so "bitcoind -foo=bar
// -foo=baz" gives GetArg(am,"foo")=={true,"baz"}
found_result = GetArgHelper(am.m_override_args, arg, true);
if (found_result.first) {
return found_result;
}
// But in contrast we return the first argument seen in a config file,
// so "foo=bar \n foo=baz" in the config file gives
// GetArg(am,"foo")={true,"bar"}
if (!am.m_network.empty()) {
found_result = GetArgHelper(am.m_config_args, NetworkArg(am, arg));
if (found_result.first) {
return found_result;
}
}
if (UseDefaultSection(am, arg)) {
found_result = GetArgHelper(am.m_config_args, arg);
if (found_result.first) {
return found_result;
}
}
return found_result;
}
/* Special test for -testnet and -regtest args, because we
* don't want to be confused by craziness like "[regtest] testnet=1"
*/
static inline bool GetNetBoolArg(const ArgsManager &am, const std::string& net_arg) EXCLUSIVE_LOCKS_REQUIRED(am.cs_args)
{
std::pair<bool,std::string> found_result(false,std::string());
found_result = GetArgHelper(am.m_override_args, net_arg, true);
if (!found_result.first) {
found_result = GetArgHelper(am.m_config_args, net_arg, true);
if (!found_result.first) {
return false; // not set
}
}
return InterpretBool(found_result.second); // is set, so evaluate
}
};
/**
* Interpret -nofoo as if the user supplied -foo=0.
*
* This method also tracks when the -no form was supplied, and if so,
* checks whether there was a double-negative (-nofoo=0 -> -foo=1).
*
* If there was not a double negative, it removes the "no" from the key,
* and returns true, indicating the caller should clear the args vector
* to indicate a negated option.
*
* If there was a double negative, it removes "no" from the key, sets the
* value to "1" and returns false.
*
* If there was no "no", it leaves key and value untouched and returns
* false.
*
* Where an option was negated can be later checked using the
* IsArgNegated() method. One use case for this is to have a way to disable
* options that are not normally boolean (e.g. using -nodebuglogfile to request
* that debug log output is not sent to any file at all).
*/
static bool InterpretNegatedOption(std::string& key, std::string& val)
{
assert(key[0] == '-');
size_t option_index = key.find('.');
if (option_index == std::string::npos) {
option_index = 1;
} else {
++option_index;
}
if (key.substr(option_index, 2) == "no") {
bool bool_val = InterpretBool(val);
key.erase(option_index, 2);
if (!bool_val ) {
// Double negatives like -nofoo=0 are supported (but discouraged)
LogPrintf("Warning: parsed potentially confusing double-negative %s=%s\n", key, val);
val = "1";
} else {
return true;
}
}
return false;
}
ArgsManager::ArgsManager() :
/* These options would cause cross-contamination if values for
* mainnet were used while running on regtest/testnet (or vice-versa).
* Setting them as section_only_args ensures that sharing a config file
* between mainnet and regtest/testnet won't cause problems due to these
* parameters by accident. */
m_network_only_args{
"-addnode", "-connect",
"-port", "-bind",
"-rpcport", "-rpcbind",
"-wallet",
}
{
// nothing to do
}
const std::set<std::string> ArgsManager::GetUnsuitableSectionOnlyArgs() const
{
std::set<std::string> unsuitables;
LOCK(cs_args);
// if there's no section selected, don't worry
if (m_network.empty()) return std::set<std::string> {};
// if it's okay to use the default section for this network, don't worry
if (m_network == CBaseChainParams::MAIN) return std::set<std::string> {};
for (const auto& arg : m_network_only_args) {
std::pair<bool, std::string> found_result;
// if this option is overridden it's fine
found_result = ArgsManagerHelper::GetArgHelper(m_override_args, arg);
if (found_result.first) continue;
// if there's a network-specific value for this option, it's fine
found_result = ArgsManagerHelper::GetArgHelper(m_config_args, ArgsManagerHelper::NetworkArg(*this, arg));
if (found_result.first) continue;
// if there isn't a default value for this option, it's fine
found_result = ArgsManagerHelper::GetArgHelper(m_config_args, arg);
if (!found_result.first) continue;
// otherwise, issue a warning
unsuitables.insert(arg);
}
return unsuitables;
}
const std::set<std::string> ArgsManager::GetUnrecognizedSections() const
{
// Section names to be recognized in the config file.
static const std::set<std::string> available_sections{
CBaseChainParams::REGTEST,
CBaseChainParams::TESTNET,
CBaseChainParams::MAIN
};
std::set<std::string> diff;
LOCK(cs_args);
std::set_difference(
m_config_sections.begin(), m_config_sections.end(),
available_sections.begin(), available_sections.end(),
std::inserter(diff, diff.end()));
return diff;
}
void ArgsManager::SelectConfigNetwork(const std::string& network)
{
LOCK(cs_args);
m_network = network;
}
bool ArgsManager::ParseParameters(int argc, const char* const argv[], std::string& error)
{
LOCK(cs_args);
m_override_args.clear();
for (int i = 1; i < argc; i++) {
std::string key(argv[i]);
std::string val;
size_t is_index = key.find('=');
if (is_index != std::string::npos) {
val = key.substr(is_index + 1);
key.erase(is_index);
}
#ifdef WIN32
std::transform(key.begin(), key.end(), key.begin(), ToLower);
if (key[0] == '/')
key[0] = '-';
#endif
if (key[0] != '-')
break;
// Transform --foo to -foo
if (key.length() > 1 && key[1] == '-')
key.erase(0, 1);
// Check for -nofoo
if (InterpretNegatedOption(key, val)) {
m_override_args[key].clear();
} else {
m_override_args[key].push_back(val);
}
// Check that the arg is known
if (!(IsSwitchChar(key[0]) && key.size() == 1)) {
if (!IsArgKnown(key)) {
error = strprintf("Invalid parameter %s", key.c_str());
return false;
}
}
}
// we do not allow -includeconf from command line, so we clear it here
auto it = m_override_args.find("-includeconf");
if (it != m_override_args.end()) {
if (it->second.size() > 0) {
for (const auto& ic : it->second) {
error += "-includeconf cannot be used from commandline; -includeconf=" + ic + "\n";
}
return false;
}
}
return true;
}
bool ArgsManager::IsArgKnown(const std::string& key) const
{
size_t option_index = key.find('.');
std::string arg_no_net;
if (option_index == std::string::npos) {
arg_no_net = key;
} else {
arg_no_net = std::string("-") + key.substr(option_index + 1, std::string::npos);
}
LOCK(cs_args);
for (const auto& arg_map : m_available_args) {
if (arg_map.second.count(arg_no_net)) return true;
}
return false;
}
std::vector<std::string> ArgsManager::GetArgs(const std::string& strArg) const
{
std::vector<std::string> result = {};
if (IsArgNegated(strArg)) return result; // special case
LOCK(cs_args);
ArgsManagerHelper::AddArgs(result, m_override_args, strArg);
if (!m_network.empty()) {
ArgsManagerHelper::AddArgs(result, m_config_args, ArgsManagerHelper::NetworkArg(*this, strArg));
}
if (ArgsManagerHelper::UseDefaultSection(*this, strArg)) {
ArgsManagerHelper::AddArgs(result, m_config_args, strArg);
}
return result;
}
bool ArgsManager::IsArgSet(const std::string& strArg) const
{
if (IsArgNegated(strArg)) return true; // special case
return ArgsManagerHelper::GetArg(*this, strArg).first;
}
bool ArgsManager::IsArgNegated(const std::string& strArg) const
{
LOCK(cs_args);
const auto& ov = m_override_args.find(strArg);
if (ov != m_override_args.end()) return ov->second.empty();
if (!m_network.empty()) {
const auto& cfs = m_config_args.find(ArgsManagerHelper::NetworkArg(*this, strArg));
if (cfs != m_config_args.end()) return cfs->second.empty();
}
const auto& cf = m_config_args.find(strArg);
if (cf != m_config_args.end()) return cf->second.empty();
return false;
}
std::string ArgsManager::GetArg(const std::string& strArg, const std::string& strDefault) const
{
if (IsArgNegated(strArg)) return "0";
std::pair<bool,std::string> found_res = ArgsManagerHelper::GetArg(*this, strArg);
if (found_res.first) return found_res.second;
return strDefault;
}
int64_t ArgsManager::GetArg(const std::string& strArg, int64_t nDefault) const
{
if (IsArgNegated(strArg)) return 0;
std::pair<bool,std::string> found_res = ArgsManagerHelper::GetArg(*this, strArg);
if (found_res.first) return atoi64(found_res.second);
return nDefault;
}
bool ArgsManager::GetBoolArg(const std::string& strArg, bool fDefault) const
{
if (IsArgNegated(strArg)) return false;
std::pair<bool,std::string> found_res = ArgsManagerHelper::GetArg(*this, strArg);
if (found_res.first) return InterpretBool(found_res.second);
return fDefault;
}
bool ArgsManager::SoftSetArg(const std::string& strArg, const std::string& strValue)
{
LOCK(cs_args);
if (IsArgSet(strArg)) return false;
ForceSetArg(strArg, strValue);
return true;
}
bool ArgsManager::SoftSetBoolArg(const std::string& strArg, bool fValue)
{
if (fValue)
return SoftSetArg(strArg, std::string("1"));
else
return SoftSetArg(strArg, std::string("0"));
}
void ArgsManager::ForceSetArg(const std::string& strArg, const std::string& strValue)
{
LOCK(cs_args);
m_override_args[strArg] = {strValue};
}
void ArgsManager::AddArg(const std::string& name, const std::string& help, const bool debug_only, const OptionsCategory& cat)
{
// Split arg name from its help param
size_t eq_index = name.find('=');
if (eq_index == std::string::npos) {
eq_index = name.size();
}
LOCK(cs_args);
std::map<std::string, Arg>& arg_map = m_available_args[cat];
auto ret = arg_map.emplace(name.substr(0, eq_index), Arg(name.substr(eq_index, name.size() - eq_index), help, debug_only));
assert(ret.second); // Make sure an insertion actually happened
}
void ArgsManager::AddHiddenArgs(const std::vector<std::string>& names)
{
for (const std::string& name : names) {
AddArg(name, "", false, OptionsCategory::HIDDEN);
}
}
std::string ArgsManager::GetHelpMessage() const
{
const bool show_debug = gArgs.GetBoolArg("-help-debug", false);
std::string usage = "";
LOCK(cs_args);
for (const auto& arg_map : m_available_args) {
switch(arg_map.first) {
case OptionsCategory::OPTIONS:
usage += HelpMessageGroup("Options:");
break;
case OptionsCategory::CONNECTION:
usage += HelpMessageGroup("Connection options:");
break;
case OptionsCategory::ZMQ:
usage += HelpMessageGroup("ZeroMQ notification options:");
break;
case OptionsCategory::DEBUG_TEST:
usage += HelpMessageGroup("Debugging/Testing options:");
break;
case OptionsCategory::NODE_RELAY:
usage += HelpMessageGroup("Node relay options:");
break;
case OptionsCategory::BLOCK_CREATION:
usage += HelpMessageGroup("Block creation options:");
break;
case OptionsCategory::RPC:
usage += HelpMessageGroup("RPC server options:");
break;
case OptionsCategory::WALLET:
usage += HelpMessageGroup("Wallet options:");
break;
case OptionsCategory::WALLET_DEBUG_TEST:
if (show_debug) usage += HelpMessageGroup("Wallet debugging/testing options:");
break;
case OptionsCategory::CHAINPARAMS:
usage += HelpMessageGroup("Chain selection options:");
break;
case OptionsCategory::GUI:
usage += HelpMessageGroup("UI Options:");
break;
case OptionsCategory::COMMANDS:
usage += HelpMessageGroup("Commands:");
break;
case OptionsCategory::REGISTER_COMMANDS:
usage += HelpMessageGroup("Register Commands:");
break;
default:
break;
}
// When we get to the hidden options, stop
if (arg_map.first == OptionsCategory::HIDDEN) break;
for (const auto& arg : arg_map.second) {
if (show_debug || !arg.second.m_debug_only) {
std::string name;
if (arg.second.m_help_param.empty()) {
name = arg.first;
} else {
name = arg.first + arg.second.m_help_param;
}
usage += HelpMessageOpt(name, arg.second.m_help_text);
}
}
}
return usage;
}
bool HelpRequested(const ArgsManager& args)
{
return args.IsArgSet("-?") || args.IsArgSet("-h") || args.IsArgSet("-help") || args.IsArgSet("-help-debug");
}
void SetupHelpOptions(ArgsManager& args)
{
args.AddArg("-?", "Print this help message and exit", false, OptionsCategory::OPTIONS);
args.AddHiddenArgs({"-h", "-help"});
}
static const int screenWidth = 79;
static const int optIndent = 2;
static const int msgIndent = 7;
std::string HelpMessageGroup(const std::string &message) {
return std::string(message) + std::string("\n\n");
}
std::string HelpMessageOpt(const std::string &option, const std::string &message) {
return std::string(optIndent,' ') + std::string(option) +
std::string("\n") + std::string(msgIndent,' ') +
FormatParagraph(message, screenWidth - msgIndent, msgIndent) +
std::string("\n\n");
}
static std::string FormatException(const std::exception* pex, const char* pszThread)
{
#ifdef WIN32
char pszModule[MAX_PATH] = "";
GetModuleFileNameA(nullptr, pszModule, sizeof(pszModule));
#else
const char* pszModule = "bitcoin";
#endif
if (pex)
return strprintf(
"EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
else
return strprintf(
"UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread);
}
void PrintExceptionContinue(const std::exception* pex, const char* pszThread)
{
std::string message = FormatException(pex, pszThread);
LogPrintf("\n\n************************\n%s\n", message);
tfm::format(std::cerr, "\n\n************************\n%s\n", message.c_str());
}
fs::path GetDefaultDataDir()
{
// Windows < Vista: C:\Documents and Settings\Username\Application Data\BCS
// Windows >= Vista: C:\Users\Username\AppData\Roaming\BCS
// Mac: ~/Library/Application Support/BCS
// Unix: ~/.bcs
#ifdef WIN32
// Windows
return GetSpecialFolderPath(CSIDL_APPDATA) / "BCS";
#else
fs::path pathRet;
char* pszHome = getenv("HOME");
if (pszHome == nullptr || strlen(pszHome) == 0)
pathRet = fs::path("/");
else
pathRet = fs::path(pszHome);
#ifdef MAC_OSX
// Mac
return pathRet / "Library/Application Support/BCS";
#else
// Unix
return pathRet / ".bcs";
#endif
#endif
}
static fs::path g_blocks_path_cache_net_specific;
static fs::path pathCached;
static fs::path pathCachedNetSpecific;
static CCriticalSection csPathCached;
const fs::path &GetBlocksDir()
{
LOCK(csPathCached);
fs::path &path = g_blocks_path_cache_net_specific;
// This can be called during exceptions by LogPrintf(), so we cache the
// value so we don't have to do memory allocations after that.
if (!path.empty())
return path;
if (gArgs.IsArgSet("-blocksdir")) {
path = fs::system_complete(gArgs.GetArg("-blocksdir", ""));
if (!fs::is_directory(path)) {
path = "";
return path;
}
} else {
path = GetDataDir(false);
}
path /= BaseParams().DataDir();
path /= "blocks";
fs::create_directories(path);
return path;
}
const fs::path &GetDataDir(bool fNetSpecific)
{
LOCK(csPathCached);
fs::path &path = fNetSpecific ? pathCachedNetSpecific : pathCached;
// This can be called during exceptions by LogPrintf(), so we cache the
// value so we don't have to do memory allocations after that.
if (!path.empty())
return path;
if (gArgs.IsArgSet("-datadir")) {
path = fs::system_complete(gArgs.GetArg("-datadir", ""));
if (!fs::is_directory(path)) {
path = "";
return path;
}
} else {
path = GetDefaultDataDir();
}
if (fNetSpecific)
path /= BaseParams().DataDir();
if (fs::create_directories(path)) {
// This is the first run, create wallets subdirectory too
fs::create_directories(path / "wallets");
}
return path;
}
void ClearDatadirCache()
{
LOCK(csPathCached);
pathCached = fs::path();
pathCachedNetSpecific = fs::path();
g_blocks_path_cache_net_specific = fs::path();
}
fs::path GetConfigFile(const std::string& confPath)
{
return AbsPathForConfigVal(fs::path(confPath), false);
}
static std::string TrimString(const std::string& str, const std::string& pattern)
{
std::string::size_type front = str.find_first_not_of(pattern);
if (front == std::string::npos) {
return std::string();
}
std::string::size_type end = str.find_last_not_of(pattern);
return str.substr(front, end - front + 1);
}
static bool GetConfigOptions(std::istream& stream, std::string& error, std::vector<std::pair<std::string, std::string>>& options, std::set<std::string>& sections)
{
std::string str, prefix;
std::string::size_type pos;
int linenr = 1;
while (std::getline(stream, str)) {
bool used_hash = false;
if ((pos = str.find('#')) != std::string::npos) {
str = str.substr(0, pos);
used_hash = true;
}
const static std::string pattern = " \t\r\n";
str = TrimString(str, pattern);
if (!str.empty()) {
if (*str.begin() == '[' && *str.rbegin() == ']') {
const std::string section = str.substr(1, str.size() - 2);
sections.insert(section);
prefix = section + '.';
} else if (*str.begin() == '-') {
error = strprintf("parse error on line %i: %s, options in configuration file must be specified without leading -", linenr, str);
return false;
} else if ((pos = str.find('=')) != std::string::npos) {
std::string name = prefix + TrimString(str.substr(0, pos), pattern);
std::string value = TrimString(str.substr(pos + 1), pattern);
if (used_hash && name.find("rpcpassword") != std::string::npos) {
error = strprintf("parse error on line %i, using # in rpcpassword can be ambiguous and should be avoided", linenr);
return false;
}
options.emplace_back(name, value);
if ((pos = name.rfind('.')) != std::string::npos) {
sections.insert(name.substr(0, pos));
}
} else {
error = strprintf("parse error on line %i: %s", linenr, str);
if (str.size() >= 2 && str.substr(0, 2) == "no") {
error += strprintf(", if you intended to specify a negated option, use %s=1 instead", str);
}
return false;
}
}
++linenr;
}
return true;
}
bool ArgsManager::ReadConfigStream(std::istream& stream, std::string& error, bool ignore_invalid_keys)
{
LOCK(cs_args);
std::vector<std::pair<std::string, std::string>> options;
m_config_sections.clear();
if (!GetConfigOptions(stream, error, options, m_config_sections)) {
return false;
}
for (const std::pair<std::string, std::string>& option : options) {
std::string strKey = std::string("-") + option.first;
std::string strValue = option.second;
if (InterpretNegatedOption(strKey, strValue)) {
m_config_args[strKey].clear();
} else {
m_config_args[strKey].push_back(strValue);
}
// Check that the arg is known
if (!IsArgKnown(strKey)) {
if (!ignore_invalid_keys) {
error = strprintf("Invalid configuration value %s", option.first.c_str());
return false;
} else {
LogPrintf("Ignoring unknown configuration value %s\n", option.first);
}
}
}
return true;
}
bool ArgsManager::ReadConfigFiles(std::string& error, bool ignore_invalid_keys)
{
{
LOCK(cs_args);
m_config_args.clear();
}
const std::string confPath = GetArg("-conf", BITCOIN_CONF_FILENAME);
fsbridge::ifstream stream(GetConfigFile(confPath));
// ok to not have a config file
if (stream.good()) {
if (!ReadConfigStream(stream, error, ignore_invalid_keys)) {
return false;
}
// if there is an -includeconf in the override args, but it is empty, that means the user
// passed '-noincludeconf' on the command line, in which case we should not include anything
bool emptyIncludeConf;
{
LOCK(cs_args);
emptyIncludeConf = m_override_args.count("-includeconf") == 0;
}
if (emptyIncludeConf) {
std::string chain_id = GetChainName();
std::vector<std::string> includeconf(GetArgs("-includeconf"));
{
// We haven't set m_network yet (that happens in SelectParams()), so manually check
// for network.includeconf args.
std::vector<std::string> includeconf_net(GetArgs(std::string("-") + chain_id + ".includeconf"));
includeconf.insert(includeconf.end(), includeconf_net.begin(), includeconf_net.end());
}
// Remove -includeconf from configuration, so we can warn about recursion
// later
{
LOCK(cs_args);
m_config_args.erase("-includeconf");
m_config_args.erase(std::string("-") + chain_id + ".includeconf");
}
for (const std::string& to_include : includeconf) {
fsbridge::ifstream include_config(GetConfigFile(to_include));
if (include_config.good()) {
if (!ReadConfigStream(include_config, error, ignore_invalid_keys)) {
return false;
}
LogPrintf("Included configuration file %s\n", to_include.c_str());
} else {
error = "Failed to include configuration file " + to_include;
return false;
}
}
// Warn about recursive -includeconf
includeconf = GetArgs("-includeconf");
{
std::vector<std::string> includeconf_net(GetArgs(std::string("-") + chain_id + ".includeconf"));
includeconf.insert(includeconf.end(), includeconf_net.begin(), includeconf_net.end());
std::string chain_id_final = GetChainName();
if (chain_id_final != chain_id) {
// Also warn about recursive includeconf for the chain that was specified in one of the includeconfs
includeconf_net = GetArgs(std::string("-") + chain_id_final + ".includeconf");
includeconf.insert(includeconf.end(), includeconf_net.begin(), includeconf_net.end());
}
}
for (const std::string& to_include : includeconf) {
tfm::format(std::cerr, "warning: -includeconf cannot be used from included files; ignoring -includeconf=%s\n", to_include.c_str());
}
}
}
// If datadir is changed in .conf file:
ClearDatadirCache();
if (!fs::is_directory(GetDataDir(false))) {
error = strprintf("specified data directory \"%s\" does not exist.", gArgs.GetArg("-datadir", "").c_str());
return false;
}
return true;
}
std::string ArgsManager::GetChainName() const
{
LOCK(cs_args);
bool fRegTest = ArgsManagerHelper::GetNetBoolArg(*this, "-regtest");
bool fTestNet = ArgsManagerHelper::GetNetBoolArg(*this, "-testnet");
if (fTestNet && fRegTest)
throw std::runtime_error("Invalid combination of -regtest and -testnet.");
if (fRegTest)
return CBaseChainParams::REGTEST;
if (fTestNet)
return CBaseChainParams::TESTNET;
return CBaseChainParams::MAIN;
}
bool RenameOver(fs::path src, fs::path dest)
{
#ifdef WIN32
return MoveFileExW(src.wstring().c_str(), dest.wstring().c_str(),
MOVEFILE_REPLACE_EXISTING) != 0;
#else
int rc = std::rename(src.string().c_str(), dest.string().c_str());
return (rc == 0);
#endif /* WIN32 */
}
/**
* Ignores exceptions thrown by Boost's create_directories if the requested directory exists.
* Specifically handles case where path p exists, but it wasn't possible for the user to
* write to the parent directory.
*/
bool TryCreateDirectories(const fs::path& p)
{
try
{
return fs::create_directories(p);
} catch (const fs::filesystem_error&) {
if (!fs::exists(p) || !fs::is_directory(p))
throw;
}
// create_directories didn't create the directory, it had to have existed already
return false;
}
bool FileCommit(FILE *file)
{
if (fflush(file) != 0) { // harmless if redundantly called
LogPrintf("%s: fflush failed: %d\n", __func__, errno);
return false;
}
#ifdef WIN32
HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(file));
if (FlushFileBuffers(hFile) == 0) {
LogPrintf("%s: FlushFileBuffers failed: %d\n", __func__, GetLastError());
return false;
}
#else
#if defined(__linux__) || defined(__NetBSD__)
if (fdatasync(fileno(file)) != 0 && errno != EINVAL) { // Ignore EINVAL for filesystems that don't support sync
LogPrintf("%s: fdatasync failed: %d\n", __func__, errno);
return false;
}
#elif defined(MAC_OSX) && defined(F_FULLFSYNC)
if (fcntl(fileno(file), F_FULLFSYNC, 0) == -1) { // Manpage says "value other than -1" is returned on success
LogPrintf("%s: fcntl F_FULLFSYNC failed: %d\n", __func__, errno);
return false;
}
#else
if (fsync(fileno(file)) != 0 && errno != EINVAL) {
LogPrintf("%s: fsync failed: %d\n", __func__, errno);
return false;
}
#endif
#endif
return true;
}
bool TruncateFile(FILE *file, unsigned int length) {
#if defined(WIN32)
return _chsize(_fileno(file), length) == 0;
#else
return ftruncate(fileno(file), length) == 0;
#endif
}
/**
* this function tries to raise the file descriptor limit to the requested number.
* It returns the actual file descriptor limit (which may be more or less than nMinFD)
*/
int RaiseFileDescriptorLimit(int nMinFD) {
#if defined(WIN32)
return 2048;
#else
struct rlimit limitFD;
if (getrlimit(RLIMIT_NOFILE, &limitFD) != -1) {
if (limitFD.rlim_cur < (rlim_t)nMinFD) {
limitFD.rlim_cur = nMinFD;
if (limitFD.rlim_cur > limitFD.rlim_max)
limitFD.rlim_cur = limitFD.rlim_max;
setrlimit(RLIMIT_NOFILE, &limitFD);
getrlimit(RLIMIT_NOFILE, &limitFD);
}
return limitFD.rlim_cur;
}
return nMinFD; // getrlimit failed, assume it's fine
#endif
}
/**
* this function tries to make a particular range of a file allocated (corresponding to disk space)
* it is advisory, and the range specified in the arguments will never contain live data
*/
void AllocateFileRange(FILE *file, unsigned int offset, unsigned int length) {
#if defined(WIN32)
// Windows-specific version
HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(file));
LARGE_INTEGER nFileSize;
int64_t nEndPos = (int64_t)offset + length;
nFileSize.u.LowPart = nEndPos & 0xFFFFFFFF;
nFileSize.u.HighPart = nEndPos >> 32;
SetFilePointerEx(hFile, nFileSize, 0, FILE_BEGIN);
SetEndOfFile(hFile);
#elif defined(MAC_OSX)
// OSX specific version
fstore_t fst;
fst.fst_flags = F_ALLOCATECONTIG;
fst.fst_posmode = F_PEOFPOSMODE;
fst.fst_offset = 0;
fst.fst_length = (off_t)offset + length;
fst.fst_bytesalloc = 0;
if (fcntl(fileno(file), F_PREALLOCATE, &fst) == -1) {
fst.fst_flags = F_ALLOCATEALL;
fcntl(fileno(file), F_PREALLOCATE, &fst);
}
ftruncate(fileno(file), fst.fst_length);
#elif defined(__linux__)
// Version using posix_fallocate
off_t nEndPos = (off_t)offset + length;
posix_fallocate(fileno(file), 0, nEndPos);
#else
// Fallback version
// TODO: just write one byte per block
static const char buf[65536] = {};
if (fseek(file, offset, SEEK_SET)) {
return;
}
while (length > 0) {
unsigned int now = 65536;
if (length < now)
now = length;
fwrite(buf, 1, now, file); // allowed to fail; this function is advisory anyway
length -= now;
}
#endif
}
#ifdef WIN32
fs::path GetSpecialFolderPath(int nFolder, bool fCreate)
{
WCHAR pszPath[MAX_PATH] = L"";
if(SHGetSpecialFolderPathW(nullptr, pszPath, nFolder, fCreate))
{
return fs::path(pszPath);
}
LogPrintf("SHGetSpecialFolderPathW() failed, could not obtain requested path.\n");
return fs::path("");
}
#endif
void runCommand(const std::string& strCommand)
{
if (strCommand.empty()) return;
#ifndef WIN32
int nErr = ::system(strCommand.c_str());
#else
int nErr = ::_wsystem(std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>,wchar_t>().from_bytes(strCommand).c_str());
#endif
if (nErr)
LogPrintf("runCommand error: system(%s) returned %d\n", strCommand, nErr);
}
void RenameThread(const char* name)
{
#if defined(PR_SET_NAME)
// Only the first 15 characters are used (16 - NUL terminator)
::prctl(PR_SET_NAME, name, 0, 0, 0);
#elif (defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__DragonFly__))
pthread_set_name_np(pthread_self(), name);
#elif defined(MAC_OSX)
pthread_setname_np(name);
#else
// Prevent warnings for unused parameters...
(void)name;
#endif
}
void SetupEnvironment()
{
#ifdef HAVE_MALLOPT_ARENA_MAX
// glibc-specific: On 32-bit systems set the number of arenas to 1.
// By default, since glibc 2.10, the C library will create up to two heap
// arenas per core. This is known to cause excessive virtual address space
// usage in our usage. Work around it by setting the maximum number of
// arenas to 1.
if (sizeof(void*) == 4) {
mallopt(M_ARENA_MAX, 1);
}
#endif
// On most POSIX systems (e.g. Linux, but not BSD) the environment's locale
// may be invalid, in which case the "C" locale is used as fallback.
#if !defined(WIN32) && !defined(MAC_OSX) && !defined(__FreeBSD__) && !defined(__OpenBSD__)
try {
std::locale(""); // Raises a runtime error if current locale is invalid
} catch (const std::runtime_error&) {
setenv("LC_ALL", "C", 1);
}
#elif defined(WIN32)
// Set the default input/output charset is utf-8
SetConsoleCP(CP_UTF8);
SetConsoleOutputCP(CP_UTF8);
#endif
// The path locale is lazy initialized and to avoid deinitialization errors
// in multithreading environments, it is set explicitly by the main thread.
// A dummy locale is used to extract the internal default locale, used by
// fs::path, which is then used to explicitly imbue the path.
std::locale loc = fs::path::imbue(std::locale::classic());
#ifndef WIN32
fs::path::imbue(loc);
#else
fs::path::imbue(std::locale(loc, new std::codecvt_utf8_utf16<wchar_t>()));
#endif
}
bool SetupNetworking()
{
#ifdef WIN32
// Initialize Windows Sockets
WSADATA wsadata;
int ret = WSAStartup(MAKEWORD(2,2), &wsadata);
if (ret != NO_ERROR || LOBYTE(wsadata.wVersion ) != 2 || HIBYTE(wsadata.wVersion) != 2)
return false;
#endif
return true;
}
int GetNumCores()
{
return std::thread::hardware_concurrency();
}
std::string CopyrightHolders(const std::string& strPrefix)
{
std::string strCopyrightHolders = strPrefix + strprintf(_(COPYRIGHT_HOLDERS), _(COPYRIGHT_HOLDERS_SUBSTITUTION));
// Check for untranslated substitution to make sure Bitcoin Core copyright is not removed by accident
if (strprintf(COPYRIGHT_HOLDERS, COPYRIGHT_HOLDERS_SUBSTITUTION).find("BCS Core") == std::string::npos) {
strCopyrightHolders += "\n" + strPrefix + "The BCS Core Developers";
}
return strCopyrightHolders;
}
bool CheckHex(const std::string& str) {
size_t data=0;
if(str.size() > 2 && (str.compare(0, 2, "0x") == 0 || str.compare(0, 2, "0X") == 0)){
data=2;
}
return str.size() > data && str.find_first_not_of("0123456789abcdefABCDEF", data) == std::string::npos;
}
// Obtain the application startup time (used for uptime calculation)
int64_t GetStartupTime()
{
return nStartupTime;
}
fs::path AbsPathForConfigVal(const fs::path& path, bool net_specific)
{
return fs::absolute(path, GetDataDir(net_specific));
}
int ScheduleBatchPriority()
{
#ifdef SCHED_BATCH
const static sched_param param{};
if (int ret = pthread_setschedparam(pthread_self(), SCHED_BATCH, ¶m)) {
LogPrintf("Failed to pthread_setschedparam: %s\n", strerror(errno));
return ret;
}
return 0;
#else
return 1;
#endif
}
std::string toHexString(int64_t intValue) {
//Store big endian representation in a vector
uint64_t num = (uint64_t)intValue;
std::vector<unsigned char> bigEndian;
for(int i=sizeof(num) -1; i>=0; i--){
bigEndian.push_back( (num>>(8*i)) & 0xff );
}
//Convert the vector into hex string
return "0x" + HexStr(bigEndian.begin(), bigEndian.end());
}
void ReplaceInt(const int64_t& number, const std::string& key, std::string& str)
{
// Convert the number into hex string
std::string num_hex = toHexString(number);
// Search for key in str and replace it with the hex string
std::string str_replaced = std::regex_replace(str, std::regex(key), num_hex);
str = str_replaced;
}
namespace util {
#ifdef WIN32
WinCmdLineArgs::WinCmdLineArgs()
{
wchar_t** wargv = CommandLineToArgvW(GetCommandLineW(), &argc);
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>, wchar_t> utf8_cvt;
argv = new char*[argc];
args.resize(argc);
for (int i = 0; i < argc; i++) {
args[i] = utf8_cvt.to_bytes(wargv[i]);
argv[i] = &*args[i].begin();
}
LocalFree(wargv);
}
WinCmdLineArgs::~WinCmdLineArgs()
{
delete[] argv;
}
std::pair<int, char**> WinCmdLineArgs::get()
{
return std::make_pair(argc, argv);
}
#endif
} // namespace util
|
/*
* Copyright (C) 2019 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "gtest/gtest.h"
#include "usm_linked_list/usm_linked_list.hpp"
#include "test_harness/test_harness.hpp"
TEST(UsmLinkedListSystemTests,
ApplicationReturnsSkipStatusGivenHelpMessageIsRequested) {
compute_samples::UsmLinkedListApplication application;
std::vector<std::string> command_line = {"--help"};
EXPECT_EQ(compute_samples::Application::Status::SKIP,
application.run(command_line));
}
HWTEST(UsmLinkedListSystemTests, GivenHostUsmThenApplicationReturnsOKStatus) {
compute_samples::UsmLinkedListApplication application;
std::vector<std::string> command_line = {"host"};
EXPECT_EQ(compute_samples::Application::Status::OK,
application.run(command_line));
}
HWTEST(UsmLinkedListSystemTests, GivenDeviceUsmThenApplicationReturnsOKStatus) {
compute_samples::UsmLinkedListApplication application;
std::vector<std::string> command_line = {"device"};
EXPECT_EQ(compute_samples::Application::Status::OK,
application.run(command_line));
}
HWTEST(UsmLinkedListSystemTests, GivenSharedUsmThenApplicationReturnsOKStatus) {
compute_samples::UsmLinkedListApplication application;
std::vector<std::string> command_line = {"shared"};
EXPECT_EQ(compute_samples::Application::Status::OK,
application.run(command_line));
}
HWTEST(UsmLinkedListSystemTests,
GivenCustomListSizeThenApplicationReturnsOKStatus) {
compute_samples::UsmLinkedListApplication application;
std::vector<std::string> command_line = {"host", "--size", "1024"};
EXPECT_EQ(compute_samples::Application::Status::OK,
application.run(command_line));
}
|
// Copyright (C) 2007, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: wan@google.com (Zhanyong Wan)
// Google Test - The Google C++ Testing Framework
//
// This file implements a universal value printer that can print a
// value of any type T:
//
// void ::testing::internal::UniversalPrinter<T>::Print(value, ostream_ptr);
//
// It uses the << operator when possible, and prints the bytes in the
// object otherwise. A user can override its behavior for a class
// type Foo by defining either operator<<(::std::ostream&, const Foo&)
// or void PrintTo(const Foo&, ::std::ostream*) in the namespace that
// defines Foo.
#include "gtest/gtest-printers.h"
#include <ctype.h>
#include <stdio.h>
#include <ostream> // NOLINT
#include <string>
#include "gtest/internal/gtest-port.h"
namespace testing {
namespace {
using ::std::ostream;
// Prints a segment of bytes in the given object.
void PrintByteSegmentInObjectTo(const unsigned char* obj_bytes, size_t start,
size_t count, ostream* os) {
char text[5] = "";
for (size_t i = 0; i != count; i++) {
const size_t j = start + i;
if (i != 0) {
// Organizes the bytes into groups of 2 for easy parsing by
// human.
if ((j % 2) == 0)
*os << ' ';
else
*os << '-';
}
GTEST_SNPRINTF_(text, sizeof(text), "%02X", obj_bytes[j]);
*os << text;
}
}
// Prints the bytes in the given value to the given ostream.
void PrintBytesInObjectToImpl(const unsigned char* obj_bytes, size_t count,
ostream* os) {
// Tells the user how big the object is.
*os << count << "-byte object <";
const size_t kThreshold = 132;
const size_t kChunkSize = 64;
// If the object size is bigger than kThreshold, we'll have to omit
// some details by printing only the first and the last kChunkSize
// bytes.
// TODO(wan): let the user control the threshold using a flag.
if (count < kThreshold) {
PrintByteSegmentInObjectTo(obj_bytes, 0, count, os);
} else {
PrintByteSegmentInObjectTo(obj_bytes, 0, kChunkSize, os);
*os << " ... ";
// Rounds up to 2-byte boundary.
const size_t resume_pos = (count - kChunkSize + 1)/2*2;
PrintByteSegmentInObjectTo(obj_bytes, resume_pos, count - resume_pos, os);
}
*os << ">";
}
} // namespace
namespace internal2 {
// Delegates to PrintBytesInObjectToImpl() to print the bytes in the
// given object. The delegation simplifies the implementation, which
// uses the << operator and thus is easier done outside of the
// ::testing::internal namespace, which contains a << operator that
// sometimes conflicts with the one in STL.
void PrintBytesInObjectTo(const unsigned char* obj_bytes, size_t count,
ostream* os) {
PrintBytesInObjectToImpl(obj_bytes, count, os);
}
} // namespace internal2
namespace internal {
// Depending on the value of a char (or wchar_t), we print it in one
// of three formats:
// - as is if it's a printable ASCII (e.g. 'a', '2', ' '),
// - as a hexidecimal escape sequence (e.g. '\x7F'), or
// - as a special escape sequence (e.g. '\r', '\n').
enum CharFormat {
kAsIs,
kHexEscape,
kSpecialEscape
};
// Returns true if c is a printable ASCII character. We test the
// value of c directly instead of calling isprint(), which is buggy on
// Windows Mobile.
inline bool IsPrintableAscii(wchar_t c) {
return 0x20 <= c && c <= 0x7E;
}
// Prints a wide or narrow char c as a character literal without the
// quotes, escaping it when necessary; returns how c was formatted.
// The template argument UnsignedChar is the unsigned version of Char,
// which is the type of c.
template <typename UnsignedChar, typename Char>
static CharFormat PrintAsCharLiteralTo(Char c, ostream* os) {
switch (static_cast<wchar_t>(c)) {
case L'\0':
*os << "\\0";
break;
case L'\'':
*os << "\\'";
break;
case L'\\':
*os << "\\\\";
break;
case L'\a':
*os << "\\a";
break;
case L'\b':
*os << "\\b";
break;
case L'\f':
*os << "\\f";
break;
case L'\n':
*os << "\\n";
break;
case L'\r':
*os << "\\r";
break;
case L'\t':
*os << "\\t";
break;
case L'\v':
*os << "\\v";
break;
default:
if (IsPrintableAscii(c)) {
*os << static_cast<char>(c);
return kAsIs;
} else {
*os << "\\x" + String::FormatHexInt(static_cast<UnsignedChar>(c));
return kHexEscape;
}
}
return kSpecialEscape;
}
// Prints a wchar_t c as if it's part of a string literal, escaping it when
// necessary; returns how c was formatted.
static CharFormat PrintAsStringLiteralTo(wchar_t c, ostream* os) {
switch (c) {
case L'\'':
*os << "'";
return kAsIs;
case L'"':
*os << "\\\"";
return kSpecialEscape;
default:
return PrintAsCharLiteralTo<wchar_t>(c, os);
}
}
// Prints a char c as if it's part of a string literal, escaping it when
// necessary; returns how c was formatted.
static CharFormat PrintAsStringLiteralTo(char c, ostream* os) {
return PrintAsStringLiteralTo(
static_cast<wchar_t>(static_cast<unsigned char>(c)), os);
}
// Prints a wide or narrow character c and its code. '\0' is printed
// as "'\\0'", other unprintable characters are also properly escaped
// using the standard C++ escape sequence. The template argument
// UnsignedChar is the unsigned version of Char, which is the type of c.
template <typename UnsignedChar, typename Char>
void PrintCharAndCodeTo(Char c, ostream* os) {
// First, print c as a literal in the most readable form we can find.
*os << ((sizeof(c) > 1) ? "L'" : "'");
const CharFormat format = PrintAsCharLiteralTo<UnsignedChar>(c, os);
*os << "'";
// To aid user debugging, we also print c's code in decimal, unless
// it's 0 (in which case c was printed as '\\0', making the code
// obvious).
if (c == 0)
return;
*os << " (" << static_cast<int>(c);
// For more convenience, we print c's code again in hexidecimal,
// unless c was already printed in the form '\x##' or the code is in
// [1, 9].
if (format == kHexEscape || (1 <= c && c <= 9)) {
// Do nothing.
} else {
*os << ", 0x" << String::FormatHexInt(static_cast<UnsignedChar>(c));
}
*os << ")";
}
void PrintTo(unsigned char c, ::std::ostream* os) {
PrintCharAndCodeTo<unsigned char>(c, os);
}
void PrintTo(signed char c, ::std::ostream* os) {
PrintCharAndCodeTo<unsigned char>(c, os);
}
// Prints a wchar_t as a symbol if it is printable or as its internal
// code otherwise and also as its code. L'\0' is printed as "L'\\0'".
void PrintTo(wchar_t wc, ostream* os) {
PrintCharAndCodeTo<wchar_t>(wc, os);
}
// Prints the given array of characters to the ostream. CharType must be either
// char or wchar_t.
// The array starts at begin, the length is len, it may include '\0' characters
// and may not be NUL-terminated.
template <typename CharType>
static void PrintCharsAsStringTo(
const CharType* begin, size_t len, ostream* os) {
const char* const kQuoteBegin = sizeof(CharType) == 1 ? "\"" : "L\"";
*os << kQuoteBegin;
bool is_previous_hex = false;
for (size_t index = 0; index < len; ++index) {
const CharType cur = begin[index];
if (is_previous_hex && IsXDigit(cur)) {
// Previous character is of '\x..' form and this character can be
// interpreted as another hexadecimal digit in its number. Break string to
// disambiguate.
*os << "\" " << kQuoteBegin;
}
is_previous_hex = PrintAsStringLiteralTo(cur, os) == kHexEscape;
}
*os << "\"";
}
// Prints a (const) char/wchar_t array of 'len' elements, starting at address
// 'begin'. CharType must be either char or wchar_t.
template <typename CharType>
static void UniversalPrintCharArray(
const CharType* begin, size_t len, ostream* os) {
// The code
// const char kFoo[] = "foo";
// generates an array of 4, not 3, elements, with the last one being '\0'.
//
// Therefore when printing a char array, we don't print the last element if
// it's '\0', such that the output matches the string literal as it's
// written in the source code.
if (len > 0 && begin[len - 1] == '\0') {
PrintCharsAsStringTo(begin, len - 1, os);
return;
}
// If, however, the last element in the array is not '\0', e.g.
// const char kFoo[] = { 'f', 'o', 'o' };
// we must print the entire array. We also print a message to indicate
// that the array is not NUL-terminated.
PrintCharsAsStringTo(begin, len, os);
*os << " (no terminating NUL)";
}
// Prints a (const) char array of 'len' elements, starting at address 'begin'.
void UniversalPrintArray(const char* begin, size_t len, ostream* os) {
UniversalPrintCharArray(begin, len, os);
}
// Prints a (const) wchar_t array of 'len' elements, starting at address
// 'begin'.
void UniversalPrintArray(const wchar_t* begin, size_t len, ostream* os) {
UniversalPrintCharArray(begin, len, os);
}
// Prints the given C string to the ostream.
void PrintTo(const char* s, ostream* os) {
if (s == NULL) {
*os << "NULL";
} else {
*os << ImplicitCast_<const void*>(s) << " pointing to ";
PrintCharsAsStringTo(s, strlen(s), os);
}
}
// MSVC compiler can be configured to define whar_t as a typedef
// of unsigned short. Defining an overload for const wchar_t* in that case
// would cause pointers to unsigned shorts be printed as wide strings,
// possibly accessing more memory than intended and causing invalid
// memory accesses. MSVC defines _NATIVE_WCHAR_T_DEFINED symbol when
// wchar_t is implemented as a native type.
#if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)
// Prints the given wide C string to the ostream.
void PrintTo(const wchar_t* s, ostream* os) {
if (s == NULL) {
*os << "NULL";
} else {
*os << ImplicitCast_<const void*>(s) << " pointing to ";
PrintCharsAsStringTo(s, wcslen(s), os);
}
}
#endif // wchar_t is native
// Prints a ::string object.
#if GTEST_HAS_GLOBAL_STRING
void PrintStringTo(const ::string& s, ostream* os) {
PrintCharsAsStringTo(s.data(), s.size(), os);
}
#endif // GTEST_HAS_GLOBAL_STRING
void PrintStringTo(const ::std::string& s, ostream* os) {
PrintCharsAsStringTo(s.data(), s.size(), os);
}
// Prints a ::wstring object.
#if GTEST_HAS_GLOBAL_WSTRING
void PrintWideStringTo(const ::wstring& s, ostream* os) {
PrintCharsAsStringTo(s.data(), s.size(), os);
}
#endif // GTEST_HAS_GLOBAL_WSTRING
#if GTEST_HAS_STD_WSTRING
void PrintWideStringTo(const ::std::wstring& s, ostream* os) {
PrintCharsAsStringTo(s.data(), s.size(), os);
}
#endif // GTEST_HAS_STD_WSTRING
} // namespace internal
} // namespace testing
|
#ifndef CONNECT___SERVER__HPP
#define CONNECT___SERVER__HPP
/* $Id: server.hpp 364724 2012-05-30 14:57:38Z ivanovp $
* ===========================================================================
*
* PUBLIC DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
*
* ===========================================================================
*
* Authors: Aaron Ucko, Victor Joukov, Denis Vakatov
*
*/
/// @file server.hpp
/// Framework to create multithreaded network servers with thread-per-request
/// scheduling.
#include <connect/impl/thread_pool_for_server.hpp>
#include <connect/ncbi_conn_stream.hpp>
#include <connect/ncbi_conn_exception.hpp>
#include <connect/ncbi_socket.hpp>
/** @addtogroup ThreadedServer
*
* @{
*/
BEGIN_NCBI_SCOPE
class IServer_ConnectionFactory;
class IServer_ConnectionBase;
struct SServer_Parameters;
class CServer_ConnectionPool;
class CServer_Connection;
/// Extended copy of the type EIO_Event allowing to distinguish between
/// connection closing from client and from ourselves
enum EServIO_Event {
eServIO_Open = 0x00,
eServIO_Read = 0x01,
eServIO_Write = 0x02,
eServIO_ReadWrite = 0x03, /**< eIO_Read | eIO_Write */
eServIO_ClientClose = 0x04,
eServIO_OurClose = 0x08,
eServIO_Inactivity = 0x10,
eServIO_Delete = 0x20
};
/// Transform EIO_Event type to EServIO_Event
inline EServIO_Event
IOEventToServIOEvent(EIO_Event event)
{
return (EServIO_Event) event;
}
class CNetCacheServer;
/////////////////////////////////////////////////////////////////////////////
///
/// CServer::
///
/// Thread-pool based server. On every event it allocates one of threads
/// from pool to serve the event, thereby making possible to serve large
/// number of concurrent connections efficiently. You need to subclass it
/// only if you want to provide gentle shutdown ability (override
/// ShutdownRequested) or process data in main thread on timeout (override
/// ProcessTimeout and set parameter accept_timeout to non-zero value).
///
class NCBI_XCONNECT_EXPORT CServer : protected CConnIniter
{
public:
// 'ctors
CServer(void);
virtual ~CServer();
/// Register a listener
void AddListener(IServer_ConnectionFactory* factory,
unsigned short port);
///
void SetParameters(const SServer_Parameters& new_params);
///
void GetParameters(SServer_Parameters* params);
/// Start listening before the main loop. If called, tries
/// to listen on all requested ports for all listeners, correcting
/// errors by calling listeners' OnFailure
void StartListening(void);
/// Enter the main loop
void Run(void);
/// Submit request to be executed by the server thread pool
void SubmitRequest(const CRef<CStdRequest>& request);
/// Mark connection as deferred for processing, i.e. do not poll on it
/// and wait when IsReadyToProcess() will return true.
void DeferConnectionProcessing(IServer_ConnectionBase* conn);
void DeferConnectionProcessing(CSocket* sock);
/// Close connection. Method should be called only when closing is
/// initiated by server itself, because it will generate then event
/// eServIO_OurClose.
///
/// @sa EServIO_Event
void CloseConnection(CSocket* sock);
/// Add externally created connection to the connection pool which server
/// polls on. Throws exception if pool is full.
/// NOTE: events to this connection can come theoretically even
/// NOTE: if connection gets some error or its peer closes it then conn
/// object will be deleted after processing OnClose event. If you don't
/// want that you have to call RemoveConnectionFromPool while handling
/// OnClose.
void AddConnectionToPool(CServer_Connection* conn);
/// Remove externally created connection from pool.
void RemoveConnectionFromPool(CServer_Connection* conn);
/// Force poll cycle to make another iteration.
/// Should be called if IsReadyToProcess() for some connection handler
/// became true.
void WakeUpPollCycle(void);
/// Set custom suffix to use on all threads in the server's pool.
/// Value can be set only before call to Run(), any change of the value
/// after call to Run() will be ignored.
void SetCustomThreadSuffix(const string& suffix)
{ m_ThreadSuffix = suffix; }
protected:
/// Initialize the server
///
/// Called by Run method before poll cycle.
virtual void Init();
/// Cleanup the server
///
/// Called by Run method after poll cycle when all processing threads
/// are stopped, but before releasing listening ports. Here you're still
/// guaranteed that another instance running on the same set of ports will
/// fail at StartListening point.
virtual void Exit();
/// Runs synchronously when no socket activity has occurred in a
/// while (as determined by m_AcceptTimeout).
/// @sa m_Parameters->accept_timeout
virtual void ProcessTimeout(void) { }
/// Runs synchronously between iterations.
/// @return
/// whether to shut down service and return from Run.
virtual bool ShutdownRequested(void) { return false; }
private:
void x_AddRequests(const vector<CRef<CStdRequest> >& reqs);
void x_DoRun(void);
friend class CNetCacheServer;
CPoolOfThreads_ForServer* GetThreadPool(void) { return m_ThreadPool.get(); }
auto_ptr<CPoolOfThreads_ForServer> m_ThreadPool;
SServer_Parameters* m_Parameters;
CServer_ConnectionPool* m_ConnectionPool;
string m_ThreadSuffix;
};
/////////////////////////////////////////////////////////////////////////////
///
/// Error codes for OnOverflow method in IServer_ConnectionHandler
enum EOverflowReason
{
eOR_Unknown = 0,
eOR_ConnectionPoolFull,
eOR_RequestQueueFull,
eOR_UnpollableSocket
};
/////////////////////////////////////////////////////////////////////////////
///
/// IServer_ConnectionHandler::
///
/// Implement this interface to provide server functionality.
///
class NCBI_XCONNECT_EXPORT IServer_ConnectionHandler
{
public:
virtual ~IServer_ConnectionHandler() { }
/// Following three methods are guaranteed to be called NOT
/// at the same time as On*, so if you implement them
/// you should not guard the variables which they can use with
/// mutexes.
/// @param alarm_time
/// Set this parameter to a pointer to a CTime object to recieve
/// an OnTimer event at the moment in time specified by this object.
/// @return
/// Returns the set of events for which Poll should check.
virtual EIO_Event GetEventsToPollFor(const CTime** /*alarm_time*/) const
{ return eIO_Read; }
/// Returns the timeout for this connection
virtual const STimeout* GetTimeout(void)
{ return kDefaultTimeout; }
/// Returns connection handler's perception of whether we open or not.
/// It is unsafe to just close underlying socket because of the race,
/// emerging due to the fact that the socket can linger for a while.
virtual bool IsOpen(void)
{ return true; }
/// Returns the handler's readiness to process input data or to write
/// some output data. OnRead() and OnWrite() are not called unless this
/// method return true.
virtual bool IsReadyToProcess(void) const
{ return true; }
/// Runs in response to an external event [asynchronous].
/// You can get socket by calling GetSocket(), if you close the socket
/// this object will be destroyed.
/// Individual events are:
/// A client has just established this connection.
virtual void OnOpen(void) = 0;
/// The client has just sent data.
virtual void OnRead(void) = 0;
/// The client is ready to receive data.
virtual void OnWrite(void) = 0;
/// Type of connection closing
enum EClosePeer {
eOurClose, ///< Connection closed by ourselves
eClientClose ///< Connection closed by other peer
};
/// The connection has closed (with information on type of closing)
virtual void OnClose(EClosePeer /*peer*/) { }
/// Runs when a client has been idle for too long, prior to
/// closing the connection [synchronous].
virtual void OnTimeout(void) { }
/// This method is called at the moment in time specified earlier by the
/// alarm_time parameter of the GetEventsToPollFor method [synchronous].
virtual void OnTimer(void) { }
/// Runs when there are insufficient resources to queue a
/// connection, prior to closing it. Provides a reason why the
/// connection is being close, which can be reported back to the client.
// See comment for CAcceptRequest::Process and CServer::CreateRequest
virtual void OnOverflow(EOverflowReason) { }
/// Get underlying socket
CSocket& GetSocket(void) { return *m_Socket; }
public: // TODO: make it protected. Public is for DEBUG purposes only
friend class CServer_Connection;
void SetSocket(CSocket *socket) { m_Socket = socket; }
private:
CSocket* m_Socket;
};
/////////////////////////////////////////////////////////////////////////////
///
/// IServer_MessageHandler::
///
/// TODO:
class NCBI_XCONNECT_EXPORT IServer_MessageHandler :
public IServer_ConnectionHandler
{
public:
IServer_MessageHandler() :
m_Buffer(0)
{ }
virtual ~IServer_MessageHandler() { BUF_Destroy(m_Buffer); }
virtual void OnRead(void);
// You should implement this look-ahead function to decide, did you get
// a message in the series of read events. If not, you should return -1.
// If yes, return number of chars, beyond well formed message. E.g., if
// your message spans all the buffer, return 0. If you returned non-zero
// value, this piece of data will be used in the next CheckMessage to
// simplify client state management.
// You also need to copy bytes, comprising the message from data to buffer.
virtual int CheckMessage(BUF* buffer, const void *data, size_t size) = 0;
// Process incoming message in the buffer, by using
// BUF_Read(buffer, your_data_buffer, BUF_Size(buffer)).
virtual void OnMessage(BUF buffer) = 0;
private:
BUF m_Buffer;
};
int NCBI_XCONNECT_EXPORT
Server_CheckLineMessage(BUF* buffer, const void *data, size_t size,
bool& seen_CR);
/////////////////////////////////////////////////////////////////////////////
///
/// IServer_LineMessageHandler::
///
/// TODO:
class NCBI_XCONNECT_EXPORT IServer_LineMessageHandler :
public IServer_MessageHandler
{
public:
IServer_LineMessageHandler() :
IServer_MessageHandler(), m_SeenCR(false)
{ }
virtual int CheckMessage(BUF* buffer, const void *data, size_t size) {
return Server_CheckLineMessage(buffer, data, size, m_SeenCR);
}
private:
bool m_SeenCR;
};
/////////////////////////////////////////////////////////////////////////////
///
/// IServer_StreamHandler::
///
/// TODO:
class NCBI_XCONNECT_EXPORT IServer_StreamHandler :
public IServer_ConnectionHandler
{
public:
CNcbiIostream &GetStream();
private:
CConn_SocketStream m_Stream;
};
/////////////////////////////////////////////////////////////////////////////
///
/// IServer_ConnectionFactory::
///
/// Factory to be registered with CServer instance. You usually do not
/// need to implement it, default template CServer_ConnectionFactory will
/// suffice. You NEED to implement it manually to pass server-wide parameters
/// to ConnectionHandler instances, e.g. for implementation of gentle shutdown.
///
class NCBI_XCONNECT_EXPORT IServer_ConnectionFactory
{
public:
/// What to do if the port is busy
enum EListenAction {
eLAFail = 0, // Can not live without this port, default
eLAIgnore = 1, // Do nothing, throw away this listener
eLARetry = 2 // Listener should provide another port to try
};
virtual ~IServer_ConnectionFactory() { }
/// @return
/// a new instance of handler for connection
virtual IServer_ConnectionHandler* Create(void) = 0;
/// Return desired action if the port, mentioned in AddListener is busy.
/// If the action is eLARetry, provide new port. The
virtual EListenAction OnFailure(unsigned short* /* port */)
{ return eLAFail; }
};
/////////////////////////////////////////////////////////////////////////////
///
/// CServer_ConnectionFactory::
///
/// Reasonable default implementation for IServer_ConnectionFactory
///
template <class TServer_ConnectionHandler>
class CServer_ConnectionFactory : public IServer_ConnectionFactory
{
public:
virtual IServer_ConnectionHandler* Create()
{ return new TServer_ConnectionHandler(); }
};
/////////////////////////////////////////////////////////////////////////////
///
/// SServer_Parameters::
///
/// Settings for CServer
///
struct NCBI_XCONNECT_EXPORT SServer_Parameters
{
/// Maximum # of open connections
unsigned int max_connections;
/// Temporarily close listener when queue fills?
bool temporarily_stop_listening;
/// Maximum t between exit checks
const STimeout* accept_timeout;
/// For how long to keep inactive non-listening sockets open
/// (default: 10 minutes)
const STimeout* idle_timeout;
// (settings for the thread pool)
unsigned int init_threads; ///< Number of initial threads
unsigned int max_threads; ///< Maximum simultaneous threads
unsigned int spawn_threshold; ///< Controls when to spawn more threads
/// Create structure with the default set of parameters
SServer_Parameters();
};
/////////////////////////////////////////////////////////////////////////////
///
/// CServer_Exception::
///
/// Exceptions thrown by CServer::Run()
///
class NCBI_XCONNECT_EXPORT CServer_Exception
: EXCEPTION_VIRTUAL_BASE public CConnException
{
public:
enum EErrCode {
eBadParameters, ///< Out-of-range parameters given
eCouldntListen, ///< Unable to bind listening port
ePoolOverflow ///< Connection pool overflowed
};
virtual const char* GetErrCodeString(void) const;
NCBI_EXCEPTION_DEFAULT(CServer_Exception, CConnException);
};
END_NCBI_SCOPE
/* @} */
#endif /* CONNECT___SERVER__HPP */
|
// { Driver Code Starts
#include<bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution
{
public:
//Function to find minimum time required to rot all oranges.
int orangesRotting(vector<vector<int>>& grid) {
// Code here
int n = grid.size();
int m = grid[0].size();
// BFS traversal
// stores index of rotten oranges
queue<pair<int,int>> rotten;
// first count total oranges in grid and push the rotten
// into the queue to be processed
int totOranges = 0;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
// if cell not empty
if(grid[i][j]!=0){
totOranges++;
// if rotten push to queue
if(grid[i][j]==2) rotten.push({i,j});
}
}
}
int mx[] = { 0,0,-1,1};
int my[] = {-1,1, 0,0};
// count of total oranges rotted or will rot
int cntRot = 0, days = 0;
while(!rotten.empty()){
// getting number of oranges rotten each day
int k = rotten.size();
cntRot += k;
while(k--){
int x = rotten.front().first, y = rotten.front().second;
rotten.pop();
// traversing all 4 directions from current node
for(int i=0;i<4;i++){
int nx = x+mx[i], ny = y+my[i];
// if index out of bound or orange not present
// or rotten from before then ignore
if(nx<0 or ny<0 or nx>=n or ny>=m or grid[nx][ny]!=1)
continue;
// else rot the fresh orange and push to queue
grid[nx][ny] = 2;
rotten.push({nx,ny});
}
}
// at end of day we check if rotten isn't empty
// means another day is required to rot oranges
// increasing day to rot all fresh oranges
if(!rotten.empty()) days++;
}
// now check if all oranges in grid have rotted or not
// then return number of days else not possible return -1
return (totOranges==cntRot)?days:-1;
}
};
// { Driver Code Starts.
int main(){
int tc;
cin >> tc;
while(tc--){
int n, m;
cin >> n >> m;
vector<vector<int>>grid(n, vector<int>(m, -1));
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
cin >> grid[i][j];
}
}
Solution obj;
int ans = obj.orangesRotting(grid);
cout << ans << "\n";
}
return 0;
} // } Driver Code Ends
|
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int getHeight(TreeNode *node) {
if (!node) {
return 0;
}
else if (!node -> left & !node -> right) {
return 1;
}
int left = getHeight(node -> left), right = getHeight(node -> right);
if (left == -1 | right == -1) {
return -1;
}
else if (abs(left - right) <= 1) {
return max(left, right) + 1;
}
else {
return -1;
}
}
bool isBalanced(TreeNode *root) {
return !(getHeight(root) == -1);
}
};
|
#include <check.h>
#include <stdint.h>
#include "signals.h"
#include "diagnostics.h"
#include "lights.h"
#include "config.h"
#include "pipeline.h"
#include "power.h"
namespace diagnostics = openxc::diagnostics;
namespace usb = openxc::interface::usb;
using openxc::pipeline::Pipeline;
using openxc::signals::getCanBuses;
using openxc::signals::getCanBusCount;
using openxc::config::getConfiguration;
extern openxc::lights::RGB LIGHT_A_LAST_COLOR;
extern unsigned long FAKE_TIME;
// TODO this should be refactored out of vi_firmware.cpp, and include a header
// file so we don't have to use extern.
extern void receiveCan(Pipeline* pipeline, CanBus* bus);
extern void checkBusActivity();
extern void initializeVehicleInterface();
extern void firmwareLoop();
static bool canQueueEmpty(int bus) {
return QUEUE_EMPTY(CanMessage, &getCanBuses()[bus].sendQueue);
}
void setup() {
initializeVehicleInterface();
fail_unless(canQueueEmpty(0));
}
CanMessage message = {
id: 0x1,
format: CanMessageFormat::STANDARD,
data: {0x1, 0x2}
};
START_TEST (test_update_data_lights_can_active)
{
CanBus* bus = &getCanBuses()[0];
QUEUE_PUSH(CanMessage, &bus->receiveQueue, message);
receiveCan(&getConfiguration()->pipeline, bus);
checkBusActivity();
ck_assert(openxc::lights::colors_equal(LIGHT_A_LAST_COLOR,
openxc::lights::COLORS.blue));
}
END_TEST
START_TEST (test_update_data_lights_can_inactive)
{
checkBusActivity();
ck_assert(openxc::lights::colors_equal(LIGHT_A_LAST_COLOR,
openxc::lights::COLORS.red));
CanBus* bus = &getCanBuses()[0];
QUEUE_PUSH(CanMessage, &bus->receiveQueue, message);
receiveCan(&getConfiguration()->pipeline, bus);
FAKE_TIME += (openxc::can::CAN_ACTIVE_TIMEOUT_S * 1000) * 2;
}
END_TEST
START_TEST (test_update_data_lights_suspend)
{
CanBus* bus = &getCanBuses()[0];
QUEUE_PUSH(CanMessage, &bus->receiveQueue, message);
receiveCan(&getConfiguration()->pipeline, bus);
FAKE_TIME += (openxc::can::CAN_ACTIVE_TIMEOUT_S * 1000) * 2;
checkBusActivity();
if(getConfiguration()->powerManagement == openxc::config::PowerManagement::ALWAYS_ON) {
ck_assert(openxc::lights::colors_equal(LIGHT_A_LAST_COLOR,
openxc::lights::COLORS.red));
} else {
ck_assert(openxc::lights::colors_equal(LIGHT_A_LAST_COLOR,
openxc::lights::COLORS.black));
}
}
END_TEST
START_TEST (test_loop)
{
firmwareLoop();
}
END_TEST
Suite* suite(void) {
Suite* s = suite_create("firmware");
TCase *tc_core = tcase_create("core");
tcase_add_checked_fixture(tc_core, setup, NULL);
tcase_add_test(tc_core, test_update_data_lights_can_active);
tcase_add_test(tc_core, test_update_data_lights_can_inactive);
tcase_add_test(tc_core, test_update_data_lights_suspend);
tcase_add_test(tc_core, test_loop);
suite_add_tcase(s, tc_core);
return s;
}
int main(void) {
int numberFailed;
Suite* s = suite();
SRunner *sr = srunner_create(s);
// Don't fork so we can actually use gdb
srunner_set_fork_status(sr, CK_NOFORK);
srunner_run_all(sr, CK_NORMAL);
numberFailed = srunner_ntests_failed(sr);
srunner_free(sr);
return (numberFailed == 0) ? 0 : 1;
}
|
/******************************************************************************
The MIT License(MIT)
Embedded Template Library.
https://github.com/ETLCPP/etl
https://www.etlcpp.com
Copyright(c) 2020 jwellbelove
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files(the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions :
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
******************************************************************************/
#include "unit_test_framework.h"
#include <string>
#include <array>
#include <algorithm>
#include "etl/string.h"
#include "etl/fnv_1.h"
#undef STR
#define STR(x) x
namespace
{
bool compares_agree(int result1, int result2)
{
return ((result1 < 0) && (result2 < 0)) ||
((result1 == 0) && (result2 == 0)) ||
((result1 > 0) && (result2 > 0));
}
SUITE(test_string_char)
{
static constexpr size_t SIZE = 11UL;
static constexpr size_t SIZE_L = 52UL;
static constexpr size_t SIZE_S = 4UL;
using Text = etl::string_ext;
using IText = etl::istring;
using TextT = etl::string<SIZE>;
using Compare_Text = std::string;
using value_t = Text::value_type;
using TextBuffer = std::array<IText::value_type, SIZE + 1>;
using TextBufferL = std::array<IText::value_type, SIZE_L + 1>;
using TextBufferS = std::array<IText::value_type, SIZE_S + 1>;
Compare_Text initial_text;
Compare_Text less_text;
Compare_Text greater_text;
Compare_Text shorter_text;
Compare_Text different_text;
Compare_Text insert_text;
Compare_Text longer_text;
Compare_Text short_text;
const value_t* pinitial_text = STR("Hello World");
value_t array_text[12];
value_t* p_text = array_text;
//*************************************************************************
template <typename T1, typename T2>
bool Equal(const T1& compare_text, const T2& text)
{
return (compare_text.size() == text.size()) && std::equal(text.begin(), text.end(), compare_text.begin());
}
//*************************************************************************
struct SetupFixture
{
SetupFixture()
{
initial_text = STR("Hello World");
insert_text = STR("Insert");
less_text = STR("Hello Vorld");
greater_text = STR("Hello Xorld");
shorter_text = STR("Hello Worl");
different_text = STR("Byee Planet");
longer_text = STR("Hello World There");
short_text = STR("Hello");
std::copy(pinitial_text, pinitial_text + etl::strlen(pinitial_text), array_text);
}
};
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_default_constructor)
{
TextBuffer buffer;
Text text(buffer.data(), buffer.size());
CHECK_EQUAL(text.size(), size_t(0));
CHECK(text.empty());
CHECK_EQUAL(SIZE, text.capacity());
CHECK_EQUAL(SIZE, text.max_size());
CHECK(text.begin() == text.end());
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_default_constructor_use_buffer_and_size)
{
size_t length = etl::strlen(p_text);
Text text(p_text, length + 1);
CHECK_EQUAL(0U, text.size());
CHECK(text.empty());
CHECK_EQUAL(length, text.capacity());
CHECK_EQUAL(length, text.max_size());
CHECK(text.begin() == text.end());
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_default_constructor_use_buffer_text_and_size)
{
Text text(p_text, p_text, etl::strlen(p_text) + 1);
CHECK_EQUAL(text.size(), etl::strlen(p_text));
CHECK(!text.empty());
CHECK_EQUAL(etl::strlen(p_text), text.capacity());
CHECK_EQUAL(etl::strlen(p_text), text.max_size());
CHECK(text.begin() != text.end());
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_default_constructor_use_array_buffer)
{
Text text(array_text, std::size(array_text));
CHECK_EQUAL(0U, text.size());
CHECK(text.empty());
CHECK_EQUAL(std::size(array_text) - 1, text.capacity());
CHECK_EQUAL(std::size(array_text) - 1, text.max_size());
CHECK(text.begin() == text.end());
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_default_constructor_use_array_buffer_text)
{
Text text(array_text, array_text, std::size(array_text));
CHECK_EQUAL(text.size(), etl::strlen(array_text));
CHECK(!text.empty());
CHECK_EQUAL(std::size(array_text) - 1, text.capacity());
CHECK_EQUAL(std::size(array_text) - 1, text.max_size());
CHECK(text.begin() != text.end());
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
}
//*************************************************************************
TEST(test_iterator_comparison_empty)
{
TextBuffer buffer;
Text text(buffer.data(), buffer.size());
CHECK(text.begin() == text.end());
CHECK(text.cbegin() == text.cend());
CHECK(text.rbegin() == text.rend());
CHECK(text.crbegin() == text.crend());
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_constructor_size_value)
{
const size_t INITIAL_SIZE = 5UL;
const value_t INITIAL_VALUE = STR('A');
TextBuffer buffer;
Compare_Text compare_text(INITIAL_SIZE, INITIAL_VALUE);
Text text(INITIAL_SIZE, INITIAL_VALUE, buffer.data(), buffer.size());
CHECK(text.size() == INITIAL_SIZE);
CHECK(!text.empty());
bool is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_constructor_size_excess)
{
TextBuffer buffer;
Text text(buffer.size() + 1, STR('A'), buffer.data(), buffer.size());
CHECK_EQUAL(buffer.size() - 1, text.size());
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_constructor_char_pointer)
{
TextBuffer buffer;
Compare_Text compare_text(initial_text.c_str());
Text text(initial_text.c_str(), buffer.data(), buffer.size());
CHECK(!text.empty());
bool is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_constructor_char_pointer_excess)
{
Compare_Text compare_text(initial_text.c_str());
TextBuffer buffer;
Text text(longer_text.c_str(), buffer.data(), buffer.size());
CHECK(!text.empty());
bool is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_constructor_char_pointer_size)
{
Compare_Text compare_text(SIZE, STR('A'));
TextBuffer buffer;
Text text(SIZE, STR('A'), buffer.data(), buffer.size());
CHECK(!text.empty());
bool is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_constructor_char_pointer_size_excess)
{
Compare_Text compare_text(SIZE, STR('A'));
TextBuffer buffer;
Text text(SIZE + 1, STR('A'), buffer.data(), buffer.size());
CHECK(!text.empty());
bool is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_constructor_size_char)
{
Compare_Text compare_text(initial_text.c_str(), initial_text.size() / 2);
TextBuffer buffer;
Text text(initial_text.c_str(), initial_text.size() / 2, buffer.data(), buffer.size());
CHECK(!text.empty());
bool is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_constructor_size_char_excess)
{
Compare_Text compare_text(initial_text.c_str(), initial_text.size());
TextBuffer buffer;
Text text(longer_text.c_str(), longer_text.size(), buffer.data(), buffer.size());
CHECK(!text.empty());
bool is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_constructor_range)
{
Compare_Text compare_text(initial_text.begin(), initial_text.end());
TextBuffer buffer;
Text text(compare_text.begin(), compare_text.end(), buffer.data(), buffer.size());
CHECK(text.size() == SIZE);
CHECK(!text.empty());
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_constructor_range_excess)
{
TextBuffer buffer;
Text text(longer_text.begin(), longer_text.end(), buffer.data(), buffer.size());
bool is_equal = Equal(initial_text, text);
CHECK(is_equal);
CHECK(text.size() == SIZE);
CHECK(!text.empty());
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_constructor_from_literal)
{
TextBuffer buffer;
Text text(STR("Hello World"), buffer.data(), buffer.size());
bool is_equal = Equal(initial_text, text);
CHECK(is_equal);
CHECK(text.size() == SIZE);
CHECK(!text.empty());
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_constructor_from_string_view)
{
etl::string_view view(initial_text.data(), initial_text.size());
TextBuffer buffer;
Text text(view, buffer.data(), buffer.size());
bool is_equal = Equal(initial_text, text);
CHECK(is_equal);
CHECK(text.size() == SIZE);
CHECK(!text.empty());
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_copy_constructor)
{
TextBuffer buffer;
Text text(initial_text.c_str(), buffer.data(), buffer.size());
TextBuffer buffer2;
Text text2(text, buffer2.data(), buffer2.size());
CHECK(text2 == text);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text2.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_copy_constructor_i)
{
TextBuffer buffer;
Text text(initial_text.c_str(), buffer.data(), buffer.size());
IText& itext = text;
TextBuffer buffer2;
Text text2(itext, buffer2.data(), buffer2.size());
CHECK(text2 == text);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text2.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_copy_constructor_excess)
{
TextBuffer buffer;
Text text(initial_text.c_str(), buffer.data(), buffer.size());
TextBufferL bufferl;
Text textl(longer_text.c_str(), bufferl.data(), bufferl.size());
TextBuffer buffer2;
Text text2(textl, buffer2.data(), buffer2.size());
CHECK(text2 == text);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(text2.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_copy_constructor_from_truncated)
{
TextBuffer buffer;
Text text(longer_text.c_str(), buffer.data(), buffer.size());
TextBuffer buffer2;
Text text2(text, buffer2.data(), buffer2.size());
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(text2.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_construct_position_length)
{
Compare_Text compare_text(initial_text.c_str());
Compare_Text compare_text2(compare_text, 2, 4);
TextBuffer buffer;
Text text(initial_text.c_str(), buffer.data(), buffer.size());
TextBuffer buffer2;
Text text2(text, buffer2.data(), buffer2.size(), 2, 4);
bool is_equal = Equal(compare_text2, text2);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text2.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_construct_position_length_excess)
{
Compare_Text compare_text(longer_text.c_str());
Compare_Text compare_text2(compare_text, 2, 11);
TextBufferL bufferl;
Text textl(longer_text.c_str(), bufferl.data(), bufferl.size());
TextBuffer buffer;
Text text2(textl, buffer.data(), buffer.size(), 2, 12);
bool is_equal = Equal(compare_text2, text2);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(text2.is_truncated());
#endif
}
#if ETL_HAS_INITIALIZER_LIST
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_construct_initializer_list)
{
Compare_Text compare_text = { STR('H'), STR('e'), STR('l') , STR('l') , STR('o') };
std::initializer_list<Text::value_type> il = { STR('H'), STR('e'), STR('l') , STR('l') , STR('o') };
TextBuffer buffer;
Text text(il, buffer.data(), buffer.size());
bool is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_construct_initializer_list_excess)
{
Compare_Text compare_text = { STR('H'), STR('e'), STR('l'), STR('l'), STR('o'), STR(' '),
STR('W'), STR('o'), STR('r'), STR('l'), STR('d') };
std::initializer_list<Text::value_type> il = { STR('H'), STR('e'), STR('l'), STR('l'), STR('o'), STR(' '),
STR('W'), STR('o'), STR('r'), STR('l'), STR('d'), STR(' '),
STR('T'), STR('h'), STR('e'), STR('r'), STR('e') };
TextBuffer buffer;
Text text(il, buffer.data(), buffer.size());
bool is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(text.is_truncated());
#endif
}
#endif
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_assignment)
{
TextBuffer buffer;
Text text(initial_text.begin(), initial_text.end(), buffer.data(), buffer.size());
TextBuffer buffer2;
Text other_text(buffer2.data(), buffer2.size());
other_text = text;
bool is_equal = Equal(text, other_text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
CHECK(!other_text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_assignment_excess)
{
TextBuffer buffer;
Text text(longer_text.begin(), longer_text.end(), buffer.data(), buffer.size());
TextBuffer buffer2;
Text other_text(buffer2.data(), buffer2.size());
other_text = text;
bool is_equal = Equal(text, other_text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(text.is_truncated());
CHECK(other_text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_assignment_iterface)
{
TextBuffer buffer;
Text text1(initial_text.begin(), initial_text.end(), buffer.data(), buffer.size());
TextBuffer buffer2;
Text text2(buffer2.data(), buffer2.size());
IText& itext1 = text1;
IText& itext2 = text2;
itext2 = itext1;
bool is_equal = Equal(text1, text2);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text1.is_truncated());
CHECK(!text2.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_assignment_iterface_excess)
{
TextBuffer buffer;
Text text1(longer_text.begin(), longer_text.end(), buffer.data(), buffer.size());
TextBuffer buffer2;
Text text2(buffer2.data(), buffer2.size());
IText& itext1 = text1;
IText& itext2 = text2;
itext2 = itext1;
bool is_equal = Equal(text1, text2);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(text1.is_truncated());
CHECK(text2.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_self_assignment)
{
TextBuffer buffer;
Text text(initial_text.begin(), initial_text.end(), buffer.data(), buffer.size());
TextBuffer buffer2;
Text other_text(text, buffer2.data(), buffer2.size());
other_text = other_text;
bool is_equal = Equal(text, other_text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
CHECK(!other_text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_self_assignment_excess)
{
TextBuffer buffer;
Text text(longer_text.begin(), longer_text.end(), buffer.data(), buffer.size());
TextBuffer buffer2;
Text other_text(text, buffer2.data(), buffer2.size());
other_text = other_text;
bool is_equal = Equal(text, other_text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(text.is_truncated());
CHECK(other_text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_assignment_from_literal)
{
TextBuffer buffer;
Text text(buffer.data(), buffer.size());
text = STR("Hello World");
bool is_equal = Equal(std::string(STR("Hello World")), text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_assignment_from_literal_excess)
{
TextBuffer buffer;
Text text(buffer.data(), buffer.size());
text = STR("Hello World There");
bool is_equal = Equal(std::string(STR("Hello World")), text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_assignment_from_literal_via_interface)
{
TextBuffer buffer;
Text text(buffer.data(), buffer.size());
IText& itext = text;
itext = STR("Hello World");
bool is_equal = Equal(std::string(STR("Hello World")), itext);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!itext.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_assignment_from_literal_via_interface_excess)
{
TextBuffer buffer;
Text text(buffer.data(), buffer.size());
IText& itext = text;
itext = STR("Hello World There");
bool is_equal = Equal(std::string(STR("Hello World")), itext);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(itext.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_begin)
{
TextBuffer buffer;
Text text(initial_text.c_str(), buffer.data(), buffer.size());
TextBuffer buffer2;
const Text constText(initial_text.c_str(), buffer2.data(), buffer2.size());
CHECK_EQUAL(&text[0], text.begin());
CHECK_EQUAL(&constText[0], constText.begin());
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_end)
{
TextBuffer buffer;
Text text(initial_text.c_str(), buffer.data(), buffer.size());
TextBuffer buffer2;
const Text constText(initial_text.c_str(), buffer2.data(), buffer2.size());
CHECK_EQUAL(&text[initial_text.size()], text.end());
CHECK_EQUAL(&constText[initial_text.size()], constText.end());
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_resize_up)
{
const size_t INITIAL_SIZE = 5;
const size_t NEW_SIZE = 8;
TextBuffer buffer;
Text text(initial_text.c_str(), INITIAL_SIZE, buffer.data(), buffer.size());
text.resize(NEW_SIZE);
CHECK_EQUAL(text.size(), NEW_SIZE);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_resize_up_value)
{
const size_t INITIAL_SIZE = 5;
const size_t NEW_SIZE = 8;
const value_t INITIAL_VALUE = STR('A');
TextBuffer buffer;
Text text(INITIAL_SIZE, INITIAL_VALUE, buffer.data(), buffer.size());
text.resize(NEW_SIZE, INITIAL_VALUE);
std::array<value_t, NEW_SIZE> compare_text;
compare_text.fill(INITIAL_VALUE);
bool is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_resize_excess)
{
const size_t INITIAL_SIZE = 5;
const size_t NEW_SIZE = SIZE + 1;
TextBuffer buffer;
Text text(INITIAL_SIZE, STR('A'), buffer.data(), buffer.size());
text.resize(NEW_SIZE, STR('A'));
CHECK_EQUAL(SIZE, text.size());
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_resize_down)
{
const size_t INITIAL_SIZE = 5;
const size_t NEW_SIZE = 2;
TextBuffer buffer;
Text text(INITIAL_SIZE, STR('A'), buffer.data(), buffer.size());
text.resize(NEW_SIZE);
CHECK_EQUAL(text.size(), NEW_SIZE);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_resize_down_value)
{
const size_t INITIAL_SIZE = 5;
const size_t NEW_SIZE = 2;
const value_t INITIAL_VALUE = STR('A');
TextBuffer buffer;
Text text(INITIAL_SIZE, INITIAL_VALUE, buffer.data(), buffer.size());
text.resize(NEW_SIZE, INITIAL_VALUE);
CHECK_EQUAL(text.size(), NEW_SIZE);
std::array<value_t, NEW_SIZE> compare_text;
compare_text.fill(INITIAL_VALUE);
bool is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_uninitialized_resize_up)
{
const size_t INITIAL_SIZE = 5UL;
const size_t NEW_SIZE = 8;
const value_t INITIAL_VALUE = STR('A');
const value_t FILL_VALUE = STR('B');
TextBuffer buffer;
Text text(INITIAL_SIZE, INITIAL_VALUE, buffer.data(), buffer.size());
Text::pointer pbegin = &text.front();
Text::pointer pend = &text.back() + 1;
Text::pointer pmax = pbegin + text.max_size();
// Fill free space with a pattern.
std::fill(pend, pmax, FILL_VALUE);
text.uninitialized_resize(NEW_SIZE);
std::array<value_t, NEW_SIZE> compare_text;
compare_text.fill(FILL_VALUE);
std::fill(compare_text.begin(), compare_text.begin() + INITIAL_SIZE, INITIAL_VALUE);
bool is_equal = Equal(compare_text, text);
CHECK(is_equal);
CHECK_EQUAL(text.size(), NEW_SIZE);
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_uninitialized_resize_up_excess)
{
const size_t INITIAL_SIZE = 5;
const size_t NEW_SIZE = SIZE + 1;
TextBuffer buffer;
Text text(INITIAL_SIZE, STR('A'), buffer.data(), buffer.size());
text.uninitialized_resize(NEW_SIZE);
CHECK_EQUAL(text.size(), SIZE);
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_uninitialized_resize_down)
{
const size_t INITIAL_SIZE = 5UL;
const size_t NEW_SIZE = 2;
const value_t INITIAL_VALUE = STR('A');
const value_t FILL_VALUE = STR('B');
TextBuffer buffer;
Text text(INITIAL_SIZE, INITIAL_VALUE, buffer.data(), buffer.size());
Text::pointer pbegin = &text.front();
Text::pointer pend = &text.back() + 1;
Text::pointer pmax = pbegin + text.max_size();
// Fill free space with a pattern.
std::fill(pend, pmax, FILL_VALUE);
text.uninitialized_resize(NEW_SIZE);
std::array<value_t, NEW_SIZE> compare_text;
compare_text.fill(INITIAL_VALUE);
bool is_equal = Equal(compare_text, text);
CHECK(is_equal);
CHECK_EQUAL(text.size(), NEW_SIZE);
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_empty_full)
{
TextBuffer buffer;
Text text(buffer.data(), buffer.size());
text.resize(text.max_size(), STR('A'));
CHECK(!text.empty());
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_empty_half)
{
TextBuffer buffer;
Text text(buffer.data(), buffer.size());
text.resize(text.max_size() / 2, STR('A'));
CHECK(!text.empty());
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_empty_empty)
{
TextBuffer buffer;
Text text(buffer.data(), buffer.size());
CHECK(text.empty());
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_full_full)
{
TextBuffer buffer;
Text text(buffer.data(), buffer.size());
text.resize(text.max_size(), STR('A'));
CHECK(text.full());
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_full_half)
{
TextBuffer buffer;
Text text(buffer.data(), buffer.size());
text.resize(text.max_size() / 2, STR('A'));
CHECK(!text.full());
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_full_empty)
{
TextBuffer buffer;
Text text(buffer.data(), buffer.size());
CHECK(!text.full());
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_index)
{
Compare_Text compare_text(initial_text.c_str());
TextBuffer buffer;
Text text(initial_text.c_str(), buffer.data(), buffer.size());
for (size_t i = 0UL; i < text.size(); ++i)
{
CHECK_EQUAL(text[i], compare_text[i]);
}
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_index_const)
{
const Compare_Text compare_text(initial_text.c_str());
TextBuffer buffer;
const Text text(initial_text.c_str(), buffer.data(), buffer.size());
for (size_t i = 0UL; i < text.size(); ++i)
{
CHECK_EQUAL(text[i], compare_text[i]);
}
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_at)
{
Compare_Text compare_text(initial_text.c_str());
TextBuffer buffer;
Text text(initial_text.c_str(), buffer.data(), buffer.size());
for (size_t i = 0UL; i < text.size(); ++i)
{
CHECK_EQUAL(text.at(i), compare_text.at(i));
}
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
CHECK_THROW(text.at(text.size()), etl::string_out_of_bounds);
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_at_const)
{
const Compare_Text compare_text(initial_text.c_str());
TextBuffer buffer;
const Text text(initial_text.c_str(), buffer.data(), buffer.size());
for (size_t i = 0UL; i < text.size(); ++i)
{
CHECK_EQUAL(text.at(i), compare_text.at(i));
}
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
CHECK_THROW(text.at(text.size()), etl::string_out_of_bounds);
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_front)
{
Compare_Text compare_text(initial_text.c_str());
TextBuffer buffer;
Text text(initial_text.c_str(), buffer.data(), buffer.size());
CHECK(text.front() == compare_text.front());
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_front_const)
{
const Compare_Text compare_text(initial_text.c_str());
TextBuffer buffer;
const Text text(initial_text.c_str(), buffer.data(), buffer.size());
CHECK(text.front() == compare_text.front());
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_back)
{
Compare_Text compare_text(initial_text.c_str());
TextBuffer buffer;
Text text(initial_text.c_str(), buffer.data(), buffer.size());
CHECK(text.back() == compare_text.back());
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_back_const)
{
const Compare_Text compare_text(initial_text.c_str());
TextBuffer buffer;
const Text text(initial_text.c_str(), buffer.data(), buffer.size());
CHECK(text.back() == compare_text.back());
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_data)
{
Compare_Text compare_text(initial_text.c_str());
TextBuffer buffer;
Text text(compare_text.begin(), compare_text.end(), buffer.data(), buffer.size());
bool is_equal = std::equal(text.data(),
text.data() + text.size(),
compare_text.begin());
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_data_const)
{
Compare_Text compare_text(initial_text.c_str());
TextBuffer buffer;
const Text text(compare_text.begin(), compare_text.end(), buffer.data(), buffer.size());
bool is_equal = std::equal(text.data(),
text.data() + text.size(),
compare_text.begin());
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_assign_string)
{
Compare_Text compare_input(initial_text.c_str());
TextBuffer buffer;
Text input(initial_text.c_str(), buffer.data(), buffer.size());
Compare_Text compare_text;
TextBuffer buffer2;
Text text(buffer2.data(), buffer2.size());
compare_text.assign(compare_input);
text.assign(input);
bool is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_assign_string_excess)
{
Compare_Text compare_input(initial_text.c_str());
TextBufferL bufferl;
Text input(longer_text.c_str(), bufferl.data(), bufferl.size());
Compare_Text compare_text;
TextBuffer buffer;
Text text(buffer.data(), buffer.size());
compare_text.assign(compare_input);
text.assign(input);
bool is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_assign_pointer)
{
Compare_Text compare_text(initial_text.c_str());
TextBuffer buffer;
Text text(buffer.data(), buffer.size());
text.assign(initial_text.c_str());
bool is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_assign_pointer_excess)
{
Compare_Text compare_text(initial_text.c_str());
TextBuffer buffer;
Text text(buffer.data(), buffer.size());
text.assign(longer_text.c_str());
bool is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_assign_pointer_length)
{
Compare_Text compare_text(initial_text.c_str());
TextBuffer buffer;
Text text(buffer.data(), buffer.size());
text.assign(initial_text.c_str(), initial_text.size());
bool is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_assign_pointer_length_excess)
{
Compare_Text compare_text(longer_text.c_str());
TextBuffer buffer;
Text text(buffer.data(), buffer.size());
text.assign(longer_text.c_str(), longer_text.size());
compare_text.resize(text.max_size());
bool is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_assign_range)
{
Compare_Text compare_text(initial_text.c_str());
TextBuffer buffer;
Text text(buffer.data(), buffer.size());
text.assign(compare_text.begin(), compare_text.end());
bool is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_assign_range_excess)
{
TextBuffer buffer;
Text text(buffer.data(), buffer.size());
text.assign(longer_text.begin(), longer_text.end());
CHECK_EQUAL(initial_text.size(), text.size());
bool is_equal = Equal(initial_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_assign_size_value)
{
const size_t INITIAL_SIZE = 5;
const value_t INITIAL_VALUE = STR('A');
std::array<value_t, INITIAL_SIZE> compare_text;
compare_text.fill(INITIAL_VALUE);
TextBuffer buffer;
Text text(buffer.data(), buffer.size());
text.assign(INITIAL_SIZE, INITIAL_VALUE);
CHECK(text.size() == INITIAL_SIZE);
bool is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_assign_size_value_excess)
{
const size_t INITIAL_SIZE = SIZE;
const size_t EXCESS_SIZE = SIZE + 1;
const value_t INITIAL_VALUE = STR('A');
std::array<value_t, INITIAL_SIZE> compare_text;
compare_text.fill(INITIAL_VALUE);
TextBuffer buffer;
Text text(buffer.data(), buffer.size());
text.assign(EXCESS_SIZE, INITIAL_VALUE);
bool is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_push_back)
{
Compare_Text compare_text;
TextBuffer buffer;
Text text(buffer.data(), buffer.size());
for (size_t i = 0UL; i < SIZE; ++i)
{
compare_text.push_back(STR('A') + value_t(i));
}
for (size_t i = 0UL; i < SIZE; ++i)
{
text.push_back(STR('A') + value_t(i));
}
CHECK_EQUAL(etl::strlen(compare_text.data()), etl::strlen(text.data()));
CHECK_EQUAL(compare_text.size(), text.size());
bool is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_push_back_excess)
{
Compare_Text compare_text;
TextBuffer buffer;
Text text(buffer.data(), buffer.size());
for (size_t i = 0UL; i < SIZE; ++i)
{
compare_text.push_back(STR('A') + value_t(i));
}
for (size_t i = 0UL; i < SIZE; ++i)
{
text.push_back(STR('A') + value_t(i));
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
}
text.push_back(STR('A') + value_t(SIZE));
CHECK_EQUAL(etl::strlen(compare_text.data()), etl::strlen(text.data()));
CHECK_EQUAL(compare_text.size(), text.size());
bool is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_pop_back)
{
Compare_Text compare_text(initial_text.c_str());
TextBuffer buffer;
Text text(initial_text.c_str(), buffer.data(), buffer.size());
compare_text.pop_back();
compare_text.pop_back();
text.pop_back();
text.pop_back();
CHECK_EQUAL(compare_text.size(), text.size());
bool is_equal = Equal(compare_text, text);
CHECK(is_equal);
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_insert_position_value)
{
const size_t INITIAL_SIZE = 5;
const value_t INITIAL_VALUE = STR('A');
for (size_t offset = 0; offset <= INITIAL_SIZE; ++offset)
{
Compare_Text compare_text;
TextBuffer buffer;
Text text(buffer.data(), buffer.size());
text.assign(initial_text.begin(), initial_text.begin() + INITIAL_SIZE);
compare_text.assign(initial_text.begin(), initial_text.begin() + INITIAL_SIZE);
text.insert(text.begin() + offset, INITIAL_VALUE);
compare_text.insert(compare_text.begin() + offset, INITIAL_VALUE);
CHECK_EQUAL(compare_text.size(), text.size());
bool is_equal = Equal(compare_text, text);
CHECK(is_equal);
}
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_insert_position_value_excess)
{
Compare_Text compare_text(initial_text.begin(), initial_text.end());
TextBuffer buffer;
Text text(initial_text.begin(), initial_text.end(), buffer.data(), buffer.size());
const value_t INITIAL_VALUE = STR('A');
size_t offset = 2UL;
text.insert(text.cbegin() + offset, INITIAL_VALUE);
compare_text.insert(compare_text.cbegin() + offset, INITIAL_VALUE);
compare_text.erase(compare_text.cend() - 1);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(text.is_truncated());
#endif
bool is_equal = Equal(compare_text, text);
CHECK(is_equal);
offset = 0;
text.insert(text.cbegin() + offset, STR('A'));
compare_text.insert(compare_text.cbegin() + offset, STR('A'));
compare_text.erase(compare_text.cend() - 1);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(text.is_truncated());
#endif
is_equal = Equal(compare_text, text);
CHECK(is_equal);
offset = text.size();
text.insert(text.cbegin() + offset, STR('A'));
compare_text.insert(compare_text.cbegin() + offset, STR('A'));
compare_text.erase(compare_text.cend() - 1);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(text.is_truncated());
#endif
is_equal = Equal(compare_text, text);
CHECK(is_equal);
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_insert_position_n_value)
{
Compare_Text compare_text;
TextBuffer buffer;
Text text(buffer.data(), buffer.size());
const size_t INITIAL_SIZE = 5UL;
const size_t INSERT_SIZE = 3UL;
const value_t INITIAL_VALUE = STR('A');
for (size_t offset = 0UL; offset <= INITIAL_SIZE; ++offset)
{
text.assign(initial_text.begin(), initial_text.begin() + INITIAL_SIZE);
compare_text.assign(initial_text.begin(), initial_text.begin() + INITIAL_SIZE);
text.insert(text.begin() + offset, INSERT_SIZE, INITIAL_VALUE);
compare_text.insert(compare_text.begin() + offset, INSERT_SIZE, INITIAL_VALUE);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
bool is_equal = Equal(compare_text, text);
CHECK(is_equal);
}
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_insert_position_n_value_excess)
{
Compare_Text compare_text;
TextBuffer buffer;
Text text(buffer.data(), buffer.size());
const size_t INSERT_SIZE = 4UL;
const value_t INSERT_VALUE = STR('A');
size_t offset = 0UL;
compare_text.assign(initial_text.cbegin(), initial_text.cend());
text.assign(initial_text.cbegin(), initial_text.cend());
compare_text.insert(compare_text.cbegin() + offset, INSERT_SIZE, INSERT_VALUE);
compare_text.erase(compare_text.cend() - INSERT_SIZE, compare_text.cend());
text.insert(text.cbegin() + offset, INSERT_SIZE, INSERT_VALUE);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(text.is_truncated());
#endif
bool is_equal = Equal(compare_text, text);
CHECK(is_equal);
offset = 2;
compare_text.assign(initial_text.cbegin(), initial_text.cend());
text.assign(initial_text.cbegin(), initial_text.cend());
compare_text.insert(compare_text.cbegin() + offset, INSERT_SIZE, INSERT_VALUE);
compare_text.erase(compare_text.cend() - INSERT_SIZE, compare_text.cend());
text.assign(initial_text.cbegin(), initial_text.cend());
text.insert(text.cbegin() + offset, INSERT_SIZE, INSERT_VALUE);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(text.is_truncated());
#endif
is_equal = Equal(compare_text, text);
CHECK(is_equal);
offset = 4;
compare_text.assign(initial_text.cbegin(), initial_text.cend());
text.assign(initial_text.cbegin(), initial_text.cend());
compare_text.insert(compare_text.cbegin() + offset, INSERT_SIZE, INSERT_VALUE);
compare_text.erase(compare_text.cend() - INSERT_SIZE, compare_text.cend());
text.assign(initial_text.cbegin(), initial_text.cend());
text.insert(text.cbegin() + offset, INSERT_SIZE, INSERT_VALUE);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(text.is_truncated());
#endif
is_equal = Equal(compare_text, text);
CHECK(is_equal);
offset = text.size();
compare_text.assign(initial_text.cbegin(), initial_text.cend());
text.assign(initial_text.cbegin(), initial_text.cend());
compare_text.insert(compare_text.cbegin() + offset, INSERT_SIZE, INSERT_VALUE);
compare_text.erase(compare_text.cend() - INSERT_SIZE, compare_text.cend());
text.assign(initial_text.cbegin(), initial_text.cend());
text.insert(text.cbegin() + offset, INSERT_SIZE, INSERT_VALUE);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(text.is_truncated());
#endif
is_equal = Equal(compare_text, text);
CHECK(is_equal);
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_insert_position_range)
{
const size_t INITIAL_SIZE = 5UL;
for (size_t offset = 0UL; offset <= INITIAL_SIZE; ++offset)
{
Compare_Text compare_text;
TextBuffer buffer;
Text text(buffer.data(), buffer.size());
text.assign(initial_text.cbegin(), initial_text.cbegin() + INITIAL_SIZE);
compare_text.assign(initial_text.cbegin(), initial_text.cbegin() + INITIAL_SIZE);
text.insert(text.cbegin() + offset, insert_text.cbegin(), insert_text.cend());
compare_text.insert(compare_text.cbegin() + offset, insert_text.cbegin(), insert_text.cend());
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
bool is_equal = Equal(compare_text, text);
CHECK(is_equal);
}
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_insert_position_range_excess)
{
const size_t INITIAL_SIZE = 5UL;
const value_t INITIAL_VALUE = STR('A');
Compare_Text compare_text;
TextBuffer buffer;
Text text(buffer.data(), buffer.size());
size_t offset = 0UL;
compare_text.assign(INITIAL_SIZE, INITIAL_VALUE);
text.assign(INITIAL_SIZE, INITIAL_VALUE);
compare_text.insert(compare_text.cbegin() + offset, initial_text.cbegin(), initial_text.cend());
compare_text.resize(initial_text.size());
text.insert(text.cbegin() + offset, initial_text.cbegin(), initial_text.cend());
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(text.is_truncated());
#endif
bool is_equal = Equal(compare_text, text);
CHECK(is_equal);
offset = 2;
compare_text.assign(INITIAL_SIZE, INITIAL_VALUE);
text.assign(INITIAL_SIZE, INITIAL_VALUE);
compare_text.insert(compare_text.cbegin() + offset, initial_text.cbegin(), initial_text.cend());
compare_text.resize(initial_text.size());
text.insert(text.cbegin() + offset, initial_text.cbegin(), initial_text.cend());
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(text.is_truncated());
#endif
is_equal = Equal(compare_text, text);
CHECK(is_equal);
offset = 4;
compare_text.assign(INITIAL_SIZE, INITIAL_VALUE);
text.assign(INITIAL_SIZE, INITIAL_VALUE);
compare_text.insert(compare_text.cbegin() + offset, initial_text.cbegin(), initial_text.cend());
compare_text.resize(initial_text.size());
text.insert(text.cbegin() + offset, initial_text.cbegin(), initial_text.cend());
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(text.is_truncated());
#endif
CHECK_EQUAL(compare_text.size(), text.size());
is_equal = Equal(compare_text, text);
CHECK(is_equal);
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_insert_position_range_self)
{
size_t length = SIZE_L / 2;
for (size_t offset = 10UL; offset < length; ++offset)
{
Compare_Text compare_text = STR("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
TextBufferL bufferl;
Text text(bufferl.data(), bufferl.size());
text = STR("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
text.insert(text.cbegin() + offset, text.cbegin() + 5, text.cbegin() + 10);
compare_text.insert(compare_text.cbegin() + offset, compare_text.cbegin() + 5, compare_text.cbegin() + 10);
bool is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
}
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_insert_size_t_position_string)
{
for (size_t offset = 0UL; offset <= short_text.size(); ++offset)
{
Compare_Text compare_text(short_text.cbegin(), short_text.cend());
TextBuffer buffer;
Text text(short_text.begin(), short_text.end(), buffer.data(), buffer.size());
TextBuffer buffer2;
Text insert(insert_text.begin(), insert_text.end(), buffer2.data(), buffer2.size());
text.insert(offset, insert);
compare_text.insert(offset, insert_text);
compare_text.resize(std::min(compare_text.size(), SIZE));
bool is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
}
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_insert_size_t_position_string_excess)
{
for (size_t offset = 0UL; offset <= initial_text.size(); ++offset)
{
Compare_Text compare_text(initial_text.cbegin(), initial_text.cend());
TextBuffer buffer;
Text text(initial_text.begin(), initial_text.end(), buffer.data(), buffer.size());
TextBuffer buffer2;
Text insert(insert_text.begin(), insert_text.end(), buffer2.data(), buffer2.size());
text.insert(offset, insert);
compare_text.insert(offset, insert_text);
compare_text.resize(std::min(compare_text.size(), SIZE));
bool is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(text.is_truncated());
#endif
}
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_insert_size_t_position_string_from_truncated)
{
for (size_t offset = 0UL; offset <= short_text.size(); ++offset)
{
Compare_Text compare_text(short_text.cbegin(), short_text.cend());
TextBuffer buffer;
Text text(short_text.begin(), short_text.end(), buffer.data(), buffer.size());
TextBuffer buffer2;
Text insert(longer_text.begin(), longer_text.end(), buffer2.data(), buffer2.size());
insert.erase(insert.cbegin(), insert.cend());
insert.append(insert_text.cbegin(), insert_text.cend());
text.insert(offset, insert);
compare_text.insert(offset, insert_text);
compare_text.resize(std::min(compare_text.size(), SIZE));
bool is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(text.is_truncated());
#endif
}
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_insert_size_t_position_string_subpos_sunlen)
{
Compare_Text compare_text(short_text.cbegin(), short_text.cend());
TextBuffer buffer;
Text text(short_text.begin(), short_text.end(), buffer.data(), buffer.size());
TextBuffer buffer2;
Text insert(insert_text.begin(), insert_text.end(), buffer2.data(), buffer2.size());
text.insert(0, insert, 0, insert.size());
compare_text.insert(0, insert_text, 0, insert_text.size());
compare_text.resize(std::min(compare_text.size(), SIZE));
bool is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
compare_text.assign(short_text.cbegin(), short_text.cend());
text.assign(short_text.cbegin(), short_text.cend());
text.insert(2, insert, 2, insert.size() - 2);
compare_text.insert(2, insert_text, 2, insert_text.size() - 2);
compare_text.resize(std::min(compare_text.size(), SIZE));
CHECK_EQUAL(compare_text.size(), text.size());
is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
compare_text.assign(short_text.cbegin(), short_text.cend());
text.assign(short_text.cbegin(), short_text.cend());
text.insert(short_text.size(), insert, 0, insert.size());
compare_text.insert(short_text.size(), insert_text, 0, insert_text.size());
compare_text.resize(std::min(compare_text.size(), SIZE));
is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_append_string)
{
Compare_Text compare_text(short_text.c_str());
TextBuffer buffer;
Text text(short_text.c_str(), buffer.data(), buffer.size());
TextBuffer buffer2;
Text append(insert_text.c_str(), buffer2.data(), buffer2.size());
// Non-overflow.
compare_text.append(insert_text);
text.append(append);
bool is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
// Overflow.
compare_text.assign(short_text.c_str());
text.assign(short_text.c_str());
append.assign(initial_text.c_str());
compare_text.append(initial_text);
compare_text.resize(std::min(compare_text.size(), SIZE));
text.append(append);
is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_append_truncated_string)
{
TextBuffer buffer;
Text text(short_text.c_str(), buffer.data(), buffer.size());
TextBufferS buffers;
Text append(short_text.c_str(), buffers.data(), buffers.size());
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(append.is_truncated());
#endif
text.append(append);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_append_string_to_self)
{
Compare_Text compare_text(short_text.c_str());
TextBuffer buffer;
Text text(short_text.c_str(), buffer.data(), buffer.size());
// Non-overflow.
compare_text.append(compare_text);
text.append(text);
bool is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
// Overflow.
compare_text.assign(shorter_text.c_str());
text.assign(shorter_text.c_str());
compare_text.append(compare_text);
compare_text.resize(std::min(compare_text.size(), SIZE));
text.append(text);
is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_append_string_subpos_sublen)
{
Compare_Text compare_text(short_text.c_str());
TextBuffer buffer;
Text text(short_text.c_str(), buffer.data(), buffer.size());
TextBuffer buffer2;
Text append(insert_text.c_str(), buffer2.data(), buffer2.size());
// Whole string.
compare_text.append(insert_text, 0, std::string::npos);
text.append(append, 0, Text::npos);
bool is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
// Partial string.
compare_text.assign(short_text.c_str());
text.assign(short_text.c_str());
append.assign(initial_text.c_str());
compare_text.append(short_text, 1, 3);
compare_text.resize(std::min(compare_text.size(), SIZE));
text.append(append, 1, 3);
is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
// Overflow.
compare_text.assign(short_text.c_str());
text.assign(short_text.c_str());
append.assign(initial_text.c_str());
compare_text.append(initial_text, 1, initial_text.size());
compare_text.resize(std::min(compare_text.size(), SIZE));
text.append(append, 1, append.size());
is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_append_truncated_string_subpos_sublen)
{
TextBuffer buffer;
Text text(short_text.c_str(), buffer.data(), buffer.size());
TextBufferS buffer2;
Text append(short_text.c_str(), buffer2.data(), buffer2.size());
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(append.is_truncated());
#endif
text.append(append, 1, 2);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_append_c_string)
{
// Non-overflow.
Compare_Text compare_text(short_text.c_str());
TextBuffer buffer;
Text text(short_text.c_str(), buffer.data(), buffer.size());
// Whole string.
compare_text.append(insert_text.c_str());
text.append(insert_text.c_str());
bool is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
// Overflow.
compare_text.assign(short_text.c_str());
text.assign(short_text.c_str());
compare_text.append(initial_text.c_str());
compare_text.resize(std::min(compare_text.size(), SIZE));
text.append(initial_text.c_str());
is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_append_n_c)
{
// Non-overflow.
Compare_Text compare_text(short_text.c_str());
TextBuffer buffer;
Text text(short_text.c_str(), buffer.data(), buffer.size());
// Non-overflow.
compare_text.append(5, STR('A'));
text.append(5, STR('A'));
bool is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
// Overflow.
compare_text.assign(short_text.c_str());
text.assign(short_text.c_str());
compare_text.append(SIZE, STR('A'));
compare_text.resize(std::min(compare_text.size(), SIZE));
text.append(SIZE, STR('A'));
is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_append_range)
{
// Non-overflow.
Compare_Text compare_text(short_text.c_str());
TextBuffer buffer;
Text text(short_text.c_str(), buffer.data(), buffer.size());
TextBuffer buffer2;
Text append(insert_text.c_str(), buffer2.data(), buffer2.size());
compare_text.append(insert_text.begin(), insert_text.end());
text.append(append.begin(), append.end());
bool is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
// Overflow.
compare_text.assign(short_text.c_str());
text.assign(short_text.c_str());
append.assign(initial_text.c_str());
compare_text.append(initial_text.begin(), initial_text.end());
compare_text.resize(std::min(compare_text.size(), SIZE));
text.append(append.begin(), append.end());
is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_replace_position_length_string)
{
// Non-overflow short text, npos.
Compare_Text compare_text(short_text.c_str());
TextBuffer buffer;
Text text(short_text.c_str(), buffer.data(), buffer.size());
compare_text.replace(2, Compare_Text::npos, Compare_Text(STR("Replace")));
compare_text.resize(std::min(compare_text.size(), SIZE));
text.replace(2, Text::npos, TextT(STR("Replace")));
bool is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
// Non-overflow short text.
compare_text.assign(short_text.c_str());
text.assign(short_text.c_str());
compare_text.replace(2, 2, Compare_Text(STR("Replace")));
compare_text.resize(std::min(compare_text.size(), SIZE));
text.replace(2, 2, TextT(STR("Replace")));
is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
// Overflow short text.
compare_text.assign(short_text.c_str());
text.assign(short_text.c_str());
compare_text.replace(2, 2, Compare_Text(STR("Replace with some text")));
compare_text.resize(std::min(compare_text.size(), SIZE));
text.replace(2, 2, TextT(STR("Replace with some text")));
is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(text.is_truncated());
#endif
// Overflow short text, npos.
compare_text.assign(short_text.c_str());
text.assign(short_text.c_str());
compare_text.replace(2, Compare_Text::npos, Compare_Text(STR("Replace with some text")));
compare_text.resize(std::min(compare_text.size(), SIZE));
text.replace(2, Text::npos, TextT(STR("Replace with some text")));
is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(text.is_truncated());
#endif
// Non-overflow.
compare_text.assign(initial_text.c_str());
text.assign(initial_text.c_str());
compare_text.replace(2, 7, Compare_Text(STR("Replace")));
compare_text.resize(std::min(compare_text.size(), SIZE));
text.replace(2, 7, TextT(STR("Replace")));
is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
// Overflow.
compare_text.assign(initial_text.c_str());
text.assign(initial_text.c_str());
compare_text.replace(2, 2, Compare_Text(STR("Replace with some text")));
compare_text.resize(std::min(compare_text.size(), SIZE));
text.replace(2, 2, TextT(STR("Replace with some text")));
is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(text.is_truncated());
#endif
// Overflow, npos.
compare_text.assign(initial_text.c_str());
text.assign(initial_text.c_str());
compare_text.replace(2, Compare_Text::npos, Compare_Text(STR("Replace with some text")));
compare_text.resize(std::min(compare_text.size(), SIZE));
text.replace(2, Text::npos, TextT(STR("Replace with some text")));
is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_replace_first_last_string)
{
// Non-overflow short text.
Compare_Text compare_text(short_text.c_str());
TextBuffer buffer;
Text text(short_text.c_str(), buffer.data(), buffer.size());
compare_text.replace(compare_text.begin() + 2, compare_text.begin() + 4, Compare_Text(STR("Replace")));
compare_text.resize(std::min(compare_text.size(), SIZE));
text.replace(text.begin() + 2, text.begin() + 4, TextT(STR("Replace")));
bool is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
// Overflow short text.
compare_text.assign(short_text.c_str());
text.assign(short_text.c_str());
compare_text.replace(compare_text.begin() + 2, compare_text.begin() + 4, Compare_Text(STR("Replace with some text")));
compare_text.resize(std::min(compare_text.size(), SIZE));
text.replace(text.begin() + 2, text.begin() + 4, TextT(STR("Replace with some text")));
is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(text.is_truncated());
#endif
// Non-overflow.
compare_text.assign(initial_text.c_str());
text.assign(initial_text.c_str());
compare_text.replace(compare_text.begin() + 2, compare_text.begin() + 9, Compare_Text(STR("Replace")));
compare_text.resize(std::min(compare_text.size(), SIZE));
text.replace(text.begin() + 2, text.begin() + 9, TextT(STR("Replace")));
is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
// Overflow.
compare_text.assign(initial_text.c_str());
text.assign(initial_text.c_str());
compare_text.replace(compare_text.begin() + 2, compare_text.begin() + 4, Compare_Text(STR("Replace with some text")));
compare_text.resize(std::min(compare_text.size(), SIZE));
text.replace(text.begin() + 2, text.begin() + 4, TextT(STR("Replace with some text")));
is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_replace_position_length_string_subposition_sublength)
{
// Non-overflow short text.
Compare_Text compare_text(short_text.c_str());
TextBuffer buffer;
Text text(short_text.c_str(), buffer.data(), buffer.size());
compare_text.replace(2, 4, Compare_Text(STR("Replace")), 1, 5);
compare_text.resize(std::min(compare_text.size(), SIZE));
text.replace(2, 4, TextT(STR("Replace")), 1, 5);
bool is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
// Non-overflow short text, npos.
compare_text.assign(short_text.c_str());
text.assign(short_text.c_str());
compare_text.replace(2, Compare_Text::npos, Compare_Text(STR("Replace")), 1, Compare_Text::npos);
compare_text.resize(std::min(compare_text.size(), SIZE));
text.replace(2, Text::npos, TextT(STR("Replace")), 1, Text::npos);
is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
// Overflow short text.
compare_text.assign(short_text.c_str());
text.assign(short_text.c_str());
compare_text.replace(2, 4, Compare_Text(STR("Replace with some text")), 1, 15);
compare_text.resize(std::min(compare_text.size(), SIZE));
text.replace(2, 4, TextT(STR("Replace with some text")), 1, 15);
is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(text.is_truncated());
#endif
// Overflow short text, npos.
compare_text.assign(short_text.c_str());
text.assign(short_text.c_str());
compare_text.replace(2, Compare_Text::npos, Compare_Text(STR("Replace with some text")), 1, Compare_Text::npos);
compare_text.resize(std::min(compare_text.size(), SIZE));
text.replace(2, Text::npos, TextT(STR("Replace with some text")), 1, Text::npos);
is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(text.is_truncated());
#endif
// Non-overflow.
compare_text.assign(initial_text.c_str());
text.assign(initial_text.c_str());
compare_text.replace(2, 7, Compare_Text(STR("Replace")), 1, 5);
compare_text.resize(std::min(compare_text.size(), SIZE));
text.replace(2, 7, TextT(STR("Replace")), 1, 5);
is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
// Non-overflow, npos.
compare_text.assign(initial_text.c_str());
text.assign(initial_text.c_str());
compare_text.replace(2, Compare_Text::npos, Compare_Text(STR("Replace")), 1, Compare_Text::npos);
compare_text.resize(std::min(compare_text.size(), SIZE));
text.replace(2, Text::npos, TextT(STR("Replace")), 1, Text::npos);
is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
// Overflow.
compare_text.assign(initial_text.c_str());
text.assign(initial_text.c_str());
compare_text.replace(2, 4, Compare_Text(STR("Replace with some text")), 1, 15);
compare_text.resize(std::min(compare_text.size(), SIZE));
text.replace(2, 4, TextT(STR("Replace with some text")), 1, 15);
is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(text.is_truncated());
#endif
// Overflow, npos.
compare_text.assign(initial_text.c_str());
text.assign(initial_text.c_str());
compare_text.replace(2, Compare_Text::npos, Compare_Text(STR("Replace with some text")), 1, Compare_Text::npos);
compare_text.resize(std::min(compare_text.size(), SIZE));
text.replace(2, Text::npos, TextT(STR("Replace with some text")), 1, Text::npos);
is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_replace_position_length_pointer)
{
// Non-overflow short text.
Compare_Text compare_text(short_text.c_str());
TextBuffer buffer;
Text text(short_text.c_str(), buffer.data(), buffer.size());
compare_text.replace(2, 4, Compare_Text(STR("Replace")).c_str());
compare_text.resize(std::min(compare_text.size(), SIZE));
text.replace(2, 4, TextT(STR("Replace")).c_str());
bool is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
// Non-overflow short text, npos.
compare_text.assign(short_text.c_str());
text.assign(short_text.c_str());
compare_text.replace(2, Compare_Text::npos, Compare_Text(STR("Replace")).c_str());
compare_text.resize(std::min(compare_text.size(), SIZE));
text.replace(2, Text::npos, TextT(STR("Replace")).c_str());
is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
// Overflow short text.
compare_text.assign(short_text.c_str());
text.assign(short_text.c_str());
compare_text.replace(2, 4, Compare_Text(STR("Replace with some text")).c_str());
compare_text.resize(std::min(compare_text.size(), SIZE));
text.replace(2, 4, TextT(STR("Replace with some text")).c_str());
is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(text.is_truncated());
#endif
// Overflow short text, npos.
compare_text.assign(short_text.c_str());
text.assign(short_text.c_str());
compare_text.replace(2, Compare_Text::npos, Compare_Text(STR("Replace with some text")).c_str());
compare_text.resize(std::min(compare_text.size(), SIZE));
text.replace(2, Text::npos, TextT(STR("Replace with some text")).c_str());
is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(text.is_truncated());
#endif
// Non-overflow.
compare_text.assign(initial_text.c_str());
text.assign(initial_text.c_str());
compare_text.replace(2, 7, Compare_Text(STR("Replace")).c_str());
compare_text.resize(std::min(compare_text.size(), SIZE));
text.replace(2, 7, TextT(STR("Replace")).c_str());
is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
// Non-overflow, npos.
compare_text.assign(initial_text.c_str());
text.assign(initial_text.c_str());
compare_text.replace(2, Compare_Text::npos, Compare_Text(STR("Replace")).c_str());
compare_text.resize(std::min(compare_text.size(), SIZE));
text.replace(2, Text::npos, TextT(STR("Replace")).c_str());
is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
// Overflow.
compare_text.assign(initial_text.c_str());
text.assign(initial_text.c_str());
compare_text.replace(2, 4, Compare_Text(STR("Replace with some text")).c_str());
compare_text.resize(std::min(compare_text.size(), SIZE));
text.replace(2, 4, TextT(STR("Replace with some text")).c_str());
is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(text.is_truncated());
#endif
// Overflow, npos.
compare_text.assign(initial_text.c_str());
text.assign(initial_text.c_str());
compare_text.replace(2, Compare_Text::npos, Compare_Text(STR("Replace with some text")).c_str());
compare_text.resize(std::min(compare_text.size(), SIZE));
text.replace(2, Text::npos, TextT(STR("Replace with some text")).c_str());
is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_replace_first_last_pointer)
{
// Non-overflow short text.
Compare_Text compare_text(short_text.c_str());
TextBuffer buffer;
Text text(short_text.c_str(), buffer.data(), buffer.size());
compare_text.replace(compare_text.begin() + 2, compare_text.begin() + 4, Compare_Text(STR("Replace")).c_str());
compare_text.resize(std::min(compare_text.size(), SIZE));
text.replace(text.begin() + 2, text.begin() + 4, TextT(STR("Replace")).c_str());
bool is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
// Overflow short text.
compare_text.assign(short_text.c_str());
text.assign(short_text.c_str());
compare_text.replace(compare_text.begin() + 2, compare_text.begin() + 4, Compare_Text(STR("Replace with some text")).c_str());
compare_text.resize(std::min(compare_text.size(), SIZE));
text.replace(text.begin() + 2, text.begin() + 4, TextT(STR("Replace with some text")).c_str());
is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(text.is_truncated());
#endif
// Non-overflow.
compare_text.assign(initial_text.c_str());
text.assign(initial_text.c_str());
compare_text.replace(compare_text.begin() + 2, compare_text.begin() + 9, Compare_Text(STR("Replace")).c_str());
compare_text.resize(std::min(compare_text.size(), SIZE));
text.replace(text.begin() + 2, text.begin() + 9, TextT(STR("Replace")).c_str());
is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
// Overflow.
compare_text.assign(initial_text.c_str());
text.assign(initial_text.c_str());
compare_text.replace(compare_text.begin() + 2, compare_text.begin() + 4, Compare_Text(STR("Replace with some text")).c_str());
compare_text.resize(std::min(compare_text.size(), SIZE));
text.replace(text.begin() + 2, text.begin() + 4, TextT(STR("Replace with some text")).c_str());
is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_replace_position_length_pointer_n)
{
// Non-overflow short text.
Compare_Text compare_text(short_text.c_str());
TextBuffer buffer;
Text text(short_text.c_str(), buffer.data(), buffer.size());
compare_text.replace(2, 4, Compare_Text(STR("Replace")).c_str(), 5);
compare_text.resize(std::min(compare_text.size(), SIZE));
text.replace(2, 4, TextT(STR("Replace")).c_str(), 5);
bool is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
// Non-overflow short text, npos.
compare_text.assign(short_text.c_str());
text.assign(short_text.c_str());
compare_text.replace(2, Compare_Text::npos, Compare_Text(STR("Replace")).c_str(), 5);
compare_text.resize(std::min(compare_text.size(), SIZE));
text.replace(2, Text::npos, TextT(STR("Replace")).c_str(), 5);
is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
// Overflow short text.
compare_text.assign(short_text.c_str());
text.assign(short_text.c_str());
compare_text.replace(2, 4, Compare_Text(STR("Replace with some text")).c_str(), 15);
compare_text.resize(std::min(compare_text.size(), SIZE));
text.replace(2, 4, TextT(STR("Replace with some text")).c_str(), 15);
is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(text.is_truncated());
#endif
// Overflow short text, npos.
compare_text.assign(short_text.c_str());
text.assign(short_text.c_str());
compare_text.replace(2, Compare_Text::npos, Compare_Text(STR("Replace with some text")).c_str(), 15);
compare_text.resize(std::min(compare_text.size(), SIZE));
text.replace(2, Text::npos, TextT(STR("Replace with some text")).c_str(), 15);
is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(text.is_truncated());
#endif
// Non-overflow.
compare_text.assign(initial_text.c_str());
text.assign(initial_text.c_str());
compare_text.replace(2, 7, Compare_Text(STR("Replace")).c_str(), 5);
compare_text.resize(std::min(compare_text.size(), SIZE));
text.replace(2, 7, TextT(STR("Replace")).c_str(), 5);
is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
// Non-overflow, npos.
compare_text.assign(initial_text.c_str());
text.assign(initial_text.c_str());
compare_text.replace(2, Compare_Text::npos, Compare_Text(STR("Replace")).c_str(), 5);
compare_text.resize(std::min(compare_text.size(), SIZE));
text.replace(2, Text::npos, TextT(STR("Replace")).c_str(), 5);
is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
// Overflow.
compare_text.assign(initial_text.c_str());
text.assign(initial_text.c_str());
compare_text.replace(2, 4, Compare_Text(STR("Replace with some text")).c_str(), 15);
compare_text.resize(std::min(compare_text.size(), SIZE));
text.replace(2, 4, TextT(STR("Replace with some text")).c_str(), 15);
is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(text.is_truncated());
#endif
// Overflow, npos.
compare_text.assign(initial_text.c_str());
text.assign(initial_text.c_str());
compare_text.replace(2, Compare_Text::npos, Compare_Text(STR("Replace with some text")).c_str(), 15);
compare_text.resize(std::min(compare_text.size(), SIZE));
text.replace(2, Text::npos, TextT(STR("Replace with some text")).c_str(), 15);
is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_replace_first_last_pointer_n)
{
// Non-overflow short text.
Compare_Text compare_text(short_text.c_str());
TextBuffer buffer;
Text text(short_text.c_str(), buffer.data(), buffer.size());
compare_text.replace(compare_text.begin() + 2, compare_text.begin() + 4, Compare_Text(STR("Replace")).c_str(), 5);
compare_text.resize(std::min(compare_text.size(), SIZE));
text.replace(text.begin() + 2, text.begin() + 4, TextT(STR("Replace")).c_str(), 5);
bool is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
// Overflow short text.
compare_text.assign(short_text.c_str());
text.assign(short_text.c_str());
compare_text.replace(compare_text.begin() + 2, compare_text.begin() + 4, Compare_Text(STR("Replace with some text")).c_str(), 15);
compare_text.resize(std::min(compare_text.size(), SIZE));
text.replace(text.begin() + 2, text.begin() + 4, TextT(STR("Replace with some text")).c_str(), 15);
is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(text.is_truncated());
#endif
// Non-overflow.
compare_text.assign(initial_text.c_str());
text.assign(initial_text.c_str());
compare_text.replace(compare_text.begin() + 2, compare_text.begin() + 9, Compare_Text(STR("Replace")).c_str(), 5);
compare_text.resize(std::min(compare_text.size(), SIZE));
text.replace(text.begin() + 2, text.begin() + 9, TextT(STR("Replace")).c_str(), 5);
is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
// Overflow.
compare_text.assign(initial_text.c_str());
text.assign(initial_text.c_str());
compare_text.replace(compare_text.begin() + 2, compare_text.begin() + 4, Compare_Text(STR("Replace with some text")).c_str(), 15);
compare_text.resize(std::min(compare_text.size(), SIZE));
text.replace(text.begin() + 2, text.begin() + 4, TextT(STR("Replace with some text")).c_str(), 15);
is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_replace_position_length_n_c)
{
// Non-overflow short text.
Compare_Text compare_text(short_text.c_str());
TextBuffer buffer;
Text text(short_text.c_str(), buffer.data(), buffer.size());
compare_text.replace(2, 4, 7, STR('A'));
compare_text.resize(std::min(compare_text.size(), SIZE));
text.replace(2, 4, 7, STR('A'));
bool is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
// Non-overflow short text, npos.
compare_text.assign(short_text.c_str());
text.assign(short_text.c_str());
compare_text.replace(2, Compare_Text::npos, 7, STR('A'));
compare_text.resize(std::min(compare_text.size(), SIZE));
text.replace(2, Text::npos, 7, STR('A'));
is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
// Overflow short text.
compare_text.assign(short_text.c_str());
text.assign(short_text.c_str());
compare_text.replace(2, 4, 15, STR('A'));
compare_text.resize(std::min(compare_text.size(), SIZE));
text.replace(2, 4, 15, STR('A'));
is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(text.is_truncated());
#endif
// Overflow short text, npos.
compare_text.assign(short_text.c_str());
text.assign(short_text.c_str());
compare_text.replace(2, Compare_Text::npos, 15, STR('A'));
compare_text.resize(std::min(compare_text.size(), SIZE));
text.replace(2, Text::npos, 15, STR('A'));
is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(text.is_truncated());
#endif
// Non-overflow.
compare_text.assign(initial_text.c_str());
text.assign(initial_text.c_str());
compare_text.replace(2, 7, 7, STR('A'));
compare_text.resize(std::min(compare_text.size(), SIZE));
text.replace(2, 7, 7, STR('A'));
is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
// Non-overflow, npos.
compare_text.assign(initial_text.c_str());
text.assign(initial_text.c_str());
compare_text.replace(2, Compare_Text::npos, 7, STR('A'));
compare_text.resize(std::min(compare_text.size(), SIZE));
text.replace(2, Text::npos, 7, STR('A'));
is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
// Overflow.
compare_text.assign(initial_text.c_str());
text.assign(initial_text.c_str());
compare_text.replace(2, 4, 15, STR('A'));
compare_text.resize(std::min(compare_text.size(), SIZE));
text.replace(2, 4, 15, STR('A'));
is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(text.is_truncated());
#endif
// Overflow, npos.
compare_text.assign(initial_text.c_str());
text.assign(initial_text.c_str());
compare_text.replace(2, Compare_Text::npos, 15, STR('A'));
compare_text.resize(std::min(compare_text.size(), SIZE));
text.replace(2, Text::npos, 15, STR('A'));
is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_replace_first_last_n_c)
{
// Non-overflow short text.
Compare_Text compare_text(short_text.c_str());
TextBuffer buffer;
Text text(short_text.c_str(), buffer.data(), buffer.size());
compare_text.replace(compare_text.begin() + 2, compare_text.begin() + 4, 7, STR('A'));
compare_text.resize(std::min(compare_text.size(), SIZE));
text.replace(text.begin() + 2, text.begin() + 4, 7, STR('A'));
bool is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
// Overflow short text.
compare_text.assign(short_text.c_str());
text.assign(short_text.c_str());
compare_text.replace(compare_text.begin() + 2, compare_text.begin() + 4, 15, STR('A'));
compare_text.resize(std::min(compare_text.size(), SIZE));
text.replace(text.begin() + 2, text.begin() + 4, 15, STR('A'));
is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(text.is_truncated());
#endif
// Non-overflow.
compare_text.assign(initial_text.c_str());
text.assign(initial_text.c_str());
compare_text.replace(compare_text.begin() + 2, compare_text.begin() + 9, 7, STR('A'));
compare_text.resize(std::min(compare_text.size(), SIZE));
text.replace(text.begin() + 2, text.begin() + 9, 7, STR('A'));
is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
// Overflow.
compare_text.assign(initial_text.c_str());
text.assign(initial_text.c_str());
compare_text.replace(compare_text.begin() + 2, compare_text.begin() + 4, 15, STR('A'));
compare_text.resize(std::min(compare_text.size(), SIZE));
text.replace(text.begin() + 2, text.begin() + 4, 15, STR('A'));
is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_replace_first_last_first_last)
{
// Non-overflow short text.
Compare_Text compare_text(short_text.c_str());
TextBuffer buffer;
Text text(short_text.c_str(), buffer.data(), buffer.size());
Compare_Text replace(STR("Replace"));
Compare_Text replace_long(STR("Replace with some text"));
compare_text.replace(compare_text.begin() + 2, compare_text.begin() + 4, replace.begin() + 1, replace.begin() + 5);
compare_text.resize(std::min(compare_text.size(), SIZE));
text.replace(text.begin() + 2, text.begin() + 4, replace.begin() + 1, replace.begin() + 5);
bool is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
// Overflow short text.
compare_text.assign(short_text.c_str());
text.assign(short_text.c_str());
compare_text.replace(compare_text.begin() + 2, compare_text.begin() + 4, replace_long.begin() + 1, replace_long.begin() + 15);
compare_text.resize(std::min(compare_text.size(), SIZE));
text.replace(text.begin() + 2, text.begin() + 4, replace_long.begin() + 1, replace_long.begin() + 15);
is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(text.is_truncated());
#endif
// Non-overflow.
compare_text.assign(initial_text.c_str());
text.assign(initial_text.c_str());
compare_text.replace(compare_text.begin() + 2, compare_text.begin() + 7, replace.begin() + 1, replace.begin() + 5);
compare_text.resize(std::min(compare_text.size(), SIZE));
text.replace(text.begin() + 2, text.begin() + 7, replace_long.begin() + 1, replace_long.begin() + 5);
is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
// Overflow.
compare_text.assign(initial_text.c_str());
text.assign(initial_text.c_str());
compare_text.replace(compare_text.begin() + 2, compare_text.begin() + 4, replace_long.begin() + 1, replace_long.begin() + 15);
compare_text.resize(std::min(compare_text.size(), SIZE));
text.replace(text.begin() + 2, text.begin() + 4, replace_long.begin() + 1, replace_long.begin() + 15);
is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_erase_single)
{
Compare_Text compare_text(initial_text.c_str());
TextBuffer buffer;
Text text(initial_text.c_str(), buffer.data(), buffer.size());
compare_text.erase(compare_text.begin() + 2);
text.erase(text.begin() + 2);
bool is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_erase_range)
{
Compare_Text compare_text(initial_text.c_str());
TextBuffer buffer;
Text text(initial_text.c_str(), buffer.data(), buffer.size());
compare_text.erase(compare_text.begin() + 2, compare_text.begin() + 4);
text.erase(text.begin() + 2, text.begin() + 4);
bool is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_clear)
{
TextBuffer buffer;
Text text(initial_text.c_str(), buffer.data(), buffer.size());
text.clear();
CHECK_EQUAL(text.size(), size_t(0));
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_iterator)
{
Compare_Text compare_text(initial_text.c_str());
TextBuffer buffer;
Text text(initial_text.c_str(), buffer.data(), buffer.size());
bool is_equal = std::equal(text.begin(), text.end(), compare_text.begin());
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_const_iterator)
{
Compare_Text compare_text(initial_text.c_str());
TextBuffer buffer;
Text text(initial_text.c_str(), buffer.data(), buffer.size());
bool is_equal = std::equal(text.cbegin(), text.cend(), compare_text.cbegin());
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_reverse_iterator)
{
Compare_Text compare_text(initial_text.c_str());
TextBuffer buffer;
Text text(initial_text.c_str(), buffer.data(), buffer.size());
bool is_equal = std::equal(text.rbegin(), text.rend(), compare_text.rbegin());
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_const_reverse_iterator)
{
Compare_Text compare_text(initial_text.c_str());
TextBuffer buffer;
Text text(initial_text.c_str(), buffer.data(), buffer.size());
bool is_equal = std::equal(text.crbegin(), text.crend(), compare_text.crbegin());
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_equal)
{
TextBuffer buffer;
const Text initial1(initial_text.c_str(), buffer.data(), buffer.size());
TextBuffer buffer2;
const Text initial2(initial_text.c_str(), buffer2.data(), buffer2.size());
CHECK(initial1 == initial2);
TextBuffer buffer3;
const Text different(different_text.c_str(), buffer3.data(), buffer3.size());
CHECK(!(initial1 == different));
TextBuffer buffer4;
const Text shorter(shorter_text.c_str(), buffer4.data(), buffer4.size());
CHECK(!(shorter == initial1));
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_not_equal)
{
TextBuffer buffer;
const Text initial1(initial_text.c_str(), buffer.data(), buffer.size());
TextBuffer buffer2;
const Text initial2(initial_text.c_str(), buffer2.data(), buffer2.size());
CHECK(!(initial1 != initial2));
TextBuffer buffer3;
const Text different(different_text.begin(), different_text.end(), buffer3.data(), buffer3.size());
CHECK(initial1 != different);
TextBuffer buffer4;
const Text shorter(shorter_text.begin(), shorter_text.end(), buffer4.data(), buffer4.size());
CHECK(shorter != initial1);
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_less_than)
{
TextBuffer buffer;
const Text less(less_text.c_str(), buffer.data(), buffer.size());
TextBuffer buffer2;
const Text initial(initial_text.c_str(), buffer2.data(), buffer2.size());
// String-String
CHECK((less < initial) == (less_text < initial_text));
CHECK((initial < less) == (initial_text < less_text));
TextBuffer buffer3;
const Text greater(greater_text.c_str(), buffer3.data(), buffer3.size());
CHECK((greater < initial) == (greater_text < initial_text));
CHECK((initial < greater) == (initial_text < greater_text));
TextBuffer buffer4;
const Text shorter(shorter_text.c_str(), buffer4.data(), buffer4.size());
CHECK((shorter < initial) == (shorter_text < initial_text));
CHECK((initial < shorter) == (initial_text < shorter_text));
CHECK((initial < initial) == (initial_text < initial_text));
CHECK((initial < initial) == (initial_text < initial_text));
// String-Pointer Pointer-String
CHECK((less < pinitial_text) == (less_text < pinitial_text));
CHECK((pinitial_text < less) == (pinitial_text < less_text));
CHECK((greater < pinitial_text) == (greater_text < pinitial_text));
CHECK((pinitial_text < greater) == (pinitial_text < greater_text));
CHECK((shorter < pinitial_text) == (shorter_text < pinitial_text));
CHECK((pinitial_text < shorter) == (pinitial_text < shorter_text));
CHECK((initial < pinitial_text) == (initial_text < pinitial_text));
CHECK((pinitial_text < initial) == (pinitial_text < initial_text));
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_less_than_or_equal)
{
TextBuffer buffer;
const Text less(less_text.c_str(), buffer.data(), buffer.size());
TextBuffer buffer2;
const Text initial(initial_text.c_str(), buffer2.data(), buffer2.size());
// String-String
CHECK((less <= initial) == (less_text <= initial_text));
CHECK((initial <= less) == (initial_text <= less_text));
TextBuffer buffer3;
const Text greater(greater_text.c_str(), buffer3.data(), buffer3.size());
CHECK((greater <= initial) == (greater_text <= initial_text));
CHECK((initial <= greater) == (initial_text <= greater_text));
TextBuffer buffer4;
const Text shorter(shorter_text.c_str(), buffer4.data(), buffer4.size());
CHECK((shorter <= initial) == (shorter_text <= initial_text));
CHECK((initial <= shorter) == (initial_text <= shorter_text));
CHECK((initial <= initial) == (initial_text <= initial_text));
CHECK((initial <= initial) == (initial_text <= initial_text));
// String-Pointer Pointer-String
CHECK((less <= pinitial_text) == (less_text <= pinitial_text));
CHECK((pinitial_text <= less) == (pinitial_text <= less_text));
CHECK((greater <= pinitial_text) == (greater_text <= pinitial_text));
CHECK((pinitial_text <= greater) == (pinitial_text <= greater_text));
CHECK((shorter <= pinitial_text) == (shorter_text <= pinitial_text));
CHECK((pinitial_text <= shorter) == (pinitial_text <= shorter_text));
CHECK((initial <= pinitial_text) == (initial_text <= pinitial_text));
CHECK((pinitial_text <= initial) == (pinitial_text <= initial_text));
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_greater_than)
{
TextBuffer buffer;
const Text less(less_text.c_str(), buffer.data(), buffer.size());
TextBuffer buffer2;
const Text initial(initial_text.c_str(), buffer2.data(), buffer2.size());
// String-String
CHECK((less > initial) == (less_text > initial_text));
CHECK((initial > less) == (initial_text > less_text));
TextBuffer buffer3;
const Text greater(greater_text.c_str(), buffer3.data(), buffer3.size());
CHECK((greater > initial) == (greater_text > initial_text));
CHECK((initial > greater) == (initial_text > greater_text));
TextBuffer buffer4;
const Text shorter(shorter_text.c_str(), buffer4.data(), buffer4.size());
CHECK((shorter > initial) == (shorter_text > initial_text));
CHECK((initial > shorter) == (initial_text > shorter_text));
CHECK((initial > initial) == (initial_text > initial_text));
CHECK((initial > initial) == (initial_text > initial_text));
// String-Pointer Pointer-String
CHECK((less > pinitial_text) == (less_text > pinitial_text));
CHECK((pinitial_text > less) == (pinitial_text > less_text));
CHECK((greater > pinitial_text) == (greater_text > pinitial_text));
CHECK((pinitial_text > greater) == (pinitial_text > greater_text));
CHECK((shorter > pinitial_text) == (shorter_text > pinitial_text));
CHECK((pinitial_text > shorter) == (pinitial_text > shorter_text));
CHECK((initial > pinitial_text) == (initial_text > pinitial_text));
CHECK((pinitial_text > initial) == (pinitial_text > initial_text));
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_greater_than_or_equal)
{
TextBuffer buffer;
const Text less(less_text.begin(), less_text.end(), buffer.data(), buffer.size());
TextBuffer buffer2;
const Text initial(initial_text.begin(), initial_text.end(), buffer2.data(), buffer2.size());
// String-String
CHECK((less >= initial) == (less_text >= initial_text));
CHECK((initial >= less) == (initial_text >= less_text));
TextBuffer buffer3;
const Text greater(greater_text.begin(), greater_text.end(), buffer3.data(), buffer3.size());
CHECK((greater >= initial) == (greater_text >= initial_text));
CHECK((initial >= greater) == (initial_text >= greater_text));
TextBuffer buffer4;
const Text shorter(shorter_text.begin(), shorter_text.end(), buffer4.data(), buffer4.size());
CHECK((shorter >= initial) == (shorter_text >= initial_text));
CHECK((initial >= shorter) == (initial_text > shorter_text));
CHECK((initial >= initial) == (initial_text >= initial_text));
CHECK((initial >= initial) == (initial_text >= initial_text));
// String-Pointer Pointer-String
CHECK((less >= pinitial_text) == (less_text >= pinitial_text));
CHECK((pinitial_text >= less) == (pinitial_text >= less_text));
CHECK((greater >= pinitial_text) == (greater_text >= pinitial_text));
CHECK((pinitial_text >= greater) == (pinitial_text >= greater_text));
CHECK((shorter >= pinitial_text) == (shorter_text >= pinitial_text));
CHECK((pinitial_text >= shorter) == (pinitial_text >= shorter_text));
CHECK((initial >= pinitial_text) == (initial_text >= pinitial_text));
CHECK((pinitial_text >= initial) == (pinitial_text >= initial_text));
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_copy)
{
Compare_Text compare_text(initial_text.c_str());
TextBuffer buffer;
Text text(initial_text.c_str(), buffer.data(), buffer.size());
value_t buffer1[SIZE];
value_t buffer2[SIZE];
size_t length1 = compare_text.copy(buffer1, 5, 2);
buffer1[length1] = STR('\0');
size_t length2 = text.copy(buffer2, 5, 2);
buffer2[length2] = STR('\0');
CHECK_EQUAL(length1, length2);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
bool is_equal = std::equal(buffer1,
buffer1 + length1,
buffer2);
CHECK(is_equal);
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_copy_start_pos_too_large)
{
TextBuffer buffer;
Text text(initial_text.c_str(), buffer.data(), buffer.size());
value_t buffer1[SIZE];
size_t length1 = text.copy(buffer1, 5, SIZE);
CHECK_EQUAL(0U, length1);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_copy_count_equals_npos)
{
Compare_Text compare_text(initial_text.c_str());
TextBuffer buffer;
Text text(initial_text.c_str(), buffer.data(), buffer.size());
value_t buffer1[SIZE];
value_t buffer2[SIZE];
size_t length1 = compare_text.copy(buffer1, Compare_Text::npos, 2);
buffer1[length1] = STR('\0');
size_t length2 = text.copy(buffer2, Text::npos, 2);
buffer2[length2] = STR('\0');
CHECK_EQUAL(length1, length2);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
bool is_equal = std::equal(buffer1,
buffer1 + length1,
buffer2);
CHECK(is_equal);
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_copy_count_too_large)
{
Compare_Text compare_text(initial_text.c_str());
TextBuffer buffer;
Text text(initial_text.c_str(), buffer.data(), buffer.size());
value_t buffer1[SIZE];
value_t buffer2[SIZE];
size_t length1 = compare_text.copy(buffer1, SIZE, 2);
buffer1[length1] = STR('\0');
size_t length2 = text.copy(buffer2, SIZE, 2);
buffer2[length2] = STR('\0');
CHECK_EQUAL(length1, length2);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
bool is_equal = std::equal(buffer1,
buffer1 + length1,
buffer2);
CHECK(is_equal);
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_find_string)
{
const value_t* the_haystack = STR("A haystack with a needle and another needle");
std::string compare_needle(STR("needle"));
TextBuffer buffer;
Text needle(STR("needle"), buffer.data(), buffer.size());
std::string compare_haystack(the_haystack);
TextBufferL buffer2;
Text haystack(the_haystack, buffer2.data(), buffer2.size());
size_t position1 = 0;
size_t position2 = 0;
position1 = compare_haystack.find(compare_needle, position1);
position2 = haystack.find(needle, position2);
CHECK_EQUAL(position1, position2);
position1 = compare_haystack.find(compare_needle, position1 + 1);
position2 = haystack.find(needle, position2 + 1);
CHECK_EQUAL(position1, position2);
position2 = haystack.find(needle, position2 + 1);
CHECK_EQUAL(etl::string<50>::npos, position2);
etl::string<50> pin(STR("pin"));
position2 = haystack.find(pin);
CHECK_EQUAL(IText::npos, position2);
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_find_pointer)
{
const value_t* the_haystack = STR("A haystack with a needle and another needle");
const value_t* needle = STR("needle");
std::string compare_haystack(the_haystack);
TextBufferL buffer;
Text haystack(the_haystack, buffer.data(), buffer.size());
size_t position1 = 0;
size_t position2 = 0;
position1 = compare_haystack.find(needle, position1);
position2 = haystack.find(needle, position2);
CHECK_EQUAL(position1, position2);
position1 = compare_haystack.find(needle, position1 + 1);
position2 = haystack.find(needle, position2 + 1);
CHECK_EQUAL(position1, position2);
position2 = haystack.find(needle, position2 + 1);
CHECK_EQUAL(IText::npos, position2);
const value_t *pin = STR("pin");
position2 = haystack.find(pin);
CHECK_EQUAL(IText::npos, position2);
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_find_char_pointer_n)
{
const value_t* the_haystack = STR("A haystack with a needle and another needle");
const value_t* needle = STR("needle");
std::string compare_haystack(the_haystack);
TextBufferL buffer;
Text haystack(the_haystack, buffer.data(), buffer.size());
size_t position1 = 0;
size_t position2 = 0;
position1 = compare_haystack.find(needle, position1, 3);
position2 = haystack.find(needle, position2, 3);
CHECK_EQUAL(position1, position2);
position1 = compare_haystack.find(needle, position1 + 1, 3);
position2 = haystack.find(needle, position2 + 1, 3);
CHECK_EQUAL(position1, position2);
position2 = haystack.find(needle, position2 + 1, 3);
CHECK_EQUAL(IText::npos, position2);
const value_t *pin = STR("pin");
position2 = haystack.find(pin, 0, 3);
CHECK_EQUAL(IText::npos, position2);
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_rfind_string)
{
const value_t* the_haystack = STR("A haystack with a needle and another needle");
std::string compare_needle(STR("needle"));
TextBufferL buffer;
Text needle(STR("needle"), buffer.data(), buffer.size());
std::string compare_haystack(the_haystack);
TextBufferL buffer2;
Text haystack(the_haystack, buffer2.data(), buffer2.size());
size_t position1 = std::string::npos;
size_t position2 = etl::string<50>::npos;
position1 = compare_haystack.rfind(compare_needle, position1);
position2 = haystack.rfind(needle, position2);
CHECK_EQUAL(position1, position2);
position1 = compare_haystack.rfind(compare_needle, compare_haystack.size() - 10);
position2 = haystack.rfind(needle, haystack.size() - 10);
CHECK_EQUAL(position1, position2);
TextBufferL buffer3;
Text pin(STR("pin"), buffer3.data(), buffer3.size());
position2 = haystack.rfind(pin);
CHECK_EQUAL(IText::npos, position2);
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_rfind_pointer)
{
const value_t*the_haystack = STR("A haystack with a needle and another needle");
std::string compare_haystack(the_haystack);
TextBufferL buffer;
Text haystack(the_haystack, buffer.data(), buffer.size());
const value_t* needle = STR("needle");
size_t position1 = std::string::npos;
size_t position2 = etl::string<50>::npos;
position1 = compare_haystack.rfind(needle, position1);
position2 = haystack.rfind(needle, position2);
CHECK_EQUAL(position1, position2);
position1 = compare_haystack.rfind(needle, compare_haystack.size() - 10);
position2 = haystack.rfind(needle, haystack.size() - 10);
CHECK_EQUAL(position1, position2);
TextBufferL buffer2;
Text pin(STR("pin"), buffer2.data(), buffer2.size());
position2 = haystack.rfind(pin);
CHECK_EQUAL(IText::npos, position2);
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_rfind_pointer_n)
{
const value_t*the_haystack = STR("A haystack with a needle and another needle");
std::string compare_haystack(the_haystack);
TextBufferL buffer;
Text haystack(the_haystack, buffer.data(), buffer.size());
const value_t* needle = STR("needle");
size_t position1 = std::string::npos;
size_t position2 = Text::npos;
position1 = compare_haystack.rfind(needle, position1, 3);
position2 = haystack.rfind(needle, position2, 3);
CHECK_EQUAL(position1, position2);
position1 = compare_haystack.rfind(needle, compare_haystack.size() - 10, 3);
position2 = haystack.rfind(needle, haystack.size() - 10, 3);
CHECK_EQUAL(position1, position2);
position2 = haystack.rfind(STR("pin"), 3);
CHECK_EQUAL(IText::npos, position2);
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_rfind_c_position)
{
const value_t*the_haystack = STR("A haystack with a needle and another needle");
std::string compare_haystack(the_haystack);
TextBufferL buffer;
Text haystack(the_haystack, buffer.data(), buffer.size());
size_t position1 = std::string::npos;
size_t position2 = etl::string<50>::npos;
position1 = compare_haystack.rfind(STR('e'), position1);
position2 = haystack.rfind(STR('e'), position2);
CHECK_EQUAL(position1, position2);
position1 = compare_haystack.rfind(STR('e'), compare_haystack.size() - 10);
position2 = haystack.rfind(STR('e'), haystack.size() - 10);
CHECK_EQUAL(position1, position2);
position2 = haystack.rfind(STR('z'));
CHECK_EQUAL(IText::npos, position2);
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_compare_string)
{
Compare_Text compare_text(STR("ABCDEF"));
TextBuffer buffer;
Text text(STR("ABCDEF"), buffer.data(), buffer.size());
int compare_result;
int result;
// Equal.
compare_result = compare_text.compare(Compare_Text(STR("ABCDEF")));
result = text.compare(TextT(STR("ABCDEF")));
CHECK(compares_agree(compare_result, result));
// Less.
compare_result = compare_text.compare(Compare_Text(STR("ABCDEE")));
result = text.compare(TextT(STR("ABCDEE")));
CHECK(compares_agree(compare_result, result));
// Greater.
compare_result = compare_text.compare(Compare_Text(STR("ABCDEG")));
result = text.compare(TextT(STR("ABCDEG")));
CHECK(compares_agree(compare_result, result));
// Shorter.
compare_result = compare_text.compare(Compare_Text(STR("ABCDE")));
result = text.compare(TextT(STR("ABCDE")));
CHECK(compares_agree(compare_result, result));
// Longer.
compare_result = compare_text.compare(Compare_Text(STR("ABCDEFG")));
result = text.compare(TextT(STR("ABCDEFG")));
CHECK(compares_agree(compare_result, result));
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_compare_positon_length_string)
{
Compare_Text compare_text(STR("xxxABCDEFyyy"));
TextBuffer buffer;
Text text(STR("xxxABCDEFyyy"), buffer.data(), buffer.size());
int compare_result;
int result;
// Equal.
compare_result = compare_text.compare(3, 6, Compare_Text(STR("ABCDEF")));
result = text.compare(3, 6, TextT(STR("ABCDEF")));
CHECK(compares_agree(compare_result, result));
// Less.
compare_result = compare_text.compare(3, 6, Compare_Text(STR("ABCDEE")));
result = text.compare(3, 6, TextT(STR("ABCDEE")));
CHECK(compares_agree(compare_result, result));
// Greater.
compare_result = compare_text.compare(3, 6, Compare_Text(STR("ABCDEG")));
result = text.compare(3, 6, TextT(STR("ABCDEG")));
CHECK(compares_agree(compare_result, result));
// Shorter.
compare_result = compare_text.compare(3, 6, Compare_Text(STR("ABCDE")));
result = text.compare(3, 6, TextT(STR("ABCDE")));
CHECK(compares_agree(compare_result, result));
// Longer.
compare_result = compare_text.compare(3, 6, Compare_Text(STR("ABCDEFG")));
result = text.compare(3, 6, TextT(STR("ABCDEFG")));
CHECK(compares_agree(compare_result, result));
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_compare_positon_length_string_subposition_sublength)
{
Compare_Text compare_text(STR("xxxABCDEFyyy"));
TextBuffer buffer;
Text text(STR("xxxABCDEFyyy"), buffer.data(), buffer.size());
int compare_result;
int result;
// Equal.
compare_result = compare_text.compare(3, 6, Compare_Text(STR("aaABCDEFbb")), 2, 6);
result = text.compare(3, 6, TextT(STR("aaABCDEFbb")), 2, 6);
CHECK(compares_agree(compare_result, result));
// Less.
compare_result = compare_text.compare(3, 6, Compare_Text(STR("aaABCDEEbb")), 2, 6);
result = text.compare(3, 6, TextT(STR("aaABCDEEbb")), 2, 6);
CHECK(compares_agree(compare_result, result));
// Greater.
compare_result = compare_text.compare(3, 6, Compare_Text(STR("aaABCDEGbb")), 2, 6);
result = text.compare(3, 6, TextT(STR("aaABCDEGbb")), 2, 6);
CHECK(compares_agree(compare_result, result));
// Shorter.
compare_result = compare_text.compare(3, 6, Compare_Text(STR("aaABCDEbb")), 2, 5);
result = text.compare(3, 6, TextT(STR("aaABCDEbb")), 2, 5);
CHECK(compares_agree(compare_result, result));
// Longer.
compare_result = compare_text.compare(3, 6, Compare_Text(STR("aaABCDEFGbb")), 2, 7);
result = text.compare(3, 6, TextT(STR("aaABCDEFGbb")), 2, 7);
CHECK(compares_agree(compare_result, result));
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_compare_c_string)
{
Compare_Text compare_text(STR("ABCDEF"));
TextBuffer buffer;
Text text(STR("ABCDEF"), buffer.data(), buffer.size());
int compare_result;
int result;
// Equal.
compare_result = compare_text.compare(STR("ABCDEF"));
result = text.compare(STR("ABCDEF"));
CHECK(compares_agree(compare_result, result));
// Less.
compare_result = compare_text.compare(STR("ABCDEE"));
result = text.compare(STR("ABCDEE"));
CHECK(compares_agree(compare_result, result));
// Greater.
compare_result = compare_text.compare(STR("ABCDEG"));
result = text.compare(STR("ABCDEG"));
CHECK(compares_agree(compare_result, result));
// Shorter.
compare_result = compare_text.compare(STR("ABCDE"));
result = text.compare(STR("ABCDE"));
CHECK(compares_agree(compare_result, result));
// Longer.
compare_result = compare_text.compare(STR("ABCDEFG"));
result = text.compare(STR("ABCDEFG"));
CHECK(compares_agree(compare_result, result));
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_compare_positon_length_c_string)
{
Compare_Text compare_text(STR("xxxABCDEFyyy"));
TextBuffer buffer;
Text text(STR("xxxABCDEFyyy"), buffer.data(), buffer.size());
int compare_result;
int result;
// Equal.
compare_result = compare_text.compare(3, 6, STR("ABCDEF"));
result = text.compare(3, 6, STR("ABCDEF"));
CHECK(compares_agree(compare_result, result));
// Less.
compare_result = compare_text.compare(3, 6, STR("ABCDEE"));
result = text.compare(3, 6, STR("ABCDEE"));
CHECK(compares_agree(compare_result, result));
// Greater.
compare_result = compare_text.compare(3, 6, STR("ABCDEG"));
result = text.compare(3, 6, STR("ABCDEG"));
CHECK(compares_agree(compare_result, result));
// Shorter.
compare_result = compare_text.compare(3, 6, STR("ABCDE"));
result = text.compare(3, 6, STR("ABCDE"));
CHECK(compares_agree(compare_result, result));
// Longer.
compare_result = compare_text.compare(3, 6, STR("ABCDEFG"));
result = text.compare(3, 6, STR("ABCDEFG"));
CHECK(compares_agree(compare_result, result));
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_compare_positon_length_c_string_n)
{
Compare_Text compare_text(STR("xxxABCDEFyyy"));
TextBuffer buffer;
Text text(STR("xxxABCDEFyyy"), buffer.data(), buffer.size());
int compare_result;
int result;
// Equal.
compare_result = compare_text.compare(3, 6, STR("ABCDEFbb"), 6);
result = text.compare(3, 6, STR("ABCDEFbb"), 6);
CHECK(compares_agree(compare_result, result));
// Less.
compare_result = compare_text.compare(3, 6, STR("ABCDEEbb"), 6);
result = text.compare(3, 6, STR("ABCDEEbb"), 6);
CHECK(compares_agree(compare_result, result));
// Greater.
compare_result = compare_text.compare(3, 6, STR("ABCDEGbb"), 6);
result = text.compare(3, 6, STR("ABCDEGbb"), 6);
CHECK(compares_agree(compare_result, result));
// Shorter.
compare_result = compare_text.compare(3, 6, STR("ABCDEbb"), 5);
result = text.compare(3, 6, STR("ABCDEbb"), 5);
CHECK(compares_agree(compare_result, result));
// Longer.
compare_result = compare_text.compare(3, 6, STR("ABCDEFGbb"), 7);
result = text.compare(3, 6, STR("ABCDEFGbb"), 7);
CHECK(compares_agree(compare_result, result));
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_find_first_of_string_position)
{
Compare_Text compare_text(STR("ABCDEF"));
TextBuffer buffer;
Text text(STR("ABCDEF"), buffer.data(), buffer.size());
size_t position1 = compare_text.find_first_of(Compare_Text(STR("ZCXF")));
size_t position2 = text.find_first_of(TextT(STR("ZCXF")));
CHECK_EQUAL(position1, position2);
position1 = compare_text.find_first_of(Compare_Text(STR("WXYZ")));
position2 = text.find_first_of(TextT(STR("WXYZ")));
CHECK_EQUAL(position1, position2);
position1 = compare_text.find_first_of(Compare_Text(STR("ZCXF")), 3);
position2 = text.find_first_of(TextT(STR("ZCXF")), 3);
CHECK_EQUAL(position1, position2);
position1 = compare_text.find_first_of(Compare_Text(STR("ZCXF")), 100);
position2 = text.find_first_of(TextT(STR("ZCXF")), 100);
CHECK_EQUAL(position1, position2);
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_find_first_of_pointer_position)
{
Compare_Text compare_text(STR("ABCDEF"));
TextBuffer buffer;
Text text(STR("ABCDEF"), buffer.data(), buffer.size());
size_t position1 = compare_text.find_first_of(STR("ZCXF"));
size_t position2 = text.find_first_of(STR("ZCXF"));
CHECK_EQUAL(position1, position2);
position1 = compare_text.find_first_of(STR("WXYZ"));
position2 = text.find_first_of(STR("WXYZ"));
CHECK_EQUAL(position1, position2);
position1 = compare_text.find_first_of(STR("ZCXF"), 3);
position2 = text.find_first_of(STR("ZCXF"), 3);
CHECK_EQUAL(position1, position2);
position1 = compare_text.find_first_of(STR("ZCXF"), 100);
position2 = text.find_first_of(STR("ZCXF"), 100);
CHECK_EQUAL(position1, position2);
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_find_first_of_pointer_position_n)
{
Compare_Text compare_text(STR("ABCDEF"));
TextBuffer buffer;
Text text(STR("ABCDEF"), buffer.data(), buffer.size());
size_t position1 = compare_text.find_first_of(STR("ZCXF"), 0, 4);
size_t position2 = text.find_first_of(STR("ZCXF"), 0, 4);
CHECK_EQUAL(position1, position2);
position1 = compare_text.find_first_of(STR("WXYZ"), 0, 4);
position2 = text.find_first_of(STR("WXYZ"), 0, 4);
CHECK_EQUAL(position1, position2);
position1 = compare_text.find_first_of(STR("ZCXF"), 1, 3);
position2 = text.find_first_of(STR("ZCXF"), 1, 3);
CHECK_EQUAL(position1, position2);
position1 = compare_text.find_first_of(STR("ZCXF"), 3, 3);
position2 = text.find_first_of(STR("ZCXF"), 3, 3);
CHECK_EQUAL(position1, position2);
position1 = compare_text.find_first_of(STR("ZCXF"), 100);
position2 = text.find_first_of(STR("ZCXF"), 100);
CHECK_EQUAL(position1, position2);
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_find_first_of_character_position)
{
Compare_Text compare_text(STR("ABCDEF"));
TextBuffer buffer;
Text text(STR("ABCDEF"), buffer.data(), buffer.size());
size_t position1 = compare_text.find_first_of(STR('C'));
size_t position2 = text.find_first_of(STR('C'));
CHECK_EQUAL(position1, position2);
position1 = compare_text.find_first_of(STR('Z'));
position2 = text.find_first_of(STR('Z'));
CHECK_EQUAL(position1, position2);
position1 = compare_text.find_first_of(STR('F'), 3);
position2 = text.find_first_of(STR('F'), 3);
CHECK_EQUAL(position1, position2);
position1 = compare_text.find_first_of(STR('C'), 3);
position2 = text.find_first_of(STR('C'), 3);
CHECK_EQUAL(position1, position2);
position1 = compare_text.find_first_of(STR('C'), compare_text.size());
position2 = text.find_first_of(STR('C'), text.size());
CHECK_EQUAL(position1, position2);
position1 = compare_text.find_first_of(STR('C'), 100);
position2 = text.find_first_of(STR('C'), 100);
CHECK_EQUAL(position1, position2);
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_find_last_of_string_position)
{
Compare_Text compare_text(STR("ABCDEFABCDE"));
TextBuffer buffer;
Text text(STR("ABCDEFABCDE"), buffer.data(), buffer.size());
size_t position1 = compare_text.find_last_of(Compare_Text(STR("ZCXE")));
size_t position2 = text.find_last_of(TextT(STR("ZCXE")));
CHECK_EQUAL(position1, position2);
position1 = compare_text.find_last_of(Compare_Text(STR("WXYZ")), 3);
position2 = text.find_last_of(TextT(STR("WXYZ")), 3);
CHECK_EQUAL(position1, position2);
position1 = compare_text.find_last_of(Compare_Text(STR("ZCXE")), 5);
position2 = text.find_last_of(TextT(STR("ZCXE")), 5);
CHECK_EQUAL(position1, position2);
position1 = compare_text.find_last_of(Compare_Text(STR("ZCXE")), compare_text.size());
position2 = text.find_last_of(TextT(STR("ZCXE")), text.size());
CHECK_EQUAL(position1, position2);
position1 = compare_text.find_last_of(Compare_Text(STR("ZCXE")), 100);
position2 = text.find_last_of(TextT(STR("ZCXE")), 100);
CHECK_EQUAL(position1, position2);
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_find_last_of_pointer_position)
{
Compare_Text compare_text(STR("ABCDEFABCDE"));
TextBuffer buffer;
Text text(STR("ABCDEFABCDE"), buffer.data(), buffer.size());
size_t position1 = compare_text.find_last_of(STR("ZCXE"));
size_t position2 = text.find_last_of(STR("ZCXE"));
CHECK_EQUAL(position1, position2);
position1 = compare_text.find_last_of(STR("WXYZ"), 3);
position2 = text.find_last_of(STR("WXYZ"), 3);
CHECK_EQUAL(position1, position2);
position1 = compare_text.find_last_of(STR("ZCXE"), 5);
position2 = text.find_last_of(STR("ZCXE"), 5);
CHECK_EQUAL(position1, position2);
position1 = compare_text.find_last_of(STR("ZCXE"), 6);
position2 = text.find_last_of(STR("ZCXE"), 6);
CHECK_EQUAL(position1, position2);
position1 = compare_text.find_last_of(STR("ZCXE"), compare_text.size());
position2 = text.find_last_of(STR("ZCXE"), text.size());
CHECK_EQUAL(position1, position2);
position1 = compare_text.find_last_of(STR("ZCXE"), 100);
position2 = text.find_last_of(STR("ZCXE"), 100);
CHECK_EQUAL(position1, position2);
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_find_last_of_pointer_position_n)
{
Compare_Text compare_text(STR("ABCDEFABCDE"));
TextBuffer buffer;
Text text(STR("ABCDEFABCDE"), buffer.data(), buffer.size());
size_t position1 = compare_text.find_last_of(STR("AZCXE"), 0, 4);
size_t position2 = text.find_last_of(STR("AZCXE"), 0, 4);
CHECK_EQUAL(position1, position2);
position1 = compare_text.find_last_of(STR("WXYZ"), 4, 3);
position2 = text.find_last_of(STR("WXYZ"), 4, 3);
CHECK_EQUAL(position1, position2);
position1 = compare_text.find_last_of(STR("ZCXE"), 5, 3);
position2 = text.find_last_of(STR("ZCXE"), 5, 3);
CHECK_EQUAL(position1, position2);
position1 = compare_text.find_last_of(STR("ZCXE"), 1, 3);
position2 = text.find_last_of(STR("ZCXE"), 1, 3);
CHECK_EQUAL(position1, position2);
position1 = compare_text.find_last_of(STR("ZCXE"), compare_text.size(), 4);
position2 = text.find_last_of(STR("ZCXE"), text.size(), 4);
CHECK_EQUAL(position1, position2);
position1 = compare_text.find_last_of(STR("ZCXE"), 100, 4);
position2 = text.find_last_of(STR("ZCXE"), 100, 4);
CHECK_EQUAL(position1, position2);
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_find_last_of_character_position)
{
Compare_Text compare_text(STR("ABCDEF"));
TextBuffer buffer;
Text text(STR("ABCDEF"), buffer.data(), buffer.size());
size_t position1 = compare_text.find_last_of(STR('C'));
size_t position2 = text.find_last_of(STR('C'));
CHECK_EQUAL(position1, position2);
position1 = compare_text.find_last_of(STR('Z'));
position2 = text.find_last_of(STR('Z'));
CHECK_EQUAL(position1, position2);
position1 = compare_text.find_last_of(STR('F'), compare_text.size());
position2 = text.find_last_of(STR('F'), text.size());
CHECK_EQUAL(position1, position2);
position1 = compare_text.find_last_of(STR('C'), 3);
position2 = text.find_last_of(STR('C'), 3);
CHECK_EQUAL(position1, position2);
position1 = compare_text.find_last_of(STR('C'), compare_text.size());
position2 = text.find_last_of(STR('C'), text.size());
CHECK_EQUAL(position1, position2);
position1 = compare_text.find_last_of(STR('C'), 100);
position2 = text.find_last_of(STR('C'), 100);
CHECK_EQUAL(position1, position2);
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_find_first_not_of_string_position)
{
Compare_Text compare_text(STR("ABCDEF"));
TextBuffer buffer;
Text text(STR("ABCDEF"), buffer.data(), buffer.size());
size_t position1 = compare_text.find_first_not_of(Compare_Text(STR("ZAXB")));
size_t position2 = text.find_first_not_of(TextT(STR("ZAXB")));
CHECK_EQUAL(position1, position2);
position1 = compare_text.find_first_not_of(Compare_Text(STR("ZAXB")));
position2 = text.find_first_not_of(TextT(STR("ZAXB")));
CHECK_EQUAL(position1, position2);
position1 = compare_text.find_first_not_of(Compare_Text(STR("ZAXB")), 3);
position2 = text.find_first_not_of(TextT(STR("ZAXB")), 3);
CHECK_EQUAL(position1, position2);
position1 = compare_text.find_first_not_of(Compare_Text(STR("ZAXB")), compare_text.size());
position2 = text.find_first_not_of(TextT(STR("ZAXB")), text.size());
CHECK_EQUAL(position1, position2);
position1 = compare_text.find_first_not_of(Compare_Text(STR("ZAXB")), 100);
position2 = text.find_first_not_of(TextT(STR("ZAXB")), 100);
CHECK_EQUAL(position1, position2);
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_find_first_not_of_pointer_position)
{
Compare_Text compare_text(STR("ABCDEF"));
TextBuffer buffer;
Text text(STR("ABCDEF"), buffer.data(), buffer.size());
size_t position1 = compare_text.find_first_not_of(STR("ZAXB"));
size_t position2 = text.find_first_not_of(STR("ZAXB"));
CHECK_EQUAL(position1, position2);
position1 = compare_text.find_first_not_of(STR("ZAXB"));
position2 = text.find_first_not_of(STR("ZAXB"));
CHECK_EQUAL(position1, position2);
position1 = compare_text.find_first_not_of(STR("ZAXB"), 3);
position2 = text.find_first_not_of(STR("ZAXB"), 3);
CHECK_EQUAL(position1, position2);
position1 = compare_text.find_first_not_of(STR("ZAXB"), compare_text.size());
position2 = text.find_first_not_of(STR("ZAXB"), text.size());
CHECK_EQUAL(position1, position2);
position1 = compare_text.find_first_not_of(STR("ZAXB"), 100);
position2 = text.find_first_not_of(STR("ZAXB"), 100);
CHECK_EQUAL(position1, position2);
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_find_first_not_of_pointer_position_n)
{
Compare_Text compare_text(STR("ABCDEF"));
TextBuffer buffer;
Text text(STR("ABCDEF"), buffer.data(), buffer.size());
size_t position1 = compare_text.find_first_not_of(STR("ZAXB"), 0, 4);
size_t position2 = text.find_first_not_of(STR("ZAXB"), 0, 4);
CHECK_EQUAL(position1, position2);
position1 = compare_text.find_first_not_of(STR("ZAXB"), 0, 4);
position2 = text.find_first_not_of(STR("ZAXB"), 0, 4);
CHECK_EQUAL(position1, position2);
position1 = compare_text.find_first_not_of(STR("ZAXB"), 1, 3);
position2 = text.find_first_not_of(STR("ZAXB"), 1, 3);
CHECK_EQUAL(position1, position2);
position1 = compare_text.find_first_not_of(STR("ZAXB"), 3, 3);
position2 = text.find_first_not_of(STR("ZAXB"), 3, 3);
CHECK_EQUAL(position1, position2);
position1 = compare_text.find_first_not_of(STR("ZAXB"), compare_text.size(), 3);
position2 = text.find_first_not_of(STR("ZAXB"), text.size(), 3);
CHECK_EQUAL(position1, position2);
position1 = compare_text.find_first_not_of(STR("ZAXB"), 100);
position2 = text.find_first_not_of(STR("ZAXB"), 100);
CHECK_EQUAL(position1, position2);
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_find_first_not_of_character_position)
{
Compare_Text compare_text(STR("ABCDEF"));
TextBuffer buffer;
Text text(STR("ABCDEF"), buffer.data(), buffer.size());
size_t position1 = compare_text.find_first_not_of(STR('A'));
size_t position2 = text.find_first_not_of(STR('A'));
CHECK_EQUAL(position1, position2);
position1 = compare_text.find_first_not_of(STR('B'));
position2 = text.find_first_not_of(STR('B'));
CHECK_EQUAL(position1, position2);
position1 = compare_text.find_first_not_of(STR('C'), 3);
position2 = text.find_first_not_of(STR('C'), 3);
CHECK_EQUAL(position1, position2);
position1 = compare_text.find_first_not_of(STR('D'), 3);
position2 = text.find_first_not_of(STR('D'), 3);
CHECK_EQUAL(position1, position2);
position1 = compare_text.find_first_not_of(STR('C'), compare_text.size());
position2 = text.find_first_not_of(STR('C'), text.size());
CHECK_EQUAL(position1, position2);
position1 = compare_text.find_first_not_of(STR('C'), 100);
position2 = text.find_first_not_of(STR('C'), 100);
CHECK_EQUAL(position1, position2);
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_find_last_not_of_string_position)
{
Compare_Text compare_text(STR("ABCDEFABCDE"));
TextBuffer buffer;
Text text(STR("ABCDEFABCDE"), buffer.data(), buffer.size());
size_t position1 = compare_text.find_last_not_of(Compare_Text(STR("ZEXD")));
size_t position2 = text.find_last_not_of(TextT(STR("ZEXD")));
CHECK_EQUAL(position1, position2);
position1 = compare_text.find_last_not_of(Compare_Text(STR("ZEXD")), 3);
position2 = text.find_last_not_of(TextT(STR("ZEXD")), 3);
CHECK_EQUAL(position1, position2);
position1 = compare_text.find_last_not_of(Compare_Text(STR("ZEXD")), 5);
position2 = text.find_last_not_of(TextT(STR("ZEXD")), 5);
CHECK_EQUAL(position1, position2);
position1 = compare_text.find_last_not_of(Compare_Text(STR("ZEXD")), compare_text.size());
position2 = text.find_last_not_of(TextT(STR("ZEXD")), text.size());
CHECK_EQUAL(position1, position2);
position1 = compare_text.find_last_not_of(Compare_Text(STR("ZEXD")), 100);
position2 = text.find_last_not_of(TextT(STR("ZEXD")), 100);
CHECK_EQUAL(position1, position2);
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_find_last_not_of_pointer_position)
{
Compare_Text compare_text(STR("ABCDEFABCDE"));
TextBuffer buffer;
Text text(STR("ABCDEFABCDE"), buffer.data(), buffer.size());
size_t position1 = compare_text.find_last_not_of(STR("ZEXD"));
size_t position2 = text.find_last_not_of(STR("ZEXD"));
CHECK_EQUAL(position1, position2);
position1 = compare_text.find_last_not_of(STR("ZEXD"), 3);
position2 = text.find_last_not_of(STR("ZEXD"), 3);
CHECK_EQUAL(position1, position2);
position1 = compare_text.find_last_not_of(STR("ZEXD"), 5);
position2 = text.find_last_not_of(STR("ZEXD"), 5);
CHECK_EQUAL(position1, position2);
position1 = compare_text.find_last_not_of(STR("ZEXD"), compare_text.size());
position2 = text.find_last_not_of(STR("ZEXD"), text.size());
CHECK_EQUAL(position1, position2);
position1 = compare_text.find_last_not_of(STR("ZEXD"), 100);
position2 = text.find_last_not_of(STR("ZEXD"), 100);
CHECK_EQUAL(position1, position2);
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_find_last_not_of_pointer_position_n)
{
Compare_Text compare_text(STR("ABCDEFABCDE"));
TextBuffer buffer;
Text text(STR("ABCDEFABCDE"), buffer.data(), buffer.size());
size_t position1 = compare_text.find_last_not_of(STR("ZEXD"), 0, 4);
size_t position2 = text.find_last_not_of(STR("ZEXD"), 0, 4);
CHECK_EQUAL(position1, position2);
position1 = compare_text.find_last_not_of(STR("ZEXD"), 5, 3);
position2 = text.find_last_not_of(STR("ZEXD"), 5, 3);
CHECK_EQUAL(position1, position2);
position1 = compare_text.find_last_not_of(STR("ZEXD"), 1, 3);
position2 = text.find_last_not_of(STR("ZEXD"), 1, 3);
CHECK_EQUAL(position1, position2);
position1 = compare_text.find_last_not_of(STR("ZEXD"), compare_text.size(), 4);
position2 = text.find_last_not_of(STR("ZEXD"), text.size(), 4);
CHECK_EQUAL(position1, position2);
position1 = compare_text.find_last_not_of(STR("ZEXD"), 100, 4);
position2 = text.find_last_not_of(STR("ZEXD"), 100, 4);
CHECK_EQUAL(position1, position2);
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_find_last_not_of_character_position)
{
Compare_Text compare_text(STR("ABCDEF"));
TextBuffer buffer;
Text text(STR("ABCDEF"), buffer.data(), buffer.size());
size_t position1 = compare_text.find_last_not_of(STR('F'));
size_t position2 = text.find_last_not_of(STR('F'));
CHECK_EQUAL(position1, position2);
position1 = compare_text.find_last_not_of(STR('Z'));
position2 = text.find_last_not_of(STR('Z'));
CHECK_EQUAL(position1, position2);
position1 = compare_text.find_last_not_of(STR('A'), compare_text.size());
position2 = text.find_last_not_of(STR('A'), text.size());
CHECK_EQUAL(position1, position2);
position1 = compare_text.find_last_not_of(STR('C'), 3);
position2 = text.find_last_not_of(STR('C'), 3);
CHECK_EQUAL(position1, position2);
position1 = compare_text.find_last_not_of(STR('C'), compare_text.size());
position2 = text.find_last_not_of(STR('C'), text.size());
CHECK_EQUAL(position1, position2);
position1 = compare_text.find_last_not_of(STR('C'), 100);
position2 = text.find_last_not_of(STR('C'), 100);
CHECK_EQUAL(position1, position2);
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_hash)
{
// Test with actual string type.
TextBuffer buffer;
Text text(STR("ABCDEFHIJKL"), buffer.data(), buffer.size());
size_t hash = etl::hash<Text>()(text);
size_t compare_hash = etl::private_hash::generic_hash<size_t>(reinterpret_cast<const uint8_t*>(&text[0]), reinterpret_cast<const uint8_t*>(&text[text.size()]));
CHECK_EQUAL(compare_hash, hash);
// Test with interface string type.
IText& itext = text;
hash = etl::hash<IText>()(itext);
CHECK_EQUAL(compare_hash, hash);
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_memcpy_repair)
{
TextBuffer buffer;
Text text(buffer.data(), buffer.size());
text.assign(STR("ABCDEF"));
char buffer2[sizeof(Text)];
// Will not copy the buffer!
memcpy(&buffer2, (const void*)&text, sizeof(text));
Text& rtext(*reinterpret_cast<Text*>(buffer2));
rtext.repair();
CHECK(!rtext.empty());
CHECK(!rtext.full());
bool is_equal = Equal(text, rtext);
CHECK(is_equal);
text = STR("GHIJKL");
is_equal = Equal(text, rtext);
CHECK(is_equal);
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_memcpy_repair_virtual)
{
TextBuffer buffer;
Text text(buffer.data(), buffer.size());
text.assign(STR("ABCDEF"));
char buffer2[sizeof(Text)];
// Will not copy the buffer!
memcpy(&buffer2, (const void*)&text, sizeof(text));
IText& itext(*reinterpret_cast<IText*>(buffer2));
itext.repair();
CHECK(!itext.empty());
CHECK(!itext.full());
bool is_equal = Equal(text, itext);
CHECK(is_equal);
text = STR("GHIJKL");
is_equal = Equal(text, itext);
CHECK(is_equal);
}
#if ETL_HAS_STRING_TRUNCATION_CHECKS
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_truncate_over_many_operations)
{
TextBuffer buffer;
Text text(short_text.c_str(), buffer.data(), buffer.size());
CHECK(!text.is_truncated());
text.insert(3, initial_text.c_str());
CHECK(text.is_truncated());
while (text.size() != 0)
{
text.pop_back();
CHECK(text.is_truncated());
}
text.clear();
CHECK(!text.is_truncated());
text.assign(longer_text.c_str());
CHECK(text.is_truncated());
text.assign(short_text.c_str());
CHECK(!text.is_truncated());
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_add_from_truncated)
{
TextBuffer buffer;
Text text1(short_text.c_str(), buffer.data(), buffer.size());
TextBufferS buffers;
Text text2(short_text.c_str(), buffers.data(), buffers.size());
CHECK(!text1.is_truncated());
CHECK(text2.is_truncated());
// text2 has the truncate flag set.
text1 += text2;
CHECK(text1.is_truncated());
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_add_to_truncated)
{
TextBuffer buffer;
Text text1(longer_text.c_str(), buffer.data(), buffer.size());
TextBuffer buffer2;
Text text2(short_text.c_str(), buffer2.data(), buffer2.size());
CHECK(text1.is_truncated());
CHECK(!text2.is_truncated());
// Clear text but not the truncate flag.
text1.erase(text1.begin(), text1.end());
// text1 still has the truncate flag set.
text1 += text2;
CHECK(text1.is_truncated());
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_clear_truncated)
{
TextBuffer buffer;
Text text(longer_text.c_str(), buffer.data(), buffer.size());
CHECK(text.is_truncated());
text.clear_truncated();
CHECK(!text.is_truncated());
}
#endif
#if ETL_HAS_STRING_CLEAR_AFTER_USE
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_secure_after_destructor)
{
char buffer[sizeof(Text)];
std::fill_n(buffer, sizeof(Text), 0);
TextBuffer buffer2;
::new (buffer) Text(STR("ABCDEF"), buffer2.data(), buffer2.size());
Text& text = *reinterpret_cast<Text*>(buffer);
text.set_secure();
CHECK(TextT(STR("ABCDEF")) == text);
Text::pointer pb = text.begin();
Text::pointer pe = text.end();
// Destroy the text object.
text.~Text();
// Check there no non-zero values in the string.
CHECK(std::find_if(pb, pe, [](Text::value_type x) { return x != 0; }) == pe);
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_secure_after_assign)
{
TextBuffer buffer;
Text text(buffer.data(), buffer.size());
text.set_secure();
text.assign(STR("ABCDEF"));
Text::pointer pe = text.end();
text.assign(STR("ABC"));
CHECK(std::find_if(text.end(), pe, [](Text::value_type x) { return x != 0; }) == pe);
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_secure_after_resize_down)
{
TextBuffer buffer;
Text text(buffer.data(), buffer.size());
text.set_secure();
text.assign(STR("ABCDEF"));
Text::pointer pe = text.end();
text.resize(text.size() - 3U);
CHECK(std::find_if(text.end(), pe, [](Text::value_type x) { return x != 0; }) == pe);
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_secure_after_erase)
{
TextBuffer buffer;
Text text(buffer.data(), buffer.size());
text.set_secure();
text.assign(STR("ABCDEF"));
Text::pointer pb = text.begin();
Text::pointer pe = text.end();
text.erase(pb + 2, pb + 5);
// Check there no non-zero values in the remainder of the string.
CHECK(std::find_if(text.end(), pe, [](Text::value_type x) { return x != 0; }) == pe);
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_secure_after_replace)
{
TextBuffer buffer;
Text text(buffer.data(), buffer.size());
text.set_secure();
text.assign(STR("ABCDEF"));
Text::pointer pb = text.begin();
Text::pointer pe = text.end();
text.replace(pb + 1, pb + 4, STR("G"));
// Check there no non-zero values in the remainder of the string.
CHECK(std::find_if(text.end(), pe, [](Text::value_type x) { return x != 0; }) == pe);
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_secure_after_clear)
{
TextBuffer buffer;
Text text(buffer.data(), buffer.size());
text.set_secure();
text.assign(STR("ABCDEF"));
Text::pointer pb = text.begin();
Text::pointer pe = text.end();
text.clear();
// Check there no non-zero values in the remainder of the string.
CHECK(std::find_if(pb, pe, [](Text::value_type x) { return x != 0; }) == pe);
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_secure_flag_after_copy)
{
TextBuffer buffer1;
Text text1(STR("Hello World"), buffer1.data(), buffer1.size());
text1.set_secure();
TextBuffer buffer2;
Text text2(text1, buffer2.data(), buffer2.size());
TextBuffer buffer3;
Text text3(buffer3.data(), buffer3.size());
text3 = text1;
TextBuffer buffer4;
Text text4(text1, buffer4.data(), buffer4.size(), 6U, 2U);
CHECK(text2.is_secure());
CHECK(text3.is_secure());
CHECK(text4.is_secure());
}
#endif
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_initialize_free_space_empty_string)
{
TextBuffer buffer1;
TextBuffer buffer2;
Text text(buffer1.data(), buffer1.size());
Text empty(buffer2.data(), buffer2.size());
text.initialize_free_space();
CHECK(text.empty());
CHECK(text == empty);
for (size_t i = text.size(); i < text.max_size(); ++i)
{
CHECK_EQUAL(0, text[i]);
}
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_initialize_free_space_part_filled_string)
{
TextBuffer buffer1;
TextBuffer buffer2;
Text initial(STR("ABC"), buffer1.data(), buffer1.size());
Text empty(buffer2.data(), buffer2.size());
Text text(initial, buffer2.data(), buffer2.size());
text.initialize_free_space();
CHECK(text == initial);
CHECK(text != empty);
for (size_t i = text.size(); i < text.max_size(); ++i)
{
CHECK_EQUAL(0, text[i]);
}
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_update_after_c_string_max_size)
{
TextBuffer buffer1;
Text text(buffer1.data(), buffer1.size());
text.initialize_free_space();
std::fill(text.data(), text.data() + text.max_size(), STR('A'));
text.trim_to_terminator();
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
CHECK_EQUAL(text.max_size(), text.size());
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_update_after_c_string_shorter_size)
{
TextBuffer buffer1;
Text text(buffer1.data(), buffer1.size());
text.initialize_free_space();
std::fill(text.data(), text.data() + text.max_size() - 1, STR('A'));
text.trim_to_terminator();
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
CHECK_EQUAL(text.max_size() - 1, text.size());
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_update_after_c_string_greater_size)
{
TextBuffer buffer1;
Text text(buffer1.data(), buffer1.size());
text.initialize_free_space();
std::fill(text.data(), text.data() + text.max_size() + 1, STR('A')); // Overwrites to terminating null.
text.trim_to_terminator();
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(text.is_truncated());
#endif
CHECK_EQUAL(text.max_size(), text.size());
}
};
}
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_main.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: lfrasson <lfrasson@student.42sp.org.br> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/12/11 19:35:20 by phemsi-a #+# #+# */
/* Updated: 2022/04/22 17:57:26 by lfrasson ### ########.fr */
/* */
/* ************************************************************************** */
#include "tests.hpp"
#include <time.h>
int main(void)
{
clock_t start;
clock_t end;
clock_t elapsed_time;
start = clock();
std::cout.setf(std::ios::boolalpha);
test_constructors();
test_simple_assignment_operator();
test_iterators();
test_const_iterators();
test_reverse_iterators();
test_const_reverse_iterators();
test_empty();
test_pop_back(test_push_back());
test_out_of_bounds();
test_assign();
test_at_front_back_and_dereference();
test_clear();
test_erase();
test_reserve();
test_get_allocator();
test_resize();
test_insert();
test_relational_operators();
test_swap();
end = clock();
elapsed_time = end - start;
print_title(VERSION);
std::cout << "Test duration:" << static_cast<float>(elapsed_time) / CLOCKS_PER_SEC << std::endl;
}
|
/*
Copyright: © 2018 SIL International.
Description: Implementation of the context API functions using internal
data structures and functions.
Create Date: 27 Sep 2018
Authors: Tim Eves (TSE)
History: 27 Sep 2018 - TSE - Initial implementation.
5 Oct 2018 - TSE - Refactor out adaptor and internal classes
into context.hpp
*/
#include <cassert>
#include <algorithm>
#include <vector>
#include <keyman/keyboardprocessor.h>
#include "context.hpp"
#include "json.hpp"
#include "utfcodec.hpp"
namespace {
template<class U>
km_kbp_status
_context_items_from(typename U::codeunit_t const *text,
km_kbp_context_item **out_ptr)
{
assert(text); assert(out_ptr);
if (!text || !out_ptr) return KM_KBP_STATUS_INVALID_ARGUMENT;
*out_ptr = nullptr;
try
{
std::vector<km_kbp_context_item> res;
for (auto i = typename U::const_iterator(text); *i; ++i)
{
if(i.error()) return KM_KBP_STATUS_INVALID_UTF;
res.emplace_back(km_kbp_context_item {KM_KBP_CT_CHAR, {0,}, {*i}});
}
// Terminate the context_items array.
res.emplace_back(km_kbp_context_item KM_KBP_CONTEXT_ITEM_END);
*out_ptr = new km_kbp_context_item[res.size()];
std::move(res.begin(), res.end(), *out_ptr);
}
catch (std::bad_alloc &)
{
return KM_KBP_STATUS_NO_MEM;
}
return KM_KBP_STATUS_OK;
}
template<class U>
km_kbp_status _context_items_to(km_kbp_context_item const *ci,
typename U::codeunit_t *buf,
size_t * sz_ptr)
{
assert(ci); assert(sz_ptr);
if (!ci || !sz_ptr) return KM_KBP_STATUS_INVALID_ARGUMENT;
auto const buf_size = *sz_ptr;
if (buf && buf_size > 0)
{
auto i = typename U::iterator(buf);
auto const e = decltype(i)(buf + buf_size - 1);
for (;i != e && ci->type != KM_KBP_CT_END && !i.error(); ++ci)
{
if (ci->type == KM_KBP_CT_CHAR)
{
*i = ci->character; ++i;
}
}
*i = 0; // null terminate the UTF16 string.
*sz_ptr = buf_size - (e - i);
// Skip over any final markers - they are execluded from context
while(ci->type == KM_KBP_CT_MARKER) {
ci++;
}
return ci->type == KM_KBP_CT_END
? KM_KBP_STATUS_OK
: KM_KBP_STATUS_INSUFFICENT_BUFFER;
}
else
{
auto n = 0;
typename U::codeunit_t cps[4];
do
{
if (ci->type == KM_KBP_CT_CHAR)
{
int8_t l = 4;
U::codec::put(cps, ci->character, l);
n += l;
}
}
while(ci++->type != KM_KBP_CT_END);
*sz_ptr = n+1;
return KM_KBP_STATUS_OK;
}
}
}
km_kbp_status
km_kbp_context_items_from_utf16(km_kbp_cp const *text,
km_kbp_context_item **out_ptr)
{
return _context_items_from<utf16>(reinterpret_cast<utf16::codeunit_t const *>(text), out_ptr);
}
km_kbp_status
km_kbp_context_items_from_utf8(char const *text,
km_kbp_context_item **out_ptr)
{
return _context_items_from<utf8>(reinterpret_cast<utf8::codeunit_t const *>(text), out_ptr);
}
km_kbp_status km_kbp_context_items_to_utf8(km_kbp_context_item const *ci,
char *buf, size_t * sz_ptr)
{
return _context_items_to<utf8>(ci,
reinterpret_cast<utf8::codeunit_t *>(buf),
sz_ptr);
}
km_kbp_status km_kbp_context_items_to_utf16(km_kbp_context_item const *ci,
km_kbp_cp *buf, size_t * sz_ptr)
{
return _context_items_to<utf16>(ci,
reinterpret_cast<utf16::codeunit_t *>(buf),
sz_ptr);
}
void km_kbp_context_items_dispose(km_kbp_context_item *ci)
{
delete [] ci;
}
km_kbp_status km_kbp_context_set(km_kbp_context *ctxt, km_kbp_context_item const *ci)
{
km_kbp_context_clear(ctxt);
return km_kbp_context_append(ctxt, ci);
}
km_kbp_status km_kbp_context_get(km_kbp_context const *ctxt,
km_kbp_context_item **out_ptr)
{
assert(ctxt); assert(out_ptr);
if (!ctxt || !out_ptr) return KM_KBP_STATUS_INVALID_ARGUMENT;
try
{
*out_ptr = new km_kbp_context_item[ctxt->size() + 1];
}
catch (std::bad_alloc &)
{
return KM_KBP_STATUS_NO_MEM;
}
std::copy(ctxt->begin(), ctxt->end(), *out_ptr);
(*out_ptr)[ctxt->size()].type = KM_KBP_CT_END;
return KM_KBP_STATUS_OK;
}
void km_kbp_context_clear(km_kbp_context *ctxt)
{
assert(ctxt);
if (ctxt)
{
ctxt->clear();
}
}
size_t km_kbp_context_length(km_kbp_context *ctxt)
{
assert(ctxt);
return ctxt ? ctxt->size() : 0;
}
km_kbp_status km_kbp_context_append(km_kbp_context *ctxt,
km_kbp_context_item const *ci)
{
assert(ctxt); assert(ci);
if (!ctxt || !ci) return KM_KBP_STATUS_INVALID_ARGUMENT;
try
{
for (;ci->type != KM_KBP_CT_END; ++ci)
{
ctxt->emplace_back(*ci);
}
} catch (std::bad_alloc &) {
return KM_KBP_STATUS_NO_MEM;
}
return KM_KBP_STATUS_OK;
}
km_kbp_status km_kbp_context_shrink(km_kbp_context *ctxt, size_t num,
km_kbp_context_item const * ci)
{
assert(ctxt);
if (!ctxt) return KM_KBP_STATUS_INVALID_ARGUMENT;
try
{
ctxt->resize(ctxt->size() - std::min(num, ctxt->size()));
if (ci)
{
auto const ip = ctxt->begin();
while(num-- && ci->type != KM_KBP_CT_END)
{
ctxt->emplace(ip, *ci);
ci++;
}
}
} catch (std::bad_alloc &) {
return KM_KBP_STATUS_NO_MEM;
}
return KM_KBP_STATUS_OK;
}
json & operator << (json & j, km::kbp::context const & ctxt) {
j << json::array;
for (auto & i: ctxt) j << i;
return j << json::close;
}
json & operator << (json & j, km_kbp_context_item const & i)
{
utf8::codeunit_t cps[7] = {0,}; // 6 bytes for maximal UTF-8 char (e.g. U+10FFFF) + nul terminator
int8_t l = 4;
switch (i.type)
{
case KM_KBP_CT_CHAR:
utf8::codec::put(cps, i.character, l);
j << json::string(&cps[0]);
break;
case KM_KBP_CT_MARKER:
j << json::integer_u(i.marker);
break;
default:
j << json::flat << json::object
<< "invalid type" << i.type
<< json::close;
}
return j;
}
|
// Copyright (c) 2014 BitPay Inc.
// Copyright (c) 2014-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <stdint.h>
#include <vector>
#include <string>
#include <map>
#include <univalue.h>
#include "test/test_coinrac.h"
#include <boost/test/unit_test.hpp>
BOOST_FIXTURE_TEST_SUITE(univalue_tests, BasicTestingSetup)
BOOST_AUTO_TEST_CASE(univalue_constructor)
{
UniValue v1;
BOOST_CHECK(v1.isNull());
UniValue v2(UniValue::VSTR);
BOOST_CHECK(v2.isStr());
UniValue v3(UniValue::VSTR, "foo");
BOOST_CHECK(v3.isStr());
BOOST_CHECK_EQUAL(v3.getValStr(), "foo");
UniValue numTest;
BOOST_CHECK(numTest.setNumStr("82"));
BOOST_CHECK(numTest.isNum());
BOOST_CHECK_EQUAL(numTest.getValStr(), "82");
uint64_t vu64 = 82;
UniValue v4(vu64);
BOOST_CHECK(v4.isNum());
BOOST_CHECK_EQUAL(v4.getValStr(), "82");
int64_t vi64 = -82;
UniValue v5(vi64);
BOOST_CHECK(v5.isNum());
BOOST_CHECK_EQUAL(v5.getValStr(), "-82");
int vi = -688;
UniValue v6(vi);
BOOST_CHECK(v6.isNum());
BOOST_CHECK_EQUAL(v6.getValStr(), "-688");
double vd = -7.21;
UniValue v7(vd);
BOOST_CHECK(v7.isNum());
BOOST_CHECK_EQUAL(v7.getValStr(), "-7.21");
std::string vs("yawn");
UniValue v8(vs);
BOOST_CHECK(v8.isStr());
BOOST_CHECK_EQUAL(v8.getValStr(), "yawn");
const char *vcs = "zappa";
UniValue v9(vcs);
BOOST_CHECK(v9.isStr());
BOOST_CHECK_EQUAL(v9.getValStr(), "zappa");
}
BOOST_AUTO_TEST_CASE(univalue_typecheck)
{
UniValue v1;
BOOST_CHECK(v1.setNumStr("1"));
BOOST_CHECK(v1.isNum());
BOOST_CHECK_THROW(v1.get_bool(), std::runtime_error);
UniValue v2;
BOOST_CHECK(v2.setBool(true));
BOOST_CHECK_EQUAL(v2.get_bool(), true);
BOOST_CHECK_THROW(v2.get_int(), std::runtime_error);
UniValue v3;
BOOST_CHECK(v3.setNumStr("32482348723847471234"));
BOOST_CHECK_THROW(v3.get_int64(), std::runtime_error);
BOOST_CHECK(v3.setNumStr("1000"));
BOOST_CHECK_EQUAL(v3.get_int64(), 1000);
UniValue v4;
BOOST_CHECK(v4.setNumStr("2147483648"));
BOOST_CHECK_EQUAL(v4.get_int64(), 2147483648ULL);
BOOST_CHECK_THROW(v4.get_int(), std::runtime_error);
BOOST_CHECK(v4.setNumStr("1000"));
BOOST_CHECK_EQUAL(v4.get_int(), 1000);
BOOST_CHECK_THROW(v4.get_str(), std::runtime_error);
BOOST_CHECK_EQUAL(v4.get_real(), 1000);
BOOST_CHECK_THROW(v4.get_array(), std::runtime_error);
BOOST_CHECK_THROW(v4.getKeys(), std::runtime_error);
BOOST_CHECK_THROW(v4.getValues(), std::runtime_error);
BOOST_CHECK_THROW(v4.get_obj(), std::runtime_error);
BOOST_CHECK(v4.setNumStr("2.01"));
BOOST_CHECK_THROW(v4.get_int(), std::runtime_error);
BOOST_CHECK_THROW(v4.get_int64(), std::runtime_error);
BOOST_CHECK_THROW(v4.get_str(), std::runtime_error);
BOOST_CHECK_EQUAL(v4.get_real(), 2.01);
BOOST_CHECK_THROW(v4.get_array(), std::runtime_error);
BOOST_CHECK_THROW(v4.getKeys(), std::runtime_error);
BOOST_CHECK_THROW(v4.getValues(), std::runtime_error);
BOOST_CHECK_THROW(v4.get_obj(), std::runtime_error);
UniValue v5;
BOOST_CHECK(v5.read("[true, 10]"));
BOOST_CHECK_NO_THROW(v5.get_array());
std::vector<UniValue> vals = v5.getValues();
BOOST_CHECK_THROW(vals[0].get_int(), std::runtime_error);
BOOST_CHECK_EQUAL(vals[0].get_bool(), true);
BOOST_CHECK_EQUAL(vals[1].get_int(), 10);
BOOST_CHECK_THROW(vals[1].get_bool(), std::runtime_error);
}
BOOST_AUTO_TEST_CASE(univalue_set)
{
UniValue v(UniValue::VSTR, "foo");
v.clear();
BOOST_CHECK(v.isNull());
BOOST_CHECK_EQUAL(v.getValStr(), "");
BOOST_CHECK(v.setObject());
BOOST_CHECK(v.isObject());
BOOST_CHECK_EQUAL(v.size(), 0);
BOOST_CHECK_EQUAL(v.getType(), UniValue::VOBJ);
BOOST_CHECK(v.empty());
BOOST_CHECK(v.setArray());
BOOST_CHECK(v.isArray());
BOOST_CHECK_EQUAL(v.size(), 0);
BOOST_CHECK(v.setStr("zum"));
BOOST_CHECK(v.isStr());
BOOST_CHECK_EQUAL(v.getValStr(), "zum");
BOOST_CHECK(v.setFloat(-1.01));
BOOST_CHECK(v.isNum());
BOOST_CHECK_EQUAL(v.getValStr(), "-1.01");
BOOST_CHECK(v.setInt((int)1023));
BOOST_CHECK(v.isNum());
BOOST_CHECK_EQUAL(v.getValStr(), "1023");
BOOST_CHECK(v.setInt((int64_t)-1023LL));
BOOST_CHECK(v.isNum());
BOOST_CHECK_EQUAL(v.getValStr(), "-1023");
BOOST_CHECK(v.setInt((uint64_t)1023ULL));
BOOST_CHECK(v.isNum());
BOOST_CHECK_EQUAL(v.getValStr(), "1023");
BOOST_CHECK(v.setNumStr("-688"));
BOOST_CHECK(v.isNum());
BOOST_CHECK_EQUAL(v.getValStr(), "-688");
BOOST_CHECK(v.setBool(false));
BOOST_CHECK_EQUAL(v.isBool(), true);
BOOST_CHECK_EQUAL(v.isTrue(), false);
BOOST_CHECK_EQUAL(v.isFalse(), true);
BOOST_CHECK_EQUAL(v.getBool(), false);
BOOST_CHECK(v.setBool(true));
BOOST_CHECK_EQUAL(v.isBool(), true);
BOOST_CHECK_EQUAL(v.isTrue(), true);
BOOST_CHECK_EQUAL(v.isFalse(), false);
BOOST_CHECK_EQUAL(v.getBool(), true);
BOOST_CHECK(!v.setNumStr("zombocom"));
BOOST_CHECK(v.setNull());
BOOST_CHECK(v.isNull());
}
BOOST_AUTO_TEST_CASE(univalue_array)
{
UniValue arr(UniValue::VARR);
UniValue v((int64_t)1023LL);
BOOST_CHECK(arr.push_back(v));
std::string vStr("zippy");
BOOST_CHECK(arr.push_back(vStr));
const char *s = "pippy";
BOOST_CHECK(arr.push_back(s));
std::vector<UniValue> vec;
v.setStr("boing");
vec.push_back(v);
v.setStr("going");
vec.push_back(v);
BOOST_CHECK(arr.push_backV(vec));
BOOST_CHECK_EQUAL(arr.empty(), false);
BOOST_CHECK_EQUAL(arr.size(), 5);
BOOST_CHECK_EQUAL(arr[0].getValStr(), "1023");
BOOST_CHECK_EQUAL(arr[1].getValStr(), "zippy");
BOOST_CHECK_EQUAL(arr[2].getValStr(), "pippy");
BOOST_CHECK_EQUAL(arr[3].getValStr(), "boing");
BOOST_CHECK_EQUAL(arr[4].getValStr(), "going");
BOOST_CHECK_EQUAL(arr[999].getValStr(), "");
arr.clear();
BOOST_CHECK(arr.empty());
BOOST_CHECK_EQUAL(arr.size(), 0);
}
BOOST_AUTO_TEST_CASE(univalue_object)
{
UniValue obj(UniValue::VOBJ);
std::string strKey, strVal;
UniValue v;
strKey = "age";
v.setInt(100);
BOOST_CHECK(obj.pushKV(strKey, v));
strKey = "first";
strVal = "John";
BOOST_CHECK(obj.pushKV(strKey, strVal));
strKey = "last";
const char *cVal = "Smith";
BOOST_CHECK(obj.pushKV(strKey, cVal));
strKey = "distance";
BOOST_CHECK(obj.pushKV(strKey, (int64_t) 25));
strKey = "time";
BOOST_CHECK(obj.pushKV(strKey, (uint64_t) 3600));
strKey = "calories";
BOOST_CHECK(obj.pushKV(strKey, (int) 12));
strKey = "temperature";
BOOST_CHECK(obj.pushKV(strKey, (double) 90.012));
UniValue obj2(UniValue::VOBJ);
BOOST_CHECK(obj2.pushKV("cat1", 9000));
BOOST_CHECK(obj2.pushKV("cat2", 12345));
BOOST_CHECK(obj.pushKVs(obj2));
BOOST_CHECK_EQUAL(obj.empty(), false);
BOOST_CHECK_EQUAL(obj.size(), 9);
BOOST_CHECK_EQUAL(obj["age"].getValStr(), "100");
BOOST_CHECK_EQUAL(obj["first"].getValStr(), "John");
BOOST_CHECK_EQUAL(obj["last"].getValStr(), "Smith");
BOOST_CHECK_EQUAL(obj["distance"].getValStr(), "25");
BOOST_CHECK_EQUAL(obj["time"].getValStr(), "3600");
BOOST_CHECK_EQUAL(obj["calories"].getValStr(), "12");
BOOST_CHECK_EQUAL(obj["temperature"].getValStr(), "90.012");
BOOST_CHECK_EQUAL(obj["cat1"].getValStr(), "9000");
BOOST_CHECK_EQUAL(obj["cat2"].getValStr(), "12345");
BOOST_CHECK_EQUAL(obj["nyuknyuknyuk"].getValStr(), "");
BOOST_CHECK(obj.exists("age"));
BOOST_CHECK(obj.exists("first"));
BOOST_CHECK(obj.exists("last"));
BOOST_CHECK(obj.exists("distance"));
BOOST_CHECK(obj.exists("time"));
BOOST_CHECK(obj.exists("calories"));
BOOST_CHECK(obj.exists("temperature"));
BOOST_CHECK(obj.exists("cat1"));
BOOST_CHECK(obj.exists("cat2"));
BOOST_CHECK(!obj.exists("nyuknyuknyuk"));
std::map<std::string, UniValue::VType> objTypes;
objTypes["age"] = UniValue::VNUM;
objTypes["first"] = UniValue::VSTR;
objTypes["last"] = UniValue::VSTR;
objTypes["distance"] = UniValue::VNUM;
objTypes["time"] = UniValue::VNUM;
objTypes["calories"] = UniValue::VNUM;
objTypes["temperature"] = UniValue::VNUM;
objTypes["cat1"] = UniValue::VNUM;
objTypes["cat2"] = UniValue::VNUM;
BOOST_CHECK(obj.checkObject(objTypes));
objTypes["cat2"] = UniValue::VSTR;
BOOST_CHECK(!obj.checkObject(objTypes));
obj.clear();
BOOST_CHECK(obj.empty());
BOOST_CHECK_EQUAL(obj.size(), 0);
}
static const char *json1 =
"[1.10000000,{\"key1\":\"str\\u0000\",\"key2\":800,\"key3\":{\"name\":\"martian http://test.com\"}}]";
BOOST_AUTO_TEST_CASE(univalue_readwrite)
{
UniValue v;
BOOST_CHECK(v.read(json1));
std::string strJson1(json1);
BOOST_CHECK(v.read(strJson1));
BOOST_CHECK(v.isArray());
BOOST_CHECK_EQUAL(v.size(), 2);
BOOST_CHECK_EQUAL(v[0].getValStr(), "1.10000000");
UniValue obj = v[1];
BOOST_CHECK(obj.isObject());
BOOST_CHECK_EQUAL(obj.size(), 3);
BOOST_CHECK(obj["key1"].isStr());
std::string correctValue("str");
correctValue.push_back('\0');
BOOST_CHECK_EQUAL(obj["key1"].getValStr(), correctValue);
BOOST_CHECK(obj["key2"].isNum());
BOOST_CHECK_EQUAL(obj["key2"].getValStr(), "800");
BOOST_CHECK(obj["key3"].isObject());
BOOST_CHECK_EQUAL(strJson1, v.write());
/* Check for (correctly reporting) a parsing error if the initial
JSON construct is followed by more stuff. Note that whitespace
is, of course, exempt. */
BOOST_CHECK(v.read(" {}\n "));
BOOST_CHECK(v.isObject());
BOOST_CHECK(v.read(" []\n "));
BOOST_CHECK(v.isArray());
BOOST_CHECK(!v.read("@{}"));
BOOST_CHECK(!v.read("{} garbage"));
BOOST_CHECK(!v.read("[]{}"));
BOOST_CHECK(!v.read("{}[]"));
BOOST_CHECK(!v.read("{} 42"));
}
BOOST_AUTO_TEST_SUITE_END()
|
// Dear ImGui: standalone example application for DirectX 11
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
// Read online: https://github.com/ocornut/imgui/tree/master/docs
#include "imgui.h"
#include "imgui_impl_win32.h"
#include "imgui_impl_dx11.h"
#include <d3d11.h>
#include <tchar.h>
#include <chrono>
#include "App.h"
// Data
static ID3D11Device* g_pd3dDevice = NULL;
static ID3D11DeviceContext* g_pd3dDeviceContext = NULL;
static IDXGISwapChain* g_pSwapChain = NULL;
static ID3D11RenderTargetView* g_mainRenderTargetView = NULL;
// Forward declarations of helper functions
bool CreateDeviceD3D(HWND hWnd);
void CleanupDeviceD3D();
void CreateRenderTarget();
void CleanupRenderTarget();
LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
double GetTimeInSeconds() {
using FbSeconds = std::chrono::duration<double, std::chrono::seconds::period>;
auto now = std::chrono::high_resolution_clock::now();
return FbSeconds(now.time_since_epoch()).count();
}
// Main code
int main(int, char**)
{
// Create application window
//ImGui_ImplWin32_EnableDpiAwareness();
WNDCLASSEX wc = { sizeof(WNDCLASSEX), CS_CLASSDC, WndProc, 0L, 0L, GetModuleHandle(NULL), NULL, NULL, NULL, NULL, _T("ImGui Example"), NULL };
::RegisterClassEx(&wc);
HWND hwnd = ::CreateWindow(wc.lpszClassName, _T("Tic Tac Toe Example"), WS_OVERLAPPEDWINDOW, 100, 100, 1280, 800, NULL, NULL, wc.hInstance, NULL);
// Initialize Direct3D
if (!CreateDeviceD3D(hwnd))
{
CleanupDeviceD3D();
::UnregisterClass(wc.lpszClassName, wc.hInstance);
return 1;
}
// Show the window
::ShowWindow(hwnd, SW_SHOWDEFAULT);
::UpdateWindow(hwnd);
// Setup Dear ImGui context
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO(); (void)io;
//io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls
//io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls
// Setup Dear ImGui style
ImGui::StyleColorsDark();
//ImGui::StyleColorsClassic();
// Setup Platform/Renderer backends
ImGui_ImplWin32_Init(hwnd);
ImGui_ImplDX11_Init(g_pd3dDevice, g_pd3dDeviceContext);
// Load Fonts
// - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them.
// - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple.
// - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit).
// - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call.
// - Read 'docs/FONTS.md' for more instructions and details.
// - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ !
//io.Fonts->AddFontDefault();
//io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f);
//io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f);
//io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f);
//io.Fonts->AddFontFromFileTTF("../../misc/fonts/ProggyTiny.ttf", 10.0f);
//ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese());
//IM_ASSERT(font != NULL);
// Our state
ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f);
//
App theApp;
// Main loop
bool done = false;
double timePrevious = GetTimeInSeconds();
double timeDelta = 0.0f;
while (!done)
{
// Poll and handle messages (inputs, window resize, etc.)
// You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
// - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application.
// - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application.
// Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
MSG msg;
while (::PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE))
{
::TranslateMessage(&msg);
::DispatchMessage(&msg);
if (msg.message == WM_QUIT)
done = true;
}
if (done)
break;
// Start the Dear ImGui frame
ImGui_ImplDX11_NewFrame();
ImGui_ImplWin32_NewFrame();
ImGui::NewFrame();
double timeNow = GetTimeInSeconds();
timeDelta = timeNow - timePrevious;
timePrevious = timeNow;
theApp.update(timeDelta);
theApp.render(timeDelta);
// Rendering
ImGui::Render();
const float clear_color_with_alpha[4] = { clear_color.x * clear_color.w, clear_color.y * clear_color.w, clear_color.z * clear_color.w, clear_color.w };
g_pd3dDeviceContext->OMSetRenderTargets(1, &g_mainRenderTargetView, NULL);
g_pd3dDeviceContext->ClearRenderTargetView(g_mainRenderTargetView, clear_color_with_alpha);
ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());
g_pSwapChain->Present(1, 0); // Present with vsync
//g_pSwapChain->Present(0, 0); // Present without vsync
}
// Cleanup
ImGui_ImplDX11_Shutdown();
ImGui_ImplWin32_Shutdown();
ImGui::DestroyContext();
CleanupDeviceD3D();
::DestroyWindow(hwnd);
::UnregisterClass(wc.lpszClassName, wc.hInstance);
return 0;
}
// Helper functions
bool CreateDeviceD3D(HWND hWnd)
{
// Setup swap chain
DXGI_SWAP_CHAIN_DESC sd;
ZeroMemory(&sd, sizeof(sd));
sd.BufferCount = 2;
sd.BufferDesc.Width = 0;
sd.BufferDesc.Height = 0;
sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
sd.BufferDesc.RefreshRate.Numerator = 60;
sd.BufferDesc.RefreshRate.Denominator = 1;
sd.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;
sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
sd.OutputWindow = hWnd;
sd.SampleDesc.Count = 1;
sd.SampleDesc.Quality = 0;
sd.Windowed = TRUE;
sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
UINT createDeviceFlags = 0;
//createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG;
D3D_FEATURE_LEVEL featureLevel;
const D3D_FEATURE_LEVEL featureLevelArray[2] = { D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_0, };
if (D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, createDeviceFlags, featureLevelArray, 2, D3D11_SDK_VERSION, &sd, &g_pSwapChain, &g_pd3dDevice, &featureLevel, &g_pd3dDeviceContext) != S_OK)
return false;
CreateRenderTarget();
return true;
}
void CleanupDeviceD3D()
{
CleanupRenderTarget();
if (g_pSwapChain) { g_pSwapChain->Release(); g_pSwapChain = NULL; }
if (g_pd3dDeviceContext) { g_pd3dDeviceContext->Release(); g_pd3dDeviceContext = NULL; }
if (g_pd3dDevice) { g_pd3dDevice->Release(); g_pd3dDevice = NULL; }
}
void CreateRenderTarget()
{
ID3D11Texture2D* pBackBuffer;
g_pSwapChain->GetBuffer(0, IID_PPV_ARGS(&pBackBuffer));
g_pd3dDevice->CreateRenderTargetView(pBackBuffer, NULL, &g_mainRenderTargetView);
pBackBuffer->Release();
}
void CleanupRenderTarget()
{
if (g_mainRenderTargetView) { g_mainRenderTargetView->Release(); g_mainRenderTargetView = NULL; }
}
// Forward declare message handler from imgui_impl_win32.cpp
extern IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
// Win32 message handler
LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
if (ImGui_ImplWin32_WndProcHandler(hWnd, msg, wParam, lParam))
return true;
switch (msg)
{
case WM_SIZE:
if (g_pd3dDevice != NULL && wParam != SIZE_MINIMIZED)
{
CleanupRenderTarget();
g_pSwapChain->ResizeBuffers(0, (UINT)LOWORD(lParam), (UINT)HIWORD(lParam), DXGI_FORMAT_UNKNOWN, 0);
CreateRenderTarget();
}
return 0;
case WM_SYSCOMMAND:
if ((wParam & 0xfff0) == SC_KEYMENU) // Disable ALT application menu
return 0;
break;
case WM_DESTROY:
::PostQuitMessage(0);
return 0;
}
return ::DefWindowProc(hWnd, msg, wParam, lParam);
}
|
// Copyright 2021 Kuznetsov Nikita
#include <gtest/gtest.h>
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
|
#pragma once
#include <eosio/eosio.hpp>
#include <eosio/asset.hpp>
#include <eosio/system.hpp>
using namespace eosio;
using namespace std;
namespace mixin {
class [[eosio::contract("mtg.xin")]] mvmcontract : public eosio::contract {
public:
using contract::contract;
struct [[eosio::table]] tx_log {
uint64_t id;
uint64_t nonce;
name contract;
uint128_t process;
uint128_t asset;
std::vector<uint128_t> members;
int32_t threshold;
uint128_t amount;
std::vector<uint8_t> extra;
uint64_t timestamp;
uint64_t primary_key()const { return id; }
uint64_t get_contract_tx_request_nonce() const { return nonce; }
};
struct [[eosio::table]] counter {
uint64_t id;
uint64_t count;
uint64_t primary_key()const { return id; }
};
struct [[eosio::table]] process {
name contract;
uint128_t process;
uint64_t primary_key()const { return contract.value; }
};
typedef eosio::multi_index< "logs"_n, tx_log,
eosio::indexed_by< "bytxnonce"_n, eosio::const_mem_fun<tx_log, uint64_t, &tx_log::get_contract_tx_request_nonce>>
> tx_log_table;
typedef eosio::multi_index<"counters"_n, counter> counter_table;
typedef eosio::multi_index<"processes"_n, process> process_table;
[[eosio::action]]
void sayhello();
[[eosio::action]]
void addprocess(name contract, uint128_t process);
[[eosio::action]]
void txrequest(uint64_t nonce, name contract, uint128_t process, uint128_t asset,
vector<uint128_t> members, int32_t threshold, uint128_t amount,
vector<uint8_t> extra);
[[eosio::action]]
void ontxlog(ignore<tx_log>& log);
uint64_t get_next_index(uint64_t key);
uint64_t get_next_seq();
};
}
|
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/iot/model/DynamoKeyType.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/core/Globals.h>
#include <aws/core/utils/EnumParseOverflowContainer.h>
using namespace Aws::Utils;
namespace Aws
{
namespace IoT
{
namespace Model
{
namespace DynamoKeyTypeMapper
{
static const int STRING_HASH = HashingUtils::HashString("STRING");
static const int NUMBER_HASH = HashingUtils::HashString("NUMBER");
DynamoKeyType GetDynamoKeyTypeForName(const Aws::String& name)
{
int hashCode = HashingUtils::HashString(name.c_str());
if (hashCode == STRING_HASH)
{
return DynamoKeyType::STRING;
}
else if (hashCode == NUMBER_HASH)
{
return DynamoKeyType::NUMBER;
}
EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
if(overflowContainer)
{
overflowContainer->StoreOverflow(hashCode, name);
return static_cast<DynamoKeyType>(hashCode);
}
return DynamoKeyType::NOT_SET;
}
Aws::String GetNameForDynamoKeyType(DynamoKeyType enumValue)
{
switch(enumValue)
{
case DynamoKeyType::STRING:
return "STRING";
case DynamoKeyType::NUMBER:
return "NUMBER";
default:
EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
if(overflowContainer)
{
return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue));
}
return {};
}
}
} // namespace DynamoKeyTypeMapper
} // namespace Model
} // namespace IoT
} // namespace Aws
|
/*
* Copyright (C) 2005-2019 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef otbKeyPointDensityImageFilter_hxx
#define otbKeyPointDensityImageFilter_hxx
#include "otbKeyPointDensityImageFilter.h"
#include "itkImageRegionIterator.h"
namespace otb
{
/**---------------------------------------------------------
* Constructor
----------------------------------------------------------*/
template <class TInputImage, class TOutputImage, class TDetector>
KeyPointDensityImageFilter<TInputImage, TOutputImage, TDetector>
::KeyPointDensityImageFilter()
{
this->SetNumberOfRequiredInputs(1);
m_NeighborhoodRadius = 1;
m_Detector = DetectorType::New();
m_PointSetToDensityImageFilter = PointSetToDensityImageType::New();
}
/*---------------------------------------------------------
* Destructor.c
----------------------------------------------------------*/
template <class TInputImage, class TOutputImage, class TDetector>
KeyPointDensityImageFilter<TInputImage, TOutputImage, TDetector>
::~KeyPointDensityImageFilter()
{}
/**
* threaded Generate Data
*/
/**
* GenerateData Performs the pixel-wise addition
*/
template <class TInputImage, class TOutputImage, class TDetector>
void
KeyPointDensityImageFilter<TInputImage, TOutputImage, TDetector>
::GenerateData()
//::GenerateData( const OutputImageRegionType &outputRegionForThread, itk::ThreadIdType threadId )
{
typename Superclass::OutputImagePointer outputImage = this->GetOutput();
InputImagePointerType ptr = const_cast<InputImageType *>(this->GetInput());
if (!ptr) return;
/** Detector*/
m_Detector->SetInput(ptr);
/** Applying the pointsetTodensityImageFilter*/
m_PointSetToDensityImageFilter->SetInput(m_Detector->GetOutput());
m_PointSetToDensityImageFilter->SetRadius(m_NeighborhoodRadius);
m_PointSetToDensityImageFilter->SetSpacing(ptr->GetSignedSpacing());
m_PointSetToDensityImageFilter->SetSize(ptr->GetLargestPossibleRegion().GetSize());
m_PointSetToDensityImageFilter->SetOrigin(ptr->GetOrigin());
m_PointSetToDensityImageFilter->Update();
/** updating the output*/
this->GraftOutput(m_PointSetToDensityImageFilter->GetOutput());
}
/**
* Set Detector
*/
template <class TInputImage, class TOutputImage, class TDetector>
void
KeyPointDensityImageFilter<TInputImage, TOutputImage, TDetector>
::SetDetector(DetectorType* detector)
{
m_Detector = detector;
}
/**
* Get Detector
*/
template <class TInputImage, class TOutputImage, class TDetector>
typename KeyPointDensityImageFilter<TInputImage, TOutputImage, TDetector>
::DetectorType *
KeyPointDensityImageFilter<TInputImage, TOutputImage, TDetector>
::GetDetector()
{
return m_Detector;
}
/*----------------------------------------------------------------
PrintSelf
-----------------------------------------------------------------*/
template <class TInputImage, class TOutputImage, class TDetector>
void
KeyPointDensityImageFilter<TInputImage, TOutputImage, TDetector>
::PrintSelf(std::ostream& os, itk::Indent indent) const
{
Superclass::PrintSelf(os, indent);
os << indent << "Neighborhood Radius " << m_NeighborhoodRadius << std::endl;
}
} /** end namesapce otb*/
#endif
|
#include "Application.h"
#include "Window.h"
#include "Menu.h"
#include "Shader.h"
#include "../Engine/Renderer.h"
#include "../Engine/Camera.h"
#include "../Engine/Scene.h"
#include "../path.h"
float lastTime = 0;
long int currentFrame = 0;
namespace Viewer
{
static const inline std::vector<std::string> CONFIGS =
{
"ajax.scene",
"bedroom.scene",
"boy.scene",
"coffee_cart.scene",
"coffee_maker.scene",
"cornell_box.scene",
"diningroom.scene",
"dragon.scene",
"hyperion.scene",
"panther.scene",
"spaceship.scene",
"staircase.scene",
"stormtrooper.scene",
"teapot.scene",
"hyperion2.scene",
"mustang.scene",
"mustang_red.scene",
"furnace.scene"
};
static std::string GetScenePath(uint32_t index)
{
auto root = Path::Root({ "Rasterizer", "Assets", "PBRScenes" });
const auto path = root / CONFIGS[index];
std::cout << "[SCENE] Scene selected " << path.string() << std::endl;
return path.string();
}
Application::Application()
{
CreateRender();
CreateWindow();
CreatePipeline();
RegisterCallbacks();
menu->GetSettings().trianglesCount = scene->GetIndexSize() / 3;
menu->GetSettings().resolution = scene->GetRendererOptions().resolution;
}
Application::~Application() = default;
void Application::CreateWindow()
{
// Viewer composition
window.reset(new Window(scene->GetCamera().GetWidth(), scene->GetCamera().GetHeight()));
menu.reset(new Menu(*window));
shader.reset(new Shader("Quad.vert", "Quad.frag"));
}
void Application::CreateRender()
{
// Renderer composition
scene.reset(new Engine::Scene(GetScenePath(settings.sceneId)));
renderer.reset(new Engine::Renderer(*scene, scene->GetCamera()));
}
void Application::Run()
{
lastTime = glfwGetTime();
while (!glfwWindowShouldClose(window->Get()))
{
Engine::Camera::TimeDeltaUpdate();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
scene->GetCamera().OnBeforeRender();
renderer->Render(menu->GetSettings());
DrawQuad();
menu->Render();
glfwSwapBuffers(window->Get());
glfwPollEvents();
MeasureTime();
UpdateSettings();
}
}
void Application::DrawQuad() const
{
// Copy frameBuffer to texture
glTexImage2D(
GL_TEXTURE_2D, 0, GL_RGBA, scene->GetCamera().GetWidth(), scene->GetCamera().GetHeight(), 0, GL_RGBA, GL_UNSIGNED_BYTE,
renderer->GetColorBuffer());
glBindTexture(GL_TEXTURE_2D, texture);
shader->Use();
glBindVertexArray(VAO);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, nullptr);
}
void Application::RegisterCallbacks()
{
window->AddOnCursorPositionChanged([this](const double xpos, const double ypos)-> void
{
if (menu->WantCaptureKeyboard() || menu->WantCaptureMouse())
return;
if (scene->GetCamera().OnCursorPositionChanged(xpos, ypos)) {}
});
window->AddOnKeyChanged([this](const int key, const int scancode, const int action, const int mods)-> void
{
if (menu->WantCaptureKeyboard())
return;
scene->GetCamera().OnKeyChanged(key, scancode, action, mods);
});
window->AddOnMouseButtonChanged([this](const int button, const int action, const int mods)-> void
{
if (menu->WantCaptureMouse())
return;
scene->GetCamera().OnMouseButtonChanged(button, action, mods);
});
window->AddOnScrollChanged([this](const double xoffset, const double yoffset)-> void { });
}
void Application::MeasureTime() const
{
currentFrame++;
const float currentTime = glfwGetTime();
const float delta = currentTime - lastTime;
if (delta > 1.0)
{
const double fFPS = currentFrame / delta;
lastTime = currentTime;
currentFrame = 0L;
menu->GetSettings().fps = static_cast<float>(fFPS);
}
}
void Application::Resize() const
{
const auto width = scene->GetCamera().GetWidth();
const auto height = scene->GetCamera().GetHeight();
glfwSetWindowSize(window->Get(), width, height);
glViewport(0, 0, width, height);
}
void Application::UpdateSettings()
{
if (settings.sceneId != menu->GetSettings().sceneId)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
settings = menu->GetSettings();
Recreate();
menu->GetSettings().trianglesCount = scene->GetIndexSize() / 3;
menu->GetSettings().resolution = scene->GetRendererOptions().resolution;
}
}
void Application::Recreate()
{
CreateRender();
Resize();
}
void Application::CreatePipeline()
{
static float vertices[] =
{
1.f, 1.f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, // top right
1.f, -1.f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, // bottom right
-1.f, -1.f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, // bottom left
-1.f, 1.f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f // top left
};
static unsigned int indices[] =
{
0, 1, 3,
1, 2, 3
};
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
glGenBuffers(1, &EBO);
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), static_cast<void*>(nullptr));
glEnableVertexAttribArray(0);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), reinterpret_cast<void*>(3 * sizeof(float)));
glEnableVertexAttribArray(1);
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(float), reinterpret_cast<void*>(6 * sizeof(float)));
glEnableVertexAttribArray(2);
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
}
}
|
#include <_economy_history_dataDetail.hpp>
#include <common/ATFCore.hpp>
START_ATF_NAMESPACE
namespace Detail
{
Info::_economy_history_dataInit2_ptr _economy_history_dataInit2_next(nullptr);
Info::_economy_history_dataInit2_clbk _economy_history_dataInit2_user(nullptr);
Info::_economy_history_datactor__economy_history_data4_ptr _economy_history_datactor__economy_history_data4_next(nullptr);
Info::_economy_history_datactor__economy_history_data4_clbk _economy_history_datactor__economy_history_data4_user(nullptr);
void _economy_history_dataInit2_wrapper(struct _economy_history_data* _this)
{
_economy_history_dataInit2_user(_this, _economy_history_dataInit2_next);
};
void _economy_history_datactor__economy_history_data4_wrapper(struct _economy_history_data* _this)
{
_economy_history_datactor__economy_history_data4_user(_this, _economy_history_datactor__economy_history_data4_next);
};
::std::array<hook_record, 2> _economy_history_data_functions =
{
_hook_record {
(LPVOID)0x1402058c0L,
(LPVOID *)&_economy_history_dataInit2_user,
(LPVOID *)&_economy_history_dataInit2_next,
(LPVOID)cast_pointer_function(_economy_history_dataInit2_wrapper),
(LPVOID)cast_pointer_function((void(_economy_history_data::*)())&_economy_history_data::Init)
},
_hook_record {
(LPVOID)0x140205870L,
(LPVOID *)&_economy_history_datactor__economy_history_data4_user,
(LPVOID *)&_economy_history_datactor__economy_history_data4_next,
(LPVOID)cast_pointer_function(_economy_history_datactor__economy_history_data4_wrapper),
(LPVOID)cast_pointer_function((void(_economy_history_data::*)())&_economy_history_data::ctor__economy_history_data)
},
};
}; // end namespace Detail
END_ATF_NAMESPACE
|
#include <dae.h>
#include <dae/daeDom.h>
#include <1.5/dom/domMatrix.h>
#include <dae/daeMetaCMPolicy.h>
#include <dae/daeMetaSequence.h>
#include <dae/daeMetaChoice.h>
#include <dae/daeMetaGroup.h>
#include <dae/daeMetaAny.h>
#include <dae/daeMetaElementAttribute.h>
namespace ColladaDOM150 {
daeElementRef
domMatrix::create(DAE& dae)
{
domMatrixRef ref = new domMatrix(dae);
return ref;
}
daeMetaElement *
domMatrix::registerElement(DAE& dae)
{
daeMetaElement* meta = dae.getMeta(ID());
if ( meta != NULL ) return meta;
meta = new daeMetaElement(dae);
dae.setMeta(ID(), *meta);
meta->setName( "matrix" );
meta->registerClass(domMatrix::create);
// Add attribute: _value
{
daeMetaAttribute *ma = new daeMetaArrayAttribute;
ma->setName( "_value" );
ma->setType( dae.getAtomicTypes().get("Float4x4"));
ma->setOffset( daeOffsetOf( domMatrix , _value ));
ma->setContainer( meta );
meta->appendAttribute(ma);
}
// Add attribute: sid
{
daeMetaAttribute *ma = new daeMetaAttribute;
ma->setName( "sid" );
ma->setType( dae.getAtomicTypes().get("Sid"));
ma->setOffset( daeOffsetOf( domMatrix , attrSid ));
ma->setContainer( meta );
meta->appendAttribute(ma);
}
meta->setElementSize(sizeof(domMatrix));
meta->validate();
return meta;
}
} // ColladaDOM150
|
class Solution {
public:
int minSubArrayLen(int s, vector<int>& nums) {
if (nums.size() == 0) return 0;
int ans = INT_MAX;
int count = 0;
int sum = 0;
for (int i = 0; i < nums.size(); i++) {
sum += nums[i];
count++;
while (sum >= s) {
if (sum >= s) ans = min(ans, count);
sum -= nums[i - count + 1];
count--;
}
}
if (ans == INT_MAX) return 0;
return ans;
}
};
|
#include<fstream>
#include<math.h>
using namespace std;
ifstream cin("triplet.in");
ofstream cout("triplet.out");
long long n, pp[200000005], i, j, li, ls, mij ;
int cautbin1(int x)
{
li=1; ls=n;
while(li<ls)
{ mij=(li+ls)/2;
if(pp[mij]==x) return 1;
else if(pp[mij]>x) ls=mij-1;
else li=mij+1;}
return 0;
}
int main()
{
cin>>n;
for(i=1;i<=n;i++)
{pp[i]=i*i; //cout<<pp[i]<<" ";}
}
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
if(cautbin1(n-pp[i]-pp[j]))
{ cout<<i<<" "<<j<<" "<<mij; return 0; }
}
|
#include "lipch.h"
#include "RenderCommand.h"
#include "Platform/OpenGL/OpenGLRendererAPI.h"
namespace Lilith {
RendererAPI* RenderCommand::s_RendererAPI = new OpenGLRendererAPI;
}
|
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
#include "beatsaber-hook/shared/utils/typedefs-string.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System
namespace System {
// Forward declaring type: TypeCode
struct TypeCode;
// Forward declaring type: IFormatProvider
class IFormatProvider;
// Forward declaring type: Decimal
struct Decimal;
// Forward declaring type: DateTime
struct DateTime;
// Forward declaring type: Type
class Type;
}
// Completed forward declares
// Type namespace: System
namespace System {
// Forward declaring type: IConvertible
class IConvertible;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::System::IConvertible);
DEFINE_IL2CPP_ARG_TYPE(::System::IConvertible*, "System", "IConvertible");
// Type namespace: System
namespace System {
// Size: 0x10
#pragma pack(push, 1)
// Autogenerated type: System.IConvertible
// [TokenAttribute] Offset: FFFFFFFF
// [ComVisibleAttribute] Offset: 11A8764
// [CLSCompliantAttribute] Offset: 11A8764
class IConvertible {
public:
// public System.TypeCode GetTypeCode()
// Offset: 0xFFFFFFFFFFFFFFFF
::System::TypeCode GetTypeCode();
// public System.Boolean ToBoolean(System.IFormatProvider provider)
// Offset: 0xFFFFFFFFFFFFFFFF
bool ToBoolean(::System::IFormatProvider* provider);
// public System.Char ToChar(System.IFormatProvider provider)
// Offset: 0xFFFFFFFFFFFFFFFF
::Il2CppChar ToChar(::System::IFormatProvider* provider);
// public System.SByte ToSByte(System.IFormatProvider provider)
// Offset: 0xFFFFFFFFFFFFFFFF
int8_t ToSByte(::System::IFormatProvider* provider);
// public System.Byte ToByte(System.IFormatProvider provider)
// Offset: 0xFFFFFFFFFFFFFFFF
uint8_t ToByte(::System::IFormatProvider* provider);
// public System.Int16 ToInt16(System.IFormatProvider provider)
// Offset: 0xFFFFFFFFFFFFFFFF
int16_t ToInt16(::System::IFormatProvider* provider);
// public System.UInt16 ToUInt16(System.IFormatProvider provider)
// Offset: 0xFFFFFFFFFFFFFFFF
uint16_t ToUInt16(::System::IFormatProvider* provider);
// public System.Int32 ToInt32(System.IFormatProvider provider)
// Offset: 0xFFFFFFFFFFFFFFFF
int ToInt32(::System::IFormatProvider* provider);
// public System.UInt32 ToUInt32(System.IFormatProvider provider)
// Offset: 0xFFFFFFFFFFFFFFFF
uint ToUInt32(::System::IFormatProvider* provider);
// public System.Int64 ToInt64(System.IFormatProvider provider)
// Offset: 0xFFFFFFFFFFFFFFFF
int64_t ToInt64(::System::IFormatProvider* provider);
// public System.UInt64 ToUInt64(System.IFormatProvider provider)
// Offset: 0xFFFFFFFFFFFFFFFF
uint64_t ToUInt64(::System::IFormatProvider* provider);
// public System.Single ToSingle(System.IFormatProvider provider)
// Offset: 0xFFFFFFFFFFFFFFFF
float ToSingle(::System::IFormatProvider* provider);
// public System.Double ToDouble(System.IFormatProvider provider)
// Offset: 0xFFFFFFFFFFFFFFFF
double ToDouble(::System::IFormatProvider* provider);
// public System.Decimal ToDecimal(System.IFormatProvider provider)
// Offset: 0xFFFFFFFFFFFFFFFF
::System::Decimal ToDecimal(::System::IFormatProvider* provider);
// public System.DateTime ToDateTime(System.IFormatProvider provider)
// Offset: 0xFFFFFFFFFFFFFFFF
::System::DateTime ToDateTime(::System::IFormatProvider* provider);
// public System.String ToString(System.IFormatProvider provider)
// Offset: 0xFFFFFFFFFFFFFFFF
::StringW ToString(::System::IFormatProvider* provider);
// public System.Object ToType(System.Type conversionType, System.IFormatProvider provider)
// Offset: 0xFFFFFFFFFFFFFFFF
::Il2CppObject* ToType(::System::Type* conversionType, ::System::IFormatProvider* provider);
}; // System.IConvertible
#pragma pack(pop)
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: System::IConvertible::GetTypeCode
// Il2CppName: GetTypeCode
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::TypeCode (System::IConvertible::*)()>(&System::IConvertible::GetTypeCode)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::IConvertible*), "GetTypeCode", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::IConvertible::ToBoolean
// Il2CppName: ToBoolean
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (System::IConvertible::*)(::System::IFormatProvider*)>(&System::IConvertible::ToBoolean)> {
static const MethodInfo* get() {
static auto* provider = &::il2cpp_utils::GetClassFromName("System", "IFormatProvider")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::IConvertible*), "ToBoolean", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{provider});
}
};
// Writing MetadataGetter for method: System::IConvertible::ToChar
// Il2CppName: ToChar
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Il2CppChar (System::IConvertible::*)(::System::IFormatProvider*)>(&System::IConvertible::ToChar)> {
static const MethodInfo* get() {
static auto* provider = &::il2cpp_utils::GetClassFromName("System", "IFormatProvider")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::IConvertible*), "ToChar", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{provider});
}
};
// Writing MetadataGetter for method: System::IConvertible::ToSByte
// Il2CppName: ToSByte
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int8_t (System::IConvertible::*)(::System::IFormatProvider*)>(&System::IConvertible::ToSByte)> {
static const MethodInfo* get() {
static auto* provider = &::il2cpp_utils::GetClassFromName("System", "IFormatProvider")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::IConvertible*), "ToSByte", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{provider});
}
};
// Writing MetadataGetter for method: System::IConvertible::ToByte
// Il2CppName: ToByte
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<uint8_t (System::IConvertible::*)(::System::IFormatProvider*)>(&System::IConvertible::ToByte)> {
static const MethodInfo* get() {
static auto* provider = &::il2cpp_utils::GetClassFromName("System", "IFormatProvider")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::IConvertible*), "ToByte", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{provider});
}
};
// Writing MetadataGetter for method: System::IConvertible::ToInt16
// Il2CppName: ToInt16
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int16_t (System::IConvertible::*)(::System::IFormatProvider*)>(&System::IConvertible::ToInt16)> {
static const MethodInfo* get() {
static auto* provider = &::il2cpp_utils::GetClassFromName("System", "IFormatProvider")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::IConvertible*), "ToInt16", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{provider});
}
};
// Writing MetadataGetter for method: System::IConvertible::ToUInt16
// Il2CppName: ToUInt16
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<uint16_t (System::IConvertible::*)(::System::IFormatProvider*)>(&System::IConvertible::ToUInt16)> {
static const MethodInfo* get() {
static auto* provider = &::il2cpp_utils::GetClassFromName("System", "IFormatProvider")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::IConvertible*), "ToUInt16", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{provider});
}
};
// Writing MetadataGetter for method: System::IConvertible::ToInt32
// Il2CppName: ToInt32
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (System::IConvertible::*)(::System::IFormatProvider*)>(&System::IConvertible::ToInt32)> {
static const MethodInfo* get() {
static auto* provider = &::il2cpp_utils::GetClassFromName("System", "IFormatProvider")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::IConvertible*), "ToInt32", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{provider});
}
};
// Writing MetadataGetter for method: System::IConvertible::ToUInt32
// Il2CppName: ToUInt32
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<uint (System::IConvertible::*)(::System::IFormatProvider*)>(&System::IConvertible::ToUInt32)> {
static const MethodInfo* get() {
static auto* provider = &::il2cpp_utils::GetClassFromName("System", "IFormatProvider")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::IConvertible*), "ToUInt32", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{provider});
}
};
// Writing MetadataGetter for method: System::IConvertible::ToInt64
// Il2CppName: ToInt64
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int64_t (System::IConvertible::*)(::System::IFormatProvider*)>(&System::IConvertible::ToInt64)> {
static const MethodInfo* get() {
static auto* provider = &::il2cpp_utils::GetClassFromName("System", "IFormatProvider")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::IConvertible*), "ToInt64", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{provider});
}
};
// Writing MetadataGetter for method: System::IConvertible::ToUInt64
// Il2CppName: ToUInt64
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<uint64_t (System::IConvertible::*)(::System::IFormatProvider*)>(&System::IConvertible::ToUInt64)> {
static const MethodInfo* get() {
static auto* provider = &::il2cpp_utils::GetClassFromName("System", "IFormatProvider")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::IConvertible*), "ToUInt64", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{provider});
}
};
// Writing MetadataGetter for method: System::IConvertible::ToSingle
// Il2CppName: ToSingle
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<float (System::IConvertible::*)(::System::IFormatProvider*)>(&System::IConvertible::ToSingle)> {
static const MethodInfo* get() {
static auto* provider = &::il2cpp_utils::GetClassFromName("System", "IFormatProvider")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::IConvertible*), "ToSingle", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{provider});
}
};
// Writing MetadataGetter for method: System::IConvertible::ToDouble
// Il2CppName: ToDouble
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<double (System::IConvertible::*)(::System::IFormatProvider*)>(&System::IConvertible::ToDouble)> {
static const MethodInfo* get() {
static auto* provider = &::il2cpp_utils::GetClassFromName("System", "IFormatProvider")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::IConvertible*), "ToDouble", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{provider});
}
};
// Writing MetadataGetter for method: System::IConvertible::ToDecimal
// Il2CppName: ToDecimal
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Decimal (System::IConvertible::*)(::System::IFormatProvider*)>(&System::IConvertible::ToDecimal)> {
static const MethodInfo* get() {
static auto* provider = &::il2cpp_utils::GetClassFromName("System", "IFormatProvider")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::IConvertible*), "ToDecimal", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{provider});
}
};
// Writing MetadataGetter for method: System::IConvertible::ToDateTime
// Il2CppName: ToDateTime
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::DateTime (System::IConvertible::*)(::System::IFormatProvider*)>(&System::IConvertible::ToDateTime)> {
static const MethodInfo* get() {
static auto* provider = &::il2cpp_utils::GetClassFromName("System", "IFormatProvider")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::IConvertible*), "ToDateTime", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{provider});
}
};
// Writing MetadataGetter for method: System::IConvertible::ToString
// Il2CppName: ToString
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::StringW (System::IConvertible::*)(::System::IFormatProvider*)>(&System::IConvertible::ToString)> {
static const MethodInfo* get() {
static auto* provider = &::il2cpp_utils::GetClassFromName("System", "IFormatProvider")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::IConvertible*), "ToString", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{provider});
}
};
// Writing MetadataGetter for method: System::IConvertible::ToType
// Il2CppName: ToType
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Il2CppObject* (System::IConvertible::*)(::System::Type*, ::System::IFormatProvider*)>(&System::IConvertible::ToType)> {
static const MethodInfo* get() {
static auto* conversionType = &::il2cpp_utils::GetClassFromName("System", "Type")->byval_arg;
static auto* provider = &::il2cpp_utils::GetClassFromName("System", "IFormatProvider")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::IConvertible*), "ToType", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{conversionType, provider});
}
};
|
/**********************************************************************************
* MIT License
*
* Copyright (c) 2018 Antoine Beauchamp
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*********************************************************************************/
#include "ArrayGenerator.h"
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <stdlib.h>
#include "rapidassist/code_cpp.h"
#include "rapidassist/strings.h"
#include "rapidassist/filesystem.h"
namespace bin2cpp
{
ArrayGenerator::ArrayGenerator()
{
}
ArrayGenerator::~ArrayGenerator()
{
}
const char * ArrayGenerator::getName() const
{
return "array";
}
bool ArrayGenerator::createCppSourceFile(const char * cpp_file_path)
{
//check if input file exists
FILE * input = fopen(mInputFile.c_str(), "rb");
if (!input)
return false;
//Uppercase function identifier
std::string functionIdentifier = ra::strings::CapitalizeFirstCharacter(mFunctionIdentifier);
//Build header and cpp file path
std::string headerPath = getHeaderFilePath(cpp_file_path);
std::string cppPath = cpp_file_path;
std::string headerFilename = ra::filesystem::GetFilename(headerPath.c_str());
std::string cppFilename = ra::filesystem::GetFilename(cpp_file_path);
//create cpp file
FILE * cpp = fopen(cppPath.c_str(), "w");
if (!cpp)
{
fclose(input);
return false;
}
//determine file properties
uint32_t fileSize = ra::filesystem::GetFileSize(input);
std::string filename = ra::filesystem::GetFilename(mInputFile.c_str());
//Build class name
std::string className = getClassName();
//Build function
std::string getterFunctionName = getGetterFunctionName();
//write cpp file heading
fprintf(cpp, "%s", getHeaderTemplate().c_str());
fprintf(cpp, "#include \"%s\"\n", headerFilename.c_str() );
fprintf(cpp, "#include <stdio.h> //for FILE\n");
fprintf(cpp, "#include <string> //for memcpy\n");
fprintf(cpp, "namespace %s\n", mNamespace.c_str());
fprintf(cpp, "{\n");
fprintf(cpp, " class %s : public virtual %s::%s\n", className.c_str(), mNamespace.c_str(), mBaseClass.c_str());
fprintf(cpp, " {\n");
fprintf(cpp, " public:\n");
fprintf(cpp, " %s() {}\n", className.c_str());
fprintf(cpp, " virtual ~%s() {}\n", className.c_str());
fprintf(cpp, " virtual size_t getSize() const { return %u; }\n", fileSize);
fprintf(cpp, " virtual const char * getFilename() const { return \"%s\"; }\n", ra::filesystem::GetFilename(mInputFile.c_str()).c_str());
fprintf(cpp, " virtual const char * getBuffer() const\n");
fprintf(cpp, " {\n");
fprintf(cpp, " static const unsigned char buffer[] = {\n");
//create buffer for each chunks from input buffer
int numLinePrinted = 0;
unsigned char * buffer = new unsigned char[mChunkSize];
while(!feof(input))
{
//read a chunk of the file
size_t readSize = fread(buffer, 1, mChunkSize, input);
bool isLastChunk = !(readSize == mChunkSize);
if (readSize > 0)
{
if (numLinePrinted > 0)
{
//end previous line
fprintf(cpp, ",\n");
}
//output
fprintf(cpp, " %s", ra::code::cpp::ToCppCharactersArray(buffer, readSize).c_str());
numLinePrinted++;
}
//end the array. all the file content is printed
if (isLastChunk)
{
fprintf(cpp, "\n");
fprintf(cpp, " };\n");
}
}
delete[] buffer;
buffer = NULL;
//write cpp file footer
fprintf(cpp, " return (const char *)buffer;\n");
fprintf(cpp, " }\n");
fprintf(cpp, "%s", getSaveMethodTemplate().c_str());
fprintf(cpp, " };\n");
fprintf(cpp, " const %s & %s() { static %s _instance; return _instance; }\n", mBaseClass.c_str(), getterFunctionName.c_str(), className.c_str());
if (isRegisterFileEnabled())
{
std::string fileManagerTemplate = getFileManagerRegistrationTemplate();
fprintf(cpp, "%s", fileManagerTemplate.c_str());
}
fprintf(cpp, "}; //%s\n", mNamespace.c_str());
fclose(input);
fclose(cpp);
return true;
}
}; //bin2cpp
|
/**
*
* @file regist.cpp
* @brief
* @author rururu
*
*/
#include <windows.h>
#include "winamp/in2.h"
#include "winamp/wa_ipc.h"
#include "interface.hpp"
#include "version.hpp"
namespace FmPmd {
In_Module module = {
IN_VER,
PLUGIN_DETAIL,
0, /* hMainWindow (filled in by winamp after init() ) */
0, /* hDllInstance ( Also filled in by winamp) */
NULL, // FileExtensions handled by this DLL
1, /* is_seekable (is this stream seekable?) */
1, /* uses output (does this plug-in use the output plug-ins?) */
Config,
About,
Init,
Quit,
GetFileInfo,
InfoBox,
IsOurFile,
/* PLAYBACK STUFF */
Play,
Pause,
UnPause,
IsPaused,
Stop,
/* TIME STUFF */
GetLength,
GetOutputTime,
SetOutputTime,
/* VOLUME STUFF */
SetVolume,
SetPan,
/* VIS STUFF */
0,0,0,0,0,0,0,0,0,
/* DSP STUFF */
0,0,
/* EQ STUFF */
SetEq,
/* info setting (filled in by winamp) */
NULL,
/* Out_Module *outMod; (filled in by winamp, optionally used) */
0
};
}
extern "C" {
/**
* Get module pointer
*
* @return pointer of input plugin's module
*/
__declspec(dllexport) In_Module *winampGetInModule2()
{
// Load DLL
if (!FmPmd::module.FileExtensions)
FmPmd::LoadDll(const_cast<const char*&>(FmPmd::module.FileExtensions));
return &FmPmd::module;
}
#ifndef UNICODE_INPUT_PLUGIN
/**
* Get extendeed file information(ANSI/MultiByte)
*
* @param p_file [in]
*
* @param p_metadeta [in]
*
* @param p_ret [out]
*
* @param p_retlen [out]
*
* @return ok(1) / ng(0)
*/
__declspec(dllexport) int winampGetExtendedFileInfo(char *p_file, char *p_metadata, char *p_ret, int p_retlen)
{
return FmPmd::GetExtendedFileInfo(p_file, p_metadata, p_ret, p_retlen);
}
#else
/**
* Get extendeed file information(UTF-16)
*
* @param p_extended_info [in/out]
*
* @return ok(1) / ng(0)
*/
__declspec(dllexport) int winampGetExtendedFileInfoW(extendedFileInfoStructW p_extended_info)
{
return FmPmd::GetExtendedFileInfoW(p_extended_info);
}
}
#endif
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#include <catch.hpp>
#include <sstream>
#include "frequent_items_sketch.hpp"
#include "test_type.hpp"
namespace datasketches {
typedef frequent_items_sketch<test_type, float, test_type_hash, test_type_equal, test_type_serde> frequent_test_type_sketch;
TEST_CASE("frequent items: custom type", "[frequent_items_sketch]") {
frequent_test_type_sketch sketch(3);
sketch.update(1, 10); // should survive the purge
sketch.update(2);
sketch.update(3);
sketch.update(4);
sketch.update(5);
sketch.update(6);
sketch.update(7);
test_type a8(8);
sketch.update(a8);
REQUIRE_FALSE(sketch.is_empty());
REQUIRE(sketch.get_total_weight() == 17);
REQUIRE(sketch.get_estimate(1) == 10);
//std::cerr << "num active: " << sketch.get_num_active_items() << std::endl;
//std::cerr << "get frequent items" << std::endl;
auto items = sketch.get_frequent_items(frequent_items_error_type::NO_FALSE_POSITIVES);
REQUIRE(items.size() == 1); // only 1 item should be above threshold
REQUIRE(items[0].get_item().get_value() == 1);
REQUIRE(items[0].get_estimate() == 10);
std::stringstream s(std::ios::in | std::ios::out | std::ios::binary);
//std::cerr << "serialize" << std::endl;
sketch.serialize(s);
//std::cerr << "deserialize" << std::endl;
auto sketch2 = frequent_test_type_sketch::deserialize(s);
REQUIRE_FALSE(sketch2.is_empty());
REQUIRE(sketch2.get_total_weight() == 17);
REQUIRE(sketch2.get_estimate(1) == 10);
REQUIRE(sketch.get_num_active_items() == sketch2.get_num_active_items());
REQUIRE(sketch.get_maximum_error() == sketch2.get_maximum_error());
//std::cerr << "end" << std::endl;
sketch2.to_stream(std::cerr, true);
}
// this is to see the debug print from test_type if enabled there to make sure items are moved
TEST_CASE("frequent items: moving merge", "[frequent_items_sketch]") {
frequent_test_type_sketch sketch1(3);
sketch1.update(1);
frequent_test_type_sketch sketch2(3);
sketch2.update(2);
sketch2.merge(std::move(sketch1));
REQUIRE(sketch2.get_total_weight() == 2);
}
TEST_CASE("frequent items: negative weight", "[frequent_items_sketch]") {
frequent_test_type_sketch sketch(3);
REQUIRE_THROWS_AS(sketch.update(1, -1), std::invalid_argument);
}
} /* namespace datasketches */
|
/** \file MaskPredictorIndex.hh
*
* Auto generated C++ code started by /home/magnus/gem5-stable_2014_12_14/src/mem/slicc/symbols/Type.py:444
*/
#ifndef __MaskPredictorIndex_HH__
#define __MaskPredictorIndex_HH__
#include <iostream>
#include <string>
// Class definition
/** \enum MaskPredictorIndex
* \brief ...
*/
enum MaskPredictorIndex {
MaskPredictorIndex_FIRST,
MaskPredictorIndex_Undefined = MaskPredictorIndex_FIRST, /**< Undefined */
MaskPredictorIndex_DataBlock, /**< Data Block */
MaskPredictorIndex_PC, /**< Program Counter */
MaskPredictorIndex_NUM
};
// Code to convert from a string to the enumeration
MaskPredictorIndex string_to_MaskPredictorIndex(const std::string& str);
// Code to convert state to a string
std::string MaskPredictorIndex_to_string(const MaskPredictorIndex& obj);
// Code to increment an enumeration type
MaskPredictorIndex &operator++(MaskPredictorIndex &e);
std::ostream& operator<<(std::ostream& out, const MaskPredictorIndex& obj);
#endif // __MaskPredictorIndex_HH__
|
/*=========================================================================
*
* Copyright NumFOCUS
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#include "itkBinaryBallStructuringElement.h"
#include "itkMorphologyHistogram.h"
#include "itkMovingHistogramMorphologyImageFilter.h"
#include "itkTestingMacros.h"
int
itkMovingHistogramMorphologyImageFilterTest(int, char ** const)
{
constexpr unsigned int Dimension = 2;
using PixelType = float;
using ImageType = itk::Image<PixelType, Dimension>;
using KernelType = itk::BinaryBallStructuringElement<PixelType, Dimension>;
using HistogramType = itk::Function::MorphologyHistogram<PixelType, std::greater<PixelType>>;
using FilterType = itk::MovingHistogramMorphologyImageFilter<ImageType, ImageType, KernelType, HistogramType>;
auto filter = FilterType::New();
ITK_EXERCISE_BASIC_OBJECT_METHODS(filter, MovingHistogramMorphologyImageFilter, MovingHistogramImageFilter);
typename FilterType::InputImagePixelType boundary = 255;
filter->SetBoundary(boundary);
ITK_TEST_SET_GET_VALUE(boundary, filter->GetBoundary());
std::cout << "Test finished." << std::endl;
return EXIT_SUCCESS;
}
|
/* libs/pixelflinger/scanline.cpp
**
** Copyright 2006, The Android Open Source Project
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
#define LOG_TAG "pixelflinger"
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <cutils/memory.h>
#include <cutils/log.h>
#include "buffer.h"
#include "scanline.h"
#include "codeflinger/CodeCache.h"
#include "codeflinger/GGLAssembler.h"
#include "codeflinger/ARMAssembler.h"
//#include "codeflinger/ARMAssemblerOptimizer.h"
// ----------------------------------------------------------------------------
#define ANDROID_CODEGEN_GENERIC 0 // force generic pixel pipeline
#define ANDROID_CODEGEN_C 1 // hand-written C, fallback generic
#define ANDROID_CODEGEN_ASM 2 // hand-written asm, fallback generic
#define ANDROID_CODEGEN_GENERATED 3 // hand-written asm, fallback codegen
#ifdef NDEBUG
# define ANDROID_RELEASE
# define ANDROID_CODEGEN ANDROID_CODEGEN_GENERATED
#else
# define ANDROID_DEBUG
# define ANDROID_CODEGEN ANDROID_CODEGEN_GENERATED
#endif
#if defined(__arm__)
# define ANDROID_ARM_CODEGEN 1
#else
# define ANDROID_ARM_CODEGEN 0
#endif
#define DEBUG__CODEGEN_ONLY 0
#define ASSEMBLY_SCRATCH_SIZE 2048
// ----------------------------------------------------------------------------
namespace android {
// ----------------------------------------------------------------------------
static void init_y(context_t*, int32_t);
static void init_y_noop(context_t*, int32_t);
static void init_y_packed(context_t*, int32_t);
static void init_y_error(context_t*, int32_t);
static void step_y__generic(context_t* c);
static void step_y__nop(context_t*);
static void step_y__smooth(context_t* c);
static void step_y__tmu(context_t* c);
static void step_y__w(context_t* c);
static void scanline(context_t* c);
static void scanline_perspective(context_t* c);
static void scanline_perspective_single(context_t* c);
static void scanline_t32cb16blend(context_t* c);
static void scanline_t32cb16(context_t* c);
static void scanline_memcpy(context_t* c);
static void scanline_memset8(context_t* c);
static void scanline_memset16(context_t* c);
static void scanline_memset32(context_t* c);
static void scanline_noop(context_t* c);
static void scanline_set(context_t* c);
static void scanline_clear(context_t* c);
static void rect_generic(context_t* c, size_t yc);
static void rect_memcpy(context_t* c, size_t yc);
extern "C" void scanline_t32cb16blend_arm(uint16_t*, uint32_t*, size_t);
extern "C" void scanline_t32cb16_arm(uint16_t *dst, uint32_t *src, size_t ct);
// ----------------------------------------------------------------------------
struct shortcut_t {
needs_filter_t filter;
const char* desc;
void (*scanline)(context_t*);
void (*init_y)(context_t*, int32_t);
};
// Keep in sync with needs
static shortcut_t shortcuts[] = {
{ { { 0x03515104, 0x00000077, { 0x00000A01, 0x00000000 } },
{ 0xFFFFFFFF, 0xFFFFFFFF, { 0xFFFFFFFF, 0x0000003F } } },
"565 fb, 8888 tx, blend", scanline_t32cb16blend, init_y_noop },
{ { { 0x03010104, 0x00000077, { 0x00000A01, 0x00000000 } },
{ 0xFFFFFFFF, 0xFFFFFFFF, { 0xFFFFFFFF, 0x0000003F } } },
"565 fb, 8888 tx", scanline_t32cb16, init_y_noop },
{ { { 0x00000000, 0x00000000, { 0x00000000, 0x00000000 } },
{ 0x00000000, 0x00000007, { 0x00000000, 0x00000000 } } },
"(nop) alpha test", scanline_noop, init_y_noop },
{ { { 0x00000000, 0x00000000, { 0x00000000, 0x00000000 } },
{ 0x00000000, 0x00000070, { 0x00000000, 0x00000000 } } },
"(nop) depth test", scanline_noop, init_y_noop },
{ { { 0x05000000, 0x00000000, { 0x00000000, 0x00000000 } },
{ 0x0F000000, 0x00000080, { 0x00000000, 0x00000000 } } },
"(nop) logic_op", scanline_noop, init_y_noop },
{ { { 0xF0000000, 0x00000000, { 0x00000000, 0x00000000 } },
{ 0xF0000000, 0x00000080, { 0x00000000, 0x00000000 } } },
"(nop) color mask", scanline_noop, init_y_noop },
{ { { 0x0F000000, 0x00000077, { 0x00000000, 0x00000000 } },
{ 0xFF000000, 0x000000F7, { 0x00000000, 0x00000000 } } },
"(set) logic_op", scanline_set, init_y_noop },
{ { { 0x00000000, 0x00000077, { 0x00000000, 0x00000000 } },
{ 0xFF000000, 0x000000F7, { 0x00000000, 0x00000000 } } },
"(clear) logic_op", scanline_clear, init_y_noop },
{ { { 0x03000000, 0x00000077, { 0x00000000, 0x00000000 } },
{ 0xFFFFFF00, 0x000000F7, { 0x00000000, 0x00000000 } } },
"(clear) blending 0/0", scanline_clear, init_y_noop },
{ { { 0x00000000, 0x00000000, { 0x00000000, 0x00000000 } },
{ 0x0000003F, 0x00000000, { 0x00000000, 0x00000000 } } },
"(error) invalid color-buffer format", scanline_noop, init_y_error },
};
static const needs_filter_t noblend1to1 = {
// (disregard dithering, see below)
{ 0x03010100, 0x00000077, { 0x00000A00, 0x00000000 } },
{ 0xFFFFFFC0, 0xFFFFFEFF, { 0xFFFFFFC0, 0x0000003F } }
};
static const needs_filter_t fill16noblend = {
{ 0x03010100, 0x00000077, { 0x00000000, 0x00000000 } },
{ 0xFFFFFFC0, 0xFFFFFFFF, { 0x0000003F, 0x0000003F } }
};
// ----------------------------------------------------------------------------
#if ANDROID_ARM_CODEGEN
static CodeCache gCodeCache(12 * 1024);
class ScanlineAssembly : public Assembly {
AssemblyKey<needs_t> mKey;
public:
ScanlineAssembly(needs_t needs, size_t size)
: Assembly(size), mKey(needs) { }
const AssemblyKey<needs_t>& key() const { return mKey; }
};
#endif
// ----------------------------------------------------------------------------
void ggl_init_scanline(context_t* c)
{
c->init_y = init_y;
c->step_y = step_y__generic;
c->scanline = scanline;
}
void ggl_uninit_scanline(context_t* c)
{
if (c->state.buffers.coverage)
free(c->state.buffers.coverage);
#if ANDROID_ARM_CODEGEN
if (c->scanline_as)
c->scanline_as->decStrong(c);
#endif
}
// ----------------------------------------------------------------------------
static void pick_scanline(context_t* c)
{
#if (!defined(DEBUG__CODEGEN_ONLY) || (DEBUG__CODEGEN_ONLY == 0))
#if ANDROID_CODEGEN == ANDROID_CODEGEN_GENERIC
c->init_y = init_y;
c->step_y = step_y__generic;
c->scanline = scanline;
return;
#endif
//printf("*** needs [%08lx:%08lx:%08lx:%08lx]\n",
// c->state.needs.n, c->state.needs.p,
// c->state.needs.t[0], c->state.needs.t[1]);
// first handle the special case that we cannot test with a filter
const uint32_t cb_format = GGL_READ_NEEDS(CB_FORMAT, c->state.needs.n);
if (GGL_READ_NEEDS(T_FORMAT, c->state.needs.t[0]) == cb_format) {
if (c->state.needs.match(noblend1to1)) {
// this will match regardless of dithering state, since both
// src and dest have the same format anyway, there is no dithering
// to be done.
const GGLFormat* f =
&(c->formats[GGL_READ_NEEDS(T_FORMAT, c->state.needs.t[0])]);
if ((f->components == GGL_RGB) ||
(f->components == GGL_RGBA) ||
(f->components == GGL_LUMINANCE) ||
(f->components == GGL_LUMINANCE_ALPHA))
{
// format must have all of RGB components
// (so the current color doesn't show through)
c->scanline = scanline_memcpy;
c->init_y = init_y_noop;
return;
}
}
}
if (c->state.needs.match(fill16noblend)) {
c->init_y = init_y_packed;
switch (c->formats[cb_format].size) {
case 1: c->scanline = scanline_memset8; return;
case 2: c->scanline = scanline_memset16; return;
case 4: c->scanline = scanline_memset32; return;
}
}
const int numFilters = sizeof(shortcuts)/sizeof(shortcut_t);
for (int i=0 ; i<numFilters ; i++) {
if (c->state.needs.match(shortcuts[i].filter)) {
c->scanline = shortcuts[i].scanline;
c->init_y = shortcuts[i].init_y;
return;
}
}
#endif // DEBUG__CODEGEN_ONLY
c->init_y = init_y;
c->step_y = step_y__generic;
#if ANDROID_ARM_CODEGEN
// we're going to have to generate some code...
// here, generate code for our pixel pipeline
const AssemblyKey<needs_t> key(c->state.needs);
sp<Assembly> assembly = gCodeCache.lookup(key);
if (assembly == 0) {
// create a new assembly region
sp<ScanlineAssembly> a = new ScanlineAssembly(c->state.needs,
ASSEMBLY_SCRATCH_SIZE);
// initialize our assembler
GGLAssembler assembler( new ARMAssembler(a) );
//GGLAssembler assembler(
// new ARMAssemblerOptimizer(new ARMAssembler(a)) );
// generate the scanline code for the given needs
int err = assembler.scanline(c->state.needs, c);
if (ggl_likely(!err)) {
// finally, cache this assembly
err = gCodeCache.cache(a->key(), a);
}
if (ggl_unlikely(err)) {
LOGE("error generating or caching assembly. Reverting to NOP.");
c->scanline = scanline_noop;
c->init_y = init_y_noop;
c->step_y = step_y__nop;
return;
}
assembly = a;
}
// release the previous assembly
if (c->scanline_as) {
c->scanline_as->decStrong(c);
}
//LOGI("using generated pixel-pipeline");
c->scanline_as = assembly.get();
c->scanline_as->incStrong(c); // hold on to assembly
c->scanline = (void(*)(context_t* c))assembly->base();
#else
// LOGW("using generic (slow) pixel-pipeline");
c->scanline = scanline;
#endif
}
void ggl_pick_scanline(context_t* c)
{
pick_scanline(c);
if ((c->state.enables & GGL_ENABLE_W) &&
(c->state.enables & GGL_ENABLE_TMUS))
{
c->span = c->scanline;
c->scanline = scanline_perspective;
if (!(c->state.enabled_tmu & (c->state.enabled_tmu - 1))) {
// only one TMU enabled
c->scanline = scanline_perspective_single;
}
}
}
// ----------------------------------------------------------------------------
static void blending(context_t* c, pixel_t* fragment, pixel_t* fb);
static void blend_factor(context_t* c, pixel_t* r, uint32_t factor,
const pixel_t* src, const pixel_t* dst);
static void rescale(uint32_t& u, uint8_t& su, uint32_t& v, uint8_t& sv);
#if ANDROID_ARM_CODEGEN && (ANDROID_CODEGEN == ANDROID_CODEGEN_GENERATED)
// no need to compile the generic-pipeline, it can't be reached
void scanline(context_t*)
{
}
#else
void rescale(uint32_t& u, uint8_t& su, uint32_t& v, uint8_t& sv)
{
if (su && sv) {
if (su > sv) {
v = ggl_expand(v, sv, su);
sv = su;
} else if (su < sv) {
u = ggl_expand(u, su, sv);
su = sv;
}
}
}
void blending(context_t* c, pixel_t* fragment, pixel_t* fb)
{
rescale(fragment->c[0], fragment->s[0], fb->c[0], fb->s[0]);
rescale(fragment->c[1], fragment->s[1], fb->c[1], fb->s[1]);
rescale(fragment->c[2], fragment->s[2], fb->c[2], fb->s[2]);
rescale(fragment->c[3], fragment->s[3], fb->c[3], fb->s[3]);
pixel_t sf, df;
blend_factor(c, &sf, c->state.blend.src, fragment, fb);
blend_factor(c, &df, c->state.blend.dst, fragment, fb);
fragment->c[1] =
gglMulAddx(fragment->c[1], sf.c[1], gglMulx(fb->c[1], df.c[1]));
fragment->c[2] =
gglMulAddx(fragment->c[2], sf.c[2], gglMulx(fb->c[2], df.c[2]));
fragment->c[3] =
gglMulAddx(fragment->c[3], sf.c[3], gglMulx(fb->c[3], df.c[3]));
if (c->state.blend.alpha_separate) {
blend_factor(c, &sf, c->state.blend.src_alpha, fragment, fb);
blend_factor(c, &df, c->state.blend.dst_alpha, fragment, fb);
}
fragment->c[0] =
gglMulAddx(fragment->c[0], sf.c[0], gglMulx(fb->c[0], df.c[0]));
// clamp to 1.0
if (fragment->c[0] >= (1LU<<fragment->s[0]))
fragment->c[0] = (1<<fragment->s[0])-1;
if (fragment->c[1] >= (1LU<<fragment->s[1]))
fragment->c[1] = (1<<fragment->s[1])-1;
if (fragment->c[2] >= (1LU<<fragment->s[2]))
fragment->c[2] = (1<<fragment->s[2])-1;
if (fragment->c[3] >= (1LU<<fragment->s[3]))
fragment->c[3] = (1<<fragment->s[3])-1;
}
static inline int blendfactor(uint32_t x, uint32_t size, uint32_t def = 0)
{
if (!size)
return def;
// scale to 16 bits
if (size > 16) {
x >>= (size - 16);
} else if (size < 16) {
x = ggl_expand(x, size, 16);
}
x += x >> 15;
return x;
}
void blend_factor(context_t* c, pixel_t* r,
uint32_t factor, const pixel_t* src, const pixel_t* dst)
{
switch (factor) {
case GGL_ZERO:
r->c[1] =
r->c[2] =
r->c[3] =
r->c[0] = 0;
break;
case GGL_ONE:
r->c[1] =
r->c[2] =
r->c[3] =
r->c[0] = FIXED_ONE;
break;
case GGL_DST_COLOR:
r->c[1] = blendfactor(dst->c[1], dst->s[1]);
r->c[2] = blendfactor(dst->c[2], dst->s[2]);
r->c[3] = blendfactor(dst->c[3], dst->s[3]);
r->c[0] = blendfactor(dst->c[0], dst->s[0]);
break;
case GGL_SRC_COLOR:
r->c[1] = blendfactor(src->c[1], src->s[1]);
r->c[2] = blendfactor(src->c[2], src->s[2]);
r->c[3] = blendfactor(src->c[3], src->s[3]);
r->c[0] = blendfactor(src->c[0], src->s[0]);
break;
case GGL_ONE_MINUS_DST_COLOR:
r->c[1] = FIXED_ONE - blendfactor(dst->c[1], dst->s[1]);
r->c[2] = FIXED_ONE - blendfactor(dst->c[2], dst->s[2]);
r->c[3] = FIXED_ONE - blendfactor(dst->c[3], dst->s[3]);
r->c[0] = FIXED_ONE - blendfactor(dst->c[0], dst->s[0]);
break;
case GGL_ONE_MINUS_SRC_COLOR:
r->c[1] = FIXED_ONE - blendfactor(src->c[1], src->s[1]);
r->c[2] = FIXED_ONE - blendfactor(src->c[2], src->s[2]);
r->c[3] = FIXED_ONE - blendfactor(src->c[3], src->s[3]);
r->c[0] = FIXED_ONE - blendfactor(src->c[0], src->s[0]);
break;
case GGL_SRC_ALPHA:
r->c[1] =
r->c[2] =
r->c[3] =
r->c[0] = blendfactor(src->c[0], src->s[0], FIXED_ONE);
break;
case GGL_ONE_MINUS_SRC_ALPHA:
r->c[1] =
r->c[2] =
r->c[3] =
r->c[0] = FIXED_ONE - blendfactor(src->c[0], src->s[0], FIXED_ONE);
break;
case GGL_DST_ALPHA:
r->c[1] =
r->c[2] =
r->c[3] =
r->c[0] = blendfactor(dst->c[0], dst->s[0], FIXED_ONE);
break;
case GGL_ONE_MINUS_DST_ALPHA:
r->c[1] =
r->c[2] =
r->c[3] =
r->c[0] = FIXED_ONE - blendfactor(dst->c[0], dst->s[0], FIXED_ONE);
break;
case GGL_SRC_ALPHA_SATURATE:
// XXX: GGL_SRC_ALPHA_SATURATE
break;
}
}
static GGLfixed wrapping(int32_t coord, uint32_t size, int tx_wrap)
{
GGLfixed d;
if (tx_wrap == GGL_REPEAT) {
d = (uint32_t(coord)>>16) * size;
} else if (tx_wrap == GGL_CLAMP) { // CLAMP_TO_EDGE semantics
const GGLfixed clamp_min = FIXED_HALF;
const GGLfixed clamp_max = (size << 16) - FIXED_HALF;
if (coord < clamp_min) coord = clamp_min;
if (coord > clamp_max) coord = clamp_max;
d = coord;
} else { // 1:1
const GGLfixed clamp_min = 0;
const GGLfixed clamp_max = (size << 16);
if (coord < clamp_min) coord = clamp_min;
if (coord > clamp_max) coord = clamp_max;
d = coord;
}
return d;
}
static inline
GGLcolor ADJUST_COLOR_ITERATOR(GGLcolor v, GGLcolor dvdx, int len)
{
const int32_t end = dvdx * (len-1) + v;
if (end < 0)
v -= end;
v &= ~(v>>31);
return v;
}
void scanline(context_t* c)
{
const uint32_t enables = c->state.enables;
const int xs = c->iterators.xl;
const int x1 = c->iterators.xr;
int xc = x1 - xs;
const int16_t* covPtr = c->state.buffers.coverage + xs;
// All iterated values are sampled at the pixel center
// reset iterators for that scanline...
GGLcolor r, g, b, a;
iterators_t& ci = c->iterators;
if (enables & GGL_ENABLE_SMOOTH) {
r = (xs * c->shade.drdx) + ci.ydrdy;
g = (xs * c->shade.dgdx) + ci.ydgdy;
b = (xs * c->shade.dbdx) + ci.ydbdy;
a = (xs * c->shade.dadx) + ci.ydady;
r = ADJUST_COLOR_ITERATOR(r, c->shade.drdx, xc);
g = ADJUST_COLOR_ITERATOR(g, c->shade.dgdx, xc);
b = ADJUST_COLOR_ITERATOR(b, c->shade.dbdx, xc);
a = ADJUST_COLOR_ITERATOR(a, c->shade.dadx, xc);
} else {
r = ci.ydrdy;
g = ci.ydgdy;
b = ci.ydbdy;
a = ci.ydady;
}
// z iterators are 1.31
GGLfixed z = (xs * c->shade.dzdx) + ci.ydzdy;
GGLfixed f = (xs * c->shade.dfdx) + ci.ydfdy;
struct {
GGLfixed s, t;
} tc[GGL_TEXTURE_UNIT_COUNT];
if (enables & GGL_ENABLE_TMUS) {
for (int i=0 ; i<GGL_TEXTURE_UNIT_COUNT ; ++i) {
if (c->state.texture[i].enable) {
texture_iterators_t& ti = c->state.texture[i].iterators;
if (enables & GGL_ENABLE_W) {
tc[i].s = ti.ydsdy;
tc[i].t = ti.ydtdy;
} else {
tc[i].s = (xs * ti.dsdx) + ti.ydsdy;
tc[i].t = (xs * ti.dtdx) + ti.ydtdy;
}
}
}
}
pixel_t fragment;
pixel_t texel;
pixel_t fb;
uint32_t x = xs;
uint32_t y = c->iterators.y;
while (xc--) {
{ // just a scope
// read color (convert to 8 bits by keeping only the integer part)
fragment.s[1] = fragment.s[2] =
fragment.s[3] = fragment.s[0] = 8;
fragment.c[1] = r >> (GGL_COLOR_BITS-8);
fragment.c[2] = g >> (GGL_COLOR_BITS-8);
fragment.c[3] = b >> (GGL_COLOR_BITS-8);
fragment.c[0] = a >> (GGL_COLOR_BITS-8);
// texturing
if (enables & GGL_ENABLE_TMUS) {
for (int i=0 ; i<GGL_TEXTURE_UNIT_COUNT ; ++i) {
texture_t& tx = c->state.texture[i];
if (!tx.enable)
continue;
texture_iterators_t& ti = tx.iterators;
int32_t u, v;
// s-coordinate
if (tx.s_coord != GGL_ONE_TO_ONE) {
const int w = tx.surface.width;
u = wrapping(tc[i].s, w, tx.s_wrap);
tc[i].s += ti.dsdx;
} else {
u = (((tx.shade.is0>>16) + x)<<16) + FIXED_HALF;
}
// t-coordinate
if (tx.t_coord != GGL_ONE_TO_ONE) {
const int h = tx.surface.height;
v = wrapping(tc[i].t, h, tx.t_wrap);
tc[i].t += ti.dtdx;
} else {
v = (((tx.shade.it0>>16) + y)<<16) + FIXED_HALF;
}
// read texture
if (tx.mag_filter == GGL_NEAREST &&
tx.min_filter == GGL_NEAREST)
{
u >>= 16;
v >>= 16;
tx.surface.read(&tx.surface, c, u, v, &texel);
} else {
const int w = tx.surface.width;
const int h = tx.surface.height;
u -= FIXED_HALF;
v -= FIXED_HALF;
int u0 = u >> 16;
int v0 = v >> 16;
int u1 = u0 + 1;
int v1 = v0 + 1;
if (tx.s_wrap == GGL_REPEAT) {
if (u0<0) u0 += w;
if (u1<0) u1 += w;
if (u0>=w) u0 -= w;
if (u1>=w) u1 -= w;
} else {
if (u0<0) u0 = 0;
if (u1<0) u1 = 0;
if (u0>=w) u0 = w-1;
if (u1>=w) u1 = w-1;
}
if (tx.t_wrap == GGL_REPEAT) {
if (v0<0) v0 += h;
if (v1<0) v1 += h;
if (v0>=h) v0 -= h;
if (v1>=h) v1 -= h;
} else {
if (v0<0) v0 = 0;
if (v1<0) v1 = 0;
if (v0>=h) v0 = h-1;
if (v1>=h) v1 = h-1;
}
pixel_t texels[4];
uint32_t mm[4];
tx.surface.read(&tx.surface, c, u0, v0, &texels[0]);
tx.surface.read(&tx.surface, c, u0, v1, &texels[1]);
tx.surface.read(&tx.surface, c, u1, v0, &texels[2]);
tx.surface.read(&tx.surface, c, u1, v1, &texels[3]);
u = (u >> 12) & 0xF;
v = (v >> 12) & 0xF;
u += u>>3;
v += v>>3;
mm[0] = (0x10 - u) * (0x10 - v);
mm[1] = (0x10 - u) * v;
mm[2] = u * (0x10 - v);
mm[3] = 0x100 - (mm[0] + mm[1] + mm[2]);
for (int j=0 ; j<4 ; j++) {
texel.s[j] = texels[0].s[j];
if (!texel.s[j]) continue;
texel.s[j] += 8;
texel.c[j] = texels[0].c[j]*mm[0] +
texels[1].c[j]*mm[1] +
texels[2].c[j]*mm[2] +
texels[3].c[j]*mm[3] ;
}
}
// Texture environnement...
for (int j=0 ; j<4 ; j++) {
uint32_t& Cf = fragment.c[j];
uint32_t& Ct = texel.c[j];
uint8_t& sf = fragment.s[j];
uint8_t& st = texel.s[j];
uint32_t At = texel.c[0];
uint8_t sat = texel.s[0];
switch (tx.env) {
case GGL_REPLACE:
if (st) {
Cf = Ct;
sf = st;
}
break;
case GGL_MODULATE:
if (st) {
uint32_t factor = Ct + (Ct>>(st-1));
Cf = (Cf * factor) >> st;
}
break;
case GGL_DECAL:
if (sat) {
rescale(Cf, sf, Ct, st);
Cf += ((Ct - Cf) * (At + (At>>(sat-1)))) >> sat;
}
break;
case GGL_BLEND:
if (st) {
uint32_t Cc = tx.env_color[i];
if (sf>8) Cc = (Cc * ((1<<sf)-1))>>8;
else if (sf<8) Cc = (Cc - (Cc>>(8-sf)))>>(8-sf);
uint32_t factor = Ct + (Ct>>(st-1));
Cf = ((((1<<st) - factor) * Cf) + Ct*Cc)>>st;
}
break;
case GGL_ADD:
if (st) {
rescale(Cf, sf, Ct, st);
Cf += Ct;
}
break;
}
}
}
}
// coverage application
if (enables & GGL_ENABLE_AA) {
int16_t cf = *covPtr++;
fragment.c[0] = (int64_t(fragment.c[0]) * cf) >> 15;
}
// alpha-test
if (enables & GGL_ENABLE_ALPHA_TEST) {
GGLcolor ref = c->state.alpha_test.ref;
GGLcolor alpha = (uint64_t(fragment.c[0]) *
((1<<GGL_COLOR_BITS)-1)) / ((1<<fragment.s[0])-1);
switch (c->state.alpha_test.func) {
case GGL_NEVER: goto discard;
case GGL_LESS: if (alpha<ref) break; goto discard;
case GGL_EQUAL: if (alpha==ref) break; goto discard;
case GGL_LEQUAL: if (alpha<=ref) break; goto discard;
case GGL_GREATER: if (alpha>ref) break; goto discard;
case GGL_NOTEQUAL: if (alpha!=ref) break; goto discard;
case GGL_GEQUAL: if (alpha>=ref) break; goto discard;
}
}
// depth test
if (c->state.buffers.depth.format) {
if (enables & GGL_ENABLE_DEPTH_TEST) {
surface_t* cb = &(c->state.buffers.depth);
uint16_t* p = (uint16_t*)(cb->data)+(x+(cb->stride*y));
uint16_t zz = uint32_t(z)>>(16);
uint16_t depth = *p;
switch (c->state.depth_test.func) {
case GGL_NEVER: goto discard;
case GGL_LESS: if (zz<depth) break; goto discard;
case GGL_EQUAL: if (zz==depth) break; goto discard;
case GGL_LEQUAL: if (zz<=depth) break; goto discard;
case GGL_GREATER: if (zz>depth) break; goto discard;
case GGL_NOTEQUAL: if (zz!=depth) break; goto discard;
case GGL_GEQUAL: if (zz>=depth) break; goto discard;
}
// depth buffer is not enabled, if depth-test is not enabled
/*
fragment.s[1] = fragment.s[2] =
fragment.s[3] = fragment.s[0] = 8;
fragment.c[1] =
fragment.c[2] =
fragment.c[3] =
fragment.c[0] = 255 - (zz>>8);
*/
if (c->state.mask.depth) {
*p = zz;
}
}
}
// fog
if (enables & GGL_ENABLE_FOG) {
for (int i=1 ; i<=3 ; i++) {
GGLfixed fc = (c->state.fog.color[i] * 0x10000) / 0xFF;
uint32_t& c = fragment.c[i];
uint8_t& s = fragment.s[i];
c = (c * 0x10000) / ((1<<s)-1);
c = gglMulAddx(c, f, gglMulx(fc, 0x10000 - f));
s = 16;
}
}
// blending
if (enables & GGL_ENABLE_BLENDING) {
fb.c[1] = fb.c[2] = fb.c[3] = fb.c[0] = 0; // placate valgrind
fb.s[1] = fb.s[2] = fb.s[3] = fb.s[0] = 0;
c->state.buffers.color.read(
&(c->state.buffers.color), c, x, y, &fb);
blending( c, &fragment, &fb );
}
// write
c->state.buffers.color.write(
&(c->state.buffers.color), c, x, y, &fragment);
}
discard:
// iterate...
x += 1;
if (enables & GGL_ENABLE_SMOOTH) {
r += c->shade.drdx;
g += c->shade.dgdx;
b += c->shade.dbdx;
a += c->shade.dadx;
}
z += c->shade.dzdx;
f += c->shade.dfdx;
}
}
#endif // ANDROID_ARM_CODEGEN && (ANDROID_CODEGEN == ANDROID_CODEGEN_GENERATED)
// ----------------------------------------------------------------------------
#if 0
#pragma mark -
#pragma mark Scanline
#endif
template <typename T, typename U>
static inline __attribute__((const))
T interpolate(int y, T v0, U dvdx, U dvdy) {
// interpolates in pixel's centers
// v = v0 + (y + 0.5) * dvdy + (0.5 * dvdx)
return (y * dvdy) + (v0 + ((dvdy + dvdx) >> 1));
}
// ----------------------------------------------------------------------------
#if 0
#pragma mark -
#endif
void init_y(context_t* c, int32_t ys)
{
const uint32_t enables = c->state.enables;
// compute iterators...
iterators_t& ci = c->iterators;
// sample in the center
ci.y = ys;
if (enables & (GGL_ENABLE_DEPTH_TEST|GGL_ENABLE_W|GGL_ENABLE_FOG)) {
ci.ydzdy = interpolate(ys, c->shade.z0, c->shade.dzdx, c->shade.dzdy);
ci.ydwdy = interpolate(ys, c->shade.w0, c->shade.dwdx, c->shade.dwdy);
ci.ydfdy = interpolate(ys, c->shade.f0, c->shade.dfdx, c->shade.dfdy);
}
if (ggl_unlikely(enables & GGL_ENABLE_SMOOTH)) {
ci.ydrdy = interpolate(ys, c->shade.r0, c->shade.drdx, c->shade.drdy);
ci.ydgdy = interpolate(ys, c->shade.g0, c->shade.dgdx, c->shade.dgdy);
ci.ydbdy = interpolate(ys, c->shade.b0, c->shade.dbdx, c->shade.dbdy);
ci.ydady = interpolate(ys, c->shade.a0, c->shade.dadx, c->shade.dady);
c->step_y = step_y__smooth;
} else {
ci.ydrdy = c->shade.r0;
ci.ydgdy = c->shade.g0;
ci.ydbdy = c->shade.b0;
ci.ydady = c->shade.a0;
// XXX: do only if needed, or make sure this is fast
c->packed = ggl_pack_color(c, c->state.buffers.color.format,
ci.ydrdy, ci.ydgdy, ci.ydbdy, ci.ydady);
c->packed8888 = ggl_pack_color(c, GGL_PIXEL_FORMAT_RGBA_8888,
ci.ydrdy, ci.ydgdy, ci.ydbdy, ci.ydady);
}
// initialize the variables we need in the shader
generated_vars_t& gen = c->generated_vars;
gen.argb[GGLFormat::ALPHA].c = ci.ydady;
gen.argb[GGLFormat::ALPHA].dx = c->shade.dadx;
gen.argb[GGLFormat::RED ].c = ci.ydrdy;
gen.argb[GGLFormat::RED ].dx = c->shade.drdx;
gen.argb[GGLFormat::GREEN].c = ci.ydgdy;
gen.argb[GGLFormat::GREEN].dx = c->shade.dgdx;
gen.argb[GGLFormat::BLUE ].c = ci.ydbdy;
gen.argb[GGLFormat::BLUE ].dx = c->shade.dbdx;
gen.dzdx = c->shade.dzdx;
gen.f = ci.ydfdy;
gen.dfdx = c->shade.dfdx;
if (enables & GGL_ENABLE_TMUS) {
for (int i=0 ; i<GGL_TEXTURE_UNIT_COUNT ; ++i) {
texture_t& t = c->state.texture[i];
if (!t.enable) continue;
texture_iterators_t& ti = t.iterators;
if (t.s_coord == GGL_ONE_TO_ONE && t.t_coord == GGL_ONE_TO_ONE) {
// we need to set all of these to 0 because in some cases
// step_y__generic() or step_y__tmu() will be used and
// therefore will update dtdy, however, in 1:1 mode
// this is always done by the scanline rasterizer.
ti.dsdx = ti.dsdy = ti.dtdx = ti.dtdy = 0;
ti.ydsdy = t.shade.is0;
ti.ydtdy = t.shade.it0;
} else {
const int adjustSWrap = ((t.s_wrap==GGL_CLAMP)?0:16);
const int adjustTWrap = ((t.t_wrap==GGL_CLAMP)?0:16);
ti.sscale = t.shade.sscale + adjustSWrap;
ti.tscale = t.shade.tscale + adjustTWrap;
if (!(enables & GGL_ENABLE_W)) {
// S coordinate
const int32_t sscale = ti.sscale;
const int32_t sy = interpolate(ys,
t.shade.is0, t.shade.idsdx, t.shade.idsdy);
if (sscale>=0) {
ti.ydsdy= sy << sscale;
ti.dsdx = t.shade.idsdx << sscale;
ti.dsdy = t.shade.idsdy << sscale;
} else {
ti.ydsdy= sy >> -sscale;
ti.dsdx = t.shade.idsdx >> -sscale;
ti.dsdy = t.shade.idsdy >> -sscale;
}
// T coordinate
const int32_t tscale = ti.tscale;
const int32_t ty = interpolate(ys,
t.shade.it0, t.shade.idtdx, t.shade.idtdy);
if (tscale>=0) {
ti.ydtdy= ty << tscale;
ti.dtdx = t.shade.idtdx << tscale;
ti.dtdy = t.shade.idtdy << tscale;
} else {
ti.ydtdy= ty >> -tscale;
ti.dtdx = t.shade.idtdx >> -tscale;
ti.dtdy = t.shade.idtdy >> -tscale;
}
}
}
// mirror for generated code...
generated_tex_vars_t& gen = c->generated_vars.texture[i];
gen.width = t.surface.width;
gen.height = t.surface.height;
gen.stride = t.surface.stride;
gen.data = int32_t(t.surface.data);
gen.dsdx = ti.dsdx;
gen.dtdx = ti.dtdx;
}
}
// choose the y-stepper
c->step_y = step_y__nop;
if (enables & GGL_ENABLE_FOG) {
c->step_y = step_y__generic;
} else if (enables & GGL_ENABLE_TMUS) {
if (enables & GGL_ENABLE_SMOOTH) {
c->step_y = step_y__generic;
} else if (enables & GGL_ENABLE_W) {
c->step_y = step_y__w;
} else {
c->step_y = step_y__tmu;
}
} else {
if (enables & GGL_ENABLE_SMOOTH) {
c->step_y = step_y__smooth;
}
}
// choose the rectangle blitter
c->rect = rect_generic;
if ((c->step_y == step_y__nop) &&
(c->scanline == scanline_memcpy))
{
c->rect = rect_memcpy;
}
}
void init_y_packed(context_t* c, int32_t y0)
{
uint8_t f = c->state.buffers.color.format;
c->packed = ggl_pack_color(c, f,
c->shade.r0, c->shade.g0, c->shade.b0, c->shade.a0);
c->iterators.y = y0;
c->step_y = step_y__nop;
// choose the rectangle blitter
c->rect = rect_generic;
if (c->scanline == scanline_memcpy) {
c->rect = rect_memcpy;
}
}
void init_y_noop(context_t* c, int32_t y0)
{
c->iterators.y = y0;
c->step_y = step_y__nop;
// choose the rectangle blitter
c->rect = rect_generic;
if (c->scanline == scanline_memcpy) {
c->rect = rect_memcpy;
}
}
void init_y_error(context_t* c, int32_t y0)
{
// woooops, shoud never happen,
// fail gracefully (don't display anything)
init_y_noop(c, y0);
LOGE("color-buffer has an invalid format!");
}
// ----------------------------------------------------------------------------
#if 0
#pragma mark -
#endif
void step_y__generic(context_t* c)
{
const uint32_t enables = c->state.enables;
// iterate...
iterators_t& ci = c->iterators;
ci.y += 1;
if (enables & GGL_ENABLE_SMOOTH) {
ci.ydrdy += c->shade.drdy;
ci.ydgdy += c->shade.dgdy;
ci.ydbdy += c->shade.dbdy;
ci.ydady += c->shade.dady;
}
const uint32_t mask =
GGL_ENABLE_DEPTH_TEST |
GGL_ENABLE_W |
GGL_ENABLE_FOG;
if (enables & mask) {
ci.ydzdy += c->shade.dzdy;
ci.ydwdy += c->shade.dwdy;
ci.ydfdy += c->shade.dfdy;
}
if ((enables & GGL_ENABLE_TMUS) && (!(enables & GGL_ENABLE_W))) {
for (int i=0 ; i<GGL_TEXTURE_UNIT_COUNT ; ++i) {
if (c->state.texture[i].enable) {
texture_iterators_t& ti = c->state.texture[i].iterators;
ti.ydsdy += ti.dsdy;
ti.ydtdy += ti.dtdy;
}
}
}
}
void step_y__nop(context_t* c)
{
c->iterators.y += 1;
c->iterators.ydzdy += c->shade.dzdy;
}
void step_y__smooth(context_t* c)
{
iterators_t& ci = c->iterators;
ci.y += 1;
ci.ydrdy += c->shade.drdy;
ci.ydgdy += c->shade.dgdy;
ci.ydbdy += c->shade.dbdy;
ci.ydady += c->shade.dady;
ci.ydzdy += c->shade.dzdy;
}
void step_y__w(context_t* c)
{
iterators_t& ci = c->iterators;
ci.y += 1;
ci.ydzdy += c->shade.dzdy;
ci.ydwdy += c->shade.dwdy;
}
void step_y__tmu(context_t* c)
{
iterators_t& ci = c->iterators;
ci.y += 1;
ci.ydzdy += c->shade.dzdy;
for (int i=0 ; i<GGL_TEXTURE_UNIT_COUNT ; ++i) {
if (c->state.texture[i].enable) {
texture_iterators_t& ti = c->state.texture[i].iterators;
ti.ydsdy += ti.dsdy;
ti.ydtdy += ti.dtdy;
}
}
}
// ----------------------------------------------------------------------------
#if 0
#pragma mark -
#endif
void scanline_perspective(context_t* c)
{
struct {
union {
struct {
int32_t s, sq;
int32_t t, tq;
};
struct {
int32_t v, q;
} st[2];
};
} tc[GGL_TEXTURE_UNIT_COUNT] __attribute__((aligned(16)));
// XXX: we should have a special case when dwdx = 0
// 32 pixels spans works okay. 16 is a lot better,
// but hey, it's a software renderer...
const uint32_t SPAN_BITS = 5;
const uint32_t ys = c->iterators.y;
const uint32_t xs = c->iterators.xl;
const uint32_t x1 = c->iterators.xr;
const uint32_t xc = x1 - xs;
uint32_t remainder = xc & ((1<<SPAN_BITS)-1);
uint32_t numSpans = xc >> SPAN_BITS;
const iterators_t& ci = c->iterators;
int32_t w0 = (xs * c->shade.dwdx) + ci.ydwdy;
int32_t q0 = gglRecipQ(w0, 30);
const int iwscale = 32 - gglClz(q0);
const int32_t dwdx = c->shade.dwdx << SPAN_BITS;
int32_t xl = c->iterators.xl;
// We process s & t with a loop to reduce the code size
// (and i-cache pressure).
for (int i=0 ; i<GGL_TEXTURE_UNIT_COUNT ; ++i) {
const texture_t& tmu = c->state.texture[i];
if (!tmu.enable) continue;
int32_t s = tmu.shade.is0 +
(tmu.shade.idsdy * ys) + (tmu.shade.idsdx * xs) +
((tmu.shade.idsdx + tmu.shade.idsdy)>>1);
int32_t t = tmu.shade.it0 +
(tmu.shade.idtdy * ys) + (tmu.shade.idtdx * xs) +
((tmu.shade.idtdx + tmu.shade.idtdy)>>1);
tc[i].s = s;
tc[i].t = t;
tc[i].sq = gglMulx(s, q0, iwscale);
tc[i].tq = gglMulx(t, q0, iwscale);
}
int32_t span = 0;
do {
int32_t w1;
if (ggl_likely(numSpans)) {
w1 = w0 + dwdx;
} else {
if (remainder) {
// finish off the scanline...
span = remainder;
w1 = (c->shade.dwdx * span) + w0;
} else {
break;
}
}
int32_t q1 = gglRecipQ(w1, 30);
for (int i=0 ; i<GGL_TEXTURE_UNIT_COUNT ; ++i) {
texture_t& tmu = c->state.texture[i];
if (!tmu.enable) continue;
texture_iterators_t& ti = tmu.iterators;
for (int j=0 ; j<2 ; j++) {
int32_t v = tc[i].st[j].v;
if (span) v += (tmu.shade.st[j].dx)*span;
else v += (tmu.shade.st[j].dx)<<SPAN_BITS;
const int32_t v0 = tc[i].st[j].q;
const int32_t v1 = gglMulx(v, q1, iwscale);
int32_t dvdx = v1 - v0;
if (span) dvdx /= span;
else dvdx >>= SPAN_BITS;
tc[i].st[j].v = v;
tc[i].st[j].q = v1;
const int scale = ti.st[j].scale + (iwscale - 30);
if (scale >= 0) {
ti.st[j].ydvdy = v0 << scale;
ti.st[j].dvdx = dvdx << scale;
} else {
ti.st[j].ydvdy = v0 >> -scale;
ti.st[j].dvdx = dvdx >> -scale;
}
}
generated_tex_vars_t& gen = c->generated_vars.texture[i];
gen.dsdx = ti.st[0].dvdx;
gen.dtdx = ti.st[1].dvdx;
}
c->iterators.xl = xl;
c->iterators.xr = xl = xl + (span ? span : (1<<SPAN_BITS));
w0 = w1;
q0 = q1;
c->span(c);
} while(numSpans--);
}
void scanline_perspective_single(context_t* c)
{
// 32 pixels spans works okay. 16 is a lot better,
// but hey, it's a software renderer...
const uint32_t SPAN_BITS = 5;
const uint32_t ys = c->iterators.y;
const uint32_t xs = c->iterators.xl;
const uint32_t x1 = c->iterators.xr;
const uint32_t xc = x1 - xs;
const iterators_t& ci = c->iterators;
int32_t w = (xs * c->shade.dwdx) + ci.ydwdy;
int32_t iw = gglRecipQ(w, 30);
const int iwscale = 32 - gglClz(iw);
const int i = 31 - gglClz(c->state.enabled_tmu);
generated_tex_vars_t& gen = c->generated_vars.texture[i];
texture_t& tmu = c->state.texture[i];
texture_iterators_t& ti = tmu.iterators;
const int sscale = ti.sscale + (iwscale - 30);
const int tscale = ti.tscale + (iwscale - 30);
int32_t s = tmu.shade.is0 +
(tmu.shade.idsdy * ys) + (tmu.shade.idsdx * xs) +
((tmu.shade.idsdx + tmu.shade.idsdy)>>1);
int32_t t = tmu.shade.it0 +
(tmu.shade.idtdy * ys) + (tmu.shade.idtdx * xs) +
((tmu.shade.idtdx + tmu.shade.idtdy)>>1);
int32_t s0 = gglMulx(s, iw, iwscale);
int32_t t0 = gglMulx(t, iw, iwscale);
int32_t xl = c->iterators.xl;
int32_t sq, tq, dsdx, dtdx;
int32_t premainder = xc & ((1<<SPAN_BITS)-1);
uint32_t numSpans = xc >> SPAN_BITS;
if (c->shade.dwdx == 0) {
// XXX: we could choose to do this if the error is small enough
numSpans = 0;
premainder = xc;
goto no_perspective;
}
if (premainder) {
w += c->shade.dwdx * premainder;
iw = gglRecipQ(w, 30);
no_perspective:
s += tmu.shade.idsdx * premainder;
t += tmu.shade.idtdx * premainder;
sq = gglMulx(s, iw, iwscale);
tq = gglMulx(t, iw, iwscale);
dsdx = (sq - s0) / premainder;
dtdx = (tq - t0) / premainder;
c->iterators.xl = xl;
c->iterators.xr = xl = xl + premainder;
goto finish;
}
while (numSpans--) {
w += c->shade.dwdx << SPAN_BITS;
s += tmu.shade.idsdx << SPAN_BITS;
t += tmu.shade.idtdx << SPAN_BITS;
iw = gglRecipQ(w, 30);
sq = gglMulx(s, iw, iwscale);
tq = gglMulx(t, iw, iwscale);
dsdx = (sq - s0) >> SPAN_BITS;
dtdx = (tq - t0) >> SPAN_BITS;
c->iterators.xl = xl;
c->iterators.xr = xl = xl + (1<<SPAN_BITS);
finish:
if (sscale >= 0) {
ti.ydsdy = s0 << sscale;
ti.dsdx = dsdx << sscale;
} else {
ti.ydsdy = s0 >>-sscale;
ti.dsdx = dsdx >>-sscale;
}
if (tscale >= 0) {
ti.ydtdy = t0 << tscale;
ti.dtdx = dtdx << tscale;
} else {
ti.ydtdy = t0 >>-tscale;
ti.dtdx = dtdx >>-tscale;
}
s0 = sq;
t0 = tq;
gen.dsdx = ti.dsdx;
gen.dtdx = ti.dtdx;
c->span(c);
}
}
// ----------------------------------------------------------------------------
void scanline_t32cb16(context_t* c)
{
int32_t x = c->iterators.xl;
size_t ct = c->iterators.xr - x;
int32_t y = c->iterators.y;
surface_t* cb = &(c->state.buffers.color);
union {
uint16_t* dst;
uint32_t* dst32;
};
dst = reinterpret_cast<uint16_t*>(cb->data) + (x+(cb->stride*y));
surface_t* tex = &(c->state.texture[0].surface);
const int32_t u = (c->state.texture[0].shade.is0>>16) + x;
const int32_t v = (c->state.texture[0].shade.it0>>16) + y;
uint32_t *src = reinterpret_cast<uint32_t*>(tex->data)+(u+(tex->stride*v));
int sR, sG, sB;
uint32_t s, d;
if (ct==1 || uint32_t(dst)&2) {
last_one:
s = GGL_RGBA_TO_HOST( *src++ );
sR = (s >> ( 3))&0x1F;
sG = (s >> ( 8+2))&0x3F;
sB = (s >> (16+3))&0x1F;
*dst++ = uint16_t((sR<<11)|(sG<<5)|sB);
ct--;
}
while (ct >= 2) {
s = GGL_RGBA_TO_HOST( *src++ );
sR = (s >> ( 3))&0x1F;
sG = (s >> ( 8+2))&0x3F;
sB = (s >> (16+3))&0x1F;
d = (sR<<11)|(sG<<5)|sB;
s = GGL_RGBA_TO_HOST( *src++ );
sR = (s >> ( 3))&0x1F;
sG = (s >> ( 8+2))&0x3F;
sB = (s >> (16+3))&0x1F;
d |= ((sR<<11)|(sG<<5)|sB)<<16;
#if BYTE_ORDER == BIG_ENDIAN
d = (d>>16) | (d<<16);
#endif
*dst32++ = d;
ct -= 2;
}
if (ct > 0) {
goto last_one;
}
}
void scanline_t32cb16blend(context_t* c)
{
int32_t x = c->iterators.xl;
size_t ct = c->iterators.xr - x;
int32_t y = c->iterators.y;
surface_t* cb = &(c->state.buffers.color);
uint16_t* dst = reinterpret_cast<uint16_t*>(cb->data) + (x+(cb->stride*y));
surface_t* tex = &(c->state.texture[0].surface);
const int32_t u = (c->state.texture[0].shade.is0>>16) + x;
const int32_t v = (c->state.texture[0].shade.it0>>16) + y;
uint32_t *src = reinterpret_cast<uint32_t*>(tex->data)+(u+(tex->stride*v));
#if ((ANDROID_CODEGEN >= ANDROID_CODEGEN_ASM) && defined(__arm__))
scanline_t32cb16blend_arm(dst, src, ct);
#else
while (ct--) {
uint32_t s = *src++;
if (!s) {
dst++;
continue;
}
uint16_t d = *dst;
s = GGL_RGBA_TO_HOST(s);
int sR = (s >> ( 3))&0x1F;
int sG = (s >> ( 8+2))&0x3F;
int sB = (s >> (16+3))&0x1F;
int sA = (s>>24);
int f = 0x100 - (sA + (sA>>7));
int dR = (d>>11)&0x1f;
int dG = (d>>5)&0x3f;
int dB = (d)&0x1f;
sR += (f*dR)>>8;
sG += (f*dG)>>8;
sB += (f*dB)>>8;
*dst++ = uint16_t((sR<<11)|(sG<<5)|sB);
}
#endif
}
void scanline_memcpy(context_t* c)
{
int32_t x = c->iterators.xl;
size_t ct = c->iterators.xr - x;
int32_t y = c->iterators.y;
surface_t* cb = &(c->state.buffers.color);
const GGLFormat* fp = &(c->formats[cb->format]);
uint8_t* dst = reinterpret_cast<uint8_t*>(cb->data) +
(x + (cb->stride * y)) * fp->size;
surface_t* tex = &(c->state.texture[0].surface);
const int32_t u = (c->state.texture[0].shade.is0>>16) + x;
const int32_t v = (c->state.texture[0].shade.it0>>16) + y;
uint8_t *src = reinterpret_cast<uint8_t*>(tex->data) +
(u + (tex->stride * v)) * fp->size;
const size_t size = ct * fp->size;
memcpy(dst, src, size);
}
void scanline_memset8(context_t* c)
{
int32_t x = c->iterators.xl;
size_t ct = c->iterators.xr - x;
int32_t y = c->iterators.y;
surface_t* cb = &(c->state.buffers.color);
uint8_t* dst = reinterpret_cast<uint8_t*>(cb->data) + (x+(cb->stride*y));
uint32_t packed = c->packed;
memset(dst, packed, ct);
}
void scanline_memset16(context_t* c)
{
int32_t x = c->iterators.xl;
size_t ct = c->iterators.xr - x;
int32_t y = c->iterators.y;
surface_t* cb = &(c->state.buffers.color);
uint16_t* dst = reinterpret_cast<uint16_t*>(cb->data) + (x+(cb->stride*y));
uint32_t packed = c->packed;
android_memset16(dst, packed, ct*2);
}
void scanline_memset32(context_t* c)
{
int32_t x = c->iterators.xl;
size_t ct = c->iterators.xr - x;
int32_t y = c->iterators.y;
surface_t* cb = &(c->state.buffers.color);
uint32_t* dst = reinterpret_cast<uint32_t*>(cb->data) + (x+(cb->stride*y));
uint32_t packed = GGL_HOST_TO_RGBA(c->packed);
android_memset32(dst, packed, ct*4);
}
void scanline_clear(context_t* c)
{
int32_t x = c->iterators.xl;
size_t ct = c->iterators.xr - x;
int32_t y = c->iterators.y;
surface_t* cb = &(c->state.buffers.color);
const GGLFormat* fp = &(c->formats[cb->format]);
uint8_t* dst = reinterpret_cast<uint8_t*>(cb->data) +
(x + (cb->stride * y)) * fp->size;
const size_t size = ct * fp->size;
memset(dst, 0, size);
}
void scanline_set(context_t* c)
{
int32_t x = c->iterators.xl;
size_t ct = c->iterators.xr - x;
int32_t y = c->iterators.y;
surface_t* cb = &(c->state.buffers.color);
const GGLFormat* fp = &(c->formats[cb->format]);
uint8_t* dst = reinterpret_cast<uint8_t*>(cb->data) +
(x + (cb->stride * y)) * fp->size;
const size_t size = ct * fp->size;
memset(dst, 0xFF, size);
}
void scanline_noop(context_t* c)
{
}
void rect_generic(context_t* c, size_t yc)
{
do {
c->scanline(c);
c->step_y(c);
} while (--yc);
}
void rect_memcpy(context_t* c, size_t yc)
{
int32_t x = c->iterators.xl;
size_t ct = c->iterators.xr - x;
int32_t y = c->iterators.y;
surface_t* cb = &(c->state.buffers.color);
const GGLFormat* fp = &(c->formats[cb->format]);
uint8_t* dst = reinterpret_cast<uint8_t*>(cb->data) +
(x + (cb->stride * y)) * fp->size;
surface_t* tex = &(c->state.texture[0].surface);
const int32_t u = (c->state.texture[0].shade.is0>>16) + x;
const int32_t v = (c->state.texture[0].shade.it0>>16) + y;
uint8_t *src = reinterpret_cast<uint8_t*>(tex->data) +
(u + (tex->stride * v)) * fp->size;
if (cb->stride == tex->stride && ct == size_t(cb->stride)) {
memcpy(dst, src, ct * fp->size * yc);
} else {
const size_t size = ct * fp->size;
const size_t dbpr = cb->stride * fp->size;
const size_t sbpr = tex->stride * fp->size;
do {
memcpy(dst, src, size);
dst += dbpr;
src += sbpr;
} while (--yc);
}
}
// ----------------------------------------------------------------------------
}; // namespace android
using namespace android;
extern "C" void ggl_test_codegen(uint32_t n, uint32_t p, uint32_t t0, uint32_t t1)
{
#if ANDROID_ARM_CODEGEN
GGLContext* c;
gglInit(&c);
needs_t needs;
needs.n = n;
needs.p = p;
needs.t[0] = t0;
needs.t[1] = t1;
sp<ScanlineAssembly> a(new ScanlineAssembly(needs, ASSEMBLY_SCRATCH_SIZE));
GGLAssembler assembler( new ARMAssembler(a) );
int err = assembler.scanline(needs, (context_t*)c);
if (err != 0) {
printf("error %08x (%s)\n", err, strerror(-err));
}
gglUninit(c);
#else
printf("This test runs only on ARM\n");
#endif
}
|
/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/drivers/canbus/can_client/fake/fake_can_client.h"
#include <memory>
#include <sstream>
#include <string>
#include <thread>
#include "gtest/gtest.h"
#include "cyber/common/log.h"
#include "modules/drivers/canbus/common/byte.h"
namespace apollo {
namespace drivers {
namespace canbus {
namespace can {
using apollo::common::ErrorCode;
class FakeCanClientTest : public ::testing::Test {
public:
static const int32_t FRAME_LEN = 10;
virtual void SetUp() {
send_time_ = 0;
recv_time_ = 0;
send_succ_count_ = 0;
recv_succ_count_ = 0;
send_err_count_ = 0;
recv_err_count_ = 0;
param_.set_brand(CANCardParameter::ESD_CAN);
param_.set_channel_id(CANCardParameter::CHANNEL_ID_ZERO);
send_client_ = std::unique_ptr<FakeCanClient>(new FakeCanClient());
send_client_->Init(param_);
send_client_->Start();
recv_client_ = std::unique_ptr<FakeCanClient>(new FakeCanClient());
recv_client_->Init(param_);
recv_client_->Start();
}
protected:
std::unique_ptr<FakeCanClient> send_client_;
std::unique_ptr<FakeCanClient> recv_client_;
int64_t send_time_ = 0;
int64_t recv_time_ = 0;
int32_t send_succ_count_ = 0;
int32_t recv_succ_count_ = 0;
int32_t send_err_count_ = 0;
int32_t recv_err_count_ = 0;
std::stringstream recv_ss_;
CANCardParameter param_;
};
TEST_F(FakeCanClientTest, SendMessage) {
std::vector<CanFrame> frames;
frames.resize(FRAME_LEN);
for (int32_t i = 0; i < FRAME_LEN; ++i) {
frames[i].id = 1 & 0x3FF;
frames[i].len = 8;
frames[i].data[7] = 1 % 256;
for (uint8_t j = 0; j < 7; ++j) {
frames[i].data[j] = j;
}
}
int32_t frame_num = FRAME_LEN;
auto ret = send_client_->Send(frames, &frame_num);
EXPECT_EQ(ret, ErrorCode::OK);
EXPECT_EQ(send_client_->GetErrorString(0), "");
send_client_->Stop();
}
TEST_F(FakeCanClientTest, ReceiveMessage) {
std::vector<CanFrame> buf;
int32_t frame_num = FRAME_LEN;
auto ret = recv_client_->Receive(&buf, &frame_num);
EXPECT_EQ(ret, ErrorCode::OK);
recv_client_->Stop();
}
} // namespace can
} // namespace canbus
} // namespace drivers
} // namespace apollo
|
/*
* Copyright 2012 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "GrConfigConversionEffect.h"
#include "GrContext.h"
#include "GrRenderTargetContext.h"
#include "GrInvariantOutput.h"
#include "GrSimpleTextureEffect.h"
#include "SkMatrix.h"
#include "glsl/GrGLSLFragmentProcessor.h"
#include "glsl/GrGLSLFragmentShaderBuilder.h"
#include "../private/GrGLSL.h"
class GrGLConfigConversionEffect : public GrGLSLFragmentProcessor {
public:
void emitCode(EmitArgs& args) override {
const GrConfigConversionEffect& cce = args.fFp.cast<GrConfigConversionEffect>();
const GrSwizzle& swizzle = cce.swizzle();
GrConfigConversionEffect::PMConversion pmConversion = cce.pmConversion();
// Using highp for GLES here in order to avoid some precision issues on specific GPUs.
GrShaderVar tmpVar("tmpColor", kVec4f_GrSLType, 0, kHigh_GrSLPrecision);
SkString tmpDecl;
tmpVar.appendDecl(args.fShaderCaps, &tmpDecl);
GrGLSLFPFragmentBuilder* fragBuilder = args.fFragBuilder;
fragBuilder->codeAppendf("%s;", tmpDecl.c_str());
fragBuilder->codeAppendf("%s = ", tmpVar.c_str());
fragBuilder->appendTextureLookup(args.fTexSamplers[0], args.fTransformedCoords[0].c_str(),
args.fTransformedCoords[0].getType());
fragBuilder->codeAppend(";");
if (GrConfigConversionEffect::kNone_PMConversion == pmConversion) {
SkASSERT(GrSwizzle::RGBA() != swizzle);
fragBuilder->codeAppendf("%s = %s.%s;", args.fOutputColor, tmpVar.c_str(),
swizzle.c_str());
} else {
switch (pmConversion) {
case GrConfigConversionEffect::kMulByAlpha_RoundUp_PMConversion:
fragBuilder->codeAppendf(
"%s = vec4(ceil(%s.rgb * %s.a * 255.0) / 255.0, %s.a);",
tmpVar.c_str(), tmpVar.c_str(), tmpVar.c_str(), tmpVar.c_str());
break;
case GrConfigConversionEffect::kMulByAlpha_RoundDown_PMConversion:
// Add a compensation(0.001) here to avoid the side effect of the floor operation.
// In Intel GPUs, the integer value converted from floor(%s.r * 255.0) / 255.0
// is less than the integer value converted from %s.r by 1 when the %s.r is
// converted from the integer value 2^n, such as 1, 2, 4, 8, etc.
fragBuilder->codeAppendf(
"%s = vec4(floor(%s.rgb * %s.a * 255.0 + 0.001) / 255.0, %s.a);",
tmpVar.c_str(), tmpVar.c_str(), tmpVar.c_str(), tmpVar.c_str());
break;
case GrConfigConversionEffect::kDivByAlpha_RoundUp_PMConversion:
fragBuilder->codeAppendf(
"%s = %s.a <= 0.0 ? vec4(0,0,0,0) : vec4(ceil(%s.rgb / %s.a * 255.0) / 255.0, %s.a);",
tmpVar.c_str(), tmpVar.c_str(), tmpVar.c_str(), tmpVar.c_str(),
tmpVar.c_str());
break;
case GrConfigConversionEffect::kDivByAlpha_RoundDown_PMConversion:
fragBuilder->codeAppendf(
"%s = %s.a <= 0.0 ? vec4(0,0,0,0) : vec4(floor(%s.rgb / %s.a * 255.0) / 255.0, %s.a);",
tmpVar.c_str(), tmpVar.c_str(), tmpVar.c_str(), tmpVar.c_str(),
tmpVar.c_str());
break;
default:
SkFAIL("Unknown conversion op.");
break;
}
fragBuilder->codeAppendf("%s = %s.%s;", args.fOutputColor, tmpVar.c_str(),
swizzle.c_str());
}
SkString modulate;
GrGLSLMulVarBy4f(&modulate, args.fOutputColor, args.fInputColor);
fragBuilder->codeAppend(modulate.c_str());
}
static inline void GenKey(const GrProcessor& processor, const GrShaderCaps&,
GrProcessorKeyBuilder* b) {
const GrConfigConversionEffect& cce = processor.cast<GrConfigConversionEffect>();
uint32_t key = (cce.swizzle().asKey()) | (cce.pmConversion() << 16);
b->add32(key);
}
private:
typedef GrGLSLFragmentProcessor INHERITED;
};
///////////////////////////////////////////////////////////////////////////////
GrConfigConversionEffect::GrConfigConversionEffect(GrTexture* texture,
const GrSwizzle& swizzle,
PMConversion pmConversion,
const SkMatrix& matrix)
: INHERITED(texture, nullptr, matrix)
, fSwizzle(swizzle)
, fPMConversion(pmConversion) {
this->initClassID<GrConfigConversionEffect>();
// We expect to get here with non-BGRA/RGBA only if we're doing not doing a premul/unpremul
// conversion.
SkASSERT((kRGBA_8888_GrPixelConfig == texture->config() ||
kBGRA_8888_GrPixelConfig == texture->config()) ||
kNone_PMConversion == pmConversion);
// Why did we pollute our texture cache instead of using a GrSingleTextureEffect?
SkASSERT(swizzle != GrSwizzle::RGBA() || kNone_PMConversion != pmConversion);
}
bool GrConfigConversionEffect::onIsEqual(const GrFragmentProcessor& s) const {
const GrConfigConversionEffect& other = s.cast<GrConfigConversionEffect>();
return other.fSwizzle == fSwizzle &&
other.fPMConversion == fPMConversion;
}
void GrConfigConversionEffect::onComputeInvariantOutput(GrInvariantOutput* inout) const {
this->updateInvariantOutputForModulation(inout);
}
///////////////////////////////////////////////////////////////////////////////
GR_DEFINE_FRAGMENT_PROCESSOR_TEST(GrConfigConversionEffect);
#if !defined(__clang__) && _MSC_FULL_VER >= 190024213
// Work around VS 2015 Update 3 optimizer bug that causes internal compiler error
//https://connect.microsoft.com/VisualStudio/feedback/details/3100520/internal-compiler-error
#pragma optimize("t", off)
#endif
sk_sp<GrFragmentProcessor> GrConfigConversionEffect::TestCreate(GrProcessorTestData* d) {
PMConversion pmConv = static_cast<PMConversion>(d->fRandom->nextULessThan(kPMConversionCnt));
GrSwizzle swizzle;
do {
swizzle = GrSwizzle::CreateRandom(d->fRandom);
} while (pmConv == kNone_PMConversion && swizzle == GrSwizzle::RGBA());
return sk_sp<GrFragmentProcessor>(
new GrConfigConversionEffect(d->fTextures[GrProcessorUnitTest::kSkiaPMTextureIdx],
swizzle, pmConv, GrTest::TestMatrix(d->fRandom)));
}
#if !defined(__clang__) && _MSC_FULL_VER >= 190024213
// Restore optimization settings.
#pragma optimize("", on)
#endif
///////////////////////////////////////////////////////////////////////////////
void GrConfigConversionEffect::onGetGLSLProcessorKey(const GrShaderCaps& caps,
GrProcessorKeyBuilder* b) const {
GrGLConfigConversionEffect::GenKey(*this, caps, b);
}
GrGLSLFragmentProcessor* GrConfigConversionEffect::onCreateGLSLInstance() const {
return new GrGLConfigConversionEffect();
}
void GrConfigConversionEffect::TestForPreservingPMConversions(GrContext* context,
PMConversion* pmToUPMRule,
PMConversion* upmToPMRule) {
*pmToUPMRule = kNone_PMConversion;
*upmToPMRule = kNone_PMConversion;
static constexpr int kSize = 256;
static constexpr GrPixelConfig kConfig = kRGBA_8888_GrPixelConfig;
SkAutoTMalloc<uint32_t> data(kSize * kSize * 3);
uint32_t* srcData = data.get();
uint32_t* firstRead = data.get() + kSize * kSize;
uint32_t* secondRead = data.get() + 2 * kSize * kSize;
// Fill with every possible premultiplied A, color channel value. There will be 256-y duplicate
// values in row y. We set r,g, and b to the same value since they are handled identically.
for (int y = 0; y < kSize; ++y) {
for (int x = 0; x < kSize; ++x) {
uint8_t* color = reinterpret_cast<uint8_t*>(&srcData[kSize*y + x]);
color[3] = y;
color[2] = SkTMin(x, y);
color[1] = SkTMin(x, y);
color[0] = SkTMin(x, y);
}
}
sk_sp<GrRenderTargetContext> readRTC(context->makeRenderTargetContext(SkBackingFit::kExact,
kSize, kSize,
kConfig, nullptr));
sk_sp<GrRenderTargetContext> tempRTC(context->makeRenderTargetContext(SkBackingFit::kExact,
kSize, kSize,
kConfig, nullptr));
if (!readRTC || !tempRTC) {
return;
}
GrSurfaceDesc desc;
desc.fWidth = kSize;
desc.fHeight = kSize;
desc.fConfig = kConfig;
sk_sp<GrTexture> dataTex(context->textureProvider()->createTexture(
desc, SkBudgeted::kYes, data, 0));
if (!dataTex.get()) {
return;
}
static const PMConversion kConversionRules[][2] = {
{kDivByAlpha_RoundDown_PMConversion, kMulByAlpha_RoundUp_PMConversion},
{kDivByAlpha_RoundUp_PMConversion, kMulByAlpha_RoundDown_PMConversion},
};
bool failed = true;
for (size_t i = 0; i < SK_ARRAY_COUNT(kConversionRules) && failed; ++i) {
*pmToUPMRule = kConversionRules[i][0];
*upmToPMRule = kConversionRules[i][1];
static const SkRect kDstRect = SkRect::MakeIWH(kSize, kSize);
static const SkRect kSrcRect = SkRect::MakeIWH(1, 1);
// We do a PM->UPM draw from dataTex to readTex and read the data. Then we do a UPM->PM draw
// from readTex to tempTex followed by a PM->UPM draw to readTex and finally read the data.
// We then verify that two reads produced the same values.
if (!readRTC->asTexture()) {
continue;
}
GrPaint paint1;
GrPaint paint2;
GrPaint paint3;
sk_sp<GrFragmentProcessor> pmToUPM1(new GrConfigConversionEffect(
dataTex.get(), GrSwizzle::RGBA(), *pmToUPMRule, SkMatrix::I()));
sk_sp<GrFragmentProcessor> upmToPM(new GrConfigConversionEffect(
readRTC->asTexture().get(), GrSwizzle::RGBA(), *upmToPMRule, SkMatrix::I()));
sk_sp<GrFragmentProcessor> pmToUPM2(new GrConfigConversionEffect(
tempRTC->asTexture().get(), GrSwizzle::RGBA(), *pmToUPMRule, SkMatrix::I()));
paint1.addColorFragmentProcessor(std::move(pmToUPM1));
paint1.setPorterDuffXPFactory(SkBlendMode::kSrc);
readRTC->fillRectToRect(GrNoClip(), paint1, SkMatrix::I(), kDstRect, kSrcRect);
readRTC->asTexture()->readPixels(0, 0, kSize, kSize, kConfig, firstRead);
paint2.addColorFragmentProcessor(std::move(upmToPM));
paint2.setPorterDuffXPFactory(SkBlendMode::kSrc);
tempRTC->fillRectToRect(GrNoClip(), paint2, SkMatrix::I(), kDstRect, kSrcRect);
paint3.addColorFragmentProcessor(std::move(pmToUPM2));
paint3.setPorterDuffXPFactory(SkBlendMode::kSrc);
readRTC->fillRectToRect(GrNoClip(), paint3, SkMatrix::I(), kDstRect, kSrcRect);
readRTC->asTexture()->readPixels(0, 0, kSize, kSize, kConfig, secondRead);
failed = false;
for (int y = 0; y < kSize && !failed; ++y) {
for (int x = 0; x <= y; ++x) {
if (firstRead[kSize * y + x] != secondRead[kSize * y + x]) {
failed = true;
break;
}
}
}
}
if (failed) {
*pmToUPMRule = kNone_PMConversion;
*upmToPMRule = kNone_PMConversion;
}
}
sk_sp<GrFragmentProcessor> GrConfigConversionEffect::Make(GrTexture* texture,
const GrSwizzle& swizzle,
PMConversion pmConversion,
const SkMatrix& matrix) {
if (swizzle == GrSwizzle::RGBA() && kNone_PMConversion == pmConversion) {
// If we returned a GrConfigConversionEffect that was equivalent to a GrSimpleTextureEffect
// then we may pollute our texture cache with redundant shaders. So in the case that no
// conversions were requested we instead return a GrSimpleTextureEffect.
return GrSimpleTextureEffect::Make(texture, nullptr, matrix);
} else {
if (kRGBA_8888_GrPixelConfig != texture->config() &&
kBGRA_8888_GrPixelConfig != texture->config() &&
kNone_PMConversion != pmConversion) {
// The PM conversions assume colors are 0..255
return nullptr;
}
return sk_sp<GrFragmentProcessor>(
new GrConfigConversionEffect(texture, swizzle, pmConversion, matrix));
}
}
|
// Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "src/backends/pytorch/libtorch_backend.h"
#include <stdint.h>
#include <exception>
#include <memory>
#include "src/core/constants.h"
#include "src/core/logging.h"
#include "src/core/model_config_cuda.h"
#include "src/core/model_config_utils.h"
#include "src/core/provider.h"
#include "src/core/server_status.h"
#ifdef TRTIS_ENABLE_GPU
#include <c10/cuda/CUDACachingAllocator.h>
#include <cuda_runtime_api.h>
#endif // TRTIS_ENABLE_GPU
namespace nvidia { namespace inferenceserver {
LibTorchBackend::Context::Context(
const std::string& name, const int gpu_device, const int max_batch_size)
: BackendContext(name, gpu_device, max_batch_size),
device_(torch::Device(torch::kCPU))
{
}
LibTorchBackend::Context::~Context()
{
torch_model_.reset();
#ifdef TRTIS_ENABLE_GPU
c10::cuda::CUDACachingAllocator::emptyCache();
#endif // TRTIS_ENABLE_GPU
LOG_VERBOSE(1) << "~LibTorchBackend::Context ";
}
std::pair<bool, torch::ScalarType>
ConvertDataTypeToTorchType(const DataType& dtype)
{
torch::ScalarType type = torch::kInt;
switch (dtype) {
case TYPE_BOOL:
type = torch::kBool;
break;
case TYPE_UINT8:
type = torch::kByte;
break;
case TYPE_INT8:
type = torch::kChar;
break;
case TYPE_INT16:
type = torch::kShort;
break;
case TYPE_INT32:
type = torch::kInt;
break;
case TYPE_INT64:
type = torch::kLong;
break;
case TYPE_FP16:
type = torch::kHalf;
break;
case TYPE_FP32:
type = torch::kFloat;
break;
case TYPE_FP64:
type = torch::kDouble;
break;
case TYPE_UINT16:
case TYPE_UINT32:
case TYPE_UINT64:
case TYPE_STRING:
default:
return std::make_pair(false, type);
}
return std::make_pair(true, type);
}
DataType
ConvertTorchTypeToDataType(const torch::ScalarType& ttype)
{
switch (ttype) {
case torch::kBool:
return TYPE_BOOL;
case torch::kByte:
return TYPE_UINT8;
case torch::kChar:
return TYPE_INT8;
case torch::kShort:
return TYPE_INT16;
case torch::kInt:
return TYPE_INT32;
case torch::kLong:
return TYPE_INT64;
case torch::kHalf:
return TYPE_FP16;
case torch::kFloat:
return TYPE_FP32;
case torch::kDouble:
return TYPE_FP64;
default:
return TYPE_FP32;
}
}
Status
LibTorchBackend::Init(const std::string& path, const ModelConfig& config)
{
RETURN_IF_ERROR(ValidateModelConfig(config, kPyTorchLibTorchPlatform));
RETURN_IF_ERROR(SetModelConfig(path, config));
return Status::Success;
}
Status
LibTorchBackend::CreateExecutionContexts(
const std::unordered_map<std::string, std::string>& models)
{
uint32_t total_context_cnt = 0;
// Create a context for each instance.
for (const auto& group : Config().instance_group()) {
for (int c = 0; c < group.count(); c++) {
if (group.kind() == ModelInstanceGroup::KIND_CPU) {
const std::string instance_name =
group.name() + "_" + std::to_string(c) + "_cpu";
RETURN_IF_ERROR(CreateExecutionContext(
instance_name, Context::NO_GPU_DEVICE, models));
total_context_cnt++;
} else {
for (int gpu_device : group.gpus()) {
const std::string instance_name = group.name() + "_" +
std::to_string(c) + "_gpu" +
std::to_string(gpu_device);
RETURN_IF_ERROR(
CreateExecutionContext(instance_name, gpu_device, models));
total_context_cnt++;
}
}
}
}
// Create a scheduler with one thread for each context available for
// this model. Each runner is exclusively tied to the context.
RETURN_IF_ERROR(SetConfiguredScheduler(
total_context_cnt,
[](uint32_t runner_idx) -> Status { return Status::Success; },
[this](
uint32_t runner_idx, std::vector<Scheduler::Payload>* payloads,
std::function<void(Status)> func) {
Run(runner_idx, payloads, func);
}));
return Status::Success;
}
Status
LibTorchBackend::CreateExecutionContext(
const std::string& instance_name, const int gpu_device,
const std::unordered_map<std::string, std::string>& models)
{
// For a GPU context, determine the model file to use for device
// compute capability. CPU always uses the default model file.
std::string cc;
std::string cc_model_filename;
if (gpu_device == Context::NO_GPU_DEVICE) {
cc_model_filename = Config().default_model_filename();
} else {
#ifdef TRTIS_ENABLE_GPU
cudaDeviceProp cuprops;
cudaError_t cuerr = cudaGetDeviceProperties(&cuprops, gpu_device);
if (cuerr != cudaSuccess) {
return Status(
RequestStatusCode::INTERNAL,
"unable to get CUDA device properties for " + Name() + ": " +
cudaGetErrorString(cuerr));
}
cc = std::to_string(cuprops.major) + "." + std::to_string(cuprops.minor);
const auto& cc_itr = Config().cc_model_filenames().find(cc);
cc_model_filename = (cc_itr == Config().cc_model_filenames().end())
? Config().default_model_filename()
: cc_itr->second;
#else
return Status(RequestStatusCode::INTERNAL, "GPU instances not supported");
#endif // TRTIS_ENABLE_GPU
}
const auto& lp_itr = models.find(cc_model_filename);
if (lp_itr == models.end()) {
return Status(
RequestStatusCode::INTERNAL, "unable to find LibTorch model '" +
cc_model_filename + "' for " + Name());
}
if (gpu_device == Context::NO_GPU_DEVICE) {
LOG_INFO << "Creating instance " << instance_name << " on CPU using "
<< cc_model_filename;
} else {
LOG_INFO << "Creating instance " << instance_name << " on GPU "
<< gpu_device << " (" << cc << ") using " << cc_model_filename;
}
// Max batch size. A value of 0 in the config becomes NO_BATCHING.
const int mbs = (Config().max_batch_size() <= 0) ? Context::NO_BATCHING
: Config().max_batch_size();
contexts_.emplace_back(new Context(instance_name, gpu_device, mbs));
Context* context = contexts_.back().get();
RETURN_IF_ERROR(context->CreateCudaStream());
if (gpu_device == Context::NO_GPU_DEVICE) {
context->device_ = torch::Device(torch::kCPU);
} else {
context->device_ = torch::Device(torch::kCUDA, gpu_device);
}
try {
// lp_itr->second is the torch model serialized to string
std::istringstream model_stream(lp_itr->second);
context->torch_model_ = std::make_shared<torch::jit::script::Module>(
torch::jit::load(model_stream, context->device_));
}
catch (const std::exception& ex) {
return Status(
RequestStatusCode::INTERNAL, "load failed for libtorch model -> '" +
Config().name() + "': " + ex.what());
}
RETURN_IF_ERROR(context->ValidateInputs(Config().input()));
RETURN_IF_ERROR(context->ValidateOutputs(Config().output()));
return Status::Success;
}
Status
LibTorchBackend::Context::ValidateInputs(
const ::google::protobuf::RepeatedPtrField<ModelInput>& ios)
{
std::string deliminator = "__";
int ip_index;
for (const auto& io : ios) {
const auto pr = ConvertDataTypeToTorchType(io.data_type());
if (!pr.first) {
return Status(
RequestStatusCode::INTERNAL,
"unsupported datatype " + DataType_Name(io.data_type()) +
" for input '" + io.name() + "' for model '" + name_ + "'");
} else {
const std::string& name = io.name();
try {
int start_pos = name.find(deliminator);
if (start_pos == -1) {
throw std::invalid_argument(
"Input '" + name +
"' does not follow naming convention i.e. <name>__<index>.");
}
ip_index = std::atoi(name.substr(start_pos + 2).c_str());
}
catch (std::exception& ex) {
return Status(
RequestStatusCode::INTERNAL,
"Input '" + name +
"' does not follow naming convention i.e. <name>__<index>.");
}
input_index_map_[name] = ip_index;
}
}
return Status::Success;
}
Status
LibTorchBackend::Context::ValidateOutputs(
const ::google::protobuf::RepeatedPtrField<ModelOutput>& ios)
{
std::string deliminator = "__";
int op_index;
for (const auto& io : ios) {
const auto pr = ConvertDataTypeToTorchType(io.data_type());
if (!pr.first) {
return Status(
RequestStatusCode::INTERNAL,
"unsupported datatype " + DataType_Name(io.data_type()) +
" for output '" + io.name() + "' for model '" + name_ + "'");
} else {
const std::string& name = io.name();
try {
int start_pos = name.find(deliminator);
if (start_pos == -1) {
throw std::invalid_argument(
"Output '" + name +
"' does not follow naming convention i.e. <name>__<index>.");
}
op_index = std::atoi(name.substr(start_pos + 2).c_str());
}
catch (std::exception& ex) {
return Status(
RequestStatusCode::INTERNAL,
"Output '" + name +
"' does not follow naming convention i.e. <name>__<index>.");
}
output_index_map_[name] = op_index;
}
}
return Status::Success;
}
void
LibTorchBackend::Run(
uint32_t runner_idx, std::vector<Scheduler::Payload>* payloads,
std::function<void(Status)> OnCompleteQueuedPayloads)
{
// Each runner executes using the corresponding context...
if (runner_idx >= contexts_.size()) {
OnCompleteQueuedPayloads(Status(
RequestStatusCode::INTERNAL,
"unexpected runner index" + std::to_string(runner_idx) +
", max allowed " + std::to_string(contexts_.size())));
return;
}
std::vector<ModelInferStats::ScopedTimer> compute_timers;
for (auto& payload : *payloads) {
// Stop queue timer when the payload is scheduled to run
if (payload.queue_timer_ != nullptr) {
payload.queue_timer_.reset();
}
if (payload.stats_ != nullptr) {
compute_timers.emplace_back();
payload.stats_->StartComputeTimer(&compute_timers.back());
payload.stats_->SetGPUDevice(contexts_[runner_idx]->gpu_device_);
}
}
Status status = contexts_[runner_idx]->Run(this, payloads);
// reset compute timers before calling OnComplete function
compute_timers.clear();
OnCompleteQueuedPayloads(status);
}
Status
LibTorchBackend::Context::SetFixedSizedInputTensor(
std::vector<torch::jit::IValue>* inputs_, const std::string& name,
const int& ip_index, const std::vector<int64_t>& shape,
const DataType dtype, const size_t batch1_byte_size,
const size_t total_byte_size, std::vector<Scheduler::Payload>* payloads,
std::vector<std::unique_ptr<AllocatedSystemMemory>>* input_buffers,
bool* cuda_copy)
{
// The entire input tensor must be delivered as a single
// contiguous chunk so create a buffer large enough to hold the
// entire dynamic batched input.
auto memory_type = (gpu_device_ == NO_GPU_DEVICE) ? TRTSERVER_MEMORY_CPU
: TRTSERVER_MEMORY_GPU;
input_buffers->emplace_back();
input_buffers->back().reset(
new AllocatedSystemMemory(total_byte_size, memory_type));
char* buffer = input_buffers->back()->MutableBuffer(&memory_type);
// Visit the payloads in order and copy the input tensors to 'buffer'.
std::vector<size_t> expected_byte_sizes;
for (auto& payload : *payloads) {
const InferRequestHeader& request_header =
payload.request_provider_->RequestHeader();
expected_byte_sizes.push_back(
request_header.batch_size() * batch1_byte_size);
}
auto local_cuda_copy =
SetInputBuffer(name, expected_byte_sizes, payloads, memory_type, buffer);
// Make sure the copy is finished before creating Torch tensor from the buffer
// [TODO] Delay SetInputTensor to after all input buffer copies are initiated,
// so that cudaStreamSynchronize() only needs to be called once.
#ifdef TRTIS_ENABLE_GPU
if (local_cuda_copy) {
cudaStreamSynchronize(stream_);
}
#endif // TRTIS_ENABLE_GPU
*cuda_copy |= local_cuda_copy;
RETURN_IF_ERROR(SetInputTensor(
inputs_, name, ip_index, shape, dtype, static_cast<char*>(buffer),
total_byte_size, memory_type));
return Status::Success;
}
Status
LibTorchBackend::Context::SetInputTensor(
std::vector<torch::jit::IValue>* inputs_, const std::string& name,
const int& ip_index, const std::vector<int64_t>& shape,
const DataType dtype, char* content, const size_t byte_size,
const TRTSERVER_Memory_Type memory_type)
{
const auto pr = ConvertDataTypeToTorchType(dtype);
if (!pr.first) {
return Status(
RequestStatusCode::INTERNAL, "Failed to convert DataType '" +
DataType_Name(dtype) +
"' to Torch datatype");
}
torch::TensorOptions options{pr.second};
auto updated_options = options.device(
(memory_type == TRTSERVER_MEMORY_CPU) ? torch::kCPU : torch::kCUDA);
torch::Tensor input_tensor =
torch::from_blob(content, shape, updated_options);
input_tensor = input_tensor.to(device_);
if (input_tensor.nbytes() != byte_size) {
return Status(
RequestStatusCode::INTERNAL,
"unexpected size " + std::to_string(byte_size) +
" for inference input '" + name + "', expecting " +
std::to_string(input_tensor.nbytes()));
}
(*inputs_)[ip_index] = input_tensor;
return Status::Success;
}
Status
LibTorchBackend::Context::ReadFixedSizedOutputTensor(
std::vector<torch::Tensor>* outputs_, const std::string& name,
const int& op_index, const DataType dtype, const size_t dtype_byte_size,
const size_t total_batch_size, const DimsList& dims,
std::vector<Scheduler::Payload>* payloads, bool* cuda_copy)
{
std::vector<int64_t> content_shape;
void* content = nullptr;
size_t byte_size = 0;
RETURN_IF_ERROR(GetOutputTensor(
outputs_, op_index, name, dtype, &content, &byte_size, &content_shape));
// verify shape of output matches shape from model config
const int batch_offset = ((max_batch_size_ == NO_BATCHING) ? 0 : 1);
for (int i = 0; i < dims.size(); i++) {
if (dims[i] != -1) {
if (dims[i] != content_shape[i + batch_offset]) {
return Status(
RequestStatusCode::INVALID_ARG,
"unexpected shape for output '" + name +
"', model configuration shape is " + DimsListToString(dims) +
", inference shape is " + DimsListToString(content_shape));
}
}
}
const size_t total_byte_size =
GetElementCount(content_shape) * dtype_byte_size;
const size_t batch1_byte_size = total_byte_size / total_batch_size;
if (byte_size != total_byte_size) {
return Status(
RequestStatusCode::INVALID_ARG,
"unexpected size for output '" + name + "', byte-size " +
std::to_string(byte_size) + " does not equal " +
std::to_string(total_batch_size) + " * " +
std::to_string(batch1_byte_size));
}
auto content_memory_type =
(device_ == torch::kCPU) ? TRTSERVER_MEMORY_CPU : TRTSERVER_MEMORY_GPU;
*cuda_copy |= SetFixedSizeOutputBuffer(
name, batch1_byte_size, (char*)content, content_shape,
content_memory_type, payloads);
return Status::Success;
}
Status
LibTorchBackend::Context::GetOutputTensor(
std::vector<torch::Tensor>* outputs_, const int& op_index,
const std::string& name, const DataType dtype, void** content,
size_t* byte_size, std::vector<int64_t>* content_shape)
{
try {
torch::Tensor output_flat = (*outputs_)[op_index].flatten();
// verify output datatype matches datatype from model config
DataType rec_dtype = ConvertTorchTypeToDataType(output_flat.scalar_type());
if (dtype != rec_dtype) {
return Status(
RequestStatusCode::INVALID_ARG,
"unexpected datatype " + DataType_Name(rec_dtype) +
" for inference output '" + name + "', expecting " +
DataType_Name(dtype));
}
*byte_size = output_flat.nbytes();
// Copy output into buffer
*content = output_flat.data_ptr();
// Set content shape
auto shape = (*outputs_)[op_index].sizes();
for (auto itr = shape.begin(); itr != shape.end(); itr++) {
content_shape->push_back(*itr);
}
}
catch (std::exception& ex) {
return Status(RequestStatusCode::INTERNAL, "failed to get LibTorch output");
}
return Status::Success;
}
Status
LibTorchBackend::Context::SetInput(
std::vector<torch::jit::IValue>* inputs_, const std::string& name,
const int& ip_index, const DataType datatype, const DimsList& dims,
const size_t total_batch_size, std::vector<Scheduler::Payload>* payloads,
std::vector<std::unique_ptr<AllocatedSystemMemory>>* input_buffers,
bool* cuda_copy)
{
// Get the shape of the input. The provider has already checked that
// the request shape is valid so don't need to do it here.
std::vector<int64_t> shape;
// If model supports batching then prepend the batch dimension
// onto the input shape.
if (max_batch_size_ != NO_BATCHING) {
shape.push_back(total_batch_size);
}
size_t batch1_element_cnt = 1;
for (auto dim : dims) {
shape.push_back(dim);
batch1_element_cnt *= dim;
}
// Checked at initialization time to make sure that STRING is not
// being used for an input, so can just assume fixed-sized here.
const size_t batch1_byte_size =
batch1_element_cnt * GetDataTypeByteSize(datatype);
const size_t total_byte_size = total_batch_size * batch1_byte_size;
return SetFixedSizedInputTensor(
inputs_, name, ip_index, shape, datatype, batch1_byte_size,
total_byte_size, payloads, input_buffers, cuda_copy);
}
Status
LibTorchBackend::Context::Run(
const LibTorchBackend* base, std::vector<Scheduler::Payload>* payloads)
{
LOG_VERBOSE(1) << "Running " << name_ << " with " << payloads->size()
<< " request payloads";
std::shared_ptr<InferRequestProvider> input_request_provider;
// For each request in 'payloads' collect the total batch size for
// this inference execution. The batch-size, number of inputs, and
// size of each input has already been checked by each payloads
// request provider so don't need to do that here.
size_t total_batch_size = 0;
for (auto& payload : *payloads) {
if (!payload.status_.IsOk()) {
return Status(
RequestStatusCode::INTERNAL,
"unexpected payload with non-OK status given to runner for '" +
name_ + "'");
}
total_batch_size += payload.request_provider_->RequestHeader().batch_size();
// All payloads must have equally-sized input tensors so use any
// payload as the representative for the input tensors.
input_request_provider = payload.request_provider_;
}
// If there are no valid payloads then no need to run the
// inference. The payloads will have their error status set so can
// just return.
if (total_batch_size == 0) {
return Status::Success;
}
// total_batch_size can be 1 for models that don't support batching
// (i.e. max_batch_size_ == 0).
if ((total_batch_size != 1) && (total_batch_size > (size_t)max_batch_size_)) {
return Status(
RequestStatusCode::INTERNAL,
"dynamic batch size " + std::to_string(total_batch_size) + " for '" +
name_ + "', max allowed is " + std::to_string(max_batch_size_));
}
// Additional inputs added to the provider...
const std::shared_ptr<InferRequestProvider::InputOverrideMap>&
input_override_map = input_request_provider->GetInputOverride();
// Hold reference to each buffer of input data to that it stays
// until the inference has completed.
std::vector<std::unique_ptr<AllocatedSystemMemory>> input_buffers;
size_t overide_inputs = 0;
if (input_override_map != nullptr) {
overide_inputs = input_override_map->size();
}
// Store input and output tensors
std::vector<torch::jit::IValue> inputs_(
input_request_provider->RequestHeader().input().size() + overide_inputs);
std::vector<torch::Tensor> outputs_;
// Inputs from the request...
bool cuda_copy = false;
for (const auto& input : input_request_provider->RequestHeader().input()) {
const std::string& name = input.name();
int ip_index = input_index_map_[name];
const ModelInput* input_config;
RETURN_IF_ERROR(base->GetInput(name, &input_config));
RETURN_IF_ERROR(SetInput(
&inputs_, name, ip_index, input_config->data_type(), input.dims(),
total_batch_size, payloads, &input_buffers, &cuda_copy));
}
std::string deliminator = "__";
int ip_index;
if (input_override_map != nullptr) {
for (const auto& pr : *input_override_map) {
const std::string& name = pr.first;
LOG_VERBOSE(1) << "Processing extra input: " << name;
const std::shared_ptr<InferRequestProvider::InputOverride>& override =
pr.second;
try {
int start_pos = name.find(deliminator);
if (start_pos == -1) {
throw std::invalid_argument(
"Input '" + name +
"' does not follow naming convention i.e. <name>__<index>.");
}
ip_index = std::atoi(name.substr(start_pos + 2).c_str());
}
catch (std::exception& ex) {
return Status(
RequestStatusCode::INTERNAL,
"Input '" + name +
"' does not follow naming convention i.e. <name>__<index>.");
}
input_index_map_[name] = ip_index;
RETURN_IF_ERROR(SetInput(
&inputs_, name, ip_index, override->datatype_, override->dims_,
total_batch_size, payloads, &input_buffers, &cuda_copy));
}
}
#ifdef TRTIS_ENABLE_GPU
if (cuda_copy) {
cudaStreamSynchronize(stream_);
}
#endif // TRTIS_ENABLE_GPU
// Run...
RETURN_IF_ERROR(Execute(&inputs_, &outputs_));
// verify output indices are valid with number of outputs after execution
for (const auto& output : base->Config().output()) {
int op_index = output_index_map_[output.name()];
int max_index = outputs_.size() - 1;
if ((op_index < 0) || (op_index > max_index)) {
return Status(
RequestStatusCode::INVALID_ARG,
"The output " + output.name() +
" in the model config refers to an output index which doesn't "
"exist. This model has " +
std::to_string(max_index + 1) + " outputs");
}
}
// Prepare set of Outputs requested for
std::set<std::string> required_outputs;
for (auto& payload : *payloads) {
const InferRequestHeader& request_header =
payload.request_provider_->RequestHeader();
for (const auto& output : request_header.output()) {
required_outputs.insert(output.name());
}
}
// Ensure outputs have the expected size and copy it to the payload responses.
cuda_copy = false;
for (const auto& name : required_outputs) {
int op_index = output_index_map_[name];
const ModelOutput* output_config;
RETURN_IF_ERROR(base->GetOutput(name, &output_config));
const DataType dtype = output_config->data_type();
// If a reshape is provided for the output then use that when
// validating that the model matches what is expected.
const DimsList& output_dims = (output_config->has_reshape())
? output_config->reshape().shape()
: output_config->dims();
// Checked at initialization time to make sure that STRING is not
// being used for an output, so can just assume fixed-sized here.
RETURN_IF_ERROR(ReadFixedSizedOutputTensor(
&outputs_, name, op_index, dtype,
GetDataTypeByteSize(output_config->data_type()), total_batch_size,
output_dims, payloads, &cuda_copy));
}
#ifdef TRTIS_ENABLE_GPU
if (cuda_copy) {
cudaStreamSynchronize(stream_);
}
#endif // TRTIS_ENABLE_GPU
return Status::Success;
}
Status
LibTorchBackend::Context::Execute(
std::vector<torch::jit::IValue>* inputs_,
std::vector<torch::Tensor>* outputs_)
{
torch::jit::IValue model_outputs_;
try {
model_outputs_ = torch_model_->forward(*inputs_);
auto model_outputs_tuple = model_outputs_.toTuple();
for (auto& m_op : model_outputs_tuple->elements()) {
outputs_->push_back(m_op.toTensor());
}
}
catch (std::exception& ex) {
try {
auto model_output_tensor = model_outputs_.toTensor();
outputs_->push_back(model_output_tensor);
}
catch (std::exception& exx) {
LOG_VERBOSE(1) << ex.what();
return Status(
RequestStatusCode::INTERNAL, "failed to run model '" + name_);
}
}
return Status::Success;
}
std::ostream&
operator<<(std::ostream& out, const LibTorchBackend& pb)
{
out << "name=" << pb.Name() << std::endl;
out << "contexts:" << std::endl;
for (const auto& context : pb.contexts_) {
out << " name=" << context->name_ << ", gpu="
<< ((context->gpu_device_ == LibTorchBackend::Context::NO_GPU_DEVICE)
? "<none>"
: std::to_string(context->gpu_device_));
}
return out;
}
}} // namespace nvidia::inferenceserver
|
/****************************************************************************************
* @author: kzvd4729 created: Sep/14/2018 00:55
* solution_verdict: Accepted language: GNU C++14
* run_time: 1435 ms memory_used: 101900 KB
* problem: https://codeforces.com/contest/342/problem/E
****************************************************************************************/
#include<bits/stdc++.h>
#define long long long
using namespace std;
const int N=1e5,inf=1e8;
int n,m,sz[N+2],mark[N+2];
int anc[N+2],ans[N+2],tot;
vector<int>adj[N+2];
unordered_map<int,int>dist[N+2];
int reckon(int node,int par)
{
tot++;sz[node]=1;
for(auto x:adj[node])
{
if(x==par||mark[x])continue;
sz[node]+=reckon(x,node);
}
return sz[node];
}
int find_center(int node,int par)
{
int mx=-1,nx=-1;
for(auto x:adj[node])
{
if(x==par||mark[x])continue;
if(sz[x]>tot/2)return find_center(x,node);
}
return node;
}
void cal_dist(int center,int node,int par,int lv)
{
dist[center][node]=dist[node][center]=lv;
for(auto x:adj[node])
{
if(x==par||mark[x])continue;
cal_dist(center,x,node,lv+1);
}
}
void centroid(int node,int par)
{
tot=0;reckon(node,-1);
int center=find_center(node,par);
anc[center]=par;mark[center]=1;
cal_dist(center,center,-1,0);
for(auto x:adj[center])
{
if(mark[x])continue;
centroid(x,center);
}
}
int main()
{
ios_base::sync_with_stdio(0);cin.tie(0);
for(int i=1;i<=n;i++)
{
dist[i].max_load_factor(0.25);
dist[i].reserve(1024);
}
cin>>n>>m;
for(int i=1;i<n;i++)
{
int u,v;cin>>u>>v;
adj[u].push_back(v);
adj[v].push_back(u);
}
centroid(1,-1);
for(int i=1;i<=n;i++)ans[i]=inf;int tmp=1;
while(tmp!=-1)
{
ans[tmp]=min(ans[tmp],dist[tmp][1]);
tmp=anc[tmp];
}
while(m--)
{
int ty,nd;cin>>ty>>nd;
if(ty==1)
{
int tmp=nd;
while(nd!=-1)
{
ans[nd]=min(ans[nd],dist[nd][tmp]);
nd=anc[nd];
}
}
else
{
int tmp=nd,pr=inf;
while(nd!=-1)
{
pr=min(pr,dist[nd][tmp]+ans[nd]);
nd=anc[nd];
}
cout<<pr<<endl;
}
}
return 0;
}
|
// Copyright Louis Dionne 2015
// Distributed under the Boost Software License, Version 1.0.
#include <cassert>
#include <cstddef>
#include <sstream>
#include <tuple>
#include <utility>
// sample(transform)
template <typename ...T, typename F, std::size_t ...i>
auto transform_impl(std::tuple<T...> const& tuple, F const& f,
std::index_sequence<i...>)
{
return std::make_tuple(f(std::get<i>(tuple))...);
}
template <typename ...T, typename F>
auto transform(std::tuple<T...> const& tuple, F const& f) {
return transform_impl(tuple, f,
std::make_index_sequence<sizeof...(T)>{});
}
// end-sample
int main() {
std::tuple<int, char, float> ts{1, '2', 3.3f};
auto us = transform(ts, [](auto x) {
std::ostringstream ss;
ss << x;
return ss.str();
});
assert(us == std::make_tuple("1", "2", "3.3"));
}
|
// Copyright (c) 2009-2018 The Emircoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include <config/emircoin-config.h>
#endif
#include <cstring>
#if HAVE_DECL_STRNLEN == 0
size_t strnlen( const char *start, size_t max_len)
{
const char *end = (const char *)memchr(start, '\0', max_len);
return end ? (size_t)(end - start) : max_len;
}
#endif // HAVE_DECL_STRNLEN
|
/*
Copyright 2021 MacKenzie Strand
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "Toy.hpp"
#include "Component.hpp"
#include "Scene.hpp"
ctHoneybell::ToyBase::ToyBase(ConstructContext& ctx) {
identifier = 0;
transform.position = ctx.spawn.transform.position;
transform.rotation = ctx.spawn.transform.rotation;
transform.scale = ctx.spawn.transform.scale;
aabb = ctBoundBox();
pFirstComponent = NULL;
}
ctHoneybell::ToyBase::~ToyBase() {
/* Auto destruct all components */
ComponentBase* nextComponent = pFirstComponent;
if (!nextComponent) { return; }
while (nextComponent->pNextSiblingComponent) {
ComponentBase* lastComponent = nextComponent;
nextComponent = nextComponent->pNextSiblingComponent;
delete lastComponent;
}
delete nextComponent;
}
ctResults ctHoneybell::ToyBase::OnBegin(BeginContext& ctx) {
return CT_SUCCESS;
}
ctResults ctHoneybell::ToyBase::OnTickSerial(TickContext& ctx) {
return CT_SUCCESS;
}
ctResults ctHoneybell::ToyBase::OnTickParallel(TickContext& ctx) {
return CT_SUCCESS;
}
ctResults ctHoneybell::ToyBase::OnFrameUpdate(FrameUpdateContext& ctx) {
return CT_SUCCESS;
}
ctResults ctHoneybell::ToyBase::OnTryPossess(PossessionContext& ctx) {
return CT_FAILURE_INACCESSIBLE;
}
/* Default point of view handling */
ctResults ctHoneybell::ToyBase::GetPointOfView(PointOfViewContext& ctx) {
ctTransform transform = GetWorldTransform();
float radius = ctBoundSphere(GetAABB()).radius;
if (radius < 0.0f) { radius = 1.0f; }
ctx.cameraInfo.rotation = transform.rotation;
ctx.cameraInfo.position = transform.position +
(transform.rotation.getBack() * radius * 10.0f) +
transform.rotation.getUp() * radius * 2.0f;
return CT_SUCCESS;
}
void ctHoneybell::ToyBase::SetWorldTransform(ctTransform v) {
transform = v;
}
void ctHoneybell::ToyBase::CopyComponentTransform(ComponentBase* pComponent) {
if (!pComponent) { return; }
SetWorldTransform(pComponent->GetWorldTransform());
}
ctTransform ctHoneybell::ToyBase::GetWorldTransform() {
return transform;
}
ctBoundBox ctHoneybell::ToyBase::GetAABB() {
return aabb;
}
void ctHoneybell::ToyBase::SetAABB(ctBoundBox v) {
aabb = v;
}
void ctHoneybell::ToyBase::BeginComponents(BeginContext& ctx) {
if (!pFirstComponent) { return; }
ComponentBase* nextComponent = pFirstComponent;
while (nextComponent->pNextSiblingComponent) {
nextComponent->Begin(ctx);
nextComponent = nextComponent->pNextSiblingComponent;
}
nextComponent->Begin(ctx);
}
ctHandle ctHoneybell::ToyBase::GetIdentifier() {
return identifier;
}
ctResults ctHoneybell::ToyBase::_CallSignal(SignalContext& ctx) {
return CT_FAILURE_INACCESSIBLE;
}
void ctHoneybell::ToyBase::_RegisterComponent(ComponentBase* v) {
if (!pFirstComponent) {
pFirstComponent = v;
} else {
ComponentBase* nextComponent = pFirstComponent;
while (nextComponent->pNextSiblingComponent) {
nextComponent = nextComponent->pNextSiblingComponent;
}
nextComponent->pNextSiblingComponent = v;
}
}
void ctHoneybell::ToyBase::_SetIdentifier(ctHandle hndl) {
identifier = hndl;
}
ctHoneybell::ToyBase* ctHoneybell::ToyTypeRegistry::NewToy(ConstructContext& ctx) {
ZoneScoped;
uint64_t typeHash = ctXXHash64(ctx.typePath);
ctAssert(typeHash != 0);
ToyNewFunction* pCallback = _callbacks.FindPtr(typeHash);
if (!pCallback) {
ctDebugError("Failed to spawn toy of type: %s", ctx.typePath);
return NULL;
}
return (*pCallback)(ctx);
}
ctResults ctHoneybell::ToyTypeRegistry::RegisterToyType(const char* typePath,
ToyNewFunction toyNewFunction) {
ZoneScoped;
uint64_t typeHash = ctXXHash64(typePath);
ctAssert(typeHash != 0);
if (!_callbacks.Insert(typeHash, toyNewFunction)) { return CT_FAILURE_UNKNOWN; }
return CT_SUCCESS;
}
|
#include <qt/test/wallettests.h>
#include <qt/test/util.h>
#include <interfaces/node.h>
#include <qt/bitcoinamountfield.h>
#include <qt/callback.h>
#include <qt/optionsmodel.h>
#include <qt/platformstyle.h>
#include <qt/qvalidatedlineedit.h>
#include <qt/sendcoinsdialog.h>
#include <qt/sendcoinsentry.h>
#include <qt/transactiontablemodel.h>
#include <qt/transactionview.h>
#include <qt/walletmodel.h>
#include <key_io.h>
#include <test/test_bitcoin.h>
#include <validation.h>
#include <wallet/wallet.h>
#include <qt/overviewpage.h>
#include <qt/receivecoinsdialog.h>
#include <qt/recentrequeststablemodel.h>
#include <qt/receiverequestdialog.h>
#include <memory>
#include <QAbstractButton>
#include <QAction>
#include <QApplication>
#include <QCheckBox>
#include <QPushButton>
#include <QTimer>
#include <QVBoxLayout>
#include <QTextEdit>
#include <QListView>
#include <QDialogButtonBox>
namespace
{
//! Press "Yes" or "Cancel" buttons in modal send confirmation dialog.
void ConfirmSend(QString* text = nullptr, bool cancel = false)
{
QTimer::singleShot(0, makeCallback([text, cancel](Callback* callback) {
for (QWidget* widget : QApplication::topLevelWidgets()) {
if (widget->inherits("SendConfirmationDialog")) {
SendConfirmationDialog* dialog = qobject_cast<SendConfirmationDialog*>(widget);
if (text) *text = dialog->text();
QAbstractButton* button = dialog->button(cancel ? QMessageBox::Cancel : QMessageBox::Yes);
button->setEnabled(true);
button->click();
}
}
delete callback;
}), SLOT(call()));
}
//! Send coins to address and return txid.
uint256 SendCoins(CWallet& wallet, SendCoinsDialog& sendCoinsDialog, const CTxDestination& address, CAmount amount, bool rbf)
{
QVBoxLayout* entries = sendCoinsDialog.findChild<QVBoxLayout*>("entries");
SendCoinsEntry* entry = qobject_cast<SendCoinsEntry*>(entries->itemAt(0)->widget());
entry->findChild<QValidatedLineEdit*>("payTo")->setText(QString::fromStdString(EncodeDestination(address)));
entry->findChild<BitcoinAmountField*>("payAmount")->setValue(amount);
/* Litecon: Disabled RBF UI
sendCoinsDialog.findChild<QFrame*>("frameFee")
->findChild<QFrame*>("frameFeeSelection")
->findChild<QCheckBox*>("optInRBF")
->setCheckState(rbf ? Qt::Checked : Qt::Unchecked);
*/
uint256 txid;
boost::signals2::scoped_connection c(wallet.NotifyTransactionChanged.connect([&txid](CWallet*, const uint256& hash, ChangeType status) {
if (status == CT_NEW) txid = hash;
}));
ConfirmSend();
QMetaObject::invokeMethod(&sendCoinsDialog, "on_sendButton_clicked");
return txid;
}
//! Find index of txid in transaction list.
QModelIndex FindTx(const QAbstractItemModel& model, const uint256& txid)
{
QString hash = QString::fromStdString(txid.ToString());
int rows = model.rowCount({});
for (int row = 0; row < rows; ++row) {
QModelIndex index = model.index(row, 0, {});
if (model.data(index, TransactionTableModel::TxHashRole) == hash) {
return index;
}
}
return {};
}
//! Invoke bumpfee on txid and check results.
/* Granacoin: Disable RBF
void BumpFee(TransactionView& view, const uint256& txid, bool expectDisabled, std::string expectError, bool cancel)
{
QTableView* table = view.findChild<QTableView*>("transactionView");
QModelIndex index = FindTx(*table->selectionModel()->model(), txid);
QVERIFY2(index.isValid(), "Could not find BumpFee txid");
// Select row in table, invoke context menu, and make sure bumpfee action is
// enabled or disabled as expected.
QAction* action = view.findChild<QAction*>("bumpFeeAction");
table->selectionModel()->select(index, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
action->setEnabled(expectDisabled);
table->customContextMenuRequested({});
QCOMPARE(action->isEnabled(), !expectDisabled);
action->setEnabled(true);
QString text;
if (expectError.empty()) {
ConfirmSend(&text, cancel);
} else {
ConfirmMessage(&text);
}
action->trigger();
QVERIFY(text.indexOf(QString::fromStdString(expectError)) != -1);
}
*/
//! Simple qt wallet tests.
//
// Test widgets can be debugged interactively calling show() on them and
// manually running the event loop, e.g.:
//
// sendCoinsDialog.show();
// QEventLoop().exec();
//
// This also requires overriding the default minimal Qt platform:
//
// src/qt/test/test_bitcoin-qt -platform xcb # Linux
// src/qt/test/test_bitcoin-qt -platform windows # Windows
// src/qt/test/test_bitcoin-qt -platform cocoa # macOS
void TestGUI()
{
// Set up wallet and chain with 105 blocks (5 mature blocks for spending).
TestChain100Setup test;
for (int i = 0; i < 5; ++i) {
test.CreateAndProcessBlock({}, GetScriptForRawPubKey(test.coinbaseKey.GetPubKey()));
}
std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>("mock", WalletDatabase::CreateMock());
bool firstRun;
wallet->LoadWallet(firstRun);
{
LOCK(wallet->cs_wallet);
wallet->SetAddressBook(GetDestinationForKey(test.coinbaseKey.GetPubKey(), wallet->m_default_address_type), "", "receive");
wallet->AddKeyPubKey(test.coinbaseKey, test.coinbaseKey.GetPubKey());
}
{
LOCK(cs_main);
WalletRescanReserver reserver(wallet.get());
reserver.reserve();
wallet->ScanForWalletTransactions(chainActive.Genesis(), nullptr, reserver, true);
}
wallet->SetBroadcastTransactions(true);
// Create widgets for sending coins and listing transactions.
std::unique_ptr<const PlatformStyle> platformStyle(PlatformStyle::instantiate("other"));
SendCoinsDialog sendCoinsDialog(platformStyle.get());
TransactionView transactionView(platformStyle.get());
auto node = interfaces::MakeNode();
OptionsModel optionsModel(*node);
AddWallet(wallet);
WalletModel walletModel(std::move(node->getWallets().back()), *node, platformStyle.get(), &optionsModel);
RemoveWallet(wallet);
sendCoinsDialog.setModel(&walletModel);
transactionView.setModel(&walletModel);
// Send two transactions, and verify they are added to transaction list.
TransactionTableModel* transactionTableModel = walletModel.getTransactionTableModel();
QCOMPARE(transactionTableModel->rowCount({}), 105);
uint256 txid1 = SendCoins(*wallet.get(), sendCoinsDialog, CKeyID(), 5 * COIN, false /* rbf */);
uint256 txid2 = SendCoins(*wallet.get(), sendCoinsDialog, CKeyID(), 10 * COIN, true /* rbf */);
QCOMPARE(transactionTableModel->rowCount({}), 107);
QVERIFY(FindTx(*transactionTableModel, txid1).isValid());
QVERIFY(FindTx(*transactionTableModel, txid2).isValid());
// Call bumpfee. Test disabled, canceled, enabled, then failing cases.
// Granacoin: Disable BumpFee tests
// BumpFee(transactionView, txid1, true /* expect disabled */, "not BIP 125 replaceable" /* expected error */, false /* cancel */);
// BumpFee(transactionView, txid2, false /* expect disabled */, {} /* expected error */, true /* cancel */);
// BumpFee(transactionView, txid2, false /* expect disabled */, {} /* expected error */, false /* cancel */);
// BumpFee(transactionView, txid2, true /* expect disabled */, "already bumped" /* expected error */, false /* cancel */);
// Check current balance on OverviewPage
OverviewPage overviewPage(platformStyle.get());
overviewPage.setWalletModel(&walletModel);
QLabel* balanceLabel = overviewPage.findChild<QLabel*>("labelBalance");
QString balanceText = balanceLabel->text();
int unit = walletModel.getOptionsModel()->getDisplayUnit();
CAmount balance = walletModel.wallet().getBalance();
QString balanceComparison = BitcoinUnits::formatWithUnit(unit, balance, false, BitcoinUnits::separatorAlways);
QCOMPARE(balanceText, balanceComparison);
// Check Request Payment button
ReceiveCoinsDialog receiveCoinsDialog(platformStyle.get());
receiveCoinsDialog.setModel(&walletModel);
RecentRequestsTableModel* requestTableModel = walletModel.getRecentRequestsTableModel();
// Label input
QLineEdit* labelInput = receiveCoinsDialog.findChild<QLineEdit*>("reqLabel");
labelInput->setText("TEST_LABEL_1");
// Amount input
BitcoinAmountField* amountInput = receiveCoinsDialog.findChild<BitcoinAmountField*>("reqAmount");
amountInput->setValue(1);
// Message input
QLineEdit* messageInput = receiveCoinsDialog.findChild<QLineEdit*>("reqMessage");
messageInput->setText("TEST_MESSAGE_1");
int initialRowCount = requestTableModel->rowCount({});
QPushButton* requestPaymentButton = receiveCoinsDialog.findChild<QPushButton*>("receiveButton");
requestPaymentButton->click();
for (QWidget* widget : QApplication::topLevelWidgets()) {
if (widget->inherits("ReceiveRequestDialog")) {
ReceiveRequestDialog* receiveRequestDialog = qobject_cast<ReceiveRequestDialog*>(widget);
QTextEdit* rlist = receiveRequestDialog->QObject::findChild<QTextEdit*>("outUri");
QString paymentText = rlist->toPlainText();
QStringList paymentTextList = paymentText.split('\n');
QCOMPARE(paymentTextList.at(0), QString("Payment information"));
QVERIFY(paymentTextList.at(1).indexOf(QString("URI: granacoin:")) != -1);
QVERIFY(paymentTextList.at(2).indexOf(QString("Address:")) != -1);
QCOMPARE(paymentTextList.at(3), QString("Amount: 0.00000001 ") + QString::fromStdString(CURRENCY_UNIT));
QCOMPARE(paymentTextList.at(4), QString("Label: TEST_LABEL_1"));
QCOMPARE(paymentTextList.at(5), QString("Message: TEST_MESSAGE_1"));
}
}
// Clear button
QPushButton* clearButton = receiveCoinsDialog.findChild<QPushButton*>("clearButton");
clearButton->click();
QCOMPARE(labelInput->text(), QString(""));
QCOMPARE(amountInput->value(), CAmount(0));
QCOMPARE(messageInput->text(), QString(""));
// Check addition to history
int currentRowCount = requestTableModel->rowCount({});
QCOMPARE(currentRowCount, initialRowCount+1);
// Check Remove button
QTableView* table = receiveCoinsDialog.findChild<QTableView*>("recentRequestsView");
table->selectRow(currentRowCount-1);
QPushButton* removeRequestButton = receiveCoinsDialog.findChild<QPushButton*>("removeRequestButton");
removeRequestButton->click();
QCOMPARE(requestTableModel->rowCount({}), currentRowCount-1);
}
} // namespace
void WalletTests::walletTests()
{
#ifdef Q_OS_MAC
if (QApplication::platformName() == "minimal") {
// Disable for mac on "minimal" platform to avoid crashes inside the Qt
// framework when it tries to look up unimplemented cocoa functions,
// and fails to handle returned nulls
// (https://bugreports.qt.io/browse/QTBUG-49686).
QWARN("Skipping WalletTests on mac build with 'minimal' platform set due to Qt bugs. To run AppTests, invoke "
"with 'test_bitcoin-qt -platform cocoa' on mac, or else use a linux or windows build.");
return;
}
#endif
TestGUI();
}
|
/*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2010-2011, Willow Garage, Inc.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the copyright holder(s) nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <pcl/visualization/pcl_visualizer.h>
#include <pcl/io/pcd_io.h>
#include <pcl/common/transforms.h>
#include <vtkPLYReader.h>
#include <vtkOBJReader.h>
#include <vtkPolyDataMapper.h>
#include <pcl/filters/voxel_grid.h>
#include <pcl/console/print.h>
#include <pcl/console/parse.h>
#include <pcl/apps/render_views_tesselated_sphere.h>
#include "mesh2pcd.h"
using namespace pcl;
using namespace pcl::io;
using namespace pcl::console;
/**
* @function obj2pcd
*/
void obj2pcd( std::string _inputOBJ,
std::string _outputPCD,
double _resolution,
int _tesselated_sphere_level,
double _leaf_size ) {
vtkSmartPointer<vtkPolyData> polydata1;
vtkSmartPointer<vtkOBJReader> readerQuery = vtkSmartPointer<vtkOBJReader>::New ();
readerQuery->SetFileName ( _inputOBJ.c_str() );
polydata1 = readerQuery->GetOutput ();
polydata1->Update ();
processPolydata( polydata1, _outputPCD );
}
/**
* @function ply2pcd
*/
void ply2pcd( std::string _inputPLY,
std::string _outputPCD,
double _resolution,
int _tesselated_sphere_level,
double _leaf_size ) {
vtkSmartPointer<vtkPolyData> polydata1;
vtkSmartPointer<vtkPLYReader> readerQuery = vtkSmartPointer<vtkPLYReader>::New ();
readerQuery->SetFileName ( _inputPLY.c_str() );
polydata1 = readerQuery->GetOutput ();
polydata1->Update ();
processPolydata( polydata1, _outputPCD );
}
/**
* @functin processPolyData
*/
void processPolydata( vtkSmartPointer<vtkPolyData> _polydata,
std::string _pcdFile,
double _resolution,
int _tesselated_sphere_level,
double _leaf_size ) {
bool INTER_VIS = false;
bool VIS = true;
// Get views
std::vector< PointCloud<PointXYZ>::Ptr > views_xyz; views_xyz.resize(0);
std::vector<Eigen::Matrix4f, Eigen::aligned_allocator<Eigen::Matrix4f> > poses; poses.resize(0);
std::vector<float> enthropies; enthropies.resize(0);
pcl::apps::RenderViewsTesselatedSphere render_views;
render_views.addModelFromPolyData( _polydata );
render_views.setResolution( _resolution );
render_views.setComputeEntropies( false );
render_views.setTesselationLevel( _tesselated_sphere_level );
render_views.generateViews();
render_views.getPoses( poses );
render_views.getViews( views_xyz );
//render_views.getEntropies( enthropies );
//Take views and fuse them together
std::vector<PointCloud<PointXYZ>::Ptr> aligned_clouds;
aligned_clouds.resize(0);
for (size_t i = 0; i < views_xyz.size (); i++)
{
PointCloud<PointXYZ>::Ptr cloud (new PointCloud<PointXYZ> ());
Eigen::Matrix4f pose_inverse;
pose_inverse = poses[i].inverse ();
transformPointCloud ( *views_xyz[i], *cloud, pose_inverse);
aligned_clouds.push_back (cloud);
}
// ** INTER_VIS **
if (INTER_VIS)
{
visualization::PCLVisualizer vis2 ("visualize");
for (size_t i = 0; i < aligned_clouds.size (); i++)
{
std::stringstream name;
name << "cloud_" << i;
vis2.addPointCloud (aligned_clouds[i], name.str ());
vis2.spin ();
}
}
// Fuse clouds
PointCloud<PointXYZ>::Ptr big_boy (new PointCloud<PointXYZ> ());
big_boy->points.resize(0);
for (size_t i = 0; i < aligned_clouds.size (); i++)
*big_boy += *aligned_clouds[i];
// ** VIS **
if (VIS)
{
visualization::PCLVisualizer vis2 ("visualize");
vis2.addPointCloud (big_boy);
vis2.spin ();
}
// Voxelgrid
PointCloud<PointXYZ>::Ptr big_boyFiltered (new PointCloud<PointXYZ> ());
VoxelGrid<PointXYZ> grid_;
grid_.setInputCloud (big_boy);
grid_.setLeafSize ( _leaf_size, _leaf_size, _leaf_size);
grid_.filter (*big_boyFiltered);
if (VIS)
{
visualization::PCLVisualizer vis3 ("visualize");
vis3.addPointCloud (big_boy);
vis3.spin ();
}
printf("Saving to PCD \n");
savePCDFileASCII ( _pcdFile, *big_boyFiltered);
printf(" Closing visualization windows \n");
return;
}
|
/*
* Copyright 2017 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "include/core/SkTypes.h"
#if SK_SUPPORT_GPU
#include "include/core/SkCanvas.h"
#include "include/core/SkPaint.h"
#include "include/core/SkPath.h"
#include "samplecode/Sample.h"
#include "src/core/SkRectPriv.h"
#include "src/gpu/GrClip.h"
#include "src/gpu/GrContextPriv.h"
#include "src/gpu/GrGpu.h"
#include "src/gpu/GrMemoryPool.h"
#include "src/gpu/GrOnFlushResourceProvider.h"
#include "src/gpu/GrOpFlushState.h"
#include "src/gpu/GrRenderTargetContext.h"
#include "src/gpu/GrRenderTargetContextPriv.h"
#include "src/gpu/GrResourceProvider.h"
#include "src/gpu/ccpr/GrCCCoverageProcessor.h"
#include "src/gpu/ccpr/GrCCFillGeometry.h"
#include "src/gpu/ccpr/GrCCStroker.h"
#include "src/gpu/ccpr/GrGSCoverageProcessor.h"
#include "src/gpu/ccpr/GrVSCoverageProcessor.h"
#include "src/gpu/geometry/GrPathUtils.h"
#include "src/gpu/glsl/GrGLSLFragmentShaderBuilder.h"
#include "src/gpu/ops/GrDrawOp.h"
#ifdef SK_GL
#include "src/gpu/gl/GrGLGpu.h"
#endif
using TriPointInstance = GrCCCoverageProcessor::TriPointInstance;
using QuadPointInstance = GrCCCoverageProcessor::QuadPointInstance;
using PrimitiveType = GrCCCoverageProcessor::PrimitiveType;
static constexpr float kDebugBloat = 40;
/**
* This sample visualizes the AA bloat geometry generated by the ccpr geometry shaders. It
* increases the AA bloat by 50x and outputs color instead of coverage (coverage=+1 -> green,
* coverage=0 -> black, coverage=-1 -> red). Use the keys 1-7 to cycle through the different
* geometry processors.
*/
class CCPRGeometryView : public Sample {
void onOnceBeforeDraw() override { this->updateGpuData(); }
void onDrawContent(SkCanvas*) override;
Sample::Click* onFindClickHandler(SkScalar x, SkScalar y, skui::ModifierKey) override;
bool onClick(Sample::Click*) override;
bool onChar(SkUnichar) override;
SkString name() override { return SkString("CCPRGeometry"); }
class Click;
class DrawCoverageCountOp;
class VisualizeCoverageCountFP;
void updateAndInval() { this->updateGpuData(); }
void updateGpuData();
PrimitiveType fPrimitiveType = PrimitiveType::kTriangles;
SkCubicType fCubicType;
SkMatrix fCubicKLM;
SkPoint fPoints[4] = {
{100.05f, 100.05f}, {400.75f, 100.05f}, {400.75f, 300.95f}, {100.05f, 300.95f}};
float fConicWeight = .5;
float fStrokeWidth = 40;
bool fDoStroke = false;
SkTArray<TriPointInstance> fTriPointInstances;
SkTArray<QuadPointInstance> fQuadPointInstances;
SkPath fPath;
};
class CCPRGeometryView::DrawCoverageCountOp : public GrDrawOp {
DEFINE_OP_CLASS_ID
public:
DrawCoverageCountOp(CCPRGeometryView* view) : INHERITED(ClassID()), fView(view) {
this->setBounds(SkRect::MakeIWH(fView->width(), fView->height()), GrOp::HasAABloat::kNo,
GrOp::IsHairline::kNo);
}
const char* name() const override {
return "[Testing/Sample code] CCPRGeometryView::DrawCoverageCountOp";
}
private:
FixedFunctionFlags fixedFunctionFlags() const override { return FixedFunctionFlags::kNone; }
GrProcessorSet::Analysis finalize(const GrCaps&, const GrAppliedClip*,
bool hasMixedSampledCoverage, GrClampType) override {
return GrProcessorSet::EmptySetAnalysis();
}
void onPrePrepare(GrRecordingContext*,
const GrSurfaceProxyView* writeView,
GrAppliedClip*,
const GrXferProcessor::DstProxyView&) override {}
void onPrepare(GrOpFlushState*) override {}
void onExecute(GrOpFlushState*, const SkRect& chainBounds) override;
CCPRGeometryView* fView;
typedef GrDrawOp INHERITED;
};
class CCPRGeometryView::VisualizeCoverageCountFP : public GrFragmentProcessor {
public:
VisualizeCoverageCountFP() : GrFragmentProcessor(kTestFP_ClassID, kNone_OptimizationFlags) {}
private:
const char* name() const override {
return "[Testing/Sample code] CCPRGeometryView::VisualizeCoverageCountFP";
}
std::unique_ptr<GrFragmentProcessor> clone() const override {
return std::make_unique<VisualizeCoverageCountFP>();
}
void onGetGLSLProcessorKey(const GrShaderCaps&, GrProcessorKeyBuilder*) const override {}
bool onIsEqual(const GrFragmentProcessor&) const override { return true; }
class Impl : public GrGLSLFragmentProcessor {
void emitCode(EmitArgs& args) override {
GrGLSLFPFragmentBuilder* f = args.fFragBuilder;
f->codeAppendf("half count = %s.a;", args.fInputColor);
f->codeAppendf("%s = half4(clamp(-count, 0, 1), clamp(+count, 0, 1), 0, abs(count));",
args.fOutputColor);
}
};
GrGLSLFragmentProcessor* onCreateGLSLInstance() const override { return new Impl; }
};
static void draw_klm_line(int w, int h, SkCanvas* canvas, const SkScalar line[3], SkColor color) {
SkPoint p1, p2;
if (SkScalarAbs(line[1]) > SkScalarAbs(line[0])) {
// Draw from vertical edge to vertical edge.
p1 = {0, -line[2] / line[1]};
p2 = {(SkScalar)w, (-line[2] - w * line[0]) / line[1]};
} else {
// Draw from horizontal edge to horizontal edge.
p1 = {-line[2] / line[0], 0};
p2 = {(-line[2] - h * line[1]) / line[0], (SkScalar)h};
}
SkPaint linePaint;
linePaint.setColor(color);
linePaint.setAlpha(128);
linePaint.setStyle(SkPaint::kStroke_Style);
linePaint.setStrokeWidth(0);
linePaint.setAntiAlias(true);
canvas->drawLine(p1, p2, linePaint);
}
void CCPRGeometryView::onDrawContent(SkCanvas* canvas) {
canvas->clear(SK_ColorBLACK);
if (!fDoStroke) {
SkPaint outlinePaint;
outlinePaint.setColor(0x80ffffff);
outlinePaint.setStyle(SkPaint::kStroke_Style);
outlinePaint.setStrokeWidth(0);
outlinePaint.setAntiAlias(true);
canvas->drawPath(fPath, outlinePaint);
}
#if 0
SkPaint gridPaint;
gridPaint.setColor(0x10000000);
gridPaint.setStyle(SkPaint::kStroke_Style);
gridPaint.setStrokeWidth(0);
gridPaint.setAntiAlias(true);
for (int y = 0; y < this->height(); y += kDebugBloat) {
canvas->drawLine(0, y, this->width(), y, gridPaint);
}
for (int x = 0; x < this->width(); x += kDebugBloat) {
canvas->drawLine(x, 0, x, this->height(), outlinePaint);
}
#endif
SkString caption;
if (GrRenderTargetContext* rtc = canvas->internal_private_accessTopLayerRenderTargetContext()) {
// Render coverage count.
GrContext* ctx = canvas->getGrContext();
SkASSERT(ctx);
GrOpMemoryPool* pool = ctx->priv().opMemoryPool();
int width = this->width();
int height = this->height();
auto ccbuff = GrRenderTargetContext::Make(
ctx, GrColorType::kAlpha_F16, nullptr, SkBackingFit::kApprox, {width, height});
SkASSERT(ccbuff);
ccbuff->clear(nullptr, SK_PMColor4fTRANSPARENT,
GrRenderTargetContext::CanClearFullscreen::kYes);
ccbuff->priv().testingOnly_addDrawOp(pool->allocate<DrawCoverageCountOp>(this));
// Visualize coverage count in main canvas.
GrPaint paint;
paint.addColorFragmentProcessor(
GrTextureEffect::Make(ccbuff->readSurfaceView(), ccbuff->colorInfo().alphaType()));
paint.addColorFragmentProcessor(
std::make_unique<VisualizeCoverageCountFP>());
paint.setPorterDuffXPFactory(SkBlendMode::kSrcOver);
rtc->drawRect(GrNoClip(), std::move(paint), GrAA::kNo, SkMatrix::I(),
SkRect::MakeIWH(this->width(), this->height()));
// Add label.
caption.appendf("PrimitiveType_%s",
GrCCCoverageProcessor::PrimitiveTypeName(fPrimitiveType));
if (PrimitiveType::kCubics == fPrimitiveType) {
caption.appendf(" (%s)", SkCubicTypeName(fCubicType));
} else if (PrimitiveType::kConics == fPrimitiveType) {
caption.appendf(" (w=%f)", fConicWeight);
}
if (fDoStroke) {
caption.appendf(" (stroke_width=%f)", fStrokeWidth);
}
} else {
caption = "Use GPU backend to visualize geometry.";
}
SkPaint pointsPaint;
pointsPaint.setColor(SK_ColorBLUE);
pointsPaint.setStrokeWidth(8);
pointsPaint.setAntiAlias(true);
if (PrimitiveType::kCubics == fPrimitiveType) {
canvas->drawPoints(SkCanvas::kPoints_PointMode, 4, fPoints, pointsPaint);
if (!fDoStroke) {
int w = this->width(), h = this->height();
draw_klm_line(w, h, canvas, &fCubicKLM[0], SK_ColorYELLOW);
draw_klm_line(w, h, canvas, &fCubicKLM[3], SK_ColorBLUE);
draw_klm_line(w, h, canvas, &fCubicKLM[6], SK_ColorRED);
}
} else {
canvas->drawPoints(SkCanvas::kPoints_PointMode, 2, fPoints, pointsPaint);
canvas->drawPoints(SkCanvas::kPoints_PointMode, 1, fPoints + 3, pointsPaint);
}
SkFont font(nullptr, 20);
SkPaint captionPaint;
captionPaint.setColor(SK_ColorWHITE);
canvas->drawString(caption, 10, 30, font, captionPaint);
}
void CCPRGeometryView::updateGpuData() {
using Verb = GrCCFillGeometry::Verb;
fTriPointInstances.reset();
fQuadPointInstances.reset();
fPath.reset();
fPath.moveTo(fPoints[0]);
if (PrimitiveType::kCubics == fPrimitiveType) {
double t[2], s[2];
fCubicType = GrPathUtils::getCubicKLM(fPoints, &fCubicKLM, t, s);
GrCCFillGeometry geometry;
geometry.beginContour(fPoints[0]);
geometry.cubicTo(fPoints, kDebugBloat / 2, kDebugBloat / 2);
geometry.endContour();
int ptsIdx = 0;
for (Verb verb : geometry.verbs()) {
switch (verb) {
case Verb::kLineTo:
++ptsIdx;
continue;
case Verb::kMonotonicQuadraticTo:
ptsIdx += 2;
continue;
case Verb::kMonotonicCubicTo:
fQuadPointInstances.push_back().set(&geometry.points()[ptsIdx], 0, 0);
ptsIdx += 3;
continue;
default:
continue;
}
}
fPath.cubicTo(fPoints[1], fPoints[2], fPoints[3]);
} else if (PrimitiveType::kTriangles != fPrimitiveType) {
SkPoint P3[3] = {fPoints[0], fPoints[1], fPoints[3]};
GrCCFillGeometry geometry;
geometry.beginContour(P3[0]);
if (PrimitiveType::kQuadratics == fPrimitiveType) {
geometry.quadraticTo(P3);
fPath.quadTo(fPoints[1], fPoints[3]);
} else {
SkASSERT(PrimitiveType::kConics == fPrimitiveType);
geometry.conicTo(P3, fConicWeight);
fPath.conicTo(fPoints[1], fPoints[3], fConicWeight);
}
geometry.endContour();
int ptsIdx = 0, conicWeightIdx = 0;
for (Verb verb : geometry.verbs()) {
if (Verb::kBeginContour == verb ||
Verb::kEndOpenContour == verb ||
Verb::kEndClosedContour == verb) {
continue;
}
if (Verb::kLineTo == verb) {
++ptsIdx;
continue;
}
SkASSERT(Verb::kMonotonicQuadraticTo == verb || Verb::kMonotonicConicTo == verb);
if (PrimitiveType::kQuadratics == fPrimitiveType &&
Verb::kMonotonicQuadraticTo == verb) {
fTriPointInstances.push_back().set(
&geometry.points()[ptsIdx], Sk2f(0, 0),
TriPointInstance::Ordering::kXYTransposed);
} else if (PrimitiveType::kConics == fPrimitiveType &&
Verb::kMonotonicConicTo == verb) {
fQuadPointInstances.push_back().setW(&geometry.points()[ptsIdx], Sk2f(0, 0),
geometry.getConicWeight(conicWeightIdx++));
}
ptsIdx += 2;
}
} else {
fTriPointInstances.push_back().set(
fPoints[0], fPoints[1], fPoints[3], Sk2f(0, 0),
TriPointInstance::Ordering::kXYTransposed);
fPath.lineTo(fPoints[1]);
fPath.lineTo(fPoints[3]);
fPath.close();
}
}
void CCPRGeometryView::DrawCoverageCountOp::onExecute(GrOpFlushState* state,
const SkRect& chainBounds) {
GrResourceProvider* rp = state->resourceProvider();
GrContext* context = state->gpu()->getContext();
#ifdef SK_GL
GrGLGpu* glGpu = GrBackendApi::kOpenGL == context->backend()
? static_cast<GrGLGpu*>(state->gpu())
: nullptr;
if (glGpu) {
glGpu->handleDirtyContext();
// GR_GL_CALL(glGpu->glInterface(), PolygonMode(GR_GL_FRONT_AND_BACK, GR_GL_LINE));
GR_GL_CALL(glGpu->glInterface(), Enable(GR_GL_LINE_SMOOTH));
}
#endif
GrPipeline pipeline(GrScissorTest::kDisabled, SkBlendMode::kPlus,
state->drawOpArgs().writeSwizzle());
std::unique_ptr<GrCCCoverageProcessor> proc;
if (state->caps().shaderCaps()->geometryShaderSupport()) {
proc = std::make_unique<GrGSCoverageProcessor>();
} else {
proc = std::make_unique<GrVSCoverageProcessor>();
}
SkDEBUGCODE(proc->enableDebugBloat(kDebugBloat));
GrOpsRenderPass* renderPass = state->opsRenderPass();
if (!fView->fDoStroke) {
for (int i = 0; i < proc->numSubpasses(); ++i) {
proc->reset(fView->fPrimitiveType, i, rp);
proc->bindPipeline(state, pipeline, this->bounds());
if (PrimitiveType::kCubics == fView->fPrimitiveType ||
PrimitiveType::kConics == fView->fPrimitiveType) {
sk_sp<GrGpuBuffer> instBuff(rp->createBuffer(
fView->fQuadPointInstances.count() * sizeof(QuadPointInstance),
GrGpuBufferType::kVertex, kDynamic_GrAccessPattern,
fView->fQuadPointInstances.begin()));
if (!fView->fQuadPointInstances.empty() && instBuff) {
proc->bindBuffers(renderPass, instBuff.get());
proc->drawInstances(renderPass, fView->fQuadPointInstances.count(), 0);
}
} else {
sk_sp<GrGpuBuffer> instBuff(rp->createBuffer(
fView->fTriPointInstances.count() * sizeof(TriPointInstance),
GrGpuBufferType::kVertex, kDynamic_GrAccessPattern,
fView->fTriPointInstances.begin()));
if (!fView->fTriPointInstances.empty() && instBuff) {
proc->bindBuffers(renderPass, instBuff.get());
proc->drawInstances(renderPass, fView->fTriPointInstances.count(), 0);
}
}
}
} else if (PrimitiveType::kConics != fView->fPrimitiveType) { // No conic stroke support yet.
GrCCStroker stroker(0,0,0);
SkPaint p;
p.setStyle(SkPaint::kStroke_Style);
p.setStrokeWidth(fView->fStrokeWidth);
p.setStrokeJoin(SkPaint::kMiter_Join);
p.setStrokeMiter(4);
// p.setStrokeCap(SkPaint::kRound_Cap);
stroker.parseDeviceSpaceStroke(fView->fPath, SkPathPriv::PointData(fView->fPath),
SkStrokeRec(p), p.getStrokeWidth(), GrScissorTest::kDisabled,
SkIRect::MakeWH(fView->width(), fView->height()), {0, 0});
GrCCStroker::BatchID batchID = stroker.closeCurrentBatch();
GrOnFlushResourceProvider onFlushRP(context->priv().drawingManager());
stroker.prepareToDraw(&onFlushRP);
SkIRect ibounds;
this->bounds().roundOut(&ibounds);
stroker.drawStrokes(state, proc.get(), batchID, ibounds);
}
#ifdef SK_GL
if (glGpu) {
context->resetContext(kMisc_GrGLBackendState);
}
#endif
}
class CCPRGeometryView::Click : public Sample::Click {
public:
Click(int ptIdx) : fPtIdx(ptIdx) {}
void doClick(SkPoint points[]) {
if (fPtIdx >= 0) {
points[fPtIdx] += fCurr - fPrev;
} else {
for (int i = 0; i < 4; ++i) {
points[i] += fCurr - fPrev;
}
}
}
private:
int fPtIdx;
};
Sample::Click* CCPRGeometryView::onFindClickHandler(SkScalar x, SkScalar y, skui::ModifierKey) {
for (int i = 0; i < 4; ++i) {
if (PrimitiveType::kCubics != fPrimitiveType && 2 == i) {
continue;
}
if (fabs(x - fPoints[i].x()) < 20 && fabsf(y - fPoints[i].y()) < 20) {
return new Click(i);
}
}
return new Click(-1);
}
bool CCPRGeometryView::onClick(Sample::Click* click) {
Click* myClick = (Click*)click;
myClick->doClick(fPoints);
this->updateAndInval();
return true;
}
bool CCPRGeometryView::onChar(SkUnichar unichar) {
if (unichar >= '1' && unichar <= '4') {
fPrimitiveType = PrimitiveType(unichar - '1');
if (fPrimitiveType >= PrimitiveType::kWeightedTriangles) {
fPrimitiveType = (PrimitiveType) ((int)fPrimitiveType + 1);
}
this->updateAndInval();
return true;
}
float* valueToScale = nullptr;
if (fDoStroke) {
valueToScale = &fStrokeWidth;
} else if (PrimitiveType::kConics == fPrimitiveType) {
valueToScale = &fConicWeight;
}
if (valueToScale) {
if (unichar == '+') {
*valueToScale *= 2;
this->updateAndInval();
return true;
}
if (unichar == '+' || unichar == '=') {
*valueToScale *= 5/4.f;
this->updateAndInval();
return true;
}
if (unichar == '-') {
*valueToScale *= 4/5.f;
this->updateAndInval();
return true;
}
if (unichar == '_') {
*valueToScale *= .5f;
this->updateAndInval();
return true;
}
}
if (unichar == 'D') {
SkDebugf(" SkPoint fPoints[4] = {\n");
SkDebugf(" {%ff, %ff},\n", fPoints[0].x(), fPoints[0].y());
SkDebugf(" {%ff, %ff},\n", fPoints[1].x(), fPoints[1].y());
SkDebugf(" {%ff, %ff},\n", fPoints[2].x(), fPoints[2].y());
SkDebugf(" {%ff, %ff}\n", fPoints[3].x(), fPoints[3].y());
SkDebugf(" };\n");
return true;
}
if (unichar == 'S') {
fDoStroke = !fDoStroke;
this->updateAndInval();
}
return false;
}
DEF_SAMPLE(return new CCPRGeometryView;)
#endif // SK_SUPPORT_GPU
|
/*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "IBL.h"
#include <fstream>
#include <string>
#include <filament/Engine.h>
#include <filament/Material.h>
#include <filament/MaterialInstance.h>
#include <filament/Texture.h>
#include <filament/Skybox.h>
#include <image/KtxBundle.h>
#include <image/KtxUtility.h>
#include <stb_image.h>
#include <utils/Path.h>
#include <filament/IndirectLight.h>
using namespace filament;
using namespace image;
using namespace filament::math;
using namespace utils;
static constexpr float IBL_INTENSITY = 30000.0f;
IBL::IBL(Engine& engine) : mEngine(engine) {
}
IBL::~IBL() {
mEngine.destroy(mIndirectLight);
mEngine.destroy(mTexture);
mEngine.destroy(mSkybox);
mEngine.destroy(mSkyboxTexture);
}
bool IBL::loadFromKtx(const std::string& prefix) {
// First check for compressed variants of the environment.
Path iblPath(prefix + "_ibl_s3tc.ktx");
if (!iblPath.exists()) {
iblPath = Path(prefix + "_ibl.ktx");
if (!iblPath.exists()) {
return false;
}
}
Path skyPath(prefix + "_skybox_s3tc.ktx");
if (!skyPath.exists()) {
skyPath = Path(prefix + "_skybox.ktx");
if (!skyPath.exists()) {
return false;
}
}
auto createKtx = [] (Path path) {
using namespace std;
ifstream file(path.getPath(), ios::binary);
vector<uint8_t> contents((istreambuf_iterator<char>(file)), {});
return new image::KtxBundle(contents.data(), contents.size());
};
KtxBundle* iblKtx = createKtx(iblPath);
KtxBundle* skyKtx = createKtx(skyPath);
mSkyboxTexture = KtxUtility::createTexture(&mEngine, skyKtx, false);
mTexture = KtxUtility::createTexture(&mEngine, iblKtx, false);
if (!iblKtx->getSphericalHarmonics(mBands)) {
return false;
}
mIndirectLight = IndirectLight::Builder()
.reflections(mTexture)
.irradiance(3, mBands)
.intensity(IBL_INTENSITY)
.build(mEngine);
mSkybox = Skybox::Builder().environment(mSkyboxTexture).showSun(true).build(mEngine);
return true;
}
bool IBL::loadFromDirectory(const utils::Path& path) {
// First check if KTX files are available.
if (loadFromKtx(Path::concat(path, path.getName()))) {
return true;
}
// Read spherical harmonics
Path sh(Path::concat(path, "sh.txt"));
if (sh.exists()) {
std::ifstream shReader(sh);
shReader >> std::skipws;
std::string line;
for (float3& band : mBands) {
std::getline(shReader, line);
int n = sscanf(line.c_str(), "(%f,%f,%f)", &band.r, &band.g, &band.b); // NOLINT(cert-err34-c)
if (n != 3) return false;
}
} else {
return false;
}
// Read mip-mapped cubemap
const std::string prefix = "m";
if (!loadCubemapLevel(&mTexture, path, 0, prefix + "0_")) return false;
size_t numLevels = mTexture->getLevels();
for (size_t i = 1; i<numLevels; i++) {
const std::string levelPrefix = prefix + std::to_string(i) + "_";
if (!loadCubemapLevel(&mTexture, path, i, levelPrefix)) return false;
}
if (!loadCubemapLevel(&mSkyboxTexture, path)) return false;
mIndirectLight = IndirectLight::Builder()
.reflections(mTexture)
.irradiance(3, mBands)
.intensity(IBL_INTENSITY)
.build(mEngine);
mSkybox = Skybox::Builder().environment(mSkyboxTexture).showSun(true).build(mEngine);
return true;
}
bool IBL::loadCubemapLevel(filament::Texture** texture, const utils::Path& path, size_t level,
std::string const& levelPrefix) const {
Texture::FaceOffsets offsets;
Texture::PixelBufferDescriptor buffer;
bool success = loadCubemapLevel(texture, &buffer, &offsets, path, level, levelPrefix);
if (!success) return false;
(*texture)->setImage(mEngine, level, std::move(buffer), offsets);
return true;
}
bool IBL::loadCubemapLevel(
filament::Texture** texture,
Texture::PixelBufferDescriptor* outBuffer,
Texture::FaceOffsets* outOffsets,
const utils::Path& path, size_t level, std::string const& levelPrefix) const {
static const char* faceSuffix[6] = { "px", "nx", "py", "ny", "pz", "nz" };
size_t size = 0;
size_t numLevels = 1;
{ // this is just a scope to avoid variable name hidding below
int w, h;
std::string faceName = levelPrefix + faceSuffix[0] + ".rgb32f";
Path facePath(Path::concat(path, faceName));
if (!facePath.exists()) {
std::cerr << "The face " << faceName << " does not exist" << std::endl;
return false;
}
stbi_info(facePath.getAbsolutePath().c_str(), &w, &h, nullptr);
if (w != h) {
std::cerr << "width != height" << std::endl;
return false;
}
size = (size_t)w;
if (!levelPrefix.empty()) {
numLevels = (size_t)std::log2(size) + 1;
}
if (level == 0) {
*texture = Texture::Builder()
.width((uint32_t)size)
.height((uint32_t)size)
.levels((uint8_t)numLevels)
.format(Texture::InternalFormat::R11F_G11F_B10F)
.sampler(Texture::Sampler::SAMPLER_CUBEMAP)
.build(mEngine);
}
}
// RGB_10_11_11_REV encoding: 4 bytes per pixel
const size_t faceSize = size * size * sizeof(uint32_t);
Texture::FaceOffsets offsets;
Texture::PixelBufferDescriptor buffer(
malloc(faceSize * 6), faceSize * 6,
Texture::Format::RGB, Texture::Type::UINT_10F_11F_11F_REV,
(Texture::PixelBufferDescriptor::Callback) &free);
bool success = true;
uint8_t* p = static_cast<uint8_t*>(buffer.buffer);
for (size_t j = 0; j < 6; j++) {
offsets[j] = faceSize * j;
std::string faceName = levelPrefix + faceSuffix[j] + ".rgb32f";
Path facePath(Path::concat(path, faceName));
if (!facePath.exists()) {
std::cerr << "The face " << faceName << " does not exist" << std::endl;
success = false;
break;
}
int w, h, n;
unsigned char* data = stbi_load(facePath.getAbsolutePath().c_str(), &w, &h, &n, 4);
if (w != h || w != size) {
std::cerr << "Face " << faceName << "has a wrong size " << w << " x " << h <<
", instead of " << size << " x " << size << std::endl;
success = false;
break;
}
if (data == nullptr || n != 4) {
std::cerr << "Could not decode face " << faceName << std::endl;
success = false;
break;
}
memcpy(p + offsets[j], data, w * h * sizeof(uint32_t));
stbi_image_free(data);
}
if (!success) return false;
*outBuffer = std::move(buffer);
*outOffsets = offsets;
return true;
}
|
// Copyright (c) 2011-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
// Unit tests for denial-of-service detection/prevention code
#include "chainparams.h"
#include "keystore.h"
#include "net.h"
#include "net_processing.h"
#include "pow.h"
#include "script/sign.h"
#include "serialize.h"
#include "util.h"
#include "validation.h"
#include "test/test_thought.h"
#include <stdint.h>
#include <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <boost/date_time/posix_time/posix_time_types.hpp>
#include <boost/foreach.hpp>
#include <boost/test/unit_test.hpp>
// Tests these internal-to-net_processing.cpp methods:
extern bool AddOrphanTx(const CTransactionRef& tx, NodeId peer);
extern void EraseOrphansFor(NodeId peer);
extern unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans);
struct COrphanTx {
CTransactionRef tx;
NodeId fromPeer;
int64_t nTimeExpire;
};
extern std::map<uint256, COrphanTx> mapOrphanTransactions;
CService ip(uint32_t i)
{
struct in_addr s;
s.s_addr = i;
return CService(CNetAddr(s), Params().GetDefaultPort());
}
static NodeId id = 0;
BOOST_FIXTURE_TEST_SUITE(DoS_tests, TestingSetup)
BOOST_AUTO_TEST_CASE(DoS_banning)
{
std::atomic<bool> interruptDummy(false);
connman->ClearBanned();
CAddress addr1(ip(0xa0b0c001), NODE_NONE);
CNode dummyNode1(id++, NODE_NETWORK, 0, INVALID_SOCKET, addr1, 0, 0, "", true);
dummyNode1.SetSendVersion(PROTOCOL_VERSION);
GetNodeSignals().InitializeNode(&dummyNode1, *connman);
dummyNode1.nVersion = 1;
dummyNode1.fSuccessfullyConnected = true;
Misbehaving(dummyNode1.GetId(), 100); // Should get banned
SendMessages(&dummyNode1, *connman, interruptDummy);
BOOST_CHECK(connman->IsBanned(addr1));
BOOST_CHECK(!connman->IsBanned(ip(0xa0b0c001|0x0000ff00))); // Different IP, not banned
CAddress addr2(ip(0xa0b0c002), NODE_NONE);
CNode dummyNode2(id++, NODE_NETWORK, 0, INVALID_SOCKET, addr2, 1, 1, "", true);
dummyNode2.SetSendVersion(PROTOCOL_VERSION);
GetNodeSignals().InitializeNode(&dummyNode2, *connman);
dummyNode2.nVersion = 1;
dummyNode2.fSuccessfullyConnected = true;
Misbehaving(dummyNode2.GetId(), 50);
SendMessages(&dummyNode2, *connman, interruptDummy);
BOOST_CHECK(!connman->IsBanned(addr2)); // 2 not banned yet...
BOOST_CHECK(connman->IsBanned(addr1)); // ... but 1 still should be
Misbehaving(dummyNode2.GetId(), 50);
SendMessages(&dummyNode2, *connman, interruptDummy);
BOOST_CHECK(connman->IsBanned(addr2));
}
BOOST_AUTO_TEST_CASE(DoS_banscore)
{
std::atomic<bool> interruptDummy(false);
connman->ClearBanned();
ForceSetArg("-banscore", "111"); // because 11 is my favorite number
CAddress addr1(ip(0xa0b0c001), NODE_NONE);
CNode dummyNode1(id++, NODE_NETWORK, 0, INVALID_SOCKET, addr1, 3, 1, "", true);
dummyNode1.SetSendVersion(PROTOCOL_VERSION);
GetNodeSignals().InitializeNode(&dummyNode1, *connman);
dummyNode1.nVersion = 1;
dummyNode1.fSuccessfullyConnected = true;
Misbehaving(dummyNode1.GetId(), 100);
SendMessages(&dummyNode1, *connman, interruptDummy);
BOOST_CHECK(!connman->IsBanned(addr1));
Misbehaving(dummyNode1.GetId(), 10);
SendMessages(&dummyNode1, *connman, interruptDummy);
BOOST_CHECK(!connman->IsBanned(addr1));
Misbehaving(dummyNode1.GetId(), 1);
SendMessages(&dummyNode1, *connman, interruptDummy);
BOOST_CHECK(connman->IsBanned(addr1));
ForceSetArg("-banscore", std::to_string(DEFAULT_BANSCORE_THRESHOLD));
}
BOOST_AUTO_TEST_CASE(DoS_bantime)
{
std::atomic<bool> interruptDummy(false);
connman->ClearBanned();
int64_t nStartTime = GetTime();
SetMockTime(nStartTime); // Overrides future calls to GetTime()
CAddress addr(ip(0xa0b0c001), NODE_NONE);
CNode dummyNode(id++, NODE_NETWORK, 0, INVALID_SOCKET, addr, 4, 4, "", true);
dummyNode.SetSendVersion(PROTOCOL_VERSION);
GetNodeSignals().InitializeNode(&dummyNode, *connman);
dummyNode.nVersion = 1;
dummyNode.fSuccessfullyConnected = true;
Misbehaving(dummyNode.GetId(), 100);
SendMessages(&dummyNode, *connman, interruptDummy);
BOOST_CHECK(connman->IsBanned(addr));
SetMockTime(nStartTime+60*60);
BOOST_CHECK(connman->IsBanned(addr));
SetMockTime(nStartTime+60*60*24+1);
BOOST_CHECK(!connman->IsBanned(addr));
}
CTransactionRef RandomOrphan()
{
std::map<uint256, COrphanTx>::iterator it;
it = mapOrphanTransactions.lower_bound(GetRandHash());
if (it == mapOrphanTransactions.end())
it = mapOrphanTransactions.begin();
return it->second.tx;
}
BOOST_AUTO_TEST_CASE(DoS_mapOrphans)
{
CKey key;
key.MakeNewKey(true);
CBasicKeyStore keystore;
keystore.AddKey(key);
// 50 orphan transactions:
for (int i = 0; i < 50; i++)
{
CMutableTransaction tx;
tx.vin.resize(1);
tx.vin[0].prevout.n = 0;
tx.vin[0].prevout.hash = GetRandHash();
tx.vin[0].scriptSig << OP_1;
tx.vout.resize(1);
tx.vout[0].nValue = 1*CENT;
tx.vout[0].scriptPubKey = GetScriptForDestination(key.GetPubKey().GetID());
AddOrphanTx(MakeTransactionRef(tx), i);
}
// ... and 50 that depend on other orphans:
for (int i = 0; i < 50; i++)
{
CTransactionRef txPrev = RandomOrphan();
CMutableTransaction tx;
tx.vin.resize(1);
tx.vin[0].prevout.n = 0;
tx.vin[0].prevout.hash = txPrev->GetHash();
tx.vout.resize(1);
tx.vout[0].nValue = 1*CENT;
tx.vout[0].scriptPubKey = GetScriptForDestination(key.GetPubKey().GetID());
SignSignature(keystore, *txPrev, tx, 0);
AddOrphanTx(MakeTransactionRef(tx), i);
}
// This really-big orphan should be ignored:
for (int i = 0; i < 10; i++)
{
CTransactionRef txPrev = RandomOrphan();
CMutableTransaction tx;
tx.vout.resize(1);
tx.vout[0].nValue = 1*CENT;
tx.vout[0].scriptPubKey = GetScriptForDestination(key.GetPubKey().GetID());
tx.vin.resize(2777);
for (unsigned int j = 0; j < tx.vin.size(); j++)
{
tx.vin[j].prevout.n = j;
tx.vin[j].prevout.hash = txPrev->GetHash();
}
SignSignature(keystore, *txPrev, tx, 0);
// Re-use same signature for other inputs
// (they don't have to be valid for this test)
for (unsigned int j = 1; j < tx.vin.size(); j++)
tx.vin[j].scriptSig = tx.vin[0].scriptSig;
BOOST_CHECK(!AddOrphanTx(MakeTransactionRef(tx), i));
}
// Test EraseOrphansFor:
for (NodeId i = 0; i < 3; i++)
{
size_t sizeBefore = mapOrphanTransactions.size();
EraseOrphansFor(i);
BOOST_CHECK(mapOrphanTransactions.size() < sizeBefore);
}
// Test LimitOrphanTxSize() function:
LimitOrphanTxSize(40);
BOOST_CHECK(mapOrphanTransactions.size() <= 40);
LimitOrphanTxSize(10);
BOOST_CHECK(mapOrphanTransactions.size() <= 10);
LimitOrphanTxSize(0);
BOOST_CHECK(mapOrphanTransactions.empty());
}
BOOST_AUTO_TEST_SUITE_END()
|
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2016-2021, Intel Corporation
//
// SPDX-License-Identifier: MIT
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Author(s): Filip Strugar (filip.strugar@intel.com)
//
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include "Core\vaCoreIncludes.h"
#include "vaCompressionStream.h"
#include "IntegratedExternals/vaZlibIntegration.h"
//////////////////////////////////////////////////////////////////////////////
// vaCompressionStream
//////////////////////////////////////////////////////////////////////////////
using namespace Vanilla;
using namespace Zlib;
//
namespace Vanilla
{
struct vaCompressionStreamWorkingContext
{
z_stream strm;
unsigned char workingBuffer[256*1024];
bool flushFlag; // if set during decompression then it means 'no more input data'
vaCompressionStreamWorkingContext( )
{
strm.zalloc = Z_NULL;
strm.zfree = Z_NULL;
strm.opaque = Z_NULL;
strm.avail_in = 0;
strm.next_in = Z_NULL;
flushFlag = false;
workingBuffer[0]= 0;
}
};
}
//
vaCompressionStream::vaCompressionStream( bool decompressing, shared_ptr<vaStream> inoutStream, Profile profile )
: m_decompressing( decompressing ), m_compressedStream( inoutStream ), m_compressedStreamNakedPtr(nullptr), m_compressionProfile( profile ), m_workingContext( nullptr )
{
Initialize( decompressing );
}
//
vaCompressionStream::vaCompressionStream( bool decompressing, vaStream * inoutStream, Profile profile )
: m_decompressing( decompressing ), m_compressedStream( nullptr ), m_compressedStreamNakedPtr(inoutStream), m_compressionProfile( profile ), m_workingContext( nullptr )
{
Initialize( decompressing );
}
//
void vaCompressionStream::Initialize( bool decompressing )
{
m_workingContext = new vaCompressionStreamWorkingContext( );
// just to make sure we're actually reading/writing an underlying vaCompressionStream
const uint32 c_magicHeader = 0x37EB769C;
uint32 magicHeader = 0;
// nothing else supported
assert( m_compressionProfile == vaCompressionStream::Profile::Default );
int ret;
if( decompressing )
{
bool allOk = true;
uint32 dummy0; // to expand with something
uint64 dummy1; // to expand with something else (possibly packed file size?)
allOk &= GetInnerStream( )->ReadValue<uint32>( magicHeader );
allOk &= GetInnerStream( )->ReadValue<uint32>( (uint32&)m_compressionProfile );
allOk &= GetInnerStream( )->ReadValue<uint32>( dummy0 );
allOk &= GetInnerStream( )->ReadValue<uint64>( dummy1 );
allOk &= magicHeader == c_magicHeader;
allOk &= m_compressionProfile == vaCompressionStream::Profile::Default;
if( allOk )
ret = inflateInit( &m_workingContext->strm );
else
ret = Z_DATA_ERROR;
}
else
{
bool allOk = true;
allOk &= GetInnerStream( )->WriteValue<uint32>( c_magicHeader );
allOk &= GetInnerStream( )->WriteValue<uint32>( (uint32)m_compressionProfile );
allOk &= GetInnerStream( )->WriteValue<uint32>( 0 );
allOk &= GetInnerStream( )->WriteValue<uint64>( 0 );
if( allOk )
ret = deflateInit( &m_workingContext->strm, Z_DEFAULT_COMPRESSION );
else
ret = Z_DATA_ERROR;
}
if( ret != Z_OK )
{
assert( false );
m_compressedStream = nullptr;
m_compressedStreamNakedPtr = nullptr;
return;
}
}
//
vaCompressionStream::~vaCompressionStream(void)
{
Close( );
}
//
void vaCompressionStream::Close( )
{
if( !IsOpen() )
return;
int ret = 0;
if( !m_decompressing )
{
m_workingContext->flushFlag = true;
bool allOk = Write( nullptr, 0 );
assert( allOk ); allOk;
ret = deflateEnd( &m_workingContext->strm );
}
else
{
if( m_workingContext != nullptr )
{
ret = inflateEnd( &m_workingContext->strm );
}
}
ret;
assert( ret >= 0 );
m_compressedStream = nullptr;
m_compressedStreamNakedPtr = nullptr;
if( m_workingContext != nullptr )
{
delete m_workingContext;
m_workingContext = nullptr;
}
}
//
bool vaCompressionStream::Read( void * buffer, int64 count, int64 * outCountRead )
{
if( !m_decompressing || !IsOpen() )
{
if( outCountRead != nullptr )
*outCountRead = 0;
return false;
}
assert( m_workingContext != nullptr );
if( count >= INT_MAX )
{
const int64 stepSize = 0x40000000;
int stepsToDo = (int)(( count + stepSize - 1 ) / stepSize);
for( int step = 0; step < stepsToDo; step++ )
{
void * bufferStep = ( (char *)buffer ) + stepSize * step;
int64 bufferStepCount = vaMath::Min( stepSize, count - step * stepSize );
int64 stepOutRead = 0;
bool retVal = Read( bufferStep, bufferStepCount, &stepOutRead );
if( outCountRead != nullptr )
(*outCountRead) += stepOutRead;
if( !retVal )
return false;
}
return true;
}
int64 totalRead = 0;
m_workingContext->strm.avail_out = (uint32)count;
m_workingContext->strm.next_out = (Bytef *)buffer;
do
{
// if 0 available, need to load from input stream - flushFlag serves as "input empty"
if( m_workingContext->strm.avail_in == 0 )
{
if( !m_workingContext->flushFlag )
{
int64 numRead = 0;
GetInnerStream( )->Read( m_workingContext->workingBuffer, sizeof(m_workingContext->workingBuffer), &numRead );
m_workingContext->strm.next_in = m_workingContext->workingBuffer;
m_workingContext->strm.avail_in = (uint32)numRead;
m_workingContext->flushFlag = numRead == 0; // reached end of reading
}
else
{
// no more in available but not Z_STREAM_END? bad.
assert( false );
Close( );
if( outCountRead != nullptr )
*outCountRead = totalRead;
return totalRead == count;
}
}
int availOutPrev = m_workingContext->strm.avail_out;
int ret = inflate( &m_workingContext->strm, Z_NO_FLUSH );
assert( ret != Z_STREAM_ERROR ); /* state not clobbered */
switch( ret )
{
case Z_NEED_DICT:
ret = Z_DATA_ERROR; /* and fall through */
case Z_DATA_ERROR:
case Z_MEM_ERROR:
(void)inflateEnd( &m_workingContext->strm );
assert( false );
delete m_workingContext;
m_workingContext = nullptr;
Close();
return false;
}
int numInflated = availOutPrev - m_workingContext->strm.avail_out;
totalRead += numInflated;
if( ret == Z_STREAM_END )
{
// assert( m_workingContext->flushFlag );
Close( );
if( outCountRead != nullptr )
*outCountRead = totalRead;
return totalRead == count;
}
} while( totalRead < count );
m_workingContext->strm.avail_out = 0;
m_workingContext->strm.next_out = nullptr;
if( outCountRead != nullptr )
*outCountRead = totalRead;
return totalRead == count;
}
bool vaCompressionStream::Write( const void * buffer, int64 count, int64 * outCountWritten )
{
if( m_decompressing || !IsOpen())
{
assert( false );
return false;
}
assert( m_workingContext != nullptr );
if( count >= INT_MAX )
{
const int64 stepSize = 0x40000000;
int stepsToDo = (int)( ( count + stepSize - 1 ) / stepSize );
for( int step = 0; step < stepsToDo; step++ )
{
const void * bufferStep = ((const char *)buffer) + stepSize * step;
int64 bufferStepCount = vaMath::Min( stepSize, count - step * stepSize );
int64 stepOutWritten = 0;
bool retVal = Write( bufferStep, bufferStepCount, &stepOutWritten );
if( outCountWritten != nullptr )
(*outCountWritten) += stepOutWritten;
if( !retVal )
return false;
}
return true;
}
m_workingContext->strm.avail_in = (uint32)count;
m_workingContext->strm.next_in = (z_const Bytef *)buffer;
int flush = m_workingContext->flushFlag ? Z_FINISH : Z_NO_FLUSH;
int64 totalNumDeflated = 0;
/* run deflate() on input until output buffer not full, finish
compression if all of source has been read in */
do
{
m_workingContext->strm.avail_out = sizeof( m_workingContext->workingBuffer );
m_workingContext->strm.next_out = m_workingContext->workingBuffer;
int ret = deflate( &m_workingContext->strm, flush );
// negative values are errors
if( ret < 0 )
{
assert( false );
Close();
return false;
}
int numDeflated = sizeof(m_workingContext->workingBuffer) - m_workingContext->strm.avail_out;
totalNumDeflated += numDeflated;
bool allOk = GetInnerStream( )->Write( m_workingContext->workingBuffer, numDeflated );
assert( allOk ); allOk;
} while( m_workingContext->strm.avail_out == 0 );
m_workingContext->strm.avail_in = 0;
m_workingContext->strm.next_in = nullptr;
// all input should have been used
assert( m_workingContext->strm.avail_in == 0 );
if( outCountWritten != nullptr )
*outCountWritten = count;
return true;
}
//
// USED FOR TESTING
/*
auto memStream = vaFileTools::LoadMemoryStream( "C:\\Work\\INTC_SHARE\\bistro_compressed_vs_uncompressed_textures.pdn" );// "C:\\Work\\INTC_SHARE\\CMAA2\\Projects\\CMAA2\\Media\\AssetPacks\\Bistro_Research_Interior_AssetPack.apack" );
#if 0
shared_ptr<vaFileStream> fileOut = std::make_shared<vaFileStream>();
fileOut->Open( "C:\\Work\\INTC_SHARE\\CMAA2\\Projects\\CMAA2\\Media\\AssetPacks\\aaa.aaa", FileCreationMode::Create );
vaCompressionStream compressor( false, fileOut );
compressor.Write( memStream->GetBuffer(), memStream->GetLength() );
compressor.Close();
#else
{
auto memStreamComp = vaFileTools::LoadMemoryStream( "C:\\Work\\INTC_SHARE\\CMAA2\\Projects\\CMAA2\\Media\\AssetPacks\\aaa.aaa" );
//shared_ptr<vaMemoryStream> memStreamOut = std::make_shared<vaMemoryStream>( (int64)0, 1024*1024 );
shared_ptr<vaFileStream> fileOut = std::make_shared<vaFileStream>( );
fileOut->Open( "C:\\Work\\INTC_SHARE\\bistro_compressed_vs_uncompressed_textures_1.pdn", FileCreationMode::Create );
vaCompressionStream compressor( true, memStreamComp );
char buffer[768 * 1024];
int64 numberRead = 0;
do
{
compressor.Read( buffer, sizeof(buffer), &numberRead );
if( numberRead > 0 )
fileOut->Write( buffer, numberRead );
//memStreamOut->Write( buffer, numberRead );
} while( numberRead > 0 );
//assert( memStream->GetLength() == memStreamOut->GetLength() );
//assert( memcmp( memStream->GetBuffer(), memStreamOut->GetBuffer(), memStream->GetLength() ) == 0 );
}
#endif
*/
///////////////////////////////////////////////////////////////////////////////////////////////////
|
/* Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of NVIDIA CORPORATION nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
///////////////////////////////////////////////////////////////////////////////
// Monte Carlo: Single Asian Option
// ================================
//
// This sample demonstrates pricing a single European-exercise average-price
// Asian option (arithmetic discrete average).
//
// This file, main.cpp, contains the setup information to run the test, for
// example parsing the command line and integrating this sample with the
// samples framework. As such it is perhaps less interesting than the guts of
// the sample. Readers wishing to skip the clutter are advised to skip straight
// to Test.operator() in test.cpp.
///////////////////////////////////////////////////////////////////////////////
#include <iostream>
#include <iomanip>
#include <stdexcept>
#include <cuda_runtime.h>
#include <helper_timer.h>
#include <helper_cuda.h>
#include "../inc/test.h"
// Forward declarations
void showHelp(const int argc, const char **argv);
template <typename Real>
void runTest(int argc, const char **argv);
int main(int argc, char **argv) {
using std::invalid_argument;
using std::string;
// Open the log file
printf("Monte Carlo Single Asian Option (with PRNG)\n");
printf("===========================================\n\n");
// If help flag is set, display help and exit immediately
if (checkCmdLineFlag(argc, (const char **)argv, "help")) {
printf("Displaying help on console\n");
showHelp(argc, (const char **)argv);
exit(EXIT_SUCCESS);
}
// Check the precision (checked against the device capability later)
try {
char *value;
if (getCmdLineArgumentString(argc, (const char **)argv, "precision",
&value)) {
// Check requested precision is valid
string prec(value);
if (prec.compare("single") == 0 || prec.compare("\"single\"") == 0) {
runTest<float>(argc, (const char **)argv);
} else if (prec.compare("double") == 0 ||
prec.compare("\"double\"") == 0) {
runTest<double>(argc, (const char **)argv);
} else {
printf(
"specified precision (%s) is invalid, must be \"single\" or "
"\"double\".\n",
value);
throw invalid_argument("precision");
}
} else {
runTest<float>(argc, (const char **)argv);
}
} catch (invalid_argument &e) {
printf("invalid command line argument (%s)\n", e.what());
exit(EXIT_FAILURE);
}
// Finish
exit(EXIT_SUCCESS);
}
template <typename Real>
void runTest(int argc, const char **argv) {
using std::invalid_argument;
using std::runtime_error;
try {
Test<Real> test;
int deviceCount = 0;
cudaError_t cudaResult = cudaSuccess;
// by default specify GPU Device == 0
test.device = 0;
// Get number of available devices
cudaResult = cudaGetDeviceCount(&deviceCount);
if (cudaResult != cudaSuccess) {
printf("could not get device count.\n");
throw runtime_error("cudaGetDeviceCount");
}
// (default parameters)
test.numSims = k_sims_qa;
test.threadBlockSize = k_bsize_qa;
test.seed = k_seed_qa;
{
char *value = 0;
if (getCmdLineArgumentString(argc, argv, "device", &value)) {
test.device = (int)atoi(value);
if (test.device >= deviceCount) {
printf(
"invalid target device specified on command line (device %d does "
"not exist).\n",
test.device);
throw invalid_argument("device");
}
} else {
test.device = gpuGetMaxGflopsDeviceId();
}
if (getCmdLineArgumentString(argc, argv, "sims", &value)) {
test.numSims = (unsigned int)atoi(value);
if (test.numSims < k_sims_min || test.numSims > k_sims_max) {
printf(
"specified number of simulations (%d) is invalid, must be "
"between %d and %d.\n",
test.numSims, k_sims_min, k_sims_max);
throw invalid_argument("sims");
}
} else {
test.numSims = k_sims_def;
}
if (getCmdLineArgumentString(argc, argv, "block-size", &value)) {
// Determine max threads per block
cudaDeviceProp deviceProperties;
cudaResult = cudaGetDeviceProperties(&deviceProperties, test.device);
if (cudaResult != cudaSuccess) {
printf("cound not get device properties for device %d.\n",
test.device);
throw runtime_error("cudaGetDeviceProperties");
}
// Check requested size is valid
test.threadBlockSize = (unsigned int)atoi(value);
if (test.threadBlockSize < k_bsize_min ||
test.threadBlockSize > static_cast<unsigned int>(
deviceProperties.maxThreadsPerBlock)) {
printf(
"specified block size (%d) is invalid, must be between %d and %d "
"for device %d.\n",
test.threadBlockSize, k_bsize_min,
deviceProperties.maxThreadsPerBlock, test.device);
throw invalid_argument("block-size");
}
if (test.threadBlockSize & test.threadBlockSize - 1) {
printf(
"specified block size (%d) is invalid, must be a power of two "
"(see reduction function).\n",
test.threadBlockSize);
throw invalid_argument("block-size");
}
} else {
test.threadBlockSize = k_bsize_def;
}
if (getCmdLineArgumentString(argc, argv, "seed", &value)) {
// Check requested seed is valid
test.seed = (unsigned int)atoi(value);
if (test.seed == 0) {
printf("specified seed (%d) is invalid, must be non-zero.\n",
test.seed);
throw invalid_argument("seed");
}
} else {
test.seed = k_seed_def;
}
}
// Execute
test();
} catch (invalid_argument &e) {
printf("invalid command line argument (%s)\n", e.what());
exit(EXIT_FAILURE);
} catch (runtime_error &e) {
printf("runtime error (%s)\n", e.what());
exit(EXIT_FAILURE);
}
}
void showHelp(int argc, const char **argv) {
using std::cout;
using std::endl;
using std::left;
using std::setw;
if (argc > 0) {
cout << endl << argv[0] << endl;
}
cout << endl << "Syntax:" << endl;
cout << left;
cout << " " << setw(20) << "--device=<device>"
<< "Specify device to use for execution" << endl;
cout << " " << setw(20) << "--sims=<N>"
<< "Specify number of Monte Carlo simulations" << endl;
cout << " " << setw(20) << "--block-size=<N>"
<< "Specify number of threads per block" << endl;
cout << " " << setw(20) << "--seed=<N>"
<< "Specify the seed to use for the random number generator" << endl;
cout << " " << setw(20) << "--precision=<P>"
<< "Specify the precision (\"single\" or \"double\")" << endl;
cout << endl;
cout << " " << setw(20) << "--noprompt"
<< "Skip prompt before exit" << endl;
cout << endl;
}
|
//
// Author: Jon Trulson <jon@radscan.com>
// Copyright (c) 1994-2018 Jon Trulson
//
// The MIT License
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use, copy,
// modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
// BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
#include "c_defs.h"
#define NOEXTERN_CB
#include "cb.h" /* common block vars defined here */
#include "global.h"
#include "conqdef.h"
#include "conqlb.h"
#include "conqutil.h"
#include "conqunix.h"
#if !defined(MINGW)
# include <sys/mman.h>
#endif
#include "context.h" /* some extra stuff */
#include "user.h"
#include "sem.h"
static char *_cbBasePtr = NULL; /* common block base ptr, the Universe. */
static unsigned int _cbOffset = 0; /* offset into common block */
static unsigned int _cbSavedSize = 0; /* for msync() and friends */
static bool fakeCommon = false; /* for the clients */
/* Some architectures do not like unaligned accesses (like sparc) so
* we need to ensure proper alignment of the structures contained
* within the common block. We will use 16-byte alignment, which
* should work for everybody.
*/
#define CB_ALIGNMENT (16)
#define CB_ALIGN(_off, _align) ( ((_off) + (_align)) & ~((_align) - 1) )
// This macro maps a global variable into the memory region starting
// at _cbBasePtr. The memory region is either a heap-allocated chunk
// of memory (in the case of the clients), or a memory mapped file
// (via mmap()) used for persistent storage (on the server only). This
// emulation of a Fortran "Common Block" is used to hold the state of
// the Universe. Be careful with it.
#define MAP_VARIABLE(thevarp, thetype, size, doAssign) { \
if (doAssign) { thevarp = (thetype *) (_cbBasePtr + _cbOffset); } \
_cbOffset += (sizeof(thetype) * (size)); \
_cbOffset = CB_ALIGN(_cbOffset, CB_ALIGNMENT); \
}
// Static functions...
static int _checkCB(char *fname, int fmode, int sizeofcb);
/* my malloc wrapper. used only when mapping or initializing a
commonblock */
static void *_mymalloc(size_t size)
{
void *ptr;
if ((ptr = malloc(size)) == NULL)
{
perror("_mymalloc()");
exit(1);
}
return(ptr);
}
/* maps the actual vars into the common block, if doAssign is set.
* Otherwise, this can be used to determine how many bytes are
* required for the CB by only modifying the offset during mapping */
static void _mapCBVariables(bool doAssign)
{
_cbOffset = 0;
// This must be the first var
MAP_VARIABLE(cbRevision, unsigned int, 1, doAssign);
MAP_VARIABLE(cbConqInfo, cbConqInfo_t, 1, doAssign);
MAP_VARIABLE(cbUsers, User_t, cbLimits.maxUsers(), doAssign);
MAP_VARIABLE(cbRobot, Robot_t, 1, doAssign);
MAP_VARIABLE(cbPlanets, Planet_t, cbLimits.maxPlanets(), doAssign);
MAP_VARIABLE(cbTeams, Team_t, NUM_ALLTEAMS, doAssign);
MAP_VARIABLE(cbDoomsday, Doomsday_t, 1, doAssign);
MAP_VARIABLE(cbHistory, History_t, cbLimits.maxHist(), doAssign);
MAP_VARIABLE(cbDriver, Driver_t, 1, doAssign);
MAP_VARIABLE(cbShips, Ship_t, cbLimits.maxShips(), doAssign);
MAP_VARIABLE(cbShipTypes, ShipType_t, MAXNUMSHIPTYPES, doAssign);
MAP_VARIABLE(cbMsgs, Msg_t, cbLimits.maxMsgs(), doAssign);
// if we did actual assignments, save the offset
if (doAssign)
_cbSavedSize = _cbOffset;
return;
}
static void _unmapCBVariables()
{
// this simply sets all the CB variables to NULL. It should only
// be called by cbUnmap() and cbUnmapLocal()
// This must be the first var
cbRevision = NULL;
cbConqInfo = NULL;
cbUsers = NULL;
cbRobot = NULL;
cbPlanets = NULL;
cbTeams = NULL;
cbDoomsday = NULL;
cbHistory = NULL;
cbDriver = NULL;
cbShips = NULL;
cbShipTypes = NULL;
cbMsgs = NULL;
return;
}
static void _initFakeCB(void)
{
fakeCommon = true;
/* this will exit if it fails */
if (!_cbBasePtr)
_cbBasePtr = (char *)_mymalloc(cbGetSize());
_mapCBVariables(true);
cbZero();
return;
}
/* we'll use a hack to translate the lock[mesg|word] pointers into
a semaphore selector */
void cbLock(int *lockptr)
{
int semnum;
if (lockptr == &cbConqInfo->lockmesg)
semnum = LOCKMSG;
else
semnum = LOCKCMN;
semLock(semnum);
(*lockptr)++;
return;
}
void cbUnlock(int *lockptr)
{
int semnum;
if (lockptr == &cbConqInfo->lockmesg)
semnum = LOCKMSG;
else
semnum = LOCKCMN;
semUnlock(semnum);
return;
}
/* cbFlush() - flush a common block */
void cbFlush(void)
{
if (fakeCommon)
return;
#if !defined(MINGW)
/* fbsd doesn't like MS_SYNC */
/* which is prefered, but oh well */
# if defined(FREEBSD)
if (msync((caddr_t)_cbBasePtr, _cbSavedSize, 0) == -1)
# else
if (msync((caddr_t)_cbBasePtr, _cbSavedSize, MS_SYNC) == -1)
# endif
utLog("cbFlush(): msync(): %s", strerror(errno));
#endif
return;
}
/* _checkCB() - open/verify a common block - init if necc, return true
if successful */
static int _checkCB(char *fname, int fmode, int sizeofcb)
{
int ffd = -1;
struct stat sbuf;
/* first stat the file, if it exists then verify the size. rename
it if a size mismatch */
if (stat(fname, &sbuf) != -1) /* ok if this fails */
{
// file exists - verify size
if (sbuf.st_size != sizeofcb)
{
// we have a problem - we cannot use this CB. So, try to
// rename it to something else so we can create a fresh
// new one. By renaming the old one, we don't risk
// throwing away an important CB due to someone fiddling
// with the limits in cbGlobal.
// we create a new file tagged with the unix time
char newfile[PATH_MAX] = {};
snprintf(newfile, PATH_MAX, "%s/%s-%lu",
CONQSTATE, C_CONQ_COMMONBLK,
time(0));
utLog("%s: %s: ERROR: File size mismatch (expected %d, was %ld), "
"renaming to %s.",
__FUNCTION__,
fname,
sizeofcb,
(long int)sbuf.st_size,
newfile);
if (rename(fname, newfile) == -1)
{
utLog("%s: rename(%s, %s) failed: %s\n",
__FUNCTION__,
fname,
newfile,
strerror(errno));
return(false);
}
}
}
/* ok, either the file exists with the right
size, or it doesn't exist at all -
now open (and create) if necc */
umask(0); /* clear umask, just in case... */
if ((ffd = open(fname, O_RDONLY)) == -1)
{ /* Error or not there... */
if (errno == ENOENT) /* Not There */
{ /* create it */
if ((ffd = creat(fname, fmode)) == -1)
{
utLog("_checkCB(): creat(%s) failed: %s\n",
fname,
strerror(errno));
return(false);
}
else
{ /* Create it */
utLog("%s: Initializing new common block: %s\n",
__FUNCTION__, fname);
// this exits if malloc fails
void *memptr = _mymalloc(sizeofcb);
memset(memptr, 0, sizeofcb);
if (write(ffd, memptr, sizeofcb) <= 0)
{
utLog("_checkCB(): write() failed: %s\n",
strerror(errno));
close(ffd);
ffd = -1;
free(memptr);
memptr = NULL;
return false;
}
close(ffd);
ffd = -1;
free(_cbBasePtr);
_cbBasePtr = NULL;
free(memptr);
}
}
else
{ /* some other error */
utLog("_checkCB(): open(%s, O_RDONLY) failed: %s\n",
fname,
strerror(errno));
return(false);
}
}
if (ffd >= 0)
close(ffd); /* everything ok.. */
#if !defined(MINGW)
/* set ownership */
if (chown(fname, 0, -1) == -1)
{
// don't whine on EPERM. Many systems don't allow
// ordinary users to chown anymore
if (errno != EPERM)
utLog("_checkCB(): chown() failed: %s\n",
strerror(errno));
}
#endif
return(true); /* everything there, and right size */
}
void cbMap(void)
{
#if !defined(MINGW)
int cmn_fd;
static char cmnfile[PATH_MAX] = {};
#endif
if (fakeCommon)
return;
utLog("%s: Mapping the common block", __FUNCTION__);
#if defined(MINGW)
fprintf(stderr,
"%s: Only fake (client) common blocks are supported under MINGW\n",
__FUNCTION__);
exit(1);
#else /* MINGW */
utLog("%s: CB size: %u bytes", __FUNCTION__,
cbGetSize());
snprintf(cmnfile, PATH_MAX, "%s/%s/%s", CONQSTATE,
gameSubdirectory.get().c_str(),
C_CONQ_COMMONBLK);
/* verify it's validity */
if (_checkCB(cmnfile, CMN_MODE, cbGetSize()) == false)
exit(1); /* an unrecoverable error */
/* reopen it... */
if ((cmn_fd = open(cmnfile, O_RDWR)) == -1)
{
utLog("cbMap(): open(O_RDWR) failed: %s", strerror(errno));
exit(1);
}
/* Now lets map it */
# ifndef MAP_FILE
# define MAP_FILE 0 /* some arch's don't def this */
# endif
if ((_cbBasePtr = (char *)mmap(NULL, (size_t) cbGetSize(),
PROT_READ | PROT_WRITE, MAP_SHARED | MAP_FILE,
cmn_fd, 0)) == MAP_FAILED)
{
close(cmn_fd);
utLog("cbMap(): mmap() failed: %s", strerror(errno));
exit(1);
}
#endif /* MINGW */
/* now map the variables into the
common block */
_mapCBVariables(true);
// go ahead and close the fd, we don't need it anymore.
close(cmn_fd);
return;
}
void cbZero(void)
{ /* zero the common block, called from
init everything */
memset(_cbBasePtr, 0, cbGetSize());
upchuck(); /* flush the commonblock */
return;
}
/* short cut */
void cbMapLocal(void)
{
/* a parallel universe, it is */
utLog("%s: CB size needed: %u bytes", __FUNCTION__,
cbGetSize());
utLog("%s: Mapping the common block", __FUNCTION__);
_initFakeCB();
clbInitEverything(true);
clbInitMsgs();
*cbRevision = COMMONSTAMP;
cbDriver->drivstat = DRS_OFF;
cbDriver->drivpid = 0;
cbDriver->drivowner[0] = 0;
return;
}
unsigned int cbGetSize()
{
// Do a pretend map of the variables (at their current sizes) and
// return the offset (_cbOffset). Note, this number includes
// any trailing alignment up to 16 bytes.
_mapCBVariables(false);
return (_cbOffset);
}
void cbUnmap()
{
if (!_cbBasePtr)
return;
if (fakeCommon) // only for real file-backed mmapped common blocks
return;
utLog("%s: Unmapping the common block", __FUNCTION__);
// reset all variables and unmap the common block
_unmapCBVariables();
// not much we can do if this fails...
munmap((void *)_cbBasePtr, _cbSavedSize);
_cbBasePtr = NULL;
_cbOffset = 0;
_cbSavedSize = 0;
}
void cbUnmapLocal()
{
if (!_cbBasePtr)
return;
if (!fakeCommon) // only for heap allocated "fake" common blocks
return;
utLog("%s: Freeing the common block", __FUNCTION__);
// reset all variables, free the "fake" common block
_unmapCBVariables();
// not much we can do if this fails...
free((void *)_cbBasePtr);
_cbBasePtr = NULL;
_cbOffset = 0;
_cbSavedSize = 0;
}
bool cbIsMapped()
{
return ( (_cbBasePtr) ? true : false );
}
|
// Timer for the HPCSE I course
//
#ifndef HPCSE15_TIMER_HPP
#define HPCSE15_TIMER_HPP
#include <sys/time.h>
class timer {
public:
timer() {
start_time.tv_sec = 0;
start_time.tv_usec = 0;
stop_time.tv_sec = 0;
stop_time.tv_usec = 0;
}
inline void start() {
gettimeofday(&start_time, NULL);
}
inline void stop() {
gettimeofday(&stop_time, NULL);
}
double get_timing() const {
return (stop_time.tv_sec - start_time.tv_sec) + (stop_time.tv_usec - start_time.tv_usec)*1e-6;
}
private:
struct timeval start_time, stop_time;
};
#endif //HPCSE15_TIMER_HPP
|
//
//
//
#include "MotorCtrl.h"
#include "ValueFunDefine.h"
int MotorCtrl::MotorCw(void)
{
MotorStop();
delay(3);
digitalWrite(RelayPin0, LOW);
digitalWrite(RelayPin1, HIGH);
return 1;
}
int MotorCtrl::MotorCcw(void)
{
MotorStop();
delay(3);
digitalWrite(RelayPin0, HIGH);
digitalWrite(RelayPin1, LOW);
return -1;
}
int MotorCtrl::MotorStop(void)
{
digitalWrite(RelayPin0, HIGH);
digitalWrite(RelayPin1, HIGH);
return 0;
}
int MotorCtrl::MotorStateCtrl(int state)
{
if (state == 0)
{
MotorStop();
}
if (state == 1)
{
MotorCw();
}
if (state == -1)
{
MotorCcw();
}
return state;
}
|
// stdafx.cpp : source file that includes just the standard includes
// KG_Goddess.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "Precompile.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
|
// Copyright 2018 The gVisor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "test/syscalls/linux/socket_generic.h"
#include <stdio.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/un.h>
#include "gtest/gtest.h"
#include "absl/strings/str_format.h"
#include "absl/strings/string_view.h"
#include "test/syscalls/linux/socket_test_util.h"
#include "test/syscalls/linux/unix_domain_socket_test_util.h"
#include "test/util/test_util.h"
// This file is a generic socket test file. It must be built with another file
// that provides the test types.
namespace gvisor {
namespace testing {
TEST_P(AllSocketPairTest, BasicReadWrite) {
auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());
char buf[20];
const std::string data = "abc";
ASSERT_THAT(WriteFd(sockets->first_fd(), data.c_str(), 3),
SyscallSucceedsWithValue(3));
ASSERT_THAT(ReadFd(sockets->second_fd(), buf, 3),
SyscallSucceedsWithValue(3));
EXPECT_EQ(data, absl::string_view(buf, 3));
}
TEST_P(AllSocketPairTest, BasicReadWriteBadBuffer) {
auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());
const std::string data = "abc";
ASSERT_THAT(WriteFd(sockets->first_fd(), data.c_str(), 3),
SyscallSucceedsWithValue(3));
ASSERT_THAT(ReadFd(sockets->second_fd(), nullptr, 3),
SyscallFailsWithErrno(EFAULT));
}
TEST_P(AllSocketPairTest, BasicSendRecv) {
auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());
char sent_data[512];
RandomizeBuffer(sent_data, sizeof(sent_data));
ASSERT_THAT(
RetryEINTR(send)(sockets->first_fd(), sent_data, sizeof(sent_data), 0),
SyscallSucceedsWithValue(sizeof(sent_data)));
char received_data[sizeof(sent_data)];
ASSERT_THAT(RetryEINTR(recv)(sockets->second_fd(), received_data,
sizeof(received_data), 0),
SyscallSucceedsWithValue(sizeof(received_data)));
EXPECT_EQ(0, memcmp(sent_data, received_data, sizeof(sent_data)));
}
TEST_P(AllSocketPairTest, BasicSendmmsg) {
auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());
char sent_data[200];
RandomizeBuffer(sent_data, sizeof(sent_data));
std::vector<struct mmsghdr> msgs(10);
std::vector<struct iovec> iovs(msgs.size());
const int chunk_size = sizeof(sent_data) / msgs.size();
for (size_t i = 0; i < msgs.size(); i++) {
iovs[i].iov_len = chunk_size;
iovs[i].iov_base = &sent_data[i * chunk_size];
msgs[i].msg_hdr.msg_iov = &iovs[i];
msgs[i].msg_hdr.msg_iovlen = 1;
}
ASSERT_THAT(
RetryEINTR(sendmmsg)(sockets->first_fd(), &msgs[0], msgs.size(), 0),
SyscallSucceedsWithValue(msgs.size()));
for (const struct mmsghdr& msg : msgs) {
EXPECT_EQ(chunk_size, msg.msg_len);
}
char received_data[sizeof(sent_data)];
for (size_t i = 0; i < msgs.size(); i++) {
ASSERT_THAT(ReadFd(sockets->second_fd(), &received_data[i * chunk_size],
chunk_size),
SyscallSucceedsWithValue(chunk_size));
}
EXPECT_EQ(0, memcmp(sent_data, received_data, sizeof(sent_data)));
}
TEST_P(AllSocketPairTest, BasicRecvmmsg) {
auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());
char sent_data[200];
RandomizeBuffer(sent_data, sizeof(sent_data));
char received_data[sizeof(sent_data)];
std::vector<struct mmsghdr> msgs(10);
std::vector<struct iovec> iovs(msgs.size());
const int chunk_size = sizeof(sent_data) / msgs.size();
for (size_t i = 0; i < msgs.size(); i++) {
iovs[i].iov_len = chunk_size;
iovs[i].iov_base = &received_data[i * chunk_size];
msgs[i].msg_hdr.msg_iov = &iovs[i];
msgs[i].msg_hdr.msg_iovlen = 1;
}
for (size_t i = 0; i < msgs.size(); i++) {
ASSERT_THAT(
WriteFd(sockets->first_fd(), &sent_data[i * chunk_size], chunk_size),
SyscallSucceedsWithValue(chunk_size));
}
ASSERT_THAT(RetryEINTR(recvmmsg)(sockets->second_fd(), &msgs[0], msgs.size(),
0, nullptr),
SyscallSucceedsWithValue(msgs.size()));
EXPECT_EQ(0, memcmp(sent_data, received_data, sizeof(sent_data)));
for (const struct mmsghdr& msg : msgs) {
EXPECT_EQ(chunk_size, msg.msg_len);
}
}
TEST_P(AllSocketPairTest, SendmsgRecvmsg10KB) {
auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());
std::vector<char> sent_data(10 * 1024);
RandomizeBuffer(sent_data.data(), sent_data.size());
ASSERT_NO_FATAL_FAILURE(
SendNullCmsg(sockets->first_fd(), sent_data.data(), sent_data.size()));
std::vector<char> received_data(sent_data.size());
ASSERT_NO_FATAL_FAILURE(RecvNoCmsg(sockets->second_fd(), received_data.data(),
received_data.size()));
EXPECT_EQ(0,
memcmp(sent_data.data(), received_data.data(), sent_data.size()));
}
// This test validates that a sendmsg/recvmsg w/ MSG_CTRUNC is a no-op on
// input flags.
TEST_P(AllSocketPairTest, SendmsgRecvmsgMsgCtruncNoop) {
auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());
std::vector<char> sent_data(10 * 1024);
RandomizeBuffer(sent_data.data(), sent_data.size());
ASSERT_NO_FATAL_FAILURE(
SendNullCmsg(sockets->first_fd(), sent_data.data(), sent_data.size()));
std::vector<char> received_data(sent_data.size());
struct msghdr msg = {};
char control[CMSG_SPACE(sizeof(int)) + CMSG_SPACE(sizeof(struct ucred))];
msg.msg_control = control;
msg.msg_controllen = sizeof(control);
struct iovec iov;
iov.iov_base = &received_data[0];
iov.iov_len = received_data.size();
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
// MSG_CTRUNC should be a no-op.
ASSERT_THAT(RetryEINTR(recvmsg)(sockets->second_fd(), &msg, MSG_CTRUNC),
SyscallSucceedsWithValue(received_data.size()));
struct cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);
EXPECT_EQ(cmsg, nullptr);
EXPECT_EQ(msg.msg_controllen, 0);
EXPECT_EQ(0,
memcmp(sent_data.data(), received_data.data(), sent_data.size()));
}
TEST_P(AllSocketPairTest, SendmsgRecvmsg16KB) {
auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());
std::vector<char> sent_data(16 * 1024);
RandomizeBuffer(sent_data.data(), sent_data.size());
ASSERT_NO_FATAL_FAILURE(
SendNullCmsg(sockets->first_fd(), sent_data.data(), sent_data.size()));
std::vector<char> received_data(sent_data.size());
ASSERT_NO_FATAL_FAILURE(RecvNoCmsg(sockets->second_fd(), received_data.data(),
received_data.size()));
EXPECT_EQ(0,
memcmp(sent_data.data(), received_data.data(), sent_data.size()));
}
TEST_P(AllSocketPairTest, RecvmsgMsghdrFlagsNotClearedOnFailure) {
auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());
char received_data[10] = {};
struct iovec iov;
iov.iov_base = received_data;
iov.iov_len = sizeof(received_data);
struct msghdr msg = {};
msg.msg_flags = -1;
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
ASSERT_THAT(RetryEINTR(recvmsg)(sockets->second_fd(), &msg, MSG_DONTWAIT),
SyscallFailsWithErrno(EAGAIN));
// Check that msghdr flags were not changed.
EXPECT_EQ(msg.msg_flags, -1);
}
TEST_P(AllSocketPairTest, RecvmsgMsghdrFlagsCleared) {
auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());
char sent_data[10];
RandomizeBuffer(sent_data, sizeof(sent_data));
ASSERT_THAT(
RetryEINTR(send)(sockets->first_fd(), sent_data, sizeof(sent_data), 0),
SyscallSucceedsWithValue(sizeof(sent_data)));
char received_data[sizeof(sent_data)] = {};
struct iovec iov;
iov.iov_base = received_data;
iov.iov_len = sizeof(received_data);
struct msghdr msg = {};
msg.msg_flags = -1;
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
ASSERT_THAT(RetryEINTR(recvmsg)(sockets->second_fd(), &msg, 0),
SyscallSucceedsWithValue(sizeof(sent_data)));
EXPECT_EQ(0, memcmp(received_data, sent_data, sizeof(sent_data)));
// Check that msghdr flags were cleared.
EXPECT_EQ(msg.msg_flags, 0);
}
TEST_P(AllSocketPairTest, RecvmsgPeekMsghdrFlagsCleared) {
auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());
char sent_data[10];
RandomizeBuffer(sent_data, sizeof(sent_data));
ASSERT_THAT(
RetryEINTR(send)(sockets->first_fd(), sent_data, sizeof(sent_data), 0),
SyscallSucceedsWithValue(sizeof(sent_data)));
char received_data[sizeof(sent_data)] = {};
struct iovec iov;
iov.iov_base = received_data;
iov.iov_len = sizeof(received_data);
struct msghdr msg = {};
msg.msg_flags = -1;
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
ASSERT_THAT(RetryEINTR(recvmsg)(sockets->second_fd(), &msg, MSG_PEEK),
SyscallSucceedsWithValue(sizeof(sent_data)));
EXPECT_EQ(0, memcmp(received_data, sent_data, sizeof(sent_data)));
// Check that msghdr flags were cleared.
EXPECT_EQ(msg.msg_flags, 0);
}
TEST_P(AllSocketPairTest, RecvmsgIovNotUpdated) {
auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());
char sent_data[10];
RandomizeBuffer(sent_data, sizeof(sent_data));
ASSERT_THAT(
RetryEINTR(send)(sockets->first_fd(), sent_data, sizeof(sent_data), 0),
SyscallSucceedsWithValue(sizeof(sent_data)));
char received_data[sizeof(sent_data) * 2] = {};
struct iovec iov;
iov.iov_base = received_data;
iov.iov_len = sizeof(received_data);
struct msghdr msg = {};
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
ASSERT_THAT(RetryEINTR(recvmsg)(sockets->second_fd(), &msg, 0),
SyscallSucceedsWithValue(sizeof(sent_data)));
EXPECT_EQ(0, memcmp(received_data, sent_data, sizeof(sent_data)));
// Check that the iovec length was not updated.
EXPECT_EQ(msg.msg_iov->iov_len, sizeof(received_data));
}
TEST_P(AllSocketPairTest, RecvmmsgInvalidTimeout) {
auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());
char buf[10];
struct mmsghdr msg = {};
struct iovec iov = {};
iov.iov_len = sizeof(buf);
iov.iov_base = buf;
msg.msg_hdr.msg_iov = &iov;
msg.msg_hdr.msg_iovlen = 1;
struct timespec timeout = {-1, -1};
ASSERT_THAT(RetryEINTR(recvmmsg)(sockets->first_fd(), &msg, 1, 0, &timeout),
SyscallFailsWithErrno(EINVAL));
}
TEST_P(AllSocketPairTest, RecvmmsgTimeoutBeforeRecv) {
// There is a known bug in the Linux recvmmsg(2) causing it to block forever
// if the timeout expires while blocking for the first message.
SKIP_IF(!IsRunningOnGvisor());
auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());
char buf[10];
struct mmsghdr msg = {};
struct iovec iov = {};
iov.iov_len = sizeof(buf);
iov.iov_base = buf;
msg.msg_hdr.msg_iov = &iov;
msg.msg_hdr.msg_iovlen = 1;
struct timespec timeout = {};
ASSERT_THAT(RetryEINTR(recvmmsg)(sockets->first_fd(), &msg, 1, 0, &timeout),
SyscallFailsWithErrno(EAGAIN));
}
TEST_P(AllSocketPairTest, MsgPeek) {
auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());
char sent_data[50];
memset(&sent_data, 0, sizeof(sent_data));
ASSERT_THAT(WriteFd(sockets->first_fd(), sent_data, sizeof(sent_data)),
SyscallSucceedsWithValue(sizeof(sent_data)));
char received_data[sizeof(sent_data)];
for (int i = 0; i < 3; i++) {
memset(received_data, 0, sizeof(received_data));
EXPECT_THAT(RetryEINTR(recv)(sockets->second_fd(), received_data,
sizeof(received_data), MSG_PEEK),
SyscallSucceedsWithValue(sizeof(received_data)));
EXPECT_EQ(0, memcmp(sent_data, received_data, sizeof(received_data)));
}
ASSERT_THAT(RetryEINTR(recv)(sockets->second_fd(), received_data,
sizeof(received_data), 0),
SyscallSucceedsWithValue(sizeof(received_data)));
EXPECT_EQ(0, memcmp(sent_data, received_data, sizeof(received_data)));
}
TEST_P(AllSocketPairTest, LingerSocketOption) {
auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());
struct linger got_linger = {-1, -1};
socklen_t length = sizeof(struct linger);
EXPECT_THAT(getsockopt(sockets->first_fd(), SOL_SOCKET, SO_LINGER,
&got_linger, &length),
SyscallSucceedsWithValue(0));
struct linger want_linger = {};
EXPECT_EQ(0, memcmp(&want_linger, &got_linger, sizeof(struct linger)));
EXPECT_EQ(sizeof(struct linger), length);
}
TEST_P(AllSocketPairTest, KeepAliveSocketOption) {
auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());
int keepalive = -1;
socklen_t length = sizeof(int);
EXPECT_THAT(getsockopt(sockets->first_fd(), SOL_SOCKET, SO_KEEPALIVE,
&keepalive, &length),
SyscallSucceedsWithValue(0));
EXPECT_EQ(0, keepalive);
EXPECT_EQ(sizeof(int), length);
}
TEST_P(AllSocketPairTest, RcvBufSucceeds) {
auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());
int size = 0;
socklen_t size_size = sizeof(size);
EXPECT_THAT(
getsockopt(sockets->first_fd(), SOL_SOCKET, SO_RCVBUF, &size, &size_size),
SyscallSucceeds());
EXPECT_GT(size, 0);
}
TEST_P(AllSocketPairTest, GetSndBufSucceeds) {
auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());
int size = 0;
socklen_t size_size = sizeof(size);
EXPECT_THAT(
getsockopt(sockets->first_fd(), SOL_SOCKET, SO_SNDBUF, &size, &size_size),
SyscallSucceeds());
EXPECT_GT(size, 0);
}
TEST_P(AllSocketPairTest, RecvTimeoutReadSucceeds) {
auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());
struct timeval tv {
.tv_sec = 0, .tv_usec = 10
};
EXPECT_THAT(
setsockopt(sockets->first_fd(), SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)),
SyscallSucceeds());
char buf[20] = {};
EXPECT_THAT(RetryEINTR(read)(sockets->first_fd(), buf, sizeof(buf)),
SyscallFailsWithErrno(EAGAIN));
}
TEST_P(AllSocketPairTest, RecvTimeoutRecvSucceeds) {
auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());
struct timeval tv {
.tv_sec = 0, .tv_usec = 10
};
EXPECT_THAT(
setsockopt(sockets->first_fd(), SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)),
SyscallSucceeds());
char buf[20] = {};
EXPECT_THAT(RetryEINTR(recv)(sockets->first_fd(), buf, sizeof(buf), 0),
SyscallFailsWithErrno(EAGAIN));
}
TEST_P(AllSocketPairTest, RecvTimeoutRecvOneSecondSucceeds) {
auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());
struct timeval tv {
.tv_sec = 1, .tv_usec = 0
};
EXPECT_THAT(
setsockopt(sockets->first_fd(), SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)),
SyscallSucceeds());
char buf[20] = {};
EXPECT_THAT(RetryEINTR(recv)(sockets->first_fd(), buf, sizeof(buf), 0),
SyscallFailsWithErrno(EAGAIN));
}
TEST_P(AllSocketPairTest, RecvTimeoutRecvmsgSucceeds) {
auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());
struct timeval tv {
.tv_sec = 0, .tv_usec = 10
};
EXPECT_THAT(
setsockopt(sockets->first_fd(), SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)),
SyscallSucceeds());
struct msghdr msg = {};
char buf[20] = {};
struct iovec iov;
iov.iov_base = buf;
iov.iov_len = sizeof(buf);
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
EXPECT_THAT(RetryEINTR(recvmsg)(sockets->first_fd(), &msg, 0),
SyscallFailsWithErrno(EAGAIN));
}
TEST_P(AllSocketPairTest, SendTimeoutDefault) {
auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());
timeval actual_tv = {.tv_sec = -1, .tv_usec = -1};
socklen_t len = sizeof(actual_tv);
EXPECT_THAT(getsockopt(sockets->first_fd(), SOL_SOCKET, SO_SNDTIMEO,
&actual_tv, &len),
SyscallSucceeds());
EXPECT_EQ(actual_tv.tv_sec, 0);
EXPECT_EQ(actual_tv.tv_usec, 0);
}
TEST_P(AllSocketPairTest, SetGetSendTimeout) {
auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());
// tv_usec should be a multiple of 4000 to work on most systems.
timeval tv = {.tv_sec = 89, .tv_usec = 44000};
EXPECT_THAT(
setsockopt(sockets->first_fd(), SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)),
SyscallSucceeds());
timeval actual_tv = {};
socklen_t len = sizeof(actual_tv);
EXPECT_THAT(getsockopt(sockets->first_fd(), SOL_SOCKET, SO_SNDTIMEO,
&actual_tv, &len),
SyscallSucceeds());
EXPECT_EQ(actual_tv.tv_sec, tv.tv_sec);
EXPECT_EQ(actual_tv.tv_usec, tv.tv_usec);
}
TEST_P(AllSocketPairTest, SetGetSendTimeoutLargerArg) {
auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());
struct timeval_with_extra {
struct timeval tv;
int64_t extra_data;
} ABSL_ATTRIBUTE_PACKED;
// tv_usec should be a multiple of 4000 to work on most systems.
timeval_with_extra tv_extra = {
.tv = {.tv_sec = 0, .tv_usec = 124000},
};
EXPECT_THAT(setsockopt(sockets->first_fd(), SOL_SOCKET, SO_SNDTIMEO,
&tv_extra, sizeof(tv_extra)),
SyscallSucceeds());
timeval_with_extra actual_tv = {};
socklen_t len = sizeof(actual_tv);
EXPECT_THAT(getsockopt(sockets->first_fd(), SOL_SOCKET, SO_SNDTIMEO,
&actual_tv, &len),
SyscallSucceeds());
EXPECT_EQ(actual_tv.tv.tv_sec, tv_extra.tv.tv_sec);
EXPECT_EQ(actual_tv.tv.tv_usec, tv_extra.tv.tv_usec);
}
TEST_P(AllSocketPairTest, SendTimeoutAllowsWrite) {
auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());
struct timeval tv {
.tv_sec = 0, .tv_usec = 10
};
EXPECT_THAT(
setsockopt(sockets->first_fd(), SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)),
SyscallSucceeds());
char buf[20] = {};
ASSERT_THAT(RetryEINTR(write)(sockets->first_fd(), buf, sizeof(buf)),
SyscallSucceedsWithValue(sizeof(buf)));
}
TEST_P(AllSocketPairTest, SendTimeoutAllowsSend) {
auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());
struct timeval tv {
.tv_sec = 0, .tv_usec = 10
};
EXPECT_THAT(
setsockopt(sockets->first_fd(), SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)),
SyscallSucceeds());
char buf[20] = {};
ASSERT_THAT(RetryEINTR(send)(sockets->first_fd(), buf, sizeof(buf), 0),
SyscallSucceedsWithValue(sizeof(buf)));
}
TEST_P(AllSocketPairTest, SendTimeoutAllowsSendmsg) {
auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());
struct timeval tv {
.tv_sec = 0, .tv_usec = 10
};
EXPECT_THAT(
setsockopt(sockets->first_fd(), SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)),
SyscallSucceeds());
char buf[20] = {};
ASSERT_NO_FATAL_FAILURE(SendNullCmsg(sockets->first_fd(), buf, sizeof(buf)));
}
TEST_P(AllSocketPairTest, RecvTimeoutDefault) {
auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());
timeval actual_tv = {.tv_sec = -1, .tv_usec = -1};
socklen_t len = sizeof(actual_tv);
EXPECT_THAT(getsockopt(sockets->first_fd(), SOL_SOCKET, SO_RCVTIMEO,
&actual_tv, &len),
SyscallSucceeds());
EXPECT_EQ(actual_tv.tv_sec, 0);
EXPECT_EQ(actual_tv.tv_usec, 0);
}
TEST_P(AllSocketPairTest, SetGetRecvTimeout) {
auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());
timeval tv = {.tv_sec = 123, .tv_usec = 456000};
EXPECT_THAT(
setsockopt(sockets->first_fd(), SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)),
SyscallSucceeds());
timeval actual_tv = {};
socklen_t len = sizeof(actual_tv);
EXPECT_THAT(getsockopt(sockets->first_fd(), SOL_SOCKET, SO_RCVTIMEO,
&actual_tv, &len),
SyscallSucceeds());
EXPECT_EQ(actual_tv.tv_sec, 123);
EXPECT_EQ(actual_tv.tv_usec, 456000);
}
TEST_P(AllSocketPairTest, SetGetRecvTimeoutLargerArg) {
auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());
struct timeval_with_extra {
struct timeval tv;
int64_t extra_data;
} ABSL_ATTRIBUTE_PACKED;
timeval_with_extra tv_extra = {
.tv = {.tv_sec = 0, .tv_usec = 432000},
};
EXPECT_THAT(setsockopt(sockets->first_fd(), SOL_SOCKET, SO_RCVTIMEO,
&tv_extra, sizeof(tv_extra)),
SyscallSucceeds());
timeval_with_extra actual_tv = {};
socklen_t len = sizeof(actual_tv);
EXPECT_THAT(getsockopt(sockets->first_fd(), SOL_SOCKET, SO_RCVTIMEO,
&actual_tv, &len),
SyscallSucceeds());
EXPECT_EQ(actual_tv.tv.tv_sec, 0);
EXPECT_EQ(actual_tv.tv.tv_usec, 432000);
}
TEST_P(AllSocketPairTest, RecvTimeoutRecvmsgOneSecondSucceeds) {
auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());
struct timeval tv {
.tv_sec = 1, .tv_usec = 0
};
EXPECT_THAT(
setsockopt(sockets->first_fd(), SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)),
SyscallSucceeds());
struct msghdr msg = {};
char buf[20] = {};
struct iovec iov;
iov.iov_base = buf;
iov.iov_len = sizeof(buf);
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
EXPECT_THAT(RetryEINTR(recvmsg)(sockets->first_fd(), &msg, 0),
SyscallFailsWithErrno(EAGAIN));
}
TEST_P(AllSocketPairTest, RecvTimeoutUsecTooLarge) {
auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());
struct timeval tv {
.tv_sec = 0, .tv_usec = 2000000 // 2 seconds.
};
EXPECT_THAT(
setsockopt(sockets->first_fd(), SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)),
SyscallFailsWithErrno(EDOM));
}
TEST_P(AllSocketPairTest, SendTimeoutUsecTooLarge) {
auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());
struct timeval tv {
.tv_sec = 0, .tv_usec = 2000000 // 2 seconds.
};
EXPECT_THAT(
setsockopt(sockets->first_fd(), SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)),
SyscallFailsWithErrno(EDOM));
}
TEST_P(AllSocketPairTest, RecvTimeoutUsecNeg) {
auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());
struct timeval tv {
.tv_sec = 0, .tv_usec = -1
};
EXPECT_THAT(
setsockopt(sockets->first_fd(), SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)),
SyscallFailsWithErrno(EDOM));
}
TEST_P(AllSocketPairTest, SendTimeoutUsecNeg) {
auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());
struct timeval tv {
.tv_sec = 0, .tv_usec = -1
};
EXPECT_THAT(
setsockopt(sockets->first_fd(), SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)),
SyscallFailsWithErrno(EDOM));
}
TEST_P(AllSocketPairTest, RecvTimeoutNegSecRead) {
auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());
struct timeval tv {
.tv_sec = -1, .tv_usec = 0
};
EXPECT_THAT(
setsockopt(sockets->first_fd(), SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)),
SyscallSucceeds());
char buf[20] = {};
EXPECT_THAT(RetryEINTR(read)(sockets->first_fd(), buf, sizeof(buf)),
SyscallFailsWithErrno(EAGAIN));
}
TEST_P(AllSocketPairTest, RecvTimeoutNegSecRecv) {
auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());
struct timeval tv {
.tv_sec = -1, .tv_usec = 0
};
EXPECT_THAT(
setsockopt(sockets->first_fd(), SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)),
SyscallSucceeds());
char buf[20] = {};
EXPECT_THAT(RetryEINTR(recv)(sockets->first_fd(), buf, sizeof(buf), 0),
SyscallFailsWithErrno(EAGAIN));
}
TEST_P(AllSocketPairTest, RecvTimeoutNegSecRecvmsg) {
auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());
struct timeval tv {
.tv_sec = -1, .tv_usec = 0
};
EXPECT_THAT(
setsockopt(sockets->first_fd(), SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)),
SyscallSucceeds());
struct msghdr msg = {};
char buf[20] = {};
struct iovec iov;
iov.iov_base = buf;
iov.iov_len = sizeof(buf);
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
EXPECT_THAT(RetryEINTR(recvmsg)(sockets->first_fd(), &msg, 0),
SyscallFailsWithErrno(EAGAIN));
}
TEST_P(AllSocketPairTest, RecvWaitAll) {
auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());
char sent_data[100];
RandomizeBuffer(sent_data, sizeof(sent_data));
ASSERT_THAT(write(sockets->first_fd(), sent_data, sizeof(sent_data)),
SyscallSucceedsWithValue(sizeof(sent_data)));
char received_data[sizeof(sent_data)] = {};
ASSERT_THAT(RetryEINTR(recv)(sockets->second_fd(), received_data,
sizeof(received_data), MSG_WAITALL),
SyscallSucceedsWithValue(sizeof(sent_data)));
EXPECT_EQ(0, memcmp(sent_data, received_data, sizeof(sent_data)));
}
TEST_P(AllSocketPairTest, RecvWaitAllDontWait) {
auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());
char data[100] = {};
ASSERT_THAT(RetryEINTR(recv)(sockets->second_fd(), data, sizeof(data),
MSG_WAITALL | MSG_DONTWAIT),
SyscallFailsWithErrno(EAGAIN));
}
TEST_P(AllSocketPairTest, RecvTimeoutWaitAll) {
auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());
struct timeval tv {
.tv_sec = 0, .tv_usec = 200000 // 200ms
};
EXPECT_THAT(setsockopt(sockets->second_fd(), SOL_SOCKET, SO_RCVTIMEO, &tv,
sizeof(tv)),
SyscallSucceeds());
char sent_data[100];
RandomizeBuffer(sent_data, sizeof(sent_data));
ASSERT_THAT(write(sockets->first_fd(), sent_data, sizeof(sent_data)),
SyscallSucceedsWithValue(sizeof(sent_data)));
char received_data[sizeof(sent_data) * 2] = {};
ASSERT_THAT(RetryEINTR(recv)(sockets->second_fd(), received_data,
sizeof(received_data), MSG_WAITALL),
SyscallSucceedsWithValue(sizeof(sent_data)));
EXPECT_EQ(0, memcmp(sent_data, received_data, sizeof(sent_data)));
}
TEST_P(AllSocketPairTest, GetSockoptType) {
int type = GetParam().type;
auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());
for (const int fd : {sockets->first_fd(), sockets->second_fd()}) {
int opt;
socklen_t optlen = sizeof(opt);
EXPECT_THAT(getsockopt(fd, SOL_SOCKET, SO_TYPE, &opt, &optlen),
SyscallSucceeds());
// Type may have SOCK_NONBLOCK and SOCK_CLOEXEC ORed into it. Remove these
// before comparison.
type &= ~(SOCK_NONBLOCK | SOCK_CLOEXEC);
EXPECT_EQ(opt, type) << absl::StrFormat(
"getsockopt(%d, SOL_SOCKET, SO_TYPE, &opt, &optlen) => opt=%d was "
"unexpected",
fd, opt);
}
}
TEST_P(AllSocketPairTest, GetSockoptDomain) {
const int domain = GetParam().domain;
auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());
for (const int fd : {sockets->first_fd(), sockets->second_fd()}) {
int opt;
socklen_t optlen = sizeof(opt);
EXPECT_THAT(getsockopt(fd, SOL_SOCKET, SO_DOMAIN, &opt, &optlen),
SyscallSucceeds());
EXPECT_EQ(opt, domain) << absl::StrFormat(
"getsockopt(%d, SOL_SOCKET, SO_DOMAIN, &opt, &optlen) => opt=%d was "
"unexpected",
fd, opt);
}
}
TEST_P(AllSocketPairTest, GetSockoptProtocol) {
const int protocol = GetParam().protocol;
auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());
for (const int fd : {sockets->first_fd(), sockets->second_fd()}) {
int opt;
socklen_t optlen = sizeof(opt);
EXPECT_THAT(getsockopt(fd, SOL_SOCKET, SO_PROTOCOL, &opt, &optlen),
SyscallSucceeds());
EXPECT_EQ(opt, protocol) << absl::StrFormat(
"getsockopt(%d, SOL_SOCKET, SO_PROTOCOL, &opt, &optlen) => opt=%d was "
"unexpected",
fd, opt);
}
}
TEST_P(AllSocketPairTest, SetAndGetBooleanSocketOptions) {
int sock_opts[] = {SO_BROADCAST, SO_PASSCRED, SO_NO_CHECK,
SO_REUSEADDR, SO_REUSEPORT, SO_KEEPALIVE};
for (int sock_opt : sock_opts) {
auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());
int enable = -1;
socklen_t enableLen = sizeof(enable);
// Test that the option is initially set to false.
ASSERT_THAT(getsockopt(sockets->first_fd(), SOL_SOCKET, sock_opt, &enable,
&enableLen),
SyscallSucceeds());
ASSERT_EQ(enableLen, sizeof(enable));
EXPECT_EQ(enable, 0) << absl::StrFormat(
"getsockopt(fd, SOL_SOCKET, %d, &enable, &enableLen) => enable=%d",
sock_opt, enable);
// Test that setting the option to true is reflected in the subsequent
// call to getsockopt(2).
enable = 1;
ASSERT_THAT(setsockopt(sockets->first_fd(), SOL_SOCKET, sock_opt, &enable,
sizeof(enable)),
SyscallSucceeds());
enable = -1;
enableLen = sizeof(enable);
ASSERT_THAT(getsockopt(sockets->first_fd(), SOL_SOCKET, sock_opt, &enable,
&enableLen),
SyscallSucceeds());
ASSERT_EQ(enableLen, sizeof(enable));
EXPECT_EQ(enable, 1) << absl::StrFormat(
"getsockopt(fd, SOL_SOCKET, %d, &enable, &enableLen) => enable=%d",
sock_opt, enable);
}
}
TEST_P(AllSocketPairTest, GetSocketOutOfBandInlineOption) {
// We do not support disabling this option. It is always enabled.
SKIP_IF(!IsRunningOnGvisor());
auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());
int enable = -1;
socklen_t enableLen = sizeof(enable);
int want = 1;
ASSERT_THAT(getsockopt(sockets->first_fd(), SOL_SOCKET, SO_OOBINLINE, &enable,
&enableLen),
SyscallSucceeds());
ASSERT_EQ(enableLen, sizeof(enable));
EXPECT_EQ(enable, want);
}
} // namespace testing
} // namespace gvisor
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* Form.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: vminomiy <vminomiy@student.42sp.org.br> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/03/18 08:50:49 by vminomiy #+# #+# */
/* Updated: 2022/03/23 02:05:52 by vminomiy ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef FORM_HPP
# define FORM_HPP
class Form;
class Bureaucrat;
#include "Bureaucrat.hpp"
class Form {
private:
Form(void);
std::string const name;
int const signGrade;
int const execGrade;
bool isSigned;
protected:
public:
Form(std::string const &_name, int const _signGrade, int const _execGrade);
virtual ~Form(void);
Form(Form const ©);
Form &operator=(Form const ©);
// Getter das informações necessárias;
std::string const &getName(void) const;
int getSignGrade(void) const;
int getExecGrade(void) const;
// exception classes
class GradeTooHighException: public std::exception {
virtual const char *what() const throw();
};
class GradeTooLowException: public std::exception {
virtual const char *what() const throw();
};
class FormIsSignedException: public std::exception {
virtual const char *what() const throw();
};
// Operation classes
bool getSigned(void) const;
void beSigned(Bureaucrat const ©);
};
// override da <<
std::ostream &operator<<(std::ostream &os, const Form &obj);
#endif
|
// Boost.Geometry
// Unit Test
// Copyright (c) 2016-2019 Oracle and/or its affiliates.
// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle
// Copyright (c) 2018 Adeel Ahmad, Islamabad, Pakistan.
// Contributed and/or modified by Adeel Ahmad, as part of Google Summer of Code 2018 program
// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <sstream>
#include "test_formula.hpp"
#include "inverse_cases.hpp"
#include "inverse_cases_antipodal.hpp"
#include "inverse_cases_small_angles.hpp"
#include <boost/geometry/formulas/karney_inverse.hpp>
#include <boost/geometry/srs/spheroid.hpp>
template <typename Result>
void check_inverse(std::string const& name,
Result const& results,
bg::formula::result_inverse<double> const& result,
expected_result const& expected,
expected_result const& reference,
double reference_error)
{
std::stringstream ss;
ss << "(" << results.p1.lon << " " << results.p1.lat << ")->(" << results.p2.lon << " " << results.p2.lat << ")";
check_one(name + "_d " + ss.str(),
result.distance, expected.distance, reference.distance, reference_error);
check_one(name + "_a " + ss.str(),
result.azimuth, expected.azimuth, reference.azimuth, reference_error, true);
check_one(name + "_ra " + ss.str(),
result.reverse_azimuth, expected.reverse_azimuth, reference.reverse_azimuth, reference_error, true);
check_one(name + "_rl " + ss.str(),
result.reduced_length, expected.reduced_length, reference.reduced_length, reference_error);
check_one(name + "_gs " + ss.str(),
result.geodesic_scale, expected.geodesic_scale, reference.geodesic_scale, reference_error);
}
void test_all(expected_results const& results)
{
double lon1d = results.p1.lon;
double lat1d = results.p1.lat;
double lon2d = results.p2.lon;
double lat2d = results.p2.lat;
// WGS84
bg::srs::spheroid<double> spheroid(6378137.0, 6356752.3142451793);
bg::formula::result_inverse<double> result_k;
typedef bg::formula::karney_inverse<double, true, true, true, true, true, 8> ka_t;
result_k = ka_t::apply(lon1d, lat1d, lon2d, lat2d, spheroid);
check_inverse("karney", results, result_k, results.vincenty, results.reference, 0.0000001);
}
template <typename ExpectedResults>
void test_karney(ExpectedResults const& results)
{
double lon1d = results.p1.lon;
double lat1d = results.p1.lat;
double lon2d = results.p2.lon;
double lat2d = results.p2.lat;
// WGS84
bg::srs::spheroid<double> spheroid(6378137.0, 6356752.3142451793);
bg::formula::result_inverse<double> result;
typedef bg::formula::karney_inverse<double, true, true, true, true, true, 8> ka_t;
result = ka_t::apply(lon1d, lat1d, lon2d, lat2d, spheroid);
check_inverse("karney", results, result, results.karney, results.karney, 0.0000001);
}
int test_main(int, char*[])
{
for (size_t i = 0; i < expected_size; ++i)
{
test_all(expected[i]);
}
for (size_t i = 0; i < expected_size_antipodal; ++i)
{
test_karney(expected_antipodal[i]);
}
for (size_t i = 0; i < expected_size_small_angles; ++i)
{
test_karney(expected_small_angles[i]);
}
return 0;
}
|
#include "distance.h"
#include "pointprocessed.h"
Distance::Distance()
{
}
Distance::Distance(PointProcessed* point, double distance){
p = point;
d = distance;
}
double Distance::getDistance(){
return d;
}
PointProcessed* Distance::getPoint()const {
return p;
}
bool Distance::operator<(Distance dis)const{
return d < dis.d;
}
bool Distance::operator==(Distance dis)const{
return d == dis.d;
}
bool Distance::operator!=(Distance dis)const{
return d != dis.d;
}
bool Distance::operator<=(Distance dis)const{
return d <= dis.d;
}
bool Distance::operator>(Distance dis)const{
return d > dis.d;
}
bool Distance::operator>=(Distance dis)const{
return d >= dis.d;
}
|
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include <EMotionFX/Source/Allocators.h>
namespace EMotionFX
{
// Implementation of the GetDescription methods. They are put here so they don't generate multiple
// strings in the binaries across compilation units
#define EMOTION_FX_ALLOCATOR_IMPL(ALLOCATOR_SEQUENCE) \
const char* EMOTIONFX_ALLOCATOR_SEQ_GET_NAME(ALLOCATOR_SEQUENCE)::GetDescription() const { return EMOTIONFX_ALLOCATOR_SEQ_GET_DESCRIPTION(ALLOCATOR_SEQUENCE); }
// Here we create the "GetDescription" method implementation for all the items in the header's table (Step 3)
AZ_SEQ_FOR_EACH(EMOTION_FX_ALLOCATOR_IMPL, EMOTIONFX_ALLOCATORS)
#undef EMOTION_FX_ALLOCATOR_IMPL
template <typename TAllocator, typename TSubAllocator>
class AllocatorCreator
{
public:
static void Create()
{
typename TAllocator::Descriptor descriptor;
descriptor.m_custom = &AZ::AllocatorInstance<TSubAllocator>::Get();
AZ::AllocatorInstance<TAllocator>::Create(descriptor);
}
};
template <typename TAllocator>
class AllocatorCreator<TAllocator, NoSubAllocator>
{
public:
static void Create()
{
AZ::AllocatorInstance<TAllocator>::Create();
}
};
// Create all allocators
void Allocators::Create()
{
#define EMOTION_FX_ALLOCATOR_CREATE(ALLOCATOR_SEQUENCE) \
AllocatorCreator<EMOTIONFX_ALLOCATOR_SEQ_GET_NAME(ALLOCATOR_SEQUENCE), EMOTIONFX_ALLOCATOR_SEQ_GET_SUBALLOCATOR(ALLOCATOR_SEQUENCE)>::Create();
// Here we call the "Create" to create the allocator for all the items in the header's table (Step 4)
AZ_SEQ_FOR_EACH(EMOTION_FX_ALLOCATOR_CREATE, EMOTIONFX_ALLOCATORS)
#undef EMOTION_FX_ALLOCATOR_CREATE
}
// Destroy all allocators
void Allocators::Destroy()
{
#define EMOTION_FX_ALLOCATOR_DESTROY(ALLOCATOR_SEQUENCE) \
AZ::AllocatorInstance<EMOTIONFX_ALLOCATOR_SEQ_GET_NAME(ALLOCATOR_SEQUENCE)>::Destroy();
// Here we call the "Destroy" to destroy the allocator for all the items in the header's table (Step 5)
AZ_SEQ_FOR_EACH(EMOTION_FX_ALLOCATOR_DESTROY, EMOTIONFX_ALLOCATORS)
#undef EMOTION_FX_ALLOCATOR_DESTROY
}
void Allocators::ShrinkPools()
{
AZ::AllocatorInstance<AnimGraphObjectDataAllocator>::Get().GarbageCollect();
AZ::AllocatorInstance<AnimGraphObjectUniqueDataAllocator>::Get().GarbageCollect();
AZ::AllocatorInstance<AnimGraphConditionAllocator>::Get().GarbageCollect();
}
} // EMotionFX namespace
|
// Scintilla source code edit control
/** @file LexKix.cxx
** Lexer for KIX-Scripts.
**/
// Copyright 2004 by Manfred Becker <manfred@becker-trdf.de>
// The License.txt file describes the conditions under which this software may be distributed.
// Edited by Lee Wilmott (24-Jun-2014) added support for block comments
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <stdarg.h>
#include <assert.h>
#include <ctype.h>
#include <string>
#include <string_view>
#include "ILexer.h"
#include "Scintilla.h"
#include "SciLexer.h"
#include "WordList.h"
#include "LexAccessor.h"
#include "Accessor.h"
#include "StyleContext.h"
#include "CharacterSet.h"
#include "LexerModule.h"
using namespace Lexilla;
// Extended to accept accented characters
static inline bool IsAWordChar(int ch) {
return ch >= 0x80 || isalnum(ch) || ch == '_';
}
static inline bool IsOperator(const int ch) {
return (ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch == '&' || ch == '|' || ch == '<' || ch == '>' || ch == '=');
}
static void ColouriseKixDoc(Sci_PositionU startPos, Sci_Position length, int initStyle,
WordList *keywordlists[], Accessor &styler) {
WordList &keywords = *keywordlists[0];
WordList &keywords2 = *keywordlists[1];
WordList &keywords3 = *keywordlists[2];
// WordList &keywords4 = *keywordlists[3];
styler.StartAt(startPos);
StyleContext sc(startPos, length, initStyle, styler);
for (; sc.More(); sc.Forward()) {
if (sc.state == SCE_KIX_COMMENT) {
if (sc.atLineEnd) {
sc.SetState(SCE_KIX_DEFAULT);
}
} else if (sc.state == SCE_KIX_COMMENTSTREAM) {
if (sc.ch == '/' && sc.chPrev == '*') {
sc.ForwardSetState(SCE_KIX_DEFAULT);
}
} else if (sc.state == SCE_KIX_STRING1) {
// This is a doubles quotes string
if (sc.ch == '\"') {
sc.ForwardSetState(SCE_KIX_DEFAULT);
}
} else if (sc.state == SCE_KIX_STRING2) {
// This is a single quote string
if (sc.ch == '\'') {
sc.ForwardSetState(SCE_KIX_DEFAULT);
}
} else if (sc.state == SCE_KIX_NUMBER) {
if (!IsADigit(sc.ch)) {
sc.SetState(SCE_KIX_DEFAULT);
}
} else if (sc.state == SCE_KIX_VAR) {
if (!IsAWordChar(sc.ch)) {
sc.SetState(SCE_KIX_DEFAULT);
}
} else if (sc.state == SCE_KIX_MACRO) {
if (!IsAWordChar(sc.ch) && !IsADigit(sc.ch)) {
char s[100];
sc.GetCurrentLowered(s, sizeof(s));
if (!keywords3.InList(&s[1])) {
sc.ChangeState(SCE_KIX_DEFAULT);
}
sc.SetState(SCE_KIX_DEFAULT);
}
} else if (sc.state == SCE_KIX_OPERATOR) {
if (!IsOperator(sc.ch)) {
sc.SetState(SCE_KIX_DEFAULT);
}
} else if (sc.state == SCE_KIX_IDENTIFIER) {
if (!IsAWordChar(sc.ch)) {
char s[100];
sc.GetCurrentLowered(s, sizeof(s));
if (keywords.InList(s)) {
sc.ChangeState(SCE_KIX_KEYWORD);
} else if (keywords2.InList(s)) {
sc.ChangeState(SCE_KIX_FUNCTIONS);
}
sc.SetState(SCE_KIX_DEFAULT);
}
}
// Determine if a new state should be entered.
if (sc.state == SCE_KIX_DEFAULT) {
if (sc.ch == ';') {
sc.SetState(SCE_KIX_COMMENT);
} else if (sc.ch == '/' && sc.chNext == '*') {
sc.SetState(SCE_KIX_COMMENTSTREAM);
} else if (sc.ch == '\"') {
sc.SetState(SCE_KIX_STRING1);
} else if (sc.ch == '\'') {
sc.SetState(SCE_KIX_STRING2);
} else if (sc.ch == '$') {
sc.SetState(SCE_KIX_VAR);
} else if (sc.ch == '@') {
sc.SetState(SCE_KIX_MACRO);
} else if (IsADigit(sc.ch) || ((sc.ch == '.' || sc.ch == '&') && IsADigit(sc.chNext))) {
sc.SetState(SCE_KIX_NUMBER);
} else if (IsOperator(sc.ch)) {
sc.SetState(SCE_KIX_OPERATOR);
} else if (IsAWordChar(sc.ch)) {
sc.SetState(SCE_KIX_IDENTIFIER);
}
}
}
sc.Complete();
}
LexerModule lmKix(SCLEX_KIX, ColouriseKixDoc, "kix");
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#include "core/providers/common.h"
#include "core/providers/cuda/cuda_common.h"
#include "core/providers/cuda/nn/conv.h"
#include "core/providers/cuda/shared_inc/fpgeneric.h"
namespace onnxruntime {
namespace cuda {
// Op Set 11 for Conv only update document to clearify default dilations and strides value.
// which are already convered by op set 11 cpu versoin, so simply add declaration.
#define REGISTER_KERNEL_TYPED(T) \
ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_EX( \
Conv, \
kOnnxDomain, \
1, 10, \
T, \
kCudaExecutionProvider, \
KernelDefBuilder().TypeConstraint("T", DataTypeImpl::GetTensorType<T>()), \
Conv<T>); \
ONNX_OPERATOR_TYPED_KERNEL_EX( \
Conv, \
kOnnxDomain, \
11, \
T, \
kCudaExecutionProvider, \
KernelDefBuilder().TypeConstraint("T", DataTypeImpl::GetTensorType<T>()), \
Conv<T>);
REGISTER_KERNEL_TYPED(float)
REGISTER_KERNEL_TYPED(double)
REGISTER_KERNEL_TYPED(MLFloat16)
template <typename T>
Status Conv<T>::ComputeInternal(OpKernelContext* context) const {
typedef typename ToCudaType<T>::MappedType CudaT;
const Tensor* X = context->Input<Tensor>(0);
const TensorShape& x_shape = X->Shape();
const auto& x_dims = x_shape.GetDims();
auto x_data = reinterpret_cast<const CudaT*>(X->template Data<T>());
const Tensor* W = context->Input<Tensor>(1);
const TensorShape& w_shape = W->Shape();
std::vector<int64_t> w_dims = w_shape.GetDims();
auto w_data = reinterpret_cast<const CudaT*>(W->template Data<T>());
size_t num_inputs = OpKernel::Node().InputDefs().size();
bool has_bias = (num_inputs == 3);
CudaT* y_data = nullptr;
{
std::lock_guard<OrtMutex> lock(s_.mutex);
// TODO: add a global cache if need to handle cases for multiple frames running simultaneuously with different batch_size
bool input_dims_changed = (s_.last_x_dims != x_dims);
bool w_dims_changed = (s_.last_w_dims != w_dims);
if (input_dims_changed || w_dims_changed) {
if (input_dims_changed)
s_.last_x_dims = x_dims;
if (w_dims_changed) {
s_.last_w_dims = w_dims;
s_.cached_benchmark_results.clear();
}
const int64_t N = X->Shape()[0];
const int64_t M = W->Shape()[0];
ORT_RETURN_IF_ERROR(conv_attrs_.ValidateInputShape(X, W));
std::vector<int64_t> kernel_shape;
ORT_RETURN_IF_ERROR(conv_attrs_.ComputeKernelShape(W->Shape(), kernel_shape));
auto rank = kernel_shape.size();
std::vector<int64_t> pads(conv_attrs_.pads);
if (pads.empty()) {
pads.resize(rank * 2, 0);
}
std::vector<int64_t> dilations(conv_attrs_.dilations);
if (dilations.empty()) {
dilations.resize(rank, 1);
}
std::vector<int64_t> strides(conv_attrs_.strides);
if (strides.empty()) {
strides.resize(rank, 1);
}
std::vector<int64_t> y_dims;
y_dims.insert(y_dims.begin(), {N, M});
ORT_RETURN_IF_ERROR(conv_attrs_.InferOutputShape<true>(x_shape.Slice(2), kernel_shape,
strides, dilations, &pads, &y_dims));
s_.y_dims = y_dims;
Tensor* Y = context->Output(0, TensorShape(s_.y_dims));
y_data = reinterpret_cast<CudaT*>(Y->template MutableData<T>());
// special case when there is a dim value of 0 in the shape.
if (Y->Shape().Size() == 0)
return Status::OK();
std::vector<int64_t> x_dims_cudnn = x_dims;
std::vector<int64_t> y_dims_cudnn = y_dims;
if (rank < 2) {
// cudnn only takes 4D or 5D input, so pad dimensions if needed
x_dims_cudnn.push_back(1);
y_dims_cudnn.push_back(1);
w_dims.push_back(1);
pads.insert(pads.begin() + rank, 0);
pads.insert(pads.end(), 0);
kernel_shape.push_back(1);
strides.push_back(1);
dilations.push_back(1);
}
ORT_RETURN_IF_ERROR(s_.x_tensor.Set(x_dims_cudnn, CudnnTensor::GetDataType<CudaT>()));
ORT_RETURN_IF_ERROR(s_.y_tensor.Set(y_dims_cudnn, CudnnTensor::GetDataType<CudaT>()));
if (w_dims_changed)
ORT_RETURN_IF_ERROR(s_.filter_desc.Set(w_dims, CudnnTensor::GetDataType<CudaT>()));
cudnnConvolutionMode_t mode = CUDNN_CROSS_CORRELATION;
ORT_RETURN_IF_ERROR(s_.conv_desc.Set(kernel_shape.size(), pads, strides, dilations,
mode, CudnnTensor::GetDataType<CudaT>()));
CUDNN_RETURN_IF_ERROR(cudnnSetConvolutionGroupCount(s_.conv_desc, gsl::narrow_cast<int>(conv_attrs_.group)));
if (has_bias) {
const Tensor* B = context->Input<Tensor>(2);
const auto& b_shape = B->Shape();
ORT_RETURN_IF_NOT(b_shape.NumDimensions() == 1, "bias should be 1D");
std::vector<int64_t> b_dims(2 + kernel_shape.size());
b_dims[0] = 1; // N
b_dims[1] = b_shape[0]; // C
for (size_t i = 0; i < kernel_shape.size(); i++) b_dims[2 + i] = 1;
ORT_RETURN_IF_ERROR(s_.b_tensor.Set(b_dims, CudnnTensor::GetDataType<CudaT>()));
}
if (!s_.cached_benchmark_results.contains(x_dims_cudnn)) {
IAllocatorUniquePtr<void> algo_search_workspace = GetScratchBuffer<void>(AlgoSearchWorkspaceSize);
// set math type to tensor core before algorithm search
if (std::is_same<T, MLFloat16>::value)
CUDNN_RETURN_IF_ERROR(cudnnSetConvolutionMathType(s_.conv_desc, CUDNN_TENSOR_OP_MATH));
cudnnConvolutionFwdAlgoPerf_t perf;
int algo_count = 1;
CUDNN_RETURN_IF_ERROR(cudnnFindConvolutionForwardAlgorithmEx(
CudnnHandle(),
s_.x_tensor,
x_data,
s_.filter_desc,
w_data,
s_.conv_desc,
s_.y_tensor,
y_data,
1,
&algo_count,
&perf,
algo_search_workspace.get(),
AlgoSearchWorkspaceSize));
s_.cached_benchmark_results.insert(x_dims_cudnn, {perf.algo, perf.memory, perf.mathType});
}
const auto& perf = s_.cached_benchmark_results.at(x_dims_cudnn);
CUDNN_RETURN_IF_ERROR(cudnnSetConvolutionMathType(s_.conv_desc, perf.mathType));
s_.algo = perf.algo;
s_.workspace_bytes = perf.memory;
}
if (!y_data) {
Tensor* Y = context->Output(0, TensorShape(s_.y_dims));
// special case when there is a dim value of 0 in the shape.
if (Y->Shape().Size() == 0)
return Status::OK();
y_data = reinterpret_cast<CudaT*>(Y->template MutableData<T>());
}
const auto alpha = Consts<CudaT>::One;
const auto beta = Consts<CudaT>::Zero;
IAllocatorUniquePtr<void> workspace = GetScratchBuffer<void>(s_.workspace_bytes);
CUDNN_RETURN_IF_ERROR(cudnnConvolutionForward(CudnnHandle(),
&alpha,
s_.x_tensor,
x_data,
s_.filter_desc,
w_data,
s_.conv_desc,
s_.algo,
workspace.get(),
s_.workspace_bytes,
&beta,
s_.y_tensor,
y_data));
if (has_bias) {
const Tensor* B = context->Input<Tensor>(2);
auto b_data = reinterpret_cast<const CudaT*>(B->template Data<T>());
CUDNN_RETURN_IF_ERROR(cudnnAddTensor(CudnnHandle(), &alpha, s_.b_tensor, b_data, &alpha, s_.y_tensor, y_data));
}
}
return Status::OK();
}
CudnnConvolutionDescriptor::CudnnConvolutionDescriptor() : desc_(nullptr) {
}
CudnnConvolutionDescriptor::~CudnnConvolutionDescriptor() {
if (desc_ != nullptr) {
cudnnDestroyConvolutionDescriptor(desc_);
desc_ = nullptr;
}
}
Status CudnnConvolutionDescriptor::Set(
size_t rank,
const std::vector<int64_t>& pads,
const std::vector<int64_t>& strides,
const std::vector<int64_t>& dilations,
cudnnConvolutionMode_t mode,
cudnnDataType_t data_type) {
if (!desc_)
CUDNN_RETURN_IF_ERROR(cudnnCreateConvolutionDescriptor(&desc_));
std::vector<int> pad_dims(rank);
std::vector<int> stride_dims(rank);
std::vector<int> dilation_dims(rank);
for (size_t i = 0; i < rank; i++) {
pad_dims[i] = gsl::narrow_cast<int>(pads[i]);
stride_dims[i] = gsl::narrow_cast<int>(strides[i]);
dilation_dims[i] = gsl::narrow_cast<int>(dilations[i]);
}
CUDNN_RETURN_IF_ERROR(cudnnSetConvolutionNdDescriptor(
desc_,
gsl::narrow_cast<int>(rank),
pad_dims.data(),
stride_dims.data(),
dilation_dims.data(),
mode,
data_type));
return Status::OK();
}
} // namespace cuda
} // namespace onnxruntime
|
#include "Control/ControlDialect.h"
#include "mlir/IR/Builders.h"
#include "mlir/IR/DialectImplementation.h"
#include "mlir/IR/OpImplementation.h"
#include "mlir/IR/TypeUtilities.h"
#include "llvm/ADT/TypeSwitch.h"
using namespace mlir;
using namespace hail::control;
#include "Control/ControlOpsDialect.cpp.inc"
#define GET_TYPEDEF_CLASSES
#include "Control/ControlOpsTypes.cpp.inc"
void ControlDialect::initialize() {
addOperations<
#define GET_OP_LIST
#include "Control/ControlOps.cpp.inc"
>();
addTypes<
#define GET_TYPEDEF_LIST
#include "Control/ControlOpsTypes.cpp.inc"
>();
}
Type ControlDialect::parseType(DialectAsmParser &parser) const {
llvm::SMLoc typeLoc = parser.getCurrentLocation();
{
Type genType;
StringRef typeTag;
if (failed(parser.parseKeyword(&typeTag)))
return Type();
auto parseResult = generatedTypeParser(parser.getBuilder().getContext(),
parser, typeTag, genType);
if (parseResult.hasValue())
return genType;
}
parser.emitError(typeLoc, "unknown type in Control dialect");
return Type();
}
void ControlDialect::printType(Type type, DialectAsmPrinter &os) const {
if (failed(generatedTypePrinter(type, os)))
llvm_unreachable("unexpected 'control' type kind");
}
|
//ETarget.cpp
// Copyright (c) 2008-2010, Petr Kobalicek <kobalicek.petr@gmail.com>
// Copyright (c) Querysoft Limited 2012
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//Implements an x86 jump target
#include "ArchQOR.h"
#if ( QOR_ARCH == QOR_ARCH_X86_32 || QOR_ARCH == QOR_ARCH_X86_64 )
#include "ArchQOR/x86/HLAssembler/Emittables/ETarget.h"
#include "ArchQOR/x86/HLAssembler/x86HLAContext.h"
#include <assert.h>
//------------------------------------------------------------------------------
namespace nsArch
{
namespace nsx86
{
//------------------------------------------------------------------------------
CETarget::CETarget( nsArch::CHighLevelAssemblerBase* c, const CLabel& label ) __QCMP_THROW : nsArch::CEmittable( c, EMITTABLE_TARGET ),
m_Label( label ),
m_pFrom( 0 ),
m_pState( 0 ),
m_uiJumpsCount( 0 )
{
}
//------------------------------------------------------------------------------
CETarget::~CETarget() __QCMP_THROW
{
}
//------------------------------------------------------------------------------
void CETarget::prepare( CHLAssemblerContextBase& cc) __QCMP_THROW
{
m_uiOffset = cc.IncrementCurrentOffset();
}
//------------------------------------------------------------------------------
nsArch::CEmittable* CETarget::translate( CHLAssemblerContextBase& hlac ) __QCMP_THROW
{
// If this CETarget was already translated, it's needed to change the current
// state and return 0 to tell HLAContext to process next untranslated
// emittable.
Cx86HLAContext& cc = dynamic_cast< Cx86HLAContext& >( hlac );
if( m_ucTranslated )
{
cc._restoreState( m_pState );
return 0;
}
if( cc.getUnreachable() )
{
cc.setUnreachable( 0 );
// Assign state to the compiler context.
assert( m_pState != 0 );
cc._assignState( m_pState );
}
else
{
m_pState = cc._saveState();
}
return translated();
}
//------------------------------------------------------------------------------
void CETarget::emit( CHighLevelAssemblerBase& ab ) __QCMP_THROW
{
Cx86HLAIntrinsics& a = dynamic_cast< Cx86HLAIntrinsics& >( ab );
a.getContext()->getAssembler()->bind( m_Label );
}
//------------------------------------------------------------------------------
int CETarget::getMaxSize() const __QCMP_THROW
{
return 0;
}
}//nsx86
}//nsArch
#endif//( QOR_ARCH == QOR_ARCH_X86_32 || QOR_ARCH == QOR_ARCH_X86_64 )
|
/**
* Copyright (C) 2013 10gen Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the GNU Affero General Public License in all respects
* for all of the code used other than as permitted herein. If you modify
* file(s) with this exception, you may extend this exception to your
* version of the file(s), but you are not obligated to do so. If you do not
* wish to do so, delete this exception statement from your version. If you
* delete this exception statement from all source files in the program,
* then also delete it in the license file.
*/
#define MONGO_LOG_DEFAULT_COMPONENT ::mongo::logger::LogComponent::kDefault
#include "mongo/platform/basic.h"
#include "mongo/unittest/temp_dir.h"
#include <boost/filesystem.hpp>
#include "mongo/base/init.h"
#include "mongo/unittest/unittest.h"
#include "mongo/util/mongoutils/str.h"
#include "mongo/util/log.h"
#include "mongo/util/options_parser/startup_options.h"
#include "mongo/util/options_parser/startup_option_init.h"
namespace mongo {
using std::string;
namespace unittest {
namespace str = mongoutils::str;
namespace moe = mongo::optionenvironment;
namespace {
boost::filesystem::path defaultRoot;
MONGO_GENERAL_STARTUP_OPTIONS_REGISTER(TempDirOptions)(InitializerContext* context) {
moe::startupOptions.addOptionChaining(
"tempPath", "tempPath", moe::String, "directory to place mongo::TempDir subdirectories");
return Status::OK();
}
MONGO_INITIALIZER(SetTempDirDefaultRoot)(InitializerContext* context) {
if (moe::startupOptionsParsed.count("tempPath")) {
defaultRoot = moe::startupOptionsParsed["tempPath"].as<string>();
} else {
defaultRoot = boost::filesystem::temp_directory_path();
}
if (!boost::filesystem::exists(defaultRoot)) {
return Status(ErrorCodes::BadValue,
str::stream() << "Attempted to use a tempPath (" << defaultRoot.string()
<< ") that doesn't exist");
}
if (!boost::filesystem::is_directory(defaultRoot)) {
return Status(ErrorCodes::BadValue,
str::stream() << "Attempted to use a tempPath (" << defaultRoot.string()
<< ") that exists, but isn't a directory");
}
return Status::OK();
}
}
TempDir::TempDir(const std::string& namePrefix) {
fassert(17146, namePrefix.find_first_of("/\\") == std::string::npos);
// This gives the dir name 64 bits of randomness.
const boost::filesystem::path dirName =
boost::filesystem::unique_path(namePrefix + "-%%%%-%%%%-%%%%-%%%%");
_path = (defaultRoot / dirName).string();
bool createdNewDirectory = boost::filesystem::create_directory(_path);
if (!createdNewDirectory) {
error() << "unique path (" << _path << ") already existed";
fassertFailed(17147);
}
::mongo::unittest::log() << "Created temporary directory: " << _path;
}
TempDir::~TempDir() {
try {
boost::filesystem::remove_all(_path);
} catch (const std::exception& e) {
warning() << "error encountered recursively deleting directory '" << _path
<< "': " << e.what() << ". Ignoring and continuing.";
}
}
} // namespace unittest
} // namespace mongo
|
/**
* Created by Crow on 2/9/19.
* Copyright (c) 2019 Crow All rights reserved.
* @author Crow
* @brief HTTP party headers
*/
#ifndef PLATINUM_INCLUDE_HTTP_HPP
#define PLATINUM_INCLUDE_HTTP_HPP
#include "protocol/http/request.h"
#include "protocol/http/request_parser.h"
#include "protocol/http/response.h"
#include "protocol/http/response_builder.h"
#endif //PLATINUM_INCLUDE_HTTP_HPP
|
// Distributed under the MIT License.
// See LICENSE.txt for details.
#pragma once
#include <string>
#include "DataStructures/DataBox/Tag.hpp"
#include "DataStructures/DataBox/TagName.hpp"
#include "DataStructures/DataVector.hpp"
#include "DataStructures/Tensor/EagerMath/DotProduct.hpp"
#include "DataStructures/Tensor/Tensor.hpp"
#include "Utilities/ContainerHelpers.hpp"
#include "Utilities/Gsl.hpp"
#include "Utilities/TMPL.hpp"
// @{
/*!
* \ingroup TensorGroup
* \brief Compute the Euclidean magnitude of a rank-1 tensor
*
* \details
* Computes the square root of the sum of the squares of the components of
* the rank-1 tensor.
*/
template <typename DataType, typename Index>
Scalar<DataType> magnitude(
const Tensor<DataType, Symmetry<1>, index_list<Index>>& vector) noexcept {
return Scalar<DataType>{sqrt(get(dot_product(vector, vector)))};
}
template <typename DataType, typename Index>
void magnitude(
const gsl::not_null<Scalar<DataType>*> magnitude,
const Tensor<DataType, Symmetry<1>, index_list<Index>>& vector) noexcept {
destructive_resize_components(magnitude, get_size(get<0>(vector)));
dot_product(magnitude, vector, vector);
get(*magnitude) = sqrt(get(*magnitude));
}
// @}
// @{
/*!
* \ingroup TensorGroup
* \brief Compute the magnitude of a rank-1 tensor
*
* \details
* Returns the square root of the input tensor contracted twice with the given
* metric.
*/
template <typename DataType, typename Index>
Scalar<DataType> magnitude(
const Tensor<DataType, Symmetry<1>, index_list<Index>>& vector,
const Tensor<DataType, Symmetry<1, 1>,
index_list<change_index_up_lo<Index>,
change_index_up_lo<Index>>>& metric) noexcept {
Scalar<DataType> local_magnitude{get_size(get<0>(vector))};
magnitude(make_not_null(&local_magnitude), vector, metric);
return local_magnitude;
}
template <typename DataType, typename Index>
void magnitude(
const gsl::not_null<Scalar<DataType>*> magnitude,
const Tensor<DataType, Symmetry<1>, index_list<Index>>& vector,
const Tensor<DataType, Symmetry<1, 1>,
index_list<change_index_up_lo<Index>,
change_index_up_lo<Index>>>& metric) noexcept {
dot_product(magnitude, vector, vector, metric);
get(*magnitude) = sqrt(get(*magnitude));
}
// @}
// @{
/// \ingroup TensorGroup
/// \brief Compute square root of the Euclidean magnitude of a rank-0 tensor
///
/// \details
/// Computes the square root of the absolute value of the scalar.
template <typename DataType>
Scalar<DataType> sqrt_magnitude(const Scalar<DataType>& input) noexcept {
return Scalar<DataType>{sqrt(abs(get(input)))};
}
template <typename DataType>
void sqrt_magnitude(const gsl::not_null<Scalar<DataType>*> sqrt_magnitude,
const Scalar<DataType>& input) noexcept {
destructive_resize_components(sqrt_magnitude, get_size(get(input)));
get(*sqrt_magnitude) = sqrt(abs(get(input)));
}
// @}
namespace Tags {
/// \ingroup DataBoxTagsGroup
/// \ingroup DataStructuresGroup
/// The magnitude of a (co)vector
template <typename Tag>
struct Magnitude : db::PrefixTag, db::SimpleTag {
using tag = Tag;
using type = Scalar<DataVector>;
};
/// \ingroup DataBoxTagsGroup
/// \ingroup DataStructuresGroup
/// The Euclidean magnitude of a (co)vector
///
/// This tag inherits from `Tags::Magnitude<Tag>`
template <typename Tag>
struct EuclideanMagnitude : Magnitude<Tag>, db::ComputeTag {
using base = Magnitude<Tag>;
using return_type = typename base::type;
static constexpr auto function =
static_cast<void (*)(const gsl::not_null<return_type*>,
const typename Tag::type&) noexcept>(&magnitude);
using argument_tags = tmpl::list<Tag>;
};
/// \ingroup DataBoxTagsGroup
/// \ingroup DataStructuresGroup
/// The magnitude of a (co)vector with respect to a specific metric
///
/// This tag inherits from `Tags::Magnitude<Tag>`
template <typename Tag, typename MetricTag>
struct NonEuclideanMagnitude : Magnitude<Tag>, db::ComputeTag {
using base = Magnitude<Tag>;
using return_type = typename base::type;
static constexpr auto function = static_cast<void (*)(
const gsl::not_null<return_type*>, const typename Tag::type&,
const typename MetricTag::type&) noexcept>(&magnitude);
using argument_tags = tmpl::list<Tag, MetricTag>;
};
/// \ingroup DataBoxTagsGroup
/// \ingroup DataStructuresGroup
/// The normalized (co)vector represented by Tag
template <typename Tag>
struct Normalized : db::PrefixTag, db::SimpleTag {
using tag = Tag;
using type = typename Tag::type;
};
/// \ingroup DataBoxTagsGroup
/// \ingroup DataStructuresGroup
/// Normalizes the (co)vector represented by Tag
///
/// This tag inherits from `Tags::Normalized<Tag>`
template <typename Tag>
struct NormalizedCompute : Normalized<Tag>, db::ComputeTag {
using base = Normalized<Tag>;
using return_type = typename base::type;
static void function(
const gsl::not_null<return_type*> normalized_vector,
const typename Tag::type& vector_in,
const typename Magnitude<Tag>::type& magnitude) noexcept {
destructive_resize_components(normalized_vector, get_size(get(magnitude)));
*normalized_vector = vector_in;
for (size_t d = 0; d < normalized_vector->index_dim(0); ++d) {
normalized_vector->get(d) /= get(magnitude);
}
}
using argument_tags = tmpl::list<Tag, Magnitude<Tag>>;
};
/// \ingroup DataBoxTagsGroup
/// \ingroup DataStructuresGroup
/// The square root of a scalar
template <typename Tag>
struct Sqrt : db::PrefixTag, db::SimpleTag {
using tag = Tag;
using type = Scalar<DataVector>;
};
/// \ingroup DataBoxTagsGroup
/// \ingroup DataStructuresGroup
/// The square root of a scalar
///
/// This tag inherits from `Tags::Sqrt<Tag>`
template <typename Tag>
struct SqrtCompute : Sqrt<Tag>, db::ComputeTag {
using base = Sqrt<Tag>;
using return_type = Scalar<DataVector>;
static constexpr auto function = static_cast<void (*)(
const gsl::not_null<return_type*>, const typename Tag::type&) noexcept>(
&sqrt_magnitude);
using argument_tags = tmpl::list<Tag>;
};
} // namespace Tags
|
/*
* Copyright (c) 2017, 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
#include "precompiled.hpp"
#include "logging/logStream.hpp"
#include "memory/allocation.inline.hpp"
#include "runtime/jniHandles.inline.hpp"
#include "runtime/thread.inline.hpp"
#include "runtime/threadSMR.inline.hpp"
#include "runtime/vm_operations.hpp"
#include "services/threadService.hpp"
#include "utilities/copy.hpp"
#include "utilities/globalDefinitions.hpp"
#include "utilities/ostream.hpp"
#include "utilities/resourceHash.hpp"
#include "utilities/vmError.hpp"
Monitor* ThreadsSMRSupport::_delete_lock =
new Monitor(Monitor::special, "Thread_SMR_delete_lock",
false /* allow_vm_block */,
Monitor::_safepoint_check_never);
// The '_cnt', '_max' and '_times" fields are enabled via
// -XX:+EnableThreadSMRStatistics:
// # of parallel threads in _delete_lock->wait().
// Impl note: Hard to imagine > 64K waiting threads so this could be 16-bit,
// but there is no nice 16-bit _FORMAT support.
uint ThreadsSMRSupport::_delete_lock_wait_cnt = 0;
// Max # of parallel threads in _delete_lock->wait().
// Impl note: See _delete_lock_wait_cnt note.
uint ThreadsSMRSupport::_delete_lock_wait_max = 0;
// Flag to indicate when an _delete_lock->notify() is needed.
// Impl note: See _delete_lock_wait_cnt note.
volatile uint ThreadsSMRSupport::_delete_notify = 0;
// # of threads deleted over VM lifetime.
// Impl note: Atomically incremented over VM lifetime so use unsigned for more
// range. Unsigned 64-bit would be more future proof, but 64-bit atomic inc
// isn't available everywhere (or is it?).
volatile uint ThreadsSMRSupport::_deleted_thread_cnt = 0;
// Max time in millis to delete a thread.
// Impl note: 16-bit might be too small on an overloaded machine. Use
// unsigned since this is a time value. Set via Atomic::cmpxchg() in a
// loop for correctness.
volatile uint ThreadsSMRSupport::_deleted_thread_time_max = 0;
// Cumulative time in millis to delete threads.
// Impl note: Atomically added to over VM lifetime so use unsigned for more
// range. Unsigned 64-bit would be more future proof, but 64-bit atomic inc
// isn't available everywhere (or is it?).
volatile uint ThreadsSMRSupport::_deleted_thread_times = 0;
ThreadsList* volatile ThreadsSMRSupport::_java_thread_list = new ThreadsList(0);
// # of ThreadsLists allocated over VM lifetime.
// Impl note: We allocate a new ThreadsList for every thread create and
// every thread delete so we need a bigger type than the
// _deleted_thread_cnt field.
uint64_t ThreadsSMRSupport::_java_thread_list_alloc_cnt = 1;
// # of ThreadsLists freed over VM lifetime.
// Impl note: See _java_thread_list_alloc_cnt note.
uint64_t ThreadsSMRSupport::_java_thread_list_free_cnt = 0;
// Max size ThreadsList allocated.
// Impl note: Max # of threads alive at one time should fit in unsigned 32-bit.
uint ThreadsSMRSupport::_java_thread_list_max = 0;
// Max # of nested ThreadsLists for a thread.
// Impl note: Hard to imagine > 64K nested ThreadsLists so this could be
// 16-bit, but there is no nice 16-bit _FORMAT support.
uint ThreadsSMRSupport::_nested_thread_list_max = 0;
// # of ThreadsListHandles deleted over VM lifetime.
// Impl note: Atomically incremented over VM lifetime so use unsigned for
// more range. There will be fewer ThreadsListHandles than threads so
// unsigned 32-bit should be fine.
volatile uint ThreadsSMRSupport::_tlh_cnt = 0;
// Max time in millis to delete a ThreadsListHandle.
// Impl note: 16-bit might be too small on an overloaded machine. Use
// unsigned since this is a time value. Set via Atomic::cmpxchg() in a
// loop for correctness.
volatile uint ThreadsSMRSupport::_tlh_time_max = 0;
// Cumulative time in millis to delete ThreadsListHandles.
// Impl note: Atomically added to over VM lifetime so use unsigned for more
// range. Unsigned 64-bit would be more future proof, but 64-bit atomic inc
// isn't available everywhere (or is it?).
volatile uint ThreadsSMRSupport::_tlh_times = 0;
ThreadsList* ThreadsSMRSupport::_to_delete_list = NULL;
// # of parallel ThreadsLists on the to-delete list.
// Impl note: Hard to imagine > 64K ThreadsLists needing to be deleted so
// this could be 16-bit, but there is no nice 16-bit _FORMAT support.
uint ThreadsSMRSupport::_to_delete_list_cnt = 0;
// Max # of parallel ThreadsLists on the to-delete list.
// Impl note: See _to_delete_list_cnt note.
uint ThreadsSMRSupport::_to_delete_list_max = 0;
// 'inline' functions first so the definitions are before first use:
inline void ThreadsSMRSupport::add_deleted_thread_times(uint add_value) {
Atomic::add(add_value, &_deleted_thread_times);
}
inline void ThreadsSMRSupport::inc_deleted_thread_cnt() {
Atomic::inc(&_deleted_thread_cnt);
}
inline void ThreadsSMRSupport::inc_java_thread_list_alloc_cnt() {
_java_thread_list_alloc_cnt++;
}
inline void ThreadsSMRSupport::update_deleted_thread_time_max(uint new_value) {
while (true) {
uint cur_value = _deleted_thread_time_max;
if (new_value <= cur_value) {
// No need to update max value so we're done.
break;
}
if (Atomic::cmpxchg(new_value, &_deleted_thread_time_max, cur_value) == cur_value) {
// Updated max value so we're done. Otherwise try it all again.
break;
}
}
}
inline void ThreadsSMRSupport::update_java_thread_list_max(uint new_value) {
if (new_value > _java_thread_list_max) {
_java_thread_list_max = new_value;
}
}
inline ThreadsList* ThreadsSMRSupport::xchg_java_thread_list(ThreadsList* new_list) {
return (ThreadsList*)Atomic::xchg(new_list, &_java_thread_list);
}
// Hash table of pointers found by a scan. Used for collecting hazard
// pointers (ThreadsList references). Also used for collecting JavaThreads
// that are indirectly referenced by hazard ptrs. An instance of this
// class only contains one type of pointer.
//
class ThreadScanHashtable : public CHeapObj<mtThread> {
private:
static bool ptr_equals(void * const& s1, void * const& s2) {
return s1 == s2;
}
static unsigned int ptr_hash(void * const& s1) {
// 2654435761 = 2^32 * Phi (golden ratio)
return (unsigned int)(((uint32_t)(uintptr_t)s1) * 2654435761u);
}
int _table_size;
// ResourceHashtable SIZE is specified at compile time so our
// dynamic _table_size is unused for now; 1031 is the first prime
// after 1024.
typedef ResourceHashtable<void *, int, &ThreadScanHashtable::ptr_hash,
&ThreadScanHashtable::ptr_equals, 1031,
ResourceObj::C_HEAP, mtThread> PtrTable;
PtrTable * _ptrs;
public:
// ResourceHashtable is passed to various functions and populated in
// different places so we allocate it using C_HEAP to make it immune
// from any ResourceMarks that happen to be in the code paths.
ThreadScanHashtable(int table_size) : _table_size(table_size), _ptrs(new (ResourceObj::C_HEAP, mtThread) PtrTable()) {}
~ThreadScanHashtable() { delete _ptrs; }
bool has_entry(void *pointer) {
int *val_ptr = _ptrs->get(pointer);
return val_ptr != NULL && *val_ptr == 1;
}
void add_entry(void *pointer) {
_ptrs->put(pointer, 1);
}
};
// Closure to gather JavaThreads indirectly referenced by hazard ptrs
// (ThreadsList references) into a hash table. This closure handles part 2
// of the dance - adding all the JavaThreads referenced by the hazard
// pointer (ThreadsList reference) to the hash table.
//
class AddThreadHazardPointerThreadClosure : public ThreadClosure {
private:
ThreadScanHashtable *_table;
public:
AddThreadHazardPointerThreadClosure(ThreadScanHashtable *table) : _table(table) {}
virtual void do_thread(Thread *thread) {
if (!_table->has_entry((void*)thread)) {
// The same JavaThread might be on more than one ThreadsList or
// more than one thread might be using the same ThreadsList. In
// either case, we only need a single entry for a JavaThread.
_table->add_entry((void*)thread);
}
}
};
// Closure to gather JavaThreads indirectly referenced by hazard ptrs
// (ThreadsList references) into a hash table. This closure handles part 1
// of the dance - hazard ptr chain walking and dispatch to another
// closure.
//
class ScanHazardPtrGatherProtectedThreadsClosure : public ThreadClosure {
private:
ThreadScanHashtable *_table;
public:
ScanHazardPtrGatherProtectedThreadsClosure(ThreadScanHashtable *table) : _table(table) {}
virtual void do_thread(Thread *thread) {
assert_locked_or_safepoint(Threads_lock);
if (thread == NULL) return;
// This code races with ThreadsSMRSupport::acquire_stable_list() which
// is lock-free so we have to handle some special situations.
//
ThreadsList *current_list = NULL;
while (true) {
current_list = thread->get_threads_hazard_ptr();
// No hazard ptr so nothing more to do.
if (current_list == NULL) {
return;
}
// If the hazard ptr is verified as stable (since it is not tagged),
// then it is safe to use.
if (!Thread::is_hazard_ptr_tagged(current_list)) break;
// The hazard ptr is tagged as not yet verified as being stable
// so we are racing with acquire_stable_list(). This exchange
// attempts to invalidate the hazard ptr. If we win the race,
// then we can ignore this unstable hazard ptr and the other
// thread will retry the attempt to publish a stable hazard ptr.
// If we lose the race, then we retry our attempt to look at the
// hazard ptr.
if (thread->cmpxchg_threads_hazard_ptr(NULL, current_list) == current_list) return;
}
// The current JavaThread has a hazard ptr (ThreadsList reference)
// which might be _java_thread_list or it might be an older
// ThreadsList that has been removed but not freed. In either case,
// the hazard ptr is protecting all the JavaThreads on that
// ThreadsList.
AddThreadHazardPointerThreadClosure add_cl(_table);
current_list->threads_do(&add_cl);
}
};
// Closure to gather hazard ptrs (ThreadsList references) into a hash table.
//
class ScanHazardPtrGatherThreadsListClosure : public ThreadClosure {
private:
ThreadScanHashtable *_table;
public:
ScanHazardPtrGatherThreadsListClosure(ThreadScanHashtable *table) : _table(table) {}
virtual void do_thread(Thread* thread) {
assert_locked_or_safepoint(Threads_lock);
if (thread == NULL) return;
ThreadsList *threads = thread->get_threads_hazard_ptr();
if (threads == NULL) {
return;
}
// In this closure we always ignore the tag that might mark this
// hazard ptr as not yet verified. If we happen to catch an
// unverified hazard ptr that is subsequently discarded (not
// published), then the only side effect is that we might keep a
// to-be-deleted ThreadsList alive a little longer.
threads = Thread::untag_hazard_ptr(threads);
if (!_table->has_entry((void*)threads)) {
_table->add_entry((void*)threads);
}
}
};
// Closure to print JavaThreads that have a hazard ptr (ThreadsList
// reference) that contains an indirect reference to a specific JavaThread.
//
class ScanHazardPtrPrintMatchingThreadsClosure : public ThreadClosure {
private:
JavaThread *_thread;
public:
ScanHazardPtrPrintMatchingThreadsClosure(JavaThread *thread) : _thread(thread) {}
virtual void do_thread(Thread *thread) {
assert_locked_or_safepoint(Threads_lock);
if (thread == NULL) return;
ThreadsList *current_list = thread->get_threads_hazard_ptr();
if (current_list == NULL) {
return;
}
// If the hazard ptr is unverified, then ignore it.
if (Thread::is_hazard_ptr_tagged(current_list)) return;
// The current JavaThread has a hazard ptr (ThreadsList reference)
// which might be _java_thread_list or it might be an older
// ThreadsList that has been removed but not freed. In either case,
// the hazard ptr is protecting all the JavaThreads on that
// ThreadsList, but we only care about matching a specific JavaThread.
JavaThreadIterator jti(current_list);
for (JavaThread *p = jti.first(); p != NULL; p = jti.next()) {
if (p == _thread) {
log_debug(thread, smr)("tid=" UINTX_FORMAT ": ThreadsSMRSupport::smr_delete: thread1=" INTPTR_FORMAT " has a hazard pointer for thread2=" INTPTR_FORMAT, os::current_thread_id(), p2i(thread), p2i(_thread));
break;
}
}
}
};
// Closure to determine if the specified JavaThread is found by
// threads_do().
//
class VerifyHazardPtrThreadClosure : public ThreadClosure {
private:
bool _found;
Thread *_self;
public:
VerifyHazardPtrThreadClosure(Thread *self) : _found(false), _self(self) {}
bool found() const { return _found; }
virtual void do_thread(Thread *thread) {
if (thread == _self) {
_found = true;
}
}
};
// Acquire a stable ThreadsList.
//
void SafeThreadsListPtr::acquire_stable_list() {
assert(_thread != NULL, "sanity check");
_needs_release = true;
_previous = _thread->_threads_list_ptr;
_thread->_threads_list_ptr = this;
if (_thread->get_threads_hazard_ptr() == NULL) {
// The typical case is first.
acquire_stable_list_fast_path();
return;
}
// The nested case is rare.
acquire_stable_list_nested_path();
}
// Fast path way to acquire a stable ThreadsList.
//
void SafeThreadsListPtr::acquire_stable_list_fast_path() {
assert(_thread != NULL, "sanity check");
assert(_thread->get_threads_hazard_ptr() == NULL, "sanity check");
ThreadsList* threads;
// Stable recording of a hazard ptr for SMR. This code does not use
// locks so its use of the _smr_java_thread_list & _threads_hazard_ptr
// fields is racy relative to code that uses those fields with locks.
// OrderAccess and Atomic functions are used to deal with those races.
//
while (true) {
threads = ThreadsSMRSupport::get_java_thread_list();
// Publish a tagged hazard ptr to denote that the hazard ptr is not
// yet verified as being stable. Due to the fence after the hazard
// ptr write, it will be sequentially consistent w.r.t. the
// sequentially consistent writes of the ThreadsList, even on
// non-multiple copy atomic machines where stores can be observed
// in different order from different observer threads.
ThreadsList* unverified_threads = Thread::tag_hazard_ptr(threads);
_thread->set_threads_hazard_ptr(unverified_threads);
// If _smr_java_thread_list has changed, we have lost a race with
// Threads::add() or Threads::remove() and have to try again.
if (ThreadsSMRSupport::get_java_thread_list() != threads) {
continue;
}
// We try to remove the tag which will verify the hazard ptr as
// being stable. This exchange can race with a scanning thread
// which might invalidate the tagged hazard ptr to keep it from
// being followed to access JavaThread ptrs. If we lose the race,
// we simply retry. If we win the race, then the stable hazard
// ptr is officially published.
if (_thread->cmpxchg_threads_hazard_ptr(threads, unverified_threads) == unverified_threads) {
break;
}
}
// A stable hazard ptr has been published letting other threads know
// that the ThreadsList and the JavaThreads reachable from this list
// are protected and hence they should not be deleted until everyone
// agrees it is safe to do so.
_list = threads;
verify_hazard_ptr_scanned();
}
// Acquire a nested stable ThreadsList; this is rare so it uses
// reference counting.
//
void SafeThreadsListPtr::acquire_stable_list_nested_path() {
assert(_thread != NULL, "sanity check");
assert(_thread->get_threads_hazard_ptr() != NULL,
"cannot have a NULL regular hazard ptr when acquiring a nested hazard ptr");
// The thread already has a hazard ptr (ThreadsList ref) so we need
// to create a nested ThreadsListHandle with the current ThreadsList
// since it might be different than our current hazard ptr. To remedy
// the situation, the ThreadsList pointed to by the pre-existing
// stable hazard ptr is reference counted before the hazard ptr may
// be released and moved to a new ThreadsList. The old ThreadsList
// is remembered in the ThreadsListHandle.
ThreadsList* current_list = _previous->_list;
if (EnableThreadSMRStatistics) {
_thread->inc_nested_threads_hazard_ptr_cnt();
}
current_list->inc_nested_handle_cnt();
_previous->_has_ref_count = true; // promote SafeThreadsListPtr to be reference counted
_thread->_threads_hazard_ptr = NULL; // clear the hazard ptr so we can go through the fast path below
if (EnableThreadSMRStatistics && _thread->nested_threads_hazard_ptr_cnt() > ThreadsSMRSupport::_nested_thread_list_max) {
ThreadsSMRSupport::_nested_thread_list_max = _thread->nested_threads_hazard_ptr_cnt();
}
acquire_stable_list_fast_path();
verify_hazard_ptr_scanned();
log_debug(thread, smr)("tid=" UINTX_FORMAT ": SafeThreadsListPtr::acquire_stable_list: add nested list pointer to ThreadsList=" INTPTR_FORMAT, os::current_thread_id(), p2i(_list));
}
// Release a stable ThreadsList.
//
void SafeThreadsListPtr::release_stable_list() {
assert(_thread != NULL, "sanity check");
assert(_thread->_threads_list_ptr == this, "sanity check");
_thread->_threads_list_ptr = _previous;
if (_has_ref_count) {
// If a SafeThreadsListPtr has been promoted to use reference counting
// due to nesting of ThreadsListHandles, then the reference count must be
// decremented, at which point it may be freed. The forgotten value of
// the list no longer matters at this point and should already be NULL.
assert(_thread->get_threads_hazard_ptr() == NULL, "sanity check");
if (EnableThreadSMRStatistics) {
_thread->dec_nested_threads_hazard_ptr_cnt();
}
_list->dec_nested_handle_cnt();
log_debug(thread, smr)("tid=" UINTX_FORMAT ": SafeThreadsListPtr::release_stable_list: delete nested list pointer to ThreadsList=" INTPTR_FORMAT, os::current_thread_id(), p2i(_list));
} else {
// The normal case: a leaf ThreadsListHandle. This merely requires setting
// the thread hazard ptr back to NULL.
assert(_thread->get_threads_hazard_ptr() != NULL, "sanity check");
_thread->set_threads_hazard_ptr(NULL);
}
// After releasing the hazard ptr, other threads may go ahead and
// free up some memory temporarily used by a ThreadsList snapshot.
// We use double-check locking to reduce traffic on the system
// wide Thread-SMR delete_lock.
if (ThreadsSMRSupport::delete_notify()) {
// An exiting thread might be waiting in smr_delete(); we need to
// check with delete_lock to be sure.
ThreadsSMRSupport::release_stable_list_wake_up(_has_ref_count);
}
}
// Verify that the stable hazard ptr used to safely keep threads
// alive is scanned by threads_do() which is a key piece of honoring
// the Thread-SMR protocol.
void SafeThreadsListPtr::verify_hazard_ptr_scanned() {
#ifdef ASSERT
assert(_list != NULL, "_list must not be NULL");
// The closure will attempt to verify that the calling thread can
// be found by threads_do() on the specified ThreadsList. If it
// is successful, then the specified ThreadsList was acquired as
// a stable hazard ptr by the calling thread in a way that honored
// the Thread-SMR protocol.
//
// If the calling thread cannot be found by threads_do() and if
// it is not the shutdown thread, then the calling thread is not
// honoring the Thread-SMR ptotocol. This means that the specified
// ThreadsList is not a stable hazard ptr and can be freed by
// another thread from the to-be-deleted list at any time.
//
// Note: The shutdown thread has removed itself from the Threads
// list and is safe to have a waiver from this check because
// VM_Exit::_shutdown_thread is not set until after the VMThread
// has started the final safepoint which holds the Threads_lock
// for the remainder of the VM's life.
//
VerifyHazardPtrThreadClosure cl(_thread);
ThreadsSMRSupport::threads_do(&cl, _list);
// If the calling thread is not honoring the Thread-SMR protocol,
// then we will either crash in threads_do() above because 'threads'
// was freed by another thread or we will fail the assert() below.
// In either case, we won't get past this point with a badly placed
// ThreadsListHandle.
assert(cl.found() || _thread == VM_Exit::shutdown_thread(), "Acquired a ThreadsList snapshot from a thread not recognized by the Thread-SMR protocol.");
#endif
}
// 'entries + 1' so we always have at least one entry.
ThreadsList::ThreadsList(int entries) :
_length(entries),
_next_list(NULL),
_threads(NEW_C_HEAP_ARRAY(JavaThread*, entries + 1, mtThread)),
_nested_handle_cnt(0)
{
*(JavaThread**)(_threads + entries) = NULL; // Make sure the extra entry is NULL.
}
ThreadsList::~ThreadsList() {
FREE_C_HEAP_ARRAY(JavaThread*, _threads);
}
// Add a JavaThread to a ThreadsList. The returned ThreadsList is a
// new copy of the specified ThreadsList with the specified JavaThread
// appended to the end.
ThreadsList *ThreadsList::add_thread(ThreadsList *list, JavaThread *java_thread) {
const uint index = list->_length;
const uint new_length = index + 1;
const uint head_length = index;
ThreadsList *const new_list = new ThreadsList(new_length);
if (head_length > 0) {
Copy::disjoint_words((HeapWord*)list->_threads, (HeapWord*)new_list->_threads, head_length);
}
*(JavaThread**)(new_list->_threads + index) = java_thread;
return new_list;
}
void ThreadsList::dec_nested_handle_cnt() {
// The decrement needs to be MO_ACQ_REL. At the moment, the Atomic::dec
// backend on PPC does not yet conform to these requirements. Therefore
// the decrement is simulated with an Atomic::sub(1, &addr).
// Without this MO_ACQ_REL Atomic::dec simulation, the nested SMR mechanism
// is not generally safe to use.
Atomic::sub(1, &_nested_handle_cnt);
}
int ThreadsList::find_index_of_JavaThread(JavaThread *target) {
if (target == NULL) {
return -1;
}
for (uint i = 0; i < length(); i++) {
if (target == thread_at(i)) {
return (int)i;
}
}
return -1;
}
JavaThread* ThreadsList::find_JavaThread_from_java_tid(jlong java_tid) const {
for (uint i = 0; i < length(); i++) {
JavaThread* thread = thread_at(i);
oop tobj = thread->threadObj();
// Ignore the thread if it hasn't run yet, has exited
// or is starting to exit.
if (tobj != NULL && !thread->is_exiting() &&
java_tid == java_lang_Thread::thread_id(tobj)) {
// found a match
return thread;
}
}
return NULL;
}
void ThreadsList::inc_nested_handle_cnt() {
// The increment needs to be MO_SEQ_CST. At the moment, the Atomic::inc
// backend on PPC does not yet conform to these requirements. Therefore
// the increment is simulated with a load phi; cas phi + 1; loop.
// Without this MO_SEQ_CST Atomic::inc simulation, the nested SMR mechanism
// is not generally safe to use.
intx sample = OrderAccess::load_acquire(&_nested_handle_cnt);
for (;;) {
if (Atomic::cmpxchg(sample + 1, &_nested_handle_cnt, sample) == sample) {
return;
} else {
sample = OrderAccess::load_acquire(&_nested_handle_cnt);
}
}
}
bool ThreadsList::includes(const JavaThread * const p) const {
if (p == NULL) {
return false;
}
for (uint i = 0; i < length(); i++) {
if (thread_at(i) == p) {
return true;
}
}
return false;
}
// Remove a JavaThread from a ThreadsList. The returned ThreadsList is a
// new copy of the specified ThreadsList with the specified JavaThread
// removed.
ThreadsList *ThreadsList::remove_thread(ThreadsList* list, JavaThread* java_thread) {
assert(list->_length > 0, "sanity");
uint i = (uint)list->find_index_of_JavaThread(java_thread);
assert(i < list->_length, "did not find JavaThread on the list");
const uint index = i;
const uint new_length = list->_length - 1;
const uint head_length = index;
const uint tail_length = (new_length >= index) ? (new_length - index) : 0;
ThreadsList *const new_list = new ThreadsList(new_length);
if (head_length > 0) {
Copy::disjoint_words((HeapWord*)list->_threads, (HeapWord*)new_list->_threads, head_length);
}
if (tail_length > 0) {
Copy::disjoint_words((HeapWord*)list->_threads + index + 1, (HeapWord*)new_list->_threads + index, tail_length);
}
return new_list;
}
ThreadsListHandle::ThreadsListHandle(Thread *self) : _list_ptr(self, /* acquire */ true) {
assert(self == Thread::current(), "sanity check");
if (EnableThreadSMRStatistics) {
_timer.start();
}
}
ThreadsListHandle::~ThreadsListHandle() {
if (EnableThreadSMRStatistics) {
_timer.stop();
uint millis = (uint)_timer.milliseconds();
ThreadsSMRSupport::update_tlh_stats(millis);
}
}
// Convert an internal thread reference to a JavaThread found on the
// associated ThreadsList. This ThreadsListHandle "protects" the
// returned JavaThread *.
//
// If thread_oop_p is not NULL, then the caller wants to use the oop
// after this call so the oop is returned. On success, *jt_pp is set
// to the converted JavaThread * and true is returned. On error,
// returns false.
//
bool ThreadsListHandle::cv_internal_thread_to_JavaThread(jobject jthread,
JavaThread ** jt_pp,
oop * thread_oop_p) {
assert(this->list() != NULL, "must have a ThreadsList");
assert(jt_pp != NULL, "must have a return JavaThread pointer");
// thread_oop_p is optional so no assert()
// The JVM_* interfaces don't allow a NULL thread parameter; JVM/TI
// allows a NULL thread parameter to signify "current thread" which
// allows us to avoid calling cv_external_thread_to_JavaThread().
// The JVM_* interfaces have no such leeway.
oop thread_oop = JNIHandles::resolve_non_null(jthread);
// Looks like an oop at this point.
if (thread_oop_p != NULL) {
// Return the oop to the caller; the caller may still want
// the oop even if this function returns false.
*thread_oop_p = thread_oop;
}
JavaThread *java_thread = java_lang_Thread::thread(thread_oop);
if (java_thread == NULL) {
// The java.lang.Thread does not contain a JavaThread * so it has
// not yet run or it has died.
return false;
}
// Looks like a live JavaThread at this point.
if (java_thread != JavaThread::current()) {
// jthread is not for the current JavaThread so have to verify
// the JavaThread * against the ThreadsList.
if (EnableThreadSMRExtraValidityChecks && !includes(java_thread)) {
// Not on the JavaThreads list so it is not alive.
return false;
}
}
// Return a live JavaThread that is "protected" by the
// ThreadsListHandle in the caller.
*jt_pp = java_thread;
return true;
}
void ThreadsSMRSupport::add_thread(JavaThread *thread){
ThreadsList *new_list = ThreadsList::add_thread(get_java_thread_list(), thread);
if (EnableThreadSMRStatistics) {
inc_java_thread_list_alloc_cnt();
update_java_thread_list_max(new_list->length());
}
// Initial _java_thread_list will not generate a "Threads::add" mesg.
log_debug(thread, smr)("tid=" UINTX_FORMAT ": Threads::add: new ThreadsList=" INTPTR_FORMAT, os::current_thread_id(), p2i(new_list));
ThreadsList *old_list = xchg_java_thread_list(new_list);
free_list(old_list);
}
// set_delete_notify() and clear_delete_notify() are called
// under the protection of the delete_lock, but we also use an
// Atomic operation to ensure the memory update is seen earlier than
// when the delete_lock is dropped.
//
void ThreadsSMRSupport::clear_delete_notify() {
Atomic::dec(&_delete_notify);
}
bool ThreadsSMRSupport::delete_notify() {
// Use load_acquire() in order to see any updates to _delete_notify
// earlier than when delete_lock is grabbed.
return (OrderAccess::load_acquire(&_delete_notify) != 0);
}
// Safely free a ThreadsList after a Threads::add() or Threads::remove().
// The specified ThreadsList may not get deleted during this call if it
// is still in-use (referenced by a hazard ptr). Other ThreadsLists
// in the chain may get deleted by this call if they are no longer in-use.
void ThreadsSMRSupport::free_list(ThreadsList* threads) {
assert_locked_or_safepoint(Threads_lock);
threads->set_next_list(_to_delete_list);
_to_delete_list = threads;
if (EnableThreadSMRStatistics) {
_to_delete_list_cnt++;
if (_to_delete_list_cnt > _to_delete_list_max) {
_to_delete_list_max = _to_delete_list_cnt;
}
}
// Hash table size should be first power of two higher than twice the length of the ThreadsList
int hash_table_size = MIN2((int)get_java_thread_list()->length(), 32) << 1;
hash_table_size--;
hash_table_size |= hash_table_size >> 1;
hash_table_size |= hash_table_size >> 2;
hash_table_size |= hash_table_size >> 4;
hash_table_size |= hash_table_size >> 8;
hash_table_size |= hash_table_size >> 16;
hash_table_size++;
// Gather a hash table of the current hazard ptrs:
ThreadScanHashtable *scan_table = new ThreadScanHashtable(hash_table_size);
ScanHazardPtrGatherThreadsListClosure scan_cl(scan_table);
threads_do(&scan_cl);
OrderAccess::acquire(); // Must order reads of hazard ptr before reads of
// nested reference counters
// Walk through the linked list of pending freeable ThreadsLists
// and free the ones that are not referenced from hazard ptrs.
ThreadsList* current = _to_delete_list;
ThreadsList* prev = NULL;
ThreadsList* next = NULL;
bool threads_is_freed = false;
while (current != NULL) {
next = current->next_list();
if (!scan_table->has_entry((void*)current) && current->_nested_handle_cnt == 0) {
// This ThreadsList is not referenced by a hazard ptr.
if (prev != NULL) {
prev->set_next_list(next);
}
if (_to_delete_list == current) {
_to_delete_list = next;
}
log_debug(thread, smr)("tid=" UINTX_FORMAT ": ThreadsSMRSupport::free_list: threads=" INTPTR_FORMAT " is freed.", os::current_thread_id(), p2i(current));
if (current == threads) threads_is_freed = true;
delete current;
if (EnableThreadSMRStatistics) {
_java_thread_list_free_cnt++;
_to_delete_list_cnt--;
}
} else {
prev = current;
}
current = next;
}
if (!threads_is_freed) {
// Only report "is not freed" on the original call to
// free_list() for this ThreadsList.
log_debug(thread, smr)("tid=" UINTX_FORMAT ": ThreadsSMRSupport::free_list: threads=" INTPTR_FORMAT " is not freed.", os::current_thread_id(), p2i(threads));
}
delete scan_table;
}
// Return true if the specified JavaThread is protected by a hazard
// pointer (ThreadsList reference). Otherwise, returns false.
//
bool ThreadsSMRSupport::is_a_protected_JavaThread(JavaThread *thread) {
assert_locked_or_safepoint(Threads_lock);
// Hash table size should be first power of two higher than twice
// the length of the Threads list.
int hash_table_size = MIN2((int)get_java_thread_list()->length(), 32) << 1;
hash_table_size--;
hash_table_size |= hash_table_size >> 1;
hash_table_size |= hash_table_size >> 2;
hash_table_size |= hash_table_size >> 4;
hash_table_size |= hash_table_size >> 8;
hash_table_size |= hash_table_size >> 16;
hash_table_size++;
// Gather a hash table of the JavaThreads indirectly referenced by
// hazard ptrs.
ThreadScanHashtable *scan_table = new ThreadScanHashtable(hash_table_size);
ScanHazardPtrGatherProtectedThreadsClosure scan_cl(scan_table);
threads_do(&scan_cl);
OrderAccess::acquire(); // Must order reads of hazard ptr before reads of
// nested reference counters
// Walk through the linked list of pending freeable ThreadsLists
// and include the ones that are currently in use by a nested
// ThreadsListHandle in the search set.
ThreadsList* current = _to_delete_list;
while (current != NULL) {
if (current->_nested_handle_cnt != 0) {
// 'current' is in use by a nested ThreadsListHandle so the hazard
// ptr is protecting all the JavaThreads on that ThreadsList.
AddThreadHazardPointerThreadClosure add_cl(scan_table);
current->threads_do(&add_cl);
}
current = current->next_list();
}
bool thread_is_protected = false;
if (scan_table->has_entry((void*)thread)) {
thread_is_protected = true;
}
delete scan_table;
return thread_is_protected;
}
// Wake up portion of the release stable ThreadsList protocol;
// uses the delete_lock().
//
void ThreadsSMRSupport::release_stable_list_wake_up(bool is_nested) {
const char* log_str = is_nested ? "nested hazard ptr" : "regular hazard ptr";
// Note: delete_lock is held in smr_delete() for the entire
// hazard ptr search so that we do not lose this notify() if
// the exiting thread has to wait. That code path also holds
// Threads_lock (which was grabbed before delete_lock) so that
// threads_do() can be called. This means the system can't start a
// safepoint which means this thread can't take too long to get to
// a safepoint because of being blocked on delete_lock.
//
MonitorLockerEx ml(ThreadsSMRSupport::delete_lock(), Monitor::_no_safepoint_check_flag);
if (ThreadsSMRSupport::delete_notify()) {
// Notify any exiting JavaThreads that are waiting in smr_delete()
// that we've released a ThreadsList.
ml.notify_all();
log_debug(thread, smr)("tid=" UINTX_FORMAT ": ThreadsSMRSupport::release_stable_list notified %s", os::current_thread_id(), log_str);
}
}
void ThreadsSMRSupport::remove_thread(JavaThread *thread) {
ThreadsList *new_list = ThreadsList::remove_thread(ThreadsSMRSupport::get_java_thread_list(), thread);
if (EnableThreadSMRStatistics) {
ThreadsSMRSupport::inc_java_thread_list_alloc_cnt();
// This list is smaller so no need to check for a "longest" update.
}
// Final _java_thread_list will not generate a "Threads::remove" mesg.
log_debug(thread, smr)("tid=" UINTX_FORMAT ": Threads::remove: new ThreadsList=" INTPTR_FORMAT, os::current_thread_id(), p2i(new_list));
ThreadsList *old_list = ThreadsSMRSupport::xchg_java_thread_list(new_list);
ThreadsSMRSupport::free_list(old_list);
}
// See note for clear_delete_notify().
//
void ThreadsSMRSupport::set_delete_notify() {
Atomic::inc(&_delete_notify);
}
// Safely delete a JavaThread when it is no longer in use by a
// ThreadsListHandle.
//
void ThreadsSMRSupport::smr_delete(JavaThread *thread) {
assert(!Threads_lock->owned_by_self(), "sanity");
bool has_logged_once = false;
elapsedTimer timer;
if (EnableThreadSMRStatistics) {
timer.start();
}
while (true) {
{
// No safepoint check because this JavaThread is not on the
// Threads list.
MutexLockerEx ml(Threads_lock, Mutex::_no_safepoint_check_flag);
// Cannot use a MonitorLockerEx helper here because we have
// to drop the Threads_lock first if we wait.
ThreadsSMRSupport::delete_lock()->lock_without_safepoint_check();
// Set the delete_notify flag after we grab delete_lock
// and before we scan hazard ptrs because we're doing
// double-check locking in release_stable_list().
ThreadsSMRSupport::set_delete_notify();
if (!is_a_protected_JavaThread(thread)) {
// This is the common case.
ThreadsSMRSupport::clear_delete_notify();
ThreadsSMRSupport::delete_lock()->unlock();
break;
}
if (!has_logged_once) {
has_logged_once = true;
log_debug(thread, smr)("tid=" UINTX_FORMAT ": ThreadsSMRSupport::smr_delete: thread=" INTPTR_FORMAT " is not deleted.", os::current_thread_id(), p2i(thread));
if (log_is_enabled(Debug, os, thread)) {
ScanHazardPtrPrintMatchingThreadsClosure scan_cl(thread);
threads_do(&scan_cl);
ThreadsList* current = _to_delete_list;
while (current != NULL) {
if (current->_nested_handle_cnt != 0 && current->includes(thread)) {
log_debug(thread, smr)("tid=" UINTX_FORMAT ": ThreadsSMRSupport::smr_delete: found nested hazard pointer to thread=" INTPTR_FORMAT, os::current_thread_id(), p2i(thread));
}
current = current->next_list();
}
}
}
} // We have to drop the Threads_lock to wait or delete the thread
if (EnableThreadSMRStatistics) {
_delete_lock_wait_cnt++;
if (_delete_lock_wait_cnt > _delete_lock_wait_max) {
_delete_lock_wait_max = _delete_lock_wait_cnt;
}
}
// Wait for a release_stable_list() call before we check again. No
// safepoint check, no timeout, and not as suspend equivalent flag
// because this JavaThread is not on the Threads list.
ThreadsSMRSupport::delete_lock()->wait(Mutex::_no_safepoint_check_flag, 0,
!Mutex::_as_suspend_equivalent_flag);
if (EnableThreadSMRStatistics) {
_delete_lock_wait_cnt--;
}
ThreadsSMRSupport::clear_delete_notify();
ThreadsSMRSupport::delete_lock()->unlock();
// Retry the whole scenario.
}
if (ThreadLocalHandshakes) {
// The thread is about to be deleted so cancel any handshake.
thread->cancel_handshake();
}
delete thread;
if (EnableThreadSMRStatistics) {
timer.stop();
uint millis = (uint)timer.milliseconds();
ThreadsSMRSupport::inc_deleted_thread_cnt();
ThreadsSMRSupport::add_deleted_thread_times(millis);
ThreadsSMRSupport::update_deleted_thread_time_max(millis);
}
log_debug(thread, smr)("tid=" UINTX_FORMAT ": ThreadsSMRSupport::smr_delete: thread=" INTPTR_FORMAT " is deleted.", os::current_thread_id(), p2i(thread));
}
// Apply the closure to all threads in the system, with a snapshot of
// all JavaThreads provided by the list parameter.
void ThreadsSMRSupport::threads_do(ThreadClosure *tc, ThreadsList *list) {
list->threads_do(tc);
Threads::non_java_threads_do(tc);
}
// Apply the closure to all threads in the system.
void ThreadsSMRSupport::threads_do(ThreadClosure *tc) {
threads_do(tc, _java_thread_list);
}
// Debug, logging, and printing stuff at the end:
// Print SMR info for a SafeThreadsListPtr to a given output stream.
void SafeThreadsListPtr::print_on(outputStream* st) {
if (this == _thread->_threads_list_ptr) {
// The top level hazard ptr.
st->print(" _threads_hazard_ptr=" INTPTR_FORMAT, p2i(_list));
} else {
// Nested hazard ptrs.
st->print(", _nested_threads_hazard_ptr=" INTPTR_FORMAT, p2i(_list));
}
}
// Log Threads class SMR info.
void ThreadsSMRSupport::log_statistics() {
LogTarget(Info, thread, smr) log;
if (log.is_enabled()) {
LogStream out(log);
print_info_on(&out);
}
}
// Print SMR info for a thread to a given output stream.
void ThreadsSMRSupport::print_info_on(const Thread* thread, outputStream* st) {
if (thread->_threads_hazard_ptr != NULL) {
st->print(" _threads_hazard_ptr=" INTPTR_FORMAT, p2i(thread->_threads_hazard_ptr));
}
if (EnableThreadSMRStatistics && thread->_threads_list_ptr != NULL) {
// The count is only interesting if we have a _threads_list_ptr.
st->print(", _nested_threads_hazard_ptr_cnt=%u", thread->_nested_threads_hazard_ptr_cnt);
}
if (SafepointSynchronize::is_at_safepoint() || Thread::current() == thread) {
// It is only safe to walk the list if we're at a safepoint or the
// calling thread is walking its own list.
SafeThreadsListPtr* current = thread->_threads_list_ptr;
if (current != NULL) {
// Skip the top nesting level as it is always printed above.
current = current->previous();
}
while (current != NULL) {
current->print_on(st);
current = current->previous();
}
}
}
// Print Threads class SMR info.
void ThreadsSMRSupport::print_info_on(outputStream* st) {
// Only grab the Threads_lock if we don't already own it
// and if we are not reporting an error.
MutexLockerEx ml((Threads_lock->owned_by_self() || VMError::is_error_reported()) ? NULL : Threads_lock);
st->print_cr("Threads class SMR info:");
st->print_cr("_java_thread_list=" INTPTR_FORMAT ", length=%u, "
"elements={", p2i(_java_thread_list),
_java_thread_list->length());
print_info_elements_on(st, _java_thread_list);
st->print_cr("}");
if (_to_delete_list != NULL) {
st->print_cr("_to_delete_list=" INTPTR_FORMAT ", length=%u, "
"elements={", p2i(_to_delete_list),
_to_delete_list->length());
print_info_elements_on(st, _to_delete_list);
st->print_cr("}");
for (ThreadsList *t_list = _to_delete_list->next_list();
t_list != NULL; t_list = t_list->next_list()) {
st->print("next-> " INTPTR_FORMAT ", length=%u, "
"elements={", p2i(t_list), t_list->length());
print_info_elements_on(st, t_list);
st->print_cr("}");
}
}
if (!EnableThreadSMRStatistics) {
return;
}
st->print_cr("_java_thread_list_alloc_cnt=" UINT64_FORMAT ", "
"_java_thread_list_free_cnt=" UINT64_FORMAT ", "
"_java_thread_list_max=%u, "
"_nested_thread_list_max=%u",
_java_thread_list_alloc_cnt,
_java_thread_list_free_cnt,
_java_thread_list_max,
_nested_thread_list_max);
if (_tlh_cnt > 0) {
st->print_cr("_tlh_cnt=%u"
", _tlh_times=%u"
", avg_tlh_time=%0.2f"
", _tlh_time_max=%u",
_tlh_cnt, _tlh_times,
((double) _tlh_times / _tlh_cnt),
_tlh_time_max);
}
if (_deleted_thread_cnt > 0) {
st->print_cr("_deleted_thread_cnt=%u"
", _deleted_thread_times=%u"
", avg_deleted_thread_time=%0.2f"
", _deleted_thread_time_max=%u",
_deleted_thread_cnt, _deleted_thread_times,
((double) _deleted_thread_times / _deleted_thread_cnt),
_deleted_thread_time_max);
}
st->print_cr("_delete_lock_wait_cnt=%u, _delete_lock_wait_max=%u",
_delete_lock_wait_cnt, _delete_lock_wait_max);
st->print_cr("_to_delete_list_cnt=%u, _to_delete_list_max=%u",
_to_delete_list_cnt, _to_delete_list_max);
}
// Print ThreadsList elements (4 per line).
void ThreadsSMRSupport::print_info_elements_on(outputStream* st, ThreadsList* t_list) {
uint cnt = 0;
JavaThreadIterator jti(t_list);
for (JavaThread *jt = jti.first(); jt != NULL; jt = jti.next()) {
st->print(INTPTR_FORMAT, p2i(jt));
if (cnt < t_list->length() - 1) {
// Separate with comma or comma-space except for the last one.
if (((cnt + 1) % 4) == 0) {
// Four INTPTR_FORMAT fit on an 80 column line so end the
// current line with just a comma.
st->print_cr(",");
} else {
// Not the last one on the current line so use comma-space:
st->print(", ");
}
} else {
// Last one so just end the current line.
st->cr();
}
cnt++;
}
}
|
//
// RemotePhotoTool - remote camera control software
// Copyright (C) 2008-2015 Michael Fink
//
/// \file ImagePropertyRibbonCombobox.hpp Image property ribbon combobox
//
#pragma once
// includes
#include "ImageProperty.hpp"
#include "IImagePropertyControl.hpp"
#include "RemoteReleaseControl.hpp"
#include "CameraException.hpp"
#include "CameraErrorDlg.hpp"
#include <ulib/thread/LightweightMutex.hpp>
// forward references
class MainFrame;
/// interface to combobox placed on a ribbon
class IRibbonCombobox
{
public:
/// dtor
virtual ~IRibbonCombobox() {}
/// called to query category text for category number
virtual LPCWSTR OnRibbonQueryCategoryText(UINT32 uCat) = 0;
/// called to query item category for item
virtual UINT32 OnRibbonQueryItemCategory(UINT32 uItem) = 0;
/// called to query item text for item
virtual LPCWSTR OnRibbonQueryItemText(UINT32 uItem) = 0;
/// called to query currently selected item
virtual bool OnRibbonQuerySelectedItem(UINT32& uSel) = 0;
/// called to query item image for item
virtual HBITMAP OnRibbonQueryItemImage(UINT32 uItem) = 0;
};
/// macro used in message map to specify handler for image property combobox
#define RIBBON_COMBOBOX_IMAGE_PROPERTY(wID, control) \
RIBBON_COMBO_CONTROL_HANDLER(wID, ##control.OnRibbonComboSelChanged)
/// ribbon combobox containing image property (and possible values to choose from)
template <UINT wID, T_enImagePropertyType enImagePropertyType>
class ImagePropertyRibbonCombobox :
public IRibbonCombobox,
public RibbonUI::CollectionCtrlImpl<MainFrame, wID,
RibbonUI::ComboCollectionImpl<ImagePropertyRibbonCombobox<wID, enImagePropertyType>, 500, 0>>,
public IImagePropertyControl
{
/// ribbon base class
typedef RibbonUI::CollectionCtrlImpl<MainFrame, wID,
RibbonUI::ComboCollectionImpl<ImagePropertyRibbonCombobox<wID, enImagePropertyType>, 500, 0 >> RibbonBaseClass;
public:
/// ctor
ImagePropertyRibbonCombobox()
:m_enImagePropertyType(enImagePropertyType),
m_uiPropertyId(0)
{
}
/// sets remote release control
void SetRemoteReleaseControl(std::shared_ptr<RemoteReleaseControl> spRemoteReleaseControl)
{
m_spRemoteReleaseControl = spRemoteReleaseControl;
if (m_spRemoteReleaseControl != nullptr)
m_uiPropertyId = m_spRemoteReleaseControl->MapImagePropertyTypeToId(m_enImagePropertyType);
else
{
LightweightMutex::LockType lock{ m_mtxValues };
m_vecValues.clear();
m_vecValueTexts.clear();
}
}
// virtual methods from IImagePropertyControl
/// returns property id of image property managed by control
virtual unsigned int GetPropertyId() override { return m_uiPropertyId; }
/// updates list of values
virtual void UpdateValuesList() override
{
if (m_spRemoteReleaseControl == nullptr)
return;
LightweightMutex::LockType lock(m_mtxValues);
m_vecValues.clear();
try
{
m_spRemoteReleaseControl->EnumImagePropertyValues(m_uiPropertyId, m_vecValues);
}
catch (CameraException& ex)
{
CameraErrorDlg dlg(_T("Couldn't enumerate values for image property"), ex);
dlg.DoModal(GetWndRibbon());
}
m_vecValueTexts.clear();
m_vecValueTexts.resize(m_vecValues.size());
Resize(m_vecValues.size(), true);
}
/// updates current value
virtual void UpdateValue() override
{
if (m_spRemoteReleaseControl == nullptr)
return;
CString cszPropertyName;
try
{
LightweightMutex::LockType lock(m_mtxValues);
ImageProperty val = m_spRemoteReleaseControl->GetImageProperty(m_uiPropertyId);
cszPropertyName = val.Name();
// no descriptions available?
if (m_vecValues.empty())
{
m_vecValueTexts.resize(1);
m_vecValueTexts[0] = val.AsString();
Resize(m_vecValueTexts.size(), true);
SetItemText(0, m_vecValueTexts[0], true);
Select(0, true);
return;
}
// search item in value list
std::vector<ImageProperty>::iterator iterValues = std::find(m_vecValues.begin(), m_vecValues.end(), val);
if (iterValues == m_vecValues.end())
return;
ptrdiff_t iPos = std::distance(m_vecValues.begin(), iterValues);
ATLASSERT(iPos >= 0);
unsigned int uiIndex = static_cast<unsigned int>(iPos);
m_vecValueTexts[uiIndex] = val.AsString();
SetItemText(uiIndex, m_vecValueTexts[uiIndex], true);
Select(uiIndex, true);
}
catch (CameraException& ex)
{
CString cszText(_T("Couldn't get value for image property"));
if (!cszPropertyName.IsEmpty())
cszText.AppendFormat(_T(": %s"), cszPropertyName.GetString());
CameraErrorDlg dlg(cszText, ex);
dlg.DoModal(GetWndRibbon());
}
}
// virtual methods from IRibbonCombobox
/// called to query category text for category number
virtual LPCWSTR OnRibbonQueryCategoryText(UINT32 /*uCat*/) override
{
return L"";
}
/// called to query item category for item
virtual UINT32 OnRibbonQueryItemCategory(UINT32 /*uItem*/) override
{
return 0; // no categories
}
/// called to query item text for item
virtual LPCWSTR OnRibbonQueryItemText(UINT32 uItem) override
{
LightweightMutex::LockType lock(m_mtxValues);
ATLASSERT(uItem < m_vecValueTexts.size());
if (uItem >= m_vecValueTexts.size())
return L"";
if (uItem < m_vecValues.size() && m_vecValueTexts[uItem].IsEmpty())
m_vecValueTexts[uItem] = m_vecValues[uItem].AsString();
return m_vecValueTexts[uItem];
}
/// called to query currently selected item
virtual bool OnRibbonQuerySelectedItem(UINT32& uSel) override
{
uSel = GetSelected();
return true;
}
/// called to query item image for item
virtual HBITMAP OnRibbonQueryItemImage(UINT32 /*uItem*/) override
{
return nullptr;
}
/// called when selection has changed
LRESULT OnRibbonComboSelChanged(UI_EXECUTIONVERB verb, WORD /*wID*/, UINT uSel, BOOL& /*bHandled*/)
{
if (verb == UI_EXECUTIONVERB_EXECUTE &&
uSel != UI_COLLECTION_INVALIDINDEX &&
m_spRemoteReleaseControl != nullptr)
{
LightweightMutex::LockType lock(m_mtxValues);
if (m_vecValues.empty())
return 0; // read-only value
ATLASSERT(uSel < m_vecValues.size());
ImageProperty& imageProperty = m_vecValues[uSel];
SetImageProperty(imageProperty);
}
return 0;
}
private:
/// sets new image property
void SetImageProperty(ImageProperty& imageProperty)
{
if (m_spRemoteReleaseControl == nullptr)
return;
try
{
m_spRemoteReleaseControl->SetImageProperty(imageProperty);
}
catch (CameraException& ex)
{
CameraErrorDlg dlg(_T("Couldn't set image property"), ex);
dlg.DoModal(GetWndRibbon());
}
}
private:
/// image property type
T_enImagePropertyType m_enImagePropertyType;
/// release control access
std::shared_ptr<RemoteReleaseControl> m_spRemoteReleaseControl;
/// property id
unsigned int m_uiPropertyId;
/// mutex to protect m_vecValues and m_vecValueTexts
LightweightMutex m_mtxValues;
/// all currently possible values for this property
std::vector<ImageProperty> m_vecValues;
/// all texts for currently possible values
std::vector<CString> m_vecValueTexts;
};
|
#pragma once
template<typename T>
inline T GetTypedProcAddress(HMODULE hModule, LPCSTR lpProcName)
{
T Func = reinterpret_cast<T>(GetProcAddress(hModule, lpProcName));
if (!Func)
{
const char* ProcName = lpProcName;
CE_LOG_ERROR("Failed to load " + std::string(ProcName));
}
return Func;
}
|
#include <bits/stdc++.h>
using namespace std;
typedef long double ld;
typedef long long int ll;
vector<vector<ll>> adjlist;
ll max(ll x, ll y) { return (x > y) ? x : y; }
ll min(ll x, ll y) { return (x > y) ? y : x; }
#define sfor(a, n, i) for (ll i = a; i < n; i++)
#define rfor(n, a, i) for (ll i = n; i >= a; i--)
#define mod 1000000007
#define pb push_back
#define in insert
#define mp make_pair
#define inf mod
#define bg begin()
#define ed end()
#define sz size()
#define vi vector<ll>
#define vc vector<char>
#define vinv vector<vector<ll, ll>>
#define imap map<ll, ll>
#define cmap map<char, ll>
#define smap map<string, ll>
#define iset set<ll>
#define bit(x, i) (x & (1 << i))
ll n;
string dict[100000 + 9];
ll cost[100000 + 9];
ll dp[100000 + 9][2];
int main()
{
cin >> n;
sfor(0, n, i) cin >> cost[i];
sfor(0, n, i) cin >> dict[i];
memset(dp, 0, (100000 + 9) * 2);
dp[0][0] = 0;
dp[0][1] = cost[0];
string last = dict[0];
string rLast = last;
reverse(rLast.bg, rLast.ed);
bool lPossible1 = true, rPossible = true;
sfor(1, n, i)
{
bool currentPossible = false, RcurrentPossible = false;
string temp = dict[i];
reverse(temp.bg, temp.ed);
if (lPossible1 && (dict[i] >= last))
{
currentPossible = true;
dp[i][0] = dp[i - 1][0];
}
if (rPossible && (dict[i] >= rLast))
{
if (currentPossible)
{
dp[i][0] = min(dp[i][0], dp[i - 1][1]);
}
else
{
dp[i][0] = dp[i - 1][1];
}
currentPossible = true;
}
if (lPossible1 && (temp >= last))
{
RcurrentPossible = true;
dp[i][1] = dp[i - 1][0] + cost[i];
}
if (rPossible && (temp >= rLast))
{
if (RcurrentPossible)
{
dp[i][1] = min(dp[i][1], dp[i - 1][1] + cost[i]);
}
else
{
dp[i][1] = dp[i - 1][1] + cost[i];
}
RcurrentPossible = true;
}
lPossible1 = currentPossible;
rPossible = RcurrentPossible;
last = dict[i];
rLast = temp;
if ((!lPossible1) && (!rPossible))
{
cout << -1;
return 0;
}
}
if (rPossible && lPossible1)
{
cout << min(dp[n - 1][0], dp[n - 1][01]);
}
else if (rPossible)
{
cout << dp[n - 1][1];
}
else if (lPossible1)
{
cout << dp[n - 1][0];
}
else{
}
return 0;
}
|
#include "../../std.h"
#include "grammar_define.h"
////////////////////////////////////////////////////////////////////////////////
// CGrammarDefine类
KC::grammar::two_level::CGrammarDefine::CGrammarDefine(IWebPageData& page, ICurrentParsePos& currPos,
const one_level::CGrammarBase& base,
const one_level::CGrammarExpr& expr
)
: CGrammarDefine::base_type(this->rDefSect, "CGrammarDefine")
, m_page(page), m_currPos(currPos), m_base(base), m_expr(expr)
{
this->SetRulePos();
this->SetRule();
}
// 设置确定关键字位置的规则
void KC::grammar::two_level::CGrammarDefine::SetRulePos(void)
{
// 延迟关键字
rKeywordDelay = qi::string(g_KeywordDelay);
// 事件关键字
rKeywordEvent = qi::string(g_KeywordEvent);
// 事件前关键字
rKeywordBefore = qi::string(g_KeywordBefore);
// 事件后关键字
rKeywordAfter = qi::string(g_KeywordAfter);
}
// 设置规则
void KC::grammar::two_level::CGrammarDefine::SetRule(void)
{
// 变量定义;例子,#int $m = 10, $i;
rVarAssBody = m_expr.rVariable [phoenix::bind(&TKcVarAssDef::SetVal<0>, _val, _1)]
>> m_base.rEvaluateSpilit [phoenix::bind(&ICurrentParsePos::Set, &m_currPos, _val, _1)]
>> m_expr [phoenix::bind(&TKcVarAssDef::SetVal<1>, _val, _1)]
;
rVarAssBodyList = rVarAssBody [phoenix::bind(&TKcVarAssListDef::PushVal, _val, _1)]
% m_base.rCommaSpilit [phoenix::bind(&ICurrentParsePos::Set, &m_currPos, _val, _1)]
;
rVarDef = m_base.rCommDataType [phoenix::bind(&TKcVarDef::SetVal<0>, _val, _1)]
>> -(m_base.rOptionPrivate [phoenix::bind(&ICurrentParsePos::Set, &m_currPos, _val, _1)]
[phoenix::bind(&TKcVarDef::SetVal<2>, _val, true)]
^ m_base.rOptionReference [phoenix::bind(&ICurrentParsePos::Set, &m_currPos, _val, _1)]
[phoenix::bind(&TKcVarDef::SetVal<3>, _val, true)]
^ m_base.rOptionStatic [phoenix::bind(&ICurrentParsePos::Set, &m_currPos, _val, _1)]
[phoenix::bind(&TKcVarDef::SetVal<4>, _val, true)]
) >> rVarAssBodyList [phoenix::bind(&TKcVarDef::SetVal<1>, _val, _1)]
>> m_base.rSentEnd [phoenix::bind(&ICurrentParsePos::Set, &m_currPos, _val, _1)]
;
// 变量赋值;例子,$i = &m;
rVarAssign = rVarAssBody [_val = _1]
>> m_base.rSentEnd [phoenix::bind(&ICurrentParsePos::Set, &m_currPos, _val, _1)]
;
// 内部变量赋值;例子,$$cookie["abc"] = &m;
rInnerVarAss = m_expr.rInnerVar [phoenix::bind(&TKcInnerVarAssDef::SetVal<0>, _val, _1)]
>> m_base.rEvaluateSpilit [phoenix::bind(&ICurrentParsePos::Set, &m_currPos, _val, _1)]
>> m_expr [phoenix::bind(&TKcInnerVarAssDef::SetVal<1>, _val, _1)]
>> m_base.rSentEnd [phoenix::bind(&ICurrentParsePos::Set, &m_currPos, _val, _1)]
;
// 表达式运算;例子,@mod1.ShowInfo(1);
rExprWork = m_expr [phoenix::bind(&TKcExprWorkDef::SetVal<0>, _val, _1)]
>> m_base.rSentEnd [phoenix::bind(&ICurrentParsePos::Set, &m_currPos, _val, _1)]
;
// 类型名称(尖括号内)
rTypeName = m_base.rSymbolLess [phoenix::bind(&ICurrentParsePos::Set, &m_currPos, _val, _1)]
>> m_base.rCommName [phoenix::bind(&TKcTypeNameDef::SetVal<0>, _val, _1)]
>> m_base.rSymbolMore [phoenix::bind(&ICurrentParsePos::Set, &m_currPos, _val, _1)]
;
// 延迟
rDelayDef = m_base.rKeyBegin [phoenix::bind(&ICurrentParsePos::Set, &m_currPos, _val, _1)]
>> rKeywordDelay [phoenix::bind(&ICurrentParsePos::Set, &m_currPos, _val, _1)]
>> rTypeName [phoenix::bind(&TKcDelayDef::SetVal<0>, _val, _1)]
>> (rVarAssign [phoenix::bind(&TKcDelayDef::SetVal<1>, _val, 0)]
[phoenix::bind(&TKcDelayDef::SetVal<2>, _val, _1)]
| rInnerVarAss [phoenix::bind(&TKcDelayDef::SetVal<1>, _val, 1)]
[phoenix::bind(&TKcDelayDef::SetVal<3>, _val, _1)]
| rExprWork [phoenix::bind(&TKcDelayDef::SetVal<1>, _val, 2)]
[phoenix::bind(&TKcDelayDef::SetVal<4>, _val, _1)]
);
// 事件
rEventOpPlace = m_base.rSymbolSubt [phoenix::bind(&ICurrentParsePos::Set, &m_currPos, _val, _1)]
>> (rKeywordBefore [phoenix::bind(&ICurrentParsePos::Set, &m_currPos, _val, _1)]
[phoenix::bind(&TKcEventOpPlaceDef::SetVal<0>, _val, OpPlaceBefore)]
| rKeywordAfter [phoenix::bind(&ICurrentParsePos::Set, &m_currPos, _val, _1)]
[phoenix::bind(&TKcEventOpPlaceDef::SetVal<0>, _val, OpPlaceAfter)]
);
rEventLevel = m_base.rSymbolArrayLeft [phoenix::bind(&ICurrentParsePos::Set, &m_currPos, _val, _1)]
>> qi::int_ [phoenix::bind(&TKcEventLevelDef::SetVal<0>, _val, _1)]
>> m_base.rSymbolArrayRight [phoenix::bind(&ICurrentParsePos::Set, &m_currPos, _val, _1)]
;
rEventBody = (m_base.rAppendSpilit [phoenix::bind(&ICurrentParsePos::Set, &m_currPos, _val, _1)]
>> m_base.rCommIDName [phoenix::bind(&TKcEventBodyDef::SetVal<0>, _val, _1)]
>> m_base.rCommMember [phoenix::bind(&TKcEventBodyDef::SetVal<1>, _val, _1)]
) | rVarAssign [phoenix::bind(&TKcEventBodyDef::SetVal<2>, _val, _1)]
| rInnerVarAss [phoenix::bind(&TKcEventBodyDef::SetVal<3>, _val, _1)]
| rExprWork [phoenix::bind(&TKcEventBodyDef::SetVal<4>, _val, _1)]
;
rEventDef = m_base.rKeyBegin [phoenix::bind(&ICurrentParsePos::Set, &m_currPos, _val, _1)]
>> rKeywordEvent [phoenix::bind(&ICurrentParsePos::Set, &m_currPos, _val, _1)]
>> -rEventOpPlace [phoenix::bind(&TKcEventDef::SetVal<0>, _val, _1)]
>> rTypeName [phoenix::bind(&TKcEventDef::SetVal<1>, _val, _1)]
>> -rEventLevel [phoenix::bind(&TKcEventDef::SetVal<2>, _val, _1)]
>> rEventBody [phoenix::bind(&TKcEventDef::SetVal<3>, _val, _1)]
>> m_base.rSentEnd [phoenix::bind(&ICurrentParsePos::Set, &m_currPos, _val, _1)]
;
// 配置项区
rDefItem = rVarDef [phoenix::bind(&IWebPageData::AddSyntaxItem, &m_page, _1)]
| rDelayDef [phoenix::bind(&IWebPageData::AddSyntaxItem, &m_page, _1)]
| rEventDef [phoenix::bind(&IWebPageData::AddSyntaxItem, &m_page, _1)]
| rVarAssign [phoenix::bind(&IWebPageData::AddSyntaxItem, &m_page, _1)]
| rInnerVarAss [phoenix::bind(&IWebPageData::AddSyntaxItem, &m_page, _1)]
| rExprWork [phoenix::bind(&IWebPageData::AddSyntaxItem, &m_page, _1)]
;
rDefSect = m_base.rSymbHead [phoenix::bind(&ICurrentParsePos::SetPos, &m_currPos, _1, c_SynSysDefID + 1)]
>> *rDefItem
>> m_base.rSymbTail [phoenix::bind(&ICurrentParsePos::SetPos, &m_currPos, _1, c_SynSysDefID + 2)]
;
}
|
#include "game_car_unit.h"
GameCar::GameCar(float x, float y): Car(x, y), pointList(Controller::currentController()->getMap().GetMapPoints()) {
}
GameCar::~GameCar() {
}
bool GameCar::update(float delta) {
Car::update(delta); // inherit
Controller& cont = *Controller::currentController();
if(pointList.size() && interval.getSeconds() > 8){
const MapPoint* selected = nullptr;
do {
for(auto& point : pointList){
if(!(rand() % pointList.size())) selected = &point;
}
} while(selected == nullptr);
position.x = selected->pos.x;
position.y = selected->pos.y;
interval.restart();
}
return true;
}
|
////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2016 ArangoDB GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Simon Grätzer
////////////////////////////////////////////////////////////////////////////////
#include "Pregel/Algos/ShortestPath.h"
#include "Pregel/Aggregator.h"
#include "Pregel/Algorithm.h"
#include "Pregel/GraphStore.h"
#include "Pregel/IncomingCache.h"
#include "Pregel/VertexComputation.h"
#include "Pregel/WorkerConfig.h"
using namespace arangodb;
using namespace arangodb::pregel;
using namespace arangodb::pregel::algos;
static std::string const spUpperPathBound = "bound";
struct SPComputation : public VertexComputation<int64_t, int64_t, int64_t> {
PregelID _target;
explicit SPComputation(PregelID const& target) : _target(target) {}
void compute(MessageIterator<int64_t> const& messages) override {
int64_t current = vertexData();
for (const int64_t* msg : messages) {
if (*msg < current) {
current = *msg;
};
}
// use global state to limit the computation of paths
bool isSource = current == 0 && localSuperstep() == 0;
int64_t const* max = getAggregatedValue<int64_t>(spUpperPathBound);
int64_t* state = mutableVertexData();
if (isSource || (current < *state && current < *max)) {
*state = current; // update state
if (this->pregelId() == _target) {
// TODO extend pregel to update certain aggregators during a GSS
aggregate(spUpperPathBound, current);
enterNextGlobalSuperstep();
LOG_TOPIC(DEBUG, Logger::PREGEL) << "Found target " << current;
return;
}
RangeIterator<Edge<int64_t>> edges = getEdges();
for (Edge<int64_t>* edge : edges) {
int64_t val = *edge->data() + current;
if (val < *max) {
sendMessage(edge, val);
}
}
}
voteHalt();
}
};
struct arangodb::pregel::algos::SPGraphFormat
: public InitGraphFormat<int64_t, int64_t> {
std::string _sourceDocId, _targetDocId;
public:
SPGraphFormat(std::string const& source, std::string const& target)
: InitGraphFormat<int64_t, int64_t>("length", 0, 1),
_sourceDocId(source),
_targetDocId(target) {}
size_t copyVertexData(std::string const& documentId,
arangodb::velocypack::Slice document,
int64_t* targetPtr, size_t maxSize) override {
*targetPtr = documentId == _sourceDocId ? 0 : INT64_MAX;
return sizeof(int64_t);
}
bool buildEdgeDocument(arangodb::velocypack::Builder& b,
const int64_t* targetPtr, size_t size) const override {
return false;
}
};
ShortestPathAlgorithm::ShortestPathAlgorithm(VPackSlice userParams)
: Algorithm("ShortestPath") {
VPackSlice val1 = userParams.get("source");
VPackSlice val2 = userParams.get("target");
if (val1.isNone() || val2.isNone()) {
THROW_ARANGO_EXCEPTION_MESSAGE(TRI_ERROR_BAD_PARAMETER,
"You must specify source and target");
}
_source = val1.copyString();
_target = val2.copyString();
}
std::set<std::string> ShortestPathAlgorithm::initialActiveSet() {
return std::set<std::string>{_source};
}
GraphFormat<int64_t, int64_t>* ShortestPathAlgorithm::inputFormat() const {
return new SPGraphFormat(_source, _target);
}
VertexComputation<int64_t, int64_t, int64_t>*
ShortestPathAlgorithm::createComputation(WorkerConfig const* _config) const {
PregelID target = _config->documentIdToPregel(_target);
return new SPComputation(target);
}
IAggregator* ShortestPathAlgorithm::aggregator(std::string const& name) const {
if (name == spUpperPathBound) { // persistent min operator
return new MinAggregator<int64_t>(INT64_MAX, true);
}
return nullptr;
}
|
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Copyright (c) 2011-2013 The Paycoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "main.h"
#include "wallet.h"
#include "db.h"
#include "walletdb.h"
#include "net.h"
#include "init.h"
#include "checkpoints.h"
#include "ui_interface.h"
#include "base58.h"
#include "bitcoinrpc.h"
#include "kernelrecord.h"
#undef printf
#include <boost/asio.hpp>
#include <boost/assign/list_of.hpp>
#include <boost/filesystem.hpp>
#include <boost/iostreams/concepts.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/asio/ssl.hpp>
#include <boost/filesystem/fstream.hpp>
typedef boost::asio::ssl::stream<boost::asio::ip::tcp::socket> SSLStream;
#define printf OutputDebugStringF
// MinGW 3.4.5 gets "fatal error: had to relocate PCH" if the json headers are
// precompiled in headers.h. The problem might be when the pch file goes over
// a certain size around 145MB. If we need access to json_spirit outside this
// file, we could use the compiled json_spirit option.
using namespace std;
using namespace boost;
using namespace boost::asio;
using namespace json_spirit;
void ThreadRPCServer2(void* parg);
// Key used by getwork/getblocktemplate miners.
// Allocated in StartRPCThreads, free'd in StopRPCThreads
CReserveKey* pMiningKey = NULL;
static std::string strRPCUserColonPass;
static int64 nWalletUnlockTime;
static CCriticalSection cs_nWalletUnlockTime;
extern Value dumpprivkey(const Array& params, bool fHelp);
extern Value importprivkey(const Array& params, bool fHelp);
Object JSONRPCError(int code, const string& message)
{
Object error;
error.push_back(Pair("code", code));
error.push_back(Pair("message", message));
return error;
}
double GetDifficulty(const CBlockIndex* blockindex = NULL)
{
// Floating point number that is a multiple of the minimum difficulty,
// minimum difficulty = 1.0.
if (blockindex == NULL)
{
if (pindexBest == NULL)
return 1.0;
else
blockindex = GetLastBlockIndex(pindexBest, false);
}
return blockindex->GetBlockDifficulty();
}
int64 AmountFromValue(const Value& value)
{
double dAmount = value.get_real();
if (dAmount <= 0.0 || dAmount > MAX_MONEY)
throw JSONRPCError(-3, "Invalid amount");
int64 nAmount = roundint64(dAmount * COIN);
if (!MoneyRange(nAmount))
throw JSONRPCError(-3, "Invalid amount");
return nAmount;
}
Value ValueFromAmount(int64 amount)
{
return (double)amount / (double)COIN;
}
std::string
HexBits(unsigned int nBits)
{
union {
int32_t nBits;
char cBits[4];
} uBits;
uBits.nBits = htonl((int32_t)nBits);
return HexStr(BEGIN(uBits.cBits), END(uBits.cBits));
}
void WalletTxToJSON(const CWalletTx& wtx, Object& entry)
{
int confirms = wtx.GetDepthInMainChain();
entry.push_back(Pair("confirmations", confirms));
if (confirms)
{
entry.push_back(Pair("blockhash", wtx.hashBlock.GetHex()));
entry.push_back(Pair("blockindex", wtx.nIndex));
}
entry.push_back(Pair("txid", wtx.GetHash().GetHex()));
entry.push_back(Pair("time", (boost::int64_t)wtx.GetTxTime()));
BOOST_FOREACH(const PAIRTYPE(string,string)& item, wtx.mapValue)
entry.push_back(Pair(item.first, item.second));
}
string AccountFromValue(const Value& value)
{
string strAccount = value.get_str();
if (strAccount == "*")
throw JSONRPCError(-11, "Invalid account name");
return strAccount;
}
void ScriptPubKeyToJSON(const CScript& scriptPubKey, Object& out)
{
txnouttype type;
vector<CTxDestination> addresses;
int nRequired;
out.push_back(Pair("asm", scriptPubKey.ToString()));
out.push_back(Pair("hex", HexStr(scriptPubKey.begin(), scriptPubKey.end())));
if (!ExtractDestinations(scriptPubKey, type, addresses, nRequired))
{
out.push_back(Pair("type", GetTxnOutputType(TX_NONSTANDARD)));
return;
}
out.push_back(Pair("reqSigs", nRequired));
out.push_back(Pair("type", GetTxnOutputType(type)));
Array a;
BOOST_FOREACH(const CTxDestination& addr, addresses)
a.push_back(CBitcoinAddress(addr).ToString());
out.push_back(Pair("addresses", a));
}
void TxToJSON(const CTransaction& tx, const uint256 hashBlock, Object& entry)
{
entry.push_back(Pair("txid", tx.GetHash().GetHex()));
entry.push_back(Pair("version", tx.nVersion));
entry.push_back(Pair("time", (boost::int64_t)tx.nTime));
entry.push_back(Pair("locktime", (boost::int64_t)tx.nLockTime));
Array vin;
BOOST_FOREACH(const CTxIn& txin, tx.vin)
{
Object in;
if (tx.IsCoinBase())
in.push_back(Pair("coinbase", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())));
else
{
in.push_back(Pair("txid", txin.prevout.hash.GetHex()));
in.push_back(Pair("vout", (boost::int64_t)txin.prevout.n));
Object o;
o.push_back(Pair("asm", txin.scriptSig.ToString()));
o.push_back(Pair("hex", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())));
in.push_back(Pair("scriptSig", o));
}
in.push_back(Pair("sequence", (boost::int64_t)txin.nSequence));
vin.push_back(in);
}
entry.push_back(Pair("vin", vin));
Array vout;
for (unsigned int i = 0; i < tx.vout.size(); i++)
{
const CTxOut& txout = tx.vout[i];
Object out;
out.push_back(Pair("value", ValueFromAmount(txout.nValue)));
out.push_back(Pair("n", (boost::int64_t)i));
Object o;
ScriptPubKeyToJSON(txout.scriptPubKey, o);
out.push_back(Pair("scriptPubKey", o));
vout.push_back(out);
}
entry.push_back(Pair("vout", vout));
if (hashBlock != 0)
{
entry.push_back(Pair("blockhash", hashBlock.GetHex()));
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
if (mi != mapBlockIndex.end() && (*mi).second)
{
CBlockIndex* pindex = (*mi).second;
if (pindex->IsInMainChain())
{
entry.push_back(Pair("confirmations", 1 + nBestHeight - pindex->nHeight));
entry.push_back(Pair("blocktime", (boost::int64_t)pindex->nTime));
}
else
entry.push_back(Pair("confirmations", 0));
}
}
}
void TxToJSON(const CTransaction& tx, Object& txdata)
{
// tx data
txdata.push_back(Pair("txid", tx.GetHash().ToString().c_str()));
txdata.push_back(Pair("version", (int)tx.nVersion));
txdata.push_back(Pair("locktime", (int)tx.nLockTime));
txdata.push_back(Pair("is_coinbase", tx.IsCoinBase()));
txdata.push_back(Pair("is_coinstake", tx.IsCoinStake()));
// add inputs
Array vins;
BOOST_FOREACH(const CTxIn& txin, tx.vin)
{
Object vin;
if (txin.prevout.IsNull())
{
vin.push_back(Pair("coinbase", HexStr(txin.scriptSig).c_str()));
}
else
{
vin.push_back(Pair("txid", txin.prevout.hash.ToString().c_str()));
vin.push_back(Pair("vout", (int)txin.prevout.n));
}
vin.push_back(Pair("sequence", (boost::uint64_t)txin.nSequence));
vins.push_back(vin);
}
txdata.push_back(Pair("vin", vins));
// add outputs
Array vouts;
int n = 0;
BOOST_FOREACH(const CTxOut& txout, tx.vout)
{
Object vout;
std::vector<CTxDestination> addresses;
txnouttype txtype;
int nRequired;
vout.push_back(Pair("value", ValueFromAmount(txout.nValue)));
vout.push_back(Pair("n", n));
Object scriptpubkey;
scriptpubkey.push_back(Pair("asm", txout.scriptPubKey.ToString()));
scriptpubkey.push_back(Pair("hex", HexStr(txout.scriptPubKey.begin(), txout.scriptPubKey.end())));
if (ExtractDestinations(txout.scriptPubKey, txtype, addresses, nRequired))
{
scriptpubkey.push_back(Pair("type", GetTxnOutputType(txtype)));
scriptpubkey.push_back(Pair("reqSig", nRequired));
Array addrs;
BOOST_FOREACH(const CTxDestination& addr, addresses)
addrs.push_back(CBitcoinAddress(addr).ToString());
scriptpubkey.push_back(Pair("addresses", addrs));
}
else
{
scriptpubkey.push_back(Pair("type", GetTxnOutputType(TX_NONSTANDARD)));
}
vout.push_back(Pair("scriptPubKey",scriptpubkey));
vouts.push_back(vout);
n++;
}
txdata.push_back(Pair("vout", vouts));
}
Object blockToJSON(const CBlock& block, const CBlockIndex* blockindex, bool fTxInfo, bool fTxDetails)
{
Object result;
result.push_back(Pair("hash", block.GetHash().GetHex()));
result.push_back(Pair("size", (int)::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION)));
result.push_back(Pair("height", blockindex->nHeight));
result.push_back(Pair("version", block.nVersion));
result.push_back(Pair("merkleroot", block.hashMerkleRoot.GetHex()));
result.push_back(Pair("time", DateTimeStrFormat(block.GetBlockTime())));
result.push_back(Pair("nonce", (boost::uint64_t)block.nNonce));
result.push_back(Pair("bits", HexBits(block.nBits)));
result.push_back(Pair("difficulty", GetDifficulty(blockindex)));
result.push_back(Pair("mint", ValueFromAmount(blockindex->nMint)));
if (blockindex->pprev)
result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex()));
if (blockindex->pnext)
result.push_back(Pair("nextblockhash", blockindex->pnext->GetBlockHash().GetHex()));
result.push_back(Pair("flags", strprintf("%s%s", blockindex->IsProofOfStake()? "proof-of-stake" : "proof-of-work", blockindex->GeneratedStakeModifier()? " stake-modifier": "")));
result.push_back(Pair("proofhash", blockindex->IsProofOfStake()? blockindex->hashProofOfStake.GetHex() : blockindex->GetBlockHash().GetHex()));
result.push_back(Pair("entropybit", (int)blockindex->GetStakeEntropyBit()));
result.push_back(Pair("modifier", strprintf("%016"PRI64x, blockindex->nStakeModifier)));
result.push_back(Pair("modifierchecksum", strprintf("%08x", blockindex->nStakeModifierChecksum)));
Array txinfo;
BOOST_FOREACH (const CTransaction& tx, block.vtx)
{
if (fTxInfo && !fTxDetails)
{
txinfo.push_back(tx.ToStringShort());
txinfo.push_back(DateTimeStrFormat(tx.nTime));
BOOST_FOREACH(const CTxIn& txin, tx.vin)
txinfo.push_back(txin.ToStringShort());
BOOST_FOREACH(const CTxOut& txout, tx.vout)
txinfo.push_back(txout.ToStringShort());
}
else if (fTxDetails)
{
Object txdata;
TxToJSON(tx, txdata);
txinfo.push_back(txdata);
}
else
txinfo.push_back(tx.GetHash().GetHex());
}
result.push_back(Pair("tx", txinfo));
return result;
}
///
/// Note: This interface may still be subject to change.
///
string CRPCTable::help(string strCommand) const
{
string strRet;
set<rpcfn_type> setDone;
for (map<string, const CRPCCommand*>::const_iterator mi = mapCommands.begin(); mi != mapCommands.end(); ++mi)
{
const CRPCCommand *pcmd = mi->second;
string strMethod = mi->first;
// We already filter duplicates, but these deprecated screw up the sort order
if (strMethod == "getamountreceived" ||
strMethod == "getallreceived" ||
strMethod == "getblocknumber" || // deprecated
(strMethod.find("label") != string::npos))
continue;
if (strCommand != "" && strMethod != strCommand)
continue;
try
{
Array params;
rpcfn_type pfn = pcmd->actor;
if (setDone.insert(pfn).second)
(*pfn)(params, true);
}
catch (std::exception& e)
{
// Help text is returned in an exception
string strHelp = string(e.what());
if (strCommand == "")
if (strHelp.find('\n') != string::npos)
strHelp = strHelp.substr(0, strHelp.find('\n'));
strRet += strHelp + "\n";
}
}
if (strRet == "")
strRet = strprintf("help: unknown command: %s\n", strCommand.c_str());
strRet = strRet.substr(0,strRet.size()-1);
return strRet;
}
Value help(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"help [command]\n"
"List commands, or get help for a command.");
string strCommand;
if (params.size() > 0)
strCommand = params[0].get_str();
return tableRPC.help(strCommand);
}
Value stop(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"stop\n"
"Stop Paycoin server.");
// Shutdown will take long enough that the response should get back
StartShutdown();
return "Paycoin server stopping";
}
Value getblockcount(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getblockcount\n"
"Returns the number of blocks in the longest block chain.");
return nBestHeight;
}
// deprecated
Value getblocknumber(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getblocknumber\n"
"Deprecated. Use getblockcount.");
return nBestHeight;
}
Value getconnectioncount(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getconnectioncount\n"
"Returns the number of connections to other nodes.");
LOCK(cs_vNodes);
return (int)vNodes.size();
}
static void CopyNodeStats(std::vector<CNodeStats>& vstats)
{
vstats.clear();
LOCK(cs_vNodes);
vstats.reserve(vNodes.size());
BOOST_FOREACH(CNode* pnode, vNodes) {
CNodeStats stats;
pnode->copyStats(stats);
vstats.push_back(stats);
}
}
Value getpeerinfo(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getpeerinfo\n"
"Returns data about each connected network node.");
vector<CNodeStats> vstats;
CopyNodeStats(vstats);
Array ret;
BOOST_FOREACH(const CNodeStats& stats, vstats) {
Object obj;
obj.push_back(Pair("addr", stats.addrName));
obj.push_back(Pair("services", strprintf("%08"PRI64x, stats.nServices)));
obj.push_back(Pair("lastsend", (boost::int64_t)stats.nLastSend));
obj.push_back(Pair("lastrecv", (boost::int64_t)stats.nLastRecv));
obj.push_back(Pair("conntime", (boost::int64_t)stats.nTimeConnected));
obj.push_back(Pair("version", stats.nVersion));
obj.push_back(Pair("subver", stats.strSubVer));
obj.push_back(Pair("inbound", stats.fInbound));
obj.push_back(Pair("releasetime", (boost::int64_t)stats.nReleaseTime));
obj.push_back(Pair("height", stats.nStartingHeight));
obj.push_back(Pair("banscore", stats.nMisbehavior));
ret.push_back(obj);
}
return ret;
}
Value getdifficulty(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getdifficulty\n"
"Returns difficulty as a multiple of the minimum difficulty.");
Object obj;
obj.push_back(Pair("proof-of-work", GetDifficulty()));
obj.push_back(Pair("proof-of-stake", GetDifficulty(GetLastBlockIndex(pindexBest, true))));
obj.push_back(Pair("search-interval", (int)nLastCoinStakeSearchInterval));
return obj;
}
Value getgenerate(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getgenerate\n"
"Returns true or false.");
return GetBoolArg("-gen");
}
Value setgenerate(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"setgenerate <generate> [genproclimit]\n"
"<generate> is true or false to turn generation on or off.\n"
"Generation is limited to [genproclimit] processors, -1 is unlimited.");
bool fGenerate = true;
if (params.size() > 0)
fGenerate = params[0].get_bool();
if (params.size() > 1)
{
int nGenProcLimit = params[1].get_int();
mapArgs["-genproclimit"] = itostr(nGenProcLimit);
if (nGenProcLimit == 0)
fGenerate = false;
}
mapArgs["-gen"] = (fGenerate ? "1" : "0");
GenerateBitcoins(fGenerate, pwalletMain);
return Value::null;
}
Value gethashespersec(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"gethashespersec\n"
"Returns a recent hashes per second performance measurement while generating.");
if (GetTimeMillis() - nHPSTimerStart > 8000)
return (boost::int64_t)0;
return (boost::int64_t)dHashesPerSec;
}
// paycoin: get network Gh/s estimate
Value getnetworkghps(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getnetworkghps\n"
"Returns a recent Ghash/second network mining estimate.");
if (pindexBest != NULL && pindexBest->nTime > POW_END_TIME)
return (double)0.00f;
int64 nTargetSpacingWorkMin = 30;
int64 nTargetSpacingWork = nTargetSpacingWorkMin;
int64 nInterval = 72;
CBlockIndex* pindex = pindexGenesisBlock;
CBlockIndex* pindexPrevWork = pindexGenesisBlock;
while (pindex)
{
// Exponential moving average of recent proof-of-work block spacing
if (pindex->IsProofOfWork())
{
int64 nActualSpacingWork = pindex->GetBlockTime() - pindexPrevWork->GetBlockTime();
nTargetSpacingWork = ((nInterval - 1) * nTargetSpacingWork + nActualSpacingWork + nActualSpacingWork) / (nInterval + 1);
nTargetSpacingWork = max(nTargetSpacingWork, nTargetSpacingWorkMin);
pindexPrevWork = pindex;
}
pindex = pindex->pnext;
}
double dNetworkGhps = GetDifficulty() * 4.294967296 / nTargetSpacingWork;
return dNetworkGhps;
}
Value getinfo(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getinfo\n"
"Returns an object containing various state info.");
Object obj;
obj.push_back(Pair("version", FormatFullVersion()));
obj.push_back(Pair("protocolversion",(int)PROTOCOL_VERSION));
obj.push_back(Pair("walletversion", pwalletMain->GetVersion()));
obj.push_back(Pair("balance", ValueFromAmount(pwalletMain->GetBalance())));
obj.push_back(Pair("newmint", ValueFromAmount(pwalletMain->GetNewMint())));
obj.push_back(Pair("stake", ValueFromAmount(pwalletMain->GetStake())));
obj.push_back(Pair("blocks", (int)nBestHeight));
obj.push_back(Pair("moneysupply", ValueFromAmount(pindexBest->nMoneySupply)));
obj.push_back(Pair("connections", (int)vNodes.size()));
obj.push_back(Pair("proxy", (fUseProxy ? addrProxy.ToStringIPPort() : string())));
obj.push_back(Pair("ip", addrSeenByPeer.ToStringIP()));
obj.push_back(Pair("difficulty", (double)GetDifficulty()));
obj.push_back(Pair("testnet", fTestNet));
obj.push_back(Pair("keypoololdest", (boost::int64_t)pwalletMain->GetOldestKeyPoolTime()));
obj.push_back(Pair("keypoolsize", pwalletMain->GetKeyPoolSize()));
obj.push_back(Pair("paytxfee", ValueFromAmount(nTransactionFee)));
if (pwalletMain->IsCrypted())
obj.push_back(Pair("unlocked_until", (boost::int64_t)nWalletUnlockTime / 1000));
obj.push_back(Pair("errors", GetWarnings("statusbar")));
return obj;
}
double GetPoSKernelPS2(const CBlockIndex* pindex)
{
int nPoSInterval = 72;
double dStakeKernelsTriedAvg = 0;
int nStakesHandled = 0, nStakesTime = 0;
const CBlockIndex* pindexPrevStake = NULL;
while (pindex && nStakesHandled < nPoSInterval)
{
if (pindex->IsProofOfStake())
{
dStakeKernelsTriedAvg += GetDifficulty(pindex) * 4294967296.0;
nStakesTime += pindexPrevStake ? (pindexPrevStake->nTime - pindex->nTime) : 0;
pindexPrevStake = pindex;
nStakesHandled++;
}
pindex = pindex->pprev;
}
return nStakesTime ? dStakeKernelsTriedAvg / nStakesTime : 0;
}
double GetPoSKernelPS() {
return GetPoSKernelPS2(pindexBest);
}
Value getmininginfo(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getmininginfo\n"
"Returns an object containing mining-related information.");
uint64 nMinWeight = 0, nMaxWeight = 0, nWeight = 0;
pwalletMain->GetStakeWeight(*pwalletMain, nMinWeight, nMaxWeight, nWeight);
Object obj, weight;
obj.push_back(Pair("blocks", (int)nBestHeight));
obj.push_back(Pair("currentblocksize",(uint64_t)nLastBlockSize));
obj.push_back(Pair("currentblocktx",(uint64_t)nLastBlockTx));
obj.push_back(Pair("difficulty", (double)GetDifficulty()));
obj.push_back(Pair("errors", GetWarnings("statusbar")));
obj.push_back(Pair("generate", GetBoolArg("-gen")));
obj.push_back(Pair("genproclimit", (int)GetArg("-genproclimit", -1)));
obj.push_back(Pair("hashespersec", gethashespersec(params, false)));
obj.push_back(Pair("netstakeweight", GetPoSKernelPS()));
weight.push_back(Pair("minimum", (uint64_t)nMinWeight));
weight.push_back(Pair("maximum", (uint64_t)nMaxWeight));
weight.push_back(Pair("combined", (uint64_t)nWeight));
obj.push_back(Pair("stakeweight", weight));
obj.push_back(Pair("networkghps", getnetworkghps(params, false)));
obj.push_back(Pair("pooledtx", (uint64_t)mempool.size()));
obj.push_back(Pair("testnet", fTestNet));
return obj;
}
Value getnewaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"getnewaddress [account]\n"
"Returns a new Paycoin address for receiving payments. "
"If [account] is specified (recommended), it is added to the address book "
"so payments received with the address will be credited to [account].");
// Parse the account first so we don't generate a key if there's an error
string strAccount;
if (params.size() > 0)
strAccount = AccountFromValue(params[0]);
if (!pwalletMain->IsLocked())
pwalletMain->TopUpKeyPool();
// Generate a new key that is added to wallet
CPubKey newKey;
if (!pwalletMain->GetKeyFromPool(newKey, false))
throw JSONRPCError(-12, "Error: Keypool ran out, please call keypoolrefill first");
CKeyID keyID = newKey.GetID();
pwalletMain->SetAddressBookName(keyID, strAccount);
return CBitcoinAddress(keyID).ToString();
}
CBitcoinAddress GetAccountAddress(string strAccount, bool bForceNew=false)
{
CWalletDB walletdb(pwalletMain->strWalletFile);
CAccount account;
walletdb.ReadAccount(strAccount, account);
bool bKeyUsed = false;
// Check if the current key has been used
if (account.vchPubKey.IsValid())
{
CScript scriptPubKey;
scriptPubKey.SetDestination(account.vchPubKey.GetID());
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin();
it != pwalletMain->mapWallet.end() && account.vchPubKey.IsValid();
++it)
{
const CWalletTx& wtx = (*it).second;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
if (txout.scriptPubKey == scriptPubKey)
bKeyUsed = true;
}
}
// Generate a new key
if (!account.vchPubKey.IsValid() || bForceNew || bKeyUsed)
{
if (!pwalletMain->GetKeyFromPool(account.vchPubKey, false))
throw JSONRPCError(-12, "Error: Keypool ran out, please call keypoolrefill first");
pwalletMain->SetAddressBookName(account.vchPubKey.GetID(), strAccount);
walletdb.WriteAccount(strAccount, account);
}
return CBitcoinAddress(account.vchPubKey.GetID());
}
Value getaccountaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"getaccountaddress <account>\n"
"Returns the current Paycoin address for receiving payments to this account.");
// Parse the account first so we don't generate a key if there's an error
string strAccount = AccountFromValue(params[0]);
Value ret;
ret = GetAccountAddress(strAccount).ToString();
return ret;
}
Value setaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"setaccount <paycoinaddress> <account>\n"
"Sets the account associated with the given address.");
CBitcoinAddress address(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(-5, "Invalid Paycoin address");
string strAccount;
if (params.size() > 1)
strAccount = AccountFromValue(params[1]);
// Detect when changing the account of an address that is the 'unused current key' of another account:
if (pwalletMain->mapAddressBook.count(address.Get()))
{
string strOldAccount = pwalletMain->mapAddressBook[address.Get()];
if (address == GetAccountAddress(strOldAccount))
GetAccountAddress(strOldAccount, true);
}
pwalletMain->SetAddressBookName(address.Get(), strAccount);
return Value::null;
}
Value getaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"getaccount <paycoinaddress>\n"
"Returns the account associated with the given address.");
CBitcoinAddress address(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(-5, "Invalid Paycoin address");
string strAccount;
map<CTxDestination, string>::iterator mi = pwalletMain->mapAddressBook.find(address.Get());
if (mi != pwalletMain->mapAddressBook.end() && !(*mi).second.empty())
strAccount = (*mi).second;
return strAccount;
}
Value getaddressesbyaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"getaddressesbyaccount <account>\n"
"Returns the list of addresses for the given account.");
string strAccount = AccountFromValue(params[0]);
// Find all addresses that have the given account
Array ret;
BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress, string)& item, pwalletMain->mapAddressBook)
{
const CBitcoinAddress& address = item.first;
const string& strName = item.second;
if (strName == strAccount)
ret.push_back(address.ToString());
}
return ret;
}
Value settxfee(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 1 || AmountFromValue(params[0]) < MIN_TX_FEE)
throw runtime_error(
"settxfee <amount>\n"
"<amount> is a real and is rounded to 0.01 (cent)\n"
"Minimum and default transaction fee per KB is 1 cent");
nTransactionFee = AmountFromValue(params[0]);
nTransactionFee = (nTransactionFee / CENT) * CENT; // round to cent
return true;
}
Value sendtoaddress(const Array& params, bool fHelp)
{
if (pwalletMain->IsCrypted() && (fHelp || params.size() < 2 || params.size() > 4))
throw runtime_error(
"sendtoaddress <paycoinaddress> <amount> [comment] [comment-to]\n"
"<amount> is a real and is rounded to the nearest 0.000001\n"
"requires wallet passphrase to be set with walletpassphrase first");
if (!pwalletMain->IsCrypted() && (fHelp || params.size() < 2 || params.size() > 4))
throw runtime_error(
"sendtoaddress <paycoinaddress> <amount> [comment] [comment-to]\n"
"<amount> is a real and is rounded to the nearest 0.000001");
CBitcoinAddress address(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(-5, "Invalid Paycoin address");
// Amount
int64 nAmount = AmountFromValue(params[1]);
if (nAmount < MIN_TXOUT_AMOUNT)
throw JSONRPCError(-101, "Send amount too small");
// Wallet comments
CWalletTx wtx;
if (params.size() > 2 && params[2].type() != null_type && !params[2].get_str().empty())
wtx.mapValue["comment"] = params[2].get_str();
if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty())
wtx.mapValue["to"] = params[3].get_str();
if (pwalletMain->IsLocked())
throw JSONRPCError(-13, "Error: Please enter the wallet passphrase with walletpassphrase first.");
string strError = pwalletMain->SendMoneyToDestination(address.Get(), nAmount, wtx);
if (strError != "")
throw JSONRPCError(-4, strError);
return wtx.GetHash().GetHex();
}
Value signmessage(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 2)
throw runtime_error(
"signmessage <paycoinaddress> <message>\n"
"Sign a message with the private key of an address");
if (pwalletMain->IsLocked())
throw JSONRPCError(-13, "Error: Please enter the wallet passphrase with walletpassphrase first.");
string strAddress = params[0].get_str();
string strMessage = params[1].get_str();
CBitcoinAddress addr(strAddress);
if (!addr.IsValid())
throw JSONRPCError(-3, "Invalid address");
CKeyID keyID;
if (!addr.GetKeyID(keyID))
throw JSONRPCError(-3, "Address does not refer to key");
CKey key;
if (!pwalletMain->GetKey(keyID, key))
throw JSONRPCError(-4, "Private key not available");
CDataStream ss(SER_GETHASH, 0);
ss << strMessageMagic;
ss << strMessage;
vector<unsigned char> vchSig;
if (!key.SignCompact(Hash(ss.begin(), ss.end()), vchSig))
throw JSONRPCError(-5, "Sign failed");
return EncodeBase64(&vchSig[0], vchSig.size());
}
Value verifymessage(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 3)
throw runtime_error(
"verifymessage <paycoinaddress> <signature> <message>\n"
"Verify a signed message");
string strAddress = params[0].get_str();
string strSign = params[1].get_str();
string strMessage = params[2].get_str();
CBitcoinAddress addr(strAddress);
if (!addr.IsValid())
throw JSONRPCError(-3, "Invalid address");
CKeyID keyID;
if (!addr.GetKeyID(keyID))
throw JSONRPCError(-3, "Address does not refer to key");
bool fInvalid = false;
vector<unsigned char> vchSig = DecodeBase64(strSign.c_str(), &fInvalid);
if (fInvalid)
throw JSONRPCError(-5, "Malformed base64 encoding");
CDataStream ss(SER_GETHASH, 0);
ss << strMessageMagic;
ss << strMessage;
CKey key;
if (!key.SetCompactSignature(Hash(ss.begin(), ss.end()), vchSig))
return false;
return (key.GetPubKey().GetID() == keyID);
}
Value getreceivedbyaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getreceivedbyaddress <paycoinaddress> [minconf=1]\n"
"Returns the total amount received by <paycoinaddress> in transactions with at least [minconf] confirmations.");
// Bitcoin address
CBitcoinAddress address = CBitcoinAddress(params[0].get_str());
CScript scriptPubKey;
if (!address.IsValid())
throw JSONRPCError(-5, "Invalid Paycoin address");
scriptPubKey.SetDestination(address.Get());
if (!IsMine(*pwalletMain,scriptPubKey))
return (double)0.0;
// Minimum confirmations
int nMinDepth = 1;
if (params.size() > 1)
nMinDepth = params[1].get_int();
// Tally
int64 nAmount = 0;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (wtx.IsCoinBase() || wtx.IsCoinStake() || !wtx.IsFinal())
continue;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
if (txout.scriptPubKey == scriptPubKey)
if (wtx.GetDepthInMainChain() >= nMinDepth)
nAmount += txout.nValue;
}
return ValueFromAmount(nAmount);
}
void GetAccountAddresses(string strAccount, set<CTxDestination>& setAddress)
{
BOOST_FOREACH(const PAIRTYPE(CTxDestination, string)& item, pwalletMain->mapAddressBook)
{
const CTxDestination& address = item.first;
const string& strName = item.second;
if (strName == strAccount)
setAddress.insert(address);
}
}
Value listminting(const Array& params, bool fHelp)
{
if(fHelp || params.size() > 2)
throw runtime_error(
"listminting [count=-1] [from=0]\n"
"Return all mintable outputs and provide details for each of them.");
int count = -1;
if(params.size() > 0)
count = params[0].get_int();
int from = 0;
if(params.size() > 1)
from = params[1].get_int();
Array ret;
const CBlockIndex *p = GetLastBlockIndex(pindexBest, true);
double difficulty = p->GetBlockDifficulty();
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
std::vector<KernelRecord> txList = KernelRecord::decomposeOutput(pwalletMain, it->second);
int minAge = nStakeMinAge / 60 / 60 / 24;
BOOST_FOREACH(KernelRecord& kr, txList) {
if(!kr.spent) {
if((count > 0 && ret.size() >= count) || from > 0) {
from--;
break;
}
string strTime = boost::lexical_cast<std::string>(kr.nTime);
string strAmount = boost::lexical_cast<std::string>(kr.nValue);
string strAge = boost::lexical_cast<std::string>(kr.getAge());
string strCoinAge = boost::lexical_cast<std::string>(kr.coinAge);
Array params;
params.push_back(kr.address);
string account = AccountFromValue(getaccount(params, false));
string status = "immature";
int searchInterval = 0;
int attemps = 0;
if(kr.getAge() >= minAge)
{
status = "mature";
searchInterval = (int)nLastCoinStakeSearchInterval;
attemps = GetAdjustedTime() - kr.nTime - nStakeMinAge;
}
Object obj;
obj.push_back(Pair("account", account));
obj.push_back(Pair("address", kr.address));
obj.push_back(Pair("input-txid", kr.hash.ToString()));
obj.push_back(Pair("time", strTime));
obj.push_back(Pair("amount", strAmount));
obj.push_back(Pair("status", status));
obj.push_back(Pair("age-in-day", strAge));
obj.push_back(Pair("coin-day-weight", strCoinAge));
obj.push_back(Pair("proof-of-stake-difficulty", difficulty));
obj.push_back(Pair("minting-probability-10min", kr.getProbToMintWithinNMinutes(difficulty, 10)));
obj.push_back(Pair("minting-probability-24h", kr.getProbToMintWithinNMinutes(difficulty, 60*24)));
obj.push_back(Pair("minting-probability-30d", kr.getProbToMintWithinNMinutes(difficulty, 60*24*30)));
obj.push_back(Pair("minting-probability-90d", kr.getProbToMintWithinNMinutes(difficulty, 60*24*90)));
obj.push_back(Pair("search-interval-in-sec", searchInterval));
obj.push_back(Pair("attempts", attemps));
ret.push_back(obj);
}
}
}
return ret;
}
Value getreceivedbyaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getreceivedbyaccount <account> [minconf=1]\n"
"Returns the total amount received by addresses with <account> in transactions with at least [minconf] confirmations.");
// Minimum confirmations
int nMinDepth = 1;
if (params.size() > 1)
nMinDepth = params[1].get_int();
// Get the set of pub keys assigned to account
string strAccount = AccountFromValue(params[0]);
set<CTxDestination> setAddress;
GetAccountAddresses(strAccount, setAddress);
// Tally
int64 nAmount = 0;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (wtx.IsCoinBase() || wtx.IsCoinStake() || !wtx.IsFinal())
continue;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
{
CTxDestination address;
if (ExtractDestination(txout.scriptPubKey, address) && IsMine(*pwalletMain, address) && setAddress.count(address))
if (wtx.GetDepthInMainChain() >= nMinDepth)
nAmount += txout.nValue;
}
}
return (double)nAmount / (double)COIN;
}
int64 GetAccountBalance(CWalletDB& walletdb, const string& strAccount, int nMinDepth)
{
int64 nBalance = 0;
// Tally wallet transactions
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (!wtx.IsFinal())
continue;
int64 nGenerated, nReceived, nSent, nFee;
wtx.GetAccountAmounts(strAccount, nGenerated, nReceived, nSent, nFee);
if (nReceived != 0 && wtx.GetDepthInMainChain() >= nMinDepth)
nBalance += nReceived;
nBalance += nGenerated - nSent - nFee;
}
// Tally internal accounting entries
nBalance += walletdb.GetAccountCreditDebit(strAccount);
return nBalance;
}
int64 GetAccountBalance(const string& strAccount, int nMinDepth)
{
CWalletDB walletdb(pwalletMain->strWalletFile);
return GetAccountBalance(walletdb, strAccount, nMinDepth);
}
Value getbalance(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
"getbalance [account] [minconf=1]\n"
"If [account] is not specified, returns the server's total available balance.\n"
"If [account] is specified, returns the balance in the account.");
if (params.size() == 0)
return ValueFromAmount(pwalletMain->GetBalance());
int nMinDepth = 1;
if (params.size() > 1)
nMinDepth = params[1].get_int();
if (params[0].get_str() == "*") {
// Calculate total balance a different way from GetBalance()
// (GetBalance() sums up all unspent TxOuts)
// getbalance and getbalance '*' should always return the same number.
int64 nBalance = 0;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (!wtx.IsFinal())
continue;
int64 allGeneratedImmature, allGeneratedMature, allFee;
allGeneratedImmature = allGeneratedMature = allFee = 0;
string strSentAccount;
list<pair<CTxDestination, int64> > listReceived;
list<pair<CTxDestination, int64> > listSent;
wtx.GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount);
if (wtx.GetDepthInMainChain() >= nMinDepth)
{
BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& r, listReceived)
nBalance += r.second;
}
BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& r, listSent)
nBalance -= r.second;
nBalance -= allFee;
nBalance += allGeneratedMature;
}
return ValueFromAmount(nBalance);
}
string strAccount = AccountFromValue(params[0]);
int64 nBalance = GetAccountBalance(strAccount, nMinDepth);
return ValueFromAmount(nBalance);
}
Value movecmd(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 3 || params.size() > 5)
throw runtime_error(
"move <fromaccount> <toaccount> <amount> [minconf=1] [comment]\n"
"Move from one account in your wallet to another.");
string strFrom = AccountFromValue(params[0]);
string strTo = AccountFromValue(params[1]);
int64 nAmount = AmountFromValue(params[2]);
if (params.size() > 3)
// unused parameter, used to be nMinDepth, keep type-checking it though
(void)params[3].get_int();
string strComment;
if (params.size() > 4)
strComment = params[4].get_str();
CWalletDB walletdb(pwalletMain->strWalletFile);
if (!walletdb.TxnBegin())
throw JSONRPCError(-20, "database error");
int64 nNow = GetAdjustedTime();
// Debit
CAccountingEntry debit;
debit.strAccount = strFrom;
debit.nCreditDebit = -nAmount;
debit.nTime = nNow;
debit.strOtherAccount = strTo;
debit.strComment = strComment;
walletdb.WriteAccountingEntry(debit);
// Credit
CAccountingEntry credit;
credit.strAccount = strTo;
credit.nCreditDebit = nAmount;
credit.nTime = nNow;
credit.strOtherAccount = strFrom;
credit.strComment = strComment;
walletdb.WriteAccountingEntry(credit);
if (!walletdb.TxnCommit())
throw JSONRPCError(-20, "database error");
return true;
}
Value sendfrom(const Array& params, bool fHelp)
{
if (pwalletMain->IsCrypted() && (fHelp || params.size() < 3 || params.size() > 6))
throw runtime_error(
"sendfrom <fromaccount> <topaycoinaddress> <amount> [minconf=1] [comment] [comment-to]\n"
"<amount> is a real and is rounded to the nearest 0.000001\n"
"requires wallet passphrase to be set with walletpassphrase first");
if (!pwalletMain->IsCrypted() && (fHelp || params.size() < 3 || params.size() > 6))
throw runtime_error(
"sendfrom <fromaccount> <topaycoinaddress> <amount> [minconf=1] [comment] [comment-to]\n"
"<amount> is a real and is rounded to the nearest 0.000001");
string strAccount = AccountFromValue(params[0]);
CBitcoinAddress address(params[1].get_str());
if (!address.IsValid())
throw JSONRPCError(-5, "Invalid Paycoin address");
int64 nAmount = AmountFromValue(params[2]);
if (nAmount < MIN_TXOUT_AMOUNT)
throw JSONRPCError(-101, "Send amount too small");
int nMinDepth = 1;
if (params.size() > 3)
nMinDepth = params[3].get_int();
CWalletTx wtx;
wtx.strFromAccount = strAccount;
if (params.size() > 4 && params[4].type() != null_type && !params[4].get_str().empty())
wtx.mapValue["comment"] = params[4].get_str();
if (params.size() > 5 && params[5].type() != null_type && !params[5].get_str().empty())
wtx.mapValue["to"] = params[5].get_str();
if (pwalletMain->IsLocked())
throw JSONRPCError(-13, "Error: Please enter the wallet passphrase with walletpassphrase first.");
// Check funds
int64 nBalance = GetAccountBalance(strAccount, nMinDepth);
if (nAmount > nBalance)
throw JSONRPCError(-6, "Account has insufficient funds");
// Send
string strError = pwalletMain->SendMoneyToDestination(address.Get(), nAmount, wtx);
if (strError != "")
throw JSONRPCError(-4, strError);
return wtx.GetHash().GetHex();
}
Value sendmany(const Array& params, bool fHelp)
{
if (pwalletMain->IsCrypted() && (fHelp || params.size() < 2 || params.size() > 4))
throw runtime_error(
"sendmany <fromaccount> {address:amount,...} [minconf=1] [comment]\n"
"amounts are double-precision floating point numbers\n"
"requires wallet passphrase to be set with walletpassphrase first");
if (!pwalletMain->IsCrypted() && (fHelp || params.size() < 2 || params.size() > 4))
throw runtime_error(
"sendmany <fromaccount> {address:amount,...} [minconf=1] [comment]\n"
"amounts are double-precision floating point numbers");
string strAccount = params[0].get_str();
bool fFromAllAccounts = false;
if (strAccount == "*")
{
fFromAllAccounts = true;
strAccount = "";
}
Object sendTo = params[1].get_obj();
int nMinDepth = 1;
if (params.size() > 2)
nMinDepth = params[2].get_int();
CWalletTx wtx;
wtx.strFromAccount = strAccount;
if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty())
wtx.mapValue["comment"] = params[3].get_str();
set<CBitcoinAddress> setAddress;
vector<pair<CScript, int64> > vecSend;
int64 totalAmount = 0;
BOOST_FOREACH(const Pair& s, sendTo)
{
CBitcoinAddress address(s.name_);
if (!address.IsValid())
throw JSONRPCError(-5, string("Invalid Paycoin address:")+s.name_);
if (setAddress.count(address))
throw JSONRPCError(-8, string("Invalid parameter, duplicated address: ")+s.name_);
setAddress.insert(address);
CScript scriptPubKey;
scriptPubKey.SetDestination(address.Get());
int64 nAmount = AmountFromValue(s.value_);
if (nAmount < MIN_TXOUT_AMOUNT)
throw JSONRPCError(-101, "Send amount too small");
totalAmount += nAmount;
vecSend.push_back(make_pair(scriptPubKey, nAmount));
}
if (pwalletMain->IsLocked())
throw JSONRPCError(-13, "Error: Please enter the wallet passphrase with walletpassphrase first.");
if (fWalletUnlockMintOnly)
throw JSONRPCError(-13, "Error: Wallet unlocked for block minting only.");
// Check funds
if (fFromAllAccounts)
{
int64 nBalance = pwalletMain->GetBalance();
if (totalAmount > nBalance)
throw JSONRPCError(-6, "Wallet has insufficient funds");
}
else
{
int64 nBalance = GetAccountBalance(strAccount, nMinDepth);
if (totalAmount > nBalance)
throw JSONRPCError(-6, "Account has insufficient funds");
}
// Send
CReserveKey keyChange(pwalletMain);
int64 nFeeRequired = 0;
bool fCreated = pwalletMain->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired);
if (!fCreated)
{
if (totalAmount + nFeeRequired > pwalletMain->GetBalance())
throw JSONRPCError(-6, "Insufficient funds");
throw JSONRPCError(-4, "Transaction creation failed");
}
if (!pwalletMain->CommitTransaction(wtx, keyChange))
throw JSONRPCError(-4, "Transaction commit failed");
return wtx.GetHash().GetHex();
}
struct tallyitem
{
int64 nAmount;
int nConf;
tallyitem()
{
nAmount = 0;
nConf = std::numeric_limits<int>::max();
}
};
Value ListReceived(const Array& params, bool fByAccounts)
{
// Minimum confirmations
int nMinDepth = 1;
if (params.size() > 0)
nMinDepth = params[0].get_int();
// Whether to include empty accounts
bool fIncludeEmpty = false;
if (params.size() > 1)
fIncludeEmpty = params[1].get_bool();
// Tally
map<CBitcoinAddress, tallyitem> mapTally;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (wtx.IsCoinBase() || wtx.IsCoinStake() || !wtx.IsFinal())
continue;
int nDepth = wtx.GetDepthInMainChain();
if (nDepth < nMinDepth)
continue;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
{
CTxDestination address;
if (!ExtractDestination(txout.scriptPubKey, address) || !IsMine(*pwalletMain, address))
continue;
tallyitem& item = mapTally[address];
item.nAmount += txout.nValue;
item.nConf = min(item.nConf, nDepth);
}
}
// Reply
Array ret;
map<string, tallyitem> mapAccountTally;
BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress, string)& item, pwalletMain->mapAddressBook)
{
const CBitcoinAddress& address = item.first;
const string& strAccount = item.second;
map<CBitcoinAddress, tallyitem>::iterator it = mapTally.find(address);
if (it == mapTally.end() && !fIncludeEmpty)
continue;
int64 nAmount = 0;
int nConf = std::numeric_limits<int>::max();
if (it != mapTally.end())
{
nAmount = (*it).second.nAmount;
nConf = (*it).second.nConf;
}
if (fByAccounts)
{
tallyitem& item = mapAccountTally[strAccount];
item.nAmount += nAmount;
item.nConf = min(item.nConf, nConf);
}
else
{
Object obj;
obj.push_back(Pair("address", address.ToString()));
obj.push_back(Pair("account", strAccount));
obj.push_back(Pair("amount", ValueFromAmount(nAmount)));
obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf)));
ret.push_back(obj);
}
}
if (fByAccounts)
{
for (map<string, tallyitem>::iterator it = mapAccountTally.begin(); it != mapAccountTally.end(); ++it)
{
int64 nAmount = (*it).second.nAmount;
int nConf = (*it).second.nConf;
Object obj;
obj.push_back(Pair("account", (*it).first));
obj.push_back(Pair("amount", ValueFromAmount(nAmount)));
obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf)));
ret.push_back(obj);
}
}
return ret;
}
Value listreceivedbyaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
"listreceivedbyaddress [minconf=1] [includeempty=false]\n"
"[minconf] is the minimum number of confirmations before payments are included.\n"
"[includeempty] whether to include addresses that haven't received any payments.\n"
"Returns an array of objects containing:\n"
" \"address\" : receiving address\n"
" \"account\" : the account of the receiving address\n"
" \"amount\" : total amount received by the address\n"
" \"confirmations\" : number of confirmations of the most recent transaction included");
return ListReceived(params, false);
}
Value listreceivedbyaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
"listreceivedbyaccount [minconf=1] [includeempty=false]\n"
"[minconf] is the minimum number of confirmations before payments are included.\n"
"[includeempty] whether to include accounts that haven't received any payments.\n"
"Returns an array of objects containing:\n"
" \"account\" : the account of the receiving addresses\n"
" \"amount\" : total amount received by addresses with this account\n"
" \"confirmations\" : number of confirmations of the most recent transaction included");
return ListReceived(params, true);
}
void ListTransactions(const CWalletTx& wtx, const string& strAccount, int nMinDepth, bool fLong, Array& ret)
{
int64 nGeneratedImmature, nGeneratedMature, nFee;
string strSentAccount;
list<pair<CTxDestination, int64> > listReceived;
list<pair<CTxDestination, int64> > listSent;
wtx.GetAmounts(nGeneratedImmature, nGeneratedMature, listReceived, listSent, nFee, strSentAccount);
bool fAllAccounts = (strAccount == string("*"));
// Generated blocks assigned to account ""
if ((nGeneratedMature+nGeneratedImmature) != 0 && (fAllAccounts || strAccount == ""))
{
Object entry;
entry.push_back(Pair("account", string("")));
if (nGeneratedImmature)
{
entry.push_back(Pair("category", wtx.GetDepthInMainChain() ? "immature" : "orphan"));
entry.push_back(Pair("amount", ValueFromAmount(nGeneratedImmature)));
}
else if (wtx.IsCoinStake())
{
entry.push_back(Pair("category", "stake"));
entry.push_back(Pair("amount", ValueFromAmount(nGeneratedMature)));
}
else
{
entry.push_back(Pair("category", "generate"));
entry.push_back(Pair("amount", ValueFromAmount(nGeneratedMature)));
}
if (fLong)
WalletTxToJSON(wtx, entry);
ret.push_back(entry);
}
// Sent
if ((!listSent.empty() || nFee != 0) && (fAllAccounts || strAccount == strSentAccount))
{
BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& s, listSent)
{
Object entry;
entry.push_back(Pair("account", strSentAccount));
entry.push_back(Pair("address", CBitcoinAddress(s.first).ToString()));
entry.push_back(Pair("category", "send"));
entry.push_back(Pair("amount", ValueFromAmount(-s.second)));
entry.push_back(Pair("fee", ValueFromAmount(-nFee)));
if (fLong)
WalletTxToJSON(wtx, entry);
ret.push_back(entry);
}
}
// Received
if (listReceived.size() > 0 && wtx.GetDepthInMainChain() >= nMinDepth)
{
BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& r, listReceived)
{
string account;
if (pwalletMain->mapAddressBook.count(r.first))
account = pwalletMain->mapAddressBook[r.first];
if (fAllAccounts || (account == strAccount))
{
Object entry;
entry.push_back(Pair("account", account));
entry.push_back(Pair("address", CBitcoinAddress(r.first).ToString()));
entry.push_back(Pair("category", "receive"));
entry.push_back(Pair("amount", ValueFromAmount(r.second)));
if (fLong)
WalletTxToJSON(wtx, entry);
ret.push_back(entry);
}
}
}
}
void AcentryToJSON(const CAccountingEntry& acentry, const string& strAccount, Array& ret)
{
bool fAllAccounts = (strAccount == string("*"));
if (fAllAccounts || acentry.strAccount == strAccount)
{
Object entry;
entry.push_back(Pair("account", acentry.strAccount));
entry.push_back(Pair("category", "move"));
entry.push_back(Pair("time", (boost::int64_t)acentry.nTime));
entry.push_back(Pair("amount", ValueFromAmount(acentry.nCreditDebit)));
entry.push_back(Pair("otheraccount", acentry.strOtherAccount));
entry.push_back(Pair("comment", acentry.strComment));
ret.push_back(entry);
}
}
Value listtransactions(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 3)
throw runtime_error(
"listtransactions [account] [count=10] [from=0]\n"
"Returns up to [count] most recent transactions skipping the first [from] transactions for account [account].");
string strAccount = "*";
if (params.size() > 0)
strAccount = params[0].get_str();
int nCount = 10;
if (params.size() > 1)
nCount = params[1].get_int();
int nFrom = 0;
if (params.size() > 2)
nFrom = params[2].get_int();
if (nCount < 0)
throw JSONRPCError(-8, "Negative count");
if (nFrom < 0)
throw JSONRPCError(-8, "Negative from");
Array ret;
CWalletDB walletdb(pwalletMain->strWalletFile);
// First: get all CWalletTx and CAccountingEntry into a sorted-by-time multimap.
typedef pair<CWalletTx*, CAccountingEntry*> TxPair;
typedef multimap<int64, TxPair > TxItems;
TxItems txByTime;
// Note: maintaining indices in the database of (account,time) --> txid and (account, time) --> acentry
// would make this much faster for applications that do this a lot.
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
CWalletTx* wtx = &((*it).second);
txByTime.insert(make_pair(wtx->GetTxTime(), TxPair(wtx, (CAccountingEntry*)0)));
}
list<CAccountingEntry> acentries;
walletdb.ListAccountCreditDebit(strAccount, acentries);
BOOST_FOREACH(CAccountingEntry& entry, acentries)
{
txByTime.insert(make_pair(entry.nTime, TxPair((CWalletTx*)0, &entry)));
}
// iterate backwards until we have nCount items to return:
for (TxItems::reverse_iterator it = txByTime.rbegin(); it != txByTime.rend(); ++it)
{
CWalletTx *const pwtx = (*it).second.first;
if (pwtx != 0)
ListTransactions(*pwtx, strAccount, 0, true, ret);
CAccountingEntry *const pacentry = (*it).second.second;
if (pacentry != 0)
AcentryToJSON(*pacentry, strAccount, ret);
if (ret.size() >= (nCount+nFrom)) break;
}
// ret is newest to oldest
if (nFrom > (int)ret.size())
nFrom = ret.size();
if ((nFrom + nCount) > (int)ret.size())
nCount = ret.size() - nFrom;
Array::iterator first = ret.begin();
std::advance(first, nFrom);
Array::iterator last = ret.begin();
std::advance(last, nFrom+nCount);
if (last != ret.end()) ret.erase(last, ret.end());
if (first != ret.begin()) ret.erase(ret.begin(), first);
std::reverse(ret.begin(), ret.end()); // Return oldest to newest
return ret;
}
Value listaccounts(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"listaccounts [minconf=1]\n"
"Returns Object that has account names as keys, account balances as values.");
int nMinDepth = 1;
if (params.size() > 0)
nMinDepth = params[0].get_int();
map<string, int64> mapAccountBalances;
BOOST_FOREACH(const PAIRTYPE(CTxDestination, string)& entry, pwalletMain->mapAddressBook) {
if (IsMine(*pwalletMain, entry.first)) // This address belongs to me
mapAccountBalances[entry.second] = 0;
}
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
int64 nGeneratedImmature, nGeneratedMature, nFee;
string strSentAccount;
list<pair<CTxDestination, int64> > listReceived;
list<pair<CTxDestination, int64> > listSent;
wtx.GetAmounts(nGeneratedImmature, nGeneratedMature, listReceived, listSent, nFee, strSentAccount);
mapAccountBalances[strSentAccount] -= nFee;
BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& s, listSent)
mapAccountBalances[strSentAccount] -= s.second;
if (wtx.GetDepthInMainChain() >= nMinDepth)
{
mapAccountBalances[""] += nGeneratedMature;
BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& r, listReceived)
if (pwalletMain->mapAddressBook.count(r.first))
mapAccountBalances[pwalletMain->mapAddressBook[r.first]] += r.second;
else
mapAccountBalances[""] += r.second;
}
}
list<CAccountingEntry> acentries;
CWalletDB(pwalletMain->strWalletFile).ListAccountCreditDebit("*", acentries);
BOOST_FOREACH(const CAccountingEntry& entry, acentries)
mapAccountBalances[entry.strAccount] += entry.nCreditDebit;
Object ret;
BOOST_FOREACH(const PAIRTYPE(string, int64)& accountBalance, mapAccountBalances) {
ret.push_back(Pair(accountBalance.first, ValueFromAmount(accountBalance.second)));
}
return ret;
}
Value listsinceblock(const Array& params, bool fHelp)
{
if (fHelp)
throw runtime_error(
"listsinceblock [blockhash] [target-confirmations]\n"
"Get all transactions in blocks since block [blockhash], or all transactions if omitted");
CBlockIndex *pindex = NULL;
int target_confirms = 1;
if (params.size() > 0)
{
uint256 blockId = 0;
blockId.SetHex(params[0].get_str());
pindex = CBlockLocator(blockId).GetBlockIndex();
}
if (params.size() > 1)
{
target_confirms = params[1].get_int();
if (target_confirms < 1)
throw JSONRPCError(-8, "Invalid parameter");
}
int depth = pindex ? (1 + nBestHeight - pindex->nHeight) : -1;
Array transactions;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); it++)
{
CWalletTx tx = (*it).second;
if (depth == -1 || tx.GetDepthInMainChain() < depth)
ListTransactions(tx, "*", 0, true, transactions);
}
uint256 lastblock;
if (target_confirms == 1)
{
lastblock = hashBestChain;
}
else
{
int target_height = pindexBest->nHeight + 1 - target_confirms;
CBlockIndex *block;
for (block = pindexBest;
block && block->nHeight > target_height;
block = block->pprev) { }
lastblock = block ? block->GetBlockHash() : 0;
}
Object ret;
ret.push_back(Pair("transactions", transactions));
ret.push_back(Pair("lastblock", lastblock.GetHex()));
return ret;
}
Value gettransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"gettransaction <txid>\n"
"Get detailed information about <txid>");
uint256 hash;
hash.SetHex(params[0].get_str());
Object entry;
if (!pwalletMain->mapWallet.count(hash))
throw JSONRPCError(-5, "Invalid or non-wallet transaction id");
const CWalletTx& wtx = pwalletMain->mapWallet[hash];
int64 nCredit = wtx.GetCredit();
int64 nDebit = wtx.GetDebit();
int64 nNet = nCredit - nDebit;
int64 nFee = (wtx.IsFromMe() ? wtx.GetValueOut() - nDebit : 0);
entry.push_back(Pair("amount", ValueFromAmount(nNet - nFee)));
if (wtx.IsFromMe())
entry.push_back(Pair("fee", ValueFromAmount(nFee)));
WalletTxToJSON(pwalletMain->mapWallet[hash], entry);
Array details;
ListTransactions(pwalletMain->mapWallet[hash], "*", 0, false, details);
entry.push_back(Pair("details", details));
return entry;
}
Value backupwallet(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"backupwallet <destination>\n"
"Safely copies wallet.dat to destination, which can be a directory or a path with filename.");
string strDest = params[0].get_str();
BackupWallet(*pwalletMain, strDest);
return Value::null;
}
Value keypoolrefill(const Array& params, bool fHelp)
{
if (pwalletMain->IsCrypted() && (fHelp || params.size() > 0))
throw runtime_error(
"keypoolrefill\n"
"Fills the keypool, requires wallet passphrase to be set.");
if (!pwalletMain->IsCrypted() && (fHelp || params.size() > 0))
throw runtime_error(
"keypoolrefill\n"
"Fills the keypool.");
if (pwalletMain->IsLocked())
throw JSONRPCError(-13, "Error: Please enter the wallet passphrase with walletpassphrase first.");
pwalletMain->TopUpKeyPool();
if (pwalletMain->GetKeyPoolSize() < GetArg("-keypool", 100))
throw JSONRPCError(-4, "Error refreshing keypool.");
return Value::null;
}
void ThreadTopUpKeyPool(void* parg)
{
pwalletMain->TopUpKeyPool();
}
void ThreadCleanWalletPassphrase(void* parg)
{
int64 nMyWakeTime = GetTimeMillis() + *((int64*)parg) * 1000;
ENTER_CRITICAL_SECTION(cs_nWalletUnlockTime);
if (nWalletUnlockTime == 0)
{
nWalletUnlockTime = nMyWakeTime;
do
{
if (nWalletUnlockTime==0)
break;
int64 nToSleep = nWalletUnlockTime - GetTimeMillis();
if (nToSleep <= 0)
break;
LEAVE_CRITICAL_SECTION(cs_nWalletUnlockTime);
Sleep(nToSleep);
ENTER_CRITICAL_SECTION(cs_nWalletUnlockTime);
} while(1);
if (nWalletUnlockTime)
{
nWalletUnlockTime = 0;
pwalletMain->Lock();
}
}
else
{
if (nWalletUnlockTime < nMyWakeTime)
nWalletUnlockTime = nMyWakeTime;
}
LEAVE_CRITICAL_SECTION(cs_nWalletUnlockTime);
delete (int64*)parg;
}
Value walletpassphrase(const Array& params, bool fHelp)
{
if (pwalletMain->IsCrypted() && (fHelp || params.size() < 2 || params.size() > 3))
throw runtime_error(
"walletpassphrase <passphrase> <timeout> [mintonly]\n"
"Stores the wallet decryption key in memory for <timeout> seconds.\n"
"mintonly is optional true/false allowing only block minting.");
if (fHelp)
return true;
if (!pwalletMain->IsCrypted())
throw JSONRPCError(-15, "Error: running with an unencrypted wallet, but walletpassphrase was called.");
if (!pwalletMain->IsLocked())
throw JSONRPCError(-17, "Error: Wallet is already unlocked, use walletlock first if need to change unlock settings.");
// Note that the walletpassphrase is stored in params[0] which is not mlock()ed
SecureString strWalletPass;
strWalletPass.reserve(100);
// TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
// Alternately, find a way to make params[0] mlock()'d to begin with.
strWalletPass = params[0].get_str().c_str();
if (strWalletPass.length() > 0)
{
if (!pwalletMain->Unlock(strWalletPass))
throw JSONRPCError(-14, "Error: The wallet passphrase entered was incorrect.");
}
else
throw runtime_error(
"walletpassphrase <passphrase> <timeout>\n"
"Stores the wallet decryption key in memory for <timeout> seconds.");
CreateThread(ThreadTopUpKeyPool, NULL);
int64* pnSleepTime = new int64(params[1].get_int64());
CreateThread(ThreadCleanWalletPassphrase, pnSleepTime);
// paycoin: if user OS account compromised prevent trivial sendmoney commands
if (params.size() > 2)
fWalletUnlockMintOnly = params[2].get_bool();
else
fWalletUnlockMintOnly = false;
return Value::null;
}
Value walletpassphrasechange(const Array& params, bool fHelp)
{
if (pwalletMain->IsCrypted() && (fHelp || params.size() != 2))
throw runtime_error(
"walletpassphrasechange <oldpassphrase> <newpassphrase>\n"
"Changes the wallet passphrase from <oldpassphrase> to <newpassphrase>.");
if (fHelp)
return true;
if (!pwalletMain->IsCrypted())
throw JSONRPCError(-15, "Error: running with an unencrypted wallet, but walletpassphrasechange was called.");
// TODO: get rid of these .c_str() calls by implementing SecureString::operator=(std::string)
// Alternately, find a way to make params[0] mlock()'d to begin with.
SecureString strOldWalletPass;
strOldWalletPass.reserve(100);
strOldWalletPass = params[0].get_str().c_str();
SecureString strNewWalletPass;
strNewWalletPass.reserve(100);
strNewWalletPass = params[1].get_str().c_str();
if (strOldWalletPass.length() < 1 || strNewWalletPass.length() < 1)
throw runtime_error(
"walletpassphrasechange <oldpassphrase> <newpassphrase>\n"
"Changes the wallet passphrase from <oldpassphrase> to <newpassphrase>.");
if (!pwalletMain->ChangeWalletPassphrase(strOldWalletPass, strNewWalletPass))
throw JSONRPCError(-14, "Error: The wallet passphrase entered was incorrect.");
return Value::null;
}
Value walletlock(const Array& params, bool fHelp)
{
if (pwalletMain->IsCrypted() && (fHelp || params.size() != 0))
throw runtime_error(
"walletlock\n"
"Removes the wallet encryption key from memory, locking the wallet.\n"
"After calling this method, you will need to call walletpassphrase again\n"
"before being able to call any methods which require the wallet to be unlocked.");
if (fHelp)
return true;
if (!pwalletMain->IsCrypted())
throw JSONRPCError(-15, "Error: running with an unencrypted wallet, but walletlock was called.");
{
LOCK(cs_nWalletUnlockTime);
pwalletMain->Lock();
nWalletUnlockTime = 0;
}
return Value::null;
}
Value encryptwallet(const Array& params, bool fHelp)
{
if (!pwalletMain->IsCrypted() && (fHelp || params.size() != 1))
throw runtime_error(
"encryptwallet <passphrase>\n"
"Encrypts the wallet with <passphrase>.");
if (fHelp)
return true;
if (pwalletMain->IsCrypted())
throw JSONRPCError(-15, "Error: running with an encrypted wallet, but encryptwallet was called.");
// TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
// Alternately, find a way to make params[0] mlock()'d to begin with.
SecureString strWalletPass;
strWalletPass.reserve(100);
strWalletPass = params[0].get_str().c_str();
if (strWalletPass.length() < 1)
throw runtime_error(
"encryptwallet <passphrase>\n"
"Encrypts the wallet with <passphrase>.");
if (!pwalletMain->EncryptWallet(strWalletPass))
throw JSONRPCError(-16, "Error: Failed to encrypt the wallet.");
// BDB seems to have a bad habit of writing old data into
// slack space in .dat files; that is bad if the old data is
// unencrypted private keys. So:
StartShutdown();
return "wallet encrypted; Paycoin server stopping, restart to run with encrypted wallet";
}
class DescribeAddressVisitor : public boost::static_visitor<Object>
{
public:
Object operator()(const CNoDestination &dest) const { return Object(); }
Object operator()(const CKeyID &keyID) const {
Object obj;
CPubKey vchPubKey;
pwalletMain->GetPubKey(keyID, vchPubKey);
obj.push_back(Pair("isscript", false));
obj.push_back(Pair("pubkey", HexStr(vchPubKey.Raw())));
obj.push_back(Pair("iscompressed", vchPubKey.IsCompressed()));
return obj;
}
Object operator()(const CScriptID &scriptID) const {
Object obj;
obj.push_back(Pair("isscript", true));
CScript subscript;
pwalletMain->GetCScript(scriptID, subscript);
std::vector<CTxDestination> addresses;
txnouttype whichType;
int nRequired;
ExtractDestinations(subscript, whichType, addresses, nRequired);
obj.push_back(Pair("script", GetTxnOutputType(whichType)));
Array a;
BOOST_FOREACH(const CTxDestination& addr, addresses)
a.push_back(CBitcoinAddress(addr).ToString());
obj.push_back(Pair("addresses", a));
if (whichType == TX_MULTISIG)
obj.push_back(Pair("sigsrequired", nRequired));
return obj;
}
};
Value validateaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"validateaddress <paycoinaddress>\n"
"Return information about <paycoinaddress>.");
CBitcoinAddress address(params[0].get_str());
bool isValid = address.IsValid();
Object ret;
ret.push_back(Pair("isvalid", isValid));
if (isValid)
{
CTxDestination dest = address.Get();
string currentAddress = address.ToString();
ret.push_back(Pair("address", currentAddress));
bool fMine = IsMine(*pwalletMain, dest);
ret.push_back(Pair("ismine", fMine));
if (fMine) {
Object detail = boost::apply_visitor(DescribeAddressVisitor(), dest);
ret.insert(ret.end(), detail.begin(), detail.end());
}
if (pwalletMain->mapAddressBook.count(dest))
ret.push_back(Pair("account", pwalletMain->mapAddressBook[dest]));
}
return ret;
}
Value getwork(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"getwork [data]\n"
"If [data] is not specified, returns formatted hash data to work on:\n"
" \"midstate\" : precomputed hash state after hashing the first half of the data (DEPRECATED)\n" // deprecated
" \"data\" : block data\n"
" \"hash1\" : formatted hash buffer for second hash (DEPRECATED)\n" // deprecated
" \"target\" : little endian hash target\n"
"If [data] is specified, tries to solve the block and returns true if it was successful.");
if (vNodes.empty())
throw JSONRPCError(-9, "Paycoin is not connected!");
if (IsInitialBlockDownload())
throw JSONRPCError(-10, "Paycoin is downloading blocks...");
if (pindexBest != NULL && pindexBest->nTime > POW_END_TIME)
throw JSONRPCError(-10, "Paycoin is currently on pure PoS state");
typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
static mapNewBlock_t mapNewBlock;
static vector<CBlock*> vNewBlock;
if (params.size() == 0)
{
// Update block
static unsigned int nTransactionsUpdatedLast;
static CBlockIndex* pindexPrev;
static int64 nStart;
static CBlock* pblock;
if (pindexPrev != pindexBest ||
(nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
{
if (pindexPrev != pindexBest)
{
// Deallocate old blocks since they're obsolete now
mapNewBlock.clear();
BOOST_FOREACH(CBlock* pblock, vNewBlock)
delete pblock;
vNewBlock.clear();
}
nTransactionsUpdatedLast = nTransactionsUpdated;
pindexPrev = pindexBest;
nStart = GetTime();
// Create new block
pblock = CreateNewBlock(*pMiningKey, pwalletMain);
if (!pblock)
throw JSONRPCError(-7, "Out of memory");
vNewBlock.push_back(pblock);
}
// Update nTime
pblock->UpdateTime(pindexPrev);
pblock->nNonce = 0;
// Update nExtraNonce
static unsigned int nExtraNonce = 0;
IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
// Save
mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
// Prebuild hash buffers
char pmidstate[32];
char pdata[128];
char phash1[64];
FormatHashBuffers(pblock, pmidstate, pdata, phash1);
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
Object result;
result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate)))); // deprecated
result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
result.push_back(Pair("hash1", HexStr(BEGIN(phash1), END(phash1)))); // deprecated
result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
return result;
}
else
{
// Parse parameters
vector<unsigned char> vchData = ParseHex(params[0].get_str());
if (vchData.size() != 128)
throw JSONRPCError(-8, "Invalid parameter");
CBlock* pdata = (CBlock*)&vchData[0];
// Byte reverse
for (int i = 0; i < 128/4; i++)
((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
// Get saved block
if (!mapNewBlock.count(pdata->hashMerkleRoot))
return false;
CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
pblock->nTime = pdata->nTime;
pblock->nNonce = pdata->nNonce;
pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
pblock->hashMerkleRoot = pblock->BuildMerkleTree();
assert(pwalletMain != NULL);
if (!pblock->SignBlock(*pwalletMain))
throw JSONRPCError(-100, "Unable to sign block, wallet locked?");
return CheckWork(pblock, *pwalletMain, *pMiningKey);
}
}
Value getblocktemplate(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"getblocktemplate [params]\n"
"Returns data needed to construct a block to work on:\n"
" \"version\" : block version\n"
" \"previousblockhash\" : hash of current highest block\n"
" \"transactions\" : contents of non-coinbase transactions that should be included in the next block\n"
" \"coinbaseaux\" : data that should be included in coinbase\n"
" \"coinbasevalue\" : maximum allowable input to coinbase transaction, including the generation award and transaction fees\n"
" \"target\" : hash target\n"
" \"mintime\" : minimum timestamp appropriate for next block\n"
" \"curtime\" : current timestamp\n"
" \"mutable\" : list of ways the block template may be changed\n"
" \"noncerange\" : range of valid nonces\n"
" \"sigoplimit\" : limit of sigops in blocks\n"
" \"sizelimit\" : limit of block size\n"
" \"bits\" : compressed target of next block\n"
" \"height\" : height of the next block\n"
"See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
std::string strMode = "template";
if (params.size() > 0)
{
const Object& oparam = params[0].get_obj();
const Value& modeval = find_value(oparam, "mode");
if (modeval.type() == str_type)
strMode = modeval.get_str();
else if (modeval.type() == null_type)
{
/* Do nothing */
}
else
throw JSONRPCError(-8, "Invalid mode");
}
if (strMode != "template")
throw JSONRPCError(-8, "Invalid mode");
{
if (vNodes.empty())
throw JSONRPCError(-9, "Paycoin is not connected!");
if (IsInitialBlockDownload())
throw JSONRPCError(-10, "Paycoin is downloading blocks...");
if (pindexBest != NULL && pindexBest->nTime > POW_END_TIME)
throw JSONRPCError(-10, "Paycoin is currently on pure PoS state");
// Update block
static unsigned int nTransactionsUpdatedLast;
static CBlockIndex* pindexPrev;
static int64 nStart;
static CBlock* pblock;
if (pindexPrev != pindexBest ||
(nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 5))
{
// Clear pindexPrev so future calls make a new block, despite any failures from here on
pindexPrev = NULL;
// Store the pindexBest used before CreateNewBlock, to avoid races
nTransactionsUpdatedLast = nTransactionsUpdated;
CBlockIndex* pindexPrevNew = pindexBest;
nStart = GetTime();
// Create new block
if(pblock)
{
delete pblock;
pblock = NULL;
}
pblock = CreateNewBlock(*pMiningKey, pwalletMain);
if (!pblock)
throw JSONRPCError(-7, "Out of memory");
// Need to update only after we know CreateNewBlock succeeded
pindexPrev = pindexPrevNew;
}
// Update nTime
pblock->UpdateTime(pindexPrev);
pblock->nNonce = 0;
Array transactions;
map<uint256, int64_t> setTxIndex;
int i = 0;
CTxDB txdb("r");
BOOST_FOREACH (CTransaction& tx, pblock->vtx)
{
uint256 txHash = tx.GetHash();
setTxIndex[txHash] = i++;
if (tx.IsCoinBase())
continue;
Object entry;
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
ssTx << tx;
entry.push_back(Pair("data", HexStr(ssTx.begin(), ssTx.end())));
entry.push_back(Pair("hash", txHash.GetHex()));
MapPrevTx mapInputs;
map<uint256, CTxIndex> mapUnused;
bool fInvalid = false;
if (tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
{
entry.push_back(Pair("fee", (int64_t)(tx.GetValueIn(mapInputs) - tx.GetValueOut())));
Array deps;
BOOST_FOREACH (MapPrevTx::value_type& inp, mapInputs)
{
if (setTxIndex.count(inp.first))
deps.push_back(setTxIndex[inp.first]);
}
entry.push_back(Pair("depends", deps));
int64_t nSigOps = tx.GetLegacySigOpCount();
nSigOps += tx.GetP2SHSigOpCount(mapInputs);
entry.push_back(Pair("sigops", nSigOps));
}
transactions.push_back(entry);
}
Object aux;
aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
static Array aMutable;
if (aMutable.empty())
{
aMutable.push_back("time");
aMutable.push_back("transactions");
aMutable.push_back("prevblock");
}
Object result;
result.push_back(Pair("version", pblock->nVersion));
result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
result.push_back(Pair("transactions", transactions));
result.push_back(Pair("coinbaseaux", aux));
result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue));
result.push_back(Pair("target", hashTarget.GetHex()));
result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1));
result.push_back(Pair("mutable", aMutable));
result.push_back(Pair("noncerange", "00000000ffffffff"));
result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS));
result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE));
result.push_back(Pair("curtime", (int64_t)pblock->nTime));
result.push_back(Pair("bits", HexBits(pblock->nBits)));
result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1)));
return result;
}
}
Value submitblock(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"submitblock <hex data> [optional-params-obj]\n"
"[optional-params-obj] parameter is currently ignored.\n"
"Attempts to submit new block to network.\n"
"See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
vector<unsigned char> blockData(ParseHex(params[0].get_str()));
CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);
CBlock block;
try {
ssBlock >> block;
}
catch (std::exception &e) {
throw JSONRPCError(-22, "Block decode failed");
}
// Paycoin: sign block
if (!block.SignBlock(*pwalletMain))
throw JSONRPCError(-100, "Unable to sign block, wallet locked?");
bool fAccepted = CheckWork(&block, *pwalletMain, *pMiningKey);
if (!fAccepted)
return "rejected"; // TODO: report validation state
return Value::null;
}
Value getblockhash(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"getblockhash <index>\n"
"Returns hash of block in best-block-chain at <index>.");
int nHeight = params[0].get_int();
if (nHeight < 0 || nHeight > nBestHeight)
throw runtime_error("Block number out of range.");
CBlock block;
CBlockIndex* pblockindex = mapBlockIndex[hashBestChain];
while (pblockindex->nHeight > nHeight)
pblockindex = pblockindex->pprev;
return pblockindex->phashBlock->GetHex();
}
Value getblock(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 3)
throw runtime_error(
"getblock <hash> [txinfo] [txdetails]\n"
"txinfo optional to print more detailed tx info\n"
"txdetails optional to print even more detailed tx info\n"
"Returns details of a block with given block-hash.");
std::string strHash = params[0].get_str();
uint256 hash(strHash);
if (mapBlockIndex.count(hash) == 0)
throw JSONRPCError(-5, "Block not found");
CBlock block;
CBlockIndex* pblockindex = mapBlockIndex[hash];
block.ReadFromDisk(pblockindex, true);
bool fTxInfo = params.size() > 1 ? params[1].get_bool() : false;
bool fTxDetails = params.size() > 2 ? params[2].get_bool() : false;
return blockToJSON(block, pblockindex, fTxInfo, fTxDetails);
}
// paycoin: get information of sync-checkpoint
Value getcheckpoint(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getcheckpoint\n"
"Show info of synchronized checkpoint.\n");
Object result;
CBlockIndex* pindexCheckpoint;
result.push_back(Pair("synccheckpoint", Checkpoints::hashSyncCheckpoint.ToString().c_str()));
pindexCheckpoint = mapBlockIndex[Checkpoints::hashSyncCheckpoint];
result.push_back(Pair("height", pindexCheckpoint->nHeight));
result.push_back(Pair("timestamp", DateTimeStrFormat(pindexCheckpoint->GetBlockTime()).c_str()));
if (mapArgs.count("-checkpointkey"))
result.push_back(Pair("checkpointmaster", true));
return result;
}
// paycoin: reserve balance from being staked for network protection
Value reservebalance(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
"reservebalance [<reserve> [amount]]\n"
"<reserve> is true or false to turn balance reserve on or off.\n"
"<amount> is a real and rounded to cent.\n"
"Set reserve amount not participating in network protection.\n"
"If no parameters provided current setting is printed.\n");
if (params.size() > 0)
{
bool fReserve = params[0].get_bool();
if (fReserve)
{
if (params.size() == 1)
throw runtime_error("must provide amount to reserve balance.\n");
int64 nAmount = AmountFromValue(params[1]);
nAmount = (nAmount / CENT) * CENT; // round to cent
if (nAmount < 0)
throw runtime_error("amount cannot be negative.\n");
mapArgs["-reservebalance"] = FormatMoney(nAmount).c_str();
}
else
{
if (params.size() > 1)
throw runtime_error("cannot specify amount to turn off reserve.\n");
mapArgs["-reservebalance"] = "0";
}
}
Object result;
int64 nReserveBalance = 0;
if (mapArgs.count("-reservebalance") && !ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
throw runtime_error("invalid reserve balance amount\n");
result.push_back(Pair("reserve", (nReserveBalance > 0)));
result.push_back(Pair("amount", ValueFromAmount(nReserveBalance)));
return result;
}
// paycoin: check wallet integrity
Value checkwallet(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 0)
throw runtime_error(
"checkwallet\n"
"Check wallet for integrity.\n");
int nMismatchSpent;
int64 nBalanceInQuestion;
pwalletMain->FixSpentCoins(nMismatchSpent, nBalanceInQuestion, true);
Object result;
if (nMismatchSpent == 0)
result.push_back(Pair("wallet check passed", true));
else
{
result.push_back(Pair("mismatched spent coins", nMismatchSpent));
result.push_back(Pair("amount in question", ValueFromAmount(nBalanceInQuestion)));
}
return result;
}
// paycoin: repair wallet
Value repairwallet(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 0)
throw runtime_error(
"repairwallet\n"
"Repair wallet if checkwallet reports any problem.\n");
int nMismatchSpent;
int64 nBalanceInQuestion;
pwalletMain->FixSpentCoins(nMismatchSpent, nBalanceInQuestion);
Object result;
if (nMismatchSpent == 0)
result.push_back(Pair("wallet check passed", true));
else
{
result.push_back(Pair("mismatched spent coins", nMismatchSpent));
result.push_back(Pair("amount affected by repair", ValueFromAmount(nBalanceInQuestion)));
}
return result;
}
// paycoin: make a public-private key pair
Value makekeypair(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"makekeypair [prefix]\n"
"Make a public/private key pair.\n"
"[prefix] is optional preferred prefix for the public key.\n");
string strPrefix = "";
if (params.size() > 0)
strPrefix = params[0].get_str();
CKey key;
int nCount = 0;
do
{
key.MakeNewKey(false);
nCount++;
} while (nCount < 10000 && strPrefix != HexStr(key.GetPubKey().Raw()).substr(0, strPrefix.size()));
if (strPrefix != HexStr(key.GetPubKey().Raw()).substr(0, strPrefix.size()))
return Value::null;
CPrivKey vchPrivKey = key.GetPrivKey();
Object result;
result.push_back(Pair("PrivateKey", HexStr<CPrivKey::iterator>(vchPrivKey.begin(), vchPrivKey.end())));
result.push_back(Pair("PublicKey", HexStr(key.GetPubKey().Raw())));
return result;
}
extern CCriticalSection cs_mapAlerts;
extern map<uint256, CAlert> mapAlerts;
// paycoin: send alert.
// There is a known deadlock situation with ThreadMessageHandler
// ThreadMessageHandler: holds cs_vSend and acquiring cs_main in SendMessages()
// ThreadRPCServer: holds cs_main and acquiring cs_vSend in alert.RelayTo()/PushMessage()/BeginMessage()
Value sendalert(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 6)
throw runtime_error(
"sendalert <message> <privatekey> <minver> <maxver> <priority> <id> [cancelupto]\n"
"<message> is the alert text message\n"
"<privatekey> is hex string of alert master private key\n"
"<minver> is the minimum applicable internal client version\n"
"<maxver> is the maximum applicable internal client version\n"
"<priority> is integer priority number\n"
"<id> is the alert id\n"
"[cancelupto] cancels all alert id's up to this number\n"
"Returns true or false.");
CAlert alert;
CKey key;
alert.strStatusBar = params[0].get_str();
alert.nMinVer = params[2].get_int();
alert.nMaxVer = params[3].get_int();
alert.nPriority = params[4].get_int();
alert.nID = params[5].get_int();
if (params.size() > 6)
alert.nCancel = params[6].get_int();
alert.nVersion = PROTOCOL_VERSION;
alert.nRelayUntil = GetAdjustedTime() + 365*24*60*60;
alert.nExpiration = GetAdjustedTime() + 365*24*60*60;
CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION);
sMsg << (CUnsignedAlert)alert;
alert.vchMsg = vector<unsigned char>(sMsg.begin(), sMsg.end());
vector<unsigned char> vchPrivKey = ParseHex(params[1].get_str());
key.SetPrivKey(CPrivKey(vchPrivKey.begin(), vchPrivKey.end())); // if key is not correct openssl may crash
if (!key.Sign(Hash(alert.vchMsg.begin(), alert.vchMsg.end()), alert.vchSig))
throw runtime_error(
"Unable to sign alert, check private key?\n");
if(!alert.ProcessAlert())
throw runtime_error(
"Failed to process alert.\n");
// Relay alert
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
alert.RelayTo(pnode);
}
Object result;
result.push_back(Pair("strStatusBar", alert.strStatusBar));
result.push_back(Pair("nVersion", alert.nVersion));
result.push_back(Pair("nMinVer", alert.nMinVer));
result.push_back(Pair("nMaxVer", alert.nMaxVer));
result.push_back(Pair("nPriority", alert.nPriority));
result.push_back(Pair("nID", alert.nID));
if (alert.nCancel > 0)
result.push_back(Pair("nCancel", alert.nCancel));
return result;
}
//
// Used by addmultisigaddress / createmultisig:
//
CScript _createmultisig(const Array& params)
{
int nRequired = params[0].get_int();
const Array& keys = params[1].get_array();
// Gather public keys
if (nRequired < 1)
throw runtime_error("a multisignature address must require at least one key to redeem");
if ((int)keys.size() < nRequired)
throw runtime_error(strprintf("not enough keys supplied (got %u keys, but need at least %d to redeem)", keys.size(), nRequired));
std::vector<CPubKey> pubkeys;
pubkeys.resize(keys.size());
for (unsigned int i = 0; i < keys.size(); i++)
{
const std::string& ks = keys[i].get_str();
// Case 1: Bitcoin address and we have full public key:
CBitcoinAddress address(ks);
if (pwalletMain && address.IsValid())
{
CKeyID keyID;
if (!address.GetKeyID(keyID))
throw runtime_error(strprintf("%s does not refer to a key",ks.c_str()));
CPubKey vchPubKey;
if (!pwalletMain->GetPubKey(keyID, vchPubKey))
throw runtime_error(strprintf("no full public key for address %s",ks.c_str()));
if (!vchPubKey.IsFullyValid())
throw runtime_error(" Invalid public key: "+ks);
pubkeys[i] = vchPubKey;
}
// Case 2: hex public key
else if (IsHex(ks))
{
CPubKey vchPubKey(ParseHex(ks));
if (!vchPubKey.IsFullyValid())
throw runtime_error(" Invalid public key: "+ks);
pubkeys[i] = vchPubKey;
}
else
{
throw runtime_error(" Invalid public key: "+ks);
}
}
CScript result;
result.SetMultisig(nRequired, pubkeys);
return result;
}
Value addmultisigaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 3)
{
string msg = "addmultisigaddress <nrequired> <'[\"key\",\"key\"]'> [account]\n"
"Add a nrequired-to-sign multisignature address to the wallet\n"
"each key is a paycoin address or hex-encoded public key\n"
"If [account] is specified, assign address to [account].";
throw runtime_error(msg);
}
string strAccount;
if (params.size() > 2)
strAccount = AccountFromValue(params[2]);
// Construct using pay-to-script-hash:
CScript inner = _createmultisig(params);
CScriptID innerID = inner.GetID();
pwalletMain->AddCScript(inner);
pwalletMain->SetAddressBookName(innerID, strAccount);
return CBitcoinAddress(innerID).ToString();
}
Value createmultisig(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 2)
{
string msg = "createmultisig nrequired [\"key\",...]\n"
"\nCreates a multi-signature address with n signature of m keys required.\n"
"It returns a json object with the address and redeemScript.\n"
"\nArguments:\n"
"1. nrequired (numeric, required) The number of required signatures out of the n keys or addresses.\n"
"2. \"keys\" (string, required) A json array of keys which are paycoin addresses or hex-encoded public keys\n"
" [\n"
" \"key\" (string) paycoin address or hex-encoded public key\n"
" ,...\n"
" ]\n"
"\nResult:\n"
"{\n"
" \"address\":\"multisigaddress\", (string) The value of the new multisig address.\n"
" \"redeemScript\":\"script\" (string) The string value of the hex-encoded redemption script.\n"
"}\n"
"\nExamples:\n"
"\nCreate a multisig address from 2 addresses\n"
"paycoind createmultisig 2 \"[\\\"PCHAhUGKiFKDHKW8Pgw3qrp2vMfhwWjuCo\\\",\\\"PJrhyo8CUvFZQT8j67Expre2PYLhavnHXb\\\"]\""
"\nAs a json rpc call\n"
"curl --user myusername --data-binary '{\"jsonrpc\": \"1.0\", \"id\": \"curltest\", \"method\": \"icreatemultisig\", \"params\": [2, \"[\\\"PCHAhUGKiFKDHKW8Pgw3qrp2vMfhwWjuCo\\\",\\\"PJrhyo8CUvFZQT8j67Expre2PYLhavnHXb\\\"]\"]} -H 'content-type: text/plain;' http://127.0.0.1:9902"
;
throw runtime_error(msg);
}
// Construct using pay-to-script-hash:
CScript inner = _createmultisig(params);
CScriptID innerID = inner.GetID();
CBitcoinAddress address(innerID);
Object result;
result.push_back(Pair("address", address.ToString()));
result.push_back(Pair("redeemScript", HexStr(inner.begin(), inner.end())));
return result;
}
//
// Raw transactions
//
Value getrawtransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getrawtransaction <txid> [verbose=0]\n"
"If verbose=0, returns a string that is\n"
"serialized, hex-encoded data for <txid>.\n"
"If verbose is non-zero, returns an Object\n"
"with information about <txid>.");
uint256 hash;
hash.SetHex(params[0].get_str());
bool fVerbose = false;
if (params.size() > 1)
fVerbose = (params[1].get_int() != 0);
CTransaction tx;
uint256 hashBlock = 0;
if (!GetTransaction(hash, tx, hashBlock))
throw JSONRPCError(-5, "No information available about transaction");
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
ssTx << tx;
string strHex = HexStr(ssTx.begin(), ssTx.end());
if (!fVerbose)
return strHex;
Object result;
result.push_back(Pair("hex", strHex));
TxToJSON(tx, hashBlock, result);
return result;
}
Value listunspent(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 3)
throw runtime_error(
"listunspent [minconf=1] [maxconf=9999999] [\"address\",...]\n"
"Returns array of unspent transaction outputs\n"
"with between minconf and maxconf (inclusive) confirmations.\n"
"Optionally filtered to only include txouts paid to specified addresses.\n"
"Results are an array of Objects, each of which has:\n"
"{txid, vout, scriptPubKey, amount, confirmations}");
int nMinDepth = 1;
if (params.size() > 0)
nMinDepth = params[0].get_int();
int nMaxDepth = 9999999;
if (params.size() > 1)
nMaxDepth = params[1].get_int();
set<CBitcoinAddress> setAddress;
if (params.size() > 2)
{
Array inputs = params[2].get_array();
BOOST_FOREACH(Value& input, inputs)
{
CBitcoinAddress address(input.get_str());
if (!address.IsValid())
throw JSONRPCError(-5, string("Invalid Bitcoin address: ")+input.get_str());
if (setAddress.count(address))
throw JSONRPCError(-8, string("Invalid parameter, duplicated address: ")+input.get_str());
setAddress.insert(address);
}
}
Array results;
vector<COutput> vecOutputs;
pwalletMain->AvailableCoins(vecOutputs, false);
BOOST_FOREACH(const COutput& out, vecOutputs)
{
if (out.nDepth < nMinDepth || out.nDepth > nMaxDepth)
continue;
if(setAddress.size())
{
CTxDestination address;
if(!ExtractDestination(out.tx->vout[out.i].scriptPubKey, address))
continue;
if (!setAddress.count(address))
continue;
}
int64 nValue = out.tx->vout[out.i].nValue;
const CScript& pk = out.tx->vout[out.i].scriptPubKey;
CTxDestination address;
Object entry;
entry.push_back(Pair("txid", out.tx->GetHash().GetHex()));
entry.push_back(Pair("vout", out.i));
if (ExtractDestination(pk, address))
{
entry.push_back(Pair("address", CBitcoinAddress(address).ToString()));
if (pwalletMain->mapAddressBook.count(address))
entry.push_back(Pair("account", pwalletMain->mapAddressBook[address]));
}
entry.push_back(Pair("scriptPubKey", HexStr(pk.begin(), pk.end())));
entry.push_back(Pair("amount",ValueFromAmount(nValue)));
entry.push_back(Pair("confirmations",out.nDepth));
results.push_back(entry);
}
return results;
}
Value createrawtransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 2)
throw runtime_error(
"createrawtransaction [{\"txid\":txid,\"vout\":n},...] {address:amount,...}\n"
"Create a transaction spending given inputs\n"
"(array of objects containing transaction id and output number),\n"
"sending to given address(es).\n"
"Returns hex-encoded raw transaction.\n"
"Note that the transaction's inputs are not signed, and\n"
"it is not stored in the wallet or transmitted to the network.");
Array inputs = params[0].get_array();
Object sendTo = params[1].get_obj();
CTransaction rawTx;
BOOST_FOREACH(Value& input, inputs)
{
const Object& o = input.get_obj();
const Value& txid_v = find_value(o, "txid");
if (txid_v.type() != str_type)
throw JSONRPCError(-8, "Invalid parameter, missing txid key");
string txid = txid_v.get_str();
if (!IsHex(txid))
throw JSONRPCError(-8, "Invalid parameter, expected hex txid");
const Value& vout_v = find_value(o, "vout");
if (vout_v.type() != int_type)
throw JSONRPCError(-8, "Invalid parameter, missing vout key");
int nOutput = vout_v.get_int();
if (nOutput < 0)
throw JSONRPCError(-8, "Invalid parameter, vout must be positive");
CTxIn in(COutPoint(uint256(txid), nOutput));
rawTx.vin.push_back(in);
}
set<CBitcoinAddress> setAddress;
BOOST_FOREACH(const Pair& s, sendTo)
{
CBitcoinAddress address(s.name_);
if (!address.IsValid())
throw JSONRPCError(-5, string("Invalid Bitcoin address: ")+s.name_);
if (setAddress.count(address))
throw JSONRPCError(-8, string("Invalid parameter, duplicated address: ")+s.name_);
setAddress.insert(address);
CScript scriptPubKey;
scriptPubKey.SetDestination(address.Get());
int64 nAmount = AmountFromValue(s.value_);
CTxOut out(nAmount, scriptPubKey);
rawTx.vout.push_back(out);
}
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << rawTx;
return HexStr(ss.begin(), ss.end());
}
Value decoderawtransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"decoderawtransaction <hex string>\n"
"Return a JSON object representing the serialized, hex-encoded transaction.");
vector<unsigned char> txData(ParseHex(params[0].get_str()));
CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
CTransaction tx;
try {
ssData >> tx;
}
catch (std::exception &e) {
throw JSONRPCError(-22, "TX decode failed");
}
Object result;
TxToJSON(tx, 0, result);
return result;
}
Value signrawtransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 4)
throw runtime_error(
"signrawtransaction <hex string> [{\"txid\":txid,\"vout\":n,\"scriptPubKey\":hex},...] [<privatekey1>,...] [sighashtype=\"ALL\"]\n"
"Sign inputs for raw transaction (serialized, hex-encoded).\n"
"Second optional argument (may be null) is an array of previous transaction outputs that\n"
"this transaction depends on but may not yet be in the blockchain.\n"
"Third optional argument (may be null) is an array of base58-encoded private\n"
"keys that, if given, will be the only keys used to sign the transaction.\n"
"Fourth optional argument is a string that is one of six values; ALL, NONE, SINGLE or\n"
"ALL|ANYONECANPAY, NONE|ANYONECANPAY, SINGLE|ANYONECANPAY.\n"
"Returns json object with keys:\n"
" hex : raw transaction with signature(s) (hex-encoded string)\n"
" complete : 1 if transaction has a complete set of signature (0 if not)\n");
vector<unsigned char> txData(ParseHex(params[0].get_str()));
CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
vector<CTransaction> txVariants;
while (!ssData.empty())
{
try {
CTransaction tx;
ssData >> tx;
txVariants.push_back(tx);
}
catch (std::exception &e) {
throw JSONRPCError(-22, "TX decode failed");
}
}
if (txVariants.empty())
throw JSONRPCError(-22, "Missing transaction");
// mergedTx will end up with all the signatures; it
// starts as a clone of the rawtx:
CTransaction mergedTx(txVariants[0]);
bool fComplete = true;
// Fetch previous transactions (inputs):
map<COutPoint, CScript> mapPrevOut;
for (unsigned int i = 0; i < mergedTx.vin.size(); i++)
{
CTransaction tempTx;
MapPrevTx mapPrevTx;
CTxDB txdb("r");
map<uint256, CTxIndex> unused;
bool fInvalid;
// FetchInputs aborts on failure, so we go one at a time.
tempTx.vin.push_back(mergedTx.vin[i]);
tempTx.FetchInputs(txdb, unused, false, false, mapPrevTx, fInvalid);
// Copy results into mapPrevOut:
BOOST_FOREACH(const CTxIn& txin, tempTx.vin)
{
const uint256& prevHash = txin.prevout.hash;
if (mapPrevTx.count(prevHash) && mapPrevTx[prevHash].second.vout.size()>txin.prevout.n)
mapPrevOut[txin.prevout] = mapPrevTx[prevHash].second.vout[txin.prevout.n].scriptPubKey;
}
}
bool fGivenKeys = false;
CBasicKeyStore tempKeystore;
if (params.size() > 2 && params[2].type() != null_type)
{
fGivenKeys = true;
Array keys = params[2].get_array();
BOOST_FOREACH(Value k, keys)
{
CBitcoinSecret vchSecret;
bool fGood = vchSecret.SetString(k.get_str());
if (!fGood)
throw JSONRPCError(-5,"Invalid private key");
CKey key;
bool fCompressed;
CSecret secret = vchSecret.GetSecret(fCompressed);
key.SetSecret(secret, fCompressed);
tempKeystore.AddKey(key);
}
}
else if(pwalletMain->IsCrypted())
throw runtime_error("The wallet must be unlocked with walletpassphrase first");
// Add previous txouts given in the RPC call:
if (params.size() > 1 && params[1].type() != null_type)
{
Array prevTxs = params[1].get_array();
BOOST_FOREACH(Value& p, prevTxs)
{
if (p.type() != obj_type)
throw JSONRPCError(-22, "expected object with {\"txid'\",\"vout\",\"scriptPubKey\"}");
Object prevOut = p.get_obj();
string txidHex = find_value(prevOut, "txid").get_str();
if (!IsHex(txidHex))
throw JSONRPCError(-22, "txid must be hexadecimal");
uint256 txid;
txid.SetHex(txidHex);
int nOut = find_value(prevOut, "vout").get_int();
if (nOut < 0)
throw JSONRPCError(-22, "vout must be positive");
string pkHex = find_value(prevOut, "scriptPubKey").get_str();
if (!IsHex(pkHex))
throw JSONRPCError(-22, "scriptPubKey must be hexadecimal");
vector<unsigned char> pkData(ParseHex(pkHex));
CScript scriptPubKey(pkData.begin(), pkData.end());
COutPoint outpoint(txid, nOut);
if (mapPrevOut.count(outpoint))
{
// Complain if scriptPubKey doesn't match
if (mapPrevOut[outpoint] != scriptPubKey)
{
string err("Previous output scriptPubKey mismatch:\n");
err = err + mapPrevOut[outpoint].ToString() + "\nvs:\n"+
scriptPubKey.ToString();
throw JSONRPCError(-22, err);
}
}
else
mapPrevOut[outpoint] = scriptPubKey;
// if redeemScript given and not using the local wallet (private keys
// given), add redeemScript to the tempKeystore so it can be signed:
if (fGivenKeys && scriptPubKey.IsPayToScriptHash())
{
Value v = find_value(prevOut, "redeemScript");
if (!(v == Value::null))
{
vector<unsigned char> rsData(ParseHex(v.get_str()));
CScript redeemScript(rsData.begin(), rsData.end());
tempKeystore.AddCScript(redeemScript);
}
}
}
}
const CKeyStore& keystore = (fGivenKeys ? tempKeystore : *pwalletMain);
int nHashType = SIGHASH_ALL;
if (params.size() > 3 && params[3].type() != null_type)
{
static map<string, int> mapSigHashValues =
boost::assign::map_list_of
(string("ALL"), int(SIGHASH_ALL))
(string("ALL|ANYONECANPAY"), int(SIGHASH_ALL|SIGHASH_ANYONECANPAY))
(string("NONE"), int(SIGHASH_NONE))
(string("NONE|ANYONECANPAY"), int(SIGHASH_NONE|SIGHASH_ANYONECANPAY))
(string("SINGLE"), int(SIGHASH_SINGLE))
(string("SINGLE|ANYONECANPAY"), int(SIGHASH_SINGLE|SIGHASH_ANYONECANPAY))
;
string strHashType = params[3].get_str();
if (mapSigHashValues.count(strHashType))
nHashType = mapSigHashValues[strHashType];
else
throw JSONRPCError(-8, "Invalid sighash param");
}
bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE);
// Sign what we can:
for (unsigned int i = 0; i < mergedTx.vin.size(); i++)
{
CTxIn& txin = mergedTx.vin[i];
if (mapPrevOut.count(txin.prevout) == 0)
{
fComplete = false;
continue;
}
const CScript& prevPubKey = mapPrevOut[txin.prevout];
txin.scriptSig.clear();
// Only sign SIGHASH_SINGLE if there's a corresponding output:
if (!fHashSingle || (i < mergedTx.vout.size()))
SignSignature(keystore, prevPubKey, mergedTx, i, nHashType);
// ... and merge in other signatures:
BOOST_FOREACH(const CTransaction& txv, txVariants)
{
txin.scriptSig = CombineSignatures(prevPubKey, mergedTx, i, txin.scriptSig, txv.vin[i].scriptSig);
}
if (!VerifyScript(txin.scriptSig, prevPubKey, mergedTx, i, true, 0))
fComplete = false;
}
Object result;
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
ssTx << mergedTx;
result.push_back(Pair("hex", HexStr(ssTx.begin(), ssTx.end())));
result.push_back(Pair("complete", fComplete));
return result;
}
Value sendrawtransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"sendrawtransaction <hex string> [checkinputs=0]\n"
"Submits raw transaction (serialized, hex-encoded) to local node and network.\n"
"If checkinputs is non-zero, checks the validity of the inputs of the transaction before sending it.");
// parse hex string from parameter
vector<unsigned char> txData(ParseHex(params[0].get_str()));
CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
bool fCheckInputs = false;
if (params.size() > 1)
fCheckInputs = (params[1].get_int() != 0);
CTransaction tx;
// deserialize binary data stream
try {
ssData >> tx;
}
catch (std::exception &e) {
throw JSONRPCError(-22, "TX decode failed");
}
uint256 hashTx = tx.GetHash();
// See if the transaction is already in a block
// or in the memory pool:
CTransaction existingTx;
uint256 hashBlock = 0;
if (GetTransaction(hashTx, existingTx, hashBlock))
{
if (hashBlock != 0)
throw JSONRPCError(-5, string("transaction already in block ")+hashBlock.GetHex());
// Not in block, but already in the memory pool; will drop
// through to re-relay it.
}
else
{
// push to local node
CTxDB txdb("r");
if (!tx.AcceptToMemoryPool(txdb, fCheckInputs))
throw JSONRPCError(-22, "TX rejected");
SyncWithWallets(tx, NULL, true);
}
RelayMessage(CInv(MSG_TX, hashTx), tx);
return hashTx.GetHex();
}
Value gettxout(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 3)
throw runtime_error(
"gettxout \"txid\" n ( includemempool )\n"
"\nReturns details about an unspent transaction output.\n"
"\nArguments:\n"
"1. \"txid\" (string, required) The transaction id\n"
"2. n (numeric, required) vout value\n"
"3. includemempool (boolean, optional) Whether to included the mem pool\n"
"\nResult:\n"
"{\n"
" \"bestblock\" : \"hash\", (string) the block hash\n"
" \"confirmations\" : n, (numeric) The number of confirmations\n"
" \"value\" : x.xxx, (numeric) The transaction value in btc\n"
" \"scriptPubKey\" : { (json object)\n"
" \"asm\" : \"code\", (string) \n"
" \"hex\" : \"hex\", (string) \n"
" \"reqSigs\" : n, (numeric) Number of required signatures\n"
" \"type\" : \"pubkeyhash\", (string) The type, eg pubkeyhash\n"
" \"addresses\" : [ (array of string) array of bitcoin addresses\n"
" \"bitcoinaddress\" (string) bitcoin address\n"
" ,...\n"
" ]\n"
" },\n"
" \"version\" : n, (numeric) The version\n"
" \"coinbase\" : true|false (boolean) Coinbase or not\n"
"}\n");
Object ret;
std::string strHash = params[0].get_str();
uint256 hash(strHash);
int n = params[1].get_int();
bool fMempool = true;
if (params.size() > 2)
fMempool = params[2].get_bool();
if (n < 0)
return Value::null;
COutPoint outpoint = COutPoint(hash, n);
bool fFound = false, fInMempool = false;
uint256 hashBlock;
int nConfirmations = 0;
CTransaction tx;
if(fMempool)
{
LOCK(mempool.cs);
if (mempool.mapNextTx.count(outpoint))
return Value::null;
if (mempool.exists(hash))
{
tx = mempool.lookup(hash);
if (n >= tx.vout.size())
return Value::null;
fFound = true;
fInMempool = true;
}
}
if(!fFound)
{
CTxDB txdb("r");
CTxIndex txindex;
if (!txdb.ReadTxIndex(hash, txindex))
return Value::null;
if (n >= txindex.vSpent.size())
return Value::null;
if (!txindex.vSpent[n].IsNull())
return Value::null;
if (!tx.ReadFromDisk(txindex.pos))
return Value::null;
CBlock block;
if (block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
{
hashBlock = block.GetHash();
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
if (mi != mapBlockIndex.end() && (*mi).second)
{
CBlockIndex* pindex = (*mi).second;
if (pindex->IsInMainChain())
{
nConfirmations = 1 + nBestHeight - pindex->nHeight;
}
}
}
}
ret.push_back(Pair("bestblock", fInMempool ? "" : hashBlock.GetHex()));
ret.push_back(Pair("confirmations", nConfirmations));
ret.push_back(Pair("value", ValueFromAmount(tx.vout[n].nValue)));
ret.push_back(Pair("version", tx.nVersion));
Object o;
ScriptPubKeyToJSON(tx.vout[n].scriptPubKey, o);
ret.push_back(Pair("scriptPubKey", o));
ret.push_back(Pair("coinbase", tx.IsCoinBase()));
ret.push_back(Pair("coinstake", tx.IsCoinStake()));
return ret;
}
Value getrawmempool(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getrawmempool\n"
"Returns all transaction ids in memory pool.");
vector<uint256> vtxid;
mempool.queryHashes(vtxid);
Array a;
BOOST_FOREACH(const uint256& hash, vtxid)
a.push_back(hash.ToString());
return a;
}
//
// Call Table
//
static const CRPCCommand vRPCCommands[] =
{ // name function safe mode?
// ------------------------ ----------------------- ----------
{ "help", &help, true },
{ "stop", &stop, true },
{ "getblockcount", &getblockcount, true },
{ "getblocknumber", &getblocknumber, true },
{ "getconnectioncount", &getconnectioncount, true },
{ "getpeerinfo", &getpeerinfo, true },
{ "getdifficulty", &getdifficulty, true },
{ "getgenerate", &getgenerate, true },
{ "setgenerate", &setgenerate, true },
{ "gethashespersec", &gethashespersec, true },
{ "getnetworkghps", &getnetworkghps, true },
{ "getinfo", &getinfo, true },
{ "getmininginfo", &getmininginfo, true },
{ "getnewaddress", &getnewaddress, true },
{ "getaccountaddress", &getaccountaddress, true },
{ "setaccount", &setaccount, true },
{ "getaccount", &getaccount, false },
{ "getaddressesbyaccount", &getaddressesbyaccount, true },
{ "sendtoaddress", &sendtoaddress, false },
{ "getreceivedbyaddress", &getreceivedbyaddress, false },
{ "getreceivedbyaccount", &getreceivedbyaccount, false },
{ "listminting", &listminting, false },
{ "listreceivedbyaddress", &listreceivedbyaddress, false },
{ "listreceivedbyaccount", &listreceivedbyaccount, false },
{ "backupwallet", &backupwallet, true },
{ "keypoolrefill", &keypoolrefill, true },
{ "walletpassphrase", &walletpassphrase, true },
{ "walletpassphrasechange", &walletpassphrasechange, false },
{ "walletlock", &walletlock, true },
{ "encryptwallet", &encryptwallet, false },
{ "validateaddress", &validateaddress, true },
{ "getbalance", &getbalance, false },
{ "move", &movecmd, false },
{ "sendfrom", &sendfrom, false },
{ "sendmany", &sendmany, false },
{ "addmultisigaddress", &addmultisigaddress, false },
{ "createmultisig", &createmultisig, true },
{ "getblock", &getblock, false },
{ "getblockhash", &getblockhash, false },
{ "gettransaction", &gettransaction, false },
{ "listtransactions", &listtransactions, false },
{ "signmessage", &signmessage, false },
{ "verifymessage", &verifymessage, false },
{ "getwork", &getwork, true },
{ "listaccounts", &listaccounts, false },
{ "settxfee", &settxfee, false },
{ "getblocktemplate", &getblocktemplate, true },
{ "submitblock", &submitblock, false },
{ "listsinceblock", &listsinceblock, false },
{ "dumpprivkey", &dumpprivkey, false },
{ "importprivkey", &importprivkey, false },
{ "getcheckpoint", &getcheckpoint, true },
{ "reservebalance", &reservebalance, false},
{ "checkwallet", &checkwallet, false},
{ "repairwallet", &repairwallet, false},
{ "makekeypair", &makekeypair, false},
{ "sendalert", &sendalert, false},
{ "listunspent", &listunspent, false},
{ "getrawtransaction", &getrawtransaction, false},
{ "createrawtransaction", &createrawtransaction, false},
{ "decoderawtransaction", &decoderawtransaction, false},
{ "signrawtransaction", &signrawtransaction, false},
{ "sendrawtransaction", &sendrawtransaction, false},
{ "gettxout", &gettxout, true },
{ "getrawmempool", &getrawmempool, true },
};
CRPCTable::CRPCTable()
{
unsigned int vcidx;
for (vcidx = 0; vcidx < (sizeof(vRPCCommands) / sizeof(vRPCCommands[0])); vcidx++)
{
const CRPCCommand *pcmd;
pcmd = &vRPCCommands[vcidx];
mapCommands[pcmd->name] = pcmd;
}
}
const CRPCCommand *CRPCTable::operator[](string name) const
{
map<string, const CRPCCommand*>::const_iterator it = mapCommands.find(name);
if (it == mapCommands.end())
return NULL;
return (*it).second;
}
//
// HTTP protocol
//
// This ain't Apache. We're just using HTTP header for the length field
// and to be compatible with other JSON-RPC implementations.
//
string HTTPPost(const string& strMsg, const map<string,string>& mapRequestHeaders)
{
ostringstream s;
s << "POST / HTTP/1.1\r\n"
<< "User-Agent: paycoin-json-rpc/" << FormatFullVersion() << "\r\n"
<< "Host: 127.0.0.1\r\n"
<< "Content-Type: application/json\r\n"
<< "Content-Length: " << strMsg.size() << "\r\n"
<< "Connection: close\r\n"
<< "Accept: application/json\r\n";
BOOST_FOREACH(const PAIRTYPE(string, string)& item, mapRequestHeaders)
s << item.first << ": " << item.second << "\r\n";
s << "\r\n" << strMsg;
return s.str();
}
string rfc1123Time()
{
char buffer[64];
time_t now;
time(&now);
struct tm* now_gmt = gmtime(&now);
string locale(setlocale(LC_TIME, NULL));
setlocale(LC_TIME, "C"); // we want posix (aka "C") weekday/month strings
strftime(buffer, sizeof(buffer), "%a, %d %b %Y %H:%M:%S +0000", now_gmt);
setlocale(LC_TIME, locale.c_str());
return string(buffer);
}
static string HTTPReply(int nStatus, const string& strMsg)
{
if (nStatus == 401)
return strprintf("HTTP/1.0 401 Authorization Required\r\n"
"Date: %s\r\n"
"Server: paycoin-json-rpc/%s\r\n"
"WWW-Authenticate: Basic realm=\"jsonrpc\"\r\n"
"Content-Type: text/html\r\n"
"Content-Length: 296\r\n"
"\r\n"
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\r\n"
"\"http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd\">\r\n"
"<HTML>\r\n"
"<HEAD>\r\n"
"<TITLE>Error</TITLE>\r\n"
"<META HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=ISO-8859-1'>\r\n"
"</HEAD>\r\n"
"<BODY><H1>401 Unauthorized.</H1></BODY>\r\n"
"</HTML>\r\n", rfc1123Time().c_str(), FormatFullVersion().c_str());
const char *cStatus;
if (nStatus == 200) cStatus = "OK";
else if (nStatus == 400) cStatus = "Bad Request";
else if (nStatus == 403) cStatus = "Forbidden";
else if (nStatus == 404) cStatus = "Not Found";
else if (nStatus == 500) cStatus = "Internal Server Error";
else cStatus = "";
return strprintf(
"HTTP/1.1 %d %s\r\n"
"Date: %s\r\n"
"Connection: close\r\n"
"Content-Length: %d\r\n"
"Content-Type: application/json\r\n"
"Server: paycoin-json-rpc/%s\r\n"
"\r\n"
"%s",
nStatus,
cStatus,
rfc1123Time().c_str(),
strMsg.size(),
FormatFullVersion().c_str(),
strMsg.c_str());
}
int ReadHTTPStatus(std::basic_istream<char>& stream)
{
string str;
getline(stream, str);
vector<string> vWords;
boost::split(vWords, str, boost::is_any_of(" "));
if (vWords.size() < 2)
return 500;
return atoi(vWords[1].c_str());
}
int ReadHTTPHeader(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet)
{
int nLen = 0;
loop
{
string str;
std::getline(stream, str);
if (str.empty() || str == "\r")
break;
string::size_type nColon = str.find(":");
if (nColon != string::npos)
{
string strHeader = str.substr(0, nColon);
boost::trim(strHeader);
boost::to_lower(strHeader);
string strValue = str.substr(nColon+1);
boost::trim(strValue);
mapHeadersRet[strHeader] = strValue;
if (strHeader == "content-length")
nLen = atoi(strValue.c_str());
}
}
return nLen;
}
int ReadHTTP(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet, string& strMessageRet)
{
mapHeadersRet.clear();
strMessageRet = "";
// Read status
int nStatus = ReadHTTPStatus(stream);
// Read header
int nLen = ReadHTTPHeader(stream, mapHeadersRet);
if (nLen < 0 || nLen > (int)MAX_SIZE)
return 500;
// Read message
if (nLen > 0)
{
vector<char> vch(nLen);
stream.read(&vch[0], nLen);
strMessageRet = string(vch.begin(), vch.end());
}
return nStatus;
}
bool HTTPAuthorized(map<string, string>& mapHeaders)
{
string strAuth = mapHeaders["authorization"];
if (strAuth.substr(0,6) != "Basic ")
return false;
string strUserPass64 = strAuth.substr(6); boost::trim(strUserPass64);
string strUserPass = DecodeBase64(strUserPass64);
return strUserPass == strRPCUserColonPass;
}
//
// JSON-RPC protocol. Bitcoin speaks version 1.0 for maximum compatibility,
// but uses JSON-RPC 1.1/2.0 standards for parts of the 1.0 standard that were
// unspecified (HTTP errors and contents of 'error').
//
// 1.0 spec: http://json-rpc.org/wiki/specification
// 1.2 spec: http://groups.google.com/group/json-rpc/web/json-rpc-over-http
// http://www.codeproject.com/KB/recipes/JSON_Spirit.aspx
//
string JSONRPCRequest(const string& strMethod, const Array& params, const Value& id)
{
Object request;
request.push_back(Pair("method", strMethod));
request.push_back(Pair("params", params));
request.push_back(Pair("id", id));
return write_string(Value(request), false) + "\n";
}
Object JSONRPCReplyObj(const Value& result, const Value& error, const Value& id)
{
Object reply;
if (error.type() != null_type)
reply.push_back(Pair("result", Value::null));
else
reply.push_back(Pair("result", result));
reply.push_back(Pair("error", error));
reply.push_back(Pair("id", id));
return reply;
}
string JSONRPCReply(const Value& result, const Value& error, const Value& id)
{
Object reply = JSONRPCReplyObj(result, error, id);
return write_string(Value(reply), false) + "\n";
}
void ErrorReply(std::ostream& stream, const Object& objError, const Value& id)
{
// Send error reply from json-rpc error object
int nStatus = 500;
int code = find_value(objError, "code").get_int();
if (code == -32600) nStatus = 400;
else if (code == -32601) nStatus = 404;
string strReply = JSONRPCReply(Value::null, objError, id);
stream << HTTPReply(nStatus, strReply) << std::flush;
}
bool ClientAllowed(const string& strAddress)
{
if (strAddress == asio::ip::address_v4::loopback().to_string())
return true;
const vector<string>& vAllow = mapMultiArgs["-rpcallowip"];
BOOST_FOREACH(string strAllow, vAllow)
if (WildcardMatch(strAddress, strAllow))
return true;
return false;
}
//
// IOStream device that speaks SSL but can also speak non-SSL
//
class SSLIOStreamDevice : public iostreams::device<iostreams::bidirectional> {
public:
SSLIOStreamDevice(SSLStream &streamIn, bool fUseSSLIn) : stream(streamIn)
{
fUseSSL = fUseSSLIn;
fNeedHandshake = fUseSSLIn;
}
void handshake(ssl::stream_base::handshake_type role)
{
if (!fNeedHandshake) return;
fNeedHandshake = false;
stream.handshake(role);
}
std::streamsize read(char* s, std::streamsize n)
{
handshake(ssl::stream_base::server); // HTTPS servers read first
if (fUseSSL) return stream.read_some(asio::buffer(s, n));
return stream.next_layer().read_some(asio::buffer(s, n));
}
std::streamsize write(const char* s, std::streamsize n)
{
handshake(ssl::stream_base::client); // HTTPS clients write first
if (fUseSSL) return asio::write(stream, asio::buffer(s, n));
return asio::write(stream.next_layer(), asio::buffer(s, n));
}
bool connect(const std::string& server, const std::string& port)
{
ip::tcp::resolver resolver(stream.get_io_service());
ip::tcp::resolver::query query(server.c_str(), port.c_str());
ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
ip::tcp::resolver::iterator end;
boost::system::error_code error = asio::error::host_not_found;
while (error && endpoint_iterator != end)
{
stream.lowest_layer().close();
stream.lowest_layer().connect(*endpoint_iterator++, error);
}
if (error)
return false;
return true;
}
private:
bool fNeedHandshake;
bool fUseSSL;
SSLStream& stream;
};
void ThreadRPCServer(void* parg)
{
IMPLEMENT_RANDOMIZE_STACK(ThreadRPCServer(parg));
// getwork/getblocktemplate mining rewards paid here:
pMiningKey = new CReserveKey(pwalletMain);
try
{
vnThreadsRunning[THREAD_RPCSERVER]++;
ThreadRPCServer2(parg);
vnThreadsRunning[THREAD_RPCSERVER]--;
}
catch (std::exception& e) {
vnThreadsRunning[THREAD_RPCSERVER]--;
PrintException(&e, "ThreadRPCServer()");
} catch (...) {
vnThreadsRunning[THREAD_RPCSERVER]--;
PrintException(NULL, "ThreadRPCServer()");
}
delete pMiningKey; pMiningKey = NULL;
printf("ThreadRPCServer exiting\n");
}
static Object JSONRPCExecOne(const Value& request)
{
Object rpc_result;
Object req = request.get_obj();
Value id = Value::null;
try {
id = find_value(req, "id");
// Parse method
Value valMethod = find_value(req, "method");
if (valMethod.type() == null_type)
throw JSONRPCError(-32600, "Missing method");
if (valMethod.type() != str_type)
throw JSONRPCError(-32600, "Method must be a string");
string strMethod = valMethod.get_str();
if (strMethod != "getwork" && strMethod != "getblocktemplate")
printf("ThreadRPCServer method=%s\n", strMethod.c_str());
// Parse params
Value valParams = find_value(req, "params");
Array params;
if (valParams.type() == array_type)
params = valParams.get_array();
else if (valParams.type() == null_type)
params = Array();
else
throw JSONRPCError(-32600, "Params must be an array");
Value result = tableRPC.execute(strMethod, params);
rpc_result = JSONRPCReplyObj(result, Value::null, id);
}
catch (Object& objError)
{
rpc_result = JSONRPCReplyObj(Value::null, objError, id);
}
catch (std::exception& e)
{
rpc_result = JSONRPCReplyObj(Value::null, JSONRPCError(-32700, e.what()), id);
}
return rpc_result;
}
static string JSONRPCExecBatch(const Array& vReq)
{
Array ret;
for (unsigned int reqIdx = 0; reqIdx < vReq.size(); reqIdx++)
ret.push_back(JSONRPCExecOne(vReq[reqIdx]));
return write_string(Value(ret), false) + "\n";
}
void ThreadRPCServer2(void* parg)
{
printf("ThreadRPCServer started\n");
strRPCUserColonPass = mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"];
if (mapArgs["-rpcpassword"] == "")
{
unsigned char rand_pwd[32];
RAND_bytes(rand_pwd, 32);
string strWhatAmI = "To use paycoin(paycoind)";
if (mapArgs.count("-server"))
strWhatAmI = strprintf(_("To use the %s option"), "\"-server\"");
else if (mapArgs.count("-daemon"))
strWhatAmI = strprintf(_("To use the %s option"), "\"-daemon\"");
ThreadSafeMessageBox(strprintf(
_("%s, you must set a rpcpassword in the configuration file:\n %s\n"
"It is recommended you use the following random password:\n"
"rpcuser=bitcoinrpc\n"
"rpcpassword=%s\n"
"(you do not need to remember this password)\n"
"If the file does not exist, create it with owner-readable-only file permissions.\n"),
strWhatAmI.c_str(),
GetConfigFile().string().c_str(),
EncodeBase58(&rand_pwd[0],&rand_pwd[0]+32).c_str()),
_("Error"), wxOK | wxMODAL);
StartShutdown();
return;
}
bool fUseSSL = GetBoolArg("-rpcssl");
asio::ip::address bindAddress = mapArgs.count("-rpcallowip") ? asio::ip::address_v4::any() : asio::ip::address_v4::loopback();
asio::io_service io_service;
ip::tcp::endpoint endpoint(bindAddress, GetArg("-rpcport", fTestNet? TESTNET_RPC_PORT : RPC_PORT));
ip::tcp::acceptor acceptor(io_service);
try
{
acceptor.open(endpoint.protocol());
acceptor.set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
acceptor.bind(endpoint);
acceptor.listen(socket_base::max_connections);
}
catch(boost::system::system_error &e)
{
ThreadSafeMessageBox(strprintf(_("An error occured while setting up the RPC port %i for listening: %s"), endpoint.port(), e.what()),
_("Error"), wxOK | wxMODAL);
StartShutdown();
return;
}
ssl::context context(io_service, ssl::context::sslv23);
if (fUseSSL)
{
context.set_options(ssl::context::no_sslv2);
filesystem::path pathCertFile(GetArg("-rpcsslcertificatechainfile", "server.cert"));
if (!pathCertFile.is_complete()) pathCertFile = filesystem::path(GetDataDir()) / pathCertFile;
if (filesystem::exists(pathCertFile)) context.use_certificate_chain_file(pathCertFile.string());
else printf("ThreadRPCServer ERROR: missing server certificate file %s\n", pathCertFile.string().c_str());
filesystem::path pathPKFile(GetArg("-rpcsslprivatekeyfile", "server.pem"));
if (!pathPKFile.is_complete()) pathPKFile = filesystem::path(GetDataDir()) / pathPKFile;
if (filesystem::exists(pathPKFile)) context.use_private_key_file(pathPKFile.string(), ssl::context::pem);
else printf("ThreadRPCServer ERROR: missing server private key file %s\n", pathPKFile.string().c_str());
string strCiphers = GetArg("-rpcsslciphers", "TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH");
SSL_CTX_set_cipher_list(context.impl(), strCiphers.c_str());
}
loop
{
// Accept connection
SSLStream sslStream(io_service, context);
SSLIOStreamDevice d(sslStream, fUseSSL);
iostreams::stream<SSLIOStreamDevice> stream(d);
ip::tcp::endpoint peer;
vnThreadsRunning[THREAD_RPCSERVER]--;
acceptor.accept(sslStream.lowest_layer(), peer);
vnThreadsRunning[4]++;
if (fShutdown)
return;
// Restrict callers by IP
if (!ClientAllowed(peer.address().to_string()))
{
// Only send a 403 if we're not using SSL to prevent a DoS during the SSL handshake.
if (!fUseSSL)
stream << HTTPReply(403, "") << std::flush;
continue;
}
map<string, string> mapHeaders;
string strRequest;
boost::thread api_caller(ReadHTTP, boost::ref(stream), boost::ref(mapHeaders), boost::ref(strRequest));
if (!api_caller.timed_join(boost::posix_time::seconds(GetArg("-rpctimeout", 30))))
{ // Timed out:
acceptor.cancel();
printf("ThreadRPCServer ReadHTTP timeout\n");
continue;
}
// Check authorization
if (mapHeaders.count("authorization") == 0)
{
stream << HTTPReply(401, "") << std::flush;
continue;
}
if (!HTTPAuthorized(mapHeaders))
{
printf("ThreadRPCServer incorrect password attempt from %s\n",peer.address().to_string().c_str());
/* Deter brute-forcing short passwords.
If this results in a DOS the user really
shouldn't have their RPC port exposed.*/
if (mapArgs["-rpcpassword"].size() < 20)
Sleep(250);
stream << HTTPReply(401, "") << std::flush;
continue;
}
Value id = Value::null;
try
{
// Parse request
Value valRequest;
if (!read_string(strRequest, valRequest))
throw JSONRPCError(-32700, "Parse error");
string strReply;
if (valRequest.type() == obj_type) {
// singleton request
Object result;
result = JSONRPCExecOne(valRequest);
strReply = write_string(Value(result), false) + "\n";
} else if (valRequest.type() == array_type) {
// array of requests
strReply = JSONRPCExecBatch(valRequest.get_array());
} else
throw JSONRPCError(-32600, "Top-level object parse error");
// Send reply
stream << HTTPReply(200, strReply) << std::flush;
}
catch (Object& objError)
{
ErrorReply(stream, objError, id);
}
catch (std::exception& e)
{
ErrorReply(stream, JSONRPCError(-32700, e.what()), id);
}
}
}
json_spirit::Value CRPCTable::execute(const std::string &strMethod, const json_spirit::Array ¶ms) const
{
// Find method
const CRPCCommand *pcmd = tableRPC[strMethod];
if (!pcmd)
throw JSONRPCError(-32601, "Method not found");
// Observe safe mode
string strWarning = GetWarnings("rpc");
if (strWarning != "" && !GetBoolArg("-disablesafemode") &&
!pcmd->okSafeMode)
throw JSONRPCError(-2, string("Safe mode: ") + strWarning);
try
{
// Execute
Value result;
{
LOCK2(cs_main, pwalletMain->cs_wallet);
result = pcmd->actor(params, false);
}
return result;
}
catch (std::exception& e)
{
throw JSONRPCError(-1, e.what());
}
}
Object CallRPC(const string& strMethod, const Array& params)
{
if (mapArgs["-rpcuser"] == "" && mapArgs["-rpcpassword"] == "")
throw runtime_error(strprintf(
_("You must set rpcpassword=<password> in the configuration file:\n%s\n"
"If the file does not exist, create it with owner-readable-only file permissions."),
GetConfigFile().string().c_str()));
// Connect to localhost
bool fUseSSL = GetBoolArg("-rpcssl");
asio::io_service io_service;
ssl::context context(io_service, ssl::context::sslv23);
context.set_options(ssl::context::no_sslv2);
SSLStream sslStream(io_service, context);
SSLIOStreamDevice d(sslStream, fUseSSL);
iostreams::stream<SSLIOStreamDevice> stream(d);
if (!d.connect(GetArg("-rpcconnect", "127.0.0.1"), GetArg("-rpcport", CBigNum(fTestNet? TESTNET_RPC_PORT : RPC_PORT).ToString().c_str())))
throw runtime_error("couldn't connect to server");
// HTTP basic authentication
string strUserPass64 = EncodeBase64(mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]);
map<string, string> mapRequestHeaders;
mapRequestHeaders["Authorization"] = string("Basic ") + strUserPass64;
// Send request
string strRequest = JSONRPCRequest(strMethod, params, 1);
string strPost = HTTPPost(strRequest, mapRequestHeaders);
stream << strPost << std::flush;
// Receive reply
map<string, string> mapHeaders;
string strReply;
int nStatus = ReadHTTP(stream, mapHeaders, strReply);
if (nStatus == 401)
throw runtime_error("incorrect rpcuser or rpcpassword (authorization failed)");
else if (nStatus >= 400 && nStatus != 400 && nStatus != 404 && nStatus != 500)
throw runtime_error(strprintf("server returned HTTP error %d", nStatus));
else if (strReply.empty())
throw runtime_error("no response from server");
// Parse reply
Value valReply;
if (!read_string(strReply, valReply))
throw runtime_error("couldn't parse reply from server");
const Object& reply = valReply.get_obj();
if (reply.empty())
throw runtime_error("expected reply to have result, error and id properties");
return reply;
}
template<typename T>
void ConvertTo(Value& value)
{
if (value.type() == str_type)
{
// reinterpret string as unquoted json value
Value value2;
if (!read_string(value.get_str(), value2))
throw runtime_error("type mismatch");
value = value2.get_value<T>();
}
else
{
value = value.get_value<T>();
}
}
// Convert strings to command-specific RPC representation
Array RPCConvertValues(const std::string &strMethod, const std::vector<std::string> &strParams)
{
Array params;
BOOST_FOREACH(const std::string ¶m, strParams)
params.push_back(param);
int n = params.size();
//
// Special case non-string parameter types
//
if (strMethod == "setgenerate" && n > 0) ConvertTo<bool>(params[0]);
if (strMethod == "setgenerate" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "sendtoaddress" && n > 1) ConvertTo<double>(params[1]);
if (strMethod == "settxfee" && n > 0) ConvertTo<double>(params[0]);
if (strMethod == "getreceivedbyaddress" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "getreceivedbyaccount" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "listreceivedbyaddress" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "listreceivedbyaddress" && n > 1) ConvertTo<bool>(params[1]);
if (strMethod == "listreceivedbyaccount" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "listreceivedbyaccount" && n > 1) ConvertTo<bool>(params[1]);
if (strMethod == "getbalance" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "getblockhash" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "getblock" && n > 1) ConvertTo<bool>(params[1]);
if (strMethod == "getblock" && n > 2) ConvertTo<bool>(params[2]);
if (strMethod == "move" && n > 2) ConvertTo<double>(params[2]);
if (strMethod == "move" && n > 3) ConvertTo<boost::int64_t>(params[3]);
if (strMethod == "sendfrom" && n > 2) ConvertTo<double>(params[2]);
if (strMethod == "sendfrom" && n > 3) ConvertTo<boost::int64_t>(params[3]);
if (strMethod == "listtransactions" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "listtransactions" && n > 2) ConvertTo<boost::int64_t>(params[2]);
if (strMethod == "listaccounts" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "walletpassphrase" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "walletpassphrase" && n > 2) ConvertTo<bool>(params[2]);
if (strMethod == "getblocktemplate" && n > 0) ConvertTo<Object>(params[0]);
if (strMethod == "listsinceblock" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "sendalert" && n > 2) ConvertTo<boost::int64_t>(params[2]);
if (strMethod == "sendalert" && n > 3) ConvertTo<boost::int64_t>(params[3]);
if (strMethod == "sendalert" && n > 4) ConvertTo<boost::int64_t>(params[4]);
if (strMethod == "sendalert" && n > 5) ConvertTo<boost::int64_t>(params[5]);
if (strMethod == "sendalert" && n > 6) ConvertTo<boost::int64_t>(params[6]);
if (strMethod == "sendmany" && n > 1)
{
string s = params[1].get_str();
Value v;
if (!read_string(s, v) || v.type() != obj_type)
throw runtime_error("type mismatch");
params[1] = v.get_obj();
}
if (strMethod == "sendmany" && n > 2) ConvertTo<boost::int64_t>(params[2]);
if (strMethod == "reservebalance" && n > 0) ConvertTo<bool>(params[0]);
if (strMethod == "reservebalance" && n > 1) ConvertTo<double>(params[1]);
if (strMethod == "createmultisig" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "createmultisig" && n > 1)
{
string s = params[1].get_str();
Value v;
if (!read_string(s, v) || v.type() != array_type)
throw runtime_error("type mismatch "+s);
params[1] = v.get_array();
}
if (strMethod == "addmultisigaddress" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "addmultisigaddress" && n > 1)
{
string s = params[1].get_str();
Value v;
if (!read_string(s, v) || v.type() != array_type)
throw runtime_error("type mismatch "+s);
params[1] = v.get_array();
}
if (strMethod == "listunspent" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "listunspent" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "listunspent" && n > 2) ConvertTo<Array>(params[2]);
if (strMethod == "getrawtransaction" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "createrawtransaction" && n > 0) ConvertTo<Array>(params[0]);
if (strMethod == "createrawtransaction" && n > 1) ConvertTo<Object>(params[1]);
if (strMethod == "signrawtransaction" && n > 1) ConvertTo<Array>(params[1]);
if (strMethod == "signrawtransaction" && n > 2) ConvertTo<Array>(params[2]);
if (strMethod == "sendrawtransaction" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "gettxout" && n > 1) ConvertTo<int64_t>(params[1]);
if (strMethod == "gettxout" && n > 2) ConvertTo<bool>(params[2]);
if (strMethod == "listminting" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "listminting" && n > 1) ConvertTo<boost::int64_t>(params[1]);
return params;
}
int CommandLineRPC(int argc, char *argv[])
{
string strPrint;
int nRet = 0;
try
{
// Skip switches
while (argc > 1 && IsSwitchChar(argv[1][0]))
{
argc--;
argv++;
}
// Method
if (argc < 2)
throw runtime_error("too few parameters");
string strMethod = argv[1];
// Parameters default to strings
std::vector<std::string> strParams(&argv[2], &argv[argc]);
Array params = RPCConvertValues(strMethod, strParams);
// Execute
Object reply = CallRPC(strMethod, params);
// Parse reply
const Value& result = find_value(reply, "result");
const Value& error = find_value(reply, "error");
if (error.type() != null_type)
{
// Error
strPrint = "error: " + write_string(error, false);
int code = find_value(error.get_obj(), "code").get_int();
nRet = abs(code);
}
else
{
// Result
if (result.type() == null_type)
strPrint = "";
else if (result.type() == str_type)
strPrint = result.get_str();
else
strPrint = write_string(result, true);
}
}
catch (std::exception& e)
{
strPrint = string("error: ") + e.what();
nRet = 87;
}
catch (...)
{
PrintException(NULL, "CommandLineRPC()");
}
if (strPrint != "")
{
fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str());
}
return nRet;
}
#ifdef TEST
int main(int argc, char *argv[])
{
#ifdef _MSC_VER
// Turn off microsoft heap dump noise
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_WARN, CreateFile("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
#endif
setbuf(stdin, NULL);
setbuf(stdout, NULL);
setbuf(stderr, NULL);
try
{
if (argc >= 2 && string(argv[1]) == "-server")
{
printf("server ready\n");
ThreadRPCServer(NULL);
}
else
{
return CommandLineRPC(argc, argv);
}
}
catch (std::exception& e) {
PrintException(&e, "main()");
} catch (...) {
PrintException(NULL, "main()");
}
return 0;
}
#endif
const CRPCTable tableRPC;
|
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "google/cloud/storage/internal/grpc_resumable_upload_session.h"
#include "google/cloud/storage/oauth2/google_credentials.h"
#include "google/cloud/storage/testing/random_names.h"
#include "google/cloud/grpc_options.h"
#include "google/cloud/testing_util/status_matchers.h"
#include "absl/memory/memory.h"
#include <gmock/gmock.h>
namespace google {
namespace cloud {
namespace storage {
inline namespace STORAGE_CLIENT_NS {
namespace internal {
namespace {
using ::google::cloud::storage::testing::MakeRandomData;
using ::google::cloud::testing_util::StatusIs;
using ::testing::AtLeast;
using ::testing::Return;
class MockInsertStream : public GrpcClient::InsertStream {
public:
MOCK_METHOD(bool, Write,
(google::storage::v1::InsertObjectRequest const&,
grpc::WriteOptions),
(override));
MOCK_METHOD(StatusOr<google::storage::v1::Object>, Close, (), (override));
MOCK_METHOD(void, Cancel, (), (override));
};
class MockGrpcClient : public GrpcClient {
public:
static std::shared_ptr<MockGrpcClient> Create() {
return std::make_shared<MockGrpcClient>();
}
MockGrpcClient()
: GrpcClient(DefaultOptionsGrpc(Options{}.set<GrpcCredentialOption>(
grpc::InsecureChannelCredentials())),
/*channel_id=*/0) {}
MOCK_METHOD(std::unique_ptr<GrpcClient::InsertStream>, CreateUploadWriter,
(std::unique_ptr<grpc::ClientContext>), (override));
MOCK_METHOD(StatusOr<ResumableUploadResponse>, QueryResumableUpload,
(QueryResumableUploadRequest const&), (override));
};
StatusOr<google::storage::v1::Object> MockCloseSuccess() {
return google::storage::v1::Object{};
}
StatusOr<google::storage::v1::Object> MockCloseError(Status s) {
return StatusOr<google::storage::v1::Object>(std::move(s));
}
TEST(GrpcResumableUploadSessionTest, Simple) {
auto mock = MockGrpcClient::Create();
GrpcResumableUploadSession session(
mock, {"test-bucket", "test-object", "test-upload-id"});
std::string const payload = "test payload";
auto const size = payload.size();
auto writer = absl::make_unique<MockInsertStream>();
EXPECT_FALSE(session.done());
EXPECT_EQ(0, session.next_expected_byte());
EXPECT_CALL(*mock, CreateUploadWriter)
.WillOnce([&](std::unique_ptr<grpc::ClientContext>) {
auto writer = absl::make_unique<MockInsertStream>();
EXPECT_CALL(*writer, Write)
.WillOnce([&](google::storage::v1::InsertObjectRequest const& r,
grpc::WriteOptions const& options) {
EXPECT_EQ("test-upload-id", r.upload_id());
EXPECT_EQ(payload, r.checksummed_data().content());
EXPECT_EQ(0, r.write_offset());
EXPECT_FALSE(r.finish_write());
EXPECT_FALSE(options.is_last_message());
return true;
})
.WillOnce([&](google::storage::v1::InsertObjectRequest const& r,
grpc::WriteOptions const& options) {
EXPECT_EQ("test-upload-id", r.upload_id());
EXPECT_EQ(payload, r.checksummed_data().content());
EXPECT_EQ(size, r.write_offset());
EXPECT_TRUE(r.finish_write());
EXPECT_TRUE(options.is_last_message());
return true;
});
EXPECT_CALL(*writer, Close()).WillOnce(Return(MockCloseSuccess()));
return std::unique_ptr<GrpcClient::InsertStream>(writer.release());
});
auto upload = session.UploadChunk({{payload}});
EXPECT_STATUS_OK(upload);
EXPECT_EQ(size - 1, upload->last_committed_byte);
EXPECT_EQ(size, session.next_expected_byte());
EXPECT_FALSE(session.done());
upload = session.UploadFinalChunk({{payload}}, 2 * size);
EXPECT_STATUS_OK(upload);
EXPECT_EQ(2 * size - 1, upload->last_committed_byte);
EXPECT_EQ(2 * size, session.next_expected_byte());
EXPECT_TRUE(session.done());
}
TEST(GrpcResumableUploadSessionTest, SingleStreamForLargeChunks) {
auto mock = MockGrpcClient::Create();
GrpcResumableUploadSession session(
mock, {"test-bucket", "test-object", "test-upload-id"});
auto rng = google::cloud::internal::MakeDefaultPRNG();
auto const payload = MakeRandomData(rng, 8 * 1024 * 1024L);
auto const size = payload.size();
EXPECT_FALSE(session.done());
EXPECT_EQ(0, session.next_expected_byte());
std::size_t expected_write_offset = 0;
EXPECT_CALL(*mock, CreateUploadWriter)
.WillOnce([&](std::unique_ptr<grpc::ClientContext>) {
auto writer = absl::make_unique<MockInsertStream>();
using google::storage::v1::InsertObjectRequest;
EXPECT_CALL(*writer, Write)
.Times(AtLeast(2))
.WillRepeatedly([&](InsertObjectRequest const& r,
grpc::WriteOptions const&) {
EXPECT_EQ("test-upload-id", r.upload_id());
EXPECT_EQ(expected_write_offset, r.write_offset());
EXPECT_TRUE(r.has_checksummed_data());
auto const content_size = r.checksummed_data().content().size();
EXPECT_LE(
content_size,
google::storage::v1::ServiceConstants::MAX_WRITE_CHUNK_BYTES);
expected_write_offset += content_size;
return true;
});
EXPECT_CALL(*writer, Close).WillOnce(Return(MockCloseSuccess()));
return std::unique_ptr<GrpcClient::InsertStream>(writer.release());
});
auto upload = session.UploadChunk({{payload}});
EXPECT_STATUS_OK(upload);
EXPECT_EQ(size - 1, upload->last_committed_byte);
EXPECT_EQ(size, session.next_expected_byte());
EXPECT_FALSE(session.done());
upload = session.UploadFinalChunk({{payload}}, 2 * size);
EXPECT_STATUS_OK(upload);
EXPECT_EQ(2 * size - 1, upload->last_committed_byte);
EXPECT_EQ(2 * size, session.next_expected_byte());
EXPECT_TRUE(session.done());
}
TEST(GrpcResumableUploadSessionTest, Reset) {
auto mock = MockGrpcClient::Create();
GrpcResumableUploadSession session(
mock, {"test-bucket", "test-object", "test-upload-id"});
std::string const payload = "test payload";
auto const size = payload.size();
EXPECT_EQ(0, session.next_expected_byte());
EXPECT_CALL(*mock, CreateUploadWriter)
.WillOnce([&](std::unique_ptr<grpc::ClientContext>) {
auto writer = absl::make_unique<MockInsertStream>();
EXPECT_CALL(*writer, Write)
.WillOnce([&](google::storage::v1::InsertObjectRequest const& r,
grpc::WriteOptions const&) {
EXPECT_EQ("test-upload-id", r.upload_id());
EXPECT_EQ(payload, r.checksummed_data().content());
EXPECT_EQ(0, r.write_offset());
EXPECT_FALSE(r.finish_write());
return true;
})
.WillOnce([&](google::storage::v1::InsertObjectRequest const& r,
grpc::WriteOptions const&) {
EXPECT_EQ("test-upload-id", r.upload_id());
EXPECT_EQ(payload, r.checksummed_data().content());
EXPECT_EQ(size, r.write_offset());
EXPECT_FALSE(r.finish_write());
return false;
});
EXPECT_CALL(*writer, Close)
.WillOnce(Return(
MockCloseError(Status(StatusCode::kUnavailable, "try again"))));
return std::unique_ptr<GrpcClient::InsertStream>(writer.release());
});
ResumableUploadResponse const resume_response{
{}, 2 * size - 1, {}, ResumableUploadResponse::kInProgress, {}};
EXPECT_CALL(*mock, QueryResumableUpload)
.WillOnce([&](QueryResumableUploadRequest const& request) {
EXPECT_EQ("test-upload-id", request.upload_session_url());
return make_status_or(resume_response);
});
auto upload = session.UploadChunk({{payload}});
EXPECT_EQ(size, session.next_expected_byte());
EXPECT_STATUS_OK(upload);
upload = session.UploadChunk({{payload}});
EXPECT_THAT(upload, StatusIs(StatusCode::kUnavailable));
session.ResetSession();
EXPECT_EQ(2 * size, session.next_expected_byte());
auto decoded_session_url =
DecodeGrpcResumableUploadSessionUrl(session.session_id());
ASSERT_STATUS_OK(decoded_session_url);
EXPECT_EQ("test-upload-id", decoded_session_url->upload_id);
StatusOr<ResumableUploadResponse> const& last_response =
session.last_response();
ASSERT_STATUS_OK(last_response);
EXPECT_EQ(last_response.value(), resume_response);
}
TEST(GrpcResumableUploadSessionTest, ResumeFromEmpty) {
auto mock = MockGrpcClient::Create();
GrpcResumableUploadSession session(
mock, {"test-bucket", "test-object", "test-upload-id"});
std::string const payload = "test payload";
auto const size = payload.size();
EXPECT_EQ(0, session.next_expected_byte());
EXPECT_CALL(*mock, CreateUploadWriter)
.WillOnce([&](std::unique_ptr<grpc::ClientContext>) {
auto writer = absl::make_unique<MockInsertStream>();
EXPECT_CALL(*writer, Write)
.WillOnce([&](google::storage::v1::InsertObjectRequest const& r,
grpc::WriteOptions const&) {
EXPECT_EQ("test-upload-id", r.upload_id());
EXPECT_EQ(payload, r.checksummed_data().content());
EXPECT_EQ(0, r.write_offset());
EXPECT_TRUE(r.finish_write());
return false;
});
EXPECT_CALL(*writer, Close)
.WillOnce(Return(
MockCloseError(Status(StatusCode::kUnavailable, "try again"))));
return std::unique_ptr<GrpcClient::InsertStream>(writer.release());
})
.WillOnce([&](std::unique_ptr<grpc::ClientContext>) {
auto writer = absl::make_unique<MockInsertStream>();
EXPECT_CALL(*writer, Write)
.WillOnce([&](google::storage::v1::InsertObjectRequest const& r,
grpc::WriteOptions const&) {
EXPECT_EQ("test-upload-id", r.upload_id());
EXPECT_EQ(payload, r.checksummed_data().content());
EXPECT_EQ(0, r.write_offset());
EXPECT_TRUE(r.finish_write());
return true;
});
EXPECT_CALL(*writer, Close).WillOnce(Return(MockCloseSuccess()));
return std::unique_ptr<GrpcClient::InsertStream>(writer.release());
});
ResumableUploadResponse const resume_response{
{}, 0, {}, ResumableUploadResponse::kInProgress, {}};
EXPECT_CALL(*mock, QueryResumableUpload)
.WillOnce([&](QueryResumableUploadRequest const& request) {
EXPECT_EQ("test-upload-id", request.upload_session_url());
return make_status_or(resume_response);
});
auto upload = session.UploadFinalChunk({{payload}}, size);
EXPECT_THAT(upload, StatusIs(StatusCode::kUnavailable));
session.ResetSession();
EXPECT_EQ(0, session.next_expected_byte());
auto decoded_session_url =
DecodeGrpcResumableUploadSessionUrl(session.session_id());
ASSERT_STATUS_OK(decoded_session_url);
EXPECT_EQ("test-upload-id", decoded_session_url->upload_id);
StatusOr<ResumableUploadResponse> const& last_response =
session.last_response();
ASSERT_STATUS_OK(last_response);
EXPECT_EQ(last_response.value(), resume_response);
upload = session.UploadFinalChunk({{payload}}, size);
EXPECT_STATUS_OK(upload);
EXPECT_EQ(size, session.next_expected_byte());
EXPECT_TRUE(session.done());
}
} // namespace
} // namespace internal
} // namespace STORAGE_CLIENT_NS
} // namespace storage
} // namespace cloud
} // namespace google
|
/*
* Copyright (c) 2010-2011 frankee zhou (frankee.zhou at gmail dot com)
*
* Distributed under under the Apache License, version 2.0 (the "License").
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
#include "cetty/handler/codec/replay/ReplayingDecoderBuffer.h"
#include "cetty/handler/codec/replay/UnreplayableOperationException.h"
#include "cetty/buffer/ChannelBuffers.h"
#include "cetty/util/Integer.h"
namespace cetty { namespace handler { namespace codec { namespace replay {
using namespace cetty::buffer;
using namespace cetty::util;
int ReplayingDecoderBuffer::capacity() const {
if (terminated) {
return buffer->capacity();
}
else {
return Integer::MAX_VALUE;
}
}
bool ReplayingDecoderBuffer::hasArray() const {
return buffer->hasArray();
}
const Array& ReplayingDecoderBuffer::array() {
return buffer->array();
}
ConstArray ReplayingDecoderBuffer::array() const {
return buffer->array();
}
int ReplayingDecoderBuffer::arrayOffset() const {
return buffer->arrayOffset();
}
void ReplayingDecoderBuffer::clear() {
throw UnreplayableOperationException();
}
bool ReplayingDecoderBuffer::equals(const ChannelBuffer& buffer) const {
return this == &buffer;
}
int ReplayingDecoderBuffer::compareTo(const ChannelBuffer& buffer) const {
throw UnreplayableOperationException();
}
cetty::buffer::ChannelBufferPtr ReplayingDecoderBuffer::copy() const {
throw UnreplayableOperationException();
}
cetty::buffer::ChannelBufferPtr ReplayingDecoderBuffer::copy(int index, int length) const {
if (checkIndex(index, length)) {
return buffer->copy(index, length);
}
return ChannelBuffers::EMPTY_BUFFER;
}
void ReplayingDecoderBuffer::discardReadBytes() {
throw UnreplayableOperationException();
}
void ReplayingDecoderBuffer::ensureWritableBytes(int writableBytes) {
throw UnreplayableOperationException();
}
cetty::buffer::ChannelBufferPtr ReplayingDecoderBuffer::duplicate() {
throw UnreplayableOperationException();
}
boost::int8_t ReplayingDecoderBuffer::getByte(int index) const {
if (checkIndex(index)) {
return buffer->getByte(index);
}
return 0;
}
boost::uint8_t ReplayingDecoderBuffer::getUnsignedByte(int index) const {
if (checkIndex(index)) {
return buffer->getUnsignedByte(index);
}
return 0;
}
void ReplayingDecoderBuffer::getBytes(int index, const Array& dst, int dstIndex, int length) const {
if (checkIndex(index, length)) {
buffer->getBytes(index, dst, dstIndex, length);
}
}
void ReplayingDecoderBuffer::getBytes(int index, const Array& dst) const {
if (checkIndex(index, dst.length())) {
buffer->getBytes(index, dst);
}
}
void ReplayingDecoderBuffer::getBytes(int index, std::string& dst, int length) const {
if (checkIndex(index, length)) {
buffer->getBytes(index, dst, length);
}
}
void ReplayingDecoderBuffer::getBytes(int index, std::string& dst, int dstIndex, int length) const {
if (checkIndex(index, length)) {
buffer->getBytes(index, dst, dstIndex, length);
}
}
void ReplayingDecoderBuffer::getBytes(int index, ChannelBuffer& dst, int dstIndex, int length) const {
if (checkIndex(index, length)) {
buffer->getBytes(index, dst, dstIndex, length);
}
}
void ReplayingDecoderBuffer::getBytes(int index, ChannelBuffer& dst, int length) const {
throw UnreplayableOperationException();
}
void ReplayingDecoderBuffer::getBytes(int index, ChannelBuffer& dst) const {
throw UnreplayableOperationException();
}
void ReplayingDecoderBuffer::getBytes(int index, OutputStream& out, int length) const {
throw UnreplayableOperationException();
}
boost::int32_t ReplayingDecoderBuffer::getInt(int index) const {
if (checkIndex(index, 4)) {
return buffer->getInt(index);
}
return 0;
}
boost::uint32_t ReplayingDecoderBuffer::getUnsignedInt(int index) const {
if (checkIndex(index, 4)) {
return buffer->getUnsignedInt(index);
}
return 0;
}
boost::int64_t ReplayingDecoderBuffer::getLong(int index) const {
if (checkIndex(index, 8)) {
return buffer->getLong(index);
}
return 0;
}
boost::int32_t ReplayingDecoderBuffer::getMedium(int index) const {
if (checkIndex(index, 3)) {
return buffer->getMedium(index);
}
return 0;
}
boost::int32_t ReplayingDecoderBuffer::getUnsignedMedium(int index) const {
if (checkIndex(index, 3)) {
return buffer->getUnsignedMedium(index);
}
return 0;
}
boost::int16_t ReplayingDecoderBuffer::getShort(int index) const {
if (checkIndex(index, 2)) {
return buffer->getShort(index);
}
return 0;
}
boost::uint16_t ReplayingDecoderBuffer::getUnsignedShort(int index) const {
if (checkIndex(index, 2)) {
return buffer->getUnsignedShort(index);
}
return 0;
}
wchar_t ReplayingDecoderBuffer::getChar(int index) const {
if (checkIndex(index, 2)) {
return buffer->getChar(index);
}
return 0;
}
float ReplayingDecoderBuffer::getFloat(int index) const {
if (checkIndex(index, 4)) {
return buffer->getFloat(index);
}
return 0;
}
double ReplayingDecoderBuffer::getDouble(int index) const {
if (checkIndex(index, 8)) {
return buffer->getDouble(index);
}
return 0;
}
int ReplayingDecoderBuffer::hashCode() const {
throw UnreplayableOperationException();
}
int ReplayingDecoderBuffer::indexOf(int fromIndex, int toIndex, boost::int8_t value) const {
int endIndex = buffer->indexOf(fromIndex, toIndex, value);
needMore = (endIndex < 0);
return endIndex;
}
int ReplayingDecoderBuffer::indexOf(int fromIndex, int toIndex, const ChannelBufferIndexFinder& indexFinder) const {
int endIndex = buffer->indexOf(fromIndex, toIndex, indexFinder);
needMore = (endIndex < 0);
return endIndex;
}
int ReplayingDecoderBuffer::bytesBefore(boost::int8_t value) const {
int bytes = buffer->bytesBefore(value);
needMore = (bytes < 0);
return bytes;
}
int ReplayingDecoderBuffer::bytesBefore(const ChannelBufferIndexFinder& indexFinder) const {
int bytes = buffer->bytesBefore(indexFinder);
needMore = (bytes < 0);
return bytes;
}
int ReplayingDecoderBuffer::bytesBefore(int length, boost::int8_t value) const {
if (checkReadableBytes(length)) {
int bytes = buffer->bytesBefore(length, value);
needMore = (bytes < 0);
return bytes;
}
return -1;
}
int ReplayingDecoderBuffer::bytesBefore(int length, const ChannelBufferIndexFinder& indexFinder) const {
if (checkReadableBytes(length)) {
int bytes = buffer->bytesBefore(length, indexFinder);
needMore = (bytes < 0);
return bytes;
}
return -1;
}
int ReplayingDecoderBuffer::bytesBefore(int index, int length, boost::int8_t value) const {
int bytes = buffer->bytesBefore(index, length, value);
needMore = (bytes < 0);
return bytes;
}
int ReplayingDecoderBuffer::bytesBefore(int index, int length, const ChannelBufferIndexFinder& indexFinder) const {
int bytes = buffer->bytesBefore(index, length, indexFinder);
needMore = (bytes < 0);
return bytes;
}
void ReplayingDecoderBuffer::markReaderIndex() {
buffer->markReaderIndex();
}
void ReplayingDecoderBuffer::markWriterIndex() {
throw UnreplayableOperationException();
}
ChannelBufferFactory& ReplayingDecoderBuffer::factory() const {
return buffer->factory();
}
cetty::buffer::ByteOrder ReplayingDecoderBuffer::order() const {
return buffer->order();
}
bool ReplayingDecoderBuffer::readable() const {
return terminated ? buffer->readable() : true;
}
int ReplayingDecoderBuffer::readableBytes() const {
if (terminated) {
return buffer->readableBytes();
}
else {
return Integer::MAX_VALUE - buffer->readerIndex();
}
}
boost::int8_t ReplayingDecoderBuffer::readByte() {
if (checkReadableBytes(1)) {
return buffer->readByte();
}
return 0;
}
boost::uint8_t ReplayingDecoderBuffer::readUnsignedByte() {
if (checkReadableBytes(1)) {
return buffer->readUnsignedByte();
}
return 0;
}
void ReplayingDecoderBuffer::readBytes(const Array& dst, int dstIndex, int length) {
if (checkReadableBytes(length)) {
buffer->readBytes(dst, dstIndex, length);
}
}
void ReplayingDecoderBuffer::readBytes(const Array& dst) {
if (checkReadableBytes(dst.length())) {
buffer->readBytes(dst);
}
}
void ReplayingDecoderBuffer::readBytes(std::string& dst) {
if (checkReadableBytes(readableBytes())) {
buffer->readBytes(dst);
}
}
void ReplayingDecoderBuffer::readBytes(std::string& dst, int length) {
if (checkReadableBytes(length)) {
buffer->readBytes(dst, length);
}
}
void ReplayingDecoderBuffer::readBytes(std::string& dst, int dstIndex, int length) {
if (checkReadableBytes(length)) {
buffer->readBytes(dst, dstIndex, length);
}
}
void ReplayingDecoderBuffer::readBytes(ChannelBuffer& dst, int dstIndex, int length) {
if (checkReadableBytes(length)) {
buffer->readBytes(dst, dstIndex, length);
}
}
void ReplayingDecoderBuffer::readBytes(ChannelBuffer& dst, int length) {
throw UnreplayableOperationException();
}
void ReplayingDecoderBuffer::readBytes(ChannelBuffer& dst) {
throw UnreplayableOperationException();
}
cetty::buffer::ChannelBufferPtr ReplayingDecoderBuffer::readBytes() {
return readBytes(readableBytes());
}
cetty::buffer::ChannelBufferPtr ReplayingDecoderBuffer::readBytes(int length) {
if (checkReadableBytes(length)) {
return buffer->readBytes(length);
}
return ChannelBuffers::EMPTY_BUFFER;
}
void ReplayingDecoderBuffer::readBytes(OutputStream& out, int length) {
throw UnreplayableOperationException();
}
ChannelBufferPtr ReplayingDecoderBuffer::readSlice(int length) {
if (checkReadableBytes(length)) {
return buffer->readSlice(length);
}
return ChannelBuffers::EMPTY_BUFFER;
}
ChannelBufferPtr ReplayingDecoderBuffer::readSlice() {
return readSlice(readableBytes());
}
int ReplayingDecoderBuffer::readerIndex() const {
return buffer->readerIndex();
}
void ReplayingDecoderBuffer::readerIndex(int readerIndex) {
buffer->readerIndex(readerIndex);
}
boost::int32_t ReplayingDecoderBuffer::readInt() {
if (checkReadableBytes(4)) {
return buffer->readInt();
}
return 0;
}
boost::uint32_t ReplayingDecoderBuffer::readUnsignedInt() {
if (checkReadableBytes(4)) {
return buffer->readUnsignedInt();
}
return 0;
}
boost::int64_t ReplayingDecoderBuffer::readLong() {
if (checkReadableBytes(8)) {
return buffer->readLong();
}
return 0;
}
boost::int32_t ReplayingDecoderBuffer::readMedium() {
if (checkReadableBytes(3)) {
return buffer->readMedium();
}
return 0;
}
boost::int32_t ReplayingDecoderBuffer::readUnsignedMedium() {
if (checkReadableBytes(3)) {
return buffer->readUnsignedMedium();
}
return 0;
}
boost::int16_t ReplayingDecoderBuffer::readShort() {
if (checkReadableBytes(2)) {
return buffer->readShort();
}
return 0;
}
boost::uint16_t ReplayingDecoderBuffer::readUnsignedShort() {
if (checkReadableBytes(2)) {
return buffer->readUnsignedShort();
}
return 0;
}
wchar_t ReplayingDecoderBuffer::readChar() {
if (checkReadableBytes(2)) {
return buffer->readChar();
}
return 0;
}
float ReplayingDecoderBuffer::readFloat() {
if (checkReadableBytes(4)) {
return buffer->readFloat();
}
return 0;
}
double ReplayingDecoderBuffer::readDouble() {
if (checkReadableBytes(8)) {
return buffer->readDouble();
}
return 0;
}
void ReplayingDecoderBuffer::resetReaderIndex() {
buffer->resetReaderIndex();
}
void ReplayingDecoderBuffer::resetWriterIndex() {
throw UnreplayableOperationException();
}
void ReplayingDecoderBuffer::setByte(int index, int value) {
throw UnreplayableOperationException();
}
void ReplayingDecoderBuffer::setBytes(int index, const ConstArray& src, int srcIndex, int length) {
throw UnreplayableOperationException();
}
void ReplayingDecoderBuffer::setBytes(int index, const ConstArray& src) {
throw UnreplayableOperationException();
}
void ReplayingDecoderBuffer::setBytes(int index, const std::string& src) {
throw UnreplayableOperationException();
}
void ReplayingDecoderBuffer::setBytes(int index, const std::string& src, int srcIndex, int length) {
throw UnreplayableOperationException();
}
void ReplayingDecoderBuffer::setBytes(int index, const ChannelBuffer& src, int srcIndex, int length) {
throw UnreplayableOperationException();
}
void ReplayingDecoderBuffer::setBytes(int index, ChannelBuffer& src, int length) {
throw UnreplayableOperationException();
}
void ReplayingDecoderBuffer::setBytes(int index, ChannelBuffer& src) {
throw UnreplayableOperationException();
}
int ReplayingDecoderBuffer::setBytes(int index, InputStream& in, int length) {
throw UnreplayableOperationException();
}
void ReplayingDecoderBuffer::setZero(int index, int length) {
throw UnreplayableOperationException();
}
void ReplayingDecoderBuffer::setIndex(int readerIndex, int writerIndex) {
throw UnreplayableOperationException();
}
void ReplayingDecoderBuffer::setInt(int index, int value) {
throw UnreplayableOperationException();
}
void ReplayingDecoderBuffer::setLong(int index, boost::int64_t value) {
throw UnreplayableOperationException();
}
void ReplayingDecoderBuffer::setMedium(int index, int value) {
throw UnreplayableOperationException();
}
void ReplayingDecoderBuffer::setShort(int index, int value) {
throw UnreplayableOperationException();
}
void ReplayingDecoderBuffer::setChar(int index, int value) {
throw UnreplayableOperationException();
}
void ReplayingDecoderBuffer::setFloat(int index, float value) {
throw UnreplayableOperationException();
}
void ReplayingDecoderBuffer::setDouble(int index, double value) {
throw UnreplayableOperationException();
}
void ReplayingDecoderBuffer::skipBytes(int length) {
if (checkReadableBytes(length)) {
buffer->skipBytes(length);
}
}
ChannelBufferPtr ReplayingDecoderBuffer::slice() {
throw UnreplayableOperationException();
}
ChannelBufferPtr ReplayingDecoderBuffer::slice(int index, int length) {
if (checkIndex(index, length)) {
return buffer->slice(index, length);
}
return ChannelBuffers::EMPTY_BUFFER;
}
std::string ReplayingDecoderBuffer::toString() const {
return std::string("ReplayingDecoderBuffer (ridx=") +
Integer::toString(readerIndex()) +
std::string(", widx=") +
Integer::toString(writerIndex()) +
std::string(")");
}
std::string ReplayingDecoderBuffer::toString(const Charset& charsetName) {
throw UnreplayableOperationException();
}
std::string ReplayingDecoderBuffer::toString(int index, int length, const Charset& charset) {
if (checkIndex(index, length)) {
return buffer->toString(index, length, charset);
}
return "";
}
std::wstring ReplayingDecoderBuffer::toWideString(const Charset& charsetName) {
throw UnreplayableOperationException();
}
std::wstring ReplayingDecoderBuffer::toWideString(int index, int length, const Charset& charset) {
if (checkIndex(index, length)) {
return buffer->toWideString(index, length, charset);
}
return L"";
}
bool ReplayingDecoderBuffer::writable() const {
return false;
}
int ReplayingDecoderBuffer::writableBytes() const {
return 0;
}
void ReplayingDecoderBuffer::writeByte(int value) {
throw UnreplayableOperationException();
}
void ReplayingDecoderBuffer::writeBytes(const ConstArray& src, int srcIndex, int length) {
throw UnreplayableOperationException();
}
void ReplayingDecoderBuffer::writeBytes(const ConstArray& src) {
throw UnreplayableOperationException();
}
void ReplayingDecoderBuffer::writeBytes(const ChannelBuffer& src, int srcIndex, int length) {
throw UnreplayableOperationException();
}
void ReplayingDecoderBuffer::writeBytes(ChannelBuffer& src, int length) {
throw UnreplayableOperationException();
}
void ReplayingDecoderBuffer::writeBytes(ChannelBuffer& src) {
throw UnreplayableOperationException();
}
void ReplayingDecoderBuffer::writeBytes(const std::string& src) {
throw UnreplayableOperationException();
}
void ReplayingDecoderBuffer::writeBytes(const std::string& src, int srcIndex, int length) {
throw UnreplayableOperationException();
}
int ReplayingDecoderBuffer::writeBytes(InputStream& in, int length) {
throw UnreplayableOperationException();
}
void ReplayingDecoderBuffer::writeInt(int value) {
throw UnreplayableOperationException();
}
void ReplayingDecoderBuffer::writeLong(boost::int64_t value) {
throw UnreplayableOperationException();
}
void ReplayingDecoderBuffer::writeMedium(int value) {
throw UnreplayableOperationException();
}
void ReplayingDecoderBuffer::writeZero(int length) {
throw UnreplayableOperationException();
}
int ReplayingDecoderBuffer::writerIndex() const {
return buffer->writerIndex();
}
void ReplayingDecoderBuffer::writerIndex(int writerIndex) {
throw UnreplayableOperationException();
}
void ReplayingDecoderBuffer::writeShort(int value) {
throw UnreplayableOperationException();
}
void ReplayingDecoderBuffer::writeChar(int value) {
throw UnreplayableOperationException();
}
void ReplayingDecoderBuffer::writeFloat(float value) {
throw UnreplayableOperationException();
}
void ReplayingDecoderBuffer::writeDouble(double value) {
throw UnreplayableOperationException();
}
}}}}
|
/***************************************************************************
* Copyright 1998-2018 by authors (see AUTHORS.txt) *
* *
* This file is part of LuxCoreRender. *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); *
* you may not use this file except in compliance with the License. *
* You may obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.*
* See the License for the specific language governing permissions and *
* limitations under the License. *
***************************************************************************/
#include <boost/lexical_cast.hpp>
#include "luxrays/utils/serializationutils.h"
#include "slg/kernels/kernels.h"
#include "slg/film/film.h"
#include "slg/film/imagepipeline/plugins/tonemaps/linear.h"
using namespace std;
using namespace luxrays;
using namespace slg;
//------------------------------------------------------------------------------
// Linear tone mapping
//------------------------------------------------------------------------------
BOOST_CLASS_EXPORT_IMPLEMENT(slg::LinearToneMap)
LinearToneMap::LinearToneMap() {
scale = 1.f;
#if !defined(LUXRAYS_DISABLE_OPENCL)
applyKernel = NULL;
#endif
}
LinearToneMap::LinearToneMap(const float s) {
scale = s;
#if !defined(LUXRAYS_DISABLE_OPENCL)
applyKernel = NULL;
#endif
}
LinearToneMap::~LinearToneMap() {
#if !defined(LUXRAYS_DISABLE_OPENCL)
delete applyKernel;
#endif
}
//------------------------------------------------------------------------------
// CPU version
//------------------------------------------------------------------------------
void LinearToneMap::Apply(Film &film, const u_int index) {
Spectrum *pixels = (Spectrum *)film.channel_IMAGEPIPELINEs[index]->GetPixels();
const u_int pixelCount = film.GetWidth() * film.GetHeight();
const bool hasPN = film.HasChannel(Film::RADIANCE_PER_PIXEL_NORMALIZED);
const bool hasSN = film.HasChannel(Film::RADIANCE_PER_SCREEN_NORMALIZED);
#pragma omp parallel for
for (
// Visual C++ 2013 supports only OpenMP 2.5
#if _OPENMP >= 200805
unsigned
#endif
int i = 0; i < pixelCount; ++i) {
if (film.HasSamples(hasPN, hasSN, i))
pixels[i] = scale * pixels[i];
}
}
//------------------------------------------------------------------------------
// OpenCL version
//------------------------------------------------------------------------------
#if !defined(LUXRAYS_DISABLE_OPENCL)
void LinearToneMap::ApplyOCL(Film &film, const u_int index) {
if (!applyKernel) {
// Compile sources
const double tStart = WallClockTime();
cl::Program *program = ImagePipelinePlugin::CompileProgram(film, "",
slg::ocl::KernelSource_tonemap_linear_funcs, "LinearToneMap");
SLG_LOG("[LinearToneMap] Compiling LinearToneMap_Apply Kernel");
applyKernel = new cl::Kernel(*program, "LinearToneMap_Apply");
delete program;
// Set kernel arguments
u_int argIndex = 0;
applyKernel->setArg(argIndex++, film.GetWidth());
applyKernel->setArg(argIndex++, film.GetHeight());
applyKernel->setArg(argIndex++, *(film.ocl_IMAGEPIPELINE));
applyKernel->setArg(argIndex++, scale);
const double tEnd = WallClockTime();
SLG_LOG("[LinearToneMap] Kernels compilation time: " << int((tEnd - tStart) * 1000.0) << "ms");
}
film.oclIntersectionDevice->GetOpenCLQueue().enqueueNDRangeKernel(*applyKernel,
cl::NullRange, cl::NDRange(RoundUp(film.GetWidth() * film.GetHeight(), 256u)), cl::NDRange(256));
}
#endif
|
#include <errno.h>
#include <time.h>
#include <optional>
#include <Common/ProfileEvents.h>
#include <Common/Stopwatch.h>
#include <Common/Exception.h>
#include <Common/CurrentMetrics.h>
#include <IO/ReadBufferFromFileDescriptor.h>
#include <IO/WriteHelpers.h>
#include <IO/Progress.h>
#include <sys/stat.h>
#ifdef HAS_RESERVED_IDENTIFIER
#pragma clang diagnostic ignored "-Wreserved-identifier"
#endif
namespace ProfileEvents
{
extern const Event ReadBufferFromFileDescriptorRead;
extern const Event ReadBufferFromFileDescriptorReadFailed;
extern const Event ReadBufferFromFileDescriptorReadBytes;
extern const Event DiskReadElapsedMicroseconds;
extern const Event Seek;
}
namespace CurrentMetrics
{
extern const Metric Read;
}
namespace DB
{
namespace ErrorCodes
{
extern const int CANNOT_READ_FROM_FILE_DESCRIPTOR;
extern const int ARGUMENT_OUT_OF_BOUND;
extern const int CANNOT_SEEK_THROUGH_FILE;
extern const int CANNOT_SELECT;
extern const int CANNOT_FSTAT;
extern const int CANNOT_ADVISE;
}
std::string ReadBufferFromFileDescriptor::getFileName() const
{
return "(fd = " + toString(fd) + ")";
}
bool ReadBufferFromFileDescriptor::nextImpl()
{
/// If internal_buffer size is empty, then read() cannot be distinguished from EOF
assert(!internal_buffer.empty());
/// This is a workaround of a read pass EOF bug in linux kernel with pread()
if (file_size.has_value() && file_offset_of_buffer_end >= *file_size)
return false;
size_t bytes_read = 0;
while (!bytes_read)
{
ProfileEvents::increment(ProfileEvents::ReadBufferFromFileDescriptorRead);
Stopwatch watch(profile_callback ? clock_type : CLOCK_MONOTONIC);
ssize_t res = 0;
{
CurrentMetrics::Increment metric_increment{CurrentMetrics::Read};
if (use_pread)
res = ::pread(fd, internal_buffer.begin(), internal_buffer.size(), file_offset_of_buffer_end);
else
res = ::read(fd, internal_buffer.begin(), internal_buffer.size());
}
if (!res)
break;
if (-1 == res && errno != EINTR)
{
ProfileEvents::increment(ProfileEvents::ReadBufferFromFileDescriptorReadFailed);
throwFromErrnoWithPath("Cannot read from file " + getFileName(), getFileName(),
ErrorCodes::CANNOT_READ_FROM_FILE_DESCRIPTOR);
}
if (res > 0)
bytes_read += res;
/// It reports real time spent including the time spent while thread was preempted doing nothing.
/// And it is Ok for the purpose of this watch (it is used to lower the number of threads to read from tables).
/// Sometimes it is better to use taskstats::blkio_delay_total, but it is quite expensive to get it
/// (TaskStatsInfoGetter has about 500K RPS).
watch.stop();
ProfileEvents::increment(ProfileEvents::DiskReadElapsedMicroseconds, watch.elapsedMicroseconds());
if (profile_callback)
{
ProfileInfo info;
info.bytes_requested = internal_buffer.size();
info.bytes_read = res;
info.nanoseconds = watch.elapsed();
profile_callback(info);
}
}
file_offset_of_buffer_end += bytes_read;
if (bytes_read)
{
ProfileEvents::increment(ProfileEvents::ReadBufferFromFileDescriptorReadBytes, bytes_read);
working_buffer = internal_buffer;
working_buffer.resize(bytes_read);
}
else
return false;
return true;
}
void ReadBufferFromFileDescriptor::prefetch()
{
#if defined(POSIX_FADV_WILLNEED)
/// For direct IO, loading data into page cache is pointless.
if (required_alignment)
return;
/// Ask OS to prefetch data into page cache.
if (0 != posix_fadvise(fd, file_offset_of_buffer_end, internal_buffer.size(), POSIX_FADV_WILLNEED))
throwFromErrno("Cannot posix_fadvise", ErrorCodes::CANNOT_ADVISE);
#endif
}
/// If 'offset' is small enough to stay in buffer after seek, then true seek in file does not happen.
off_t ReadBufferFromFileDescriptor::seek(off_t offset, int whence)
{
size_t new_pos;
if (whence == SEEK_SET)
{
assert(offset >= 0);
new_pos = offset;
}
else if (whence == SEEK_CUR)
{
new_pos = file_offset_of_buffer_end - (working_buffer.end() - pos) + offset;
}
else
{
throw Exception("ReadBufferFromFileDescriptor::seek expects SEEK_SET or SEEK_CUR as whence", ErrorCodes::ARGUMENT_OUT_OF_BOUND);
}
/// Position is unchanged.
if (new_pos + (working_buffer.end() - pos) == file_offset_of_buffer_end)
return new_pos;
if (file_offset_of_buffer_end - working_buffer.size() <= static_cast<size_t>(new_pos)
&& new_pos <= file_offset_of_buffer_end)
{
/// Position is still inside the buffer.
/// Probably it is at the end of the buffer - then we will load data on the following 'next' call.
pos = working_buffer.end() - file_offset_of_buffer_end + new_pos;
assert(pos >= working_buffer.begin());
assert(pos <= working_buffer.end());
return new_pos;
}
else
{
/// Position is out of the buffer, we need to do real seek.
off_t seek_pos = required_alignment > 1
? new_pos / required_alignment * required_alignment
: new_pos;
off_t offset_after_seek_pos = new_pos - seek_pos;
/// First reset the buffer so the next read will fetch new data to the buffer.
resetWorkingBuffer();
/// In case of using 'pread' we just update the info about the next position in file.
/// In case of using 'read' we call 'lseek'.
/// We account both cases as seek event as it leads to non-contiguous reads from file.
ProfileEvents::increment(ProfileEvents::Seek);
if (!use_pread)
{
Stopwatch watch(profile_callback ? clock_type : CLOCK_MONOTONIC);
off_t res = ::lseek(fd, seek_pos, SEEK_SET);
if (-1 == res)
throwFromErrnoWithPath(fmt::format("Cannot seek through file {} at offset {}", getFileName(), seek_pos), getFileName(),
ErrorCodes::CANNOT_SEEK_THROUGH_FILE);
/// Also note that seeking past the file size is not allowed.
if (res != seek_pos)
throw Exception(ErrorCodes::CANNOT_SEEK_THROUGH_FILE,
"The 'lseek' syscall returned value ({}) that is not expected ({})", res, seek_pos);
watch.stop();
ProfileEvents::increment(ProfileEvents::DiskReadElapsedMicroseconds, watch.elapsedMicroseconds());
}
file_offset_of_buffer_end = seek_pos;
if (offset_after_seek_pos > 0)
ignore(offset_after_seek_pos);
return seek_pos;
}
}
void ReadBufferFromFileDescriptor::rewind()
{
if (!use_pread)
{
ProfileEvents::increment(ProfileEvents::Seek);
off_t res = ::lseek(fd, 0, SEEK_SET);
if (-1 == res)
throwFromErrnoWithPath("Cannot seek through file " + getFileName(), getFileName(),
ErrorCodes::CANNOT_SEEK_THROUGH_FILE);
}
/// In case of pread, the ProfileEvents::Seek is not accounted, but it's Ok.
/// Clearing the buffer with existing data. New data will be read on subsequent call to 'next'.
working_buffer.resize(0);
pos = working_buffer.begin();
file_offset_of_buffer_end = 0;
}
/// Assuming file descriptor supports 'select', check that we have data to read or wait until timeout.
bool ReadBufferFromFileDescriptor::poll(size_t timeout_microseconds)
{
fd_set fds;
FD_ZERO(&fds);
FD_SET(fd, &fds);
timeval timeout = { time_t(timeout_microseconds / 1000000), suseconds_t(timeout_microseconds % 1000000) };
int res = select(1, &fds, nullptr, nullptr, &timeout);
if (-1 == res)
throwFromErrno("Cannot select", ErrorCodes::CANNOT_SELECT);
return res > 0;
}
off_t ReadBufferFromFileDescriptor::size()
{
struct stat buf;
int res = fstat(fd, &buf);
if (-1 == res)
throwFromErrnoWithPath("Cannot execute fstat " + getFileName(), getFileName(), ErrorCodes::CANNOT_FSTAT);
return buf.st_size;
}
void ReadBufferFromFileDescriptor::setProgressCallback(ContextPtr context)
{
auto file_progress_callback = context->getFileProgressCallback();
if (!file_progress_callback)
return;
setProfileCallback([file_progress_callback](const ProfileInfo & progress)
{
file_progress_callback(FileProgress(progress.bytes_read, 0));
});
}
}
|
#include "caching_metric.h"
#include "metric.h"
#include "description_utils.h"
#include "classification_utils.h"
#include "kappa.h"
#include <catboost/libs/helpers/dispatch_generic_lambda.h>
#include <catboost/libs/helpers/math_utils.h>
#include <catboost/libs/helpers/vector_helpers.h>
#include <catboost/private/libs/options/data_processing_options.h>
#include <catboost/private/libs/options/enum_helpers.h>
#include <util/generic/string.h>
#include <util/generic/set.h>
using NCB::AppendTemporaryMetricsVector;
using NCB::AsVector;
constexpr int BinaryClassesCount = 2;
static const TString ConfusionMatrixCacheKey = "Confusion Matrix";
/* Caching metric */
namespace {
class ICacheHolder {
public:
virtual ~ICacheHolder() = default;
};
template <typename TValue, typename... TKeys>
class TCacheHolder : public ICacheHolder {
public:
template <typename TValueMaker>
TValue& Get(TValueMaker maker, const TKeys & ...keys) {
auto key = std::make_tuple(keys...);
if (!Cache.contains(key)) {
Cache.insert({key, maker()});
}
return Cache.at(key);
}
private:
TMap<std::tuple<TKeys...>, TValue> Cache;
};
class TCache {
public:
template <typename TValueMaker, typename... TKeys>
auto Get(const TString& cacheKey, TValueMaker maker, TKeys... keys) -> const decltype(maker()) & {
if (!Cache.contains(cacheKey)) {
Cache.insert({cacheKey, MakeHolder<TCacheHolder<decltype(maker()), TKeys...>>()});
}
auto cache = dynamic_cast<TCacheHolder<decltype(maker()), TKeys...> *>(Cache.at(cacheKey).Get());
CB_ENSURE(cache, "Cache is typed differently");
return cache->Get(maker, keys...);
}
private:
TMap<TString, THolder<ICacheHolder>> Cache;
};
struct TCachingMetric: public TMetric {
explicit TCachingMetric(ELossFunction lossFunction, const TLossParams& params)
: TMetric(lossFunction, params)
{}
TMetricHolder Eval(
const TVector<TVector<double>>& approx,
TConstArrayRef<float> target,
TConstArrayRef<float> weight,
TConstArrayRef<TQueryInfo> queriesInfo,
int begin,
int end,
NPar::ILocalExecutor& executor
) const override {
return Eval(To2DConstArrayRef<double>(approx), /*approxDelta*/{}, /*isExpApprox*/false, target, weight, queriesInfo, begin, end, executor);
}
TMetricHolder Eval(
const TConstArrayRef<TConstArrayRef<double>> approx,
const TConstArrayRef<TConstArrayRef<double>> approxDelta,
bool isExpApprox,
TConstArrayRef<float> target,
TConstArrayRef<float> weight,
TConstArrayRef<TQueryInfo> queriesInfo,
int begin,
int end,
NPar::ILocalExecutor& executor
) const override {
const auto evalMetric = [&](int from, int to) {
return Eval(approx, approxDelta, isExpApprox, target, weight, queriesInfo, from, to, Nothing());
};
if (IsAdditiveMetric()) {
return ParallelEvalMetric(evalMetric, GetMinBlockSize(end - begin), begin, end, executor);
} else {
return evalMetric(begin, end);
}
}
virtual TMetricHolder Eval(
const TConstArrayRef<TConstArrayRef<double>> approx,
const TConstArrayRef<TConstArrayRef<double>> approxDelta,
bool isExpApprox,
TConstArrayRef<float> target,
TConstArrayRef<float> weight,
TConstArrayRef<TQueryInfo> queriesInfo,
int begin,
int end,
TMaybe<TCache*> cache
) const = 0;
};
}
/* Confusion matrix */
static TMetricHolder BuildConfusionMatrix(
const TConstArrayRef<TConstArrayRef<double>> approx,
TConstArrayRef<float> target,
TConstArrayRef<float> weight,
int begin,
int end,
double targetBorder,
double predictionBorder
) {
const bool isMultiClass = approx.size() > 1;
const int classesCount = isMultiClass ? approx.size() : BinaryClassesCount;
const double predictionLogitBorder = NCB::Logit(predictionBorder);
const auto buildImpl = [&](auto useWeights, auto isMultiClass) {
TMetricHolder confusionMatrix(classesCount * classesCount);
for (int idx = begin; idx < end; ++idx) {
int approxClass = GetApproxClass(approx, idx, predictionLogitBorder);
int targetClass = isMultiClass ? static_cast<int>(target[idx]) : target[idx] > targetBorder;
float w = useWeights ? weight[idx] : 1;
Y_ASSERT(targetClass >= 0 && targetClass < classesCount);
confusionMatrix.Stats[approxClass * classesCount + targetClass] += w;
}
return confusionMatrix;
};
return DispatchGenericLambda(buildImpl, !weight.empty(), isMultiClass);
}
/* MCC caching metric */
namespace {
struct TMCCCachingMetric final : public TCachingMetric {
explicit TMCCCachingMetric(const TLossParams& params,
int classesCount)
: TCachingMetric(ELossFunction::MCC, params)
, ClassesCount(classesCount) {
}
explicit TMCCCachingMetric(const TLossParams& params,
double predictionBorder)
: TCachingMetric(ELossFunction::MCC, params)
, PredictionBorder(predictionBorder)
{
}
TMetricHolder Eval(
const TConstArrayRef<TConstArrayRef<double>> approx,
const TConstArrayRef<TConstArrayRef<double>> approxDelta,
bool isExpApprox,
TConstArrayRef<float> target,
TConstArrayRef<float> weight,
TConstArrayRef<TQueryInfo> queriesInfo,
int begin,
int end,
TMaybe<TCache*> cache
) const override;
double GetFinalError(const TMetricHolder &error) const override;
void GetBestValue(EMetricBestValue *valueType, float *bestPossibleValue) const override;
bool IsAdditiveMetric() const override {
return true;
}
private:
static constexpr double TargetBorder = GetDefaultTargetBorder();
const int ClassesCount = BinaryClassesCount;
const double PredictionBorder = GetDefaultPredictionBorder();
};
}
THolder<IMetric> MakeMCCMetric(const TLossParams& params, int classesCount) {
return MakeHolder<TMCCCachingMetric>(params, classesCount);
}
TMetricHolder TMCCCachingMetric::Eval(
const TConstArrayRef<TConstArrayRef<double>> approx,
const TConstArrayRef<TConstArrayRef<double>> approxDelta,
bool isExpApprox,
TConstArrayRef<float> target,
TConstArrayRef<float> weight,
TConstArrayRef<TQueryInfo> /*queriesInfo*/,
int begin,
int end,
TMaybe<TCache*> cache
) const {
Y_ASSERT(!isExpApprox);
Y_ASSERT(approxDelta.empty());
const auto MakeMatrix = [&]() {
return BuildConfusionMatrix(approx, target, UseWeights ? weight : TVector<float>{}, begin, end,
TargetBorder, PredictionBorder);
};
auto confusionMatrix = cache.Empty() ? MakeMatrix() : cache.GetRef()->Get(ConfusionMatrixCacheKey, MakeMatrix, bool(UseWeights),
TargetBorder, PredictionBorder);
return confusionMatrix;
}
double TMCCCachingMetric::GetFinalError(const TMetricHolder &error) const {
TVector<double> rowSum(ClassesCount);
TVector<double> columnSum(ClassesCount);
double totalSum = 0;
const auto getStats = [&](int i, int j) { return error.Stats[i * ClassesCount + j]; };
for (auto i : xrange(ClassesCount)) {
for (auto j : xrange(ClassesCount)) {
rowSum[i] += getStats(i, j);
columnSum[j] += getStats(i, j);
totalSum += getStats(i, j);
}
}
double numerator = 0;
for (auto i : xrange(ClassesCount)) {
numerator += getStats(i, i) * totalSum - rowSum[i] * columnSum[i];
}
double sumSquareRowSums = 0;
double sumSquareColumnSums = 0;
for (auto i : xrange(ClassesCount)) {
sumSquareRowSums += Sqr(rowSum[i]);
sumSquareColumnSums += Sqr(columnSum[i]);
}
double denominator = sqrt((Sqr(totalSum) - sumSquareRowSums) * (Sqr(totalSum) - sumSquareColumnSums));
return denominator != 0 ? numerator / denominator : 0.0;
}
void TMCCCachingMetric::GetBestValue(EMetricBestValue *valueType, float *) const {
*valueType = EMetricBestValue::Max;
}
/* Zero one loss caching metric */
namespace {
struct TZeroOneLossCachingMetric final: public TCachingMetric {
explicit TZeroOneLossCachingMetric(const TLossParams& params,
int classesCount)
: TCachingMetric(ELossFunction::ZeroOneLoss, params)
, ClassesCount(classesCount) {
}
explicit TZeroOneLossCachingMetric(const TLossParams& params,
double predictionBorder)
: TCachingMetric(ELossFunction::ZeroOneLoss, params)
, PredictionBorder(predictionBorder) {
}
TMetricHolder Eval(
const TConstArrayRef<TConstArrayRef<double>> approx,
const TConstArrayRef<TConstArrayRef<double>> approxDelta,
bool isExpApprox,
TConstArrayRef<float> target,
TConstArrayRef<float> weight,
TConstArrayRef<TQueryInfo> queriesInfo,
int begin,
int end,
TMaybe<TCache*> cache
) const override;
double GetFinalError(const TMetricHolder &error) const override;
void GetBestValue(EMetricBestValue *valueType, float *bestPossibleValue) const override;
bool IsAdditiveMetric() const override {
return true;
}
private:
static constexpr double TargetBorder = GetDefaultTargetBorder();
const int ClassesCount = BinaryClassesCount;
const double PredictionBorder = GetDefaultPredictionBorder();
};
}
TMetricHolder TZeroOneLossCachingMetric::Eval(
const TConstArrayRef<TConstArrayRef<double>> approx,
const TConstArrayRef<TConstArrayRef<double>> approxDelta,
bool isExpApprox,
TConstArrayRef<float> target,
TConstArrayRef<float> weight,
TConstArrayRef<TQueryInfo> /*queriesInfo*/,
int begin,
int end,
TMaybe<TCache*> cache
) const {
Y_ASSERT(!isExpApprox);
Y_ASSERT(approxDelta.empty());
const auto MakeMatrix = [&]() {
return BuildConfusionMatrix(approx, target, UseWeights ? weight : TVector<float>{}, begin, end,
TargetBorder, PredictionBorder);
};
auto confusionMatrix = cache.Empty() ? MakeMatrix() : cache.GetRef()->Get(ConfusionMatrixCacheKey, MakeMatrix, bool(UseWeights),
TargetBorder, PredictionBorder);
const auto getStats = [&](int i, int j) { return confusionMatrix.Stats[i * ClassesCount + j]; };
TMetricHolder error(2);
for (auto i : xrange(ClassesCount)) {
error.Stats[0] += getStats(i, i);
for (auto j : xrange(ClassesCount)) {
error.Stats[1] += getStats(i, j);
}
}
return error;
}
double TZeroOneLossCachingMetric::GetFinalError(const TMetricHolder &error) const {
return 1 - error.Stats[0] / error.Stats[1];
}
void TZeroOneLossCachingMetric::GetBestValue(EMetricBestValue *valueType, float *) const {
*valueType = EMetricBestValue::Min;
}
/* Accuracy caching metric */
namespace {
struct TAccuracyCachingMetric final: public TCachingMetric {
explicit TAccuracyCachingMetric(const TLossParams& params,
double predictionBorder)
: TCachingMetric(ELossFunction::Accuracy, params)
, PredictionBorder(predictionBorder) {
}
explicit TAccuracyCachingMetric(const TLossParams& params,
int classesCount)
: TCachingMetric(ELossFunction::Accuracy, params)
, ClassesCount(classesCount) {
}
TMetricHolder Eval(
const TConstArrayRef<TConstArrayRef<double>> approx,
const TConstArrayRef<TConstArrayRef<double>> approxDelta,
bool isExpApprox,
TConstArrayRef<float> target,
TConstArrayRef<float> weight,
TConstArrayRef<TQueryInfo> /*queriesInfo*/,
int begin,
int end,
TMaybe<TCache *> cache
) const override;
void GetBestValue(EMetricBestValue* valueType, float* bestValue) const override;
bool IsAdditiveMetric() const override {
return true;
}
private:
static constexpr double TargetBorder = GetDefaultTargetBorder();
const double PredictionBorder = GetDefaultPredictionBorder();
const int ClassesCount = BinaryClassesCount;
};
}
TMetricHolder TAccuracyCachingMetric::Eval(
const TConstArrayRef<TConstArrayRef<double>> approx,
const TConstArrayRef<TConstArrayRef<double>> approxDelta,
bool isExpApprox,
TConstArrayRef<float> target,
TConstArrayRef<float> weight,
TConstArrayRef<TQueryInfo> /*queriesInfo*/,
int begin,
int end,
TMaybe<TCache*> cache
) const {
Y_ASSERT(!isExpApprox);
Y_ASSERT(approxDelta.empty());
const auto MakeMatrix = [&]() {
return BuildConfusionMatrix(approx, target, UseWeights ? weight : TVector<float>{}, begin, end,
TargetBorder, PredictionBorder);
};
auto confusionMatrix = cache.Empty() ? MakeMatrix() : cache.GetRef()->Get(ConfusionMatrixCacheKey, MakeMatrix, bool(UseWeights),
TargetBorder, PredictionBorder);
const auto getStats = [&](int i, int j) { return confusionMatrix.Stats[i * ClassesCount + j]; };
TMetricHolder error(2);
for (auto i : xrange(ClassesCount)) {
error.Stats[0] += getStats(i, i);
for (auto j : xrange(ClassesCount)) {
error.Stats[1] += getStats(i, j);
}
}
return error;
}
void TAccuracyCachingMetric::GetBestValue(EMetricBestValue* valueType, float*) const {
*valueType = EMetricBestValue::Max;
}
/* Recall caching metric */
namespace {
struct TRecallCachingMetric final: public TCachingMetric {
explicit TRecallCachingMetric(const TLossParams& params,
double predictionBorder)
: TCachingMetric(ELossFunction::Recall, params)
, ClassesCount(BinaryClassesCount)
, PredictionBorder(predictionBorder)
, IsMultiClass(false) {
}
explicit TRecallCachingMetric(const TLossParams& params,
int classesCount, int positiveClass)
: TCachingMetric(ELossFunction::Recall, params)
, ClassesCount(classesCount)
, PositiveClass(positiveClass)
, IsMultiClass(true) {
}
TMetricHolder Eval(
const TConstArrayRef<TConstArrayRef<double>> approx,
const TConstArrayRef<TConstArrayRef<double>> approxDelta,
bool isExpApprox,
TConstArrayRef<float> target,
TConstArrayRef<float> weight,
TConstArrayRef<TQueryInfo> /*queriesInfo*/,
int begin,
int end,
TMaybe<TCache*> cache
) const override;
TString GetDescription() const override;
double GetFinalError(const TMetricHolder& error) const override;
void GetBestValue(EMetricBestValue* valueType, float* bestValue) const override;
bool IsAdditiveMetric() const override {
return true;
}
private:
static constexpr double TargetBorder = GetDefaultTargetBorder();
const int ClassesCount = BinaryClassesCount;
const int PositiveClass = 1;
const double PredictionBorder = GetDefaultPredictionBorder();
const bool IsMultiClass = false;
};
}
THolder<IMetric> MakeBinClassRecallMetric(const TLossParams& params,
double predictionBorder) {
return MakeHolder<TRecallCachingMetric>(params, predictionBorder);
}
THolder<IMetric> MakeMultiClassRecallMetric(const TLossParams& params,
int classesCount, int positiveClass) {
return MakeHolder<TRecallCachingMetric>(params, classesCount, positiveClass);
}
TMetricHolder TRecallCachingMetric::Eval(
const TConstArrayRef<TConstArrayRef<double>> approx,
const TConstArrayRef<TConstArrayRef<double>> approxDelta,
bool isExpApprox,
TConstArrayRef<float> target,
TConstArrayRef<float> weight,
TConstArrayRef<TQueryInfo> /*queriesInfo*/,
int begin,
int end,
TMaybe<TCache*> cache
) const {
Y_ASSERT(!isExpApprox);
Y_ASSERT(approxDelta.empty());
const auto MakeMatrix = [&]() {
return BuildConfusionMatrix(approx, target, UseWeights ? weight : TVector<float>{}, begin, end,
TargetBorder, PredictionBorder);
};
auto confusionMatrix = cache.Empty() ? MakeMatrix() : cache.GetRef()->Get(ConfusionMatrixCacheKey, MakeMatrix, bool(UseWeights), TargetBorder, PredictionBorder);
const auto getStats = [&](int i, int j) { return confusionMatrix.Stats[i * ClassesCount + j]; };
TMetricHolder error(2);
error.Stats[0] = getStats(PositiveClass, PositiveClass);
for (auto i : xrange(ClassesCount)) {
error.Stats[1] += getStats(i, PositiveClass);
}
return error;
}
TString TRecallCachingMetric::GetDescription() const {
if (IsMultiClass) {
const TMetricParam<int> positiveClass("class", PositiveClass, /*userDefined*/true);
return BuildDescription(ELossFunction::Recall, UseWeights, positiveClass);
} else {
return BuildDescription(ELossFunction::Recall, UseWeights, "%.3g", MakeTargetBorderParam(TargetBorder),
MakePredictionBorderParam(PredictionBorder));
}
}
double TRecallCachingMetric::GetFinalError(const TMetricHolder& error) const {
return error.Stats[1] != 0 ? error.Stats[0] / error.Stats[1] : 1;
}
void TRecallCachingMetric::GetBestValue(EMetricBestValue* valueType, float*) const {
*valueType = EMetricBestValue::Max;
}
/* Precision caching metric */
namespace {
struct TPrecisionCachingMetric final: public TCachingMetric {
explicit TPrecisionCachingMetric(const TLossParams& params,
double predictionBorder)
: TCachingMetric(ELossFunction::Precision, params)
, ClassesCount(BinaryClassesCount)
, PredictionBorder(predictionBorder)
, IsMultiClass(false) {
}
explicit TPrecisionCachingMetric(const TLossParams& params,
int classesCount, int positiveClass)
: TCachingMetric(ELossFunction::Precision, params)
, ClassesCount(classesCount)
, PositiveClass(positiveClass)
, IsMultiClass(true) {
}
TMetricHolder Eval(
const TConstArrayRef<TConstArrayRef<double>> approx,
const TConstArrayRef<TConstArrayRef<double>> approxDelta,
bool isExpApprox,
TConstArrayRef<float> target,
TConstArrayRef<float> weight,
TConstArrayRef<TQueryInfo> /*queriesInfo*/,
int begin,
int end,
TMaybe<TCache *> cache
) const override;
TString GetDescription() const override;
double GetFinalError(const TMetricHolder& error) const override;
void GetBestValue(EMetricBestValue* valueType, float* bestValue) const override;
bool IsAdditiveMetric() const override {
return true;
}
private:
static constexpr double TargetBorder = GetDefaultTargetBorder();
const int ClassesCount = BinaryClassesCount;
const int PositiveClass = 1;
const double PredictionBorder = GetDefaultPredictionBorder();
const bool IsMultiClass = false;
};
}
THolder<IMetric> MakeBinClassPrecisionMetric(const TLossParams& params,
double predictionBorder) {
return MakeHolder<TPrecisionCachingMetric>(params, predictionBorder);
}
THolder<IMetric> MakeMultiClassPrecisionMetric(const TLossParams& params,
int classesCount, int positiveClass) {
return MakeHolder<TPrecisionCachingMetric>(params, classesCount, positiveClass);
}
TMetricHolder TPrecisionCachingMetric::Eval(
const TConstArrayRef<TConstArrayRef<double>> approx,
const TConstArrayRef<TConstArrayRef<double>> approxDelta,
bool isExpApprox,
TConstArrayRef<float> target,
TConstArrayRef<float> weight,
TConstArrayRef<TQueryInfo> /*queriesInfo*/,
int begin,
int end,
TMaybe<TCache*> cache
) const {
Y_ASSERT(!isExpApprox);
Y_ASSERT(approxDelta.empty());
const auto MakeMatrix = [&]() {
return BuildConfusionMatrix(approx, target, UseWeights ? weight : TVector<float>{}, begin, end,
TargetBorder, PredictionBorder);
};
auto confusionMatrix = cache.Empty() ? MakeMatrix() : cache.GetRef()->Get(ConfusionMatrixCacheKey, MakeMatrix, bool(UseWeights), TargetBorder, PredictionBorder);
const auto getStats = [&](int i, int j) { return confusionMatrix.Stats[i * ClassesCount + j]; };
TMetricHolder error(2);
error.Stats[0] = getStats(PositiveClass, PositiveClass);
for (auto i : xrange(ClassesCount)) {
error.Stats[1] += getStats(PositiveClass, i);
}
return error;
}
TString TPrecisionCachingMetric::GetDescription() const {
if (IsMultiClass) {
const TMetricParam<int> positiveClass("class", PositiveClass, /*userDefined*/true);
return BuildDescription(ELossFunction::Precision, UseWeights, positiveClass);
} else {
return BuildDescription(ELossFunction::Precision, UseWeights, "%.3g", MakeTargetBorderParam(TargetBorder),
MakePredictionBorderParam(PredictionBorder));
}
}
double TPrecisionCachingMetric::GetFinalError(const TMetricHolder& error) const {
return error.Stats[1] != 0 ? error.Stats[0] / error.Stats[1] : 1;
}
void TPrecisionCachingMetric::GetBestValue(EMetricBestValue* valueType, float*) const {
*valueType = EMetricBestValue::Max;
}
/* F1 caching metric */
namespace {
struct TF1CachingMetric final: public TCachingMetric {
explicit TF1CachingMetric(const TLossParams& params,
double predictionBorder)
: TCachingMetric(ELossFunction::F1, params)
, ClassesCount(BinaryClassesCount)
, PredictionBorder(predictionBorder)
, IsMultiClass(false) {
}
explicit TF1CachingMetric(const TLossParams& params,
int classesCount, int positiveClass)
: TCachingMetric(ELossFunction::F1, params)
, ClassesCount(classesCount)
, PositiveClass(positiveClass)
, IsMultiClass(true) {
}
TMetricHolder Eval(
const TConstArrayRef<TConstArrayRef<double>> approx,
const TConstArrayRef<TConstArrayRef<double>> approxDelta,
bool isExpApprox,
TConstArrayRef<float> target,
TConstArrayRef<float> weight,
TConstArrayRef<TQueryInfo> /*queriesInfo*/,
int begin,
int end,
TMaybe<TCache *> cache
) const override;
TString GetDescription() const override;
TVector<TString> GetStatDescriptions() const override;
double GetFinalError(const TMetricHolder& error) const override;
void GetBestValue(EMetricBestValue* valueType, float* bestValue) const override;
bool IsAdditiveMetric() const override {
return true;
}
private:
static constexpr double TargetBorder = GetDefaultTargetBorder();
const int ClassesCount = BinaryClassesCount;
const int PositiveClass = 1;
const double PredictionBorder = GetDefaultPredictionBorder();
const bool IsMultiClass = false;
};
}
THolder<IMetric> MakeBinClassF1Metric(const TLossParams& params,
double predictionBorder) {
return MakeHolder<TF1CachingMetric>(params, predictionBorder);
}
THolder<IMetric> MakeMultiClassF1Metric(const TLossParams& params,
int classesCount, int positiveClass) {
return MakeHolder<TF1CachingMetric>(params, classesCount, positiveClass);
}
TMetricHolder TF1CachingMetric::Eval(
const TConstArrayRef<TConstArrayRef<double>> approx,
const TConstArrayRef<TConstArrayRef<double>> approxDelta,
bool isExpApprox,
TConstArrayRef<float> target,
TConstArrayRef<float> weight,
TConstArrayRef<TQueryInfo> /*queriesInfo*/,
int begin,
int end,
TMaybe<TCache*> cache
) const {
Y_ASSERT(!isExpApprox);
Y_ASSERT(approxDelta.empty());
const auto MakeMatrix = [&]() {
return BuildConfusionMatrix(approx, target, UseWeights ? weight : TVector<float>{}, begin, end,
TargetBorder, PredictionBorder);
};
auto confusionMatrix = cache.Empty() ? MakeMatrix() : cache.GetRef()->Get(ConfusionMatrixCacheKey, MakeMatrix, bool(UseWeights), TargetBorder, PredictionBorder);
const auto getStats = [&](int i, int j) { return confusionMatrix.Stats[i * ClassesCount + j]; };
TMetricHolder error(3);
error.Stats[0] = getStats(PositiveClass, PositiveClass);
for (auto i : xrange(ClassesCount)) {
error.Stats[1] += getStats(PositiveClass, i);
error.Stats[2] += getStats(i, PositiveClass);
}
return error;
}
TVector<TString> TF1CachingMetric::GetStatDescriptions() const {
return {"TP", "TP+FP", "TP+FN"};
}
TString TF1CachingMetric::GetDescription() const {
if (IsMultiClass) {
const TMetricParam<int> positiveClass("class", PositiveClass, /*userDefined*/true);
return BuildDescription(ELossFunction::F1, UseWeights, positiveClass);
} else {
return BuildDescription(ELossFunction::F1, UseWeights, "%.3g", MakeTargetBorderParam(TargetBorder),
MakePredictionBorderParam(PredictionBorder));
}
}
double TF1CachingMetric::GetFinalError(const TMetricHolder& error) const {
double precision = error.Stats[1] != 0 ? error.Stats[0] / error.Stats[1] : 1.0;
double recall = error.Stats[2] != 0 ? error.Stats[0] / error.Stats[2] : 1.0;
return precision + recall != 0 ? 2 * precision * recall / (precision + recall) : 0.0;
}
void TF1CachingMetric::GetBestValue(EMetricBestValue* valueType, float*) const {
*valueType = EMetricBestValue::Max;
}
/* TotalF1 caching metric */
namespace {
struct TTotalF1CachingMetric final: public TCachingMetric {
static constexpr int StatsCardinality = 3;
explicit TTotalF1CachingMetric(const TLossParams& params,
double predictionBorder, EF1AverageType averageType)
: TCachingMetric(ELossFunction::TotalF1, params)
, ClassesCount(BinaryClassesCount)
, PredictionBorder(predictionBorder)
, AverageType(averageType) {
}
explicit TTotalF1CachingMetric(const TLossParams& params,
int classesCount, EF1AverageType averageType)
: TCachingMetric(ELossFunction::TotalF1, params)
, ClassesCount(classesCount)
, AverageType(averageType) {
}
TMetricHolder Eval(
const TConstArrayRef<TConstArrayRef<double>> approx,
const TConstArrayRef<TConstArrayRef<double>> approxDelta,
bool isExpApprox,
TConstArrayRef<float> target,
TConstArrayRef<float> weight,
TConstArrayRef<TQueryInfo> /*queriesInfo*/,
int begin,
int end,
TMaybe<TCache *> cache
) const override;
TVector<TString> GetStatDescriptions() const override;
double GetFinalError(const TMetricHolder& error) const override;
void GetBestValue(EMetricBestValue* valueType, float* bestValue) const override;
bool IsAdditiveMetric() const override {
return true;
}
private:
static constexpr double TargetBorder = GetDefaultTargetBorder();
const int ClassesCount = BinaryClassesCount;
const double PredictionBorder = GetDefaultPredictionBorder();
const EF1AverageType AverageType;
};
}
THolder<IMetric> MakeTotalF1Metric(const TLossParams& params,
int classesCount, EF1AverageType averageType) {
return MakeHolder<TTotalF1CachingMetric>(params, classesCount, averageType);
}
TMetricHolder TTotalF1CachingMetric::Eval(
const TConstArrayRef<TConstArrayRef<double>> approx,
const TConstArrayRef<TConstArrayRef<double>> approxDelta,
bool isExpApprox,
TConstArrayRef<float> target,
TConstArrayRef<float> weight,
TConstArrayRef<TQueryInfo> /*queriesInfo*/,
int begin,
int end,
TMaybe<TCache*> cache
) const {
Y_ASSERT(!isExpApprox);
Y_ASSERT(approxDelta.empty());
const auto MakeMatrix = [&]() {
return BuildConfusionMatrix(approx, target, UseWeights ? weight : TVector<float>{}, begin, end,
TargetBorder, PredictionBorder);
};
auto confusionMatrix = cache.Empty() || 1 ? MakeMatrix() : cache.GetRef()->Get(ConfusionMatrixCacheKey, MakeMatrix, bool(UseWeights), TargetBorder, PredictionBorder);
const auto getStats = [&](int i, int j) { return confusionMatrix.Stats[i * ClassesCount + j]; };
TVector<double> classTruePositive(ClassesCount);
TVector<double> classSize(ClassesCount);
TVector<double> classPredictedSize(ClassesCount);
for (auto i : xrange(ClassesCount)) {
classTruePositive[i] = getStats(i, i);
for (auto j : xrange(ClassesCount)) {
classSize[i] += getStats(j, i);
classPredictedSize[i] += getStats(i, j);
}
}
TMetricHolder error(StatsCardinality * ClassesCount);
for (auto i : xrange(ClassesCount)) {
error.Stats[StatsCardinality * i + 0] = classSize[i];
error.Stats[StatsCardinality * i + 1] = classPredictedSize[i];
error.Stats[StatsCardinality * i + 2] = classTruePositive[i];
}
return error;
}
TVector<TString> TTotalF1CachingMetric::GetStatDescriptions() const {
TVector<TString> description;
for (auto classIdx : xrange(ClassesCount)) {
auto prefix = "Class=" + ToString(classIdx) + ",";
description.push_back(prefix + "TP+FN");
description.push_back(prefix + "TP+FP");
description.push_back(prefix + "TP");
}
return description;
}
double TTotalF1CachingMetric::GetFinalError(const TMetricHolder& error) const {
double numerator = 0.0;
double denumerator = 0.0;
for (auto i : xrange(ClassesCount)) {
double classSize = error.Stats[StatsCardinality * i + 0];
double classPredictedSize = error.Stats[StatsCardinality * i + 1];
double truePositive = error.Stats[StatsCardinality * i + 2];
double f1 = classSize + classPredictedSize != 0 ? 2 * truePositive / (classSize + classPredictedSize) : 0.0;
if (AverageType == EF1AverageType::Weighted) {
numerator += f1 * classSize;
denumerator += classSize;
} else if (AverageType == EF1AverageType::Micro) {
numerator += 2 * truePositive;
denumerator += classSize + classPredictedSize;
} else if (AverageType == EF1AverageType::Macro) {
numerator += f1;
denumerator += 1;
}
}
return numerator / denumerator;
}
void TTotalF1CachingMetric::GetBestValue(EMetricBestValue* valueType, float*) const {
*valueType = EMetricBestValue::Max;
}
/* Kappa */
namespace {
struct TKappaMetric final: public TCachingMetric {
explicit TKappaMetric(const TLossParams& params,
int classCount = 2, double predictionBorder = GetDefaultPredictionBorder())
: TCachingMetric(ELossFunction::Kappa, params)
, TargetBorder(GetDefaultTargetBorder())
, PredictionBorder(predictionBorder)
, ClassCount(classCount) {
}
static TVector<THolder<IMetric>> Create(const TMetricConfig& config);
TMetricHolder Eval(
const TConstArrayRef<TConstArrayRef<double>> approx,
const TConstArrayRef<TConstArrayRef<double>> approxDelta,
bool isExpApprox,
TConstArrayRef<float> target,
TConstArrayRef<float> weight,
TConstArrayRef<TQueryInfo> queriesInfo,
int begin,
int end,
TMaybe<TCache*> cache
) const override;
TString GetDescription() const override;
double GetFinalError(const TMetricHolder& error) const override;
void GetBestValue(EMetricBestValue* valueType, float* bestValue) const override;
bool IsAdditiveMetric() const override {
return true;
}
private:
const double TargetBorder = GetDefaultTargetBorder();
const double PredictionBorder = GetDefaultPredictionBorder();
const int ClassCount;
};
}
// static.
TVector<THolder<IMetric>> TKappaMetric::Create(const TMetricConfig& config) {
if (config.ApproxDimension == 1) {
config.ValidParams->insert("border");
return AsVector(MakeHolder<TKappaMetric>(config.Params, /*classCount=*/2, config.GetPredictionBorderOrDefault()));
} else {
return AsVector(MakeHolder<TKappaMetric>(config.Params, config.ApproxDimension));
}
}
TMetricHolder TKappaMetric::Eval(
const TConstArrayRef<TConstArrayRef<double>> approx,
const TConstArrayRef<TConstArrayRef<double>> approxDelta,
bool isExpApprox,
TConstArrayRef<float> target,
TConstArrayRef<float> weight,
TConstArrayRef<TQueryInfo> /*queriesInfo*/,
int begin,
int end,
TMaybe<TCache*> cache
) const {
Y_ASSERT(approxDelta.empty());
Y_ASSERT(!isExpApprox);
const auto MakeMatrix = [&]() {
return BuildConfusionMatrix(approx, target, UseWeights ? weight : TVector<float>{}, begin, end,
TargetBorder, PredictionBorder);
};
return cache.Empty() || 1 ? MakeMatrix() : cache.GetRef()->Get(ConfusionMatrixCacheKey, MakeMatrix, bool(UseWeights), TargetBorder, PredictionBorder);
}
TString TKappaMetric::GetDescription() const {
return BuildDescription(ELossFunction::Kappa, "%.3g", MakeTargetBorderParam(TargetBorder),
MakePredictionBorderParam(PredictionBorder));
}
void TKappaMetric::GetBestValue(EMetricBestValue* valueType, float*) const {
*valueType = EMetricBestValue::Max;
}
double TKappaMetric::GetFinalError(const TMetricHolder& error) const {
return CalcKappa(error, ClassCount, EKappaMetricType::Cohen);
}
/* WKappa */
namespace {
struct TWKappaMetric final: public TCachingMetric {
explicit TWKappaMetric(const TLossParams& params,
int classCount = 2, double predictionBorder = GetDefaultPredictionBorder())
: TCachingMetric(ELossFunction::WKappa, params)
, TargetBorder(GetDefaultTargetBorder())
, PredictionBorder(predictionBorder)
, ClassCount(classCount) {
}
static TVector<THolder<IMetric>> Create(const TMetricConfig& config);
TMetricHolder Eval(
const TConstArrayRef<TConstArrayRef<double>> approx,
const TConstArrayRef<TConstArrayRef<double>> approxDelta,
bool isExpApprox,
TConstArrayRef<float> target,
TConstArrayRef<float> weight,
TConstArrayRef<TQueryInfo> queriesInfo,
int begin,
int end,
TMaybe<TCache*> cache
) const override;
TString GetDescription() const override;
double GetFinalError(const TMetricHolder& error) const override;
void GetBestValue(EMetricBestValue *valueType, float *bestValue) const override;
bool IsAdditiveMetric() const override {
return true;
}
private:
const double TargetBorder = GetDefaultTargetBorder();
const double PredictionBorder = GetDefaultPredictionBorder();
const int ClassCount;
};
}
// static.
TVector<THolder<IMetric>> TWKappaMetric::Create(const TMetricConfig& config) {
if (config.ApproxDimension == 1) {
config.ValidParams->insert("border");
return AsVector(MakeHolder<TWKappaMetric>(config.Params, /*classCount=*/2, config.GetPredictionBorderOrDefault()));
} else {
return AsVector(MakeHolder<TWKappaMetric>(config.Params, config.ApproxDimension));
}
}
TMetricHolder TWKappaMetric::Eval(
const TConstArrayRef<TConstArrayRef<double>> approx,
const TConstArrayRef<TConstArrayRef<double>> approxDelta,
bool isExpApprox,
TConstArrayRef<float> target,
TConstArrayRef<float> weight,
TConstArrayRef<TQueryInfo> /*queriesInfo*/,
int begin,
int end,
TMaybe<TCache*> cache
) const {
Y_ASSERT(approxDelta.empty());
Y_ASSERT(!isExpApprox);
const auto MakeMatrix = [&]() {
return BuildConfusionMatrix(approx, target, UseWeights ? weight : TVector<float>{}, begin, end,
TargetBorder, PredictionBorder);
};
return cache.Empty() || 1 ? MakeMatrix() : cache.GetRef()->Get(ConfusionMatrixCacheKey, MakeMatrix, bool(UseWeights), TargetBorder, PredictionBorder);
}
TString TWKappaMetric::GetDescription() const {
return BuildDescription(ELossFunction::WKappa, "%.3g", MakeTargetBorderParam(TargetBorder),
MakePredictionBorderParam(PredictionBorder));
}
void TWKappaMetric::GetBestValue(EMetricBestValue* valueType, float*) const {
*valueType = EMetricBestValue::Max;
}
double TWKappaMetric::GetFinalError(const TMetricHolder& error) const {
return CalcKappa(error, ClassCount, EKappaMetricType::Weighted);
}
TVector<TMetricHolder> EvalErrorsWithCaching(
const TVector<TVector<double>>& approx,
const TVector<TVector<double>>& approxDelta,
bool isExpApprox,
TConstArrayRef<TConstArrayRef<float>> target,
TConstArrayRef<float> weight,
TConstArrayRef<TQueryInfo> queriesInfo,
TConstArrayRef<const IMetric*> metrics,
NPar::ILocalExecutor* localExecutor
) {
const auto threadCount = localExecutor->GetThreadCount() + 1;
const auto objectCount = approx.front().size();
const auto queryCount = queriesInfo.size();
const auto calcCaching = [&](auto metric, auto from, auto to, auto *cache) {
CB_ENSURE(!metric->NeedTarget() || target.size() == 1, "Metric [" + metric->GetDescription() + "] requires "
<< (target.size() > 1 ? "one-dimensional" : "") << "target");
return metric->Eval(To2DConstArrayRef<double>(approx), To2DConstArrayRef<double>(approxDelta), isExpApprox, metric->NeedTarget() ? target[0] : TConstArrayRef<float>(),
weight, queriesInfo, from, to, cache);
};
const auto calcNonCaching = [&](auto metric, auto from, auto to) {
CB_ENSURE(!metric->NeedTarget() || target.size() == 1, "Metric [" + metric->GetDescription() + "] requires "
<< (target.size() > 1 ? "one-dimensional" : "") << "target");
return metric->Eval(To2DConstArrayRef<double>(approx), To2DConstArrayRef<double>(approxDelta), isExpApprox, metric->NeedTarget() ? target[0] : TConstArrayRef<float>(),
weight, queriesInfo, from, to, *localExecutor);
};
const auto calcMultiRegression = [&](auto metric, auto from, auto to) {
CB_ENSURE(!metric->NeedTarget() || target.size() > 0, "Metric [" + metric->GetDescription() + "] requires target");
CB_ENSURE(!isExpApprox, "Metric [" << metric->GetDescription() << "] does not support exponentiated approxes");
return metric->Eval(approx, approxDelta, target,
weight, from, to, *localExecutor);
};
TVector<TMetricHolder> errors;
errors.reserve(metrics.size());
NPar::ILocalExecutor::TExecRangeParams objectwiseBlockParams(0, objectCount);
if (!target.empty()) {
const auto objectwiseEffectiveBlockCount = Min(threadCount, int(ceil(double(objectCount) / GetMinBlockSize(objectCount))));
objectwiseBlockParams.SetBlockCount(objectwiseEffectiveBlockCount);
}
NPar::ILocalExecutor::TExecRangeParams querywiseBlockParams(0, queryCount);
if (!queriesInfo.empty()) {
const auto querywiseEffectiveBlockCount = Min(threadCount, int(ceil(double(queryCount) / GetMinBlockSize(objectCount))));
querywiseBlockParams.SetBlockCount(querywiseEffectiveBlockCount);
}
TCache nonAdditiveCache;
TVector<TCache> objectwiseAdditiveCache(objectwiseBlockParams.GetBlockCount());
TVector<TCache> querywiseAdditiveCache(querywiseBlockParams.GetBlockCount());
TVector<TMetricHolder> objectwiseBlockResults(objectwiseBlockParams.GetBlockCount());
TVector<TMetricHolder> querywiseBlockResults(querywiseBlockParams.GetBlockCount());
for (auto i : xrange(metrics.size())) {
auto metric = metrics[i];
auto cachingMetric = dynamic_cast<const TCachingMetric*>(metrics[i]);
auto multiMetric = dynamic_cast<const TMultiRegressionMetric*>(metrics[i]);
Y_ASSERT(cachingMetric == nullptr || multiMetric == nullptr);
const bool isObjectwise = metric->GetErrorType() == EErrorType::PerObjectError;
if (cachingMetric && metric->IsAdditiveMetric()) {
const auto blockSize = isObjectwise ? objectwiseBlockParams.GetBlockSize() : querywiseBlockParams.GetBlockSize();
const auto blockCount = isObjectwise ? objectwiseBlockParams.GetBlockCount() : querywiseBlockParams.GetBlockCount();
auto &results = isObjectwise ? objectwiseBlockResults : querywiseBlockResults;
auto &cache = isObjectwise ? objectwiseAdditiveCache : querywiseAdditiveCache;
const auto end = isObjectwise ? objectCount : queryCount;
NPar::ParallelFor(*localExecutor, 0, blockCount, [&](auto blockId) {
const auto from = blockId * blockSize;
const auto to = Min<int>((blockId + 1) * blockSize, end);
results[blockId] = calcCaching(cachingMetric, from, to, &cache[blockId]);
});
TMetricHolder error;
for (const auto &blockResult : results) {
error.Add(blockResult);
}
errors.push_back(error);
} else {
const auto end = isObjectwise ? objectCount : queryCount;
if (cachingMetric) {
errors.push_back(calcCaching(cachingMetric, 0, end, &nonAdditiveCache));
} else if (multiMetric) {
errors.push_back(calcMultiRegression(multiMetric, 0, end));
} else {
errors.push_back(calcNonCaching(metric, 0, end));
}
}
}
return errors;
}
template <typename TMetricType>
static TVector<THolder<IMetric>> CreateMetric(int approxDimension, const TMetricConfig& config) {
TVector<THolder<IMetric>> result;
if (approxDimension == 1) {
result.emplace_back(MakeHolder<TMetricType>(config.Params, config.GetPredictionBorderOrDefault()));
} else {
result.emplace_back(MakeHolder<TMetricType>(config.Params, approxDimension));
}
return result;
}
template <typename TMetricType>
static TVector<THolder<IMetric>> CreateMetricClasswise(int approxDimension, const TMetricConfig& config) {
TVector<THolder<IMetric>> result;
if (approxDimension == 1) {
result.emplace_back(MakeHolder<TMetricType>(config.Params, config.GetPredictionBorderOrDefault()));
} else {
for (int i : xrange(approxDimension)) {
result.emplace_back(MakeHolder<TMetricType>(config.Params, approxDimension, i));
}
}
return result;
}
TVector<THolder<IMetric>> CreateCachingMetrics(const TMetricConfig& config) {
*config.ValidParams = TSet<TString>{};
TVector<THolder<IMetric>> result;
switch(config.Metric) {
case ELossFunction::F1: {
return CreateMetricClasswise<TF1CachingMetric>(config.ApproxDimension, config);
}
case ELossFunction::TotalF1: {
config.ValidParams->insert("average");
EF1AverageType averageType = EF1AverageType::Weighted;
if (config.GetParamsMap().contains("average")) {
averageType = FromString<EF1AverageType>(config.GetParamsMap().at("average"));
}
if (config.ApproxDimension == 1) {
result.emplace_back(MakeHolder<TTotalF1CachingMetric>(config.Params, config.GetPredictionBorderOrDefault(), averageType));
} else {
result.emplace_back(MakeHolder<TTotalF1CachingMetric>(config.Params, config.ApproxDimension, averageType));
}
return result;
}
case ELossFunction::MCC: {
return CreateMetric<TMCCCachingMetric>(config.ApproxDimension, config);
}
case ELossFunction::BrierScore: {
CB_ENSURE(config.ApproxDimension == 1, "Brier Score is used only for binary classification problems.");
result.emplace_back(MakeBrierScoreMetric(config.Params));
return result;
}
case ELossFunction::ZeroOneLoss: {
return CreateMetric<TZeroOneLossCachingMetric>(config.ApproxDimension, config);
}
case ELossFunction::Accuracy: {
return CreateMetric<TAccuracyCachingMetric>(config.ApproxDimension, config);
}
case ELossFunction::CtrFactor: {
result.emplace_back(MakeCtrFactorMetric(config.Params));
return result;
}
case ELossFunction::Precision: {
return CreateMetricClasswise<TPrecisionCachingMetric>(config.ApproxDimension, config);
}
case ELossFunction::Recall:
return CreateMetricClasswise<TRecallCachingMetric>(config.ApproxDimension, config);
break;
case ELossFunction::Kappa:
AppendTemporaryMetricsVector(TKappaMetric::Create(config), &result);
break;
case ELossFunction::WKappa:
AppendTemporaryMetricsVector(TWKappaMetric::Create(config), &result);
break;
default:
break;
}
return result;
}
|
// -*- C++ -*-
//
// $Id: Method_Request_Updates_T.inl 1861 2011-08-31 16:18:08Z mesnierp $
#include "tao/debug.h"
#include "orbsvcs/Notify/Peer.h"
TAO_BEGIN_VERSIONED_NAMESPACE_DECL
template <class SEQ, class PROXY, class SEQ_PARAM, class PROXY_PARAM> ACE_INLINE int
TAO_Notify_Method_Request_Updates_T<SEQ, PROXY, SEQ_PARAM, PROXY_PARAM>::execute_i (void)
{
if (this->proxy_->has_shutdown ())
return 0; // If we were shutdown while waiting in the queue, return with no action.
try
{
TAO_Notify_Peer* peer = this->proxy_->peer();
if (peer != 0)
{
peer->dispatch_updates (this->added_, this->removed_);
}
}
catch (const CORBA::Exception& ex)
{
if (TAO_debug_level > 0)
ex._tao_print_exception (
"TAO_Notify_Method_Request_Updates::execute error sending updates\n");
}
return 0;
}
TAO_END_VERSIONED_NAMESPACE_DECL
|
/* Copyright 2017 - 2022 R. Thomas
* Copyright 2017 - 2022 Quarkslab
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <iostream>
#include <memory>
#include <LIEF/VDEX.hpp>
#include <LIEF/logging.hpp>
using namespace LIEF::VDEX;
int main(int argc, char **argv) {
LIEF::logging::set_level(LIEF::logging::LOGGING_LEVEL::LOG_DEBUG);
if (argc != 2) {
std::cerr << "Usage: " << argv[0] << " <VDEX file>" << '\n';
return EXIT_FAILURE;
}
std::unique_ptr<const File> file;
try {
file = std::unique_ptr<const File>{LIEF::VDEX::Parser::parse(argv[1])};
for (auto& f : file->dex_files()) {
std::cout << f.location() << '\n';
}
} catch (const LIEF::exception& e) {
std::cerr << e.what() << '\n';
return EXIT_FAILURE;
}
}
|
extern const BulletStepFunc bullet_9d9f287906e0540e2a8dc3a6d1211be4_d2333f29a4c9742a90a78c7706523640[] = {
stepfunc_a82599f300e4b150f54085b7056bd26d_d2333f29a4c9742a90a78c7706523640,
stepfunc_c2db9f05d4f182941e7e9906f14f63c0_d2333f29a4c9742a90a78c7706523640,
stepfunc_d2b0356cea9b35dc55335e5a82562c63_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_d2b0356cea9b35dc55335e5a82562c63_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_d2b0356cea9b35dc55335e5a82562c63_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_d2b0356cea9b35dc55335e5a82562c63_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_d2b0356cea9b35dc55335e5a82562c63_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_d2b0356cea9b35dc55335e5a82562c63_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_d2b0356cea9b35dc55335e5a82562c63_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_d2b0356cea9b35dc55335e5a82562c63_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_d2b0356cea9b35dc55335e5a82562c63_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_d2b0356cea9b35dc55335e5a82562c63_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_d2b0356cea9b35dc55335e5a82562c63_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_d2b0356cea9b35dc55335e5a82562c63_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_d2b0356cea9b35dc55335e5a82562c63_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_d2b0356cea9b35dc55335e5a82562c63_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_d2b0356cea9b35dc55335e5a82562c63_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_d2b0356cea9b35dc55335e5a82562c63_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_d2b0356cea9b35dc55335e5a82562c63_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_d2b0356cea9b35dc55335e5a82562c63_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_d2b0356cea9b35dc55335e5a82562c63_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_d2b0356cea9b35dc55335e5a82562c63_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_be4e8fee0f10cc7b24954694f2d8a550_d2333f29a4c9742a90a78c7706523640,
stepfunc_dae2cf81747ffb5070f05c8837b1d568_d2333f29a4c9742a90a78c7706523640,
NULL};
|
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cerrno>
#include <fcntl.h>
#include <unistd.h>
using std::cout;
using std::endl;
int main(const int argc, const char * argv []) {
if (argc != 2) {
cout << "Usage: " << argv[0] << " FILE" << endl;
exit(0);
} // if
const char * filename = argv[1];
int fd = open(filename, O_WRONLY | O_TRUNC | O_CREAT, 0666);
if (fd != -1) {
cout << "Opened " << filename << "; "
<< "fd = " << fd << "; "
<< "error = " << strerror(errno)
<< endl;
} else {
cout << "Could not open " << filename << "; "
<< "fd = " << fd << " (should be -1); "
<< "error = " << strerror(errno)
<< endl;
exit(0);
} // if
int ofd = dup(STDOUT_FILENO); // make duplicate of standard out
int nfd = dup2(fd, STDOUT_FILENO); // redirect standard out
if (nfd == -1) {
cout << "Could not dup2 with " << filename << "; "
<< "nfd = " << nfd << " (should be -1); "
<< "error = " << strerror(errno)
<< endl;
exit(0);
} // if
cout << "hello" << endl;
// redirect standard out again
dup2(ofd, STDOUT_FILENO);
int cr = close(fd);
if (cr != -1) {
cout << "Closed " << filename << "; "
<< "cr = " << cr << "; "
<< "error = " << strerror(errno)
<< endl;
} else {
cout << "Could not close " << filename << "; "
<< "cr = " << cr << " (should be -1); "
<< "error = " << strerror(errno)
<< endl;
} // if
return EXIT_SUCCESS;
} // main
|
#include <cstdlib>
#include <memory>
#include <algorithm>
#include <complex>
#include <iostream>
#include <fstream>
#include <map>
#include <utility>
#include <vector>
#include <numeric>
#if defined(USE_MPI)
#include <mpi.h>
#endif
#include <boost/version.hpp>
#include "io/hdf_multi.h"
#include "io/hdf_archive.h"
#include "AFQMC/config.h"
#include "AFQMC/Hamiltonians/HamiltonianFactory.h"
#include "AFQMC/Hamiltonians/HamiltonianFactory_Helper.h"
#include "AFQMC/Hamiltonians/THCHamiltonian.h"
#include "AFQMC/Hamiltonians/FactorizedSparseHamiltonian.h"
#include "AFQMC/Hamiltonians/KPFactorizedHamiltonian.h"
#include "AFQMC/Hamiltonians/RealDenseHamiltonian.h"
#include "AFQMC/Hamiltonians/RealDenseHamiltonian_v2.h"
//#include "AFQMC/Hamiltonians/KPTHCHamiltonian.h"
#include "AFQMC/Utilities/readHeader.h"
#include "AFQMC/Utilities/Utils.hpp"
#include "AFQMC/Numerics/ma_operations.hpp"
#include "AFQMC/Matrix/csr_matrix.hpp"
#include "AFQMC/Matrix/hdf5_readers.hpp"
#include "AFQMC/Utilities/hdf5_consistency_helper.hpp"
#include "AFQMC/Matrix/array_partition.hpp"
namespace qmcplusplus
{
namespace afqmc
{
Hamiltonian HamiltonianFactory::fromHDF5(GlobalTaskGroup& gTG, xmlNodePtr cur)
{
if (cur == NULL)
APP_ABORT("Error: NULL xml pointer in HamiltonianFactory::parse(). \n");
std::string info("info0");
OhmmsAttributeSet oAttrib;
oAttrib.add(info, "info");
oAttrib.put(cur);
if (InfoMap.find(info) == InfoMap.end())
{
app_error() << "ERROR: Undefined info in execute block. \n";
APP_ABORT("ERROR: Undefined info in execute block. \n");
}
AFQMCInfo& AFinfo = InfoMap[info];
int NMO = AFinfo.NMO;
int NAEA = AFinfo.NAEA;
int NAEB = AFinfo.NAEB;
// defaults
double cutoff1bar = 1e-8;
std::string fileName = "";
int number_of_TGs = 1;
int n_reading_cores = -1;
std::string alt = "";
ParameterSet m_param;
m_param.add(cutoff1bar, "cutoff_1bar", "double");
m_param.add(fileName, "filename", "std::string");
m_param.add(number_of_TGs, "nblocks", "int");
m_param.add(n_reading_cores, "num_io_cores", "int");
m_param.add(alt, "alternate", "std::string");
m_param.put(cur);
// make or get TG
number_of_TGs = std::max(1, std::min(number_of_TGs, gTG.getTotalNodes()));
TaskGroup_& TG = getTG(gTG, number_of_TGs);
// processor info
int ncores = TG.getTotalCores(), coreid = TG.getCoreID();
int nread = (n_reading_cores <= 0) ? (ncores) : (std::min(n_reading_cores, ncores));
int head = TG.getGlobalRank() == 0;
app_log() << " Initializing Hamiltonian from file: " << fileName << std::endl;
// FIX FIX FIX
hdf_archive dump(TG.Global());
// these cores will read from hdf file
if (coreid < nread)
{
if (!dump.open(fileName, H5F_ACC_RDONLY))
{
app_error() << " Error opening integral file in SparseGeneralHamiltonian. \n";
APP_ABORT("");
}
if (!dump.push("Hamiltonian", false))
{
app_error() << " Error in HamiltonianFactory::fromHDF5(): Group not Hamiltonian found. \n";
APP_ABORT("");
}
}
HamiltonianTypes htype = UNKNOWN;
if (head)
htype = peekHamType(dump);
{
int htype_ = int(htype);
TG.Global().broadcast_n(&htype_, 1, 0);
htype = HamiltonianTypes(htype_);
}
int complex_integrals;
// Hamiltonian file may not contain flag.
bool have_complex_flag = true;
if (head)
{
if (!dump.readEntry(complex_integrals, "ComplexIntegrals"))
{
have_complex_flag = false;
}
}
TG.Global().broadcast_n(&have_complex_flag, 1, 0);
if (have_complex_flag && head)
{
#ifdef QMC_COMPLEX
if (!complex_integrals)
app_log() << " Note: Found real integrals with QMC_COMPLEX=1.\n";
#else
if (complex_integrals)
{
app_error() << " Error in HamiltonianFactory::fromHDF5(): Found complex integrals but QMC_COMPLEX=0.\n";
app_error() << " Please build QMCPACK with complex support or write real integrals if appropriate.\n";
APP_ABORT("");
}
#endif
}
int int_blocks, nvecs;
std::vector<int> Idata(8);
if (head)
if (!dump.readEntry(Idata, "dims"))
{
app_error() << " Error in HamiltonianFactory::fromHDF5(): Problems reading dims. \n";
APP_ABORT("");
}
TG.Global().broadcast(Idata.begin(), Idata.end());
int_blocks = Idata[2];
if (Idata[3] != NMO)
{
app_error() << " ERROR: NMO differs from value in integral file. \n";
APP_ABORT(" Error: NMO differs from value in integral file. \n");
}
if (Idata[4] != NAEA)
{
app_log() << " WARNING: NAEA differs from value in integral file. \n";
// APP_ABORT(" ");
}
if (Idata[5] != NAEB)
{
app_log() << " WARNING: NAEB differs from value in integral file. \n";
// APP_ABORT(" ");
}
nvecs = Idata[7];
#ifdef QMC_COMPLEX
int nkpts = -1;
if (htype == KPFactorized || htype == KPTHC)
nkpts = Idata[2];
#endif
// 1 body hamiltonian: Why isn't this in shared memory!!!
boost::multi::array<ValueType, 2> H1({NMO, NMO});
ValueType NuclearCoulombEnergy(0);
ValueType FrozenCoreEnergy(0);
if (head)
{
std::vector<RealType> Rdata(2);
if (!dump.readEntry(Rdata, "Energies"))
{
app_error() << " Error in HamiltonianFactory::fromHDF5(): Problems reading dataset. \n";
APP_ABORT(" ");
}
if (Rdata.size() > 0)
NuclearCoulombEnergy = Rdata[0];
if (Rdata.size() > 1)
FrozenCoreEnergy = Rdata[1];
}
TG.Global().broadcast_n(&NuclearCoulombEnergy, 1, 0);
TG.Global().broadcast_n(&FrozenCoreEnergy, 1, 0);
if (head)
{
using ma::conj;
using std::imag;
bool foundH1 = false;
#ifdef QMC_COMPLEX
if (htype == KPFactorized || htype == KPTHC)
{
#else
if (htype == RealDenseFactorized)
{
#endif
// nothing to do, H1 is read during construction of HamiltonianOperations object.
}
else
{
if (readComplexOrReal(dump, "hcore", H1)) {}
else
{
app_log() << " Reading one-body Hamiltonian in sparse format.\n";
H1.reextent({NMO, NMO});
if (Idata[0] < 1)
{
app_error() << " Error in HamiltonianFactory::fromHDF5(): Dimensions of H1 < 1. \n";
APP_ABORT(" ");
}
std::vector<OrbitalType> ivec(2 * Idata[0]);
if (!dump.readEntry(ivec, "H1_indx"))
{
app_error() << " Error in HamiltonianFactory::fromHDF5(): Problems reading H1_indx. \n";
APP_ABORT(" ");
}
std::vector<ValueType> vvec(Idata[0]);
if (!readComplexOrReal(dump, "H1", vvec))
{
app_error() << " Error in HamiltonianFactory::fromHDF5(): Problems reading H1. \n";
APP_ABORT(" ");
}
for (int i = 0; i < Idata[0]; i++)
{
// keep i<=j by default
if (ivec[i] <= ivec[i])
{
H1[ivec[2 * i]][ivec[2 * i + 1]] = vvec[i];
H1[ivec[2 * i + 1]][ivec[2 * i]] = ma::conj(vvec[i]);
}
else
{
H1[ivec[2 * i]][ivec[2 * i + 1]] = ma::conj(vvec[i]);
H1[ivec[2 * i + 1]][ivec[2 * i]] = vvec[i];
}
}
}
app_log() << " Successfully read one-body Hamiltonian.\n";
app_log() << " Shape of one-body Hamiltonian: (" << NMO << ", " << NMO << ")." << std::endl;
}
}
TG.Global().broadcast_n(to_address(H1.origin()), H1.num_elements(), 0);
// now read the integrals
#ifdef QMC_COMPLEX
if (htype == KPTHC)
{
APP_ABORT(" Error: KPTHC hamiltonian not yet working. \n");
if (coreid < nread && !dump.push("KPTHC", false))
{
app_error() << " Error in HamiltonianFactory::fromHDF5(): Group not KPTHC found. \n";
APP_ABORT("");
}
if (coreid < nread)
{
dump.pop();
dump.pop();
dump.close();
}
TG.global_barrier();
return Hamiltonian{};
// return Hamiltonian(KPTHCHamiltonian(AFinfo,cur,std::move(H1),TG,
// NuclearCoulombEnergy,FrozenCoreEnergy));
}
else if (htype == KPFactorized)
{
if (coreid < nread && !dump.push("KPFactorized", false))
{
app_error() << " Error in HamiltonianFactory::fromHDF5(): Group not KPFactorized found. \n";
APP_ABORT("");
}
if (coreid < nread)
{
dump.pop();
dump.pop();
dump.close();
}
TG.global_barrier();
// KPFactorizedHamiltonian matrices are read by THCHamiltonian object when needed,
// since their ownership is passed to the HamOps object.
return Hamiltonian(KPFactorizedHamiltonian(AFinfo, cur, std::move(H1), TG, NuclearCoulombEnergy, FrozenCoreEnergy));
}
else
#else
if (htype == RealDenseFactorized)
{
if (coreid < nread && !dump.push("DenseFactorized", false))
{
app_error() << " Error in HamiltonianFactory::fromHDF5(): Group not DenseFactorized found. \n";
APP_ABORT("");
}
if (coreid < nread)
{
dump.pop();
dump.pop();
dump.close();
}
TG.global_barrier();
// KPFactorizedHamiltonian matrices are read by THCHamiltonian object when needed,
// since their ownership is passed to the HamOps object.
#if defined(ENABLE_CUDA) || defined(ENABLE_HIP)
// if(alt == "yes" || alt == "true")
// return Hamiltonian(RealDenseHamiltonian(AFinfo,cur,std::move(H1),TG,
// NuclearCoulombEnergy,FrozenCoreEnergy));
// else
return Hamiltonian(RealDenseHamiltonian_v2(AFinfo, cur, std::move(H1), TG, NuclearCoulombEnergy, FrozenCoreEnergy));
#else
return Hamiltonian(RealDenseHamiltonian(AFinfo, cur, std::move(H1), TG, NuclearCoulombEnergy, FrozenCoreEnergy));
#endif
}
else
#endif
if (htype == THC)
{
if (coreid < nread && !dump.push("THC", false))
{
app_error() << " Error in HamiltonianFactory::fromHDF5(): Group not THC found. \n";
APP_ABORT("");
}
if (coreid < nread)
{
dump.pop();
dump.pop();
dump.close();
}
TG.global_barrier();
// THC matrices are read by THCHamiltonian object when needed, since their ownership is
// passed to the HamOps object.
return Hamiltonian(THCHamiltonian(AFinfo, cur, std::move(H1), TG, NuclearCoulombEnergy, FrozenCoreEnergy));
}
else if (htype == Factorized)
{
if (coreid < nread && !dump.push("Factorized", false))
{
app_error() << " Error in HamiltonianFactory::fromHDF5(): Group Factorized not found. \n";
APP_ABORT("");
}
if (TG.getNumberOfTGs() > 1)
APP_ABORT(" Error: Distributed Factorized hamiltonian not yet implemented. \n\n");
FactorizedSparseHamiltonian::shm_csr_matrix V2_fact =
read_V2fact(dump, TG, nread, NMO, nvecs, cutoff1bar, int_blocks);
app_log() << " Memory used by factorized 2-el integral table (on head node): "
<< (V2_fact.capacity() * (sizeof(ValueType) + sizeof(IndexType)) +
V2_fact.size(0) * (2 * sizeof(std::size_t))) /
1024.0 / 1024.0
<< " MB. " << std::endl;
if (coreid < nread)
{
dump.pop();
dump.pop();
dump.close();
}
TG.global_barrier();
return Hamiltonian(FactorizedSparseHamiltonian(AFinfo, cur, std::move(H1), std::move(V2_fact), TG,
NuclearCoulombEnergy, FrozenCoreEnergy));
}
app_error() << " Error in HamiltonianFactory::fromHDF5(): Unknown Hamiltonian Type. \n";
APP_ABORT("");
return Hamiltonian{};
}
} // namespace afqmc
} // namespace qmcplusplus
|
struct C
{
int d;
};
struct B
{
C c;
C* operator->()
{
return &c;
}
};
struct A
{
B b;
B& operator->()
{
return b;
}
};
int main()
{
A a;
a->d = 2;
assert(a.b.c.d==2);
}
|
#include <pomegranate/pomegranate.hpp>
#include "embed/shader/basic_frag_spv.hpp"
#include "embed/shader/basic_vert_spv.hpp"
#include "embed/img/empty_png.hpp"
#include <spirv_reflect.hpp>
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
struct Vertex {
pom::maths::vec3 pos;
pom::Color color;
pom::maths::vec2 uv;
};
struct UniformMVP {
pom::maths::mat4 model;
pom::maths::mat4 view;
pom::maths::mat4 projection;
};
static Vertex VERTEX_DATA[] = {
{ { -0.5f, -0.5f, 0.5f }, { 0.0f, 0.0f, 1.0f, 1.0f }, { 0.f, 0.f } },
{ { 0.5f, -0.5f, 0.5f }, { 1.0f, 0.0f, 1.0f, 1.0f }, { 1.f, 0.f } },
{ { 0.5f, 0.5f, 0.5f }, { 0.0f, 1.0f, 1.0f, 1.0f }, { 1.f, 1.f } },
{ { -0.5f, 0.5f, 0.5f }, { 0.0f, 1.0f, 0.0f, 1.0f }, { 0.f, 1.f } },
{ { -0.5f, -0.5f, -0.5f }, { 0.0f, 1.0f, 1.0f, 1.0f }, { 0.f, 0.f } },
{ { 0.5f, -0.5f, -0.5f }, { 0.0f, 1.0f, 0.0f, 1.0f }, { 1.f, 0.f } },
{ { 0.5f, 0.5f, -0.5f }, { 0.0f, 0.0f, 1.0f, 1.0f }, { 1.f, 1.f } },
{ { -0.5f, 0.5f, -0.5f }, { 1.0f, 0.0f, 1.0f, 1.0f }, { 0.f, 1.f } },
};
static const f32 SCALE_DATA[] = { 2, 1.5, 1, 0.5 };
static const u16 INDEX_DATA[]
= { 0, 1, 2, 2, 3, 0, 1, 5, 6, 6, 2, 1, 7, 6, 5, 5, 4, 7, 4, 0, 3, 3, 7, 4, 4, 5, 1, 1, 0, 4, 3, 2, 6, 6, 7, 3 };
struct GameState {
// instance
pom::Ref<pom::gfx::CommandBuffer> commandBuffer;
// vertex buffer
pom::Ref<pom::gfx::Buffer> vertexBuffers[POM_MAX_FRAMES_IN_FLIGHT];
pom::Ref<pom::gfx::Buffer> scaleBuffer;
pom::Ref<pom::gfx::Buffer> indexBuffer;
// uniform buffers
pom::maths::vec3 cameraPos = pom::maths::vec3(2, 2, 2);
pom::Ref<pom::gfx::Buffer> uniformBuffers[POM_MAX_FRAMES_IN_FLIGHT];
// pipeline
pom::Ref<pom::gfx::PipelineLayout> pipelineLayout;
pom::Ref<pom::gfx::DescriptorSet> descriptorSets[POM_MAX_FRAMES_IN_FLIGHT];
pom::Ref<pom::gfx::Pipeline> pipeline;
// other context test.
pom::Window* otherWindow;
pom::Ref<pom::gfx::CommandBuffer> otherCommandBuffer;
pom::Ref<pom::gfx::Buffer> otherVertexBuffer;
// texture
pom::Ref<pom::gfx::Texture> texture;
};
POM_CLIENT_EXPORT const pom::AppCreateInfo* clientGetAppCreateInfo(int /*argc*/, char** /*argv*/)
{
static const pom::AppCreateInfo aci = {
.name = "Pomegranate Sandbox Application",
};
return &aci;
}
POM_CLIENT_EXPORT GameState* clientCreateState()
{
auto* gc = new GameState;
return gc;
}
POM_CLIENT_EXPORT void clientUpdate(GameState* gamestate, pom::DeltaTime dt);
POM_CLIENT_EXPORT void clientBegin(GameState* gamestate)
{
auto* contextVk = dynamic_cast<pom::gfx::ContextVk*>(pom::Application::get()->getMainWindow().getContext());
gamestate->otherWindow = new pom::Window("other window", pom::gfx::GraphicsAPI::VULKAN, true);
gamestate->otherWindow->setEventHandler([gamestate](pom::InputEvent ev) {
if (ev.type == pom::InputEventType::WINDOW_RESIZE) {
clientUpdate(gamestate, {});
}
});
gamestate->otherCommandBuffer = pom::gfx::CommandBuffer::create(pom::gfx::CommandBufferSpecialization::GRAPHICS);
gamestate->otherVertexBuffer = pom::gfx::Buffer::create(pom::gfx::BufferUsage::VERTEX,
pom::gfx::BufferMemoryAccess::GPU_ONLY,
sizeof(VERTEX_DATA),
VERTEX_DATA);
// texture
i32 width, height, channels;
const unsigned char* pixels = stbi_load_from_memory(empty_png_data,
static_cast<int>(empty_png_size),
&width,
&height,
&channels,
STBI_rgb_alpha);
size_t textureSize = width * height * 4;
gamestate->texture = pom::gfx::Texture::create(
{
.type = pom::gfx::TextureType::IMAGE_2D,
.usage = pom::gfx::TextureUsage::SAMPLED | pom::gfx::TextureUsage::TRANSFER_DST,
.textureFormat = pom::gfx::Format::R8G8B8A8_SRGB,
.viewFormat = pom::gfx::Format::R8G8B8A8_SRGB,
},
width,
height,
1,
pixels,
0,
textureSize);
// pipeline
spirv_cross::CompilerReflection vertShaderModuleReflection(reinterpret_cast<const u32*>(basic_vert_spv_data),
basic_vert_spv_size / sizeof(u32));
spirv_cross::ShaderResources vertShaderResources = vertShaderModuleReflection.get_shader_resources();
auto inputs = vertShaderResources.stage_inputs;
for (auto& input : inputs) {
u32 set = vertShaderModuleReflection.get_decoration(input.id, spv::DecorationDescriptorSet);
u32 location = vertShaderModuleReflection.get_decoration(input.id, spv::DecorationLocation);
u32 offset = vertShaderModuleReflection.get_decoration(input.id, spv::DecorationOffset);
POM_DEBUG("vertex attribute: ", input.name, ", ", set, ", ", location, ", ", offset);
}
pom::Ref<pom::gfx::ShaderModule> vertShader
= pom::gfx::ShaderModule::create(pom::gfx::ShaderStage::VERTEX,
basic_vert_spv_size,
reinterpret_cast<const u32*>(basic_vert_spv_data));
pom::Ref<pom::gfx::ShaderModule> fragShader
= pom::gfx::ShaderModule::create(pom::gfx::ShaderStage::FRAGMENT,
basic_frag_spv_size,
reinterpret_cast<const u32*>(basic_frag_spv_data));
pom::Ref<pom::gfx::Shader> shader = pom::gfx::Shader::create({ vertShader, fragShader });
gamestate->pipelineLayout = pom::gfx::PipelineLayout::create({
{
.type = pom::gfx::DescriptorType::UNIFORM_BUFFER,
.set = 0,
.binding = 0,
.stages = pom::gfx::ShaderStageFlags::VERTEX,
},
{
.type = pom::gfx::DescriptorType::COMBINED_TEXTURE_SAMPLER,
.set = 0,
.binding = 1,
.stages = pom::gfx::ShaderStageFlags::FRAGMENT,
},
});
// descriptor set
for (u32 i = 0; i < POM_MAX_FRAMES_IN_FLIGHT; i++) {
gamestate->uniformBuffers[i] = pom::gfx::Buffer::create(pom::gfx::BufferUsage::UNIFORM,
pom::gfx::BufferMemoryAccess::CPU_WRITE,
sizeof(UniformMVP));
gamestate->descriptorSets[i] = pom::gfx::DescriptorSet::create(gamestate->pipelineLayout, 0);
gamestate->descriptorSets[i]->setBuffer(0, gamestate->uniformBuffers[i]);
gamestate->descriptorSets[i]->setTexture(1, gamestate->texture);
}
gamestate->pipeline = pom::gfx::Pipeline::create(
{},
shader,
contextVk->getSwapchainRenderPass(),
{ {
.binding = 0,
.attribs = { { .location = 0, .format = pom::gfx::Format::R32G32B32_SFLOAT },
{ .location = 1, .format = pom::gfx::Format::R32G32B32A32_SFLOAT },
{ .location = 2, .format = pom::gfx::Format::R32G32_SFLOAT } },
},
{
.binding = 1,
.attribs = { { .location = 3, .format = pom::gfx::Format::R32_SFLOAT } },
} },
gamestate->pipelineLayout);
// command buffer
gamestate->commandBuffer = pom::gfx::CommandBuffer::create(pom::gfx::CommandBufferSpecialization::GRAPHICS);
// vertex buffer
for (auto& vertexBuffer : gamestate->vertexBuffers) {
vertexBuffer = pom::gfx::Buffer::create(pom::gfx::BufferUsage::VERTEX,
pom::gfx::BufferMemoryAccess::CPU_WRITE,
sizeof(VERTEX_DATA));
}
gamestate->scaleBuffer = pom::gfx::Buffer::create(pom::gfx::BufferUsage::VERTEX,
pom::gfx::BufferMemoryAccess::GPU_ONLY,
sizeof(SCALE_DATA),
SCALE_DATA);
// index buffer
gamestate->indexBuffer = pom::gfx::Buffer::create(pom::gfx::BufferUsage::INDEX,
pom::gfx::BufferMemoryAccess::GPU_ONLY,
sizeof(INDEX_DATA),
INDEX_DATA);
}
POM_CLIENT_EXPORT void clientMount(GameState* gamestate)
{
}
POM_CLIENT_EXPORT void clientUpdate(GameState* gamestate, pom::DeltaTime dt)
{
auto frame = pom::Application::get()->getFrame();
POM_PROFILE_SCOPE("update");
{
if (!pom::Application::get()->getMainWindow().isMinimized()) {
auto* context = dynamic_cast<pom::gfx::ContextVk*>(pom::Application::get()->getMainWindow().getContext());
pom::Ref<pom::gfx::Buffer> vertexBuffer = gamestate->vertexBuffers[frame % POM_MAX_FRAMES_IN_FLIGHT];
{
// Vertex* data = (Vertex*)vertexBuffer->map();
// memcpy(data, VERTEX_DATA, sizeof(VERTEX_DATA));
// pom::maths::mat3 m = pom::maths::mat3::rotate({ (f32)(TAU / 100.f * (f32)frame) });
// for (u8 i = 0; i < 4; i++) {
// data[i].pos = m * VERTEX_DATA[i].pos;
// }
// vertexBuffer->unmap();
}
const f32 cameraSpeed = 0.01f;
if (pom::keyDown(pom::KeyHid::KEY_W)) {
gamestate->cameraPos.y += cameraSpeed * dt;
} else if (pom::keyDown(pom::KeyHid::KEY_S)) {
gamestate->cameraPos.y -= cameraSpeed * dt;
}
if (pom::keyDown(pom::KeyHid::KEY_D)) {
gamestate->cameraPos.x += cameraSpeed * dt;
} else if (pom::keyDown(pom::KeyHid::KEY_A)) {
gamestate->cameraPos.x -= cameraSpeed * dt;
}
if (pom::keyDown(pom::KeyHid::KEY_Q)) {
gamestate->cameraPos.z += cameraSpeed * dt;
} else if (pom::keyDown(pom::KeyHid::KEY_E)) {
gamestate->cameraPos.z -= cameraSpeed * dt;
}
{
pom::Ref<pom::gfx::Buffer> uniformBuffer = gamestate->uniformBuffers[frame % POM_MAX_FRAMES_IN_FLIGHT];
UniformMVP* data = (UniformMVP*)uniformBuffer->map();
data->model = pom::maths::mat4::rotate({ TAU / 100.f * 0, 0, 0 });
data->projection = pom::maths::mat4::perspective(TAU / 8.f,
context->swapchainViewport.width
/ context->swapchainViewport.height,
0.01f,
1000.f);
data->view = pom::maths::mat4::lookAt(gamestate->cameraPos,
pom::maths::vec3(0.f, 0.f, 0.f),
pom::maths::vec3(0.f, 0.f, 1.f));
uniformBuffer->unmap();
}
gamestate->commandBuffer->begin();
gamestate->commandBuffer->beginRenderPass(context->getSwapchainRenderPass(), context);
gamestate->commandBuffer->setViewport(context->getSwapchainViewport());
gamestate->commandBuffer->setScissor({ 0, 0 },
{ context->swapchainExtent.width, context->swapchainExtent.height });
gamestate->commandBuffer->bindVertexBuffer(gamestate->otherVertexBuffer);
gamestate->commandBuffer->bindVertexBuffer(gamestate->scaleBuffer, 1);
gamestate->commandBuffer->bindIndexBuffer(gamestate->indexBuffer, pom::gfx::IndexType::U16);
gamestate->commandBuffer->bindPipeline(gamestate->pipeline);
gamestate->commandBuffer->bindDescriptorSet(gamestate->pipelineLayout,
0,
gamestate->descriptorSets[frame % POM_MAX_FRAMES_IN_FLIGHT]);
gamestate->commandBuffer->drawIndexed(gamestate->indexBuffer->getSize() / sizeof(u16));
gamestate->commandBuffer->endRenderPass();
gamestate->commandBuffer->end();
gamestate->commandBuffer->submit();
pom::Application::get()->getMainWindow().getContext()->present();
}
}
if (!gamestate->otherWindow->isMinimized()) {
auto* ctx = dynamic_cast<pom::gfx::ContextVk*>(gamestate->otherWindow->getContext());
gamestate->otherCommandBuffer->begin();
gamestate->otherCommandBuffer->beginRenderPass(ctx->getSwapchainRenderPass(), ctx);
gamestate->otherCommandBuffer->setViewport(ctx->getSwapchainViewport());
gamestate->otherCommandBuffer->setScissor({ 0, 0 },
{ ctx->swapchainExtent.width, ctx->swapchainExtent.height });
gamestate->otherCommandBuffer->bindVertexBuffer(gamestate->otherVertexBuffer);
gamestate->otherCommandBuffer->bindVertexBuffer(gamestate->scaleBuffer, 1);
gamestate->otherCommandBuffer->bindIndexBuffer(gamestate->indexBuffer, pom::gfx::IndexType::U16);
gamestate->otherCommandBuffer->bindPipeline(gamestate->pipeline);
gamestate->otherCommandBuffer->bindDescriptorSet(gamestate->pipelineLayout,
0,
gamestate->descriptorSets[frame % POM_MAX_FRAMES_IN_FLIGHT]);
gamestate->otherCommandBuffer->drawIndexed(gamestate->indexBuffer->getSize() / sizeof(u16));
gamestate->otherCommandBuffer->endRenderPass();
gamestate->otherCommandBuffer->end();
gamestate->otherCommandBuffer->submit();
ctx->present();
}
// POM_DEBUG("dt: ", dt, "ms");
}
POM_CLIENT_EXPORT void clientOnInputEvent(GameState* gamestate, pom::InputEvent* ev)
{
}
POM_CLIENT_EXPORT void clientUnmount(GameState* gamestate)
{
}
POM_CLIENT_EXPORT void clientEnd(GameState* gamestate)
{
delete gamestate->otherWindow;
delete gamestate;
}
|
#include <okiidoku/puzzle/ua_set.hpp>
#include <okiidoku/detail/contract.hpp>
#include <array>
#include <okiidoku/puzzle/solver/cand_elim_find.macros.hpp>
namespace okiidoku::mono { namespace {
// outer dimension for lines of chute.
// inner dimension maps syms to house-cells.
template<Order O> requires(is_order_compiled(O))
using chute_lines_sym_to_cell_t = std::array<
std::array<int_ts::o2xs_t<O>, Ints<O>::O2>,
Ints<O>::O1
>;
template<Order O> requires(is_order_compiled(O))
void find_size_4_minimal_unavoidable_sets_in_chute(
const Grid<O>& soln_grid,
MinimalUnavoidableSets<O>& found,
const LineType line_type,
const int_ts::o1i_t<O> chute
) noexcept {
OKIIDOKU_CAND_ELIM_FINDER_TYPEDEFS
OKIIDOKU_CONTRACT_TRIVIAL_EVAL(chute < T::O1);
const auto chute_lines_sym_to_cell {[&](){
chute_lines_sym_to_cell_t<O> map;
for (o1i_t chute_line {0}; chute_line < T::O1; ++chute_line) {
for (o2i_t house_cell {0}; house_cell < T::O2; ++house_cell) {
const auto chute_cell_i {static_cast<o3i_t>((T::O2*chute_line)+house_cell)};
OKIIDOKU_CONTRACT_TRIVIAL_EVAL(chute_cell_i < T::O3);
const auto rmi {chute_cell_to_rmi<O>(line_type, chute, chute_cell_i)};
const auto& sym {soln_grid.at_rmi(rmi)};
OKIIDOKU_CONTRACT_TRIVIAL_EVAL(sym < T::O2);
map[chute_line][sym] = static_cast<o2xs_t>(house_cell);
}}
return map;
}()};
for (o1i_t chute_line_a {0}; chute_line_a < T::O1; ++chute_line_a) {
for (o1i_t chute_line_b {0}; chute_line_b < T::O1; ++chute_line_b) {
for (o2i_t slice_c {0}; slice_c < T::O2; ++slice_c) {
const auto c_a_rmi {chute_cell_to_rmi<O>(line_type, chute, static_cast<o3i_t>((T::O2*chute_line_a)+slice_c))};
const auto c_b_rmi {chute_cell_to_rmi<O>(line_type, chute, static_cast<o3i_t>((T::O2*chute_line_b)+slice_c))};
const auto& c_a_sym {soln_grid.at_rmi(c_a_rmi)}; OKIIDOKU_CONTRACT_TRIVIAL_EVAL(c_a_sym < T::O2);
const auto& c_b_sym {soln_grid.at_rmi(c_b_rmi)}; OKIIDOKU_CONTRACT_TRIVIAL_EVAL(c_b_sym < T::O2);
const auto& d_a_cell {chute_lines_sym_to_cell[chute_line_a][c_b_sym]};
const auto& d_b_cell {chute_lines_sym_to_cell[chute_line_b][c_a_sym]};
if ((d_a_cell == d_b_cell) && (d_a_cell > slice_c)) [[unlikely]] {
found.ua_set_4s.emplace_back(UaSet4<O>{
static_cast<rmi_t>(c_a_rmi),
static_cast<rmi_t>(c_b_rmi),
static_cast<rmi_t>(chute_cell_to_rmi<O>(line_type, chute, static_cast<o3i_t>((T::O2*chute_line_a)+d_a_cell))),
static_cast<rmi_t>(chute_cell_to_rmi<O>(line_type, chute, static_cast<o3i_t>((T::O2*chute_line_b)+d_b_cell))),
});
}
}
}}
}
}}
namespace okiidoku::mono {
template<Order O> requires(is_order_compiled(O))
MinimalUnavoidableSets<O> find_size_4_minimal_unavoidable_sets(const Grid<O>& soln_grid) noexcept {
OKIIDOKU_CAND_ELIM_FINDER_TYPEDEFS
MinimalUnavoidableSets<O> found; // TODO actually populate with found UA sets.
for (const auto line_type : line_types) {
for (o1i_t chute {0}; chute < T::O1; ++chute) {
find_size_4_minimal_unavoidable_sets_in_chute(
soln_grid, found, line_type, chute
);
}
}
return found;
}
#define OKIIDOKU_FOR_COMPILED_O(O_) \
template MinimalUnavoidableSets<O_> find_size_4_minimal_unavoidable_sets<O_>(const Grid<O_>&) noexcept;
OKIIDOKU_INSTANTIATE_ORDER_TEMPLATES
#undef OKIIDOKU_FOR_COMPILED_O
}
|
#pragma once
#include <array>
#include <optional>
namespace ruckig {
using Limits = Profile::Limits;
using JerkSigns = Profile::JerkSigns;
//! Mathematical equations for Step 1 in position interface: Extremal profiles
class PositionStep1 {
double p0, v0, a0;
double pf, vf, af;
double _vMax, _vMin, _aMax, _aMin, _jMax;
// Pre-calculated expressions
double pd;
double v0_v0, vf_vf;
double a0_a0, a0_p3, a0_p4, a0_p5, a0_p6;
double af_af, af_p3, af_p4, af_p5, af_p6;
double jMax_jMax;
// Only a single velocity-limited profile can be valid
bool has_up_vel {false}, has_down_vel {false};
// Max 5 valid profiles + 1 spare for numerical issues
std::array<Profile, 6> valid_profiles;
size_t valid_profile_counter;
void time_acc0_acc1_vel(Profile& profile, double vMax, double aMax, double aMin, double jMax);
void time_acc1_vel(Profile& profile, double vMax, double aMax, double aMin, double jMax);
void time_acc0_vel(Profile& profile, double vMax, double aMax, double aMin, double jMax);
void time_vel(Profile& profile, double vMax, double aMax, double aMin, double jMax);
void time_acc0_acc1(Profile& profile, double vMax, double aMax, double aMin, double jMax);
void time_acc1(Profile& profile, double vMax, double aMax, double aMin, double jMax);
void time_acc0(Profile& profile, double vMax, double aMax, double aMin, double jMax);
void time_none(Profile& profile, double vMax, double aMax, double aMin, double jMax);
// Only for numerical issues
void time_acc0_two_step(Profile& profile, double vMax, double aMax, double aMin, double jMax);
void time_vel_two_step(Profile& profile, double vMax, double aMax, double aMin, double jMax);
void time_none_two_step(Profile& profile, double vMax, double aMax, double aMin, double jMax);
inline void add_profile(Profile profile, double jMax) {
profile.direction = (jMax > 0) ? Profile::Direction::UP : Profile::Direction::DOWN;
if (profile.limits == Limits::ACC0_ACC1_VEL || profile.limits == Limits::ACC0_VEL || profile.limits == Limits::ACC1_VEL || profile.limits == Limits::VEL) {
switch (profile.direction) {
case Profile::Direction::UP: has_up_vel = true; break;
case Profile::Direction::DOWN: has_down_vel = true; break;
}
}
valid_profiles[valid_profile_counter] = profile;
++valid_profile_counter;
}
public:
explicit PositionStep1(double p0, double v0, double a0, double pf, double vf, double af, double vMax, double vMin, double aMax, double aMin, double jMax);
bool get_profile(const Profile& input, Block& block);
};
//! Mathematical equations for Step 2 in position interface: Time synchronization
class PositionStep2 {
double p0, v0, a0;
double tf, pf, vf, af;
double _vMax, _vMin, _aMax, _aMin, _jMax;
// Pre-calculated expressions
double pd;
double tf_tf, tf_p3, tf_p4;
double vd, vd_vd;
double ad, ad_ad;
double v0_v0, vf_vf;
double a0_a0, a0_p3, a0_p4, a0_p5, a0_p6;
double af_af, af_p3, af_p4, af_p5, af_p6;
double jMax_jMax;
double g1, g2;
bool time_acc0_acc1_vel(Profile& profile, double vMax, double aMax, double aMin, double jMax);
bool time_acc1_vel(Profile& profile, double vMax, double aMax, double aMin, double jMax);
bool time_acc0_vel(Profile& profile, double vMax, double aMax, double aMin, double jMax);
bool time_vel(Profile& profile, double vMax, double aMax, double aMin, double jMax);
bool time_acc0_acc1(Profile& profile, double vMax, double aMax, double aMin, double jMax);
bool time_acc1(Profile& profile, double vMax, double aMax, double aMin, double jMax);
bool time_acc0(Profile& profile, double vMax, double aMax, double aMin, double jMax);
bool time_none(Profile& profile, double vMax, double aMax, double aMin, double jMax);
inline bool check_all(Profile& profile, double vMax, double aMax, double aMin, double jMax) {
return time_acc0_acc1_vel(profile, vMax, aMax, aMin, jMax)
|| time_acc0_vel(profile, vMax, aMax, aMin, jMax)
|| time_acc1_vel(profile, vMax, aMax, aMin, jMax)
|| time_vel(profile, vMax, aMax, aMin, jMax)
|| time_acc0(profile, vMax, aMax, aMin, jMax)
|| time_acc1(profile, vMax, aMax, aMin, jMax)
|| time_acc0_acc1(profile, vMax, aMax, aMin, jMax)
|| time_none(profile, vMax, aMax, aMin, jMax);
}
public:
explicit PositionStep2(double tf, double p0, double v0, double a0, double pf, double vf, double af, double vMax, double vMin, double aMax, double aMin, double jMax);
bool get_profile(Profile& profile);
};
} // namespace ruckig
|
/* -*- mode: C++ ; c-file-style: "stroustrup" -*- *****************************
* Qwt Widget Library
* Copyright (C) 1997 Josef Wilgen
* Copyright (C) 2002 Uwe Rathmann
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the Qwt License, Version 1.0
*****************************************************************************/
#include "qwt_text_label.h"
#include "qwt_text.h"
#include "qwt_painter.h"
#include <qpainter.h>
#include <qevent.h>
#include <qmath.h>
class QwtTextLabel::PrivateData
{
public:
PrivateData():
indent( 4 ),
margin( 0 )
{
}
int indent;
int margin;
QwtText text;
};
/*!
Constructs an empty label.
\param parent Parent widget
*/
QwtTextLabel::QwtTextLabel( QWidget *parent ):
QFrame( parent )
{
init();
}
/*!
Constructs a label that displays the text, text
\param parent Parent widget
\param text Text
*/
QwtTextLabel::QwtTextLabel( const QwtText &text, QWidget *parent ):
QFrame( parent )
{
init();
d_data->text = text;
}
//! Destructor
QwtTextLabel::~QwtTextLabel()
{
delete d_data;
}
void QwtTextLabel::init()
{
d_data = new PrivateData();
setSizePolicy( QSizePolicy::Preferred, QSizePolicy::Preferred );
}
/*!
Interface for the designer plugin - does the same as setText()
\sa plainText()
*/
void QwtTextLabel::setPlainText( const QString &text )
{
setText( QwtText( text ) );
}
/*!
Interface for the designer plugin
\return Text as plain text
\sa setPlainText(), text()
*/
QString QwtTextLabel::plainText() const
{
return d_data->text.text();
}
/*!
Change the label's text, keeping all other QwtText attributes
\param text New text
\param textFormat Format of text
\sa QwtText
*/
void QwtTextLabel::setText( const QString &text,
QwtText::TextFormat textFormat )
{
d_data->text.setText( text, textFormat );
update();
updateGeometry();
}
/*!
Change the label's text
\param text New text
*/
void QwtTextLabel::setText( const QwtText &text )
{
d_data->text = text;
update();
updateGeometry();
}
//! Return the text
const QwtText &QwtTextLabel::text() const
{
return d_data->text;
}
//! Clear the text and all QwtText attributes
void QwtTextLabel::clear()
{
d_data->text = QwtText();
update();
updateGeometry();
}
//! Return label's text indent in pixels
int QwtTextLabel::indent() const
{
return d_data->indent;
}
/*!
Set label's text indent in pixels
\param indent Indentation in pixels
*/
void QwtTextLabel::setIndent( int indent )
{
if ( indent < 0 )
indent = 0;
d_data->indent = indent;
update();
updateGeometry();
}
//! Return label's text margin in pixels
int QwtTextLabel::margin() const
{
return d_data->margin;
}
/*!
Set label's margin in pixels
\param margin Margin in pixels
*/
void QwtTextLabel::setMargin( int margin )
{
d_data->margin = margin;
update();
updateGeometry();
}
//! Return a size hint
QSize QwtTextLabel::sizeHint() const
{
return minimumSizeHint();
}
//! Return a minimum size hint
QSize QwtTextLabel::minimumSizeHint() const
{
QSizeF sz = d_data->text.textSize( font() );
int mw = 2 * ( frameWidth() + d_data->margin );
int mh = mw;
int indent = d_data->indent;
if ( indent <= 0 )
indent = defaultIndent();
if ( indent > 0 )
{
const int align = d_data->text.renderFlags();
if ( align & Qt::AlignLeft || align & Qt::AlignRight )
mw += d_data->indent;
else if ( align & Qt::AlignTop || align & Qt::AlignBottom )
mh += d_data->indent;
}
sz += QSizeF( mw, mh );
return QSize( qCeil( sz.width() ), qCeil( sz.height() ) );
}
/*!
\param width Width
\return Preferred height for this widget, given the width.
*/
int QwtTextLabel::heightForWidth( int width ) const
{
const int renderFlags = d_data->text.renderFlags();
int indent = d_data->indent;
if ( indent <= 0 )
indent = defaultIndent();
width -= 2 * frameWidth();
if ( renderFlags & Qt::AlignLeft || renderFlags & Qt::AlignRight )
width -= indent;
int height = qCeil( d_data->text.heightForWidth( width, font() ) );
if ( ( renderFlags & Qt::AlignTop ) || ( renderFlags & Qt::AlignBottom ) )
height += indent;
height += 2 * frameWidth();
return height;
}
/*!
Qt paint event
\param event Paint event
*/
void QwtTextLabel::paintEvent( QPaintEvent *event )
{
QPainter painter( this );
if ( !contentsRect().contains( event->rect() ) )
{
painter.save();
painter.setClipRegion( event->region() & frameRect() );
drawFrame( &painter );
painter.restore();
}
painter.setClipRegion( event->region() & contentsRect() );
drawContents( &painter );
}
//! Redraw the text and focus indicator
void QwtTextLabel::drawContents( QPainter *painter )
{
const QRect r = textRect();
if ( r.isEmpty() )
return;
painter->setFont( font() );
painter->setPen( palette().color( QPalette::Active, QPalette::Text ) );
drawText( painter, QRectF( r ) );
if ( hasFocus() )
{
const int m = 2;
QRect focusRect = contentsRect().adjusted( m, m, -m + 1, -m + 1);
QwtPainter::drawFocusRect( painter, this, focusRect );
}
}
//! Redraw the text
void QwtTextLabel::drawText( QPainter *painter, const QRectF &textRect )
{
d_data->text.draw( painter, textRect );
}
/*!
Calculate geometry for the text in widget coordinates
\return Geometry for the text
*/
QRect QwtTextLabel::textRect() const
{
QRect r = contentsRect();
if ( !r.isEmpty() && d_data->margin > 0 )
{
r.setRect( r.x() + d_data->margin, r.y() + d_data->margin,
r.width() - 2 * d_data->margin, r.height() - 2 * d_data->margin );
}
if ( !r.isEmpty() )
{
int indent = d_data->indent;
if ( indent <= 0 )
indent = defaultIndent();
if ( indent > 0 )
{
const int renderFlags = d_data->text.renderFlags();
if ( renderFlags & Qt::AlignLeft )
r.setX( r.x() + indent );
else if ( renderFlags & Qt::AlignRight )
r.setWidth( r.width() - indent );
else if ( renderFlags & Qt::AlignTop )
r.setY( r.y() + indent );
else if ( renderFlags & Qt::AlignBottom )
r.setHeight( r.height() - indent );
}
}
return r;
}
int QwtTextLabel::defaultIndent() const
{
if ( frameWidth() <= 0 )
return 0;
QFont fnt;
if ( d_data->text.testPaintAttribute( QwtText::PaintUsingTextFont ) )
fnt = d_data->text.font();
else
fnt = font();
return QFontMetrics( fnt ).width( 'x' ) / 2;
}
|
/*
Title:
322. Coin Change
322. 零钱兑换
Description:
给定不同面额的硬币 coins 和一个总金额 amount。编写一个函数来计算可以凑成总金额所需的最少的硬币个数。
如果没有任何一种硬币组合能组成总金额,返回 -1。
说明:
你可以认为每种硬币的数量是无限的。
测试用例:
输入: coins = [1, 2, 5], amount = 11
输出: 3
解释: 11 = 5 + 5 + 1
Address:
https://leetcode-cn.com/problems/coin-change/
*/
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
// 方法三:动态规划 - 自上而下
// https://leetcode-cn.com/problems/coin-change/solution/322-ling-qian-dui-huan-by-leetcode-solution/
// 方法一:动态规划 - 自下而上
// 【完全背包】
// https://leetcode-cn.com/problems/coin-change/solution/322-ling-qian-dui-huan-by-leetcode-solution/
class Solution {
public:
int coinChange(vector<int>& coins, int amount) {
// 极端情况下, 最多需要 amount 个硬币,即:amount 个 1 元硬币
// 申请一个长度为 amount + 1 的数组,其元素填充为 amount + 1
// 此时, dp[amount + 1] == amount + 1, 即: 没有任何一种硬币组合能组成总金额
vector<int> dp( amount + 1, amount + 1 );
dp[0] = 0; // 置零
for ( int i = 1; i <= amount; ++i ) { // i : 当前金额
for ( int coin : coins ) { // coin : 当前硬币面值
if ( coin <= i ) {
// 初始时, dp[i] == amount + 1, 表示最坏情况
dp[i] = min( dp[i], dp[i - coin] + 1 );
}
}
}
return ( dp[amount] == amount + 1 ) ? -1 : dp[amount];
}
};
// 方法二:贪心 + DFS剪枝
// https://leetcode-cn.com/problems/coin-change/solution/322-by-ikaruga/
class Solution_2 {
public:
int coinChange(vector<int>& coins, int amount){
if (amount == 0)
return 0;
sort(coins.rbegin(), coins.rend()); // 降序排列
int ans = INT_MAX;
dfs(coins, amount, 0, 0, ans);
return ans == INT_MAX ? -1 : ans;
}
void dfs(vector<int>& coins, int amount, int c_index, int count, int& ans){
if (amount == 0) {
ans = min(ans, count);
return;
}
if (c_index == (int)coins.size())
return;
for (int k = amount / coins[c_index]; k >= 0 && k + count < ans; k--)
dfs(coins, amount - k * coins[c_index], c_index + 1, count + k, ans);
}
};
int main()
{
return 0;
}
|
/*=========================================================================
Program: Visualization Toolkit
Module: vtkPolyDataGeodesicDistance.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
/*=========================================================================
Copyright (c) 2013 Karthik Krishnan.
Contributed to the VisualizationToolkit by the author under the terms
of the Visualization Toolkit copyright
=========================================================================*/
#include "vtkPolyDataGeodesicDistance.h"
#include "vtkExecutive.h"
#include "vtkFieldData.h"
#include "vtkFloatArray.h"
#include "vtkIdList.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
#include "vtkPolyData.h"
vtkCxxSetObjectMacro(vtkPolyDataGeodesicDistance, Seeds, vtkIdList);
//-----------------------------------------------------------------------------
vtkPolyDataGeodesicDistance::vtkPolyDataGeodesicDistance()
{
this->SetNumberOfInputPorts(1);
this->FieldDataName = nullptr;
this->Seeds = nullptr;
}
//-----------------------------------------------------------------------------
vtkPolyDataGeodesicDistance::~vtkPolyDataGeodesicDistance()
{
this->SetFieldDataName(nullptr);
this->SetSeeds(nullptr);
}
//-----------------------------------------------------------------------------
vtkFloatArray* vtkPolyDataGeodesicDistance::GetGeodesicDistanceField(vtkPolyData* pd)
{
if (this->FieldDataName == nullptr)
{
return nullptr;
}
vtkDataArray* arr = pd->GetPointData()->GetArray(this->FieldDataName);
if (vtkFloatArray* farr = vtkFloatArray::SafeDownCast(arr))
{
// Resize the existing one
farr->SetNumberOfValues(pd->GetNumberOfPoints());
if (!pd->GetPointData()->GetScalars())
{
pd->GetPointData()->SetScalars(farr);
}
return farr;
}
else if (!arr)
{
// Create a new one
vtkFloatArray* farray = vtkFloatArray::New();
farray->SetName(this->FieldDataName);
farray->SetNumberOfValues(pd->GetNumberOfPoints());
pd->GetPointData()->AddArray(farray);
farray->Delete();
if (!pd->GetPointData()->GetScalars())
{
pd->GetPointData()->SetScalars(farray);
}
return vtkFloatArray::SafeDownCast(pd->GetPointData()->GetArray(this->FieldDataName));
}
else
{
vtkErrorMacro(
<< "A array with a different datatype already exists with the same name on this polydata");
}
return nullptr;
}
//-----------------------------------------------------------------------------
int vtkPolyDataGeodesicDistance::Compute()
{
if (!this->Seeds || !this->Seeds->GetNumberOfIds())
{
vtkErrorMacro(<< "Please supply at least one seed.");
return 0;
}
return 1;
}
//----------------------------------------------------------------------------
vtkMTimeType vtkPolyDataGeodesicDistance::GetMTime()
{
vtkMTimeType mTime = this->Superclass::GetMTime(), time;
if (this->Seeds)
{
time = this->Seeds->GetMTime();
mTime = (time > mTime ? time : mTime);
}
return mTime;
}
//-----------------------------------------------------------------------------
void vtkPolyDataGeodesicDistance::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
if (this->Seeds)
{
os << indent << "Seeds: " << this->Seeds << endl;
this->Seeds->PrintSelf(os, indent.GetNextIndent());
}
os << indent << "FieldDataName: " << (this->FieldDataName ? this->FieldDataName : "None") << endl;
}
|
//
// Sphere.hpp
// src
//
// Created by David María Arribas on 3/10/17.
// Copyright © 2017 David María Arribas. All rights reserved.
//
#ifndef Sphere_hpp
#define Sphere_hpp
#include <stdio.h>
#include "BasePrimitive.hpp"
class Sphere : public BasePrimitive {
float radius = 0.0f;
public:
Sphere();
Sphere(float radius, Vertex3D position, Vertex3D velocity, Color color);
Sphere(const Sphere &sphere);
Sphere* clone();
void render();
void update(float dt);
BoundingBox calculateBoundingBox();
// Setters y getters
void setRadius(float radius);
float getRadius();
};
#endif /* Sphere_hpp */
|
//
// Created by furture on 2018/8/25.
//
#include <render/core/parser/StyleUpdater.h>
#include <render/core/rendering/RenderParagraph.h>
#include "SpanView.h"
namespace weexuikit {
SpanView::SpanView(UIContext *context, Node *node) : View(context, node) {
}
blink::RenderObject* SpanView::createRenderObject(blink::RenderObject *parent, RefPtr<blink::RenderStyle> renderStyle) {
if(parent->isRenderParagraph() || parent->isRenderInline()){
WTF::String string = getRenderText();
renderText = new blink::RenderText(string.impl());
RefPtr<blink::RenderStyle> textStyle = StyleUpdater::createRenderStyle(renderStyle, mNode->styles());
renderText->setStyle(textStyle);
renderText->setNode(mNode);
blink::RenderInline* renderInline = new blink::RenderInline();
renderInline->setStyle(renderStyle);
renderInline->addChild(renderText);
mRenderContainer = renderInline;
return renderInline;
}else{
WTF::String string = getRenderText();
RefPtr<blink::RenderStyle> textStyle = StyleUpdater::createRenderStyle(renderStyle, mNode->styles());
renderText = new blink::RenderText(string.impl());
renderText->setStyle(textStyle);
renderText->setNode(mNode);
renderText->setNeedsLayoutAndPrefWidthsRecalc();
blink::RenderParagraph* paragraph = new blink::RenderParagraph();
paragraph->setStyle(renderStyle);
paragraph->addChild(renderText);
paragraph->setNeedsLayoutAndPrefWidthsRecalc();
mRenderContainer = paragraph;
return paragraph;
}
}
void SpanView::updateAttr(const std::string& key, const std::string& value) {
if(Html::Attr::ATTR_VALUE == key || Html::Attr::ATTR_SPACE_RID_ONE == key){
WTF::String string = getRenderText();
renderText->setText(string.impl());
renderText->setNeedsLayoutAndPrefWidthsRecalc();
mRenderObject->setNeedsLayoutAndPrefWidthsRecalc();
markParentNeedLayout(mRenderObject);
return;
}
View::updateAttr(key, value);
}
void SpanView::updateStyles(std::map<std::string, std::string> *styles) {
View::updateStyles(styles);
RefPtr<blink::RenderStyle> renderStyle = StyleUpdater::newRenderStyleUpdates(renderText->style(), styles);
renderText->setStyle(renderStyle);
renderText->setNeedsLayoutAndPrefWidthsRecalc();
markParentNeedLayout(mRenderObject);
}
WTF::String SpanView::getRenderText() {
std::string cstring = getText();
const char* text = cstring.c_str();
int length = cstring.length();
WTF::String string = WTF::String::fromUTF8(text, length);
if(isSpaceRidOne()){//rid space two to one
string.replace(" ", " ");
}
return string;
}
const std::string SpanView::getText() {
if(mNode->attrs() != nullptr){
std::map<std::string, std::string>::iterator it = mNode->attrs()->find(Html::Attr::ATTR_VALUE);
if(it != mNode->attrs()->end()){
return it->second;
}
}
return "";
}
bool SpanView::isSpaceRidOne(){
if(mNode->attrs() != nullptr) {
std::map<std::string, std::string>::iterator it = mNode->attrs()->find(Html::Attr::ATTR_SPACE_RID_ONE);
if (it != mNode->attrs()->end()) {
return it->second == Html::Attr::Value::ATTR_VALUE_TRUE;
}
}
return false;
}
}
|
/*
Copyright 2017-2019 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "lullaby/modules/input_processor/touchscreen_gestures.h"
#include "lullaby/modules/input/input_focus.h"
#include "lullaby/modules/input_processor/gesture.h"
namespace lull {
namespace {
const float kInchesToCM = 2.54f;
const float kDragDeltaCM = 0.1f * kInchesToCM;
const float kDragDeltaSquared = kDragDeltaCM * kDragDeltaCM;
const float kTwistThreshold = 5.0f * kDegreesToRadians;
const float kPinchDirectionTheshold = cosf(30.f * kDegreesToRadians);
const float kPinchDelta = 0.05f * kInchesToCM;
float CalculateDeltaRotation(mathfu::vec2 current_position1,
mathfu::vec2 current_position2,
mathfu::vec2 previous_position1,
mathfu::vec2 previous_position2) {
const mathfu::vec2 current_direction =
(current_position1 - current_position2).Normalized();
const mathfu::vec2 previous_direction =
(previous_position1 - previous_position2).Normalized();
const float sign = (previous_direction.x * current_direction.y -
previous_direction.y * current_direction.x) > 0
? 1
: -1;
return mathfu::vec2::Angle(current_direction, previous_direction) * sign;
}
} // namespace
GesturePtr OneFingerDragRecognizer::TryStart(InputManager::DeviceType device,
InputManager::TouchpadId touchpad,
Gesture::TouchIdSpan ids) {
// If the touch is already owned, ignore it.
if (input_processor_->GetTouchOwner(device, touchpad, ids[0]) != nullptr) {
return nullptr;
}
const mathfu::vec2 start_pos =
touchpad_size_cm_ *
input_manager_->GetTouchGestureOrigin(device, touchpad, ids[0]);
const mathfu::vec2 cur_pos =
touchpad_size_cm_ *
input_manager_->GetTouchLocation(device, touchpad, ids[0]);
const mathfu::vec2 delta_cm = (start_pos - cur_pos);
DCHECK(start_pos != InputManager::kInvalidTouchLocation);
DCHECK(cur_pos != InputManager::kInvalidTouchLocation);
if (delta_cm.LengthSquared() >= kDragDeltaSquared) {
return std::make_shared<OneFingerDrag>(callback_);
}
return nullptr;
}
Gesture::State OneFingerDragRecognizer::OneFingerDrag::AdvanceFrame(
const Clock::duration& delta_time) {
if (state_ == kCanceled) {
// Callback should revert changes.
callback_(state_, target_, InputManager::kInvalidTouchLocation);
return state_;
}
if (!input_manager_->IsValidTouch(device_, touchpad_, ids_[0])) {
// Touch has been released, so end the gesture.
state_ = kEnding;
// Set state before the callback, since this will be the last call.
callback_(state_, target_, InputManager::kInvalidTouchLocation);
return state_;
}
// Gesture is ongoing.
const mathfu::vec2 cur_pos =
input_manager_->GetTouchLocation(device_, touchpad_, ids_[0]);
callback_(state_, target_, cur_pos);
// Set state after the callback, so that the first frame will have
// kStarting.
state_ = kRunning;
return state_;
}
GesturePtr TwistRecognizer::TryStart(InputManager::DeviceType device,
InputManager::TouchpadId touchpad,
Gesture::TouchIdSpan ids) {
// If the touch is already owned, ignore it.
if (input_processor_->GetTouchOwner(device, touchpad, ids[0]) != nullptr ||
input_processor_->GetTouchOwner(device, touchpad, ids[1]) != nullptr) {
return nullptr;
}
const mathfu::vec2 delta1 =
input_manager_->GetTouchDelta(device, touchpad, ids[0]);
const mathfu::vec2 delta2 =
input_manager_->GetTouchDelta(device, touchpad, ids[1]);
// Make sure both touches are moving.
if (delta1.LengthSquared() < 0.00001f || delta2.LengthSquared() < 0.00001f) {
return nullptr;
}
// all positions should be in cm before calculating rotation.
const mathfu::vec2 start_pos1 =
touchpad_size_cm_ *
input_manager_->GetTouchGestureOrigin(device, touchpad, ids[0]);
const mathfu::vec2 cur_pos1 =
touchpad_size_cm_ *
input_manager_->GetTouchLocation(device, touchpad, ids[0]);
const mathfu::vec2 start_pos2 =
touchpad_size_cm_ *
input_manager_->GetTouchGestureOrigin(device, touchpad, ids[1]);
const mathfu::vec2 cur_pos2 =
touchpad_size_cm_ *
input_manager_->GetTouchLocation(device, touchpad, ids[1]);
DCHECK(start_pos1 != InputManager::kInvalidTouchLocation);
DCHECK(start_pos2 != InputManager::kInvalidTouchLocation);
DCHECK(cur_pos1 != InputManager::kInvalidTouchLocation);
DCHECK(cur_pos2 != InputManager::kInvalidTouchLocation);
const float rotation =
CalculateDeltaRotation(cur_pos1, cur_pos2, start_pos1, start_pos2);
if (std::abs(rotation) > kTwistThreshold) {
return std::make_shared<Twist>(callback_);
}
return nullptr;
}
Gesture::State TwistRecognizer::Twist::AdvanceFrame(
const Clock::duration& delta_time) {
if (state_ == kCanceled) {
// Callback should revert changes.
callback_(state_, target_, 0.0f);
return state_;
}
if (!input_manager_->IsValidTouch(device_, touchpad_, ids_[0]) ||
!input_manager_->IsValidTouch(device_, touchpad_, ids_[1])) {
// A touch has been released, so end the gesture.
state_ = kEnding;
// Set state before the callback, since this will be the last call.
callback_(state_, target_, 0.0f);
return state_;
}
// Gesture is ongoing.
const mathfu::vec2 prev_pos1 =
touchpad_size_cm_ *
input_manager_->GetPreviousTouchLocation(device_, touchpad_, ids_[0]);
const mathfu::vec2 cur_pos1 =
touchpad_size_cm_ *
input_manager_->GetTouchLocation(device_, touchpad_, ids_[0]);
const mathfu::vec2 prev_pos2 =
touchpad_size_cm_ *
input_manager_->GetPreviousTouchLocation(device_, touchpad_, ids_[1]);
const mathfu::vec2 cur_pos2 =
touchpad_size_cm_ *
input_manager_->GetTouchLocation(device_, touchpad_, ids_[1]);
const float rotation =
CalculateDeltaRotation(cur_pos1, cur_pos2, prev_pos1, prev_pos2);
callback_(state_, target_, rotation);
// Set state after the callback, so that the first frame will have
// kStarting.
state_ = kRunning;
return state_;
}
GesturePtr PinchRecognizer::TryStart(InputManager::DeviceType device,
InputManager::TouchpadId touchpad,
Gesture::TouchIdSpan ids) {
// If the touch is already owned, ignore it.
if (input_processor_->GetTouchOwner(device, touchpad, ids[0]) != nullptr ||
input_processor_->GetTouchOwner(device, touchpad, ids[1]) != nullptr) {
return nullptr;
}
const mathfu::vec2 delta1 = touchpad_size_cm_ * input_manager_->GetTouchDelta(
device, touchpad, ids[0]);
const mathfu::vec2 delta2 = touchpad_size_cm_ * input_manager_->GetTouchDelta(
device, touchpad, ids[1]);
const mathfu::vec2 start_pos1 =
touchpad_size_cm_ *
input_manager_->GetTouchGestureOrigin(device, touchpad, ids[0]);
const mathfu::vec2 start_pos2 =
touchpad_size_cm_ *
input_manager_->GetTouchGestureOrigin(device, touchpad, ids[1]);
const mathfu::vec2 cur_pos1 =
touchpad_size_cm_ *
input_manager_->GetTouchLocation(device, touchpad, ids[0]);
const mathfu::vec2 cur_pos2 =
touchpad_size_cm_ *
input_manager_->GetTouchLocation(device, touchpad, ids[1]);
DCHECK(start_pos1 != InputManager::kInvalidTouchLocation);
DCHECK(start_pos2 != InputManager::kInvalidTouchLocation);
DCHECK(cur_pos1 != InputManager::kInvalidTouchLocation);
DCHECK(cur_pos2 != InputManager::kInvalidTouchLocation);
const mathfu::vec2 first_to_second = start_pos1 - start_pos2;
const mathfu::vec2 first_to_second_dir = first_to_second.Normalized();
const float dot1 =
mathfu::vec2::DotProduct(delta1.Normalized(), -first_to_second_dir);
const float dot2 =
mathfu::vec2::DotProduct(delta2.Normalized(), first_to_second_dir);
// check that if a touch is moving, it's either moving towards or away from
// the other touch.
if (delta1.LengthSquared() < 0.005f &&
std::abs(dot1) < kPinchDirectionTheshold) {
return nullptr;
}
if (delta2.LengthSquared() < 0.005f &&
std::abs(dot2) < kPinchDirectionTheshold) {
return nullptr;
}
const float start_gap = first_to_second.Length();
const float cur_gap = (cur_pos1 - cur_pos2).Length();
if (std::abs(start_gap - cur_gap) >= kPinchDelta) {
return std::make_shared<Pinch>(callback_);
}
return nullptr;
}
void PinchRecognizer::Pinch::Initialize() {
const mathfu::vec2 cur_pos1 =
touchpad_size_cm_ *
input_manager_->GetTouchLocation(device_, touchpad_, ids_[0]);
const mathfu::vec2 cur_pos2 =
touchpad_size_cm_ *
input_manager_->GetTouchLocation(device_, touchpad_, ids_[1]);
start_gap_ = (cur_pos1 - cur_pos2).Length();
}
Gesture::State PinchRecognizer::Pinch::AdvanceFrame(
const Clock::duration& delta_time) {
if (state_ == kCanceled) {
// Callback should revert changes.
callback_(state_, target_, 1.0f);
return state_;
}
if (!input_manager_->IsValidTouch(device_, touchpad_, ids_[0]) ||
!input_manager_->IsValidTouch(device_, touchpad_, ids_[1])) {
// A touch has been released, so end the gesture.
state_ = kEnding;
// Set state before the callback, since this will be the last call.
callback_(state_, target_, 1.0f);
return state_;
}
// Gesture is ongoing.
const mathfu::vec2 cur_pos1 =
touchpad_size_cm_ *
input_manager_->GetTouchLocation(device_, touchpad_, ids_[0]);
const mathfu::vec2 cur_pos2 =
touchpad_size_cm_ *
input_manager_->GetTouchLocation(device_, touchpad_, ids_[1]);
const float cur_gap = (cur_pos1 - cur_pos2).Length();
const float ratio = cur_gap / start_gap_;
callback_(state_, target_, ratio);
// Set state after the callback, so that the first frame will have
// kStarting.
state_ = kRunning;
return state_;
}
} // namespace lull
|
/*
* Copyright (c) 2012-2014 ARM Limited
* All rights reserved
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Andrew Bardsley
*/
#include "arch/utility.hh"
#include "cpu/minor/cpu.hh"
#include "cpu/minor/dyn_inst.hh"
#include "cpu/minor/fetch1.hh"
#include "cpu/minor/pipeline.hh"
#include "debug/Drain.hh"
#include "debug/MinorCPU.hh"
#include "debug/Quiesce.hh"
MinorCPU::MinorCPU(MinorCPUParams *params) :
BaseCPU(params),
drainManager(NULL)
{
/* This is only written for one thread at the moment */
Minor::MinorThread *thread;
if (FullSystem) {
thread = new Minor::MinorThread(this, 0, params->system, params->itb,
params->dtb, params->isa[0]);
} else {
/* thread_id 0 */
thread = new Minor::MinorThread(this, 0, params->system,
params->workload[0], params->itb, params->dtb, params->isa[0]);
}
threads.push_back(thread);
threadActivateEvents.push_back(new ThreadActivateEvent(*this, 0));
thread->setStatus(ThreadContext::Halted);
ThreadContext *tc = thread->getTC();
if (params->checker) {
fatal("The Minor model doesn't support checking (yet)\n");
}
threadContexts.push_back(tc);
Minor::MinorDynInst::init();
pipeline = new Minor::Pipeline(*this, *params);
activityRecorder = pipeline->getActivityRecorder();
}
MinorCPU::~MinorCPU()
{
delete pipeline;
for (ThreadID thread_id = 0; thread_id < threads.size(); thread_id++) {
delete threads[thread_id];
delete threadActivateEvents[thread_id];
}
}
void
MinorCPU::init()
{
BaseCPU::init();
if (!params()->switched_out &&
system->getMemoryMode() != Enums::timing)
{
fatal("The Minor CPU requires the memory system to be in "
"'timing' mode.\n");
}
/* Initialise the ThreadContext's memory proxies */
for (ThreadID thread_id = 0; thread_id < threads.size(); thread_id++) {
ThreadContext *tc = getContext(thread_id);
tc->initMemProxies(tc);
}
/* Initialise CPUs (== threads in the ISA) */
if (FullSystem && !params()->switched_out) {
for (ThreadID thread_id = 0; thread_id < threads.size(); thread_id++)
{
ThreadContext *tc = getContext(thread_id);
/* Initialize CPU, including PC */
TheISA::initCPU(tc, cpuId());
}
}
}
/** Stats interface from SimObject (by way of BaseCPU) */
void
MinorCPU::regStats()
{
BaseCPU::regStats();
stats.regStats(name(), *this);
pipeline->regStats();
}
void
MinorCPU::serializeThread(std::ostream &os, ThreadID thread_id)
{
threads[thread_id]->serialize(os);
}
void
MinorCPU::unserializeThread(Checkpoint *cp, const std::string §ion,
ThreadID thread_id)
{
if (thread_id != 0)
fatal("Trying to load more than one thread into a MinorCPU\n");
threads[thread_id]->unserialize(cp, section);
}
void
MinorCPU::serialize(std::ostream &os)
{
pipeline->serialize(os);
BaseCPU::serialize(os);
}
void
MinorCPU::unserialize(Checkpoint *cp, const std::string §ion)
{
pipeline->unserialize(cp, section);
BaseCPU::unserialize(cp, section);
}
Addr
MinorCPU::dbg_vtophys(Addr addr)
{
/* Note that this gives you the translation for thread 0 */
panic("No implementation for vtophy\n");
return 0;
}
void
MinorCPU::wakeup()
{
DPRINTF(Drain, "MinorCPU wakeup\n");
for (auto i = threads.begin(); i != threads.end(); i ++) {
if ((*i)->status() == ThreadContext::Suspended)
(*i)->activate();
}
DPRINTF(Drain,"Suspended Processor awoke\n");
}
void
MinorCPU::startup()
{
DPRINTF(MinorCPU, "MinorCPU startup\n");
BaseCPU::startup();
for (auto i = threads.begin(); i != threads.end(); i ++)
(*i)->startup();
}
unsigned int
MinorCPU::drain(DrainManager *drain_manager)
{
DPRINTF(Drain, "MinorCPU drain\n");
drainManager = drain_manager;
/* Need to suspend all threads and wait for Execute to idle.
* Tell Fetch1 not to fetch */
unsigned int ret = pipeline->drain(drain_manager);
if (ret == 0)
DPRINTF(Drain, "MinorCPU drained\n");
else
DPRINTF(Drain, "MinorCPU not finished draining\n");
return ret;
}
void
MinorCPU::signalDrainDone()
{
DPRINTF(Drain, "MinorCPU drain done\n");
setDrainState(Drainable::Drained);
drainManager->signalDrainDone();
drainManager = NULL;
}
void
MinorCPU::drainResume()
{
assert(getDrainState() == Drainable::Drained ||
getDrainState() == Drainable::Running);
if (switchedOut()) {
DPRINTF(Drain, "drainResume while switched out. Ignoring\n");
return;
}
DPRINTF(Drain, "MinorCPU drainResume\n");
if (!system->isTimingMode()) {
fatal("The Minor CPU requires the memory system to be in "
"'timing' mode.\n");
}
wakeup();
pipeline->drainResume();
setDrainState(Drainable::Running);
}
void
MinorCPU::memWriteback()
{
DPRINTF(Drain, "MinorCPU memWriteback\n");
}
void
MinorCPU::switchOut()
{
DPRINTF(MinorCPU, "MinorCPU switchOut\n");
assert(!switchedOut());
BaseCPU::switchOut();
/* Check that the CPU is drained? */
activityRecorder->reset();
}
void
MinorCPU::takeOverFrom(BaseCPU *old_cpu)
{
DPRINTF(MinorCPU, "MinorCPU takeOverFrom\n");
BaseCPU::takeOverFrom(old_cpu);
/* Don't think I need to do anything here */
}
void
MinorCPU::activateContext(ThreadID thread_id, Cycles delay)
{
DPRINTF(MinorCPU, "ActivateContext thread: %d delay: %d\n",
thread_id, delay);
if (!threadActivateEvents[thread_id]->scheduled()) {
schedule(threadActivateEvents[thread_id], clockEdge(delay));
}
}
void
MinorCPU::ThreadActivateEvent::process()
{
DPRINTFS(MinorCPU, (&cpu), "Activating thread: %d\n", thread_id);
/* Do some cycle accounting. lastStopped is reset to stop the
* wakeup call on the pipeline from adding the quiesce period
* to BaseCPU::numCycles */
cpu.stats.quiesceCycles += cpu.pipeline->cyclesSinceLastStopped();
cpu.pipeline->resetLastStopped();
/* Wake up the thread, wakeup the pipeline tick */
cpu.threads[thread_id]->activate();
cpu.wakeupOnEvent(Minor::Pipeline::CPUStageId);
cpu.pipeline->wakeupFetch();
}
void
MinorCPU::suspendContext(ThreadID thread_id)
{
DPRINTF(MinorCPU, "SuspendContext %d\n", thread_id);
threads[thread_id]->suspend();
}
void
MinorCPU::wakeupOnEvent(unsigned int stage_id)
{
DPRINTF(Quiesce, "Event wakeup from stage %d\n", stage_id);
/* Mark that some activity has taken place and start the pipeline */
activityRecorder->activateStage(stage_id);
pipeline->start();
}
MinorCPU *
MinorCPUParams::create()
{
numThreads = 1;
if (!FullSystem && workload.size() != 1)
panic("only one workload allowed");
return new MinorCPU(this);
}
MasterPort &MinorCPU::getInstPort()
{
return pipeline->getInstPort();
}
MasterPort &MinorCPU::getDataPort()
{
return pipeline->getDataPort();
}
Counter
MinorCPU::totalInsts() const
{
Counter ret = 0;
for (auto i = threads.begin(); i != threads.end(); i ++)
ret += (*i)->numInst;
return ret;
}
Counter
MinorCPU::totalOps() const
{
Counter ret = 0;
for (auto i = threads.begin(); i != threads.end(); i ++)
ret += (*i)->numOp;
return ret;
}
|
#include "Tools/TexturePacker/ResourcePacker2D.h"
#include "Tools/TexturePacker/DefinitionFile.h"
#include "Tools/TexturePacker/TexturePacker.h"
#include <CommandLine/CommandLineParser.h>
#include <Engine/Engine.h>
#include <FileSystem/FileSystem.h>
#include <FileSystem/FileList.h>
#include <Core/Core.h>
#include <Utils/StringUtils.h>
#include <Platform/DeviceInfo.h>
#include <Time/DateTime.h>
#include <Time/SystemTimer.h>
#include <Utils/MD5.h>
#include <Utils/StringFormat.h>
#include <Utils/UTF8Utils.h>
#include <Render/GPUFamilyDescriptor.h>
#include <Platform/Process.h>
#include <Render/TextureDescriptor.h>
#include <Logger/Logger.h>
namespace DAVA
{
const String ResourcePacker2D::VERSION = "0.0.5";
const String ResourcePacker2D::INTERNAL_LIBPSD_VERSION = "0.0.1";
String ResourcePacker2D::GetProcessFolderName()
{
return "$process/";
}
void ResourcePacker2D::SetConvertQuality(const TextureConverter::eConvertQuality arg)
{
quality = arg;
}
void ResourcePacker2D::SetRunning(bool arg)
{
if (arg != running)
{
Logger::FrameworkDebug(arg ? "ResourcePacker2D was started" : "ResourcePacker2D was stopped");
}
running = arg;
}
void ResourcePacker2D::InitFolders(const FilePath& inputPath, const FilePath& outputPath)
{
DVASSERT(inputPath.IsDirectoryPathname() && outputPath.IsDirectoryPathname());
inputGfxDirectory = inputPath;
outputGfxDirectory = outputPath;
rootDirectory = inputPath + "../";
dataSourceDirectory = inputPath + "../../";
}
void ResourcePacker2D::PackResources(const Vector<eGPUFamily>& forGPUs)
{
SetRunning(true);
Logger::FrameworkDebug("\nInput: %s \nOutput: %s \nExclude: %s",
inputGfxDirectory.GetAbsolutePathname().c_str(),
outputGfxDirectory.GetAbsolutePathname().c_str(),
rootDirectory.GetAbsolutePathname().c_str());
if (FileSystem::Instance()->Exists(inputGfxDirectory) == false)
{
AddError(Format("Input folder is not exist: '%s'", inputGfxDirectory.GetStringValue().c_str()));
SetRunning(false);
return;
}
if (StringUtils::HasWhitespace(texturePostfix))
{
AddError(Format("Texture name postfix '%s' has whitespaces", texturePostfix.c_str()).c_str());
SetRunning(false);
return;
}
for (eGPUFamily gpu : forGPUs)
{
Logger::FrameworkDebug("For GPU: %s", (GPU_INVALID != gpu) ? GlobalEnumMap<eGPUFamily>::Instance()->ToString(gpu) : "Unknown");
}
Vector<PackingAlgorithm> packAlgorithms;
String alg = CommandLineParser::Instance()->GetCommandParam("-alg");
if (alg.empty() || CompareCaseInsensitive(alg, "maxrect") == 0)
{
packAlgorithms.push_back(PackingAlgorithm::ALG_MAXRECTS_BEST_AREA_FIT);
packAlgorithms.push_back(PackingAlgorithm::ALG_MAXRECTS_BEST_LONG_SIDE_FIT);
packAlgorithms.push_back(PackingAlgorithm::ALG_MAXRECTS_BEST_SHORT_SIDE_FIT);
packAlgorithms.push_back(PackingAlgorithm::ALG_MAXRECTS_BOTTOM_LEFT);
packAlgorithms.push_back(PackingAlgorithm::ALG_MAXRRECT_BEST_CONTACT_POINT);
}
else if (CompareCaseInsensitive(alg, "maxrect_fast") == 0)
{
packAlgorithms.push_back(PackingAlgorithm::ALG_MAXRECTS_BEST_AREA_FIT);
}
else if (CompareCaseInsensitive(alg, "basic") == 0)
{
packAlgorithms.push_back(PackingAlgorithm::ALG_BASIC);
}
else
{
AddError(Format("Unknown algorithm: '%s'", alg.c_str()));
SetRunning(false);
return;
}
requestedGPUs = forGPUs;
outputDirModified = false;
gfxDirName = inputGfxDirectory.GetLastDirectoryName();
std::transform(gfxDirName.begin(), gfxDirName.end(), gfxDirName.begin(), ::tolower);
FilePath processDirectoryPath = rootDirectory + GetProcessFolderName();
FileSystem::Instance()->CreateDirectory(processDirectoryPath, true);
FileSystem::Instance()->CreateDirectory(outputGfxDirectory, true);
if (RecalculateDirMD5(outputGfxDirectory, processDirectoryPath + gfxDirName + ".md5", true))
{
#if defined(__DAVAENGINE_COREV2__)
if (Engine::Instance()->IsConsoleMode())
#else
if (Core::Instance()->IsConsoleMode())
#endif
{
Logger::FrameworkDebug("[Gfx not available or changed - performing full repack]");
}
outputDirModified = true;
// Remove whole output directory
if (clearOutputDirectory)
{
bool isDeleted = FileSystem::Instance()->DeleteDirectory(outputGfxDirectory);
if (isDeleted)
{
Logger::FrameworkDebug("Removed output directory: %s", outputGfxDirectory.GetAbsolutePathname().c_str());
}
else
{
if (FileSystem::Instance()->IsDirectory(outputGfxDirectory))
{
AddError(Format("Can't delete directory [%s]", outputGfxDirectory.GetAbsolutePathname().c_str()));
}
}
}
}
RecursiveTreeWalk(inputGfxDirectory, outputGfxDirectory, packAlgorithms);
// Put latest md5 after convertation
RecalculateDirMD5(outputGfxDirectory, processDirectoryPath + gfxDirName + ".md5", true);
}
void ResourcePacker2D::RecalculateMD5ForOutputDir()
{
gfxDirName = inputGfxDirectory.GetLastDirectoryName();
std::transform(gfxDirName.begin(), gfxDirName.end(), gfxDirName.begin(), ::tolower);
FilePath processDirectoryPath = rootDirectory + GetProcessFolderName();
FileSystem::Instance()->CreateDirectory(processDirectoryPath, true);
RecalculateDirMD5(outputGfxDirectory, processDirectoryPath + gfxDirName + ".md5", true);
}
bool ResourcePacker2D::ReadMD5FromFile(const FilePath& md5file, MD5::MD5Digest& digest) const
{
ScopedPtr<File> file(File::Create(md5file, File::OPEN | File::READ));
if (file)
{
auto bytesRead = file->Read(digest.digest.data(), static_cast<uint32>(digest.digest.size()));
DVASSERT(bytesRead == MD5::MD5Digest::DIGEST_SIZE && "We should always read 16 bytes from md5 file");
return true;
}
else
{
return false;
}
}
void ResourcePacker2D::WriteMD5ToFile(const FilePath& md5file, const MD5::MD5Digest& digest) const
{
ScopedPtr<File> file(File::Create(md5file, File::CREATE | File::WRITE));
DVASSERT(file && "Can't create md5 file");
auto bytesWritten = file->Write(digest.digest.data(), static_cast<uint32>(digest.digest.size()));
DVASSERT(bytesWritten == MD5::MD5Digest::DIGEST_SIZE && "16 bytes should be always written for md5 file");
}
bool ResourcePacker2D::RecalculateParamsMD5(const String& params, const FilePath& md5file) const
{
MD5::MD5Digest oldMD5Digest;
MD5::MD5Digest newMD5Digest;
bool oldMD5Read = ReadMD5FromFile(md5file, oldMD5Digest);
MD5::ForData(reinterpret_cast<const uint8*>(params.data()), static_cast<uint32>(params.size()), newMD5Digest);
WriteMD5ToFile(md5file, newMD5Digest);
bool isChanged = true;
if (oldMD5Read)
{
isChanged = !(oldMD5Digest == newMD5Digest);
}
return isChanged;
}
bool ResourcePacker2D::RecalculateDirMD5(const FilePath& pathname, const FilePath& md5file, bool isRecursive) const
{
MD5::MD5Digest oldMD5Digest;
MD5::MD5Digest newMD5Digest;
bool oldMD5Read = ReadMD5FromFile(md5file, oldMD5Digest);
MD5::ForDirectory(pathname, newMD5Digest, isRecursive, false);
WriteMD5ToFile(md5file, newMD5Digest);
bool isChanged = true;
if (oldMD5Read)
{
isChanged = !(oldMD5Digest == newMD5Digest);
}
return isChanged;
}
bool ResourcePacker2D::RecalculateFileMD5(const FilePath& pathname, const FilePath& md5file) const
{
FilePath md5FileName = FilePath::CreateWithNewExtension(md5file, ".md5");
MD5::MD5Digest oldMD5Digest;
MD5::MD5Digest newMD5Digest;
bool oldMD5Read = ReadMD5FromFile(md5file, oldMD5Digest);
MD5::ForFile(pathname, newMD5Digest);
WriteMD5ToFile(md5file, newMD5Digest);
bool isChanged = true;
if (oldMD5Read)
{
isChanged = !(oldMD5Digest == newMD5Digest);
}
return isChanged;
}
Vector<String> ResourcePacker2D::FetchFlags(const FilePath& flagsPathname)
{
Vector<String> tokens;
ScopedPtr<File> file(File::Create(flagsPathname, File::READ | File::OPEN));
if (!file)
{
AddError(Format("Failed to open file: %s", flagsPathname.GetAbsolutePathname().c_str()));
return tokens;
}
String tokenString = file->ReadLine();
Split(tokenString, " ", tokens, false);
return tokens;
}
uint32 ResourcePacker2D::GetMaxTextureSize() const
{
uint32 maxTextureSize = TexturePacker::DEFAULT_TEXTURE_SIZE;
String tsizeValue = CommandLineParser::Instance()->GetParamForFlag("--tsize");
if (!tsizeValue.empty())
{
uint32 fetchedValue;
int fetchedCount = sscanf(tsizeValue.c_str(), "%u", &fetchedValue);
if (fetchedCount == 1 && IsPowerOf2(fetchedValue))
{
maxTextureSize = fetchedValue;
}
else
{
Logger::Warning("--tsize value '%s' is incorrect: should be uint of power of 2. Using default value: %u", tsizeValue.c_str(), maxTextureSize);
}
}
return maxTextureSize;
}
void ResourcePacker2D::RecursiveTreeWalk(const FilePath& inputPath, const FilePath& outputPath, const Vector<PackingAlgorithm>& packAlgorithms, const Vector<String>& passedFlags)
{
DVASSERT(inputPath.IsDirectoryPathname() && outputPath.IsDirectoryPathname());
if (!running)
{
return;
}
uint64 packTime = SystemTimer::GetMs();
String inputRelativePath = inputPath.GetRelativePathname(rootDirectory);
FilePath processDir = rootDirectory + GetProcessFolderName() + inputRelativePath;
FileSystem::Instance()->CreateDirectory(processDir, true);
if (forceRepack)
{
FileSystem::Instance()->DeleteDirectoryFiles(processDir, false);
}
FileSystem::Instance()->CreateDirectory(outputPath);
Vector<String> currentFlags;
const auto flagsPathname = inputPath + "flags.txt";
if (FileSystem::Instance()->Exists(flagsPathname))
{
currentFlags = FetchFlags(flagsPathname);
}
else
{
currentFlags = passedFlags;
}
CommandLineParser::Instance()->SetFlags(currentFlags);
String mergedFlags;
Merge(currentFlags, ' ', mergedFlags);
String packingParams = mergedFlags;
for (eGPUFamily gpu : requestedGPUs)
{
packingParams += String("GPU = ") + GlobalEnumMap<eGPUFamily>::Instance()->ToString(gpu);
}
packingParams += String("PackerVersion = ") + VERSION;
packingParams += String("LibPSDVersion = ") + INTERNAL_LIBPSD_VERSION;
for (const auto& algorithm : packAlgorithms)
{
packingParams += String("PackerAlgorithm = ") + GlobalEnumMap<DAVA::PackingAlgorithm>::Instance()->ToString(static_cast<int>(algorithm));
}
ScopedPtr<FileList> fileList(new FileList(inputPath));
fileList->Sort();
bool inputDirHasFiles = false;
uint64 allFilesSize = 0;
uint32 allFilesCount = 0;
static const Vector<String> ignoredFileNames = { ".DS_Store", "flags.txt", "Thumbs.db", ".gitignore" };
auto IsFileIgnoredByName = [](const Vector<String>& ignoredFileNames, const String& filename)
{
auto found = std::find_if(ignoredFileNames.begin(), ignoredFileNames.end(), [&filename](const String& name)
{
return (CompareCaseInsensitive(filename, name) == 0);
});
return (found != ignoredFileNames.end());
};
for (uint32 fi = 0; fi < fileList->GetCount(); ++fi)
{
if (!fileList->IsDirectory(fi))
{
String fileName = fileList->GetFilename(fi);
if (IsFileIgnoredByName(ignoredFileNames, fileName))
{
continue;
}
inputDirHasFiles = true;
packingParams += fileName;
allFilesSize += fileList->GetFileSize(fi);
++allFilesCount;
}
}
packingParams += Format("FilesSize = %llu", allFilesSize);
packingParams += Format("FilesCount = %u", allFilesCount);
packingParams += Format("DescriptorVersion = %i", TextureDescriptor::CURRENT_VERSION);
bool inputDirModified = RecalculateDirMD5(inputPath, processDir + "dir.md5", false);
bool paramsModified = RecalculateParamsMD5(packingParams, processDir + "params.md5");
bool modified = outputDirModified || inputDirModified || paramsModified;
if (modified)
{
if (inputDirHasFiles)
{
AssetCache::CacheItemKey cacheKey;
if (IsUsingCache())
{
MD5::MD5Digest digest;
ReadMD5FromFile(processDir + "dir.md5", digest);
cacheKey.SetPrimaryKey(digest);
ReadMD5FromFile(processDir + "params.md5", digest);
cacheKey.SetSecondaryKey(digest);
}
bool needRepack = (false == GetFilesFromCache(cacheKey, inputPath, outputPath));
if (needRepack)
{
// read textures margins settings
bool useTwoSideMargin = CommandLineParser::Instance()->IsFlagSet("--add2sidepixel");
uint32 marginInPixels = useTwoSideMargin ? 0 : 1;
if (CommandLineParser::Instance()->IsFlagSet("--add0pixel"))
marginInPixels = 0;
else if (CommandLineParser::Instance()->IsFlagSet("--add1pixel"))
marginInPixels = 1;
else if (CommandLineParser::Instance()->IsFlagSet("--add2pixel"))
marginInPixels = 2;
else if (CommandLineParser::Instance()->IsFlagSet("--add4pixel"))
marginInPixels = 4;
uint32 maxTextureSize = GetMaxTextureSize();
bool withAlpha = CommandLineParser::Instance()->IsFlagSet("--disableCropAlpha");
bool useLayerNames = CommandLineParser::Instance()->IsFlagSet("--useLayerNames");
bool verbose = CommandLineParser::Instance()->GetVerbose();
if (clearOutputDirectory)
{
FileSystem::Instance()->DeleteDirectoryFiles(outputPath, false);
}
DefinitionFile::Collection definitionFileList;
definitionFileList.reserve(fileList->GetCount());
for (uint32 fi = 0; fi < fileList->GetCount() && running; ++fi)
{
if (fileList->IsDirectory(fi))
continue;
definitionFileList.emplace_back(new DefinitionFile());
DefinitionFile::Pointer& defFile = definitionFileList.back();
bool shouldAcceptFile = false;
FilePath fullname = fileList->GetPathname(fi);
if (fullname.IsEqualToExtension(".psd"))
{
shouldAcceptFile = defFile->LoadPSD(fullname, processDir, maxTextureSize,
withAlpha, useLayerNames, verbose);
}
else if (isLightmapsPacking && fullname.IsEqualToExtension(".png"))
{
shouldAcceptFile = true;
defFile->LoadPNG(fullname, processDir);
}
else if (fullname.IsEqualToExtension(".pngdef"))
{
shouldAcceptFile = defFile->LoadPNGDef(fullname, processDir);
}
if (shouldAcceptFile == false)
{
definitionFileList.pop_back();
}
}
if (!definitionFileList.empty())
{
TexturePacker packer;
packer.SetConvertQuality(quality);
if (isLightmapsPacking)
{
packer.SetUseOnlySquareTextures();
packer.SetMaxTextureSize(2048);
}
else
{
if (CommandLineParser::Instance()->IsFlagSet("--square"))
{
packer.SetUseOnlySquareTextures();
}
packer.SetMaxTextureSize(maxTextureSize);
}
packer.SetTwoSideMargin(useTwoSideMargin);
packer.SetTexturesMargin(marginInPixels);
packer.SetAlgorithms(packAlgorithms);
packer.SetTexturePostfix(texturePostfix);
if (CommandLineParser::Instance()->IsFlagSet("--split"))
{
packer.PackToTexturesSeparate(outputPath, definitionFileList, requestedGPUs);
}
else
{
packer.PackToTextures(outputPath, definitionFileList, requestedGPUs);
}
Set<String> currentErrors = packer.GetErrors();
if (!currentErrors.empty())
{
errors.insert(currentErrors.begin(), currentErrors.end());
}
}
packTime = SystemTimer::GetMs() - packTime;
#if defined(__DAVAENGINE_COREV2__)
if (Engine::Instance()->IsConsoleMode())
#else
if (Core::Instance()->IsConsoleMode())
#endif
{
Logger::Info("[%u files packed with flags: %s]", static_cast<uint32>(definitionFileList.size()), mergedFlags.c_str());
}
const char* result = definitionFileList.empty() ? "[unchanged]" : "[REPACKED]";
Logger::Info("[%s - %.2lf secs] - %s", inputPath.GetAbsolutePathname().c_str(),
static_cast<float64>(packTime) / 1000.0, result);
AddFilesToCache(cacheKey, inputPath, outputPath);
}
}
else if (outputDirModified || inputDirModified)
{
Logger::Info("[%s] - empty directory. Clearing output folder", inputPath.GetAbsolutePathname().c_str());
FileSystem::Instance()->DeleteDirectoryFiles(outputPath, false);
}
}
else
{
Logger::Info("[%s] - unchanged", inputPath.GetAbsolutePathname().c_str());
}
const auto& flagsToPass = CommandLineParser::Instance()->IsFlagSet("--recursive") ? currentFlags : passedFlags;
for (uint32 fi = 0; fi < fileList->GetCount(); ++fi)
{
if (fileList->IsDirectory(fi))
{
String filename = fileList->GetFilename(fi);
if (!fileList->IsNavigationDirectory(fi) && (filename != "$process") && (filename != ".svn"))
{
if ((filename.size() > 0) && (filename[0] != '.'))
{
FilePath input = inputPath + filename;
input.MakeDirectoryPathname();
FilePath output = outputPath + filename;
output.MakeDirectoryPathname();
RecursiveTreeWalk(input, output, packAlgorithms, flagsToPass);
}
}
}
}
}
void ResourcePacker2D::SetCacheClient(AssetCacheClient* cacheClient_, const String& comment)
{
cacheClient = cacheClient_;
cacheItemDescription.machineName = UTF8Utils::EncodeToUTF8(DeviceInfo::GetName());
DateTime timeNow = DateTime::Now();
cacheItemDescription.creationDate = UTF8Utils::EncodeToUTF8(timeNow.GetLocalizedDate()) + "_" + UTF8Utils::EncodeToUTF8(timeNow.GetLocalizedTime());
cacheItemDescription.comment = comment;
}
void ResourcePacker2D::SetTexturePostfix(const String& postfix)
{
texturePostfix = postfix;
}
bool ResourcePacker2D::GetFilesFromCache(const AssetCache::CacheItemKey& key, const FilePath& inputPath, const FilePath& outputPath)
{
#ifdef __DAVAENGINE_WIN_UAP__
//no cache client in win uap
return false;
#else
if (!IsUsingCache())
{
return false;
}
String requestedDataRelativePath = "..." + inputPath.GetRelativePathname(dataSourceDirectory);
AssetCache::CachedItemValue retrievedData;
AssetCache::Error requestError = cacheClient->RequestFromCacheSynchronously(key, &retrievedData);
if (requestError == AssetCache::Error::NO_ERRORS)
{
Logger::Info("%s - retrieved from cache", requestedDataRelativePath.c_str());
retrievedData.ExportToFolder(outputPath);
return true;
}
else
{
String errorInfo = AssetCache::ErrorToString(requestError);
if (requestError == AssetCache::Error::OPERATION_TIMEOUT)
{
errorInfo.append(Format(" (%u ms)", cacheClient->GetTimeoutMs()));
}
Logger::Info("%s - can't retrieve from cache: %s", requestedDataRelativePath.c_str(), errorInfo.c_str());
}
return false;
#endif
}
bool ResourcePacker2D::AddFilesToCache(const AssetCache::CacheItemKey& key, const FilePath& inputPath, const FilePath& outputPath)
{
#ifdef __DAVAENGINE_WIN_UAP__
//no cache client in win uap
return false;
#else
if (!IsUsingCache())
{
return false;
}
AssetCache::CachedItemValue value;
ScopedPtr<FileList> outFilesList(new FileList(outputPath));
for (uint32 fi = 0; fi < outFilesList->GetCount(); ++fi)
{
if (!outFilesList->IsDirectory(fi))
{
value.Add(outFilesList->GetPathname(fi));
}
}
String addedDataRelativePath = "..." + inputPath.GetRelativePathname(dataSourceDirectory);
if (!value.IsEmpty())
{
value.UpdateValidationData();
value.SetDescription(cacheItemDescription);
AssetCache::Error addError = cacheClient->AddToCacheSynchronously(key, value);
if (addError == AssetCache::Error::NO_ERRORS)
{
Logger::Info("%s - added to cache", addedDataRelativePath.c_str());
return true;
}
else
{
String errorInfo = AssetCache::ErrorToString(addError);
if (addError == AssetCache::Error::OPERATION_TIMEOUT)
{
errorInfo.append(Format(" (%u ms)", cacheClient->GetTimeoutMs()));
}
Logger::Info("%s - can't add to cache: %s", addedDataRelativePath.c_str(), errorInfo.c_str());
}
}
else
{
Logger::Info("%s - empty folder", addedDataRelativePath.c_str());
}
return false;
#endif
}
const Set<String>& ResourcePacker2D::GetErrors() const
{
return errors;
}
void ResourcePacker2D::AddError(const String& errorMsg)
{
Logger::Error(errorMsg.c_str());
errors.insert(errorMsg);
}
bool ResourcePacker2D::IsUsingCache() const
{
#ifdef __DAVAENGINE_WIN_UAP__
//no cache in win uap
return false;
#else
return (cacheClient != nullptr) && cacheClient->IsConnected();
#endif
}
};
|
/*************************************************************************/
/* polygon_2d_editor_plugin.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2017 Godot Engine contributors (cf. AUTHORS.md) */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "polygon_2d_editor_plugin.h"
#include "canvas_item_editor_plugin.h"
#include "editor/editor_settings.h"
#include "os/file_access.h"
#include "os/input.h"
#include "os/keyboard.h"
void Polygon2DEditor::_notification(int p_what) {
switch (p_what) {
case NOTIFICATION_READY: {
button_create->set_icon(get_icon("Edit", "EditorIcons"));
button_edit->set_icon(get_icon("MovePoint", "EditorIcons"));
button_edit->set_pressed(true);
button_uv->set_icon(get_icon("Uv", "EditorIcons"));
uv_button[UV_MODE_EDIT_POINT]->set_icon(get_icon("ToolSelect", "EditorIcons"));
uv_button[UV_MODE_MOVE]->set_icon(get_icon("ToolMove", "EditorIcons"));
uv_button[UV_MODE_ROTATE]->set_icon(get_icon("ToolRotate", "EditorIcons"));
uv_button[UV_MODE_SCALE]->set_icon(get_icon("ToolScale", "EditorIcons"));
b_snap_grid->set_icon(get_icon("Grid", "EditorIcons"));
b_snap_enable->set_icon(get_icon("Snap", "EditorIcons"));
uv_icon_zoom->set_texture(get_icon("Zoom", "EditorIcons"));
get_tree()->connect("node_removed", this, "_node_removed");
} break;
case NOTIFICATION_FIXED_PROCESS: {
} break;
}
}
void Polygon2DEditor::_node_removed(Node *p_node) {
if (p_node == node) {
edit(NULL);
hide();
canvas_item_editor->get_viewport_control()->update();
}
}
void Polygon2DEditor::_menu_option(int p_option) {
switch (p_option) {
case MODE_CREATE: {
mode = MODE_CREATE;
button_create->set_pressed(true);
button_edit->set_pressed(false);
} break;
case MODE_EDIT: {
mode = MODE_EDIT;
button_create->set_pressed(false);
button_edit->set_pressed(true);
} break;
case MODE_EDIT_UV: {
if (node->get_texture().is_null()) {
error->set_text("No texture in this polygon.\nSet a texture to be able to edit UV.");
error->popup_centered_minsize();
return;
}
PoolVector<Vector2> points = node->get_polygon();
PoolVector<Vector2> uvs = node->get_uv();
if (uvs.size() != points.size()) {
undo_redo->create_action(TTR("Create UV Map"));
undo_redo->add_do_method(node, "set_uv", points);
undo_redo->add_undo_method(node, "set_uv", uvs);
undo_redo->add_do_method(uv_edit_draw, "update");
undo_redo->add_undo_method(uv_edit_draw, "update");
undo_redo->commit_action();
}
uv_edit->popup_centered_ratio(0.85);
} break;
case UVEDIT_POLYGON_TO_UV: {
PoolVector<Vector2> points = node->get_polygon();
if (points.size() == 0)
break;
PoolVector<Vector2> uvs = node->get_uv();
undo_redo->create_action(TTR("Create UV Map"));
undo_redo->add_do_method(node, "set_uv", points);
undo_redo->add_undo_method(node, "set_uv", uvs);
undo_redo->add_do_method(uv_edit_draw, "update");
undo_redo->add_undo_method(uv_edit_draw, "update");
undo_redo->commit_action();
} break;
case UVEDIT_UV_TO_POLYGON: {
PoolVector<Vector2> points = node->get_polygon();
PoolVector<Vector2> uvs = node->get_uv();
if (uvs.size() == 0)
break;
undo_redo->create_action(TTR("Create UV Map"));
undo_redo->add_do_method(node, "set_polygon", uvs);
undo_redo->add_undo_method(node, "set_polygon", points);
undo_redo->add_do_method(uv_edit_draw, "update");
undo_redo->add_undo_method(uv_edit_draw, "update");
undo_redo->commit_action();
} break;
case UVEDIT_UV_CLEAR: {
PoolVector<Vector2> uvs = node->get_uv();
if (uvs.size() == 0)
break;
undo_redo->create_action(TTR("Create UV Map"));
undo_redo->add_do_method(node, "set_uv", PoolVector<Vector2>());
undo_redo->add_undo_method(node, "set_uv", uvs);
undo_redo->add_do_method(uv_edit_draw, "update");
undo_redo->add_undo_method(uv_edit_draw, "update");
undo_redo->commit_action();
} break;
}
}
void Polygon2DEditor::_set_use_snap(bool p_use) {
use_snap = p_use;
}
void Polygon2DEditor::_set_show_grid(bool p_show) {
snap_show_grid = p_show;
uv_edit_draw->update();
}
void Polygon2DEditor::_set_snap_off_x(float p_val) {
snap_offset.x = p_val;
uv_edit_draw->update();
}
void Polygon2DEditor::_set_snap_off_y(float p_val) {
snap_offset.y = p_val;
uv_edit_draw->update();
}
void Polygon2DEditor::_set_snap_step_x(float p_val) {
snap_step.x = p_val;
uv_edit_draw->update();
}
void Polygon2DEditor::_set_snap_step_y(float p_val) {
snap_step.y = p_val;
uv_edit_draw->update();
}
void Polygon2DEditor::_wip_close() {
undo_redo->create_action(TTR("Create Poly"));
undo_redo->add_undo_method(node, "set_polygon", node->get_polygon());
undo_redo->add_do_method(node, "set_polygon", wip);
undo_redo->add_do_method(canvas_item_editor->get_viewport_control(), "update");
undo_redo->add_undo_method(canvas_item_editor->get_viewport_control(), "update");
undo_redo->commit_action();
wip.clear();
wip_active = false;
mode = MODE_EDIT;
button_edit->set_pressed(true);
button_create->set_pressed(false);
edited_point = -1;
}
bool Polygon2DEditor::forward_gui_input(const Ref<InputEvent> &p_event) {
if (node == NULL)
return false;
Ref<InputEventMouseButton> mb = p_event;
if (mb.is_valid()) {
Transform2D xform = canvas_item_editor->get_canvas_transform() * node->get_global_transform();
Vector2 gpoint = mb->get_position();
Vector2 cpoint = canvas_item_editor->get_canvas_transform().affine_inverse().xform(gpoint);
cpoint = canvas_item_editor->snap_point(cpoint);
cpoint = node->get_global_transform().affine_inverse().xform(cpoint);
Vector<Vector2> poly = Variant(node->get_polygon());
//first check if a point is to be added (segment split)
real_t grab_threshold = EDITOR_DEF("editors/poly_editor/point_grab_radius", 8);
switch (mode) {
case MODE_CREATE: {
if (mb->get_button_index() == BUTTON_LEFT && mb->is_pressed()) {
if (!wip_active) {
wip.clear();
wip.push_back(cpoint - node->get_offset());
wip_active = true;
edited_point_pos = cpoint;
canvas_item_editor->get_viewport_control()->update();
edited_point = 1;
return true;
} else {
if (wip.size() > 1 && xform.xform(wip[0] + node->get_offset()).distance_to(gpoint) < grab_threshold) {
//wip closed
_wip_close();
return true;
} else {
wip.push_back(cpoint - node->get_offset());
edited_point = wip.size();
canvas_item_editor->get_viewport_control()->update();
return true;
//add wip point
}
}
} else if (mb->get_button_index() == BUTTON_RIGHT && mb->is_pressed() && wip_active) {
_wip_close();
}
} break;
case MODE_EDIT: {
if (mb->get_button_index() == BUTTON_LEFT) {
if (mb->is_pressed()) {
if (mb->get_control()) {
if (poly.size() < 3) {
undo_redo->create_action(TTR("Edit Poly"));
undo_redo->add_undo_method(node, "set_polygon", poly);
poly.push_back(cpoint);
undo_redo->add_do_method(node, "set_polygon", poly);
undo_redo->add_do_method(canvas_item_editor->get_viewport_control(), "update");
undo_redo->add_undo_method(canvas_item_editor->get_viewport_control(), "update");
undo_redo->commit_action();
return true;
}
//search edges
int closest_idx = -1;
Vector2 closest_pos;
real_t closest_dist = 1e10;
for (int i = 0; i < poly.size(); i++) {
Vector2 points[2] = { xform.xform(poly[i] + node->get_offset()),
xform.xform(poly[(i + 1) % poly.size()] + node->get_offset()) };
Vector2 cp = Geometry::get_closest_point_to_segment_2d(gpoint, points);
if (cp.distance_squared_to(points[0]) < CMP_EPSILON2 || cp.distance_squared_to(points[1]) < CMP_EPSILON2)
continue; //not valid to reuse point
real_t d = cp.distance_to(gpoint);
if (d < closest_dist && d < grab_threshold) {
closest_dist = d;
closest_pos = cp;
closest_idx = i;
}
}
if (closest_idx >= 0) {
pre_move_edit = poly;
poly.insert(closest_idx + 1, xform.affine_inverse().xform(closest_pos) - node->get_offset());
edited_point = closest_idx + 1;
edited_point_pos = xform.affine_inverse().xform(closest_pos);
node->set_polygon(Variant(poly));
canvas_item_editor->get_viewport_control()->update();
return true;
}
} else {
//look for points to move
int closest_idx = -1;
Vector2 closest_pos;
real_t closest_dist = 1e10;
for (int i = 0; i < poly.size(); i++) {
Vector2 cp = xform.xform(poly[i] + node->get_offset());
real_t d = cp.distance_to(gpoint);
if (d < closest_dist && d < grab_threshold) {
closest_dist = d;
closest_pos = cp;
closest_idx = i;
}
}
if (closest_idx >= 0) {
pre_move_edit = poly;
edited_point = closest_idx;
edited_point_pos = xform.affine_inverse().xform(closest_pos);
canvas_item_editor->get_viewport_control()->update();
return true;
}
}
} else {
if (edited_point != -1) {
//apply
ERR_FAIL_INDEX_V(edited_point, poly.size(), false);
poly[edited_point] = edited_point_pos - node->get_offset();
undo_redo->create_action(TTR("Edit Poly"));
undo_redo->add_do_method(node, "set_polygon", poly);
undo_redo->add_undo_method(node, "set_polygon", pre_move_edit);
undo_redo->add_do_method(canvas_item_editor->get_viewport_control(), "update");
undo_redo->add_undo_method(canvas_item_editor->get_viewport_control(), "update");
undo_redo->commit_action();
edited_point = -1;
return true;
}
}
} else if (mb->get_button_index() == BUTTON_RIGHT && mb->is_pressed() && edited_point == -1) {
int closest_idx = -1;
Vector2 closest_pos;
real_t closest_dist = 1e10;
for (int i = 0; i < poly.size(); i++) {
Vector2 cp = xform.xform(poly[i] + node->get_offset());
real_t d = cp.distance_to(gpoint);
if (d < closest_dist && d < grab_threshold) {
closest_dist = d;
closest_pos = cp;
closest_idx = i;
}
}
if (closest_idx >= 0) {
undo_redo->create_action(TTR("Edit Poly (Remove Point)"));
undo_redo->add_undo_method(node, "set_polygon", poly);
poly.remove(closest_idx);
undo_redo->add_do_method(node, "set_polygon", poly);
undo_redo->add_do_method(canvas_item_editor->get_viewport_control(), "update");
undo_redo->add_undo_method(canvas_item_editor->get_viewport_control(), "update");
undo_redo->commit_action();
return true;
}
}
} break;
}
}
Ref<InputEventMouseMotion> mm = p_event;
if (mm.is_valid()) {
if (edited_point != -1 && (wip_active || mm->get_button_mask() & BUTTON_MASK_LEFT)) {
Vector2 gpoint = mm->get_position();
Vector2 cpoint = canvas_item_editor->get_canvas_transform().affine_inverse().xform(gpoint);
cpoint = canvas_item_editor->snap_point(cpoint);
edited_point_pos = node->get_global_transform().affine_inverse().xform(cpoint);
if (!wip_active) {
Vector<Vector2> poly = Variant(node->get_polygon());
ERR_FAIL_INDEX_V(edited_point, poly.size(), false);
poly[edited_point] = edited_point_pos - node->get_offset();
node->set_polygon(Variant(poly));
}
canvas_item_editor->get_viewport_control()->update();
}
}
return false;
}
void Polygon2DEditor::_canvas_draw() {
if (!node)
return;
Control *vpc = canvas_item_editor->get_viewport_control();
Vector<Vector2> poly;
if (wip_active)
poly = wip;
else
poly = Variant(node->get_polygon());
Transform2D xform = canvas_item_editor->get_canvas_transform() * node->get_global_transform();
Ref<Texture> handle = get_icon("EditorHandle", "EditorIcons");
if (!wip_active && edited_point >= 0 && EDITOR_DEF("editors/poly_editor/show_previous_outline", true)) {
const Color col = node->get_color().contrasted();
const int n = pre_move_edit.size();
for (int i = 0; i < n; i++) {
Vector2 p, p2;
p = pre_move_edit[i] + node->get_offset();
p2 = pre_move_edit[(i + 1) % n] + node->get_offset();
Vector2 point = xform.xform(p);
Vector2 next_point = xform.xform(p2);
vpc->draw_line(point, next_point, col, 2);
}
}
for (int i = 0; i < poly.size(); i++) {
Vector2 p, p2;
p = i == edited_point ? edited_point_pos : (poly[i] + node->get_offset());
if ((wip_active && i == poly.size() - 1) || (((i + 1) % poly.size()) == edited_point))
p2 = edited_point_pos;
else
p2 = poly[(i + 1) % poly.size()] + node->get_offset();
Vector2 point = xform.xform(p);
Vector2 next_point = xform.xform(p2);
Color col = Color(1, 0.3, 0.1, 0.8);
vpc->draw_line(point, next_point, col, 2);
vpc->draw_texture(handle, point - handle->get_size() * 0.5);
}
}
void Polygon2DEditor::_uv_mode(int p_mode) {
uv_mode = UVMode(p_mode);
for (int i = 0; i < UV_MODE_MAX; i++) {
uv_button[i]->set_pressed(p_mode == i);
}
}
void Polygon2DEditor::_uv_input(const Ref<InputEvent> &p_input) {
Transform2D mtx;
mtx.elements[2] = -uv_draw_ofs;
mtx.scale_basis(Vector2(uv_draw_zoom, uv_draw_zoom));
Ref<InputEventMouseButton> mb = p_input;
if (mb.is_valid()) {
if (mb->get_button_index() == BUTTON_LEFT) {
if (mb->is_pressed()) {
uv_drag_from = Vector2(mb->get_position().x, mb->get_position().y);
uv_drag = true;
uv_prev = node->get_uv();
uv_move_current = uv_mode;
if (uv_move_current == UV_MODE_EDIT_POINT) {
if (mb->get_shift() && mb->get_command())
uv_move_current = UV_MODE_SCALE;
else if (mb->get_shift())
uv_move_current = UV_MODE_MOVE;
else if (mb->get_command())
uv_move_current = UV_MODE_ROTATE;
}
if (uv_move_current == UV_MODE_EDIT_POINT) {
uv_drag_index = -1;
for (int i = 0; i < uv_prev.size(); i++) {
Vector2 tuv = mtx.xform(uv_prev[i]);
if (tuv.distance_to(Vector2(mb->get_position().x, mb->get_position().y)) < 8) {
uv_drag_from = tuv;
uv_drag_index = i;
}
}
if (uv_drag_index == -1) {
uv_drag = false;
}
}
} else if (uv_drag) {
undo_redo->create_action(TTR("Transform UV Map"));
undo_redo->add_do_method(node, "set_uv", node->get_uv());
undo_redo->add_undo_method(node, "set_uv", uv_prev);
undo_redo->add_do_method(uv_edit_draw, "update");
undo_redo->add_undo_method(uv_edit_draw, "update");
undo_redo->commit_action();
uv_drag = false;
}
} else if (mb->get_button_index() == BUTTON_RIGHT && mb->is_pressed()) {
if (uv_drag) {
uv_drag = false;
node->set_uv(uv_prev);
uv_edit_draw->update();
}
} else if (mb->get_button_index() == BUTTON_WHEEL_UP && mb->is_pressed()) {
uv_zoom->set_value(uv_zoom->get_value() / (1 - (0.1 * mb->get_factor())));
} else if (mb->get_button_index() == BUTTON_WHEEL_DOWN && mb->is_pressed()) {
uv_zoom->set_value(uv_zoom->get_value() * (1 - (0.1 * mb->get_factor())));
}
}
Ref<InputEventMouseMotion> mm = p_input;
if (mm.is_valid()) {
if (mm->get_button_mask() & BUTTON_MASK_MIDDLE || Input::get_singleton()->is_key_pressed(KEY_SPACE)) {
Vector2 drag(mm->get_relative().x, mm->get_relative().y);
uv_hscroll->set_value(uv_hscroll->get_value() - drag.x);
uv_vscroll->set_value(uv_vscroll->get_value() - drag.y);
} else if (uv_drag) {
Vector2 uv_drag_to = mm->get_position();
Vector2 drag = mtx.affine_inverse().xform(uv_drag_to) - mtx.affine_inverse().xform(uv_drag_from);
switch (uv_move_current) {
case UV_MODE_EDIT_POINT: {
PoolVector<Vector2> uv_new = uv_prev;
uv_new.set(uv_drag_index, uv_new[uv_drag_index] + drag);
node->set_uv(uv_new);
} break;
case UV_MODE_MOVE: {
PoolVector<Vector2> uv_new = uv_prev;
for (int i = 0; i < uv_new.size(); i++)
uv_new.set(i, uv_new[i] + drag);
node->set_uv(uv_new);
} break;
case UV_MODE_ROTATE: {
Vector2 center;
PoolVector<Vector2> uv_new = uv_prev;
for (int i = 0; i < uv_new.size(); i++)
center += uv_prev[i];
center /= uv_new.size();
float angle = (uv_drag_from - mtx.xform(center)).normalized().angle_to((uv_drag_to - mtx.xform(center)).normalized());
for (int i = 0; i < uv_new.size(); i++) {
Vector2 rel = uv_prev[i] - center;
rel = rel.rotated(angle);
uv_new.set(i, center + rel);
}
node->set_uv(uv_new);
} break;
case UV_MODE_SCALE: {
Vector2 center;
PoolVector<Vector2> uv_new = uv_prev;
for (int i = 0; i < uv_new.size(); i++)
center += uv_prev[i];
center /= uv_new.size();
float from_dist = uv_drag_from.distance_to(mtx.xform(center));
float to_dist = uv_drag_to.distance_to(mtx.xform(center));
if (from_dist < 2)
break;
float scale = to_dist / from_dist;
for (int i = 0; i < uv_new.size(); i++) {
Vector2 rel = uv_prev[i] - center;
rel = rel * scale;
uv_new.set(i, center + rel);
}
node->set_uv(uv_new);
} break;
}
uv_edit_draw->update();
}
}
}
void Polygon2DEditor::_uv_scroll_changed(float) {
if (updating_uv_scroll)
return;
uv_draw_ofs.x = uv_hscroll->get_value();
uv_draw_ofs.y = uv_vscroll->get_value();
uv_draw_zoom = uv_zoom->get_value();
uv_edit_draw->update();
}
void Polygon2DEditor::_uv_draw() {
Ref<Texture> base_tex = node->get_texture();
if (base_tex.is_null())
return;
Transform2D mtx;
mtx.elements[2] = -uv_draw_ofs;
mtx.scale_basis(Vector2(uv_draw_zoom, uv_draw_zoom));
VS::get_singleton()->canvas_item_add_set_transform(uv_edit_draw->get_canvas_item(), mtx);
uv_edit_draw->draw_texture(base_tex, Point2());
VS::get_singleton()->canvas_item_add_set_transform(uv_edit_draw->get_canvas_item(), Transform2D());
if (snap_show_grid) {
Size2 s = uv_edit_draw->get_size();
int last_cell = 0;
if (snap_step.x != 0) {
for (int i = 0; i < s.width; i++) {
int cell = Math::fast_ftoi(Math::floor((mtx.affine_inverse().xform(Vector2(i, 0)).x - snap_offset.x) / snap_step.x));
if (i == 0)
last_cell = cell;
if (last_cell != cell)
uv_edit_draw->draw_line(Point2(i, 0), Point2(i, s.height), Color(0.3, 0.7, 1, 0.3));
last_cell = cell;
}
}
if (snap_step.y != 0) {
for (int i = 0; i < s.height; i++) {
int cell = Math::fast_ftoi(Math::floor((mtx.affine_inverse().xform(Vector2(0, i)).y - snap_offset.y) / snap_step.y));
if (i == 0)
last_cell = cell;
if (last_cell != cell)
uv_edit_draw->draw_line(Point2(0, i), Point2(s.width, i), Color(0.3, 0.7, 1, 0.3));
last_cell = cell;
}
}
}
PoolVector<Vector2> uvs = node->get_uv();
Ref<Texture> handle = get_icon("EditorHandle", "EditorIcons");
Rect2 rect(Point2(), mtx.basis_xform(base_tex->get_size()));
rect.expand_to(mtx.basis_xform(uv_edit_draw->get_size()));
for (int i = 0; i < uvs.size(); i++) {
int next = (i + 1) % uvs.size();
uv_edit_draw->draw_line(mtx.xform(uvs[i]), mtx.xform(uvs[next]), Color(0.9, 0.5, 0.5), 2);
uv_edit_draw->draw_texture(handle, mtx.xform(uvs[i]) - handle->get_size() * 0.5);
rect.expand_to(mtx.basis_xform(uvs[i]));
}
rect = rect.grow(200);
updating_uv_scroll = true;
uv_hscroll->set_min(rect.position.x);
uv_hscroll->set_max(rect.position.x + rect.size.x);
uv_hscroll->set_page(uv_edit_draw->get_size().x);
uv_hscroll->set_value(uv_draw_ofs.x);
uv_hscroll->set_step(0.001);
uv_vscroll->set_min(rect.position.y);
uv_vscroll->set_max(rect.position.y + rect.size.y);
uv_vscroll->set_page(uv_edit_draw->get_size().y);
uv_vscroll->set_value(uv_draw_ofs.y);
uv_vscroll->set_step(0.001);
updating_uv_scroll = false;
}
void Polygon2DEditor::edit(Node *p_collision_polygon) {
if (!canvas_item_editor) {
canvas_item_editor = CanvasItemEditor::get_singleton();
}
if (p_collision_polygon) {
node = Object::cast_to<Polygon2D>(p_collision_polygon);
//Enable the pencil tool if the polygon is empty
if (node->get_polygon().size() == 0) {
_menu_option(MODE_CREATE);
}
if (!canvas_item_editor->get_viewport_control()->is_connected("draw", this, "_canvas_draw"))
canvas_item_editor->get_viewport_control()->connect("draw", this, "_canvas_draw");
wip.clear();
wip_active = false;
edited_point = -1;
} else {
node = NULL;
if (canvas_item_editor->get_viewport_control()->is_connected("draw", this, "_canvas_draw"))
canvas_item_editor->get_viewport_control()->disconnect("draw", this, "_canvas_draw");
}
}
void Polygon2DEditor::_bind_methods() {
ClassDB::bind_method(D_METHOD("_menu_option"), &Polygon2DEditor::_menu_option);
ClassDB::bind_method(D_METHOD("_canvas_draw"), &Polygon2DEditor::_canvas_draw);
ClassDB::bind_method(D_METHOD("_uv_mode"), &Polygon2DEditor::_uv_mode);
ClassDB::bind_method(D_METHOD("_uv_draw"), &Polygon2DEditor::_uv_draw);
ClassDB::bind_method(D_METHOD("_uv_input"), &Polygon2DEditor::_uv_input);
ClassDB::bind_method(D_METHOD("_uv_scroll_changed"), &Polygon2DEditor::_uv_scroll_changed);
ClassDB::bind_method(D_METHOD("_node_removed"), &Polygon2DEditor::_node_removed);
ClassDB::bind_method(D_METHOD("_set_use_snap"), &Polygon2DEditor::_set_use_snap);
ClassDB::bind_method(D_METHOD("_set_show_grid"), &Polygon2DEditor::_set_show_grid);
ClassDB::bind_method(D_METHOD("_set_snap_off_x"), &Polygon2DEditor::_set_snap_off_x);
ClassDB::bind_method(D_METHOD("_set_snap_off_y"), &Polygon2DEditor::_set_snap_off_y);
ClassDB::bind_method(D_METHOD("_set_snap_step_x"), &Polygon2DEditor::_set_snap_step_x);
ClassDB::bind_method(D_METHOD("_set_snap_step_y"), &Polygon2DEditor::_set_snap_step_y);
}
inline float _snap_scalar(float p_offset, float p_step, float p_target) {
return p_step != 0 ? Math::stepify(p_target - p_offset, p_step) + p_offset : p_target;
}
Vector2 Polygon2DEditor::snap_point(Vector2 p_target) const {
if (use_snap) {
p_target.x = _snap_scalar(snap_offset.x * uv_draw_zoom - uv_draw_ofs.x, snap_step.x * uv_draw_zoom, p_target.x);
p_target.y = _snap_scalar(snap_offset.y * uv_draw_zoom - uv_draw_ofs.y, snap_step.y * uv_draw_zoom, p_target.y);
}
return p_target;
}
Polygon2DEditor::Polygon2DEditor(EditorNode *p_editor) {
node = NULL;
canvas_item_editor = NULL;
editor = p_editor;
undo_redo = editor->get_undo_redo();
snap_step = Vector2(10, 10);
use_snap = false;
snap_show_grid = false;
add_child(memnew(VSeparator));
button_create = memnew(ToolButton);
add_child(button_create);
button_create->connect("pressed", this, "_menu_option", varray(MODE_CREATE));
button_create->set_toggle_mode(true);
button_edit = memnew(ToolButton);
add_child(button_edit);
button_edit->connect("pressed", this, "_menu_option", varray(MODE_EDIT));
button_edit->set_toggle_mode(true);
button_uv = memnew(ToolButton);
add_child(button_uv);
button_uv->connect("pressed", this, "_menu_option", varray(MODE_EDIT_UV));
mode = MODE_EDIT;
wip_active = false;
uv_mode = UV_MODE_EDIT_POINT;
uv_edit = memnew(AcceptDialog);
add_child(uv_edit);
uv_edit->set_title(TTR("Polygon 2D UV Editor"));
uv_edit->set_self_modulate(Color(1, 1, 1, 0.9));
VBoxContainer *uv_main_vb = memnew(VBoxContainer);
uv_edit->add_child(uv_main_vb);
//uv_edit->set_child_rect(uv_main_vb);
HBoxContainer *uv_mode_hb = memnew(HBoxContainer);
uv_main_vb->add_child(uv_mode_hb);
for (int i = 0; i < UV_MODE_MAX; i++) {
uv_button[i] = memnew(ToolButton);
uv_button[i]->set_toggle_mode(true);
uv_mode_hb->add_child(uv_button[i]);
uv_button[i]->connect("pressed", this, "_uv_mode", varray(i));
uv_button[i]->set_focus_mode(FOCUS_NONE);
}
uv_button[0]->set_tooltip(TTR("Move Point") + "\n" + TTR("Ctrl: Rotate") + "\n" + TTR("Shift: Move All") + "\n" + TTR("Shift+Ctrl: Scale"));
uv_button[1]->set_tooltip(TTR("Move Polygon"));
uv_button[2]->set_tooltip(TTR("Rotate Polygon"));
uv_button[3]->set_tooltip(TTR("Scale Polygon"));
uv_button[0]->set_pressed(true);
HBoxContainer *uv_main_hb = memnew(HBoxContainer);
uv_main_vb->add_child(uv_main_hb);
uv_edit_draw = memnew(Control);
uv_main_hb->add_child(uv_edit_draw);
uv_main_hb->set_v_size_flags(SIZE_EXPAND_FILL);
uv_edit_draw->set_h_size_flags(SIZE_EXPAND_FILL);
uv_menu = memnew(MenuButton);
uv_mode_hb->add_child(uv_menu);
uv_menu->set_text(TTR("Edit"));
uv_menu->get_popup()->add_item(TTR("Polygon->UV"), UVEDIT_POLYGON_TO_UV);
uv_menu->get_popup()->add_item(TTR("UV->Polygon"), UVEDIT_UV_TO_POLYGON);
uv_menu->get_popup()->add_separator();
uv_menu->get_popup()->add_item(TTR("Clear UV"), UVEDIT_UV_CLEAR);
uv_menu->get_popup()->connect("id_pressed", this, "_menu_option");
uv_mode_hb->add_child(memnew(VSeparator));
b_snap_enable = memnew(ToolButton);
uv_mode_hb->add_child(b_snap_enable);
b_snap_enable->set_text(TTR("Snap"));
b_snap_enable->set_focus_mode(FOCUS_NONE);
b_snap_enable->set_toggle_mode(true);
b_snap_enable->set_pressed(use_snap);
b_snap_enable->set_tooltip(TTR("Enable Snap"));
b_snap_enable->connect("toggled", this, "_set_use_snap");
b_snap_grid = memnew(ToolButton);
uv_mode_hb->add_child(b_snap_grid);
b_snap_grid->set_text(TTR("Grid"));
b_snap_grid->set_focus_mode(FOCUS_NONE);
b_snap_grid->set_toggle_mode(true);
b_snap_grid->set_pressed(snap_show_grid);
b_snap_grid->set_tooltip(TTR("Show Grid"));
b_snap_grid->connect("toggled", this, "_set_show_grid");
uv_mode_hb->add_child(memnew(VSeparator));
uv_mode_hb->add_child(memnew(Label(TTR("Grid Offset:"))));
SpinBox *sb_off_x = memnew(SpinBox);
sb_off_x->set_min(-256);
sb_off_x->set_max(256);
sb_off_x->set_step(1);
sb_off_x->set_value(snap_offset.x);
sb_off_x->set_suffix("px");
sb_off_x->connect("value_changed", this, "_set_snap_off_x");
uv_mode_hb->add_child(sb_off_x);
SpinBox *sb_off_y = memnew(SpinBox);
sb_off_y->set_min(-256);
sb_off_y->set_max(256);
sb_off_y->set_step(1);
sb_off_y->set_value(snap_offset.y);
sb_off_y->set_suffix("px");
sb_off_y->connect("value_changed", this, "_set_snap_off_y");
uv_mode_hb->add_child(sb_off_y);
uv_mode_hb->add_child(memnew(VSeparator));
uv_mode_hb->add_child(memnew(Label(TTR("Grid Step:"))));
SpinBox *sb_step_x = memnew(SpinBox);
sb_step_x->set_min(-256);
sb_step_x->set_max(256);
sb_step_x->set_step(1);
sb_step_x->set_value(snap_step.x);
sb_step_x->set_suffix("px");
sb_step_x->connect("value_changed", this, "_set_snap_step_x");
uv_mode_hb->add_child(sb_step_x);
SpinBox *sb_step_y = memnew(SpinBox);
sb_step_y->set_min(-256);
sb_step_y->set_max(256);
sb_step_y->set_step(1);
sb_step_y->set_value(snap_step.y);
sb_step_y->set_suffix("px");
sb_step_y->connect("value_changed", this, "_set_snap_step_y");
uv_mode_hb->add_child(sb_step_y);
uv_mode_hb->add_child(memnew(VSeparator));
uv_icon_zoom = memnew(TextureRect);
uv_mode_hb->add_child(uv_icon_zoom);
uv_zoom = memnew(HSlider);
uv_zoom->set_min(0.01);
uv_zoom->set_max(4);
uv_zoom->set_value(1);
uv_zoom->set_step(0.01);
uv_mode_hb->add_child(uv_zoom);
uv_zoom->set_custom_minimum_size(Size2(200, 0));
uv_zoom_value = memnew(SpinBox);
uv_zoom->share(uv_zoom_value);
uv_zoom_value->set_custom_minimum_size(Size2(50, 0));
uv_mode_hb->add_child(uv_zoom_value);
uv_zoom->connect("value_changed", this, "_uv_scroll_changed");
uv_vscroll = memnew(VScrollBar);
uv_main_hb->add_child(uv_vscroll);
uv_vscroll->connect("value_changed", this, "_uv_scroll_changed");
uv_hscroll = memnew(HScrollBar);
uv_main_vb->add_child(uv_hscroll);
uv_hscroll->connect("value_changed", this, "_uv_scroll_changed");
uv_edit_draw->connect("draw", this, "_uv_draw");
uv_edit_draw->connect("gui_input", this, "_uv_input");
uv_draw_zoom = 1.0;
uv_drag_index = -1;
uv_drag = false;
updating_uv_scroll = false;
error = memnew(AcceptDialog);
add_child(error);
uv_edit_draw->set_clip_contents(true);
}
void Polygon2DEditorPlugin::edit(Object *p_object) {
collision_polygon_editor->edit(Object::cast_to<Node>(p_object));
}
bool Polygon2DEditorPlugin::handles(Object *p_object) const {
return p_object->is_class("Polygon2D");
}
void Polygon2DEditorPlugin::make_visible(bool p_visible) {
if (p_visible) {
collision_polygon_editor->show();
} else {
collision_polygon_editor->hide();
collision_polygon_editor->edit(NULL);
}
}
Polygon2DEditorPlugin::Polygon2DEditorPlugin(EditorNode *p_node) {
editor = p_node;
collision_polygon_editor = memnew(Polygon2DEditor(p_node));
CanvasItemEditor::get_singleton()->add_control_to_menu_panel(collision_polygon_editor);
collision_polygon_editor->hide();
}
Polygon2DEditorPlugin::~Polygon2DEditorPlugin() {
}
|
#ifndef VARIANT_VARIANT_HPP
#define VARIANT_VARIANT_HPP
#include <stdexcept>
#include <type_traits>
#include <limits>
#include <algorithm>
namespace util::detail {
using index_t = size_t;
}
namespace util {
inline constexpr detail::index_t variant_npos = std::numeric_limits<decltype(variant_npos)>::max();
}
namespace util::detail {
template<typename ...Ts>
constexpr size_t max_size = std::max({sizeof(Ts)...});
template<typename ...Ts>
constexpr size_t max_align = std::max({alignof(Ts)...});
template<index_t I, typename U>
constexpr index_t find_same_type_index() {
return variant_npos;
}
template<index_t I, typename U, typename T, typename ...Ts>
constexpr index_t find_same_type_index() {
if constexpr (std::is_same_v<U, T>) {
return I;
} else {
return find_same_type_index<I + 1, U, Ts...>();
}
}
template<typename U, typename ...Ts>
constexpr index_t index_of_same() {
return find_same_type_index<0, U, Ts...>();
}
template<typename U, typename ...Ts>
constexpr bool contains_same() {
return index_of_same<U, Ts...>() != variant_npos;
}
template<index_t I, typename U>
constexpr index_t find_convertible_index() {
return variant_npos;
}
template<index_t I, typename U, typename T, typename ...Ts>
constexpr index_t find_convertible_index() {
if constexpr (std::is_convertible_v<U, T>) {
return I;
} else {
return find_convertible_index<I + 1, U, Ts...>();
}
}
template<typename U, typename ...Ts>
constexpr index_t index_of_convertible() {
return find_convertible_index<0, U, Ts...>();
}
template<typename U, typename ...Ts>
constexpr bool contains_convertible() {
return index_of_convertible<U, Ts...>() != variant_npos;
}
template<index_t I, typename ...Ts>
using type_at = std::tuple_element_t<I, std::tuple<Ts...>>;
template<typename ...Ts>
inline constexpr size_t variadic_count = sizeof...(Ts);
template<typename U, typename ...Ts>
constexpr index_t index_of_init() {
if constexpr (index_of_same<U, Ts...>() != variant_npos) {
return index_of_same<U, Ts...>();
}
return index_of_convertible<U, Ts...>();
}
template<typename U, typename ...Ts>
constexpr bool contains_init() {
return contains_same<U, Ts...>() || contains_convertible<U, Ts...>();
}
template<typename U, typename ...Ts>
using selected_type = detail::type_at<detail::index_of_init<U, Ts...>(), Ts...>;
}
namespace util::detail::visitors {
struct clear_visitor {
template<typename T>
std::enable_if_t<!std::is_trivially_destructible_v<T>> operator()(const T &object) {
object.~T();
}
template<typename T>
std::enable_if_t<std::is_trivially_destructible_v<T>> operator()(const T &) {
}
void operator()() {}
};
template<typename ...Ts>
class copy_visitor;
template<typename ...Ts>
class move_visitor;
}
namespace util {
struct bad_get : std::runtime_error {
using runtime_error::runtime_error;
};
template<typename Visitor, typename Variant>
void apply_visitor(Visitor &&visitor, Variant &&variant);
template<typename ...Types>
struct variant final {
template<typename ...Ts>
friend
class detail::visitors::copy_visitor;
template<typename ...Ts>
friend
class detail::visitors::move_visitor;
using index_t = detail::index_t;
using storage_t = std::aligned_storage_t<detail::max_size<Types...>, detail::max_align<Types...>>;
static constexpr size_t arg_count = detail::variadic_count<Types...>;
variant() : _type_index(variant_npos) {}
variant(const variant &var);
variant(variant &&var) noexcept(((std::is_nothrow_move_constructible_v<Types> &&
std::is_nothrow_move_assignable_v<Types>) && ...));
template<class U, typename = std::enable_if_t<detail::contains_init<U, Types...>()>, typename R = detail::selected_type<U, Types...>>
variant(U &&value) noexcept(std::is_nothrow_assignable_v<R &, U> && std::is_nothrow_constructible_v<R, U>)
: _type_index(detail::index_of_init<U, Types...>()) {
new(&_storage) R(std::forward<U>(value));
}
~variant() {
clear();
}
variant &operator=(const variant &var) {
if (this != &var) {
variant other{var};
other.swap(*this);
}
return *this;
}
variant &operator=(variant &&var) noexcept(((std::is_nothrow_move_constructible_v<Types> &&
std::is_nothrow_move_assignable_v<Types>) && ...)) {
if (this != &var) {
clear();
apply_visitor(detail::visitors::move_visitor(std::move(var), *this), var);
_type_index = var._type_index;
}
return *this;
}
template<class U, typename = std::enable_if_t<detail::contains_init<U, Types...>()>, typename R = detail::selected_type<U, Types...>>
variant &
operator=(U &&value) noexcept(std::is_nothrow_assignable_v<R &, U> && std::is_nothrow_constructible_v<R, U>) {
variant var(std::forward<U>(value));
clear();
swap(var);
return *this;
}
void swap(variant &other) noexcept(((std::is_nothrow_move_constructible_v<Types> &&
std::is_nothrow_move_assignable_v<Types>) && ...));
[[nodiscard]] bool empty() const { return index() == variant_npos; }
[[nodiscard]] index_t index() const { return _type_index; }
void clear() {
apply_visitor(detail::visitors::clear_visitor(), *this);
_type_index = variant_npos;
}
template<typename U, typename ...Ts>
friend const U *get(const variant<Ts...> *var);
private:
index_t _type_index = variant_npos;
storage_t _storage;
};
template<typename U, typename ...Ts>
const U *get(const variant<Ts...> *var) {
if (!var || var->empty())
return nullptr;
constexpr detail::index_t type_index = detail::index_of_same<std::decay_t<U>, Ts...>();
if (type_index != var->index())
return nullptr;
const U *value = reinterpret_cast<const U *>(&var->_storage);
return value;
}
template<typename U, typename ...Ts>
U *get(variant<Ts...> *var) {
return const_cast<U *>(get<U>(const_cast<const variant<Ts...> *>(var)));
}
template<typename U, typename ...Ts>
const U &get(const variant<Ts...> &var) {
const U *value = get<U>(&var);
if (!value)
throw bad_get("");
return *value;
}
template<typename U, typename ...Ts>
U &get(variant<Ts...> &var) {
U *value = get<U>(&var);
if (!value)
throw bad_get("");
return *value;
}
template<typename U, typename ...Ts>
U &&get(variant<Ts...> &&var) {
U *value = get<U>(&var);
if (!value)
throw bad_get("");
return std::move(*value);
}
template<detail::index_t I, typename ...Ts>
const detail::type_at<I, Ts...> *get(const variant<Ts...> *var) {
using U = detail::type_at<I, Ts...>;
return get<const U>(var);
}
template<detail::index_t I, typename ...Ts>
detail::type_at<I, Ts...> *get(variant<Ts...> *var) {
using U = detail::type_at<I, Ts...>;
return get<U>(var);
}
template<detail::index_t I, typename ...Ts>
const detail::type_at<I, Ts...> &get(const variant<Ts...> &var) {
using U = detail::type_at<I, Ts...>;
return get<U>(var);
}
template<detail::index_t I, typename ...Ts>
detail::type_at<I, Ts...> &get(variant<Ts...> &var) {
using U = detail::type_at<I, Ts...>;
return get<U>(var);
}
template<detail::index_t I, typename ...Ts>
detail::type_at<I, Ts...> &&get(variant<Ts...> &&var) {
using U = detail::type_at<I, Ts...>;
return get<U>(std::move(var));
}
template<typename ...Ts>
void swap(variant<Ts...> &lhs, variant<Ts...> &rhs) {
lhs.swap(rhs);
}
}
namespace util::detail {
template<typename Visitor, typename Variant, size_t... Indexes>
void apply_visitor_helper(Visitor &&visitor, Variant &&variant, std::index_sequence<Indexes...> &&) {
((get<Indexes>(&variant) ? visitor(get<Indexes>(std::forward<Variant>(variant))) : void()), ...);
}
}
namespace util {
template<typename Visitor, typename Variant>
void apply_visitor(Visitor &&visitor, Variant &&variant) {
using variant_t = std::decay_t<Variant>;
if (variant.empty()) {
visitor();
} else {
detail::apply_visitor_helper(
std::forward<Visitor>(visitor),
std::forward<Variant>(variant),
std::make_index_sequence<variant_t::arg_count>{}
);
}
}
}
namespace util::detail::visitors {
template<typename ...Ts>
class copy_visitor {
using variant_t = variant<Ts...>;
public:
copy_visitor(const variant_t &source, variant_t &destination) : source(source), destination(destination) {}
template<class T>
void operator()(const T &source_object) {
new(&destination._storage) T(source_object);
}
void operator()() {}
private:
const variant_t &source;
variant_t &destination;
};
template<typename ...Ts>
class move_visitor {
using variant_t = variant<Ts...>;
public:
move_visitor(variant_t &&source, variant_t &destination) : source(std::move(source)),
destination(destination) {}
template<class T>
void operator()(T &&source_object) {
using U = std::decay_t<T>;
new(&destination._storage) U(std::move(source_object));
}
void operator()() {}
private:
variant_t &&source;
variant_t &destination;
};
template<typename ...Ts>
class swap_lhs_visitor {
using variant_t = variant<Ts...>;
template<typename V>
struct swap_rhs_visitor {
swap_rhs_visitor(V &rhsValue) : _lhs_value(rhsValue) {}
template<typename T>
void operator()(T &rhs_object) {
if constexpr (std::is_same_v<V, T>) {
std::swap(_lhs_value, rhs_object);
}
}
void operator()() {}
private:
V &_lhs_value;
};
public:
swap_lhs_visitor(variant_t &lhs, variant_t &rhs) : lhs(lhs), rhs(rhs) {}
template<class T>
void operator()(T &lhs_object) {
swap_rhs_visitor<T> visitor(lhs_object);
apply_visitor(visitor, rhs);
}
void operator()() {}
private:
variant_t &lhs;
variant_t &rhs;
};
}
namespace util {
template<typename ...Ts>
variant<Ts...>::variant(const variant &var): _type_index(var._type_index) {
apply_visitor(detail::visitors::copy_visitor(var, *this), var);
}
template<typename ...Types>
variant<Types...>::variant(variant &&var) noexcept(((std::is_nothrow_move_constructible_v<Types> &&
std::is_nothrow_move_assignable_v<Types>) && ...))
: _type_index(var._type_index) {
apply_visitor(detail::visitors::move_visitor(std::move(var), *this), var);
var._type_index = variant_npos;
}
template<typename ...Types>
void variant<Types...>::swap(variant &other) noexcept(((std::is_nothrow_move_constructible_v<Types> &&
std::is_nothrow_move_assignable_v<Types>) && ...)) {
if (empty() && other.empty())
return;
if (_type_index == other._type_index) {
detail::visitors::swap_lhs_visitor visitor(*this, other);
apply_visitor(visitor, *this);
} else {
std::swap(*this, other);
}
}
}
#endif //VARIANT_VARIANT_HPP
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.