hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4154f0845f18ec1e6c102c2171fd1da3a8b4d1d9 | 1,187 | cpp | C++ | src/unitTest/rootNodeTest/piecewiseLR_test.cpp | JiaoYiZhang/learned_index | bc8028edcc8c63609bbad7b9c591704fbca838bb | [
"MIT"
] | 3 | 2021-03-13T07:07:51.000Z | 2021-11-17T10:36:57.000Z | src/unitTest/rootNodeTest/piecewiseLR_test.cpp | JiaoYiZhang/learned_index | bc8028edcc8c63609bbad7b9c591704fbca838bb | [
"MIT"
] | null | null | null | src/unitTest/rootNodeTest/piecewiseLR_test.cpp | JiaoYiZhang/learned_index | bc8028edcc8c63609bbad7b9c591704fbca838bb | [
"MIT"
] | null | null | null | /**
* @file piecewiseLR_test.cpp
* @author Jiaoyi
* @brief
* @version 0.1
* @date 2021-11-03
*
* @copyright Copyright (c) 2021
*
*/
#include "../../include/nodes/rootNode/trainModel/piecewiseLR.h"
#include "../../experiment/dataset/lognormal_distribution.h"
#include "gtest/gtest.h"
std::vector<std::pair<double, double>> initData;
std::vector<std::pair<double, double>> insertData;
std::vector<std::pair<double, double>> testInsert;
const int kChildNum = 512;
const int kTestMaxValue = kMaxValue;
LognormalDataset logData(0.9);
PiecewiseLR<DataVecType, double> model;
TEST(TestTrain, TrainPLRModel) {
logData.GenerateDataset(&initData, &insertData, &testInsert);
model.maxChildIdx = kChildNum - 1;
model.Train(initData);
EXPECT_EQ(kChildNum - 1, model.maxChildIdx);
}
TEST(TestPredictInitData, PredictInitData) {
for (int i = 0; i < initData.size(); i++) {
int p = model.Predict(initData[i].first);
EXPECT_GE(p, 0);
EXPECT_LT(p, kChildNum);
}
}
TEST(TestPredictInsertData, PredictInsertData) {
for (int i = 0; i < insertData.size(); i++) {
int p = model.Predict(insertData[i].first);
EXPECT_GE(p, 0);
EXPECT_LT(p, kChildNum);
}
} | 24.729167 | 64 | 0.69166 | JiaoYiZhang |
41567abfdebadc704807cf4e935b66d0d9c258f7 | 6,703 | cc | C++ | GeneratorInterface/GenFilters/src/STFilter.cc | NTrevisani/cmssw | a212a27526f34eb9507cf8b875c93896e6544781 | [
"Apache-2.0"
] | 1 | 2020-02-07T11:20:02.000Z | 2020-02-07T11:20:02.000Z | GeneratorInterface/GenFilters/src/STFilter.cc | NTrevisani/cmssw | a212a27526f34eb9507cf8b875c93896e6544781 | [
"Apache-2.0"
] | 7 | 2016-07-17T02:34:54.000Z | 2019-08-13T07:58:37.000Z | GeneratorInterface/GenFilters/src/STFilter.cc | NTrevisani/cmssw | a212a27526f34eb9507cf8b875c93896e6544781 | [
"Apache-2.0"
] | 2 | 2019-09-27T08:33:22.000Z | 2019-11-14T10:52:30.000Z | // -*- C++ -*-
// Package: STFilter
// Class: STFilter
/**\class STFilter STFilter.cc MyEDFilter/STFilter/src/STFilter.cc
Description:
** used for single top t-channel events generated with MadEvent
and matched the "Karlsruhe way"
** filter on 2->2 process events, where the crucial candidate (the 2nd b quark)
is not available until parton showering is done
** filter criterion: transverse momentum of 2nd b quark "pT < pTMax" -> event accepted!
** How-To: include STFilter.cfg in your .cfg, replace pTMax by the desired value,
include module "STFilter" in outpath
Implementation:
<Notes on implementation>
*/
// Original Author: Julia Weinelt
// Created: Wed Jan 23 15:12:46 CET 2008
#include <memory>
#include "FWCore/MessageLogger/interface/MessageLogger.h"
#include "GeneratorInterface/GenFilters/interface/STFilter.h"
#include "SimDataFormats/GeneratorProducts/interface/HepMCProduct.h"
#include "HepMC/GenEvent.h"
STFilter::STFilter(const edm::ParameterSet& iConfig)
: hepMCProductTag_(
iConfig.getUntrackedParameter<edm::InputTag>("hepMCProductTag", edm::InputTag("generator", "unsmeared"))) {
pTMax_ = iConfig.getParameter<double>("pTMax");
edm::LogInfo("SingleTopMatchingFilter") << "+++ maximum pt of associated-b pTMax = " << pTMax_;
DEBUGLVL = iConfig.getUntrackedParameter<int>("debuglvl", 0); // get debug level
input_events = 0;
accepted_events = 0; // counters
m_produceHistos = iConfig.getParameter<bool>("produceHistos"); // produce histograms?
fOutputFileName =
iConfig.getUntrackedParameter<std::string>("histOutFile"); // get name of output file with histograms
conf_ = iConfig;
}
STFilter::~STFilter() {}
bool STFilter::filter(edm::Event& iEvent, const edm::EventSetup& iSetup) {
using namespace edm;
bool accEvt = false;
bool lo = false;
int secBcount = 0;
double pTSecB = 100;
double etaSecB = 100;
++input_events;
Handle<HepMCProduct> evt;
iEvent.getByLabel(hepMCProductTag_, evt);
const HepMC::GenEvent* myEvt = evt->GetEvent(); // GET EVENT FROM HANDLE
bool bQuarksOpposite = false;
for (HepMC::GenEvent::particle_const_iterator i = myEvt->particles_begin(); (*i)->status() == 3;
++i) { // abort after status 3 particles
// logic:
// - in 2->2 matrix elements, the incoming (top production)
// b quark and the outgoing (top decay) b quark have same sign,
// so we flip the bQuarksOpposite flag twice -> false
// (opposite-sign b quark comes from the shower and has status 2)
// - in 2->3 matrix elements, we have two outgoing b quarks with status
// 3 and opposite signs -> true
if ((*i)->pdg_id() == -5)
bQuarksOpposite = !bQuarksOpposite;
}
// ---- 22 or 23? ----
if (!bQuarksOpposite) // 22
lo = true;
else
accEvt = true; // 23
// ---- filter only 22 events ----
if (lo) {
for (HepMC::GenEvent::particle_const_iterator p = myEvt->particles_begin(); p != myEvt->particles_end(); ++p) {
// ---- look in shower for 2nd b quark ----
if ((*p)->status() == 2 && abs((*p)->pdg_id()) == 5) {
// ---- if b quark is found, loop over its parents ----
for (HepMC::GenVertex::particle_iterator m = (*p)->production_vertex()->particles_begin(HepMC::parents);
m != (*p)->production_vertex()->particles_end(HepMC::parents);
++m) {
// ---- found 2ndb-candidate in shower ---- // ---- check mother of this candidate ----
if (abs((*m)->barcode()) < 5) {
if (secBcount == 1)
break;
secBcount++;
pTSecB = (*p)->operator HepMC::FourVector().perp();
etaSecB = (*p)->operator HepMC::FourVector().eta();
}
}
}
}
if (pTSecB < pTMax_)
accEvt = true;
// fill histos if requested
if (m_produceHistos) {
hbPt->Fill(pTSecB);
hbEta->Fill(etaSecB);
if (accEvt) {
hbPtFiltered->Fill(pTSecB);
hbEtaFiltered->Fill(etaSecB);
}
}
}
if (accEvt)
++accepted_events;
return accEvt;
}
void STFilter::beginJob() {
if (m_produceHistos) { // initialize histogram output file
edm::ParameterSet Parameters;
edm::LogInfo("SingleTopMatchingFilter)")
<< "beginJob : creating histogram file: " << fOutputFileName.c_str() << std::endl;
hOutputFile = new TFile(fOutputFileName.c_str(), "RECREATE");
hOutputFile->cd();
// book histograms
Parameters = conf_.getParameter<edm::ParameterSet>("TH1bPt");
hbPt = new TH1D("bPt",
"Pt of 2nd b quark",
Parameters.getParameter<int32_t>("Nbinx"),
Parameters.getParameter<double>("xmin"),
Parameters.getParameter<double>("xmax"));
Parameters = conf_.getParameter<edm::ParameterSet>("TH1bEta");
hbEta = new TH1D("bEta",
"Eta of 2nd b quark",
Parameters.getParameter<int32_t>("Nbinx"),
Parameters.getParameter<double>("xmin"),
Parameters.getParameter<double>("xmax"));
Parameters = conf_.getParameter<edm::ParameterSet>("TH1bPtFiltered");
hbPtFiltered = new TH1D("bPtFiltered",
"Pt of 2nd b quark filtered",
Parameters.getParameter<int32_t>("Nbinx"),
Parameters.getParameter<double>("xmin"),
Parameters.getParameter<double>("xmax"));
Parameters = conf_.getParameter<edm::ParameterSet>("TH1bEtaFiltered");
hbEtaFiltered = new TH1D("bEtaFiltered",
"Eta of 2nd b quark filtered",
Parameters.getParameter<int32_t>("Nbinx"),
Parameters.getParameter<double>("xmin"),
Parameters.getParameter<double>("xmax"));
}
}
void STFilter::endJob() {
if (m_produceHistos) {
hOutputFile->cd();
hbPt->Write();
hbEta->Write();
hbPtFiltered->Write();
hbEtaFiltered->Write();
hOutputFile->Write();
hOutputFile->Close();
} // Write out histograms to file, then close it
double fraction = (double)accepted_events / (double)input_events;
double percent = 100. * fraction;
double error = 100. * sqrt(fraction * (1 - fraction) / (double)input_events);
std::cout << "STFilter ++ accepted_events/input_events = " << accepted_events << "/" << input_events << " = "
<< fraction << std::endl;
std::cout << "STFilter ++ efficiency = " << percent << " % +/- " << error << " %" << std::endl;
}
//DEFINE_FWK_MODULE(STFilter);
| 38.97093 | 117 | 0.60913 | NTrevisani |
415704f4b50e4fbda53e66a4c20d451e2d2493ec | 933 | cpp | C++ | luogu_1378/luogu_1378.cpp | skyfackr/luogu_personal_cppcode | b59af9839745d65091e6c01cddf53e5bb6fb274a | [
"BSD-3-Clause"
] | null | null | null | luogu_1378/luogu_1378.cpp | skyfackr/luogu_personal_cppcode | b59af9839745d65091e6c01cddf53e5bb6fb274a | [
"BSD-3-Clause"
] | null | null | null | luogu_1378/luogu_1378.cpp | skyfackr/luogu_personal_cppcode | b59af9839745d65091e6c01cddf53e5bb6fb274a | [
"BSD-3-Clause"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
double allsquare;
double beginx,beginy,endx,endy,ans;
bool bj[10];
int n,i,j,k;
const double pi=3.1415926535;
struct oils
{
double x,y;
double r;
} oil[10];
void rget(int i)
{
oil[i].r=min(min(abs(oil[i].x-beginx),abs(oil[i].x-endx)),min(abs(oil[i].y-beginy),abs(oil[i].y-endy)));
for (int j=1;j<=n;j++)
{
if (i!=j&&bj[j]==1)
{
oil[i].r=min(oil[i].r,max(0.0,sqrt(pow(oil[i].x-oil[j].x,2)+pow(oil[i].y-oil[j].y,2))-oil[j].r));
}
}
}
void dfs(int now,double ansx)
{
if (now>n)
{
ans=max(ans,ansx);
return ;
}
for (int i=1;i<=n;i++)
{
if (bj[i]==0)
{
bj[i]=1;
rget(i);
dfs(now+1,ansx+pow(oil[i].r,2)*pi);
bj[i]=0;
}
}
}
int main()
{
cin>>n;
cin>>beginx>>beginy>>endx>>endy;
for (i=1;i<=n;i++)
{
cin>>oil[i].x>>oil[i].y;
}
allsquare=abs(beginx-endx)*abs(beginy-endy);
dfs(1,0);
cout<<int(allsquare-ans+0.5)<<endl;
return 0;
}
| 16.660714 | 106 | 0.562701 | skyfackr |
4159c0f78d3e75c0d3e38523117ebefd0e8603f1 | 4,095 | cpp | C++ | PseudoContact.cpp | fanufree/assign-it | 7eae0828aea4964f1d459a14a0e13025fefc4c9a | [
"MIT"
] | null | null | null | PseudoContact.cpp | fanufree/assign-it | 7eae0828aea4964f1d459a14a0e13025fefc4c9a | [
"MIT"
] | null | null | null | PseudoContact.cpp | fanufree/assign-it | 7eae0828aea4964f1d459a14a0e13025fefc4c9a | [
"MIT"
] | null | null | null | /*
* PseudoContact.cpp
*
* Created on: 2012-05-03
* Author: e4k2
*/
#include <algorithm>
#include <cassert>
#include "PseudoContact.h"
#include "Utilities.h"
PseudoContact::PseudoContact() : contacts(), res1(-1), res2(-1)
{
}
PseudoContact::PseudoContact(const Contact& c) : contacts(), res1(c.r1->num), res2(c.r2->num)
{
contacts.insert(c);
}
PseudoContact::~PseudoContact()
{
}
PseudoContact::PseudoContact(const PseudoContact& pc) : contacts(pc.contacts), res1(pc.res1), res2(pc.res2)
{
}
void swap(PseudoContact& first, PseudoContact& second)
{
using std::swap;
swap(first.contacts,second.contacts);
swap(first.res1,second.res1);
swap(first.res2,second.res2);
}
//PseudoContact::PseudoContact(PseudoContact&& pc) : contacts()
//{
// swap(*this,pc);
//}
PseudoContact& PseudoContact::operator=(PseudoContact pc)
{
swap(*this,pc);
return *this;
}
void PseudoContact::add(const Contact& c)
{
contacts.insert(c);
if (res1 < 0)
{
res1 = c.r1->num;
res2 = c.r2->num;
}
else
{
assert(c.r1->num == res1 && c.r2->num == res2);
}
}
int PseudoContact::numContacts() const
{
return contacts.size();
}
void PseudoContact::print() const
{
for (tr1::unordered_set<Contact>::const_iterator it = contacts.begin(); it != contacts.end(); ++it)
{
it->print();
}
}
bool PseudoContact::operator==(const PseudoContact& pc) const
{
if (contacts.size() != pc.contacts.size())
return false;
for (tr1::unordered_set<Contact>::const_iterator it = pc.contacts.begin(); it != pc.contacts.end(); ++it)
{
if (contacts.find(*it) == contacts.end())
return false;
}
return true;
}
bool PseudoContact::areSymmetric(const PseudoContact& pc) const
{
if (contacts.size() != pc.contacts.size())
return false;
for (tr1::unordered_set<Contact>::const_iterator it = pc.contacts.begin(); it != pc.contacts.end(); ++it)
{
Contact c = it->reverse();
if (contacts.find(c) == contacts.end())
return false;
}
return true;
}
bool PseudoContact::operator!=(const PseudoContact& pc) const
{
return !(*this == pc);
}
tr1::unordered_set<Contact>& PseudoContact::getContacts()
{
return contacts;
}
Contact PseudoContact::getOneContact()
{
return *(contacts.begin());
}
// returns res1 <= res2
void PseudoContact::getResPairOrdered(int& res1, int& res2) const
{
if (this->res1 <= this->res2)
{
res1 = this->res1;
res2 = this->res2;
}
else
{
res1 = this->res2;
res2 = this->res1;
}
}
void PseudoContact::getResPair(int& res1, int& res2) const
{
res1 = this->res1;
res2 = this->res2;
}
void PseudoContact::setReverse()
{
std::swap(res1,res2);
vector<Contact> temp(contacts.begin(),contacts.end());
contacts.clear();
for (vector<Contact>::iterator it = temp.begin(); it != temp.end(); ++it)
{
contacts.insert(it->reverse());
}
}
bool PseudoContact::overlaps(const PseudoContact& pc) const
{
if (res1 == pc.res1 && res2 == pc.res2)
{
for (tr1::unordered_set<Contact>::const_iterator it1 = contacts.begin(); it1 != contacts.end(); ++it1)
{
const Contact& c1 = *it1;
for (tr1::unordered_set<Contact>::const_iterator it2 = pc.contacts.begin(); it2 != pc.contacts.end(); ++it2)
{
const Contact& c2 = *it2;
if (c1 == c2)
return true;
}
}
}
else if (res1 == pc.res2 && res2 == pc.res1)
{
for (tr1::unordered_set<Contact>::const_iterator it1 = contacts.begin(); it1 != contacts.end(); ++it1)
{
const Contact& c1 = *it1;
for (tr1::unordered_set<Contact>::const_iterator it2 = pc.contacts.begin(); it2 != pc.contacts.end(); ++it2)
{
const Contact& c2 = it2->reverse();
if (c1 == c2)
return true;
}
}
}
return false;
}
void PseudoContact::addAll(const PseudoContact& pc)
{
if (res1 == pc.res1 && res2 == pc.res2)
{
contacts.insert(pc.contacts.begin(),pc.contacts.end());
}
else if (res1 == pc.res2 && res2 == pc.res1)
{
for (tr1::unordered_set<Contact>::const_iterator it2 = pc.contacts.begin(); it2 != pc.contacts.end(); ++it2)
{
const Contact& c2 = it2->reverse();
contacts.insert(c2);
}
}
}
int PseudoContact::getSeqSep() const
{
return abs(res1-res2);
}
| 20.475 | 111 | 0.652259 | fanufree |
415a0601f9d104e6a6c2922a448f82de09c901bf | 6,714 | hpp | C++ | test/profiling/PubSubWriter.hpp | zhangzhimin/Fast-RTPS | 3032f11d0c62d226eea39ea4f8428afef4558693 | [
"Apache-2.0"
] | null | null | null | test/profiling/PubSubWriter.hpp | zhangzhimin/Fast-RTPS | 3032f11d0c62d226eea39ea4f8428afef4558693 | [
"Apache-2.0"
] | null | null | null | test/profiling/PubSubWriter.hpp | zhangzhimin/Fast-RTPS | 3032f11d0c62d226eea39ea4f8428afef4558693 | [
"Apache-2.0"
] | 1 | 2021-08-23T01:09:51.000Z | 2021-08-23T01:09:51.000Z | // Copyright 2016 Proyectos y Sistemas de Mantenimiento SL (eProsima).
//
// 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.
/**
* @file PubSubWriter.hpp
*
*/
#ifndef _TEST_PROFILING_PUBSUBWRITER_HPP_
#define _TEST_PROFILING_PUBSUBWRITER_HPP_
#include <fastrtps/fastrtps_fwd.h>
#include <fastrtps/Domain.h>
#include <fastrtps/participant/Participant.h>
#include <fastrtps/attributes/ParticipantAttributes.h>
#include <fastrtps/publisher/Publisher.h>
#include <fastrtps/publisher/PublisherListener.h>
#include <fastrtps/attributes/PublisherAttributes.h>
#include <string>
#include <list>
#include <condition_variable>
#include <boost/asio.hpp>
#include <boost/interprocess/detail/os_thread_functions.hpp>
template<class TypeSupport>
class PubSubWriter
{
class Listener : public eprosima::fastrtps::PublisherListener
{
public:
Listener(PubSubWriter &writer) : writer_(writer){};
~Listener(){};
void onPublicationMatched(eprosima::fastrtps::Publisher* /*pub*/, MatchingInfo &info)
{
if (info.status == MATCHED_MATCHING)
writer_.matched();
else
writer_.unmatched();
}
private:
Listener& operator=(const Listener&) NON_COPYABLE_CXX11;
PubSubWriter &writer_;
} listener_;
public:
typedef TypeSupport type_support;
typedef typename type_support::type type;
PubSubWriter(const std::string &topic_name) : listener_(*this), participant_(nullptr),
publisher_(nullptr), topic_name_(topic_name), initialized_(false), matched_(0)
{
publisher_attr_.topic.topicDataType = type_.getName();
// Generate topic name
std::ostringstream t;
t << topic_name_ << "_" << boost::asio::ip::host_name() << "_" << boost::interprocess::ipcdetail::get_current_process_id();
publisher_attr_.topic.topicName = t.str();
}
~PubSubWriter()
{
if(participant_ != nullptr)
eprosima::fastrtps::Domain::removeParticipant(participant_);
}
void init()
{
//Create participant
eprosima::fastrtps::ParticipantAttributes pattr;
pattr.rtps.builtin.domainId = (uint32_t)boost::interprocess::ipcdetail::get_current_process_id() % 230;
participant_ = eprosima::fastrtps::Domain::createParticipant(pattr);
if(participant_ != nullptr)
{
// Register type
eprosima::fastrtps::Domain::registerType(participant_, &type_);
//Create publisher
publisher_ = eprosima::fastrtps::Domain::createPublisher(participant_, publisher_attr_, &listener_);
if(publisher_ != nullptr)
{
initialized_ = true;
return;
}
eprosima::fastrtps::Domain::removeParticipant(participant_);
}
}
bool isInitialized() const { return initialized_; }
void destroy()
{
if(participant_ != nullptr)
{
eprosima::fastrtps::Domain::removeParticipant(participant_);
participant_ = nullptr;
}
}
void send(std::list<type>& msgs)
{
auto it = msgs.begin();
while(it != msgs.end())
{
if(publisher_->write((void*)&(*it)))
{
it = msgs.erase(it);
}
else
break;
}
}
void waitDiscovery()
{
std::cout << "Writer waiting for discovery..." << std::endl;
std::unique_lock<std::mutex> lock(mutex_);
if(matched_ == 0)
cv_.wait_for(lock, std::chrono::seconds(10));
std::cout << "Writer discovery phase finished" << std::endl;
}
void waitRemoval()
{
std::unique_lock<std::mutex> lock(mutex_);
if(matched_ != 0)
cv_.wait_for(lock, std::chrono::seconds(10));
}
bool waitForAllAcked(const std::chrono::seconds& max_wait)
{
return publisher_->wait_for_all_acked(Time_t((int32_t)max_wait.count(), 0));
}
/*** Function to change QoS ***/
PubSubWriter& reliability(const eprosima::fastrtps::ReliabilityQosPolicyKind kind)
{
publisher_attr_.qos.m_reliability.kind = kind;
return *this;
}
PubSubWriter& asynchronously(const eprosima::fastrtps::PublishModeQosPolicyKind kind)
{
publisher_attr_.qos.m_publishMode.kind = kind;
return *this;
}
PubSubWriter& history_kind(const eprosima::fastrtps::HistoryQosPolicyKind kind)
{
publisher_attr_.topic.historyQos.kind = kind;
return *this;
}
PubSubWriter& history_depth(const int32_t depth)
{
publisher_attr_.topic.historyQos.depth = depth;
return *this;
}
PubSubWriter& durability_kind(const eprosima::fastrtps::DurabilityQosPolicyKind kind)
{
publisher_attr_.qos.m_durability.kind = kind;
return *this;
}
PubSubWriter& resource_limits_max_samples(const int32_t max)
{
publisher_attr_.topic.resourceLimitsQos.max_samples = max;
return *this;
}
PubSubWriter& heartbeat_period_seconds(int32_t sec)
{
publisher_attr_.times.heartbeatPeriod.seconds = sec;
return *this;
}
PubSubWriter& heartbeat_period_fraction(uint32_t frac)
{
publisher_attr_.times.heartbeatPeriod.fraction = frac;
return *this;
}
private:
void matched()
{
std::unique_lock<std::mutex> lock(mutex_);
++matched_;
cv_.notify_one();
}
void unmatched()
{
std::unique_lock<std::mutex> lock(mutex_);
--matched_;
cv_.notify_one();
}
PubSubWriter& operator=(const PubSubWriter&)NON_COPYABLE_CXX11;
eprosima::fastrtps::Participant *participant_;
eprosima::fastrtps::PublisherAttributes publisher_attr_;
eprosima::fastrtps::Publisher *publisher_;
std::string topic_name_;
bool initialized_;
std::mutex mutex_;
std::condition_variable cv_;
unsigned int matched_;
type_support type_;
};
#endif // _TEST_PROFILING_PUBSUBWRITER_HPP_
| 28.09205 | 135 | 0.634346 | zhangzhimin |
41631e8b04c2f6036e704431fc39dfbc79b021d2 | 240 | hpp | C++ | include/parse.hpp | samcoppini/Glass-Interpreter | 373d1bf9d5fbed144b7198da1b065ded533f99cd | [
"BSL-1.0"
] | null | null | null | include/parse.hpp | samcoppini/Glass-Interpreter | 373d1bf9d5fbed144b7198da1b065ded533f99cd | [
"BSL-1.0"
] | null | null | null | include/parse.hpp | samcoppini/Glass-Interpreter | 373d1bf9d5fbed144b7198da1b065ded533f99cd | [
"BSL-1.0"
] | null | null | null | #ifndef PARSE_HPP
#define PARSE_HPP
#include "class.hpp"
#include <fstream>
#include <map>
#include <optional>
#include <string>
#include <utility>
std::optional<ClassMap> get_classes(const std::string &filename, bool pedantic);
#endif
| 16 | 80 | 0.75 | samcoppini |
4163569c04b7b4642862a8c55b79a1a106519f25 | 11,046 | cpp | C++ | qt-creator-opensource-src-4.6.1/src/libs/qmleditorwidgets/easingpane/easinggraph.cpp | kevinlq/Qt-Creator-Opensource-Study | b8cadff1f33f25a5d4ef33ed93f661b788b1ba0f | [
"MIT"
] | 5 | 2018-12-22T14:49:13.000Z | 2022-01-13T07:21:46.000Z | qt-creator-opensource-src-4.6.1/src/libs/qmleditorwidgets/easingpane/easinggraph.cpp | kevinlq/Qt-Creator-Opensource-Study | b8cadff1f33f25a5d4ef33ed93f661b788b1ba0f | [
"MIT"
] | null | null | null | qt-creator-opensource-src-4.6.1/src/libs/qmleditorwidgets/easingpane/easinggraph.cpp | kevinlq/Qt-Creator-Opensource-Study | b8cadff1f33f25a5d4ef33ed93f661b788b1ba0f | [
"MIT"
] | 8 | 2018-07-17T03:55:48.000Z | 2021-12-22T06:37:53.000Z | /****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
****************************************************************************/
#include "easinggraph.h"
#include <QPainter>
#include <QStyleOptionGraphicsItem>
#include <math.h>
QT_BEGIN_NAMESPACE
EasingGraph::EasingGraph(QWidget *parent):QWidget(parent),
m_color(Qt::magenta), m_zeroColor(Qt::gray),m_duration(0),
m_easingExtremes(QLatin1String("In"))
{
// setFlag(QGraphicsItem::ItemHasNoContents, false);
// populate the hash
m_availableNames.insert(QLatin1String("Linear"), QEasingCurve::Linear);
m_availableNames.insert(QLatin1String("InQuad"), QEasingCurve::InQuad);
m_availableNames.insert(QLatin1String("OutQuad"), QEasingCurve::OutQuad);
m_availableNames.insert(QLatin1String("InOutQuad"), QEasingCurve::InOutQuad);
m_availableNames.insert(QLatin1String("OutInQuad"), QEasingCurve::OutInQuad);
m_availableNames.insert(QLatin1String("InCubic"), QEasingCurve::InCubic);
m_availableNames.insert(QLatin1String("OutCubic"), QEasingCurve::OutCubic);
m_availableNames.insert(QLatin1String("InOutCubic"), QEasingCurve::InOutCubic);
m_availableNames.insert(QLatin1String("OutInCubic"), QEasingCurve::OutInCubic);
m_availableNames.insert(QLatin1String("InQuart"), QEasingCurve::InQuart);
m_availableNames.insert(QLatin1String("OutQuart"), QEasingCurve::OutQuart);
m_availableNames.insert(QLatin1String("InOutQuart"), QEasingCurve::InOutQuart);
m_availableNames.insert(QLatin1String("OutInQuart"), QEasingCurve::OutInQuart);
m_availableNames.insert(QLatin1String("InQuint"), QEasingCurve::InQuint);
m_availableNames.insert(QLatin1String("OutQuint"), QEasingCurve::OutQuint);
m_availableNames.insert(QLatin1String("InOutQuint"), QEasingCurve::InOutQuint);
m_availableNames.insert(QLatin1String("OutInQuint"), QEasingCurve::OutInQuint);
m_availableNames.insert(QLatin1String("InSine"), QEasingCurve::InSine);
m_availableNames.insert(QLatin1String("OutSine"), QEasingCurve::OutSine);
m_availableNames.insert(QLatin1String("InOutSine"), QEasingCurve::InOutSine);
m_availableNames.insert(QLatin1String("OutInSine"), QEasingCurve::OutInSine);
m_availableNames.insert(QLatin1String("InExpo"), QEasingCurve::InExpo);
m_availableNames.insert(QLatin1String("OutExpo"), QEasingCurve::OutExpo);
m_availableNames.insert(QLatin1String("InOutExpo"), QEasingCurve::InOutExpo);
m_availableNames.insert(QLatin1String("OutInExpo"), QEasingCurve::OutInExpo);
m_availableNames.insert(QLatin1String("InCirc"), QEasingCurve::InCirc);
m_availableNames.insert(QLatin1String("OutCirc"), QEasingCurve::OutCirc);
m_availableNames.insert(QLatin1String("InOutCirc"), QEasingCurve::InOutCirc);
m_availableNames.insert(QLatin1String("OutInCirc"), QEasingCurve::OutInCirc);
m_availableNames.insert(QLatin1String("InElastic"), QEasingCurve::InElastic);
m_availableNames.insert(QLatin1String("OutElastic"), QEasingCurve::OutElastic);
m_availableNames.insert(QLatin1String("InOutElastic"), QEasingCurve::InOutElastic);
m_availableNames.insert(QLatin1String("OutInElastic"), QEasingCurve::OutInElastic);
m_availableNames.insert(QLatin1String("InBack"), QEasingCurve::InBack);
m_availableNames.insert(QLatin1String("OutBack"), QEasingCurve::OutBack);
m_availableNames.insert(QLatin1String("InOutBack"), QEasingCurve::InOutBack);
m_availableNames.insert(QLatin1String("OutInBack"), QEasingCurve::OutInBack);
m_availableNames.insert(QLatin1String("InBounce"), QEasingCurve::InBounce);
m_availableNames.insert(QLatin1String("OutBounce"), QEasingCurve::OutBounce);
m_availableNames.insert(QLatin1String("InOutBounce"), QEasingCurve::InOutBounce);
m_availableNames.insert(QLatin1String("OutInBounce"), QEasingCurve::OutInBounce);
m_availableNames.insert(QLatin1String("InCurve"), QEasingCurve::InCurve);
m_availableNames.insert(QLatin1String("OutCurve"), QEasingCurve::OutCurve);
m_availableNames.insert(QLatin1String("SineCurve"), QEasingCurve::SineCurve);
m_availableNames.insert(QLatin1String("CosineCurve"), QEasingCurve::CosineCurve);
}
EasingGraph::~EasingGraph()
{
}
QEasingCurve::Type EasingGraph::easingType() const
{
return m_curveFunction.type();
}
QEasingCurve EasingGraph::easingCurve() const
{
return m_curveFunction;
}
QString EasingGraph::easingShape() const
{
QString name = easingName();
if (name.left(5)==QLatin1String("InOut")) return name.right(name.length()-5);
if (name.left(5)==QLatin1String("OutIn")) return name.right(name.length()-5);
if (name.left(3)==QLatin1String("Out")) return name.right(name.length()-3);
if (name.left(2)==QLatin1String("In")) return name.right(name.length()-2);
return name;
}
void EasingGraph::setEasingShape(const QString &newShape)
{
if (easingShape() != newShape) {
if (newShape==QLatin1String("Linear"))
setEasingName(newShape);
else
setEasingName(m_easingExtremes+newShape);
}
}
QString EasingGraph::easingExtremes() const
{
QString name = easingName();
if (name.left(5)==QLatin1String("InOut")) return QLatin1String("InOut");
if (name.left(5)==QLatin1String("OutIn")) return QLatin1String("OutIn");
if (name.left(3)==QLatin1String("Out")) return QLatin1String("Out");
if (name.left(2)==QLatin1String("In")) return QLatin1String("In");
return QString();
}
void EasingGraph::setEasingExtremes(const QString &newExtremes)
{
if (m_easingExtremes != newExtremes) {
m_easingExtremes = newExtremes;
if (easingShape()!=QLatin1String("Linear"))
setEasingName(newExtremes+easingShape());
}
}
QString EasingGraph::easingName() const
{
return m_availableNames.key(m_curveFunction.type());
}
void EasingGraph::setEasingName(const QString &newName)
{
if (easingName() != newName) {
if (!m_availableNames.contains(newName)) return;
m_curveFunction = QEasingCurve(m_availableNames.value(newName));
emit easingNameChanged();
emit easingExtremesChanged();
emit easingShapeChanged();
update();
}
}
qreal EasingGraph::overshoot() const
{
return m_curveFunction.overshoot();
}
void EasingGraph::setOvershoot(qreal newOvershoot)
{
if ((overshoot() != newOvershoot) && (easingShape()==QLatin1String("Back"))) {
m_curveFunction.setOvershoot(newOvershoot);
emit overshootChanged();
update();
}
}
qreal EasingGraph::amplitude() const
{
return m_curveFunction.amplitude();
}
void EasingGraph::setAmplitude(qreal newAmplitude)
{
if ((amplitude() != newAmplitude) && ((easingShape()==QLatin1String("Bounce")) ||(easingShape()==QLatin1String("Elastic")))) {
m_curveFunction.setAmplitude(newAmplitude);
emit amplitudeChanged();
update();
}
}
qreal EasingGraph::period() const
{
return m_curveFunction.period();
}
void EasingGraph::setPeriod(qreal newPeriod)
{
if ((period() != newPeriod) && (easingShape()==QLatin1String("Elastic"))) {
m_curveFunction.setPeriod(newPeriod);
emit periodChanged();
update();
}
}
qreal EasingGraph::duration() const
{
return m_duration;
}
void EasingGraph::setDuration(qreal newDuration)
{
if (m_duration != newDuration) {
m_duration = newDuration;
emit durationChanged();
}
}
QColor EasingGraph::color() const
{
return m_color;
}
void EasingGraph::setColor(const QColor &newColor)
{
if (m_color != newColor) {
m_color = newColor;
emit colorChanged();
update();
}
}
QColor EasingGraph::zeroColor() const{
return m_zeroColor;
}
void EasingGraph::setZeroColor(const QColor &newColor)
{
if (m_zeroColor != newColor) {
m_zeroColor = newColor;
emit zeroColorChanged();
update();
}
}
QRectF EasingGraph::boundingRect() const
{
return QRectF(0, 0, width(), height());
}
void EasingGraph::paintEvent(QPaintEvent *event)
//void EasingGraph::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *)
{
QWidget::paintEvent(event);
QPainter *painter = new QPainter(this);
painter->save();
bool drawZero = false;
// no background
int length = width();
int breadth = height()-2;
QPainterPath path;
path.moveTo(0,int((1-m_curveFunction.valueForProgress(0))*breadth));
for (int i=0;i<length;i++) {
qreal progress = i/qreal(length);
qreal value = m_curveFunction.valueForProgress(progress);
int x = int(length*progress);
int y = int(breadth*(1-value));
path.lineTo(x,y);
}
QRectF pathRect = path.controlPointRect();
if ( (pathRect.height()>breadth)) {
// scale vertically
qreal scale = breadth/pathRect.height();
qreal displacement = -pathRect.top();
// reset path and recompute scaled version
path = QPainterPath();
path.moveTo(0,int(scale*((1-m_curveFunction.valueForProgress(0))*breadth+displacement)));
for (int i=0;i<length;i++) {
qreal progress = i/qreal(length);
qreal value = m_curveFunction.valueForProgress(progress);
int x = int(length*progress);
int y = int(scale*(breadth*(1-value)+displacement));
path.lineTo(x,y);
}
drawZero = true;
}
painter->setBrush(Qt::transparent);
if (drawZero) {
// "zero" and "one" lines
QPen zeroPen = QPen(m_zeroColor);
zeroPen.setStyle(Qt::DashLine);
painter->setPen(zeroPen);
int y = int(-pathRect.top()*breadth/pathRect.height());
if (y>0)
painter->drawLine(0,y,length,y);
y = int(breadth/pathRect.height()*(breadth-pathRect.top()));
if (y<breadth)
painter->drawLine(0,y,length,y);
}
painter->setPen(m_color);
painter->drawPath(path);
painter->restore();
delete painter;
}
QT_END_NAMESPACE
| 35.517685 | 130 | 0.696451 | kevinlq |
4163f0229edb2eeda4f6cdd66a0b3c9b5e0da52e | 2,216 | hpp | C++ | src/common/Surface.hpp | LibreSprite/Dotto | 3d057875fd0e33d2a72add44c316af9fdc5be7c8 | [
"MIT"
] | 151 | 2021-12-28T21:22:42.000Z | 2022-03-30T13:53:28.000Z | src/common/Surface.hpp | LibreSprite/Dotto | 3d057875fd0e33d2a72add44c316af9fdc5be7c8 | [
"MIT"
] | 9 | 2021-12-29T13:20:00.000Z | 2022-03-18T12:47:19.000Z | src/common/Surface.hpp | Linux-Gamer/Dotto | ed722f0bbcbcb230b7c40977a5552cba81e5075d | [
"MIT"
] | 18 | 2021-12-28T19:58:49.000Z | 2022-03-31T16:38:14.000Z | // Copyright (c) 2021 LibreSprite Authors (cf. AUTHORS.md)
// This file is released under the terms of the MIT license.
// Read LICENSE.txt for more information.
#pragma once
#include <memory>
#include <variant>
#include <common/Color.hpp>
#include <common/Rect.hpp>
#include <common/types.hpp>
#include <gui/Texture.hpp>
class Surface : public std::enable_shared_from_this<Surface> {
public:
using PixelType = U32;
private:
U32 _width = 0, _height = 0;
Vector<PixelType> pixels;
std::unique_ptr<TextureInfo> _textureInfo;
public:
U32 width() const {return _width;}
U32 height() const {return _height;}
Rect rect() const {return {0, 0, _width, _height};}
PixelType* data() {return pixels.data();}
U32 dataSize() {return _width * _height * sizeof(PixelType);};
const Vector<PixelType>& getPixels() {return pixels;}
std::shared_ptr<Surface> clone();
TextureInfo& info();
void resize(U32 width, U32 height);
void setDirty(const Rect& region);
void setPixels(const Vector<PixelType>& read);
Color getPixel(U32 x, U32 y) {
U32 index = x + y * _width;
return (index >= _width * _height) ? Color{} : getColor(pixels[index]);
}
PixelType getPixelUnsafe(U32 x, U32 y) {
return pixels[x + y * _width];
}
void setPixelUnsafe(U32 x, U32 y, PixelType pixel) {
U32 index = x + y * _width;
pixels[index] = pixel;
setDirty({S32(x), S32(y), 1, 1});
}
void setHLine(S32 x, S32 y, S32 w, PixelType pixel);
void antsHLine(S32 x, S32 y, S32 w, U32 age, PixelType A, PixelType B);
void setVLine(S32 x, S32 y, S32 h, PixelType pixel);
void antsVLine(S32 x, S32 y, S32 h, U32 age, PixelType A, PixelType B);
void fillRect(const Rect& rect, PixelType pixel);
void setPixel(U32 x, U32 y, PixelType pixel);
void setPixel(U32 x, U32 y, const Color& color) {
setPixel(x, y, color.toU32());
}
Color getColor(PixelType pixel) {
return pixel;
}
Surface& operator = (const Surface& other) {
_width = other._width;
_height = other._height;
pixels = other.pixels;
setDirty(rect());
return *this;
}
};
| 29.157895 | 79 | 0.636733 | LibreSprite |
416478ca5304aa6aef8c4067d01d680ee1fe73de | 10,946 | cpp | C++ | hal/src/main/native/cpp/jni/simulation/CTREPCMDataJNI.cpp | shueja-personal/allwpilib | 4b2f6be29e21986703d9c3ddcd2fe07121b2ff6b | [
"BSD-3-Clause"
] | 707 | 2016-05-11T16:54:13.000Z | 2022-03-30T13:03:15.000Z | hal/src/main/native/cpp/jni/simulation/CTREPCMDataJNI.cpp | shueja-personal/allwpilib | 4b2f6be29e21986703d9c3ddcd2fe07121b2ff6b | [
"BSD-3-Clause"
] | 2,308 | 2016-05-12T00:17:17.000Z | 2022-03-30T20:08:10.000Z | hal/src/main/native/cpp/jni/simulation/CTREPCMDataJNI.cpp | shueja-personal/allwpilib | 4b2f6be29e21986703d9c3ddcd2fe07121b2ff6b | [
"BSD-3-Clause"
] | 539 | 2016-05-11T20:33:26.000Z | 2022-03-28T20:20:25.000Z | // Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
#include <jni.h>
#include "CallbackStore.h"
#include "edu_wpi_first_hal_simulation_CTREPCMDataJNI.h"
#include "hal/simulation/CTREPCMData.h"
using namespace hal;
extern "C" {
/*
* Class: edu_wpi_first_hal_simulation_CTREPCMDataJNI
* Method: registerInitializedCallback
* Signature: (ILjava/lang/Object;Z)I
*/
JNIEXPORT jint JNICALL
Java_edu_wpi_first_hal_simulation_CTREPCMDataJNI_registerInitializedCallback
(JNIEnv* env, jclass, jint index, jobject callback, jboolean initialNotify)
{
return sim::AllocateCallback(env, index, callback, initialNotify,
&HALSIM_RegisterCTREPCMInitializedCallback);
}
/*
* Class: edu_wpi_first_hal_simulation_CTREPCMDataJNI
* Method: cancelInitializedCallback
* Signature: (II)V
*/
JNIEXPORT void JNICALL
Java_edu_wpi_first_hal_simulation_CTREPCMDataJNI_cancelInitializedCallback
(JNIEnv* env, jclass, jint index, jint handle)
{
return sim::FreeCallback(env, handle, index,
&HALSIM_CancelCTREPCMInitializedCallback);
}
/*
* Class: edu_wpi_first_hal_simulation_CTREPCMDataJNI
* Method: getInitialized
* Signature: (I)Z
*/
JNIEXPORT jboolean JNICALL
Java_edu_wpi_first_hal_simulation_CTREPCMDataJNI_getInitialized
(JNIEnv*, jclass, jint index)
{
return HALSIM_GetCTREPCMInitialized(index);
}
/*
* Class: edu_wpi_first_hal_simulation_CTREPCMDataJNI
* Method: setInitialized
* Signature: (IZ)V
*/
JNIEXPORT void JNICALL
Java_edu_wpi_first_hal_simulation_CTREPCMDataJNI_setInitialized
(JNIEnv*, jclass, jint index, jboolean value)
{
HALSIM_SetCTREPCMInitialized(index, value);
}
/*
* Class: edu_wpi_first_hal_simulation_CTREPCMDataJNI
* Method: registerSolenoidOutputCallback
* Signature: (IILjava/lang/Object;Z)I
*/
JNIEXPORT jint JNICALL
Java_edu_wpi_first_hal_simulation_CTREPCMDataJNI_registerSolenoidOutputCallback
(JNIEnv* env, jclass, jint index, jint channel, jobject callback,
jboolean initialNotify)
{
return sim::AllocateChannelCallback(
env, index, channel, callback, initialNotify,
&HALSIM_RegisterCTREPCMSolenoidOutputCallback);
}
/*
* Class: edu_wpi_first_hal_simulation_CTREPCMDataJNI
* Method: cancelSolenoidOutputCallback
* Signature: (III)V
*/
JNIEXPORT void JNICALL
Java_edu_wpi_first_hal_simulation_CTREPCMDataJNI_cancelSolenoidOutputCallback
(JNIEnv* env, jclass, jint index, jint channel, jint handle)
{
return sim::FreeChannelCallback(env, handle, index, channel,
&HALSIM_CancelCTREPCMSolenoidOutputCallback);
}
/*
* Class: edu_wpi_first_hal_simulation_CTREPCMDataJNI
* Method: getSolenoidOutput
* Signature: (II)Z
*/
JNIEXPORT jboolean JNICALL
Java_edu_wpi_first_hal_simulation_CTREPCMDataJNI_getSolenoidOutput
(JNIEnv*, jclass, jint index, jint channel)
{
return HALSIM_GetCTREPCMSolenoidOutput(index, channel);
}
/*
* Class: edu_wpi_first_hal_simulation_CTREPCMDataJNI
* Method: setSolenoidOutput
* Signature: (IIZ)V
*/
JNIEXPORT void JNICALL
Java_edu_wpi_first_hal_simulation_CTREPCMDataJNI_setSolenoidOutput
(JNIEnv*, jclass, jint index, jint channel, jboolean value)
{
HALSIM_SetCTREPCMSolenoidOutput(index, channel, value);
}
/*
* Class: edu_wpi_first_hal_simulation_CTREPCMDataJNI
* Method: registerCompressorOnCallback
* Signature: (ILjava/lang/Object;Z)I
*/
JNIEXPORT jint JNICALL
Java_edu_wpi_first_hal_simulation_CTREPCMDataJNI_registerCompressorOnCallback
(JNIEnv* env, jclass, jint index, jobject callback, jboolean initialNotify)
{
return sim::AllocateCallback(env, index, callback, initialNotify,
&HALSIM_RegisterCTREPCMCompressorOnCallback);
}
/*
* Class: edu_wpi_first_hal_simulation_CTREPCMDataJNI
* Method: cancelCompressorOnCallback
* Signature: (II)V
*/
JNIEXPORT void JNICALL
Java_edu_wpi_first_hal_simulation_CTREPCMDataJNI_cancelCompressorOnCallback
(JNIEnv* env, jclass, jint index, jint handle)
{
return sim::FreeCallback(env, handle, index,
&HALSIM_CancelCTREPCMCompressorOnCallback);
}
/*
* Class: edu_wpi_first_hal_simulation_CTREPCMDataJNI
* Method: getCompressorOn
* Signature: (I)Z
*/
JNIEXPORT jboolean JNICALL
Java_edu_wpi_first_hal_simulation_CTREPCMDataJNI_getCompressorOn
(JNIEnv*, jclass, jint index)
{
return HALSIM_GetCTREPCMCompressorOn(index);
}
/*
* Class: edu_wpi_first_hal_simulation_CTREPCMDataJNI
* Method: setCompressorOn
* Signature: (IZ)V
*/
JNIEXPORT void JNICALL
Java_edu_wpi_first_hal_simulation_CTREPCMDataJNI_setCompressorOn
(JNIEnv*, jclass, jint index, jboolean value)
{
HALSIM_SetCTREPCMCompressorOn(index, value);
}
/*
* Class: edu_wpi_first_hal_simulation_CTREPCMDataJNI
* Method: registerClosedLoopEnabledCallback
* Signature: (ILjava/lang/Object;Z)I
*/
JNIEXPORT jint JNICALL
Java_edu_wpi_first_hal_simulation_CTREPCMDataJNI_registerClosedLoopEnabledCallback
(JNIEnv* env, jclass, jint index, jobject callback, jboolean initialNotify)
{
return sim::AllocateCallback(
env, index, callback, initialNotify,
&HALSIM_RegisterCTREPCMClosedLoopEnabledCallback);
}
/*
* Class: edu_wpi_first_hal_simulation_CTREPCMDataJNI
* Method: cancelClosedLoopEnabledCallback
* Signature: (II)V
*/
JNIEXPORT void JNICALL
Java_edu_wpi_first_hal_simulation_CTREPCMDataJNI_cancelClosedLoopEnabledCallback
(JNIEnv* env, jclass, jint index, jint handle)
{
return sim::FreeCallback(env, handle, index,
&HALSIM_CancelCTREPCMClosedLoopEnabledCallback);
}
/*
* Class: edu_wpi_first_hal_simulation_CTREPCMDataJNI
* Method: getClosedLoopEnabled
* Signature: (I)Z
*/
JNIEXPORT jboolean JNICALL
Java_edu_wpi_first_hal_simulation_CTREPCMDataJNI_getClosedLoopEnabled
(JNIEnv*, jclass, jint index)
{
return HALSIM_GetCTREPCMClosedLoopEnabled(index);
}
/*
* Class: edu_wpi_first_hal_simulation_CTREPCMDataJNI
* Method: setClosedLoopEnabled
* Signature: (IZ)V
*/
JNIEXPORT void JNICALL
Java_edu_wpi_first_hal_simulation_CTREPCMDataJNI_setClosedLoopEnabled
(JNIEnv*, jclass, jint index, jboolean value)
{
HALSIM_SetCTREPCMClosedLoopEnabled(index, value);
}
/*
* Class: edu_wpi_first_hal_simulation_CTREPCMDataJNI
* Method: registerPressureSwitchCallback
* Signature: (ILjava/lang/Object;Z)I
*/
JNIEXPORT jint JNICALL
Java_edu_wpi_first_hal_simulation_CTREPCMDataJNI_registerPressureSwitchCallback
(JNIEnv* env, jclass, jint index, jobject callback, jboolean initialNotify)
{
return sim::AllocateCallback(env, index, callback, initialNotify,
&HALSIM_RegisterCTREPCMPressureSwitchCallback);
}
/*
* Class: edu_wpi_first_hal_simulation_CTREPCMDataJNI
* Method: cancelPressureSwitchCallback
* Signature: (II)V
*/
JNIEXPORT void JNICALL
Java_edu_wpi_first_hal_simulation_CTREPCMDataJNI_cancelPressureSwitchCallback
(JNIEnv* env, jclass, jint index, jint handle)
{
return sim::FreeCallback(env, handle, index,
&HALSIM_CancelCTREPCMPressureSwitchCallback);
}
/*
* Class: edu_wpi_first_hal_simulation_CTREPCMDataJNI
* Method: getPressureSwitch
* Signature: (I)Z
*/
JNIEXPORT jboolean JNICALL
Java_edu_wpi_first_hal_simulation_CTREPCMDataJNI_getPressureSwitch
(JNIEnv*, jclass, jint index)
{
return HALSIM_GetCTREPCMPressureSwitch(index);
}
/*
* Class: edu_wpi_first_hal_simulation_CTREPCMDataJNI
* Method: setPressureSwitch
* Signature: (IZ)V
*/
JNIEXPORT void JNICALL
Java_edu_wpi_first_hal_simulation_CTREPCMDataJNI_setPressureSwitch
(JNIEnv*, jclass, jint index, jboolean value)
{
HALSIM_SetCTREPCMPressureSwitch(index, value);
}
/*
* Class: edu_wpi_first_hal_simulation_CTREPCMDataJNI
* Method: registerCompressorCurrentCallback
* Signature: (ILjava/lang/Object;Z)I
*/
JNIEXPORT jint JNICALL
Java_edu_wpi_first_hal_simulation_CTREPCMDataJNI_registerCompressorCurrentCallback
(JNIEnv* env, jclass, jint index, jobject callback, jboolean initialNotify)
{
return sim::AllocateCallback(
env, index, callback, initialNotify,
&HALSIM_RegisterCTREPCMCompressorCurrentCallback);
}
/*
* Class: edu_wpi_first_hal_simulation_CTREPCMDataJNI
* Method: cancelCompressorCurrentCallback
* Signature: (II)V
*/
JNIEXPORT void JNICALL
Java_edu_wpi_first_hal_simulation_CTREPCMDataJNI_cancelCompressorCurrentCallback
(JNIEnv* env, jclass, jint index, jint handle)
{
return sim::FreeCallback(env, handle, index,
&HALSIM_CancelCTREPCMCompressorCurrentCallback);
}
/*
* Class: edu_wpi_first_hal_simulation_CTREPCMDataJNI
* Method: getCompressorCurrent
* Signature: (I)D
*/
JNIEXPORT jdouble JNICALL
Java_edu_wpi_first_hal_simulation_CTREPCMDataJNI_getCompressorCurrent
(JNIEnv*, jclass, jint index)
{
return HALSIM_GetCTREPCMCompressorCurrent(index);
}
/*
* Class: edu_wpi_first_hal_simulation_CTREPCMDataJNI
* Method: setCompressorCurrent
* Signature: (ID)V
*/
JNIEXPORT void JNICALL
Java_edu_wpi_first_hal_simulation_CTREPCMDataJNI_setCompressorCurrent
(JNIEnv*, jclass, jint index, jdouble value)
{
HALSIM_SetCTREPCMCompressorCurrent(index, value);
}
/*
* Class: edu_wpi_first_hal_simulation_CTREPCMDataJNI
* Method: registerAllNonSolenoidCallbacks
* Signature: (ILjava/lang/Object;Z)V
*/
JNIEXPORT void JNICALL
Java_edu_wpi_first_hal_simulation_CTREPCMDataJNI_registerAllNonSolenoidCallbacks
(JNIEnv* env, jclass, jint index, jobject callback, jboolean initialNotify)
{
sim::AllocateCallback(
env, index, callback, initialNotify,
[](int32_t index, HAL_NotifyCallback cb, void* param, HAL_Bool in) {
HALSIM_RegisterCTREPCMAllNonSolenoidCallbacks(index, cb, param, in);
return 0;
});
}
/*
* Class: edu_wpi_first_hal_simulation_CTREPCMDataJNI
* Method: registerAllSolenoidCallbacks
* Signature: (IILjava/lang/Object;Z)V
*/
JNIEXPORT void JNICALL
Java_edu_wpi_first_hal_simulation_CTREPCMDataJNI_registerAllSolenoidCallbacks
(JNIEnv* env, jclass, jint index, jint channel, jobject callback,
jboolean initialNotify)
{
sim::AllocateChannelCallback(
env, index, channel, callback, initialNotify,
[](int32_t index, int32_t channel, HAL_NotifyCallback cb, void* param,
HAL_Bool in) {
HALSIM_RegisterCTREPCMAllSolenoidCallbacks(index, channel, cb, param,
in);
return 0;
});
}
/*
* Class: edu_wpi_first_hal_simulation_CTREPCMDataJNI
* Method: resetData
* Signature: (I)V
*/
JNIEXPORT void JNICALL
Java_edu_wpi_first_hal_simulation_CTREPCMDataJNI_resetData
(JNIEnv*, jclass, jint index)
{
HALSIM_ResetCTREPCMData(index);
}
} // extern "C"
| 29.663957 | 82 | 0.76786 | shueja-personal |
416b5fab9b61a030672653091ad09ce3e4bb9f7a | 3,965 | hpp | C++ | ql/experimental/preexperimental/cmsSwap.hpp | universe1987/QuantLib | bbb0145aff285853755b9f6ed013f53a41163acb | [
"BSD-3-Clause"
] | 4 | 2016-03-28T15:05:23.000Z | 2020-02-17T23:05:57.000Z | ql/experimental/preexperimental/cmsSwap.hpp | universe1987/QuantLib | bbb0145aff285853755b9f6ed013f53a41163acb | [
"BSD-3-Clause"
] | 1 | 2015-02-02T20:32:43.000Z | 2015-02-02T20:32:43.000Z | ql/experimental/preexperimental/cmsSwap.hpp | pcaspers/quantlib | bbb0145aff285853755b9f6ed013f53a41163acb | [
"BSD-3-Clause"
] | 10 | 2015-01-26T14:50:24.000Z | 2015-10-23T07:41:30.000Z | /*! \file cmsSwap.hpp
\brief Cms Swap
Peter Caspers
*/
#include <ql/quantlib.hpp>
#include <CmsPricer.hpp>
#ifndef quantlib_cmsSwap_hpp
#define quantlib_cmsSwap_hpp
using namespace boost;
using namespace std;
namespace QuantLib {
/*! cms swap */
class CmsSwap {
public:
/*! construct cms swap
for the structured leg the curve in the cms pricer is used as estimation and discount curve
for the float leg the estimation curve is the curve of the floatIndex
the discount curve for the float leg must be specified separately */
CmsSwap(boost::shared_ptr<Schedule> fixingSchedule,
boost::shared_ptr<Schedule> paymentSchedule,
boost::shared_ptr<Schedule> calculationSchedule,
boost::shared_ptr<SwapIndex> swapIndex,
DayCounter couponDayCounter,
boost::shared_ptr<Schedule> floatLegFixingSchedule,
boost::shared_ptr<Schedule> floatLegPaymentSchedule,
boost::shared_ptr<Schedule> floatLegCalculationSchedule,
boost::shared_ptr<IborIndex> floatIndex,
DayCounter floatLegCouponDayCounter,
boost::shared_ptr<YieldTermStructure> floatDiscountCurve
);
CmsSwap(boost::shared_ptr<Schedule> calculationSchedule,
int fixingDays,
boost::shared_ptr<SwapIndex> swapIndex,
DayCounter couponDayCounter,
boost::shared_ptr<Schedule> floatLegCalculationSchedule,
int floatFixingDays,
boost::shared_ptr<IborIndex> iborIndex,
DayCounter floatLegCouponDayCounter,
boost::shared_ptr<YieldTermStructure> floatDiscountCurve,
double strike=0.0000,
int flavour=1);
/*! return schedules */
std::vector<Date> fixingSchedule();
std::vector<Date> paymentSchedule();
std::vector<Date> calculationSchedule();
/*! return cms rates
adjusted = false => forward swap rates
adjusted = true => convexity adjusted forward swap rates */
std::vector<double> rates(bool adjusted);
/*! return upper bound of hedge portfolio */
std::vector<double> upperBounds();
/*! set cap floor payoff
flavour = 1 cap, -1 floor
strike of cap or floor */
bool setCapPayoff(double strike, int flavour) {
strike_=strike;
flavour_=flavour;
return true;
}
/*! set margin this is added _after_ flooring / capping (!) to structured leg */
bool setMargin(double margin) {
margin_=margin;
return true;
}
/*! npv of structured leg
precomputedSwaplets is the number of already computed swaplet prices
precomputedPrice is the price of the precomputed swaplets
swapletUppterBound is the index of the first swaplet that will not be computed (if 0 all swaplets will be computed) */
Real npv(boost::shared_ptr<CmsPricer> pricer,int precomputedSwaplets=0,double precomputedPrice=0.0,int swapletUpperBound=0);
/*! total npv of swap (pay structured leg, receive float leg with flat margin) */
Real CmsSwap::totalNpv(boost::shared_ptr<CmsPricer> pricer);
/*! get implied margin for cms swap
if number of swaplets is given, only implied margin of this part is returned (but including precomputed swaplets)
precomputed floatlets and floatlets upper bound refer to the float leg of the swap
they must be given, because the frequency of this leg can be different
if the latter two numbers are zero they are set to the corresponding values of the cms leg */
Real margin(boost::shared_ptr<CmsPricer> pricer, int precomputedSwaplets=0, double precomputedMargin=0.0, int swapletUpperBound=0, int precomputedFloatlets=0, int floatletUpperBound=0);
private:
vector<Date> fixings_,payments_,calc_;
vector<Date> floatFixings_,floatPayments_,floatCalc_;
vector<double> rates_,adjustedRates_,upperBound_;
boost::shared_ptr<SwapIndex> swapIndex_;
boost::shared_ptr<IborIndex> floatIndex_;
DayCounter couponDayCounter_,floatLegCouponDayCounter_;
double strike_,margin_;
int flavour_;
boost::shared_ptr<YieldTermStructure> floatDiscountCurve_;
};
}
#endif
| 35.720721 | 188 | 0.743253 | universe1987 |
416b984d852fec81708615caf4def63394124b70 | 1,056 | cpp | C++ | src/NeuralNetwork.cpp | lymven-io/NeuralNet | a1f997cea55d9e74e766c8a7f81e0d76e88f81b1 | [
"MIT"
] | null | null | null | src/NeuralNetwork.cpp | lymven-io/NeuralNet | a1f997cea55d9e74e766c8a7f81e0d76e88f81b1 | [
"MIT"
] | null | null | null | src/NeuralNetwork.cpp | lymven-io/NeuralNet | a1f997cea55d9e74e766c8a7f81e0d76e88f81b1 | [
"MIT"
] | null | null | null | #include "../include/NeuralNetwork.hpp"
void NeuralNetwork::printToConsole()
{
for(int i = 0; i < this->layers.size(); i++)
{
if(i == 0) {
Matrix *m = this->layers.at(i)->matrixifyVals();
m->printToConsole();
}
else {
Matrix *m = this->layers.at(i)->matrixifyActivatedVals();
m->printToConsole();
}
}
}
void NeuralNetwork::setCurrentInput(vector<double> input)
{
this->input = input;
for(int i = 0; i < input.size(); i++) {
this->layers.at(0)->setVal(i, input.at(i));
}
this->layers.at(0);
}
NeuralNetwork::NeuralNetwork(vector<int> topology) {
this->topology = topology;
this->topologySize = topology.size();
for(int i = 0; i < topology.size(); i++)
{
Layer *l = new Layer(topology.at(i));
this->layers.push_back(l);
}
for(int i = 0; i < (topologySize - 1); i++)
{
Matrix *m = new Matrix(topology.at(i), topology.at(i + 1), true);
this->weightMatrices.push_back(m);
}
} | 25.142857 | 73 | 0.542614 | lymven-io |
416def2f661532e2721ba6137ca76ccaa59f3195 | 72 | hpp | C++ | include/mruby_integration/shapes/pixel.hpp | HellRok/Taylor | aa9d901b4db77395a0bde896500016353adcd73b | [
"MIT"
] | 40 | 2021-05-25T04:21:49.000Z | 2022-02-19T05:05:45.000Z | include/mruby_integration/shapes/pixel.hpp | HellRok/Taylor | aa9d901b4db77395a0bde896500016353adcd73b | [
"MIT"
] | 4 | 2021-09-17T06:52:35.000Z | 2021-12-29T23:07:18.000Z | include/mruby_integration/shapes/pixel.hpp | HellRok/Taylor | aa9d901b4db77395a0bde896500016353adcd73b | [
"MIT"
] | 1 | 2021-12-23T00:59:27.000Z | 2021-12-23T00:59:27.000Z | #pragma once
#include "mruby.h"
void append_shapes_pixel(mrb_state*);
| 12 | 37 | 0.763889 | HellRok |
416e3d7562ab77b8fd720358d9d4ca7535311cce | 2,515 | cpp | C++ | compile/mclinker/lib/Target/Mips/MipsEmulation.cpp | Keneral/aframeworks | af1d0010bfb88751837fb1afc355705bd8a9ad8b | [
"Unlicense"
] | 75 | 2015-03-18T06:01:37.000Z | 2022-01-27T15:17:23.000Z | compile/mclinker/lib/Target/Mips/MipsEmulation.cpp | Keneral/aframeworks | af1d0010bfb88751837fb1afc355705bd8a9ad8b | [
"Unlicense"
] | 5 | 2015-07-08T07:47:25.000Z | 2018-10-08T12:12:04.000Z | compile/mclinker/lib/Target/Mips/MipsEmulation.cpp | Keneral/aframeworks | af1d0010bfb88751837fb1afc355705bd8a9ad8b | [
"Unlicense"
] | 28 | 2015-04-14T16:05:13.000Z | 2021-11-18T01:31:01.000Z | //===- MipsEmulation.cpp --------------------------------------------------===//
//
// The MCLinker Project
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "Mips.h"
#include "mcld/LinkerScript.h"
#include "mcld/LinkerConfig.h"
#include "mcld/Support/TargetRegistry.h"
#include "mcld/Target/ELFEmulation.h"
namespace mcld {
static bool MCLDEmulateMipsELF(LinkerScript& pScript, LinkerConfig& pConfig) {
if (!MCLDEmulateELF(pScript, pConfig))
return false;
// set up bitclass and endian
pConfig.targets().setEndian(TargetOptions::Little);
llvm::Triple::ArchType arch = pConfig.targets().triple().getArch();
assert(arch == llvm::Triple::mipsel || arch == llvm::Triple::mips64el);
unsigned bitclass = arch == llvm::Triple::mipsel ? 32 : 64;
pConfig.targets().setBitClass(bitclass);
// set up target-dependent constraints of attributes
pConfig.attribute().constraint().enableWholeArchive();
pConfig.attribute().constraint().enableAsNeeded();
pConfig.attribute().constraint().setSharedSystem();
// set up the predefined attributes
pConfig.attribute().predefined().unsetWholeArchive();
pConfig.attribute().predefined().unsetAsNeeded();
pConfig.attribute().predefined().setDynamic();
return true;
}
//===----------------------------------------------------------------------===//
// emulateMipsLD - the help function to emulate Mips ld
//===----------------------------------------------------------------------===//
bool emulateMipsLD(LinkerScript& pScript, LinkerConfig& pConfig) {
if (pConfig.targets().triple().isOSDarwin()) {
assert(0 && "MachO linker has not supported yet");
return false;
}
if (pConfig.targets().triple().isOSWindows()) {
assert(0 && "COFF linker has not supported yet");
return false;
}
return MCLDEmulateMipsELF(pScript, pConfig);
}
} // namespace mcld
//===----------------------------------------------------------------------===//
// MipsEmulation
//===----------------------------------------------------------------------===//
extern "C" void MCLDInitializeMipsEmulation() {
mcld::TargetRegistry::RegisterEmulation(mcld::TheMipselTarget,
mcld::emulateMipsLD);
mcld::TargetRegistry::RegisterEmulation(mcld::TheMips64elTarget,
mcld::emulateMipsLD);
}
| 36.985294 | 80 | 0.566998 | Keneral |
4171965d7b2f8f298c7d9367bd1de9df30a13c78 | 303 | cc | C++ | projects/extractMPISkeleton/tests/sample4/sample4/sample4.cc | maurizioabba/rose | 7597292cf14da292bdb9a4ef573001b6c5b9b6c0 | [
"BSD-3-Clause"
] | 488 | 2015-01-09T08:54:48.000Z | 2022-03-30T07:15:46.000Z | projects/extractMPISkeleton/tests/sample4/sample4/sample4.cc | sujankh/rose-matlab | 7435d4fa1941826c784ba97296c0ec55fa7d7c7e | [
"BSD-3-Clause"
] | 174 | 2015-01-28T18:41:32.000Z | 2022-03-31T16:51:05.000Z | projects/extractMPISkeleton/tests/sample4/sample4/sample4.cc | sujankh/rose-matlab | 7435d4fa1941826c784ba97296c0ec55fa7d7c7e | [
"BSD-3-Clause"
] | 146 | 2015-04-27T02:48:34.000Z | 2022-03-04T07:32:53.000Z | #include <iostream>
typedef float Real;
int main( )
{
int x=0;
#pragma skel loop iterate atleast(10)
for (int i=0; x < 100 ; i++) {
x = i + 1;
if (x % 2)
x += 5;
}
int j;
#pragma skel loop iterate atmost(30)
for (j=0; x < 100 ; j++) {
x = j + 1;
}
return x;
}
| 12.625 | 40 | 0.488449 | maurizioabba |
41719d9f5d2a3d432d638ae0f2cbc50467bc6b22 | 1,008 | cpp | C++ | C++/Operator/Logika/logika.cpp | rafipriatna/Belajar-Bahasa-Pemrograman | e6e1f00526897a9d37065d70f9509cb4db5a61f8 | [
"MIT"
] | 1 | 2019-11-26T06:06:34.000Z | 2019-11-26T06:06:34.000Z | C++/Operator/Logika/logika.cpp | rafipriatna/Belajar-Bahasa-Pemrograman | e6e1f00526897a9d37065d70f9509cb4db5a61f8 | [
"MIT"
] | null | null | null | C++/Operator/Logika/logika.cpp | rafipriatna/Belajar-Bahasa-Pemrograman | e6e1f00526897a9d37065d70f9509cb4db5a61f8 | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
int main(){
int a = 2;
int b = 6;
bool hasil;
// Operator NOT
cout << "Operator NOT : \n";
hasil = !(a == b);
cout << hasil << endl;
cout << endl;
// Operator AND
cout << "Operator AND : \n";
hasil = (a == 2) && (b == 6); // Benar dan Benar
cout << hasil << endl;
hasil = (a == 2) && (b == 5); // Benar dan Salah
cout << hasil << endl;
hasil = (a == 1) and (b == 5); // Salah dan Salah
cout << hasil << endl;
hasil = (a == 1) and (b == 6); // Salah dan Benar
cout << hasil << endl;
cout << endl;
// Operator OR
cout << "Operator OR : \n";
hasil = (a == 2) || (b == 6); // Benar dan Benar
cout << hasil << endl;
hasil = (a == 2) || (b == 5); // Benar dan Salah
cout << hasil << endl;
hasil = (a == 1) or (b == 5); // Salah dan Salah
cout << hasil << endl;
hasil = (a == 1) or (b == 6); // Salah dan Benar
cout << hasil << endl;
return 0;
} | 23.44186 | 53 | 0.46627 | rafipriatna |
4174b84df1271075afe71f1bb0f028e0b2917692 | 3,898 | cpp | C++ | examples/model.cpp | afranchuk/clipp | 74f40c1718acc0822a4338587b9bbea9fdc5f737 | [
"MIT"
] | 910 | 2017-11-08T20:27:19.000Z | 2022-03-31T03:35:11.000Z | examples/model.cpp | afranchuk/clipp | 74f40c1718acc0822a4338587b9bbea9fdc5f737 | [
"MIT"
] | 58 | 2017-11-15T20:13:10.000Z | 2022-03-26T20:14:22.000Z | examples/model.cpp | afranchuk/clipp | 74f40c1718acc0822a4338587b9bbea9fdc5f737 | [
"MIT"
] | 98 | 2017-11-11T00:02:07.000Z | 2022-03-29T06:54:19.000Z | /*****************************************************************************
*
* demo program - part of CLIPP (command line interfaces for modern C++)
*
* released under MIT license
*
* (c) 2017-2018 André Müller; foss@andremueller-online.de
*
*****************************************************************************/
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>
#include <clipp.h>
//-------------------------------------------------------------------
enum class mode {
none, train, validate, classify
};
struct settings {
mode selected = mode::none;
std::string imageFile;
std::string labelFile;
std::string modelFile = "out.mdl";
std::size_t batchSize = 128;
std::size_t threads = 0;
std::size_t inputLimit = 0;
std::vector<std::string> inputFiles;
};
//-------------------------------------------------------------------
settings configuration(int argc, char* argv[])
{
using namespace clipp;
settings s;
std::vector<std::string> unrecognized;
auto isfilename = clipp::match::prefix_not("-");
auto inputOptions = (
required("-i", "-I", "--img") & !value(isfilename, "image file", s.imageFile),
required("-l", "-L", "--lbl") & !value(isfilename, "label file", s.labelFile)
);
auto trainMode = (
command("train", "t", "T").set(s.selected,mode::train)
.if_conflicted([]{std::cerr << "conflicting modes\n"; }),
inputOptions,
(option("-n") & integer("limit", s.inputLimit))
% "limit number of input images",
(option("-o", "-O", "--out") & !value("model file", s.modelFile))
% "write model to specific file; default: 'out.mdl'",
(option("-b", "--batch-size") & integer("batch size", s.batchSize)),
(option("-p") & integer("threads", s.threads))
% "number of threads to use; default: optimum for machine"
);
auto validationMode = (
command("validate", "v", "V").set(s.selected,mode::validate),
!value(isfilename, "model", s.modelFile),
inputOptions
);
auto classificationMode = (
command("classify", "c", "C").set(s.selected,mode::classify),
!value(isfilename, "model", s.modelFile),
!values(isfilename, "images", s.inputFiles)
);
auto cli = (
trainMode | validationMode | classificationMode,
any_other(unrecognized)
);
auto res = parse(argc, argv, cli);
debug::print(std::cout, res);
if(!res || !unrecognized.empty()) {
std::string msg = "Wrong command line arguments!\n";
if(s.selected == mode::none) {
msg += "Please select a mode!\n";
}
else {
for(const auto& m : res.missing()) {
if(!m.param()->flags().empty()) {
msg += "Missing option: " + m.param()->flags().front() + '\n';
}
else if(!m.param()->label().empty()) {
msg += "Missing value: " + m.param()->label() + '\n';
}
}
for(const auto& arg : unrecognized) {
msg += "Argument not recognized: " + arg + '\n';
}
}
auto fmt = doc_formatting{}.first_column(8).doc_column(16);
//.max_flags_per_param_in_usage(3).surround_alternative_flags("(", ")");
msg += "\nUsage:\n" + usage_lines(cli, argv[0], fmt).str() + '\n';
msg += "\nOptions:\n" + documentation(cli, fmt).str() + '\n';
throw std::invalid_argument{msg};
}
return s;
}
//-------------------------------------------------------------------
int main(int argc, char* argv[])
{
try {
auto conf = configuration(argc, argv);
std::cout << "SUCCESS\n";
}
catch(std::exception& e) {
std::cerr << "ERROR: " << e.what() << '\n';
}
}
| 28.452555 | 86 | 0.491534 | afranchuk |
41770e60478c742e82f65457e4ad1a28ef475e5f | 6,064 | cc | C++ | ecs/src/model/DescribeSecurityGroupsRequest.cc | iamzken/aliyun-openapi-cpp-sdk | 3c991c9ca949b6003c8f498ce7a672ea88162bf1 | [
"Apache-2.0"
] | null | null | null | ecs/src/model/DescribeSecurityGroupsRequest.cc | iamzken/aliyun-openapi-cpp-sdk | 3c991c9ca949b6003c8f498ce7a672ea88162bf1 | [
"Apache-2.0"
] | null | null | null | ecs/src/model/DescribeSecurityGroupsRequest.cc | iamzken/aliyun-openapi-cpp-sdk | 3c991c9ca949b6003c8f498ce7a672ea88162bf1 | [
"Apache-2.0"
] | 1 | 2020-11-27T09:13:12.000Z | 2020-11-27T09:13:12.000Z | /*
* Copyright 2009-2017 Alibaba Cloud 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 <alibabacloud/ecs/model/DescribeSecurityGroupsRequest.h>
using AlibabaCloud::Ecs::Model::DescribeSecurityGroupsRequest;
DescribeSecurityGroupsRequest::DescribeSecurityGroupsRequest() :
RpcServiceRequest("ecs", "2014-05-26", "DescribeSecurityGroups")
{
setMethod(HttpRequest::Method::Post);
}
DescribeSecurityGroupsRequest::~DescribeSecurityGroupsRequest()
{}
long DescribeSecurityGroupsRequest::getResourceOwnerId()const
{
return resourceOwnerId_;
}
void DescribeSecurityGroupsRequest::setResourceOwnerId(long resourceOwnerId)
{
resourceOwnerId_ = resourceOwnerId;
setParameter("ResourceOwnerId", std::to_string(resourceOwnerId));
}
bool DescribeSecurityGroupsRequest::getFuzzyQuery()const
{
return fuzzyQuery_;
}
void DescribeSecurityGroupsRequest::setFuzzyQuery(bool fuzzyQuery)
{
fuzzyQuery_ = fuzzyQuery;
setParameter("FuzzyQuery", fuzzyQuery ? "true" : "false");
}
std::string DescribeSecurityGroupsRequest::getSecurityGroupId()const
{
return securityGroupId_;
}
void DescribeSecurityGroupsRequest::setSecurityGroupId(const std::string& securityGroupId)
{
securityGroupId_ = securityGroupId;
setParameter("SecurityGroupId", securityGroupId);
}
bool DescribeSecurityGroupsRequest::getIsQueryEcsCount()const
{
return isQueryEcsCount_;
}
void DescribeSecurityGroupsRequest::setIsQueryEcsCount(bool isQueryEcsCount)
{
isQueryEcsCount_ = isQueryEcsCount;
setParameter("IsQueryEcsCount", isQueryEcsCount ? "true" : "false");
}
std::string DescribeSecurityGroupsRequest::getNetworkType()const
{
return networkType_;
}
void DescribeSecurityGroupsRequest::setNetworkType(const std::string& networkType)
{
networkType_ = networkType;
setParameter("NetworkType", networkType);
}
std::string DescribeSecurityGroupsRequest::getSecurityGroupName()const
{
return securityGroupName_;
}
void DescribeSecurityGroupsRequest::setSecurityGroupName(const std::string& securityGroupName)
{
securityGroupName_ = securityGroupName;
setParameter("SecurityGroupName", securityGroupName);
}
int DescribeSecurityGroupsRequest::getPageNumber()const
{
return pageNumber_;
}
void DescribeSecurityGroupsRequest::setPageNumber(int pageNumber)
{
pageNumber_ = pageNumber;
setParameter("PageNumber", std::to_string(pageNumber));
}
std::string DescribeSecurityGroupsRequest::getResourceGroupId()const
{
return resourceGroupId_;
}
void DescribeSecurityGroupsRequest::setResourceGroupId(const std::string& resourceGroupId)
{
resourceGroupId_ = resourceGroupId;
setParameter("ResourceGroupId", resourceGroupId);
}
std::string DescribeSecurityGroupsRequest::getRegionId()const
{
return regionId_;
}
void DescribeSecurityGroupsRequest::setRegionId(const std::string& regionId)
{
regionId_ = regionId;
setParameter("RegionId", regionId);
}
int DescribeSecurityGroupsRequest::getPageSize()const
{
return pageSize_;
}
void DescribeSecurityGroupsRequest::setPageSize(int pageSize)
{
pageSize_ = pageSize;
setParameter("PageSize", std::to_string(pageSize));
}
std::vector<DescribeSecurityGroupsRequest::Tag> DescribeSecurityGroupsRequest::getTag()const
{
return tag_;
}
void DescribeSecurityGroupsRequest::setTag(const std::vector<Tag>& tag)
{
tag_ = tag;
for(int dep1 = 0; dep1!= tag.size(); dep1++) {
auto tagObj = tag.at(dep1);
std::string tagObjStr = "Tag." + std::to_string(dep1 + 1);
setParameter(tagObjStr + ".Value", tagObj.value);
setParameter(tagObjStr + ".Key", tagObj.key);
}
}
bool DescribeSecurityGroupsRequest::getDryRun()const
{
return dryRun_;
}
void DescribeSecurityGroupsRequest::setDryRun(bool dryRun)
{
dryRun_ = dryRun;
setParameter("DryRun", dryRun ? "true" : "false");
}
std::string DescribeSecurityGroupsRequest::getResourceOwnerAccount()const
{
return resourceOwnerAccount_;
}
void DescribeSecurityGroupsRequest::setResourceOwnerAccount(const std::string& resourceOwnerAccount)
{
resourceOwnerAccount_ = resourceOwnerAccount;
setParameter("ResourceOwnerAccount", resourceOwnerAccount);
}
std::string DescribeSecurityGroupsRequest::getOwnerAccount()const
{
return ownerAccount_;
}
void DescribeSecurityGroupsRequest::setOwnerAccount(const std::string& ownerAccount)
{
ownerAccount_ = ownerAccount;
setParameter("OwnerAccount", ownerAccount);
}
long DescribeSecurityGroupsRequest::getOwnerId()const
{
return ownerId_;
}
void DescribeSecurityGroupsRequest::setOwnerId(long ownerId)
{
ownerId_ = ownerId;
setParameter("OwnerId", std::to_string(ownerId));
}
std::string DescribeSecurityGroupsRequest::getSecurityGroupIds()const
{
return securityGroupIds_;
}
void DescribeSecurityGroupsRequest::setSecurityGroupIds(const std::string& securityGroupIds)
{
securityGroupIds_ = securityGroupIds;
setParameter("SecurityGroupIds", securityGroupIds);
}
std::string DescribeSecurityGroupsRequest::getSecurityGroupType()const
{
return securityGroupType_;
}
void DescribeSecurityGroupsRequest::setSecurityGroupType(const std::string& securityGroupType)
{
securityGroupType_ = securityGroupType;
setParameter("SecurityGroupType", securityGroupType);
}
std::string DescribeSecurityGroupsRequest::getVpcId()const
{
return vpcId_;
}
void DescribeSecurityGroupsRequest::setVpcId(const std::string& vpcId)
{
vpcId_ = vpcId;
setParameter("VpcId", vpcId);
}
| 26.025751 | 101 | 0.770613 | iamzken |
41780564bbf49892598f3708aef43749eaedd17a | 1,173 | hpp | C++ | Types/Containers/GpBytesArray.hpp | ITBear/GpCore2 | 7ae6d9d93aae55e2b3060077b5bb9d5f07e59ee4 | [
"MIT"
] | null | null | null | Types/Containers/GpBytesArray.hpp | ITBear/GpCore2 | 7ae6d9d93aae55e2b3060077b5bb9d5f07e59ee4 | [
"MIT"
] | 1 | 2020-06-19T18:38:40.000Z | 2020-06-19T18:38:40.000Z | Types/Containers/GpBytesArray.hpp | ITBear/GpCore2 | 7ae6d9d93aae55e2b3060077b5bb9d5f07e59ee4 | [
"MIT"
] | 6 | 2020-06-04T07:32:59.000Z | 2021-05-17T15:41:30.000Z | #pragma once
#include "../../Config/GpConfig.hpp"
#if defined(GP_USE_CONTAINERS)
#include "GpContainersT.hpp"
#include "../../Constexpr/GpConstexprIterator.hpp"
#include "../Pointers/GpRawPtr.hpp"
namespace GPlatform {
using GpBytesArray = GpVector<std::byte>;
class GpBytesArrayUtils
{
CLASS_REMOVE_CTRS_DEFAULT_MOVE_COPY(GpBytesArrayUtils)
public:
template<typename FROM, typename = std::enable_if_t<has_random_access_iter_v<FROM>, FROM>>
static GpBytesArray SMake (const FROM& aContainer)
{
GpBytesArray res;
const size_t size = aContainer.size();
res.resize(size);
MemOps::SCopy(res.data(),
reinterpret_cast<const std::byte*>(aContainer.data()),
count_t::SMake(size));
return res;
}
static GpBytesArray SMake (GpRawPtr<const std::byte*> aData)
{
GpBytesArray res;
res.resize(aData.CountLeft().As<size_t>());
GpRawPtr<std::byte*> resPtr(res);
resPtr.CopyFrom(aData);
return res;
}
};
}//GPlatform
#endif//#if defined(GP_USE_CONTAINERS)
| 24.957447 | 95 | 0.614663 | ITBear |
417b1b70e7606aacc175addf77c75c6a4037f285 | 16,048 | hpp | C++ | sprout/type_traits/std_type_traits.hpp | EzoeRyou/Sprout | 12e12373d0f70543eac5f2ecfbec8f5112765f98 | [
"BSL-1.0"
] | 1 | 2016-09-29T21:55:58.000Z | 2016-09-29T21:55:58.000Z | sprout/type_traits/std_type_traits.hpp | EzoeRyou/Sprout | 12e12373d0f70543eac5f2ecfbec8f5112765f98 | [
"BSL-1.0"
] | null | null | null | sprout/type_traits/std_type_traits.hpp | EzoeRyou/Sprout | 12e12373d0f70543eac5f2ecfbec8f5112765f98 | [
"BSL-1.0"
] | null | null | null | /*=============================================================================
Copyright (c) 2011-2014 Bolero MURAKAMI
https://github.com/bolero-MURAKAMI/Sprout
Distributed under 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)
=============================================================================*/
#ifndef SPROUT_TYPE_TRAITS_STD_TYPE_TRAITS_HPP
#define SPROUT_TYPE_TRAITS_STD_TYPE_TRAITS_HPP
#include <cstddef>
#include <type_traits>
#include <sprout/config.hpp>
#include <sprout/detail/predef.hpp>
#include <sprout/type_traits/detail/type_traits_wrapper.hpp>
#if !defined(_LIBCPP_VERSION) || (_LIBCPP_VERSION < 1101)
# include <sprout/tpp/algorithm/max_element.hpp>
#endif
namespace sprout {
// 20.10.4.1 Primary type categories
template<typename T>
struct is_void
: public sprout::detail::type_traits_wrapper<std::is_void<T> >
{};
template<typename T>
struct is_null_pointer
: public sprout::detail::type_traits_wrapper<std::is_same<typename std::remove_cv<T>::type, std::nullptr_t> >
{};
template<typename T>
struct is_integral
: public sprout::detail::type_traits_wrapper<std::is_integral<T> >
{};
template<typename T>
struct is_floating_point
: public sprout::detail::type_traits_wrapper<std::is_floating_point<T> >
{};
template<typename T>
struct is_array
: public sprout::detail::type_traits_wrapper<std::is_array<T> >
{};
template<typename T>
struct is_pointer
: public sprout::detail::type_traits_wrapper<std::is_pointer<T> >
{};
template<typename T>
struct is_lvalue_reference
: public sprout::detail::type_traits_wrapper<std::is_lvalue_reference<T> >
{};
template<typename T>
struct is_rvalue_reference
: public sprout::detail::type_traits_wrapper<std::is_rvalue_reference<T> >
{};
template<typename T>
struct is_member_object_pointer
: public sprout::detail::type_traits_wrapper<std::is_member_object_pointer<T> >
{};
template<typename T>
struct is_member_function_pointer
: public sprout::detail::type_traits_wrapper<std::is_member_function_pointer<T> >
{};
template<typename T>
struct is_enum
: public sprout::detail::type_traits_wrapper<std::is_enum<T> >
{};
template<typename T>
struct is_union
: public sprout::detail::type_traits_wrapper<std::is_union<T> >
{};
template<typename T>
struct is_class
: public sprout::detail::type_traits_wrapper<std::is_class<T> >
{};
template<typename T>
struct is_function
: public sprout::detail::type_traits_wrapper<std::is_function<T> >
{};
// 20.10.4.2 Composite type traits
template<typename T>
struct is_reference
: public sprout::detail::type_traits_wrapper<std::is_reference<T> >
{};
template<typename T>
struct is_arithmetic
: public sprout::detail::type_traits_wrapper<std::is_arithmetic<T> >
{};
template<typename T>
struct is_fundamental
: public sprout::detail::type_traits_wrapper<std::is_fundamental<T> >
{};
template<typename T>
struct is_object
: public sprout::detail::type_traits_wrapper<std::is_object<T> >
{};
template<typename T>
struct is_scalar
: public sprout::detail::type_traits_wrapper<std::is_scalar<T> >
{};
template<typename T>
struct is_compound
: public sprout::detail::type_traits_wrapper<std::is_compound<T> >
{};
template<typename T>
struct is_member_pointer
: public sprout::detail::type_traits_wrapper<std::is_member_pointer<T> >
{};
// 20.10.4.3 Type properties
template<typename T>
struct is_const
: public sprout::detail::type_traits_wrapper<std::is_const<T> >
{};
template<typename T>
struct is_volatile
: public sprout::detail::type_traits_wrapper<std::is_volatile<T> >
{};
template<typename T>
struct is_trivial
: public sprout::detail::type_traits_wrapper<std::is_trivial<T> >
{};
#if !defined(_LIBCPP_VERSION)
template<typename T>
struct is_trivially_copyable
: public sprout::is_scalar<typename std::remove_all_extents<T>::type>
{};
#else
template<typename T>
struct is_trivially_copyable
: public sprout::detail::type_traits_wrapper<std::is_trivially_copyable<T> >
{};
#endif
template<typename T>
struct is_standard_layout
: public sprout::detail::type_traits_wrapper<std::is_standard_layout<T> >
{};
template<typename T>
struct is_pod
: public sprout::detail::type_traits_wrapper<std::is_pod<T> >
{};
template<typename T>
struct is_literal_type
: public sprout::detail::type_traits_wrapper<std::is_literal_type<T> >
{};
template<typename T>
struct is_empty
: public sprout::detail::type_traits_wrapper<std::is_empty<T> >
{};
template<typename T>
struct is_polymorphic
: public sprout::detail::type_traits_wrapper<std::is_polymorphic<T> >
{};
template<typename T>
struct is_abstract
: public sprout::detail::type_traits_wrapper<std::is_abstract<T> >
{};
template<typename T>
struct is_signed
: public sprout::detail::type_traits_wrapper<std::is_signed<T> >
{};
template<typename T>
struct is_unsigned
: public sprout::detail::type_traits_wrapper<std::is_unsigned<T> >
{};
template<typename T, typename... Args>
struct is_constructible
: public sprout::detail::type_traits_wrapper<std::is_constructible<T, Args...> >
{};
template<typename T>
struct is_default_constructible
: public sprout::detail::type_traits_wrapper<std::is_default_constructible<T> >
{};
template<typename T>
struct is_copy_constructible
: public sprout::detail::type_traits_wrapper<std::is_copy_constructible<T> >
{};
template<typename T>
struct is_move_constructible
: public sprout::detail::type_traits_wrapper<std::is_move_constructible<T> >
{};
template<typename T, typename U>
struct is_assignable
: public sprout::detail::type_traits_wrapper<std::is_assignable<T, U> >
{};
template<typename T>
struct is_copy_assignable
: public sprout::detail::type_traits_wrapper<std::is_copy_assignable<T> >
{};
template<typename T>
struct is_move_assignable
: public sprout::detail::type_traits_wrapper<std::is_move_assignable<T> >
{};
template<typename T>
struct is_destructible
: public sprout::detail::type_traits_wrapper<std::is_destructible<T> >
{};
#if !defined(_LIBCPP_VERSION)
#if SPROUT_CLANG_HAS_FUTURE(is_trivially_constructible)
template<typename T, typename... Args>
struct is_trivially_constructible
: public sprout::integral_constant<bool, __is_trivially_constructible(T, Args...)>
{};
#else // #if SPROUT_CLANG_HAS_FUTURE(is_trivially_constructible)
template<typename T, typename... Args>
struct is_trivially_constructible
: public sprout::false_type
{};
#if SPROUT_CLANG_HAS_FUTURE(has_trivial_constructor) || SPROUT_GCC_OR_LATER(4, 3, 0)
template<typename T>
struct is_trivially_constructible<T>
: public sprout::integral_constant<bool, __has_trivial_constructor(T)>
{};
#else // #if SPROUT_CLANG_HAS_FUTURE(has_trivial_constructor) || SPROUT_GCC_OR_LATER(4, 3, 0)
template<typename T>
struct is_trivially_constructible<T>
: public sprout::is_scalar<T>
{};
#endif // #if SPROUT_CLANG_HAS_FUTURE(has_trivial_constructor) || SPROUT_GCC_OR_LATER(4, 3, 0)
template<typename T>
struct is_trivially_constructible<T, T&>
: public sprout::is_scalar<T>
{};
template<typename T>
struct is_trivially_constructible<T, T const&>
: public sprout::is_scalar<T>
{};
template<typename T>
struct is_trivially_constructible<T, T&&>
: public sprout::is_scalar<T>
{};
template<typename T>
struct is_trivially_constructible<T, T const&&>
: public sprout::is_scalar<T>
{};
#endif // #if SPROUT_CLANG_HAS_FUTURE(is_trivially_constructible)
template<typename T>
struct is_trivially_default_constructible
: public sprout::is_trivially_constructible<T>
{};
template<typename T>
struct is_trivially_copy_constructible
: public sprout::is_trivially_constructible<T, typename std::add_lvalue_reference<T>::type const>
{};
template<typename T>
struct is_trivially_move_constructible
: public sprout::is_trivially_constructible<T, typename std::add_rvalue_reference<T>::type const>
{};
#if SPROUT_CLANG_HAS_FUTURE(is_trivially_assignable)
template<typename T, typename U>
struct is_trivially_assignable
: public sprout::integral_constant<bool, __is_trivially_assignable(T, U)>
{};
#else // #if SPROUT_CLANG_HAS_FUTURE(is_trivially_assignable)
template<typename T, typename U>
struct is_trivially_assignable
: public sprout::false_type
{};
template<typename T>
struct is_trivially_assignable<T&, T>
: public sprout::is_scalar<T>
{};
template<typename T>
struct is_trivially_assignable<T&, T&>
: public sprout::is_scalar<T>
{};
template<typename T>
struct is_trivially_assignable<T&, T const&>
: public sprout::is_scalar<T>
{};
template<typename T>
struct is_trivially_assignable<T&, T&&>
: public sprout::is_scalar<T>
{};
template<typename T>
struct is_trivially_assignable<T&, T const&&>
: public sprout::is_scalar<T>
{};
#endif // #if SPROUT_CLANG_HAS_FUTURE(is_trivially_assignable)
template<typename T>
struct is_trivially_copy_assignable
: public sprout::is_trivially_assignable<
typename std::add_lvalue_reference<T>::type,
typename std::add_lvalue_reference<T>::type const
>
{};
template<typename T>
struct is_trivially_move_assignable
: public sprout::is_trivially_assignable<
typename std::add_lvalue_reference<T>::type,
typename std::add_rvalue_reference<T>::type
>
{};
#else // #if !defined(_LIBCPP_VERSION)
template<typename T, typename... Args>
struct is_trivially_constructible
: public sprout::detail::type_traits_wrapper<std::is_trivially_constructible<T, Args...> >
{};
template<typename T>
struct is_trivially_default_constructible
: public sprout::detail::type_traits_wrapper<std::is_trivially_default_constructible<T> >
{};
template<typename T>
struct is_trivially_copy_constructible
: public sprout::detail::type_traits_wrapper<std::is_trivially_copy_constructible<T> >
{};
template<typename T>
struct is_trivially_move_constructible
: public sprout::detail::type_traits_wrapper<std::is_trivially_move_constructible<T> >
{};
template<typename T, typename U>
struct is_trivially_assignable
: public sprout::detail::type_traits_wrapper<std::is_trivially_assignable<T, U> >
{};
template<typename T>
struct is_trivially_copy_assignable
: public sprout::detail::type_traits_wrapper<std::is_trivially_copy_assignable<T> >
{};
template<typename T>
struct is_trivially_move_assignable
: public sprout::detail::type_traits_wrapper<std::is_trivially_move_assignable<T> >
{};
#endif // #if !defined(_LIBCPP_VERSION)
#if !defined(_LIBCPP_VERSION) && SPROUT_GCC_EARLIER(4, 8, 0)
#if SPROUT_CLANG_HAS_FUTURE(has_trivial_destructor) || SPROUT_GCC_OR_LATER(4, 3, 0)
template<typename T>
struct is_trivially_destructible
: public sprout::integral_constant<bool, __has_trivial_destructor(T)>
{};
#else // #if SPROUT_CLANG_HAS_FUTURE(has_trivial_destructor) || SPROUT_GCC_OR_LATER(4, 3, 0)
template<typename T>
struct is_trivially_destructible
: public sprout::integral_constant<
bool,
std::is_scalar<typename std::remove_all_extents<T>::type>::value
|| std::is_reference<typename std::remove_all_extents<T>::type>::value
>
{};
#endif // #if SPROUT_CLANG_HAS_FUTURE(has_trivial_destructor) || SPROUT_GCC_OR_LATER(4, 3, 0)
#else // #if !defined(_LIBCPP_VERSION) && SPROUT_GCC_EARLIER(4, 8, 0)
template<typename T>
struct is_trivially_destructible
: public sprout::detail::type_traits_wrapper<std::is_trivially_destructible<T> >
{};
#endif // #if !defined(_LIBCPP_VERSION) && SPROUT_GCC_EARLIER(4, 8, 0)
template<typename T, typename... Args>
struct is_nothrow_constructible
: public sprout::detail::type_traits_wrapper<std::is_nothrow_constructible<T, Args...> >
{};
template<typename T>
struct is_nothrow_default_constructible
: public sprout::detail::type_traits_wrapper<std::is_nothrow_default_constructible<T> >
{};
template<typename T>
struct is_nothrow_copy_constructible
: public sprout::detail::type_traits_wrapper<std::is_nothrow_copy_constructible<T> >
{};
template<typename T>
struct is_nothrow_move_constructible
: public sprout::detail::type_traits_wrapper<std::is_nothrow_move_constructible<T> >
{};
template<typename T, typename U>
struct is_nothrow_assignable
: public sprout::detail::type_traits_wrapper<std::is_nothrow_assignable<T, U> >
{};
template<typename T>
struct is_nothrow_copy_assignable
: public sprout::detail::type_traits_wrapper<std::is_nothrow_copy_assignable<T> >
{};
template<typename T>
struct is_nothrow_move_assignable
: public sprout::detail::type_traits_wrapper<std::is_nothrow_move_assignable<T> >
{};
#if !defined(_LIBCPP_VERSION) && SPROUT_GCC_EARLIER(4, 8, 0)
template<typename T>
struct is_nothrow_destructible
: public sprout::integral_constant<
bool,
std::is_scalar<typename std::remove_all_extents<T>::type>::value
|| std::is_reference<typename std::remove_all_extents<T>::type>::value
>
{};
#else // #if !defined(_LIBCPP_VERSION) && SPROUT_GCC_EARLIER(4, 8, 0)
template<typename T>
struct is_nothrow_destructible
: public sprout::detail::type_traits_wrapper<std::is_nothrow_destructible<T> >
{};
#endif // #if !defined(_LIBCPP_VERSION) && SPROUT_GCC_EARLIER(4, 8, 0)
template<typename T>
struct has_virtual_destructor
: public sprout::detail::type_traits_wrapper<std::has_virtual_destructor<T> >
{};
// 20.10.5 Type property queries
template<typename T>
struct alignment_of
: public sprout::detail::type_traits_wrapper<std::alignment_of<T> >
{};
template<typename T>
struct rank
: public sprout::detail::type_traits_wrapper<std::rank<T> >
{};
template<typename T, unsigned I = 0>
struct extent
: public sprout::detail::type_traits_wrapper<std::extent<T, I> >
{};
// 20.10.6 Relationships between types
template<typename T, typename U>
struct is_same
: public sprout::detail::type_traits_wrapper<std::is_same<T, U> >
{};
template<typename From, typename To>
struct is_base_of
: public sprout::detail::type_traits_wrapper<std::is_base_of<From, To> >
{};
template<typename From, typename To>
struct is_convertible
: public sprout::detail::type_traits_wrapper<std::is_convertible<From, To> >
{};
// 20.10.7.1 Const-volatile modifications
using std::remove_const;
using std::remove_volatile;
using std::remove_cv;
using std::add_const;
using std::add_volatile;
using std::add_cv;
// 20.10.7.2 Reference modifications
using std::remove_reference;
using std::add_lvalue_reference;
using std::add_rvalue_reference;
// 20.10.7.3 Sign modifications
using std::make_signed;
using std::make_unsigned;
// 20.10.7.4 Array modifications
using std::remove_extent;
using std::remove_all_extents;
// 20.10.7.5 Pointer modifications
using std::remove_pointer;
using std::add_pointer;
// 20.10.7.6 Other transformations
using std::aligned_storage;
#if !defined(_LIBCPP_VERSION) || (_LIBCPP_VERSION < 1101)
template<std::size_t Len, typename... Types>
struct aligned_union
: public std::aligned_storage<
sprout::tpp::max_element_c<std::size_t, Len, sizeof(Types)...>::value,
sprout::tpp::max_element_c<std::size_t, std::alignment_of<Types>::value...>::value
>
{};
#else // #if !defined(_LIBCPP_VERSION) || (_LIBCPP_VERSION < 1101)
using std::aligned_union;
#endif // #if !defined(_LIBCPP_VERSION) || (_LIBCPP_VERSION < 1101)
using std::decay;
using std::enable_if;
using std::conditional;
using std::common_type;
using std::underlying_type;
using std::result_of;
} // namespace sprout
#endif // #ifndef SPROUT_TYPE_TRAITS_STD_TYPE_TRAITS_HPP
| 33.433333 | 112 | 0.730122 | EzoeRyou |
417c4a8dbd295fa9a54b47e487a667ba1b57d815 | 5,772 | cpp | C++ | src/common/test/test_term_tokenizer.cpp | datavetaren/prologcoin | 8583db7d99a8007f634210aefdfb92bf45596fd3 | [
"MIT"
] | 38 | 2017-06-14T07:13:10.000Z | 2022-02-16T15:41:25.000Z | src/common/test/test_term_tokenizer.cpp | datavetaren/prologcoin | 8583db7d99a8007f634210aefdfb92bf45596fd3 | [
"MIT"
] | 10 | 2017-07-01T11:13:10.000Z | 2021-02-27T05:40:30.000Z | src/common/test/test_term_tokenizer.cpp | datavetaren/prologcoin | 8583db7d99a8007f634210aefdfb92bf45596fd3 | [
"MIT"
] | 7 | 2017-07-05T20:38:51.000Z | 2021-08-02T04:30:46.000Z | #include <iostream>
#include <iomanip>
#include <assert.h>
#include <common/term_tokenizer.hpp>
#include <common/token_chars.hpp>
using namespace prologcoin::common;
static void header( const std::string &str )
{
std::cout << "\n";
std::cout << "--- [" + str + "] " + std::string(60 - str.length(), '-') << "\n";
std::cout << "\n";
}
static void test_is_symbol_char()
{
header( "test_is_symbol_char()" );
std::string str;
bool in_seq = false;
for (int i = 0; i < 500; i++) {
if (term_tokenizer::is_symbol_char(i)) {
if (!in_seq && !str.empty()) {
str += ", ";
}
if (!in_seq) {
str += boost::lexical_cast<std::string>(i);
}
if (!in_seq &&
term_tokenizer::is_symbol_char(i+1) &&
term_tokenizer::is_symbol_char(i+2)) {
in_seq = true;
}
}
if (in_seq && !term_tokenizer::is_symbol_char(i)) {
str += "..";
str += boost::lexical_cast<std::string>(i-1);
in_seq = false;
}
}
std::cout << "Symbol chars: " + str + "\n";
assert( str ==
"35, 36, 38, 42, 43, 45..47, 58, 60..64, 92, 94, 96, 126, "
"160..191, 215, 247");
}
static void test_tokens()
{
header( "test_tokens()" );
std::string s = "this is a test'\\^?\\^Z\\^a'\t\n\t+=/*bla/* ha */ xx *q*/\001%To/*themoon\xf0\n'foo'!0'a0'\\^g4242 42.4711 42e3 47.11e-12Foo_Bar\"string\"\"\\^g\" _Baz__ 'bar\x55'[;].";
std::string expected[] = { "token<NAME>[this]@(L1,C1)",
"token<LAYOUT_TEXT>[\\x20]@(L1,C5)",
"token<NAME>[is]@(L1,C6)",
"token<LAYOUT_TEXT>[\\x20]@(L1,C8)",
"token<NAME>[a]@(L1,C9)",
"token<LAYOUT_TEXT>[\\x20]@(L1,C10)",
"token<NAME>[test]@(L1,C11)",
"token<NAME>[\\x7f\\x1a\\x01]@(L1,C15)",
"token<LAYOUT_TEXT>[\\x09\\x0a\\x09]@(L1,C26)",
"token<NAME>[+=]@(L2,C8)",
"token<LAYOUT_TEXT>[/*bla/*\\x20ha\\x20*/\\x20xx\\x20*q*/\\x01%To/*themoon\\xf0\\x0a]@(L2,C10)",
"token<NAME>[foo]@(L3,C1)",
"token<NAME>[!]@(L3,C6)",
"token<NATURAL_NUMBER>[97]@(L3,C7)",
"token<NATURAL_NUMBER>[7]@(L3,C10)",
"token<NATURAL_NUMBER>[4242]@(L3,C15)",
"token<LAYOUT_TEXT>[\\x20]@(L3,C19)",
"token<UNSIGNED_FLOAT>[42.4711]@(L3,C20)",
"token<LAYOUT_TEXT>[\\x20]@(L3,C27)",
"token<UNSIGNED_FLOAT>[42e3]@(L3,C28)",
"token<LAYOUT_TEXT>[\\x20]@(L3,C32)",
"token<UNSIGNED_FLOAT>[47.11e-12]@(L3,C33)",
"token<VARIABLE>[Foo_Bar]@(L3,C42)",
"token<STRING>[string\\x22\\x07]@(L3,C49)",
"token<LAYOUT_TEXT>[\\x20]@(L3,C62)",
"token<VARIABLE>[_Baz__]@(L3,C63)",
"token<LAYOUT_TEXT>[\\x20]@(L3,C69)",
"token<NAME>[barU]@(L3,C70)",
"token<PUNCTUATION_CHAR>[[]@(L3,C76)",
"token<NAME>[;]@(L3,C77)",
"token<PUNCTUATION_CHAR>[]]@(L3,C78)",
"token<FULL_STOP>[.]@(L3,C79)" };
std::stringstream ss(s, (std::stringstream::in | std::stringstream::binary));
term_tokenizer tt(ss);
int cnt = 0;
while (tt.has_more_tokens()) {
auto tok = tt.next_token();
std::cout << tok.str() << "\n";
if (tok.str() != expected[cnt]) {
std::cout << "Expected token: " << expected[cnt] << "\n";
std::cout << "But got : " << tok.str() << "\n";
}
assert( tok.str() == expected[cnt] );
cnt++;
}
}
static void test_negative_tokens()
{
header( "test_negative_tokens()" );
struct entry { std::string str;
token_exception *exc;
};
auto p = [](int line, int col) { return token_position(line,col); };
entry table[] =
{ { "'foo", new token_exception_unterminated_quoted_name("",p(1,1)) }
,{ "'esc\\", new token_exception_unterminated_escape("",p(1,1)) }
,{ "'esc\\x", new token_exception_unterminated_escape("",p(1,1)) }
,{ "'esc\\x3", new token_exception_unterminated_escape("",p(1,1)) }
,{ "'esc\\^", new token_exception_unterminated_escape("",p(1,1)) }
,{ "'esc\\^\t", new token_exception_control_char("",p(1,1)) }
,{ "'esc\\xg", new token_exception_hex_code("", p(1,1)) }
,{ "0'", new token_exception_no_char_code("", p(1,1)) }
,{ "11'", new token_exception_missing_number_after_base("", p(1,1)) }
,{ "1.x", new token_exception_missing_decimal("", p(1,1)) }
,{ "1.e", new token_exception_missing_decimal("", p(1,1)) }
,{ "1ex", new token_exception_missing_exponent("", p(1,1)) }
,{ "1e+", new token_exception_missing_exponent("", p(1,1)) }
,{ "1e-", new token_exception_missing_exponent("", p(1,1)) }
,{ "2E-", new token_exception_missing_exponent("", p(1,1)) }
,{ "\"foo", new token_exception_unterminated_string("", p(1,1)) }
};
for (auto e : table) {
std::stringstream ss(e.str);
term_tokenizer tt(ss);
try {
std::cout << "Testing token: " << e.str << "\n";
tt.next_token();
std::cout << " (Expected exception '" << typeid(e.exc).name() << "' not thrown)\n";
assert(false);
} catch (token_exception &exc) {
std::string actual = typeid(exc).name();
std::string expected = typeid(*e.exc).name();
std::cout << " Thrown: " << actual << "\n";
if (actual != expected) {
std::cout << " (Expected exception '" << expected
<< "' but got '" << actual << "'\n";
assert(false);
}
if (exc.pos() != e.exc->pos()) {
std::cout << " (Expected position " << e.exc->pos().str()
<< " but got " << exc.pos().str() << ")\n";
assert(false);
}
delete e.exc; // Free memory (good for valgrind)
}
}
}
int main( int argc, char *argv[] )
{
test_is_symbol_char();
test_tokens();
test_negative_tokens();
return 0;
}
| 33.754386 | 190 | 0.537769 | datavetaren |
41810bee9ee062e7d157e3b6810e18d0ad0ab638 | 41 | cpp | C++ | libwinston/Route.cpp | danie1kr/winston | 18fe865dc59e8315cb1d85c6fa60c4ddeaf83202 | [
"MIT"
] | null | null | null | libwinston/Route.cpp | danie1kr/winston | 18fe865dc59e8315cb1d85c6fa60c4ddeaf83202 | [
"MIT"
] | null | null | null | libwinston/Route.cpp | danie1kr/winston | 18fe865dc59e8315cb1d85c6fa60c4ddeaf83202 | [
"MIT"
] | null | null | null | #include "Route.h"
namespace winston {
} | 10.25 | 19 | 0.707317 | danie1kr |
4181584b4077eb16adf436c1548283fa45fe66fc | 2,530 | cc | C++ | local/Ground.cc | jube/pong | df14055f4185a6b680acb9de685a94ccd6b33946 | [
"MIT"
] | null | null | null | local/Ground.cc | jube/pong | df14055f4185a6b680acb9de685a94ccd6b33946 | [
"MIT"
] | null | null | null | local/Ground.cc | jube/pong | df14055f4185a6b680acb9de685a94ccd6b33946 | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2015, Julien Bernard
*
* 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 "Ground.h"
#include "Ball.h"
#include "Events.h"
#include "Singletons.h"
Ground::Ground() {
gEventManager().registerHandler<BallLocationEvent>(&Ground::onBallLocation, this);
}
void Ground::render(sf::RenderWindow& window) {
sf::RectangleShape shape({ WIDTH, HEIGHT });
shape.setOrigin(WIDTH / 2, HEIGHT / 2);
shape.setPosition(0.0f, 0.0f);
shape.setFillColor(sf::Color::Black);
window.draw(shape);
}
game::EventStatus Ground::onBallLocation(game::EventType type, game::Event *event) {
auto loc = static_cast<BallLocationEvent*>(event);
static constexpr float Y_LIMIT = HEIGHT / 2 - Ball::RADIUS;
if (loc->position.y > Y_LIMIT) {
loc->velocity.y = -loc->velocity.y;
loc->position.y = Y_LIMIT;
}
if (loc->position.y < -Y_LIMIT) {
loc->velocity.y = -loc->velocity.y;
loc->position.y = -Y_LIMIT;
}
static constexpr float X_LIMIT = WIDTH / 2 - Ball::RADIUS;
if (loc->position.x > X_LIMIT) {
PointEvent point;
point.location = Paddle::Location::RIGHT;
gEventManager().triggerEvent(&point);
loc->velocity.x = -loc->velocity.x;
loc->position = sf::Vector2f(0, 0);
}
if (loc->position.x < -X_LIMIT) {
PointEvent point;
point.location = Paddle::Location::LEFT;
gEventManager().triggerEvent(&point);
loc->velocity.x = -loc->velocity.x;
loc->position = sf::Vector2f(0, 0);
}
return game::EventStatus::KEEP;
}
| 32.857143 | 84 | 0.706719 | jube |
41818d38234d8c35bf69d2d6bde7964c8054c9a5 | 13,341 | cpp | C++ | src/xrNetServer/NET_Compressor.cpp | clayne/xray-16 | 32ebf81a252c7179e2824b2874f911a91e822ad1 | [
"OML",
"Linux-OpenIB"
] | 2 | 2015-02-23T10:43:02.000Z | 2015-06-11T14:45:08.000Z | src/xrNetServer/NET_Compressor.cpp | clayne/xray-16 | 32ebf81a252c7179e2824b2874f911a91e822ad1 | [
"OML",
"Linux-OpenIB"
] | 17 | 2022-01-25T08:58:23.000Z | 2022-03-28T17:18:28.000Z | src/xrNetServer/NET_Compressor.cpp | clayne/xray-16 | 32ebf81a252c7179e2824b2874f911a91e822ad1 | [
"OML",
"Linux-OpenIB"
] | 1 | 2015-06-05T20:04:00.000Z | 2015-06-05T20:04:00.000Z | // NET_Compressor.cpp: implementation of the NET_Compressor class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "NET_Common.h"
#include "NET_Compressor.h"
#include "xrCore/Threading/Lock.hpp"
#if NET_USE_COMPRESSION
#if NET_USE_LZO_COMPRESSION
#define ENCODE rtc9_compress
#define DECODE rtc9_decompress
#else // NET_USE_LZO_COMPRESSION
#include "xrCore/ppmd_compressor.h"
#define ENCODE ppmd_compress
#define DECODE ppmd_decompress
#endif // NET_USE_LZO_COMPRESSION
#endif // NET_USE_COMPRESSION
#if 1 // def DEBUG
// static FILE* OriginalTrafficDump = NULL;
// static FILE* CompressedTrafficDump = NULL;
static FILE* RawTrafficDump = nullptr;
static FILE* CompressionDump = nullptr;
#endif // DEBUG
#define NOWARN
// size of range encoding code values
#define PPM_CODE_BITS 32
#define PPM_TOP_VALUE ((NET_Compressor::code_value)1 << (PPM_CODE_BITS - 1))
#define SHIFT_BITS (PPM_CODE_BITS - 9)
#define EXTRA_BITS ((PPM_CODE_BITS - 2) % 8 + 1)
#define PPM_BOTTOM_VALUE (PPM_TOP_VALUE >> 8)
/*
// c is written as first byte in the datastream
// one could do without c, but then you have an additional if
// per outputbyte.
void NET_Compressor::start_encoding(BYTE* dest, u32 header_size)
{
dest += header_size - 1;
RNGC.low = 0; // Full code range
RNGC.range = PPM_TOP_VALUE;
RNGC.buffer = 0;
RNGC.help = 0; // No bytes to follow
RNGC.bytecount = 0;
RNGC.ptr = dest;
}
// I do the normalization before I need a defined state instead of
// after messing it up. This simplifies starting and ending.
void NET_Compressor::encode_normalize()
{
while (RNGC.range <= PPM_BOTTOM_VALUE) // do we need renormalisation?
{
if (RNGC.low < code_value(0xff) << SHIFT_BITS) // no carry possible --> output
{
RNGC.byte_out(RNGC.buffer);
for (; RNGC.help; RNGC.help--)
RNGC.byte_out(0xff);
RNGC.buffer = (BYTE)(RNGC.low >> SHIFT_BITS);
}
else if (RNGC.low & PPM_TOP_VALUE) // carry now, no future carry
{
RNGC.byte_out(RNGC.buffer + 1);
for (; RNGC.help; RNGC.help--)
RNGC.byte_out(0);
RNGC.buffer = (BYTE)(RNGC.low >> SHIFT_BITS);
}
else // passes on a potential carry
{
RNGC.help++;
}
RNGC.range <<= 8;
RNGC.low = (RNGC.low << 8) & (PPM_TOP_VALUE - 1);
RNGC.bytecount ++;
}
}
// Encode a symbol using frequencies
// sy_f is the interval length (frequency of the symbol)
// lt_f is the lower end (frequency sum of < symbols)
// tot_f is the total interval length (total frequency sum)
// or (faster): tot_f = (code_value)1<<shift
void NET_Compressor::encode_freq(freq sy_f, freq lt_f, freq tot_f)
{
encode_normalize();
code_value r = RNGC.range / tot_f;
code_value tmp = r * lt_f;
RNGC.low += tmp;
if (lt_f + sy_f < tot_f) RNGC.range = r * sy_f;
else RNGC.range -= tmp;
}
void NET_Compressor::encode_shift(freq sy_f, freq lt_f, freq shift)
{
encode_normalize();
code_value r = RNGC.range >> shift;
code_value tmp = r * lt_f;
RNGC.low += tmp;
if ((lt_f + sy_f) >> shift) RNGC.range -= tmp;
else RNGC.range = r * sy_f;
}
// Finish encoding
// actually not that many bytes need to be output, but who
// cares. I output them because decode will read them :)
// the return value is the number of bytes written
u32 NET_Compressor::done_encoding()
{
encode_normalize(); // now we have a normalized state
RNGC.bytecount += 3;
u32 tmp = ((RNGC.low & (PPM_BOTTOM_VALUE - 1)) < ((RNGC.bytecount & 0xffffffL) >> 1))
? (RNGC.low >> SHIFT_BITS)
: (RNGC.low >> SHIFT_BITS) + 1;
if (tmp > 0xff) // we have a carry
{
RNGC.byte_out(RNGC.buffer + 1);
for (; RNGC.help; RNGC.help--)
RNGC.byte_out(0);
}
else // no carry
{
RNGC.byte_out(RNGC.buffer);
for (; RNGC.help; RNGC.help--)
RNGC.byte_out(0xff);
}
RNGC.byte_out((BYTE)(tmp & 0xff));
RNGC.byte_out(0);
return RNGC.bytecount;
}
// Start the decoder
int NET_Compressor::start_decoding(BYTE* src, u32 header_size)
{
src += header_size;
RNGC.ptr = src;
RNGC.buffer = RNGC.byte_in();
RNGC.low = RNGC.buffer >> (8 - EXTRA_BITS);
RNGC.range = (code_value)1 << EXTRA_BITS;
return 0;
}
void NET_Compressor::decode_normalize()
{
while (RNGC.range <= PPM_BOTTOM_VALUE)
{
RNGC.low = (RNGC.low << 8) | ((RNGC.buffer << EXTRA_BITS) & 0xff);
RNGC.buffer = RNGC.byte_in();
RNGC.low |= RNGC.buffer >> (8 - EXTRA_BITS);
RNGC.range <<= 8;
}
}
// Calculate culmulative frequency for next symbol. Does NO update!
// tot_f is the total frequency
// or: totf is (code_value)1<<shift
// returns the culmulative frequency
NET_Compressor::freq NET_Compressor::decode_culfreq(freq tot_f)
{
decode_normalize();
RNGC.help = RNGC.range / tot_f;
freq tmp = RNGC.low / RNGC.help;
return (tmp >= tot_f) ? (tot_f - 1) : (tmp);
}
NET_Compressor::freq NET_Compressor::decode_culshift(freq shift)
{
decode_normalize();
RNGC.help = RNGC.range >> shift;
freq tmp = RNGC.low / RNGC.help;
return (tmp >> shift) ? ((code_value(1) << shift) - 1) : (tmp);
}
// Update decoding state
// sy_f is the interval length (frequency of the symbol)
// lt_f is the lower end (frequency sum of < symbols)
// tot_f is the total interval length (total frequency sum)
void NET_Compressor::decode_update(freq sy_f, freq lt_f, freq tot_f)
{
code_value tmp = RNGC.help * lt_f;
RNGC.low -= tmp;
if (lt_f + sy_f < tot_f) RNGC.range = RNGC.help * sy_f;
else RNGC.range -= tmp;
}
// Decode a byte/short without modelling
BYTE NET_Compressor::decode_byte()
{
u32 tmp = decode_culshift(8);
decode_update(1, tmp, (freq)1 << 8);
return BYTE(tmp);
}
u16 NET_Compressor::decode_short()
{
u32 tmp = decode_culshift(16);
decode_update(1, tmp, (freq)1 << 16);
return u16(tmp);
}
// Finish decoding
// rc is the range coder to be used
void NET_Compressor::done_decoding()
{
decode_normalize(); // normalize to use up all bytes
}
*/
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
#ifdef CONFIG_PROFILE_LOCKS
NET_Compressor::NET_Compressor() : pcs(xr_new<Lock>(MUTEX_PROFILE_ID(NET_Compressor))) {}
#else
NET_Compressor::NET_Compressor() : pcs(xr_new<Lock>()) {}
#endif
NET_Compressor::~NET_Compressor()
{
#if 1 // def DEBUG
//if (strstr(Core.Params, "-dump_traffic"))
//{
// fclose(OriginalTrafficDump);
// fclose(CompressedTrafficDump);
//}
if (CompressionDump)
{
fclose(CompressionDump);
CompressionDump = nullptr;
}
if (RawTrafficDump)
{
fclose(RawTrafficDump);
RawTrafficDump = nullptr;
}
#endif // DEBUG
delete pcs;
}
/*
void NET_Compressor::Initialize ()
{
pcs->Enter();
#if 1//def DEBUG
if (strstr(Core.Params, "-dump_traffic"))
{
OriginalTrafficDump = fopen("x:/network_out_original.dat", "wb");
CompressedTrafficDump = fopen("x:/network_out_compressed.dat", "wb");
}
#endif // DEBUG
pcs->Leave();
}*/
u16 NET_Compressor::compressed_size(const u32& count) const
{
#if NET_USE_COMPRESSION
#if NET_USE_LZO_COMPRESSION
u32 result = rtc_csize(count) + 1;
#else // NET_USE_LZO_COMPRESSION
u32 result = 64 + (count / 8 + 1) * 10;
#endif // NET_USE_LZO_COMPRESSION
R_ASSERT(result <= u32(u16(-1)));
return (u16)result;
#else
return (u16)count;
#endif // #if NET_USE_COMPRESSION
}
XRNETSERVER_API BOOL g_net_compressor_enabled = FALSE;
XRNETSERVER_API BOOL g_net_compressor_gather_stats = FALSE;
u16 NET_Compressor::Compress(u8* dest, const u32& dest_size, u8* src, const u32& count)
{
SCompressorStats::SStatPacket* _p = nullptr;
bool b_compress_packet = (count > 36);
if (g_net_compressor_gather_stats && b_compress_packet)
{
_p = m_stats.get(count);
_p->hit_count += 1;
m_stats.total_uncompressed_bytes += count;
}
VERIFY(dest);
VERIFY(src);
VERIFY(count);
#if 0 // def DEBUG
if (strstr(Core.Params, "-dump_traffic"))
{
fwrite(src, count, 1, OriginalTrafficDump);
fflush(OriginalTrafficDump);
}
#endif // DEBUG
#if !NET_USE_COMPRESSION
CopyMemory(dest, src, count);
return (u16(count));
#else // !NET_USE_COMPRESSION
R_ASSERT(dest_size >= compressed_size(count));
u32 compressed_size = count;
u32 offset = 1;
#if NET_USE_COMPRESSION_CRC
offset += sizeof(u32);
#endif // NET_USE_COMPRESSION_CRC
if (!psNET_direct_connect && g_net_compressor_enabled && b_compress_packet)
{
pcs->Enter();
compressed_size = offset + ENCODE(dest + offset, dest_size - offset, src, count);
if (g_net_compressor_gather_stats)
m_stats.total_compressed_bytes += compressed_size;
pcs->Leave();
}
if (compressed_size < count)
{
*dest = NET_TAG_COMPRESSED;
#if NET_USE_COMPRESSION_CRC
u32 crc = crc32(dest + offset, compressed_size);
*((u32*)(dest + 1)) = crc;
#endif // NET_USE_COMPRESSION_CRC
#if NET_LOG_COMPRESSION
Msg("# compress %u->%u %02X (%08X)", count, compressed_size, *dest, *((u32*)(src + 1)));
#endif
#if NET_DUMP_COMPRESSION
#if NET_USE_LZO_COMPRESSION
static const char* compressor_name = "LZO";
#else
static const char* compressor_name = "PPMd";
#endif
if (!CompressionDump)
CompressionDump = fopen("net-compression.log", "w+b");
fprintf(CompressionDump, "%s compress %2.0f%% %u->%u\r\n", compressor_name,
100.0f * float(compressed_size) / float(count), count, compressed_size);
#endif // NET_DUMP_COMPRESSION
}
else
{
if (g_net_compressor_gather_stats && b_compress_packet)
_p->unlucky_attempts += 1;
*dest = NET_TAG_NONCOMPRESSED;
compressed_size = count + 1;
CopyMemory(dest + 1, src, count);
#if NET_LOG_COMPRESSION
Msg("# compress/as-is %u->%u %02X", count, compressed_size, *dest);
#endif
}
if (g_net_compressor_gather_stats && b_compress_packet)
_p->compressed_size += compressed_size;
#if 0 // def DEBUG
if (strstr(Core.Params, "-dump_traffic"))
{
fwrite(dest, compressed_size, 1, CompressedTrafficDump);
fflush(CompressedTrafficDump);
}
#endif // DEBUG
#if 0 //def DEBUG
u8* src_back = (u8*)xr_alloca(count);
Decompress(src_back, count, dest, compressed_size);
u8* I = src_back;
u8* E = src_back + count;
u8* J = src;
for (; I != E; ++I , ++J)
VERIFY (*I == *J);
pcs->Leave();
#endif // DEBUG
return (u16(compressed_size));
#endif // if !NET_USE_COMPRESSION
}
u16 NET_Compressor::Decompress(u8* dest, const u32& dest_size, u8* src, const u32& count)
{
VERIFY(dest);
VERIFY(src);
VERIFY(count);
#if NET_LOG_COMPRESSION
Msg("# decompress %u %02X (%08X)", count, src[0], *((u32*)(src + 1)));
#endif
#if NET_USE_COMPRESSSION
if (src[0] != NET_TAG_COMPRESSED && src[0] != NET_TAG_NONCOMPRESSED)
{
Msg("! invalid compression-tag %02X", src[0]);
DEBUG_BREAK;
}
#endif // NET_USE_COMPRESSSION
#if !NET_USE_COMPRESSION
CopyMemory(dest, src, count);
return (u16(count));
#else
if (*src != NET_TAG_COMPRESSED)
{
if (count)
{
CopyMemory(dest, src + 1, count - 1);
return (u16(count - 1));
}
return (0);
}
u32 offset = 1;
#if NET_USE_COMPRESSION_CRC
offset += sizeof(u32);
#endif // NET_USE_COMPRESSION_CRC
#if NET_USE_COMPRESSION_CRC
u32 crc = crc32(src + offset, count);
//Msg("decompressed %d -> ? [0x%08x]", count, crc);
if (crc != *((u32*)(src + 1)))
Msg("! CRC mismatch");
R_ASSERT2(crc == *((u32*)(src + 1)), make_string("crc is different! (0x%08x != 0x%08x)", crc, *((u32*)(src + 1))));
#endif // NET_USE_COMPRESSION_CRC
pcs->Enter();
u32 uncompressed_size = DECODE(dest, dest_size, src + offset, count - offset);
pcs->Leave();
return (u16)uncompressed_size;
#endif // !NET_USE_COMPRESSION
}
void NET_Compressor::DumpStats(bool brief) const
{
auto cit = m_stats.m_packets.cbegin();
auto cit_e = m_stats.m_packets.cend();
Msg("---------NET_Compressor::DumpStats-----------");
Msg("Active=[%s]", g_net_compressor_enabled ? "yes" : "no");
Msg("uncompressed [%d]", m_stats.total_uncompressed_bytes);
Msg("compressed [%d]", m_stats.total_compressed_bytes);
u32 total_hits = 0;
u32 unlucky_hits = 0;
for (; cit != cit_e; ++cit)
{
total_hits += cit->second.hit_count;
unlucky_hits += cit->second.unlucky_attempts;
if (!brief)
{
Msg("size[%d] count[%d] unlucky[%d] avg_c[%d]", cit->first, cit->second.hit_count,
cit->second.unlucky_attempts, iFloor(float(cit->second.compressed_size) / float(cit->second.hit_count)));
}
}
Msg("total [%d]", total_hits);
Msg("unlucky [%d]", unlucky_hits);
}
| 25.705202 | 121 | 0.623716 | clayne |
41868d148862cc4c37bf157b2c06ca6d9b488c22 | 1,002 | cpp | C++ | 14/tests/into.cpp | rapha-opensource/viper | 78f25771c7198ac66b846afde3f38c8b2c1c7cc9 | [
"MIT"
] | 2 | 2018-04-28T19:54:49.000Z | 2021-01-13T17:31:12.000Z | 17/tests/into.cpp | rapha-opensource/viper | 78f25771c7198ac66b846afde3f38c8b2c1c7cc9 | [
"MIT"
] | null | null | null | 17/tests/into.cpp | rapha-opensource/viper | 78f25771c7198ac66b846afde3f38c8b2c1c7cc9 | [
"MIT"
] | null | null | null | #include <vector>
#include "catch.hpp"
#include "../headers/iterator_cast.h"
SCENARIO(" 'into' with only an input container, no transformation", "[into]") {
GIVEN(" a std::vector<char> vc") {
std::vector<char> vc{'a','b','c','d'};
WHEN( " make a string using into<std::string>(vc) " ) {
auto str = into<std::string>(vc);
THEN(" the size and value match ") {
REQUIRE( str.size() == vc.size() );
REQUIRE( str == "abcd" );
}
}
}
}
SCENARIO( " 'into' with a unary fn ", "[into], [transform]") {
GIVEN(" a std::vector<int> ") {
std::vector<int> vi{1,2,3,4};
WHEN(" transformed 'into' in a string ") {
auto str = into<std::string>([](const int& i) { return (char)(i+48); }, vi);
THEN(" must match in size and content ") {
REQUIRE( str.size() == vi.size() );
REQUIRE( str == "1234" );
}
}
}
}
| 23.302326 | 89 | 0.474052 | rapha-opensource |
4189e9260add3f96370d11651bb4c773844223d5 | 2,658 | cpp | C++ | contracts/calculator/calc.cpp | koinos/koinos-contract-examples | 27f2bd11b31997ac69d824a5d8a729295072a4c3 | [
"MIT"
] | 1 | 2021-12-21T20:01:36.000Z | 2021-12-21T20:01:36.000Z | contracts/calculator/calc.cpp | koinos/koinos-contract-examples | 27f2bd11b31997ac69d824a5d8a729295072a4c3 | [
"MIT"
] | null | null | null | contracts/calculator/calc.cpp | koinos/koinos-contract-examples | 27f2bd11b31997ac69d824a5d8a729295072a4c3 | [
"MIT"
] | 1 | 2021-11-23T19:10:26.000Z | 2021-11-23T19:10:26.000Z | #include <koinos/system/system_calls.hpp>
#include <koinos/buffer.hpp>
#include <koinos/common.h>
#include <calc.h>
using namespace koinos;
using namespace koinos::contracts;
enum entries : uint32_t
{
add_entry = 1,
sub_entry = 2,
mul_entry = 3,
div_entry = 4
};
class calculator
{
public:
calc::add_result add( int64_t x, int64_t y ) noexcept;
calc::sub_result sub( int64_t x, int64_t y ) noexcept;
calc::mul_result mul( int64_t x, int64_t y ) noexcept;
calc::div_result div( int64_t x, int64_t y ) noexcept;
};
calc::add_result calculator::add( int64_t x, int64_t y ) noexcept
{
calc::add_result res;
res.set_value( x + y );
return res;
}
calc::sub_result calculator::sub( int64_t x, int64_t y ) noexcept
{
calc::sub_result res;
res.set_value( x - y );
return res;
}
calc::mul_result calculator::mul( int64_t x, int64_t y ) noexcept
{
calc::mul_result res;
res.set_value( x * y );
return res;
}
calc::div_result calculator::div( int64_t x, int64_t y ) noexcept
{
calc::div_result res;
if ( y == 0 )
{
system::print( "cannot divide by zero" );
system::exit_contract( 1 );
}
res.set_value( x / y );
return res;
}
int main()
{
auto entry_point = system::get_entry_point();
auto args = system::get_contract_arguments();
std::array< uint8_t, 32 > retbuf;
koinos::read_buffer rdbuf( (uint8_t*)args.c_str(), args.size() );
koinos::write_buffer buffer( retbuf.data(), retbuf.size() );
calculator c;
switch( entry_point )
{
case entries::add_entry:
{
calc::add_arguments args;
args.deserialize( rdbuf );
auto res = c.add( args.x(), args.y() );
res.serialize( buffer );
break;
}
case entries::sub_entry:
{
calc::sub_arguments args;
args.deserialize( rdbuf );
auto res = c.sub( args.x(), args.y() );
res.serialize( buffer );
break;
}
case entries::mul_entry:
{
calc::mul_arguments args;
args.deserialize( rdbuf );
auto res = c.mul( args.x(), args.y() );
res.serialize( buffer );
break;
}
case entries::div_entry:
{
calc::div_arguments args;
args.deserialize( rdbuf );
auto res = c.div( args.x(), args.y() );
res.serialize( buffer );
break;
}
default:
system::exit_contract( 1 );
}
std::string retval( reinterpret_cast< const char* >( buffer.data() ), buffer.get_size() );
system::set_contract_result_bytes( retval );
system::exit_contract( 0 );
return 0;
}
| 21.435484 | 93 | 0.599323 | koinos |
418bdfec7fda7154914b35e520e56e4938b33c3b | 1,198 | cpp | C++ | Foundation/src/ASN1Codec.cpp | RangelReale/poco | b5d9177abebac49da74722b5f193958dbef1ce94 | [
"BSL-1.0"
] | null | null | null | Foundation/src/ASN1Codec.cpp | RangelReale/poco | b5d9177abebac49da74722b5f193958dbef1ce94 | [
"BSL-1.0"
] | null | null | null | Foundation/src/ASN1Codec.cpp | RangelReale/poco | b5d9177abebac49da74722b5f193958dbef1ce94 | [
"BSL-1.0"
] | 1 | 2021-07-16T12:16:40.000Z | 2021-07-16T12:16:40.000Z | //
// ASN1Codec.cpp
//
// $Id: //poco/1.4/Foundation/src/ASN1Codec.cpp#1 $
//
// Library: Foundation
// Package: Streams
// Module: ASN1Codec
//
// Copyright (c) 2010, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "Poco/ASN1Codec.h"
#include "Poco/ASN1FactoryDefault.h"
#include "Poco/BinaryReader.h"
#include "Poco/BinaryWriter.h"
namespace Poco {
ASN1Codec::ASN1Codec() : _factory(new ASN1FactoryDefault)
{
}
ASN1Codec::ASN1Codec(Poco::SharedPtr<ASN1Factory> factory) : _factory(factory)
{
if (factory.isNull())
throw InvalidArgumentException("Factory is required");
}
void ASN1Codec::setFactory(Poco::SharedPtr<ASN1Factory> factory)
{
if (factory.isNull())
throw InvalidArgumentException("Factory is required");
_factory = factory;
}
void ASN1Codec::encode(ASN1::Ptr data, std::ostream &stream)
{
Poco::BinaryWriter swrite(stream);
data->encode(swrite);
}
ASN1::Ptr ASN1Codec::decode(std::istream &stream)
{
ASN1::Ptr ret;
Poco::BinaryReader sread(stream);
ASN1Type tp;
tp.decodeData(sread);
ret = _factory->create(tp);
ret->decode(_factory, sread);
return ret;
}
} // namespace Poco
| 16.873239 | 78 | 0.715359 | RangelReale |
418d9b77a6c64fdf521ccc324cec54c858d1fc4a | 2,233 | cc | C++ | re2c/src/codegen/helpers.cc | adesutherland/crexx | e8d17152c565e9387ee8c33c653b4910b56f5165 | [
"MIT"
] | 8 | 2020-11-08T15:36:14.000Z | 2022-03-27T13:50:07.000Z | re2c/src/codegen/helpers.cc | adesutherland/crexx | e8d17152c565e9387ee8c33c653b4910b56f5165 | [
"MIT"
] | 98 | 2020-11-12T11:49:41.000Z | 2022-03-27T17:24:13.000Z | re2c/src/codegen/helpers.cc | adesutherland/crexx | e8d17152c565e9387ee8c33c653b4910b56f5165 | [
"MIT"
] | 10 | 2021-03-31T13:50:52.000Z | 2021-12-02T03:34:42.000Z | #include <iostream>
#include "src/codegen/helpers.h"
namespace re2c {
static bool is_space(uint32_t c)
{
switch (c) {
case '\t':
case '\f':
case '\v':
case '\n':
case '\r':
case ' ': return true;
default: return false;
}
}
static inline char hex(uint32_t c)
{
static const char * sHex = "0123456789ABCDEF";
return sHex[c & 0x0F];
}
static void prtCh(std::ostream& o, uint32_t c, bool dot)
{
switch (c) {
case '\'': o << (dot ? "'" : "\\'"); break;
case '"': o << (dot ? "\\\"" : "\""); break;
case '\n': o << (dot ? "\\\\n" : "\\n"); break;
case '\t': o << (dot ? "\\\\t" : "\\t"); break;
case '\v': o << (dot ? "\\\\v" : "\\v"); break;
case '\b': o << (dot ? "\\\\b" : "\\b"); break;
case '\r': o << (dot ? "\\\\r" : "\\r"); break;
case '\f': o << (dot ? "\\\\f" : "\\f"); break;
case '\a': o << (dot ? "\\\\a" : "\\a"); break;
case '\\': o << "\\\\"; break; // both .dot and C/C++ code expect "\\"
default: o << static_cast<char> (c); break;
}
}
bool is_print(uint32_t c)
{
return c >= 0x20 && c < 0x7F;
}
void prtHex(std::ostream& o, uint32_t c, uint32_t szcunit)
{
o << "0x";
if (szcunit >= 4) {
o << hex(c >> 28u) << hex(c >> 24u) << hex(c >> 20u) << hex(c >> 16u);
}
if (szcunit >= 2) {
o << hex(c >> 12u) << hex(c >> 8u);
}
o << hex(c >> 4u) << hex(c);
}
void prtChOrHex(std::ostream& o, uint32_t c, uint32_t szcunit, bool ebcdic, bool dot)
{
if (!ebcdic && (is_print(c) || is_space(c))) {
o << '\'';
prtCh(o, c, dot);
o << '\'';
} else {
prtHex(o, c, szcunit);
}
}
static void prtChOrHexForSpan(std::ostream& o, uint32_t c, uint32_t szcunit, bool ebcdic, bool dot)
{
if (!ebcdic && c != ']' && is_print(c)) {
prtCh(o, c, dot);
} else {
prtHex(o, c, szcunit);
}
}
void printSpan(std::ostream& o, uint32_t l, uint32_t u, uint32_t szcunit, bool ebcdic, bool dot)
{
o << "[";
prtChOrHexForSpan(o, l, szcunit, ebcdic, dot);
if (u - l > 1) {
o << "-";
prtChOrHexForSpan(o, u - 1, szcunit, ebcdic, dot);
}
o << "]";
}
} // namespace re2c
| 23.260417 | 99 | 0.467532 | adesutherland |
418df50b16205e781e5fc25d772cd4ffbaf5a2c1 | 311 | cpp | C++ | beginners/easy/014.grade-description/034.rishankahn.grade-description.cpp | Md-Maruf-Sarker/strangers | 6f9eae6c15f1e1c5b6ef2965eb2422a01203f1ad | [
"MIT"
] | 3 | 2022-03-26T17:56:38.000Z | 2022-03-27T10:47:26.000Z | beginners/easy/014.grade-description/034.rishankahn.grade-description.cpp | Md-Maruf-Sarker/strangers | 6f9eae6c15f1e1c5b6ef2965eb2422a01203f1ad | [
"MIT"
] | null | null | null | beginners/easy/014.grade-description/034.rishankahn.grade-description.cpp | Md-Maruf-Sarker/strangers | 6f9eae6c15f1e1c5b6ef2965eb2422a01203f1ad | [
"MIT"
] | 8 | 2022-03-26T18:19:49.000Z | 2022-03-31T18:18:34.000Z | #include <iostream>
using namespace std;
int main() {
char g;
cout<<"Input the grade : ";
cin>>g;
if(g=='E'){
cout<<"Excellent\n";
}
else if(g=='V'){
cout<<"Very Good\n";
}
else if(g=='G'){
cout<<"Good\n";
}
else if(g=='A'){
cout<<"Average\n";
}
else{
cout<<"Fail\n";
}
}
| 12.958333 | 28 | 0.495177 | Md-Maruf-Sarker |
418e73335586695d6d3a4a1a90da24abbbdcc2f6 | 529 | cpp | C++ | core/CameraSystemProcessor.cpp | ChaosKit/ChaosKit | e7cba03db1ae34160868656ea357c7166ae1d84a | [
"Apache-2.0"
] | 3 | 2021-01-09T17:25:18.000Z | 2021-07-11T00:04:22.000Z | core/CameraSystemProcessor.cpp | ChaosKit/ChaosKit | e7cba03db1ae34160868656ea357c7166ae1d84a | [
"Apache-2.0"
] | 1 | 2021-03-21T13:17:04.000Z | 2021-03-21T14:03:46.000Z | core/CameraSystemProcessor.cpp | ChaosKit/ChaosKit | e7cba03db1ae34160868656ea357c7166ae1d84a | [
"Apache-2.0"
] | 1 | 2020-04-03T16:32:53.000Z | 2020-04-03T16:32:53.000Z | #include "CameraSystemProcessor.h"
namespace chaoskit::core {
void CameraSystemProcessor::setCameraSystem(const CameraSystem& cameraSystem) {
setSystem(cameraSystem.system);
setCamera(cameraSystem.camera);
}
SystemParticle CameraSystemProcessor::processCamera(
SystemParticle input) const {
if (!camera_) return input;
SystemParticle output = input;
output.applyParticle(interpreter_.interpret(
input.asParticle(), camera_->transform, camera_->params));
return output;
}
} // namespace chaoskit::core
| 25.190476 | 79 | 0.769376 | ChaosKit |
419050b5d7d6c529e2ce372b58fcd687d264f826 | 11,356 | cpp | C++ | 2d ball game/TextRenderer.cpp | DennisWandschura/GravBall | f140e304368ce1bfb9a8750c5a5c68ceac4c24bd | [
"MIT"
] | null | null | null | 2d ball game/TextRenderer.cpp | DennisWandschura/GravBall | f140e304368ce1bfb9a8750c5a5c68ceac4c24bd | [
"MIT"
] | null | null | null | 2d ball game/TextRenderer.cpp | DennisWandschura/GravBall | f140e304368ce1bfb9a8750c5a5c68ceac4c24bd | [
"MIT"
] | null | null | null | /*
The MIT License (MIT)
Copyright (c) 2015 Dennis Wandschura
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 "TextRenderer.h"
#include <vxLib/File/FileHandle.h>
#include "ResourceDesc.h"
#include "d3d.h"
#include <vxlib/Graphics/Font.h>
#include <vxlib/Graphics/Texture.h>
#include "UploadManager.h"
#include <gamelib/MainAllocator.h>
#include "GpuResourceManager.h"
//#include "RenderPassText.h"
//#include "ResourceView.h"
namespace Graphics
{
struct TextRenderer::Entry
{
char m_text[48];
vx::float4 m_color;
vx::float2 m_position;
u32 m_size;
};
struct TextRenderer::TextVertex
{
vx::float3 position;
vx::float2 uv;
vx::float4 color;
};
TextRenderer::TextRenderer()
:m_entries(),
m_vertices(),
m_drawTextProgram(nullptr),
m_size(0),
m_capacity(0),
m_texureIndex(0),
m_font(nullptr)
{
}
TextRenderer::~TextRenderer()
{
}
void TextRenderer::getRequiredMemory(u64* bufferSize, u32* bufferCount, u64* textureSize, u32*textureCount, ID3D12Device* device, u32 maxCharacters)
{
const auto verticesPerCharacter = 4u;
auto totalVertexCount = verticesPerCharacter * maxCharacters;
const auto indicesPerCharacter = 6u;
auto indexCount = indicesPerCharacter * maxCharacters;
auto vertexSizeInBytes = totalVertexCount * sizeof(TextVertex);
auto indexSizeInBytes = indexCount * sizeof(u32);
auto fontTexResDesc = d3d::ResourceDesc::createDescTexture2D(vx::uint3(1024, 1024, 1), DXGI_FORMAT_R8G8B8A8_UNORM_SRGB, D3D12_RESOURCE_FLAG_NONE);
auto fontTexAllocInfo = device->GetResourceAllocationInfo(1, 1,&fontTexResDesc);
*textureSize += fontTexAllocInfo.SizeInBytes;
*bufferSize += vx::getAlignedSize(vertexSizeInBytes, 64llu KBYTE) + vx::getAlignedSize(indexSizeInBytes, 64llu KBYTE);
*bufferCount += 2;
*textureCount += 1;
}
bool TextRenderer::createData(ID3D12Device* device, GpuResourceManager* resourceManager, UploadManager* uploadManager, u32 maxCharacters)
{
//auto fontTexResDesc = d3d::ResourceDesc::createDescTexture2D(vx::uint3(1024, 1024, 3), DXGI_FORMAT_R8G8B8A8_UNORM_SRGB);
//auto fontTexAllocInfo = device->GetResourceAllocationInfo(1, 1, &fontTexResDesc);
const auto verticesPerCharacter = 4u;
auto totalVertexCount = verticesPerCharacter * maxCharacters;
const auto indicesPerCharacter = 6u;
auto indexCount = indicesPerCharacter * maxCharacters;
auto vertexSizeInBytes = vx::getAlignedSize(vx::getAlignedSize(totalVertexCount * sizeof(TextVertex), 256) * 2, 64llu KBYTE);
auto indexSizeInBytes = vx::getAlignedSize(vx::getAlignedSize(indexCount * sizeof(u32), 256), 64llu KBYTE);
if(!resourceManager->createTextureResource("fontTexture", vx::uint3(1024, 1024, 1), DXGI_FORMAT_R8G8B8A8_UNORM_SRGB, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, nullptr))
{
return false;
}
if (!resourceManager->createBufferResource("textVertexBuffer", vertexSizeInBytes, D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER))
{
return false;
}
if (!resourceManager->createBufferResource("textIndexBuffer", indexSizeInBytes, D3D12_RESOURCE_STATE_INDEX_BUFFER))
{
return false;
}
return true;
}
bool TextRenderer::initialize(u32 maxCharacters, Allocator::MainAllocator* allocator, UploadManager* uploadManager, ID3D12Device* device, GpuResourceManager* resourceManager, DrawTextProgram* drawTextProgram)
{
m_capacity = maxCharacters;
if (!createData(device, resourceManager, uploadManager, maxCharacters))
return false;
vx::array<Entry, DebugAllocatorRenderer<Allocator::MainAllocator>> entries(allocator, s_maxEntryCount);
m_entries.swap(entries);
const auto verticesPerCharacter = 4u;
auto totalVertexCount = verticesPerCharacter * m_capacity;
const auto indicesPerCharacter = 6u;
auto indexCount = indicesPerCharacter * m_capacity;
//auto vertexSizeInBytes = vx::getAlignedSize(totalVertexCount * sizeof(TextVertex), 64llu KBYTE);
//auto indexSizeInBytes = (indexCount * sizeof(u32), 64llu KBYTE);
/*
m_renderPassText = desc->m_renderPassText;
auto textVertexBuffer = desc->resourceManager->getBuffer(L"textVertexBuffer");
d3d::ResourceView vbv;
vbv.vbv.BufferLocation = textVertexBuffer->GetGPUVirtualAddress();
vbv.vbv.SizeInBytes = vertexSizeInBytes;
vbv.vbv.StrideInBytes = sizeof(TextVertex);
vbv.type = d3d::ResourceView::Type::VertexBufferView;
desc->resourceManager->insertResourceView("textVbv", vbv);
auto textIndexBuffer = desc->resourceManager->getBuffer(L"textIndexBuffer");
d3d::ResourceView textIbv;
textIbv.type = d3d::ResourceView::Type::IndexBufferView;
textIbv.ibv.BufferLocation = textIndexBuffer->GetGPUVirtualAddress();
textIbv.ibv.Format = DXGI_FORMAT_R32_UINT;
textIbv.ibv.SizeInBytes = indexSizeInBytes;
desc->resourceManager->insertResourceView("textIbv", textIbv);*/
vx::array<TextVertex, DebugAllocatorRenderer<Allocator::MainAllocator>> vertices(allocator, totalVertexCount);
m_vertices.swap(vertices);
/*auto indexDataSize = sizeof(u32) * indexCount;
auto indexBlock = allocator->allocate(indexDataSize, __alignof(u32), Allocator::Channels::Renderer, "text renderer indices");
auto incides = (u32*)indexBlock.ptr;
for (u32 i = 0, j = 0; i < indexCount; i += 6, j += 4)
{
incides[i] = j;
incides[i + 1] = j + 1;
incides[i + 2] = j + 2;
incides[i + 3] = j + 2;
incides[i + 4] = j + 3;
incides[i + 5] = j;
}
auto uploaded = uploadManager->pushUploadBuffer((u8*)incides, indexDataSize, 0, resourceManager->findBufferResource("textIndexBuffer"), 0, D3D12_RESOURCE_STATE_INDEX_BUFFER);
VX_ASSERT(uploaded);
auto indexSubBufferOffset = vx::getAlignedSize(indexDataSize, 256);
uploaded = uploadManager->pushUploadBuffer((u8*)incides, indexDataSize, indexSubBufferOffset, resourceManager->findBufferResource("textIndexBuffer"), D3D12_RESOURCE_STATE_INDEX_BUFFER);
VX_ASSERT(uploaded);
allocator->deallocate(indexBlock, Allocator::Channels::Renderer, "text renderer indices");*/
m_drawTextProgram = drawTextProgram;
return true;
}
void TextRenderer::shutdown()
{
m_vertices.release();
m_entries.release();
}
void TextRenderer::pushEntry(const char(&text)[48], u32 strSize, const vx::float2 &topLeftPosition, const vx::float3 &color)
{
VX_ASSERT(m_entries.size() < s_maxEntryCount);
Entry entry;
strncpy(entry.m_text, text, 48);
entry.m_position = topLeftPosition;
entry.m_color = vx::float4(color, 1.0f);
entry.m_size = strSize;
m_entries.push_back(entry);
m_size += strSize;
}
void TextRenderer::update(UploadManager* uploadManager, GpuResourceManager* resourceManager, bool upload)
{
if (m_size == 0 || m_font == nullptr)
return;
if (upload)
{
updateVertexBuffer(uploadManager, resourceManager);
m_entries.clear();
}
m_size = 0;
}
void TextRenderer::updateVertexBuffer(UploadManager* uploadManager, GpuResourceManager* resourceManager)
{
u32 offset = 0;
auto fontTexture = m_font->getTexture();
auto textureSize = fontTexture->getFace(0).getDimension().x;
vx::float4a invTextureSize;
invTextureSize.x = 1.0f / textureSize;
auto vInvTexSize = _mm_shuffle_ps(invTextureSize.v, invTextureSize.v, _MM_SHUFFLE(0, 0, 0, 0));
auto entryCount = m_entries.size();
auto entries = m_entries.data();
for (u32 i = 0; i < entryCount; ++i)
{
writeEntryToVertexBuffer(vInvTexSize, entries[i], &offset, textureSize);
}
if (offset != 0)
{
/*auto indexCount = offset * 6;
auto vertexCount = offset * 4;
auto textVertexBuffer = resourceManager->getBuffer(L"textVertexBuffer");
uploadManager->pushUploadBuffer((u8*)m_vertices.get(), textVertexBuffer->get(), 0, sizeof(TextVertex) * vertexCount, D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER);
m_renderPassText->setIndexCount(indexCount);*/
}
}
void TextRenderer::writeEntryToVertexBuffer(const __m128 invTextureSize, const Entry &entry, u32* offset, u32 textureSize)
{
auto entryText = entry.m_text;
auto entryTextSize = entry.m_size;
auto entryOrigin = entry.m_position;
auto entryColor = vx::loadFloat4(&entry.m_color);
auto currentSize = m_size;
if (currentSize + entryTextSize >= m_capacity)
return;
u32 vertexOffset = (*offset) * 4;
*offset += entryTextSize;
auto vertices = &m_vertices[vertexOffset];
u32 vertexIndex = 0;
const f32 scale = 0.25f;
const __m128 vScale = { scale, scale, 0, 0 };
const __m128 tmp = { -1.0f, 0, 0, 0 };
auto cursorPosition = entryOrigin;
for (u32 i = 0; i < entryTextSize; ++i)
{
char ascii_code = entryText[i];
if (ascii_code == '\n')
{
cursorPosition.y -= 53.0f * scale;
cursorPosition.x = entryOrigin.x;
}
else
{
__m128 vCursorPos = { cursorPosition.x, cursorPosition.y, 0.0f, 0.0f };
auto pAtlasEntry = m_font->getAtlasEntry(ascii_code);
vx::float4a texRect(pAtlasEntry->x, textureSize - pAtlasEntry->y - pAtlasEntry->height, pAtlasEntry->width, pAtlasEntry->height);
__m128 vAtlasPos = { pAtlasEntry->offsetX, pAtlasEntry->offsetY, 0.0f, 0.0f };
__m128 vEntrySize = { texRect.z, -texRect.w, 0.0f, 0.0f };
__m128 vCurrentPosition = _mm_div_ps(vEntrySize, vx::g_VXTwo);
vCurrentPosition = _mm_add_ps(vCurrentPosition, vAtlasPos);
vCurrentPosition = vx::fma(vCurrentPosition, vScale, vCursorPos);
vCurrentPosition = _mm_movelh_ps(vCurrentPosition, tmp);
__m128 vSource = _mm_mul_ps(texRect, invTextureSize);
__m128 vSourceSize = _mm_shuffle_ps(vSource, vSource, _MM_SHUFFLE(3, 2, 3, 2));
static const __m128 texOffsets[4] =
{
{ 0, 0, 0, 0 },
{ 1, 0, 0, 0 },
{ 1, 1, 0, 0 },
{ 0, 1, 0, 0 }
};
static const __m128 posOffsets[4] =
{
{ -0.5f, -0.5f, 0, 0 },
{ 0.5f, -0.5f, 0, 0 },
{ 0.5f, 0.5f, 0, 0 },
{ -0.5f, 0.5f, 0, 0 }
};
vEntrySize = _mm_shuffle_ps(texRect, texRect, _MM_SHUFFLE(3, 2, 3, 2));
for (u32 k = 0; k < 4; ++k)
{
u32 index = vertexIndex + k;
auto pos = _mm_mul_ps(posOffsets[k], vEntrySize);
pos = vx::fma(pos, vScale, vCurrentPosition);
_mm_storeu_ps(&vertices[index].position.x, pos);
__m128 uv = vx::fma(texOffsets[k], vSourceSize, vSource);
_mm_storeu_ps(&vertices[index].uv.x, uv);
_mm_storeu_ps(&vertices[index].color.x, entryColor);
}
vertexIndex += 4;
cursorPosition.x = fmaf(pAtlasEntry->advanceX, scale, cursorPosition.x);
}
}
}
} | 32.353276 | 209 | 0.72957 | DennisWandschura |
41911c52cdeaa0cca080120286aca4e7b91bf0f9 | 2,036 | cxx | C++ | src/samples/xsd_parser.cxx | abdelkaderamar/fix2xml | fa781b747a8e40ed4c2d3dee8294fb51654f7428 | [
"MIT"
] | 1 | 2019-09-26T12:08:19.000Z | 2019-09-26T12:08:19.000Z | src/samples/xsd_parser.cxx | abdelkaderamar/fix2xml | fa781b747a8e40ed4c2d3dee8294fb51654f7428 | [
"MIT"
] | null | null | null | src/samples/xsd_parser.cxx | abdelkaderamar/fix2xml | fa781b747a8e40ed4c2d3dee8294fb51654f7428 | [
"MIT"
] | 1 | 2020-12-11T04:11:44.000Z | 2020-12-11T04:11:44.000Z | // MIT License
//
// Copyright 2018 Abdelkader Amar
//
// 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 "util/fix_env.hxx"
#include "fixml/fixml_xsd_parser.hxx"
#include <boost/log/trivial.hpp>
using namespace fix2xml;
using namespace std;
int usage(const int ret) {
static string text = "Usage: xsd_parser {xsd_files}";
if (ret == 0) BOOST_LOG_TRIVIAL(info) << text;
else BOOST_LOG_TRIVIAL(error) << text;
return ret;
}
int main(int argc, char *argv[])
{
if (argc < 2) return usage(1);
if ( ! fix_env::init_xerces()) {
BOOST_LOG_TRIVIAL(error) << "Failed to initialize xerces environment";
return 1;
}
BOOST_LOG_TRIVIAL(info) << "xerces environment initialized";
{
fixml_xsd_parser parser;
BOOST_LOG_TRIVIAL(info) << "xsd parser created";
if (parser.parse(argv[1])) BOOST_LOG_TRIVIAL(info) << "parsing " << argv[1] << " done";
else BOOST_LOG_TRIVIAL(error) << "parsing " << argv[1] << " failed";
}
fix_env::terminate_xerces();
return 0;
}
| 33.933333 | 91 | 0.721513 | abdelkaderamar |
419128b7f02f57221852f41e68a339a1b09b74b5 | 59,379 | cpp | C++ | src/test/op_rawleftbitshift_tests.cpp | ngocviet/lotusd | 769802c5db7302aa1c23cf81cf42b2e861c45732 | [
"MIT"
] | 3 | 2019-06-17T03:48:07.000Z | 2021-03-07T05:47:18.000Z | src/test/op_rawleftbitshift_tests.cpp | ngocviet/lotusd | 769802c5db7302aa1c23cf81cf42b2e861c45732 | [
"MIT"
] | 68 | 2019-06-17T01:54:12.000Z | 2021-04-10T17:59:15.000Z | src/test/op_rawleftbitshift_tests.cpp | ngocviet/lotusd | 769802c5db7302aa1c23cf81cf42b2e861c45732 | [
"MIT"
] | 1 | 2021-02-21T23:51:33.000Z | 2021-02-21T23:51:33.000Z | // Copyright (c) 2012-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 <policy/policy.h>
#include <script/interpreter.h>
#include <script/script.h>
#include <test/lcg.h>
#include <test/util/setup_common.h>
#include <boost/test/unit_test.hpp>
#include <core_io.h>
#include <util/strencodings.h>
BOOST_FIXTURE_TEST_SUITE(op_rawleftbitshift_tests, BasicTestingSetup)
typedef std::vector<uint8_t> valtype;
typedef std::vector<valtype> stacktype;
std::array<uint32_t, 2> flagset{{0, STANDARD_SCRIPT_VERIFY_FLAGS}};
static valtype FromUint64(uint64_t num) {
valtype num_item;
num_item.reserve(8);
for (int i = 7; i >= 0; --i) {
num_item.push_back((num >> (i * 8)) & 0xff);
}
return num_item;
}
static void CheckTestResultForAllFlags(const stacktype &original_stack,
const CScript &script,
const stacktype &expected) {
BaseSignatureChecker sigchecker;
for (uint32_t flags : flagset) {
ScriptError err = ScriptError::OK;
stacktype stack{original_stack};
bool r = EvalScript(stack, script, flags, sigchecker, &err);
BOOST_CHECK_MESSAGE(r, "Expected success but got failure for '"
<< ScriptToAsmStr(script) << "'");
BOOST_CHECK_MESSAGE(stack == expected,
"Expected stacks to be equal for '"
<< ScriptToAsmStr(script) << "'");
}
}
static void CheckTestLeftShift(const valtype &num, int32_t shift,
const valtype &expected) {
valtype test_num;
valtype test_expected;
test_num.reserve(num.size());
test_expected.reserve(num.size());
for (int i = num.size() - 1; i >= 0; --i) {
test_num.insert(test_num.begin(), num[i]);
test_expected.insert(test_expected.begin(), expected[i]);
CheckTestResultForAllFlags({test_num},
CScript() << shift << OP_RAWLEFTBITSHIFT,
{test_expected});
}
}
static void CheckTestRightShift(const valtype &num, int32_t shift,
const valtype &expected) {
valtype test_num;
valtype test_expected;
test_num.reserve(num.size());
test_expected.reserve(num.size());
for (size_t i = 0; i < num.size(); ++i) {
test_num.push_back(num[i]);
test_expected.push_back(expected[i]);
CheckTestResultForAllFlags({test_num},
CScript() << -shift << OP_RAWLEFTBITSHIFT,
{test_expected});
}
}
static void CheckTestU64Shift(uint64_t num, int32_t shift) {
valtype num_encoded = FromUint64(num);
valtype right_shifted_encoded = FromUint64(shift < 64 ? num >> shift : 0);
valtype left_shifted_encoded = FromUint64(shift < 64 ? num << shift : 0);
CheckTestRightShift(num_encoded, shift, right_shifted_encoded);
CheckTestLeftShift(num_encoded, shift, left_shifted_encoded);
}
static void CheckTestRightShiftHex(std::string num_hex, int32_t shift,
std::string expected_hex) {
CheckTestRightShift(ParseHex(num_hex), shift, ParseHex(expected_hex));
}
static void CheckTestLeftShiftHex(std::string num_hex, int32_t shift,
std::string expected_hex) {
CheckTestLeftShift(ParseHex(num_hex), shift, ParseHex(expected_hex));
}
BOOST_AUTO_TEST_CASE(u64_shift_test) {
MMIXLinearCongruentialGenerator lcg;
for (int test = 0; test < 20; ++test) {
uint64_t num = lcg.next();
num <<= 32;
num |= lcg.next();
for (uint32_t i = 0; i <= 100; ++i) {
CheckTestU64Shift(num, i);
}
}
}
BOOST_AUTO_TEST_CASE(left_shift_test) {
CheckTestLeftShiftHex("", 0, "");
CheckTestLeftShiftHex("", 1, "");
CheckTestLeftShiftHex("63", 0, "63");
CheckTestLeftShiftHex("63", 1, "c6");
CheckTestLeftShiftHex("63", 2, "8c");
CheckTestLeftShiftHex("63", 3, "18");
CheckTestLeftShiftHex("63", 4, "30");
CheckTestLeftShiftHex("63", 5, "60");
CheckTestLeftShiftHex("63", 6, "c0");
CheckTestLeftShiftHex("63", 7, "80");
CheckTestLeftShiftHex("63", 8, "00");
CheckTestLeftShiftHex("6347", 0, "6347");
CheckTestLeftShiftHex("6347", 1, "c68e");
CheckTestLeftShiftHex("6347", 7, "a380");
CheckTestLeftShiftHex("6347", 8, "4700");
CheckTestLeftShiftHex("6347", 9, "8e00");
CheckTestLeftShiftHex(
"ebd076435d1fe29d4bc6165d49e32b2d88d58919a8106bcc9afaeda9137c10ee7131b2"
"f45d61b781b9c1d29f8f87c8be440a27379ada1e811fd3cc9cdd06fb139d1c3e01becb"
"e8be85da9657859766de3add40b1f7345056866f33dc6ef85ec89e7d02805eca428195"
"31cc4fe5c2e692f1fa9f39e7f85eba444e378e024c693e089fbb46fe36781e36ce5be1"
"068b2f36cf9cd6dcd0bc480e53549bde70a3560e32dcc697299a0bdad2fcdf869bcf56"
"45aa5baa5b8560a3b7368072e2d4f4dee7a07b0c0d747089827c09f6dbf866f8f7d94a"
"8c3592e9d1bca02a9686cc3cb2eb3b6c932d1905f832e40d4559095a416d0e74c7259c"
"266b0ad9b18f12571093ec026ecb1d7e942228e5058f2d3c9b591cb79e4a53f84499b9"
"dda1f4bf26047ab591670c3b8939759f942f3ac4d6754a88a3c909126823dc4241ecea"
"de263e9e6ae603126eb7d6ca9510184a70effb2f424079237bc7e1243438dc44ae7467"
"f49cb3f46cfc5c98a72fe8b3a45c6e60f83444c5ba911596b82359b807271d0d3d8cd5"
"e6d5dca1034de6572306407e9e248f7edd6add140fd61709b040c0b44b2cf24e9207ba"
"2fbe5b851764485541cd8ad0e35c9bf6dc27579141dc8c6e1d6b96de06fca85b248dc1"
"36906eab64287864fd3dba3d3b8483e24495ae0e19471d0f51d847e7c5b088081e491c"
"fa39ae48eae4392fe499af54c0d6adc47deed067d106a129fbc7bd7f612e",
1,
"d7a0ec86ba3fc53a978c2cba93c6565b11ab12335020d79935f5db5226f821dce26365"
"e8bac36f037383a53f1f0f917c88144e6f35b43d023fa79939ba0df6273a387c037d97"
"d17d0bb52caf0b2ecdbc75ba8163ee68a0ad0cde67b8ddf0bd913cfa0500bd9485032a"
"63989fcb85cd25e3f53e73cff0bd74889c6f1c0498d27c113f768dfc6cf03c6d9cb7c2"
"0d165e6d9f39adb9a178901ca6a937bce146ac1c65b98d2e533417b5a5f9bf0d379eac"
"8b54b754b70ac1476e6d00e5c5a9e9bdcf40f6181ae8e11304f813edb7f0cdf1efb295"
"186b25d3a37940552d0d987965d676d9265a320bf065c81a8ab212b482da1ce98e4b38"
"4cd615b3631e24ae2127d804dd963afd284451ca0b1e5a7936b2396f3c94a7f0893373"
"bb43e97e4c08f56b22ce18771272eb3f285e7589acea951147921224d047b88483d9d5"
"bc4c7d3cd5cc0624dd6fad952a203094e1dff65e8480f246f78fc2486871b8895ce8cf"
"e93967e8d9f8b9314e5fd16748b8dcc1f068898b75222b2d7046b3700e4e3a1a7b19ab"
"cdabb942069bccae460c80fd3c491efdbad5ba281fac2e13608181689659e49d240f74"
"5f7cb70a2ec890aa839b15a1c6b937edb84eaf2283b918dc3ad72dbc0df950b6491b82"
"6d20dd56c850f0c9fa7b747a770907c4892b5c1c328e3a1ea3b08fcf8b6110103c9239"
"f4735c91d5c8725fc9335ea981ad5b88fbdda0cfa20d4253f78f7afec25c");
CheckTestLeftShiftHex(
"2a467c005ae83afa9d8df8b13a0e0d6a3d085e8c71e4ea210ceeeb30c84cd771c5c226"
"45091dc8e91619c4525b5986db05e54174bdc02cc5b5bf12c22fe377b60615666595ba"
"323d6b4a2f354f68c93481884d7a6aba0d235e45262eeeb93c3453dcd52faf35fb569d"
"b221305dadbc74c55a40806d9838be5c42de74481450e6a672adbdddd8f541edc26b27"
"b15e5487da9ab8f7f335e1fc97d137466d97bc737c74ef8f4dfcbdb0d11268981c7a83"
"313ca63a67dac5ecda6c06e6d69eae5b51171d6d32e577bc9d13e14789a148a97c7755"
"0b2225aec7179491e0e5bc04a2aba3244d9431e5272714a0b78b6284d0fd4e6802ce98"
"0802ac9637a2140219781fddcf45652c518e6602e59a7f35bca10543ded6552559ae9d"
"de1a6dcb9e4a7812511ec18cc9a9f2740190010392ea45961ef78370ad6f5d8e7516cb"
"6db3516c14aa42ea63011d065cca4d7a23d1e0b196da933d474c058639dee71da091b3"
"ec86f4cb30ea66175725ccf5c9c99e8b30c4faa1a83cb095d5b55d3882cf5c545bb515"
"a3607c46d32792f207ff13123f08bc0fc1d2605a890ad31895c5b22c180deed8a4736d"
"891afdb0409e0402cd326f596fca4439b131e8251e1c0ef437be6832ead0e458c64388"
"87776adc2d0aa92bacac6303ca48f0c7b6c91282dea7b86d312e687582eadf90be7774"
"e7f70f9189abb9690a80bf333574f6b249eead1244b0d14fe69e7cb12f56",
2,
"a919f0016ba0ebea7637e2c4e83835a8f4217a31c793a88433bbacc321335dc7170899"
"14247723a4586711496d661b6c179505d2f700b316d6fc4b08bf8dded81855999656e8"
"c8f5ad28bcd53da324d2062135e9aae8348d791498bbbae4f0d14f7354bebcd7ed5a76"
"c884c176b6f1d315690201b660e2f9710b79d12051439a99cab6f77763d507b709ac9e"
"c579521f6a6ae3dfccd787f25f44dd19b65ef1cdf1d3be3d37f2f6c34449a26071ea0c"
"c4f298e99f6b17b369b01b9b5a7ab96d445c75b4cb95def2744f851e268522a5f1dd54"
"2c8896bb1c5e52478396f0128aae8c913650c7949c9c5282de2d8a1343f539a00b3a60"
"200ab258de88500865e07f773d1594b14639980b9669fcd6f284150f7b59549566ba77"
"7869b72e7929e049447b063326a7c9d00640040e4ba916587bde0dc2b5bd7639d45b2d"
"b6cd45b052a90ba98c047419732935e88f4782c65b6a4cf51d301618e77b9c768246cf"
"b21bd32cc3a9985d5c9733d727267a2cc313ea86a0f2c25756d574e20b3d71516ed456"
"8d81f11b4c9e4bc81ffc4c48fc22f03f0749816a242b4c625716c8b06037bb6291cdb6"
"246bf6c10278100b34c9bd65bf2910e6c4c7a09478703bd0def9a0cbab439163190e22"
"1dddab70b42aa4aeb2b18c0f2923c31edb244a0b7a9ee1b4c4b9a1d60bab7e42f9ddd3"
"9fdc3e4626aee5a42a02fcccd5d3dac927bab44912c3453f9a79f2c4bd58");
return;
CheckTestLeftShiftHex(
"a98494f07b4dab376b2ab766f30fca375985cdc9b5de0774a98618702da6939883fa98"
"baed23fbe29cda508742ebd2120da4f680b58f69d7368c2ffef15c3571ea7b19cfcbef"
"31fbc998fe5b3548b6b935e067f4b9778a883c164edbf0cd7c4a8c9c4b53e80a9d6517"
"438c5034a6fec75924e40722ac1622972bbafed27ee574443ab1028ca2120ff7727cbe"
"471f0493afe8c8f196aed1e1a571769b495ccb04c1e1c19bab7f22bc29adebf1cb505a"
"d4a659d42dc06458d463826178f0c60d2ef594d3c587f1eec3b0aff01be5fab31dfa65"
"93a5a0d5aa295891fbb3a9a8d18eda9a9b8d78cde2a3e868493365796ac496e27a7876"
"c8d7b3c6b292ff13be312f610afbf5509c618f7e9def06c6d7ae88b36227838d02a8d6"
"65a8259b0ba7644a9445bd0d237d4626ce9a67f1653862df093e6aa8b09717dde3917f"
"44a4e5f4c35d0cc6b58fad65c42a5b5fb9bcdf1f716caddc9c0be86ef1726762858986"
"f9aa901e5963f73bc2ca5fada5bd4b14febe10910c32c72daae28107a3cda032115601"
"7c5b8ed36dc486bf41b8cf6ea54f3bfee549c515552cabb1f0e67af5cead0e24557732"
"bedeb2d2a4c7f37693389d38fd994166fd733b5b50e4dfd6b2df1b84612ba7f329e5be"
"4131e46299656011308426fd1b900956c1ea4a726b850e806ee8afb1f1ab2054d8b80d"
"5664ede7f7d827e49a7bbadc3a06dd490045207937cc5ef43f4607b992d7",
3,
"4c24a783da6d59bb5955bb37987e51bacc2e6e4daef03ba54c30c3816d349cc41fd4c5"
"d7691fdf14e6d2843a175e90906d27b405ac7b4eb9b4617ff78ae1ab8f53d8ce7e5f79"
"8fde4cc7f2d9aa45b5c9af033fa5cbbc5441e0b276df866be25464e25a9f4054eb28ba"
"1c6281a537f63ac92720391560b114b95dd7f693f72ba221d588146510907fbb93e5f2"
"38f8249d7f46478cb5768f0d2b8bb4da4ae658260f0e0cdd5bf915e14d6f5f8e5a82d6"
"a532cea16e0322c6a31c130bc786306977aca69e2c3f8f761d857f80df2fd598efd32c"
"9d2d06ad514ac48fdd9d4d468c76d4d4dc6bc66f151f4342499b2bcb5624b713d3c3b6"
"46bd9e359497f89df1897b0857dfaa84e30c7bf4ef783636bd74459b113c1c681546b3"
"2d412cd85d3b2254a22de8691bea313674d33f8b29c316f849f3554584b8beef1c8bfa"
"25272fa61ae86635ac7d6b2e2152dafdcde6f8fb8b656ee4e05f43778b933b142c4c37"
"cd5480f2cb1fb9de1652fd6d2dea58a7f5f084886196396d5714083d1e6d01908ab00b"
"e2dc769b6e2435fa0dc67b752a79dff72a4e28aaa9655d8f8733d7ae75687122abb995"
"f6f59695263f9bb499c4e9c7ecca0b37eb99dada8726feb596f8dc23095d3f994f2df2"
"098f2314cb2b0089842137e8dc804ab60f5253935c28740377457d8f8d5902a6c5c06a"
"b3276f3fbec13f24d3ddd6e1d036ea48022903c9be62f7a1fa303dcc96b8");
CheckTestLeftShiftHex(
"98660ce335e12462fb5c2be76c46443825e3da19fc21a01b93271e5a9b7da55503b1de"
"3778909a36ce44ff4983706091dfcf49e5d2a4c3743fa1f5451b4a60c87836149758b1"
"01be65dfb2442a01e5203da712b205ea4d202dc6aecfeb76cf0ebff9977f1ef90cf419"
"80907d74c36e45d0804bc340058fa75f0941d4b68ad179830fc6a4e4abaa99eb9be486"
"cff2486a768135f227c01aa15bfe066fcd1a89c09d794489f836165072e68c422ca508"
"804909206d135cdc5f893b4a1a99ed9bda7eba63dbe7583b8d87b794b8230fd1b8597c"
"9c352d0fefb2526c78a536349c31df3da254666809ff3eb89737bcc901030cefe13955"
"d379f555d9295fc4b8c0d7089ed0c9856f48fcbbb9a011b26490e2b70eb4a15e60cc1f"
"2978c8e53b974a1323da9b9f1ca2db98079c8ab44c3d5086949752a3d8383cd62abd21"
"7725c3f930f1a8f40ea90499a8055b1bf46c1d59af3192e9b3fd79f6e858ebc4c1a9aa"
"654f3bea4e3030c0d898558d7d0b8394188c48cd92e2cd8b11cef98743ef724d374e9b"
"d9fa7f47a77444686d2f6c578febae518649dc14b333e8a5b199d9f98350e35cc59b56"
"437770d524ae262869ef97c9e70b897399dd3e1ca642b7a78675c51d0799a58e5fc299"
"29ef66bf9ef458101ad03bea6adbb7ef7222bf8e2b0836c77ce70ea3a71c568f309549"
"7924079c108268493e1606c67ffbe8dcfe84b3e2382dace9e3d4fe5a666d",
7,
"3306719af092317dae15f3b623221c12f1ed0cfe10d00dc9938f2d4dbed2aa81d8ef1b"
"bc484d1b67227fa4c1b83048efe7a4f2e95261ba1fd0faa28da530643c1b0a4bac5880"
"df32efd9221500f2901ed3895902f5269016e35767f5bb67875ffccbbf8f7c867a0cc0"
"483eba61b722e84025e1a002c7d3af84a0ea5b4568bcc187e3527255d54cf5cdf24367"
"f924353b409af913e00d50adff0337e68d44e04ebca244fc1b0b283973462116528440"
"2484903689ae6e2fc49da50d4cf6cded3f5d31edf3ac1dc6c3dbca5c1187e8dc2cbe4e"
"1a9687f7d929363c529b1a4e18ef9ed12a333404ff9f5c4b9bde6480818677f09caae9"
"bcfaaaec94afe25c606b844f6864c2b7a47e5ddcd008d93248715b875a50af30660f94"
"bc64729dcba50991ed4dcf8e516dcc03ce455a261ea8434a4ba951ec1c1e6b155e90bb"
"92e1fc9878d47a0754824cd402ad8dfa360eacd798c974d9febcfb742c75e260d4d532"
"a79df5271818606c4c2ac6be85c1ca0c462466c97166c588e77cc3a1f7b9269ba74dec"
"fd3fa3d3ba22343697b62bc7f5d728c324ee0a5999f452d8ccecfcc1a871ae62cdab21"
"bbb86a9257131434f7cbe4f385c4b9ccee9f0e53215bd3c33ae28e83ccd2c72fe14c94"
"f7b35fcf7a2c080d681df5356ddbf7b9115fc715841b63be738751d38e2b47984aa4bc"
"9203ce084134249f0b03633ffdf46e7f4259f11c16d674f1ea7f2d333680");
CheckTestLeftShiftHex(
"ed9ff2b4ee2266892c3b73076199fceb72282b9d3bb617602257c97aee257c56601d1d"
"8526ddc75db4a791bf37cc524359475a5851df1bb7340b2b3c114170578d241ef2f625"
"67557964e588679b8f896c4a4ea1bb43a2088527705022b32056bd696c207b4d990c7b"
"6ee1aa88acef9c583da516d6338e2e77011d9c272c5805cf4ebf5508e926eb6c6d7235"
"339f1abe8aa897263ceb9fa77a4394bb7949eb6b1caf6364000c2bf5d3c650ccb39572"
"51689f7d26a4690150a623d471552dccbdcafe4d08b9eaa31863174d0f5e09f2058384"
"91f0cfa43f9eb0e77b7a1a19b12fb28997b7e667da7e9c8c46b10a45782810f52f1432"
"fa2d4860dea805e8953850e6f802e8c7ee00e4d8ae2010d9f562504796494259c7de41"
"29bd83f5a39c796ffa9c40e682198881f1d54a66497be452d80d1a3145880c67fe2086"
"49eaa2dca31bbd68aef2563b0e3d68c71e984000926291ab459c25fc16ab818ddd3ce4"
"69e826710b5f8c888ce56df3f524785cc6d17556436c2069964288e9587d644fb00558"
"b0aba76f2fad2df2130f4b030775b24b92f0d06d8bae4972e914ea9b11cb3c80197730"
"83d81de532fc43275a708a76a97e1e1f2a7d7269b2d01b2ff8095b3619cae0dd6879cf"
"3f88073db3c3e05fc27b294dd18992c32021456bf577324d996583d09681085fb42cc2"
"426433d354e8c6278db8433aa2cc7cc78af569b7c352427e9e68fd704cc8",
13,
"fe569dc44cd125876e60ec333f9d6e450573a776c2ec044af92f5dc4af8acc03a3b0a4"
"dbb8ebb694f237e6f98a486b28eb4b0a3be376e681656782282e0af1a483de5ec4acea"
"af2c9cb10cf371f12d8949d43768744110a4ee0a0456640ad7ad2d840f69b3218f6ddc"
"3551159df38b07b4a2dac671c5cee023b384e58b00b9e9d7eaa11d24dd6d8dae46a673"
"e357d15512e4c79d73f4ef4872976f293d6d6395ec6c8001857eba78ca199672ae4a2d"
"13efa4d48d202a14c47a8e2aa5b997b95fc9a1173d54630c62e9a1ebc13e40b070923e"
"19f487f3d61cef6f43433625f65132f6fcccfb4fd39188d62148af05021ea5e2865f45"
"a90c1bd500bd12a70a1cdf005d18fdc01c9b15c4021b3eac4a08f2c9284b38fbc82537"
"b07eb4738f2dff53881cd04331103e3aa94cc92f7c8a5b01a34628b1018cffc410c93d"
"545b946377ad15de4ac761c7ad18e3d30800124c523568b384bf82d57031bba79c8d3d"
"04ce216bf191119cadbe7ea48f0b98da2eaac86d840d32c8511d2b0fac89f600ab1615"
"74ede5f5a5be4261e96060eeb649725e1a0db175c92e5d229d5362396790032ee6107b"
"03bca65f8864eb4e114ed52fc3c3e54fae4d365a0365ff012b66c3395c1bad0f39e7f1"
"00e7b6787c0bf84f6529ba313258640428ad7eaee649b32cb07a12d0210bf68598484c"
"867a6a9d18c4f1b7086754598f98f15ead36f86a484fd3cd1fae09990000");
CheckTestLeftShiftHex(
"db80c7ae597014003cefd376acb535485a8fa13acb24e611b8f57dd752e88459512767"
"51a2360a2183dcea76da8dbbc04a94f7d2df715ad03ec69eb03ebbcf42251b5c4b3ecc"
"c5833c0c213e6e3c789e7595e3460842ae5930a1b01fcc265c6fd59f0ca6c6cb6ac6d0"
"49ec14f2fa94fc44f51c4be16233728f7908e806020cf1f01ed14fd11c5d04705cfe59"
"2b0ad022a3eaf02f52998c2702510c1804eab35cabe07e576999c6156263fd9654e8d9"
"ecc417dd5b935ac25396088b15d1a235725076fe35dceb05cd27a236b1f5c205feca69"
"a9495ccdfe81ade23d311a28cf45d58545caaf4485f2f61764f63d64991d85a6ce1181"
"85055d18099c66b1457a34bb8fc447e31e9c81c8dace80c34c63ffb07d198bb3ca2f79"
"1a54eeef3af7761192dcc152cdb9d0fdfb448aecb01d7c486f7e823462cf59a8eef23d"
"c42821104650a96330ff2b9d25e353d673df6ee0d47dff09835fcf537ee789ba27305b"
"b9f50a1b30a4ac107346452df736bb59488ee82353469a5dd70cf17fb6c6560581012c"
"a216c55c2720a658c3e45548bb5eef5e1682beadf81d0e8490a278c9b5d15bc2c2318e"
"27353b6b648b820859a1c4e878e24ec51e209067e004d094cbae59ed7cd4c2029320c2"
"979c46024dee84090ae3559155c84939dae8eca6b7771f464ad82e5fef1730c93a1457"
"af6f129d4c99b910d541a95761d9f6d990ff3b16cd981ae1e148a77a9ef7",
37,
"2e0280079dfa6ed596a6a90b51f42759649cc2371eafbaea5d108b2a24ecea3446c144"
"307b9d4edb51b77809529efa5bee2b5a07d8d3d607d779e844a36b8967d998b0678184"
"27cdc78f13ceb2bc68c10855cb26143603f984cb8dfab3e194d8d96d58da093d829e5f"
"529f889ea3897c2c466e51ef211d00c0419e3e03da29fa238ba08e0b9fcb25615a0454"
"7d5e05ea533184e04a2183009d566b957c0fcaed3338c2ac4c7fb2ca9d1b3d9882fbab"
"726b584a72c11162ba3446ae4a0edfc6bb9d60b9a4f446d63eb840bfd94d35292b99bf"
"d035bc47a6234519e8bab0a8b955e890be5ec2ec9ec7ac9323b0b4d9c23030a0aba301"
"338cd628af469771f888fc63d390391b59d018698c7ff60fa331767945ef234a9ddde7"
"5eeec2325b982a59b73a1fbf68915d9603af890defd0468c59eb351dde47b885042208"
"ca152c661fe573a4bc6a7ace7beddc1a8fbfe1306bf9ea6fdcf13744e60b773ea14366"
"1495820e68c8a5bee6d76b2911dd046a68d34bbae19e2ff6d8cac0b020259442d8ab84"
"e414cb187c8aa9176bddebc2d057d5bf03a1d092144f1936ba2b78584631c4e6a76d6c"
"9170410b34389d0f1c49d8a3c4120cfc009a129975cb3daf9a984052641852f388c049"
"bdd081215c6ab22ab909273b5d1d94d6eee3e8c95b05cbfde2e61927428af5ede253a9"
"9337221aa8352aec3b3edb321fe762d9b3035c3c2914ef53dee000000000");
CheckTestLeftShiftHex(
"91b89e3b793648555b4bf4c22263939848879ffcd9151a3d32c893ee81360bb0134822"
"cc6c990a3d3de9eeb8c90fbbf4d94d94c21c49bfe1a2dd6b6323ae20a2f7270c50411b"
"db851c7d2d226ddc2587e452bbfbd4962a72a898de3d93b294891c8099b8351fa3ccfb"
"7e20f96683190a8dff9382103ea653cabd6ae6f01d19d86e78054c5d89e5bb088f504b"
"a623c8a6d1db4085442a2122394a5037c1e5adaf31ecd491f9b460228fef50d2dd1e50"
"c46a73c8499cd4fc9552134b19fcfeb213b59cd1c718b385199b44304e3e4a8a680d43"
"2fbe1d9e63692b8694f4ec46b8316cec5eb01f096e13d55ddcc79c94b63c6feb3ca290"
"69267a6a8a0268b5394874bad4470b0feb17541ad1310298458360af0ccf09d7fa7026"
"3a9df7947351661fa8f7afaa9aa6744318b1f5ab7f30f92b8eda6af1cd2d712a44eb06"
"e66c715068163776ed0c72d23c951cb416464c8468b68a16d2b80b061fd79d1956b8cc"
"badd86c6bf1258444f216b21969bc1b514bafef04d6bf25bf610f71a88bf69a28176a9"
"4f72a79a99d382ec46b8f3114a6bd605f9a6246ca8d5cae14cdb6b5958c181ea70fb80"
"47a6e07671953e24b93e223f525c1f735b025ec9d619aca79e2b341df5b9e7ca91c4c4"
"7c3c867c7170cb737c93df5b45f8c2cd71d1f79385e2e5ae44f4a9047e9788ddac95a8"
"5d6e07fc5bd812d2e6d44c693fe6f1616475f038778c5d394299999f4113",
398,
"653087126ff868b75ad8c8eb8828bdc9c3141046f6e1471f4b489b770961f914aefef5"
"258a9caa26378f64eca5224720266e0d47e8f33edf883e59a0c642a37fe4e0840fa994"
"f2af5ab9bc0746761b9e01531762796ec223d412e988f229b476d021510a88488e5294"
"0df0796b6bcc7b35247e6d1808a3fbd434b74794311a9cf21267353f255484d2c67f3f"
"ac84ed673471c62ce14666d10c138f92a29a0350cbef876798da4ae1a53d3b11ae0c5b"
"3b17ac07c25b84f5577731e7252d8f1bfacf28a41a499e9aa2809a2d4e521d2eb511c2"
"c3fac5d506b44c40a61160d82bc333c275fe9c098ea77de51cd45987ea3debeaa6a99d"
"10c62c7d6adfcc3e4ae3b69abc734b5c4a913ac1b99b1c541a058dddbb431cb48f2547"
"2d059193211a2da285b4ae02c187f5e74655ae332eb761b1afc4961113c85ac865a6f0"
"6d452ebfbc135afc96fd843dc6a22fda68a05daa53dca9e6a674e0bb11ae3cc4529af5"
"817e69891b2a3572b85336dad65630607a9c3ee011e9b81d9c654f892e4f888fd49707"
"dcd6c097b275866b29e78acd077d6e79f2a471311f0f219f1c5c32dcdf24f7d6d17e30"
"b35c747de4e178b96b913d2a411fa5e2376b256a175b81ff16f604b4b9b5131a4ff9bc"
"58591d7c0e1de3174e50a66667d044c000000000000000000000000000000000000000"
"000000000000000000000000000000000000000000000000000000000000");
CheckTestLeftShiftHex(
"eb8baf207037a28801f631673410255a2b8f36e868f98793d4cdd5180907b801be38ef"
"aa1ab75420f57f80825d5c0638a7519a777bf85772b616e5883d3f5c6c424cb1f32d71"
"c051203ca1465b15729d0b2a865600c7614db607bc6fe8564ab0c2f2e4a12f252004dd"
"f82bb0d36b23b8f8f1efb2814bdd6a6fb17f90028494a67db72fda1d0c2ef72f170f30"
"4b4a28b3bc51c2e58e8e009785c6584dbdd665834326a6d59b98736836b9044608f3d6"
"37616570a83904b934e0db5c3741e3a83c7d209802cf8c89a6af2d74af2e313630411d"
"240f00c3aca3fb343d20be9f2ce48949ca291d9604963321d2eb4d5732e84749c4d9d1"
"5071595e1a10a665b62ec9da697952efa8f231dd7cb429447f607ec116b9eedfc0bb3f"
"a86366120306c27c5e3ee5918717148ee3481183a181726fa2de825cfbc3d922ff7b2f"
"003d7873f40853b2fa45128ef712df2a46f241907db643cadf5145fcb77cc1a11a2fad"
"fdfabc2b137e68300f2f4cc5d6d508f93f0bab9d5abab5952ebf0e12614801c78d8dde"
"7d43e243d165677ee2d0d92b2c2c98fb86ae736e796536757f54a68ee69e60f2c3c201"
"3418d16d67842414004b3da73ab0c2cc1625b18af0bc73c32e1fa44219f4a4bfcc3975"
"993a6935b6d056f37b14f38009ff817bd8f09139a7fcb065a5562d22976846f883588f"
"d5a7904a54c6b3997aab24aa09e85fb670cf9fe0e72c9fd2351177d18b0a",
2489,
"45fef65e007af0e7e810a765f48a251dee25be548de48320fb6c8795bea28bf96ef983"
"42345f5bfbf5785626fcd0601e5e998badaa11f27e17573ab5756b2a5d7e1c24c29003"
"8f1b1bbcfa87c487a2cacefdc5a1b256585931f70d5ce6dcf2ca6ceafea94d1dcd3cc1"
"e58784026831a2dacf08482800967b4e756185982c4b6315e178e7865c3f488433e949"
"7f9872eb3274d26b6da0ade6f629e70013ff02f7b1e122734ff960cb4aac5a452ed08d"
"f106b11fab4f2094a98d6732f556495413d0bf6ce19f3fc1ce593fa46a22efa3161400"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"000000000000000000000000000000000000000000000000000000000000");
CheckTestLeftShiftHex(
"0b0d15d774b99ba942850db1c241026d622134010042e6ee81030c23e4d6d4b0668cfb"
"1be94b064ed5d51ab700c999c41b2b6be0f4b75f3cd0dee87d682e2729f6d68ee2ab1e"
"0dd98ee038395fac6a8a7058a0ecf3353507324652e9277d9aebf6a37662cfe5cda9c3"
"10e2cf278b0a9bea20ad625dd6984fb7bb7918adae491a94293163eebdde9040652399"
"db552d312a2592fd7e7edfde6cff38c365f8f20a02fd26a124d46944381e67174c7225"
"656a5b8e41525c97cde1a5cf70b846670f1cafc655bbf115511d63d0d8db503807efc0"
"cef1716f637b8871035e092003f4709e690350b4c6ad520648a6d17b1964465ada5508"
"bd99df5e68c4915c0e389395e898fd3800d4da40010aca27cdb898126884fca767db34"
"cf03360126a2a848a4bdf28f900cc9cdf5bca267d98692d3dbf6217d9907ae8b4dac61"
"158ff7ca0b6737851967fb1cc4bf0ac841999066372472cff6143d1469bc21bae74f12"
"41f69b483b997e400b879fe90e079478b5f92c5c3c1c47837addcaac7933fedc345b7d"
"04b326d05ffbb1fc1eb10dcb833f1aa40b36c9475bbc8246d8fa5203ecd734d851ea7e"
"7ea56fda62a941016f00e36a4dd353ab6187d210dc37841357ec55b6e932ddbbf176c4"
"b2d3741f36f600a0aa6d40e8be663967a6cf46a8a941c3d5a49b6b59104aee36ab0759"
"f68d8045a2503c6090a9cf8d7daa81402774859948a779af8379b89f41db",
4134,
"27d076c000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"000000000000000000000000000000000000000000000000000000000000");
CheckTestLeftShiftHex(
"9eb21c29f8f88523b70828a457aeea014e3d1150c2f9ec6e3440672abb91272c264426"
"3b015d039aa3cfe035d34e6296867778bc476ec501e4bf944a4c29ef8f3ccc07aaed6c"
"2fa091cb67d8dfff9ae5ed254392d84211d9f600d6df7c7ef203db7cb9a9ca38c444c0"
"e977138597c39e794e54f59600eee3ca3e745624a02305ebc5d2312f7b5c67b810637a"
"06277b263e7daa6c14f80c6e7f85b6b61ec7d7c6cdcf9a62994b4c002006025d9c489c"
"120400abc37bc7ec2791b3c73237450d510f455e467c6e3f46a8a08840dd627bcf1920"
"387a207788b9c38e9c4138e03b16a54e5feb985fff0968c8de3fa0d69b6484df19ccaa"
"8faad14d3e53a57b41e13e634c31b8b7d63c8893ebc05336a38daf39b4dd226af4cc35"
"b23f93f83ebfb7168d9bbef9b5ee6403e697528e259f3cded4d6da552005f6b3033e95"
"c76a72a4c94b0ee09153ae1d16ddf451bb3f9cd1fac321417a4f0b1f3ed355635e9cd2"
"eb517cf8c051d6c29b51b4605e01af9ce415f7329cf366db4061add032f5b5c8f1d63e"
"8ae633130a6130ecd5c4751c6084b6878a548b8d4d0f3cc4e932b41b6a895238d0b8e0"
"dd04300a986524496ee5a6ef5734a36985328093c3c7a12a89bd0a304b45d85ef2c943"
"6bd8646aa6174756ec8edc5af20c79ec1a8d61b201ffe8343f31f86a6e0292968fc23a"
"aa006719ce79200dfc360bbb039004c0ecaf7448380bec2afac9542ae111",
4159,
"8000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"000000000000000000000000000000000000000000000000000000000000");
CheckTestLeftShiftHex(
"9eb21c29f8f88523b70828a457aeea014e3d1150c2f9ec6e3440672abb91272c264426"
"3b015d039aa3cfe035d34e6296867778bc476ec501e4bf944a4c29ef8f3ccc07aaed6c"
"2fa091cb67d8dfff9ae5ed254392d84211d9f600d6df7c7ef203db7cb9a9ca38c444c0"
"e977138597c39e794e54f59600eee3ca3e745624a02305ebc5d2312f7b5c67b810637a"
"06277b263e7daa6c14f80c6e7f85b6b61ec7d7c6cdcf9a62994b4c002006025d9c489c"
"120400abc37bc7ec2791b3c73237450d510f455e467c6e3f46a8a08840dd627bcf1920"
"387a207788b9c38e9c4138e03b16a54e5feb985fff0968c8de3fa0d69b6484df19ccaa"
"8faad14d3e53a57b41e13e634c31b8b7d63c8893ebc05336a38daf39b4dd226af4cc35"
"b23f93f83ebfb7168d9bbef9b5ee6403e697528e259f3cded4d6da552005f6b3033e95"
"c76a72a4c94b0ee09153ae1d16ddf451bb3f9cd1fac321417a4f0b1f3ed355635e9cd2"
"eb517cf8c051d6c29b51b4605e01af9ce415f7329cf366db4061add032f5b5c8f1d63e"
"8ae633130a6130ecd5c4751c6084b6878a548b8d4d0f3cc4e932b41b6a895238d0b8e0"
"dd04300a986524496ee5a6ef5734a36985328093c3c7a12a89bd0a304b45d85ef2c943"
"6bd8646aa6174756ec8edc5af20c79ec1a8d61b201ffe8343f31f86a6e0292968fc23a"
"aa006719ce79200dfc360bbb039004c0ecaf7448380bec2afac9542ae111",
4160,
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"000000000000000000000000000000000000000000000000000000000000");
}
BOOST_AUTO_TEST_CASE(right_shift_test) {
CheckTestRightShiftHex("", 0, "");
CheckTestRightShiftHex("", 1, "");
CheckTestRightShiftHex("63", 0, "63");
CheckTestRightShiftHex("63", 1, "31");
CheckTestRightShiftHex("63", 2, "18");
CheckTestRightShiftHex("63", 3, "0c");
CheckTestRightShiftHex("63", 4, "06");
CheckTestRightShiftHex("63", 5, "03");
CheckTestRightShiftHex("63", 6, "01");
CheckTestRightShiftHex("63", 7, "00");
CheckTestRightShiftHex("63", 8, "00");
CheckTestRightShiftHex("6347", 0, "6347");
CheckTestRightShiftHex("6347", 1, "31a3");
CheckTestRightShiftHex("6347", 7, "00c6");
CheckTestRightShiftHex("6347", 8, "0063");
CheckTestRightShiftHex("6347", 9, "0031");
CheckTestRightShiftHex(
"ebd076435d1fe29d4bc6165d49e32b2d88d58919a8106bcc9afaeda9137c10ee7131b2"
"f45d61b781b9c1d29f8f87c8be440a27379ada1e811fd3cc9cdd06fb139d1c3e01becb"
"e8be85da9657859766de3add40b1f7345056866f33dc6ef85ec89e7d02805eca428195"
"31cc4fe5c2e692f1fa9f39e7f85eba444e378e024c693e089fbb46fe36781e36ce5be1"
"068b2f36cf9cd6dcd0bc480e53549bde70a3560e32dcc697299a0bdad2fcdf869bcf56"
"45aa5baa5b8560a3b7368072e2d4f4dee7a07b0c0d747089827c09f6dbf866f8f7d94a"
"8c3592e9d1bca02a9686cc3cb2eb3b6c932d1905f832e40d4559095a416d0e74c7259c"
"266b0ad9b18f12571093ec026ecb1d7e942228e5058f2d3c9b591cb79e4a53f84499b9"
"dda1f4bf26047ab591670c3b8939759f942f3ac4d6754a88a3c909126823dc4241ecea"
"de263e9e6ae603126eb7d6ca9510184a70effb2f424079237bc7e1243438dc44ae7467"
"f49cb3f46cfc5c98a72fe8b3a45c6e60f83444c5ba911596b82359b807271d0d3d8cd5"
"e6d5dca1034de6572306407e9e248f7edd6add140fd61709b040c0b44b2cf24e9207ba"
"2fbe5b851764485541cd8ad0e35c9bf6dc27579141dc8c6e1d6b96de06fca85b248dc1"
"36906eab64287864fd3dba3d3b8483e24495ae0e19471d0f51d847e7c5b088081e491c"
"fa39ae48eae4392fe499af54c0d6adc47deed067d106a129fbc7bd7f612e",
1,
"75e83b21ae8ff14ea5e30b2ea4f19596c46ac48cd40835e64d7d76d489be08773898d9"
"7a2eb0dbc0dce0e94fc7c3e45f2205139bcd6d0f408fe9e64e6e837d89ce8e1f00df65"
"f45f42ed4b2bc2cbb36f1d6ea058fb9a282b433799ee377c2f644f3e81402f652140ca"
"98e627f2e1734978fd4f9cf3fc2f5d22271bc70126349f044fdda37f1b3c0f1b672df0"
"8345979b67ce6b6e685e240729aa4def3851ab07196e634b94cd05ed697e6fc34de7ab"
"22d52dd52dc2b051db9b4039716a7a6f73d03d8606ba3844c13e04fb6dfc337c7beca5"
"461ac974e8de50154b43661e59759db649968c82fc197206a2ac84ad20b6873a6392ce"
"1335856cd8c7892b8849f60137658ebf4a11147282c7969e4dac8e5bcf2529fc224cdc"
"eed0fa5f93023d5ac8b3861dc49cbacfca179d626b3aa54451e484893411ee2120f675"
"6f131f4f35730189375beb654a880c253877fd97a1203c91bde3f0921a1c6e22573a33"
"fa4e59fa367e2e4c5397f459d22e37307c1a2262dd488acb5c11acdc03938e869ec66a"
"f36aee5081a6f32b9183203f4f1247bf6eb56e8a07eb0b84d820605a259679274903dd"
"17df2dc28bb2242aa0e6c56871ae4dfb6e13abc8a0ee46370eb5cb6f037e542d9246e0"
"9b483755b2143c327e9edd1e9dc241f1224ad7070ca38e87a8ec23f3e2d844040f248e"
"7d1cd72475721c97f24cd7aa606b56e23ef76833e8835094fde3debfb097");
CheckTestRightShiftHex(
"2a467c005ae83afa9d8df8b13a0e0d6a3d085e8c71e4ea210ceeeb30c84cd771c5c226"
"45091dc8e91619c4525b5986db05e54174bdc02cc5b5bf12c22fe377b60615666595ba"
"323d6b4a2f354f68c93481884d7a6aba0d235e45262eeeb93c3453dcd52faf35fb569d"
"b221305dadbc74c55a40806d9838be5c42de74481450e6a672adbdddd8f541edc26b27"
"b15e5487da9ab8f7f335e1fc97d137466d97bc737c74ef8f4dfcbdb0d11268981c7a83"
"313ca63a67dac5ecda6c06e6d69eae5b51171d6d32e577bc9d13e14789a148a97c7755"
"0b2225aec7179491e0e5bc04a2aba3244d9431e5272714a0b78b6284d0fd4e6802ce98"
"0802ac9637a2140219781fddcf45652c518e6602e59a7f35bca10543ded6552559ae9d"
"de1a6dcb9e4a7812511ec18cc9a9f2740190010392ea45961ef78370ad6f5d8e7516cb"
"6db3516c14aa42ea63011d065cca4d7a23d1e0b196da933d474c058639dee71da091b3"
"ec86f4cb30ea66175725ccf5c9c99e8b30c4faa1a83cb095d5b55d3882cf5c545bb515"
"a3607c46d32792f207ff13123f08bc0fc1d2605a890ad31895c5b22c180deed8a4736d"
"891afdb0409e0402cd326f596fca4439b131e8251e1c0ef437be6832ead0e458c64388"
"87776adc2d0aa92bacac6303ca48f0c7b6c91282dea7b86d312e687582eadf90be7774"
"e7f70f9189abb9690a80bf333574f6b249eead1244b0d14fe69e7cb12f56",
2,
"0a919f0016ba0ebea7637e2c4e83835a8f4217a31c793a88433bbacc321335dc717089"
"914247723a4586711496d661b6c179505d2f700b316d6fc4b08bf8dded81855999656e"
"8c8f5ad28bcd53da324d2062135e9aae8348d791498bbbae4f0d14f7354bebcd7ed5a7"
"6c884c176b6f1d315690201b660e2f9710b79d12051439a99cab6f77763d507b709ac9"
"ec579521f6a6ae3dfccd787f25f44dd19b65ef1cdf1d3be3d37f2f6c34449a26071ea0"
"cc4f298e99f6b17b369b01b9b5a7ab96d445c75b4cb95def2744f851e268522a5f1dd5"
"42c8896bb1c5e52478396f0128aae8c913650c7949c9c5282de2d8a1343f539a00b3a6"
"0200ab258de88500865e07f773d1594b14639980b9669fcd6f284150f7b59549566ba7"
"77869b72e7929e049447b063326a7c9d00640040e4ba916587bde0dc2b5bd7639d45b2"
"db6cd45b052a90ba98c047419732935e88f4782c65b6a4cf51d301618e77b9c768246c"
"fb21bd32cc3a9985d5c9733d727267a2cc313ea86a0f2c25756d574e20b3d71516ed45"
"68d81f11b4c9e4bc81ffc4c48fc22f03f0749816a242b4c625716c8b06037bb6291cdb"
"6246bf6c10278100b34c9bd65bf2910e6c4c7a09478703bd0def9a0cbab439163190e2"
"21dddab70b42aa4aeb2b18c0f2923c31edb244a0b7a9ee1b4c4b9a1d60bab7e42f9ddd"
"39fdc3e4626aee5a42a02fcccd5d3dac927bab44912c3453f9a79f2c4bd5");
CheckTestRightShiftHex(
"a98494f07b4dab376b2ab766f30fca375985cdc9b5de0774a98618702da6939883fa98"
"baed23fbe29cda508742ebd2120da4f680b58f69d7368c2ffef15c3571ea7b19cfcbef"
"31fbc998fe5b3548b6b935e067f4b9778a883c164edbf0cd7c4a8c9c4b53e80a9d6517"
"438c5034a6fec75924e40722ac1622972bbafed27ee574443ab1028ca2120ff7727cbe"
"471f0493afe8c8f196aed1e1a571769b495ccb04c1e1c19bab7f22bc29adebf1cb505a"
"d4a659d42dc06458d463826178f0c60d2ef594d3c587f1eec3b0aff01be5fab31dfa65"
"93a5a0d5aa295891fbb3a9a8d18eda9a9b8d78cde2a3e868493365796ac496e27a7876"
"c8d7b3c6b292ff13be312f610afbf5509c618f7e9def06c6d7ae88b36227838d02a8d6"
"65a8259b0ba7644a9445bd0d237d4626ce9a67f1653862df093e6aa8b09717dde3917f"
"44a4e5f4c35d0cc6b58fad65c42a5b5fb9bcdf1f716caddc9c0be86ef1726762858986"
"f9aa901e5963f73bc2ca5fada5bd4b14febe10910c32c72daae28107a3cda032115601"
"7c5b8ed36dc486bf41b8cf6ea54f3bfee549c515552cabb1f0e67af5cead0e24557732"
"bedeb2d2a4c7f37693389d38fd994166fd733b5b50e4dfd6b2df1b84612ba7f329e5be"
"4131e46299656011308426fd1b900956c1ea4a726b850e806ee8afb1f1ab2054d8b80d"
"5664ede7f7d827e49a7bbadc3a06dd490045207937cc5ef43f4607b992d7",
3,
"1530929e0f69b566ed6556ecde61f946eb30b9b936bbc0ee9530c30e05b4d273107f53"
"175da47f7c539b4a10e85d7a4241b49ed016b1ed3ae6d185ffde2b86ae3d4f6339f97d"
"e63f79331fcb66a916d726bc0cfe972ef1510782c9db7e19af895193896a7d0153aca2"
"e8718a0694dfd8eb249c80e45582c452e5775fda4fdcae8887562051944241feee4f97"
"c8e3e09275fd191e32d5da3c34ae2ed3692b9960983c3833756fe4578535bd7e396a0b"
"5a94cb3a85b80c8b1a8c704c2f1e18c1a5deb29a78b0fe3dd87615fe037cbf5663bf4c"
"b274b41ab5452b123f7675351a31db535371af19bc547d0d09266caf2d5892dc4f4f0e"
"d91af678d6525fe277c625ec215f7eaa138c31efd3bde0d8daf5d1166c44f071a0551a"
"ccb504b36174ec895288b7a1a46fa8c4d9d34cfe2ca70c5be127cd551612e2fbbc722f"
"e8949cbe986ba198d6b1f5acb8854b6bf7379be3ee2d95bb93817d0dde2e4cec50b130"
"df355203cb2c7ee778594bf5b4b7a9629fd7c212218658e5b55c5020f479b406422ac0"
"2f8b71da6db890d7e83719edd4a9e77fdca938a2aaa595763e1ccf5eb9d5a1c48aaee6"
"57dbd65a5498fe6ed26713a71fb3282cdfae676b6a1c9bfad65be3708c2574fe653cb7"
"c8263c8c532cac02261084dfa372012ad83d494e4d70a1d00ddd15f63e35640a9b1701"
"aacc9dbcfefb04fc934f775b8740dba92008a40f26f98bde87e8c0f7325a");
CheckTestRightShiftHex(
"98660ce335e12462fb5c2be76c46443825e3da19fc21a01b93271e5a9b7da55503b1de"
"3778909a36ce44ff4983706091dfcf49e5d2a4c3743fa1f5451b4a60c87836149758b1"
"01be65dfb2442a01e5203da712b205ea4d202dc6aecfeb76cf0ebff9977f1ef90cf419"
"80907d74c36e45d0804bc340058fa75f0941d4b68ad179830fc6a4e4abaa99eb9be486"
"cff2486a768135f227c01aa15bfe066fcd1a89c09d794489f836165072e68c422ca508"
"804909206d135cdc5f893b4a1a99ed9bda7eba63dbe7583b8d87b794b8230fd1b8597c"
"9c352d0fefb2526c78a536349c31df3da254666809ff3eb89737bcc901030cefe13955"
"d379f555d9295fc4b8c0d7089ed0c9856f48fcbbb9a011b26490e2b70eb4a15e60cc1f"
"2978c8e53b974a1323da9b9f1ca2db98079c8ab44c3d5086949752a3d8383cd62abd21"
"7725c3f930f1a8f40ea90499a8055b1bf46c1d59af3192e9b3fd79f6e858ebc4c1a9aa"
"654f3bea4e3030c0d898558d7d0b8394188c48cd92e2cd8b11cef98743ef724d374e9b"
"d9fa7f47a77444686d2f6c578febae518649dc14b333e8a5b199d9f98350e35cc59b56"
"437770d524ae262869ef97c9e70b897399dd3e1ca642b7a78675c51d0799a58e5fc299"
"29ef66bf9ef458101ad03bea6adbb7ef7222bf8e2b0836c77ce70ea3a71c568f309549"
"7924079c108268493e1606c67ffbe8dcfe84b3e2382dace9e3d4fe5a666d",
7,
"0130cc19c66bc248c5f6b857ced88c88704bc7b433f8434037264e3cb536fb4aaa0763"
"bc6ef121346d9c89fe9306e0c123bf9e93cba54986e87f43ea8a3694c190f06c292eb1"
"62037ccbbf64885403ca407b4e25640bd49a405b8d5d9fd6ed9e1d7ff32efe3df219e8"
"330120fae986dc8ba1009786800b1f4ebe1283a96d15a2f3061f8d49c9575533d737c9"
"0d9fe490d4ed026be44f803542b7fc0cdf9a3513813af28913f06c2ca0e5cd1884594a"
"1100921240da26b9b8bf1276943533db37b4fd74c7b7ceb0771b0f6f2970461fa370b2"
"f9386a5a1fdf64a4d8f14a6c693863be7b44a8ccd013fe7d712e6f7992020619dfc272"
"aba6f3eaabb252bf897181ae113da1930ade91f97773402364c921c56e1d6942bcc198"
"3e52f191ca772e942647b5373e3945b7300f391568987aa10d292ea547b07079ac557a"
"42ee4b87f261e351e81d520933500ab637e8d83ab35e6325d367faf3edd0b1d7898353"
"54ca9e77d49c606181b130ab1afa1707283118919b25c59b16239df30e87dee49a6e9d"
"37b3f4fe8f4ee888d0da5ed8af1fd75ca30c93b8296667d14b6333b3f306a1c6b98b36"
"ac86eee1aa495c4c50d3df2f93ce1712e733ba7c394c856f4f0ceb8a3a0f334b1cbf85"
"3253decd7f3de8b02035a077d4d5b76fdee4457f1c56106d8ef9ce1d474e38ad1e612a"
"92f2480f382104d0927c2c0d8cfff7d1b9fd0967c4705b59d3c7a9fcb4cc");
CheckTestRightShiftHex(
"ed9ff2b4ee2266892c3b73076199fceb72282b9d3bb617602257c97aee257c56601d1d"
"8526ddc75db4a791bf37cc524359475a5851df1bb7340b2b3c114170578d241ef2f625"
"67557964e588679b8f896c4a4ea1bb43a2088527705022b32056bd696c207b4d990c7b"
"6ee1aa88acef9c583da516d6338e2e77011d9c272c5805cf4ebf5508e926eb6c6d7235"
"339f1abe8aa897263ceb9fa77a4394bb7949eb6b1caf6364000c2bf5d3c650ccb39572"
"51689f7d26a4690150a623d471552dccbdcafe4d08b9eaa31863174d0f5e09f2058384"
"91f0cfa43f9eb0e77b7a1a19b12fb28997b7e667da7e9c8c46b10a45782810f52f1432"
"fa2d4860dea805e8953850e6f802e8c7ee00e4d8ae2010d9f562504796494259c7de41"
"29bd83f5a39c796ffa9c40e682198881f1d54a66497be452d80d1a3145880c67fe2086"
"49eaa2dca31bbd68aef2563b0e3d68c71e984000926291ab459c25fc16ab818ddd3ce4"
"69e826710b5f8c888ce56df3f524785cc6d17556436c2069964288e9587d644fb00558"
"b0aba76f2fad2df2130f4b030775b24b92f0d06d8bae4972e914ea9b11cb3c80197730"
"83d81de532fc43275a708a76a97e1e1f2a7d7269b2d01b2ff8095b3619cae0dd6879cf"
"3f88073db3c3e05fc27b294dd18992c32021456bf577324d996583d09681085fb42cc2"
"426433d354e8c6278db8433aa2cc7cc78af569b7c352427e9e68fd704cc8",
13,
"00076cff95a77113344961db983b0ccfe75b91415ce9ddb0bb0112be4bd7712be2b300"
"e8ec2936ee3aeda53c8df9be62921aca3ad2c28ef8ddb9a05959e08a0b82bc6920f797"
"b12b3aabcb272c433cdc7c4b6252750dda1d1044293b8281159902b5eb4b6103da6cc8"
"63db770d5445677ce2c1ed28b6b19c7173b808ece13962c02e7a75faa84749375b636b"
"91a99cf8d5f45544b931e75cfd3bd21ca5dbca4f5b58e57b1b2000615fae9e3286659c"
"ab928b44fbe93523480a85311ea38aa96e65ee57f26845cf5518c318ba687af04f902c"
"1c248f867d21fcf5873bdbd0d0cd897d944cbdbf333ed3f4e4623588522bc14087a978"
"a197d16a4306f5402f44a9c28737c017463f700726c5710086cfab12823cb24a12ce3e"
"f2094dec1fad1ce3cb7fd4e2073410cc440f8eaa53324bdf2296c068d18a2c40633ff1"
"04324f5516e518ddeb457792b1d871eb4638f4c2000493148d5a2ce12fe0b55c0c6ee9"
"e7234f4133885afc6444672b6f9fa923c2e6368baab21b61034cb214474ac3eb227d80"
"2ac5855d3b797d696f90987a58183bad925c9786836c5d724b9748a754d88e59e400cb"
"b9841ec0ef2997e2193ad38453b54bf0f0f953eb934d9680d97fc04ad9b0ce5706eb43"
"ce79fc4039ed9e1f02fe13d94a6e8c4c9619010a2b5fabb9926ccb2c1e84b40842fda1"
"661213219e9aa746313c6dc219d51663e63c57ab4dbe1a9213f4f347eb82");
CheckTestRightShiftHex(
"db80c7ae597014003cefd376acb535485a8fa13acb24e611b8f57dd752e88459512767"
"51a2360a2183dcea76da8dbbc04a94f7d2df715ad03ec69eb03ebbcf42251b5c4b3ecc"
"c5833c0c213e6e3c789e7595e3460842ae5930a1b01fcc265c6fd59f0ca6c6cb6ac6d0"
"49ec14f2fa94fc44f51c4be16233728f7908e806020cf1f01ed14fd11c5d04705cfe59"
"2b0ad022a3eaf02f52998c2702510c1804eab35cabe07e576999c6156263fd9654e8d9"
"ecc417dd5b935ac25396088b15d1a235725076fe35dceb05cd27a236b1f5c205feca69"
"a9495ccdfe81ade23d311a28cf45d58545caaf4485f2f61764f63d64991d85a6ce1181"
"85055d18099c66b1457a34bb8fc447e31e9c81c8dace80c34c63ffb07d198bb3ca2f79"
"1a54eeef3af7761192dcc152cdb9d0fdfb448aecb01d7c486f7e823462cf59a8eef23d"
"c42821104650a96330ff2b9d25e353d673df6ee0d47dff09835fcf537ee789ba27305b"
"b9f50a1b30a4ac107346452df736bb59488ee82353469a5dd70cf17fb6c6560581012c"
"a216c55c2720a658c3e45548bb5eef5e1682beadf81d0e8490a278c9b5d15bc2c2318e"
"27353b6b648b820859a1c4e878e24ec51e209067e004d094cbae59ed7cd4c2029320c2"
"979c46024dee84090ae3559155c84939dae8eca6b7771f464ad82e5fef1730c93a1457"
"af6f129d4c99b910d541a95761d9f6d990ff3b16cd981ae1e148a77a9ef7",
37,
"0000000006dc063d72cb80a001e77e9bb565a9aa42d47d09d65927308dc7abeeba9744"
"22ca893b3a8d11b0510c1ee753b6d46dde0254a7be96fb8ad681f634f581f5de7a1128"
"dae259f6662c19e06109f371e3c4f3acaf1a30421572c9850d80fe6132e37eacf86536"
"365b5636824f60a797d4a7e227a8e25f0b119b947bc847403010678f80f68a7e88e2e8"
"2382e7f2c9585681151f57817a94cc6138128860c027559ae55f03f2bb4cce30ab131f"
"ecb2a746cf6620beeadc9ad6129cb04458ae8d11ab9283b7f1aee7582e693d11b58fae"
"102ff6534d4a4ae66ff40d6f11e988d1467a2eac2a2e557a242f97b0bb27b1eb24c8ec"
"2d36708c0c282ae8c04ce3358a2bd1a5dc7e223f18f4e40e46d674061a631ffd83e8cc"
"5d9e517bc8d2a77779d7bbb08c96e60a966dce87efda24576580ebe2437bf411a3167a"
"cd477791ee2141088232854b1987f95ce92f1a9eb39efb7706a3eff84c1afe7a9bf73c"
"4dd13982ddcfa850d9852560839a32296fb9b5daca4477411a9a34d2eeb8678bfdb632"
"b02c08096510b62ae1390532c61f22aa45daf77af0b415f56fc0e874248513c64dae8a"
"de16118c7139a9db5b245c1042cd0e2743c7127628f104833f002684a65d72cf6be6a6"
"1014990614bce230126f742048571aac8aae4249ced7476535bbb8fa3256c172ff78b9"
"8649d0a2bd7b7894ea64cdc886aa0d4abb0ecfb6cc87f9d8b66cc0d70f0a");
CheckTestRightShiftHex(
"91b89e3b793648555b4bf4c22263939848879ffcd9151a3d32c893ee81360bb0134822"
"cc6c990a3d3de9eeb8c90fbbf4d94d94c21c49bfe1a2dd6b6323ae20a2f7270c50411b"
"db851c7d2d226ddc2587e452bbfbd4962a72a898de3d93b294891c8099b8351fa3ccfb"
"7e20f96683190a8dff9382103ea653cabd6ae6f01d19d86e78054c5d89e5bb088f504b"
"a623c8a6d1db4085442a2122394a5037c1e5adaf31ecd491f9b460228fef50d2dd1e50"
"c46a73c8499cd4fc9552134b19fcfeb213b59cd1c718b385199b44304e3e4a8a680d43"
"2fbe1d9e63692b8694f4ec46b8316cec5eb01f096e13d55ddcc79c94b63c6feb3ca290"
"69267a6a8a0268b5394874bad4470b0feb17541ad1310298458360af0ccf09d7fa7026"
"3a9df7947351661fa8f7afaa9aa6744318b1f5ab7f30f92b8eda6af1cd2d712a44eb06"
"e66c715068163776ed0c72d23c951cb416464c8468b68a16d2b80b061fd79d1956b8cc"
"badd86c6bf1258444f216b21969bc1b514bafef04d6bf25bf610f71a88bf69a28176a9"
"4f72a79a99d382ec46b8f3114a6bd605f9a6246ca8d5cae14cdb6b5958c181ea70fb80"
"47a6e07671953e24b93e223f525c1f735b025ec9d619aca79e2b341df5b9e7ca91c4c4"
"7c3c867c7170cb737c93df5b45f8c2cd71d1f79385e2e5ae44f4a9047e9788ddac95a8"
"5d6e07fc5bd812d2e6d44c693fe6f1616475f038778c5d394299999f4113",
398,
"0000000000000000000000000000000000000000000000000000000000000000000000"
"00000000000000000000000000000246e278ede4d921556d2fd308898e4e61221e7ff3"
"645468f4cb224fba04d82ec04d208b31b26428f4f7a7bae3243eefd3653653087126ff"
"868b75ad8c8eb8828bdc9c3141046f6e1471f4b489b770961f914aefef5258a9caa263"
"78f64eca5224720266e0d47e8f33edf883e59a0c642a37fe4e0840fa994f2af5ab9bc0"
"746761b9e01531762796ec223d412e988f229b476d021510a88488e52940df0796b6bc"
"c7b35247e6d1808a3fbd434b74794311a9cf21267353f255484d2c67f3fac84ed67347"
"1c62ce14666d10c138f92a29a0350cbef876798da4ae1a53d3b11ae0c5b3b17ac07c25"
"b84f5577731e7252d8f1bfacf28a41a499e9aa2809a2d4e521d2eb511c2c3fac5d506b"
"44c40a61160d82bc333c275fe9c098ea77de51cd45987ea3debeaa6a99d10c62c7d6ad"
"fcc3e4ae3b69abc734b5c4a913ac1b99b1c541a058dddbb431cb48f25472d059193211"
"a2da285b4ae02c187f5e74655ae332eb761b1afc4961113c85ac865a6f06d452ebfbc1"
"35afc96fd843dc6a22fda68a05daa53dca9e6a674e0bb11ae3cc4529af5817e69891b2"
"a3572b85336dad65630607a9c3ee011e9b81d9c654f892e4f888fd49707dcd6c097b27"
"5866b29e78acd077d6e79f2a471311f0f219f1c5c32dcdf24f7d6d17e30b");
CheckTestRightShiftHex(
"eb8baf207037a28801f631673410255a2b8f36e868f98793d4cdd5180907b801be38ef"
"aa1ab75420f57f80825d5c0638a7519a777bf85772b616e5883d3f5c6c424cb1f32d71"
"c051203ca1465b15729d0b2a865600c7614db607bc6fe8564ab0c2f2e4a12f252004dd"
"f82bb0d36b23b8f8f1efb2814bdd6a6fb17f90028494a67db72fda1d0c2ef72f170f30"
"4b4a28b3bc51c2e58e8e009785c6584dbdd665834326a6d59b98736836b9044608f3d6"
"37616570a83904b934e0db5c3741e3a83c7d209802cf8c89a6af2d74af2e313630411d"
"240f00c3aca3fb343d20be9f2ce48949ca291d9604963321d2eb4d5732e84749c4d9d1"
"5071595e1a10a665b62ec9da697952efa8f231dd7cb429447f607ec116b9eedfc0bb3f"
"a86366120306c27c5e3ee5918717148ee3481183a181726fa2de825cfbc3d922ff7b2f"
"003d7873f40853b2fa45128ef712df2a46f241907db643cadf5145fcb77cc1a11a2fad"
"fdfabc2b137e68300f2f4cc5d6d508f93f0bab9d5abab5952ebf0e12614801c78d8dde"
"7d43e243d165677ee2d0d92b2c2c98fb86ae736e796536757f54a68ee69e60f2c3c201"
"3418d16d67842414004b3da73ab0c2cc1625b18af0bc73c32e1fa44219f4a4bfcc3975"
"993a6935b6d056f37b14f38009ff817bd8f09139a7fcb065a5562d22976846f883588f"
"d5a7904a54c6b3997aab24aa09e85fb670cf9fe0e72c9fd2351177d18b0a",
2489,
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000075c5d790"
"381bd14400fb18b39a0812ad15c79b74347cc3c9ea66ea8c0483dc00df1c77d50d5baa"
"107abfc0412eae031c53a8cd3bbdfc2bb95b0b72c41e9fae36212658f996b8e028901e"
"50a32d8ab94e8595432b0063b0a6db03de37f42b255861797250979290026efc15d869"
"b591dc7c78f7d940a5eeb537d8bfc801424a533edb97ed0e86177b978b879825a51459"
"de28e172c747004bc2e32c26deeb32c1a193536acdcc39b41b5c82230479eb1bb0b2b8"
"541c825c9a706dae1ba0f1d41e3e904c0167c644d35796ba5797189b1820");
CheckTestRightShiftHex(
"0b0d15d774b99ba942850db1c241026d622134010042e6ee81030c23e4d6d4b0668cfb"
"1be94b064ed5d51ab700c999c41b2b6be0f4b75f3cd0dee87d682e2729f6d68ee2ab1e"
"0dd98ee038395fac6a8a7058a0ecf3353507324652e9277d9aebf6a37662cfe5cda9c3"
"10e2cf278b0a9bea20ad625dd6984fb7bb7918adae491a94293163eebdde9040652399"
"db552d312a2592fd7e7edfde6cff38c365f8f20a02fd26a124d46944381e67174c7225"
"656a5b8e41525c97cde1a5cf70b846670f1cafc655bbf115511d63d0d8db503807efc0"
"cef1716f637b8871035e092003f4709e690350b4c6ad520648a6d17b1964465ada5508"
"bd99df5e68c4915c0e389395e898fd3800d4da40010aca27cdb898126884fca767db34"
"cf03360126a2a848a4bdf28f900cc9cdf5bca267d98692d3dbf6217d9907ae8b4dac61"
"158ff7ca0b6737851967fb1cc4bf0ac841999066372472cff6143d1469bc21bae74f12"
"41f69b483b997e400b879fe90e079478b5f92c5c3c1c47837addcaac7933fedc345b7d"
"04b326d05ffbb1fc1eb10dcb833f1aa40b36c9475bbc8246d8fa5203ecd734d851ea7e"
"7ea56fda62a941016f00e36a4dd353ab6187d210dc37841357ec55b6e932ddbbf176c4"
"b2d3741f36f600a0aa6d40e8be663967a6cf46a8a941c3d5a49b6b59104aee36ab0759"
"f68d8045a2503c6090a9cf8d7daa81402774859948a779af8379b89f41db",
4134,
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000002c3457");
CheckTestRightShiftHex(
"9eb21c29f8f88523b70828a457aeea014e3d1150c2f9ec6e3440672abb91272c264426"
"3b015d039aa3cfe035d34e6296867778bc476ec501e4bf944a4c29ef8f3ccc07aaed6c"
"2fa091cb67d8dfff9ae5ed254392d84211d9f600d6df7c7ef203db7cb9a9ca38c444c0"
"e977138597c39e794e54f59600eee3ca3e745624a02305ebc5d2312f7b5c67b810637a"
"06277b263e7daa6c14f80c6e7f85b6b61ec7d7c6cdcf9a62994b4c002006025d9c489c"
"120400abc37bc7ec2791b3c73237450d510f455e467c6e3f46a8a08840dd627bcf1920"
"387a207788b9c38e9c4138e03b16a54e5feb985fff0968c8de3fa0d69b6484df19ccaa"
"8faad14d3e53a57b41e13e634c31b8b7d63c8893ebc05336a38daf39b4dd226af4cc35"
"b23f93f83ebfb7168d9bbef9b5ee6403e697528e259f3cded4d6da552005f6b3033e95"
"c76a72a4c94b0ee09153ae1d16ddf451bb3f9cd1fac321417a4f0b1f3ed355635e9cd2"
"eb517cf8c051d6c29b51b4605e01af9ce415f7329cf366db4061add032f5b5c8f1d63e"
"8ae633130a6130ecd5c4751c6084b6878a548b8d4d0f3cc4e932b41b6a895238d0b8e0"
"dd04300a986524496ee5a6ef5734a36985328093c3c7a12a89bd0a304b45d85ef2c943"
"6bd8646aa6174756ec8edc5af20c79ec1a8d61b201ffe8343f31f86a6e0292968fc23a"
"aa006719ce79200dfc360bbb039004c0ecaf7448380bec2afac9542ae111",
4159,
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"000000000000000000000000000000000000000000000000000000000001");
CheckTestRightShiftHex(
"9eb21c29f8f88523b70828a457aeea014e3d1150c2f9ec6e3440672abb91272c264426"
"3b015d039aa3cfe035d34e6296867778bc476ec501e4bf944a4c29ef8f3ccc07aaed6c"
"2fa091cb67d8dfff9ae5ed254392d84211d9f600d6df7c7ef203db7cb9a9ca38c444c0"
"e977138597c39e794e54f59600eee3ca3e745624a02305ebc5d2312f7b5c67b810637a"
"06277b263e7daa6c14f80c6e7f85b6b61ec7d7c6cdcf9a62994b4c002006025d9c489c"
"120400abc37bc7ec2791b3c73237450d510f455e467c6e3f46a8a08840dd627bcf1920"
"387a207788b9c38e9c4138e03b16a54e5feb985fff0968c8de3fa0d69b6484df19ccaa"
"8faad14d3e53a57b41e13e634c31b8b7d63c8893ebc05336a38daf39b4dd226af4cc35"
"b23f93f83ebfb7168d9bbef9b5ee6403e697528e259f3cded4d6da552005f6b3033e95"
"c76a72a4c94b0ee09153ae1d16ddf451bb3f9cd1fac321417a4f0b1f3ed355635e9cd2"
"eb517cf8c051d6c29b51b4605e01af9ce415f7329cf366db4061add032f5b5c8f1d63e"
"8ae633130a6130ecd5c4751c6084b6878a548b8d4d0f3cc4e932b41b6a895238d0b8e0"
"dd04300a986524496ee5a6ef5734a36985328093c3c7a12a89bd0a304b45d85ef2c943"
"6bd8646aa6174756ec8edc5af20c79ec1a8d61b201ffe8343f31f86a6e0292968fc23a"
"aa006719ce79200dfc360bbb039004c0ecaf7448380bec2afac9542ae111",
4160,
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000000000"
"000000000000000000000000000000000000000000000000000000000000");
}
BOOST_AUTO_TEST_SUITE_END()
| 69.693662 | 80 | 0.836407 | ngocviet |
419cbe19c7a675128ba01b7b1ae6a134630a2d93 | 4,503 | cpp | C++ | libwoopsigfx/src/stringiterator.cpp | ant512/WoopsiGfx | 9aa29bcd8d6d336172b49bbd1363ddf0bb7dad9d | [
"MIT"
] | null | null | null | libwoopsigfx/src/stringiterator.cpp | ant512/WoopsiGfx | 9aa29bcd8d6d336172b49bbd1363ddf0bb7dad9d | [
"MIT"
] | null | null | null | libwoopsigfx/src/stringiterator.cpp | ant512/WoopsiGfx | 9aa29bcd8d6d336172b49bbd1363ddf0bb7dad9d | [
"MIT"
] | 1 | 2021-08-21T07:57:58.000Z | 2021-08-21T07:57:58.000Z | #include <ctype.h>
#include "stringiterator.h"
#include "woopsistring.h"
using namespace WoopsiGfx;
StringIterator::StringIterator(const WoopsiString* string) {
_string = string;
_currentChar = _string->getCharArray();
_currentIndex = 0;
}
void StringIterator::moveToFirst() {
_currentChar = _string->getCharArray();
_currentIndex = 0;
}
u8 StringIterator::getCodePointSize() {
// Return 0 if string has no data
if (_string->getLength() == 0) return 0;
char value=*_currentChar;
if (value<0x80) return 1;
if (value<0xC2) return 0; // Can't be a leading char
if (value<0xE0) return 2;
if (value<0xF0) return 3;
if (value<0xF4) return 4; // Doesn't have legal unicode leading char after that
return 0;
}
void StringIterator::moveToLast() {
if (_string->getLength() > 0) {
_currentChar = _string->getCharArray() + _string->getByteCount() - 1;
while ((*_currentChar >= 0x80) && (*_currentChar < 0xC0)) _currentChar--;
// String has been filtered before; no need to check if value >=0xF4
_currentIndex = _string->getLength()-1;
}
}
bool StringIterator::moveToNext() {
if (_currentIndex < _string->getLength() - 1) {
_currentChar += getCodePointSize();
_currentIndex++;
return true;
}
return false;
}
bool StringIterator::moveToPrevious() {
// Abort if already at the start of the string
if (_currentIndex == 0) return false;
// Move back one char to ensure we're in the middle of a char sequence
do {
_currentChar--;
} while ((*_currentChar >= 0x80) && (*_currentChar < 0xC0));
// Loop has ended, so we must have found a valid codepoint; we know
// that we're looking at the previous character index
_currentIndex--;
return true;
}
void StringIterator::iterateForwardsTo(s32 index) {
do {
moveToNext();
} while (index > _currentIndex);
}
void StringIterator::iterateBackwardsTo(s32 index) {
do {
moveToPrevious();
} while (_currentIndex > index);
}
bool StringIterator::moveTo(s32 index) {
// Abort if index makes no sense
if (index < 0) return false;
// Abort if index exceeds the size of the string
if (index >= _string->getLength()) return false;
// Abort if new index matches current index
if (index == _currentIndex) return true;
// Move to end if requested index is at end of string
if (index == _string->getLength() - 1) {
moveToLast();
return true;
}
// Move to start if requested index is 0
if (index == 0) {
moveToFirst();
return true;
}
// Decide if it is faster to iterate over the string from the current point
// or from the front or back
if (index > _currentIndex) {
// Requested index is past current point
// Calculate distance to the requested index from the current point
u32 distanceFromHere = index - _currentIndex;
u32 distanceFromEnd = _string->getLength() - index - 1;
if (distanceFromHere <= distanceFromEnd) {
// Shorter distance from current point to the requested index, so
// scan through string from this point forwards
iterateForwardsTo(index);
return true;
} else {
// Shorter distance from end to the requested index, so
// jump to end of string and scan through string backwards
moveToLast();
iterateBackwardsTo(index);
return true;
}
} else {
// Requested index is before current point
// Calculate distance to the requested index from the current point
u32 distanceFromHere = _currentIndex - index;
u32 distanceFromStart = index;
if (distanceFromHere <= distanceFromStart) {
// Shorter distance from current point to the requested index, so
// scan through string from this point backwards
iterateBackwardsTo(index);
return true;
} else {
// Shorter distance from start to the requested index, so
// jump to start of string and scan through string forwards
moveToFirst();
iterateForwardsTo(index);
return true;
}
}
// Should never reach this
return false;
}
u32 StringIterator::getCodePoint() const {
return _string->getCodePoint(_currentChar, NULL);
}
u32 StringIterator::getInteger(u32* charCount) {
// strtoul() will discard any white space we might currently be looking at
// which isn't the desired behaviour. We prevent this by checking that
// we're looking at a digit before we start
if (isdigit(getCodePoint())) {
char *end = NULL;
u32 digits = strtoul(_currentChar, &end, 10);
if (charCount != NULL) *charCount = (u32)(end - _currentChar);
return digits;
} else {
if (charCount != NULL) *charCount = 0;
return 0;
}
}
| 24.878453 | 80 | 0.699534 | ant512 |
41a03b9c1ade69e807c262ff82738eab90752115 | 11,890 | cpp | C++ | Components/ModelEditLinear.cpp | elix22/IogramSource | 3a4ce55d94920e060776b4aa4db710f57a4280bc | [
"MIT"
] | 28 | 2017-03-01T04:09:18.000Z | 2022-02-01T13:33:50.000Z | Components/ModelEditLinear.cpp | elix22/IogramSource | 3a4ce55d94920e060776b4aa4db710f57a4280bc | [
"MIT"
] | 3 | 2017-03-09T05:22:49.000Z | 2017-08-02T18:38:05.000Z | Components/ModelEditLinear.cpp | elix22/IogramSource | 3a4ce55d94920e060776b4aa4db710f57a4280bc | [
"MIT"
] | 17 | 2017-03-01T14:00:01.000Z | 2022-02-08T06:36:54.000Z | //
// Copyright (c) 2016 - 2017 Mesh Consultants Inc.
// 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 "ModelEditLinear.h"
#include <Urho3D/Input/InputEvents.h>
#include <Urho3D/Scene/Node.h>
#include <Urho3D/Resource/ResourceCache.h>
#include <Urho3D/Graphics/Model.h>
#include <Urho3D/Graphics/Material.h>
#include <Urho3D/Graphics/Viewport.h>
#include <Urho3D/Graphics/Renderer.h>
#include <Urho3D/Graphics/Camera.h>
#include <Urho3D/Input/Input.h>
#include <Urho3D/UI/UIElement.h>
#include <Urho3D/UI/UI.h>
#include <Urho3D/Scene/Scene.h>
#include <Urho3D/Scene/SceneEvents.h>
#include <Urho3D/IO/Log.h>
#include "TriMesh.h"
using namespace Urho3D;
ModelEditLinear::ModelEditLinear(Context* context) : Component(context),
editing_(false),
radius_(1.0f),
primaryVertexID_(-1)
{
}
void ModelEditLinear::OnNodeSet(Urho3D::Node* node)
{
Component::OnNodeSet(node);
if (!node)
{
return;
}
// //create the editor
// CreateMeshEditor();
//subscribe to events
SubscribeToEvent(E_MOUSEBUTTONDOWN, URHO3D_HANDLER(ModelEditLinear, HandleMouseDown));
SubscribeToEvent(E_MOUSEMOVE, URHO3D_HANDLER(ModelEditLinear, HandleMouseMove));
SubscribeToEvent(E_MOUSEBUTTONUP, URHO3D_HANDLER(ModelEditLinear, HandleMouseUp));
SubscribeToEvent(E_COMPONENTREMOVED, URHO3D_HANDLER(ModelEditLinear, HandleComponentRemoved));
}
void ModelEditLinear::HandleComponentRemoved(Urho3D::StringHash eventType, Urho3D::VariantMap& eventData)
{
using namespace ComponentRemoved;
URHO3D_LOGINFO("Check MB");
Component* c = (Component*)eventData[P_COMPONENT].GetPtr();
if (c == this)
{
UnsubscribeFromAllEvents();
if (meshEditor_)
{
meshEditor_->Remove();
}
}
}
void ModelEditLinear::CreateMeshEditor()
{
//create billboard set
VariantVector verts = TriMesh_GetVertexList(baseGeometry_);
ResourceCache* rc = GetSubsystem<ResourceCache>();
Material* mat = rc->GetResource<Material>("Materials/BasicPoints.xml");
SharedPtr<Material> clonedMat = mat->Clone();
//Texture* tex = rc->GetResource<Texture>("Textures/SpotWide.png");
float width = 10.0f;
Color col = Color::WHITE;
//clonedMat->SetTexture(TU_DIFFUSE, tex);
clonedMat->SetShaderParameter("MatDiffColor", col);
URHO3D_LOGINFO("Check MA");
meshEditor_ = GetNode()->CreateComponent<BillboardSet>();
meshEditor_->SetNumBillboards(verts.Size());
meshEditor_->SetMaterial(clonedMat);
meshEditor_->SetSorted(true);
meshEditor_->SetFaceCameraMode(FaceCameraMode::FC_ROTATE_XYZ);
meshEditor_->SetFixedScreenSize(true);
//create the vertex renderer
for (int i = 0; i < verts.Size(); i++)
{
Billboard* bb = meshEditor_->GetBillboard(i);
Vector3 vA = verts[i].GetVector3();
//render the point
bb = meshEditor_->GetBillboard(i);
bb->position_ = vA;
bb->size_ = Vector2(width, width);
bb->enabled_ = true;
bb->color_ = col;
}
//commit
meshEditor_->Commit();
}
void ModelEditLinear::SetBaseGeometry(const Urho3D::Variant& geometry)
{
baseGeometry_ = geometry;
//create the editor
CreateMeshEditor();
}
void ModelEditLinear::GetCurrentGeometry(Urho3D::Variant& geometryOut)
{
geometryOut = baseGeometry_;
}
IntVector2 ModelEditLinear::GetScaledMousePosition()
{
IntVector2 mPos = GetSubsystem<Input>()->GetMousePosition();
float scale = GetSubsystem<UI>()->GetScale();
mPos.x_ = (int)(mPos.x_ * (1.0f / scale));
mPos.y_ = (int)(mPos.y_ * (1.0f / scale));
return mPos;
}
void ModelEditLinear::HandleUpdate(Urho3D::StringHash eventType, Urho3D::VariantMap& eventData)
{
}
void ModelEditLinear::HandleMouseDown(Urho3D::StringHash eventType, Urho3D::VariantMap& eventData)
{
using namespace MouseButtonDown;
int mb = eventData[P_BUTTON].GetInt();
if (mb == MOUSEB_LEFT && !editing_) {
URHO3D_LOGINFO("About to raycast..");
if (Raycast()) {
URHO3D_LOGINFO("Hello mouse down!");
//UI* ui = GetSubsystem<UI>();
startScreenPos_ = GetScaledMousePosition();
primaryVertexID_ = raycastResult_.subObject_;
editing_ = true;
}
}
}
void ModelEditLinear::HandleMouseMove(Urho3D::StringHash eventType, Urho3D::VariantMap& eventData)
{
using namespace MouseMove;
if (editing_) {
int x = eventData[P_X].GetInt();
int y = eventData[P_Y].GetInt();
//mpos
//UI* ui = GetSubsystem<UI>();
IntVector2 mPos = GetScaledMousePosition();
IntVector2 screenDeltaVec = mPos - startScreenPos_;
Ray screenRay;
bool res = GetScreenRay(mPos, screenRay);
if (!res)
return;
Vector3 sceneHint = screenRay.origin_ + raycastResult_.distance_ * screenRay.direction_;
Vector3 sceneDeltaVec = sceneHint - raycastResult_.position_;
//update node visuals
BillboardSet* bs = (BillboardSet*)raycastResult_.drawable_;
if (bs && primaryVertexID_ < bs->GetNumBillboards())
{
//retrieve original vertex position
VariantVector verts = TriMesh_GetVertexList(baseGeometry_);
//get the specific billboard
Billboard* b = bs->GetBillboard(primaryVertexID_);
if (primaryVertexID_ >= verts.Size())
{
return;
}
//move the vertex
Vector3 currVert = verts[primaryVertexID_].GetVector3();
//track displacement and index
primaryDelta_ = sceneDeltaVec;
//move the vertex
b->position_ = sceneHint;
bs->Commit();
}
}
}
void ModelEditLinear::HandleMouseUp(Urho3D::StringHash eventType, Urho3D::VariantMap& eventData)
{
using namespace MouseButtonUp;
int mb = eventData[P_BUTTON].GetInt();
if (mb == MOUSEB_LEFT && editing_ && primaryVertexID_ >= 0) {
editing_ = false;
URHO3D_LOGINFO("Hello mouse up!");
//use delta and object transform to move object
Viewport* activeViewport = (Viewport*)GetGlobalVar("activeViewport").GetVoidPtr();
Camera* currentCamera = activeViewport->GetCamera();
if (!currentCamera || !activeViewport)
{
return;
}
VariantVector verts = TriMesh_GetVertexList(baseGeometry_);
VariantVector faces = TriMesh_GetFaceList(baseGeometry_);
// Need to get the billboard ID that was moved, and compute the vector from that billboard to the original vert
Vector3 disp = primaryDelta_;
int bIndex = primaryVertexID_;
Vector3 orgVert = verts[bIndex].GetVector3();
Variant geomOut;
Vector<Vector3> deltas;
Vector<int> ids;
//always push the moved vertex
deltas.Push(primaryDelta_);
ids.Push(primaryVertexID_);
//find deltas and ids
for (int i = 0; i < verts.Size(); i++)
{
Vector3 v = verts[i].GetVector3();
float dist = (v - orgVert).Length();
if (dist < radius_)
{
if (dist != 0 && radius_ != 0) {
deltas.Push(((radius_-dist)/radius_)*primaryDelta_);
ids.Push(i);
}
}
else
{
// deltas.Push(Vector3::ZERO);
// ids.Push(i);
}
}
//do deformation
DoLinearDeformation(deltas, ids, geomOut);
//update base geometry
baseGeometry_ = geomOut;
//update handles based on new geometry
UpdateHandles();
// this is roundabout
VariantMap data;
data["EditedMesh"] = geomOut;
//fill data
SendEvent("ModelEditChangeLinear", data);
//reset
primaryDelta_ = Vector3::ZERO;
primaryVertexID_ = -1;
}
}
void ModelEditLinear::UpdateHandles()
{
if (meshEditor_)
{
URHO3D_LOGINFO("Updating mesh editor");
VariantVector verts = TriMesh_GetVertexList(baseGeometry_);
if (verts.Size() == meshEditor_->GetNumBillboards())
{
for (int i = 0; i < verts.Size(); i++)
{
meshEditor_->GetBillboard(i)->position_ = verts[i].GetVector3();
}
}
meshEditor_->Commit();
}
}
void ModelEditLinear::DoHarmonicDeformation(Urho3D::Vector<Vector3> deltas, Urho3D::Vector<int> ids, Variant& geomOut)
{
//////do harmonic deformation
//init matrices
Eigen::MatrixXd V;
Eigen::MatrixXi F;
Eigen::VectorXi b;
Eigen::MatrixXd D_bc;
Eigen::MatrixXd D;
//TriMeshToMatrices(mesh, V, F);
VariantVector verts = TriMesh_GetVertexList(baseGeometry_);
TriMeshToDoubleMatrices(baseGeometry_, V, F);
//collect the disp vecs and indices
int numVecs = Min(deltas.Size(), ids.Size());
b.resize(numVecs);
D_bc.resize(numVecs, 3);
//create the handle and displacement vectors
for (int i = 0; i < numVecs; i++)
{
int idx = ids[i];
Vector3 v = deltas[i];
D_bc.row(i) = Eigen::RowVector3d(v.x_, v.y_, v.z_);
b[i] = idx;
}
//finally, proceed with calculation
int power = 2;
// igl::harmonic(V, F, b, D_bc, power, D);
int dRows = D.rows();
int dCols = D.cols();
VariantVector vecsOut;
for (int i = 0; i < D.rows(); i++)
{
Eigen::RowVector3d v = D.row(i);
Vector3 dV = Vector3(v.x(), v.y(), v.z());
vecsOut.Push(dV);
Vector3 orgVert = verts[i].GetVector3();
verts[i] = orgVert + dV;
}
//create new trimesh
geomOut = TriMesh_Make(verts, TriMesh_GetFaceList(baseGeometry_));
URHO3D_LOGINFO("Done Harmonic Deformation!");
}
void ModelEditLinear::DoLinearDeformation(Urho3D::Vector<Urho3D::Vector3> deltas, Urho3D::Vector<int> ids, Urho3D::Variant & geomOut)
{
// This will just add the deltas to the vertices specified by the vector of IDs.
VariantVector verts = TriMesh_GetVertexList(baseGeometry_);
VariantVector faces = TriMesh_GetFaceList(baseGeometry_);
for (int i = 0; i < ids.Size(); ++i) {
if (ids[i] > verts.Size())
return;
Vector3 currVert = verts[ids[i]].GetVector3();
verts[ids[i]] = currVert + deltas[i];
}
geomOut = TriMesh_Make(verts, faces);
}
bool ModelEditLinear::GetScreenRay(Urho3D::IntVector2 screenPos, Urho3D::Ray& ray)
{
//try to get default viewport first
Viewport* activeViewport = (Viewport*)GetGlobalVar("activeViewport").GetVoidPtr();
if (!activeViewport)
{
URHO3D_LOGINFO("No active viewport found...");
return false;
}
//also check if we are casting from inside a ui region
UIElement* uiRegion = (UIElement*)GetGlobalVar("activeUIRegion").GetPtr();
//get default ray
ray = activeViewport->GetScreenRay(screenPos.x_, screenPos.y_);
if (uiRegion)
{
IntVector2 ePos = uiRegion->GetScreenPosition();
IntVector2 eSize = uiRegion->GetSize();
float x = (screenPos.x_ - ePos.x_) / (float)eSize.x_;
float y = (screenPos.y_ - ePos.y_) / (float)eSize.y_;
ray = activeViewport->GetCamera()->GetScreenRay(x, y);
}
return true;
}
bool ModelEditLinear::Raycast()
{
//get mouse pos via ui system to account for scaling
UI* ui = GetSubsystem<UI>();
IntVector2 pos = GetScaledMousePosition();
//get general screen ray, taking ui stuff in to account
Ray cameraRay;
bool res = GetScreenRay(pos, cameraRay);
if(!res)
{
URHO3D_LOGINFO("Bad ray or no viewport found");
return false;
}
//do cast
PODVector<RayQueryResult> results;
RayOctreeQuery query(results, cameraRay, RAY_TRIANGLE, 600.0f, DRAWABLE_GEOMETRY);
GetScene()->GetComponent<Octree>()->Raycast(query);
if (results.Size() > 0)
{
for (int i = 0; i < results.Size(); i++)
{
BillboardSet* bs = (BillboardSet*)results[i].drawable_;
if (bs == meshEditor_)
{
raycastResult_ = results[i];
return true;
}
}
}
return false;
}
| 25.084388 | 133 | 0.713204 | elix22 |
41a2e2fb9777e837d9942e9c28e0d86e270456bc | 23,537 | cpp | C++ | fcgi/streambuf.cpp | dmitigr/cefeika | 6189843d4244f7334558708e57e952584561b1e0 | [
"Zlib"
] | 19 | 2019-07-21T15:38:12.000Z | 2022-01-06T05:24:48.000Z | fcgi/streambuf.cpp | dmitigr/cefeika | 6189843d4244f7334558708e57e952584561b1e0 | [
"Zlib"
] | 6 | 2019-12-07T22:12:37.000Z | 2022-01-10T22:31:48.000Z | fcgi/streambuf.cpp | dmitigr/cefeika | 6189843d4244f7334558708e57e952584561b1e0 | [
"Zlib"
] | 1 | 2019-08-15T14:49:00.000Z | 2019-08-15T14:49:00.000Z | // -*- C++ -*-
// Copyright (C) 2021 Dmitry Igrishin
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
//
// Dmitry Igrishin
// dmitigr@gmail.com
#include "basics.hpp"
#include "exceptions.hpp"
#include "server_connection.hpp"
#include "streambuf.hpp"
#include "../error/assert.hpp"
#include "../math.hpp"
#include <algorithm>
#include <array>
#include <cstdio>
#include <istream>
#include <limits>
#include <ostream>
/*
* By defining DMITIGR_FCGI_DEBUG some convenient stuff for debugging
* will be available, for example, server_Streambuf::print().
*/
//#define DMITIGR_FCGI_DEBUG
#ifdef DMITIGR_FCGI_DEBUG
#include <iostream>
#endif
namespace dmitigr::fcgi::detail {
/**
* @brief The base implementation of Streambuf.
*/
class iStreambuf : public Streambuf {
private:
friend server_Streambuf;
using Streambuf::Streambuf;
};
/**
* @brief The implementation of the `std::streambuf` for a FastCGI server.
*/
class server_Streambuf final : public iStreambuf {
public:
using Type = Stream_type;
~server_Streambuf() override
{
try {
close();
} catch (const std::exception& e) {
std::fprintf(stderr, "dmitigr::fcgi: %s\n", e.what());
} catch (...) {
std::fprintf(stderr, "dmitigr::fcgi: failure\n");
}
}
server_Streambuf(const server_Streambuf&) = delete;
server_Streambuf& operator=(const server_Streambuf&) = delete;
server_Streambuf(server_Streambuf&&) = delete;
server_Streambuf& operator=(server_Streambuf&&) = delete;
/**
* @brief The constructor.
*/
server_Streambuf(iServer_connection* const connection, char_type* const buffer,
const std::streamsize buffer_size, const Type type)
: type_{type}
, connection_{connection}
{
DMITIGR_ASSERT(connection);
setg(nullptr, nullptr, nullptr);
setp(nullptr, nullptr);
setbuf(buffer, buffer_size);
DMITIGR_ASSERT(is_invariant_ok());
}
/**
* @brief Closes the stream.
*
* If this instance represents the streambuf of the output stream (either
* Stream_type::err or Stream_type::out) then transmits the end records to
* the FastCGI client and sets `is_end_of_stream_` to `true`. (The
* transmission of the end records takes place if and only if it is not
* contradicts the protocol.)
*
* @par Effects
* `is_closed()`. Also, unsets both the get area and the put area.
*/
void close()
{
if (is_closed())
return;
if (!is_reader()) {
const auto* const inbuf = dynamic_cast<server_Streambuf*>(connection_->in().streambuf());
DMITIGR_ASSERT(inbuf && inbuf->is_reader() && !inbuf->is_closed());
const auto role = connection_->role();
DMITIGR_ASSERT(role == Role::authorizer || inbuf->type_ != Type::params);
if (role != Role::filter || inbuf->type_ == Type::data || inbuf->unread_content_length_ == 0) {
is_end_records_must_be_transmitted_ = true;
sync();
} else
throw Generic_exception{"not all FastCGI stdin has been read by Filter"};
DMITIGR_ASSERT(is_end_of_stream_ && !is_end_records_must_be_transmitted_);
}
setg(nullptr, nullptr, nullptr);
setp(nullptr, nullptr);
DMITIGR_ASSERT(is_closed());
DMITIGR_ASSERT(is_invariant_ok());
}
/**
* @returns `true` if this instance is for receiving the
* data from the FastCGI client, or `false` otherwise.
*/
bool is_reader() const
{
return (type_ == Type::in || type_ == Type::params || type_ == Type::data);
}
/**
* @returns `true` if this instance is unusable anymore, or `false` otherwise.
*/
bool is_closed() const
{
return is_reader() ? !eback() : !pbase();
}
/**
* @returns `true` if this instance is ready to switching to the filter mode.
*/
bool is_ready_to_filter_data() const
{
return !is_closed() && (connection_->role() == Role::filter) && (type_ == Type::in) && is_end_of_stream_;
}
/**
* @returns The stream type.
*/
Type stream_type() const
{
return type_;
}
protected:
// std::streambuf overridings:
server_Streambuf* setbuf(char_type* const buffer, const std::streamsize size) override
{
DMITIGR_ASSERT(buffer && (2048 <= size && size <= 65528));
if ((eback() != nullptr && eback() != buffer_) ||
(pbase() != nullptr && pbase() != buffer_ + sizeof(detail::Header)))
throw Generic_exception{"cannot set FastCGI buffer (there are pending data)"};
constexpr std::streamsize alignment = 8;
buffer_ = buffer;
buffer_size_ = size - (alignment - math::padding(size, alignment)) % alignment;
if (is_reader()) {
setg(buffer_, buffer_, buffer_);
buffer_end_ = buffer_;
setp(nullptr, nullptr);
} else {
/*
* First sizeof(detail::Header) bytes of the buffer_ are reserved for Header.
* Last byte of the buffer_ is reserved for byte passed to overflow(). Thus,
* epptr() can be used to store this byte.
*/
setg(nullptr, nullptr, nullptr);
setp(buffer_ + sizeof(detail::Header), buffer_ + buffer_size_ - 1);
}
DMITIGR_ASSERT(is_invariant_ok());
return this;
}
int sync() override
{
const auto ch = overflow(traits_type::eof());
return traits_type::eq_int_type(ch, traits_type::eof()) ? -1 : 0;
}
int_type underflow() override
{
DMITIGR_ASSERT(is_reader() && !is_closed());
if (is_end_of_stream_)
return traits_type::eof();
detail::Header header{};
std::size_t read_header_length{};
while (true) {
// Reading the stream records.
if (gptr() == buffer_end_) {
const std::streamsize count = connection_->io_->read(buffer_, buffer_size_);
if (count > 0) {
buffer_end_ = buffer_ + count;
setg(buffer_, buffer_, buffer_end_);
} else
throw Generic_exception{"FastCGI protocol violation"};
}
DMITIGR_ASSERT(buffer_end_ - gptr() > 0);
// Setting up the get area for the content.
if (unread_content_length_ > 0) {
const std::streamsize count = std::min(unread_content_length_, buffer_end_ - gptr());
unread_content_length_ -= count;
if (!is_content_must_be_discarded_) {
setg(gptr(), gptr(), gptr() + count); // Get area now contains all available content bytes at the moment.
DMITIGR_ASSERT(is_invariant_ok());
return traits_type::to_int_type(*gptr());
} else {
gbump(static_cast<int>(count)); // Discarding.
if (unread_content_length_ > 0)
continue;
else
is_content_must_be_discarded_ = false;
}
}
DMITIGR_ASSERT(unread_content_length_ == 0);
// Skipping the padding.
if (unread_padding_length_ > 0) {
const std::streamsize count = std::min(unread_padding_length_, buffer_end_ - gptr());
unread_padding_length_ -= count;
gbump(static_cast<int>(count)); // Skipping.
if (unread_padding_length_ > 0)
continue;
}
DMITIGR_ASSERT(unread_padding_length_ == 0);
// ---------------
// The start point
// ---------------
// Accumulating the header.
{
const std::size_t count = std::min(sizeof(header) - read_header_length, static_cast<std::size_t>(buffer_end_ - gptr()));
std::memcpy(reinterpret_cast<char*>(&header) + read_header_length, gptr(), count);
read_header_length += count;
gbump(static_cast<int>(count)); // Already consumed.
if (read_header_length < sizeof(header))
continue;
}
DMITIGR_ASSERT(read_header_length == sizeof(header));
// Processing the header.
{
const auto set_end_of_stream = [&]()
{
setg(gptr(), gptr(), gptr());
is_end_of_stream_ = true;
DMITIGR_ASSERT(is_invariant_ok());
};
setg(gptr(), gptr(), gptr());
const auto phr = process_header(header);
switch(phr) {
case Process_header_result::request_rejected:
set_end_of_stream();
return traits_type::eof();
case Process_header_result::management_processed:
continue;
case Process_header_result::content_must_be_consumed:
if (unread_content_length_ == 0) {
set_end_of_stream();
if (is_ready_to_filter_data())
reset_reader(Type::data);
return traits_type::eof();
} else
continue;
case Process_header_result::content_must_be_discarded:
is_content_must_be_discarded_ = true;
continue;
}
}
}
}
int_type overflow(const int_type ch) override
{
DMITIGR_ASSERT(!is_reader() && !is_closed());
if (is_end_of_stream_)
return traits_type::eof();
const bool is_eof = traits_type::eq_int_type(ch, traits_type::eof());
DMITIGR_ASSERT(pbase() == (buffer_ + sizeof(detail::Header)));
if (std::streamsize content_length = pptr() - pbase()) {
/*
* If `ch` is not EOF we need to place `ch` at the location pointed to by
* pptr(). (It's ok if pptr() == epptr() since that location is a valid
* writable location reserved for extra `ch`.)
* The content should be aligned by padding if necessary, and the record
* header must be injected at the reserved space [buffer_, pbase()).
* After that the result record will be ready to send to a client.
*/
// Store `ch` if it's not EOF.
if (!is_eof) {
DMITIGR_ASSERT(pptr() <= epptr());
*pptr() = static_cast<char>(ch);
pbump(1); // Yes, pptr() > epptr() is possible here, but this is ok.
content_length++;
}
// Aligning the content by padding if necessary.
const auto padding_length = dmitigr::math::padding<std::streamsize>(content_length, 8);
DMITIGR_ASSERT(padding_length <= epptr() - pptr() + 1);
std::memset(pptr(), 0, static_cast<std::size_t>(padding_length));
pbump(static_cast<int>(padding_length));
// Injecting the header.
auto* const header = reinterpret_cast<detail::Header*>(buffer_);
*header = detail::Header{static_cast<detail::Record_type>(type_),
connection_->request_id(),
static_cast<std::size_t>(content_length),
static_cast<std::size_t>(padding_length)};
// Sending the record.
if (const auto record_size = pptr() - buffer_; static_cast<std::size_t>(record_size) > sizeof(detail::Header)) {
const std::streamsize count = connection_->io_->write(static_cast<const char*>(buffer_), record_size);
DMITIGR_ASSERT(count == record_size);
is_put_area_at_least_once_consumed_ = true;
}
}
setp(buffer_ + sizeof(detail::Header), buffer_ + buffer_size_ - 1);
if (is_end_records_must_be_transmitted_) {
/*
* We'll use buffer_ directly here. (Space before pbase() will be used.)
* data_size is a size of data in the buffer_ to send.
*/
std::streamsize data_size{};
const auto is_empty = [this]()
{
return pptr() == pbase() && !is_put_area_at_least_once_consumed_;
};
if (type_ != Type::err || !is_empty()) {
/*
* When transmitting a stream other than stderr, at least one record of
* the stream type must be trasmitted, even if the stream is empty.
* When transmitting a stream of type stderr and there is no errors to
* report, either no stderr records or one zero-length stderr record
* must be transmitted. (As optimization, no stderr records are
* transmitted if the stream is empty.)
*/
auto* const header = reinterpret_cast<detail::Header*>(buffer_ + data_size);
*header = detail::Header{static_cast<detail::Record_type>(type_), connection_->request_id(), 0, 0};
data_size += sizeof(detail::Header);
}
/*
* Assume that the stream of type `out` is closes last. (This must be
* guaranteed by the implementation of Listener.)
*/
if (type_ == Type::out) {
auto* const record = reinterpret_cast<detail::End_request_record*>(buffer_ + data_size);
*record = detail::End_request_record{
connection_->request_id(),
connection_->application_status(),
detail::Protocol_status::request_complete};
data_size += sizeof(detail::End_request_record);
}
if (data_size > 0) {
const std::streamsize count = connection_->io_->write(static_cast<const char*>(buffer_), data_size);
DMITIGR_ASSERT(count == data_size);
}
is_end_records_must_be_transmitted_ = false;
is_end_of_stream_ = true;
}
DMITIGR_ASSERT(is_invariant_ok());
return is_eof ? traits_type::not_eof(ch) : ch;
}
private:
friend server_Istream;
/**
* @brief A result of process_header().
*/
enum class Process_header_result {
/** A request is rejected. */
request_rejected,
/** A management record processed. */
management_processed,
/** A content from a client must be consumed. */
content_must_be_consumed,
/** A content from a client must be discarded. */
content_must_be_discarded
};
Type type_{};
bool is_content_must_be_discarded_{};
bool is_end_of_stream_{};
bool is_end_records_must_be_transmitted_{};
bool is_put_area_at_least_once_consumed_{};
char_type* buffer_{};
char_type* buffer_end_{}; // Used by underflow() to mark the actual end of get area. (buffer_end_ <= buffer_ + buffer_size_).
std::streamsize buffer_size_{}; // The available size of the area pointed by buffer_.
std::streamsize unread_content_length_{};
std::streamsize unread_padding_length_{};
iServer_connection* const connection_{};
// ===========================================================================
bool is_invariant_ok() const
{
const bool connection_ok = (connection_ != nullptr);
const bool buffer_ok = (buffer_ != nullptr) &&
(!is_reader() || ((buffer_end_ != nullptr) && (buffer_end_ <= buffer_ + buffer_size_)));
const bool buffer_size_ok = (buffer_size_ >= 2048) && (buffer_size_ <= 65528) && (buffer_size_ % 8 == 0);
const bool unread_content_length_ok = (unread_content_length_ <= buffer_size_ &&
unread_content_length_ <= static_cast<std::streamsize>(detail::Header::max_content_length));
const bool unread_padding_length_ok = (unread_padding_length_ <= buffer_size_ &&
unread_padding_length_ <= static_cast<std::streamsize>(detail::Header::max_padding_length));
const bool reader_ok = (!is_reader() ||
(type_ == Type::params) ||
(connection_->role() == Role{0}) || // unread yet
(connection_->role() == Role::responder && type_ == Type::in) ||
(connection_->role() == Role::filter && (type_ == Type::in || type_ == Type::data)));
const bool closed_ok = (is_closed() && (is_reader() || is_end_of_stream_) &&
(eback() == nullptr && gptr() == nullptr && egptr() == nullptr) &&
(pbase() == nullptr && pptr() == nullptr && epptr() == nullptr))
||
(is_reader() &&
!(eback() == nullptr && gptr() == nullptr && egptr() == nullptr) &&
(pbase() == nullptr && pptr() == nullptr && epptr() == nullptr))
||
(!is_reader() &&
(eback() == nullptr && gptr() == nullptr && egptr() == nullptr) &&
!(pbase() == nullptr && pptr() == nullptr && epptr() == nullptr));
const bool put_area_ok = is_reader() ||
(is_closed() ||
((pbase() <= pptr() && pptr() <= epptr()) &&
(is_end_of_stream_ || (pbase() == buffer_ + sizeof(detail::Header)))));
const bool get_area_ok = !is_reader() ||
(is_closed() ||
(eback() <= gptr() && gptr() <= egptr() && egptr() <= buffer_end_));
const bool result = connection_ok && buffer_ok && buffer_size_ok && unread_content_length_ok && unread_padding_length_ok &&
reader_ok & closed_ok && put_area_ok && get_area_ok;
return result;
}
// ===========================================================================
/**
* @brief Processes a record by the header info.
*
* - (1) If `header` is the header of begin-request record then rejecting
* the request;
* - (2) If `header` is the header of management record, then responds with
* get-values-result or unknown-type record;
* - (3) If `header` is the header of stream record then do nothing.
*
* @returns
* In case (1): Process_header_result::request_rejected.
* In case (2): Process_header_result::management_processed.
* In case (3):
* a) Process_header_result::content_must_be_discarded
* if `(header.request_id() != connection_->request_id())`;
* b) Process_header_result::content_must_be_consumed
* if and only if `(header.record_type() == type_)`.
*
* @throws Generic_exception in case of (1) or on protocol violation.
*
* @par Effects
* In all cases: `(unread_content_length_ == header.content_length() && unread_padding_length_ == header.padding_length())`;
* In case (2): the effects of underflow().
*/
Process_header_result process_header(const detail::Header header)
{
header.check_validity();
unread_content_length_ = static_cast<decltype(unread_content_length_)>(header.content_length());
unread_padding_length_ = static_cast<decltype(unread_content_length_)>(header.padding_length());
const auto end_request = [&](const detail::Protocol_status protocol_status)
{
const detail::End_request_record record{header.request_id(), 0, protocol_status};
const auto count = connection_->io_->write(reinterpret_cast<const char*>(&record), sizeof(record));
DMITIGR_ASSERT(count == sizeof(record));
};
// Called in cases of protocol violation.
const auto end_request_protocol_violation = [&]()
{
end_request(detail::Protocol_status::cant_mpx_conn);
throw Generic_exception{"FastCGI protocol violation"};
};
const auto process_management_record = [&]()
{
namespace math = dmitigr::math;
if (header.record_type() == detail::Record_type::get_values) {
constexpr std::size_t max_variable_name_length = 15; // Length of "FCGI_MPXS_CONNS".
constexpr std::size_t max_body_length = 3 * (sizeof(char) + sizeof(char) + max_variable_name_length + sizeof(char));
constexpr std::streamsize max_record_length = sizeof(detail::Header) + max_body_length;
std::array<unsigned char, math::aligned<std::size_t>(max_record_length, 8)> record;
static_assert((record.size() % 8 == 0));
// Reading the requested variables.
const auto variables = [&]()
{
std::istream stream{this};
return detail::Names_values{stream, 3};
}();
if (unread_content_length_ > 0)
end_request_protocol_violation();
// Filling up the content of get-values-result.
const auto content_offset = std::begin(record) + sizeof(detail::Header);
auto p = content_offset;
const auto variables_count = variables.pair_count();
for (std::size_t i = 0; i < variables_count; ++i) {
const auto name = variables.pair(i)->name();
char value{};
if (name == "FCGI_MAX_CONNS")
value = '1';
else if (name == "FCGI_MAX_REQS")
value = '1';
else if (name == "FCGI_MPXS_CONNS")
value = '0';
else
continue; // Ignoring other variables specified in the get-values record.
const auto name_size = name.size();
if (name_size > std::numeric_limits<unsigned char>::max())
end_request_protocol_violation();
// Note: name_size + 3 - is a space required to store: {char(name_size), char(1), name.data(), char(value)} string.
DMITIGR_ASSERT(name_size + 3 <= static_cast<std::size_t>(std::cend(record) - p));
*p++ = static_cast<unsigned char>(name_size); // name_size
*p++ = static_cast<unsigned char>(1); // 1
p = std::copy(cbegin(name), cend(name), p); // name.data()
*p++ = static_cast<unsigned char>(value); // value
}
using detail::Header;
const auto content_length = p - content_offset;
const auto padding_length = math::padding<std::streamsize>(content_length, 8);
const auto record_length = static_cast<int>(sizeof(Header)) + content_length + padding_length;
auto* const h = reinterpret_cast<Header*>(record.data());
*h = detail::Header{detail::Record_type::get_values_result,
Header::null_request_id, static_cast<std::size_t>(content_length), static_cast<std::size_t>(padding_length)};
const auto count = connection_->io_->write(reinterpret_cast<const char*>(record.data()), record_length);
DMITIGR_ASSERT(count == record_length);
} else {
const detail::Unknown_type_record r{header.record_type()};
const std::streamsize record_length = sizeof(r);
const auto count = connection_->io_->write(reinterpret_cast<const char*>(&r), record_length);
DMITIGR_ASSERT(count == record_length);
}
return Process_header_result::management_processed;
};
Process_header_result result{};
if (header.record_type() == detail::Record_type::begin_request) {
end_request(detail::Protocol_status::cant_mpx_conn);
result = Process_header_result::content_must_be_discarded;
} else if (header.is_management_record())
result = process_management_record();
else if (header.request_id() != connection_->request_id())
result = Process_header_result::content_must_be_discarded;
else if (header.record_type() == static_cast<detail::Record_type>(type_))
result = Process_header_result::content_must_be_consumed;
else
end_request_protocol_violation();
DMITIGR_ASSERT(is_invariant_ok());
return result;
}
/**
* @brief Resets the input stream to read the data of the specified type.
*
* @par Requires
* `is_reader()`.
*/
void reset_reader(const Type type)
{
DMITIGR_ASSERT(is_reader() && !is_closed());
type_ = type;
is_end_of_stream_ = false;
is_content_must_be_discarded_ = false;
unread_content_length_ = 0;
unread_padding_length_ = 0;
DMITIGR_ASSERT(is_invariant_ok());
}
#ifdef DMITIGR_FCGI_DEBUG
template<typename ... Types>
void print(Types&& ... msgs) const
{
if (type_ == Stream_type::out) {
((std::cerr << std::forward<Types>(msgs) << " "), ...);
std::cerr << std::endl;
}
}
#endif
};
} // namespace dmitigr::fcgi::detail
| 36.378671 | 128 | 0.637804 | dmitigr |
41a4315da01c7f6bd5f6cdda58c57442094e2b72 | 2,145 | cpp | C++ | src/problems/1_2/solution.cpp | philong6297/modern-cpp-challenges | c3f9786aff9dd097ee1e4ec7ac65560e447c28b5 | [
"MIT"
] | null | null | null | src/problems/1_2/solution.cpp | philong6297/modern-cpp-challenges | c3f9786aff9dd097ee1e4ec7ac65560e447c28b5 | [
"MIT"
] | null | null | null | src/problems/1_2/solution.cpp | philong6297/modern-cpp-challenges | c3f9786aff9dd097ee1e4ec7ac65560e447c28b5 | [
"MIT"
] | null | null | null | // Copyright 2021 Long Le Phi. All rights reserved.
// Use of this source code is governed by a MIT license that can be
// found in the LICENSE file.
#include "problems/1_2/solution.hpp"
#include <numeric>
#if defined(_MSC_VER)
# include <intrin.h>
#endif
namespace {
using longlp::solution::Problem_1_2;
inline auto CountTrailingZeros(const uintmax_t u) -> uintmax_t {
#if defined(_MSC_VER)
unsigned long trailing_zero = 0;
if (_BitScanForward64(&trailing_zero, u) != 0U) {
return trailing_zero;
}
// This is undefined, I better choose 64 than 0
return 64;
#elif defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
return __builtin_ctzll(u);
#endif
}
} // namespace
// static
auto Problem_1_2::StandardGCD(const uintmax_t u, const uintmax_t v)
-> uintmax_t {
return std::gcd(u, v);
}
// https://lemire.me/blog/2013/12/26/fastest-way-to-compute-the-greatest-common-divisor/
// static
auto Problem_1_2::BinaryGCD(uintmax_t u, uintmax_t v) -> uintmax_t {
// Base cases: gcd(n, 0) = gcd(0, n) = n
if (u == 0) {
return v;
}
if (v == 0) {
return u;
}
// Using identity 2: gcd(2u, 2v) = 2*gcd(u, v)
// Using identity 3: gcd(2u, v) = gcd(u, v), if v is odd (2 is not a common
// divisor). Similarly, gcd(u, 2v) = gcd(u, v) if u is odd.
// gcd(u * 2^i, v * 2^j) = gcd(u, v) * 2^k with u, v odd and k = min(i, j).
// 2^k is the greatest power of two that divides both u and v
// The number of trailing 0-bits in x, starting at the least significant bit
// position, represent for k.
uintmax_t k = CountTrailingZeros(u | v);
// Identity 3: gcd(u, v * 2^j) = gcd(u, v) (u is known to be odd)
u >>= CountTrailingZeros(u);
do {
// Identity 3: gcd(u, v * 2^j) = gcd(u, v) (u is known to be odd)
v >>= CountTrailingZeros(v);
// swap to make sure u <= v
if (u > v) {
std::swap(u, v);
}
// Using identity 4 (gcd(u, v) = gcd(|v-u|, min(u, v))
v = v - u;
} while (v != 0);
// Identity 1: gcd(u, 0) = u
// The shift by k is necessary to add back the 2^k factor that was removed b
// fore the loop
return u << k;
}
| 27.151899 | 88 | 0.620513 | philong6297 |
41a5b91ef8d11b5cf20424179e29f7199438b78c | 27,391 | cpp | C++ | src/prj/Lib/StdLib/IOAddOn.cpp | LucaBallan/ArticulatedPoseEstimator | 78fa0b1eafd12997cac9c3d42987a79d6535e3c0 | [
"MIT"
] | 8 | 2018-08-06T19:14:25.000Z | 2021-02-22T03:36:38.000Z | Lib/StdLib/IOAddOn.cpp | LucaBallan/GammaLib | dbcb91dd2e0d513160c4be533a73385a6efcafcf | [
"MIT"
] | 1 | 2019-12-02T22:23:02.000Z | 2019-12-02T22:23:02.000Z | src/prj/Lib/StdLib/IOAddOn.cpp | LucaBallan/ArticulatedPoseEstimator | 78fa0b1eafd12997cac9c3d42987a79d6535e3c0 | [
"MIT"
] | 5 | 2018-09-25T10:38:28.000Z | 2020-10-05T17:13:53.000Z | //
// GammaLib: Computer Vision library
//
// Copyright (C) 1998-2015 Luca Ballan <ballanlu@gmail.com> http://lucaballan.altervista.org/
//
// Third party copyrights are property of their respective owners.
//
//
// The MIT License(MIT)
//
// 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 "../stdInclude.h"
#include "../common.h"
#include <string.h>
#include "Stack.h"
#include "IOBuffer.h"
#include "ListEntities.h"
#include "List.h"
#include "MathAddOn.h"
#include "IOAddOn.h"
#ifdef SYSTEM_WINDOWS
#include <Commdlg.h>
#endif
#pragma warning(3:4244)
ConsoleProgressBarr::ConsoleProgressBarr() {
printf("[ ] 0%%");
RelativeDisplayPos=36;
WritedPercent=0;
WritedPosition=0;
RemainTText[0]=0;
}
ConsoleProgressBarr::~ConsoleProgressBarr() {
for(UINT i=0;i<RelativeDisplayPos-36;i++) printf("\x08");
printf(" Completed.");
UINT CurDispPos=36+8+13;
for(UINT i=CurDispPos;i<RelativeDisplayPos;i++) printf(" ");
}
void ConsoleProgressBarr::Aggiorna(UINT Pos,UINT Max) {
Speed.CheckPoint(Pos);
char Out[70];
UINT CurDispPos;
bool AggiornaPercent=false;
bool AggiornaPosition=false;
bool AggiornaRemainTime=false;
double x=Pos/(double)Max;
Speed.RemainTime(Out,Max);
if (strcmp(RemainTText,Out)) {
AggiornaRemainTime=true;
strcpy(RemainTText,Out);
}
if (WritedPercent != (unsigned int)Approx(100 * x)) {
AggiornaPercent=true;
WritedPercent=Approx(100*x);
}
if (WritedPosition != (unsigned int)Approx(30 * x)) { // TODO??
AggiornaPosition=true;
WritedPosition=Approx(30*x);
}
if (AggiornaPosition) {
for(UINT i=0;i<RelativeDisplayPos;i++) printf("\x08");
for(UINT i=0;i<WritedPosition;i++) printf("=");
for(UINT i=WritedPosition;i<30;i++) printf(" ");
printf("] ");
printf("%3u%%",WritedPercent);
printf(" %s left",RemainTText);
CurDispPos=36+8+(int)strlen(RemainTText);
if (CurDispPos>RelativeDisplayPos) RelativeDisplayPos=CurDispPos;
else for(UINT i=CurDispPos;i<RelativeDisplayPos;i++) printf(" ");
} else {
if (AggiornaPercent) {
for(UINT i=0;i<RelativeDisplayPos-32;i++) printf("\x08");
printf("%3u%%",WritedPercent);
printf(" %s left",RemainTText);
CurDispPos=36+8+(int)strlen(RemainTText);
if (CurDispPos>RelativeDisplayPos) RelativeDisplayPos=CurDispPos;
else for(UINT i=CurDispPos;i<RelativeDisplayPos;i++) printf(" ");
} else {
if (AggiornaRemainTime) {
for(UINT i=0;i<RelativeDisplayPos-36;i++) printf("\x08");
printf(" %s left",RemainTText);
CurDispPos=36+8+(int)strlen(RemainTText);
if (CurDispPos>RelativeDisplayPos) RelativeDisplayPos=CurDispPos;
else for(UINT i=CurDispPos;i<RelativeDisplayPos;i++) printf(" ");
}
}
}
}
void PrintTime(UINT seconds) {
char Out[50];
PrintTime(Out,seconds);
printf(Out);
}
char *PluralSingular(int num,char *singular,char *plural) {
if (num==1) return singular;
return plural;
}
void PrintTime(char *Out,UINT seconds) {
UINT minutes,hours,days,years;
minutes=seconds/60;
seconds%=60;
hours=minutes/60;
minutes%=60;
days=hours/24;
hours%=24;
years=days/365;
days%=365;
if (years!=0) {
sprintf(Out,"%u %s, %u %s",years,PluralSingular(years,"year","years"),days,PluralSingular(days,"day","days"));
} else {
if (days!=0) {
sprintf(Out,"%u %s, %u %s",days,PluralSingular(days,"day","days"),hours,PluralSingular(hours,"hour","hours"));
} else {
if (hours!=0) {
sprintf(Out,"%u %s, %u min",hours,PluralSingular(hours,"hour","hours"),minutes);
} else {
if (minutes!=0) sprintf(Out,"%u min, %u sec",minutes,seconds);
else {
sprintf(Out,"%u sec",seconds);
}
}
}
}
}
void Add_File_Extension(char *filename,char *ext) {
size_t pos=strcspn(filename,".");
if (pos==strlen(filename)) {
strcat(filename,".");
strcat(filename,ext);
}
}
char *Get_File_Extension(char *filename) {
char *Ext=strrchr(filename,'.');
if (Ext==NULL) return NULL;
Ext++;
return Ext;
}
char *Get_File_Path(const char *filename) {
const char *Ext=strrchr(filename,'\\');
if (Ext==NULL) return NULL;
char *Path=new char[Ext-filename+1];
memcpy(Path,filename,Ext-filename);
Path[Ext-filename]=0;
return Path;
}
char *Set_File_Path(char *Path,char *filename) {
if (Path==NULL) {
char *filename_ext=new char[strlen(filename)+1];
strcpy(filename_ext,filename);
return filename_ext;
}
char *filename_ext=new char[strlen(Path)+strlen(filename)+2];
strcpy(filename_ext,Path);
strcat(filename_ext,"\\");
strcat(filename_ext,filename);
return filename_ext;
}
bool CompareFileExtension(char *filename,char *ext) {
char *Ext=Get_File_Extension(filename);
if (Ext==NULL) return false;
if (!_stricmp(Ext,ext)) return true;
return false;
}
void CenteredCout(char *text,int scr_width) {
int len=(int)strlen(text);
if (scr_width>=len) {
int padd=(scr_width-len)/2;
for(int i=0;i<padd;i++) std::cout<<" ";
std::cout<<text;
for(int i=padd+len;i<scr_width;i++) std::cout<<" ";
} else std::cout<<text;
}
#ifdef USE_FIGLET
#include "D:\Developer\Luca\Common Libs\figlet\figlet.hpp"
void AsciiArtCout(char *text) {
Figlet::standard.print(text);
}
#else
void AsciiArtCout(char *text) {
cout << text;
}
#endif
#ifdef SYSTEM_WINDOWS
MouseEvent_struct::MouseEvent_struct() {
Event[0]=Event[1]=Event[2]=Event[3]=0;
ButtonState[0]=ButtonState[1]=ButtonState[2]=-1;
pos_x=pos_y=0.0;
pos_x_pxs=pos_y_pxs=0;
last_pos_x=last_pos_y=0.0;
drag_bottom=-1;
dropped=false;
delta_x=delta_y=0.0;
TrackEvent=false;
}
bool GetMouseState(HWND hWnd,UINT uMsg,WPARAM wParam,LPARAM lParam,MouseEvent_struct *MouseEvents_) {
bool mouse_event=false;
MouseEvent_struct MouseEvents=(*MouseEvents_);
MouseEvents.Event[0]=MouseEvents.Event[1]=MouseEvents.Event[2]=MouseEvents.Event[3]=0;
MouseEvents.pos_x=MouseEvents.pos_y=0.0;
MouseEvents.pos_x_pxs=MouseEvents.pos_y_pxs=0;
MouseEvents.start_dragging=false;
MouseEvents.dropped=false;
MouseEvents.delta_x=MouseEvents.delta_y=0.0;
MouseEvents.DBLClick[0]=MouseEvents.DBLClick[1]=MouseEvents.DBLClick[2]=0;
switch(uMsg) {
case WM_RBUTTONDOWN:
MouseEvents.Event[2]=1;
MouseEvents.ButtonState[2]=1;
mouse_event=true;
break;
case WM_LBUTTONDOWN:
MouseEvents.Event[0]=1;
MouseEvents.ButtonState[0]=1;
mouse_event=true;
break;
case WM_MBUTTONDOWN:
MouseEvents.Event[1]=1;
MouseEvents.ButtonState[1]=1;
mouse_event=true;
break;
case WM_RBUTTONUP:
MouseEvents.Event[2]=-1;
MouseEvents.ButtonState[2]=-1;
mouse_event=true;
break;
case WM_LBUTTONUP:
MouseEvents.Event[0]=-1;
MouseEvents.ButtonState[0]=-1;
mouse_event=true;
break;
case WM_MBUTTONUP:
MouseEvents.Event[1]=-1;
MouseEvents.ButtonState[1]=-1;
mouse_event=true;
break;
case WM_MOUSELEAVE:
MouseEvents.Event[3]=1;
mouse_event=true;
MouseEvents.TrackEvent=false;
break;
case WM_MOUSEMOVE:
if (!MouseEvents.TrackEvent) {
MouseEvents.TrackEvent=true;
TRACKMOUSEEVENT tm;
tm.cbSize=sizeof(TRACKMOUSEEVENT);
tm.dwFlags=TME_LEAVE;
tm.hwndTrack=hWnd;
tm.dwHoverTime=0;
TrackMouseEvent(&tm);
}
MouseEvents.Event[3]=1;
mouse_event=true;
break;
case WM_LBUTTONDBLCLK:
MouseEvents.DBLClick[0]=1;
mouse_event=true;
break;
case WM_MBUTTONDBLCLK:
MouseEvents.DBLClick[1]=1;
mouse_event=true;
break;
case WM_RBUTTONDBLCLK:
MouseEvents.DBLClick[2]=1;
mouse_event=true;
break;
}
if (mouse_event) {
int mx=LOWORD(lParam);
int my=HIWORD(lParam);
if (mx & 1 << 15) mx -= (1 << 16);
if (my & 1 << 15) my -= (1 << 16);
RECT Rect;int w,h;
GetClientRect(hWnd,&Rect);
w=Rect.right-Rect.left;
h=Rect.bottom-Rect.top;
MouseEvents.pos_x=(mx-(w/2.0))/(w/2.0);
MouseEvents.pos_y=(-my+(h/2.0))/(h/2.0);
MouseEvents.pos_x_pxs=mx;
MouseEvents.pos_y_pxs=my;
if (MouseEvents.drag_bottom==-1) {
if (MouseEvents.Event[1]==1) MouseEvents.drag_bottom=1;
if (MouseEvents.Event[2]==1) MouseEvents.drag_bottom=2;
if (MouseEvents.Event[0]==1) MouseEvents.drag_bottom=0;
if (MouseEvents.drag_bottom!=-1) {
MouseEvents.last_pos_x=MouseEvents.pos_x;
MouseEvents.last_pos_y=MouseEvents.pos_y;
MouseEvents.start_dragging=true;
SetCapture(hWnd);
}
} else {
MouseEvents.delta_x=MouseEvents.pos_x-MouseEvents.last_pos_x;
MouseEvents.delta_y=MouseEvents.pos_y-MouseEvents.last_pos_y;
if (MouseEvents.Event[MouseEvents.drag_bottom]==-1) {
MouseEvents.dropped=true;
MouseEvents.drag_bottom=-1;
ReleaseCapture();
}
}
(*MouseEvents_)=MouseEvents;
}
return mouse_event;
}
bool Get_File_Dialog(HWND hWnd,char *filename,int bufflen,char *filter,int action) {
OPENFILENAME ofn;
ZeroMemory(filename, bufflen);
ofn.lStructSize = sizeof(OPENFILENAME);
ofn.hInstance = GetModuleHandle(NULL);
ofn.hwndOwner = hWnd;
ofn.lpstrFile = filename;
ofn.nMaxFile = bufflen;
ofn.lpstrFilter = filter;
ofn.lpstrCustomFilter = NULL;
ofn.nMaxCustFilter=0;
ofn.nFilterIndex = 1;
ofn.nFileOffset = 0;
ofn.lpstrDefExt = NULL;
ofn.lpfnHook = NULL;
ofn.lCustData = 0;
ofn.lpTemplateName = NULL;
ofn.lpstrFileTitle = NULL;
ofn.nMaxFileTitle = 0;
ofn.lpstrInitialDir = NULL;
ofn.Flags = OFN_EXPLORER | OFN_LONGNAMES | OFN_HIDEREADONLY | OFN_PATHMUSTEXIST | OFN_NOCHANGEDIR;
if (action==GFD_OPEN) {
ofn.lpstrTitle="Open...";
ofn.Flags=ofn.Flags|OFN_FILEMUSTEXIST;
if (GetOpenFileName(&ofn)) return true;
} else {
ofn.Flags=ofn.Flags|OFN_OVERWRITEPROMPT;
ofn.lpstrTitle="Save...";
if (GetSaveFileName(&ofn)) return true;
}
return false;
}
void PopUp(HWND hWnd,LPCTSTR Title,LPCTSTR fmt,...) {
char text[400];
va_list ap;
if (fmt == NULL) return;
va_start(ap,fmt); // Parses The String For Variables
vsprintf(text,fmt,ap); // And Converts Symbols To Actual Numbers
va_end(ap); // Results Are Stored In Text
MessageBox(hWnd,text,Title,MB_OK);
}
#endif
int Write_Over_last_index=-1;
void Write_Over(const char *fmt, ...) {
char text[256];
va_list ap;
if (fmt == NULL) return;
va_start(ap,fmt);
vsprintf(text,fmt,ap);
va_end(ap);
if (Write_Over_last_index!=-1) {
for(int i=0;i<Write_Over_last_index;i++) printf("\x08 \x08");
}
Write_Over_last_index=(int)strlen(text);
printf("%s",text);
}
void Reset_Write_Over() {
Write_Over_last_index=-1;
}
CommandParser::CommandParser(int argc,char* argv[]) {
num_elements=argc-1;
elements=argv+1;
used_ID[0]=0;
invalid_option_parameters=false;
}
CommandParser::~CommandParser() {
}
int CommandParser::GetOptionIndex(char ID) {
int index=0;
char ID_[2];ID_[0]=ID;ID_[1]=0;_strlwr(ID_);
if (strcspn(used_ID,ID_)==strlen(used_ID)) strcat(used_ID,ID_);
while (index<num_elements) {
if (elements[index][0]=='-') {
_strlwr(elements[index]);
if (elements[index][1]==ID_[0]) break;
}
index++;
}
return index;
}
int CommandParser::GetNumOptionParameters(int option_index) {
int i=1;
while(true) {
if (option_index+i>=num_elements) break;
if (elements[option_index+i][0]=='-') break;
i++;
}
i--;
return i;
}
bool CommandParser::GetParameter(char ID,int param_index,char **&Out) {
int index=GetOptionIndex(ID);
if (index==num_elements) return false;
if (param_index==0) {Out=NULL;return true;}
for(int i=1;i<=param_index;i++) {
if (index+i>=num_elements) return false;
if (elements[index+i][0]=='-') return false;
}
Out=elements+index+param_index;
return true;
}
bool CommandParser::GetParameter(char ID,char *type,...) {
char **Out;
int num=(int)strlen(type);
if (!GetParameter(ID,num,Out)) return false;
if (!GetParameter(ID,1,Out)) return false;
va_list marker;
va_start(marker,type);
for(int i=0;i<num;i++) {
if (Out[i][0]=='-') return false;
if (type[i]=='s') strcpy(va_arg(marker,char*),Out[i]);
if (type[i]=='i') *va_arg(marker,int*)=atoi(Out[i]);
if (type[i]=='c') *(va_arg(marker,char*))=Out[i][0];
if (type[i]=='f') *(va_arg(marker,float*))=(float)atof(Out[i]);
if (type[i]=='d') *(va_arg(marker,double*))=atof(Out[i]);
}
va_end(marker);
return true;
}
bool CommandParser::GetFlag(char ID) {
char **Out;
bool exists=GetParameter(ID,0,Out);
if (exists) {
if (GetNumOptionParameters(GetOptionIndex(ID))!=0) {
printf("Invalid number of parameters for option -%c.\n",ID);
invalid_option_parameters=true;
}
}
return exists;
}
bool CommandParser::GetParameterE(char ID,char *type,...) {
char **Out;
int opt_index=GetOptionIndex(ID);
if (opt_index==num_elements) return false;
int n_param=GetNumOptionParameters(opt_index);
int j=0;
int lenght=(int)strlen(type);
int num=-1;
char *typeB=new char[strlen(type)+2];
typeB[0]=0;
for(int i=0;i<lenght;i++) {
if (type[i]=='[') {
if (j<=n_param) num=j;
else break;
continue;
}
if (type[i]==']') {
if (j<=n_param) num=j;
else break;
continue;
}
typeB[j++]=type[i];
typeB[j]=0;
}
if (j<=n_param) num=j;
if (n_param!=num) {
printf("Invalid number of parameters for option -%c.\n",ID);
invalid_option_parameters=true;
delete[]typeB;
return false;
}
typeB[num]=0;
if (!GetParameter(ID,1,Out)) {delete[]typeB;return false;}
va_list marker;
va_start(marker,type);
for(int i=0;i<num;i++) {
if (Out[i][0]=='-') {delete[]typeB;return false;}
if (typeB[i]=='s') strcpy(va_arg(marker,char*),Out[i]);
if (typeB[i]=='i') *va_arg(marker,int*)=atoi(Out[i]);
if (typeB[i]=='c') *(va_arg(marker,char*))=Out[i][0];
if (typeB[i]=='f') *(va_arg(marker,float*))=(float)atof(Out[i]);
if (typeB[i]=='d') *(va_arg(marker,double*))=atof(Out[i]);
}
va_end(marker);
delete[]typeB;
return true;
}
bool CommandParser::CheckInvalid() {
int index=0;
if (invalid_option_parameters) return false;
while (index<num_elements) {
if (elements[index][0]=='-') {
char ID_[2];ID_[0]=elements[index][1];ID_[1]=0;_strlwr(ID_);
if (strcspn(used_ID,ID_)==strlen(used_ID)) {
printf("Invalid option -%s.\n",ID_);
return false;
}
}
index++;
}
return true;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////// VERSIONE ESTESA ///////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
//////// TODO: TESTARE!! ///////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
/*
CommandParser::CommandParser(int argc,char* argv[]) {
num_elements=argc-1;
elements=argv+1;
used_ID[0]=0;
}
CommandParser::~CommandParser() {
}
bool CommandParser::GetParameter(char *ID,int param_index,char **&Out,int ricorrenza=1) {
int index=0;
char *ID_=strcln(ID);strlwr(ID_);
char *ID_S=strcln(ID_);strcat(ID_S,";");
if (strcspn(used_ID,ID_S)==strlen(used_ID)) strcat(used_ID,ID_S);
delete []ID_S;
int ricorrenza_corrente=0;
while (index<num_elements) {
if (elements[index][0]=='-') {
strlwr(elements[index]);
if (!strcmp((elements[index])+1,ID_)) {
ricorrenza_corrente++;
if (ricorrenza_corrente==ricorrenza) break;
}
}
index++;
}
delete []ID_;
if (index==num_elements) return false;
if (param_index==0) {Out=NULL;return true;}
for(int i=1;i<=param_index;i++) {
if (index+i>=num_elements) return false;
if (elements[index+i][0]=='-') return false;
}
Out=elements+index+param_index;
return true;
}
bool CommandParser::GetFlag(char *ID) {
char **Out;
return GetParameter(ID,0,Out);
}
// Note:
// Si puo' aggiungere un nome di parametro piu' lungo della singola lettera
// Si puo' aggiungere ricorrenza
// CheckInvalid giusto?
bool CommandParser::GetParameter(char *ID,char *type,...) {
char **Out;
int num=(int)strlen(type);
if (!GetParameter(ID,num,Out)) return false;
if (!GetParameter(ID,1,Out)) return false;
va_list marker;
va_start(marker,type);
for(int i=0;i<num;i++) {
if (Out[i][0]=='-') return false;
if (type[i]=='s') strcpy(va_arg(marker,char*),Out[i]);
if (type[i]=='i') *va_arg(marker,int*)=atoi(Out[i]);
if (type[i]=='c') *(va_arg(marker,char*))=Out[i][0];
if (type[i]=='f') *(va_arg(marker,float*))=(float)atof(Out[i]);
if (type[i]=='d') *(va_arg(marker,double*))=atof(Out[i]);
}
va_end(marker);
return true;
}
bool CommandParser::GetParameterE(char *ID,char *type,...) {
char **Out;
int j=0;
int lenght=(int)strlen(type);
int num=-1;
char *typeB=new char[strlen(type)+2];
typeB[0]=0;
for(int i=0;i<lenght;i++) {
if (type[i]=='[') {
if (GetParameter(ID,j,Out)) num=j;
else break;
continue;
}
if (type[i]==']') {
if (GetParameter(ID,j,Out)) num=j;
else break;
continue;
}
typeB[j++]=type[i];
typeB[j]=0;
}
if (GetParameter(ID,j,Out)) num=j;
if (num==-1) {delete typeB;return false;}
typeB[num]=0;
if (!GetParameter(ID,1,Out)) {delete typeB;return false;}
va_list marker;
va_start(marker,type);
for(int i=0;i<num;i++) {
if (Out[i][0]=='-') {delete typeB;return false;}
if (typeB[i]=='s') strcpy(va_arg(marker,char*),Out[i]);
if (typeB[i]=='i') *va_arg(marker,int*)=atoi(Out[i]);
if (typeB[i]=='c') *(va_arg(marker,char*))=Out[i][0];
if (typeB[i]=='f') *(va_arg(marker,float*))=(float)atof(Out[i]);
if (typeB[i]=='d') *(va_arg(marker,double*))=atof(Out[i]);
}
va_end(marker);
delete typeB;
return true;
}
bool CommandParser::GetParameter(char *ID,int recurrence,char *type,...) {
char **Out;
int num=(int)strlen(type);
if (!GetParameter(ID,num,Out,recurrence)) return false;
if (!GetParameter(ID,1,Out,recurrence)) return false;
va_list marker;
va_start(marker,type);
for(int i=0;i<num;i++) {
if (Out[i][0]=='-') return false;
if (type[i]=='s') strcpy(va_arg(marker,char*),Out[i]);
if (type[i]=='i') *va_arg(marker,int*)=atoi(Out[i]);
if (type[i]=='c') *(va_arg(marker,char*))=Out[i][0];
if (type[i]=='f') *(va_arg(marker,float*))=(float)atof(Out[i]);
if (type[i]=='d') *(va_arg(marker,double*))=atof(Out[i]);
}
va_end(marker);
return true;
}
bool CommandParser::GetParameterE(char *ID,int recurrence,char *type,...) {
char **Out;
int j=0;
int lenght=(int)strlen(type);
int num=-1;
char *typeB=new char[strlen(type)+2];
typeB[0]=0;
for(int i=0;i<lenght;i++) {
if (type[i]=='[') {
if (GetParameter(ID,j,Out,recurrence)) num=j;
else break;
continue;
}
if (type[i]==']') {
if (GetParameter(ID,j,Out,recurrence)) num=j;
else break;
continue;
}
typeB[j++]=type[i];
typeB[j]=0;
}
if (GetParameter(ID,j,Out,recurrence)) num=j;
if (num==-1) {delete typeB;return false;}
typeB[num]=0;
if (!GetParameter(ID,1,Out,recurrence)) {delete typeB;return false;}
va_list marker;
va_start(marker,type);
for(int i=0;i<num;i++) {
if (Out[i][0]=='-') {delete typeB;return false;}
if (typeB[i]=='s') strcpy(va_arg(marker,char*),Out[i]);
if (typeB[i]=='i') *va_arg(marker,int*)=atoi(Out[i]);
if (typeB[i]=='c') *(va_arg(marker,char*))=Out[i][0];
if (typeB[i]=='f') *(va_arg(marker,float*))=(float)atof(Out[i]);
if (typeB[i]=='d') *(va_arg(marker,double*))=atof(Out[i]);
}
va_end(marker);
delete typeB;
return true;
}
bool CommandParser::CheckInvalid() {
int index=0;
while (index<num_elements) {
if (elements[index][0]=='-') {
char *ID_S=strcln((elements[index])+1);strcat(ID_S,";");strlwr(ID_S);
if (strcspn(used_ID,ID_S)==strlen(used_ID)) {
printf("Invalid -%s option.\n",(elements[index])+1);
delete []ID_S;
return false;
}
delete []ID_S;
}
index++;
}
return true;
}
*/
////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Text
//
char *OrdinalsPostFix[]={"st","nd","rd","th"};
char *OrdinalNumbersPostfix(int num) {
switch(num) {
case 1:
return OrdinalsPostFix[0];
case 2:
return OrdinalsPostFix[1];
case 3:
return OrdinalsPostFix[2];
default:
return OrdinalsPostFix[3];
}
}
//
// String Functions
//
char *strcln(const char *str) {
if (str==NULL) return NULL;
char *x=new char[strlen(str)+1];
strcpy(x,str);
return x;
}
void str_replace(char **str,const char *new_text) {
SDELETEA((*str));
(*str)=strcln(new_text);
}
wchar_t *CharToWChar(char *str) {
DWORD dwNum=MultiByteToWideChar(CP_ACP,0,str,-1,NULL,0);
wchar_t *n=new wchar_t[dwNum];
MultiByteToWideChar(CP_ACP,0,str,-1,n,dwNum);
return n;
}
bool str_begin(const char *str,const char *begin) {
// Ritorna true se str comincia con begin
int size_begin=(int)strlen(begin);
int size_str=(int)strlen(str);
if (size_str<size_begin) return false;
for(int i=0;i<size_begin;i++)
if (str[i]!=begin[i]) return false;
return true;
}
//
// Buffer Functions
//
BYTE *bsprintf(char *format,...) {
char *p;
size_t size,len;
va_list marker;
BYTE *buffer,*buffer_p;
len=strlen(format);
size=0;
p=format;
for(size_t i=0;i<len;i++) {
if (*p=='c') size+=sizeof(char);
if (*p=='i') size+=sizeof(int);
if (*p=='d') size+=sizeof(double);
if (*p=='p') size+=sizeof(void*);
p++;
}
buffer_p=buffer=new BYTE[size];
p=format;
va_start(marker,format);
for(size_t i=0;i<len;i++) {
if (*p=='c') {
*((char *)buffer_p)=va_arg(marker,char);
buffer_p+=sizeof(char);
}
if (*p=='i') {
*((int *)buffer_p)=va_arg(marker,int);
buffer_p+=sizeof(int);
}
if (*p=='d') {
*((double *)buffer_p)=va_arg(marker,double);
buffer_p+=sizeof(double);
}
if (*p=='p') {
*((void **)buffer_p)=va_arg(marker,void *);
buffer_p+=sizeof(void *);
}
p++;
}
va_end(marker);
return buffer;
}
void bscanf(BYTE *buffer,char *format,...) {
char *p;
size_t len=strlen(format);
BYTE *buffer_p;
buffer_p=buffer;
p=format;
va_list marker;
va_start(marker,format);
for(size_t i=0;i<len;i++) {
if (*p=='c') {
*(va_arg(marker,char *))=*((char *)buffer_p);
buffer_p+=sizeof(char);
}
if (*p=='i') {
*(va_arg(marker,int *))=*((int *)buffer_p);
buffer_p+=sizeof(int);
}
if (*p=='d') {
*(va_arg(marker,double *))=*((double *)buffer_p);
buffer_p+=sizeof(double);
}
if (*p=='p') {
*(va_arg(marker,void **))=*((void **)buffer_p);
buffer_p+=sizeof(void *);
}
p++;
}
va_end(marker);
}
void bscanf_pointers(BYTE *buffer,char *format,...) {
char *p;
size_t len=strlen(format);
BYTE *buffer_p;
buffer_p=buffer;
p=format;
va_list marker;
va_start(marker,format);
for(size_t i=0;i<len;i++) {
if (*p=='c') {
*(va_arg(marker,char **))=((char *)buffer_p);
buffer_p+=sizeof(char);
}
if (*p=='i') {
*(va_arg(marker,int **))=((int *)buffer_p);
buffer_p+=sizeof(int);
}
if (*p=='d') {
*(va_arg(marker,double **))=((double *)buffer_p);
buffer_p+=sizeof(double);
}
if (*p=='p') {
*(va_arg(marker,void ***))=((void **)buffer_p);
buffer_p+=sizeof(void *);
}
p++;
}
va_end(marker);
}
// ---------------------------------------------------------------------
// ---------------------------------------------------------------------
// ------------------- Console -----------------------------------------
// ---------------------------------------------------------------------
// ---------------------------------------------------------------------
void WindowsErrorExit() {
LPVOID lpMsgBuf;
LPVOID lpDisplayBuf;
DWORD dw = GetLastError();
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM,
NULL,
dw,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR) &lpMsgBuf,
0, NULL );
lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT,
(lstrlen((LPCTSTR)lpMsgBuf)+40)*sizeof(TCHAR));
wsprintf((LPTSTR)lpDisplayBuf,
TEXT("Error %d: %s\n"),
dw, lpMsgBuf);
MessageBox(NULL, (LPCTSTR)lpDisplayBuf, TEXT("Error"), MB_OK);
LocalFree(lpMsgBuf);
LocalFree(lpDisplayBuf);
ExitProcess(dw);
}
PCHAR* GetArgvArgc(int* _argc) {
PCHAR CmdLine=GetCommandLine();
PCHAR* argv;
PCHAR _argv;
ULONG len;
ULONG argc;
CHAR a;
ULONG i, j;
BOOLEAN in_QM;
BOOLEAN in_TEXT;
BOOLEAN in_SPACE;
len = (ULONG)strlen(CmdLine);
i = ((len+2)/2)*sizeof(PVOID) + sizeof(PVOID);
argv = (PCHAR*)GlobalAlloc(GMEM_FIXED,
i + (len+2)*sizeof(CHAR));
_argv = (PCHAR)(((PUCHAR)argv)+i);
argc = 0;
argv[argc] = _argv;
in_QM = FALSE;
in_TEXT = FALSE;
in_SPACE = TRUE;
i = 0;
j = 0;
while( a = CmdLine[i] ) {
if(in_QM) {
if(a == '\"') {
in_QM = FALSE;
} else {
_argv[j] = a;
j++;
}
} else {
switch(a) {
case '\"':
in_QM = TRUE;
in_TEXT = TRUE;
if(in_SPACE) {
argv[argc] = _argv+j;
argc++;
}
in_SPACE = FALSE;
break;
case ' ':
case '\t':
case '\n':
case '\r':
if(in_TEXT) {
_argv[j] = '\0';
j++;
}
in_TEXT = FALSE;
in_SPACE = TRUE;
break;
default:
in_TEXT = TRUE;
if(in_SPACE) {
argv[argc] = _argv+j;
argc++;
}
_argv[j] = a;
j++;
in_SPACE = FALSE;
break;
}
}
i++;
}
_argv[j] = '\0';
argv[argc] = NULL;
(*_argc) = argc;
return argv;
}
#include <io.h>
#include <stdio.h>
#include <fstream>
void getConsole() {
int fd;
FILE *fp;
HANDLE hCon;
AllocConsole();
// Make printf happy
hCon = GetStdHandle(STD_OUTPUT_HANDLE);
fd = _open_osfhandle((intptr_t)(hCon), 0);
fp = _fdopen(fd, "w");
*stdout = *fp;
setvbuf(stdout, NULL, _IONBF, 0);
}
void closeConsole() {
FreeConsole();
}
| 23.351236 | 113 | 0.608631 | LucaBallan |
41a5dc84a8361385f2eaea2907a30a4ea42f78a7 | 1,512 | cpp | C++ | cxx/pass.cpp | snewell/advent2020 | d7800b549401624ee75b271a37238162590b9068 | [
"X11"
] | null | null | null | cxx/pass.cpp | snewell/advent2020 | d7800b549401624ee75b271a37238162590b9068 | [
"X11"
] | null | null | null | cxx/pass.cpp | snewell/advent2020 | d7800b549401624ee75b271a37238162590b9068 | [
"X11"
] | null | null | null | #include <aoc/pass.hpp>
#include <algorithm>
#include <cassert>
#include <string_view>
namespace
{
}
namespace aoc2020
{
Seat parse_pass(std::string const & seat)
{
assert(seat.length() == 10);
auto calculate_assignment = [](std::string_view info, int low, int high,
char left, char right) {
auto calculate_midpoint = [](int low, int high) {
auto const distance = high - low + 1;
return low + (distance / 2);
};
std::for_each(
std::begin(info), std::end(info),
[&low, &high, calculate_midpoint, left, right](auto ch) {
auto const new_boundary = calculate_midpoint(low, high);
if(ch == left)
{
high = new_boundary;
}
else
{
assert(ch == right);
low = new_boundary;
}
});
return low;
};
return Seat{calculate_assignment(std::string_view(seat.data(), 7), 0,
127, 'F', 'B'),
calculate_assignment(std::string_view(seat.data() + 7, 3),
0, 8, 'L', 'R')};
}
int calculate_id(Seat const & seat) noexcept
{
return (seat.row * 8) + seat.column;
}
} // namespace aoc2020
| 28.528302 | 80 | 0.434524 | snewell |
41abf7445ba33280cd602b780962edb4a4ecfd22 | 683 | cpp | C++ | DeathMask/tests/src/TestsPerformer.cpp | demensdeum/Death-Mask | 6251bd5b3540adc494f2d8ea387e35479aa7b238 | [
"MIT"
] | null | null | null | DeathMask/tests/src/TestsPerformer.cpp | demensdeum/Death-Mask | 6251bd5b3540adc494f2d8ea387e35479aa7b238 | [
"MIT"
] | 11 | 2017-08-12T17:04:34.000Z | 2017-10-15T08:27:58.000Z | DeathMask/tests/src/TestsPerformer.cpp | demensdeum/Death-Mask | 6251bd5b3540adc494f2d8ea387e35479aa7b238 | [
"MIT"
] | null | null | null | #include "TestsPerformer.h"
#include "ObjectsGeneratorTest.h"
#include "MapGeneratorTest.h"
#include <memory>
#include <iostream>
using namespace std;
using namespace DeathMaskGame::Tests;
void TestsPerformer::perform() {
cout << "Tests started" << endl;
{
auto objectsGeneratorTest = make_shared<ObjectsGeneratorTest>();
auto result = objectsGeneratorTest->perform();
if (!result)
{
throw logic_error("Objects Generator Test failed");
}
}
{
auto mapGeneratorTest = make_shared<MapGeneratorTest>();
auto result = mapGeneratorTest->perform();
if (!result)
{
throw logic_error("Map Generator Test failed");
}
}
cout << "Tests ended" << endl;
}; | 18.972222 | 66 | 0.70571 | demensdeum |
41ac0434e2cf353fae6f2dba2ac4c34391ce4309 | 5,493 | cpp | C++ | prototype/entity.cpp | llGuy/graphics | 7e77bb04715b68465e2718077102f894371e56fc | [
"MIT"
] | null | null | null | prototype/entity.cpp | llGuy/graphics | 7e77bb04715b68465e2718077102f894371e56fc | [
"MIT"
] | null | null | null | prototype/entity.cpp | llGuy/graphics | 7e77bb04715b68465e2718077102f894371e56fc | [
"MIT"
] | null | null | null | #include "entity.h"
#include "render.h"
#include "global.h"
#include <GLFW/glfw3.h>
#include <glm/gtx/transform.hpp>
entity_data_base EntityDataBase = {};
internal void
UpdateModelMatrixComponents(std::vector<model_matrix_component> &Components
, std::vector<entity_data> &Entities)
{
model_matrix_component *End = &( Components.back() ) + 1;
for (model_matrix_component *Component = &( Components[0] )
; Component != End
; ++Component)
{
entity_data *Entity = &( Entities[Component->EntityID] );
glm::mat4 TranslateMatrix = glm::translate(Entity->Position3D);
glm::mat4 ScaleMatrix = glm::scale(Entity->Scale3D);
Component->TRS = TranslateMatrix * ScaleMatrix;
}
}
internal void
UpdateRenderComponents(std::vector<render_component> &Components
, std::vector<model_matrix_component> &ModelMatrices
, std::vector<entity_data> &Entities)
{
render_component *End = &( Components.back() ) + 1;
for (render_component *Component = &( Components[0] )
; Component != End
; ++Component)
{
entity_data *Entity = &Entities[Component->EntityID];
int32 ModelMatrixIndex = Entity->Components.ModelMatrixComponentIndex;
if (ModelMatrixIndex != MISSING_COMPONENT)
{
model_instance Instance{ Component->Model, ModelMatrices[ModelMatrixIndex].TRS };
Component->Layer->Instances.push_back(Instance);
}
}
}
internal void
UpdateKeyboardComponents(std::vector<keyboard_component> &Components
, std::vector<entity_data> &Entities)
{
local_persist auto GetLateral = [](const glm::vec3 &Vector) -> glm::vec3
{ return glm::normalize(glm::vec3(Vector.x, 0.0f, Vector.z)); };
keyboard_component *End = &( Components.back() ) + 1;
for (keyboard_component *Component = &( Components[0] )
; Component != End
; ++Component)
{
entity_data *Entity = &Entities[Component->EntityID];
if (Entity->Components.KeyboardComponentIndex != MISSING_COMPONENT)
{
glm::vec3 LateralDirection3D = GetLateral(Entity->Direction3D);
if (glm::all(glm::lessThan(Entity->Velocity3D
, glm::vec3(100000000.0f))))
{
if (WindowData.KeyMap[GLFW_KEY_W])
Entity->Velocity3D += LateralDirection3D;
if (WindowData.KeyMap[GLFW_KEY_A]) Entity->Velocity3D -= glm::cross(LateralDirection3D, glm::vec3(0.0f, 1.0f, 0.0f));
if (WindowData.KeyMap[GLFW_KEY_S]) Entity->Velocity3D -= LateralDirection3D;
if (WindowData.KeyMap[GLFW_KEY_D]) Entity->Velocity3D += glm::cross(LateralDirection3D, glm::vec3(0.0f, 1.0f, 0.0f));
if (WindowData.KeyMap[GLFW_KEY_SPACE]) Entity->Velocity3D += glm::vec3(0.0f, 1.0f, 0.0f);
if (WindowData.KeyMap[GLFW_KEY_LEFT_SHIFT]) Entity->Velocity3D += glm::vec3(0.0f, -1.0f, 0.0f);
}
}
}
}
// TODO Parameterize mouse sensitivity
#define MOUSE_SENSITIVITY 0.02f
internal void
UpdateMouseComponents(std::vector<mouse_component> &Components
, std::vector<entity_data> &Entities)
{
local_persist auto RotateDirection = [](const glm::vec2 &CursorDifference
, const glm::vec3 &Direction
, window_data &WindowData) -> glm::vec3
{
glm::vec3 NewDirection = Direction;
float XAngle = glm::radians(-CursorDifference.x) * MOUSE_SENSITIVITY;
float YAngle = glm::radians(-CursorDifference.y) * MOUSE_SENSITIVITY;
NewDirection = glm::mat3(glm::rotate(XAngle, glm::vec3(0.0f, 1.0f, 0.0f))) * NewDirection;
glm::vec3 YRotateAxis = glm::cross(NewDirection, glm::vec3(0.0f, 1.0f, 0.0f));
NewDirection = glm::mat3(glm::rotate(YAngle, YRotateAxis)) * NewDirection;
return NewDirection;
};
mouse_component *End = &( Components.back() ) + 1;
for (mouse_component *Component = &( Components[0] )
; Component != End
; ++Component)
{
entity_data *Entity = &Entities[Component->EntityID];
if (WindowData.MouseMoved)
{
glm::vec2 Difference = WindowData.CurrentMousePosition - Component->PreviousMousePosition;
Component->PreviousMousePosition = WindowData.CurrentMousePosition;
Entity->Direction3D = normalize(RotateDirection(Difference
, Entity->Direction3D
, WindowData));
}
}
}
#define SPEED 5.0f
internal void
UpdatePhysicsComponents(std::vector<physics_component> &Components
, std::vector<entity_data> &Entities)
{
physics_component *End = &( Components.back() ) + 1;
for (physics_component *Component = &( Components[0] )
; Component != End
; ++Component)
{
entity_data *Entity = &Entities[Component->EntityID];
Entity->Position3D += Entity->Velocity3D * TimeData.Elapsed() * SPEED;
Entity->Velocity3D = glm::vec3(0.0f);
}
}
uint32
entity_data_base::CreateEntity(const string_view &Name)
{
uint32 ID = Entities.size();
IndexMap[Name] = ID;
Entities.push_back(entity_data {});
return ID;
}
entity_data *
entity_data_base::GetEntity(uint32 ID)
{
return &Entities[ID];
}
void
entity_data_base::Update(void)
{
UpdateModelMatrixComponents(ModelMatrixComponents.List
, Entities);
UpdateRenderComponents(RenderComponents.List
, ModelMatrixComponents.List
, Entities);
UpdateKeyboardComponents(KeyboardComponents.List
, Entities);
UpdateMouseComponents(MouseComponents.List,
Entities);
UpdatePhysicsComponents(PhysicsComponents.List
, Entities);
}
| 31.033898 | 120 | 0.673585 | llGuy |
41ad84f0db91c4d83da32663187049ae422ab567 | 30,868 | cpp | C++ | Engine/source/terrain/terrCellMaterial.cpp | GoldenThumbs/Torque3D | 312d55be479c212f10239828fd2486fc03827d5e | [
"MIT"
] | 9 | 2015-01-07T17:24:28.000Z | 2021-08-15T17:49:08.000Z | Engine/source/terrain/terrCellMaterial.cpp | GoldenThumbs/Torque3D | 312d55be479c212f10239828fd2486fc03827d5e | [
"MIT"
] | 3 | 2015-09-24T05:10:05.000Z | 2016-07-06T15:07:54.000Z | Engine/source/terrain/terrCellMaterial.cpp | GoldenThumbs/Torque3D | 312d55be479c212f10239828fd2486fc03827d5e | [
"MIT"
] | 5 | 2015-02-14T21:00:28.000Z | 2021-07-10T01:05:09.000Z | //-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// 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 "platform/platform.h"
#include "terrain/terrCellMaterial.h"
#include "core/util/safeRelease.h"
#include "terrain/terrData.h"
#include "terrain/terrCell.h"
#include "materials/materialFeatureTypes.h"
#include "materials/materialManager.h"
#include "terrain/terrFeatureTypes.h"
#include "terrain/terrMaterial.h"
#include "renderInstance/renderDeferredMgr.h"
#include "shaderGen/shaderGen.h"
#include "shaderGen/featureMgr.h"
#include "scene/sceneRenderState.h"
#include "materials/sceneData.h"
#include "gfx/util/screenspace.h"
#include "lighting/advanced/advancedLightBinManager.h"
S32 sgMaxTerrainMaterialsPerPass = 32;
AFTER_MODULE_INIT( MaterialManager )
{
Con::NotifyDelegate callabck( &TerrainCellMaterial::_updateDefaultAnisotropy );
Con::addVariableNotify( "$pref::Video::defaultAnisotropy", callabck );
}
Vector<TerrainCellMaterial*> TerrainCellMaterial::smAllMaterials;
Vector<String> _initSamplerNames()
{
Vector<String> samplerNames;
samplerNames.push_back("$baseTexMap");
samplerNames.push_back("$layerTex");
samplerNames.push_back("$lightMapTex");
samplerNames.push_back("$lightInfoBuffer");
samplerNames.push_back("$normalMapSampler");
samplerNames.push_back("$detailMapSampler");
samplerNames.push_back("$macroMapSampler");
samplerNames.push_back("$ormMapSampler");
return samplerNames;
}
const Vector<String> TerrainCellMaterial::mSamplerNames = _initSamplerNames();
TerrainCellMaterial::TerrainCellMaterial()
: mTerrain( NULL ),
mDeferredMat( NULL ),
mReflectMat( NULL ),
mShader( NULL ),
mCurrPass( 0 ),
mMaterials( 0 )
{
smAllMaterials.push_back( this );
}
TerrainCellMaterial::~TerrainCellMaterial()
{
SAFE_DELETE( mDeferredMat );
SAFE_DELETE( mReflectMat );
smAllMaterials.remove( this );
T3D::for_each(mMaterialInfos.begin(), mMaterialInfos.end(), T3D::delete_pointer());
mMaterialInfos.clear();
}
void TerrainCellMaterial::_updateDefaultAnisotropy()
{
// TODO: We need to split the stateblock initialization
// from the shader constant lookup and pass setup in a
// future version of terrain materials.
//
// For now use some custom code in a horrible loop to
// change the anisotropy directly and fast.
//
const U32 maxAnisotropy = MATMGR->getDefaultAnisotropy();
Vector<TerrainCellMaterial*>::iterator iter = smAllMaterials.begin();
for ( ; iter != smAllMaterials.end(); iter++ )
{
// Start from the existing state block.
GFXStateBlockDesc desc = (*iter)->mStateBlock->getDesc();
if ((*iter)->mDetailTexArrayConst->isValid())
{
const S32 sampler = (*iter)->mDetailTexArrayConst->getSamplerRegister();
if (maxAnisotropy > 1)
{
desc.samplers[sampler].minFilter = GFXTextureFilterAnisotropic;
desc.samplers[sampler].maxAnisotropy = maxAnisotropy;
}
else
desc.samplers[sampler].minFilter = GFXTextureFilterLinear;
}
if ((*iter)->mMacroTexArrayConst->isValid())
{
const S32 sampler = (*iter)->mMacroTexArrayConst->getSamplerRegister();
if (maxAnisotropy > 1)
{
desc.samplers[sampler].minFilter = GFXTextureFilterAnisotropic;
desc.samplers[sampler].maxAnisotropy = maxAnisotropy;
}
else
desc.samplers[sampler].minFilter = GFXTextureFilterLinear;
}
if ((*iter)->mNormalTexArrayConst->isValid())
{
const S32 sampler = (*iter)->mNormalTexArrayConst->getSamplerRegister();
if (maxAnisotropy > 1)
{
desc.samplers[sampler].minFilter = GFXTextureFilterAnisotropic;
desc.samplers[sampler].maxAnisotropy = maxAnisotropy;
}
else
desc.samplers[sampler].minFilter = GFXTextureFilterLinear;
}
if ((*iter)->mOrmTexArrayConst->isValid())
{
const S32 sampler = (*iter)->mOrmTexArrayConst->getSamplerRegister();
if (maxAnisotropy > 1)
{
desc.samplers[sampler].minFilter = GFXTextureFilterAnisotropic;
desc.samplers[sampler].maxAnisotropy = maxAnisotropy;
}
else
desc.samplers[sampler].minFilter = GFXTextureFilterLinear;
}
// Set the updated stateblock.
desc.setCullMode(GFXCullCCW);
(*iter)->mStateBlock = GFX->createStateBlock(desc);
//reflection
desc.setCullMode(GFXCullCW);
(*iter)->mReflectionStateBlock = GFX->createStateBlock(desc);
// Create the wireframe state blocks.
GFXStateBlockDesc wireframe(desc);
wireframe.fillMode = GFXFillWireframe;
wireframe.setCullMode(GFXCullCCW);
(*iter)->mWireframeStateBlock = GFX->createStateBlock(wireframe);
}
}
void TerrainCellMaterial::setTransformAndEye( const MatrixF &modelXfm,
const MatrixF &viewXfm,
const MatrixF &projectXfm,
F32 farPlane )
{
PROFILE_SCOPE( TerrainCellMaterial_SetTransformAndEye );
MatrixF modelViewProj = projectXfm * viewXfm * modelXfm;
MatrixF invViewXfm( viewXfm );
invViewXfm.inverse();
Point3F eyePos = invViewXfm.getPosition();
MatrixF invModelXfm( modelXfm );
invModelXfm.inverse();
Point3F objEyePos = eyePos;
invModelXfm.mulP( objEyePos );
VectorF vEye = invViewXfm.getForwardVector();
vEye.normalize( 1.0f / farPlane );
mConsts->setSafe(mModelViewProjConst, modelViewProj);
if (mViewToObjConst->isValid() || mWorldViewOnlyConst->isValid())
{
MatrixF worldViewOnly = viewXfm * modelXfm;
mConsts->setSafe(mWorldViewOnlyConst, worldViewOnly);
if (mViewToObjConst->isValid())
{
worldViewOnly.affineInverse();
mConsts->set(mViewToObjConst, worldViewOnly);
}
}
mConsts->setSafe(mEyePosWorldConst, eyePos);
mConsts->setSafe(mEyePosConst, objEyePos);
mConsts->setSafe(mObjTransConst, modelXfm);
mConsts->setSafe(mWorldToObjConst, invModelXfm);
mConsts->setSafe(mVEyeConst, vEye);
}
TerrainCellMaterial* TerrainCellMaterial::getDeferredMat()
{
if ( !mDeferredMat )
{
mDeferredMat = new TerrainCellMaterial();
mDeferredMat->init( mTerrain, mMaterials, true, false, mMaterials == 0 );
}
return mDeferredMat;
}
TerrainCellMaterial* TerrainCellMaterial::getReflectMat()
{
if ( !mReflectMat )
{
mReflectMat = new TerrainCellMaterial();
mReflectMat->init( mTerrain, mMaterials, false, true, true );
}
return mReflectMat;
}
void TerrainCellMaterial::init( TerrainBlock *block,
U64 activeMaterials,
bool deferredMat,
bool reflectMat,
bool baseOnly )
{
// This isn't allowed for now.
AssertFatal( !( deferredMat && reflectMat ), "TerrainCellMaterial::init - We shouldn't get deferred and reflection in the same material!" );
mTerrain = block;
mMaterials = activeMaterials;
mMaterialInfos.clear();
for ( U32 i = 0; i < 64; i++ )
{
if ( !( mMaterials & ((U64)1 << i ) ) )
continue;
TerrainMaterial *mat = block->getMaterial( i );
MaterialInfo *info = new MaterialInfo();
info->layerId = i;
info->mat = mat;
mMaterialInfos.push_back(info);
}
if (!_initShader(deferredMat,
reflectMat,
baseOnly))
{
Con::errorf("TerrainCellMaterial::init - Failed to init shader!");
T3D::for_each(mMaterialInfos.begin(), mMaterialInfos.end(), T3D::delete_pointer());
mMaterialInfos.clear();
return;
}
// If we have attached mats then update them too.
if ( mDeferredMat )
mDeferredMat->init( mTerrain, mMaterials, true, false, baseOnly );
if ( mReflectMat )
mReflectMat->init( mTerrain, mMaterials, false, true, baseOnly );
}
bool TerrainCellMaterial::_initShader(bool deferredMat,
bool reflectMat,
bool baseOnly)
{
if (GFX->getPixelShaderVersion() < 3.0f)
baseOnly = true;
// NOTE: At maximum we only try to combine sgMaxTerrainMaterialsPerPass materials
// into a single pass. This is sub-optimal for the simplest
// cases, but the most common case results in much fewer
// shader generation failures and permutations leading to
// faster load time and less hiccups during gameplay.
U32 matCount = getMin(sgMaxTerrainMaterialsPerPass, mMaterialInfos.size());
Vector<GFXTexHandle> normalMaps;
// See if we're currently running under the
// basic lighting manager.
//
// TODO: This seems ugly... we should trigger
// features like this differently in the future.
//
bool useBLM = String::compare(LIGHTMGR->getId(), "BLM") == 0;
// Do we need to disable normal mapping?
const bool disableNormalMaps = MATMGR->getExclusionFeatures().hasFeature(MFT_NormalMap) || useBLM;
// How about parallax?
const bool disableParallaxMaps = GFX->getPixelShaderVersion() < 3.0f ||
MATMGR->getExclusionFeatures().hasFeature(MFT_Parallax);
// Has advanced lightmap support been enabled for deferred.
bool advancedLightmapSupport = false;
if (deferredMat)
{
// This sucks... but it works.
AdvancedLightBinManager* lightBin;
if (Sim::findObject("AL_LightBinMgr", lightBin))
advancedLightmapSupport = lightBin->MRTLightmapsDuringDeferred();
}
// Loop till we create a valid shader!
while (true)
{
FeatureSet features;
features.addFeature(MFT_VertTransform);
features.addFeature(MFT_TerrainBaseMap);
if (deferredMat)
{
features.addFeature(MFT_EyeSpaceDepthOut);
features.addFeature(MFT_DeferredConditioner);
features.addFeature(MFT_isDeferred);
if (advancedLightmapSupport)
features.addFeature(MFT_RenderTarget3_Zero);
}
else
{
features.addFeature(MFT_RTLighting);
// The HDR feature is always added... it will compile out
// if HDR is not enabled in the engine.
features.addFeature(MFT_HDROut);
}
// Enable lightmaps and fogging if we're in BL.
if (reflectMat || useBLM)
{
features.addFeature(MFT_Fog);
features.addFeature(MFT_ForwardShading);
}
if (useBLM)
features.addFeature(MFT_TerrainLightMap);
normalMaps.clear();
S32 featureIndex = 0;
// Now add all the material layer features.
for (U32 i = 0; i < matCount && !baseOnly; i++)
{
TerrainMaterial* mat = mMaterialInfos[i]->mat;
if (mat == NULL)
continue;
// We only include materials that
// have more than a base texture.
if (mat->getDetailSize() <= 0 ||
mat->getDetailDistance() <= 0 ||
mat->getDetailMap().isEmpty())
continue;
// check for macro detail texture
if (!(mat->getMacroSize() <= 0 || mat->getMacroDistance() <= 0 || mat->getMacroMap().isEmpty()))
{
if (deferredMat)
features.addFeature(MFT_isDeferred, featureIndex);
features.addFeature(MFT_TerrainMacroMap, featureIndex);
}
if (deferredMat)
features.addFeature(MFT_isDeferred, featureIndex);
features.addFeature(MFT_TerrainDetailMap, featureIndex);
if (deferredMat)
{
if (!(mat->getORMConfigMap().isEmpty()))
{
features.addFeature(MFT_TerrainORMMap, featureIndex);
}
else
{
features.addFeature(MFT_DeferredTerrainBlankInfoMap, featureIndex);
}
}
if (mat->getInvertRoughness())
features.addFeature(MFT_InvertRoughness, featureIndex);
normalMaps.increment();
// Skip normal maps if we need to.
if (!disableNormalMaps && mat->getNormalMap().isNotEmpty())
{
features.addFeature(MFT_TerrainNormalMap, featureIndex);
normalMaps.last().set(mat->getNormalMap(),
&GFXNormalMapProfile, "TerrainCellMaterial::_initShader() - NormalMap");
GFXFormat normalFmt = normalMaps.last().getFormat();
if (normalFmt == GFXFormatBC3)
features.addFeature(MFT_IsBC3nm, featureIndex);
else if (normalFmt == GFXFormatBC5)
features.addFeature(MFT_IsBC5nm, featureIndex);
// Do we need and can we do parallax mapping?
if (!disableParallaxMaps &&
mat->getParallaxScale() > 0.0f &&
!mat->useSideProjection())
features.addFeature(MFT_TerrainParallaxMap, featureIndex);
}
// Is this layer got side projection?
if (mat->useSideProjection())
features.addFeature(MFT_TerrainSideProject, featureIndex);
featureIndex++;
}
// New blending
if (matCount > 0 && !Con::getBoolVariable("$Terrain::LerpBlend", false))
{
features.addFeature(MFT_TerrainHeightBlend);
}
MaterialFeatureData featureData;
featureData.features = features;
featureData.materialFeatures = features;
// Check to see how many vertex shader output
// registers we're gonna need.
U32 numTex = 0;
U32 numTexReg = 0;
for (U32 i = 0; i < features.getCount(); i++)
{
S32 index;
const FeatureType& type = features.getAt(i, &index);
ShaderFeature* sf = FEATUREMGR->getByType(type);
if (!sf)
continue;
sf->setProcessIndex(index);
ShaderFeature::Resources res = sf->getResources(featureData);
numTex += res.numTex;
numTexReg += res.numTexReg;
}
// Can we build the shader?
//
// NOTE: The 10 is sort of an abitrary SM 3.0
// limit. Its really supposed to be 11, but that
// always fails to compile so far.
//
if (numTex < GFX->getNumSamplers() &&
numTexReg <= 10)
{
// NOTE: We really shouldn't be getting errors building the shaders,
// but we can generate more instructions than the ps_2_x will allow.
//
// There is no way to deal with this case that i know of other than
// letting the compile fail then recovering by trying to build it
// with fewer materials.
//
// We normally disable the shader error logging so that the user
// isn't fooled into thinking there is a real bug. That is until
// we get down to a single material. If a single material case
// fails it means it cannot generate any passes at all!
const bool logErrors = true;// matCount == 1;
GFXShader::setLogging(logErrors, true);
mShader = SHADERGEN->getShader(featureData, getGFXVertexFormat<TerrVertex>(), NULL, mSamplerNames);
}
// If we got a shader then we can continue.
if (mShader)
break;
// If the material count is already 1 then this
// is a real shader error... give up!
if (matCount <= 1)
return false;
// If we failed we next try half the input materials
// so that we can more quickly arrive at a valid shader.
matCount -= matCount / 2;
}
// Setup the constant buffer.
mConsts = mShader->allocConstBuffer();
// Prepare the basic constants.
mModelViewProjConst = mShader->getShaderConstHandle("$modelview");
mWorldViewOnlyConst = mShader->getShaderConstHandle("$worldViewOnly");
mViewToObjConst = mShader->getShaderConstHandle("$viewToObj");
mEyePosWorldConst = mShader->getShaderConstHandle("$eyePosWorld");
mEyePosConst = mShader->getShaderConstHandle("$eyePos");
mVEyeConst = mShader->getShaderConstHandle("$vEye");
mLayerSizeConst = mShader->getShaderConstHandle("$layerSize");
mObjTransConst = mShader->getShaderConstHandle("$objTrans");
mWorldToObjConst = mShader->getShaderConstHandle("$worldToObj");
mLightInfoBufferConst = mShader->getShaderConstHandle("$lightInfoBuffer");
mBaseTexMapConst = mShader->getShaderConstHandle("$baseTexMap");
mLayerTexConst = mShader->getShaderConstHandle("$layerTex");
mFogDataConst = mShader->getShaderConstHandle("$fogData");
mFogColorConst = mShader->getShaderConstHandle("$fogColor");
mLightMapTexConst = mShader->getShaderConstHandle("$lightMapTex");
mOneOverTerrainSizeConst = mShader->getShaderConstHandle("$oneOverTerrainSize");
mSquareSizeConst = mShader->getShaderConstHandle("$squareSize");
mBlendDepthConst = mShader->getShaderConstHandle("$baseBlendDepth");
mLightParamsConst = mShader->getShaderConstHandle("$rtParamslightInfoBuffer");
// Now prepare the basic stateblock.
GFXStateBlockDesc desc;
// We write to the zbuffer if this is a deferred
// material or if the deferred is disabled.
desc.setZReadWrite(true, !MATMGR->getDeferredEnabled() ||
deferredMat ||
reflectMat);
desc.samplersDefined = true;
if (mBaseTexMapConst->isValid())
desc.samplers[mBaseTexMapConst->getSamplerRegister()] = GFXSamplerStateDesc::getWrapLinear();
if (mLayerTexConst->isValid())
desc.samplers[mLayerTexConst->getSamplerRegister()] = GFXSamplerStateDesc::getClampPoint();
if (mLightInfoBufferConst->isValid())
desc.samplers[mLightInfoBufferConst->getSamplerRegister()] = GFXSamplerStateDesc::getClampPoint();
if (mLightMapTexConst->isValid())
desc.samplers[mLightMapTexConst->getSamplerRegister()] = GFXSamplerStateDesc::getWrapLinear();
const U32 maxAnisotropy = MATMGR->getDefaultAnisotropy();
mDetailInfoVArrayConst = mShader->getShaderConstHandle("$detailScaleAndFade");
mDetailInfoPArrayConst = mShader->getShaderConstHandle("$detailIdStrengthParallax");
mMacroInfoVArrayConst = mShader->getShaderConstHandle("$macroIdStrengthParallax");
mMacroInfoPArrayConst = mShader->getShaderConstHandle("$macroIdStrengthParallax");
mDetailTexArrayConst = mShader->getShaderConstHandle("$detailMapSampler");
if (mDetailTexArrayConst->isValid())
{
const S32 sampler = mDetailTexArrayConst->getSamplerRegister();
desc.samplers[sampler] = GFXSamplerStateDesc::getWrapLinear();
desc.samplers[sampler].magFilter = GFXTextureFilterLinear;
desc.samplers[sampler].mipFilter = GFXTextureFilterLinear;
if (maxAnisotropy > 1)
{
desc.samplers[sampler].minFilter = GFXTextureFilterAnisotropic;
desc.samplers[sampler].maxAnisotropy = maxAnisotropy;
}
else
desc.samplers[sampler].minFilter = GFXTextureFilterLinear;
}
mMacroTexArrayConst = mShader->getShaderConstHandle("$macroMapSampler");
if (mMacroTexArrayConst->isValid())
{
const S32 sampler = mMacroTexArrayConst->getSamplerRegister();
desc.samplers[sampler] = GFXSamplerStateDesc::getWrapLinear();
desc.samplers[sampler].magFilter = GFXTextureFilterLinear;
desc.samplers[sampler].mipFilter = GFXTextureFilterLinear;
if (maxAnisotropy > 1)
{
desc.samplers[sampler].minFilter = GFXTextureFilterAnisotropic;
desc.samplers[sampler].maxAnisotropy = maxAnisotropy;
}
else
desc.samplers[sampler].minFilter = GFXTextureFilterLinear;
}
mNormalTexArrayConst = mShader->getShaderConstHandle("$normalMapSampler");
if (mNormalTexArrayConst->isValid())
{
const S32 sampler = mNormalTexArrayConst->getSamplerRegister();
desc.samplers[sampler] = GFXSamplerStateDesc::getWrapLinear();
desc.samplers[sampler].magFilter = GFXTextureFilterLinear;
desc.samplers[sampler].mipFilter = GFXTextureFilterLinear;
if (maxAnisotropy > 1)
{
desc.samplers[sampler].minFilter = GFXTextureFilterAnisotropic;
desc.samplers[sampler].maxAnisotropy = maxAnisotropy;
}
else
desc.samplers[sampler].minFilter = GFXTextureFilterLinear;
}
mOrmTexArrayConst = mShader->getShaderConstHandle("$ormMapSampler");
if (mOrmTexArrayConst->isValid())
{
GFXTextureProfile* profile = &GFXStaticTextureProfile;
const S32 sampler = mOrmTexArrayConst->getSamplerRegister();
desc.samplers[sampler] = GFXSamplerStateDesc::getWrapLinear();
desc.samplers[sampler].magFilter = GFXTextureFilterLinear;
desc.samplers[sampler].mipFilter = GFXTextureFilterLinear;
if (maxAnisotropy > 1)
{
desc.samplers[sampler].minFilter = GFXTextureFilterAnisotropic;
desc.samplers[sampler].maxAnisotropy = maxAnisotropy;
}
else
desc.samplers[sampler].minFilter = GFXTextureFilterLinear;
}
for (U32 i = 0; i < matCount && !baseOnly; i++)
{
TerrainMaterial* mat = mMaterialInfos[i]->mat;
if (mat == NULL)
continue;
// We only include materials that
// have more than a base texture.
if (mat->getDetailSize() <= 0 ||
mat->getDetailDistance() <= 0 ||
mat->getDetailMap().isEmpty())
continue;
mMaterialInfos[i]->mBlendDepthConst = mShader->getShaderConstHandle(avar("$blendDepth%d", i));
mMaterialInfos[i]->mBlendContrastConst = mShader->getShaderConstHandle(avar("$blendContrast%d", i));
}
// If we're doing deferred it requires some
// special stencil settings for it to work.
if ( deferredMat )
desc.addDesc( RenderDeferredMgr::getOpaqueStenciWriteDesc( false ) );
desc.setCullMode( GFXCullCCW );
mStateBlock = GFX->createStateBlock(desc);
//reflection stateblock
desc.setCullMode( GFXCullCW );
mReflectionStateBlock = GFX->createStateBlock(desc);
// Create the wireframe state blocks.
GFXStateBlockDesc wireframe( desc );
wireframe.fillMode = GFXFillWireframe;
wireframe.setCullMode( GFXCullCCW );
mWireframeStateBlock = GFX->createStateBlock( wireframe );
return true;
}
void TerrainCellMaterial::_updateMaterialConsts( )
{
PROFILE_SCOPE( TerrainCellMaterial_UpdateMaterialConsts );
int detailMatCount = 0;
for (MaterialInfo* materialInfo : mMaterialInfos)
{
if (materialInfo == NULL)
continue;
TerrainMaterial* mat = materialInfo->mat;
if (mat == NULL)
continue;
// We only include materials that
// have more than a base texture.
if (mat->getDetailSize() <= 0 ||
mat->getDetailDistance() <= 0 ||
mat->getDetailMap().isEmpty())
continue;
detailMatCount++;
}
if (detailMatCount == 0)
{
return;
}
AlignedArray<Point4F> detailInfoArray(detailMatCount, sizeof(Point4F));
AlignedArray<Point4F> detailScaleAndFadeArray(detailMatCount, sizeof(Point4F));
int detailIndex = 0;
for (MaterialInfo* matInfo : mMaterialInfos)
{
if (matInfo == NULL)
continue;
TerrainMaterial* mat = matInfo->mat;
if (mat == NULL)
continue;
// We only include materials that
// have more than a base texture.
if (mat->getDetailSize() <= 0 ||
mat->getDetailDistance() <= 0 ||
mat->getDetailMap().isEmpty())
continue;
F32 detailSize = matInfo->mat->getDetailSize();
F32 detailScale = 1.0f;
if ( !mIsZero( detailSize ) )
detailScale = mTerrain->getWorldBlockSize() / detailSize;
// Scale the distance by the global scalar.
const F32 distance = mTerrain->smDetailScale * matInfo->mat->getDetailDistance();
// NOTE: The negation of the y scale is to make up for
// my mistake early in development and passing the wrong
// y texture coord into the system.
//
// This negation fixes detail, normal, and parallax mapping
// without harming the layer id blending code.
//
// Eventually we should rework this to correct this little
// mistake, but there isn't really a hurry to.
//
Point4F detailScaleAndFade( detailScale,
-detailScale,
distance,
0 );
if ( !mIsZero( distance ) )
detailScaleAndFade.w = 1.0f / distance;
Point4F detailIdStrengthParallax( matInfo->layerId,
matInfo->mat->getDetailStrength(),
matInfo->mat->getParallaxScale(), 0 );
detailScaleAndFadeArray[detailIndex] = detailScaleAndFade;
detailInfoArray[detailIndex] = detailIdStrengthParallax;
if (matInfo->mBlendDepthConst != NULL)
{
mConsts->setSafe(matInfo->mBlendDepthConst, matInfo->mat->getBlendDepth());
}
if (matInfo->mBlendContrastConst != NULL)
{
mConsts->setSafe(matInfo->mBlendContrastConst, matInfo->mat->getBlendContrast());
}
detailIndex++;
}
mConsts->setSafe(mDetailInfoVArrayConst, detailScaleAndFadeArray);
mConsts->setSafe(mDetailInfoPArrayConst, detailInfoArray);
}
bool TerrainCellMaterial::setupPass( const SceneRenderState *state,
const SceneData &sceneData )
{
PROFILE_SCOPE( TerrainCellMaterial_SetupPass );
if (mCurrPass > 0)
{
mCurrPass = 0;
return false;
}
mCurrPass++;
_updateMaterialConsts();
if ( mBaseTexMapConst->isValid() )
GFX->setTexture( mBaseTexMapConst->getSamplerRegister(), mTerrain->mBaseTex.getPointer() );
if ( mLayerTexConst->isValid() )
GFX->setTexture( mLayerTexConst->getSamplerRegister(), mTerrain->mLayerTex.getPointer() );
if ( mLightMapTexConst->isValid() )
GFX->setTexture( mLightMapTexConst->getSamplerRegister(), mTerrain->getLightMapTex() );
if ( sceneData.wireframe )
GFX->setStateBlock( mWireframeStateBlock );
else if ( state->isReflectPass( ))
GFX->setStateBlock( mReflectionStateBlock );
else
GFX->setStateBlock( mStateBlock );
GFX->setShader( mShader );
GFX->setShaderConstBuffer( mConsts );
// Let the light manager prepare any light stuff it needs.
LIGHTMGR->setLightInfo( NULL,
NULL,
sceneData,
state,
0,
mConsts );
if (mDetailTexArrayConst->isValid() && mTerrain->getDetailTextureArray().isValid())
GFX->setTextureArray(mDetailTexArrayConst->getSamplerRegister(), mTerrain->getDetailTextureArray());
if (mMacroTexArrayConst->isValid() && mTerrain->getMacroTextureArray().isValid())
GFX->setTextureArray(mMacroTexArrayConst->getSamplerRegister(), mTerrain->getMacroTextureArray());
if (mNormalTexArrayConst->isValid() && mTerrain->getNormalTextureArray().isValid())
GFX->setTextureArray(mNormalTexArrayConst->getSamplerRegister(), mTerrain->getNormalTextureArray());
if (mOrmTexArrayConst->isValid() && mTerrain->getOrmTextureArray().isValid())
GFX->setTextureArray(mOrmTexArrayConst->getSamplerRegister(), mTerrain->getOrmTextureArray());
mConsts->setSafe( mLayerSizeConst, (F32)mTerrain->mLayerTex.getWidth() );
if ( mOneOverTerrainSizeConst->isValid() )
{
F32 oneOverTerrainSize = 1.0f / mTerrain->getWorldBlockSize();
mConsts->set( mOneOverTerrainSizeConst, oneOverTerrainSize );
}
mConsts->setSafe( mSquareSizeConst, mTerrain->getSquareSize() );
if ( mFogDataConst->isValid() )
{
Point3F fogData;
fogData.x = sceneData.fogDensity;
fogData.y = sceneData.fogDensityOffset;
fogData.z = sceneData.fogHeightFalloff;
mConsts->set( mFogDataConst, fogData );
}
if (String::isEmpty(Con::getVariable("$Terrain::BlendDepth")))
{
mConsts->setSafe(mBlendDepthConst, 0.2f);
}
else
{
mConsts->setSafe(mBlendDepthConst, Con::getFloatVariable("$Terrain::BlendDepth"));
}
mConsts->setSafe( mFogColorConst, sceneData.fogColor );
if ( mLightInfoBufferConst->isValid() &&
mLightParamsConst->isValid() )
{
if ( !mLightInfoTarget )
mLightInfoTarget = NamedTexTarget::find( "diffuseLighting" );
GFXTextureObject *texObject = mLightInfoTarget->getTexture();
// TODO: Sometimes during reset of the light manager we get a
// NULL texture here. This is corrected on the next frame, but
// we should still investigate why that happens.
if ( texObject )
{
GFX->setTexture( mLightInfoBufferConst->getSamplerRegister(), texObject );
const Point3I &targetSz = texObject->getSize();
const RectI &targetVp = mLightInfoTarget->getViewport();
Point4F rtParams;
ScreenSpace::RenderTargetParameters(targetSz, targetVp, rtParams);
mConsts->setSafe( mLightParamsConst, rtParams );
}
}
return true;
}
BaseMatInstance* TerrainCellMaterial::getShadowMat()
{
// Find our material which has some settings
// defined on it in script.
Material *mat = MATMGR->getMaterialDefinitionByName( "AL_DefaultShadowMaterial" );
// Create the material instance adding the feature which
// handles rendering terrain cut outs.
FeatureSet features = MATMGR->getDefaultFeatures();
BaseMatInstance *matInst = mat->createMatInstance();
if ( !matInst->init( features, getGFXVertexFormat<TerrVertex>() ) )
{
delete matInst;
matInst = NULL;
}
return matInst;
}
| 34.183832 | 143 | 0.656149 | GoldenThumbs |
41adde3a124bbc581fc16211d93d399661bf27f7 | 4,938 | cc | C++ | third_party/crashpad/crashpad/snapshot/win/cpu_context_win_test.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | third_party/crashpad/crashpad/snapshot/win/cpu_context_win_test.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | third_party/crashpad/crashpad/snapshot/win/cpu_context_win_test.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2014 The Crashpad 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 "snapshot/win/cpu_context_win.h"
#include <windows.h>
#include "base/macros.h"
#include "build/build_config.h"
#include "gtest/gtest.h"
#include "test/hex_string.h"
#include "snapshot/cpu_context.h"
namespace crashpad {
namespace test {
namespace {
template <typename T>
void TestInitializeX86Context() {
T context = {0};
context.ContextFlags = WOW64_CONTEXT_INTEGER |
WOW64_CONTEXT_DEBUG_REGISTERS |
WOW64_CONTEXT_EXTENDED_REGISTERS;
context.Eax = 1;
context.Dr0 = 3;
context.ExtendedRegisters[4] = 2; // FTW
// Test the simple case, where everything in the CPUContextX86 argument is set
// directly from the supplied thread, float, and debug state parameters.
{
CPUContextX86 cpu_context_x86 = {};
InitializeX86Context(context, &cpu_context_x86);
EXPECT_EQ(cpu_context_x86.eax, 1u);
EXPECT_EQ(cpu_context_x86.fxsave.ftw, 2u);
EXPECT_EQ(cpu_context_x86.dr0, 3u);
}
}
template <typename T>
void TestInitializeX86Context_FsaveWithoutFxsave() {
T context = {0};
context.ContextFlags = WOW64_CONTEXT_INTEGER |
WOW64_CONTEXT_FLOATING_POINT |
WOW64_CONTEXT_DEBUG_REGISTERS;
context.Eax = 1;
// In fields that are wider than they need to be, set the high bits to ensure
// that they’re masked off appropriately in the output.
context.FloatSave.ControlWord = 0xffff027f;
context.FloatSave.StatusWord = 0xffff0004;
context.FloatSave.TagWord = 0xffffa9ff;
context.FloatSave.ErrorOffset = 0x01234567;
context.FloatSave.ErrorSelector = 0x0bad0003;
context.FloatSave.DataOffset = 0x89abcdef;
context.FloatSave.DataSelector = 0xffff0007;
context.FloatSave.RegisterArea[77] = 0x80;
context.FloatSave.RegisterArea[78] = 0xff;
context.FloatSave.RegisterArea[79] = 0x7f;
context.Dr0 = 3;
{
CPUContextX86 cpu_context_x86 = {};
InitializeX86Context(context, &cpu_context_x86);
EXPECT_EQ(cpu_context_x86.eax, 1u);
EXPECT_EQ(cpu_context_x86.fxsave.fcw, 0x027f);
EXPECT_EQ(cpu_context_x86.fxsave.fsw, 0x0004);
EXPECT_EQ(cpu_context_x86.fxsave.ftw, 0x00f0);
EXPECT_EQ(cpu_context_x86.fxsave.fop, 0x0bad);
EXPECT_EQ(cpu_context_x86.fxsave.fpu_ip, 0x01234567);
EXPECT_EQ(cpu_context_x86.fxsave.fpu_cs, 0x0003);
EXPECT_EQ(cpu_context_x86.fxsave.fpu_dp, 0x89abcdef);
EXPECT_EQ(cpu_context_x86.fxsave.fpu_ds, 0x0007);
for (size_t st_mm = 0; st_mm < 7; ++st_mm) {
EXPECT_EQ(
BytesToHexString(cpu_context_x86.fxsave.st_mm[st_mm].st,
arraysize(cpu_context_x86.fxsave.st_mm[st_mm].st)),
std::string(arraysize(cpu_context_x86.fxsave.st_mm[st_mm].st) * 2,
'0'))
<< "st_mm " << st_mm;
}
EXPECT_EQ(BytesToHexString(cpu_context_x86.fxsave.st_mm[7].st,
arraysize(cpu_context_x86.fxsave.st_mm[7].st)),
"0000000000000080ff7f");
EXPECT_EQ(cpu_context_x86.dr0, 3u);
}
}
#if defined(ARCH_CPU_X86_FAMILY)
#if defined(ARCH_CPU_X86_64)
TEST(CPUContextWin, InitializeX64Context) {
CONTEXT context = {0};
context.Rax = 10;
context.FltSave.TagWord = 11;
context.Dr0 = 12;
context.ContextFlags =
CONTEXT_INTEGER | CONTEXT_FLOATING_POINT | CONTEXT_DEBUG_REGISTERS;
// Test the simple case, where everything in the CPUContextX86_64 argument is
// set directly from the supplied thread, float, and debug state parameters.
{
CPUContextX86_64 cpu_context_x86_64 = {};
InitializeX64Context(context, &cpu_context_x86_64);
EXPECT_EQ(cpu_context_x86_64.rax, 10u);
EXPECT_EQ(cpu_context_x86_64.fxsave.ftw, 11u);
EXPECT_EQ(cpu_context_x86_64.dr0, 12u);
}
}
#endif // ARCH_CPU_X86_64
TEST(CPUContextWin, InitializeX86Context) {
#if defined(ARCH_CPU_X86)
TestInitializeX86Context<CONTEXT>();
#else // ARCH_CPU_X86
TestInitializeX86Context<WOW64_CONTEXT>();
#endif // ARCH_CPU_X86
}
TEST(CPUContextWin, InitializeX86Context_FsaveWithoutFxsave) {
#if defined(ARCH_CPU_X86)
TestInitializeX86Context_FsaveWithoutFxsave<CONTEXT>();
#else // ARCH_CPU_X86
TestInitializeX86Context_FsaveWithoutFxsave<WOW64_CONTEXT>();
#endif // ARCH_CPU_X86
}
#endif // ARCH_CPU_X86_FAMILY
} // namespace
} // namespace test
} // namespace crashpad
| 33.14094 | 80 | 0.720535 | metux |
41ae40c170370c26e62d938e1c06d1106419f2ac | 8,741 | cpp | C++ | Engine/Renderer/GLES3/src/GLES3Texture.cpp | LiangYue1981816/AresEngine | c1cf040a1dffaf2bc585ed75e70ddd9322fe3f67 | [
"BSD-2-Clause"
] | 3 | 2018-12-08T16:32:05.000Z | 2020-06-02T11:07:15.000Z | Engine/Renderer/GLES3/src/GLES3Texture.cpp | LiangYue1981816/AresEngine | c1cf040a1dffaf2bc585ed75e70ddd9322fe3f67 | [
"BSD-2-Clause"
] | null | null | null | Engine/Renderer/GLES3/src/GLES3Texture.cpp | LiangYue1981816/AresEngine | c1cf040a1dffaf2bc585ed75e70ddd9322fe3f67 | [
"BSD-2-Clause"
] | 1 | 2019-09-12T00:26:05.000Z | 2019-09-12T00:26:05.000Z | #include "gli.hpp"
#include "GLES3Renderer.h"
CGLES3Texture::CGLES3Texture(void)
: m_bExtern(false)
, m_target(0)
, m_texture(0)
, m_type(GFX_TEXTURE_INVALID_ENUM)
, m_format(GFX_PIXELFORMAT_UNDEFINED)
, m_width(0)
, m_height(0)
, m_layers(0)
, m_levels(0)
, m_samples(0)
{
}
CGLES3Texture::~CGLES3Texture(void)
{
Destroy();
}
void CGLES3Texture::Release(void)
{
}
uint32_t CGLES3Texture::GetTarget(void) const
{
ASSERT(m_target);
return m_target;
}
uint32_t CGLES3Texture::GetTexture(void) const
{
ASSERT(m_texture);
return m_texture;
}
GfxTextureType CGLES3Texture::GetType(void) const
{
return m_type;
}
GfxPixelFormat CGLES3Texture::GetFormat(void) const
{
return m_format;
}
int CGLES3Texture::GetWidth(void) const
{
return m_width;
}
int CGLES3Texture::GetHeight(void) const
{
return m_height;
}
int CGLES3Texture::GetLayers(void) const
{
return m_layers;
}
int CGLES3Texture::GetLevels(void) const
{
return m_levels;
}
int CGLES3Texture::GetSamples(void) const
{
return m_samples;
}
bool CGLES3Texture::Create(GfxTextureType type, GfxPixelFormat format, int width, int height, int layers, int levels, int samples, uint32_t texture)
{
ASSERT(texture);
Destroy();
m_bExtern = true;
m_target = CGLES3Helper::TranslateTextureTarget(type);
m_texture = texture;
m_type = type;
m_format = format;
m_width = width;
m_height = height;
m_layers = layers;
m_levels = levels;
m_samples = samples;
return true;
}
bool CGLES3Texture::Create(GfxTextureType type, GfxPixelFormat format, int width, int height, int layers, int levels, int samples)
{
Destroy();
m_bExtern = false;
m_target = CGLES3Helper::TranslateTextureTarget(type);
m_texture = 0;
m_type = type;
m_format = format;
m_width = width;
m_height = height;
m_layers = layers;
m_levels = levels;
gli::gl GL(gli::gl::PROFILE_ES30);
gli::gl::format glFormat = GL.translate((gli::format)format);
switch (m_target) {
case GL_TEXTURE_2D_MULTISAMPLE:
m_samples = samples;
glGenTextures(1, &m_texture);
glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, m_texture);
glTexStorage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, samples, glFormat.Internal, width, height, GL_TRUE);
glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, 0);
CHECK_GL_ERROR_ASSERT();
return true;
case GL_TEXTURE_2D:
m_samples = 1;
glGenTextures(1, &m_texture);
glBindTexture(GL_TEXTURE_2D, m_texture);
glTexStorage2D(GL_TEXTURE_2D, levels, glFormat.Internal, width, height);
glBindTexture(GL_TEXTURE_2D, 0);
CHECK_GL_ERROR_ASSERT();
return true;
case GL_TEXTURE_2D_ARRAY:
m_samples = 1;
glGenTextures(1, &m_texture);
glBindTexture(GL_TEXTURE_2D_ARRAY, m_texture);
glTexStorage3D(GL_TEXTURE_2D_ARRAY, levels, glFormat.Internal, width, height, layers);
glBindTexture(GL_TEXTURE_2D_ARRAY, 0);
CHECK_GL_ERROR_ASSERT();
return true;
case GL_TEXTURE_CUBE_MAP:
m_samples = 1;
glGenTextures(1, &m_texture);
glBindTexture(GL_TEXTURE_CUBE_MAP, m_texture);
glTexStorage2D(GL_TEXTURE_CUBE_MAP, levels, glFormat.Internal, width, height);
glBindTexture(GL_TEXTURE_CUBE_MAP, 0);
CHECK_GL_ERROR_ASSERT();
return true;
default:
Destroy();
return false;
}
}
void CGLES3Texture::Destroy(void)
{
if (m_bExtern == false) {
if (m_texture) {
glDeleteTextures(1, &m_texture);
}
}
m_bExtern = false;
m_target = 0;
m_texture = 0;
m_format = GFX_PIXELFORMAT_UNDEFINED;
m_width = 0;
m_height = 0;
m_layers = 0;
m_levels = 0;
m_samples = 0;
}
bool CGLES3Texture::Texture2DData(GfxPixelFormat format, int level, int xoffset, int yoffset, int width, int height, uint32_t size, const void* data)
{
ASSERT(size);
ASSERT(data);
ASSERT(m_texture);
ASSERT(m_bExtern == false);
ASSERT(m_target == GL_TEXTURE_2D);
ASSERT(m_format == format);
ASSERT(m_levels > level);
ASSERT(m_samples == 1);
ASSERT(xoffset >= 0 && width > 0 && xoffset + width <= m_width);
ASSERT(yoffset >= 0 && height > 0 && yoffset + height <= m_height);
gli::gl GL(gli::gl::PROFILE_ES30);
gli::gl::format glFormat = GL.translate((gli::format)format);
glBindTexture(m_target, m_texture);
glTexSubImage2D(m_target, level, xoffset, yoffset, width, height, glFormat.External, GL_UNSIGNED_BYTE, data);
glBindTexture(m_target, 0);
CHECK_GL_ERROR_ASSERT();
return true;
}
bool CGLES3Texture::Texture2DDataCompressed(GfxPixelFormat format, int level, int xoffset, int yoffset, int width, int height, uint32_t size, const void* data)
{
ASSERT(size);
ASSERT(data);
ASSERT(m_texture);
ASSERT(m_bExtern == false);
ASSERT(m_target == GL_TEXTURE_2D);
ASSERT(m_format == format);
ASSERT(m_levels > level);
ASSERT(m_samples == 1);
ASSERT(xoffset >= 0 && width > 0 && xoffset + width <= m_width);
ASSERT(yoffset >= 0 && height > 0 && yoffset + height <= m_height);
gli::gl GL(gli::gl::PROFILE_ES30);
gli::gl::format glFormat = GL.translate((gli::format)format);
glBindTexture(m_target, m_texture);
glCompressedTexSubImage2D(m_target, level, xoffset, yoffset, width, height, glFormat.Internal, size, data);
glBindTexture(m_target, 0);
CHECK_GL_ERROR_ASSERT();
return true;
}
bool CGLES3Texture::Texture2DArrayData(GfxPixelFormat format, int layer, int level, int xoffset, int yoffset, int width, int height, uint32_t size, const void* data)
{
ASSERT(size);
ASSERT(data);
ASSERT(m_texture);
ASSERT(m_bExtern == false);
ASSERT(m_target == GL_TEXTURE_2D_ARRAY);
ASSERT(m_format == format);
ASSERT(m_layers > layer);
ASSERT(m_levels > level);
ASSERT(m_samples == 1);
ASSERT(xoffset >= 0 && width > 0 && xoffset + width <= m_width);
ASSERT(yoffset >= 0 && height > 0 && yoffset + height <= m_height);
gli::gl GL(gli::gl::PROFILE_ES30);
gli::gl::format glFormat = GL.translate((gli::format)format);
glBindTexture(m_target, m_texture);
glTexSubImage3D(m_target, level, xoffset, yoffset, layer, width, height, 1, glFormat.External, GL_UNSIGNED_BYTE, data);
glBindTexture(m_target, 0);
CHECK_GL_ERROR_ASSERT();
return true;
}
bool CGLES3Texture::Texture2DArrayDataCompressed(GfxPixelFormat format, int layer, int level, int xoffset, int yoffset, int width, int height, uint32_t size, const void* data)
{
ASSERT(size);
ASSERT(data);
ASSERT(m_texture);
ASSERT(m_bExtern == false);
ASSERT(m_target == GL_TEXTURE_2D_ARRAY);
ASSERT(m_format == format);
ASSERT(m_layers > layer);
ASSERT(m_levels > level);
ASSERT(m_samples == 1);
ASSERT(xoffset >= 0 && width > 0 && xoffset + width <= m_width);
ASSERT(yoffset >= 0 && height > 0 && yoffset + height <= m_height);
gli::gl GL(gli::gl::PROFILE_ES30);
gli::gl::format glFormat = GL.translate((gli::format)format);
glBindTexture(m_target, m_texture);
glCompressedTexSubImage3D(m_target, level, xoffset, yoffset, layer, width, height, 1, glFormat.Internal, size, data);
glBindTexture(m_target, 0);
CHECK_GL_ERROR_ASSERT();
return true;
}
bool CGLES3Texture::TextureCubemapData(GfxPixelFormat format, GfxCubemapFace face, int level, int xoffset, int yoffset, int width, int height, uint32_t size, const void* data)
{
ASSERT(size);
ASSERT(data);
ASSERT(m_texture);
ASSERT(m_bExtern == false);
ASSERT(m_target == GL_TEXTURE_CUBE_MAP);
ASSERT(m_format == format);
ASSERT(m_levels > level);
ASSERT(m_samples == 1);
ASSERT(xoffset >= 0 && width > 0 && xoffset + width <= m_width);
ASSERT(yoffset >= 0 && height > 0 && yoffset + height <= m_height);
gli::gl GL(gli::gl::PROFILE_ES30);
gli::gl::format glFormat = GL.translate((gli::format)format);
glBindTexture(m_target, m_texture);
glTexSubImage2D(CGLES3Helper::TranslateTextureTarget(face), level, xoffset, yoffset, width, height, glFormat.External, GL_UNSIGNED_BYTE, data);
glBindTexture(m_target, 0);
CHECK_GL_ERROR_ASSERT();
return true;
}
bool CGLES3Texture::TextureCubemapDataCompressed(GfxPixelFormat format, GfxCubemapFace face, int level, int xoffset, int yoffset, int width, int height, uint32_t size, const void* data)
{
ASSERT(size);
ASSERT(data);
ASSERT(m_texture);
ASSERT(m_bExtern == false);
ASSERT(m_target == GL_TEXTURE_CUBE_MAP);
ASSERT(m_format == format);
ASSERT(m_levels > level);
ASSERT(m_samples == 1);
ASSERT(xoffset >= 0 && width > 0 && xoffset + width <= m_width);
ASSERT(yoffset >= 0 && height > 0 && yoffset + height <= m_height);
gli::gl GL(gli::gl::PROFILE_ES30);
gli::gl::format glFormat = GL.translate((gli::format)format);
glBindTexture(m_target, m_texture);
glCompressedTexSubImage2D(CGLES3Helper::TranslateTextureTarget(face), level, xoffset, yoffset, width, height, glFormat.Internal, size, data);
glBindTexture(m_target, 0);
CHECK_GL_ERROR_ASSERT();
return true;
}
void CGLES3Texture::Bind(uint32_t unit) const
{
ASSERT(m_target);
ASSERT(m_texture);
GLBindTexture(unit, m_target, m_texture);
CHECK_GL_ERROR_ASSERT();
}
| 25.860947 | 185 | 0.732982 | LiangYue1981816 |
41aee4ba370559df2589ee49a87be000bdffe9be | 3,623 | cc | C++ | pigasus/software/src/network_inspectors/appid/test/tp_mock.cc | zhipengzhaocmu/fpga2022_artifact | 0ac088a5b04c5c75ae6aef25202b66b0f674acd3 | [
"BSD-3-Clause-Clear",
"BSD-3-Clause"
] | null | null | null | pigasus/software/src/network_inspectors/appid/test/tp_mock.cc | zhipengzhaocmu/fpga2022_artifact | 0ac088a5b04c5c75ae6aef25202b66b0f674acd3 | [
"BSD-3-Clause-Clear",
"BSD-3-Clause"
] | null | null | null | pigasus/software/src/network_inspectors/appid/test/tp_mock.cc | zhipengzhaocmu/fpga2022_artifact | 0ac088a5b04c5c75ae6aef25202b66b0f674acd3 | [
"BSD-3-Clause-Clear",
"BSD-3-Clause"
] | null | null | null | //--------------------------------------------------------------------------
// Copyright (C) 2016-2018 Cisco and/or its affiliates. All rights reserved.
//
// This program is free software; you can redistribute it and/or modify it
// under the terms of the GNU General Public License Version 2 as published
// by the Free Software Foundation. You may not use, modify or distribute
// this program under any other version of the GNU General Public License.
//
// 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, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//--------------------------------------------------------------------------
// tp_mock.cc author Silviu Minut <sminut@cisco.com>
// Standalone compilation:
// g++ -g -Wall -I.. -I/path/to/snort3/src -c tp_mock.cc
// g++ -std=c++11 -g -Wall -I.. -I/path/to/snort3/src -shared -fPIC -o libtp_mock.so tp_mock.cc
// As a module (dynamically loaded) - see CMakeLists.txt
#include <iostream>
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "main/snort_types.h"
#include "tp_appid_module_api.h"
#include "tp_appid_session_api.h"
#define WhereMacro __FILE__ << ": " << __FUNCTION__ << ": " << __LINE__
using namespace std;
class ThirdPartyAppIDModuleImpl : public ThirdPartyAppIDModule
{
public:
ThirdPartyAppIDModuleImpl(uint32_t ver, const char* mname)
: ThirdPartyAppIDModule(ver, mname)
{
cerr << WhereMacro << endl;
}
~ThirdPartyAppIDModuleImpl()
{
cerr << WhereMacro << endl;
}
// Hack: use cfg to manipulate pinit to return 1, so we can hit the
// if (ret != 0) case in tp_lib_handler.cc.
int pinit(ThirdPartyConfig& cfg)
{
cerr << WhereMacro << endl;
return cfg.tp_appid_config.empty() ? 1 : 0;
}
int tinit() { return 0; }
int reconfigure(const ThirdPartyConfig&) { return 0; }
int pfini()
{
cerr << WhereMacro << endl;
return 0;
}
int tfini() { return 0; }
int print_stats() { return 0; }
int reset_stats() { return 0; }
};
class ThirdPartyAppIDSessionImpl : public ThirdPartyAppIDSession
{
public:
bool reset() { return 1; }
TPState process(const snort::Packet&, AppidSessionDirection, vector<AppId>&,
ThirdPartyAppIDAttributeData&) { return TP_STATE_INIT; }
int disable_flags(uint32_t) { return 0; }
TPState get_state() { return state; }
void set_state(TPState s) { state=s; }
void clear_attr(TPSessionAttr attr) { flags &= ~attr; }
void set_attr(TPSessionAttr attr) { flags |= attr; }
unsigned get_attr(TPSessionAttr attr) { return flags & attr; }
private:
unsigned flags = 0;
};
// Object factories to create module and session.
// This is the only way for outside callers to create module and session
// once the .so has been loaded.
extern "C"
{
SO_PUBLIC ThirdPartyAppIDModuleImpl* create_third_party_appid_module();
SO_PUBLIC ThirdPartyAppIDSessionImpl* create_third_party_appid_session();
SO_PUBLIC ThirdPartyAppIDModuleImpl* create_third_party_appid_module()
{
return new ThirdPartyAppIDModuleImpl(1,"foobar");
}
SO_PUBLIC ThirdPartyAppIDSessionImpl* create_third_party_appid_session()
{
return new ThirdPartyAppIDSessionImpl;
}
}
| 31.780702 | 95 | 0.668231 | zhipengzhaocmu |
41b38b15073c8ebac57b2ccf6279376ac4f692fb | 1,552 | cpp | C++ | codeforces/D - Edge Deletion/Wrong answer on test 3 (4).cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | 1 | 2022-02-11T16:55:36.000Z | 2022-02-11T16:55:36.000Z | codeforces/D - Edge Deletion/Wrong answer on test 3 (4).cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | null | null | null | codeforces/D - Edge Deletion/Wrong answer on test 3 (4).cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | null | null | null | /****************************************************************************************
* @author: kzvd4729 created: Nov/12/2018 23:55
* solution_verdict: Wrong answer on test 3 language: GNU C++14
* run_time: 15 ms memory_used: 4900 KB
* problem: https://codeforces.com/contest/1076/problem/D
****************************************************************************************/
#include<bits/stdc++.h>
#define long long long
using namespace std;
const int N=3e5;
int vis[N+2];
vector<pair<int,int> >adj[N+2];
map<pair<int,int>,int>mp;
int main()
{
ios_base::sync_with_stdio(0);cin.tie(0);
int n,m,k;cin>>n>>m>>k;
for(int i=1;i<=m;i++)
{
int u,v,w;cin>>u>>v>>w;
adj[u].push_back({v,w});
adj[v].push_back({u,w});
if(u>v)swap(u,v);mp[{u,v}]=i;
}
priority_queue<pair<long,pair<int,int> > >pq;
for(auto x:adj[1])pq.push({-x.second,{1,x.first}});
set<int>ans;vis[1]=1;
while(pq.size())
{
pair<long,pair<int,int> >p=pq.top();pq.pop();
int u=p.second.first,v=p.second.second;
if(u>v)swap(u,v);long cs=-p.first;
if(ans.size()<k)ans.insert(mp[{u,v}]);
vis[p.second.second]=1;
for(auto x:adj[p.second.second])
{
if(vis[x.first])continue;
pq.push({-(cs+x.second),{p.second.second,x.first}});
}
}
cout<<ans.size()<<endl;
for(auto x:ans)
cout<<x<<" ";
cout<<endl;
return 0;
} | 33.73913 | 111 | 0.462629 | kzvd4729 |
41b5ea8cee57938e2f3ecc192834b54f85b30cfb | 26 | cpp | C++ | src/libcdk13-201802181144/compiler.cpp | pedrodaniel10/Comp | 428522b5fa4a1c6ee00dac886b8e52ba5c05d32f | [
"Apache-2.0"
] | null | null | null | src/libcdk13-201802181144/compiler.cpp | pedrodaniel10/Comp | 428522b5fa4a1c6ee00dac886b8e52ba5c05d32f | [
"Apache-2.0"
] | null | null | null | src/libcdk13-201802181144/compiler.cpp | pedrodaniel10/Comp | 428522b5fa4a1c6ee00dac886b8e52ba5c05d32f | [
"Apache-2.0"
] | null | null | null | #include <cdk/compiler.h>
| 13 | 25 | 0.730769 | pedrodaniel10 |
41b7331464dee98a8aca55284d76d6ee922b2c5b | 572 | cpp | C++ | PlatformIO ESP32 code/OSSM_ESP32/lib/ArduinoJson-6.x/extras/tests/MsgPackDeserializer/misc.cpp | ortlof/OSSM-hardware | 1cf21ce854cbe212c752726689d3c12508a3b1ee | [
"MIT"
] | 5,800 | 2015-01-05T02:36:02.000Z | 2022-03-31T04:27:26.000Z | PlatformIO ESP32 code/OSSM_ESP32/lib/ArduinoJson-6.x/extras/tests/MsgPackDeserializer/misc.cpp | ortlof/OSSM-hardware | 1cf21ce854cbe212c752726689d3c12508a3b1ee | [
"MIT"
] | 1,681 | 2015-01-04T00:41:40.000Z | 2022-03-31T07:30:51.000Z | PlatformIO ESP32 code/OSSM_ESP32/lib/ArduinoJson-6.x/extras/tests/MsgPackDeserializer/misc.cpp | ortlof/OSSM-hardware | 1cf21ce854cbe212c752726689d3c12508a3b1ee | [
"MIT"
] | 1,169 | 2015-01-04T01:32:23.000Z | 2022-03-28T13:38:00.000Z | // ArduinoJson - https://arduinojson.org
// Copyright Benoit Blanchon 2014-2021
// MIT License
#include <ArduinoJson.h>
#include <catch.hpp>
TEST_CASE("deserializeMsgPack() returns EmptyInput") {
StaticJsonDocument<100> doc;
SECTION("from sized buffer") {
DeserializationError err = deserializeMsgPack(doc, "", 0);
REQUIRE(err == DeserializationError::EmptyInput);
}
SECTION("from stream") {
std::istringstream input("");
DeserializationError err = deserializeMsgPack(doc, input);
REQUIRE(err == DeserializationError::EmptyInput);
}
}
| 22.88 | 62 | 0.711538 | ortlof |
41b7b2455b8f69a298e6f6c4cc3c92868d093881 | 748 | cpp | C++ | src/analyzers/tokenizers/character_tokenizer.cpp | saq7/MeTA | 0392964c1cdc073ae5123f7d64affdc4105acc4f | [
"MIT"
] | null | null | null | src/analyzers/tokenizers/character_tokenizer.cpp | saq7/MeTA | 0392964c1cdc073ae5123f7d64affdc4105acc4f | [
"MIT"
] | null | null | null | src/analyzers/tokenizers/character_tokenizer.cpp | saq7/MeTA | 0392964c1cdc073ae5123f7d64affdc4105acc4f | [
"MIT"
] | 1 | 2021-09-06T06:08:38.000Z | 2021-09-06T06:08:38.000Z | /**
* @file character_tokenizer.cpp
* @author Chase Geigle
*/
#include "analyzers/tokenizers/character_tokenizer.h"
#include "corpus/document.h"
#include "io/mmap_file.h"
namespace meta
{
namespace analyzers
{
namespace tokenizers
{
const std::string character_tokenizer::id = "character-tokenizer";
character_tokenizer::character_tokenizer() : idx_{0}
{
// nothing
}
void character_tokenizer::set_content(const std::string& content)
{
idx_ = 0;
content_ = content;
}
std::string character_tokenizer::next()
{
if (!*this)
throw token_stream_exception{"next() called with no tokens left"};
return {1, content_[idx_++]};
}
character_tokenizer::operator bool() const
{
return idx_ < content_.size();
}
}
}
}
| 16.622222 | 74 | 0.703209 | saq7 |
41b94436518ed9a574d67416bcd1bf2dd2024d28 | 3,065 | cpp | C++ | src/core/exportexpressionmatrix.cpp | mfayk/KINC | 0f6565ce8e1102392382e4c716c128115b611f0c | [
"MIT"
] | 10 | 2018-08-15T13:27:35.000Z | 2020-12-10T17:20:40.000Z | src/core/exportexpressionmatrix.cpp | mfayk/KINC | 0f6565ce8e1102392382e4c716c128115b611f0c | [
"MIT"
] | 182 | 2016-07-31T07:15:15.000Z | 2022-01-30T01:25:41.000Z | src/core/exportexpressionmatrix.cpp | mfayk/KINC | 0f6565ce8e1102392382e4c716c128115b611f0c | [
"MIT"
] | 7 | 2017-10-12T22:03:42.000Z | 2020-02-26T00:01:18.000Z | #include "exportexpressionmatrix.h"
#include "exportexpressionmatrix_input.h"
#include "datafactory.h"
#include "expressionmatrix_gene.h"
/*!
* Return the total number of blocks this analytic must process as steps
* or blocks of work. This implementation uses a work block for writing the
* sample names and a work block for writing each gene.
*/
int ExportExpressionMatrix::size() const
{
EDEBUG_FUNC(this);
return 1 + _input->geneSize();
}
/*!
* Process the given index with a possible block of results if this analytic
* produces work blocks. This implementation uses only the index of the result
* block to determine which piece of work to do.
*
* @param result
*/
void ExportExpressionMatrix::process(const EAbstractAnalyticBlock* result)
{
EDEBUG_FUNC(this,result);
// write the sample names in the first step
if ( result->index() == 0 )
{
// get sample names
EMetaArray sampleNames {_input->sampleNames()};
// initialize output file stream
_stream.setDevice(_output);
_stream.setRealNumberPrecision(_precision);
// write sample names
for ( int i = 0; i < _input->sampleSize(); i++ )
{
_stream << sampleNames.at(i).toString() << "\t";
}
_stream << "\n";
}
// write each gene to the output file in a separate step
else
{
// get gene index
int i = result->index() - 1;
// get gene name
QString geneName {_input->geneNames().at(i).toString()};
// load gene from expression matrix
ExpressionMatrix::Gene gene(_input);
gene.read(i);
// write gene name
_stream << geneName;
// write expression values
for ( int j = 0; j < _input->sampleSize(); j++ )
{
float value {gene.at(j)};
// if value is NAN use the no sample token
if ( std::isnan(value) )
{
_stream << "\t" << _nanToken;
}
// else this is a normal floating point expression
else
{
_stream << "\t" << value;
}
}
_stream << "\n";
}
// make sure writing output file worked
if ( _stream.status() != QTextStream::Ok )
{
E_MAKE_EXCEPTION(e);
e.setTitle(tr("File IO Error"));
e.setDetails(tr("Qt Text Stream encountered an unknown error."));
throw e;
}
}
/*!
* Make a new input object and return its pointer.
*/
EAbstractAnalyticInput* ExportExpressionMatrix::makeInput()
{
EDEBUG_FUNC(this);
return new Input(this);
}
/*!
* Initialize this analytic. This implementation checks to make sure the input
* data object and output file have been set.
*/
void ExportExpressionMatrix::initialize()
{
EDEBUG_FUNC(this);
if ( !_input || !_output )
{
E_MAKE_EXCEPTION(e);
e.setTitle(tr("Invalid Argument"));
e.setDetails(tr("Did not get valid input and/or output arguments."));
throw e;
}
}
| 23.945313 | 78 | 0.595432 | mfayk |
41bb295f79a20e218e6a1caaaad04097536c334a | 879 | cpp | C++ | qwt/examples/radio/radio.cpp | iti-luebeck/HANSE2011 | 0bd5b3f1e0bc5a02516e7514b2241897337334c2 | [
"BSD-3-Clause"
] | null | null | null | qwt/examples/radio/radio.cpp | iti-luebeck/HANSE2011 | 0bd5b3f1e0bc5a02516e7514b2241897337334c2 | [
"BSD-3-Clause"
] | null | null | null | qwt/examples/radio/radio.cpp | iti-luebeck/HANSE2011 | 0bd5b3f1e0bc5a02516e7514b2241897337334c2 | [
"BSD-3-Clause"
] | null | null | null | #include <qapplication.h>
#include <qlayout.h>
#include "tunerfrm.h"
#include "ampfrm.h"
#include "radio.h"
MainWin::MainWin():
QWidget()
{
TunerFrame *frmTuner = new TunerFrame(this);
frmTuner->setFrameStyle(QFrame::Panel|QFrame::Raised);
AmpFrame *frmAmp = new AmpFrame(this);
frmAmp->setFrameStyle(QFrame::Panel|QFrame::Raised);
QVBoxLayout *layout = new QVBoxLayout(this);
layout->setMargin(0);
layout->setSpacing(0);
layout->addWidget(frmTuner);
layout->addWidget(frmAmp);
connect(frmTuner, SIGNAL(fieldChanged(double)),
frmAmp, SLOT(setMaster(double)));
frmTuner->setFreq(90.0);
}
int main (int argc, char **argv)
{
QApplication a(argc, argv);
MainWin w;
#if QT_VERSION < 0x040000
a.setMainWidget(&w);
#endif
w.show();
return a.exec();
}
| 21.439024 | 59 | 0.625711 | iti-luebeck |
41bc85742770c7a82c455bfea9e740c54fd94de4 | 589 | cc | C++ | src/EntityLoader.cc | BitwiseSoftware/mikan | 8454af0b611fd8366c8dbea8297882f93d2e993e | [
"MIT"
] | null | null | null | src/EntityLoader.cc | BitwiseSoftware/mikan | 8454af0b611fd8366c8dbea8297882f93d2e993e | [
"MIT"
] | null | null | null | src/EntityLoader.cc | BitwiseSoftware/mikan | 8454af0b611fd8366c8dbea8297882f93d2e993e | [
"MIT"
] | null | null | null | #include "EntityLoader.hh"
#include <fstream>
#include <iostream>
namespace Mikan {
EntityLoader::EntityLoader() {
}
void EntityLoader::load_json(const std::string file_location) {
Json::Reader reader;
std::ifstream provinces_file;
provinces_file.open(file_location);
const bool parsingSuccessful = reader.parse(provinces_file, root);
if (!parsingSuccessful) {
// Should instead print to a log file
std::cout << "Failed to parse configuration"
<< std::endl
<< reader.getFormattedErrorMessages();
return;
}
}
} // namespace Mikan
| 20.310345 | 68 | 0.687606 | BitwiseSoftware |
41bcc5037bdd32edfd6134464253036715ed087f | 5,834 | cpp | C++ | test/testXml.cpp | jack-lz/anyrpc | 89533a39ecbbc05cfd89788c4aaa034ddae92010 | [
"MIT"
] | null | null | null | test/testXml.cpp | jack-lz/anyrpc | 89533a39ecbbc05cfd89788c4aaa034ddae92010 | [
"MIT"
] | null | null | null | test/testXml.cpp | jack-lz/anyrpc | 89533a39ecbbc05cfd89788c4aaa034ddae92010 | [
"MIT"
] | null | null | null | // Copyright (C) 2015 SRG Technology, LLC
//
// 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 "anyrpc/anyrpc.h"
#include <gtest/gtest.h>
#include <fstream>
using namespace std;
using namespace anyrpc;
static string ReadWriteData(char* inString)
{
ReadStringStream is(inString);
XmlReader reader(is);
Document doc;
reader >> doc;
WriteStringStream os;
XmlWriter writer(os);
writer << doc.GetValue();
return os.GetString();
}
static void WriteReadValue(Value& value, Value& outValue)
{
WriteStringStream os;
XmlWriter writer(os);
writer << value;
//cout << "Xml: " << os.GetBuffer() << endl;
ReadStringStream is(os.GetBuffer());
XmlReader reader(is);
Document doc;
reader >> doc;
outValue.Assign(doc.GetValue());
}
static int CheckParseError(const char* inString)
{
ReadStringStream is(inString);
XmlReader reader(is);
Document doc;
reader >> doc;
return reader.GetParseErrorCode();
}
TEST(Xml,Number)
{
char inString[] = "<value><i4>5736298</i4></value>";
string outString = ReadWriteData(inString);
EXPECT_STREQ( outString.c_str(), inString);
}
TEST(Xml,Double)
{
Value value, outValue;
value.SetDouble(0);
WriteReadValue(value, outValue);
EXPECT_DOUBLE_EQ(value.GetDouble(), outValue.GetDouble());
value.SetDouble(5);
WriteReadValue(value, outValue);
EXPECT_DOUBLE_EQ(value.GetDouble(), outValue.GetDouble());
value.SetDouble(2.2348282);
WriteReadValue(value, outValue);
EXPECT_DOUBLE_EQ(value.GetDouble(), outValue.GetDouble());
value.SetDouble(-728329);
WriteReadValue(value, outValue);
EXPECT_DOUBLE_EQ(value.GetDouble(), outValue.GetDouble());
value.SetDouble(5.12393e-5);
WriteReadValue(value, outValue);
EXPECT_DOUBLE_EQ(value.GetDouble(), outValue.GetDouble());
value.SetDouble(-7.192939e-300);
WriteReadValue(value, outValue);
EXPECT_DOUBLE_EQ(value.GetDouble(), outValue.GetDouble());
value.SetDouble(8e-315);
WriteReadValue(value, outValue);
EXPECT_DOUBLE_EQ(value.GetDouble(), outValue.GetDouble());
value.SetDouble(-9.12e50);
WriteReadValue(value, outValue);
EXPECT_DOUBLE_EQ(value.GetDouble(), outValue.GetDouble());
value.SetDouble(1.642e300);
WriteReadValue(value, outValue);
EXPECT_DOUBLE_EQ(value.GetDouble(), outValue.GetDouble());
value.SetDouble(-9.999e307);
WriteReadValue(value, outValue);
EXPECT_DOUBLE_EQ(value.GetDouble(), outValue.GetDouble());
}
TEST(Xml,String)
{
char inString[] = "<value>Test string data</value>";
string outString = ReadWriteData(inString);
EXPECT_STREQ( outString.c_str(), inString);
char inString2[] = "<value><string>Test string data</string></value>";
string outString2 = ReadWriteData(inString2);
EXPECT_STREQ( outString2.c_str(), inString);
}
TEST(Xml,Array)
{
char inString[] = "<value><array><data>"
"<value><i4>1</i4></value>"
"<value><i4>2</i4></value>"
"<value><i4>3</i4></value>"
"<value><i4>4</i4></value>"
"</data></array></value>";
string outString = ReadWriteData(inString);
EXPECT_STREQ( outString.c_str(), inString);
}
TEST(Xml,Map)
{
char inString[] = "<value><struct>"
"<member><name>item1</name><value><i4>57</i4></value></member>"
"<member><name>item2</name><value><i4>89</i4></value></member>"
"<member><name>item3</name><value><i4>45</i4></value></member>"
"</struct></value>";
string outString = ReadWriteData(inString);
EXPECT_STREQ( outString.c_str(), inString);
}
TEST(Xml,DateTime)
{
Value value;
time_t dt = time(NULL);
value.SetDateTime(dt);
Value outValue;
WriteReadValue(value, outValue);
EXPECT_TRUE(outValue.IsDateTime());
EXPECT_EQ(outValue.GetDateTime(), value.GetDateTime());
}
TEST(Xml,Binary)
{
Value value;
char* binData = (char*)"\x0a\x0b\x0c\x0d\xff\x00\xee\xdd\x00";
value.SetBinary( (unsigned char*)binData, 8);
Value outValue;
WriteReadValue(value, outValue);
EXPECT_TRUE(outValue.IsBinary());
EXPECT_EQ( strncmp((char*)outValue.GetBinary(), (char*)value.GetBinary(), 8), 0);
}
TEST(Xml,ParseError1)
{
char inString[] = "<value>Test string data</string></value>";
EXPECT_EQ(CheckParseError(inString), AnyRpcErrorTagInvalid);
}
TEST(Xml,ParseError2)
{
char inString[] = "<value><i4>5736298</value>";
EXPECT_EQ(CheckParseError(inString), AnyRpcErrorTagInvalid);
}
TEST(Xml,ParseError3)
{
char inString[] = "<value><i4>5736298<i4></value>";
EXPECT_EQ(CheckParseError(inString), AnyRpcErrorTagInvalid);
}
| 29.917949 | 87 | 0.67158 | jack-lz |
41bd8ec8afffd80df54210ab5431541e91303c65 | 2,777 | cpp | C++ | modules/cudf/src/column/strings/multibyte_split.cpp | exactlyallan/node | 591f06a9c56c3d94206432677a0efd34fe6cb076 | [
"Apache-2.0"
] | null | null | null | modules/cudf/src/column/strings/multibyte_split.cpp | exactlyallan/node | 591f06a9c56c3d94206432677a0efd34fe6cb076 | [
"Apache-2.0"
] | null | null | null | modules/cudf/src/column/strings/multibyte_split.cpp | exactlyallan/node | 591f06a9c56c3d94206432677a0efd34fe6cb076 | [
"Apache-2.0"
] | null | null | null | // Copyright (c) 2022, NVIDIA CORPORATION.
//
// 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 <node_cudf/column.hpp>
#include <node_cudf/table.hpp>
#include <node_cudf/utilities/metadata.hpp>
#include <cudf/io/text/data_chunk_source_factories.hpp>
#include <cudf/io/text/multibyte_split.hpp>
namespace nv {
namespace {
Column::wrapper_t split_string_column(Napi::CallbackInfo const& info,
cudf::mutable_column_view const& col,
std::string const& delimiter) {
auto env = info.Env();
/* TODO: This only splits a string column. How to generalize */
// Check type
auto span = cudf::device_span<char const>(col.child(1).data<char const>(), col.child(1).size());
auto datasource = cudf::io::text::device_span_data_chunk_source(span);
return Column::New(env, cudf::io::text::multibyte_split(datasource, delimiter));
}
Column::wrapper_t read_text_files(Napi::CallbackInfo const& info,
std::string const& filename,
std::string const& delimiter) {
auto datasource = cudf::io::text::make_source_from_file(filename);
auto text_data = cudf::io::text::multibyte_split(*datasource, delimiter);
auto env = info.Env();
return Column::New(env, std::move(text_data));
}
} // namespace
Napi::Value Column::split(Napi::CallbackInfo const& info) {
CallbackArgs args{info};
if (args.Length() != 1) { NAPI_THROW(Napi::Error::New(info.Env(), "split expects a delimiter")); }
auto delimiter = args[0];
auto col = this->mutable_view();
try {
return split_string_column(info, col, delimiter);
} catch (cudf::logic_error const& err) { NAPI_THROW(Napi::Error::New(info.Env(), err.what())); }
}
Napi::Value Column::read_text(Napi::CallbackInfo const& info) {
CallbackArgs args{info};
if (args.Length() != 2) {
NAPI_THROW(
Napi::Error::New(info.Env(), "read_text expects a filename and an optional delimiter"));
}
std::string source = args[0];
std::string delimiter = args[1];
try {
return read_text_files(info, source, delimiter);
} catch (cudf::logic_error const& err) { NAPI_THROW(Napi::Error::New(info.Env(), err.what())); }
}
} // namespace nv
| 35.151899 | 100 | 0.671948 | exactlyallan |
41bf7956aac858c6db61d104b3fcb4d553c1fb29 | 1,139 | hh | C++ | DataProducts/inc/ExtMonFNALModuleDenseId.hh | bonventre/Offline | 77db9d6368f27ab9401c690c2c2a4257ade6c231 | [
"Apache-2.0"
] | 1 | 2021-06-25T00:00:12.000Z | 2021-06-25T00:00:12.000Z | DataProducts/inc/ExtMonFNALModuleDenseId.hh | bonventre/Offline | 77db9d6368f27ab9401c690c2c2a4257ade6c231 | [
"Apache-2.0"
] | 1 | 2019-11-22T14:45:51.000Z | 2019-11-22T14:50:03.000Z | DataProducts/inc/ExtMonFNALModuleDenseId.hh | bonventre/Offline | 77db9d6368f27ab9401c690c2c2a4257ade6c231 | [
"Apache-2.0"
] | 2 | 2019-10-14T17:46:58.000Z | 2020-03-30T21:05:15.000Z | #ifndef DataProducts_ExtMonFNALModuleDenseId_hh
#define DataProducts_ExtMonFNALModuleDenseId_hh
// Sequential number of a silicon module in Mu2e ExtMonFNAL detector.
// Zero based.
//
// $Id: ExtMonFNALModuleDenseId.hh,v 1.1 2013/07/30 18:45:00 wieschie Exp $
// $Author: wieschie $
// $Date: 2013/07/30 18:45:00 $
//
// Original author Andrei Gaponenko
#include <ostream>
namespace mu2e {
class ExtMonFNALModuleDenseId {
public:
static const unsigned int NOMODULE = -1u;
explicit ExtMonFNALModuleDenseId(unsigned int did = NOMODULE) : did_(did) {}
bool operator==( ExtMonFNALModuleDenseId const& rhs) const{
return did_ == rhs.did_;
}
bool operator!=( ExtMonFNALModuleDenseId const& rhs) const{
return !(*this == rhs);
}
bool operator<( ExtMonFNALModuleDenseId const& rhs) const{
return did_ < rhs.did_;
}
unsigned int number() const { return did_; }
private:
unsigned int did_;
};
inline std::ostream& operator<<( std::ostream& os, const ExtMonFNALModuleDenseId& id) {
return os<<id.number();
}
}
#endif /* DataProducts_ExtMonFNALModuleDenseId_hh */
| 23.729167 | 89 | 0.697981 | bonventre |
41c0336090f3f0d8a0ca993471720ec50fbf335d | 3,422 | cpp | C++ | tests/pcg.cpp | bezout/LMA | 9555e41eed5f44690c5f6e3ea2d22d520ff1a9d2 | [
"BSL-1.0"
] | 29 | 2015-12-08T12:07:30.000Z | 2022-01-08T21:23:01.000Z | tests/pcg.cpp | ayumizll/LMA | e945452e12a8b05bd17400b46a20a5322aeda01d | [
"BSL-1.0"
] | 3 | 2016-07-11T16:23:48.000Z | 2017-04-05T13:33:00.000Z | tests/pcg.cpp | bezout/LMA | 9555e41eed5f44690c5f6e3ea2d22d520ff1a9d2 | [
"BSL-1.0"
] | 8 | 2015-12-21T01:52:27.000Z | 2017-12-26T02:26:55.000Z | #include <iostream>
#include <Eigen/IterativeLinearSolvers>
#include <libv/lma/lm/solver/solver.hpp>
#include <libv/lma/lm/solver/verbose.hpp>
using namespace Eigen;
void eigen_pcg(const Eigen::MatrixXd& m, const Eigen::VectorXd& jte)
{
std::cout << "\n\n EIGEN PCG " << std::endl;
size_t n = jte.size();
VectorXd x(n), b(jte);
// typedef SparseMatrix<double> Mat;
typedef Eigen::MatrixXd Mat;
// Mat A(n,n);
Mat A = m;
// for(size_t i = 0 ; i < m.cols() ; ++i)
// for(size_t j = 0 ; j < m.rows() ; ++j)
// A.coeff(j,i) = m(j,i);
// for(size_t i = 0 ; i < n ; ++i)
// A.coeffRef(i,i) = 1.0;
// A.setIdentity();
std::cout << A << std::endl;
x.setZero();
std::cout <<"\n X = " << x.transpose() << std::endl;
std::cout <<"\n B = " << b.transpose() << std::endl;
// fill A and b
ConjugateGradient<Mat> cg;
cg.compute(A);
x = cg.solve(b);
std::cout << "#iterations: " << cg.iterations() << std::endl;
std::cout << "estimated error: " << cg.error() << std::endl;
// update b, and solve again
// x = cg.solve(b);
std::cout << "\n X = " << x.transpose() << std::endl;
}
// typedef Eigen::Matrix<double,2,1> Type0;
// typedef Eigen::Matrix<double,3,1> Type1;
// typedef Eigen::Matrix<double,1,1> Type2;
//
// struct F
// {
// bool operator()(const Type0& , const Type1& , const Type2&, Eigen::Matrix<double,2,1>&) const
// {
// return true;
// }
// };
int main()
{
/*
Type0 t0;
Type1 t1;
Type2 t2;
std::cout << " Test pcg " << std::endl;
lma::Solver<F> solver(1,1);
// solver.algo.norm_eq.seuil=0.9999;
// solver.algo.norm_eq.max_iteration=100000typedef typename SelectAlgo<Container,Container::NbClass,AlgoTag>::type Algorithm;
// Algorithm algo(config);;
auto i0 = ttt::Indice<Type0*>(0);
auto i1 = ttt::Indice<Type1*>(0);
auto i2 = ttt::Indice<Type2*>(0);
solver.add(F(),&t0,&t1,&t2);//lma::bf::make_vector(i0,i1,i2),F());
// solver.solve(lma::enable_verbose_output());
// solver.algo.compute_b(solver.algo.ba_);
// solver.algo.compute_delta_a(solver.algo.ba_);
using namespace lma;
typedef typename SelectAlgo<lma::Solver<F>::Container,lma::Solver<F>::Container::NbClass,ImplicitSchurTag<1>>::type Algorithm;
Algorithm algo(ImplicitSchurTag<1>(0.9999,100000));
algo.init(solver.bundle);
lma::bf::at_key<lma::bf::pair<Type0*,Type0*>>(algo.ba_.h())(i0,0) <<
1,0,
0,2;
lma::bf::at_key<lma::bf::pair<Type2*,Type2*>>(algo.ba_.h())(i2,0) <<
1;
lma::bf::at_key<lma::bf::pair<Type0*,Type1*>>(algo.ba_.h())(i0,0) <<
3.2,0.5,2,
0,-2.5,-1.5;
lma::bf::at_key<lma::bf::pair<Type1*,Type1*>>(algo.ba_.h())(i1,0) <<
3,0,0,
0,4,0,
0,0,5;
lma::bf::at_key<Type0*>(algo.ba_.jte())(i0) << 1,2;
lma::bf::at_key<Type1*>(algo.ba_.jte())(i1) << 3,4,5;
lma::bf::at_key<Type2*>(algo.ba_.jte())(i2) << 1;
std::cout << std::endl;
std::cout << " A = \n" << lma::to_mat(algo.ba_.h()) << std::endl;
// std::cout << " B = " << lma::to_vect(solver.algo.schur_.bs_).transpose() << std::endl;
std::cout << " B = " << lma::to_vect(algo.ba_.jte()).transpose() << std::endl;
algo.compute_y(algo.ba_);
algo.compute_b(algo.ba_);
algo.compute_delta_a(algo.ba_);
std::cout << " X = " << lma::to_vect(algo.ba_.delta()).transpose() << std::endl;
eigen_pcg(lma::to_mat(algo.ba_.h()),lma::to_vect(algo.ba_.jte()));*/
}
| 30.017544 | 128 | 0.582992 | bezout |
41c43815f08dfcce1dfc8a7c5283af6b5d86868c | 1,192 | cpp | C++ | linked_list/assignments/bubble_sort.cpp | ramchandra94/datastructures_in_cpp | 28274ff4f0d9736cfe690ef002b90b9ebbfaf2f7 | [
"MIT"
] | null | null | null | linked_list/assignments/bubble_sort.cpp | ramchandra94/datastructures_in_cpp | 28274ff4f0d9736cfe690ef002b90b9ebbfaf2f7 | [
"MIT"
] | null | null | null | linked_list/assignments/bubble_sort.cpp | ramchandra94/datastructures_in_cpp | 28274ff4f0d9736cfe690ef002b90b9ebbfaf2f7 | [
"MIT"
] | null | null | null | /****************************************************************
Following is the class structure of the Node class:
class Node
{
public:
int data;
Node *next;
Node(int data)
{
this->data = data;
this->next = NULL;
}
};
*****************************************************************/
void my_swap (Node *node_1, Node *node_2)
{
int temp = node_1->data;
node_1->data = node_2 -> data;
node_2 -> data = temp;
}
Node *bubbleSort(Node *head)
{
// Write your code here
if(head == NULL){
return head;
}
int swapped;
Node *lPtr; // left pointer will always point to the start of the list
Node *rPrt = NULL; // right pointer will always point to the end of the list
do
{
swapped = 0;
lPtr = head;
while(lPtr->next != rPrt)
{
if (lPtr->data > lPtr->next->data)
{
my_swap(lPtr, lPtr->next);
swapped = 1;
}
lPtr = lPtr->next;
}
//as the largest element is at the end of the list, assign that to rPtr as there is no need to
//check already sorted list
rPrt = lPtr;
}while(swapped);
return head;
} | 20.912281 | 96 | 0.491611 | ramchandra94 |
41c4f542ba955ec768242045d93fb537f45a2f3b | 3,771 | cpp | C++ | SurgSim/Devices/LabJack/UnitTests/LabJackChecksumsTest.cpp | dbungert/opensurgsim | bd30629f2fd83f823632293959b7654275552fa9 | [
"Apache-2.0"
] | 24 | 2015-01-19T16:18:59.000Z | 2022-03-13T03:29:11.000Z | SurgSim/Devices/LabJack/UnitTests/LabJackChecksumsTest.cpp | dbungert/opensurgsim | bd30629f2fd83f823632293959b7654275552fa9 | [
"Apache-2.0"
] | 3 | 2018-12-21T14:54:08.000Z | 2022-03-14T12:38:07.000Z | SurgSim/Devices/LabJack/UnitTests/LabJackChecksumsTest.cpp | dbungert/opensurgsim | bd30629f2fd83f823632293959b7654275552fa9 | [
"Apache-2.0"
] | 8 | 2015-04-10T19:45:36.000Z | 2022-02-02T17:00:59.000Z | // This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions Inc.
//
// 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.
/// \file
/// Tests for the LabJack specific checksum functions.
#include <gtest/gtest.h>
#include "SurgSim/Devices/LabJack/linux/LabJackConstants.h"
#include "SurgSim/Devices/LabJack/linux/LabJackChecksums.h"
using SurgSim::Devices::LabJack::extendedChecksum;
using SurgSim::Devices::LabJack::extendedChecksum8;
using SurgSim::Devices::LabJack::extendedChecksum16;
using SurgSim::Devices::LabJack::normalChecksum;
using SurgSim::Devices::LabJack::normalChecksum8;
TEST(LabJackChecksumsTest, NormalChecksum)
{
// Sum less than 256
std::array<unsigned char, SurgSim::Devices::LabJack::MAXIMUM_BUFFER> bytes;
unsigned char fillValue = 2;
bytes.fill(fillValue);
int count = 10;
int expectedValue = fillValue * (count - 1);
EXPECT_EQ(expectedValue, normalChecksum8(bytes, count));
normalChecksum(&bytes, count);
EXPECT_EQ(expectedValue, bytes[0]);
// Sum greater than 256, quotient + remainder < 256
fillValue = 100;
bytes.fill(fillValue);
count = 4;
int sum = fillValue * (count - 1); // 300
int quotient = sum / 256; // 1
int remainder = sum % 256; // 44
expectedValue = quotient + remainder;
EXPECT_EQ(expectedValue, normalChecksum8(bytes, count));
normalChecksum(&bytes, count);
EXPECT_EQ(expectedValue, bytes[0]);
// Sum greater than 256, quotient + remainder > 256
fillValue = 255;
bytes.fill(fillValue);
bytes[4] = 2;
count = 5;
// sum = 767, quotient = 2, remainder = 255, quotient + remainder = 257
// second_quotient = 1, second_remainder = 1, second_quotient + second_remainder = 2
expectedValue = 2;
EXPECT_EQ(expectedValue, normalChecksum8(bytes, count));
normalChecksum(&bytes, count);
EXPECT_EQ(expectedValue, bytes[0]);
}
TEST(LabJackChecksumsTest, ExtendedChecksum)
{
// Sums less than 256
std::array<unsigned char, SurgSim::Devices::LabJack::MAXIMUM_BUFFER> bytes;
unsigned char fillValue = 2;
bytes.fill(fillValue);
int count = 10;
int expectedValue16 = (count - 6) * fillValue; // 4 * 2 = 8
EXPECT_EQ(expectedValue16, extendedChecksum16(bytes, count));
int expectedValue8 = (6 - 1) * fillValue; // 5 * 2 = 10
EXPECT_EQ(expectedValue8, extendedChecksum8(bytes));
extendedChecksum(&bytes, count);
EXPECT_EQ(expectedValue16, bytes[4]);
EXPECT_EQ(0, bytes[5]);
// extendedChecksum alters the buffer before setting bytes[0] to the return value of extendedChecksum8.
EXPECT_EQ(expectedValue8 - 2 * fillValue + expectedValue16, bytes[0]);
// Sum greater than 256, quotient + remainder < 256
fillValue = 100;
bytes.fill(fillValue);
count = 20;
expectedValue16 = (count - 6) * fillValue; // 14 * 100 = 1400
EXPECT_EQ(expectedValue16, extendedChecksum16(bytes, count));
expectedValue8 = 245; // sum = 5 * 100 = 500, quotient = 1, remainder = 244, quotient + remainder = 245
EXPECT_EQ(expectedValue8, extendedChecksum8(bytes));
extendedChecksum(&bytes, count);
EXPECT_EQ(120, bytes[4]);
EXPECT_EQ(5, bytes[5]);
// extendedChecksum alters the buffer before setting bytes[0] to the return value of extendedChecksum8.
// sum = 100 + 100 + 100 + 120 + 5 = 425, quotient = 1, remainder = 169, quotient + remainder = 170
EXPECT_EQ(170, bytes[0]);
}
| 36.970588 | 104 | 0.733227 | dbungert |
41c54e5b780ca813a5f0fb714cb50f1201459da1 | 2,048 | cpp | C++ | src/day01.cpp | foolnotion/aoc2020 | 49738011e8181af438c13556a294b939880916c9 | [
"Unlicense"
] | null | null | null | src/day01.cpp | foolnotion/aoc2020 | 49738011e8181af438c13556a294b939880916c9 | [
"Unlicense"
] | null | null | null | src/day01.cpp | foolnotion/aoc2020 | 49738011e8181af438c13556a294b939880916c9 | [
"Unlicense"
] | 2 | 2020-12-12T21:42:53.000Z | 2020-12-16T20:56:56.000Z | #define ANKERL_NANOBENCH_IMPLEMENT
#include "advent.hpp"
#include "util.hpp"
#include <functional>
#include "nanobench.h"
auto find_terms(std::vector<int> const& values, int n, int64_t sum, int64_t product = 1) -> std::optional<int64_t>
{
if (sum <= 0) {
return std::nullopt;
}
if (n == 2) {
for (auto x : values) {
auto y = sum - x;
if (std::binary_search(values.begin(), values.end(), y)) {
return std::make_optional(x * y * product);
}
}
} else if (n > 2) {
for (auto x : values) {
if (x > sum) continue;
if (auto res = find_terms(values, n - 1, sum - x, x * product); res.has_value()) {
return res;
}
}
}
return std::nullopt;
}
int day01(int argc, char** argv)
{
if (argc < 3) {
fmt::print("Provide an input file, a target sum and a number of terms.\n");
return 1;
}
int s;
int n;
if (auto res = parse_number<int>(argv[2]); res.has_value()) {
s = res.value();
} else {
throw std::runtime_error("Unable to parse target sum argument.");
}
if (auto res = parse_number<int>(argv[3]); res.has_value()) {
n = res.value();
} else {
throw std::runtime_error("Unable to parse number of terms argument.");
}
std::vector<int> values;
std::ifstream infile(argv[1]);
std::string line;
while (std::getline(infile, line)) {
if (auto v = parse_number<int>(line); v.has_value()) {
values.push_back(v.value());
}
}
std::sort(values.begin(), values.end());
auto res = find_terms(values, n, s);
if (res.has_value()) {
fmt::print("{}-term product = {}\n", n, res.value());
} else {
fmt::print("unable to find {}-term combination summing up to {}\n", n, s);
}
fmt::print("performance benchmark:\n");
ankerl::nanobench::Bench b;
b.run("day01", [&]() { find_terms(values, n, s); });
return 0;
}
| 24.674699 | 114 | 0.532715 | foolnotion |
41cabad12060e31d5ed6f09edb760b87ef3c172e | 4,748 | cpp | C++ | samples/sonar_SRF10_test/test.cpp | mjlsuccess/mrpt | 916c41579f91573e6c309dc67956ca808bf80fe7 | [
"BSD-3-Clause"
] | null | null | null | samples/sonar_SRF10_test/test.cpp | mjlsuccess/mrpt | 916c41579f91573e6c309dc67956ca808bf80fe7 | [
"BSD-3-Clause"
] | null | null | null | samples/sonar_SRF10_test/test.cpp | mjlsuccess/mrpt | 916c41579f91573e6c309dc67956ca808bf80fe7 | [
"BSD-3-Clause"
] | 1 | 2018-07-17T11:50:42.000Z | 2018-07-17T11:50:42.000Z | /* +------------------------------------------------------------------------+
| Mobile Robot Programming Toolkit (MRPT) |
| http://www.mrpt.org/ |
| |
| Copyright (c) 2005-2018, Individual contributors, see AUTHORS file |
| See: http://www.mrpt.org/Authors - All rights reserved. |
| Released under BSD License. See details in http://www.mrpt.org/License |
+------------------------------------------------------------------------+ */
#include <mrpt/hwdrivers/CBoardSonars.h>
#include <mrpt/system/CTicTac.h>
#include <mrpt/config/CConfigFile.h>
#include <mrpt/system/os.h>
#include <mrpt/system/filesystem.h>
#include <mrpt/gui/CDisplayWindow3D.h>
#include <mrpt/opengl/CCylinder.h>
#include <mrpt/opengl/COpenGLScene.h>
#include <mrpt/opengl/CGridPlaneXY.h>
#include <mrpt/opengl/stock_objects.h>
using namespace mrpt;
using namespace mrpt::hwdrivers;
using namespace mrpt::obs;
using namespace mrpt::gui;
using namespace mrpt::opengl;
using namespace mrpt::system;
using namespace mrpt::poses;
using namespace std;
int main()
{
try
{
CBoardSonars sonarBoard;
CObservationRange obs;
std::string firmVers;
CTicTac tictac;
CDisplayWindow3D wind("Sonar representation");
COpenGLScene::Ptr& scene = wind.get3DSceneAndLock();
scene->insert(
mrpt::make_aligned_shared<mrpt::opengl::CGridPlaneXY>(
-20, 20, -20, 20, 0, 1));
scene->insert(mrpt::opengl::stock_objects::RobotPioneer());
// scene->insert( mrpt::make_aligned_shared<mrpt::opengl::CCylinder>(1,
// 1, 2.0f)
// );
wind.unlockAccess3DScene();
// Load configuration:
ASSERT_(mrpt::system::fileExists("CONFIG_sonars.ini"));
CConfigFile conf("CONFIG_sonars.ini");
sonarBoard.loadConfig(conf, "BOARD_SONAR_CONFIG");
while (!mrpt::system::os::kbhit())
{
if (!sonarBoard.queryFirmwareVersion(firmVers))
{
cout << "Cannot connect to USB device... Retrying in 1 sec"
<< endl;
std::this_thread::sleep_for(1000ms);
}
else
{
cout << "FIRMWARE VERSION: " << firmVers << endl;
break;
}
}
cout << "Select operation:" << endl;
cout << " 1. Get measures from device" << endl;
cout << " 2. Program a new I2C address to a single sonar" << endl;
cout << "?";
char c = os::getch();
if (c == '1')
{
while (!mrpt::system::os::kbhit())
{
tictac.Tic();
if (sonarBoard.getObservation(obs))
{
double T = tictac.Tac();
mrpt::system::clearConsole();
printf(
"RX: %u ranges in %.03fms\n",
(unsigned int)obs.sensedData.size(), T * 1000);
scene = wind.get3DSceneAndLock();
for (size_t i = 0; i < obs.sensedData.size(); i++)
{
printf(
"[ID:%i]=%15f 0x%04X\n",
obs.sensedData[i].sensorID,
obs.sensedData[i].sensedDistance,
(int)(100 * obs.sensedData[i].sensedDistance));
// Show the distances
std::string obj =
format("sonar%i", obs.sensedData[i].sensorID);
mrpt::opengl::CCylinder::Ptr sonarRange;
mrpt::opengl::CRenderizable::Ptr objPtr =
scene->getByName(obj);
if (!objPtr)
{
sonarRange = mrpt::make_aligned_shared<
mrpt::opengl::CCylinder>(
0.0f, 0.0f, 1.0f, 30, 10);
sonarRange->setName(obj);
scene->insert(sonarRange);
}
else
sonarRange =
std::dynamic_pointer_cast<CCylinder>(objPtr);
sonarRange->setRadii(
0, tan(obs.sensorConeApperture) *
obs.sensedData[i].sensedDistance);
sonarRange->setPose(
mrpt::poses::CPose3D(obs.sensedData[i].sensorPose) +
CPose3D(0, 0, 0, 0, DEG2RAD(90.0), 0));
sonarRange->setHeight(obs.sensedData[i].sensedDistance);
sonarRange->enableShowName();
sonarRange->setColor(0, 0, 1, 0.25);
}
wind.unlockAccess3DScene();
wind.repaint();
}
else
{
cerr << "Error rx..." << endl;
// return -1;
}
std::this_thread::sleep_for(200ms);
}
}
else if (c == '2')
{
int curAddr, newAddr;
cout << "Enter current address: (decimal, 0 to 15)" << endl;
if (1 == scanf("%i", &curAddr))
{
cout << "Enter new address: (decimal, 0 to 15)" << endl;
if (1 == scanf("%i", &newAddr))
{
ASSERT_(curAddr >= 0 && curAddr < 16);
ASSERT_(newAddr >= 0 && newAddr < 16);
printf("Changing address %i --> %i... ", curAddr, newAddr);
if (sonarBoard.programI2CAddress(curAddr, newAddr))
printf(" DONE!\n");
else
printf(" ERROR!\n");
}
}
}
}
catch (std::exception& e)
{
cerr << e.what() << endl;
return -1;
}
return 0;
}
| 28.261905 | 80 | 0.573926 | mjlsuccess |
41cd804d89e084684a7ce3bf8ca61961b62a2c80 | 170,444 | cpp | C++ | src/worklist-ai/worklistai.cpp | ChunghaSung/intAbs | b80d842993013ca40d4900498171192bd94b2602 | [
"MIT"
] | 7 | 2018-01-18T05:04:10.000Z | 2021-02-07T02:46:48.000Z | src/worklist-ai/worklistai.cpp | sch8906/intAbs | b80d842993013ca40d4900498171192bd94b2602 | [
"MIT"
] | 1 | 2021-12-15T07:45:03.000Z | 2021-12-30T04:54:49.000Z | src/worklist-ai/worklistai.cpp | sch8906/intAbs | b80d842993013ca40d4900498171192bd94b2602 | [
"MIT"
] | 4 | 2019-11-21T19:36:12.000Z | 2022-03-30T14:07:29.000Z | /**
* Author: Chungha Sung
* This is modified version of Markus' source code of his FSE 2017 submission.
*
* Original Author: Markus Kusano
*
* LLVM pass to perform abstract interpretation (using apron)
*/
#include "llvm/Pass.h"
#include "latticefact.h"
#include "varvisit.h"
#include "bbops.h"
#include "utils.h"
#include "cartesianprod.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Function.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Analysis/PostDominators.h"
#include "llvm/Analysis/DominanceFrontier.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/IR/InstIterator.h"
#include "../utils/mk_debug.h"
#include "../utils/z3_fp_helpers.h"
#include <vector>
#include <set>
#include <map>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <algorithm>
#include <cstdint>
#include "box.h"
#include "oct.h"
#include "pk.h"
#include "pkeq.h"
//#include "ap_abstract1.h"
#include <z3.h>
#include <z3++.h>
#include <z3_api.h>
#include <z3_fixedpoint.h>
using namespace llvm;
using namespace z3_fp_helpers;
ap_manager_t *manG;
int totalPairs = 0;
int filteredPairs = 0;
// Size of Z3 bitvector sort used in fixedpoint solver
//static const unsigned Z3_BV_SIZE = sizeof(uintptr_t) * 8;
// This size needs to be able to represent all the values used in the analysis.
// Increase it as necessary. If it gets too big, things seem to get pretty
// slow.
static const unsigned Z3_BV_SIZE = 16;
// Command line flags. These are used in other files!
// priority information flag
cl::opt<bool>
usePriG("priority"
, cl::desc("Use priority information")
, cl::init(false));
cl::opt<bool>
useBoxG("box"
, cl::desc("Use box abstract domain")
, cl::init(false));
cl::opt<bool>
useOctG("oct"
, cl::desc("Use octagon abstract domain")
, cl::init(false));
cl::opt<bool>
usePolyG("pkpoly"
, cl::desc("Use (strict) convex polyhedral abstract domain")
, cl::init(false));
cl::opt<bool>
useLinEqG("pklineq"
, cl::desc("Use linear inequality abstract domain")
, cl::init(false));
cl::opt<bool>
noCombinsG("nocombs"
, cl::desc("Combine all interferences into a single state (no "
"combinational exploration")
, cl::init(false));
cl::opt<bool>
useConstraintsG("constraints"
, cl::desc("Use constraint solver to prune infreasible interferences")
, cl::init(false));
cl::opt<bool>
assertSliceG("aslice"
, cl::desc("Slice on assertion(s) (requires PDG pass)")
, cl::init(false));
cl::opt<bool>
impactG("impact"
, cl::desc("Use change-impact analysis (equires change-impact pass).")
, cl::init(false));
// When true, the state at the time of a thread's creation is used instead of
// the initial state of the entire program.
cl::opt<bool>
dynInitG("dyninit"
, cl::desc("Calculate the initial state of a thread dynamically")
, cl::init(false));
cl::opt<bool>
filterMHB("filter-mhb"
, cl::desc("Filter interferences based on global program must-happen before")
, cl::init(false));
cl::opt<bool>
tsoConstrG("tso"
, cl::desc("Use TSO interference constraints")
, cl::init(false));
cl::opt<bool>
psoConstrG("pso"
, cl::desc("Use PSO interference constraints")
, cl::init(false));
cl::opt<bool>
rmoConstrG("rmo"
, cl::desc("Use RMO interference constraints")
, cl::init(false));
// The default behavior is to attempt to constrain branches on ICMP
// instructions. For example,
//
// br %1 label %2 label %3
//
// If %1 is an icmp instruction, e.g., icmp ne %5 %6 then the branch being
// true (resp. false) not only means %1 should be 1 (resp 0) but also that %5
// != %6 (resp. %5 == %6).
//
// So, when generating a fact to pass to either the true of false branch, using
// the icmp instruction allows for more acurrate facts being passed. Obviously,
// this comes with some extra overhead.
cl::opt<bool> constrICmp("-no-icmp-constr"
, cl::desc("Do not constrain branches using ICMP predicates")
, cl::init(true));
cl::opt<std::string>
z3BinLocG("z3"
, cl::desc("Location of Z3 binary")
, cl::init(""));
// Disable debugging output in debug build
#ifdef MK_DEBUG
cl::opt<bool>
nodebugG("nodebug"
, cl::desc("Disable debug output for debug build")
, cl::init(false));
#endif
// The maximum number of combinational interference permutations
static unsigned maxCombPermsG = 0;
struct WorklistAI : public ModulePass {
static char ID;
// The type of the worklist
typedef std::map<BasicBlock*, LatticeFact> worklist_t;
static constexpr const char * const constraintFile = "poconstr.smt2";
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesAll();
if (useConstraintsG || filterMHB) {
AU.addRequired<DominatorTreeWrapperPass>();
AU.addRequired<PostDominatorTree>();
}
}
// Print the passed map to stderr
void printFactMapStderr(std::map<BasicBlock*, LatticeFact> m) const {
for (auto i = m.begin(), e = m.end(); i != e; ++i) {
BasicBlock *b = i->first;
LatticeFact f = i->second;
errs() << "BasicBlock: " << *b ;
errs() << "Facts: ";
f.fprint(stderr);
errs() << '\n';
}
}
void printValToNameStderr(const std::map<Value*, std::string> m) const {
for (auto i = m.begin(), e = m.end(); i != e; ++i) {
Value *v = i->first;
std::string s = i->second;
errs() << s << ": " << *v << '\n';
}
}
WorklistAI() : ModulePass(ID) { }
// Given a lattice fact, return a map with each BasicBlock in the module
// mapped to the passed fact.
std::map<BasicBlock*, LatticeFact> initBBs(const LatticeFact &init
, Module &M) const {
std::map<BasicBlock *, LatticeFact> ret;
for (auto mi = M.begin(), me = M.end(); mi != me; ++mi) {
for (auto fi = mi->begin(), fe = mi->end(); fi != fe; ++fi) {
BasicBlock *bb = &*fi;
ret.emplace(bb, init);
}
}
return ret;
}
// Given a lattice fact, return a map with each BasicBlock in the function
// mapped to the passed fact
std::map<BasicBlock*, LatticeFact> initBBs(const LatticeFact &init
, Function *F) const {
std::map<BasicBlock *, LatticeFact> ret;
for (auto fi = F->begin(), fe = F->end(); fi != fe; ++fi) {
BasicBlock *bb = &*fi;
ret.emplace(bb, init);
}
return ret;
}
// Merge the passed vector of new facts into the passed worklist
void merge_worklist(
std::map<BasicBlock *, LatticeFact> *wl
, std::vector<std::pair<BasicBlock*, LatticeFact>> ps) const {
//errs() << "Size of ps: " << ps.size() << "\n";
for (auto p = ps.begin(), pe = ps.end(); p != pe; ++p) {
// Check if any of the basicblock are already in worklist.
// Merge if they are.
BasicBlock *newB = p->first;
DEBUG_MSG("Merging worklist: BB: " << *newB << '\n');
auto f = wl->find(newB);
if (f == wl->end()) {
DEBUG_MSG("Fact not in list: ");
DEBUG(p->second.fprint(stderr););
DEBUG_MSG("\n");
wl->emplace(newB, p->second);
}
else {
// TODO: Widen here
LatticeFact mergeFact = LatticeFact::factJoin(f->second, p->second);
//LatticeFact mergeFact = LatticeFact::factJoinWiden(f->second, p->second);
DEBUG_MSG("Fact in list, merged: ");
DEBUG(mergeFact.fprint(stderr););
DEBUG_MSG("\n");
wl->erase(f);
wl->emplace(newB, mergeFact);
}
}
return;
}
// Given a value, return its string name.
//
// This will always return a string. If the value has never been encountered
// before, it will be stored in the valToName map with a fresh name.
//
// This also updates nameToVal so a reverse lookup can be done (see
// getValue())
std::string getName(std::map<Value *, std::string> &valToName
, std::map<std::string, Value *> &nameToVal, Value *v) const {
auto f = valToName.find(v);
if (f == valToName.end()) {
size_t newSz = valToName.size();
std::string newName = "v" + std::to_string(newSz);
auto res = valToName.insert(std::make_pair(v, newName));
if (!res.second) {
assert(0 && "item already exists in valToName map");
}
nameToVal.emplace(newName, v);
return (res.first)->second;
}
return f->second;
}
// Given a string name of a value return the actual value.
//
// Note: this will crash if the value has never been saved in the map before.
Value *getValue(const std::map<std::string, Value*> nameToVal
, std::string s) const {
auto f = nameToVal.find(s);
if (f == nameToVal.end()) {
assert(0 && "item not found in nameToVal");
}
return f->second;
}
// Return the name of all the variables used in the program
VarVisitor::Vars getAllVarNames(Module &M) const {
VarVisitor vv;
vv.visit(M);
// Also add in the float/int globals variables
for (auto gi = M.global_begin(), ge = M.global_end(); gi != ge; ++gi) {
GlobalVariable &g = *gi;
if (Utils::isIntegerGlobal(&g)) {
vv.vars.ints.push_back(&g);
}
else if (Utils::isFloatGlobal(&g)) {
vv.vars.floats.push_back(&g);
}
else {
errs() << "[WARNING] Global which is neither Integer nor Float\n";
errs() << g << '\n';
errs() << "It is not being monitored (there may be errors en route)\n";
}
}
// TODO: Need to handle arrays here
return vv.vars;
}
// Return the function named "main" or NULL if the module does not have a
// "main" function
Function *getMainFuncOrNULL(Module &M) const {
for (auto mi = M.begin(), me = M.end(); mi != me; ++mi) {
Function &f = *mi;
if (f.getName() == "main") {
return &f;
}
}
return NULL;
}
// Return any function used in a pthread_create() call.
// This will crash if any indirect functions are found
std::set<Function *> getThreads(Module &M) const {
std::set<Function *> ret;
for (auto mi = M.begin(), me = M.end(); mi != me; ++mi) {
for (auto fi = mi->begin(), fe = mi->end(); fi != fe; ++fi) {
for (auto bi = fi->begin(), be = fi->end(); bi != be; ++bi) {
Instruction *I = &*bi;
if (CallInst* ci = dyn_cast<CallInst>(I)) {
Function *called = ci->getCalledFunction();
if (called->getName() == "pthread_create") {
// Found pthread_create. The 2nd argument (zero indexed) is the
// function being called
Value *v = ci->getArgOperand(2);
if (Function *tFunc = dyn_cast<Function>(v)) {
ret.insert(tFunc);
}
else {
errs() << "[ERROR] pthread_create with non function 2nd arg\n";
errs() << *v << '\n';
exit(EXIT_FAILURE);
}
}
}
} // for (bi ... )/
} // for (fi ... )
} // for (mi ... )
return ret;
}
std::vector<CallInst *> getThreadCreate(Module &M) const {
std::vector<CallInst *> ret;
for (auto mi = M.begin(), me = M.end(); mi != me; ++mi) {
Function *cur = &*mi;
Utils::addVector(ret, getThreadCreate(cur));
}
return ret;
}
std::vector<CallInst *> getThreadCreate(Function *F) const {
std::vector<CallInst *> ret;
for (auto bi = F->begin(), be = F->end(); bi != be; ++bi) {
for (auto ii = bi->begin(), ie = bi->end(); ii != ie; ++ii) {
Instruction *I = &*ii;
if (CallInst* ci = dyn_cast<CallInst>(I)) {
Function *called = ci->getCalledFunction();
if (called->getName() == "pthread_create") {
ret.push_back(ci);
}
}
} // for (ii ...)
} // for (bi ... )/
return ret;
}
// Collect the Integer/Floating point function parameters
VarVisitor::Vars getFuncParamNames(Module &M) const {
VarVisitor::Vars vars;
for (auto mi = M.begin(), me = M.end(); mi != me; ++mi) {
Function &f = *mi;
Function::ArgumentListType &al = f.getArgumentList();
for (auto ai = al.begin(), ae = al.end(); ai != ae; ++ai) {
Argument &a = *ai;
Type *at = a.getType();
if (at->isPointerTy() || at->isIntegerTy()) {
vars.ints.push_back(&a);
}
else if (at->isFloatingPointTy()) {
vars.floats.push_back(&a);
}
else {
errs() << "[ERROR] unhandled argument type: " << a << '\n';
assert(0 && "see above");
}
}
}
return vars;
}
// Given the list of integer and floating point values return an environment
// containing them all.
//
// Returns NULL if the environment could not be created
//
// Note: The user must manage the memory of the returned environment.
ap_environment_t *createEnvironment(std::map<Value *, std::string> &valToName
, std::map<std::string, Value *> &nameToVal, Module &M) const {
// TODO: Global variables should also be assigned to variable names?
VarVisitor::Vars vs = getAllVarNames(M);
vs = VarVisitor::mergeVars(vs, getFuncParamNames(M));
DEBUG_MSG("[DEBUG] Num Int vars: " << vs.ints.size() << '\n');
DEBUG_MSG("[DEBUG] Num Float vars: " << vs.floats.size() << '\n');
// Use sets to ensure no duplicates are added to the environment
std::set<const char *> intStrs;
std::set<const char *> floatStrs;
// This will create names for the all the int and float variables in the
// program and store them in the internal maps of this class (getName())
// Put all the ints in a set
for (size_t i = 0; i < vs.ints.size(); ++i) {
Value *v = vs.ints[i];
DEBUG_MSG("[DEBUG] getting int value: " << *v << '\n');
std::string vs = getName(valToName, nameToVal, v);
DEBUG_MSG("\tname: " << vs << '\n');
intStrs.insert(vs.c_str());
}
ap_var_t intVs[intStrs.size()];
size_t pos = 0;
for (auto it = intStrs.begin(), e = intStrs.end(); it != e; ++it) {
intVs[pos++] = (ap_var_t)(*it);
}
// Put all the floats in a set
for (size_t i = 0; i < vs.floats.size(); ++i) {
Value *v = vs.floats[i];
DEBUG_MSG("[DEBUG] getting float value: " << *v << '\n');
std::string vs = getName(valToName, nameToVal, v);
DEBUG_MSG("\tname: " << vs << '\n');
floatStrs.insert(vs.c_str());
}
ap_var_t floatVs[floatStrs.size()];
pos = 0;
for (auto it = floatStrs.begin(), e = floatStrs.end(); it != e; ++it) {
floatVs[pos++] = (ap_var_t)(*it);
}
ap_environment_t *env = ap_environment_alloc(intVs
, intStrs.size()
, floatVs
, floatStrs.size());
assert(env && "error creating environment");
return env;
}
// Return a vector of functions such that the parent of any thread always
// ocurrs at a lower index than the child.
std::vector<Function *> sortByCreation(Function *main
, const std::map<Function *, std::vector<Function*>> parent2child) {
std::vector<Function *> ret;
std::deque<Function *> toProcess;
// Main is the parent of everyone
toProcess.push_back(main);
while (toProcess.size()) {
Function *curParent = toProcess.front();
toProcess.pop_front();
// Add the parent
ret.push_back(curParent);
// Add all its children to be processed
auto iter = parent2child.find(curParent);
if (iter != parent2child.end()) {
std::vector<Function *> children = iter->second;
// The children of the children also need to be added to `ret`
for (Function *c : children) {
toProcess.push_back(c);
}
}
}
assert(ret.size() && "returning size zero vector");
return ret;
}
// Given the passed lattice fact with all variables at whatever initial value
// you want (e.g., undefined (top)) this will update the passed fact
// (initFact) such that all the globals are initialized to their starting
// value (from the source code).
// This assumes that all LLVM Values are mapped to name for apron to use
// (v2v).
LatticeFact getInitState(Module *M
, const LatticeFact initFact
, const std::map<Value *, std::string> v2v) const {
LatticeFact ret = initFact;
for (auto gi = M->global_begin(), ge = M->global_end(); gi != ge; ++gi) {
// Get the initializer for the global. Lookup the name, and set the value
// of the name to the initializer
GlobalVariable *g = &*gi;
if (!g->hasInitializer()) {
errs() << "[ERROR] Global without initializer (possibly external)\n"
<< *g << '\n';
assert(0 && "see above");
}
const Constant *c = g->getInitializer();
if (const ConstantInt *ci = dyn_cast<ConstantInt>(c)) {
std::string gName = Utils::valueToStringUnsafe(v2v, g);
int val = Utils::getConstantIntUnsafe(ci);
DEBUG_MSG("[DEBUG] Initializing Global: ");
DEBUG_MSG("\tGlobal Name: " << gName << '\n');
DEBUG_MSG("\tInit Val: " << val << '\n');
ret = ret.assign(gName, val);
DEBUG(ret.fprint(stderr););
}
// TODO: also need to handle floats (ConstantFloat::getValueAPF())
//if (isFloatGlobal(g)) {
// ...
//}
else {
errs() << "[WARNING] Initializing unhandled global type: " << *g
<< "\nSetting to default initial value\n";
}
} // for
return ret;
}
// Return all the stores in the passed function
std::vector<StoreInst *> getStores(Function *f) const {
std::vector<StoreInst *> ret;
for (auto fi = f->begin(), fe = f->end(); fi != fe; ++fi) {
BasicBlock &b = *fi;
for (auto bi = b.begin(), be = b.end(); bi != be; ++bi) {
Instruction *i = &*bi;
if (StoreInst *si = dyn_cast<StoreInst>(i)) {
ret.push_back(si);
}
}
}
return ret;
}
// Return all the stores in the passed BasicBlock
std::vector<StoreInst *> getStores(BasicBlock *b) {
std::vector<StoreInst *> ret;
for (auto bi = b->begin(), be = b->end(); bi != be; ++bi) {
Instruction *i = &*bi;
if (StoreInst *si = dyn_cast<StoreInst>(i)) {
ret.push_back(si);
}
}
return ret;
}
// Return all the loads in the passed function
std::vector<Instruction *> getLoads(Function *f) const {
std::vector<Instruction *> ret;
for (auto fi = f->begin(), fe = f->end(); fi != fe; ++fi) {
BasicBlock &b = *fi;
for (auto bi = b.begin(), be = b.end(); bi != be; ++bi) {
Instruction *i = &*bi;
//if (LoadInst *si = dyn_cast<LoadInst>(i)) {
if (Utils::isSomeLoad(i)) {
ret.push_back(i);
}
}
}
return ret;
}
bool loadStoreSameVal(Instruction *si, Instruction *li) const {
if (StoreInst *s = dyn_cast<StoreInst>(si)) {
if (LoadInst *l = dyn_cast<LoadInst>(li)) {
return loadStoreSameValSL(s, l);
}
else if (AtomicRMWInst *rmw = dyn_cast<AtomicRMWInst>(li)) {
return loadStoreSameValSRMW(s, rmw);
}
else {
assert(0 && "loadStoreSameVal: unhandled load type sub StoreInst");
}
}
else if (AtomicRMWInst *rmw = dyn_cast<AtomicRMWInst>(si)) {
if (LoadInst *l = dyn_cast<LoadInst>(li)) {
return loadStoreSameValRMWL(rmw, l);
}
else if (AtomicRMWInst *rmwl = dyn_cast<AtomicRMWInst>(li)) {
return loadStoreSameValRMWRMW(rmw, rmwl);
}
else {
assert(0 && "loadStoreSameVal: unhandled load type sub atomicrmw");
}
}
else {
assert(0 && "loadStoreSameVal: unhandled store type");
}
}
bool loadStoreSameValRMWL(AtomicRMWInst *rmw, LoadInst *l) const {
Value *stPtr = rmw->getPointerOperand();
Value *lPtr = l->getPointerOperand();
return stPtr == lPtr;
}
bool loadStoreSameValRMWRMW(AtomicRMWInst *rmws, AtomicRMWInst *rmwl) const {
Value *stPtr = rmws->getPointerOperand();
Value *lPtr = rmwl->getPointerOperand();
return stPtr == lPtr;
}
bool loadStoreSameValSRMW(StoreInst *s, AtomicRMWInst *rmw) const {
Value *stPtr = s->getPointerOperand();
Value *lPtr = rmw->getPointerOperand();
return stPtr == lPtr;
}
// Return true if the passed store stores into the memory location loaded by
// the load
bool loadStoreSameValSL(StoreInst *s, LoadInst *l) const {
Value *stPtr = s->getPointerOperand();
Value *lPtr = l->getPointerOperand();
return stPtr == lPtr;
}
// Given the set of possible interferences for each load in the passed
// thread, reanalyze the thread in the presense of the interferences.
//
// The fact at the start of each basicblock after the analysis
// stabalizes is returned.
//
// This will do a combinational exploration of the possible interferences for
// each load, e,g, if l1 has two interferences i1 and i2, and l2 has two
// interferences i3 and i4, we will explore all the combinations of reading
// ((i1,i2), (i3,i4)) as well as reading from the thread's own memory state
// (i.e., at most 9 combinations).
//
// The passed vector, rErrors, will contain any reachable error statements as
// well as the reachable fact at the statement.
std::map<BasicBlock *, LatticeFact> analyzeThreadInterf(
ap_manager_t *man
, ap_environment_t *env
, Function *f
, CallInst *createSite
, const std::map<Instruction *, std::vector<Instruction *>> interfs
, const std::map<Instruction *, LatticeFact> stFacts
//, std::vector<std::pair<Instruction *, LatticeFact>> &rErrors
, std::set<Instruction *> &rErrors
, std::map<Instruction *, LatticeFact> &reachableStores
, std::map<CallInst *, LatticeFact> &reachThreadCreate
, LatticeFact entryFact
, const std::set<Instruction *> assertSlice
, const std::set<Instruction *> impacted
, const std::set<Instruction *> mayImpact
, const std::map<Value *, std::string> v2n
, z3::context &ctx
, Z3_fixedpoint &zfp
) const {
DEBUG_MSG("[DEBUG] analyzeThreadIntefer(): number of interferences: "
<< interfs.size() << '\n');
//std::cout << "Interf size: " << interfs.size() << "\n";
if (!interfs.size()) {
// When there are no interferences, we do not need to do any
// combinational exploration
return analyzeFuncNoInterf(man, env, rErrors, reachableStores
, reachThreadCreate, entryFact, assertSlice, impacted, mayImpact, v2n, f);
}
if (noCombinsG) {
// If we are not doing a combinatorial exploration, join all the
// interferences for each load into a single fact
std::map<Instruction *, LatticeFact> allInterfs
= joinInterfs(interfs, stFacts);
// Then, perform the analysis as usual but inform the transfer functions
// to consider both the interference and the state of the thread
// simultaneously
return analyzeFunc(man, env, allInterfs, rErrors, reachableStores
, reachThreadCreate, assertSlice, impacted, mayImpact, v2n, entryFact, f, true);
}
// Calculate the cartesian product of all possible facts from which a load
// can read from including its own memory state.
// To do this, consider that 0 indicates a thread should read from its own
// memory state at the time of some load while a value higher than 0 is an
// index into the vector of StoreInsts in intefers (note: it will be off by
// one (indexed starting from one))
std::vector<int> choicesPerLoad;
// Each location in choicesPerLoad corresponds to a load instruction. The
// ordering of load instructions is based on the iterator order of interfs.
for (auto i = interfs.begin(), ie = interfs.end(); i != ie; ++i) {
// Incluce one extra choice, the thread reading the value from its own
// memory environment
int v = i->second.size() + 1;
assert(v > 0 && "making zero choices");
choicesPerLoad.push_back(v);
}
// The results of each permutation will be joined into this map
std::map<BasicBlock *, LatticeFact> res;
CartesianProduct cp(choicesPerLoad);
// Test each possible combination
unsigned count = 1;
for (; !cp.AtEnd(); cp.Increment()) {
std::vector<int> curPerm = cp.permutation();
bool ret = testCurPerm(man
, env
, f
, createSite
, curPerm
, interfs
, stFacts
, rErrors
, reachableStores
, reachThreadCreate
, entryFact
, assertSlice
, impacted
, mayImpact
, v2n
, ctx
, zfp
, res);
if (ret) {
// Only increment the number of permutations if the permutation is
// tested.
maxCombPermsG = std::max(maxCombPermsG, count);
count++;
}
} // for (; !cp.AtEnd(); cp.Increment())
return res;
}
// Test the passed permutation.
//
// Returns true if the abstract interperter was run (i.e., the solver could
// not prove the permutation was redundant)
//
// any facts in res will be merged with the facts produced by the analysis
bool testCurPerm(ap_manager_t *man
, ap_environment_t *env
, Function *f
, CallInst *createSite
, const std::vector<int> perm
, const std::map<Instruction *, std::vector<Instruction *>> interfs
, const std::map<Instruction *, LatticeFact> stFacts
//, std::vector<std::pair<Instruction *, LatticeFact>> &rErrors
, std::set<Instruction *> &rErrors
, std::map<Instruction *, LatticeFact> &reachableStores
, std::map<CallInst *, LatticeFact> &reachThreadCreate
, LatticeFact entryFact
, const std::set<Instruction *> assertSlice
, const std::set<Instruction *> impacted
, const std::set<Instruction *> mayImpact
, const std::map<Value *, std::string> v2n
, z3::context &ctx
, Z3_fixedpoint &zfp
, std::map<BasicBlock *, LatticeFact> &res ) const {
assert(perm.size() == interfs.size() && "choice number mismatch");
// Note: since the store and load instructions are all orded (they are in a
// map) the results for the same map of store instructions will lead to the
// same order in the permutation vector. Additionally, the interferences
// can only grow and not decrease (everything is monotonic). So, if we see
// the same _exact_ permutation again we can use a cached result.
//
// This works because the constraints are based on the entire program
// (i.e., the constraints will always be the same for each call).
//
// This is a map from the permutation vector to the cached result
static std::map<std::vector<int>, bool> permCache;
DEBUG_MSG("Permutation: ");
DEBUG(for (int i : perm) DEBUG_MSG(i << " "););
DEBUG_MSG('\n');
std::map<Instruction *, LatticeFact> curInterfMap;
// Same as curInterfMap but maps a Load to the store it is reading from
std::map<Instruction *, Instruction *> curInterfStoreMap;
// Map from an instruction reading from the thread-local to the
// corresponding store its reading from.
std::map<Instruction *, Instruction *> curSelfStoreMap;
int pos = 0;
// Given the indices in the permutation, gather up the corresponding facts
// at the interfering stores.
for (auto i = interfs.begin(), ie = interfs.end(); i != ie; ++i, ++pos) {
int curChoice = perm[pos];
Instruction *l = i->first;
DEBUG_MSG("[DEBUG] Adding load--fact interference\n");
DEBUG_MSG("\tload: " << *l << '\n');
if (curChoice == 0) {
// Not including the load in the map indicates that it should read
// from its own memory environment
DEBUG_MSG("\tstore: self\n");
std::vector<Instruction *> ss = getPreviousStoresWithCreate(l, createSite);
if (ss.size() == 1) {
DEBUG_MSG("\tfound predecessor store:" << *(ss[0]) << '\n');
curSelfStoreMap.emplace(l, ss[0]);
}
else {
// TODO: what constraints can we deduce when there is more than one
// preceeding store?
}
continue;
}
// Indecies in the permutation are one indexed (since zero is used in
// the previous `if`)
size_t idx = curChoice - 1;
std::vector<Instruction*> sts = i->second;
assert(idx < sts.size() && "out-of-bounds choice");
Instruction *st = sts[idx];
assert(curInterfMap.find(l) == curInterfMap.end() && "duplicate load");
assert(stFacts.find(st) != stFacts.end()
&& "fact not found for store");
DEBUG_MSG("\tstore: " << *st << '\n');
curInterfMap.emplace(l, Utils::mapAtUnsafe(stFacts, st));
if (useConstraintsG) {
curInterfStoreMap.emplace(l, st);
}
} // for (auto i = interfs.begin(), ie = interfs.end(); ...)
// Check if this interference is feasible
if (useConstraintsG) {
auto it = permCache.find(perm);
DEBUG_MSG("Checking perm cache\n");
if (it != permCache.end()) {
DEBUG_MSG("[DEBUG] perm cache hit!\n");
if (it->second) {
DEBUG_MSG("\tviolates program order\n");
// return without testing, can safely skip.
return false;
}
// falling through this if brach (if (it != permCache.end())) leads
// to the permutation being tested but violatesProgOrder() will not
// be called thus saving the solver call time
}
else {
// Since we have never seen this permutation before, test if it
// violates the program order
if (violatesProgOrder(curInterfStoreMap, curSelfStoreMap, ctx, zfp)) {
DEBUG_MSG("\tpermutation violates program order\n");
DEBUG_MSG("\t*Permutation: ");
DEBUG(for (int i : perm) DEBUG_MSG(i << " "););
DEBUG_MSG('\n');
permCache[perm] = true;
// Test can be safely skipped
return false;
}
else {
DEBUG_MSG("\tpermutation does not violate prog. order\n");
DEBUG_MSG("\t*Permutation: ");
DEBUG(for (int i : perm) DEBUG_MSG(i << " "););
DEBUG_MSG('\n');
permCache[perm] = false;
}
}
}
DEBUG_MSG("running abstract interpretation\n");
// Test the thread in the presense of this round of interferences
std::map<BasicBlock *, LatticeFact> newRes
= analyzeFunc(man, env, curInterfMap, rErrors, reachableStores
, reachThreadCreate, assertSlice, impacted, mayImpact, v2n, entryFact, f, false);
DEBUG_MSG("merging AI results\n");
// Merge the new results for this combination with the old
res = mergeFactMaps(res, newRes);
return true;
}
// Return true if the load instructions reading from the passed store
// instructions violates the program order.
//
// This uses the baseConstrs and issues a solver call to muZ.
//
// rfs are extra (i1, i2) pairs where reads-from(i1, i2) will be added but
// not checked if its feasible
bool violatesProgOrder(const std::map<Instruction *, Instruction *> interfs
, const std::map<Instruction *, Instruction *> rfs
, z3::context &ctx, Z3_fixedpoint &zfp) const {
DEBUG_MSG("Checking prog order\n");
if (interfs.size() == 0) {
// Interferences can be of size zero when the thread is reading from its
// own memory environment. This will never violate the program order
DEBUG_MSG("\tinterf.size() is zero, skipping prog. order check\n");
return false;
}
// If a loads and stores is in this map then we already have the results
// (the associated value). The solver does not need to be called
std::map<std::set<Instruction*>, bool> readFromCache;
std::set<Instruction*> curInsts;
// The reads-from constraints are only valid for the current interation;
// so, save a backtracking location in the solver.
Z3_fixedpoint_push(ctx, zfp);
bool violates = false;
// Add the read-from constraints from the passed map
for (auto i = interfs.begin(), ie = interfs.end(); i != ie; ++i) {
Instruction *l = i->first;
Instruction *s = i->second;
curInsts.insert(l);
curInsts.insert(s);
addReadsFromFact(ctx, zfp, l ,s);
}
for (auto i = rfs.begin(), ie = rfs.end(); i != ie; ++i) {
Instruction *l = i->first;
Instruction *s = i->second;
addReadsFromFact(ctx, zfp, l ,s);
}
// Check for any infeasible reads-from
// Note: this needs to be run after the previous for-loop runs to
// completion so that all the reads-from constraints are added
for (auto i = interfs.begin(), ie = interfs.end(); i != ie; ++i) {
Instruction *l = i->first;
Instruction *s = i->second;
Z3_bool res = queryNotReads(ctx, zfp, l, s);
if (res == Z3_L_TRUE) {
violates = true;
// Finding one which violates is sufficient to stop
break;
}
else if (res == Z3_L_FALSE) {
violates = false;
DEBUG_MSG("No program order violation, moving to next reads-from\n");
}
else if (res == Z3_L_UNDEF) {
// Assume that it does not violate if it is unknown
errs() << "[WARNING] undef result from muZ\n";
violates = false;
}
else {
assert(0 && "unreachable");
}
}
// Restore the previous state of the solver. This removes all the
// reads-from constraints added
Z3_fixedpoint_pop(ctx, zfp);
// Update the cache
readFromCache[curInsts] = violates;
DEBUG_MSG("Program order violation? " << violates << '\n');
return violates;
}
// Return the results of a query on (not-rf l st)
Z3_bool queryNotReads(z3::context &ctx, Z3_fixedpoint &zfp, Instruction *l
, Instruction *st) const {
assert(Utils::isSomeLoad(l) && "reading from non-load");
z3::expr args[2] = {getValueBVID(ctx, l), getValueBVID(ctx, st)};
z3::expr nrfApp= getNotReadsFromFuncDecl(ctx)(2, args);
Z3_bool ret = Z3_fixedpoint_query(ctx, zfp, nrfApp);
#if 0
z3::sort bvSort = ctx.bv_sort(Z3_BV_SIZE);
z3::sort boolSort = ctx.bool_sort();
//Z3_fixedpoint_register_relation(ctx, zfp
//, Z3_get_app_decl(ctx
//, Z3_to_app(ctx, qAst)));
//Z3_ast ldID = getValueBVID(ctx, l);
//Z3_ast stID = getValueBVID(ctx, st);
z3::expr args[2] = {getValueBVID(ctx, l), getValueBVID(ctx, st)};
z3::expr nrfApp = getNotReadsFromFuncDecl(ctx)(2, args);
// Create a relation which is true if the query is true.
// The truth of the query is based off a rule
z3::expr qAst = z3::expr(ctx, Z3_mk_fresh_const(ctx, "query", boolSort));
Z3_fixedpoint_add_rule(ctx, zfp
, Z3_mk_implies(ctx, nrfApp, qAst), NULL);
Z3_bool ret = Z3_fixedpoint_query(ctx, zfp, qAst);
#endif
#ifdef MK_DEBUG
DEBUG_MSG("NRF Query Stats\n");
z3::stats sts = z3::stats(ctx, Z3_fixedpoint_get_statistics(ctx, zfp));
std::cerr << sts << '\n';
std::string rules = Z3_fixedpoint_to_string(ctx, zfp, 0, NULL);
DEBUG_MSG("Rules: " << rules << '\n';);
DEBUG_MSG("Query: " << Z3_ast_to_string(ctx, nrfApp) << '\n');
#endif
return ret;
}
// Return the results of a query on (linehigh l st)
// Result of query: 1:true, -1:false, 0:undefined
bool queryPri(z3::context &ctx, Z3_fixedpoint &zfp, Instruction *l
, Instruction *st) const {
// check nonLastSt first
z3::expr args[1] = {getValueBVID(ctx, st)};
z3::expr nonLastStApp = getNonLastStFuncDecl(ctx)(1, args);
Z3_bool nonLastRet = Z3_fixedpoint_query(ctx, zfp, nonLastStApp);
errs() << "======================================\n";
errs() << "ID of Load: " << getId(l, Z3_BV_SIZE) << "\n";
errs() << *l << "\n";
errs() << "ID of Store: " << getId(st, Z3_BV_SIZE) << "\n";
errs() << *st << "\n";
if (nonLastRet == 1) {
errs() << "St is nonLast\n";
} else {
errs() << "St is NOT nonLast\n";
}
// check complete ld
z3::expr args3[1] = {getValueBVID(ctx, l)};
z3::expr compLdApp = getCompLdFuncDecl(ctx)(1, args3);
Z3_bool compLdRet = Z3_fixedpoint_query(ctx, zfp, compLdApp);
if (compLdRet == 1) {
errs() << "Load is completeLoad\n";
} else {
errs() << "Load is not completeLoad\n";
}
if (compLdRet == 1 && nonLastRet == 1) {
errs() << "======================================\n";
return false;
}
if (compLdRet != 1 && nonLastRet != 1) {
errs() << "======================================\n";
return true;
}
// check ld-st higher
z3::expr args1[2] = {getValueBVID(ctx, l), getValueBVID(ctx, st)};
z3::expr lineHighApp = getLineHighFuncDecl(ctx)(2, args1);
Z3_bool ldStRet = Z3_fixedpoint_query(ctx, zfp, lineHighApp);
// check st-ld higher
z3::expr args2[2] = {getValueBVID(ctx, st), getValueBVID(ctx, l)};
z3::expr lineHighApp2 = getLineHighFuncDecl(ctx)(2, args2);
Z3_bool stLdRet = Z3_fixedpoint_query(ctx, zfp, lineHighApp2);
if (compLdRet != 1 && nonLastRet == 1 && ldStRet == 1) {
errs() << "ld is higher than st\n";
errs() << "======================================\n";
return true;
} else if (compLdRet !=1 && nonLastRet == 1 && ldStRet != 1) {
errs() << "ld is not higher than st\n";
errs() << "======================================\n";
return false;
} else if (compLdRet == 1 && nonLastRet != 1 && stLdRet == 1) {
errs() << "st is higher than ld\n";
errs() << "======================================\n";
return true;
} else if (compLdRet == 1 && nonLastRet != 1 && stLdRet != 1) {
errs() << "st is not higher than ld\n";
errs() << "======================================\n";
return false;
} else {
assert(0 && "There is no case for here");
}
/*
std::cout << "Priority Query Stats";
z3::stats sts = z3::stats(ctx, Z3_fixedpoint_get_statistics(ctx, zfp));
std::cerr << sts << "\n";
*/
//#ifdef MK_DEBUG
//DEBUG_MSG("Priority Query Stats\n");
//z3::stats sts = z3::stats(ctx, Z3_fixedpoint_get_statistics(ctx, zfp));
//std::cerr << sts << '\n';
//#endif
}
// Return the results of a query on (MHB l st)
Z3_bool queryMHB(z3::context &ctx, Z3_fixedpoint &zfp, Instruction *l
, Instruction *st) const {
z3::expr args[2] = {getValueBVID(ctx, l), getValueBVID(ctx, st)};
z3::expr mhbApp = getMHBFuncDecl(ctx)(2, args);
Z3_bool ret = Z3_fixedpoint_query(ctx, zfp, mhbApp);
#ifdef MK_DEBUG
DEBUG_MSG("MHB Query Stats\n");
z3::stats sts = z3::stats(ctx, Z3_fixedpoint_get_statistics(ctx, zfp));
std::cerr << sts << '\n';
#endif
return ret;
}
// Given an instruction and Value found the closest preceding store within
// the same function as the instruction to the passed Value.
//
// If there are none, returns an empty vector.
static std::vector<Instruction *> getPreviousStores(Instruction *i, Value *v) {
assert(i != NULL && "getPreviousStores(i,v): NULL instruction");
assert(v != NULL && "getPreviousStores(i,v): NULL value");
DEBUG_MSG("[DEBUG] getPreviousStores(): " << *i << ", v: " << *v << '\n');
Function *f = i->getParent()->getParent();
BasicBlock *b = i->getParent();
// Check if there is simply a store in this basicblock
Instruction *prevStore = NULL;
for (Instruction &bbi : *b) {
if (&bbi == i) {
break;
}
Value *strPtr = Utils::getStorePtr(&bbi);
if (strPtr == v) {
prevStore = &bbi;
}
}
if (prevStore != NULL) {
std::vector<Instruction *> ret;
ret.push_back(prevStore);
return ret;
}
// We know there is no store before `i` to `v` in the BasicBlock. If there
// is one it must come from some other BasicBlock.
std::map<BasicBlock *, std::set<Instruction*>> reach = getReachingStores(f);
std::set<Instruction*> bReachIn = Utils::mapAtUnsafe(reach, b);
DEBUG_MSG(" numReachingStores:" << bReachIn.size() << '\n');
// Find all the incoming stores to `v`
std::vector<Instruction*> storesToV;
for (auto it = bReachIn.begin(), et = bReachIn.end(); it != et; ++it) {
Instruction *st = *it;
assert(st != NULL && "getPreviousStores: NULL in reachable map");
Value *stPtr = Utils::getStorePtr(st);
assert(stPtr != NULL
&& "getPreviousStores: reachable store with NULL ptr operand");
if (stPtr == v) {
storesToV.push_back(st);
}
}
// storesToV contains zero or more preceeding stores
return storesToV;
//if (storesToV.size() == 0) {
// // There are no stores before `i` to `v` in the BasicBlock and there are no
// return storesToV;
//}
//else if (storesToV.size() == 1) {
// Instruction *storeIn = storesToV[0];
// assert(storeIn != NULL && "getPreviousStore: NULL reachable store");
// assert(Utils::getStorePtr(storeIn) != NULL
// && "getPreviousStore: storeIn with NULL ptr operand");
// return storeIn;
//}
//else {
// DEBUG_MSG("num reaching stores:" << storesToV.size() << '\n');
// for (size_t i = 0; i < storesToV.size(); ++i) {
// DEBUG_MSG(" " << *(storesToV[i]) << '\n');
// }
// assert(0 && "getPreviousStore: more than one reaching store");
//}
}
// CallInst is the thread_create function of `i`. Attempt to look backwards
// from i to find a previous store including looking before the thread
// creation site.
static std::vector<Instruction *> getPreviousStoresWithCreate(Instruction *i
, CallInst *cre) {
if (LoadInst *l = dyn_cast<LoadInst>(i)) {
Value *v = l->getPointerOperand();
std::vector<Instruction *> ret = getPreviousStores(i, v);
if (ret.size() > 0) {
// Found some previous store
return ret;
}
else {
// Try to look back from the creation site.
// TODO: this could continue up the thread creation chain but it doesn't
DEBUG_MSG("[DEBUG] Search searching back from creation stite for store\n");
if (cre == NULL) {
DEBUG_MSG(" NULL creation site, not searching\n");
return ret; // ret.size <= 0
}
ret = getPreviousStores(cre, v);
return ret;
}
}
else {
errs() << "[ERROR] getPreviousStoreWithCreate: unimplemented instruction type: "
<< * i << '\n';
assert(0 && "unreachable");
}
}
// Given an instruction performing a load find the closest precding store
// within the same Function. If no store is found, return NULL.
static std::vector<Instruction *> getPreviousStore(Instruction *i) {
if (LoadInst *l = dyn_cast<LoadInst>(i)) {
Value *v = l->getPointerOperand();
return getPreviousStores(i, v);
}
else {
errs() << "[ERROR] getPreviousStores: unimplemented instruction type: "
<< * i << '\n';
assert(0 && "unreachable");
}
//DEBUG_MSG("[DEBUG] getPreviousStore(): " << *l << '\n');
//Function *f = l->getParent()->getParent();
//BasicBlock *b = l->getParent();
//std::map<BasicBlock *, std::set<Instruction*>> reach = getReachingStores(f);
//std::set<Instruction*> bReachIn = Utils::mapAtUnsafe(reach, b);
//DEBUG_MSG(" numReachingStores:" << bReachIn.size() << '\n');
//if (bReachIn.size() == 0) {
// return NULL;
//}
//else if (bReachIn.size() == 1) {
// Instruction *storeIn = *(bReachIn.begin());
// assert(storeIn != NULL && "getPreviousStore: NULL reachable store");
// assert(Utils::getStorePtr(storeIn) != NULL
// && "getPreviousStore: storeIn with NULL ptr operand");
// // Check for any killing stores before l
// for (Instruction &bbi : *(l->getParent())) {
// if (&bbi == l) {
// // Reached the target instruction
// break;
// }
// Value *strPtr = Utils::getStorePtr(&bbi);
// if (strPtr != NULL && strPtr == Utils::getStorePtr(storeIn)) {
// // strPtr kills in incoming store
// storeIn = &bbi;
// }
// }
// return storeIn;
//}
//else {
// assert(0 && "getPreviousStore: more than one reaching store");
//}
}
// Return all the store instructions which reach the entry of each basicblock
// in F.
//
// Memoizes the results based on the functon address. So, this assumes the
// function is never modified.
static std::map<BasicBlock *, std::set<Instruction *>> getReachingStores(Function *f) {
static std::map<Function *, std::map<BasicBlock *, std::set<Instruction *>>> memoizer;
DEBUG_MSG("Get reaching stores:" << f->getName() << '\n');
auto memIt = memoizer.find(f);
if (memIt != memoizer.end()) {
return memIt->second;
}
// Defininitions reaching the end of a BB
std::map <BasicBlock *, std::set<Instruction *>> reachOut;
std::map <BasicBlock *, std::set<Instruction *>> reachIn;
// Definitions generated by a basicblock
std::map <BasicBlock *, std::set<Instruction *>> bb2gen;
// Variables overwritten by a basicblock
std::map <BasicBlock *, std::set<Value *>> bb2rem;
// Initialze all the maps
for (BasicBlock &B : *f) {
bb2gen[&B] = getGen(&B);
bb2rem[&B] = getRemVars(&B);
reachOut[&B] = std::set<Instruction*>();
}
bool updated = true;
while (updated) {
updated = false;
for (BasicBlock &B : *f) {
std::set<Instruction *> curGen = Utils::mapAtUnsafe(bb2gen, &B);
std::set<Value *> curRem = Utils::mapAtUnsafe(bb2rem, &B);
// The definitions reaching the input to this block is the union of the
// output of the predecessors. Iterate over all the preds and find this
// union.
std::set<Instruction*> curReach;
for (auto it = pred_begin(&B), et = pred_end(&B); it != et; ++it) {
BasicBlock *pred = *it;
std::set<Instruction *> predReachOut = Utils::mapAtUnsafe(reachOut, pred);
curReach.insert(predReachOut.begin(), predReachOut.end());
}
reachIn[&B] = curReach;
// Remove all those things which were killed
for (Value *v : curRem) {
for (auto it = curReach.begin(), et = curReach.end(); it != et; ++it) {
Instruction *curSt = *it;
Value *stPtr = Utils::getStorePtr(curSt);
assert(stPtr != NULL && "reaching store with NULL pointer arg");
if (v == stPtr) {
curReach.erase(it);
}
}
}
// Add all those things generated
curReach.insert(curGen.begin(), curGen.end());
std::set<Instruction*> oldReach = Utils::mapAtUnsafe(reachOut, &B);
if (curReach.size() > oldReach.size()) {
updated = true;
reachOut[&B] = curReach;
}
}
} // while (updated)
memoizer[f] = reachIn;
return reachIn;
}
// Get those stores created in the B
static std::set<Instruction *> getGen(BasicBlock *B) {
// A map keeping track of which values already have stores associated with
// them.
std::map<Value *, Instruction *> valToSt;
// Assumption: the for loop below goes in order
for (Instruction &i : *B) {
Value *stPtr = Utils::getStorePtr(&i);
if (stPtr != NULL) {
// Only maintain the most recent store to each value
valToSt[stPtr] = &i;
}
}
// Flatten the map to a set
std::set<Instruction*> ret;
for (auto it = valToSt.begin(), et = valToSt.end(); it != et; ++it) {
ret.insert(it->second);
}
return ret;
}
static std::set<Value *> getRemVars(BasicBlock *B) {
std::set<Value *> ret;
for (Instruction &i : *B) {
if (Utils::isSomeStore(&i)) {
Value *p = Utils::getStorePtr(&i);
assert(p != NULL && "getKilledVars: store w/o ptr operand");
ret.insert(p);
}
}
return ret;
}
// Return a read-from rule using the two passed strings. Also returns a query
// if the read is satisfiable (check if not-rf is SAT)
static std::string getReadFromRuleAndQuery(const std::string loader
, const std::string storer) {
std::string ret = "";
ret += "(rule (rf " + loader + " " + storer + "))\n";
ret += "(query (not-rf " + loader + " " + storer + "))";
return ret;
}
// Merge the contents of m1 with m2. If they both have Facts for the same
// LatticeFact, the facts will be joined ("unioned") together
std::map<BasicBlock *, LatticeFact> mergeFactMaps(
const std::map<BasicBlock *, LatticeFact> m1
, const std::map<BasicBlock *, LatticeFact> m2) const {
// First, make return contain everything in m1
std::map<BasicBlock *, LatticeFact> ret = m1;
// Then, merge everything in m2 with the return
for (auto i = m2.begin(), ie = m2.end(); i != ie; ++i) {
BasicBlock *b = i->first;
LatticeFact f = i->second;
auto it = ret.find(b);
if (it == ret.end()) {
// Not found in ret , no need to join
ret.emplace(b, f);
}
else {
// Join the two facts
LatticeFact otherF = it->second;
LatticeFact joinedF = LatticeFact::factJoin(f, otherF);
ret.erase(b);
ret.emplace(b, joinedF);
}
}
return ret;
}
// Helper function for analyzeThreadInterf().
// Collapses the map from functions to maps of storeinsts to facts to a map
// from storeinsts to lattice facts. Then calls the function performing the
// analysis.
// This merge can be done because each store instruction is unique.
std::map<BasicBlock *, LatticeFact> analyzeThreadInterf(
ap_manager_t *man
, ap_environment_t *env
, Function *f
, CallInst *createSite
, const std::map<Instruction *, std::vector<Instruction *>> interfs
, const std::map<Function *, std::map<Instruction *, LatticeFact>> fInterfs
//, std::vector<std::pair<Instruction *, LatticeFact>> &rErrors
, std::set<Instruction *> &rErrors
, std::map<Instruction *, LatticeFact> &reachableStores
, std::map<CallInst *, LatticeFact> &reachThreadCreate
, LatticeFact entryFact
, const std::set<Instruction *> assertSlice
, const std::set<Instruction *> impacted
, const std::set<Instruction *> mayImpact
, const std::map<Value *, std::string> v2n
, z3::context &ctx
, Z3_fixedpoint &zfp
) {
DEBUG_MSG("[DEBUG] Printing interference map\n");
DEBUG(printFuncInterfMap(fInterfs););
std::map<Instruction *, LatticeFact> storeToInterf = flattenReachStores(fInterfs);
return analyzeThreadInterf(man, env, f, createSite, interfs, storeToInterf, rErrors
, reachableStores, reachThreadCreate, entryFact, assertSlice, impacted, mayImpact
, v2n, ctx, zfp);
}
// Given a set of interferences from all threads, i.e., that generated on the
// current iteration of the analysis, return a map from each load instruction
// in the passed function to a vector of StoreInsts it could read from
//
// In other words, map each load instruction within the passed function
// (thread) to every store instruction to the same variable from other
// threads
//
// Note: The LatticeFacts in the inner map of interfs is not actually used
// (i.e., interfs could be a map from functions to lists of storeinsts).
//
// TODO: This cannot handle the same function interfering with itself (i.e.,
// multiple threads executing the same function)
std::map<Instruction *, std::vector<Instruction*>> getInterferingStores(
Function *f
, const std::map<Function *, std::map<Instruction *, LatticeFact>> rStores
, const std::map<Value *, std::string> v2n
) const {
DEBUG_MSG("[DEBUG] Getting interfering stores for function: "
<< f->getName() << '\n');
std::map<Instruction *, std::vector<Instruction*>> ret;
for (auto i = rStores.begin(), ie = rStores.end(); i != ie; ++i) {
Function *otherF = i->first;
if (otherF == f) {
// A function cannot interfere with itself (the only case where this
// can happen is for unbounded thread instances)
continue;
}
std::map<Instruction *, LatticeFact> currStores = i->second;
std::vector<Instruction *> fLoads = getLoads(f);
for (Instruction *l : fLoads) {
// For each load, find all the stores in the current thread and get
// the interfering fact
for (auto j = currStores.begin(), je = currStores.end()
; j != je; ++j) {
Instruction *s = j->first;
if (loadStoreSameVal(s, l)) {
DEBUG_MSG("Found intefering store: " << *s << "\nt" << *l << '\n');
Utils::mapInsertToVector(ret, l, s);
//LatticeFact sFact = j->second;
//mapInsertToVector(ret, l, sFact);
}
}
}
} // for (auto ii = rStores.begin() ... )
return ret;
}
// Given a map of loads to their corresponding interfering stores, remove
// those stores which have lower priority than loads
std::map<Instruction*, std::vector<Instruction *>> filterPriInterfs(
z3::context &ctx
, Z3_fixedpoint &zfp
, std::map<Instruction *, std::vector<Instruction *>> interfs) const {
static std::map<std::pair<Instruction*, Instruction*>, Z3_bool> cache;
DEBUG_MSG("Filtering Priority Interferences\n");
// Map from a Load to the vector of interfering stores
std::map<Instruction *, std::vector<Instruction *>> ret;
#ifdef MK_DEBUG
if (interfs.size() == 0) {
DEBUG_MSG("No interferences to filter\n");
}
#endif
for (auto it = interfs.begin(); it != interfs.end(); ++it) {
Instruction *curL = it->first;
std::vector<Instruction *> stores = it->second;
// Pass only stores which have higher priority
std::vector<Instruction *> lInterfs;
// Issue a query for every load--store pair
for (Instruction *st : stores) {
// Use cached query result if possible
bool queryResult;
auto cacheIt = cache.find(std::make_pair(curL, st));
if (cacheIt == cache.end()) {
DEBUG_MSG("Priority filter cache miss\n");
//errs() << "Priority filter cache miss\n";
// never seen this pair before
queryResult = queryPri(ctx, zfp, curL, st);
cache[std::make_pair(curL, st)] = queryResult;
} else {
DEBUG_MSG("Priority filter cache hit\n");
//errs() << "Priority filter cache hit\n";
queryResult = cacheIt->second;
}
totalPairs ++;
if (queryResult) {
// if query is true than it is valid pair
lInterfs.push_back(st);
} else {
filteredPairs ++;
/*
errs() << "Infeasible load--store from MHB\n";
errs() << "Load: " << *curL << '\n';
errs() << "Load Function: " << curL->getParent()->getParent()->getName() << '\n';
errs() << "Store: " << *st << '\n';
errs() << "Store Function: " << st->getParent()->getParent()->getName() << '\n';
*/
DEBUG_MSG("Infeasible load--store from Prioirity\n");
DEBUG_MSG("Load: " << *curL << '\n');
DEBUG_MSG("Load Function: " << curL->getParent()->getParent()->getName() << '\n');
DEBUG_MSG("Store: " << *st << '\n');
DEBUG_MSG("Store Function: " << st->getParent()->getParent()->getName() << '\n');
}
}
assert(lInterfs.size() <= stores.size());
#ifdef MK_DEBUG
if (lInterfs.size() < stores.size()) {
DEBUG_MSG("Pruned interferences via priority: "
<< stores.size() - lInterfs.size() << '\n');
} else {
DEBUG_MSG("No interferences pruned via priority\n");
}
#endif
ret[curL] = lInterfs;
}
return ret;
}
// Given a map of loads to their corresponding interfering stores, remove
// those stores which must-happen-after the load. These can be removed since
// the effect of the store cannot travel backwards in time. These removals
// are valid over all interference permutations
std::map<Instruction *, std::vector<Instruction *>> filterMHBInterfs(
z3::context &ctx
, Z3_fixedpoint &zfp
, std::map<Instruction *, std::vector<Instruction *>> interfs) const {
// Only need to ever check MHB once per load-store pair
static std::map<std::pair<Instruction*, Instruction*>, Z3_bool> cache;
DEBUG_MSG("Filtering MHB Interferences\n");
// Map from a Load to the vector of interfering stores
std::map<Instruction *, std::vector<Instruction *>> ret;
#ifdef MK_DEBUG
if (interfs.size() == 0) {
DEBUG_MSG("No interferences to filter\n");
}
#endif
for (auto it = interfs.begin(); it != interfs.end(); ++it) {
Instruction *curL = it->first;
std::vector<Instruction *> stores = it->second;
// Interfering stores which do not violate MHB. Will be populated in the
// for-loop below
std::vector<Instruction *> lInterfs;
// Issue a query for every load--store pair
for (Instruction *st : stores) {
// Use cached query result if possible
Z3_bool queryResult;
auto cacheIt = cache.find(std::make_pair(curL, st));
if (cacheIt == cache.end()) {
DEBUG_MSG("MHB filter cache miss\n");
// never seen this pair before
queryResult = queryMHB(ctx, zfp, curL, st);
cache[std::make_pair(curL, st)] = queryResult;
}
else {
DEBUG_MSG("MHB filter cache hit\n");
queryResult = cacheIt->second;
}
if (queryResult == Z3_L_FALSE || queryResult == Z3_L_UNDEF) {
// either l may-not-happen before st, or unknown. In both cases,
// conservatively assume that the load can read from the store
lInterfs.push_back(st);
}
else {
DEBUG_MSG("Infeasible load--store from MHB\n");
DEBUG_MSG("Load: " << *curL << '\n');
DEBUG_MSG("Load Function: " << curL->getParent()->getParent()->getName() << '\n');
DEBUG_MSG("Store: " << *st << '\n');
DEBUG_MSG("Store Function: " << st->getParent()->getParent()->getName() << '\n');
}
}
assert(lInterfs.size() <= stores.size());
#ifdef MK_DEBUG
if (lInterfs.size() < stores.size()) {
DEBUG_MSG("Pruned interferences via MHB: "
<< stores.size() - lInterfs.size() << '\n');
}
else {
DEBUG_MSG("No interferences pruned via MHB\n");
}
#endif
ret[curL] = lInterfs;
}
return ret;
}
// Combine the inner map of the passed across all functions.
std::map<Instruction *, LatticeFact> flattenReachStores(
const std::map<Function *, std::map<Instruction *, LatticeFact>> reachStrs
) {
std::map<Instruction *, LatticeFact> facts;
for (auto i = reachStrs.begin(), ie = reachStrs.end(); i != ie; ++i) {
std::map<Instruction *, LatticeFact> cur = i->second;
for (auto j = cur.begin(), je = cur.end(); j != je; ++j) {
Instruction *s = j->first;
// Assumption: Store instructions are unique
assert(facts.find(s) == facts.end() && "duplicate store");
facts.emplace(s, j->second);
}
}
return facts;
}
// Return true if every fact for every storeinst in new is contained in old
bool stableStores(
const std::map<Function *, std::map<Instruction *, LatticeFact>> oldI
, std::map<Function *, std::map<Instruction *, LatticeFact>> newI) {
// Since the store instructions are unique (not shared across threads).
// we can flatten the results and just work on the combined inner maps
std::map<Instruction *, LatticeFact> flatOld = flattenReachStores(oldI);
std::map<Instruction *, LatticeFact> flatNew = flattenReachStores(newI);
// Check if every fact in new is in old
for (auto ni = flatNew.begin(), ne = flatNew.end(); ni != ne; ++ni) {
Instruction *s = ni->first;
LatticeFact newF = ni->second;
auto oi = flatOld.find(s);
if (oi == flatOld.end()) {
// This means the store was not even reachable in the prior execution
// (but, it was reachable in this execution). So, we can stop now since
// we have a completely new fact created in new
assert(!newF.isBottom() && "reachable bottom fact");
DEBUG_MSG("stableStores(): new fact not in old, returning false\n");
return false;
}
// Compare the old and new facts
else {
LatticeFact oldF = oi->second;
// If the new fact is definitely larger (strictly greater than) than
// the old one, we can stop
if (!LatticeFact::areValsEq(newF, oldF)
&& LatticeFact::areValsGEq(newF, oldF)) {
return false;
}
}
}
// At this point, we know none of the new facts are *definitively* larger
// than the old facts. areValsGEq will return false either in the case of
// "no" or "don't know"
// TODO: What to do in this case? return true?
return true;
}
// Convience wrapper to analyze a function in the presense of no inteferences
std::map<BasicBlock *, LatticeFact> analyzeFuncNoInterf(ap_manager_t *man
, ap_environment_t *env
//, std::vector<std::pair<Instruction *, LatticeFact>> &rErrors
, std::set<Instruction *> &rErrors
, std::map<Instruction *, LatticeFact> &reachableStores
, std::map<CallInst *, LatticeFact> &reachThreadCreate
, LatticeFact entryFact
, const std::set<Instruction *> assertSlice
, const std::set<Instruction *> impacted
, const std::set<Instruction *> mayImpact
, const std::map<Value *, std::string> &valToName
, Function *f) const {
std::map<Instruction *, LatticeFact> empty;
return analyzeFunc(man, env, empty, rErrors, reachableStores
, reachThreadCreate, assertSlice, impacted, mayImpact
, valToName, entryFact, f, false);
}
// Analyze the passed function. Returns a map from each basicblock in the
// function to the stabalized facts at the begining of the block.
//
// The passed manager and environment are assumed to be initialized. The
// environment should at least include every variable in the passed map from
// LLVM Values to Apron names.
//
// The passed vector, rErrors, will be updated with any reachable errors
// states and the fact reaching the statement.
//
// If mergeInterfs is true, then the analysis will simultaneously consider
// both any interfering memory state and the state within the thread. This
// means, on any load of `x` both the value within the thread for `x` and the
// value of `x` in the interference are loaded.
std::map<BasicBlock *, LatticeFact> analyzeFunc(ap_manager_t *man
, ap_environment_t *env
, const std::map<Instruction *, LatticeFact> interf
//, std::vector<std::pair<Instruction*, LatticeFact>> &rErrors
, std::set<Instruction*> &rErrors
, std::map<Instruction *, LatticeFact> &reachableStores
, std::map<CallInst *, LatticeFact> &reachThreadCreate
, const std::set<Instruction *> assertSlice
, const std::set<Instruction *> impacted
, const std::set<Instruction *> mayImpact
, const std::map<Value *, std::string> &valToName
, LatticeFact entryFact
, Function *f
, bool mergeInterfs) const {
assert(f && "analyzeFunc: null passed");
if (f->begin() == f->end()) {
errs() << "[ERROR] function has no body\n";
exit(EXIT_FAILURE);
}
// The worklist. It is a map from a basicblock to the new facts reaching
// the block. A map is used so that if multiple predecessors of a
// basicblock add items to the worklist they can be met. In this way, the
// predecessors of a BasicBlock do not need to be explicitly found.
std::map<BasicBlock *, LatticeFact> worklist;
// Bottom and top facts used in initialization
ap_abstract1_t factBot = ap_abstract1_bottom(man, env);
ap_abstract1_t factTop = ap_abstract1_top(man, env);
LatticeFact latBot = LatticeFact(&factBot);
LatticeFact latTop = LatticeFact(&factTop);
// The current state of the analysis.
// This is the facts at the begining of each basicblock.
// If a key is not in the map it is assumed to be an error.
// The initial state is passed by the user
std::map<BasicBlock *, LatticeFact> analState = initBBs(latBot, f);
//Module *M = f->getParent();
//LatticeFact initFact = getInitState(M, latTop, valToName);
// get the first basic block
BasicBlock &firstBb = *(f->begin());
worklist.emplace(&firstBb, entryFact);
while (worklist.size()) {
try {
DEBUG_MSG("New worklist iteration, size: "
<< worklist.size() << '\n');
// Iterator to first item in the list
auto it = worklist.begin();
auto cur = *it;
worklist.erase(it);
BasicBlock *curBb = cur.first;
LatticeFact newFact = cur.second;
DEBUG_MSG("[DEBUG] analyzing block: " << *curBb << '\n');
LatticeFact oldFact = analState.at(curBb);
DEBUG_MSG(" Incomming Fact: ");
DEBUG(newFact.fprint(stderr););
DEBUG_MSG(" Old Fact: ");
DEBUG(oldFact.fprint(stderr););
DEBUG_MSG(" new leq old? " << newFact.leq(oldFact) << '\n');
// If the new fact is the same size or smaller than the old one
// then we can stop.
// It should never really be smaller (assuming the transfer
// functions are monotonicly increasing).
if (newFact.leq(oldFact)) {
continue;
}
// If the new fact is bigger, save it in the analysis state
// Note: the end fact of each block is not saved
// (but, it can be recovered by just running the
// transfer function over the input fact)
analState.erase(curBb);
analState.emplace(curBb, newFact);
std::vector<std::pair<BasicBlock*, LatticeFact> > outFacts
= BBOps::run_transfer_funcs(curBb, newFact, interf, rErrors
, reachableStores, reachThreadCreate, assertSlice
, impacted, mayImpact, valToName, noCombinsG);
// Combine the outfacts of the just analyzed block with any in the
// worklist
//worklist = merge_worklist(worklist, outFacts);
merge_worklist(&worklist, outFacts);
}
catch (const std::out_of_range &oor) {
errs() << "[ERROR] item not found in analysis state\n";
assert(0 && "see above");
exit(EXIT_FAILURE);
}
}
// Cleanup the initial abstract value
ap_abstract1_clear(man, &factBot);
ap_abstract1_clear(man, &factTop);
return analState;
}
// Add the "dom" relation and it's transitive property.
void addDomRel(z3::context &ctx, Z3_fixedpoint &zfp) {
// Create dominance relation
z3::func_decl domDecl = getDomFuncDecl(ctx);
Z3_fixedpoint_register_relation(ctx, zfp, domDecl);
// Create post-dominance relation
z3::func_decl postDomDecl = getPostDomFuncDecl(ctx);
Z3_fixedpoint_register_relation(ctx, zfp, postDomDecl);
addTransRuleBVBV(ctx, zfp, domDecl, Z3_BV_SIZE);
addTransRuleBVBV(ctx, zfp, postDomDecl, Z3_BV_SIZE);
}
// And relations indicating a certain instruction is either a load or store
void addLoadStoreRels(z3::context &ctx, Z3_fixedpoint &zfp) {
// Store relation: (st s v): store s loads value v
z3::func_decl stDecl = getStFuncDecl(ctx);
Z3_fixedpoint_register_relation(ctx, zfp, stDecl);
// Load relation
z3::func_decl ldDecl = getLdFuncDecl(ctx);
Z3_fixedpoint_register_relation(ctx, zfp, ldDecl);
}
// Add MHB relation
void addMHBRel(z3::context &ctx, Z3_fixedpoint &zfp) {
z3::func_decl mhbDecl = getMHBFuncDecl(ctx);
Z3_fixedpoint_register_relation(ctx, zfp, mhbDecl);
}
// Add fence relation
void addFenceRel(z3::context &ctx, Z3_fixedpoint &zfp) {
z3::func_decl fenceDecl = getFenceFuncDecl(ctx);
Z3_fixedpoint_register_relation(ctx, zfp, fenceDecl);
}
void addLwSyncRel(z3::context &ctx, Z3_fixedpoint &zfp) {
z3::func_decl fenceDecl = getFenceFuncDecl(ctx);
Z3_fixedpoint_register_relation(ctx, zfp, fenceDecl);
}
// Add not-reach relation
void addNotReachRel(z3::context &ctx, Z3_fixedpoint &zfp) {
z3::func_decl nreachRel = getNotReachFuncDecl(ctx);
Z3_fixedpoint_register_relation(ctx, zfp, nreachRel);
}
void addReadsFromRel(z3::context &ctx, Z3_fixedpoint &zfp) {
z3::func_decl rf = getReadsFromFuncDecl(ctx);
Z3_fixedpoint_register_relation(ctx, zfp, rf);
}
void addNoReorderRel(z3::context &ctx, Z3_fixedpoint &zfp) {
z3::func_decl no = getNoReorderFuncDecl(ctx);
Z3_fixedpoint_register_relation(ctx, zfp, no);
}
void addNotReadsFromRel(z3::context &ctx, Z3_fixedpoint &zfp) {
z3::func_decl nrf = getNotReadsFromFuncDecl(ctx);
Z3_fixedpoint_register_relation(ctx, zfp, nrf);
}
// Add MHB edges from creation site to child
//
// Currently, this requires that all the pthread_create sites have explicit
// function arguments.
void addCreateFacts(Module &M, z3::context &ctx, Z3_fixedpoint &zfp) {
for (Function &F : M) {
for (BasicBlock &B : F) {
for (Instruction &I : B) {
CallInst *ci = dyn_cast<CallInst>(&I);
if (ci == NULL) {
continue;
}
Function *called = ci->getCalledFunction();
if (called->getName() != "pthread_create") {
continue;
}
// Found pthread_create. The 2nd argument (zero indexed) is the
// function being called
Value *v = ci->getArgOperand(2);
if (Function *tFunc = dyn_cast<Function>(v)) {
// Make sure the function has a body
if (tFunc->empty()) {
errs() << "[WARNING] thread function without body\n";
continue;
}
// The pthread_create site must happen before the first instruction
// in the function
//addMHBFact(ctx, zfp, ci, &tFunc->front().front());
addMHBFact(ctx, zfp, ci
, getFirstLoadStoreCallTerm(&tFunc->front()));
addCreateStoreLoadFacts(ctx, zfp, ci, tFunc);
addThreadLocalNotRead(ctx, zfp, ci, tFunc);
}
else {
errs() << "[ERROR] pthread_create with non function 2nd arg\n";
errs() << *v << '\n';
exit(EXIT_FAILURE);
}
} // for (Instruction &I : B)
} // for (BasicBlock &B : F)
} // for (Function &F : M)
}
// Any store instruction which must ocurr before a thread's creation cannot
// be read by this thread.
//
// If the store before the thread's creation can propagate to the thread,
// then its value will be in the initial environment of the thread
//
// ci is assumed to be the pthread_create call creating tFunc
void addCreateStoreLoadFacts(z3::context &ctx, Z3_fixedpoint &zfp
, CallInst *ci, Function *tFunc) {
std::vector<Instruction*> lds = getLoads(tFunc);
for (Instruction *l : lds) {
addStoreCreateLoadFact(ctx, zfp, ci, l);
}
}
// Add: (=> (and (is-store s _) (mhb s ci)) (nrf s l))
void addStoreCreateLoadFact(z3::context &ctx, Z3_fixedpoint &zfp
, CallInst *ci, Instruction *l) {
assert(Utils::isSomeLoad(l));
z3::sort bvSort = ctx.bv_sort(Z3_BV_SIZE);
z3::expr s = z3::expr(ctx, Z3_mk_bound(ctx, 0, bvSort));
z3::expr v = z3::expr(ctx, Z3_mk_bound(ctx, 1, bvSort));
z3::expr ciExp = getValueBVID(ctx, ci);
z3::expr lExp = getValueBVID(ctx, l);
z3::expr args[2] = {s, v};
z3::expr isStoreS = getStFuncDecl(ctx)(2, args);
args[0] = s;
args[1] = ciExp;
z3::expr mhbSCi = getMHBFuncDecl(ctx)(2, args);
args[0] = s;
args[1] = lExp;
z3::expr nrfSL = getNotReadsFromFuncDecl(ctx)(2, args);
// (and (is-store s v) (mhb s ci))
z3::expr andSMHB = isStoreS && mhbSCi;
Z3_fixedpoint_add_rule(ctx, zfp, z3::implies(andSMHB, nrfSL), NULL);
}
// Add the "pri" and "higher" relation and it's transitive property
void addPriHighRel(z3::context &ctx, Z3_fixedpoint &zfp) {
// Create (function-decl pri (number))
z3::func_decl priDecl = getPriFuncDecl(ctx);
Z3_fixedpoint_register_relation(ctx, zfp, priDecl);
// add priority related rules
addPriRule(ctx, zfp, priDecl, Z3_BV_SIZE);
// Create (function-decl higher (number number))
z3::func_decl highDecl = getHighFuncDecl(ctx);
Z3_fixedpoint_register_relation(ctx, zfp, highDecl);
// add higher related rules
addHighRule(ctx, zfp, priDecl, highDecl, Z3_BV_SIZE);
// add higher transitive rules
addTransRuleBVBV(ctx, zfp, highDecl, Z3_BV_SIZE);
// Create (function-decl lineHigh (lineNum lineNum))
z3::func_decl lineHighDecl = getLineHighFuncDecl(ctx);
Z3_fixedpoint_register_relation(ctx, zfp, lineHighDecl);
// Create (function-decl linePri (lineNum Priority))
z3::func_decl linePriDecl = getLinePriFuncDecl(ctx);
Z3_fixedpoint_register_relation(ctx, zfp, linePriDecl);
// Build rules for linehigh inference
z3::func_decl ldDecl = getLdFuncDecl(ctx);
z3::func_decl stDecl = getStFuncDecl(ctx);
addLineHighRule(ctx, zfp, ldDecl, stDecl, highDecl, linePriDecl, lineHighDecl, Z3_BV_SIZE);
// Create (function-decl compLd (lineNum))
z3::func_decl compLdDecl = getCompLdFuncDecl(ctx);
Z3_fixedpoint_register_relation(ctx, zfp, compLdDecl);
// Create (function-decl nonLastSt (lineNum))
z3::func_decl nonLastStDecl = getNonLastStFuncDecl(ctx);
Z3_fixedpoint_register_relation(ctx, zfp, nonLastStDecl);
// Build rules for compLd and nonLastSt inferences
z3::func_decl domDecl = getDomFuncDecl(ctx);
z3::func_decl postDomDecl = getPostDomFuncDecl(ctx);
addCombRule(ctx
, zfp
, ldDecl
, stDecl
, domDecl
, postDomDecl
, compLdDecl
, nonLastStDecl
, Z3_BV_SIZE);
}
// Update the context and fixedpoint to contain dominance relation, rules,
// and facts, and also relations and facts about instructions being
// loads/stores
void addDomLoadStoreFacts(std::set<Function*> threadFuncs
, z3::context &ctx
, Z3_fixedpoint &zfp) {
addDomRel(ctx, zfp);
addLoadStoreRels(ctx, zfp);
if (usePriG) {
addPriHighRel(ctx, zfp);
}
// read priority info file and save priority information
std::map<std::string, std::string> priorityInfo;
if (usePriG) {
std::ifstream file("priority.info");
std::string line;
while(std::getline(file, line)) {
std::stringstream linestream(line);
std::string data;
std::string val1;
// read up-to the first tab (discard tab).
std::getline(linestream, data, ':');
// Read the integers using the operator >>
linestream >> val1;
//errs() << data << ":::" << val1 << "\n";
priorityInfo.insert(
std::pair<std::string, std::string> (data, val1));
}
}
for (Function *f : threadFuncs) {
unsigned priority;
if (usePriG) {
// get priority information
std::string name = f->getName();
//errs() << "function: " << name << "\n";
if (name.compare("main") == 0) {
// for the main function priority is just 1
priority = 1;
} else {
priority =
std::stoi(priorityInfo.find(f->getName().str())->second);
}
}
//DominatorTree &dt = getAnalysis<DominatorTreeWrapperPass>(*f).getDomTree();
DominatorTree dt = DominatorTree(*f);
PostDominatorTree pdt;
pdt.runOnFunction(*f);
// The first instruction of the thread may have a happens-before edge
// from the parent-thread. So, connect this first instruction (which may
// not be a load/store) to a load/store/terminator so that transitive
// orderings can be calculated
/*
Instruction *first = &f->front().front();
Instruction *lst = getFirstLoadStoreCallTerm(&f->front());
if (first != lst) {
addDomFact(ctx, zfp, first, lst);
addPostDomFact(ctx, zfp, lst, first);
}
*/
for (BasicBlock &b : *f) {
// add internal dom facts of read/write/call
// inside of each basic block
addInternalDomAndPostDomFacts(&b, ctx, zfp);
if (usePriG) {
addLoadStoreFacts(&b, ctx, zfp, priority);
} else {
addLoadStoreFacts(&b, ctx, zfp);
}
// for dominator tree
DomTreeNodeBase<BasicBlock> *bbNode = dt.getNode(&b);
if (bbNode != NULL) {
// For the dom children of `b`,
// connect the terminator of `b` to the
// first relevant (load, store, terminator) instruction
// in the child
Instruction *from = b.getTerminator();
const std::vector<DomTreeNodeBase<BasicBlock> *> &children
= bbNode->getChildren();
for (size_t i = 0; i < children.size(); ++i) {
BasicBlock *c = children[i]->getBlock();
// check assertion
Instruction *t = &(c->front());
if (CallInst *ci = dyn_cast<CallInst>(t)) {
// Chungha: This is a modification to support
// post-dominance relation for assert.
// Since assert makes branches so that the instruction
// after the branch can't post-dominate the instruction
// before the branch. Therefore, I forcely insert it.
if (ci->getCalledFunction()->getName()
== "__assert_fail") {
BasicBlock *c2 = children[i+1]->getBlock();
Instruction *postFrom
= getFirstLoadStoreCallTerm(c2);
/*
errs() << "PostFrom!!!\n";
errs() << *postFrom;
errs() << "PostTo!!!\n";
errs() << *from;
errs() << "\n";
*/
addPostDomFact(ctx, zfp, postFrom, from);
}
}
Instruction *to = getFirstLoadStoreCallTerm(c);
addDomFact(ctx, zfp, from, to);
}
}
// for post dominator tree
DomTreeNodeBase<BasicBlock> *btNode = pdt.getNode(&b);
if (btNode != NULL) {
// For the post dom children of `b`
// connect the first call/read/write of `b` to the
// last instruction in the child
Instruction *from = getFirstLoadStoreCallTerm(&b);
const std::vector<DomTreeNodeBase<BasicBlock> *> &children
= btNode->getChildren();
for (size_t i = 0; i < children.size(); ++i) {
BasicBlock *c = children[i]->getBlock();
//Instruction *to = getFirstLoadStoreCallTerm(c);
Instruction *to = c->getTerminator();
addPostDomFact(ctx, zfp, from, to);
}
}
} // for (BasicBlock &b : *f)
} // for (Function f : threadFuncs)
}
// Validate the set parameters. This will crash the program on errors
void validateParams(z3::context &ctx, Z3_fixedpoint &zfp, z3::params ¶ms) {
DEBUG_MSG("checking parameters\n");
Z3_param_descrs p_desc = Z3_fixedpoint_get_param_descrs(ctx, zfp);
Z3_param_descrs_inc_ref(ctx, p_desc);
Z3_params_validate(ctx, params, p_desc);
try {
ctx.check_error();
}
catch (z3::exception ex) {
errs() << "[ERROR] Parameter error: " << ex.msg() << '\n';
Z3_param_descrs_dec_ref(ctx, p_desc);
exit(EXIT_FAILURE);
}
Z3_param_descrs_dec_ref(ctx, p_desc);
}
// Add facts about fence instructions in the program. This also will add a
// definition of the fence relation (see addFenceRel()).
void addFenceFacts(std::set<Function*> threadFuncs
, z3::context &ctx
, Z3_fixedpoint &zfp) {
addFenceRel(ctx, zfp);
addLwSyncRel(ctx, zfp);
for (Function *f : threadFuncs) {
for (BasicBlock &b : *f) {
for (Instruction &i : b) {
if (isFence(&i)) {
addFenceFact(ctx, zfp, &i);
}
if (isLwSync(&i)) {
// TODO: how to handle lwsync
//addLwSyncFact(ctx, zfp, &i);
addFenceFact(ctx, zfp, &i);
}
}
}
}
}
// Return true if the passed instruction is a POWER lwsync
//
// An lwsync preserves everything but write--read order
bool isLwSync(Instruction *i) {
if (CallInst *ci = dyn_cast<CallInst>(i)) {
// TSO/PSO fence
if (ci->getCalledFunction()->getName() == "MLWSYNC") {
return true;
}
}
return false;
}
// Return true if the passed instruction operates as a fence or is an
// explicit fence. The programmer can add in explicit fences via a call to a
// function named MFENCE.
bool isFence(Instruction *i) {
if (CallInst *ci = dyn_cast<CallInst>(i)) {
// TSO/PSO fence
if (ci->getCalledFunction()->getName() == "MFENCE") {
return true;
}
// PPC/ARM full fence
if (ci->getCalledFunction()->getName() == "MSYNC") {
return true;
}
else {
// No other call instructions are treated as fences
return false;
}
}
else if (isa<AtomicRMWInst>(i)) {
return true;
}
else if (isa<AtomicCmpXchgInst>(i)) {
return true;
}
else {
// TODO: probably some other instructions to handle as fences
return false;
}
}
bool runOnModule(Module &M) {
manG = Utils::getManager();
ap_manager_set_abort_if_exception(manG, AP_EXC_TIMEOUT, true);
ap_manager_set_abort_if_exception(manG, AP_EXC_OUT_OF_SPACE, true);
ap_manager_set_abort_if_exception(manG, AP_EXC_OVERFLOW, true);
ap_manager_set_abort_if_exception(manG, AP_EXC_INVALID_ARGUMENT, true);
ap_manager_set_abort_if_exception(manG, AP_EXC_NOT_IMPLEMENTED, true);
ap_manager_set_abort_if_exception(manG, AP_EXC_SIZE, true);
// Maps from a Value to a name and vice-versa.
//
// These are used since Apron requires variables to have names
std::map<Value *, std::string> valToName;
std::map<std::string, Value *> nameToVal;
DEBUG_MSG("[DEBUG] Starting WorklistAI\n");
checkCommandLineArgs();
// Initialize fixpoint solver
z3::config cfg;
//Z3_set_param_value(cfg, "DL_DEFAULT_RELATION", "smt_relation2");
z3::context ctx(cfg);
Z3_fixedpoint zfp = Z3_mk_fixedpoint(ctx);
Z3_fixedpoint_inc_ref(ctx, zfp);
z3::params params(ctx);
params.set("engine", ctx.str_symbol("datalog"));
params.set("datalog.default_table", ctx.str_symbol("hashtable"));
params.set("datalog.magic_sets_for_queries", true);
DEBUG_MSG("params:\n" << Z3_fixedpoint_get_help(ctx, zfp));
DEBUG_MSG("Set Parameters:\n");
DEBUG_MSG(Z3_params_to_string(ctx, params) << '\n');
validateParams(ctx, zfp, params);
ap_manager_t* man = Utils::getManager();
ap_environment_t *env = createEnvironment(valToName, nameToVal, M);
DEBUG(printValToNameStderr(valToName););
// Try to find the main function
Function *main = getMainFuncOrNULL(M);
if (main == NULL) {
// TODO: the user should be able to specify the entry of the analysis
errs() << "[ERROR] main function not found\n";
exit(EXIT_FAILURE);
}
// try to find any threads
std::set<Function *> threadFuncs = getThreads(M);
std::vector<CallInst *> threadSites = getThreadCreate(M);
// If there are no threads, then this is a single threaded analysis
bool noThreads = threadSites.size() == 0;
//threadFuncs.insert(main);
// This also addes priority and higher information
addDomLoadStoreFacts(threadFuncs, ctx, zfp);
addMHBRel(ctx, zfp);
if (useConstraintsG || filterMHB) {
DEBUG_MSG("adding constraints: number of threads: "
<< threadFuncs.size() << '\n');
if (tsoConstrG || psoConstrG || rmoConstrG) {
addFenceFacts(threadFuncs, ctx, zfp);
}
addCreateFacts(M, ctx, zfp);
addJoinFacts(M, ctx, zfp);
addNotReachableFacts(M, ctx, zfp);
if (tsoConstrG) {
//addTSOPruningRules(ctx, zfp);
addNoReorderRules(ctx, zfp);
addTSOReorderRules(ctx, zfp);
// TODO: is reads-from MHB?
addReadsFromIsMHB(ctx, zfp);
}
else if (psoConstrG) {
//addPSOPruningRules(ctx, zfp);
addNoReorderRules(ctx, zfp);
addPSOReorderRules(ctx, zfp);
// TODO: is reads-from MHB?
addReadsFromIsMHB(ctx, zfp);
}
else if (rmoConstrG) {
addNoReorderRules(ctx, zfp);
addRMOReorderRules(ctx, zfp);
// TODO: is reads-from MHB?
addReadsFromIsMHB(ctx, zfp);
}
else {
addPruningRules(ctx, zfp);
// TODO: is reads-from MHB?
addReadsFromIsMHB(ctx, zfp);
//addNoReorderRules(ctx, zfp);
//addSCReorderRules(ctx, zfp);
}
}
std::string rules = Z3_fixedpoint_to_string(ctx, zfp, 0, NULL);
errs() << "Rules: " << rules << '\n';
DEBUG_MSG("Rules: " << rules << '\n';);
// This is kind of a hack: NULL in threadSites indicates main (there is not
// CallSite for main)
threadSites.push_back(NULL);
// When using constraints, we start the analysis of the main thread and
// check the reachability of any thread creation sites. If any are
// reachable, then they are subsequently analyzed.
// This is a little bit roundabout since we are clearing the vectors.
if (dynInitG) {
threadFuncs.clear();
threadSites.clear();
threadFuncs.insert(main);
threadSites.push_back(NULL);
}
std::set<Instruction *> assertSlice = getAssertSliceInvIfEnabled(M);
std::set<Instruction *> impacted = getImpactedIfEnabled(M);
std::set<Instruction *> mayImpact = getMayImpactIfEnabled(M);
// Vector containing reachable error states
//std::vector<std::pair<Instruction *, LatticeFact>> rErrors;
std::set<Instruction *> rErrors;
// Repeatedly analyze the main function and any threads until the
// interferences (facts at stores in threads) stabalize
std::map<Function *, std::map<Instruction *, LatticeFact>> allReachStores;
// Map from a Function (thread) to a map from each of its Loads to the
// vector of all interfering store instructions from other threads.
std::map<Function *, std::map<Instruction *, std::vector<Instruction *>>> interfs;
std::map<Function *, std::map<BasicBlock *, LatticeFact>> threadRes;
// The inital state of the thread being analyzed
ap_abstract1_t factTop = ap_abstract1_top(man, env);
LatticeFact latTop = LatticeFact(&factTop);
LatticeFact progInitState = getInitState(&M, latTop, valToName);
ap_abstract1_clear(man, &factTop);
// A map saving the entry fact for a thread. This is only used when
// dynamic thread initialization in enabled
std::map<CallInst *, LatticeFact> threadEntryFacts;
bool stable;
size_t iter = 1;
do {
errs() << "Interference Iteration: " << iter << '\n';
// The reachable stores for this round of the analysis.
// We save this in a new map so we can compare it with
// the results of the previous analysis (allReachStores).
// If the facts stabalize, then we can stop.
std::map<Function *, std::map<Instruction *, LatticeFact>> newReachStores = allReachStores;
// This deque contains the thread functions which still need to be
// processed for this interference iteration. A deque is used because
// when constraints are used the threads are processed as they are
// reached. In other words, the threads to processed is increasing if a
// new thread creation site is reached
std::deque<CallInst *> threadsToProcess;
// Note: when dynInitG is enabled then threadSites only contains main.
// This means that each iteration starts analyzing main
// and then analyzes the children of main recursively.
threadsToProcess.insert(threadsToProcess.end(), threadSites.begin()
, threadSites.end());
assert(threadsToProcess.size() == threadSites.size());
size_t tCount = 0; // only here for output
while (threadsToProcess.size()) {
errs() << "Analyzing thread: " << tCount++ << '\n';
// ci is the CallInst of the pthread_create() creating the thread.
CallInst *ci = threadsToProcess.front();
threadsToProcess.pop_front();
Function *f = NULL;
if (ci == NULL) {
// NULL is a special callsite indicating main
f = main;
} else {
f = getPThreadThreadFunc(ci);
}
LatticeFact entryFact = progInitState;
#if 0
if (dynInitG) {
// If we are dynamically calculating the entry state of
// each thread, then we retrieve the entry fact here.
// Otherwise, the entry fact is simply initialized to be
// the initial state of the program
if (ci != NULL) {
entryFact = Utils::mapAtUnsafe(threadEntryFacts, ci);
}
}
#endif
// Subset of all interferences.
// Only those which could affect this thread.
std::map<Instruction *, std::vector<Instruction *>> curFInterf = interfs[f];
curFInterf = filterMHBInterfs(ctx, zfp, curFInterf);
if (usePriG) {
curFInterf = filterPriInterfs(ctx, zfp, curFInterf);
}
// A map of reachable thread creations in `f`.
// This is used to determine other threads which should be analyzed
std::map<CallInst *, LatticeFact> reachThreadCreate;
// Analyze function in the presense of interferences
std::map<Instruction *, LatticeFact> newStores;
std::map<BasicBlock *, LatticeFact> res = analyzeThreadInterf(man
, env
, f
, ci
, curFInterf
, newReachStores
, rErrors
, newStores
, reachThreadCreate
, entryFact
, assertSlice
, impacted
, mayImpact
, valToName
, ctx
, zfp);
threadRes[f] = res;
// Save the reachable stores for this iteration. We can erase all the
// old ones since the reachable stores are monotonic (on iteration i+1
// we at least reach all the stores of iteration i)
auto fit = newReachStores.find(f);
if (fit != newReachStores.end()) {
newReachStores.erase(fit);
}
newReachStores.emplace(f, newStores);
#if 0
if (dynInitG) {
// When calculating the initial state dynamically, we are calculating
// the threads to explore on-the-fly. Any reachable pthread_create
// call at this point needs to be analyzed during this iteration.
// Note: the facts at each callinstruction are "forgotten" on each
// iteration. However, the facts at the callsites are increasing
// (potentially) since the interferences on the stores are
// increasing.
for (auto rci = reachThreadCreate.begin()
, rce = reachThreadCreate.end(); rci != rce; ++ rci) {
// Get the entry fact for the thread
CallInst *curCall = rci->first;
LatticeFact callFact = rci->second;
Function *thrdFunc = getPThreadThreadFunc(curCall);
DEBUG_MSG("[DEBUG] Found new thread: " << thrdFunc->getName()
<< '\n');
// This function is now saved as being one of the threads we are
// analyzing
threadFuncs.insert(thrdFunc);
// Add the most recent fact to the entry point. Note: we do not
// support threads executing the same function
auto old = threadEntryFacts.find(curCall);
if (old != threadEntryFacts.end()) {
threadEntryFacts.erase(old);
}
threadEntryFacts.emplace(curCall, callFact);
// Add the thread to be processed
threadsToProcess.push_back(curCall);
}
}
#endif
}
// If there are no threads, even if the main() thread has interferences
// they will not do anything since main does not interfer with itself
// (the analysis will finish after a useless 2nd iteration)
if (noThreads) {
break;
}
stable = stableStores(allReachStores, newReachStores);
DEBUG_MSG("Iteration " << iter << ":\n");
DEBUG_MSG("Previous reachable stores:\n");
DEBUG(printStoreFacts(allReachStores););
DEBUG_MSG("\nNew reachable stores:\n");
DEBUG(printStoreFacts(newReachStores););
// Setup the data for the next iteration. This only needs to be done if
// the results have not yet stabalized.
// We calculate the new interferences and save the reachable facts at
// store instructions
if (!stable) {
// Calculate the interferences to be used for each thread
// to be used in the next round of the analysis.
// This uses the reachable stores caluclated for each thread
// in the previous for-loop.
for (Function *f : threadFuncs) {
std::map<Instruction *, std::vector<Instruction *>> interfStores;
interfStores = getInterferingStores(f, newReachStores, valToName);
// Remove those loads which are not the slice, those can read
// arbitrary values without affecting property reachability
if (assertSliceG || impactG) {
for (auto it = interfStores.begin(), ie = interfStores.end()
; it != ie; ++it) {
// assertSlice contains those statements *not*
// on the slice.
// So, if it is found in the assertSlice structure
// then the statement must not be on the slice.
// So, its interference can be removed.
// TODO: for some reason performing this removal
// causes some false alarms??
// These should be mutually exclusive so as
// not to double erase
if (assertSliceG && assertSlice.count(it->first)) {
interfStores.erase(it);
}
else if (impactG && !mayImpact.count(it->first) && !impacted.count(it->first)) {
interfStores.erase(it);
}
//else if (impactG && !impacted.count(it->first)) {
// interfStores.erase(it);
//}
}
}
interfs[f] = interfStores;
}
allReachStores = newReachStores;
}
iter++;
} while (!stable);
//std::map<BasicBlock *, LatticeFact> mainRes = threadRes[main];
//errs() << "==== Main Results ====\n";
//printFactMapStderr(mainRes);
//errs() << "======================\n";
// Print out the map from values to apron names so the results can be
// interpreted
printValToNameStderr(valToName);
for (auto i = threadRes.begin(), ie = threadRes.end(); i != ie; ++i) {
Function *f = i->first;
std::string fname = f->getName();
errs() << "==== " << fname << "() Results ====\n";
std::map<BasicBlock *, LatticeFact> res = i->second;
printFactMapStderr(res);
errs() << "======================\n";
}
z3_fp_helpers::valueCacheToMetadata(M, Z3_BV_SIZE);
// The errors are counted by the number of unique reachable error
// statements. If the statement is reachable multiple times (i.e., on
// multiple iterations) it is only counted once.
//std::set<Instruction *> errInsts;
//for (auto i : rErrors) {
// errInsts.insert(i.first);
//}
//errs() << "Errors found: " << errInsts.size() << '\n';
errs() << "Errors found: " << rErrors.size() << '\n';
errs() << "Max Permutations: " << maxCombPermsG << '\n';
errs() << "Total pairs: " << totalPairs << '\n';
errs() << "Filtered pairs: " << filteredPairs << '\n';
// cleanup the environment (Going Green (tm))
ap_environment_free(env);
// Cleanup Z3 stuff
Z3_fixedpoint_dec_ref(ctx, zfp);
// The IR was modified with metadata only, but still modified
return true;
}
// Join all the facts at the vector of stores for each load into a single
// fact
std::map<Instruction *, LatticeFact> joinInterfs(
const std::map<Instruction *, std::vector<Instruction *>> l2Ss
, const std::map<Instruction *, LatticeFact> sToF
) const {
std::map<Instruction *, LatticeFact> joined;
for (auto i = l2Ss.begin(), ie = l2Ss.end(); i != ie; ++i) {
Instruction *l = i->first;
std::vector<Instruction *> ss = i->second;
if (!ss.size()) {
continue;
}
assert(ss.size() && "load with zero interfering stores");
LatticeFact lfact = Utils::mapAtUnsafe(sToF, ss[0]);
for (size_t j = 1; j < ss.size(); ++j) {
Instruction *s = ss[j];
LatticeFact nextF = Utils::mapAtUnsafe(sToF, s);
lfact = LatticeFact::factJoin(lfact, nextF);
}
assert(joined.find(l) == joined.end() && "duplicate load");
joined.emplace(l, lfact);
}
return joined;
}
// Print the contents of the passed interference map
void printStoreFacts(
std::map<Function *, std::map<Instruction *, LatticeFact>> ints) const {
for (auto ii = ints.begin(), ie = ints.end(); ii != ie; ++ii) {
Function *f = ii->first;
errs() << "Interferences for Function: " << f->getName() << '\n';
std::map<Instruction *, LatticeFact> fInts = ii->second;
for (auto fi = fInts.begin(), fe = fInts.end(); fi != fe; ++fi) {
const Instruction *si = fi->first;
LatticeFact f = fi->second;
errs() << "\tStoreInst: " << *si << "\n\tFact: ";
f.fprint(stderr);
}
}
}
void addLoadStoreFacts(BasicBlock *b, z3::context &ctx, Z3_fixedpoint &zfp) {
for (auto i = b->begin(), ie = b->end(); i != ie; ++i) {
Instruction *cur = &*i;
if (LoadInst *l = dyn_cast<LoadInst>(cur)) {
Value *ptrOp = l->getPointerOperand();
addLoadFact(ctx, zfp, l, ptrOp);
}
else if (StoreInst *s = dyn_cast<StoreInst>(cur)) {
Value *ptrOp = s->getPointerOperand();
addStoreFact(ctx, zfp, s, ptrOp);
}
}
}
void addLoadStoreFacts(BasicBlock *b, z3::context &ctx, Z3_fixedpoint &zfp, unsigned priority) {
z3::func_decl linePriDecl = getLinePriFuncDecl(ctx);
for (auto i = b->begin(), ie = b->end(); i != ie; ++i) {
Instruction *cur = &*i;
if (LoadInst *l = dyn_cast<LoadInst>(cur)) {
Value *ptrOp = l->getPointerOperand();
addLoadFact(ctx, zfp, l, ptrOp);
// add linepri fact for each load
addLinePriFact(ctx, zfp, linePriDecl, l, priority);
} else if (StoreInst *s = dyn_cast<StoreInst>(cur)) {
Value *ptrOp = s->getPointerOperand();
addStoreFact(ctx, zfp, s, ptrOp);
// add linepri fact for each store
addLinePriFact(ctx, zfp, linePriDecl, s, priority);
}
}
}
// Search for any pthread_join calls and add must-happen-before constraints;
// see the overloaded version of this function
void addJoinFacts(Module &M, z3::context &ctx, Z3_fixedpoint &zfp) {
for (Function &F : M) {
for (BasicBlock &BB : F) {
for (Instruction &I : BB) {
CallInst *ci = dyn_cast<CallInst>(&I);
if (ci != NULL) {
if (ci->getCalledFunction()->getName() == "pthread_join") {
addJoinFacts(ci, ctx, zfp);
}
}
} // for (Instruciton ...)
} // for (BasicBlock ...)
} // for (Function ...)
}
// Search for pthread_join() calls and add the happens-before fact that the
// thread must terminate before the join.
//
// This performs the following:
// 1. Check if the instruction is a pthread_join call
// 2. Attempt to find the pthread_create call where the thread ID is used
// 3. If found, return a happens-before fact
// Otherwise, return an emptry string
//
// Note: this makes a few assumptions
// 1. The pthread_t associated with the pthread_join() was only used to
// create a thread in a single function
// 2. The pthread_create() call associated with the passed join is in the
// same function
//
// Point 1 is not explicitly enforced
void addJoinFacts(CallInst *i, z3::context &ctx, Z3_fixedpoint &zfp) {
// Find the associated thread function
assert(i->getNumOperands() >= 1 && "join without operand");
Function *thrdFunc = findCreateFromJoin(i->getOperand(0));
if (thrdFunc == NULL) {
errs() << "[WARNING] no create matching join: " << *i << '\n';
return;
}
if (thrdFunc->empty()) {
errs() << "[WARNING] empty thread function: " << thrdFunc->getName()
<< '\n';
return;
}
// Add happens-before edges from all the return sites of the function to
// the join site
std::vector<ReturnInst*> rets = getRets(thrdFunc);
assert(rets.size() && "function without returns");
for (ReturnInst *r : rets) {
// The return must happen before the join
addMHBFact(ctx, zfp, r, i);
}
}
// Given a pthread_t argument used in a join call, search the def-use chain
// to find where it is used in pthread_create. Return the thread function
// create by the pthread_create call.
//
// Returns NULL if no function was found.
//
// Note: a program actually could use the same pthread_t in multiple
// pthread_create() calls. This function returns the first one found
Function* findCreateFromJoin(Value *pt) {
assert(pt != NULL);
Instruction *i = dyn_cast<Instruction>(pt);
// This iteratively follows the defs of pt backwards until a
// pthread_create() is found
// This assumes the only things on the use-def chain are instructions
if (i != NULL) {
DEBUG_MSG("[DEBUG] Found pthread_t from instruction\n");
}
else {
errs() << "[WARNING] Unhandled pthread_t def: " << *pt << '\n';
return NULL;
}
// A vector of Values is used since, in general, the use-def chains can
// contain any value and not just instructions
std::vector<Value *> toVisit;
toVisit.push_back(i);
while (toVisit.size()) {
Instruction *i = dyn_cast<Instruction>(toVisit.back());
toVisit.pop_back();
if (i == NULL) {
errs() << "[ERROR] non instruction value on use-def chain: "
<< *toVisit.back() << '\n';
exit(EXIT_FAILURE);
}
// Check if the visited instruciton is a call to pthread_create. If it
// is, assume that we are done.
// Note: is there ever a case where the join argument is data dependent
if (CallInst *ci = dyn_cast<CallInst>(i)) {
if (ci->getCalledFunction()->getName() == "pthread_create") {
DEBUG_MSG("paired join with create: " << *ci);
return getPThreadThreadFunc(ci);
}
}
else if (AllocaInst *ai = dyn_cast<AllocaInst>(i)) {
// If we find an alloca, then we've found the site where the pthread_t
// was allocated. Search forward from the alloca for the pthread_create
// site.
return forwardSearchCreate(ai);
}
else if (LoadInst *li = dyn_cast<LoadInst>(i)) {
// Get the defs of the load instruction
for (Use &U : li->operands()) {
Value *useV = U.get();
toVisit.push_back(useV);
}
}
// TODO: Handle additional types here. Might be able to just blindly
// search backwards on all the operands of the instruction
else {
errs() << "[ERROR] Unahandled instruction type while searching for "
<< "pthread_create: " << *i << '\n';
DEBUG_MSG("checking isa loadinst\n");
DEBUG_MSG("isa loadinst? " << isa<LoadInst>(i) << '\n');
exit(EXIT_FAILURE);
}
}
// Reach here means we didn't find the create site
return NULL;
}
// Given an alloca instruction allocating a pthread_t, search forward for the
// site where the pthread_t is being used. Return the function created by the
// pthread_create call
//
// This returns the first site found
Function *forwardSearchCreate(AllocaInst *ai) {
std::vector<Instruction *> toVisit;
toVisit.push_back(ai);
while (toVisit.size()) {
Instruction *cur = toVisit.back();
toVisit.pop_back();
for (User *u : cur->users()) {
// Check if we've found pthread_create
if (CallInst *ci = dyn_cast<CallInst>(u)) {
if (ci->getCalledFunction()->getName() == "pthread_create") {
DEBUG_MSG("found pthread_create on forward search: "
<< *ci << '\n');
return getPThreadThreadFunc(ci);
}
}
if (Instruction *i = dyn_cast<Instruction>(u)) {
toVisit.push_back(i);
}
else {
errs() << "[ERROR] unhandled User searching forward for "
<< "pthread_create: " << *u << '\n';
exit(EXIT_FAILURE);
}
}
} // while (toVisit.size())
// Reach here means we did not find pthread_create
return NULL;
}
// Given a Function, return all of its return instructions
std::vector<ReturnInst*> getRets(Function *f) {
std::vector<ReturnInst*> ret;
for (BasicBlock &BB : *f) {
for (Instruction &I : BB) {
if (ReturnInst *r = dyn_cast<ReturnInst>(&I)) {
ret.push_back(r);
}
}
}
return ret;
}
// Starting from `main`, find all the children threads. Using the
// happen-before relation caused by thread creation, get those stores which a
// thread function must not be able to read from
void getNotReadFrom(std::map<Function *, Function*> &child2parent
, std::map<Function *, std::vector<Function*>> &parent2child
, std::map<Function *, std::vector<StoreInst *>> ¬ReadFrom
, std::map<Function *, CallInst *> &createLocs
, Function *main) {
// List containing function to be processed. The order the functions are
// processed does matter! The parent of a thread must be processed before
// the child. This is required because the parent's information needs to be
// availible (the things the parent cannot read from) in order to evaluate
// the child.
std::deque<Function *> worklist;
worklist.push_back(main);
while (worklist.size()) {
// Get and delete the first item
Function *curParent = worklist.front();
DEBUG_MSG("[DEBUG] getNotReadFrom: analyzing function: "
<< curParent->getName() << '\n');
worklist.pop_front();
// Get all the threads created by `f`. These are all the children of `f`
std::vector<CallInst *> creats = getThreadCreate(curParent);
DEBUG_MSG("\t" << creats.size() << " thread creations\n");
std::vector<Function *> curParentChildren;
for (CallInst *ci : creats) {
Function *thrdFunc = getPThreadThreadFunc(ci);
curParentChildren.push_back(thrdFunc);
// This error could be fixed: see the comment above the assertion below
assert(createLocs.find(thrdFunc) == createLocs.end()
&& "thread function created twice");
createLocs.emplace(thrdFunc, ci);
// The child of curParent also needs to be processed (we need to find
// if it has any children)
worklist.push_back(thrdFunc);
// In general, we should allow the same function to be created twice.
// We could handle this by instead making the child2parent map a map
// from a pair of Function * and CallInst:
// std::map<std::pair<Function *, CallInst *>, Function*>
// In this way, we only require each CallSite to be unique
assert(child2parent.find(thrdFunc) == child2parent.end()
&& "function being created twice");
child2parent.emplace(thrdFunc, curParent);
// Get those store's within the thread that cannot be read by this call
// instruction
std::vector<StoreInst *> mnrl = getThreadLocalNotRead(ci);
DEBUG_MSG("\t" << mnrl.size() << " local not-read from\n");
// Get the stores which cannot be read by any ancestors of the parent
std::vector<StoreInst *> mnrp
= getParentNotRead(ci->getParent()->getParent(), child2parent
, notReadFrom);
DEBUG_MSG("\t" << mnrp.size() << " parent not-read from\n");
// Merge the results
std::vector<StoreInst *> merge;
merge.reserve(mnrl.size() + mnrp.size());
merge.insert(merge.end(), mnrl.begin(), mnrl.end());
merge.insert(merge.end(), mnrp.begin(), mnrp.end());
// Update must-not read-from results
assert(notReadFrom.find(thrdFunc) == notReadFrom.end()
&& "function being created twice");
notReadFrom.emplace(thrdFunc, merge);
} // for (CallInst *ci : creats)
// save the parents children
assert(parent2child.find(curParent) == parent2child.end()
&& "parent visited twice");
parent2child.emplace(curParent, curParentChildren);
}
}
// Given a call instruction `ci`, find those stores within the Function
// calling `ci` which must happen-before `ci`. Any store which must happen
// before `ci` is not visible to the child thread created by `ci`
std::vector<StoreInst *> getThreadLocalNotRead(CallInst *ci) {
BasicBlock *ciBB = ci->getParent();
Function *ciF = ci->getParent()->getParent();
// First, get the stores within the basicblock which happen before the
// CallInst. These trivially must happen before the callinst
std::vector<StoreInst *> ret = getStoresInBBBefore(ci);
DEBUG_MSG("[DEBUG] getThreadLocalNotRead(): "
"intra-BB happens-before stores: " << ret.size() << '\n');
// Next, get all those stores in basicblock which post dominate `ci`. Since
// we just got the stores within the same basicblock as `ci`, we can ignore
// the block containing `ci` (any basicblock post-dominates itself).
PostDominatorTree &PDT = getAnalysis<PostDominatorTree>(*ciF);
SmallVector<BasicBlock *, 10> pdoms;
PDT.getDescendants(ciBB, pdoms);
for (BasicBlock *b : pdoms) {
if (b == ciBB) {
// Do not analyze the BasicBlock containing `ci`
continue;
}
std::vector<StoreInst *> bStores = getStores(b);
// Add bStores to the end of ret
Utils::addVector(ret, bStores);
}
return ret;
}
// Given a pthread_create call, find all the stores within the calling thread
// much must ocurr before the call. These are not visible to the child thread
// unless the value is not overwritten. In that case, the value will be
// present in the initial environment of the thread
void addThreadLocalNotRead(z3::context &ctx, Z3_fixedpoint &zfp, CallInst *ci
, Function *tfunc) {
std::vector<StoreInst*> sts = getThreadLocalNotRead(ci);
std::vector<Instruction*> ls = getLoads(tfunc);
for (StoreInst *s : sts) {
for (Instruction *l : ls) {
addNotReadFact(ctx, zfp, l, s);
}
}
}
// Return the StoreInsts which ocurr before `i` within the same basicblock as
// `i`.
std::vector<StoreInst *> getStoresInBBBefore(Instruction *i) {
BasicBlock *b = i->getParent();
std::vector<StoreInst *> ret;
for (auto bi = b->begin(), be = b->end(); bi != be; ++bi) {
Instruction *cur = &*bi;
if (cur == i) {
return ret;
}
if (StoreInst *si = dyn_cast<StoreInst>(cur)) {
ret.push_back(si);
}
}
// Reaching this point means `i` was not found in its own basicblock. This
// should never happen!
assert(0 && "passed instruction not found");
}
// Given a function `f`, get all the stores which the parents of `f` cannot
// read from. Transitively, `f` can also not read from these stores
std::vector<StoreInst *> getParentNotRead(Function *f
, std::map<Function*, Function*> child2parent
, std::map<Function *, std::vector<StoreInst *>> notReadFrom) {
std::vector<StoreInst *> ret;
std::vector<Function *> parents = getParents(f, child2parent);
for (Function *par : parents) {
auto nri = notReadFrom.find(par);
if (nri != notReadFrom.end()) {
std::vector<StoreInst *> nr = nri->second;
ret.insert(ret.end(), nr.begin(), nr.end());
}
}
return ret;
}
// Given a child thread, follow the child2parent map and return all the
// parents of `child` (i.e., its creater, its creater's creater, and so on)
std::vector<Function *> getParents(Function *child
, const std::map<Function *, Function*> child2parent) const {
std::vector<Function *> ret;
auto iter = child2parent.find(child);
while (iter != child2parent.end()) {
Function *parent = iter->second;
ret.push_back(parent);
// Find the parent of `parent`
iter = child2parent.find(parent);
}
return ret;
}
// Return the first instruction in the passed function. If the function is
// external (i.e., we do not have the source code, return NULL.
Instruction *getFirstInst(Function *f) {
if (f->begin() == f->end()) {
// No basicblocks
return NULL;
}
auto ii = f->begin()->begin();
Instruction *ret = &*ii;
return ret;
}
// Return the function being created in a thread by the passed call
// instruction. It is assumed the call instruction is a pthread_create call.
//
// Otherwise, this will crash.
Function *getPThreadThreadFunc(CallInst *ci) {
Value *v = ci->getArgOperand(2);
if (Function *tFunc = dyn_cast<Function>(v)) {
return tFunc;
}
else {
errs() << "[ERROR] pthread_create with non function 2nd arg\n";
errs() << *v << '\n';
exit(EXIT_FAILURE);
}
}
std::set<BasicBlock *> getAllBBs(Function *F) {
std::set<BasicBlock *> ret;
for (BasicBlock &B : *F) {
ret.insert(&B);
}
return ret;
}
// Update fixedpoint and context to contain not-reachable information
void addNotReachableFacts(Module &M, z3::context &ctx, Z3_fixedpoint &zfp) {
addNotReachRel(ctx, zfp);
for (Function &F : M) {
std::set<BasicBlock*> allBBs = getAllBBs(&F);
std::map<BasicBlock *, std::set<BasicBlock*>> reachMap;
reachMap = getReachability(&F);
for (BasicBlock &B : F) {
auto it = reachMap.find(&B);
assert(it != reachMap.end());
std::set<BasicBlock *> reach = it->second;
if (reach.find(&B) != reach.end()) {
DEBUG_MSG("Self reachable basicblock\n");
}
// At most there will be allBBs.size() items in the result
std::vector<BasicBlock*> notReach(allBBs.size());
// allBbs - reach
// i.e., the not reachable BBs
auto nrIt = set_difference(allBBs.begin()
, allBBs.end()
, reach.begin()
, reach.end()
, notReach.begin());
// Resize notReach to remove any of the non-used slots
notReach.resize(nrIt - notReach.begin());
for (BasicBlock *notReachB : notReach) {
// Every instruyction in B cannot reach notReachB
for (Instruction &BI : B) {
if (!isaStoreLoadCallOrTerm(&BI)) {
continue;
}
for (Instruction &nrBI : *notReachB) {
if (!isaStoreLoadCallOrTerm(&nrBI)) {
continue;
}
addNotReachFact(ctx, zfp, &BI, &nrBI);
}
}
}
}
}
}
// Return true if the passed instruction is a StoreInst, LoadInst, or
// TerminatorInst
bool isaStoreLoadCallOrTerm(Instruction *I) const {
if (isa<StoreInst>(I)) {
return true;
}
else if (isa<LoadInst>(I)) {
return true;
}
else if (isa<TerminatorInst>(I)) {
return true;
}
else if (isa<CallInst>(I)) {
return true;
}
else {
return false;
}
}
std::map<BasicBlock *, std::set<BasicBlock*>> getReachability(Function *F) {
std::map<BasicBlock *, std::set<BasicBlock*>> ret;
for (BasicBlock &B : *F) {
ret.emplace(&B, forwardDfs(&B));
}
return ret;
}
// Return all the basicblocks forwardly reachable from `b`
//
// This only includes `b`in the return if there exists a path from `b` to
// `b`.
std::set<BasicBlock *> forwardDfs(BasicBlock *b) {
std::set<BasicBlock*> ret;
std::set<BasicBlock*> visited;
std::vector<BasicBlock*> s;
// Do not add `b` to ret unless there is a path from `b` to `b`.
// To do this, initialize the stack with the successors
std::vector<BasicBlock*> bSuccs = getSuccsFromBB(b);
s.insert(s.end(), bSuccs.begin(), bSuccs.end());
while (!s.empty()) {
BasicBlock *cur = s.back();
s.pop_back();
if (visited.find(cur) == visited.end()) {
visited.insert(cur);
if (cur == b) {
DEBUG_MSG("self-reachable basicblock: " << b->front() << '\n');
}
ret.insert(cur);
std::vector<BasicBlock*> curSuccs = getSuccsFromBB(cur);
s.insert(s.end(), curSuccs.begin(), curSuccs.end());
}
}
if (ret.find(b) != ret.end()) {
DEBUG_MSG("basicblock can reach itself\n");
}
return ret;
}
std::vector<BasicBlock*> getSuccsFromBB(BasicBlock *B) {
std::vector<BasicBlock *> ret;
TerminatorInst *ti = B->getTerminator();
assert(ti && "malformed basic block");
for (size_t i = 0; i < ti->getNumSuccessors(); ++i) {
ret.push_back(ti->getSuccessor(i));
}
return ret;
}
// Return a const bitvector ID for the passed instruction.
//
// This uses the address of the instruction; LLVM guarantees this is unique.
//
// The size of the bitvector is the size of the pointer-type (e.g.,
// sizeof(uintptr_t))
z3::expr getValueBVID(z3::context &ctx, Value *v) const {
return getValueBVIDSz(ctx, v, Z3_BV_SIZE);
}
// get function declaration of ld relation
z3::func_decl getLdFuncDecl(z3::context &ctx) const {
return getBVBVFuncDecl(ctx, "ld");
}
// get function declarion of st relation
z3::func_decl getStFuncDecl(z3::context &ctx) {
return getBVBVFuncDecl(ctx, "st");
}
z3::func_decl getMHBFuncDecl(z3::context &ctx) const {
return getBVBVFuncDecl(ctx, "mhb");
}
z3::func_decl getNoReorderFuncDecl(z3::context &ctx) const {
return getBVBVFuncDecl(ctx, "noreorder");
}
z3::func_decl getFenceFuncDecl(z3::context &ctx) const {
return getBVFuncDecl(ctx, "fence");
}
z3::func_decl getLwSyncFuncDecl(z3::context &ctx) const {
return getBVFuncDecl(ctx, "lwsync");
}
// Return func_decl of dominance relation
z3::func_decl getDomFuncDecl(z3::context &ctx) const {
return getBVBVFuncDecl(ctx, "dom");
}
// Return func_decl of post dominance relation
z3::func_decl getPostDomFuncDecl(z3::context &ctx) const {
return getBVBVFuncDecl(ctx, "postDom");
}
// Return func_decl of priority
z3::func_decl getPriFuncDecl(z3::context &ctx) const {
return getBVFuncDecl(ctx, "pri");
}
// Return func_decl of higher
z3::func_decl getHighFuncDecl(z3::context &ctx) const {
return getBVBVFuncDecl(ctx, "higher");
}
// Return func_decl of lineHigh
z3::func_decl getLineHighFuncDecl(z3::context &ctx) const {
return getBVBVFuncDecl(ctx, "linehigh");
}
// return func_decl of compLoad
z3::func_decl getCompLdFuncDecl(z3::context &ctx) const {
return getBVFuncDecl(ctx, "compLd");
}
// return func_decl of nonLastStore
z3::func_decl getNonLastStFuncDecl(z3::context &ctx) const {
return getBVFuncDecl(ctx, "nonLastSt");
}
// Return func_decl of linePri
z3::func_decl getLinePriFuncDecl(z3::context &ctx) const {
return getBVBVFuncDecl(ctx, "linepri");
}
z3::func_decl getNotReachFuncDecl(z3::context &ctx) const {
return getBVBVFuncDecl(ctx, "not-reach");
}
z3::func_decl getNotReadsFromFuncDecl(z3::context &ctx) const {
return getBVBVFuncDecl(ctx, "not-rf");
}
z3::func_decl getReadsFromFuncDecl(z3::context &ctx) const {
return getBVBVFuncDecl(ctx, "rf");
}
// Given the name of a relation with arguments (bitvector, bitvector) return
// its function declaration.
z3::func_decl getBVBVFuncDecl(z3::context &ctx, const char *name) const {
return z3_fp_helpers::getBVBVFuncDecl(ctx, name, Z3_BV_SIZE);
}
// Given the name of a relation with arguments (bitvector) return
// its function declaration.
z3::func_decl getBVFuncDecl(z3::context &ctx, const char *name) const {
return z3_fp_helpers::getBVFuncDecl(ctx, name, Z3_BV_SIZE);
}
void addLinePriFact(z3::context &ctx
, Z3_fixedpoint &zfp
, z3::func_decl fd
, llvm::Instruction *l
, unsigned priority) const {
addLinePriFactSz(ctx, zfp, fd, l, priority, Z3_BV_SIZE);
}
void addFact2(z3::context &ctx
, Z3_fixedpoint &zfp
, z3::func_decl fd
, llvm::Value *v1
, llvm::Value *v2) const {
addFact2Sz(ctx, zfp, fd, v1, v2, Z3_BV_SIZE);
}
void addFact1(z3::context &ctx
, Z3_fixedpoint &zfp
, z3::func_decl fd
, llvm::Value *v) const {
addFact1Sz(ctx, zfp, fd, v, Z3_BV_SIZE);
}
// Add a fact that `l` loads `v`
void addLoadFact(z3::context &ctx
, Z3_fixedpoint &zfp
, Instruction *l
, Value *v) {
addFact2(ctx, zfp, getLdFuncDecl(ctx), l, v);
}
// Add a fact that `f` is a fence
void addFenceFact(z3::context &ctx
, Z3_fixedpoint &zfp
, Instruction *f) {
addFact1(ctx, zfp, getFenceFuncDecl(ctx), f);
}
void addLwSyncFact(z3::context &ctx
, Z3_fixedpoint &zfp
, Instruction *f) {
addFact1(ctx, zfp, getLwSyncFuncDecl(ctx), f);
}
// Add (rf l v)
void addReadsFromFact(z3::context &ctx
, Z3_fixedpoint &zfp
, Instruction *l
, Value *v) const {
assert(Utils::isSomeLoad(l) && "non load reading");
addFact2(ctx, zfp, getReadsFromFuncDecl(ctx), l, v);
}
// Add a fact that `l` stores `v`
void addStoreFact(z3::context &ctx
, Z3_fixedpoint &zfp
, Instruction *s
, Value *v) {
addFact2(ctx, zfp, getStFuncDecl(ctx), s, v);
}
// Add (mhb to from)
void addMHBFact(z3::context &ctx, Z3_fixedpoint &zfp, Instruction *from
, Instruction *to) {
//Z3_ast fromId = getValueBVID(ctx, from);
//Z3_ast toId = getValueBVID(ctx, to);
//addMHBFact(ctx, zfp, fromId, toId);
addFact2(ctx, zfp, getMHBFuncDecl(ctx), from, to);
}
// Add fact: (dom a b)
// Converts to instructions to bitvector ids
void addDomFact(z3::context &ctx
, Z3_fixedpoint &zfp
, Instruction *a
, Instruction *b) {
addFact2(ctx, zfp, getDomFuncDecl(ctx), a, b);
}
// Add fact: (dom a b)
// Converts to instructions to bitvector ids
void addPostDomFact(z3::context &ctx
, Z3_fixedpoint &zfp
, Instruction *a
, Instruction *b) {
addFact2(ctx, zfp, getPostDomFuncDecl(ctx), a, b);
}
// Add fact: (not-read s l)
void addNotReadFact(z3::context &ctx
, Z3_fixedpoint &zfp
, Instruction *s
, Instruction *l) {
addFact2(ctx, zfp, getNotReadsFromFuncDecl(ctx), s, l);
}
// Add: (not-reach a b): a cannot reach b
void addNotReachFact(z3::context &ctx
, Z3_fixedpoint &zfp
, Instruction *a
, Instruction *b) {
addFact2(ctx, zfp, getNotReachFuncDecl(ctx), a, b);
}
// Return the dominance and post dominance facts
// within the basicblock (i.e., the order of instructions in the block).
// Since we are only interested in loads and stores, this will ignore all
// other instruction types except the basicblock terminator and calls.
void addInternalDomAndPostDomFacts(BasicBlock *b, z3::context &ctx, Z3_fixedpoint &zfp) {
std::vector<Instruction *> loadsNStores = getLoadStoreCallOrdered(b);
loadsNStores.push_back(b->getTerminator());
assert(loadsNStores.size() > 0 && "basicblock with no terminator");
if (loadsNStores.size() == 1) {
// With only one instruction (the terminator) there is no internal
// dominance facts
return;
}
assert(loadsNStores.size() > 1);
Instruction *prev = loadsNStores[0];
for (size_t i = 1; i < loadsNStores.size(); ++i) {
Instruction *cur = loadsNStores[i];
// prev dominates cur
addDomFact(ctx, zfp, prev, cur);
addPostDomFact(ctx, zfp, cur, prev);
// Update prev for the next iteration
prev = cur;
}
}
// (=> (and (dom a b) (not-reach b a)) (mhb a b))
void addDomNotReachRule(z3::context &ctx, Z3_fixedpoint &zfp) {
z3::sort bvSort = ctx.bv_sort(Z3_BV_SIZE);
//Z3_ast a = Z3_mk_const(ctx, Z3_mk_string_symbol(ctx, "aDom"), bvSort);
//Z3_ast b = Z3_mk_const(ctx, Z3_mk_string_symbol(ctx, "bDom"), bvSort);
z3::expr a = z3::expr(ctx, Z3_mk_bound(ctx, 0, bvSort));
z3::expr b = z3::expr(ctx, Z3_mk_bound(ctx, 1, bvSort));
z3::func_decl domDecl = getDomFuncDecl(ctx);
z3::func_decl nrDecl = getNotReachFuncDecl(ctx);
z3::func_decl mhbDecl = getMHBFuncDecl(ctx);
// (dom a b)
// (mhb a b)
z3::expr args[2] = {a, b};
z3::expr domAB = domDecl(2, args);
z3::expr mhbAB = mhbDecl(2, args);
// (not-reach b a)
args[0] = b;
args[1] = a;
z3::expr nrBA = nrDecl(2, args);
// (and (dom a b) (not-reach b a))
//args[0] = domAB;
//args[1] = nrBA;
z3::expr domNrAnd = domAB && nrBA;
z3::expr imp = z3::implies(domNrAnd, mhbAB);
Z3_fixedpoint_add_rule(ctx, zfp, imp, NULL);
}
// (=> (and (dom a b) (not-reach b a)) (mhb a b))
void addDomNotReachReorderRule(z3::context &ctx, Z3_fixedpoint &zfp) {
z3::sort bvSort = ctx.bv_sort(Z3_BV_SIZE);
//Z3_ast a = Z3_mk_const(ctx, Z3_mk_string_symbol(ctx, "aDom"), bvSort);
//Z3_ast b = Z3_mk_const(ctx, Z3_mk_string_symbol(ctx, "bDom"), bvSort);
z3::expr a = z3::expr(ctx, Z3_mk_bound(ctx, 0, bvSort));
z3::expr b = z3::expr(ctx, Z3_mk_bound(ctx, 1, bvSort));
z3::func_decl domDecl = getDomFuncDecl(ctx);
z3::func_decl nrDecl = getNotReachFuncDecl(ctx);
z3::func_decl mhbDecl = getMHBFuncDecl(ctx);
z3::func_decl noReoDecl = getNoReorderFuncDecl(ctx);
// (dom a b)
// (mhb a b)
// (noreorder a b)
z3::expr args[2] = {a, b};
z3::expr domAB = domDecl(2, args);
z3::expr mhbAB = mhbDecl(2, args);
z3::expr noReoAB = noReoDecl(2, args);
// (not-reach b a)
args[0] = b;
args[1] = a;
z3::expr nrBA = nrDecl(2, args);
// (and (dom a b) (not-reach b a) (noreorder a b))
//args[0] = domAB;
//args[1] = nrBA;
z3::expr domNrAnd = domAB && nrBA && noReoAB;
z3::expr imp = z3::implies(domNrAnd, mhbAB);
Z3_fixedpoint_add_rule(ctx, zfp, imp, NULL);
}
// (=> (and (reads-from l s1)
// (mhb s1 s2)
// (is-load l v)
// (is-store s1 v)
// (is-store s2 v))
// (mhb l s2))
void addReadsFromMHB(z3::context &ctx, Z3_fixedpoint &zfp) {
z3::sort bvSort = ctx.bv_sort(Z3_BV_SIZE);
//Z3_ast s1 = Z3_mk_const(ctx, Z3_mk_string_symbol(ctx, "s1"), bvSort);
//Z3_ast s2 = Z3_mk_const(ctx, Z3_mk_string_symbol(ctx, "s2"), bvSort);
//Z3_ast l = Z3_mk_const(ctx, Z3_mk_string_symbol(ctx, "l"), bvSort);
//Z3_ast v = Z3_mk_const(ctx, Z3_mk_string_symbol(ctx, "v"), bvSort);
z3::expr s1 = z3::expr(ctx, Z3_mk_bound(ctx, 0, bvSort));
z3::expr s2 = z3::expr(ctx, Z3_mk_bound(ctx, 1, bvSort));
z3::expr l = z3::expr(ctx, Z3_mk_bound(ctx, 2, bvSort));
z3::expr v = z3::expr(ctx, Z3_mk_bound(ctx, 3, bvSort));
z3::func_decl mhbDecl = getMHBFuncDecl(ctx);
z3::func_decl rfDecl = getReadsFromFuncDecl(ctx);
z3::func_decl ldDecl = getLdFuncDecl(ctx);
z3::func_decl stDecl = getStFuncDecl(ctx);
z3::expr args[2] = {l, s1};
z3::expr rf_l_s1 = rfDecl(2, args);
args[0] = s1;
args[1] = s2;
z3::expr mhb_s1_s2 = mhbDecl(2, args);
args[0] = l;
args[1] = v;
z3::expr ld_l_v = ldDecl(2, args);
args[0] = s1;
args[1] = v;
z3::expr st_s1_v = stDecl(2, args);
args[0] = s2;
args[1] = v;
z3::expr st_s2_v = stDecl(2, args);
args[0] = l;
args[1] = s2;
z3::expr mhb_l_s2 = mhbDecl(2, args);
//z3::expr andArgs[5] = {rf_l_s1, mhb_s1_s2, ld_l_v, st_s1_v, st_s2_v};
//z3::expr bigAnd = z3::expr(ctx, Z3_mk_and(ctx, 5, andArgs));
z3::expr bigAnd = rf_l_s1 && mhb_s1_s2 && ld_l_v && st_s1_v && st_s2_v;
z3::expr imp = z3::implies(bigAnd, mhb_l_s2);
Z3_fixedpoint_add_rule(ctx, zfp, imp, NULL);
}
// (=> (and (mhb a b) (mhb b c))
// (mhb a c))
void addMHBTrans(z3::context &ctx, Z3_fixedpoint &zfp) {
addTransRuleBVBV(ctx, zfp, getMHBFuncDecl(ctx), Z3_BV_SIZE);
}
// (=> (and (reads-from l1 s1)
// (mhb l1 s2)
// (mhb s2 l2)
// (is-load l1 v)
// (is-load l2 v)
// (is-store s2 v))
// (not-rf l2 s1))
void addOverwriteNotReads(z3::context &ctx, Z3_fixedpoint &zfp) {
z3::sort bvSort = ctx.bv_sort(Z3_BV_SIZE);
//Z3_ast l1 = Z3_mk_const(ctx, Z3_mk_string_symbol(ctx, "l1"), bvSort);
//Z3_ast l2 = Z3_mk_const(ctx, Z3_mk_string_symbol(ctx, "l2"), bvSort);
//Z3_ast s1 = Z3_mk_const(ctx, Z3_mk_string_symbol(ctx, "s1"), bvSort);
//Z3_ast s2 = Z3_mk_const(ctx, Z3_mk_string_symbol(ctx, "s2"), bvSort);
z3::expr l1 = z3::expr(ctx, Z3_mk_bound(ctx, 0, bvSort));
z3::expr l2 = z3::expr(ctx, Z3_mk_bound(ctx, 1, bvSort));
z3::expr s1 = z3::expr(ctx, Z3_mk_bound(ctx, 2, bvSort));
z3::expr s2 = z3::expr(ctx, Z3_mk_bound(ctx, 3, bvSort));
z3::expr v = z3::expr(ctx, Z3_mk_bound(ctx, 4, bvSort));
z3::func_decl rfDecl = getReadsFromFuncDecl(ctx);
z3::func_decl ldDecl = getLdFuncDecl(ctx);
z3::func_decl stDecl = getStFuncDecl(ctx);
z3::func_decl mhbDecl = getMHBFuncDecl(ctx);
z3::func_decl nrfDecl = getNotReadsFromFuncDecl(ctx);
z3::expr args[2] = {l1, s1};
z3::expr rf_l1_s1 = rfDecl(2, args);
args[0] = l1;
args[1] = s2;
z3::expr mhb_l1_s2 = mhbDecl(2, args);
args[0] = s2;
args[1] = l2;
z3::expr mhb_s2_l2 = mhbDecl(2, args);
args[0] = l1;
args[1] = v;
z3::expr ld_l1_v = ldDecl(2, args);
args[0] = l2;
args[1] = v;
z3::expr ld_l2_v = ldDecl(2, args);
args[0] = s2;
args[1] = v;
z3::expr st_s2_v = stDecl(2, args);
args[0] = l2;
args[1] = s1;
z3::expr nrf_l2_s1 = nrfDecl(2, args);
//z3::expr andArgs[6] = {rf_l1_s1, mhb_l1_s2, mhb_s2_l2, ld_l1_v, ld_l2_v
// , st_s2_v};
//z3::expr bigAnd = z3::expr(ctx, Z3_mk_and(ctx, 6, andArgs));
z3::expr bigAnd = rf_l1_s1 && mhb_l1_s2 && mhb_s2_l2 && ld_l1_v
&& ld_l2_v && st_s2_v;
z3::expr imp = z3::implies(bigAnd, nrf_l2_s1);
Z3_fixedpoint_add_rule(ctx, zfp, imp, NULL);
}
// (=> (mhb a b) (not-rf a b))
void addMHBNotReads(z3::context &ctx, Z3_fixedpoint &zfp) {
z3::sort bvSort = ctx.bv_sort(Z3_BV_SIZE);
//Z3_ast a = Z3_mk_const(ctx, Z3_mk_string_symbol(ctx, "a"), bvSort);
//Z3_ast b = Z3_mk_const(ctx, Z3_mk_string_symbol(ctx, "b"), bvSort);
z3::expr a = z3::expr(ctx, Z3_mk_bound(ctx, 0, bvSort));
z3::expr b = z3::expr(ctx, Z3_mk_bound(ctx, 1, bvSort));
z3::expr args[2] = {a, b};
z3::expr mhbAB = getMHBFuncDecl(ctx)(2, args);
z3::expr nrfAB = getNotReadsFromFuncDecl(ctx)(2, args);
Z3_fixedpoint_add_rule(ctx, zfp, Z3_mk_implies(ctx, mhbAB, nrfAB), NULL);
}
//// Add a rule sating that reads-from(a, b) ==> MHB(b, a). A write must ocurr
//// before a read for it to be witnessed
void addMHBNRFRule(z3::context &ctx, Z3_fixedpoint &zfp) const {
z3::sort bvSort = ctx.bv_sort(Z3_BV_SIZE);
z3::expr a = z3::expr(ctx, Z3_mk_bound(ctx, 0, bvSort));
z3::expr b = z3::expr(ctx, Z3_mk_bound(ctx, 1, bvSort));
z3::expr args[2] = {a, b};
z3::expr rfAB = getReadsFromFuncDecl(ctx)(2, args);
args[0] = b;
args[1] = a;
z3::expr mhbBA = getMHBFuncDecl(ctx)(2, args);
Z3_fixedpoint_add_rule(ctx, zfp, Z3_mk_implies(ctx, rfAB, mhbBA), NULL);
}
// Add rules which can prune interferences:
void addPruningRules(z3::context &ctx, Z3_fixedpoint &zfp) {
addReadsFromRel(ctx, zfp);
addNotReadsFromRel(ctx, zfp);
addMHBNRFRule(ctx, zfp);
addDomNotReachRule(ctx, zfp);
addReadsFromMHB(ctx, zfp);
addMHBTrans(ctx, zfp);
addMHBNotReads(ctx, zfp);
addOverwriteNotReads(ctx, zfp);
}
void addSCReorderRules(z3::context &ctx, Z3_fixedpoint &zfp) {
addNoReorderRel(ctx, zfp);
z3::sort bvSort = ctx.bv_sort(Z3_BV_SIZE);
z3::expr v1 = z3::expr(ctx, Z3_mk_bound(ctx, 2, bvSort));
z3::expr v2 = z3::expr(ctx, Z3_mk_bound(ctx, 2, bvSort));
z3::func_decl ldDecl = getLdFuncDecl(ctx);
z3::func_decl stDecl = getStFuncDecl(ctx);
z3::func_decl fenceDecl = getFenceFuncDecl(ctx);
/* Single Variable Rules */
// R(v) -> R(v)
addNoReoFunc2Func2(ctx, zfp, ldDecl, ldDecl, v1, v1);
// R(v) -> W(v)
addNoReoFunc2Func2(ctx, zfp, ldDecl, stDecl, v1, v1);
// W(v) -> R(v)
addNoReoFunc2Func2(ctx, zfp, stDecl, ldDecl, v1, v1);
// W(v) -> W(v)
addNoReoFunc2Func2(ctx, zfp, stDecl, stDecl, v1, v1);
/* End Single Variable Rules */
/* Double Variables Rules */
// R(v) -> R(v)
addNoReoFunc2Func2(ctx, zfp, ldDecl, ldDecl, v1, v2);
//// R(v) -> W(v)
addNoReoFunc2Func2(ctx, zfp, ldDecl, stDecl, v1, v2);
//// W(v) -> R(v)
addNoReoFunc2Func2(ctx, zfp, stDecl, ldDecl, v1, v2);
//// W(v) -> W(v)
addNoReoFunc2Func2(ctx, zfp, stDecl, stDecl, v1, v2);
/* End Double Variables Rules */
// Fences dont exist on SC
// Fences and all loads/stores are not reordered
//addNoReoFunc1Func2(ctx, zfp, fenceDecl, stDecl);
//addNoReoFunc1Func2(ctx, zfp, fenceDecl, ldDecl);
//addNoReoFunc2Func1(ctx, zfp, stDecl, fenceDecl);
//addNoReoFunc2Func1(ctx, zfp, ldDecl, fenceDecl);
}
void addTSOReorderRules(z3::context &ctx, Z3_fixedpoint &zfp) {
addNoReorderRel(ctx, zfp);
z3::sort bvSort = ctx.bv_sort(Z3_BV_SIZE);
z3::expr v1 = z3::expr(ctx, Z3_mk_bound(ctx, 2, bvSort));
z3::expr v2 = z3::expr(ctx, Z3_mk_bound(ctx, 2, bvSort));
z3::func_decl ldDecl = getLdFuncDecl(ctx);
z3::func_decl stDecl = getStFuncDecl(ctx);
z3::func_decl fenceDecl = getFenceFuncDecl(ctx);
/////// OLD DEFINITIONS
//// Loads can never be reordered with anything subsequent
//addNoReoFunc2Func2(ctx, zfp, ldDecl, stDecl, v1, v2);
//addNoReoFunc2Func2(ctx, zfp, ldDecl, ldDecl, v1, v2);
////// Nothing can ever drift past a store
//addNoReoFunc2Func2(ctx, zfp, ldDecl, stDecl, v1, v2);
////addNoReoFunc2Func2(ctx, zfp, stDecl, stDecl, v1, v2);
////// Store--Load to the same variable cannot be re-ordered
//addNoReoFunc2Func2(ctx, zfp, stDecl, ldDecl, v1, v1);
////// Store--Store to any variable cannot be reordered
//////////////addNoReoFunc2Func2(ctx, zfp, stDecl, stDecl, v1, v2);
//// Fences and all loads/stores are not reordered
//addNoReoFunc1Func2(ctx, zfp, fenceDecl, stDecl);
//addNoReoFunc1Func2(ctx, zfp, fenceDecl, ldDecl);
//addNoReoFunc2Func1(ctx, zfp, stDecl, fenceDecl);
//addNoReoFunc2Func1(ctx, zfp, ldDecl, fenceDecl);
/////// END OLD DEFINITIONS
/* Single Variable Rules */
// R(v) -> R(v)
addNoReoFunc2Func2(ctx, zfp, ldDecl, ldDecl, v1, v1);
// R(v) -> W(v)
addNoReoFunc2Func2(ctx, zfp, ldDecl, stDecl, v1, v1);
// W(v) -> R(v)
// This rule is not enforced because if it is it prevents store buffer
// forwarding
//addNoReoFunc2Func2(ctx, zfp, stDecl, ldDecl, v1, v1);
// W(v) -> W(v)
addNoReoFunc2Func2(ctx, zfp, stDecl, stDecl, v1, v1);
/* End Single Variable Rules */
/* Double Variables Rules */
// RMO/PowerPC allow all of these
// R(v) -> R(v)
addNoReoFunc2Func2(ctx, zfp, ldDecl, ldDecl, v1, v2);
//// R(v) -> W(v)
addNoReoFunc2Func2(ctx, zfp, ldDecl, stDecl, v1, v2);
//// W(v) -> R(v)
//addNoReoFunc2Func2(ctx, zfp, stDecl, ldDecl, v1, v2);
//// W(v) -> W(v)
addNoReoFunc2Func2(ctx, zfp, stDecl, stDecl, v1, v2);
/* End Double Variables Rules */
addFenceReorderRules(ctx, zfp);
// Fences and all loads/stores are not reordered
//addNoReoFunc1Func2(ctx, zfp, fenceDecl, stDecl);
//addNoReoFunc1Func2(ctx, zfp, fenceDecl, ldDecl);
//addNoReoFunc2Func1(ctx, zfp, stDecl, fenceDecl);
//addNoReoFunc2Func1(ctx, zfp, ldDecl, fenceDecl);
}
void addRMOReorderRules(z3::context &ctx, Z3_fixedpoint &zfp) {
addNoReorderRel(ctx, zfp);
z3::sort bvSort = ctx.bv_sort(Z3_BV_SIZE);
z3::expr v1 = z3::expr(ctx, Z3_mk_bound(ctx, 2, bvSort));
z3::expr v2 = z3::expr(ctx, Z3_mk_bound(ctx, 2, bvSort));
z3::func_decl ldDecl = getLdFuncDecl(ctx);
z3::func_decl stDecl = getStFuncDecl(ctx);
/* Single Variable Rules */
// R(v) -> R(v)
addNoReoFunc2Func2(ctx, zfp, ldDecl, ldDecl, v1, v1);
// R(v) -> W(v)
addNoReoFunc2Func2(ctx, zfp, ldDecl, stDecl, v1, v1);
// W(v) -> R(v)
//addNoReoFunc2Func2(ctx, zfp, stDecl, ldDecl, v1, v1);
// W(v) -> W(v)
addNoReoFunc2Func2(ctx, zfp, stDecl, stDecl, v1, v1);
/* End Single Variable Rules */
/* Double Variables Rules */
// RMO/PowerPC allow all of these
// R(v) -> R(v)
//addNoReoFunc2Func2(ctx, zfp, ldDecl, ldDecl, v1, v2);
//// R(v) -> W(v)
//addNoReoFunc2Func2(ctx, zfp, ldDecl, stDecl, v1, v2);
//// W(v) -> R(v)
//addNoReoFunc2Func2(ctx, zfp, stDecl, ldDecl, v1, v2);
//// W(v) -> W(v)
//addNoReoFunc2Func2(ctx, zfp, stDecl, stDecl, v1, v2);
/* End Double Variables Rules */
addFenceReorderRules(ctx, zfp);
//z3::func_decl lwDecl = getLwSyncFuncDecl(ctx);
//addNoReoFunc1Func2(ctx, zfp, lwDecl, stDecl);
//addNoReoFunc1Func2(ctx, zfp, lwDecl, ldDecl);
//addNoReoFunc2Func1(ctx, zfp, stDecl, lwDecl);
//addNoReoFunc2Func1(ctx, zfp, ldDecl, lwDecl);
// Fences and all loads/stores are not reordered
//addNoReoFunc1Func2(ctx, zfp, fenceDecl, stDecl);
//addNoReoFunc1Func2(ctx, zfp, fenceDecl, ldDecl);
//addNoReoFunc2Func1(ctx, zfp, stDecl, fenceDecl);
//addNoReoFunc2Func1(ctx, zfp, ldDecl, fenceDecl);
}
// Common reordering rules involving fences.
void addFenceReorderRules(z3::context &ctx, Z3_fixedpoint &zfp) {
z3::func_decl ldDecl = getLdFuncDecl(ctx);
z3::func_decl stDecl = getStFuncDecl(ctx);
z3::func_decl fenceDecl = getFenceFuncDecl(ctx);
//z3::func_decl lwDecl = getLwSyncFuncDecl(ctx);
addNoReoFunc1Func2(ctx, zfp, fenceDecl, stDecl);
addNoReoFunc1Func2(ctx, zfp, fenceDecl, ldDecl);
addNoReoFunc2Func1(ctx, zfp, stDecl, fenceDecl);
addNoReoFunc2Func1(ctx, zfp, ldDecl, fenceDecl);
// lwsync preserves everything but write-lwsync--read order
//addNoReoFunc1Func2(ctx, zfp, lwDecl, stDecl);
//addNoReoFunc1Func2(ctx, zfp, lwDecl, ldDecl);
//addNoReoFunc2Func1(ctx, zfp, stDecl, lwDecl);
//addNoReoFunc2Func1(ctx, zfp, ldDecl, lwDecl);
}
void addNoReorderRules(z3::context &ctx, Z3_fixedpoint &zfp) {
addReadsFromRel(ctx, zfp);
addNotReadsFromRel(ctx, zfp);
addDomNotReachReorderRule(ctx, zfp);
addMHBNRFRule(ctx, zfp);
addReadsFromMHB(ctx, zfp);
addMHBTrans(ctx, zfp);
addMHBNotReads(ctx, zfp);
addOverwriteNotReads(ctx, zfp);
}
void addPSOReorderRules(z3::context &ctx, Z3_fixedpoint &zfp) {
addNoReorderRel(ctx, zfp);
z3::sort bvSort = ctx.bv_sort(Z3_BV_SIZE);
z3::expr v1 = z3::expr(ctx, Z3_mk_bound(ctx, 2, bvSort));
z3::expr v2 = z3::expr(ctx, Z3_mk_bound(ctx, 2, bvSort));
z3::func_decl ldDecl = getLdFuncDecl(ctx);
z3::func_decl stDecl = getStFuncDecl(ctx);
//z3::func_decl fenceDecl = getFenceFuncDecl(ctx);
/////// OLD DEFINITIONS
//
//// Loads can never be reordered with anything subsequent
//addNoReoFunc2Func2(ctx, zfp, ldDecl, stDecl, v1, v2);
//addNoReoFunc2Func2(ctx, zfp, ldDecl, ldDecl, v1, v2);
//// Store--Load to the same variable cannot be re-ordered
//addNoReoFunc2Func2(ctx, zfp, stDecl, ldDecl, v1, v1);
//// Store--Store to the same variable cannot be reordered
////addNoReoFunc2Func2(ctx, zfp, stDecl, stDecl, v1, v1);
//// Fences and all loads/stores are not reordered
//addNoReoFunc1Func2(ctx, zfp, fenceDecl, stDecl);
//addNoReoFunc1Func2(ctx, zfp, fenceDecl, ldDecl);
//addNoReoFunc2Func1(ctx, zfp, stDecl, fenceDecl);
//addNoReoFunc2Func1(ctx, zfp, ldDecl, fenceDecl);
/* Single Variable Rules */
// R(v) -> R(v)
addNoReoFunc2Func2(ctx, zfp, ldDecl, ldDecl, v1, v1);
// R(v) -> W(v)
addNoReoFunc2Func2(ctx, zfp, ldDecl, stDecl, v1, v1);
// W(v) -> R(v)
// This rule is not enforced because if it is it prevents store buffer
// forwarding
//addNoReoFunc2Func2(ctx, zfp, stDecl, ldDecl, v1, v1);
// W(v) -> W(v)
addNoReoFunc2Func2(ctx, zfp, stDecl, stDecl, v1, v1);
/* End Single Variable Rules */
/* Double Variables Rules */
// RMO/PowerPC allow all of these
// R(v) -> R(v)
addNoReoFunc2Func2(ctx, zfp, ldDecl, ldDecl, v1, v2);
//// R(v) -> W(v)
addNoReoFunc2Func2(ctx, zfp, ldDecl, stDecl, v1, v2);
//// W(v) -> R(v)
//addNoReoFunc2Func2(ctx, zfp, stDecl, ldDecl, v1, v2);
//// W(v) -> W(v)
//addNoReoFunc2Func2(ctx, zfp, stDecl, stDecl, v1, v2);
/* End Double Variables Rules */
addFenceReorderRules(ctx, zfp);
// Fences and all loads/stores are not reordered
//addNoReoFunc1Func2(ctx, zfp, fenceDecl, stDecl);
//addNoReoFunc1Func2(ctx, zfp, fenceDecl, ldDecl);
//addNoReoFunc2Func1(ctx, zfp, stDecl, fenceDecl);
//addNoReoFunc2Func1(ctx, zfp, ldDecl, fenceDecl);
}
void addTSOPruningRules(z3::context &ctx, Z3_fixedpoint &zfp) {
addReadsFromRel(ctx, zfp);
addNotReadsFromRel(ctx, zfp);
// General Rules
addMHBNRFRule(ctx, zfp);
addReadsFromMHB(ctx, zfp);
addMHBTrans(ctx, zfp);
addMHBNotReads(ctx, zfp);
addOverwriteNotReads(ctx, zfp);
// MHB Rules
addDomStoreStoreTSO(ctx, zfp);
addLoadStoreMHB(ctx, zfp);
addStoreLoadMHB(ctx, zfp);
addLoadLoadMHB(ctx, zfp);
// Fence Rules
addPOLoadStoreFence(ctx, zfp);
}
void addPSOPruningRules(z3::context &ctx, Z3_fixedpoint &zfp) {
addReadsFromRel(ctx, zfp);
addNotReadsFromRel(ctx, zfp);
// General Rules
addMHBNRFRule(ctx, zfp);
addReadsFromMHB(ctx, zfp);
addMHBTrans(ctx, zfp);
addMHBNotReads(ctx, zfp);
addOverwriteNotReads(ctx, zfp);
// MHB Rules
addDomStoreStorePSO(ctx, zfp);
addLoadStoreMHB(ctx, zfp);
addStoreLoadMHB(ctx, zfp);
addLoadLoadMHB(ctx, zfp);
// Fence Rules
addPOLoadStoreFence(ctx, zfp);
}
// Add ordering of loads/stores before/after a fence
void addPOLoadStoreFence(z3::context &ctx, Z3_fixedpoint &zfp) {
addDomFenceFunc2(ctx, zfp, getLdFuncDecl(ctx));
addDomFenceFunc2(ctx, zfp, getStFuncDecl(ctx));
addDomFunc2Fence(ctx, zfp, getLdFuncDecl(ctx));
addDomFunc2Fence(ctx, zfp, getStFuncDecl(ctx));
}
// Add:
// (=> (and (dom a b)
// (not-reach b a)
// (is-fence a)
// (fd b v) )
// (mhb a b))
//
// where fd is the passed func_decl
void addDomFenceFunc2(z3::context &ctx, Z3_fixedpoint &zfp
, const z3::func_decl fd) {
z3::sort bvSort = ctx.bv_sort(Z3_BV_SIZE);
z3::expr a = z3::expr(ctx, Z3_mk_bound(ctx, 0, bvSort));
z3::expr b = z3::expr(ctx, Z3_mk_bound(ctx, 1, bvSort));
z3::expr v = z3::expr(ctx, Z3_mk_bound(ctx, 2, bvSort));
z3::func_decl domDecl = getDomFuncDecl(ctx);
z3::func_decl nrDecl = getNotReachFuncDecl(ctx);
z3::func_decl mhbDecl = getMHBFuncDecl(ctx);
z3::func_decl fenceDecl = getFenceFuncDecl(ctx);
// (dom a b)
// (mhb a b)
z3::expr args[2] = {a, b};
z3::expr domAB = domDecl(2, args);
z3::expr mhbAB = mhbDecl(2, args);
// (not-reach b a)
args[0] = b;
args[1] = a;
z3::expr nrBA = nrDecl(2, args);
// (is-fence a)
args[0] = a;
z3::expr fenceA = fenceDecl(1, args);
// (fd b v)
args[0] = b;
args[1] = v;
z3::expr fdBV = fd(2, args);
z3::expr bigAnd = domAB && nrBA && fenceA && fdBV;
z3::expr imp = z3::implies(bigAnd, mhbAB);
Z3_fixedpoint_add_rule(ctx, zfp, imp, NULL);
}
// Add:
// (=> (and (dom a b)
// (not-reach b a)
// (fd a v)
// (is-fence b))
// (mhb a b))
//
// where fd is the passed func_decl
void addDomFunc2Fence(z3::context &ctx, Z3_fixedpoint &zfp
, const z3::func_decl fd) {
z3::sort bvSort = ctx.bv_sort(Z3_BV_SIZE);
z3::expr a = z3::expr(ctx, Z3_mk_bound(ctx, 0, bvSort));
z3::expr b = z3::expr(ctx, Z3_mk_bound(ctx, 1, bvSort));
z3::expr v = z3::expr(ctx, Z3_mk_bound(ctx, 2, bvSort));
z3::func_decl domDecl = getDomFuncDecl(ctx);
z3::func_decl nrDecl = getNotReachFuncDecl(ctx);
z3::func_decl mhbDecl = getMHBFuncDecl(ctx);
z3::func_decl fenceDecl = getFenceFuncDecl(ctx);
// (dom a b)
// (mhb a b)
z3::expr args[2] = {a, b};
z3::expr domAB = domDecl(2, args);
z3::expr mhbAB = mhbDecl(2, args);
// (not-reach b a)
args[0] = b;
args[1] = a;
z3::expr nrBA = nrDecl(2, args);
// (is-fence b)
args[0] = b;
z3::expr fenceB = fenceDecl(1, args);
// (fd a v)
args[0] = a;
args[1] = v;
z3::expr fdAV = fd(2, args);
z3::expr bigAnd = domAB && nrBA && fenceB && fdAV;
z3::expr imp = z3::implies(bigAnd, mhbAB);
Z3_fixedpoint_add_rule(ctx, zfp, imp, NULL);
}
// (=> (reads-from b a) (mhb a b))
void addReadsFromIsMHB(z3::context &ctx, Z3_fixedpoint &zfp) {
z3::sort bvSort = ctx.bv_sort(Z3_BV_SIZE);
z3::expr a = z3::expr(ctx, Z3_mk_bound(ctx, 2, bvSort));
z3::expr b = z3::expr(ctx, Z3_mk_bound(ctx, 3, bvSort));
z3::func_decl rfDecl = getReadsFromFuncDecl(ctx);
z3::func_decl mhbDecl = getMHBFuncDecl(ctx);
z3::expr argsAB[2] = {a, b};
z3::expr argsBA[2] = {b, a};
z3::expr rf_b_a = rfDecl(2, argsBA);
z3::expr mhb_a_b = mhbDecl(2, argsAB);
z3::expr imp = z3::implies(rf_b_a, mhb_a_b);
Z3_fixedpoint_add_rule(ctx, zfp, imp, NULL);
}
// (=> (and (dom a b)
// (not-reach b a)
// (is-store a _)
// (is-store b _) )
// (mhb a b))
//
// i.e., stores to any variable are ordered on TSO
void addDomStoreStoreTSO(z3::context &ctx, Z3_fixedpoint &zfp) {
addStoreStoreMHB(ctx, zfp, false);
//z3::sort bvSort = ctx.bv_sort(Z3_BV_SIZE);
//z3::expr a = z3::expr(ctx, Z3_mk_bound(ctx, 0, bvSort));
//z3::expr b = z3::expr(ctx, Z3_mk_bound(ctx, 1, bvSort));
//z3::expr v1 = z3::expr(ctx, Z3_mk_bound(ctx, 2, bvSort));
//z3::expr v2 = z3::expr(ctx, Z3_mk_bound(ctx, 3, bvSort));
//z3::func_decl domDecl = getDomFuncDecl(ctx);
//z3::func_decl nrDecl = getNotReachFuncDecl(ctx);
//z3::func_decl stDecl = getStFuncDecl(ctx);
//z3::func_decl mhbDecl = getMHBFuncDecl(ctx);
//// (dom a b)
//// (mhb a b)
//z3::expr args[2] = {a, b};
//z3::expr domAB = domDecl(2, args);
//z3::expr mhbAB = mhbDecl(2, args);
//// (not-reach b a)
//args[0] = b;
//args[1] = a;
//z3::expr nrBA = nrDecl(2, args);
//// (is-store a v1)
//// (is-store b v2)
//// v1 may or may not equal v2 to satisfy the deduction
//args[0] = a;
//args[1] = v1;
//z3::expr isStAV1 = stDecl(2, args);
//args[0] = b;
//args[1] = v2;
//z3::expr isStBV2 = stDecl(2, args);
//// (and (dom a b)
//// (not-reach b a)
//// (is-store a _)
//// (is-store b _))
//z3::expr bigAnd = domAB && nrBA && isStAV1 && isStBV2;
//z3::expr imp = z3::implies(bigAnd, mhbAB);
//Z3_fixedpoint_add_rule(ctx, zfp, imp, NULL);
}
// (=> (and (dom a b)
// (not-reach b a)
// (is-store a v)
// (is-store b v) )
// (mhb a b))
//
// i.e., stores to the same variable are ordered on TSO
void addDomStoreStorePSO(z3::context &ctx, Z3_fixedpoint &zfp) {
addStoreStoreMHB(ctx, zfp, true);
}
// (=> (and (dom a f)
// (dom f b)
// (fd1 a v1)
// (fd2 b v2)
// (fd3 f)
// ))
void addNoReoDomFunc2Func2Func1(z3::context, Z3_fixedpoint &zfp
, const z3::func_decl fd1, const z3::func_decl fd2
, const z3::func_decl fd3, const z3::expr v1
, const z3::expr v2, const z3::expr f) {
}
// (=> (and (fd1 a v1)
// (fd2 b v2))
// (noreorder a b)
void addNoReoFunc2Func2(z3::context &ctx, Z3_fixedpoint &zfp
, const z3::func_decl fd1, const z3::func_decl fd2
, const z3::expr v1, const z3::expr v2) {
z3::sort bvSort = ctx.bv_sort(Z3_BV_SIZE);
z3::expr a = z3::expr(ctx, Z3_mk_bound(ctx, 0, bvSort));
z3::expr b = z3::expr(ctx, Z3_mk_bound(ctx, 1, bvSort));
z3::func_decl noReoDecl = getNoReorderFuncDecl(ctx);
z3::expr args[2] = {a, v1};
z3::expr fd1AV1 = fd1(2, args);
args[0] = a;
args[1] = b;
z3::expr noReo = noReoDecl(2, args);
args[0] = b;
args[1] = v2;
z3::expr fd2BV2 = fd2(2, args);
z3::expr bigAnd = fd1AV1 && fd2BV2;
z3::expr imp = z3::implies(bigAnd, noReo);
Z3_fixedpoint_add_rule(ctx, zfp, imp, NULL);
}
// (=> (and (fd1 a)
// (fd2 b v))
// (noreorder a b)
void addNoReoFunc1Func2(z3::context &ctx, Z3_fixedpoint &zfp
, const z3::func_decl fd1, const z3::func_decl fd2) {
z3::sort bvSort = ctx.bv_sort(Z3_BV_SIZE);
z3::expr a = z3::expr(ctx, Z3_mk_bound(ctx, 0, bvSort));
z3::expr b = z3::expr(ctx, Z3_mk_bound(ctx, 1, bvSort));
z3::expr v = z3::expr(ctx, Z3_mk_bound(ctx, 1, bvSort));
z3::func_decl noReoDecl = getNoReorderFuncDecl(ctx);
z3::expr args[2] = {a, v};
z3::expr fd1A = fd1(1, args); // v is not used in args here
args[0] = a;
args[1] = b;
z3::expr noReo = noReoDecl(2, args);
args[0] = b;
args[1] = v;
z3::expr fd2BV = fd2(2, args);
z3::expr bigAnd = fd1A && fd2BV;
z3::expr imp = z3::implies(bigAnd, noReo);
Z3_fixedpoint_add_rule(ctx, zfp, imp, NULL);
}
// (=> (and (fd1 a v)
// (fd2 b))
// (noreorder a b)
void addNoReoFunc2Func1(z3::context &ctx, Z3_fixedpoint &zfp
, const z3::func_decl fd1, const z3::func_decl fd2) {
z3::sort bvSort = ctx.bv_sort(Z3_BV_SIZE);
z3::expr a = z3::expr(ctx, Z3_mk_bound(ctx, 0, bvSort));
z3::expr b = z3::expr(ctx, Z3_mk_bound(ctx, 1, bvSort));
z3::expr v = z3::expr(ctx, Z3_mk_bound(ctx, 1, bvSort));
z3::func_decl noReoDecl = getNoReorderFuncDecl(ctx);
z3::expr args[2] = {a, v};
z3::expr fd1AV = fd1(2, args);
args[0] = a;
args[1] = b;
z3::expr noReo = noReoDecl(2, args);
args[0] = b;
z3::expr fd2B = fd2(1, args);
z3::expr bigAnd = fd1AV && fd2B;
z3::expr imp = z3::implies(bigAnd, noReo);
Z3_fixedpoint_add_rule(ctx, zfp, imp, NULL);
}
// Order two statements based on program order and restricted based on two
// binary predicates with the passed variables as their second item.
// (=> (and (dom a b)
// (not-reach b a)
// (fd1 a v1)
// (fd2 b v2) )
// (mhb a b))
void addPOFunc2Func2MHB(z3::context &ctx, Z3_fixedpoint &zfp
, const z3::func_decl fd1, const z3::func_decl fd2
, const z3::expr v1, const z3::expr v2) {
z3::sort bvSort = ctx.bv_sort(Z3_BV_SIZE);
z3::expr a = z3::expr(ctx, Z3_mk_bound(ctx, 0, bvSort));
z3::expr b = z3::expr(ctx, Z3_mk_bound(ctx, 1, bvSort));
z3::func_decl domDecl = getDomFuncDecl(ctx);
z3::func_decl nrDecl = getNotReachFuncDecl(ctx);
z3::func_decl mhbDecl = getMHBFuncDecl(ctx);
// (dom a b)
// (mhb a b)
z3::expr args[2] = {a, b};
z3::expr domAB = domDecl(2, args);
z3::expr mhbAB = mhbDecl(2, args);
// (not-reach b a)
args[0] = b;
args[1] = a;
z3::expr nrBA = nrDecl(2, args);
// (fd1 a v1)
args[0] = a;
args[1] = v1;
z3::expr fd1AV1 = fd1(2, args);
// (fd2 b v2)
args[0] = b;
args[1] = v2;
z3::expr fd2BV2 = fd2(2, args);
// (and (dom a b)
// (not-reach b a)
// (fd1 a v1)
// (fs2 b v2))
z3::expr bigAnd = domAB && nrBA && fd1AV1 && fd2BV2;
z3::expr imp = z3::implies(bigAnd, mhbAB);
Z3_fixedpoint_add_rule(ctx, zfp, imp, NULL);
}
// Order a store and load based on program-order and if they are to the same
// variable
// (=> (and (dom a b)
// (not-reach b a)
// (is-store a v)
// (is-load b v))
// (mhb a b))
void addStoreLoadMHB(z3::context &ctx, Z3_fixedpoint &zfp) {
z3::sort bvSort = ctx.bv_sort(Z3_BV_SIZE);
z3::expr v = z3::expr(ctx, Z3_mk_bound(ctx, 2, bvSort));
addPOFunc2Func2MHB(ctx, zfp, getStFuncDecl(ctx), getLdFuncDecl(ctx), v, v);
}
// Order a load and store based on program-order and if they are to the same
// variable
// (=> (and (dom a b)
// (not-reach b a)
// (is-load a v))
// (is-store b v)
// (mhb a b))
void addLoadStoreMHB(z3::context &ctx, Z3_fixedpoint &zfp) {
z3::sort bvSort = ctx.bv_sort(Z3_BV_SIZE);
z3::expr v = z3::expr(ctx, Z3_mk_bound(ctx, 2, bvSort));
addPOFunc2Func2MHB(ctx, zfp, getLdFuncDecl(ctx), getStFuncDecl(ctx), v, v);
}
void addLoadLoadMHB(z3::context &ctx, Z3_fixedpoint &zfp) {
z3::sort bvSort = ctx.bv_sort(Z3_BV_SIZE);
z3::expr v = z3::expr(ctx, Z3_mk_bound(ctx, 2, bvSort));
addPOFunc2Func2MHB(ctx, zfp, getLdFuncDecl(ctx), getLdFuncDecl(ctx), v, v);
}
// Add an ordering rule between two stores. If sameVar is true then the two
// stores are ordered based on the program-order and if they access the same
// variable (as on PSO). Otherwise, the stores may access any variable (as on
// TSO).
//
// That is:
//
// (=> (and (dom a b)
// (not-reach b a)
// (is-store a v1)
// (is-store b v2) )
// (mhb a b))
//
// Where v1 = v2 is sameVar is true
void addStoreStoreMHB(z3::context &ctx, Z3_fixedpoint &zfp, bool sameVar) {
z3::sort bvSort = ctx.bv_sort(Z3_BV_SIZE);
z3::expr v1 = z3::expr(ctx, Z3_mk_bound(ctx, 2, bvSort));
z3::expr v2 = v1;
if (!sameVar) {
v2 = z3::expr(ctx, Z3_mk_bound(ctx, 3, bvSort));
}
addPOFunc2Func2MHB(ctx, zfp, getStFuncDecl(ctx), getStFuncDecl(ctx), v1
, v2);
//z3::sort bvSort = ctx.bv_sort(Z3_BV_SIZE);
//z3::expr a = z3::expr(ctx, Z3_mk_bound(ctx, 0, bvSort));
//z3::expr b = z3::expr(ctx, Z3_mk_bound(ctx, 1, bvSort));
//z3::expr v1 = z3::expr(ctx, Z3_mk_bound(ctx, 2, bvSort));
//
//z3::expr v2 = v1;
//if (!sameVar) {
// v2 = z3::expr(ctx, Z3_mk_bound(ctx, 3, bvSort));
//}
//z3::func_decl domDecl = getDomFuncDecl(ctx);
//z3::func_decl nrDecl = getNotReachFuncDecl(ctx);
//z3::func_decl stDecl = getStFuncDecl(ctx);
//z3::func_decl mhbDecl = getMHBFuncDecl(ctx);
//// (dom a b)
//// (mhb a b)
//z3::expr args[2] = {a, b};
//z3::expr domAB = domDecl(2, args);
//z3::expr mhbAB = mhbDecl(2, args);
//// (not-reach b a)
//args[0] = b;
//args[1] = a;
//z3::expr nrBA = nrDecl(2, args);
//// (is-store a v1)
//// (is-store b v2)
//args[0] = a;
//args[1] = v1;
//z3::expr isStAV1 = stDecl(2, args);
//args[0] = b;
//args[1] = v2;
//z3::expr isStBV2 = stDecl(2, args);
//// (and (dom a b)
//// (not-reach b a)
//// (is-store a _)
//// (is-store b _))
//z3::expr bigAnd = domAB && nrBA && isStAV1 && isStBV2;
//z3::expr imp = z3::implies(bigAnd, mhbAB);
//Z3_fixedpoint_add_rule(ctx, zfp, imp, NULL);
}
// Return the first load, store, or terminator instruction in the basic
// block.
static Instruction *getFirstLoadStoreTerm(BasicBlock *b) {
assert(b && "NULL passed");
for (auto i = b->begin(), ie = b->end(); i != ie; ++i) {
Instruction *cur = &*i;
if (isa<LoadInst>(cur)) {
return cur;
}
else if (isa<StoreInst>(cur)) {
return cur;
}
}
// Reaching this point means the basicblock does not have any load or store
// instructions. So, just return the terminator
return b->getTerminator();
}
static Instruction *getFirstLoadStoreCallTerm(BasicBlock *b) {
assert(b && "NULL passed");
for (auto i = b->begin(), ie = b->end(); i != ie; ++i) {
Instruction *cur = &*i;
if (isa<LoadInst>(cur)) {
return cur;
}
else if (isa<StoreInst>(cur)) {
return cur;
}
else if (isa<CallInst>(cur)) {
return cur;
}
}
// Reaching this point means the basicblock does not have
// any load or store instructions. So, just return the terminator
return b->getTerminator();
}
static Instruction *getLastLoadStoreCallTerm(BasicBlock *b) {
assert(b && "NULL passed");
bool find = false;
Instruction *cur;
for (auto i = b->begin(), ie = b->end(); i != ie; ++i) {
cur = &*i;
if (isa<LoadInst>(cur)) {
find = true;
}
else if (isa<StoreInst>(cur)) {
find = true;
}
else if (isa<CallInst>(cur)) {
find = true;
}
}
if (find) {
return cur;
} else {
// Reaching this point means the basicblock does not have
// any load or store instructions. So, just return the front one
return &(b->front());
}
}
#if 0
// Given the passed basicblock, return, starting from the first, the loads
// and stores in the basicblock
static std::vector<Instruction *> getLoadStoreOrdered(BasicBlock *b) {
std::vector<Instruction *> ret;
for (auto i = b->begin(), ie = b->end(); i != ie; ++i) {
Instruction *cur = &*i;
if (isa<LoadInst>(cur)) {
DEBUG_MSG("[DEBUG] Found Load: " << cur << ": " << *cur << '\n');
ret.push_back(cur);
}
else if (isa<StoreInst>(cur)) {
DEBUG_MSG("[DEBUG] Found Store: " << cur << ": " << *cur << '\n');
ret.push_back(cur);
}
}
return ret;
}
#endif
static std::vector<Instruction *> getLoadStoreCallOrdered(BasicBlock *b) {
std::vector<Instruction *> ret;
for (auto i = b->begin(), ie = b->end(); i != ie; ++i) {
Instruction *cur = &*i;
if (isa<LoadInst>(cur)) {
DEBUG_MSG("[DEBUG] Found Load: " << cur << ": " << *cur << '\n');
ret.push_back(cur);
}
else if (isa<StoreInst>(cur)) {
DEBUG_MSG("[DEBUG] Found Store: " << cur << ": " << *cur << '\n');
ret.push_back(cur);
}
else if (isa<CallInst>(cur)) {
DEBUG_MSG("[DEBUG] Found Call" << cur << ": " << *cur << '\n');
ret.push_back(cur);
//DEBUG_MSG("[DEBUG] Found Store: " << cur << ": " << *cur << '\n');
//ret.push_back(cur);
}
}
return ret;
}
// Ensure the global command line flags are valid.
// This will crash with an error message if they are not
void checkCommandLineArgs() const {
// Atleast one abstract domain must be true
if (!useBoxG && !useOctG && !usePolyG && !useLinEqG) {
errs() << "[ERROR] Select an abstract domain (-box, -oct, -pkpoly "
<< "-pklineq)\n";
exit(EXIT_FAILURE);
}
// TSO and PSO cannot both be enabled at the same time
if (tsoConstrG && psoConstrG) {
errs() << "[ERROR] both -pso and -tso cannot be used\n";
exit(EXIT_FAILURE);
}
// Only one abstract domain should be selected
if ((useBoxG && (useOctG || usePolyG || useLinEqG))
|| (useOctG && (useBoxG || usePolyG || useLinEqG))
|| (usePolyG && (useBoxG || useOctG || useLinEqG))
|| (useLinEqG && (useBoxG || useOctG || usePolyG))) {
errs() << "[ERROR] More than one abstract domain selected\n";
exit(EXIT_FAILURE);
}
// The program-order constraint solver is only relevant in combinational
// exploration mode
if (useConstraintsG && noCombinsG) {
errs() << "[ERROR] Constraint solver mode (-constraints) must not use "
"-nocombs\n";
exit(EXIT_FAILURE);
}
// If we are using constraints, we need to know where Z3 lives
if (useConstraintsG && (z3BinLocG.size() == 0)) {
errs() << "[ERROR] -constraints without specify location of Z3 "
"(-z3 <loc>)\n";
exit(EXIT_FAILURE);
}
// Using constraints also uses dynamic thread init. Note: this is not
// strictly necessary.
if (useConstraintsG) {
dynInitG = true;
}
}
void printFuncInterfMap(
const std::map<Function *, std::map<Instruction *, LatticeFact>> fim) const {
for (auto i = fim.begin(), ie = fim.end(); i != ie; ++i) {
std::map<Instruction *, LatticeFact> stm = i->second;
for (auto j = stm.begin(), je = stm.end(); j != je; ++j) {
errs() << "Store: " << *(j->first) << '\n';
}
}
}
std::map<StoreInst *, LatticeFact> joinStFacts(
const std::map<StoreInst *, LatticeFact> m1
, const std::map<StoreInst *, LatticeFact> m2) const {
std::map<StoreInst *, LatticeFact> ret(m1);
for (auto i = m2.begin(), ie = m2.end(); i != ie; ++i) {
StoreInst *cur = i->first;
auto f = ret.find(cur);
if (f != ret.end()) {
LatticeFact newF = LatticeFact::factJoin(i->second, f->second);
ret.erase(cur);
ret.emplace(cur, newF);
}
else {
ret.emplace(cur, f->second);
}
}
return ret;
}
// Return the number of instructions in M
unsigned numInstructions(Module &M) {
unsigned n = 0;
for (auto mit = M.begin(), me = M.end(); mit != me; ++mit) {
Function &f = *mit;
for (inst_iterator ii = inst_begin(f), ie = inst_end(f); ii != ie
; ++ii) {
n++;
}
}
return n;
}
std::set<Instruction *> instsWithoutMetadata(Module &M, std::string md) {
assert(md.length() && "instsWithoutMetadata: length zero metadata");
std::set<Instruction *> ret;
return ret;
for (auto mit = M.begin(), me = M.end(); mit != me; ++mit) {
Function &f = *mit;
for (inst_iterator ii = inst_begin(f), ie = inst_end(f); ii != ie
; ++ii) {
Instruction *i = &*ii;
if (!i->getMetadata(md)) {
ret.insert(i);
}
}
}
return ret;
}
std::set<Instruction *> instsWithMetadata(Module &M, std::string md) {
assert(md.length() && "instsWithoutMetadata: length zero metadata");
std::set<Instruction *> ret;
for (auto mit = M.begin(), me = M.end(); mit != me; ++mit) {
Function &f = *mit;
for (inst_iterator ii = inst_begin(f), ie = inst_end(f); ii != ie
; ++ii) {
Instruction *i = &*ii;
if (i->getMetadata(md)) {
ret.insert(i);
}
}
}
return ret;
}
// If -impact is used then return the set of all statements in M which may
// impact a change.
//
// Otherwise, return an empty set
std::set<Instruction *> getMayImpactIfEnabled(Module &M) {
std::set<Instruction *> ret;
if (!impactG) {
return ret;
}
ret = instsWithMetadata(M, "MayImpact");
//if (ret.size() == 0) {
// errs() << "[ERROR] No may-impact statements found, did you run the change-impact pass?\n";
// exit(EXIT_FAILURE);
//}
return ret;
}
// If -impact is used then return the set of all statements in M which are
// impacted by a change.
//
// Otherwise, return an empty set
std::set<Instruction *> getImpactedIfEnabled(Module &M) {
std::set<Instruction *> ret;
if (!impactG) {
return ret;
}
ret = instsWithMetadata(M, "Impacted");
if (ret.size() == 0) {
errs() << "[ERROR] No impacted statements found, did you run the change-impact pass?\n";
exit(EXIT_FAILURE);
}
return ret;
}
// Return the inversion of the assertion slice if assertSliceG is true.
//
// The "slice inversion" is all the statements *not* on the slice.
//
// If assertSliceG is false then return an empty set.
std::set<Instruction *> getAssertSliceInvIfEnabled(Module &M) {
std::set<Instruction *> ret;
unsigned numInsts = numInstructions(M);
if (!assertSliceG) {
return ret; // size zero
}
ret = instsWithoutMetadata(M, "AssertSlice");
//for (auto mit = M.begin(), me = M.end(); mit != me; ++mit) {
// Function &f = *mit;
// for (inst_iterator ii = inst_begin(f), ie = inst_end(f); ii != ie
// ; ++ii) {
// numInsts++;
// Instruction *i = &*ii;
// if (!i->getMetadata("AssertSlice")) {
// ret.insert(i);
// }
// }
//}
//if (!ret.size()) {
if (numInsts == ret.size()) {
//errs() << "[ERROR] no statements found on slice of an assertion\n"
// "Are you sure the PDG pass has been run?\n";
errs() << "[ERROR] no statements not found on slice of an assertion\n"
"Are you sure the PDG pass has been run?\n";
exit(EXIT_FAILURE);
}
return ret;
}
};
char WorklistAI::ID = 0;
static RegisterPass<WorklistAI> X("worklist-ai"
, "worklist based abstract interpretation"
, false // unmodified CFG
, true); // analysis pass
| 36.560275 | 104 | 0.590129 | ChunghaSung |
41ce91bf7c7e8bf7c72170131baddc803b82c39d | 2,122 | cpp | C++ | src/Private/AnimSceneActions/UpdateEntitiesAction.cpp | heltena/KYEngine | 4ccb89d0b20683feb245ffe85dd34b6ffdc42c8e | [
"MIT"
] | null | null | null | src/Private/AnimSceneActions/UpdateEntitiesAction.cpp | heltena/KYEngine | 4ccb89d0b20683feb245ffe85dd34b6ffdc42c8e | [
"MIT"
] | null | null | null | src/Private/AnimSceneActions/UpdateEntitiesAction.cpp | heltena/KYEngine | 4ccb89d0b20683feb245ffe85dd34b6ffdc42c8e | [
"MIT"
] | null | null | null | #include <KYEngine/Core.h>
#include <KYEngine/SceneTimelineInfo.h>
#include <KYEngine/Utility/TiXmlHelper.h>
#include <KYEngine/Private/AnimSceneActions/UpdateEntitiesAction.h>
#include <cmath>
#include <iostream>
#include <stdexcept>
const std::string UpdateEntitiesAction::XML_NODE = "update-entities";
UpdateEntitiesAction::UpdateEntitiesAction()
{
}
UpdateEntitiesAction::~UpdateEntitiesAction()
{
}
UpdateEntitiesAction* UpdateEntitiesAction::readFromXml(TiXmlElement* node)
{
UpdateEntitiesAction* action = new UpdateEntitiesAction();
const std::string name = TiXmlHelper::readString(node, "name", false, "<<undefined>>");
action->setName(name);
TiXmlElement* curr = node->FirstChildElement();
while (curr) {
const std::string& value = curr->Value();
if (value == "add-entity") {
const std::string entityRef = TiXmlHelper::readString(node, "entity-ref", true);
action->addAddEntityRef(entityRef);
} else if (value == "remove-entity") {
const std::string entityRef = TiXmlHelper::readString(node, "entity-ref", true);
action->addRemoveEntityRef(entityRef);
} else
throw std::runtime_error("UpdateEntitiesAction: (" + name + ") tag error: " + value);
curr = curr->NextSiblingElement();
}
return action;
}
void UpdateEntitiesAction::start(SceneTimelineInfo* info)
{
std::list<Entity*> toAddEntities;
std::list<Entity*> toRemoveEntities;
for(std::list<std::string>::const_iterator it = m_toAddEntityRef.begin(); it != m_toAddEntityRef.end(); it++)
toAddEntities.push_back(Core::resourceManager().entity(*it));
for(std::list<std::string>::const_iterator it = m_toRemoveEntityRef.begin(); it != m_toRemoveEntityRef.end(); it++)
toRemoveEntities.push_back(Core::resourceManager().entity(*it));
info->layer()->updateEntities(toAddEntities, toRemoveEntities);
}
bool UpdateEntitiesAction::isBlocking()
{
return false;
}
bool UpdateEntitiesAction::isFinished()
{
return true;
}
void UpdateEntitiesAction::update(const double elapsedTime, SceneTimelineInfo* info)
{
}
| 29.472222 | 119 | 0.707352 | heltena |
41d1ac8f89497154904f297d25268ee4422b4fa9 | 4,349 | cxx | C++ | panda/src/express/profileTimer.cxx | sean5470/panda3d | ea2d4fecd4af1d4064c5fe2ae2a902ef4c9b903d | [
"PHP-3.0",
"PHP-3.01"
] | null | null | null | panda/src/express/profileTimer.cxx | sean5470/panda3d | ea2d4fecd4af1d4064c5fe2ae2a902ef4c9b903d | [
"PHP-3.0",
"PHP-3.01"
] | null | null | null | panda/src/express/profileTimer.cxx | sean5470/panda3d | ea2d4fecd4af1d4064c5fe2ae2a902ef4c9b903d | [
"PHP-3.0",
"PHP-3.01"
] | null | null | null | /**
* PANDA 3D SOFTWARE
* Copyright (c) Carnegie Mellon University. All rights reserved.
*
* All use of this software is subject to the terms of the revised BSD
* license. You should have received a copy of this license along
* with this source code in a file named "LICENSE."
*
* @file profileTimer.cxx
*/
#include "profileTimer.h"
#include "pmap.h"
using namespace std;
// See ProfileTimer.h for documentation.
EXPCL_PANDAEXPRESS ProfileTimer Skyler_timer_global=ProfileTimer("startup");
ProfileTimer* ProfileTimer::_head;
ProfileTimer::
ProfileTimer(const char* name, int maxEntries) :
_entries(0),
_autoTimerCount(0) {
// Keep a list of the ProfileTimers, so we can print them:
_next=_head;
_head=this;
if (name) {
init(name, maxEntries);
}
}
ProfileTimer::
ProfileTimer(const ProfileTimer& other) {
// Add to list:
_next=_head;
_head=this;
// init it:
_name=other._name;
_maxEntries=other._maxEntries;
if (_name) {
init(_name, _maxEntries);
}
// Copy other entries:
_on=other._on;
_elapsedTime=other._elapsedTime;
_autoTimerCount=other._autoTimerCount;
_entryCount=other._entryCount;
if (other._entries) {
memcpy(_entries, other._entries, _entryCount * sizeof(TimerEntry));
}
}
ProfileTimer::
~ProfileTimer() {
PANDA_FREE_ARRAY(_entries);
// Remove this from the list:
if (_head==this) {
_head=_next;
} else {
ProfileTimer* p=_head;
ProfileTimer* prior=p;
while (p) {
if (p==this) {
prior->_next=_next;
break;
}
prior=p;
p=p->_next;
}
}
}
void ProfileTimer::
init(const char* name, int maxEntries) {
_name=name;
_maxEntries=maxEntries;
_entries = (TimerEntry *)PANDA_MALLOC_ARRAY(_maxEntries * sizeof(TimerEntry));
_entryCount=0;
_elapsedTime=0.0;
_on=0.0;
}
double ProfileTimer::
getTotalTime() const {
double total=0;
int i;
for (i=0; i<_entryCount; ++i) {
TimerEntry& te=_entries[i];
total+=te._time;
}
return total;
}
void ProfileTimer::
consolidateAllTo(ostream &out) {
ProfileTimer* p=_head;
while (p) {
p->consolidateTo(out);
p=p->_next;
}
}
void ProfileTimer::
consolidateTo(ostream &out) const {
pmap<string, double> entries;
int i;
for (i=0; i<_entryCount; ++i) {
TimerEntry& te=_entries[i];
entries[te._tag]+=te._time;
}
out << "-------------------------------------------------------------------\n"
<< "Profile Timing of " << _name
<< "\n\n"; // ...should print data and time too.
double total=0;
{
pmap<string, double>::const_iterator i=entries.begin();
for (;i!=entries.end(); ++i) {
out << " " << setw(50) << i->first << ": "
<< setiosflags(ios::fixed) << setprecision(6) << setw(10) << i->second << "\n";
total+=i->second;
}
}
out << "\n [Total Time: "
<< setiosflags(ios::fixed) << setprecision(6) << total
<< " seconds]\n"
<< "-------------------------------------------------------------------\n";
out << endl;
}
void ProfileTimer::
printAllTo(ostream &out) {
ProfileTimer* p=_head;
while (p) {
p->printTo(out);
p=p->_next;
}
}
void ProfileTimer::
printTo(ostream &out) const {
out << "-------------------------------------------------------------------\n"
<< "Profile Timing of " << _name
<< "\n\n"; // ...should print data and time too.
double total=0;
int i;
for (i=0; i<_entryCount; ++i) {
TimerEntry& te=_entries[i];
out << " " << setw(50) << te._tag << ": "
<< setiosflags(ios::fixed) << setprecision(6) << setw(10) << te._time << "\n";
total+=te._time;
}
out << "\n [Total Time: "
<< setiosflags(ios::fixed) << setprecision(6) << total
<< " seconds]\n"
<< "-------------------------------------------------------------------\n";
out << endl;
}
ProfileTimer::AutoTimer::AutoTimer(ProfileTimer& profile, const char* tag) :
_profile(profile) {
_tag=tag;
if (_profile._autoTimerCount) {
// ...this is a nested call to another AutoTimer. Assign the time to the
// prior AutoTimer:
_profile.mark(_profile._entries[_profile._entryCount-1]._tag);
} else {
// ...this is not a nested call.
_profile.mark("other");
}
// Tell the profile that it's in an AutoTimer:
++_profile._autoTimerCount;
_profile.mark(_tag);
}
| 24.296089 | 83 | 0.584732 | sean5470 |
41d5e6fdf17048d5c977d867533b641d3d5b0f2f | 1,506 | cpp | C++ | src/HapticAssetTools.cpp | HardlightVR/HL-haptictools | c177a92ce3adab80416f0e85c1ad89083d9da6b6 | [
"MIT"
] | null | null | null | src/HapticAssetTools.cpp | HardlightVR/HL-haptictools | c177a92ce3adab80416f0e85c1ad89083d9da6b6 | [
"MIT"
] | null | null | null | src/HapticAssetTools.cpp | HardlightVR/HL-haptictools | c177a92ce3adab80416f0e85c1ad89083d9da6b6 | [
"MIT"
] | 1 | 2020-06-29T14:42:24.000Z | 2020-06-29T14:42:24.000Z | #include "stdafx.h"
#include "HapticAssetTools.h"
#include "AssetToolsLibrary.h"
#define AS_TYPE(Type, Obj) reinterpret_cast<Type *>(Obj)
#define AS_CTYPE(Type, Obj) reinterpret_cast<const Type *>(Obj)
unsigned int NS_ASSETTOOLS_API NSAT_GetVersion(void)
{
return NS_ASSETTOOLS_VERSION;
}
int NSAT_IsCompatibleDLL(void)
{
unsigned int major = NSAT_GetVersion() >> 16;
return major == NS_ASSETTOOLS_VERSION_MAJOR;
}
NS_ASSETTOOLS_API NSAT_Context_t * __stdcall NSAT_Create()
{
return AS_TYPE(NSAT_Context_t, new AssetToolsLibrary());
}
NS_ASSETTOOLS_API int __stdcall NSAT_InitializeFromDirectory(NSAT_Context_t* context, const char * dir)
{
return AS_TYPE(AssetToolsLibrary, context)->InitializeFromDirectory(dir);
}
NS_ASSETTOOLS_API void __stdcall NSAT_Delete(NSAT_Context_t * context)
{
if (!context) {
return;
}
delete AS_TYPE(AssetToolsLibrary, context);
}
NS_ASSETTOOLS_API int __stdcall NSAT_RescanFilesystem(NSAT_Context_t * context)
{
return AS_TYPE(AssetToolsLibrary, context)->Rescan();
}
NS_ASSETTOOLS_API int __stdcall NSAT_CheckIfPackage(NSAT_Context_t* context, const char* dir, PackageInfo& info, bool& isPackage)
{
return AS_TYPE(AssetToolsLibrary, context)->CheckIfPackage(dir, info, isPackage);
}
NS_ASSETTOOLS_API char * __stdcall NSAT_GetError(NSAT_Context_t * context)
{
return AS_TYPE(AssetToolsLibrary, context)->GetError();
}
NS_ASSETTOOLS_API void __stdcall NSAT_FreeError(char * stringPointer)
{
delete[] stringPointer;
stringPointer = nullptr;
}
| 23.53125 | 129 | 0.790837 | HardlightVR |
41d621c72ebdc8325cb1780ec683d6060004089d | 578 | cpp | C++ | code/1087 1 10 100 1000.cpp | PIPIKAI/ACM | b8e4416a29c0619946c9b73b0fe5699b6e96e782 | [
"MIT"
] | null | null | null | code/1087 1 10 100 1000.cpp | PIPIKAI/ACM | b8e4416a29c0619946c9b73b0fe5699b6e96e782 | [
"MIT"
] | null | null | null | code/1087 1 10 100 1000.cpp | PIPIKAI/ACM | b8e4416a29c0619946c9b73b0fe5699b6e96e782 | [
"MIT"
] | null | null | null | #include<stdio.h>
long long f[1000000];
int main()
{
int n;
long long sum=1,i=0;
while(sum<=1000000000)
{
f[i]=sum;
i++;
sum+=i;
}
scanf("%d",&n);
for(int i=0;i<n;i++)
{
int temp;
scanf("%d",&temp);
for(int j=0;j<=44721;j++)
{
if(f[j]==temp)
{
printf("1\n");
break;
}
if(f[j]>temp)
{
printf("0\n");
break;
}
}
}
return 0;
}
| 15.210526 | 33 | 0.313149 | PIPIKAI |
41d78e97494757744c4c1321b744ac7dea15b3ec | 2,771 | cpp | C++ | plot-test.cpp | kp2pml30/spring-pendulum | abbfdb7d445fc439c0d6006c0de04dc467577c7e | [
"MIT"
] | null | null | null | plot-test.cpp | kp2pml30/spring-pendulum | abbfdb7d445fc439c0d6006c0de04dc467577c7e | [
"MIT"
] | null | null | null | plot-test.cpp | kp2pml30/spring-pendulum | abbfdb7d445fc439c0d6006c0de04dc467577c7e | [
"MIT"
] | null | null | null | #include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <chrono>
#include <iostream>
#include <memory>
#include <stdexcept>
#include <numbers>
#include "Solvers.h"
using vec2 = mth::vec2<double>;
namespace
{
static constexpr double TO = 4;
static constexpr double STEP = 1;
void error_callback(int error, char const* description)
{
std::cerr << "Error : " << description << std::endl;
}
vec2 Map(vec2 a)
{
/*
* 0, 1 -> -1, -1
* 4, e(4) -> 1, 1
*/
a.Y = (a.Y - 1) / (std::exp(TO) - 1) * 2 - 1;
a.X = a.X / TO * 2 - 1;
return a;
}
template<typename F>
void Draw(F const& f, double d, double U)
{
{
auto f0 = f(0);
auto v2 = Map(f(0));
glVertex2f(v2.X, v2.Y);
}
for (double i = 0; i <= U; i += d)
{
auto v2 = Map(f(d));
glVertex2f(v2.X, v2.Y);
}
}
double EDelta(double v, double h)
{
return v;
}
}
int main()
{
glfwSetErrorCallback(error_callback);
if (!glfwInit())
return 1;
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);
GLFWwindow* window = glfwCreateWindow(640, 480, "spring pendulum", NULL, NULL);
if (!window)
{
glfwTerminate();
return 1;
}
glfwMakeContextCurrent(window);
glfwSwapInterval(1);
if (auto err = glewInit(); err != GLEW_OK)
{
std::cerr << "glew init error " << glewGetErrorString(err) << std::endl;
return 1;
}
glClearColor(0, 0, 0, 0);
glEnable(GL_LINE_WIDTH);
while (!glfwWindowShouldClose(window))
{
int width, height;
glfwGetFramebufferSize(window, &width, &height);
glViewport(0, 0, width, height);
glClear(GL_COLOR_BUFFER_BIT);
glLineWidth(5);
glBegin(GL_LINE_STRIP);
{
glColor3f(1, 1, 1);
double cur = 0;
Draw([&](double d)
{
auto r = vec2(cur, std::exp(cur));
cur += d;
return r;
},
STEP,
TO);
}
glEnd();
glLineWidth(3);
glBegin(GL_LINE_STRIP);
{
glColor3f(0, 1, 0);
double cur = 0;
double prev = 1;
Draw([&](double d)
{
prev += Euler(EDelta, prev, d);
cur += d;
auto r = vec2(cur, prev);
return r;
},
STEP,
TO);
}
glEnd();
glBegin(GL_LINE_STRIP);
{
glColor3f(1, 0, 0);
double cur = 0;
double prev = 1;
Draw([&](double d)
{
prev += RungeKutta(EDelta, prev, d);
cur += d;
auto r = vec2(cur, prev);
return r;
},
STEP,
TO);
}
glEnd();
glBegin(GL_LINE_STRIP);
{
glColor3f(0.2, 0.2, 1);
double cur = 0;
double prev = 1;
Draw([&](double d)
{
prev += Midpoint(EDelta, prev, d);
cur += d;
auto r = vec2(cur, prev);
return r;
},
STEP,
TO);
}
glEnd();
glfwSwapBuffers(window);
glfwPollEvents();
}
glfwDestroyWindow(window);
glfwTerminate();
}
| 17.537975 | 80 | 0.568387 | kp2pml30 |
41da1889fcd6a6f0b9e493676c03fa5ab2d3835b | 462 | cpp | C++ | application/pages/modplatform/TechnicPage.cpp | StephenGss/Polycraft-Launcher | d70f6729dba876e0252b075dcfd4c9caa45113b2 | [
"Apache-2.0"
] | 3 | 2020-10-08T19:55:33.000Z | 2021-11-28T04:02:39.000Z | application/pages/modplatform/TechnicPage.cpp | StephenGss/Polycraft-Launcher | d70f6729dba876e0252b075dcfd4c9caa45113b2 | [
"Apache-2.0"
] | null | null | null | application/pages/modplatform/TechnicPage.cpp | StephenGss/Polycraft-Launcher | d70f6729dba876e0252b075dcfd4c9caa45113b2 | [
"Apache-2.0"
] | null | null | null | #include "TechnicPage.h"
#include "ui_TechnicPage.h"
#include "PolycraftLauncher.h"
#include "dialogs/NewInstanceDialog.h"
TechnicPage::TechnicPage(NewInstanceDialog* dialog, QWidget *parent)
: QWidget(parent), ui(new Ui::TechnicPage), dialog(dialog)
{
ui->setupUi(this);
}
TechnicPage::~TechnicPage()
{
delete ui;
}
bool TechnicPage::shouldDisplay() const
{
return true;
}
void TechnicPage::openedImpl()
{
dialog->setSuggestedPack();
}
| 17.111111 | 68 | 0.718615 | StephenGss |
41da2a660915e34383118a58e3bb474392502bab | 559 | cc | C++ | rocks-sys/rocks/rate_limiter.cc | sezaru/rust-rocks | 06245eedaf91b8358688abefa67eba802b607142 | [
"Apache-2.0"
] | 40 | 2017-05-16T06:10:51.000Z | 2021-09-02T01:06:37.000Z | rocks-sys/rocks/rate_limiter.cc | sezaru/rust-rocks | 06245eedaf91b8358688abefa67eba802b607142 | [
"Apache-2.0"
] | 12 | 2017-06-11T09:42:02.000Z | 2020-10-11T23:46:31.000Z | rocks-sys/rocks/rate_limiter.cc | sezaru/rust-rocks | 06245eedaf91b8358688abefa67eba802b607142 | [
"Apache-2.0"
] | 8 | 2017-05-16T03:44:53.000Z | 2020-10-11T22:01:17.000Z |
#include "rocksdb/rate_limiter.h"
#include "rocks/ctypes.hpp"
using namespace ROCKSDB_NAMESPACE;
using std::shared_ptr;
extern "C" {
// FIXME: leaks a ointer size
rocks_ratelimiter_t* rocks_ratelimiter_create(int64_t rate_bytes_per_sec, int64_t refill_period_us, int32_t fairness) {
rocks_ratelimiter_t* rate_limiter = new rocks_ratelimiter_t;
rate_limiter->rep.reset(NewGenericRateLimiter(rate_bytes_per_sec, refill_period_us, fairness));
return rate_limiter;
}
void rocks_ratelimiter_destroy(rocks_ratelimiter_t* limiter) { delete limiter; }
}
| 26.619048 | 119 | 0.810376 | sezaru |
41dbdf267eacda1aa0f29f85b8807661c647fa0f | 4,647 | cc | C++ | chrome/browser/process_singleton_mac_unittest.cc | gavinp/chromium | 681563ea0f892a051f4ef3d5e53438e0bb7d2261 | [
"BSD-3-Clause"
] | 1 | 2016-03-10T09:13:57.000Z | 2016-03-10T09:13:57.000Z | chrome/browser/process_singleton_mac_unittest.cc | gavinp/chromium | 681563ea0f892a051f4ef3d5e53438e0bb7d2261 | [
"BSD-3-Clause"
] | 1 | 2022-03-13T08:39:05.000Z | 2022-03-13T08:39:05.000Z | chrome/browser/process_singleton_mac_unittest.cc | gavinp/chromium | 681563ea0f892a051f4ef3d5e53438e0bb7d2261 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <errno.h>
#include <fcntl.h>
#include <sys/file.h>
#include "chrome/browser/process_singleton.h"
#include "base/eintr_wrapper.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/base/testing_profile.h"
#include "testing/platform_test.h"
namespace {
class ProcessSingletonMacTest : public PlatformTest {
public:
virtual void SetUp() {
PlatformTest::SetUp();
// Put the lock in a temporary directory. Doesn't need to be a
// full profile to test this code.
ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
lock_path_ = temp_dir_.path().Append(chrome::kSingletonLockFilename);
}
virtual void TearDown() {
PlatformTest::TearDown();
// Verify that the lock was released.
EXPECT_FALSE(IsLocked());
}
// Return |true| if the file exists and is locked. Forces a failure
// in the containing test in case of error condition.
bool IsLocked() {
int fd = HANDLE_EINTR(open(lock_path_.value().c_str(), O_RDONLY));
if (fd == -1) {
EXPECT_EQ(ENOENT, errno) << "Unexpected error opening lockfile.";
return false;
}
file_util::ScopedFD auto_close(&fd);
int rc = HANDLE_EINTR(flock(fd, LOCK_EX|LOCK_NB));
// Got the lock, so it wasn't already locked. Close releases.
if (rc != -1)
return false;
// Someone else has the lock.
if (errno == EWOULDBLOCK)
return true;
EXPECT_EQ(EWOULDBLOCK, errno) << "Unexpected error acquiring lock.";
return false;
}
ScopedTempDir temp_dir_;
FilePath lock_path_;
};
// Test that the base case doesn't blow up.
TEST_F(ProcessSingletonMacTest, Basic) {
ProcessSingleton ps(temp_dir_.path());
EXPECT_FALSE(IsLocked());
EXPECT_TRUE(ps.Create());
EXPECT_TRUE(IsLocked());
ps.Cleanup();
EXPECT_FALSE(IsLocked());
}
// The destructor should release the lock.
TEST_F(ProcessSingletonMacTest, DestructorReleases) {
EXPECT_FALSE(IsLocked());
{
ProcessSingleton ps(temp_dir_.path());
EXPECT_TRUE(ps.Create());
EXPECT_TRUE(IsLocked());
}
EXPECT_FALSE(IsLocked());
}
// Multiple singletons should interlock appropriately.
TEST_F(ProcessSingletonMacTest, Interlock) {
ProcessSingleton ps1(temp_dir_.path());
ProcessSingleton ps2(temp_dir_.path());
// Windows and Linux use a command-line flag to suppress this, but
// it is on a sub-process so the scope is contained. Rather than
// add additional API to process_singleton.h in an #ifdef, just tell
// the reader what to expect and move on.
LOG(ERROR) << "Expect two failures to obtain the lock.";
// When |ps1| has the lock, |ps2| cannot get it.
EXPECT_FALSE(IsLocked());
EXPECT_TRUE(ps1.Create());
EXPECT_TRUE(IsLocked());
EXPECT_FALSE(ps2.Create());
ps1.Cleanup();
// And when |ps2| has the lock, |ps1| cannot get it.
EXPECT_FALSE(IsLocked());
EXPECT_TRUE(ps2.Create());
EXPECT_TRUE(IsLocked());
EXPECT_FALSE(ps1.Create());
ps2.Cleanup();
EXPECT_FALSE(IsLocked());
}
// Like |Interlock| test, but via |NotifyOtherProcessOrCreate()|.
TEST_F(ProcessSingletonMacTest, NotifyOtherProcessOrCreate) {
ProcessSingleton ps1(temp_dir_.path());
ProcessSingleton ps2(temp_dir_.path());
// Windows and Linux use a command-line flag to suppress this, but
// it is on a sub-process so the scope is contained. Rather than
// add additional API to process_singleton.h in an #ifdef, just tell
// the reader what to expect and move on.
LOG(ERROR) << "Expect two failures to obtain the lock.";
// When |ps1| has the lock, |ps2| cannot get it.
EXPECT_FALSE(IsLocked());
EXPECT_EQ(ProcessSingleton::PROCESS_NONE, ps1.NotifyOtherProcessOrCreate());
EXPECT_TRUE(IsLocked());
EXPECT_EQ(ProcessSingleton::PROFILE_IN_USE, ps2.NotifyOtherProcessOrCreate());
ps1.Cleanup();
// And when |ps2| has the lock, |ps1| cannot get it.
EXPECT_FALSE(IsLocked());
EXPECT_EQ(ProcessSingleton::PROCESS_NONE, ps2.NotifyOtherProcessOrCreate());
EXPECT_TRUE(IsLocked());
EXPECT_EQ(ProcessSingleton::PROFILE_IN_USE, ps1.NotifyOtherProcessOrCreate());
ps2.Cleanup();
EXPECT_FALSE(IsLocked());
}
// TODO(shess): Test that the lock is released when the process dies.
// DEATH_TEST? I don't know. If the code to communicate between
// browser processes is ever written, this all would need to be tested
// more like the other platforms, in which case it would be easy.
} // namespace
| 31.187919 | 80 | 0.713579 | gavinp |
41de11a203843e20f35ac3606529553f96bc13be | 10,117 | cpp | C++ | src/Event.cpp | JeromeOrtali/PureBasic-Engine3D | bc584c6469a15cee4c2c7c1deb5dadfe91595eff | [
"BSD-2-Clause",
"Apache-2.0"
] | 1 | 2020-07-26T01:30:45.000Z | 2020-07-26T01:30:45.000Z | src/Event.cpp | JeromeOrtali/PureBasic-Engine3D | bc584c6469a15cee4c2c7c1deb5dadfe91595eff | [
"BSD-2-Clause",
"Apache-2.0"
] | null | null | null | src/Event.cpp | JeromeOrtali/PureBasic-Engine3D | bc584c6469a15cee4c2c7c1deb5dadfe91595eff | [
"BSD-2-Clause",
"Apache-2.0"
] | null | null | null | /* PureBasic Engine3D licence
* --------------------------
*
* MIT License
*
* Copyright (c) 2017 Jerome Ortali
*
* 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 "Event.hpp"
///////////////////////////////////////////////////////////////////////////////
//
///////////////////////////////////////////////////////////////////////////////
PB_EventHandler::PB_EventHandler(Urho3D::Context* context) : Urho3D::Object(context) {
SubscribeToEvent(Urho3D::E_KEYDOWN, URHO3D_HANDLER(PB_EventHandler, ev_KeyDown));
SubscribeToEvent(Urho3D::E_KEYUP, URHO3D_HANDLER(PB_EventHandler, ev_KeyUp));
SubscribeToEvent(Urho3D::E_MOUSEBUTTONDOWN, URHO3D_HANDLER(PB_EventHandler, ev_MouseButtonDown));
SubscribeToEvent(Urho3D::E_MOUSEBUTTONUP, URHO3D_HANDLER(PB_EventHandler, ev_MouseButtonUp));
SubscribeToEvent(Urho3D::E_MOUSEMOVE, URHO3D_HANDLER(PB_EventHandler, ev_MouseMove));
SubscribeToEvent(Urho3D::E_MOUSEWHEEL, URHO3D_HANDLER(PB_EventHandler, ev_MouseWheel));
SubscribeToEvent(Urho3D::E_RESOURCEBACKGROUNDLOADED, URHO3D_HANDLER(PB_EventHandler, ev_BackgroundLoadResource));
SubscribeToEvent(Urho3D::E_FILECHANGED, URHO3D_HANDLER(PB_EventHandler, ev_ResourceFileChange));
attachObserver(this);
}
///////////////////////////////////////////////////////////////////////////////
//
///////////////////////////////////////////////////////////////////////////////
void PB_EventHandler::ev_KeyDown(Urho3D::StringHash eventType, Urho3D::VariantMap& eventData) {
Event event;
event.type = keyDown;
event.key.key = eventData[Urho3D::KeyDown::P_KEY].GetInt();
event.key.scancode = eventData[Urho3D::KeyDown::P_SCANCODE].GetInt();
event.key.buttons = eventData[Urho3D::KeyDown::P_BUTTONS].GetInt();
event.key.qualifiers = eventData[Urho3D::KeyDown::P_QUALIFIERS].GetInt();
event.key.repeat = eventData[Urho3D::KeyDown::P_REPEAT].GetInt();
notifyObservers((int)event.type, &event, sizeof(Event));
PB_EVENT->push(event);
}
///////////////////////////////////////////////////////////////////////////////
//
///////////////////////////////////////////////////////////////////////////////
void PB_EventHandler::ev_KeyUp(Urho3D::StringHash eventType, Urho3D::VariantMap& eventData) {
Event event;
event.type = keyUp;
event.key.key = eventData[Urho3D::KeyUp::P_KEY].GetInt();
event.key.scancode = eventData[Urho3D::KeyUp::P_SCANCODE].GetInt();
event.key.buttons = eventData[Urho3D::KeyUp::P_BUTTONS].GetInt();
event.key.qualifiers = eventData[Urho3D::KeyUp::P_QUALIFIERS].GetInt();
event.key.repeat = 0;
notifyObservers((int)event.type, &event, sizeof(Event));
PB_EVENT->push(event);
}
///////////////////////////////////////////////////////////////////////////////
//
///////////////////////////////////////////////////////////////////////////////
void PB_EventHandler::ev_MouseButtonDown(Urho3D::StringHash eventType, Urho3D::VariantMap& eventData) {
Event event;
event.type = mouseButtonDown;
event.mousebutton.button = eventData[Urho3D::MouseButtonDown::P_BUTTON].GetInt();
event.mousebutton.buttons = eventData[Urho3D::MouseButtonDown::P_BUTTONS].GetInt();
event.mousebutton.qualifiers = eventData[Urho3D::MouseButtonDown::P_QUALIFIERS].GetInt();
notifyObservers((int)event.type, &event, sizeof(Event));
PB_EVENT->push(event);
}
///////////////////////////////////////////////////////////////////////////////
//
///////////////////////////////////////////////////////////////////////////////
void PB_EventHandler::ev_MouseButtonUp(Urho3D::StringHash eventType, Urho3D::VariantMap& eventData) {
Event event;
event.type = mouseButtonUp;
event.mousebutton.button = eventData[Urho3D::MouseButtonUp::P_BUTTON].GetInt();
event.mousebutton.buttons = eventData[Urho3D::MouseButtonUp::P_BUTTONS].GetInt();
event.mousebutton.qualifiers = eventData[Urho3D::MouseButtonUp::P_QUALIFIERS].GetInt();
notifyObservers((int)event.type, &event, sizeof(Event));
PB_EVENT->push(event);
}
///////////////////////////////////////////////////////////////////////////////
//
///////////////////////////////////////////////////////////////////////////////
void PB_EventHandler::ev_MouseMove(Urho3D::StringHash eventType, Urho3D::VariantMap& eventData) {
Event event;
event.type = mouseMove;
event.mousemove.x = eventData[Urho3D::MouseMove::P_X].GetInt();
event.mousemove.y = eventData[Urho3D::MouseMove::P_Y].GetInt();
event.mousemove.dx = eventData[Urho3D::MouseMove::P_DX].GetInt();
event.mousemove.dy = eventData[Urho3D::MouseMove::P_DY].GetInt();
event.mousemove.buttons = eventData[Urho3D::MouseMove::P_BUTTONS].GetInt();
event.mousemove.qualifiers = eventData[Urho3D::MouseMove::P_QUALIFIERS].GetInt();
notifyObservers((int)event.type, &event, sizeof(Event));
PB_EVENT->push(event);
}
///////////////////////////////////////////////////////////////////////////////
//
///////////////////////////////////////////////////////////////////////////////
void PB_EventHandler::ev_MouseWheel(Urho3D::StringHash eventType, Urho3D::VariantMap& eventData) {
Event event;
event.type = mouseWheel;
event.mousewheel.wheel = eventData[Urho3D::MouseWheel::P_WHEEL].GetInt();
event.mousewheel.buttons = eventData[Urho3D::MouseWheel::P_BUTTONS].GetInt();
event.mousewheel.qualifiers = eventData[Urho3D::MouseWheel::P_QUALIFIERS].GetInt();
notifyObservers((int)event.type, &event, sizeof(Event));
PB_EVENT->push(event);
}
///////////////////////////////////////////////////////////////////////////////
//
///////////////////////////////////////////////////////////////////////////////
void PB_EventHandler::ev_BackgroundLoadResource(Urho3D::StringHash eventType, Urho3D::VariantMap& eventData) {
Event event;
event.type = backgroundResourceLoaded;
event.resourceLoaded.name = (wchar_t*)Urho3D::WString( eventData[Urho3D::ResourceBackgroundLoaded::P_RESOURCENAME].GetString() ).CString();
event.resourceLoaded.success = (int) eventData[Urho3D::ResourceBackgroundLoaded::P_SUCCESS].GetBool();
event.resourceLoaded.resource = (void*) eventData[Urho3D::ResourceBackgroundLoaded::P_RESOURCE].GetPtr();
notifyObservers((int)event.type, &event, sizeof(Event));
PB_EVENT->push(event);
}
///////////////////////////////////////////////////////////////////////////////
//
///////////////////////////////////////////////////////////////////////////////
void PB_EventHandler::ev_ResourceFileChange(Urho3D::StringHash eventType, Urho3D::VariantMap& eventData) {
Event event;
event.type = resourceFileChange;
event.resourceFileChange.resourceName = (wchar_t*)Urho3D::WString(eventData[Urho3D::FileChanged::P_RESOURCENAME].GetString()).CString();
event.resourceFileChange.fileName = (wchar_t*)Urho3D::WString(eventData[Urho3D::FileChanged::P_FILENAME].GetString()).CString();
notifyObservers((int)event.type, &event, sizeof(Event));
PB_EVENT->push(event);
}
///////////////////////////////////////////////////////////////////////////////
//
///////////////////////////////////////////////////////////////////////////////
void PB_EventHandler::notify(int what, void* data, int size) {
for (auto & m : m_bindfunction) {
if (what == m.first) {
Event &event = *(Event*)data;
(*m.second)(&event);
}
}
}
///////////////////////////////////////////////////////////////////////////////
//
///////////////////////////////////////////////////////////////////////////////
void PB_EventHandler::bindFunction(EventType type, fn_callback callback) {
auto found = m_bindfunction.find(type);
if (found == m_bindfunction.end()) {
m_bindfunction.emplace(type, callback);
}
}
///////////////////////////////////////////////////////////////////////////////
//
///////////////////////////////////////////////////////////////////////////////
void PB_EventHandler::unBindFunction(EventType type, fn_callback) {
auto found = m_bindfunction.find(type);
if (found != m_bindfunction.end()) {
m_bindfunction.erase(found);
}
}
///////////////////////////////////////////////////////////////////////////////
// EXPORTED FUNCTIONS
///////////////////////////////////////////////////////////////////////////////
PB_FUNCTION(int) uh3_PoolEvent(Event* ev) {
if (PB_EVENT->size()) {
*ev = PB_EVENT->front();
PB_EVENT->pop();
return 1;
}
return 0;
}
///////////////////////////////////////////////////////////////////////////////
//
///////////////////////////////////////////////////////////////////////////////
PB_FUNCTION(void) uh3_BindEvent(int type, void* callback) {
PB_URHOEVENT->bindFunction((EventType)type, (PB_EventHandler::fn_callback)callback);
}
///////////////////////////////////////////////////////////////////////////////
//
///////////////////////////////////////////////////////////////////////////////
PB_FUNCTION(void) uh3_UnBindEvent(int type, void* callback) {
PB_URHOEVENT->unBindFunction((EventType)type, (PB_EventHandler::fn_callback)callback);
} | 43.607759 | 142 | 0.560443 | JeromeOrtali |
41de92bde3868e46c194e39ac673bf598bf0779c | 428 | cpp | C++ | src_test/uuid.test.cpp | hannes-hochreiner/raw-data-db-agent | 1797e3b897f4e07cd253b5b45b4c1daba203ec62 | [
"MIT"
] | null | null | null | src_test/uuid.test.cpp | hannes-hochreiner/raw-data-db-agent | 1797e3b897f4e07cd253b5b45b4c1daba203ec62 | [
"MIT"
] | null | null | null | src_test/uuid.test.cpp | hannes-hochreiner/raw-data-db-agent | 1797e3b897f4e07cd253b5b45b4c1daba203ec62 | [
"MIT"
] | null | null | null | #include <gtest/gtest.h>
#include "uuid.hpp"
namespace {
TEST(global, round_trip) {
std::string res = get_uuid();
const std::string hex_chars("0123456789ABCDEF");
for (uint cntr = 0; cntr < 36; cntr++) {
if ((cntr == 8) || (cntr == 13) || (cntr == 18) || (cntr == 23)) {
EXPECT_EQ('-', res[cntr]);
} else {
EXPECT_NE(hex_chars.find(res[cntr]), std::string::npos);
}
}
}
}
| 23.777778 | 72 | 0.535047 | hannes-hochreiner |
41e09a337a7c44ec991403185888fc8b48bb448c | 9,585 | cpp | C++ | video/common/Video/jhcExpVSrc.cpp | Bhaskers-Blu-Org1/ALIA | 3184441a0720e75322497b0ed60fad35e843b900 | [
"Apache-2.0"
] | 1 | 2020-03-01T13:22:34.000Z | 2020-03-01T13:22:34.000Z | video/common/Video/jhcExpVSrc.cpp | Bhaskers-Blu-Org1/ALIA | 3184441a0720e75322497b0ed60fad35e843b900 | [
"Apache-2.0"
] | null | null | null | video/common/Video/jhcExpVSrc.cpp | Bhaskers-Blu-Org1/ALIA | 3184441a0720e75322497b0ed60fad35e843b900 | [
"Apache-2.0"
] | 1 | 2020-07-30T10:24:58.000Z | 2020-07-30T10:24:58.000Z | // jhcExpVSrc.cpp : iterator for shoveling images to analysis programs
//
// Written by Jonathan H. Connell, jconnell@alum.mit.edu
//
///////////////////////////////////////////////////////////////////////////
//
// Copyright 1998-2014 IBM Corporation
//
// 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 "Interface/jhcString.h"
#include "Interface/jhcPickStep.h"
#include "Interface/jhcPickVals.h"
#include "Interface/jhcPickString.h"
#include "Video/jhcVidReg.h"
#include "Video/jhcExpVSrc.h"
//////////////////////////////////////////////////////////////////////////////
// Basic creation and deletion //
//////////////////////////////////////////////////////////////////////////////
//= Constructor makes up a stream of the requested class.
jhcExpVSrc::jhcExpVSrc ()
{
noisy = 1;
index = 1;
Defaults();
}
//= Constructor that takes file name at creation time.
jhcExpVSrc::jhcExpVSrc (const char *name) : jhcGenVSrc(name)
{
noisy = 1;
index = 1;
Defaults();
SetSize(0, 0, 0);
}
//= Need to size internal array properly when source is changed.
int jhcExpVSrc::SetSource (const char *name)
{
if (jhcGenVSrc::SetSource(name) != 1)
return 0;
SetSize(xlim, ylim, Mono);
return 1;
}
//////////////////////////////////////////////////////////////////////////////
// Configuration Parameters //
//////////////////////////////////////////////////////////////////////////////
//= Pop dialog box asking for playback parameters.
// force stream to new values if not already there
// returns 1 if some alteration might have been made
int jhcExpVSrc::AskStep ()
{
jhcPickStep dlg;
double new_fps;
// run dialog box
if (dlg.EditStep(play, freq) < 1)
return 0;
// ask for new framerate directly from source
new_fps = freq / DispRate;
SetRate(new_fps);
DispRate = freq / new_fps;
// adjust frame stepping parameters
SetStep(Increment, ByKey);
if ((nextread < 1) ||
((nframes > 0) && (nextread > nframes)) ||
((FirstFrame > 0) && (nextread < FirstFrame)) ||
((LastFrame > 0) && (nextread > LastFrame)))
Rewind();
return 1;
}
//= Pop dialog box asking for image resizing parameters.
// returns 1 if some alteration might have been made
int jhcExpVSrc::AskSize ()
{
jhcPickVals dlg;
if (dlg.EditParams(squash) < 1)
return 0;
SetSize(xlim, ylim, Mono);
return 1;
}
//= Ask user to given a textual specification of the stream he wants.
// returns 1 if some alteration might have been made
int jhcExpVSrc::AskSource ()
{
jhcPickString dlg;
char fname[250];
strcpy0(fname, FileName, 250);
if (dlg.EditString(fname, 0, "Video source file:", 250) < 1)
return 0;
SetSource(fname);
return 1;
}
//= Ask user to choose new file for stream.
// will copy choice into string if one is provided
// returns 1 if a was file selected, 0 if user cancelled
int jhcExpVSrc::SelectFile (char *choice, int ssz)
{
CFileDialog dlg(TRUE);
OPENFILENAME *vals = &(dlg.m_ofn);
const char *filter;
jhcString kinds, sel, idir(JustDir);
int len;
if (_stricmp(Flavor, "vfw") != 0)
vals->lpstrInitialDir = idir.Txt();
filter = jvreg.FilterTxt(0, &len);
kinds.Set(filter, len);
vals->lpstrFilter = kinds.Txt();
if (dlg.DoModal() == IDOK)
{
sel.Set(vals->lpstrFile);
SetSource(sel.ch);
if (choice != NULL)
strcpy_s(choice, ssz, sel.ch);
return 1;
}
return 0;
}
//= Configure pointers and default values pairings.
// load new defaults from a file (if any)
void jhcExpVSrc::Defaults (char *fname)
{
squash.SetTag("vid_size");
squash.ClearAll();
squash.NextSpec4( &xlim, 0, "Max width");
squash.NextSpec4( &ylim, 0, "Max height");
squash.NextSpec4( &Avg, 0, "Averaging style");
squash.NextSpec4( &Mono, 0, "Monochrome style");
squash.NextSpec4( &Quad, 0, "Extracted quadrant");
squash.NextSpec4( &Shift, 0, "Downshift pixels"); // only for Kinect
squash.NextSpec4( &w, 0, "Current width");
squash.NextSpec4( &h, 0, "Current height");
// some things are for display purposes only
play.LockMatch( &w, 1);
play.LockMatch( &h, 1);
// get values from file (if any)
squash.LoadDefs(fname);
squash.RevertAll();
play.LoadDefs(fname);
play.RevertAll();
}
//= Save current values out as a defaults in specified file.
void jhcExpVSrc::SaveVals (char *fname)
{
squash.SaveVals(fname);
play.SaveVals(fname);
}
//////////////////////////////////////////////////////////////////////////////
// Core Functions //
//////////////////////////////////////////////////////////////////////////////
//= Force width, height, and base image to be consistent with these values.
// sometimes underlying stream or desired size is changed asynchronously
// can optionally request that frames be converted to monochrome (bw nonzero)
// should call this when quadrant processing is selected or deselected
// a positive quadrant picks that number, negative picks left or right side
// @see Processing.jhcGray#ForceMono
void jhcExpVSrc::SetSize (int xmax, int ymax, int bw)
{
int xreq = xmax, yreq = ymax;
double f = 1.0, f2 = 1.0;
// adjust total image size if request is for one panel
if (Quad > 0)
{
xreq *= 2;
yreq *= 2;
}
else if (Quad < 0)
xreq *= 2;
// see if source can shrink images directly via partial decoding
jhcGenVSrc::SetSize(xreq, yreq, bw);
base.SetSize(w, h, d);
base2.SetSize(w2, h2, d2);
// figure out additional shrink factor needed using new w and h
if (xreq > 0)
f = w / (double) xreq;
if (yreq > 0)
f2 = h / (double) yreq;
if ((f > 1.0) || (f2 > 1.0))
f = __max(f, f2);
else
f = __min(f, f2);
// determine size of one quadrant (or possibly whole image)
if (Quad > 0)
{
w /= 2;
h /= 2;
w2 /= 2;
h2 /= 2;
}
else if (Quad < 0)
{
w /= 2;
w2 /= 2;
}
qbase.SetSize(w, h, d);
qbase.SetSize(w2, h2, d2);
// mark whether monochrome conversion needed
// special negative Mono mode makes RGB with all equal
mc = 1;
if (Mono < 0)
{
d = 3;
if (d2 == 3)
d2 = 3;
}
else if ((Mono > 0) && (d == 3))
{
d = 1;
if (d2 == 3)
d2 = 1;
}
else
mc = 0;
mbase.SetSize(w, h, d);
mbase2.SetSize(w2, h2, d2);
// always promise to finally generate size that user asked for
w = ROUND(w / f);
h = ROUND(h / f);
w2 = ROUND(w2 / f);
h2 = ROUND(h2 / f);
}
//= Pass through to underlying video stream, reset pause counter.
int jhcExpVSrc::iSeek (int number)
{
int ans;
if (gvid == NULL)
return 0;
ans = gvid->Seek(number);
ok = gvid->Valid();
return ans;
}
//= Try retrieving next image and possibly resizing it.
// tell actual number of frames advanced
// captures into base, gets quad into qbase, gets mono into mbase
int jhcExpVSrc::iGet (jhcImg& dest, int *advance, int src)
{
int ans;
jhcImg *b = ((src > 0) ? &base2 : &base);
jhcImg *q = ((src > 0) ? &qbase2 : &qbase);
jhcImg *m = ((src > 0) ? &mbase2 : &mbase);
jhcImg *s = b;
// communicate possible auto-looping
if (gvid == NULL)
return 0;
gvid->LastFrame = LastFrame;
// get basic frame into base image or directly into output
// if (dest.SameFormat(base) && (mc <= 0))
if ((xlim <= 0) && (ylim <= 0) && (Mono == 0))
{
s = &dest;
ans = gvid->Get(*s, src);
b->SetSize(*s); // for jhcListVSrc where frames change size
dest.SetSize(*b);
}
else
ans = gvid->Get(*s, src);
// determine amount actually advanced
ok = gvid->Valid();
if (ok > 0)
*advance = gvid->Advance(); // extract "n"
else
*advance = 0;
ParseName(gvid->File());
// possibly abort if frame fetch failed or no alterations needed
if ((ans <= 0) || (s == &dest))
return ans;
// see if should get only a quadrant or one side of the image
if (Quad > 0)
{
if (dest.SameFormat(*q) && (mc <= 0))
return jr.GetQuad(dest, *s, Quad);
jr.GetQuad(*q, *s, Quad);
s = q;
}
else if (Quad < 0)
{
if (dest.SameFormat(*q) && (mc <= 0))
return jr.GetHalf(dest, *s, -Quad);
jr.GetHalf(*q, *s, -Quad);
s = q;
}
// see if color to monochrome conversion needed
if (mc > 0)
{
if (dest.SameFormat(*m))
return jg.ForceMono(dest, *s, abs(Mono));
jg.ForceMono(*m, *s, abs(Mono));
s = m;
}
// do further down-sizing as required
return jr.ForceSize(dest, *s, Avg);
}
//= Get next pair of images from source.
// NOTE: ignores any resizing
int jhcExpVSrc::iDual (jhcImg& dest, jhcImg& dest2)
{
int ans;
// communicate possible auto-looping
if (gvid == NULL)
return 0;
gvid->LastFrame = LastFrame;
// get basic frames directly
ans = gvid->DualGet(dest, dest2);
ParseName(gvid->File());
if (ans <= 0)
return ans;
return 1;
}
| 24.703608 | 78 | 0.579969 | Bhaskers-Blu-Org1 |
41e3ee186f4ae73aa31633229e39c73c7de9e52e | 3,793 | cc | C++ | middle-end-optis/live-uninit-regs/src/lib/imodule.cc | obs145628/cle | 4a4a18b2ab5a6fbf26629f6845147541edabd7c9 | [
"MIT"
] | null | null | null | middle-end-optis/live-uninit-regs/src/lib/imodule.cc | obs145628/cle | 4a4a18b2ab5a6fbf26629f6845147541edabd7c9 | [
"MIT"
] | null | null | null | middle-end-optis/live-uninit-regs/src/lib/imodule.cc | obs145628/cle | 4a4a18b2ab5a6fbf26629f6845147541edabd7c9 | [
"MIT"
] | null | null | null | #include "imodule.hh"
#include <cassert>
#include <utils/cli/err.hh>
namespace {
bool is_branch(const Ins &ins) {
const auto &opname = ins.args[0];
return opname == "b" || opname == "beq" || opname == "ret";
}
} // namespace
void BasicBlock::check() const {
for (std::size_t i = 0; i < _ins.size(); ++i) {
const auto &ins = _ins[i];
PANIC_IF(is_branch(ins) && i + 1 < _ins.size(),
"branch instruction forbidden in the middle of a basicblock");
PANIC_IF(!is_branch(ins) && i + 1 == _ins.size(),
"last instruction must must be a branch");
// @TODO Check if branch to a basicblock
const auto &op = ins.args[0];
if (op == "b")
PANIC_IF(!_mod.get_bb(ins.args[1].substr(1)), "b: invalid label name");
else if (op == "beq") {
PANIC_IF(!_mod.get_bb(ins.args[3].substr(1)) ||
!_mod.get_bb(ins.args[4].substr(1)),
"beq: invalid label name");
}
}
}
IModule::IModule() : _bb_entry(nullptr), _bb_next_id(0) {}
void IModule::check() const {
PANIC_IF(_bb_entry == nullptr, "Entry BB not set");
for (const auto &bb : _bbs_list)
bb->check();
}
std::vector<BasicBlock *> IModule::bb_list() {
std::vector<BasicBlock *> res;
for (auto &bb : _bbs_list)
res.push_back(bb.get());
return res;
}
std::vector<const BasicBlock *> IModule::bb_list() const {
std::vector<const BasicBlock *> res;
for (const auto &bb : _bbs_list)
res.push_back(bb.get());
return res;
}
BasicBlock *IModule::get_bb(bb_id_t id) {
auto it = _bbs_idsm.find(id);
return it == _bbs_idsm.end() ? nullptr : it->second;
}
BasicBlock *IModule::get_bb(const std::string &label) {
auto it = _bbs_labelsm.find(label);
return it == _bbs_labelsm.end() ? nullptr : it->second;
}
const BasicBlock *IModule::get_bb(bb_id_t id) const {
auto it = _bbs_idsm.find(id);
return it == _bbs_idsm.end() ? nullptr : it->second;
}
const BasicBlock *IModule::get_bb(const std::string &label) const {
auto it = _bbs_labelsm.find(label);
return it == _bbs_labelsm.end() ? nullptr : it->second;
}
BasicBlock &IModule::add_bb(const std::string &label) {
auto id = _bb_next_id++;
std::string cpy_label = label.empty() ? ".L" + std::to_string(id) : label;
_bbs_list.emplace_back(
new BasicBlock(*this, id, cpy_label, std::vector<Ins>{}));
BasicBlock *bb = _bbs_list.back().get();
_bbs_idsm.emplace(id, bb);
_bbs_labelsm.emplace(cpy_label, bb);
return *bb;
}
std::unique_ptr<IModule> mod2imod(const Module &mod) {
auto res = std::make_unique<IModule>();
assert(mod.code.size() > 0);
// Add special basic block jumping to code beginning
auto mod_entry = mod.code[0];
if (mod_entry.label_defs.empty())
mod_entry.label_defs.push_back("_start");
auto &entry_bb = res->add_bb("_entry");
entry_bb.ins().push_back(Ins::parse("b @" + mod_entry.label_defs[0]));
res->set_entry_bb(entry_bb);
BasicBlock *next_bb = nullptr;
// Make list of all bbs (divide by branch instructions)
for (const auto &ins : mod.code) {
if (next_bb == nullptr) {
auto label = ins.label_defs.size() > 0 ? ins.label_defs[0] : "";
next_bb = &res->add_bb(label);
}
next_bb->ins().push_back(ins);
if (is_branch(ins)) // end of basic block
next_bb = nullptr;
}
// Check module is well formed
PANIC_IF(next_bb != nullptr, "Last instruction in module isn't a branch");
res->check();
return res;
}
Module imod2mod(const IModule &mod) {
Module res;
for (const auto &bb : mod.bb_list()) {
auto first =
res.code.insert(res.code.end(), bb->ins().begin(), bb->ins().end());
first->label_defs = {bb->label()};
std::size_t first_idx = &*first - &res.code[0];
res.labels.emplace(bb->label(), first_idx);
}
return res;
}
| 27.485507 | 77 | 0.632745 | obs145628 |
41e8203349475f9d718126d436f3a11dffdb162f | 241 | cc | C++ | L3/7 - P42280 - Tauler d'escacs (1)/ex7.cc | angelgomezsa/Cplusplus | 9fd1ed5b1beffcf253019e8376b2bd41dac6e449 | [
"MIT"
] | null | null | null | L3/7 - P42280 - Tauler d'escacs (1)/ex7.cc | angelgomezsa/Cplusplus | 9fd1ed5b1beffcf253019e8376b2bd41dac6e449 | [
"MIT"
] | null | null | null | L3/7 - P42280 - Tauler d'escacs (1)/ex7.cc | angelgomezsa/Cplusplus | 9fd1ed5b1beffcf253019e8376b2bd41dac6e449 | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
int main () {
int f,c;
cin >> f >> c;
char num;
int total=0;
for (int i=0;i<f;i++) {
for (int j=0;j<c;j++) {
char num;
cin >> num;
total+=num-'0';
}
}
cout << total << endl;
} | 12.684211 | 25 | 0.506224 | angelgomezsa |
41e8efb78f24087fc373b4a0f4107eb8ed91a410 | 4,648 | cpp | C++ | src/goto-instrument/wmm/abstract_event.cpp | mauguignard/cbmc | 70cfdd5d7c62d47269bae2277ff89a9ce66ff0b5 | [
"BSD-4-Clause"
] | 412 | 2016-04-02T01:14:27.000Z | 2022-03-27T09:24:09.000Z | src/goto-instrument/wmm/abstract_event.cpp | mauguignard/cbmc | 70cfdd5d7c62d47269bae2277ff89a9ce66ff0b5 | [
"BSD-4-Clause"
] | 4,671 | 2016-02-25T13:52:16.000Z | 2022-03-31T22:14:46.000Z | src/goto-instrument/wmm/abstract_event.cpp | mauguignard/cbmc | 70cfdd5d7c62d47269bae2277ff89a9ce66ff0b5 | [
"BSD-4-Clause"
] | 266 | 2016-02-23T12:48:00.000Z | 2022-03-22T18:15:51.000Z | /*******************************************************************\
Module: abstract events
Author: Vincent Nimal
Date: 2012
\*******************************************************************/
/// \file
/// abstract events
#include "abstract_event.h"
bool abstract_eventt::unsafe_pair_lwfence_param(const abstract_eventt &next,
memory_modelt model,
bool lwsync_met) const
{
/* pairs with fences are not properly pairs */
if(operation==operationt::Fence || next.operation==operationt::Fence
|| operation==operationt::Lwfence || next.operation==operationt::Lwfence
|| operation==operationt::ASMfence || next.operation==operationt::ASMfence)
return false;
/* pairs of shared variables */
if(local || next.local)
return false;
switch(model)
{
case TSO:
return (thread==next.thread &&
operation==operationt::Write &&
next.operation==operationt::Read);
case PSO:
return (thread==next.thread && operation==operationt::Write
/* lwsyncWW -> mfenceWW */
&& !(operation==operationt::Write &&
next.operation==operationt::Write &&
lwsync_met));
case RMO:
return
thread==next.thread &&
/* lwsyncWW -> mfenceWW */
!(operation==operationt::Write &&
next.operation==operationt::Write &&
lwsync_met) &&
/* lwsyncRW -> mfenceRW */
!(operation==operationt::Read &&
next.operation==operationt::Write &&
lwsync_met) &&
/* lwsyncRR -> mfenceRR */
!(operation==operationt::Read &&
next.operation==operationt::Read &&
lwsync_met) &&
/* if posWW, wsi maintained by the processor */
!(variable==next.variable &&
operation==operationt::Write &&
next.operation==operationt::Write) &&
/* if posRW, fri maintained by the processor */
!(variable==next.variable &&
operation==operationt::Read &&
next.operation==operationt::Write);
case Power:
return ((thread==next.thread
/* lwsyncWW -> mfenceWW */
&& !(operation==operationt::Write &&
next.operation==operationt::Write &&
lwsync_met)
/* lwsyncRW -> mfenceRW */
&& !(operation==operationt::Read &&
next.operation==operationt::Write &&
lwsync_met)
/* lwsyncRR -> mfenceRR */
&& !(operation==operationt::Read &&
next.operation==operationt::Read &&
lwsync_met)
/* if posWW, wsi maintained by the processor */
&& (variable!=next.variable ||
operation!=operationt::Write ||
next.operation!=operationt::Write))
/* rfe */
|| (thread!=next.thread &&
operation==operationt::Write &&
next.operation==operationt::Read &&
variable==next.variable));
case Unknown:
{
}
}
assert(false);
/* unknown memory model */
return true;
}
bool abstract_eventt::unsafe_pair_asm(const abstract_eventt &next,
memory_modelt model,
unsigned char met) const
{
/* pairs with fences are not properly pairs */
if(operation==operationt::Fence ||
next.operation==operationt::Fence ||
operation==operationt::Lwfence ||
next.operation==operationt::Lwfence ||
operation==operationt::ASMfence ||
next.operation==operationt::ASMfence)
return false;
/* pairs of shared variables */
if(local || next.local)
return false;
switch(model)
{
case TSO:
return (thread==next.thread &&
operation==operationt::Write &&
next.operation==operationt::Read &&
(met&1)==0);
case PSO:
return (thread==next.thread &&
operation==operationt::Write &&
(met&3)==0);
case RMO:
return
thread==next.thread &&
(met&15)==0 &&
/* if posWW, wsi maintained by the processor */
!(variable==next.variable &&
operation==operationt::Write &&
next.operation==operationt::Write) &&
/* if posRW, fri maintained by the processor */
!(variable==next.variable &&
operation==operationt::Read &&
next.operation==operationt::Write);
case Power:
return
(thread==next.thread &&
(met&15)==0 &&
/* if posWW, wsi maintained by the processor */
(variable!=next.variable ||
operation!=operationt::Write ||
next.operation!=operationt::Write)) ||
/* rfe */
(thread!=next.thread &&
operation==operationt::Write &&
next.operation==operationt::Read &&
variable==next.variable);
case Unknown:
{
}
}
assert(false);
/* unknown memory model */
return true;
}
| 28.515337 | 79 | 0.579819 | mauguignard |
41ea65811bb6146c803676737fbd885795f7c6f3 | 2,551 | cpp | C++ | Math/Source/Geometry/Plane.cpp | Solidstatewater/Anubis-Engine | d2720167c0d5306d4d12a027dc31686b5cbb0f18 | [
"BSD-2-Clause"
] | 2 | 2017-10-29T06:43:05.000Z | 2020-03-27T10:27:07.000Z | Math/Source/Geometry/Plane.cpp | Solidstatewater/Anubis-Engine | d2720167c0d5306d4d12a027dc31686b5cbb0f18 | [
"BSD-2-Clause"
] | null | null | null | Math/Source/Geometry/Plane.cpp | Solidstatewater/Anubis-Engine | d2720167c0d5306d4d12a027dc31686b5cbb0f18 | [
"BSD-2-Clause"
] | 5 | 2016-02-06T11:01:51.000Z | 2019-03-18T13:56:00.000Z | //====================================================================================
//Plane.cpp : plane geometry implementation
//
//This code is part of Anubis Engine.
//
//Anubis Engine is a free game engine created as a fan project to be
//awesome platform for developing games!
//
//All sources can be found here:
// https://github.com/Dgek/Anubis-Engine
//
//Demos based on Anubis Engine can be found here:
// https://github.com/Dgek/Demos
//
//Copyright (c) 2013, Muralev Evgeny
//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 Minotower Games 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 MURALEV EVGENY "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 MURALEV EVGENY 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 "Math_pch.h"
#include "Plane.h"
using namespace Anubis;
bool Plane::Inside(const Vec & point) const
{
AREAL dist = Dot(Normal(), point) + D();
return (dist >= 0.0f);
}
bool Plane::Inside(const Vec & point, const AREAL radius) const
{
float dist = Dot(Normal(), point) + D();
// if this distance is < -radius, we are outside
return (dist >= -radius);
}
Vec Plane::Normal() const { return Vector(getx(&m_coeff), gety(&m_coeff), getz(&m_coeff), 0); }
AREAL32 Plane::D() const { return getw(&m_coeff); } | 38.074627 | 95 | 0.696198 | Solidstatewater |
41ea950f7b9ac6e2bac86adbe53fc136929102de | 7,308 | cpp | C++ | src/configure/bind/filesystem.cpp | hotgloupi/configure | 888cf725c93df5a1cf01794cc0a581586a82855c | [
"BSD-3-Clause"
] | 1 | 2015-11-13T10:37:35.000Z | 2015-11-13T10:37:35.000Z | src/configure/bind/filesystem.cpp | hotgloupi/configure | 888cf725c93df5a1cf01794cc0a581586a82855c | [
"BSD-3-Clause"
] | 19 | 2015-02-10T17:18:58.000Z | 2015-07-11T11:31:08.000Z | src/configure/bind/filesystem.cpp | hotgloupi/configure | 888cf725c93df5a1cf01794cc0a581586a82855c | [
"BSD-3-Clause"
] | null | null | null | #include <configure/bind.hpp>
#include <configure/bind/path_utils.hpp>
#include <configure/Filesystem.hpp>
#include <configure/lua/State.hpp>
#include <configure/lua/Type.hpp>
#include <configure/Node.hpp>
#include <configure/bind/path_utils.hpp>
#include <boost/filesystem.hpp>
namespace fs = boost::filesystem;
namespace configure {
static int fs_glob(lua_State* state)
{
Filesystem& self = lua::Converter<std::reference_wrapper<Filesystem>>::extract(state, 1);
std::vector<NodePtr> res;
if (lua_gettop(state) == 3)
{
res = self.glob(
utils::extract_path(state, 2),
lua::Converter<std::string>::extract(state, 3)
);
}
else if (char const* arg = lua_tostring(state, 2))
{
res = self.glob(arg);
}
else
CONFIGURE_THROW(
error::InvalidArgument("Expected a glob pattern")
);
lua_createtable(state, res.size(), 0);
for (int i = 0, len = res.size(); i < len; ++i)
{
lua::Converter<NodePtr>::push(state, res[i]);
lua_rawseti(state, -2, i + 1);
}
return 1;
}
static int fs_rglob(lua_State* state)
{
Filesystem& self = lua::Converter<std::reference_wrapper<Filesystem>>::extract(state, 1);
std::vector<NodePtr> res;
fs::path dir;
if (char const* arg = lua_tostring(state, 2))
dir = arg;
else
dir = lua::Converter<fs::path>::extract(state, 2);
if (char const* arg = lua_tostring(state, 3))
{
res = self.rglob(dir, arg);
}
lua_createtable(state, res.size(), 0);
for (int i = 0, len = res.size(); i < len; ++i)
{
lua::Converter<NodePtr>::push(state, res[i]);
lua_rawseti(state, -2, i + 1);
}
return 1;
}
static int fs_list_directory(lua_State* state)
{
Filesystem& self = lua::Converter<std::reference_wrapper<Filesystem>>::extract(state, 1);
std::vector<NodePtr> res;
if (char const* arg = lua_tostring(state, 2))
res = self.list_directory(arg);
else
res = self.list_directory(
lua::Converter<fs::path>::extract(state, 2)
);
lua_createtable(state, res.size(), 0);
for (int i = 0, len = res.size(); i < len; ++i)
{
lua::Converter<NodePtr>::push(state, res[i]);
lua_rawseti(state, -2, i + 1);
}
return 1;
}
static int fs_find_file(lua_State* state)
{
Filesystem& self = lua::Converter<std::reference_wrapper<Filesystem>>::extract(state, 1);
if (!lua_istable(state, 2))
CONFIGURE_THROW(
error::LuaError(
"Expected a table, got '" + std::string(luaL_tolstring(state, 2, nullptr)) + "'"
)
);
std::vector<fs::path> directories;
for (int i = 1, len = lua_rawlen(state, 2); i <= len; ++i)
{
lua_rawgeti(state, 2, i);
directories.push_back(utils::extract_path(state, -1));
}
lua::Converter<NodePtr>::push(
state,
self.find_file(directories, utils::extract_path(state, 3))
);
return 1;
}
static int fs_which(lua_State* state)
{
Filesystem& self = lua::Converter<std::reference_wrapper<Filesystem>>::extract(state, 1);
std::string arg;
if (fs::path* ptr = lua::Converter<fs::path>::extract_ptr(state, 2))
arg = ptr->string();
else if (char const* ptr = lua_tostring(state, 2))
arg = ptr;
if (!arg.empty())
{
auto res = self.which(arg);
if (res)
lua::Converter<fs::path>::push(state, *res);
else
lua_pushnil(state);
}
else
{
throw std::runtime_error(
"Filesystem.which(): Expected program name, got '" + std::string(luaL_tolstring(state, 2, 0)) + "'");
}
return 1;
}
static int fs_cwd(lua_State* state)
{
lua::Converter<fs::path>::push(state, fs::current_path());
return 1;
}
static int fs_current_script(lua_State* state)
{
lua_Debug ar;
if (lua_getstack(state, 1, &ar) != 1)
CONFIGURE_THROW(error::LuaError("Couldn't get the stack"));
if (lua_getinfo(state, "S", &ar) == 0)
CONFIGURE_THROW(error::LuaError("Couldn't get stack info"));
if (ar.source == nullptr)
CONFIGURE_THROW(error::LuaError("Invalid source file"));
fs::path src(ar.source[0] == '@' ? &ar.source[1] : ar.source);
if (!src.is_absolute())
src = fs::current_path() / src;
if (!fs::exists(src))
CONFIGURE_THROW(error::LuaError("Couldn't find the script path")
<< error::path(src));
lua::Converter<fs::path>::push(state, src);
return 1;
}
static int fs_copy(lua_State* state)
{
Filesystem& self = lua::Converter<std::reference_wrapper<Filesystem>>::extract(state, 1);
NodePtr res;
fs::path dst;
if (char const* arg = lua_tostring(state, 3))
dst = arg;
else if (fs::path* arg = lua::Converter<fs::path>::extract_ptr(state, 3))
dst = *arg;
else
CONFIGURE_THROW(
error::LuaError("Expected string or path for dest argument")
<< error::lua_function("Filesystem::copy")
);
if (char const* arg = lua_tostring(state, 2))
res = self.copy(arg, dst);
else if (fs::path* arg = lua::Converter<fs::path>::extract_ptr(state, 2))
res = self.copy(*arg, dst);
else if (NodePtr* arg = lua::Converter<NodePtr>::extract_ptr(state, 2))
res = self.copy(*arg, dst);
else
CONFIGURE_THROW(
error::LuaError("Expected string, path or Node for src argument")
<< error::lua_function("Filesystem::copy")
);
lua::Converter<NodePtr>::push(state, std::move(res));
return 1;
}
static int fs_create_directories(lua_State* state)
{
lua::Converter<std::reference_wrapper<Filesystem>>::extract(state, 1);
bool res = fs::create_directories(utils::extract_path(state, 2));
lua::Converter<bool>::push(state, res);
return 1;
}
void bind_filesystem(lua::State& state)
{
/// Filesystem operations.
// @classmod Filesystem
lua::Type<Filesystem, std::reference_wrapper<Filesystem>>(state, "Filesystem")
/// Find files according to a glob pattern
// @function Filesystem:glob
// @string pattern A glob pattern
// @return A list of @{Node}s
.def("glob", &fs_glob)
/// Find files recursively according to a glob pattern
// @function Filesystem:rglob
// @tparam string|Path dir The base directory
// @string pattern A glob pattern
// @return A list of @{Node}s
.def("rglob", &fs_rglob)
/// List a directory
// @function Filesystem:list_directory
// @tparam string|Path dir Directory to list
// @return A list of @{Node}s
.def("list_directory", &fs_list_directory)
/// Find a file
// @function Filesystem:find_file
// @tparam table directories A list of directories to inspect
// @tparam string|Path file The file to search for
// @return A @{Node}
.def("find_file", &fs_find_file)
/// Find an executable path
// @function Filesystem:which
// @tparam string|Path name An executable name
// @treturn Path|nil Absolute path to the executable found or nil
.def("which", &fs_which)
/// Generate rule that copy a file.
// @function Filesystem:copy
// @treturn Node the target node
.def("copy", &fs_copy)
/// Return the current working directory
// @function Filesystem:cwd
// @treturn Path current directory
.def("cwd", &fs_cwd)
/// Return the current script path
// @function Filesystem.current_script
.def("current_script", &fs_current_script)
/// Create directories
// @function Filesystem:create_directories
// @treturn bool True on success, false if the directories already exist
.def("create_directories", &fs_create_directories)
;
}
}
| 28.107692 | 108 | 0.65613 | hotgloupi |
41eccdec919e8af4a80d84f69017abeb6935d1bc | 2,044 | hh | C++ | include/arraydiff/context.hh | peterhj/arraydiff_cuda | 8825a4a79679aaaa708f47862c88e6574ff4cb3b | [
"Apache-2.0"
] | 1 | 2021-05-04T23:44:08.000Z | 2021-05-04T23:44:08.000Z | include/arraydiff/context.hh | peterhj/arraydiff_cuda | 8825a4a79679aaaa708f47862c88e6574ff4cb3b | [
"Apache-2.0"
] | null | null | null | include/arraydiff/context.hh | peterhj/arraydiff_cuda | 8825a4a79679aaaa708f47862c88e6574ff4cb3b | [
"Apache-2.0"
] | 1 | 2019-10-09T23:01:58.000Z | 2019-10-09T23:01:58.000Z | #ifndef ARRAYDIFF_CONTEXT_HH
#define ARRAYDIFF_CONTEXT_HH
#include <cuda_runtime.h>
#include <cublas.h>
#include <cudnn.h>
#include <nccl.h>
#include <cassert>
#include <experimental/optional>
#include <memory>
#include <vector>
namespace arraydiff {
using std::experimental::optional;
using std::shared_ptr;
using std::vector;
template <typename T>
class GPUMemory;
class Context {
public:
virtual ~Context() {}
virtual void sync() = 0;
};
class GPUConn {
public:
GPUConn(int device, cudaStream_t stream, cublasHandle_t cublas_h, cudnnHandle_t cudnn);
~GPUConn();
int device() const {
return this->device_;
}
cudaStream_t stream() {
return this->stream_;
}
cublasHandle_t cublas() {
return this->cublas_h_;
}
cudnnHandle_t cudnn() {
return this->cudnn_h_;
}
void sync();
private:
int device_;
cudaStream_t stream_;
cublasHandle_t cublas_h_;
cudnnHandle_t cudnn_h_;
};
class GPUContext : public virtual Context {
public:
static shared_ptr<GPUContext> Make(int device);
explicit GPUContext(int device);
virtual ~GPUContext() {}
virtual void sync();
GPUConn conn();
shared_ptr<GPUMemory<uint8_t>> get_scratch();
void reserve_scratch(size_t min_scratch_size);
private:
int device_;
cudaStream_t stream_;
cublasHandle_t cublas_h_;
cudnnHandle_t cudnn_h_;
size_t scratch_size_;
optional<shared_ptr<GPUMemory<uint8_t>>> scratch_;
};
class Spatial2DComm;
class MultiGPUContext : public virtual Context {
public:
static shared_ptr<MultiGPUContext> Make();
MultiGPUContext();
virtual ~MultiGPUContext() {}
virtual void sync();
void sync_rank(size_t rank);
size_t num_ranks() const { return this->dev_ctxs_.size(); }
shared_ptr<GPUContext> device_context(size_t rank);
ncclComm_t nccl_comm(size_t rank);
Spatial2DComm* spatial_comm(size_t rank);
private:
size_t num_ranks_;
vector<shared_ptr<GPUContext>> dev_ctxs_;
int* nccl_devs_;
ncclComm_t* nccl_comms_;
Spatial2DComm* spatial_comms_;
};
} // namespace arraydiff
#endif
| 18.752294 | 89 | 0.733366 | peterhj |
41efaa24e2497e3bdc45dbe10b8f861a9b3648fc | 1,107 | hpp | C++ | src/Map.hpp | adileo/rpg-game-cpp | f43f231b0bdb7f4618ece8174d08cf26ab3125c6 | [
"MIT"
] | null | null | null | src/Map.hpp | adileo/rpg-game-cpp | f43f231b0bdb7f4618ece8174d08cf26ab3125c6 | [
"MIT"
] | null | null | null | src/Map.hpp | adileo/rpg-game-cpp | f43f231b0bdb7f4618ece8174d08cf26ab3125c6 | [
"MIT"
] | null | null | null | /*
* Map.hpp
*
* Created on: 18 giu 2016
* Author: adileobarone
*
* La mappa è composta solo da stanze, non si deve occupare degli oggetti che ci sono sopra,
* poichè sono altre entità gestite da altre classi, l'unico link che c'è è quello che ogni oggetto
* punta a una posizione della mappa in cui si trova.
*
*/
#ifndef MAP_HPP_
#define MAP_HPP_
#include <iostream>
#include <list>
#include "Room.hpp"
#include "lib/easylogging++.hpp"
//Faccio una forward declaration per evitare le dipendenze circolari
class GameManager;
struct RoomNode{
Room* value;
RoomNode* next;
};
class RoomList{
private:
int size;
RoomNode* head;
RoomNode* tail;
public:
RoomList();
void push(Room* rm);
RoomNode* getHead();
RoomNode* getBack();
int length();
void destroy();
};
class Map{
private:
//std::list<Room> roomList;
RoomList rmlist;
GameManager* gm;
public:
Map(GameManager* g);
~Map();
Room* getRoom(Coord coord);
Room* getRoomOrCreate(Coord coord);
//std::list<Room>* getRooms();
RoomList* getRooms();
};
#endif /* MAP_HPP_ */
| 18.147541 | 100 | 0.671183 | adileo |
41f05244117e51ea6259db2cd44c2f9a70cb4313 | 2,438 | cpp | C++ | samples/snippets/cpp/VS_Snippets_CLR_System/system.Buffer.Bytes/CPP/setbyte.cpp | hamarb123/dotnet-api-docs | 6aeb55784944a2f1f5e773b657791cbd73a92dd4 | [
"CC-BY-4.0",
"MIT"
] | 421 | 2018-04-01T01:57:50.000Z | 2022-03-28T15:24:42.000Z | samples/snippets/cpp/VS_Snippets_CLR_System/system.Buffer.Bytes/CPP/setbyte.cpp | hamarb123/dotnet-api-docs | 6aeb55784944a2f1f5e773b657791cbd73a92dd4 | [
"CC-BY-4.0",
"MIT"
] | 5,797 | 2018-04-02T21:12:23.000Z | 2022-03-31T23:54:38.000Z | samples/snippets/cpp/VS_Snippets_CLR_System/system.Buffer.Bytes/CPP/setbyte.cpp | hamarb123/dotnet-api-docs | 6aeb55784944a2f1f5e773b657791cbd73a92dd4 | [
"CC-BY-4.0",
"MIT"
] | 1,482 | 2018-03-31T11:26:20.000Z | 2022-03-30T22:36:45.000Z |
//<Snippet2>
// Example of the Buffer::SetByte method.
using namespace System;
// Display the array contents in hexadecimal.
void DisplayArray( Array^ arr, String^ name )
{
// Get the array element width; format the formatting string.
int elemWidth = Buffer::ByteLength( arr ) / arr->Length;
String^ format = String::Format( " {{0:X{0}}}", 2 * elemWidth );
// Display the array elements from right to left.
Console::Write( "{0,7}:", name );
for ( int loopX = arr->Length - 1; loopX >= 0; loopX-- )
Console::Write( format, arr->GetValue( loopX ) );
Console::WriteLine();
}
int main()
{
// These are the arrays to be modified with SetByte.
array<Int16>^shorts = gcnew array<Int16>(10);
array<Int64>^longs = gcnew array<Int64>(3);
Console::WriteLine( "This example of the "
"Buffer::SetByte( Array*, int, unsigned char ) \n"
"method generates the following output.\n"
"Note: The arrays are displayed from right to left.\n" );
Console::WriteLine( " Initial values of arrays:\n" );
// Display the initial values of the arrays.
DisplayArray( shorts, "shorts" );
DisplayArray( longs, "longs" );
// Copy two regions of source array to destination array,
// and two overlapped copies from source to source.
Console::WriteLine( "\n Array values after setting byte 3 = 25, \n"
" byte 6 = 64, byte 12 = 121, and byte 17 = 196:\n" );
Buffer::SetByte( shorts, 3, 25 );
Buffer::SetByte( shorts, 6, 64 );
Buffer::SetByte( shorts, 12, 121 );
Buffer::SetByte( shorts, 17, 196 );
Buffer::SetByte( longs, 3, 25 );
Buffer::SetByte( longs, 6, 64 );
Buffer::SetByte( longs, 12, 121 );
Buffer::SetByte( longs, 17, 196 );
// Display the arrays again.
DisplayArray( shorts, "shorts" );
DisplayArray( longs, "longs" );
}
/*
This example of the Buffer::SetByte( Array*, int, unsigned char )
method generates the following output.
Note: The arrays are displayed from right to left.
Initial values of arrays:
shorts: 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000
longs: 0000000000000000 0000000000000000 0000000000000000
Array values after setting byte 3 = 25,
byte 6 = 64, byte 12 = 121, and byte 17 = 196:
shorts: 0000 C400 0000 0079 0000 0000 0040 0000 1900 0000
longs: 000000000000C400 0000007900000000 0040000019000000
*/
//</Snippet2>
| 33.861111 | 72 | 0.647252 | hamarb123 |
41f3e35c912ccd2bfb382622751e1763fe19ad24 | 1,528 | cpp | C++ | Source/ProceduralTerrainGenerator/Private/BlurFilter.cpp | McOmghall/procedural-terrain-generator-UE4-plugin | bebf4723e86eeeb75b444bef68dbaaf662813165 | [
"Apache-2.0"
] | 7 | 2019-03-20T10:06:21.000Z | 2022-01-06T14:54:47.000Z | Source/ProceduralTerrainGenerator/Private/BlurFilter.cpp | McOmghall/procedural-terrain-generator-UE4-plugin | bebf4723e86eeeb75b444bef68dbaaf662813165 | [
"Apache-2.0"
] | 1 | 2019-07-30T07:10:37.000Z | 2019-07-30T07:10:37.000Z | Source/ProceduralTerrainGenerator/Private/BlurFilter.cpp | McOmghall/procedural-terrain-generator-UE4-plugin | bebf4723e86eeeb75b444bef68dbaaf662813165 | [
"Apache-2.0"
] | 4 | 2019-08-09T07:31:07.000Z | 2022-02-13T07:13:40.000Z | // Fill out your copyright notice in the Description page of Project Settings.
#include "BlurFilter.h"
// NaÏve gaussian blur impl
bool UBlurFilter::ModifyHeightMap(TArray<uint16>* RawHeightMapData, FBounds Bounds, FRandomStream* RandomStream)
{
for (int32 j = Bounds.MinY; j <= Bounds.MaxY; j++)
{
for (int32 i = Bounds.MinX; i <= Bounds.MaxX; i++)
{
double CountPoints = 0;
double SumPointHeight = 0;
int32 RealDistanceOfInfluence = DistanceOfInfluence;
for (int32 OffsetX = -RealDistanceOfInfluence; OffsetX <= RealDistanceOfInfluence; OffsetX++)
{
int32 NeededOffsetY = RealDistanceOfInfluence - FMath::Abs(OffsetX);
for (int32 OffsetY = -NeededOffsetY; OffsetY <= NeededOffsetY; OffsetY++)
{
FIntPoint CurrentPoint(i + OffsetX, j + OffsetY);
int32 CurrentIndex = (CurrentPoint.Y - Bounds.MinY) * (Bounds.MaxX - Bounds.MinX + 1) + (CurrentPoint.X - Bounds.MinX);
if (CurrentPoint.X >= Bounds.MinX && CurrentPoint.X <= Bounds.MaxX && CurrentPoint.Y >= Bounds.MinY && CurrentPoint.Y <= Bounds.MaxY)
{
double Weight = FMath::Pow(InfluenceDecayPerDistanceUnit, FMath::Abs(OffsetX) + FMath::Abs(OffsetY));
CountPoints += Weight;
SumPointHeight += Weight * (*RawHeightMapData)[CurrentIndex];
}
}
}
int32 CurrentIndex = (j - Bounds.MinY) * (Bounds.MaxX - Bounds.MinX + 1) + (i - Bounds.MinX);
(*RawHeightMapData)[CurrentIndex] = FMath::Clamp(FMath::RoundToInt(SumPointHeight / CountPoints), 0, (int32)UINT16_MAX);
}
}
return true;
}
| 39.179487 | 138 | 0.690445 | McOmghall |
41f4297d1caf636432a0ca6c9633ab506544f07b | 333 | cpp | C++ | examples/hello/hello_world_lib.cpp | juugcatm/bazel_environment | 248cfb923ea83a270082883079af617e507cc760 | [
"Unlicense"
] | 5 | 2019-06-14T16:36:31.000Z | 2020-05-01T06:20:35.000Z | examples/hello/hello_world_lib.cpp | juugcatm/bazel_environment | 248cfb923ea83a270082883079af617e507cc760 | [
"Unlicense"
] | null | null | null | examples/hello/hello_world_lib.cpp | juugcatm/bazel_environment | 248cfb923ea83a270082883079af617e507cc760 | [
"Unlicense"
] | null | null | null | #include "examples/hello/hello_world_lib.h"
#include "glog/logging.h"
namespace hello {
bool print (proto::Hello hello_pb) {
LOG(INFO) << "Hello world!";
if (!hello_pb.extra_message().empty()) {
LOG(INFO) << hello_pb.extra_message();
}
usleep(1000000);
return !hello_pb.extra_message().empty();
}
}
| 19.588235 | 45 | 0.642643 | juugcatm |
41f4c066d8701e14e1ac7a4bbc7d3161b2a7e9de | 5,401 | cpp | C++ | src/interrupts/panic.cpp | LipkeGu1810/FoxOS-kernel | d504dcac542e5535eb0481babc0515c6fe8e9f28 | [
"MIT"
] | null | null | null | src/interrupts/panic.cpp | LipkeGu1810/FoxOS-kernel | d504dcac542e5535eb0481babc0515c6fe8e9f28 | [
"MIT"
] | null | null | null | src/interrupts/panic.cpp | LipkeGu1810/FoxOS-kernel | d504dcac542e5535eb0481babc0515c6fe8e9f28 | [
"MIT"
] | null | null | null | #include <interrupts/panic.h>
#include <scheduling/scheduler/scheduler.h>
#include <renderer/renderer2D.h>
#include <renderer/point.h>
#include <driver/serial.h>
#include <config.h>
#include <stdio.h>
#include <disassembler.h>
using namespace interrupts;
Panic::Panic(int intr) {
this->intr = intr;
this->panic = NULL;
}
Panic::Panic(char* panic) {
this->panic = panic;
}
char* Panic::get_panic_message() {
switch(this->intr){
case 0x0:
return((char*) "Divide by Zero");
break;
case 0x1:
return((char*) "Debug");
break;
case 0x2:
return((char*) "Non Maskable Interrupt");
break;
case 0x3:
return((char*) "Breakpoint");
break;
case 0x4:
return((char*) "Overflow");
break;
case 0x5:
return((char*) "Bound Range");
break;
case 0x6:
return((char*) "Invalid Opcode");
break;
case 0x7:
return((char*) "Device Not Available");
break;
case 0x8:
return((char*) "Double Fault");
break;
case 0x9:
return((char*) "Coprocessor Segment Overrun");
break;
case 0xa:
return((char*) "Invalid TSS");
break;
case 0xb:
return((char*) "Segment not Present");
break;
case 0xc:
return((char*) "Stack Fault");
break;
case 0xd:
return((char*) "General Protection");
break;
case 0xe:
return((char*) "Page Fault");
break;
case 0x10:
return((char*) "x87 Floating Point");
break;
case 0x11:
return((char*) "Alignment Check");
break;
case 0x12:
return((char*) "Machine Check");
break;
case 0x13:
return((char*) "SIMD Floating Point");
break;
case 0x1e:
return((char*) "Security-sensitive event in Host");
break;
default:
return((char*) "Reserved");
break;
}
}
void Panic::dump_regs(s_registers* regs) {
renderer::global_font_renderer->printf("cr0: %d; cr2: %d; cr3: %d; cr4: %d\n", regs->cr0, regs->cr2, regs->cr3, regs->cr4);
renderer::global_font_renderer->printf("r8: %d; r9: %d; r10: %d; r11: %d\n", regs->r8, regs->r9, regs->r10, regs->r11);
renderer::global_font_renderer->printf("r12: %d; r13: %d; r14: %d; r15: %d\n", regs->r12, regs->r13, regs->r14, regs->r15);
renderer::global_font_renderer->printf("rdi: %d; rsi: %d; rbp: %d\n", regs->rdi, regs->rsi, regs->rbp);
renderer::global_font_renderer->printf("rax: %d; rbx: %d; rcx: %d; rdx: %d\n", regs->rax, regs->rbx, regs->rcx, regs->rdx);
renderer::global_font_renderer->printf("rip: %d; cs: %d; rflags: %d; rsp: %d\n\n", regs->rip, regs->cs, regs->rflags, regs->rsp);
}
extern uint8_t screen_of_death[];
void Panic::do_it(s_registers* regs) {
renderer::point_t bmp_info = renderer::global_renderer2D->get_bitmap_info(screen_of_death);
renderer::global_font_renderer->color = 0xffe36d2d;
renderer::global_font_renderer->clear();
renderer::global_font_renderer->cursor_position = {0, 8};
renderer::global_font_renderer->color = 0xffffffff;
renderer::global_font_renderer->printf("(/ o_o)/ Oh no! Something terrible has happened and your system has been halted...\n");
renderer::global_font_renderer->printf("There isn't much you can do apart from restart the computer. More information below.\n\n");
if (!this->panic) {
renderer::global_font_renderer->printf("Kernel PANIC -> %s (0x%x)\n", this->get_panic_message(), this->intr);
} else {
renderer::global_font_renderer->printf("Kernel PANIC -> %s\n", this->panic);
}
renderer::global_font_renderer->printf("Kernel version: %d\n", VERSION);
renderer::global_font_renderer->printf("Release type: %s\n\n", RELEASE_T);
renderer::global_font_renderer->printf("Please report this issue at %fhttps://github.com/TheUltimateFoxOS/FoxOS%r by creating an issue.\n", 0xff0000ff);
renderer::global_font_renderer->printf("Feel free to fix this and submit a pull request!\n\n");
if (regs) {
renderer::global_font_renderer->printf("Register dump:\n");
dump_regs(regs);
char disassembled[0xFF];
memset(disassembled, 0, 0xFF);
unsigned char* code_location = (unsigned char*) regs->rip;
int disassembled_size = disassemble(code_location, 10, 0, disassembled);
renderer::global_font_renderer->printf("Faulting instruction: %s\n", disassembled);
renderer::global_font_renderer->printf("\nStarting stack trace:\n");
if(resolve_symbol(resolve_symbol(regs->rip)) != 0) {
char str[512];
sprintf(str, "%s + %d", resolve_symbol(regs->rip), regs->rip - resolve_symbol(resolve_symbol(regs->rip)));
renderer::global_font_renderer->printf("%s\n", str);
} else {
renderer::global_font_renderer->printf("<unknown function at 0x%x>\n", regs->rip);
}
int max_lines = (renderer::global_renderer2D->target_frame_buffer->height - renderer::global_font_renderer->cursor_position.y) / 16;
max_lines -= 4;
driver::global_serial_driver->printf("Starting stack trace using %d as max lines!\n", max_lines);
unwind(max_lines, regs->rbp, [](int frame_num, uint64_t rip) {
if(resolve_symbol(resolve_symbol(rip)) != 0) {
char str[512];
sprintf(str, "%s + %d", resolve_symbol(rip), rip - resolve_symbol(resolve_symbol(rip)));
renderer::global_font_renderer->printf("%s\n", str);
} else {
renderer::global_font_renderer->printf("<unknown function at 0x%x>\n", rip);
}
});
}
renderer::global_renderer2D->load_bitmap(screen_of_death, 0, renderer::global_renderer2D->target_frame_buffer->height - bmp_info.x);
while(true) {
halt_cpu = true;
asm volatile("cli; hlt");
}
} | 31.04023 | 153 | 0.68154 | LipkeGu1810 |
41f55010dc52b72d08f62ca9ae5c27faaa9f798b | 5,441 | cpp | C++ | src/lib/cleaver/Cleaver.cpp | thewtex/Cleaver2 | 8ef0985c451f3bbba8bb580f1737f0ef88c31147 | [
"MIT"
] | 32 | 2015-08-29T12:40:14.000Z | 2022-03-01T21:15:05.000Z | src/lib/cleaver/Cleaver.cpp | thewtex/Cleaver2 | 8ef0985c451f3bbba8bb580f1737f0ef88c31147 | [
"MIT"
] | 98 | 2015-02-04T17:22:56.000Z | 2022-03-22T07:18:10.000Z | src/lib/cleaver/Cleaver.cpp | thewtex/Cleaver2 | 8ef0985c451f3bbba8bb580f1737f0ef88c31147 | [
"MIT"
] | 19 | 2015-02-23T15:21:13.000Z | 2022-01-09T00:57:13.000Z | //-------------------------------------------------------------------
//-------------------------------------------------------------------
//
// Cleaver - A MultiMaterial Tetrahedral Mesher
// -- Mesher Class
//
// Author: Jonathan Bronson (bronson@sci.utah.edu)
//
//-------------------------------------------------------------------
//-------------------------------------------------------------------
//
// Copyright (C) 2011, 2012, Jonathan Bronson
// Scientific Computing & Imaging Institute
// University of Utah
//
// 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 "Cleaver.h"
#include "CleaverMesher.h"
#include "TetMesh.h"
#include "ScalarField.h"
#include "Volume.h"
#include <iostream>
#include <cmath>
#include <cstdlib>
#include <string>
using namespace std;
namespace cleaver
{
const std::string VersionNumber = "2.4";
const std::string VersionDate = __DATE__;
const std::string Version = std::string("Cleaver") + " " + VersionNumber + " " + VersionDate;
TetMesh* cleaveMeshToVolume(const Volume *volume, TetMesh *bgMesh, bool verbose)
{
CleaverMesher mesher;
mesher.setVolume(volume);
mesher.setBackgroundMesh(bgMesh);
mesher.buildAdjacency();
mesher.sampleVolume();
mesher.computeAlphas();
mesher.computeInterfaces();
mesher.generalizeTets();
mesher.snapsAndWarp();
mesher.stencilTets();
return mesher.getTetMesh();
}
TetMesh* createMeshFromVolume(const Volume *volume, bool verbose)
{
CleaverMesher mesher;
mesher.setVolume(volume);
mesher.createTetMesh(verbose);
return mesher.getTetMesh();
}
Volume* createFloatFieldVolumeFromVolume(Volume *base_volume)
{
int width = base_volume->width();
int height = base_volume->height();
int depth = base_volume->depth();
std::vector<AbstractScalarField*> fields;
for (int m = 0; m < base_volume->numberOfMaterials(); m++)
{
float *data = new float[width*height*depth];
for (int d = 0; d < depth; d++) {
for (int h = 0; h < height; h++) {
for (int w = 0; w < width; w++) {
data[d*width*height + h*width + w] = (float)base_volume->valueAt(w + 0.5, h + 0.5, d + 0.5, m);
}
}
}
ScalarField<float> *floatField = new ScalarField<float>(data, width, height, depth);
floatField->setName(base_volume->getMaterial(m)->name() + "_asFloat");
fields.push_back(floatField);
}
cleaver::Volume *floatVolume = new Volume(fields);
floatVolume->setName(base_volume->name());
return floatVolume;
}
ScalarField<float>* createFloatFieldFromScalarField(AbstractScalarField *scalarField)
{
int w = (int)(scalarField->bounds().size.x);
int h = (int)(scalarField->bounds().size.y);
int d = (int)(scalarField->bounds().size.z);
int wh = w*h;
int whd = wh*d;
float *data = new float[whd];
for (int k = 0; k < d; k++)
{
for (int j = 0; j < h; j++)
{
for (int i = 0; i < w; i++)
{
data[k*wh + j*w + i] = (float)scalarField->valueAt(i + 0.5, j + 0.5, k + 0.5);
}
}
}
ScalarField<float> *floatField = new ScalarField<float>(data, w, h, d);
floatField->setBounds(scalarField->bounds());
return floatField;
}
ScalarField<double>* createDoubleFieldFromScalarField(AbstractScalarField *scalarField)
{
int w = (int)(scalarField->bounds().size.x);
int h = (int)(scalarField->bounds().size.y);
int d = (int)(scalarField->bounds().size.z);
int wh = w*h;
int whd = wh*d;
double *data = new double[whd];
for (int k = 0; k < d; k++)
{
for (int j = 0; j < h; j++)
{
for (int i = 0; i < w; i++)
{
data[k*wh + j*w + i] = scalarField->valueAt(i + 0.5, j + 0.5, k + 0.5);
}
}
}
ScalarField<double> *doubleField = new ScalarField<double>(data, w, h, d);
doubleField->setBounds(scalarField->bounds());
return doubleField;
}
void stripExteriorTets(TetMesh *mesh, const Volume *volume, bool verbose)
{
// exterior material is equal to material count
mesh->stripMaterial(volume->numberOfMaterials(), verbose);
}
}
| 30.396648 | 107 | 0.588127 | thewtex |
41f5e46a1f1e2d4291072d71a2ade40d1e1829f0 | 1,289 | cpp | C++ | C++/flip_bits.cpp | Paimon-food/hacktoberfest2021 | b62d8c641aa2b27fc6d481f6719fd0981221344a | [
"CC0-1.0"
] | 1 | 2021-10-09T17:39:19.000Z | 2021-10-09T17:39:19.000Z | C++/flip_bits.cpp | Paimon-food/hacktoberfest2021 | b62d8c641aa2b27fc6d481f6719fd0981221344a | [
"CC0-1.0"
] | null | null | null | C++/flip_bits.cpp | Paimon-food/hacktoberfest2021 | b62d8c641aa2b27fc6d481f6719fd0981221344a | [
"CC0-1.0"
] | null | null | null | /*Problem Statement: You are given an array of integers ARR[] of size N consisting of zeros and ones. You have to select a subset and flip bits of that subset.
You have to return the count of maximum one’s that you can obtain by flipping chosen sub-array at most once.
A flip operation is one in which you turn 1 into 0 and 0 into 1.
Time Complexity : O(n)
*/
#include<bits/stdc++.h>
using namespace std;
int flipBits(vector<int> v, int n)
{
int ones=0;
for(int i=0;i<n;i++)
{
if(v[i]==1)
{
ones++;
}
}
for(int i=0;i<n;i++)
{
if(v[i]==1)
{
v[i]=-1;
}
else
{
v[i]=1;
}
}
int curr=0,max_sum=0;
for(int i=0;i<n;i++)
{
curr+=v[i];
max_sum = max(curr, max_sum);
if(curr<0)
{
curr=0;
}
}
return max_sum+ones;
}
int main()
{
int test;
cout<<"Enter total testcases: "<<endl;
cin>>test;
while(test--)
{
int n;
cout<<"Enter total: "<<endl;
cin>>n;
vector<int> v;
for(int i=0;i<n;i++)
{
int t;
cin>>t;
v.push_back(t);
}
cout<<flipBits(v,n)<<endl;
}
return 0;
}
| 20.140625 | 160 | 0.47789 | Paimon-food |
41f820e985264fff1bec67755323714b98ad8f08 | 2,520 | cc | C++ | rama/qt/nelder_mead.cc | teenylasers/eggshell | 7d1239eb1b143b11b5ccd1029d9bacdd601c8e4e | [
"ICU",
"OpenSSL"
] | null | null | null | rama/qt/nelder_mead.cc | teenylasers/eggshell | 7d1239eb1b143b11b5ccd1029d9bacdd601c8e4e | [
"ICU",
"OpenSSL"
] | 127 | 2017-11-01T01:28:28.000Z | 2021-03-18T05:12:21.000Z | rama/qt/nelder_mead.cc | teenylasers/eggshell | 7d1239eb1b143b11b5ccd1029d9bacdd601c8e4e | [
"ICU",
"OpenSSL"
] | 2 | 2017-10-20T01:16:49.000Z | 2018-11-04T02:36:53.000Z | // Rama Simulator, Copyright (C) 2014-2020 Russell Smith.
//
// 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.
#include <QMessageBox>
#include "nelder_mead.h"
#include "ui_nelder_mead.h"
NelderMeadOptimizer::Settings NelderMead::s_;
NelderMead::NelderMead(QWidget *parent) :
QDialog(parent),
ui(new Ui::NelderMead)
{
ui->setupUi(this);
resize(0, 0);
ui->edit_time
->setText(QString::asprintf("%.10g", s_.annealing_time));
ui->edit_initial_fraction
->setText(QString::asprintf("%.10g", s_.initial_fraction));
ui->edit_initial_temperature
->setText(QString::asprintf("%.10g", s_.initial_temperature));
ui->edit_final_temperature
->setText(QString::asprintf("%.10g", s_.final_temperature));
}
NelderMead::~NelderMead() {
delete ui;
}
void NelderMead::on_ok_button_clicked() {
if (Check()) {
accept();
}
}
void NelderMead::on_cancel_button_clicked() {
reject();
}
bool NelderMead::Check() {
bool ok;
s_.annealing_time = ui->edit_time->text().toDouble(&ok);
if (!ok || s_.annealing_time < 0) {
QMessageBox::warning(this, "Error",
"Bad annealing time value (must be a number >= 0)");
return false;
}
s_.initial_fraction = ui->edit_initial_fraction->text().toDouble(&ok);
if (!ok || s_.initial_fraction < 0 || s_.initial_fraction > 1) {
QMessageBox::warning(this, "Error", "Bad initial fraction value "
"(must be a number in the range 0..1)");
return false;
}
s_.initial_temperature = ui->edit_initial_temperature->text().toDouble(&ok);
if (!ok || s_.initial_temperature < 0) {
QMessageBox::warning(this, "Error",
"Bad initial temperature value (must be a number >= 0)");
return false;
}
s_.final_temperature = ui->edit_final_temperature->text().toDouble(&ok);
if (!ok || s_.final_temperature <= 0 || s_.final_temperature >= 1) {
QMessageBox::warning(this, "Error", "Bad final temperature value "
"(must be a number >0 and <1)");
return false;
}
return true;
}
| 30 | 80 | 0.668254 | teenylasers |
41f89a007b72f7b12b342c22a9fa4c3c7d19fd41 | 3,704 | cpp | C++ | src/modules/Phone/Call.cpp | pdumais/dhas | 424212d4766c02f5df9e363ddb8ad2c295ed49d8 | [
"MIT"
] | 12 | 2015-09-09T07:05:27.000Z | 2020-12-27T12:52:28.000Z | src/modules/Phone/Call.cpp | pdumais/dhas | 424212d4766c02f5df9e363ddb8ad2c295ed49d8 | [
"MIT"
] | null | null | null | src/modules/Phone/Call.cpp | pdumais/dhas | 424212d4766c02f5df9e363ddb8ad2c295ed49d8 | [
"MIT"
] | 2 | 2016-10-23T05:23:20.000Z | 2020-09-17T22:01:33.000Z | #include "DHASLogging.h"
#include "Call.h"
#include <stdio.h>
#include "resip/dum/InviteSession.hxx"
#include "resip/dum/ClientInviteSession.hxx"
#include "AppDialogSetNotifySoundsEmptyCommand.h"
using namespace resip;
Call::Call(resip::DialogUsageManager &dum, ActionMachine* am):AppDialogSet(dum)
{
this->mpActionMachine = am;
this->mCallState = Initial;
this->mRtpSession = 0;
this->mIncomming = false;
this->mpCurrentAction = 0;
}
Call::~Call()
{
mpActionMachine->destroyChain(this);
if (this->mRtpSession)
{
delete this->mRtpSession;
this->mRtpSession = 0;
}
}
void Call::setCurrentAction(IPhoneAction* a)
{
this->mpCurrentAction = a;
}
void Call::onCallAnswered()
{
// The call is answered by UAS, this is what triggers the action chain
mpActionMachine->asyncRunAction(this);
}
CallState Call::getCallState()
{
return mCallState;
}
void Call::setIncomming(bool i)
{
this->mIncomming = i;
}
IPhoneAction* Call::getCurrentAction()
{
return mpCurrentAction;
}
void Call::removeRTPObserver(RTPObserver *obs)
{
for (auto it = this->mRtpObservers.begin(); it != this->mRtpObservers.end(); it++)
{
if (*it != obs) continue;
this->mRtpObservers.erase(it);
return;
}
}
void Call::addRTPObserver(RTPObserver *obs)
{
for (auto it = this->mRtpObservers.begin(); it != this->mRtpObservers.end(); it++)
{
if (*it == obs) return;
}
this->mRtpObservers.push_back(obs);
}
void Call::appendAction(IPhoneAction* action)
{
if (mpCurrentAction == 0)
{
mpCurrentAction = action;
//if no action was set and the call was answered, then schedule the action to run
if (getCallState() == Answered) mpActionMachine->asyncRunAction(this);
}
else
{
// if an action is already in queue, it means that we can just append to it and
// it will eventually get invoked
IPhoneAction *a = mpCurrentAction;
while (a->getNextAction() != 0)
{
a = a->getNextAction();
}
a->setNextAction(action);
}
}
void Call::setRTPSession(Dumais::Sound::RTPSession *rtpSession)
{
this->mRtpSession = rtpSession;
this->mRtpSession->addObserver(this); //TODO should unsubscribe if overwriting observer
}
Dumais::Sound::RTPSession* Call::getRTPSession()
{
return this->mRtpSession;
}
//WARNING: This is called from the sound player thread
void Call::onSoundQueueEmpty()
{
// Don't notify from this thread, post it on the dum's thread
AppDialogSetNotifySoundsEmptyCommand* cmd = new AppDialogSetNotifySoundsEmptyCommand(this);
this->mDum.post(cmd);
}
void Call::notifySoundsEmpty()
{
// we copy the list because observers could unsubscribe in the meantime
auto list = this->mRtpObservers;
for (std::list<RTPObserver*>::iterator it = list.begin();it!=list.end();it++)
{
(*it)->onRTPSessionSoundQueueEmpty(this);
}
}
DialogUsageManager& Call::getDUM()
{
return this->mDum;
}
bool Call::isIncomming()
{
return this->mIncomming;
}
std::string Call::getDigitQueue()
{
return this->mDigitQueue;
}
void Call::clearDigitQueue()
{
this->mDigitQueue="";
}
resip::NameAddr Call::getFrom()
{
return mFrom;
}
resip::NameAddr Call::getContact()
{
return mContact;
}
std::string Call::getID()
{
return this->getDialogSetId().getCallId().c_str();
}
void Call::onTerminated()
{
}
void Call::toJSON(Dumais::JSON::JSON& json)
{
Dumais::JSON::JSON& j = json.addObject("call");
j.addValue(getID(),"id");
j.addValue(mFrom.uri().getAor().data(),"from");
j.addValue(mTo.uri().getAor().data(),"to");
}
| 21.287356 | 95 | 0.657127 | pdumais |
41fa432b5f2d2e2a90f3b00c8d094cbd16c7a44c | 3,517 | cpp | C++ | library/tree/avlTree.cpp | bluedawnstar/algorithm_library | 4c7f64ec61fc2ba059b64ad7ba20fcb5b838ced6 | [
"Unlicense"
] | 40 | 2017-11-26T05:29:18.000Z | 2020-11-13T00:29:26.000Z | library/tree/avlTree.cpp | bluedawnstar/algorithm_library | 4c7f64ec61fc2ba059b64ad7ba20fcb5b838ced6 | [
"Unlicense"
] | 101 | 2019-02-09T06:06:09.000Z | 2021-12-25T16:55:37.000Z | library/tree/avlTree.cpp | bluedawnstar/algorithm_library | 4c7f64ec61fc2ba059b64ad7ba20fcb5b838ced6 | [
"Unlicense"
] | 6 | 2017-01-03T14:17:58.000Z | 2021-01-22T10:37:04.000Z | #include <cassert>
#include <functional>
#include <algorithm>
using namespace std;
#include "avlTree.h"
/////////// For Testing ///////////////////////////////////////////////////////
#include <time.h>
#include <cassert>
#include <string>
#include <numeric>
#include <set>
#include <vector>
#include <iostream>
#include "../common/iostreamhelper.h"
#include "../common/profile.h"
#include "../common/rand.h"
static void checkSearch(AVLTree<int>& tree, vector<int>& in) {
for (int i = 0; i < int(in.size()); i++) {
int x = in[i];
assert(tree.find(x)->value == x);
}
}
static void checkIndex(AVLTree<int>& tree, vector<int>& in) {
assert(tree.size() == int(in.size()));
for (int i = 0; i < int(in.size()); i++) {
assert(tree[i]->value == in[i]);
assert(tree.indexOf(tree[i]) == i);
}
}
static int getHeight(const AVLTree<int>::Node* node) {
return node == nullptr ? 0 : node->height;
}
static void checkHeight(AVLTree<int>& tree, AVLTree<int>::Node* node) {
if (!node || node == tree.sentinel)
return;
assert(node->height == max(getHeight(node->left), getHeight(node->right)) + 1);
checkHeight(tree, node->left);
checkHeight(tree, node->right);
}
void testAVLTree() {
return; //TODO: if you want to test, make this line a comment.
cout << "--- AVL Tree -------------------------------" << endl;
{
AVLTree<int> tree;
vector<int> in(1000);
iota(in.begin(), in.end(), 0);
assert(tree.empty());
{
vector<int> t(in);
random_shuffle(t.begin(), t.end());
for (int i = 0; i < int(in.size()); i++) {
auto p = tree.insert(t[i]);
if (!p.second)
cerr << "It'll never be shown!" << endl;
assert(p.first->value == t[i] && p.second);
}
checkSearch(tree, in);
checkIndex(tree, in);
checkHeight(tree, tree.root);
}
{
assert(tree.lowerBound(-1)->value == 0);
assert(tree.lowerBound(0)->value == 0);
assert(tree.lowerBound(3)->value == 3);
assert(tree.lowerBound(77)->value == 77);
assert(tree.lowerBound(999)->value == 999);
assert(tree.upperBound(0)->value == 1);
assert(tree.upperBound(3)->value == 4);
assert(tree.upperBound(77)->value == 78);
assert(tree.upperBound(999) == tree.nullNode());
auto it = tree.lowerBound(10);
auto itE = tree.upperBound(77);
for (int i = 10; i < 77; i++) {
assert(it->value == i);
it = tree.next(it);
}
for (int i = 76; i >= 10; i--) {
it = tree.prev(it);
assert(it->value == i);
}
}
{
vector<int> t(in), org(in);
random_shuffle(t.begin(), t.end());
while (!tree.empty()) {
int x = t.back();
t.pop_back();
org.erase(find(org.begin(), org.end(), x));
bool b = tree.erase(x);
if (!b)
cerr << "It'll never be shown!" << endl;
assert(b);
assert(tree.size() == int(t.size()));
checkSearch(tree, org);
checkIndex(tree, org);
checkHeight(tree, tree.root);
}
}
}
cout << "OK!" << endl;
}
| 29.066116 | 83 | 0.473415 | bluedawnstar |
51014f83b16bccc991f6011e9ff0a6a90e4e71a3 | 482 | cpp | C++ | src/bvec/use_bvec.cpp | warelab/snapdragon | 05d969f362706a9208383545022f06e78f2bf529 | [
"MIT-0"
] | 1 | 2016-11-17T04:13:13.000Z | 2016-11-17T04:13:13.000Z | src/bvec/use_bvec.cpp | warelab/snapdragon | 05d969f362706a9208383545022f06e78f2bf529 | [
"MIT-0"
] | null | null | null | src/bvec/use_bvec.cpp | warelab/snapdragon | 05d969f362706a9208383545022f06e78f2bf529 | [
"MIT-0"
] | null | null | null | #include "bvec.h"
int main(int argc, char *argv[]) {
vector<uint64_t> vec1,vec2;
vec1.push_back(0);
vec1.push_back(100);
vec2.push_back(0);
vec2.push_back(10);
BitVector *bv1 = new BitVector(vec1);
BitVector *bv2 = new BitVector(vec2);
printf("bv1->cnt()=%llu\n",bv1->cnt());
printf("bv2->cnt()=%llu\n",bv2->cnt());
BitVector *bvu = *bv1 | *bv2;
printf("bvu->cnt()=%llu\n",bvu->cnt());
BitVector *bvi = *bv1 & *bv2;
printf("bvi->cnt()=%llu\n",bvi->cnt());
return 0;
} | 26.777778 | 40 | 0.626556 | warelab |
eedccf4ba5547f7e03ba807485b21e307c9e24cb | 9,465 | cpp | C++ | Simbody/tests/adhoc/OpenSimPartyDemoCable.cpp | elen4/simbody | 3ddbc16323afa45b7698c38e07266a7de15e2ad2 | [
"Apache-2.0"
] | 2 | 2020-01-15T05:03:30.000Z | 2021-01-16T06:18:47.000Z | Simbody/tests/adhoc/OpenSimPartyDemoCable.cpp | sohapouya/simbody | 3729532453b22ffa3693962210941184f5617f5b | [
"Apache-2.0"
] | null | null | null | Simbody/tests/adhoc/OpenSimPartyDemoCable.cpp | sohapouya/simbody | 3729532453b22ffa3693962210941184f5617f5b | [
"Apache-2.0"
] | 1 | 2021-09-24T15:20:36.000Z | 2021-09-24T15:20:36.000Z | /* -------------------------------------------------------------------------- *
* Simbody(tm) Adhoc Test: Cable Over Bicubic Surfaces *
* -------------------------------------------------------------------------- *
* This is part of the SimTK biosimulation toolkit originating from *
* Simbios, the NIH National Center for Physics-Based Simulation of *
* Biological Structures at Stanford, funded under the NIH Roadmap for *
* Medical Research, grant U54 GM072970. See https://simtk.org/home/simbody. *
* *
* Portions copyright (c) 2012 Stanford University and the Authors. *
* Authors: Michael Sherman, Andreas Scholz *
* Contributors: *
* *
* 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. *
* -------------------------------------------------------------------------- */
/* Simbody OpenSimPartyDemoCable
THIS DOESN'T WORK YET */
#include "Simbody.h"
#include <cassert>
#include <iostream>
using std::cout; using std::endl;
using namespace SimTK;
// This gets called periodically to dump out interesting things about
// the cables and the system as a whole. It also saves states so that we
// can play back at the end.
static Array_<State> saveStates;
class ShowStuff : public PeriodicEventReporter {
public:
ShowStuff(const MultibodySystem& mbs,
const CableSpring& cable1, Real interval)
: PeriodicEventReporter(interval),
mbs(mbs), cable1(cable1) {}
static void showHeading(std::ostream& o) {
printf("%8s %10s %10s %10s %10s %10s %10s %10s %10s %12s\n",
"time", "length", "rate", "integ-rate", "unitpow", "tension", "disswork",
"KE", "PE", "KE+PE-W");
}
/** This is the implementation of the EventReporter virtual. **/
void handleEvent(const State& state) const OVERRIDE_11 {
const CablePath& path1 = cable1.getCablePath();
printf("%8g %10.4g %10.4g %10.4g %10.4g %10.4g %10.4g %10.4g %10.4g %12.6g CPU=%g\n",
state.getTime(),
path1.getCableLength(state),
path1.getCableLengthDot(state),
path1.getIntegratedCableLengthDot(state),
path1.calcCablePower(state, 1), // unit power
cable1.getTension(state),
cable1.getDissipatedEnergy(state),
mbs.calcKineticEnergy(state),
mbs.calcPotentialEnergy(state),
mbs.calcEnergy(state)
+ cable1.getDissipatedEnergy(state),
cpuTime());
saveStates.push_back(state);
}
private:
const MultibodySystem& mbs;
CableSpring cable1;
};
int main() {
try {
// Create the system.
MultibodySystem system;
SimbodyMatterSubsystem matter(system);
matter.setShowDefaultGeometry(false);
CableTrackerSubsystem cables(system);
GeneralForceSubsystem forces(system);
Force::Gravity gravity(forces, matter, -YAxis, 9.81);
// Force::GlobalDamper(forces, matter, 5);
system.setUseUniformBackground(true); // no ground plane in display
MobilizedBody Ground = matter.Ground(); // convenient abbreviation
// Read in some bones.
PolygonalMesh femur;
PolygonalMesh tibia;
femur.loadVtpFile("CableOverBicubicSurfaces-femur.vtp");
tibia.loadVtpFile("CableOverBicubicSurfaces-tibia.vtp");
femur.scaleMesh(30);
tibia.scaleMesh(30);
// Build a pendulum
Body::Rigid pendulumBodyFemur( MassProperties(1.0, Vec3(0, -5, 0),
UnitInertia(1).shiftFromCentroid(Vec3(0, 5, 0))));
pendulumBodyFemur.addDecoration(Transform(), DecorativeMesh(femur).setColor(Vec3(0.8, 0.8, 0.8)));
Body::Rigid pendulumBodyTibia( MassProperties(1.0, Vec3(0, -5, 0),
UnitInertia(1).shiftFromCentroid(Vec3(0, 5, 0))));
pendulumBodyTibia.addDecoration(Transform(), DecorativeMesh(tibia).setColor(Vec3(0.8, 0.8, 0.8)));
Rotation z180(Pi, YAxis);
MobilizedBody::Pin pendulumFemur( matter.updGround(),
Transform(Vec3(0, 0, 0)),
pendulumBodyFemur,
Transform(Vec3(0, 0, 0)) );
Rotation rotZ45(-Pi/4, ZAxis);
MobilizedBody::Pin pendulumTibia( pendulumFemur,
Transform(rotZ45, Vec3(0, -12, 0)),
pendulumBodyTibia,
Transform(Vec3(0, 0, 0)) );
Real initialPendulumOffset = -0.25*Pi;
Constraint::PrescribedMotion pres(matter,
new Function::Sinusoid(0.25*Pi, 0.2*Pi, 0*initialPendulumOffset), pendulumTibia, MobilizerQIndex(0));
// Build a wrapping cable path
CablePath path2(cables, Ground, Vec3(1, 3, 1), // origin
pendulumTibia, Vec3(1, -4, 0)); // termination
// Create a bicubic surface
Vec3 patchOffset(0, -5, -1);
Rotation rotZ90(0.5*Pi, ZAxis);
Rotation rotX90(0.2*Pi, XAxis);
Rotation patchRotation = rotZ90 * rotX90 * rotZ90;
Transform patchTransform(patchRotation, patchOffset);
Real patchScaleX = 2.0;
Real patchScaleY = 2.0;
Real patchScaleF = 0.75;
const int Nx = 4, Ny = 4;
const Real xData[Nx] = { -2, -1, 1, 2 };
const Real yData[Ny] = { -2, -1, 1, 2 };
const Real fData[Nx*Ny] = { 2, 3, 3, 1,
0, 1.5, 1.5, 0,
0, 1.5, 1.5, 0,
2, 3, 3, 1 };
const Vector x_(Nx, xData);
const Vector y_(Ny, yData);
const Matrix f_(Nx, Ny, fData);
Vector x = patchScaleX*x_;
Vector y = patchScaleY*y_;
Matrix f = patchScaleF*f_;
BicubicSurface patch(x, y, f, 0);
Real highRes = 30;
Real lowRes = 1;
PolygonalMesh highResPatchMesh = patch.createPolygonalMesh(highRes);
PolygonalMesh lowResPatchMesh = patch.createPolygonalMesh(lowRes);
pendulumFemur.addBodyDecoration(patchTransform,
DecorativeMesh(highResPatchMesh).setColor(Cyan).setOpacity(.75));
pendulumFemur.addBodyDecoration(patchTransform,
DecorativeMesh(lowResPatchMesh).setRepresentation(DecorativeGeometry::DrawWireframe));
Vec3 patchP(-0.5,-1,2), patchQ(-0.5,1,2);
pendulumFemur.addBodyDecoration(patchTransform,
DecorativePoint(patchP).setColor(Green).setScale(2));
pendulumFemur.addBodyDecoration(patchTransform,
DecorativePoint(patchQ).setColor(Red).setScale(2));
CableObstacle::Surface patchObstacle(path2, pendulumFemur, patchTransform,
ContactGeometry::SmoothHeightMap(patch));
patchObstacle.setContactPointHints(patchP, patchQ);
patchObstacle.setDisabledByDefault(true);
// Sphere
Real sphRadius = 1.5;
Vec3 sphOffset(0, -0.5, 0);
Rotation sphRotation(0*Pi, YAxis);
Transform sphTransform(sphRotation, sphOffset);
CableObstacle::Surface tibiaSphere(path2, pendulumTibia, sphTransform,
ContactGeometry::Sphere(sphRadius));
Vec3 sphP(1.5,-0.5,0), sphQ(1.5,0.5,0);
tibiaSphere.setContactPointHints(sphP, sphQ);
pendulumTibia.addBodyDecoration(sphTransform,
DecorativeSphere(sphRadius).setColor(Red).setOpacity(0.5));
// Make cable a spring
CableSpring cable2(forces, path2, 50., 18., 0.1);
Visualizer viz(system);
viz.setShowFrameNumber(true);
system.addEventReporter(new Visualizer::Reporter(viz, 1./30));
system.addEventReporter(new ShowStuff(system, cable2, 0.02));
// Initialize the system and state.
system.realizeTopology();
State state = system.getDefaultState();
system.realize(state, Stage::Position);
viz.report(state);
cout << "path2 init length=" << path2.getCableLength(state) << endl;
cout << "Hit ENTER ...";
getchar();
// path1.setIntegratedCableLengthDot(state, path1.getCableLength(state));
// Simulate it.
saveStates.clear(); saveStates.reserve(2000);
// RungeKutta3Integrator integ(system);
RungeKuttaMersonIntegrator integ(system);
// CPodesIntegrator integ(system);
// integ.setAllowInterpolation(false);
integ.setAccuracy(1e-5);
TimeStepper ts(system, integ);
ts.initialize(state);
ShowStuff::showHeading(cout);
const Real finalTime = 10;
const double startTime = realTime();
ts.stepTo(finalTime);
cout << "DONE with " << finalTime
<< "s simulated in " << realTime()-startTime
<< "s elapsed.\n";
while (true) {
cout << "Hit ENTER FOR REPLAY, Q to quit ...";
const char ch = getchar();
if (ch=='q' || ch=='Q') break;
for (unsigned i=0; i < saveStates.size(); ++i)
viz.report(saveStates[i]);
}
} catch (const std::exception& e) {
cout << "EXCEPTION: " << e.what() << "\n";
}
}
| 36.125954 | 108 | 0.609192 | elen4 |
eedff2bbd0219385c868326074ac9a8d18cea3b7 | 100,758 | cpp | C++ | src/gdt/gdt_utils.cpp | dfranusic/mink-core | 98b4ab8d6322a5593ab6c05132473753915a3bb8 | [
"MIT"
] | 1 | 2022-01-28T22:29:14.000Z | 2022-01-28T22:29:14.000Z | src/gdt/gdt_utils.cpp | dfranusic/mink-core | 98b4ab8d6322a5593ab6c05132473753915a3bb8 | [
"MIT"
] | 28 | 2021-08-31T09:27:36.000Z | 2022-03-17T13:57:56.000Z | src/gdt/gdt_utils.cpp | dfranusic/mink-core | 98b4ab8d6322a5593ab6c05132473753915a3bb8 | [
"MIT"
] | 5 | 2021-08-25T13:20:39.000Z | 2022-01-27T18:04:15.000Z | /* _ _
* _ __ ___ (_)_ __ | | __
* | '_ ` _ \| | '_ \| |/ /
* | | | | | | | | | | <
* |_| |_| |_|_|_| |_|_|\_\
*
* SPDX-License-Identifier: MIT
*
*/
#include <endian.h>
#include <errno.h>
#include <iomanip>
#include <gdt_utils.h>
bool gdt::ServiceParam::FRAGMENTATION_DONE = false;
bool gdt::ServiceParam::FRAGMENTATION_NEXT = true;
gdt::ServiceMessageAsyncDone gdt::ServiceMsgManager::cb_async_done;
gdt::ServiceParam::ServiceParam() : data_size(0),
total_data_size(0),
type(SPT_UNKNOWN),
id(0),
index(0),
extra_type(0),
thread_safe(false),
fragmented(false),
linked_index(0),
param_fctry(nullptr),
fragments(0),
fragment_index(0) {
memset(data, 0, sizeof(data));
data_p = data;
in_data_p = data_p;
param_data_cb = ¶m_data_default;
pthread_mutex_init(&mtx, nullptr);
}
gdt::ServiceParam::~ServiceParam() { pthread_mutex_destroy(&mtx); }
void gdt::ServiceParam::fragment(const void *_data, unsigned int _data_size) {
// set in data pointer
in_data_p = _data;
// set first fragment data
data_size = 256;
total_data_size = _data_size;
// get param count needed to fit data size
int pc = _data_size / 256;
// remainder
int rem = _data_size % 256;
// set fragment index
fragment_index = 0;
// set total number of fragments
fragments = pc + ((rem > 0) ? 1 : 0);
// set fragmentation flag
fragmented = true;
}
int gdt::ServiceParam::param_data_file(ServiceParam *sc_param,
const void *in,
int in_size) {
FILE *f = (FILE *)in;
// get tmp service param buffer
if (sc_param->linked_index >= sc_param->linked.size())
sc_param->linked_index = 0;
ServiceParam *new_sc_param = sc_param->linked[sc_param->linked_index++];
// read file
int bc = fread(new_sc_param->data, 1, sizeof(new_sc_param->data), f);
// decrement from previous fread
sc_param->total_data_size -= sc_param->data_size;
// switch buffer of original param with new one
sc_param->data_p = new_sc_param->data;
// set data size
sc_param->data_size = bc;
return bc;
}
int gdt::ServiceParam::param_data_default(ServiceParam *sc_param,
const void *in,
int in_size) {
// calculate number of bytes needed for current fragment
int bc = (sc_param->total_data_size > sizeof(sc_param->data)
? sizeof(sc_param->data)
: sc_param->total_data_size);
sc_param->data_p += bc;
sc_param->total_data_size -= bc;
return bc;
}
int gdt::ServiceParam::set_data(FILE *_data, unsigned int _file_size) {
lock();
if (_file_size > 256) {
// file param data fetch method
param_data_cb = ¶m_data_file;
// fragmentation
fragment(_data, _file_size);
// read initial block
data_size = fread(data, 1, 256, _data);
// data_p points to internal buffer
data_p = data;
unlock();
return 0;
}
fragmented = false;
// read initial block
data_size = fread(data, 1, 256, _data);
total_data_size = data_size;
data_p = data;
unlock();
return 0;
}
void gdt::ServiceParam::set(mink_utils::VariantParam *vparam) {
switch (vparam->get_type()) {
case mink_utils::DPT_INT: {
uint64_t tmp = htobe64(vparam->get_data()->i64);
set_data(&tmp, sizeof(tmp));
extra_type = vparam->get_type();
break;
}
case mink_utils::DPT_STRING:
case mink_utils::DPT_OCTETS:
set_data(vparam->get_data()->str, vparam->get_size());
extra_type = vparam->get_type();
break;
case mink_utils::DPT_DOUBLE:
set_data(&vparam->get_data()->d, vparam->get_size());
extra_type = vparam->get_type();
break;
case mink_utils::DPT_CHAR:
set_data(&vparam->get_data()->c, vparam->get_size());
extra_type = vparam->get_type();
break;
case mink_utils::DPT_BOOL:
set_data(&vparam->get_data()->b, vparam->get_size());
extra_type = vparam->get_type();
break;
default:
break;
}
}
int gdt::ServiceParam::set_data(const void *_data, unsigned int _data_size) {
lock();
if (_data_size > 256) {
// default param data fetch method
param_data_cb = ¶m_data_default;
// fragmentation
fragment(_data, _data_size);
// set data pointer (fragmented stream does not imply copying of data)
data_p = (unsigned char *)_data;
unlock();
return 0;
}
fragmented = false;
memcpy(data, _data, _data_size);
data_size = _data_size;
total_data_size = _data_size;
data_p = data;
unlock();
return 0;
}
void gdt::ServiceParam::std_out() {
lock();
std::cout << data << std::endl;
unlock();
}
unsigned char *gdt::ServiceParam::get_data() { return data; }
unsigned char *gdt::ServiceParam::get_data_p() { return data_p; }
void gdt::ServiceParam::set_data_p(unsigned char *_data_p) {
data_p = _data_p;
}
void gdt::ServiceParam::reset_data_p() {
data_p = data;
in_data_p = data_p;
}
int gdt::ServiceParam::get_data_size() {
lock();
unsigned int tmp = data_size;
unlock();
return tmp;
}
void gdt::ServiceParam::inc_total_data_size(unsigned int _inc) {
total_data_size += _inc;
++fragment_index;
}
int gdt::ServiceParam::get_total_data_size() const { return total_data_size; }
void gdt::ServiceParam::reset() {
lock();
data_size = 0;
unlock();
id = 0;
fragmented = false;
param_data_cb = ¶m_data_default;
}
void gdt::ServiceParam::set_thread_safety(bool _thread_safe) {
thread_safe = _thread_safe;
}
void gdt::ServiceParam::set_param_factory(ServiceParamFactory *_pfact) {
param_fctry = _pfact;
}
bool gdt::ServiceParam::is_fragmented() const { return fragmented; }
bool *gdt::ServiceParam::get_fragmentation_p() { return &fragmented; }
uint32_t gdt::ServiceParam::get_index() const { return index; }
int gdt::ServiceParam::get_extra_type() const { return extra_type; }
void gdt::ServiceParam::set_extra_type(int _type) { extra_type = _type; }
int gdt::ServiceParam::get_fragment_index() const { return fragment_index; }
void gdt::ServiceParam::set_fragmented(bool _fragmented) {
fragmented = _fragmented;
}
void gdt::ServiceParam::set_callback(GDTEventType _type,
GDTCallbackMethod *cback) {
cb_handler.set_callback(_type, cback);
}
bool gdt::ServiceParam::process_callback(GDTEventType _type,
GDTCallbackArgs *args) {
return cb_handler.process_callback(_type, args);
}
void gdt::ServiceParam::clear_callbacks() { cb_handler.clear(); }
void gdt::ServiceParam::lock() {
if (thread_safe)
pthread_mutex_lock(&mtx);
}
void gdt::ServiceParam::unlock() {
if (thread_safe)
pthread_mutex_unlock(&mtx);
}
gdt::ServiceParamType gdt::ServiceParam::get_type() const { return type; }
void gdt::ServiceParam::set_id(uint32_t _id) { id = htobe32(_id); }
void gdt::ServiceParam::set_index(uint32_t idx) { index = idx; }
uint32_t gdt::ServiceParam::get_id() const { return be32toh(id); }
uint32_t *gdt::ServiceParam::get_idp() { return &id; }
gdt::ServiceParamVARIANT::ServiceParamVARIANT() { type = SPT_VARIANT; }
gdt::ServiceParamVARIANT::~ServiceParamVARIANT() = default;
int gdt::ServiceParamVARIANT::extract(void *_out) {
lock();
switch (extra_type) {
case mink_utils::DPT_INT: {
auto res = (uint64_t *)_out;
auto src = (uint64_t *)data;
// Big endian -> little endian
*res = be64toh(*src);
break;
}
default:
memcpy(_out, data, data_size);
break;
}
unlock();
return 0;
}
int gdt::ServiceParamVARIANT::set_data(const void *_data, unsigned int _data_size) {
return ServiceParam::set_data(_data, _data_size);
}
void gdt::ServiceParamVARIANT::std_out() {
lock();
for (unsigned int k = 0; k < data_size; k++) {
std::cout << std::setfill('0') << std::setw(2) << std::hex
<< (int)(data[k] & 0xff) << " ";
}
unlock();
std::cout << std::dec << std::endl;
}
gdt::ServiceParamUNKNOWN::ServiceParamUNKNOWN() { type = SPT_UNKNOWN; }
gdt::ServiceParamUNKNOWN::~ServiceParamUNKNOWN() = default;
int gdt::ServiceParamUNKNOWN::extract(void *_out) {
lock();
memcpy(_out, data, data_size);
unlock();
return 0;
}
int gdt::ServiceParamUNKNOWN::set_data(const void *_data, unsigned int _data_size) {
return ServiceParam::set_data(_data, _data_size);
}
void gdt::ServiceParamUNKNOWN::std_out() {
lock();
for (unsigned int k = 0; k < data_size; k++) {
std::cout << std::setfill('0') << std::setw(2) << std::hex
<< (int)(data[k] & 0xff) << " ";
}
unlock();
std::cout << std::dec << std::endl;
}
gdt::ServiceParamBOOL::ServiceParamBOOL() { type = SPT_BOOL; }
gdt::ServiceParamBOOL::~ServiceParamBOOL() = default;
int gdt::ServiceParamBOOL::extract(void *_out) {
auto res = (bool *)_out;
auto src = (bool *)data;
lock();
*res = *src;
unlock();
// success
return 0;
}
int gdt::ServiceParamBOOL::set_bool(bool _data) {
return ServiceParam::set_data(&_data, sizeof(bool));
}
void gdt::ServiceParamBOOL::std_out() {
auto tmp = (bool *)data;
lock();
std::cout << *tmp << std::endl;
unlock();
}
gdt::ServiceParamUINT32::ServiceParamUINT32() { type = SPT_UINT32; }
gdt::ServiceParamUINT32::~ServiceParamUINT32() = default;
int gdt::ServiceParamUINT32::extract(void *_out) {
auto res = (uint32_t *)_out;
auto src = (uint32_t *)data;
lock();
// Big endian -> little endian
*res = be32toh(*src);
unlock();
// success
return 0;
}
int gdt::ServiceParamUINT32::set_uint32(uint32_t _data) {
uint32_t tmp = htobe32(_data);
return ServiceParam::set_data(&tmp, sizeof(uint32_t));
}
void gdt::ServiceParamUINT32::std_out() {
auto tmp = (uint32_t *)data;
lock();
std::cout << be32toh(*tmp) << std::endl;
unlock();
}
gdt::ServiceParamUINT64::ServiceParamUINT64() { type = SPT_UINT64; }
gdt::ServiceParamUINT64::~ServiceParamUINT64() = default;
void gdt::ServiceParamUINT64::std_out() {
auto tmp = (uint64_t *)data;
lock();
std::cout << be64toh(*tmp) << std::endl;
unlock();
}
int gdt::ServiceParamUINT64::extract(void *_out) {
auto res = (uint64_t *)_out;
auto src = (uint64_t *)data;
lock();
// Big endian -> little endian
*res = be64toh(*src);
unlock();
// success
return 0;
}
int gdt::ServiceParamUINT64::set_uint64(uint64_t _data) {
uint64_t tmp = htobe64(_data);
return ServiceParam::set_data(&tmp, sizeof(uint64_t));
}
gdt::ServiceParamCString::ServiceParamCString() { type = SPT_CSTRING; }
gdt::ServiceParamCString::~ServiceParamCString() = default;
int gdt::ServiceParamCString::extract(void *_out) {
auto _out_cs = (char *)_out;
lock();
strncpy(_out_cs, (char *)data, strlen((char *)data) + 1);
unlock();
// success
return 0;
}
void gdt::ServiceParamCString::set_cstring(const char *cstring) {
if (cstring == nullptr) {
data_size = 0;
return;
}
set_data(cstring, strnlen(cstring, (sizeof(data) - 1) + 1));
}
gdt::ServiceParamOctets::ServiceParamOctets() { type = SPT_OCTETS; }
gdt::ServiceParamOctets::~ServiceParamOctets() = default;
int gdt::ServiceParamOctets::extract(void *_out) {
lock();
memcpy(_out, data, data_size);
unlock();
// success
return 0;
}
void gdt::ServiceParamOctets::std_out() {
lock();
for (unsigned int k = 0; k < data_size; k++) {
std::cout << std::setfill('0') << std::setw(2) << std::hex
<< (int)(data[k] & 0xff) << " ";
}
unlock();
std::cout << std::dec << std::endl;
}
gdt::ServiceParamFactory::ServiceParamFactory(bool _pooled,
bool _th_safe,
unsigned int pool_size) {
pooled = _pooled;
if (pooled) {
cstr_pool.init(pool_size);
cstr_pool.construct_objects();
oct_pool.init(pool_size);
oct_pool.construct_objects();
uint32_pool.init(pool_size);
uint32_pool.construct_objects();
uint64_pool.init(pool_size);
uint64_pool.construct_objects();
unknown_pool.init(pool_size);
unknown_pool.construct_objects();
bool_pool.init(pool_size);
bool_pool.construct_objects();
var_pool.init(pool_size);
var_pool.construct_objects();
ServiceParam *tmp_arr[pool_size];
// cstr
for (unsigned int i = 0; i < pool_size; i++) {
tmp_arr[i] = cstr_pool.allocate_constructed();
tmp_arr[i]->set_thread_safety(_th_safe);
tmp_arr[i]->set_param_factory(this);
}
for (unsigned int i = 0; i < pool_size; i++)
cstr_pool.deallocate_constructed((ServiceParamCString *)tmp_arr[i]);
// oct
for (unsigned int i = 0; i < pool_size; i++) {
tmp_arr[i] = oct_pool.allocate_constructed();
tmp_arr[i]->set_thread_safety(_th_safe);
tmp_arr[i]->set_param_factory(this);
}
for (unsigned int i = 0; i < pool_size; i++)
oct_pool.deallocate_constructed((ServiceParamOctets *)tmp_arr[i]);
// uint32
for (unsigned int i = 0; i < pool_size; i++) {
tmp_arr[i] = uint32_pool.allocate_constructed();
tmp_arr[i]->set_thread_safety(_th_safe);
tmp_arr[i]->set_param_factory(this);
}
for (unsigned int i = 0; i < pool_size; i++)
uint32_pool.deallocate_constructed(
(ServiceParamUINT32 *)tmp_arr[i]);
// uint64
for (unsigned int i = 0; i < pool_size; i++) {
tmp_arr[i] = uint64_pool.allocate_constructed();
tmp_arr[i]->set_thread_safety(_th_safe);
tmp_arr[i]->set_param_factory(this);
}
for (unsigned int i = 0; i < pool_size; i++)
uint64_pool.deallocate_constructed(
(ServiceParamUINT64 *)tmp_arr[i]);
// unknown
for (unsigned int i = 0; i < pool_size; i++) {
tmp_arr[i] = unknown_pool.allocate_constructed();
tmp_arr[i]->set_thread_safety(_th_safe);
tmp_arr[i]->set_param_factory(this);
}
for (unsigned int i = 0; i < pool_size; i++)
unknown_pool.deallocate_constructed(
(ServiceParamUNKNOWN *)tmp_arr[i]);
// bool
for (unsigned int i = 0; i < pool_size; i++) {
tmp_arr[i] = bool_pool.allocate_constructed();
tmp_arr[i]->set_thread_safety(_th_safe);
tmp_arr[i]->set_param_factory(this);
}
for (unsigned int i = 0; i < pool_size; i++)
bool_pool.deallocate_constructed((ServiceParamBOOL *)tmp_arr[i]);
// var
for (unsigned int i = 0; i < pool_size; i++) {
tmp_arr[i] = var_pool.allocate_constructed();
tmp_arr[i]->set_thread_safety(_th_safe);
tmp_arr[i]->set_param_factory(this);
}
for (unsigned int i = 0; i < pool_size; i++)
var_pool.deallocate_constructed((ServiceParamVARIANT *)tmp_arr[i]);
}
}
gdt::ServiceParamFactory::~ServiceParamFactory() = default;
gdt::ServiceParam *gdt::ServiceParamFactory::new_param(ServiceParamType param_type) {
ServiceParam *tmp = nullptr;
if (pooled) {
switch (param_type) {
case SPT_CSTRING:
tmp = cstr_pool.allocate_constructed();
break;
case SPT_OCTETS:
tmp = oct_pool.allocate_constructed();
break;
case SPT_UINT32:
tmp = uint32_pool.allocate_constructed();
break;
case SPT_UINT64:
tmp = uint64_pool.allocate_constructed();
break;
case SPT_BOOL:
tmp = bool_pool.allocate_constructed();
break;
case SPT_VARIANT:
tmp = var_pool.allocate_constructed();
break;
default:
tmp = unknown_pool.allocate_constructed();
break;
}
} else {
switch (param_type) {
case SPT_CSTRING:
tmp = new ServiceParamCString();
break;
case SPT_OCTETS:
tmp = new ServiceParamOctets();
break;
case SPT_UINT32:
tmp = new ServiceParamUINT32();
break;
case SPT_UINT64:
tmp = new ServiceParamUINT64();
break;
case SPT_BOOL:
tmp = new ServiceParamBOOL();
break;
case SPT_VARIANT:
tmp = new ServiceParamVARIANT();
break;
default:
tmp = new ServiceParamUNKNOWN();
break;
}
}
return tmp;
}
int gdt::ServiceParamFactory::free_param(ServiceParam *param) {
if (param == nullptr)
return 5;
if (pooled) {
int res = 0;
switch (param->get_type()) {
case SPT_CSTRING:
res =
cstr_pool.deallocate_constructed((ServiceParamCString *)param);
break;
case SPT_OCTETS:
res = oct_pool.deallocate_constructed((ServiceParamOctets *)param);
break;
case SPT_UINT32:
res =
uint32_pool.deallocate_constructed((ServiceParamUINT32 *)param);
break;
case SPT_UINT64:
res =
uint64_pool.deallocate_constructed((ServiceParamUINT64 *)param);
break;
case SPT_UNKNOWN:
res = unknown_pool.deallocate_constructed(
(ServiceParamUNKNOWN *)param);
break;
case SPT_BOOL:
res = bool_pool.deallocate_constructed((ServiceParamBOOL *)param);
break;
case SPT_VARIANT:
res = var_pool.deallocate_constructed((ServiceParamVARIANT *)param);
break;
default:
res = 7;
break;
}
return res;
} else {
delete param;
return 0;
}
}
gdt::ParamIdTypeMap::~ParamIdTypeMap() = default;
int gdt::ParamIdTypeMap::add(uint32_t _id, ServiceParamType _type) {
idtmap[_id] = _type;
return 0;
}
int gdt::ParamIdTypeMap::remove(uint32_t id) {
idtmap.erase(id);
return 0;
}
gdt::ServiceParamType gdt::ParamIdTypeMap::get(uint32_t id) {
// find
auto it = idtmap.find(id);
if (it != idtmap.end())
return it->second;
return SPT_UNKNOWN;
}
int gdt::ParamIdTypeMap::clear() {
idtmap.clear();
return 0;
}
gdt::ServiceMessageDone::ServiceMessageDone() {
usr_method = nullptr;
status = 0;
smsg = nullptr;
}
void gdt::ServiceMessageDone::run(GDTCallbackArgs *args) {
auto in_msg = (asn1::GDTMessage *)args->get_arg(gdt::GDT_CB_INPUT_ARGS,
gdt::GDT_CB_ARG_IN_MSG);
auto in_sess = (uint64_t *)args->get_arg(gdt::GDT_CB_INPUT_ARGS,
gdt::GDT_CB_ARG_IN_MSG_ID);
// check status (in_msg is nullptr in case if stream timeout)
if ((in_msg != nullptr) && (in_msg->_header->_status != nullptr)) {
if (in_msg->_header->_status->has_linked_data(*in_sess)) {
status = in_msg->_header->_status->linked_node->tlv->value[0];
}
// stream timeout error
} else
status = 300;
// run user handler (async mode)
if (usr_method != nullptr) {
args->add_arg(GDT_CB_INPUT_ARGS, GDT_CB_ARGS_SRVC_MSG, smsg);
usr_method->run(args);
}
// signal
smsg->signal_post();
}
static void process_fragments(unsigned int *bc,
unsigned int *tbc,
const gdt::ServiceParam *sc_param,
asn1::Parameters *params,
unsigned int idx){
// calculate number of bytes needed for current fragment
*bc = (sc_param->get_total_data_size() > gdt::ServiceParam::DATA_SZ
? gdt::ServiceParam::DATA_SZ
: sc_param->get_total_data_size());
// check if more allocations are needed
if (params->get_child(idx) == nullptr) {
params->set_child(idx);
params->get_child(idx)->set_value();
params->get_child(idx)->_value->set_child(0);
params->get_child(idx)->_value->set_child(1);
params->get_child(idx)->_value->set_child(2);
params->get_child(idx)->_value->set_child(3);
// prepare
asn1::prepare(params, params->parent_node);
}
// update total byte count
*tbc += *bc + 25;
}
void gdt::ServiceMessageNext::run(GDTCallbackArgs *args) {
auto stream = (gdt::GDTStream *)args->get_arg(gdt::GDT_CB_INPUT_ARGS,
gdt::GDT_CB_ARG_STREAM);
asn1::GDTMessage *gdtm = stream->get_gdt_message();
auto include_body = (bool *)args->get_arg(gdt::GDT_CB_INPUT_ARGS,
gdt::GDT_CB_ARG_BODY);
// param map
std::vector<ServiceParam *> *pmap = smsg->get_param_map();
// more segments
if (pindex < pc) {
unsigned int bc;
unsigned int tbc = 0;
// prepare body
if (gdtm->_body != nullptr) {
gdtm->_body->unlink(1);
gdtm->_body->_service_msg->set_linked_data(1);
} else {
gdtm->set_body();
gdtm->prepare();
}
asn1::ServiceMessage *sm = gdtm->_body->_service_msg;
// set params, allocate 10 initial children
if (sm->_params == nullptr) {
sm->set_params();
// set children, allocate more
for (int i = 0; i < 10; i++) {
sm->_params->set_child(i);
sm->_params->get_child(i)->set_value();
sm->_params->get_child(i)->_value->set_child(0);
sm->_params->get_child(i)->_value->set_child(1);
sm->_params->get_child(i)->_value->set_child(2);
sm->_params->get_child(i)->_value->set_child(3);
}
// prepare
asn1::prepare(sm, sm->parent_node);
}
// set service id
sm->_service_id->set_linked_data(1,
(unsigned char *)smsg->get_service_idp(),
sizeof(uint32_t));
// set service action
sm->_service_action->set_linked_data(1,
(unsigned char *)smsg->get_service_actionp(),
1);
// params
ServiceParam *sc_param = nullptr;
asn1::Parameters *params = sm->_params;
unsigned int j;
for (j = 0;
(tbc < ServiceMsgManager::MAX_PARAMS_SIZE) && (pos < pmap->size());
pos++, j++, pindex++) {
sc_param = (*pmap)[pos];
// check if more allocations are needed
if (params->get_child(j) == nullptr) {
params->set_child(j);
params->get_child(j)->set_value();
params->get_child(j)->_value->set_child(0);
params->get_child(j)->_value->set_child(1);
params->get_child(j)->_value->set_child(2);
params->get_child(j)->_value->set_child(3);
// prepare
asn1::prepare(params, params->parent_node);
}
// check fragmentation
if (sc_param->fragmented) {
// process fragments
while ((tbc < ServiceMsgManager::MAX_PARAMS_SIZE) &&
(sc_param->fragment_index < sc_param->fragments)) {
process_fragments(&bc, &tbc, sc_param, params, j);
// check if limit reached
if (tbc > ServiceMsgManager::MAX_PARAMS_SIZE)
break;
// set gdt values
params->get_child(j)
->_id->set_linked_data(1,
(unsigned char *)sc_param->get_idp(),
sizeof(uint32_t));
params->get_child(j)
->_value
->get_child(0)
->set_linked_data(1, sc_param->data_p, bc);
// variant param id index and type
params->get_child(j)
->_value
->get_child(2)
->set_linked_data(1, (unsigned char *)&sc_param->index, 1);
params->get_child(j)
->_value
->get_child(3)
->set_linked_data(1, (unsigned char *)&sc_param->extra_type, 1);
// check if last fragment, disable fragmentation flag (last
// fragment must not contain fragmentation flag)
if (sc_param->fragment_index == (sc_param->fragments - 1)) {
// set gdt fragmentation flag
params->get_child(j)
->_value
->get_child(1)
->set_linked_data(1,
(unsigned char*)&ServiceParam::FRAGMENTATION_DONE,
1);
} else {
// set gdt fragmentation flag
params->get_child(j)
->_value
->get_child(1)
->set_linked_data(1,
(unsigned char*)&ServiceParam::FRAGMENTATION_NEXT,
1);
}
// next
++sc_param->fragment_index;
++j;
++pindex;
// run data fetch method
(*sc_param->param_data_cb)(sc_param,
sc_param->in_data_p,
sc_param->total_data_size);
}
// break if fragmentation in progress and not finished (to skip
// increment, next call should process the same param again)
if (sc_param->fragment_index < sc_param->fragments)
break;
// rewind gdt param child count and packet index
else {
--j;
--pindex;
}
// no fragmentation
} else {
// update total byte count
tbc += sc_param->data_size + 25;
// check if limit reached
if (tbc > ServiceMsgManager::MAX_PARAMS_SIZE)
break;
params->get_child(j)
->_id->set_linked_data(1,
(unsigned char *)sc_param->get_idp(),
sizeof(uint32_t));
params->get_child(j)
->_value
->get_child(0)
->set_linked_data(1, sc_param->data, sc_param->data_size);
params->get_child(j)
->_value
->get_child(1)
->set_linked_data(1,
(unsigned char *)&ServiceParam::FRAGMENTATION_DONE,
1);
params->get_child(j)
->_value
->get_child(2)
->set_linked_data(1,
(unsigned char *)&sc_param->index,
1);
params->get_child(j)
->_value
->get_child(3)
->set_linked_data(1,
(unsigned char *)&sc_param->extra_type,
1);
}
}
// remove unused chidren
for (; j < params->children.size(); j++)
params->get_child(j)->unlink(1);
// include body
*include_body = true;
// continue
if (pindex < pc)
stream->continue_sequence();
}
}
gdt::ServiceMessage::ServiceMessage() : missing_params(false),
idt_map(nullptr),
service_id(0),
service_action(0),
smsg_m(nullptr),
frag_param(nullptr),
auto_free(true) {
sem_init(&smsg_sem, 0, 0);
sem_init(&new_param_sem, 0, 0);
msg_done.smsg = this;
msg_next.smsg = this;
}
gdt::ServiceMessage::~ServiceMessage() { tlvs.clear(); }
int gdt::ServiceMessage::add_param(uint32_t id, ServiceParam *param,
uint32_t index) {
tlvs.push_back(param);
param->set_id(id);
param->index = index;
return 0;
}
int gdt::ServiceMessage::remove_param(uint32_t id) {
for (unsigned int i = 0; i < tlvs.size(); i++)
if (tlvs[i]->get_id() == id) {
tlvs.erase(tlvs.begin() + i);
}
return 0;
}
int gdt::ServiceMessage::get_param(uint32_t id,
std::vector<ServiceParam *> *out) const {
std::all_of(tlvs.cbegin(), tlvs.cend(), [out, id](ServiceParam *p) {
if (p->get_id() == id) out->push_back(p);
return true;
});
return 0;
}
int gdt::ServiceMessage::reset() {
ServiceMsgManager *sm = get_smsg_manager();
std::all_of(tlvs.cbegin(), tlvs.cend(), [sm](ServiceParam *p) {
sm->get_param_factory()->free_param(p);
return true;
});
tlvs.clear();
return 0;
}
uint32_t gdt::ServiceMessage::get_service_id() const { return be32toh(service_id); }
uint32_t *gdt::ServiceMessage::get_service_idp() { return &service_id; }
uint32_t gdt::ServiceMessage::get_service_action() const {
return be32toh(service_action);
}
uint32_t *gdt::ServiceMessage::get_service_actionp() {
return &service_action;
}
void gdt::ServiceMessage::set_service_id(uint32_t _service_id) {
service_id = htobe32(_service_id);
}
void gdt::ServiceMessage::set_service_action(uint32_t _service_action) {
service_action = htobe32(_service_action);
}
void gdt::ServiceMessage::set_smsg_manager(ServiceMsgManager *_smsg_m) {
smsg_m = _smsg_m;
}
gdt::ServiceMsgManager *gdt::ServiceMessage::get_smsg_manager() {
return smsg_m;
}
gdt::ServiceParam *gdt::ServiceMessage::get_frag_param() {
return frag_param;
}
void gdt::ServiceMessage::set_frag_param(ServiceParam *_frag_param) {
frag_param = _frag_param;
if (frag_param != nullptr)
frag_param->fragment_index = 0;
}
bool gdt::ServiceMessage::is_complete() { return complete.get(); }
bool gdt::ServiceMessage::set_complete(bool _is_complete) {
return complete.comp_swap(!_is_complete, _is_complete);
}
bool gdt::ServiceMessage::set_auto_free(bool _auto_free) {
auto_free = _auto_free;
return auto_free;
}
bool gdt::ServiceMessage::get_auto_free() const { return auto_free; }
void gdt::ServiceMessage::set_callback(GDTEventType type,
GDTCallbackMethod *cback) {
cb_handler.set_callback(type, cback);
}
bool gdt::ServiceMessage::process_callback(GDTEventType type,
GDTCallbackArgs *args) {
return cb_handler.process_callback(type, args);
}
void gdt::ServiceMessage::clear_callbacks() { cb_handler.clear(); }
std::vector<gdt::ServiceParam *> *gdt::ServiceMessage::get_param_map() {
return &tlvs;
}
mink_utils::VariantParam *gdt::ServiceMessage::vpget(uint32_t id,
uint32_t index,
uint32_t fragment,
uint32_t context) {
return vpmap.get_param(id, index, fragment, context);
}
mink_utils::VariantParam *gdt::ServiceMessage::vpset(uint32_t id,
const std::string &s,
uint32_t index,
uint32_t fragment,
uint32_t context) {
return vpmap.set_cstr(id, s.c_str(), index, fragment, context);
}
gdt::ServiceMessageDone *gdt::ServiceMessage::get_sdone_hndlr() {
return &msg_done;
}
gdt::ServiceMessageNext *gdt::ServiceMessage::get_snext_hndlr() {
return &msg_next;
}
int gdt::ServiceMessage::signal_wait() {
// wait for signal
timespec ts;
clock_gettime(0, &ts);
ts.tv_sec += 5;
int sres = sem_wait(&smsg_sem);
// error check
if (sres == -1) {
return 1;
}
// ok
return 0;
}
int gdt::ServiceMessage::signal_post() { return sem_post(&smsg_sem); }
void gdt::ServiceMessage::set_idt_map(ParamIdTypeMap *idtm) { idt_map = idtm; }
gdt::ServiceStreamHandlerNext::ServiceStreamHandlerNext(): ssh_new(nullptr){}
void gdt::ServiceStreamHandlerNext::run(GDTCallbackArgs *args) {
auto stream = (gdt::GDTStream *)args->get_arg(gdt::GDT_CB_INPUT_ARGS,
gdt::GDT_CB_ARG_STREAM);
auto in_msg = (asn1::GDTMessage *)args->get_arg(gdt::GDT_CB_INPUT_ARGS,
gdt::GDT_CB_ARG_IN_MSG);
auto in_sess = (uint64_t *)args->get_arg(gdt::GDT_CB_INPUT_ARGS,
gdt::GDT_CB_ARG_IN_MSG_ID);
GDTCallbackArgs cb_args;
// check for params part
if ((in_msg->_body->_service_msg->_params != nullptr) &&
(in_msg->_body->_service_msg->_params->has_linked_data(*in_sess))) {
// get ID->TYPE map
ParamIdTypeMap *idt_map = ssh_new->smsg_m->get_idt_map();
// set default param type
ServiceParamType ptype = SPT_UNKNOWN;
// declare param pointer
ServiceParam *sparam = nullptr;
// param id pointer
uint32_t *param_id = nullptr;
// raw data pointer
char *tmp_val = nullptr;
// ServiceMessage pointer
auto smsg = (ServiceMessage *)stream->get_param(SMSG_PT_SMSG);
// nullptr check
if (smsg != nullptr) {
// fragmentation
bool frag = false;
asn1::ServiceMessage *sm = in_msg->_body->_service_msg;
// service id
if (sm->_service_id->has_linked_data(*in_sess)) {
auto tmp_ui32 = (uint32_t *)sm->_service_id
->linked_node
->tlv
->value;
smsg->set_service_id(be32toh(*tmp_ui32));
}
// process params
for (unsigned int i = 0; i < sm->_params->children.size(); i++) {
// check for value
if (!sm->_params
->get_child(i)
->_value) continue;
// check if value exists in current session
if (!sm->_params
->get_child(i)
->_value
->has_linked_data(*in_sess)) continue;
// check if child exists
if (!sm->_params
->get_child(i)
->_value
->get_child(0)) continue;
// check if child exists in current sesion
if (!sm->_params
->get_child(i)
->_value
->get_child(0)
->has_linked_data(*in_sess)) continue;
// getr param id
param_id = (uint32_t *)sm->_params
->get_child(i)
->_id
->linked_node
->tlv
->value;
// get param type by id
ptype = idt_map->get(be32toh(*param_id));
// get extra type
int extra_type = sm->_params
->get_child(i)
->_value
->get_child(3)
->linked_node
->tlv
->value[0];
// create param
sparam = ssh_new->smsg_m->get_param_factory()
->new_param((extra_type > 0)
? SPT_VARIANT
: ptype);
// fragmentatio flag
frag = false;
if (sparam != nullptr) {
// set id
sparam->set_id(be32toh(*param_id));
// reset data pointer
sparam->reset_data_p();
// reset index and extra type
sparam->index = 0;
sparam->extra_type = 0;
// get raw data
tmp_val = (char *)sm->_params
->get_child(i)
->_value
->get_child(0)
->linked_node
->tlv
->value;
int tmp_val_l = sm->_params
->get_child(i)
->_value
->get_child(0)
->linked_node
->tlv
->value_length;
// set service param data
sparam->set_data(tmp_val, tmp_val_l);
// check for fragmentation
if ((sm->_params
->get_child(i)
->_value
->get_child(1)) &&
(sm->_params
->get_child(i)
->_value
->get_child(1)
->has_linked_data(*in_sess))) {
const asn1::TLVNode *tlv = sm->_params
->get_child(i)
->_value
->get_child(1)
->linked_node
->tlv;
// fragmentation flag (value
// length 1 and value 1)
if ((tlv->value_length == 1) && (tlv->value[0] == 1)) {
frag = true;
}
}
// variant param id index and type
sparam->index = sm->_params
->get_child(i)
->_value
->get_child(2)
->linked_node
->tlv
->value[0];
sparam->extra_type = extra_type;
// set fragmentation flag and pointer to
// first fragment
if (frag) {
sparam->set_fragmented(true);
// first fragment
if (!smsg->get_frag_param()) {
// set first fragment pointer
smsg->set_frag_param(sparam);
sparam->fragment_index = 0;
// reset callbacks
sparam->clear_callbacks();
// process vparam
if (sparam->get_type() == SPT_VARIANT) {
smsg->vpmap.set_octets(sparam->get_id(),
sparam->get_data(),
sparam->get_data_size(),
sparam->get_index(),
smsg->get_frag_param()
->get_fragment_index());
}
// run callback
cb_args.clear_all_args();
cb_args.add_arg(GDT_CB_INPUT_ARGS,
GDT_CB_ARGS_SRVC_MSG,
smsg);
cb_args.add_arg(GDT_CB_INPUT_ARGS,
GDT_CB_ARGS_SRVC_PARAM,
sparam);
smsg->process_callback(GDT_ET_SRVC_PARAM_STREAM_NEW,
&cb_args);
// more fragments
} else {
smsg->get_frag_param()
->inc_total_data_size(sparam->get_data_size());
// process vparam
if (sparam->get_type() == SPT_VARIANT) {
smsg->vpmap.set_octets(sparam->get_id(),
sparam->get_data(),
sparam->get_data_size(),
sparam->get_index(),
smsg->get_frag_param()
->get_fragment_index());
}
// run callback
cb_args.clear_all_args();
cb_args.add_arg(GDT_CB_INPUT_ARGS,
GDT_CB_ARGS_SRVC_MSG,
smsg);
cb_args.add_arg(GDT_CB_INPUT_ARGS,
GDT_CB_ARGS_SRVC_PARAM,
sparam);
smsg->get_frag_param()
->process_callback(GDT_ET_SRVC_PARAM_STREAM_NEXT,
&cb_args);
// return to pool (fragmented
// params are not retained in
// memory)
ssh_new->smsg_m
->get_param_factory()
->free_param(sparam);
}
// no fragmentation or last fragment
} else {
// last fragment
if (smsg->get_frag_param()) {
sparam->set_fragmented(true);
smsg->get_frag_param()
->inc_total_data_size(sparam->get_data_size());
// process vparam
if (sparam->get_type() == SPT_VARIANT) {
smsg->vpmap.set_octets(sparam->get_id(),
sparam->get_data(),
sparam->get_data_size(),
sparam->get_index(),
smsg->get_frag_param()
->get_fragment_index());
mink_utils::VariantParam *vparam = smsg->vpmap.defragment(sparam->get_id(),
sparam->get_index());
if (vparam) vparam->set_type((mink_utils::VariantParamType)sparam->get_extra_type());
}
// run callback
cb_args.clear_all_args();
cb_args.add_arg(GDT_CB_INPUT_ARGS,
GDT_CB_ARGS_SRVC_MSG,
smsg);
cb_args.add_arg(GDT_CB_INPUT_ARGS,
GDT_CB_ARGS_SRVC_PARAM,
sparam);
smsg->get_frag_param()->process_callback(GDT_ET_SRVC_PARAM_STREAM_END,
&cb_args);
// return to pool (fragmented
// params are not retained in
// memory)
ssh_new->smsg_m
->get_param_factory()
->free_param(sparam);
ssh_new->smsg_m
->get_param_factory()
->free_param(smsg->get_frag_param());
// reset frag param
smsg->set_frag_param(nullptr);
// no fragmentation
} else {
sparam->set_fragmented(false);
// add param
smsg->add_param(be32toh(*param_id),
sparam,
sparam->index);
// process vparam
if (sparam->get_type() == SPT_VARIANT) {
// check param type
switch (sparam->get_extra_type()) {
// c string
case mink_utils::DPT_STRING: {
char tmp_str[256];
sparam->extract(tmp_str);
smsg->vpmap.set_cstr(sparam->get_id(),
tmp_str,
sparam->get_index());
break;
}
// int
case mink_utils::DPT_INT: {
uint64_t tmp = 0;
sparam->extract(&tmp);
smsg->vpmap.set_int(sparam->get_id(),
tmp,
sparam->get_index());
break;
}
// bool
case mink_utils::DPT_BOOL: {
bool tmp = false;
sparam->extract(&tmp);
smsg->vpmap.set_bool(sparam->get_id(),
tmp,
sparam->get_index());
break;
}
// other
default: {
unsigned char tmp_buff[256];
sparam->extract(&tmp_buff);
smsg->vpmap.set_octets(sparam->get_id(),
tmp_buff,
sparam->get_data_size(),
sparam->get_index());
break;
}
}
}
// run callback
cb_args.clear_all_args();
cb_args.add_arg(GDT_CB_INPUT_ARGS,
GDT_CB_ARGS_SRVC_MSG,
smsg);
cb_args.add_arg(GDT_CB_INPUT_ARGS,
GDT_CB_ARGS_SRVC_PARAM,
sparam);
smsg->process_callback(GDT_ET_SRVC_SHORT_PARAM_NEW,
&cb_args);
}
}
} else {
smsg->missing_params = true;
ssh_new->smsg_m->stats.inc(
SST_RX_SPARAM_POOL_EMPTY, 1);
}
}
stream->continue_sequence();
}
}
}
gdt::ServiceStreamHandlerDone::ServiceStreamHandlerDone(): ssh_new(nullptr){
}
void gdt::ServiceStreamHandlerDone::run(GDTCallbackArgs *args) {
auto stream = (gdt::GDTStream *)args->get_arg(gdt::GDT_CB_INPUT_ARGS,
gdt::GDT_CB_ARG_STREAM);
auto smsg = (ServiceMessage *)stream->get_param(SMSG_PT_SMSG);
auto in_msg = (asn1::GDTMessage *)args->get_arg(gdt::GDT_CB_INPUT_ARGS,
gdt::GDT_CB_ARG_IN_MSG);
auto in_sess = (uint64_t *)args->get_arg(gdt::GDT_CB_INPUT_ARGS,
gdt::GDT_CB_ARG_IN_MSG_ID);
// get ID->TYPE map
ParamIdTypeMap *idt_map = ssh_new->smsg_m->get_idt_map();
// set default param type
ServiceParamType ptype = SPT_UNKNOWN;
// declare param pointer
ServiceParam *sparam = nullptr;
// param id pointer
uint32_t *param_id = nullptr;
// raw data pointer
char *tmp_val = nullptr;
// raw data length
int tmp_val_l = 0;
// fragmentation
bool frag = false;
// extra type
int extra_type;
GDTCallbackArgs cb_args;
asn1::ServiceMessage *sm = nullptr;
asn1::Parameters *p = nullptr;
if(!smsg) return;
if(!in_msg) goto stream_complete;
sm = in_msg->_body->_service_msg;
// in_msg is nullptr in case of stream timeout
// check for params part
if (!sm->_params) goto stream_pre_complete;
if (!sm->_params->has_linked_data(*in_sess)) goto stream_pre_complete;
p = sm->_params;
// service id
if (sm->_service_id->has_linked_data(*in_sess)) {
auto tmp_ui32 = (uint32_t *)sm->_service_id
->linked_node
->tlv
->value;
smsg->set_service_id(be32toh(*tmp_ui32));
}
// process params
for (unsigned int i = 0; i < p->children.size(); i++) {
// check for value
if (!p->get_child(i)->_value) continue;
// check if value exists in current session
if (!p->get_child(i)
->_value
->has_linked_data(*in_sess)) continue;
// check if child exists
if (!p->get_child(i)
->_value
->get_child(0)) continue;
// check if child exists in current sesion
if (!p->get_child(i)
->_value
->get_child(0)
->has_linked_data(*in_sess)) continue;
// getr param id
param_id = (uint32_t *)p->get_child(i)
->_id
->linked_node
->tlv
->value;
// get param type by id
ptype = idt_map->get(be32toh(*param_id));
// get extra type
extra_type = p->get_child(i)
->_value
->get_child(3)
->linked_node
->tlv
->value[0];
// create param
sparam = ssh_new->smsg_m
->get_param_factory()
->new_param((extra_type > 0)
? SPT_VARIANT
: ptype);
// fragmentatio flag
frag = false;
if (sparam != nullptr) {
// set id
sparam->set_id(be32toh(*param_id));
// reset data pointer
sparam->reset_data_p();
// reset index and extra type
sparam->index = 0;
sparam->extra_type = 0;
// get raw data
tmp_val = (char *)p->get_child(i)
->_value
->get_child(0)
->linked_node
->tlv
->value;
tmp_val_l = p->get_child(i)
->_value
->get_child(0)
->linked_node
->tlv
->value_length;
// set service param data
sparam->set_data(tmp_val,
tmp_val_l);
// check for fragmentation
if ((p->get_child(i)
->_value
->get_child(1)) &&
(p->get_child(i)
->_value
->get_child(1)
->has_linked_data(*in_sess))) {
const asn1::TLVNode *tlv = p->get_child(i)
->_value
->get_child(1)
->linked_node
->tlv;
// fragmentation flag (value
// length 1 and value 1)
if ((tlv->value_length == 1) && (tlv->value[0] == 1)) {
frag = true;
}
}
// variant param id index and type
sparam->index = p->get_child(i)
->_value
->get_child(2)
->linked_node
->tlv
->value[0];
sparam->extra_type = extra_type;
// set fragmentation flag and
// pointer to first fragment
if (frag) {
sparam->set_fragmented(true);
// first fragment
if (!smsg->get_frag_param()) {
// set first fragment
// pointer
smsg->set_frag_param(sparam);
// reset callbacks
sparam->clear_callbacks();
// process vparam
if (sparam->get_type() == SPT_VARIANT) {
smsg->vpmap.set_octets(sparam->get_id(),
sparam->get_data(),
sparam->get_data_size(),
sparam->get_index(),
smsg->get_frag_param()
->get_fragment_index());
}
// run callback
cb_args.clear_all_args();
cb_args.add_arg(GDT_CB_INPUT_ARGS,
GDT_CB_ARGS_SRVC_MSG,
smsg);
cb_args.add_arg(GDT_CB_INPUT_ARGS,
GDT_CB_ARGS_SRVC_PARAM,
sparam);
smsg->process_callback(GDT_ET_SRVC_PARAM_STREAM_NEW,
&cb_args);
// more fragments
} else {
smsg->get_frag_param()
->inc_total_data_size(sparam->get_data_size());
// process vparam
if (sparam->get_type() == SPT_VARIANT) {
smsg->vpmap.set_octets(sparam->get_id(),
sparam->get_data(),
sparam->get_data_size(),
sparam->get_index(),
smsg->get_frag_param()
->get_fragment_index());
}
// run callback
cb_args.clear_all_args();
cb_args.add_arg(GDT_CB_INPUT_ARGS,
GDT_CB_ARGS_SRVC_MSG,
smsg);
cb_args.add_arg(GDT_CB_INPUT_ARGS,
GDT_CB_ARGS_SRVC_PARAM,
sparam);
smsg->get_frag_param()
->process_callback(GDT_ET_SRVC_PARAM_STREAM_NEXT,
&cb_args);
// return to pool
// (fragmented params are
// not retained in memory)
ssh_new->smsg_m
->get_param_factory()
->free_param(sparam);
}
// no fragmentation or last
// fragment
} else {
// last fragment
if (smsg->get_frag_param()) {
sparam->set_fragmented(true);
smsg->get_frag_param()
->inc_total_data_size(sparam->get_data_size());
// process vparam
if (sparam->get_type() == SPT_VARIANT) {
smsg->vpmap.set_octets(sparam->get_id(),
sparam->get_data(),
sparam->get_data_size(),
sparam->get_index(),
smsg->get_frag_param()
->get_fragment_index());
mink_utils::VariantParam *vparam = smsg->vpmap.defragment(sparam->get_id(),
sparam->get_index());
if (vparam != nullptr)
vparam->set_type((mink_utils::VariantParamType)sparam->get_extra_type());
}
// run callback
cb_args.clear_all_args();
cb_args.add_arg(GDT_CB_INPUT_ARGS,
GDT_CB_ARGS_SRVC_MSG,
smsg);
cb_args.add_arg(GDT_CB_INPUT_ARGS,
GDT_CB_ARGS_SRVC_PARAM,
sparam);
smsg->get_frag_param()
->process_callback(GDT_ET_SRVC_PARAM_STREAM_END,
&cb_args);
// return to pool
// (fragmented params are
// not retained in memory)
ssh_new->smsg_m
->get_param_factory()
->free_param(sparam);
ssh_new->smsg_m
->get_param_factory()
->free_param(smsg->get_frag_param());
// reset frag param
smsg->set_frag_param(nullptr);
// no fragmentation
} else {
sparam->set_fragmented(false);
// add param
smsg->add_param(be32toh(*param_id),
sparam,
sparam->index);
// process vparam
if (sparam->get_type() == SPT_VARIANT) {
// check param type
switch (sparam->get_extra_type()) {
// c string
case mink_utils::DPT_STRING: {
char tmp_str[256];
sparam->extract(tmp_str);
smsg->vpmap.set_cstr(sparam->get_id(),
tmp_str,
sparam->get_index());
break;
}
// int
case mink_utils::DPT_INT: {
uint64_t tmp = 0;
sparam->extract(&tmp);
smsg->vpmap.set_int(sparam->get_id(),
tmp,
sparam->get_index());
break;
}
// bool
case mink_utils::DPT_BOOL: {
bool tmp = false;
sparam->extract(&tmp);
smsg->vpmap.set_bool(sparam->get_id(),
tmp,
sparam->get_index());
break;
}
// other
default: {
unsigned char tmp_buff[256];
sparam->extract(&tmp_buff);
smsg->vpmap.set_octets(sparam->get_id(),
tmp_buff,
sparam->get_data_size(),
sparam->get_index());
break;
}
}
}
// run callback
cb_args.clear_all_args();
cb_args.add_arg(GDT_CB_INPUT_ARGS,
GDT_CB_ARGS_SRVC_MSG,
smsg);
cb_args.add_arg(GDT_CB_INPUT_ARGS,
GDT_CB_ARGS_SRVC_PARAM,
sparam);
smsg->process_callback(GDT_ET_SRVC_SHORT_PARAM_NEW,
&cb_args);
}
}
} else {
smsg->missing_params = true;
ssh_new->smsg_m->stats.inc(SST_RX_SPARAM_POOL_EMPTY, 1);
}
}
stream_pre_complete:
// set as completed if status is present and == ok (0)
if (asn1::node_exists(in_msg->_header->_status, *in_sess)) {
if (in_msg->_header->_status->linked_node->tlv->value[0] == 0)
smsg->set_complete(true);
// no status, set as completed
} else
smsg->set_complete(true);
stream_complete:
// run callback
cb_args.clear_all_args();
cb_args.add_arg(GDT_CB_INPUT_ARGS, GDT_CB_ARG_STREAM, stream);
cb_args.add_arg(GDT_CB_INPUT_ARGS, GDT_CB_ARGS_SRVC_MSG, smsg);
cb_args.add_arg(GDT_CB_INPUT_ARGS,
GDT_CB_ARG_CLIENT,
stream->get_client());
smsg->process_callback(GDT_ET_SRVC_MSG_COMPLETE, &cb_args);
// check for pass param
auto smsg_pass = (ServiceMessage *)stream->get_param(SMSG_PT_PASS);
// if pass not set
// free message if auto_free flag was set (default)
if ((smsg_pass != smsg) && (smsg->get_auto_free())) {
ssh_new->smsg_m->free_smsg(smsg);
}
// remove params
stream->remove_param(SMSG_PT_SMSG);
stream->remove_param(SMSG_PT_PASS);
// smsg not allocated in new stream event
// error should be handled in GDT_ET_SRVC_MSG_ERROR handler
}
void gdt::ServiceStreamNewClient::run(GDTCallbackArgs *args) {
auto client = (gdt::GDTClient *)args->get_arg(gdt::GDT_CB_INPUT_ARGS,
gdt::GDT_CB_ARG_CLIENT);
smsg_m->setup_client(client);
// user NEW CLIENT handler
if (usr_stream_nc_hndlr != nullptr)
usr_stream_nc_hndlr->run(args);
}
void gdt::ServiceStreamHandlerNew::run(GDTCallbackArgs *args) {
auto in_msg = (asn1::GDTMessage *)args->get_arg(gdt::GDT_CB_INPUT_ARGS,
gdt::GDT_CB_ARG_IN_MSG);
auto in_sess = (uint64_t *)args->get_arg(gdt::GDT_CB_INPUT_ARGS,
gdt::GDT_CB_ARG_IN_MSG_ID);
auto stream = (gdt::GDTStream *)args->get_arg(gdt::GDT_CB_INPUT_ARGS,
gdt::GDT_CB_ARG_STREAM);
GDTCallbackArgs cb_args;
// check for body
if (!in_msg->_body) {
// NON ServiceMessage user handler
if (usr_stream_hndlr != nullptr) usr_stream_hndlr->run(args);
return;
}
// check for ServiceMessage
if (!in_msg->_body->_service_msg->has_linked_data(*in_sess)) {
if (usr_stream_hndlr != nullptr) usr_stream_hndlr->run(args);
return;
}
// set event handlers
stream->set_callback(gdt::GDT_ET_STREAM_NEXT, &ssh_next);
stream->set_callback(gdt::GDT_ET_STREAM_END, &ssh_done);
stream->set_callback(gdt::GDT_ET_STREAM_TIMEOUT, &ssh_done);
// create new ServiceMessage
ServiceMessage *smsg = smsg_m->new_smsg();
// nullptr check
if (!smsg) {
smsg_m->stats.inc(SST_RX_SMSG_POOL_EMPTY, 1);
// run callback
cb_args.clear_all_args();
cb_args.add_arg(GDT_CB_INPUT_ARGS, GDT_CB_ARG_STREAM, stream);
smsg_m->process_callback(GDT_ET_SRVC_MSG_ERROR, &cb_args);
return;
}
// reset frag
smsg->set_frag_param(nullptr);
// reset callbacks
smsg->clear_callbacks();
// clear vpmap
smsg->vpmap.clear_params();
// set as incomplete
smsg->set_complete(false);
// clear stream params
stream->clear_params();
// set ServiceMessage as GDT stream param
stream->set_param(SMSG_PT_SMSG, smsg);
// reset auto free
smsg->set_auto_free(true);
// reset missing params
smsg->missing_params = false;
// run callback
cb_args.clear_all_args();
cb_args.add_arg(GDT_CB_INPUT_ARGS, GDT_CB_ARGS_SRVC_MSG,
smsg);
smsg_m->process_callback(GDT_ET_SRVC_MSG_NEW, &cb_args);
asn1::ServiceMessage *sm = in_msg->_body->_service_msg;
asn1::Parameters *p = sm->_params;
// get ID->TYPE map
ParamIdTypeMap *idt_map = smsg_m->get_idt_map();
// set default param type
ServiceParamType ptype = SPT_UNKNOWN;
// declare param pointer
ServiceParam *sparam = nullptr;
// param id pointer
uint32_t *param_id = nullptr;
// raw data pointer
char *tmp_val = nullptr;
// raw data length
int tmp_val_l = 0;
// fragmentation
bool frag = false;
// extra type
int extra_type;
// check for params part
if (!p) goto stream_continue;
if (!p->has_linked_data(*in_sess)) goto stream_continue;
// service id
if (sm->_service_id->has_linked_data(*in_sess)) {
auto tmp_ui32 = (uint32_t *)sm->_service_id
->linked_node
->tlv
->value;
smsg->set_service_id(be32toh(*tmp_ui32));
}
// process params
for (unsigned int i = 0; i < p->children.size(); i++) {
// check for value
if (!p->get_child(i)->_value) continue;
// check if value exists in current session
if (!p->get_child(i)
->_value
->has_linked_data(*in_sess)) continue;
// check if child exists
if (!p->get_child(i)
->_value
->get_child(0)) continue;
// check if child exists in current
// sesion
if (!p->get_child(i)
->_value
->get_child(0)
->has_linked_data(*in_sess)) continue;
// getr param id
param_id = (uint32_t *)p->get_child(i)
->_id
->linked_node
->tlv
->value;
// get param type by id
ptype = idt_map->get(be32toh(*param_id));
// get extra type
extra_type = p->get_child(i)
->_value
->get_child(3)
->linked_node
->tlv
->value[0];
// create param
sparam = smsg_m->get_param_factory()
->new_param((extra_type > 0)
? SPT_VARIANT
: ptype);
// fragmentation flag
frag = false;
if (sparam != nullptr) {
// set id
sparam->set_id(be32toh(*param_id));
// reset data pointer
sparam->reset_data_p();
// reset index and extra type
sparam->index = 0;
sparam->extra_type = 0;
// get raw data
tmp_val = (char *)p->get_child(i)
->_value
->get_child(0)
->linked_node
->tlv
->value;
tmp_val_l = p->get_child(i)
->_value
->get_child(0)
->linked_node
->tlv
->value_length;
// set service param data
sparam->set_data(tmp_val,
tmp_val_l);
// check for fragmentation
if ((p->get_child(i)
->_value
->get_child(1)) &&
(p->get_child(i)
->_value
->get_child(1)
->has_linked_data(*in_sess))) {
const asn1::TLVNode *tlv = p->get_child(i)
->_value
->get_child(1)
->linked_node
->tlv;
// fragmentation flag
// (value length 1 and
// value 1)
if ((tlv->value_length == 1) && (tlv->value[0] == 1)) {
frag = true;
}
}
// variant param id index and
// type
sparam->index = p->get_child(i)
->_value
->get_child(2)
->linked_node
->tlv
->value[0];
sparam->extra_type = extra_type;
// set fragmentation flag and
// pointer to first fragment
if (frag) {
sparam->set_fragmented(true);
// first fragment
if (!smsg->get_frag_param()) {
// set first fragment
// pointer
smsg->set_frag_param(sparam);
// reset callbacks
sparam->clear_callbacks();
// process vparam
if (sparam->get_type() == SPT_VARIANT) {
smsg->vpmap.set_octets(sparam->get_id(),
sparam->get_data(),
sparam->get_data_size(),
sparam->get_index(),
smsg->get_frag_param()
->get_fragment_index());
}
// run callback
cb_args.clear_all_args();
cb_args.add_arg(GDT_CB_INPUT_ARGS,
GDT_CB_ARGS_SRVC_MSG,
smsg);
cb_args.add_arg(GDT_CB_INPUT_ARGS,
GDT_CB_ARGS_SRVC_PARAM,
sparam);
smsg->process_callback(GDT_ET_SRVC_PARAM_STREAM_NEW,
&cb_args);
// more fragments
} else {
smsg->get_frag_param()
->inc_total_data_size(sparam->get_data_size());
// process vparam
if (sparam->get_type() == SPT_VARIANT) {
smsg->vpmap.set_octets(sparam->get_id(),
sparam->get_data(),
sparam->get_data_size(),
sparam->get_index(),
smsg->get_frag_param()
->get_fragment_index());
}
// run callback
cb_args.clear_all_args();
cb_args.add_arg(GDT_CB_INPUT_ARGS,
GDT_CB_ARGS_SRVC_MSG,
smsg);
cb_args.add_arg(GDT_CB_INPUT_ARGS,
GDT_CB_ARGS_SRVC_PARAM,
sparam);
smsg->get_frag_param()
->process_callback(GDT_ET_SRVC_PARAM_STREAM_NEXT,
&cb_args);
// return to pool
// (fragmented params
// are not retained in
// memory)
smsg_m->get_param_factory()
->free_param(sparam);
}
// no fragmentation or last
// fragment
} else {
// last fragment
if (smsg->get_frag_param()) {
sparam->set_fragmented(true);
smsg->get_frag_param()
->inc_total_data_size(sparam->get_data_size());
// process vparam
if (sparam->get_type() == SPT_VARIANT) {
smsg->vpmap.set_octets(sparam->get_id(),
sparam->get_data(),
sparam->get_data_size(),
sparam->get_index(),
smsg->get_frag_param()
->get_fragment_index());
mink_utils::VariantParam *vparam = smsg->vpmap.defragment(sparam->get_id(),
sparam->get_index());
if (vparam != nullptr)
vparam->set_type((mink_utils::VariantParamType)sparam->get_extra_type());
}
// run callback
cb_args.clear_all_args();
cb_args.add_arg(GDT_CB_INPUT_ARGS,
GDT_CB_ARGS_SRVC_MSG,
smsg);
cb_args.add_arg(GDT_CB_INPUT_ARGS,
GDT_CB_ARGS_SRVC_PARAM,
sparam);
smsg->get_frag_param()
->process_callback(GDT_ET_SRVC_PARAM_STREAM_END,
&cb_args);
// return to pool
// (fragmented params
// are not retained in
// memory)
smsg_m->get_param_factory()->free_param(sparam);
smsg_m->get_param_factory()->free_param(smsg->get_frag_param());
// reset frag param
smsg->set_frag_param(nullptr);
// no fragmentation
} else {
sparam->set_fragmented(false);
// add param
smsg->add_param(be32toh(*param_id),
sparam,
sparam->index);
// process vparam
if (sparam->get_type() == SPT_VARIANT) {
// check param type
switch (sparam->get_extra_type()) {
// c string
case mink_utils::DPT_STRING: {
char tmp_str[256];
sparam->extract(tmp_str);
smsg->vpmap.set_cstr(sparam->get_id(),
tmp_str,
sparam->get_index());
break;
}
// int
case mink_utils::DPT_INT: {
uint64_t tmp = 0;
sparam->extract(&tmp);
smsg->vpmap.set_int(sparam->get_id(),
tmp,
sparam->get_index());
break;
}
// bool
case mink_utils::DPT_BOOL: {
bool tmp = false;
sparam->extract(&tmp);
smsg->vpmap.set_bool(sparam->get_id(),
tmp,
sparam->get_index());
break;
}
// other
default: {
unsigned char tmp_buff[256];
sparam->extract(&tmp_buff);
smsg->vpmap.set_octets(sparam->get_id(),
tmp_buff,
sparam->get_data_size(),
sparam->get_index());
break;
}
}
}
// run callback
cb_args.clear_all_args();
cb_args.add_arg(GDT_CB_INPUT_ARGS,
GDT_CB_ARGS_SRVC_MSG,
smsg);
cb_args.add_arg(GDT_CB_INPUT_ARGS,
GDT_CB_ARGS_SRVC_PARAM,
sparam);
smsg->process_callback(GDT_ET_SRVC_SHORT_PARAM_NEW,
&cb_args);
}
}
} else {
smsg->missing_params = true;
smsg_m->stats.inc(SST_RX_SPARAM_POOL_EMPTY, 1);
}
}
stream_continue:
// continue
stream->continue_sequence();
}
gdt::ServiceMsgManager::ServiceMsgManager(ParamIdTypeMap *_idt_map,
GDTCallbackMethod *_new_msg_hndlr,
GDTCallbackMethod *_nonsrvc_stream_hndlr,
unsigned int pool_size,
unsigned int param_pool_size) {
idt_map = _idt_map;
param_factory = new ServiceParamFactory(true, false, param_pool_size);
sem_init(&q_sem, 0, 0);
srvcs_hndlr.smsg_m = this;
srvcs_nc.smsg_m = this;
srvcs_hndlr.usr_stream_hndlr = _nonsrvc_stream_hndlr;
srvcs_hndlr.ssh_next.ssh_new = &srvcs_hndlr;
srvcs_hndlr.ssh_done.ssh_new = &srvcs_hndlr;
msg_pool.init(pool_size);
msg_pool.construct_objects();
cb_handler.set_callback(GDT_ET_SRVC_MSG_NEW, _new_msg_hndlr);
// set manager pointers
ServiceMessage *tmp_arr[pool_size];
for (unsigned int i = 0; i < pool_size; i++) {
tmp_arr[i] = msg_pool.allocate_constructed();
tmp_arr[i]->set_smsg_manager(this);
}
// return back to pool
for (unsigned int i = 0; i < pool_size; i++)
msg_pool.deallocate_constructed(tmp_arr[i]);
// random generator
timespec tmp_time;
clock_gettime(0, &tmp_time);
// stats
stats.register_item(SST_RX_SMSG_POOL_EMPTY);
stats.register_item(SST_RX_SPARAM_POOL_EMPTY);
}
gdt::ServiceMsgManager::~ServiceMsgManager() {
sem_destroy(&q_sem);
delete param_factory;
}
void gdt::ServiceMsgManager::generate_uuid(unsigned char *out) {
random_gen.generate(out, 16);
}
gdt::GDTCallbackMethod *gdt::ServiceMsgManager::get_srvcs_hndlr() {
return &srvcs_hndlr;
}
gdt::GDTCallbackMethod *gdt::ServiceMsgManager::get_srvcs_nc_hndlr() {
return &srvcs_nc;
}
void gdt::ServiceMsgManager::set_new_msg_handler(GDTCallbackMethod *hndlr) {
cb_handler.set_callback(GDT_ET_SRVC_MSG_NEW, hndlr);
}
void gdt::ServiceMsgManager::set_msg_err_handler(GDTCallbackMethod *hndlr) {
cb_handler.set_callback(GDT_ET_SRVC_MSG_ERROR, hndlr);
}
bool gdt::ServiceMsgManager::process_callback(GDTEventType type,
GDTCallbackArgs *args) {
return cb_handler.process_callback(type, args);
}
void gdt::ServiceMsgManager::setup_server(GDTSession *gdts,
gdt::GDTCallbackMethod *_usr_stream_nc_hndlr,
gdt::GDTCallbackMethod *_usr_stream_hndlr) {
// set extra user stream handler
srvcs_nc.usr_stream_nc_hndlr = _usr_stream_nc_hndlr;
srvcs_nc.usr_stream_hndlr = _usr_stream_hndlr;
// set end event handler
gdts->set_callback(gdt::GDT_ET_CLIENT_NEW, &srvcs_nc);
}
void gdt::ServiceMsgManager::setup_client(GDTClient *gdtc) {
// nullptr check
if (gdtc == nullptr)
return;
// set end event handler
gdtc->set_callback(gdt::GDT_ET_STREAM_NEW, &srvcs_hndlr);
}
gdt::ServiceMessage *gdt::ServiceMsgManager::new_smsg() {
ServiceMessage *tmp = msg_pool.allocate_constructed();
return tmp;
}
int gdt::ServiceMsgManager::free_smsg(ServiceMessage *msg,
bool params_only,
bool clear_vpmap) {
// free params
std::vector<ServiceParam *> *params = msg->get_param_map();
ServiceParam *param = nullptr;
for (unsigned int i = 0; i < params->size(); i++) {
param = (*params)[i];
// check for temp linked buffer params
for (unsigned int j = 0; j < param->linked.size(); j++) {
param_factory->free_param(param->linked[j]);
}
param->linked.clear();
// free param
param_factory->free_param(param);
}
// check frag param
if (msg->get_frag_param() != nullptr) {
// check for temp linked buffer params in frag param
for (unsigned int j = 0; j < msg->get_frag_param()->linked.size();
j++) {
param_factory->free_param(msg->get_frag_param()->linked[j]);
}
msg->get_frag_param()->linked.clear();
// free frag param
param_factory->free_param(msg->get_frag_param());
}
// clear params
params->clear();
// clear vpmap
if (clear_vpmap)
msg->vpmap.clear_params();
// if freeing smsg also
if (!params_only) {
msg->params.clear_params();
// return to pool
int res = msg_pool.deallocate_constructed(msg);
// result
return res;
}
// ok
return 0;
}
gdt::ServiceParamFactory *gdt::ServiceMsgManager::get_param_factory() {
return param_factory;
}
gdt::ParamIdTypeMap *gdt::ServiceMsgManager::get_idt_map() { return idt_map; }
int gdt::ServiceMsgManager::vpmap_sparam_sync(ServiceMessage *msg,
const std::vector<ServiceParam*> *pmap) {
// freee sparams, do not clear vpmap
free_smsg(msg, true, false);
// vars
ServiceParam *param = nullptr;
bool err = false;
// process vpmap
for (mink_utils::VariantParamMap<uint32_t>::it_t it =
msg->vpmap.get_begin();
it != msg->vpmap.get_end(); it++) {
// skip pointer param type
if (it->second.get_type() == mink_utils::DPT_POINTER)
continue;
// skip context other then default 0
if (it->first.context != 0)
continue;
// allocate new service param
param = get_param_factory()->new_param(gdt::SPT_VARIANT);
// sanity check
if (param == nullptr) {
err = true;
break;
}
// set service param data from decoded param
param->set(&it->second);
// add service param to service message
msg->add_param(it->first.key, param, it->first.index);
}
// extra params
if(pmap != nullptr){
for(auto it = pmap->begin(); it != pmap->end(); it++){
// add service param to service message
msg->add_param((*it)->get_id(), (*it), (*it)->get_index());
}
}
// result
return err;
}
int gdt::ServiceMsgManager::send(ServiceMessage *msg,
GDTClient *gdtc,
const char *dtype,
const char *did,
bool async,
gdt::GDTCallbackMethod *on_sent) {
if ((msg != nullptr) && (gdtc != nullptr)) {
// start new GDT stream
GDTStream *gdt_stream = gdtc->allocate_stream_pool();
// if stream cannot be created, return err
if (gdt_stream == nullptr) {
gdtc->get_stats(GDT_OUTBOUND_STATS)
->strm_alloc_errors.add_fetch(1);
return 10;
}
// setup stream directly
gdt_stream->set_client(gdtc);
gdt_stream->reset(true);
gdt_stream->clear_callbacks();
gdt_stream->clear_params();
gdt_stream->set_destination(dtype, did);
unsigned int pc;
unsigned int bc;
unsigned int tbc = 0;
// param map
std::vector<ServiceParam *> *pmap = msg->get_param_map();
pc = pmap->size();
// calculate total param size (add extra 3 bytes for dual byte length
// and single byte tag)
ServiceParam *tmp_param = nullptr;
for (unsigned int i = 0; i < pmap->size(); i++) {
tmp_param = (*pmap)[i];
// check fragmentation
if (tmp_param->is_fragmented()) {
// -1 to exclude already included first fragment
pc += tmp_param->fragments - 1;
// add extra 3 bytes to size calculation (Tag + Length (BER
// Definite long))
}
}
// add extra buffer for fragmented params (used when streaming from non
// pre-allocated sources) max size is pps
ServiceParam *new_param = nullptr;
for (unsigned int i = 0; i < pmap->size(); i++) {
tmp_param = (*pmap)[i];
if (tmp_param->is_fragmented()) {
for (unsigned int j = 0; j < 4; j++) {
new_param = param_factory->new_param(tmp_param->type);
if (new_param != nullptr)
tmp_param->linked.push_back(new_param);
}
tmp_param->linked_index = 0;
}
}
// reset user handler from previous instance
msg->get_sdone_hndlr()->usr_method = nullptr;
// reset status from previous instance
msg->get_sdone_hndlr()->status = 0;
// set end event handler
gdt_stream->set_callback(gdt::GDT_ET_STREAM_END,
msg->get_sdone_hndlr());
gdt_stream->set_callback(gdt::GDT_ET_STREAM_TIMEOUT,
msg->get_sdone_hndlr());
// if async mode, set user handler
if (async)
msg->get_sdone_hndlr()->usr_method = on_sent;
// get handler
ServiceMessageNext *cb = msg->get_snext_hndlr();
// reset pos (param pos)
cb->pos = 0;
// reset pindex (param pos including fragments)
cb->pindex = 0;
cb->pc = pc;
// set callback
gdt_stream->set_callback(gdt::GDT_ET_STREAM_NEXT, cb);
// create body
asn1::GDTMessage *gdtm = gdt_stream->get_gdt_message();
// prepare body
if (gdtm->_body != nullptr) {
gdtm->_body->unlink(1);
gdtm->_body->_service_msg->set_linked_data(1);
} else {
gdtm->set_body();
gdtm->prepare();
}
asn1::ServiceMessage *sm = gdtm->_body->_service_msg;
// set params, allocate 10 initial children
if (!sm->_params) {
sm->set_params();
asn1::Parameters *p = sm->_params;
// set children, allocate more
for (int i = 0; i < 10; i++) {
p->set_child(i);
p->get_child(i)->set_value();
p->get_child(i)->_value->set_child(0);
p->get_child(i)->_value->set_child(1);
p->get_child(i)->_value->set_child(2);
p->get_child(i)->_value->set_child(3);
}
// prepare
asn1::prepare(sm, sm->parent_node);
}
// set service id
sm->_service_id->set_linked_data(1,
(unsigned char *)msg->get_service_idp(),
sizeof(uint32_t));
// set service action
sm->_service_action->set_linked_data(1,
(unsigned char *)msg->get_service_actionp(),
1);
// params
ServiceParam *sc_param = nullptr;
asn1::Parameters *params = gdtm->_body->_service_msg->_params;
// loop params
for (unsigned int j = 0;
(tbc < MAX_PARAMS_SIZE) && (cb->pos < pmap->size());
j++, cb->pos++, cb->pindex++) {
sc_param = (*pmap)[cb->pos];
// check if more allocations are needed
if (params->get_child(j) == nullptr) {
params->set_child(j);
params->get_child(j)->set_value();
params->get_child(j)->_value->set_child(0);
params->get_child(j)->_value->set_child(1);
params->get_child(j)->_value->set_child(2);
params->get_child(j)->_value->set_child(3);
// prepare
asn1::prepare(params, params->parent_node);
}
// update total byte count
tbc += sc_param->data_size + 25;
// check if limit reached
if (tbc > MAX_PARAMS_SIZE)
break;
// set gdt param id and data
params->get_child(j)->_id->set_linked_data(1,
(unsigned char *)sc_param->get_idp(),
sizeof(uint32_t));
params->get_child(j)->_value->get_child(0)->set_linked_data(1,
sc_param->data_p,
sc_param->data_size);
// check fragmentation
if (sc_param->is_fragmented()) {
params->get_child(j)->_value->get_child(1)->set_linked_data(1,
(unsigned char *)sc_param->get_fragmentation_p(),
1);
// variant param id index and type
params->get_child(j)->_value->get_child(2)->set_linked_data(1,
(unsigned char *)&sc_param->index,
1);
params->get_child(j)->_value->get_child(3)->set_linked_data(1,
(unsigned char *)&sc_param->extra_type,
1);
// next fragment
++sc_param->fragment_index;
++j;
++cb->pindex;
// run data fetch method
(*sc_param->param_data_cb)(sc_param,
sc_param->in_data_p,
sc_param->total_data_size);
// process fragments
while ((tbc < MAX_PARAMS_SIZE) && (sc_param->fragment_index < sc_param->fragments)) {
process_fragments(&bc, &tbc, sc_param, params, j);
// check if limit reached
if (tbc > MAX_PARAMS_SIZE)
break;
// set gdt values
params->get_child(j)->_id->set_linked_data(1,
(unsigned char *)sc_param->get_idp(),
sizeof(uint32_t));
params->get_child(j)->_value->get_child(0)->set_linked_data(1,
sc_param->data_p,
bc);
// variant param id index and type
params->get_child(j)->_value->get_child(2)->set_linked_data(1,
(unsigned char *)&sc_param->index,
1);
params->get_child(j)->_value->get_child(3)->set_linked_data(1,
(unsigned char *)&sc_param->extra_type,
1);
// check if last fragment, disable fragmentation flag (last
// fragment must not contain fragmentation flag)
if (sc_param->fragment_index == (sc_param->fragments - 1)) {
params->get_child(j)
->_value
->get_child(1)
->set_linked_data(1,
(unsigned char*)&ServiceParam::FRAGMENTATION_DONE,
1);
} else {
// set gdt fragmentation flag
params->get_child(j)
->_value->get_child(1)
->set_linked_data(1,
(unsigned char*)&ServiceParam::FRAGMENTATION_NEXT,
1);
}
// next
++sc_param->fragment_index;
++j;
++cb->pindex;
// run data fetch method
(*sc_param->param_data_cb)(sc_param,
sc_param->in_data_p,
sc_param->total_data_size);
}
// break if fragmentation in progress and not finished (to skip
// increment, next call should process the same param again)
if (sc_param->fragment_index < sc_param->fragments)
break;
// rewind gdt param child count and packet index
else {
--j;
--cb->pindex;
}
// no fragmentation
} else {
params->get_child(j)->_value->get_child(1)->set_linked_data(1,
(unsigned char *)sc_param->get_fragmentation_p(),
1);
// variant param id index and type
params->get_child(j)->_value->get_child(2)->set_linked_data(1,
(unsigned char *)&sc_param->index,
1);
params->get_child(j)->_value->get_child(3)->set_linked_data(1,
(unsigned char *)&sc_param->extra_type,
1);
}
}
// remove unused chidren
for (unsigned int i = cb->pindex; i < params->children.size(); i++)
params->get_child(i)->unlink(1);
// add to list of active streams directly
gdtc->add_stream(gdt_stream);
// start stream
gdt_stream->send(true);
// sync mode
if (!async) {
if (msg->signal_wait() == 1)
return 100;
else
return msg->get_sdone_hndlr()->status;
// async mode
} else {
// ok
return 0;
}
}
// err
return 1;
}
void gdt::ServiceMessageAsyncDone::run(GDTCallbackArgs *args) {
auto smsg = (gdt::ServiceMessage *)args->get_arg(gdt::GDT_CB_INPUT_ARGS,
gdt::GDT_CB_ARGS_SRVC_MSG);
smsg->get_smsg_manager()->free_smsg(smsg);
}
| 37.180074 | 125 | 0.44981 | dfranusic |
eee054ddb45e98344a7c22275a544a0007ce30fe | 135 | cpp | C++ | Plugins/KizuEngine/Source/KizuEngine/Private/Core/Combat/KizuCombat.cpp | Hiro-KE/UE4-KizuEngine | 42c5f5c934f0fa6a3265a39157087a61abeaa3a0 | [
"MIT"
] | 11 | 2020-12-26T23:16:45.000Z | 2022-03-19T20:19:36.000Z | Plugins/KizuEngine/Source/KizuEngine/Private/Core/Combat/KizuCombat.cpp | Fukaidemon/UE4-KizuEngine | 42c5f5c934f0fa6a3265a39157087a61abeaa3a0 | [
"MIT"
] | null | null | null | Plugins/KizuEngine/Source/KizuEngine/Private/Core/Combat/KizuCombat.cpp | Fukaidemon/UE4-KizuEngine | 42c5f5c934f0fa6a3265a39157087a61abeaa3a0 | [
"MIT"
] | null | null | null | // KizuEngine Copyright (c) 2019 Jed Fakhfekh. This software is released under the MIT License.
#include "Core/Combat/KizuCombat.h"
| 22.5 | 95 | 0.762963 | Hiro-KE |
eee1135884b51f4dabc53219fbf7019ecb5d2e0e | 4,181 | cpp | C++ | cdn/src/v20180606/model/HttpHeaderRule.cpp | sinjoywong/tencentcloud-sdk-cpp | 1b931d20956a90b15a6720f924e5c69f8786f9f4 | [
"Apache-2.0"
] | null | null | null | cdn/src/v20180606/model/HttpHeaderRule.cpp | sinjoywong/tencentcloud-sdk-cpp | 1b931d20956a90b15a6720f924e5c69f8786f9f4 | [
"Apache-2.0"
] | null | null | null | cdn/src/v20180606/model/HttpHeaderRule.cpp | sinjoywong/tencentcloud-sdk-cpp | 1b931d20956a90b15a6720f924e5c69f8786f9f4 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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 <tencentcloud/cdn/v20180606/model/HttpHeaderRule.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Cdn::V20180606::Model;
using namespace std;
HttpHeaderRule::HttpHeaderRule() :
m_headerModeHasBeenSet(false),
m_headerNameHasBeenSet(false),
m_headerValueHasBeenSet(false)
{
}
CoreInternalOutcome HttpHeaderRule::Deserialize(const rapidjson::Value &value)
{
string requestId = "";
if (value.HasMember("HeaderMode") && !value["HeaderMode"].IsNull())
{
if (!value["HeaderMode"].IsString())
{
return CoreInternalOutcome(Error("response `HttpHeaderRule.HeaderMode` IsString=false incorrectly").SetRequestId(requestId));
}
m_headerMode = string(value["HeaderMode"].GetString());
m_headerModeHasBeenSet = true;
}
if (value.HasMember("HeaderName") && !value["HeaderName"].IsNull())
{
if (!value["HeaderName"].IsString())
{
return CoreInternalOutcome(Error("response `HttpHeaderRule.HeaderName` IsString=false incorrectly").SetRequestId(requestId));
}
m_headerName = string(value["HeaderName"].GetString());
m_headerNameHasBeenSet = true;
}
if (value.HasMember("HeaderValue") && !value["HeaderValue"].IsNull())
{
if (!value["HeaderValue"].IsString())
{
return CoreInternalOutcome(Error("response `HttpHeaderRule.HeaderValue` IsString=false incorrectly").SetRequestId(requestId));
}
m_headerValue = string(value["HeaderValue"].GetString());
m_headerValueHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
void HttpHeaderRule::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const
{
if (m_headerModeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "HeaderMode";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_headerMode.c_str(), allocator).Move(), allocator);
}
if (m_headerNameHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "HeaderName";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_headerName.c_str(), allocator).Move(), allocator);
}
if (m_headerValueHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "HeaderValue";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_headerValue.c_str(), allocator).Move(), allocator);
}
}
string HttpHeaderRule::GetHeaderMode() const
{
return m_headerMode;
}
void HttpHeaderRule::SetHeaderMode(const string& _headerMode)
{
m_headerMode = _headerMode;
m_headerModeHasBeenSet = true;
}
bool HttpHeaderRule::HeaderModeHasBeenSet() const
{
return m_headerModeHasBeenSet;
}
string HttpHeaderRule::GetHeaderName() const
{
return m_headerName;
}
void HttpHeaderRule::SetHeaderName(const string& _headerName)
{
m_headerName = _headerName;
m_headerNameHasBeenSet = true;
}
bool HttpHeaderRule::HeaderNameHasBeenSet() const
{
return m_headerNameHasBeenSet;
}
string HttpHeaderRule::GetHeaderValue() const
{
return m_headerValue;
}
void HttpHeaderRule::SetHeaderValue(const string& _headerValue)
{
m_headerValue = _headerValue;
m_headerValueHasBeenSet = true;
}
bool HttpHeaderRule::HeaderValueHasBeenSet() const
{
return m_headerValueHasBeenSet;
}
| 28.442177 | 138 | 0.701746 | sinjoywong |
eee7b92440f44b6c9f6b37733489daef1568084a | 6,162 | hpp | C++ | include/eve/module/real/core/function/regular/generic/store.hpp | the-moisrex/eve | 80b52663eefee11460abb0aedf4158a5067cf7dc | [
"MIT"
] | 340 | 2020-09-16T21:12:48.000Z | 2022-03-28T15:40:33.000Z | third-party/eve/module/real/core/function/regular/generic/store.hpp | aguinet/ecsimd | cba9e7fe76601b98cbaeea317b6c4e671272e70b | [
"Apache-2.0"
] | 383 | 2020-09-17T06:56:35.000Z | 2022-03-13T15:58:53.000Z | third-party/eve/module/real/core/function/regular/generic/store.hpp | aguinet/ecsimd | cba9e7fe76601b98cbaeea317b6c4e671272e70b | [
"Apache-2.0"
] | 28 | 2021-02-27T23:11:23.000Z | 2022-03-25T12:31:29.000Z | //==================================================================================================
/*
EVE - Expressive Vector Engine
Copyright : EVE Contributors & Maintainers
SPDX-License-Identifier: MIT
*/
//==================================================================================================
#pragma once
#include <eve/concept/value.hpp>
#include <eve/detail/implementation.hpp>
#include <eve/detail/kumi.hpp>
#include <eve/function/bit_cast.hpp>
#include <eve/function/replace.hpp>
#include <eve/memory/aligned_ptr.hpp>
namespace eve::detail
{
// -----------------------------------------------------------------------------------------------
// simd Tuple case
template<kumi::product_type T, typename S, kumi::sized_product_type<T::size()> Ptr>
EVE_FORCEINLINE void
store_(EVE_SUPPORTS(cpu_), wide<T, S> const &value, Ptr ptrs) noexcept
requires std::same_as<abi_t<T, S>, bundle_>
{
kumi::for_each( [](auto v, auto p) { store(v, p); }, value, ptrs );
}
template< kumi::product_type T, typename S
, kumi::sized_product_type<T::size()> Ptr
, relative_conditional_expr C
>
EVE_FORCEINLINE void store_(EVE_SUPPORTS(cpu_),
C const &c,
wide<T, S> const &value,
Ptr ptrs) noexcept
{
if constexpr ( C::has_alternative )
{
auto alt = [&]{
if constexpr ( kumi::product_type<typename C::alternative_type> ) return c.alternative;
else return c.alternative.storage();
}();
kumi::for_each( [&](auto v, auto part_alt, auto p) {
auto new_c = c.map_alternative([&](auto) { return part_alt; });
store[new_c](v, p);
}, value.storage(), alt, ptrs);
}
else
{
kumi::for_each( [&](auto v, auto p) { store[c](v, p); }, value.storage(), ptrs );
}
}
// -----------------------------------------------------------------------------------------------
// simd Regular case
template<real_scalar_value T, typename N>
EVE_FORCEINLINE void
store_(EVE_SUPPORTS(cpu_), wide<T, N> value, T *ptr) noexcept
requires std::same_as<abi_t<T, N>, emulated_>
{
apply<N::value>([&](auto... I) { ((*ptr++ = value.get(I)), ...); });
}
template<real_scalar_value T, typename N>
EVE_FORCEINLINE void
store_(EVE_SUPPORTS(cpu_), wide<T, N> value, T *ptr) noexcept
requires std::same_as<abi_t<T, N>, aggregated_>
{
value.storage().apply
( [&]<typename... Sub>(Sub&... v)
{
int k = 0;
((store(v, ptr + k), k += Sub::size()), ...);
}
);
}
// -----------------------------------------------------------------------------------------------
// simd Aligned case
template<real_scalar_value T, typename S, typename Lanes>
EVE_FORCEINLINE void
store_(EVE_SUPPORTS(cpu_), wide<T, S> const &value, aligned_ptr<T, Lanes> ptr) noexcept
requires(S::value <= Lanes::value) && std::same_as<abi_t<T, S>, emulated_>
{
store(value, ptr.get());
}
template<real_scalar_value T, typename S, typename Lanes>
EVE_FORCEINLINE void
store_(EVE_SUPPORTS(cpu_), wide<T, S> const &value, aligned_ptr<T, Lanes> ptr) noexcept
requires(S::value <= Lanes::value) && std::same_as<abi_t<T, S>, aggregated_>
{
auto cast = []<typename Ptr, typename Sub>(Ptr ptr, as<Sub>)
{
return eve::aligned_ptr<T, typename Sub::cardinal_type>{ptr.get()};
};
value.storage().apply
( [&]<typename... Sub>(Sub&... v)
{
int k = 0;
((store(v, cast(ptr, as<Sub>{}) + k), k += Sub::size()), ...);
}
);
}
template<simd_value T, relative_conditional_expr C, simd_compatible_ptr<T> Ptr>
EVE_FORCEINLINE void store_(EVE_SUPPORTS(cpu_),
C const &cond,
T const &value,
Ptr ptr) noexcept
{
if constexpr ( C::is_complete && C::is_inverted ) store(value, ptr);
else if constexpr ( C::has_alternative ) store(replace_ignored(value, cond, cond.alternative), ptr);
else if constexpr ( C::is_complete ) return;
else if constexpr ( logical_simd_value<T> )
{
using mask_type_t = typename element_type_t<T>::mask_type;
if constexpr ( std::is_pointer_v<Ptr> ) store[cond](value.mask(), (mask_type_t*) ptr);
else
{
store[cond](value.mask(), typename Ptr::template rebind<mask_type_t>{(mask_type_t*)ptr.get()});
}
}
else if constexpr ( !std::is_pointer_v<Ptr> ) store[cond](value, ptr.get());
else if constexpr ( has_emulated_abi_v<T> )
{
auto offset = cond.offset( as<T>{} );
auto count = cond.count( as<T>{} );
using e_t = element_type_t<T>;
auto* src = (e_t*)(&value.storage());
std::memcpy((void*)(ptr + offset), (void*)(src + offset), sizeof(e_t) * count);
}
else
{
using e_t = element_type_t<T>;
alignas(sizeof(T)) std::array<e_t, T::size()> storage;
store(value, eve::aligned_ptr<e_t, typename T::cardinal_type>(storage.begin()));
auto offset = cond.offset( as<T>{} );
auto count = cond.count( as<T>{} );
std::memcpy((void*)(ptr + offset), (void*)(storage.begin() + offset), sizeof(e_t) * count);
}
}
template<real_scalar_value T, typename S>
EVE_FORCEINLINE void store_(EVE_SUPPORTS(cpu_),
logical<wide<T, S>> const &value,
logical<T>* ptr) noexcept
{
store(value.mask(), (typename logical<T>::mask_type*) ptr);
}
template<real_scalar_value T, typename S,typename Lanes>
EVE_FORCEINLINE void store_(EVE_SUPPORTS(cpu_),
logical<wide<T, S>> const &value,
aligned_ptr<logical<T>, Lanes> ptr) noexcept
requires (
requires {store(value.mask(), aligned_ptr<typename logical<T>::mask_type, Lanes>{}); } )
{
using mask_type_t = typename logical<T>::mask_type;
store(value.mask(), aligned_ptr<mask_type_t, Lanes>{(mask_type_t*)ptr.get()});
}
}
| 36.678571 | 118 | 0.540409 | the-moisrex |
eee80134cd760b89e821f29a1ee0ce616b0f6efa | 17,039 | cpp | C++ | src/table_functions.cpp | ThomasWitte/MiniLua | 033a357c602d2d2ebeca304d1a3660ad1e5d7298 | [
"MIT"
] | 2 | 2020-07-08T11:51:02.000Z | 2021-02-22T23:28:37.000Z | src/table_functions.cpp | ThomasWitte/MiniLua | 033a357c602d2d2ebeca304d1a3660ad1e5d7298 | [
"MIT"
] | 142 | 2020-08-31T13:21:17.000Z | 2021-09-15T18:46:10.000Z | src/table_functions.cpp | ThomasWitte/MiniLua | 033a357c602d2d2ebeca304d1a3660ad1e5d7298 | [
"MIT"
] | 3 | 2020-08-17T13:42:39.000Z | 2020-08-31T11:38:05.000Z | #include "MiniLua/table_functions.hpp"
#include "MiniLua/utils.hpp"
#include "MiniLua/values.hpp"
#include <algorithm>
#include <cmath>
#include <future>
#include <iostream>
#include <stdexcept>
#include <string>
#include <utility>
#include <variant>
#include <vector>
namespace minilua {
auto static try_value_is_int(Value s, const std::string& method_name, int arg_index) -> int {
try {
if (s.is_number()) {
return std::get<Number>(s).try_as_int();
}
} catch (const std::runtime_error& e) {
throw std::runtime_error(
"bad argument #" + std::to_string(arg_index) + " to '" + method_name +
"' (number expected, got " + s.type() + ")");
}
auto tmp = Number(1);
try {
if (s.is_string()) {
Value v = s.to_number();
if (v == Nil()) {
throw std::runtime_error("");
}
tmp = std::get<Number>(v);
} else if (!s.is_number()) {
throw std::runtime_error("");
}
} catch (const std::runtime_error& e) {
throw std::runtime_error(
"bad argument #" + std::to_string(arg_index) + " to '" + method_name +
"' (number expected, got " + s.type() + ")");
}
try {
return tmp.try_as_int();
} catch (const std::runtime_error& e) {
throw std::runtime_error(
"bad argument #" + std::to_string(arg_index) + " to '" + method_name +
"' (number has no integer representation)");
}
}
auto create_table_table(MemoryAllocator* allocator) -> Table {
Table table(allocator);
table.set("concat", table::concat);
table.set("insert", table::insert);
table.set("move", table::insert);
table.set("pack", table::pack);
table.set("remove", table::remove);
table.set("sort", table::sort);
table.set("unpack", table::unpack);
return table;
}
namespace table {
auto concat(const CallContext& ctx) -> Value {
// Didn't add an origin because i have no idea how i should reverse this because i would need
// the seperator to split it back up
std::string result;
auto list = ctx.arguments().get(0);
auto sep = ctx.arguments().get(1);
auto i = ctx.arguments().get(2);
auto j = ctx.arguments().get(3);
return std::visit(
overloaded{
[&result](const Table& list, Nil /*unused*/, Nil /*unused*/, Nil /*unused*/) -> Value {
for (int m = 1; m <= list.border(); m++) {
Value v = list.get(m);
if (!v.is_number() && !v.is_string()) {
throw std::runtime_error(
"Invalid value (" + v.type() + ") in table for 'concat'!");
}
String vs = std::get<String>(v.to_string());
result += vs.value;
}
return Value(result);
},
[&result,
&sep](const Table& list, auto /*sep*/, Nil /*unused*/, Nil /*unused*/) -> Value {
if (!sep.is_number() && !sep.is_string()) {
throw std::runtime_error(
"bad argument #2 to 'concat' (string expected, got " + sep.type() + ")");
}
String s = std::get<String>(sep.to_string());
for (int m = 1; m <= list.border(); m++) {
Value v = list.get(m);
if (!v.is_number() && !v.is_string()) {
throw std::runtime_error(
"Invalid value (" + v.type() + ") in table for 'concat'!");
}
String vs = std::get<String>(v.to_string());
result += vs.value;
if (m != list.border()) {
result += s.value;
}
}
return Value(result);
},
[&result, &sep,
&i](const Table& list, auto /*sep*/, auto /*i*/, Nil /*unused*/) -> Value {
if (!sep.is_number() && !sep.is_string()) {
throw std::runtime_error(
"bad argument #2 to 'concat' (string expected, got " + sep.type() + ")");
}
String s = std::get<String>(sep.to_string());
int m = try_value_is_int(std::move(i), "concat", 3);
for (; m <= list.border(); m++) {
Value v;
if (list.has(m)) {
v = list.get(m);
} else {
throw std::runtime_error(
"invalid value (nil) at index " + std::to_string(m) + " for 'concat'");
}
if (!v.is_number() && !v.is_string()) {
throw std::runtime_error(
"Invalid value (" + v.type() + ") in table for 'concat'!");
}
String vs = std::get<String>(v.to_string());
result += vs.value;
if (m != list.border()) {
result += s.value;
}
}
return Value(result);
},
[&result, &sep, &i,
&j](const Table& list, auto /*sep*/, auto /*i*/, auto /*j*/) -> Value {
if (!sep.is_number() && !sep.is_string()) {
throw std::runtime_error(
"bad argument #2 to 'concat' (string expected, got " + sep.type() + ")");
}
String s = std::get<String>(sep.to_string());
int m = try_value_is_int(std::move(i), "concat", 3);
int j_int = try_value_is_int(std::move(j), "concat", 4);
;
for (; m <= j_int; m++) {
Value v;
if (list.has(m)) {
v = list.get(m);
} else {
throw std::runtime_error(
"invalid value (nil) at index " + std::to_string(m) + " for 'concat'");
}
if (!v.is_number() && !v.is_string()) {
throw std::runtime_error(
"Invalid value (" + v.type() + ") in table for 'concat'!");
}
String vs = std::get<String>(v.to_string());
result += vs.value;
if (m != j_int) {
result += s.value;
}
}
return Value(result);
},
[](auto list, auto /*unused*/, auto /*unused*/, auto /*unused*/) -> Value {
throw std::runtime_error(
"bad argument #1 to 'concat' (table expected, got " + std::string(list.TYPE) +
")");
}},
list.raw(), sep.raw(), i.raw(), j.raw());
}
void insert(const CallContext& ctx) {
auto list = ctx.arguments().get(0);
auto pos = ctx.arguments().get(1);
auto value = ctx.arguments().get(2);
// Casulty because we return nil if no argument is given, but nil could be inserted. This edge
// case throws an error in our program, in lua the insertion works as intended I don't have an
// idea how to do that besides this way.
if (ctx.arguments().size() < 3) {
throw std::runtime_error("wrong number of arguments to 'insert'");
}
std::visit(
overloaded{
[&value](Table& table, Nil /*unused*/) {
Number pos = table.border() + 1;
table.set(pos, value);
},
[&pos, &value](Table& table, auto /*pos*/) {
int p = try_value_is_int(pos, "insert", 2);
if (p < 1 || p > table.border()) {
throw std::runtime_error(
"bad argument #2 to 'insert' (position out of bounds)");
} else {
// move every element one to the right so make space for the new element that is
// inserted if pos is already occupied
for (int i = table.border(); i >= p; i--) {
table.set(i + 1, table.get(i));
}
}
table.set(p, value);
},
[](auto table, auto /*unused*/) {
throw std::runtime_error(
"bad argument #1 to 'insert' (table expected, got " + std::string(table.TYPE) +
")");
}},
list.raw(), pos.raw());
}
auto move(const CallContext& ctx) -> Value {
// No origin needed because a2 is already given as an existing value
auto a1 = ctx.arguments().get(0);
auto f = ctx.arguments().get(1);
auto e = ctx.arguments().get(2);
auto t = ctx.arguments().get(3);
auto a2 = ctx.arguments().get(4);
return std::visit(
overloaded{
[&f, &e, &t](Table a1, Nil /*unused*/) -> Value {
int fi = try_value_is_int(f, "move", 2);
int ei = try_value_is_int(e, "move", 3);
int ti = try_value_is_int(t, "move", 4);
for (; fi <= ei; fi++) {
a1.set(ti, a1.get(fi));
ti++;
}
return a1;
},
[&f, &e, &t](const Table& a1, Table a2) -> Value {
int fi = try_value_is_int(f, "move", 2);
int ei = try_value_is_int(e, "move", 3);
int ti = try_value_is_int(t, "move", 4);
for (; fi <= ei; fi++) {
a2.set(ti, a1.get(fi));
ti++;
}
return a2;
},
[](const Table& /*unused*/, auto a2) -> Value {
throw std::runtime_error(
"bad argument #5 to 'move' (table expected, got " + std::string(a2.TYPE) + ")");
},
[](auto a1, auto /*unused*/) -> Value {
throw std::runtime_error(
"bad argument #1 to 'move' (table expected, got " + std::string(a1.TYPE) + ")");
}},
a1.raw(), a2.raw());
}
auto pack(const CallContext& ctx) -> Value {
Origin origin = Origin(MultipleArgsOrigin{
.values = std::make_shared<Vallist>(ctx.arguments()),
.location = ctx.call_location(),
.reverse = [](const Value& new_value,
const Vallist& args) -> std::optional<SourceChangeTree> {
Table t = std::get<Table>(new_value);
SourceChangeCombination trees;
auto it = args.begin();
for (const auto& [key, value] : t) {
if (key.type() != Number::TYPE || std::get<Number>(key).try_as_int() < 1 ||
std::get<Number>(key).try_as_int() > t.border() ||
std::get<Number>(key).try_as_int() > args.size()) {
break;
}
auto sct = *it->force(value);
trees.add(sct);
it++;
}
return SourceChangeTree(trees);
}});
Table t = Table();
int i = 1;
for (const auto& a : ctx.arguments()) {
t.set(i++, a);
}
return Value(t).with_origin(origin);
}
auto remove(const CallContext& ctx) -> Value {
// Doesn't need an origin because the value that is returned already should has one since it
// isn't generated new
auto list = ctx.arguments().get(0);
auto pos = ctx.arguments().get(1);
return std::visit(
overloaded{
[](Table list, Nil /*unused*/) -> Value {
auto tmp = list.get(list.border());
list.remove(list.border());
return tmp;
},
[&pos](Table list, auto /*pos*/) -> Value {
int posi = try_value_is_int(pos, "remove", 2);
if (posi > list.border() + 1 || (posi < 1 && list.border() != 0)) {
throw std::runtime_error(
"bad argument #2 to 'remove' (position out of bounds)");
}
auto tmp = list.get(posi);
if (posi == list.border() + 1) {
list.remove(posi);
return tmp;
}
for (int i = posi + 1; i <= list.border(); i++) {
list.set(posi, list.get(i));
posi++;
}
list.remove(list.border());
return tmp;
},
[](auto list, auto /*unused*/) -> Value {
throw std::runtime_error(
"bad argument #1 to 'remove' (table expected, got " + std::string(list.TYPE) +
")");
}},
list.raw(), pos.raw());
}
void sort(const CallContext& ctx) {
auto list = ctx.arguments().get(0);
auto comp = ctx.arguments().get(1);
std::visit(
overloaded{
[](Table list, Nil /*unused*/) {
std::vector<Value> content;
for (int i = 1; i <= list.border(); i++) {
content.push_back(list.get(i));
}
std::sort(content.begin(), content.end(), [](const Value& a, const Value& b) {
return std::get<Bool>(a.less_than(b)).value;
});
for (int i = 1; i <= list.border(); i++) {
list.set(i, content.at(i - 1));
}
},
[&ctx](Table list, const Function& comp) {
std::vector<Value> content;
for (int i = 1; i <= list.border(); i++) {
content.push_back(list.get(i));
}
std::sort(
content.begin(), content.end(),
[&ctx, &comp](const Value& a, const Value& b) -> bool {
auto c = ctx.make_new(Vallist{a, b});
auto erg = comp.call(c).values().get(0);
// More arguments than 2 are possible, but they are always Nil.
// 2 arguments must be there always since we must compare two values
if (ctx.arguments().size() >= 2 && erg.type() == "boolean") {
return std::get<Bool>(erg).value;
} else {
throw std::runtime_error("invalid order function for sorting");
}
});
for (int i = 1; i <= list.border(); i++) {
list.set(i, content.at(i - 1));
}
},
[](const Table& /*unused*/, auto a) {
throw std::runtime_error(
"bad argument #2 to 'sort' (function expected, got " + std::string(a.TYPE) +
")");
},
[](auto list, auto /*unused*/) {
throw std::runtime_error(
"bad argument #1 to 'sort' (table expected, got " + std::string(list.TYPE) +
")");
}},
list.raw(), comp.raw());
}
auto unpack(const CallContext& ctx) -> Vallist {
// It only returns the Values of the Table, so no new values are generated and every value in
// the vallist should keep its origin i think
std::vector<Value> vector;
auto list = ctx.arguments().get(0);
auto i = ctx.arguments().get(1);
auto j = ctx.arguments().get(2);
return std::visit(
overloaded{
[&vector](const Table& list, Nil /*unused*/, Nil /*unused*/) -> Vallist {
for (int i = 1; i <= list.border(); i++) {
auto v = list.get(i);
vector.push_back(v);
}
return Vallist(vector);
},
[&vector, &i](const Table& list, auto /*i*/, Nil /*unused*/) {
int i_int = try_value_is_int(i, "unpack", 2);
for (; i_int <= list.border(); i_int++) {
vector.push_back(list.get(i_int));
}
return Vallist(vector);
},
[&vector, &i, &j](const Table& list, auto /*i*/, auto /*j*/) {
int i_int = try_value_is_int(i, "unpack", 2);
int j_int = try_value_is_int(j, "unpack", 3);
for (; i_int <= j_int; i_int++) {
vector.push_back(list.get(i_int));
}
return Vallist(vector);
},
[](auto list, auto /*unused*/, auto /*unused*/) -> Vallist {
throw std::runtime_error(
"bad argument #1 for 'unpack' (table expected, got " + std::string(list.TYPE) +
")");
}},
list.raw(), i.raw(), j.raw());
}
} // end namespace table
} // end namespace minilua
| 39.810748 | 100 | 0.443453 | ThomasWitte |
eeea3c01c736a4561216e651168c651d59733849 | 404 | cpp | C++ | Tokenizer.cpp | rohan-0100010110010100/FrontEnd-ComplerDesign-Lab | dde0c8609982bf6aa209af600af781984fc0b621 | [
"MIT"
] | null | null | null | Tokenizer.cpp | rohan-0100010110010100/FrontEnd-ComplerDesign-Lab | dde0c8609982bf6aa209af600af781984fc0b621 | [
"MIT"
] | null | null | null | Tokenizer.cpp | rohan-0100010110010100/FrontEnd-ComplerDesign-Lab | dde0c8609982bf6aa209af600af781984fc0b621 | [
"MIT"
] | 2 | 2018-10-11T14:14:55.000Z | 2020-02-27T10:28:59.000Z | #include <string.h>
#include <stdio.h>
#include <conio.h>
int main()
{
char str[80];
const char s[2] = "-";
char *token;
clrscr();
printf("Enter String for tokenization: ");
gets(str);
token = strtok(str, s);
while( token != NULL )
{
printf( " %s\n", token );
token = strtok(NULL, s);
}
getch();
return(0);
}
| 15.538462 | 48 | 0.472772 | rohan-0100010110010100 |
eeec0d2d9fb95d6d0ebac8ebbbf46089ad41685d | 5,392 | cpp | C++ | lib/seqan3/test/unit/search/search_scheme_test.cpp | SGSSGene/seqan3_demo | 5602af4ba437c973d4f84eb3ccb58330044978e2 | [
"BSD-3-Clause"
] | null | null | null | lib/seqan3/test/unit/search/search_scheme_test.cpp | SGSSGene/seqan3_demo | 5602af4ba437c973d4f84eb3ccb58330044978e2 | [
"BSD-3-Clause"
] | null | null | null | lib/seqan3/test/unit/search/search_scheme_test.cpp | SGSSGene/seqan3_demo | 5602af4ba437c973d4f84eb3ccb58330044978e2 | [
"BSD-3-Clause"
] | null | null | null | // -----------------------------------------------------------------------------------------------------
// Copyright (c) 2006-2020, Knut Reinert & Freie Universität Berlin
// Copyright (c) 2016-2020, Knut Reinert & MPI für molekulare Genetik
// This file may be used, modified and/or redistributed under the terms of the 3-clause BSD-License
// shipped with this file and also available at: https://github.com/seqan/seqan3/blob/master/LICENSE.md
// -----------------------------------------------------------------------------------------------------
#include <algorithm>
#include <type_traits>
#include "helper_search_scheme.hpp"
#include <seqan3/search/algorithm/detail/search_scheme_algorithm.hpp>
#include <gtest/gtest.h>
template <uint8_t min_error, uint8_t max_error, bool precomputed_scheme>
void error_distributions(auto & expected, auto & actual)
{
if constexpr (precomputed_scheme)
{
auto const & oss{seqan3::detail::optimum_search_scheme<min_error, max_error>};
seqan3::search_scheme_error_distribution(actual, oss);
seqan3::search_scheme_error_distribution(expected, seqan3::trivial_search_scheme(min_error,
max_error,
oss.front().blocks()));
}
else
{
auto const & ss{seqan3::detail::compute_ss(min_error, max_error)};
seqan3::search_scheme_error_distribution(actual, ss);
seqan3::search_scheme_error_distribution(expected, seqan3::trivial_search_scheme(min_error,
max_error,
ss.front().blocks()));
}
std::sort(expected.begin(), expected.end());
std::sort(actual.begin(), actual.end());
}
TEST(search_scheme_test, error_distribution_coverage_optimum_search_schemes)
{
std::vector<std::vector<uint8_t> > expected, actual;
error_distributions<0, 0, true>(expected, actual);
EXPECT_EQ(actual, expected);
error_distributions<0, 1, true>(expected, actual);
EXPECT_EQ(actual, expected);
error_distributions<1, 1, true>(expected, actual);
EXPECT_EQ(actual, expected);
error_distributions<0, 2, true>(expected, actual);
EXPECT_EQ(actual, expected);
error_distributions<1, 2, true>(expected, actual);
EXPECT_EQ(actual, expected);
error_distributions<2, 2, true>(expected, actual);
EXPECT_EQ(actual, expected);
error_distributions<0, 3, true>(expected, actual);
EXPECT_EQ(actual, expected);
error_distributions<1, 3, true>(expected, actual);
EXPECT_EQ(actual, expected);
error_distributions<2, 3, true>(expected, actual);
EXPECT_EQ(actual, expected);
error_distributions<3, 3, true>(expected, actual);
EXPECT_EQ(actual, expected);
}
TEST(search_scheme_test, error_distribution_coverage_computed_search_schemes)
{
std::vector<std::vector<uint8_t> > expected, actual;
error_distributions<0, 0, false>(expected, actual);
EXPECT_EQ(actual, expected);
error_distributions<0, 1, false>(expected, actual);
EXPECT_EQ(actual, expected);
error_distributions<1, 1, false>(expected, actual);
EXPECT_EQ(actual, expected);
error_distributions<0, 2, false>(expected, actual);
EXPECT_EQ(actual, expected);
error_distributions<1, 2, false>(expected, actual);
EXPECT_EQ(actual, expected);
error_distributions<2, 2, false>(expected, actual);
EXPECT_EQ(actual, expected);
error_distributions<0, 3, false>(expected, actual);
EXPECT_EQ(actual, expected);
error_distributions<1, 3, false>(expected, actual);
EXPECT_EQ(actual, expected);
error_distributions<2, 3, false>(expected, actual);
EXPECT_EQ(actual, expected);
error_distributions<3, 3, false>(expected, actual);
EXPECT_EQ(actual, expected);
error_distributions<3, 5, false>(expected, actual);
EXPECT_EQ(actual, expected);
error_distributions<0, 6, false>(expected, actual);
EXPECT_EQ(actual, expected);
error_distributions<7, 7, false>(expected, actual);
EXPECT_EQ(actual, expected);
}
template <uint8_t min_error, uint8_t max_error, bool precomputed_scheme>
bool check_disjoint_search_scheme()
{
std::vector<std::vector<uint8_t> > error_distributions;
auto const & oss{seqan3::detail::optimum_search_scheme<min_error, max_error>};
seqan3::search_scheme_error_distribution(error_distributions, oss);
uint64_t size = error_distributions.size();
std::sort(error_distributions.begin(), error_distributions.end());
error_distributions.erase(std::unique(error_distributions.begin(),
error_distributions.end()),
error_distributions.end());
return size == error_distributions.size();
}
TEST(search_scheme_test, error_distribution_disjoint_optimum_search_schemes)
{
bool ret;
ret = check_disjoint_search_scheme<0, 0, false>();
EXPECT_TRUE(ret);
ret = check_disjoint_search_scheme<0, 1, false>();
EXPECT_TRUE(ret);
ret = check_disjoint_search_scheme<0, 2, false>();
EXPECT_TRUE(ret);
ret = check_disjoint_search_scheme<0, 3, false>();
EXPECT_TRUE(ret);
}
| 37.186207 | 112 | 0.639837 | SGSSGene |
eeecc946554d44973d88523a819de74c7bfe8446 | 9,374 | cpp | C++ | server/worker.cpp | pmakaruk/-Network-File-System | 8fddd7d9c5d850f1e3b621481f21fe378b1e8a21 | [
"MIT"
] | null | null | null | server/worker.cpp | pmakaruk/-Network-File-System | 8fddd7d9c5d850f1e3b621481f21fe378b1e8a21 | [
"MIT"
] | null | null | null | server/worker.cpp | pmakaruk/-Network-File-System | 8fddd7d9c5d850f1e3b621481f21fe378b1e8a21 | [
"MIT"
] | null | null | null | #include <fcntl.h>
#include <iostream>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <dirent.h>
#include <string.h>
#include "../libraries/core/messages.hpp"
#include "../libraries/core/serializers.hpp"
#include "../tests/utils.hpp"
//#include "worker.h"
#include "worker.hpp"
#include "handler.h"
Worker::Worker(int socket_fd) {
this->socket_fd = socket_fd;
}
std::vector<u_int8_t> open_handler(std::vector<u_int8_t> byte_request) {
std::cout << "OPEN" << std::endl;
OpenRequest request = DeserializeToOpenRequest(byte_request);
std::cout << "Request:" << std::endl;
std::cout << " path: " << request.path << std::endl;
std::cout << " oflag: " << request.oflag << std::endl;
std::cout << " mode: " << request.mode << std::endl;
int result = open(request.path.c_str(), request.oflag, request.mode);
OpenResponse response = {result, errno};
std::cout << "Response:" << std::endl;
std::cout << " fd: " << response.result << std::endl;
std::cout << " error: " << response.error << std::endl;
std::cout << std::endl;
std::vector<u_int8_t> byte_response = SerializeOpenResponse(response);
return byte_response;
}
std::vector<u_int8_t> read_handler(std::vector<u_int8_t> byte_request) {
std::cout << "READ" << std::endl;
ReadRequest request = DeserializeToReadRequest(byte_request);
std::cout << "Request:" << std::endl;
std::cout << " fd: " << request.fd << std::endl;
std::cout << " count: " << request.count << std::endl;
std::vector<u_int8_t> buf = std::vector<u_int8_t>(request.count);
int result = read(request.fd, buf.data(), request.count);
buf.resize(result);
ReadResponse response = {result, buf, errno};
std::cout << "Response:" << std::endl;
std::cout << " result: " << response.result << std::endl;
std::cout << " error: " << response.error << std::endl;
std::cout << std::endl;
std::vector<u_int8_t> byte_response = SerializeReadResponse(response);
return byte_response;
}
std::vector<u_int8_t> write_handler(std::vector<u_int8_t> byte_request) {
std::cout << "WRITE" << std::endl;
WriteRequest request = DeserializeToWriteRequest(byte_request);
std::cout << "Request:" << std::endl;
std::cout << " fd: " << request.fd << std::endl;
std::cout << " buf_size: " << request.buf.size() << std::endl;
int result = write(request.fd, request.buf.data(), request.buf.size());
WriteResponse response = {result, errno};
std::cout << "Response:" << std::endl;
std::cout << " result: " << response.result << std::endl;
std::cout << " error: " << response.error << std::endl;
std::cout << std::endl;
std::vector<u_int8_t> byte_response = SerializeWriteResponse(response);
return byte_response;
};
std::vector<u_int8_t> lseek_handler(std::vector<u_int8_t> byte_request) {
std::cout << "LSEEK" << std::endl;
LseekRequest request = DeserializeToLseekRequest(byte_request);
std::cout << "Request:" << std::endl;
std::cout << " fd: " << request.fd << std::endl;
std::cout << " offset: " << request.offset << std::endl;
std::cout << " whence: " << request.whence << std::endl;
off_t result = lseek(request.fd, request.offset, request.whence);
LseekResponse response = {result, errno};
std::cout << "Response:" << std::endl;
std::cout << " result: " << response.result << std::endl;
std::cout << " error: " << response.error << std::endl;
std::cout << std::endl;
std::vector<u_int8_t> byte_response = SerializeLseekResponse(response);
return byte_response;
};
std::vector<u_int8_t> close_handler(std::vector<u_int8_t> byte_request) {
std::cout << "CLOSE" << std::endl;
CloseRequest request = DeserializeToCloseRequest(byte_request);
std::cout << "Request:" << std::endl;
std::cout << " fd: " << request.fd << std::endl;
int result = close(request.fd);
CloseResponse response = {result, errno};
std::cout << "Response:" << std::endl;
std::cout << " result: " << response.result << std::endl;
std::cout << " error: " << response.error << std::endl;
std::cout << std::endl;
std::vector<u_int8_t> byte_response = SerializeCloseResponse(response);
return byte_response;
};
std::vector<u_int8_t> unlink_handler(std::vector<u_int8_t> byte_request) {
std::cout << "UNLINK" << std::endl;
UnlinkRequest request = DeserializeToUnlinkRequest(byte_request);
std::cout << "Request:" << std::endl;
std::cout << " pathname: " << request.pathname << std::endl;
int result = unlink(request.pathname.c_str());
UnlinkResponse response = {result, errno};
std::cout << "Response:" << std::endl;
std::cout << " result: " << response.result << std::endl;
std::cout << " error: " << response.error << std::endl;
std::cout << std::endl;
std::vector<u_int8_t> byte_response = SerializeUnlinkResponse(response);
return byte_response;
};
//
std::vector<u_int8_t> opendir_handler(std::vector<u_int8_t> byte_request) {
std::cout << "OPENDIR" << std::endl;
OpendirRequest request = DeserializeToOpendirRequest(byte_request);
std::cout << "Request:" << std::endl;
std::cout << " name: " << request.name << std::endl;
int result = -1;
DIR* dirstream = opendir(request.name.c_str());
if (dirstream != nullptr)
result = dirfd(dirstream);
OpendirResponse response = {result, errno};
std::cout << "Response:" << std::endl;
std::cout << " result: " << response.result << std::endl;
std::cout << " error: " << response.error << std::endl;
std::cout << std::endl;
std::vector<u_int8_t> byte_response = SerializeOpendirResponse(response);
return byte_response;
};
std::vector<u_int8_t> readdir_handler(std::vector<u_int8_t> byte_request) {
std::cout << "READDIR" << std::endl;
ReaddirRequest request = DeserializeToReaddirRequest(byte_request);
std::cout << "Request:" << std::endl;
std::cout << " dirfd: " << request.dirfd << std::endl;
int isDirentNull = 0;
DIR *dirp = fdopendir(request.dirfd);
dirent result;
if (dirp == nullptr)
isDirentNull = 1;
else
{
dirent* resultPtr = readdir(dirp);
if (resultPtr == nullptr)
isDirentNull = 1;
else
memcpy((void *)&result,resultPtr,sizeof(result));
}
ReaddirResponse response = {isDirentNull, result, errno};
std::cout << "Response:" << std::endl;
std::cout << " result: " << response.result.d_name << std::endl;
std::cout << " error: " << response.error << std::endl;
std::cout << std::endl;
std::vector<u_int8_t> byte_response = SerializeReaddirResponse(response);
return byte_response;
};
std::vector<u_int8_t> closedir_handler(std::vector<u_int8_t> byte_request) {
std::cout << "CLOSEDIR" << std::endl;
ClosedirRequest request = DeserializeToClosedirRequest(byte_request);
std::cout << "Request:" << std::endl;
std::cout << " dirfd: " << request.dirfd << std::endl;
int result = -1;
DIR *dirp = fdopendir(request.dirfd);
if (dirp != nullptr)
result = closedir(dirp);
ClosedirResponse response = {result, errno};
std::cout << "Response:" << std::endl;
std::cout << " result: " << response.result << std::endl;
std::cout << " error: " << response.error << std::endl;
std::cout << std::endl;
std::vector<u_int8_t> byte_response = SerializeClosedirResponse(response);
return byte_response;
};
std::vector<u_int8_t> make_response(std::vector<u_int8_t> byte_request) {
MessageParser parser = MessageParser(byte_request);
switch (parser.readMessageType()) {
case MessageType::OPEN_REQUEST:
return open_handler(byte_request);
case MessageType::READ_REQUEST:
return read_handler(byte_request);
case MessageType::WRITE_REQUEST:
return write_handler(byte_request);
case MessageType::LSEEK_REQUEST:
return lseek_handler(byte_request);
case MessageType::CLOSE_REQUEST:
return close_handler(byte_request);
case MessageType::UNLINK_REQUEST:
return unlink_handler(byte_request);
case MessageType::OPENDIR_REQUEST:
return opendir_handler(byte_request);
case MessageType::READDIR_REQUEST:
return readdir_handler(byte_request);
case MessageType::CLOSEDIR_REQUEST:
return closedir_handler(byte_request);
default:
return std::vector<u_int8_t>{0, 0, 0, 0, 0};
}
}
void Worker::run() {
if(!authenticateUser()) {
close(socket_fd);
return;
}
std::vector<u_int8_t> byte_request;
std::vector<u_int8_t> byte_response;
while(true){
try{
byte_request = receiveMessage(socket_fd);
byte_response = handler.make_response(byte_request);
sendMessage(socket_fd, byte_response);
}
catch (std::ios_base::failure&) {
std::cout << "Ending connection with client" << std::endl;
close(socket_fd);
break;
}
}
}
std::thread Worker::spawn() {
return std::thread( [this] { this->run(); } );
}
bool Worker::authenticateUser() {
std::vector<u_int8_t> byte_request = receiveMessage(socket_fd);
MessageParser parser = MessageParser(byte_request);
if(parser.readMessageType() != MessageType::AUTHENTICATE_REQUEST)
return false;
AuthenticateResponse authenticateResponse = handler.authenticate_handler(byte_request);
bool isAuthenticated = authenticateResponse.result == 0;
sendMessage(socket_fd, SerializeAuthenticateResponse(authenticateResponse));
return isAuthenticated;
}
| 33.719424 | 91 | 0.663324 | pmakaruk |
eeed81b675f735ef27211f8b2846f29330a02e90 | 790 | hpp | C++ | engine/engine/gems/image/cuda/yuv2rgb.cu.hpp | ddr95070/RMIsaac | ee3918f685f0a88563248ddea11d089581077973 | [
"FSFAP"
] | 1 | 2020-04-14T13:55:16.000Z | 2020-04-14T13:55:16.000Z | engine/engine/gems/image/cuda/yuv2rgb.cu.hpp | ddr95070/RMIsaac | ee3918f685f0a88563248ddea11d089581077973 | [
"FSFAP"
] | 4 | 2020-09-25T22:34:29.000Z | 2022-02-09T23:45:12.000Z | engine/engine/gems/image/cuda/yuv2rgb.cu.hpp | ddr95070/RMIsaac | ee3918f685f0a88563248ddea11d089581077973 | [
"FSFAP"
] | 1 | 2022-01-28T16:37:51.000Z | 2022-01-28T16:37:51.000Z | /*
Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
NVIDIA CORPORATION and its licensors retain all intellectual property
and proprietary rights in and to this software, related documentation
and any modifications thereto. Any use, reproduction, disclosure or
distribution of this software and related documentation without an express
license agreement from NVIDIA CORPORATION is strictly prohibited.
*/
#include <cuda_runtime.h>
namespace isaac {
// Converts a YUV420 (encoded as NV21) image bound to texture channels to RGB
void ConvertNv21ToRgb(cudaTextureObject_t y_channel, cudaTextureObject_t uv_channel,
unsigned char* rgb_output, unsigned int width, unsigned int height,
unsigned int output_pitch);
} // namespace isaac
| 37.619048 | 89 | 0.770886 | ddr95070 |
eef3a5ff3595dbb69f895dd41ddbce2c6e07bfb1 | 627 | hpp | C++ | RIFF/RIFFBase.hpp | SegaraRai/MeiToAvi | ce5f57d79808e5b8f397d32d3f37c79b15ff4909 | [
"MIT"
] | 6 | 2020-02-04T09:24:29.000Z | 2022-02-26T18:03:34.000Z | RIFF/RIFFBase.hpp | SegaraRai/MeiToAvi | ce5f57d79808e5b8f397d32d3f37c79b15ff4909 | [
"MIT"
] | null | null | null | RIFF/RIFFBase.hpp | SegaraRai/MeiToAvi | ce5f57d79808e5b8f397d32d3f37c79b15ff4909 | [
"MIT"
] | null | null | null | #ifndef ML_RIFFBASE_HPP
#define ML_RIFFBASE_HPP
#include <cstddef>
#include <cstdint>
#include <ios>
#include <memory>
#include "../Source/SourceBase.hpp"
class RIFFDirBase;
class RIFFBase {
public:
enum class Type {
Chunk,
List,
Root,
};
protected:
RIFFDirBase* parent;
public:
RIFFBase();
virtual ~RIFFBase() = default;
virtual Type GetType() const = 0;
virtual std::streamsize GetOffset() const;
virtual std::streamsize GetSize() const = 0;
virtual std::shared_ptr<SourceBase> GetSource() = 0;
virtual void SetParent(RIFFDirBase* parent);
virtual void CreateSource();
};
#endif
| 15.292683 | 54 | 0.698565 | SegaraRai |
eefa8465c576ba062243ea860dd9d25f8ab80104 | 8,617 | cc | C++ | tensorflow/compiler/plugin/poplar/driver/passes/io_tiles_placer.cc | chenzhengda/tensorflow | 8debb698097670458b5f21d728bc6f734a7b5a53 | [
"Apache-2.0"
] | 74 | 2020-07-06T17:11:39.000Z | 2022-01-28T06:31:28.000Z | tensorflow/compiler/plugin/poplar/driver/passes/io_tiles_placer.cc | chenzhengda/tensorflow | 8debb698097670458b5f21d728bc6f734a7b5a53 | [
"Apache-2.0"
] | 9 | 2020-10-13T23:25:29.000Z | 2022-02-10T06:54:48.000Z | tensorflow/compiler/plugin/poplar/driver/passes/io_tiles_placer.cc | chenzhengda/tensorflow | 8debb698097670458b5f21d728bc6f734a7b5a53 | [
"Apache-2.0"
] | 12 | 2020-07-08T07:27:17.000Z | 2021-12-27T08:54:27.000Z | /* Copyright 2020 The TensorFlow 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 "tensorflow/compiler/plugin/poplar/driver/passes/io_tiles_placer.h"
#include <algorithm>
#include <map>
#include <queue>
#include <utility>
#include <vector>
#include "tensorflow/compiler/plugin/poplar/driver/tools/custom_ops/remote_parameter.h"
#include "tensorflow/compiler/plugin/poplar/driver/tools/matcher_predicates.h"
#include "tensorflow/compiler/plugin/poplar/driver/tools/util.h"
#include "tensorflow/compiler/xla/service/call_graph.h"
#include "tensorflow/compiler/xla/service/hlo_casting_utils.h"
#include "tensorflow/compiler/xla/service/hlo_module.h"
#include "tensorflow/compiler/xla/service/hlo_value.h"
#include "tensorflow/compiler/xla/shape_util.h"
#include "tensorflow/compiler/xla/status_macros.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/core/status.h"
namespace xla {
namespace poplarplugin {
Status SetIoTileset(HloInstruction* inst) {
TF_ASSIGN_OR_RETURN(auto backend_config,
inst->backend_config<PoplarBackendConfig>());
backend_config.set_tileset(TILESET_IO_TILES);
return inst->set_backend_config(backend_config);
}
Status AssignToIoTilesAndPropagateToGteUsers(HloInstruction* inst) {
VLOG(3) << "Placing on IO tiles: " << inst->ToShortString();
TF_RETURN_IF_ERROR(SetIoTileset(inst));
for (auto* gte : inst->users()) {
if (gte->opcode() == HloOpcode::kGetTupleElement) {
TF_RETURN_IF_ERROR(AssignToIoTilesAndPropagateToGteUsers(gte));
}
}
return Status::OK();
}
bool IsInSerialPipeline(const HloInstruction* inst,
const CallGraph& call_graph) {
const auto callers = call_graph.GetNode(inst->parent()).caller_callsites();
return callers.size() == 1 && IsPipelineOp(callers[0].instruction()) &&
IsBatchSerializedPipelineOp(callers[0].instruction());
}
static int64 GetMaxAvailableIoBytes(
const int64 num_io_tiles, const int64 bytes_per_io_tile,
const double available_io_tile_memory_proportion) {
return static_cast<int64>(num_io_tiles * bytes_per_io_tile *
available_io_tile_memory_proportion);
}
static int64 GetInstructionBufferSize(const HloInstruction* inst) {
const auto& shape = inst->shape();
// The host exchange instructions are either 1 to 1 or 1 to token so
// only need to look at either result of operand
if (shape.IsToken()) {
// if token sum up size of all operands
return absl::c_accumulate(inst->operands(), static_cast<int64>(0),
[](int64 sum, const HloInstruction* i) {
return sum + GetInstructionBufferSize(i);
});
}
return GetByteSizeOfTotalShape(shape);
}
int64 GetMaxLiveBytes(const HloInstructionSequence& potential_io_tile_insts) {
// Looks like the Heap simulator doesn't really work for this purpose
// as none of these instructions allocate. Use just accumulation of size
// until poplar specific liveness simulator is implemented
int64 ans = absl::c_accumulate(potential_io_tile_insts.instructions(),
static_cast<int64>(0),
[](int64 sum, const HloInstruction* inst) {
return sum + GetInstructionBufferSize(inst);
});
return ans;
}
bool ShouldBeOnIoTiles(const HloInstruction* inst,
const CallGraph& call_graph) {
switch (inst->opcode()) {
case HloOpcode::kInfeed:
case HloOpcode::kOutfeed:
// Currently incompatible with batch serial pipeline lowering.
return !IsInSerialPipeline(inst, call_graph);
case HloOpcode::kCustomCall:
return IsPoplarInstruction(RemoteParameterLoad)(inst) ||
IsPoplarInstruction(RemoteParameterStore)(inst) ||
IsPoplarInstruction(BufferLoadSlice)(inst) ||
IsPoplarInstruction(BufferStoreSlice)(inst) ||
IsPoplarInstruction(RecvFromHost)(inst) ||
IsPoplarInstruction(SendToHost)(inst);
default:
return false;
}
}
StatusOr<bool> IoTilesPlacer::RunOnComputation(HloComputation* comp,
const CallGraph& call_graph) {
HloInstructionSequence potential_io_tile_insts;
for (auto* inst : comp->MakeInstructionPostOrder()) {
if (ShouldBeOnIoTiles(inst, call_graph)) {
potential_io_tile_insts.push_back(inst);
}
}
const int64 max_live_bytes = GetMaxLiveBytes(potential_io_tile_insts);
const int64 target_io_bytes = GetMaxAvailableIoBytes(
num_io_tiles, bytes_per_io_tile, AvailableMemoryProportion());
const bool insts_fit_on_io_tiles = max_live_bytes < target_io_bytes;
const bool change =
insts_fit_on_io_tiles && !potential_io_tile_insts.instructions().empty();
if (change) {
for (auto* inst : potential_io_tile_insts.instructions()) {
TF_RETURN_IF_ERROR(AssignToIoTilesAndPropagateToGteUsers(inst));
}
} else if (!insts_fit_on_io_tiles) {
LOG(INFO) << absl::StrCat(
"Computation too large to fit on IO tiles, ", max_live_bytes,
" >= ", target_io_bytes,
". Currently the number of IO tiles is set to ", num_io_tiles,
" with the available memory"
" proportion set to ",
AvailableMemoryProportion(),
". To try and fit all the data into IO tiles you either need to"
" increase the number of IO tiles or the available memory proportion"
" using the `ipu.config.IPUConfig.io_tiles` category.");
}
return change;
}
static bool PoplarInstructionUsesIOTiles(const HloInstruction* inst) {
// The call to should be on io tiles ensures this GetTileset will succeed
return GetTileset(inst).ValueOrDie() == TILESET_IO_TILES;
}
static bool UsesIOTiles(const HloInstruction* inst,
const CallGraph& call_graph) {
return ShouldBeOnIoTiles(inst, call_graph) &&
PoplarInstructionUsesIOTiles(inst);
}
static bool UsesIOTiles(const HloComputation* computation,
const CallGraph& call_graph) {
return absl::c_any_of(computation->instructions(),
[&](const HloInstruction* inst) {
return UsesIOTiles(inst, call_graph);
});
}
static bool UsesIOTiles(const std::vector<HloComputation*>& computations,
const CallGraph& call_graph) {
return absl::c_any_of(computations, [&](const HloComputation* comp) {
return UsesIOTiles(comp, call_graph);
});
}
static bool UpdateNumIoTiles(int64& resources_num_io_tiles_,
const std::vector<HloComputation*>& computations,
const CallGraph& call_graph) {
const bool any_instruction_on_io_tiles =
UsesIOTiles(computations, call_graph);
if (any_instruction_on_io_tiles || resources_num_io_tiles_ == 0) {
return false; // Haven't changed resources so return false
}
// Remove io tiles from resources/graph as no ops placed on them
resources_num_io_tiles_ = 0;
return true;
}
StatusOr<bool> IoTilesPlacer::Run(HloModule* module) {
if (!enabled_) {
return false;
}
VLOG(2) << "Before IoTilesPlacer:";
XLA_VLOG_LINES(2, module->ToString());
bool changed = false;
const auto call_graph = CallGraph::Build(module);
auto computations = module->MakeComputationPostOrder();
for (auto* comp : computations) {
if (IsPopOpsFusion(comp)) {
continue;
}
TF_ASSIGN_OR_RETURN(const bool computation_changed,
RunOnComputation(comp, *call_graph));
changed |= computation_changed;
}
changed |=
UpdateNumIoTiles(resources_num_io_tiles_, computations, *call_graph);
if (changed) {
VLOG(2) << "After IoTilesPlacer:";
XLA_VLOG_LINES(2, module->ToString());
} else {
VLOG(2) << "No changes were made.";
}
return changed;
}
} // namespace poplarplugin
} // namespace xla
| 37.465217 | 87 | 0.684113 | chenzhengda |