blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 905
values | visit_date timestamp[us]date 2015-08-09 11:21:18 2023-09-06 10:45:07 | revision_date timestamp[us]date 1997-09-14 05:04:47 2023-09-17 19:19:19 | committer_date timestamp[us]date 1997-09-14 05:04:47 2023-09-06 06:22:19 | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22
values | gha_event_created_at timestamp[us]date 2012-06-07 00:51:45 2023-09-14 21:58:39 ⌀ | gha_created_at timestamp[us]date 2008-03-27 23:40:48 2023-08-21 23:17:38 ⌀ | gha_language stringclasses 141
values | src_encoding stringclasses 34
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 3 10.4M | extension stringclasses 115
values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
45a2b7832886c0c152d41ca5aa276d351af83497 | 52e24c69c89b1a05435e84f566804871eb05327f | /main.cpp | f5e7b20b790d144d0d8fc0c91c5fbf0ab9b2edbc | [] | no_license | PauloAlvarengaAulas/trabalho-final-grupo-11 | 8dbd62c769d02deb5647314161da4c874728d185 | f5434f10313775ca06e2b2d957ee415f9679f50e | refs/heads/main | 2023-02-01T00:00:07.339266 | 2020-12-12T18:42:46 | 2020-12-12T18:42:46 | 320,881,650 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,864 | cpp |
#include <iostream>
#include <string>
using namespace std;
struct funcionario
{
string nome;
int cpf;
float salario;
};
struct No
{
funcionario dado;
No *lig;
};
typedef struct No *NoPtr;
void insere(NoPtr &L, funcionario Novo)
{
if (L == NULL)
{
L = new No;
L->dado = Novo;
L->lig = NULL;
}
else
{
NoPtr Ant = NULL;
NoPtr Aux = L;
while ((Aux != NULL) && (Aux->dado.cpf < Novo.cpf))
{
Ant = Aux;
Aux = Aux->lig;
}
Aux = new No;
Aux->dado = Novo;
if (Ant == NULL)
{
Aux->lig = L;
L = Aux;
}
else
{
Aux->lig = Ant->lig;
Ant->lig = Aux;
}
}
}
bool remover(NoPtr &L, string rem)
{
NoPtr Ant = NULL;
NoPtr Aux = L;
while ((Aux != NULL) && (Aux->dado.nome != rem && Aux->dado.cpf != atoi(rem.c_str())))
{
Ant = Aux;
Aux = Aux->lig;
}
if (Aux == NULL)
{
return false;
}
if (Aux == L)
{
L = Aux->lig;
}
else
{
Ant->lig = Aux->lig;
}
cout<< "Excluido" << endl;
delete Aux;
return true;
}
void lista(NoPtr L)
{
NoPtr Ant = NULL;
NoPtr Aux = L;
cout << "Funcionarios:\n";
while ((Aux != NULL))
{
Ant = Aux;
Aux = Aux->lig;
cout << "\nNome: " << Ant->dado.nome << endl
<< "CPF: " << Ant->dado.cpf << endl
<< "Salario: R$" << Ant->dado.salario << endl;
}
}
void menu(NoPtr &L)
{
funcionario novo;
string aRemover;
int op;
while (true)
{
cout << " Menu" << endl
<< "1: Insere" << endl
<< "2: Mostrar Todos" << endl
<< "3: Remover" << endl
<< "4: Sair" << endl;
cin >> op;
system("clear");
switch (op)
{
case 1:
cout << "Insira o Nome do funcionario: ";
getline(cin >> ws, novo.nome);
cout << "Insira o CPF do funcionario: ";
cin >> novo.cpf;
cout << "Insira o Salario do funcionario: ";
cin >> novo.salario;
insere(L, novo);
break;
case 2:
lista(L);
break;
case 3:
cout << "Insira o Nome ou CPF do funcionario que deseja remover: ";
getline(cin >> ws, aRemover);
if (!remover(L, aRemover))
{
cout << "Nao foi possivel encontrar um funcionario com os dados passados.";
}
break;
case 4:
return;
default:
cout << "Opcao Invalida, tente novamente.\n";
break;
}
}
}
int main()
{
NoPtr L = NULL;
menu(L);
}
| [
"leticia.miranda@unifei.edu.br"
] | leticia.miranda@unifei.edu.br |
b89df10e9d3d854906c45088268c656f88402c77 | ca4205c93d09d9f6b06d9133f044d7dcca67446d | /my_memcache/src/isession_owner.h | 6ca68182d8d9bc5164fda74dd5a0e78b37018a8a | [
"MIT"
] | permissive | AlexBoliachiy/tiny_memcached | 4e8a294be56c3eb4f426f5a477be5059ef120ded | d2074178df9cecdfd8d20f64daaab3aba2ea448b | refs/heads/master | 2020-03-26T15:15:34.798721 | 2018-08-16T20:31:18 | 2018-08-16T20:31:18 | 145,031,936 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 178 | h | #pragma once
class Session;
class iSessionOwner
{
public:
virtual void OnDisconnect(std::shared_ptr<Session>) = 0;
virtual void OnOverflow(std::shared_ptr<Session>) = 0;
};
| [
"alexandrboliachiy@gmail.com"
] | alexandrboliachiy@gmail.com |
467e2c5afd0649827c8d0749316df3c927d34f87 | bc3073755ed70dd63a7c947fec63ccce408e5710 | /src/Game/Systems/ParticleSystem.cpp | a83887fe9db7d8b9f59a8b67065d77ff743c2910 | [] | no_license | ptrefall/ste6274gamedesign | 9e659f7a8a4801c5eaa060ebe2d7edba9c31e310 | 7d5517aa68910877fe9aa98243f6bb2444d533c7 | refs/heads/master | 2016-09-07T18:42:48.012493 | 2011-10-13T23:41:40 | 2011-10-13T23:41:40 | 32,448,466 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,864 | cpp | #include "ParticleSystem.h"
#include <Game/Components/ParticleEmitter.h>
#include <Game/Graphics/EngineFlameParticleEngine.h>
#include <Game/Graphics/Utils.h>
#include <math.h>
using namespace Systems;
ParticleSystem::ParticleSystem()
{
}
ParticleSystem::~ParticleSystem()
{
}
void ParticleSystem::loadParticleEmitter(Components::ParticleEmitter *emitter)
{
if(emitter->getIndex() >= 0)
removeParticleEmitter(emitter);
S32 index = emitters.size();
emitter->setIndex(index);
emitters.push_back(emitter);
const glm::vec3 &pos = emitter->getPos();
const glm::vec3 &color = emitter->getColor();
const T_HashedStringType &type = emitter->getParticleType();
if(type == T_HashedString("ENGINE_FLAME").getId())
{
Graphics::EngineFlameParticleEngine *engine = new Graphics::EngineFlameParticleEngine(1.0f, 0.2f, 0.0f, 1.0f);
engine->init((int)emitter->getParticleCount());
engines.push_back(engine);
}
}
void ParticleSystem::removeParticleEmitter(Components::ParticleEmitter *emitter)
{
/*const S32 &index = emitter->getIndex();
if(index < 0)
return;
emitters[index] = emitters.back();
emitters.pop_back();
Graphics::QdParticleEngine *engine = engines[index];
engines[index] = engines.back();
engines.pop_back();
delete engine;
emitter->setIndex(-1);*/
}
void ParticleSystem::updateParticleEmitter(Components::ParticleEmitter *emitter, const F32 &deltaTime)
{
const S32 &index = emitter->getIndex();
if(index < 0)
return;
Graphics::QdParticleEngine *engine = engines[index];
}
void ParticleSystem::renderParticleEmitter(Components::ParticleEmitter *emitter)
{
const S32 &index = emitter->getIndex();
if(index < 0)
return;
Graphics::QdParticleEngine *engine = engines[index];
/*if(*/engine->draw();/* == 0)
removeParticleEmitter(emitter);*/
}
| [
"PTrefall@gmail.com@2c5777c1-dd38-1616-73a3-7306c0addc79"
] | PTrefall@gmail.com@2c5777c1-dd38-1616-73a3-7306c0addc79 |
babfd35ce17d09583d1a5b00d3939eb0874722ba | cc1c795d8b362681c2f97a71fa4e3f2641d38527 | /1/36.cpp | 38f03a8a9bf73f0c86380b0df6ae7f20df0fdee6 | [] | no_license | hedgehoCrow/AOJ | 519e4bc8d19a4110db1957f38fdcf48c9ffcc81c | f0fc763e9ffd794aba2897837c8a10b16c960732 | refs/heads/master | 2021-05-29T05:30:37.991997 | 2015-08-16T18:53:47 | 2015-08-16T18:53:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,261 | cpp | //include
//------------------------------------------
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <string>
#include <cstring>
#include <ctime>
using namespace std;
//conversion
//------------------------------------------
inline int toInt(string s) {int v; istringstream sin(s);sin>>v;return v;}
template<class T> inline string toString(T x) {ostringstream sout;sout<<x;return sout.str();}
//math
//-------------------------------------------
template<class T> inline T sqr(T x) {return x*x;}
//typedef
//------------------------------------------
typedef vector<int> VI;
typedef vector<VI> VVI;
typedef vector<string> VS;
typedef pair<int, int> PII;
typedef long long LL;
typedef unsigned long long ULL;
//container util
//------------------------------------------
#define ALL(a) (a).begin(),(a).end()
#define RALL(a) (a).rbegin(), (a).rend()
#define PB push_back
#define MP make_pair
#define SZ(a) int((a).size())
#define EACH(i,c) for(typeof((c).begin()) i=(c).begin(); i!=(c).end(); ++i)
#define EXIST(s,e) ((s).find(e)!=(s).end())
#define SORT(c) sort((c).begin(),(c).end())
//repetition
//------------------------------------------
#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define REP(i,n) FOR(i,0,n)
//constant
//--------------------------------------------
const double EPS = 1e-10;
const double PI = acos(-1.0);
//clear memory
#define CLR(a) memset((a), 0 ,sizeof(a))
//debug
#define dump(x) cerr << #x << " = " << (x) << endl;
#define debug(x) cerr << #x << " = " << (x) << " (L" << __LINE__ << ")" << " " << __FILE__ << endl;
int main() {
int n;
string s[6];
char c = '*';
cin >> n;
REP(i, n) {
double h;
cin >> h;
if(h < 165) s[0] += c;
else if(165.0 <= h && h < 170.0) s[1] += c;
else if(170.0 <= h && h < 175.0) s[2] += c;
else if(175.0 <= h && h < 180.0) s[3] += c;
else if(180.0 <= h && h < 185.0) s[4] += c;
else s[5] += c;
}
REP(i, 6) {
cout << i+1 << ':' << s[i] << endl;
}
}
| [
"crowizard@gmail.com"
] | crowizard@gmail.com |
4840eddc5126932b68cffe614a44650ff8be6a5b | f3efdf8c4466a8e1dffa40282979d68958d2cb14 | /atcoder.jp/abc083/arc088_b/Main.cpp | 934c34ce0537d0c54518fb14beae4e1b561a1b1b | [] | no_license | bokusunny/atcoder-archive | be1abd03a59ef753837e3bada6c489a990dd4ee5 | 248aca070960ee5519df5d4432595298864fa0f9 | refs/heads/master | 2023-08-20T03:37:14.215842 | 2021-10-20T04:19:15 | 2021-10-20T04:19:15 | 355,762,924 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 424 | cpp | #include <bits/stdc++.h>
using namespace std;
void solve() {
string S;
cin >> S;
int N = (int)S.size();
int l = 0, r = N - 1;
int a = 0, b = N;
while (l < r) {
if (S[l] != S[l + 1]) a = l + 1;
if (S[r] != S[r - 1]) b = r;
l++;
r--;
}
cout << min(N - a, b) << endl;
}
void setcin() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
}
int main() {
setcin();
solve();
return 0;
}
| [
"abovillage1407@gmail.com"
] | abovillage1407@gmail.com |
c10dcb360c77be36ec6f8991ad75186afee74131 | 4dbd13c93a59b6d85e03abd0ae01b8a87f30e7b3 | /Competitive_Programming/Codeforces/720-2/B_Nastia_and_a_Good_Array.cpp | 46b3e90fd1fefe05e76875e31a277ecf24c9ece8 | [] | no_license | yrenelapin/Data_Structures_and_Algorithms-1 | e6ae0b3919d6f91f39b08b4a7dbf46724ca3e306 | d890eabfeef7f18fbe0555a0951d11dcb4a85f34 | refs/heads/master | 2023-06-25T07:40:42.873766 | 2021-07-19T15:43:57 | 2021-07-19T15:43:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,542 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double ld;
typedef pair<int, int> pi;
typedef pair<ll, ll> pl;
typedef vector<int> vi;
typedef vector<ll> vl;
typedef vector<pi> vpi;
typedef vector<pl> vpl;
typedef vector<vi> vvi;
typedef vector<vl> vvl;
typedef priority_queue<ll> prq; // Max priority Queue.
#define fi first
#define se second
#define pb push_back
#define pob pop_back
#define sz(x) (ll)(x).size()
#define all(x) (x).begin(), (x).end()
#define allr(x) (x).rbegin(),(x).rend()
#define decimal(x) cout << fixed << setprecision(x)
#define fr(i,a,b) for(ll (i)=(a) ; (i) <= (b) ; ++(i))
#define frr(i,a,b) for(ll (i)=(a) ; (i) >= (b) ; --(i))
#define trav(ele,container) for(auto (ele): (container)) // Just gives a copy of the elements.
#define tra(ele,container) for(auto& (ele): (container)) // Gives the reference to the elements.
#define deb(x) cout << #x << " = " << x << endl
#define deb2(x, y) cout << #x << " = " << x << " , " << #y << "=" << y << endl
#define deb3(x, y, z) cout << #x << " = " << x << " , " << #y << "=" << y << " , " << #z << "=" << z << endl
#define fastIO ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
template <typename T> using min_prq = priority_queue<T, vector<T>, greater<T>>; // Min priority queue
inline ll pmod(ll i, ll n) { return (i % n + n) % n; }
const int mod = 1e9 + 7;
const long long INF = 1e18;
void solve() {
int n;
cin >> n;
vi v(n);
vvi results;
fr(i,0,n-1) cin >> v[i];
ll miny = *min_element(all(v));
ll miny_ind = min_element(all(v)) - v.begin();
fr(i,0,n-1) {
vi temp;
if (i != miny_ind){
temp.pb(miny_ind+1);
temp.pb(i+1);
temp.pb(miny);
temp.pb(miny+abs(miny_ind-i));
v[i] = miny + abs(miny_ind-i);
results.pb(temp);
}
}
int s = results.size();
if (s != 0){
cout << s << "\n";
fr(i, 0, s-1){
fr(j,0,3){
cout << results[i][j] << " ";
}
cout << "\n";
}
}
else{
cout << s << "\n";
}
// fr(i,0,n-1){
// cout << v[i] << " ";
// }
// cout << endl;
}
signed main() {
// freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
fastIO;
int t = 1;
cin >> t; // Comment this line if only 1 testcase exists.
fr(T,1,t){
//cout << "Case #" << T << ": ";
solve();
}
return 0;
} | [
"sanjay.mareddi@gmail.com"
] | sanjay.mareddi@gmail.com |
616e45fee991224a20a0b0cf2c564d9b8ff0b63d | 478de0280fa43b1bba49e8f1ef8dca6334c4ad91 | /include/qtvariantproperty.h | 84e0b8ec67b3ed43f79e76c4a5a3a1c11ddf39a0 | [] | no_license | chenjh1234/property | 6fde06756721bdb156364c51ae098fea621eef4e | 38beb3b28706ecd6bb04f79097ba0789dc7fb14c | refs/heads/master | 2021-06-28T22:06:38.486274 | 2017-09-18T01:02:22 | 2017-09-18T01:02:22 | 103,875,447 | 0 | 0 | null | null | null | null | ISO-8859-3 | C++ | false | false | 13,700 | h |
#ifndef QTVARIANTPROPERTY_H
#define QTVARIANTPROPERTY_H
#include "qtpropertybrowser.h"
#include <QtCore/QVariant>
#include <QtGui/QIcon>
#include <QObject>
#if QT_VERSION >= 0x040400
QT_BEGIN_NAMESPACE
#endif
typedef QMap<int, QIcon> QtIconMap;
class QtVariantPropertyManager;
class QtPathPropertyManager;
class QtCustomPropertyManager;
// predefined attribute name for user, so you can use AttrName::maximum
// instead of magic numeber like "maximum",
// see class QtVariantProperty/QtVariantPropertyManager's setter/getter method setAttribute/attributeValue
class AttrName
{
public:
static const QString minimum; // set property's minimum.
static const QString maximum; // set property's maximum.
static const QString singleStep; // set single step value when changing property's value by QSpinBox etc.
static const QString decimals; // set the number decimals of double value that is displaying in UI,
// (has no effect on editing and data stored in memery).
static const QString regExp; // set regular expression to format QVariant::String property.
static const QString constraint; // constraint attribute, to restrict the area of rectangle property.
static const QString enumIcons; // set icons that associated with enum value.
// type is QtIconMap (QMap : enum value -> QIcon).
static const QString enumNames; // set the enum name that is dispaying in QComboBox.
static const QString enumValues; // set the enum value. By default, it set or return 0, 1, 2, etc
// corresponding to QComboBox's item from top to bottom. If you have
// diffrent setting, set this attribute to property. The type is QVariantList,
// each item in QVariantList is integer.
static const QString flagNames; // set the flag name displaying in UI/QCheckBox.
};
// redefine type id because of QVariant::Bool etc conflict with GeoEast's code
// you can use QtVariant::xxx instead of QVariant::xxx,
// & use QtVariant::xxx() for short instead of QtVariantProperty::xxx()
class QtVariant
{
public:
static const int Boolean;
static const int Double;
static const int Color;
static const int Int;
static const int String;
static const int Char;
static const int Rect;
static const int RectF;
static const int Point;
static const int PointF;
static const int Size;
static const int SizeF;
static const int Font;
static const int Locale;
static const int Cursor;
static const int KeySequence;
static const int SizePolicy;
static const int DateTime;
static const int Date;
static const int Time;
static int sliderDoubleTypeId(); // double value type of property, and use slider to edit value
static int enumTypeId(); // QComboBox editor, for enum type
static int iconMapTypeId(); // QtIconMap, use in enum type, set every icon associate with enum value, QMap£şenum value -> QIcon
static int flagTypeId(); // a group QCheckBox editor, value type is int, use bits as flags
static int groupTypeId(); // represent a group properties, can just set a title for this group property
static int groupWithTextTypeId(); // represent a group properties, can set a title for this group property
// and set a text value that associated with sub-properies
static int pathTypeId(); // use for opening file, folder, or popup dialog and so on,
// provided a button and you need connect to signal openPathTriggered() for clicked event
static int customTypeId(); // custom type of property, can set value of QImage, QPixmap, EsColors, QRgb to property.
// provided 2 button and you need connect to signal customOpenTriggered() for clicked event,
// connect to signal customPopupTriggered() for popup event
static int buttonTypeId(); // only a button for property. connect to signal buttonClicked()
// 3 below does not implement now, just provide a button and emit signal openPathTriggered() when clicked
static int gradientColorTypeId(); // gradient color
static int colorTemplateTypeId(); // Color Template Type
static int materialTypeId(); // material type
};
class QtVariantProperty : public QtProperty
{
public:
~QtVariantProperty();
QVariant value() const;
QVariant attributeValue(const QString &attribute) const;
int valueType() const;
int propertyType() const;
void setValue(const QVariant &value);
void setAttribute(const QString &attribute, const QVariant &value);
protected:
QtVariantProperty(QtVariantPropertyManager *manager);
private:
friend class QtVariantPropertyManager;
class QtVariantPropertyPrivate *d_ptr;
};
class QtVariantPropertyManager : public QtAbstractPropertyManager
{
Q_OBJECT
public:
QtVariantPropertyManager(QObject *parent = 0);
~QtVariantPropertyManager();
virtual QtVariantProperty *addProperty(int propertyType, const QString &name = QString());
int propertyType(const QtProperty *property) const;
int valueType(const QtProperty *property) const;
QtVariantProperty *variantProperty(const QtProperty *property) const;
virtual bool isPropertyTypeSupported(int propertyType) const;
virtual int valueType(int propertyType) const;
virtual QStringList attributes(int propertyType) const;
virtual int attributeType(int propertyType, const QString &attribute) const;
virtual QVariant value(const QtProperty *property) const;
virtual QVariant attributeValue(const QtProperty *property, const QString &attribute) const;
// the static functions below use for getting type id
static int enumTypeId(); // QComboBox editor, for enum type
static int iconMapTypeId(); // QtIconMap, use in enum type, set every icon associate with enum value, QMap£şenum value -> QIcon
static int flagTypeId(); // a group QCheckBox editor, value type is int, use bits as flags
static int groupTypeId(); // represent a group properties, can just set a title for this group property
static int groupWithTextTypeId(); // represent a group properties, can set a title for this group property
// and set a text value that associated with sub-properies
static int pathTypeId(); // use for opening file, folder, or popup dialog and so on,
// provided a button and you need connect to signal openPathTriggered() for clicked event
static int sliderDoubleTypeId(); // double value type of property, and use slider to edit value
static int customTypeId(); // custom type of property, can set value of QImage, QPixmap, EsColors, QRgb to property.
// provided 2 button and you need connect to signal customOpenTriggered() for clicked event,
// connect to signal customPopupTriggered() for popup event
static int buttonTypeId(); // only a button for property. connect to signal buttonClicked()
// 3 below does not implement now, just provide a button and emit signal openPathTriggered() when clicked
static int gradientColorTypeId(); // gradient color
static int colorTemplateTypeId(); // Color Template Type
static int materialTypeId(); // material type
public Q_SLOTS:
virtual void setValue(QtProperty *property, const QVariant &val);
virtual void setAttribute(QtProperty *property, const QString &attribute, const QVariant &value);
Q_SIGNALS:
void valueChanged(QtProperty *property, const QVariant &val);
void attributeChanged(QtProperty *property, const QString &attribute, const QVariant &val);
// only use for property who's type is pathTypeId()
void openPathTriggered(QtVariantProperty *property, QtVariantPropertyManager *thisManager = 0);
// only use for property who's type is customTypeId()
void customOpenTriggered(QtVariantProperty *property, QtVariantPropertyManager *thisManager = 0);
// only use for property who's type is customTypeId()
void customPopupTriggered(QtVariantProperty *property, QtVariantPropertyManager *thisManager = 0);
// only use for property who's type is buttonTypeId()
void buttonClicked(QtVariantProperty *property);
protected:
virtual bool hasValue(const QtProperty *property) const;
QString valueText(const QtProperty *property) const;
QIcon valueIcon(const QtProperty *property) const;
virtual void initializeProperty(QtProperty *property);
virtual void uninitializeProperty(QtProperty *property);
virtual QtProperty *createProperty();
virtual bool hasCustomValue(const QtProperty *property) const;
virtual QVariant customValue(const QtProperty *property) const;
private:
class QtVariantPropertyManagerPrivate *d_ptr;
Q_PRIVATE_SLOT(d_func(), void slotValueChanged(QtProperty *, int))
Q_PRIVATE_SLOT(d_func(), void slotRangeChanged(QtProperty *, int, int))
Q_PRIVATE_SLOT(d_func(), void slotSingleStepChanged(QtProperty *, int))
Q_PRIVATE_SLOT(d_func(), void slotValueChanged(QtProperty *, double))
Q_PRIVATE_SLOT(d_func(), void slotRangeChanged(QtProperty *, double, double))
Q_PRIVATE_SLOT(d_func(), void slotSingleStepChanged(QtProperty *, double))
Q_PRIVATE_SLOT(d_func(), void slotDecimalsChanged(QtProperty *, int))
Q_PRIVATE_SLOT(d_func(), void slotValueChanged(QtProperty *, bool))
Q_PRIVATE_SLOT(d_func(), void slotValueChanged(QtProperty *, const QString &))
Q_PRIVATE_SLOT(d_func(), void slotRegExpChanged(QtProperty *, const QRegExp &))
Q_PRIVATE_SLOT(d_func(), void slotValueChanged(QtProperty *, const QDate &))
Q_PRIVATE_SLOT(d_func(), void slotRangeChanged(QtProperty *, const QDate &, const QDate &))
Q_PRIVATE_SLOT(d_func(), void slotValueChanged(QtProperty *, const QTime &))
Q_PRIVATE_SLOT(d_func(), void slotValueChanged(QtProperty *, const QDateTime &))
Q_PRIVATE_SLOT(d_func(), void slotValueChanged(QtProperty *, const QKeySequence &))
Q_PRIVATE_SLOT(d_func(), void slotValueChanged(QtProperty *, const QChar &))
Q_PRIVATE_SLOT(d_func(), void slotValueChanged(QtProperty *, const QLocale &))
Q_PRIVATE_SLOT(d_func(), void slotValueChanged(QtProperty *, const QPoint &))
Q_PRIVATE_SLOT(d_func(), void slotValueChanged(QtProperty *, const QPointF &))
Q_PRIVATE_SLOT(d_func(), void slotValueChanged(QtProperty *, const QSize &))
Q_PRIVATE_SLOT(d_func(), void slotRangeChanged(QtProperty *, const QSize &, const QSize &))
Q_PRIVATE_SLOT(d_func(), void slotValueChanged(QtProperty *, const QSizeF &))
Q_PRIVATE_SLOT(d_func(), void slotRangeChanged(QtProperty *, const QSizeF &, const QSizeF &))
Q_PRIVATE_SLOT(d_func(), void slotValueChanged(QtProperty *, const QRect &))
Q_PRIVATE_SLOT(d_func(), void slotConstraintChanged(QtProperty *, const QRect &))
Q_PRIVATE_SLOT(d_func(), void slotValueChanged(QtProperty *, const QRectF &))
Q_PRIVATE_SLOT(d_func(), void slotConstraintChanged(QtProperty *, const QRectF &))
Q_PRIVATE_SLOT(d_func(), void slotValueChanged(QtProperty *, const QColor &))
Q_PRIVATE_SLOT(d_func(), void slotEnumNamesChanged(QtProperty *, const QStringList &))
Q_PRIVATE_SLOT(d_func(), void slotEnumIconsChanged(QtProperty *, const QMap<int, QIcon> &))
Q_PRIVATE_SLOT(d_func(), void slotEnumValuesChanged(QtProperty *, const QList<int> &))
Q_PRIVATE_SLOT(d_func(), void slotValueChanged(QtProperty *, const QSizePolicy &))
Q_PRIVATE_SLOT(d_func(), void slotValueChanged(QtProperty *, const QFont &))
Q_PRIVATE_SLOT(d_func(), void slotValueChanged(QtProperty *, const QCursor &))
Q_PRIVATE_SLOT(d_func(), void slotFlagNamesChanged(QtProperty *, const QStringList &))
Q_PRIVATE_SLOT(d_func(), void slotOpenPathTriggered(QtProperty *, QtPathPropertyManager *))
Q_PRIVATE_SLOT(d_func(), void slotCustomOpenTriggered(QtProperty *, QtCustomPropertyManager *));
Q_PRIVATE_SLOT(d_func(), void slotCustomPopupTriggered(QtProperty *, QtCustomPropertyManager *));
Q_PRIVATE_SLOT(d_func(), void slotValueChanged(QtProperty*,QVariant))
Q_PRIVATE_SLOT(d_func(), void slotButtonClicked(QtProperty*));
Q_PRIVATE_SLOT(d_func(), void slotPropertyInserted(QtProperty *, QtProperty *, QtProperty *))
Q_PRIVATE_SLOT(d_func(), void slotPropertyRemoved(QtProperty *, QtProperty *))
Q_DECLARE_PRIVATE(QtVariantPropertyManager)
Q_DISABLE_COPY(QtVariantPropertyManager)
};
class QtVariantEditorFactory : public QtAbstractEditorFactory<QtVariantPropertyManager>
{
Q_OBJECT
public:
QtVariantEditorFactory(QObject *parent = 0);
~QtVariantEditorFactory();
protected:
void connectPropertyManager(QtVariantPropertyManager *manager);
QWidget *createEditor(QtVariantPropertyManager *manager, QtProperty *property,
QWidget *parent);
void disconnectPropertyManager(QtVariantPropertyManager *manager);
private:
class QtVariantEditorFactoryPrivate *d_ptr;
Q_DECLARE_PRIVATE(QtVariantEditorFactory)
Q_DISABLE_COPY(QtVariantEditorFactory)
};
#if QT_VERSION >= 0x040400
QT_END_NAMESPACE
#endif
Q_DECLARE_METATYPE(QIcon)
Q_DECLARE_METATYPE(QtIconMap)
#endif
| [
"chenjh1234@sina.com"
] | chenjh1234@sina.com |
e72aa8e821cf722701716e8cd14b6b3581fc5dc4 | a9c3428de7525b1d235029c01a761de4adf30e73 | /localdom/minimizeND.cpp | 50064858363ab7a9623b05b8fc01b3800c5316bb | [] | no_license | potel/DOM | e79020993a14ec10fc612109777483e4f99b090f | e50aa3770b5a7172773a8c3393f38e2fd0193ae4 | refs/heads/master | 2021-01-13T17:06:38.087320 | 2019-11-04T10:41:41 | 2019-11-04T10:41:41 | 74,409,377 | 0 | 2 | null | 2017-05-30T17:32:15 | 2016-11-21T21:55:32 | C++ | UTF-8 | C++ | false | false | 3,562 | cpp | #include "minimizeND.h"
#include <cmath>
#include <iostream>
using namespace std;
//************************************************************
minimizeND::minimizeND(int ND0)
{
ND = ND0;
pcom = new double [ND];
xicom = new double [ND];
}
//*************************************************************
minimizeND::~minimizeND()
{
delete [] pcom;
delete [] xicom;
}
//*************************************************************
//used by linmin. Provides a 1D function for use by the base class
//minimize1D
double minimizeND::funct1D(double x)
{
double xt[ND];
for (int i=0;i<ND;i++) xt[i] = pcom[i] + x*xicom[i];
return functND(xt);
}
//**************************************************************
// minimize a function along a direction specified by the vector xi[],
// starting at the initial point p[]. The minimized function value is
// returned. Used by function powell
double minimizeND::linmin(double*p,double*xi)
{
for (int i=0;i<ND;i++)
{
pcom[i] = p[i];
xicom[i] = xi[i];
}
//initial guess for brackets
double xb[3],fb[3];
xb[0] = 0.;
xb[1] = 1.;
bracket(xb,fb);
//cout << "brackets = " << xb[0] << " " << xb[1] << " " << xb[2] << endl;
//cout << "f= " << fb[0] << " " << fb[1] << " " << fb[2] << endl;
double const tolerance = 1.e-2;
double fret = Brent(xb,tolerance);
for (int i=0;i<ND;i++)
{
xi[i] *= xb[0];
p[i] += xi[i];
}
return fret;
}
//***************************
//multidimension minimization using the powell method.
//this was translated from "numerical recipes in Fortran 77"
// by Press, Teukolsky, Vetterling, Flannery , 2nd edition page 411
double minimizeND::powell(double *p,double **xi,double const &ftol)
{
const double Tiny=1.e-25;
const int iterMax = 30;
double fret = functND(p);
double pt[ND],ptt[ND];
double xit[ND];
//cout << p[0] << " " << p[1] << endl;
//save initial point
for (int i=0;i<ND;i++) pt[i] = p[i]; //save initial point
int iter = 0;
for (;;)
{
cout << "********iteration= " << iter << " funct= " << fret << endl;
iter++;
double fp = fret;
int ibig = 0;
double del= 0.; //del will record the largest function decrease
for(int i=0;i<ND;i++)
{
cout << "******para i = " << i << endl;
for (int j=0;j<ND;j++) xit[j] = xi[j][i];
double fptt = fret;
fret = linmin(p,xit); // minimize along the direction xit
//cout << fret << " " << p[0] << " " << p[1] << endl;
if (fptt-fret > del) // check to see if this was the largest decrease
{
del = fptt - fret;
ibig = i;
}
}
if (2.*(fp-fret) <= ftol*(abs(fp)+abs(fret))+Tiny) return fret;
if (iter == iterMax)
{
cout << "powell excedding maximum iterations" << endl;
return fret;
}
//construct the extrapolated point and the average direction moved.
//save the old starting place
for (int j=0;j<ND;j++)
{
ptt[j] = 2.*p[j]-pt[j];
xit[j] = p[j] - pt[j];
pt[j] = p[j];
}
double fptt = functND(ptt); // function value at extrapolated point
if (fptt >= fp) continue; // one reason not to use the new direction
double t = 2.*(fp-2.*fret+fptt)*pow(fp-fret-del,2)-del*pow(fp-fptt,2);
if (t <= 0.) continue; // another reason not to use the new direction
fret = linmin(p,xit); // move to the minimum of the new direction
//save new direction
for (int j=0;j<ND;j++)
{
xi[j][ibig] = xi[j][ND-1];
xi[j][ND-1] = xit[j];
}
}
}
| [
"gregory.potel@gmail.com"
] | gregory.potel@gmail.com |
bbca71dd43562b8b1f796291a7962e47e25484f6 | 982fdcb9842bab21dc317c9de2a05eb6f8fe6fe9 | /interface/EventInfoSelector.h | 7bf0de147471f54303f4a63b7ba8c8b672a1cea7 | [] | no_license | romeof/NtupleMaker | cc8529e54f2382197a4b14d93f63c08b2abb596c | cd700ae214f834aef4512894f43375bd530e1f00 | refs/heads/master | 2021-01-21T13:36:57.672034 | 2015-08-04T11:58:28 | 2015-08-04T11:58:28 | 40,086,235 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,939 | h | #ifndef __EVENTINFO_HE_H_
#define __EVENTINFO_HE_H_
/////
// Include files and namespaces
/////
#include <memory>
#include "FWCore/Framework/interface/Frameworkfwd.h"
#include "FWCore/Framework/interface/EDAnalyzer.h"
#include "FWCore/Framework/interface/Event.h"
#include "FWCore/Framework/interface/MakerMacros.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "FWCore/ServiceRegistry/interface/Service.h"
#include "CommonTools/UtilAlgos/interface/TFileService.h"
#include "Geometry/Records/interface/GlobalTrackingGeometryRecord.h"
#include "DataFormats/PatCandidates/interface/Tau.h"
#include "DataFormats/PatCandidates/interface/Muon.h"
#include "DataFormats/PatCandidates/interface/Electron.h"
#include "DataFormats/PatCandidates/interface/Jet.h"
#include "DataFormats/PatCandidates/interface/MET.h"
#include "DataFormats/PatCandidates/interface/CompositeCandidate.h"
#include "DataFormats/Math/interface/LorentzVector.h"
#include "DataFormats/Math/interface/LorentzVectorFwd.h"
#include "DataFormats/JetReco/interface/GenJetCollection.h"
#include "DataFormats/JetReco/interface/GenJet.h"
#include "DataFormats/PatCandidates/interface/Isolation.h"
#include "DataFormats/Math/interface/deltaR.h"
#include "DataFormats/Math/interface/normalizedPhi.h"
#include "DataFormats/TauReco/interface/PFTau.h"
#include "DataFormats/TauReco/interface/PFTauDiscriminator.h"
#include "DataFormats/MuonReco/interface/MuonSelectors.h"
#include "DataFormats/Common/interface/RefVector.h"
#include "DataFormats/HepMCCandidate/interface/GenParticle.h"
#include "DataFormats/Candidate/interface/Candidate.h"
#include "DataFormats/Common/interface/Ref.h"
#include "DataFormats/Common/interface/ValueMap.h"
#include "DataFormats/VertexReco/interface/Vertex.h"
#include "DataFormats/VertexReco/interface/VertexFwd.h"
#include "FWCore/Common/interface/TriggerNames.h"
#include "CLHEP/Random/RandGauss.h"
#include "CommonTools/CandUtils/interface/Booster.h"
#include "DataFormats/METReco/interface/GenMET.h"
#include "DataFormats/METReco/interface/GenMETCollection.h"
#include <Math/VectorUtil.h>
#include "DataFormats/HLTReco/interface/TriggerObject.h"
#include "DataFormats/HLTReco/interface/TriggerEvent.h"
#include "DataFormats/Common/interface/Handle.h"
#include "DataFormats/TrackReco/interface/Track.h"
#include "DataFormats/TrackReco/interface/HitPattern.h"
#include "TrackingTools/TransientTrack/interface/TrackTransientTrack.h"
#include "TrackingTools/TransientTrack/interface/TransientTrackBuilder.h"
#include "TrackingTools/Records/interface/TransientTrackRecord.h"
#include "CLHEP/Units/GlobalPhysicalConstants.h"
#include "CommonTools/Statistics/interface/ChiSquaredProbability.h"
#include "CondFormats/JetMETObjects/interface/FactorizedJetCorrector.h"
#include "CondFormats/JetMETObjects/interface/JetCorrectionUncertainty.h"
#include "JetMETCorrections/Objects/interface/JetCorrectionsRecord.h"
#include "CondFormats/JetMETObjects/interface/JetCorrectorParameters.h"
#include "DataFormats/ParticleFlowCandidate/interface/PFCandidate.h"
#include "DataFormats/ParticleFlowCandidate/interface/PFCandidateFwd.h"
#include "DataFormats/Common/interface/ValueMap.h"
#include "CommonTools/ParticleFlow/test/PFIsoReaderDemo.h"
#include "FWCore/Utilities/interface/Exception.h"
#include "DataFormats/JetReco/interface/PFJet.h"
#include "DataFormats/JetReco/interface/PFJetCollection.h"
#include "CondFormats/JetMETObjects/interface/JetCorrectionUncertainty.h"
#include "CondFormats/JetMETObjects/interface/JetCorrectorParameters.h"
#include "JetMETCorrections/Objects/interface/JetCorrector.h"
#include "JetMETCorrections/Objects/interface/JetCorrectionsRecord.h"
#include "DataFormats/MuonReco/interface/MuonFwd.h"
#include "FWCore/Framework/interface/ESHandle.h"
#include "boost/regex.hpp"
#include "SimDataFormats/PileupSummaryInfo/interface/PileupSummaryInfo.h"
#include "PhysicsTools/JetMCUtils/interface/JetMCTag.h"
#include "SimDataFormats/GeneratorProducts/interface/HepMCProduct.h"
#include "SimDataFormats/GeneratorProducts/interface/GenEventInfoProduct.h"
#include "SimDataFormats/GeneratorProducts/interface/GenRunInfoProduct.h"
#include <TH1.h>
#include <TH2.h>
#include <TFile.h>
#include <TProfile.h>
#include <TTree.h>
#include <string>
#include <vector>
#include <map>
#include <sstream>
#include <stdio.h>
#include <stdlib.h>
#include "baseTree.h"
#include <TRandom3.h>
#include <TBranch.h>
#include "TTree.h"
#include "TLorentzVector.h"
#include "TClonesArray.h"
using namespace std;
using namespace edm;
/////
// Class declaration
/////
class EventInfoSelector : public baseTree{
public:
EventInfoSelector(std::string name, TTree* tree, bool debug, const edm::ParameterSet& cfg);
~EventInfoSelector();
void Fill(const edm::Event& iEvent);
void SetBranches();
private:
EventInfoSelector(){};
int EVENT_event_, EVENT_run_, EVENT_lumiBlock_;
double EVENT_genWeight_;
bool _is_data;
};
#endif
| [
"fromeo@cern.ch"
] | fromeo@cern.ch |
3fe816fc2e4c6533416c03813276a604c0e00e98 | 127c53f4e7e220f44dc82d910a5eed9ae8974997 | /EngineSDK/ThirdParty/VSInclude/bullet/BulletDynamics/ConstraintSolver/btConeTwistConstraint.cpp | 113dc6fd6f22abda500d6111f57f70d539c56bf9 | [] | no_license | zhangf911/wxsj2 | 253e16265224b85cc6800176a435deaa219ffc48 | c8e5f538c7beeaa945ed2a9b5a9b04edeb12c3bd | refs/heads/master | 2020-06-11T16:44:14.179685 | 2013-03-03T08:47:18 | 2013-03-03T08:47:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,770 | cpp | /*
Bullet Continuous Collision Detection and Physics Library
btConeTwistConstraint is Copyright (c) 2007 Starbreeze Studios
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.
Written by: Marcus Hennix
*/
#include "btConeTwistConstraint.h"
#include "BulletDynamics/Dynamics/btRigidBody.h"
#include "LinearMath/btTransformUtil.h"
#include "LinearMath/btSimdMinMax.h"
#include <new>
btConeTwistConstraint::btConeTwistConstraint()
:btTypedConstraint(CONETWIST_CONSTRAINT_TYPE)
{
}
btConeTwistConstraint::btConeTwistConstraint(btRigidBody& rbA,btRigidBody& rbB,
const btTransform& rbAFrame,const btTransform& rbBFrame)
:btTypedConstraint(CONETWIST_CONSTRAINT_TYPE, rbA,rbB),m_rbAFrame(rbAFrame),m_rbBFrame(rbBFrame),
m_angularOnly(false)
{
// flip axis for correct angles
m_rbBFrame.getBasis()[1][0] *= btScalar(-1.);
m_rbBFrame.getBasis()[1][1] *= btScalar(-1.);
m_rbBFrame.getBasis()[1][2] *= btScalar(-1.);
m_swingSpan1 = btScalar(1e30);
m_swingSpan2 = btScalar(1e30);
m_twistSpan = btScalar(1e30);
m_biasFactor = 0.3f;
m_relaxationFactor = 1.0f;
m_solveTwistLimit = false;
m_solveSwingLimit = false;
}
btConeTwistConstraint::btConeTwistConstraint(btRigidBody& rbA,const btTransform& rbAFrame)
:btTypedConstraint(CONETWIST_CONSTRAINT_TYPE,rbA),m_rbAFrame(rbAFrame),
m_angularOnly(false)
{
m_rbBFrame = m_rbAFrame;
// flip axis for correct angles
m_rbBFrame.getBasis()[1][0] *= btScalar(-1.);
m_rbBFrame.getBasis()[1][1] *= btScalar(-1.);
m_rbBFrame.getBasis()[1][2] *= btScalar(-1.);
m_rbBFrame.getBasis()[2][0] *= btScalar(-1.);
m_rbBFrame.getBasis()[2][1] *= btScalar(-1.);
m_rbBFrame.getBasis()[2][2] *= btScalar(-1.);
m_swingSpan1 = btScalar(1e30);
m_swingSpan2 = btScalar(1e30);
m_twistSpan = btScalar(1e30);
m_biasFactor = 0.3f;
m_relaxationFactor = 1.0f;
m_solveTwistLimit = false;
m_solveSwingLimit = false;
}
void btConeTwistConstraint::buildJacobian()
{
m_appliedImpulse = btScalar(0.);
//set bias, sign, clear accumulator
m_swingCorrection = btScalar(0.);
m_twistLimitSign = btScalar(0.);
m_solveTwistLimit = false;
m_solveSwingLimit = false;
m_accTwistLimitImpulse = btScalar(0.);
m_accSwingLimitImpulse = btScalar(0.);
if (!m_angularOnly)
{
btVector3 pivotAInW = m_rbA.getCenterOfMassTransform()*m_rbAFrame.getOrigin();
btVector3 pivotBInW = m_rbB.getCenterOfMassTransform()*m_rbBFrame.getOrigin();
btVector3 relPos = pivotBInW - pivotAInW;
btVector3 normal[3];
if (relPos.length2() > SIMD_EPSILON)
{
normal[0] = relPos.normalized();
}
else
{
normal[0].setValue(btScalar(1.0),0,0);
}
btPlaneSpace1(normal[0], normal[1], normal[2]);
for (int i=0;i<3;i++)
{
new (&m_jac[i]) btJacobianEntry(
m_rbA.getCenterOfMassTransform().getBasis().transpose(),
m_rbB.getCenterOfMassTransform().getBasis().transpose(),
pivotAInW - m_rbA.getCenterOfMassPosition(),
pivotBInW - m_rbB.getCenterOfMassPosition(),
normal[i],
m_rbA.getInvInertiaDiagLocal(),
m_rbA.getInvMass(),
m_rbB.getInvInertiaDiagLocal(),
m_rbB.getInvMass());
}
}
btVector3 b1Axis1,b1Axis2,b1Axis3;
btVector3 b2Axis1,b2Axis2;
b1Axis1 = getRigidBodyA().getCenterOfMassTransform().getBasis() * this->m_rbAFrame.getBasis().getColumn(0);
b2Axis1 = getRigidBodyB().getCenterOfMassTransform().getBasis() * this->m_rbBFrame.getBasis().getColumn(0);
btScalar swing1=btScalar(0.),swing2 = btScalar(0.);
// Get Frame into world space
if (m_swingSpan1 >= btScalar(0.05f))
{
b1Axis2 = getRigidBodyA().getCenterOfMassTransform().getBasis() * this->m_rbAFrame.getBasis().getColumn(1);
swing1 = btAtan2Fast( b2Axis1.dot(b1Axis2),b2Axis1.dot(b1Axis1) );
}
if (m_swingSpan2 >= btScalar(0.05f))
{
b1Axis3 = getRigidBodyA().getCenterOfMassTransform().getBasis() * this->m_rbAFrame.getBasis().getColumn(2);
swing2 = btAtan2Fast( b2Axis1.dot(b1Axis3),b2Axis1.dot(b1Axis1) );
}
btScalar RMaxAngle1Sq = 1.0f / (m_swingSpan1*m_swingSpan1);
btScalar RMaxAngle2Sq = 1.0f / (m_swingSpan2*m_swingSpan2);
btScalar EllipseAngle = btFabs(swing1)* RMaxAngle1Sq + btFabs(swing2) * RMaxAngle2Sq;
if (EllipseAngle > 1.0f)
{
m_swingCorrection = EllipseAngle-1.0f;
m_solveSwingLimit = true;
// Calculate necessary axis & factors
m_swingAxis = b2Axis1.cross(b1Axis2* b2Axis1.dot(b1Axis2) + b1Axis3* b2Axis1.dot(b1Axis3));
m_swingAxis.normalize();
btScalar swingAxisSign = (b2Axis1.dot(b1Axis1) >= 0.0f) ? 1.0f : -1.0f;
m_swingAxis *= swingAxisSign;
m_kSwing = btScalar(1.) / (getRigidBodyA().computeAngularImpulseDenominator(m_swingAxis) +
getRigidBodyB().computeAngularImpulseDenominator(m_swingAxis));
}
// Twist limits
if (m_twistSpan >= btScalar(0.))
{
btVector3 b2Axis2 = getRigidBodyB().getCenterOfMassTransform().getBasis() * this->m_rbBFrame.getBasis().getColumn(1);
btQuaternion rotationArc = shortestArcQuat(b2Axis1,b1Axis1);
btVector3 TwistRef = quatRotate(rotationArc,b2Axis2);
btScalar twist = btAtan2Fast( TwistRef.dot(b1Axis3), TwistRef.dot(b1Axis2) );
btScalar lockedFreeFactor = (m_twistSpan > btScalar(0.05f)) ? m_limitSoftness : btScalar(0.);
if (twist <= -m_twistSpan*lockedFreeFactor)
{
m_twistCorrection = -(twist + m_twistSpan);
m_solveTwistLimit = true;
m_twistAxis = (b2Axis1 + b1Axis1) * 0.5f;
m_twistAxis.normalize();
m_twistAxis *= -1.0f;
m_kTwist = btScalar(1.) / (getRigidBodyA().computeAngularImpulseDenominator(m_twistAxis) +
getRigidBodyB().computeAngularImpulseDenominator(m_twistAxis));
} else
if (twist > m_twistSpan*lockedFreeFactor)
{
m_twistCorrection = (twist - m_twistSpan);
m_solveTwistLimit = true;
m_twistAxis = (b2Axis1 + b1Axis1) * 0.5f;
m_twistAxis.normalize();
m_kTwist = btScalar(1.) / (getRigidBodyA().computeAngularImpulseDenominator(m_twistAxis) +
getRigidBodyB().computeAngularImpulseDenominator(m_twistAxis));
}
}
}
void btConeTwistConstraint::solveConstraint(btScalar timeStep)
{
btVector3 pivotAInW = m_rbA.getCenterOfMassTransform()*m_rbAFrame.getOrigin();
btVector3 pivotBInW = m_rbB.getCenterOfMassTransform()*m_rbBFrame.getOrigin();
btScalar tau = btScalar(0.3);
btScalar damping = btScalar(1.);
//linear part
if (!m_angularOnly)
{
btVector3 rel_pos1 = pivotAInW - m_rbA.getCenterOfMassPosition();
btVector3 rel_pos2 = pivotBInW - m_rbB.getCenterOfMassPosition();
btVector3 vel1 = m_rbA.getVelocityInLocalPoint(rel_pos1);
btVector3 vel2 = m_rbB.getVelocityInLocalPoint(rel_pos2);
btVector3 vel = vel1 - vel2;
for (int i=0;i<3;i++)
{
const btVector3& normal = m_jac[i].m_linearJointAxis;
btScalar jacDiagABInv = btScalar(1.) / m_jac[i].getDiagonal();
btScalar rel_vel;
rel_vel = normal.dot(vel);
//positional error (zeroth order error)
btScalar depth = -(pivotAInW - pivotBInW).dot(normal); //this is the error projected on the normal
btScalar impulse = depth*tau/timeStep * jacDiagABInv - rel_vel * jacDiagABInv;
m_appliedImpulse += impulse;
btVector3 impulse_vector = normal * impulse;
m_rbA.applyImpulse(impulse_vector, pivotAInW - m_rbA.getCenterOfMassPosition());
m_rbB.applyImpulse(-impulse_vector, pivotBInW - m_rbB.getCenterOfMassPosition());
}
}
{
///solve angular part
const btVector3& angVelA = getRigidBodyA().getAngularVelocity();
const btVector3& angVelB = getRigidBodyB().getAngularVelocity();
// solve swing limit
if (m_solveSwingLimit)
{
btScalar amplitude = ((angVelB - angVelA).dot( m_swingAxis )*m_relaxationFactor*m_relaxationFactor + m_swingCorrection*(btScalar(1.)/timeStep)*m_biasFactor);
btScalar impulseMag = amplitude * m_kSwing;
// Clamp the accumulated impulse
btScalar temp = m_accSwingLimitImpulse;
m_accSwingLimitImpulse = btMax(m_accSwingLimitImpulse + impulseMag, btScalar(0.0) );
impulseMag = m_accSwingLimitImpulse - temp;
btVector3 impulse = m_swingAxis * impulseMag;
m_rbA.applyTorqueImpulse(impulse);
m_rbB.applyTorqueImpulse(-impulse);
}
// solve twist limit
if (m_solveTwistLimit)
{
btScalar amplitude = ((angVelB - angVelA).dot( m_twistAxis )*m_relaxationFactor*m_relaxationFactor + m_twistCorrection*(btScalar(1.)/timeStep)*m_biasFactor );
btScalar impulseMag = amplitude * m_kTwist;
// Clamp the accumulated impulse
btScalar temp = m_accTwistLimitImpulse;
m_accTwistLimitImpulse = btMax(m_accTwistLimitImpulse + impulseMag, btScalar(0.0) );
impulseMag = m_accTwistLimitImpulse - temp;
btVector3 impulse = m_twistAxis * impulseMag;
m_rbA.applyTorqueImpulse(impulse);
m_rbB.applyTorqueImpulse(-impulse);
}
}
}
void btConeTwistConstraint::updateRHS(btScalar timeStep)
{
(void)timeStep;
}
| [
"amwfhv@163.com"
] | amwfhv@163.com |
7ba9ffc71bbe789efffa585a0259e04421c6571e | 663f36cfff3bfaf9ad64bba430e648b0dadc0f99 | /plugins/INPUT/inputdriverDIRECTINPUT8/src/DLLMainInputDriverDI8.cpp | 0c158b67737d826d719e1ebe60205ab4c3b0607d | [
"Apache-2.0"
] | permissive | LiberatorUSA/GUCEF | b579a530ac40478e8d92d8c1688dce71634ec004 | 2f24399949bc2b2eb20b3f445100dd3e141fe6d5 | refs/heads/master | 2023-09-03T18:05:25.190918 | 2023-09-02T17:23:59 | 2023-09-02T17:23:59 | 24,012,676 | 9 | 15 | Apache-2.0 | 2021-07-04T04:53:42 | 2014-09-14T03:30:46 | C++ | UTF-8 | C++ | false | false | 41,320 | cpp | /*
* Copyright (C) Dinand Vanvelzen. 2002 - 2005. All rights reserved.
*
* All source code herein is the property of Dinand Vanvelzen. You may not sell
* or otherwise commercially exploit the source or things you created based on
* the source.
*
* THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
* EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
* WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
* IN NO EVENT SHALL DINAND VANVELZEN BE LIABLE FOR ANY SPECIAL, INCIDENTAL,
* INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER
* RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER OR NOT ADVISED OF
* THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF LIABILITY, ARISING OUT
* OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/*
* API for a Input driver plugin module
*/
/*-------------------------------------------------------------------------//
// //
// CONSTANTS //
// //
//-------------------------------------------------------------------------*/
#define DIRECTINPUT_VERSION 0x0800
//#define UNICODE // enable to compile as UNICODE, default is ANSI key codes
/*-------------------------------------------------------------------------//
// //
// INCLUDES //
// //
//-------------------------------------------------------------------------*/
#include <stdlib.h>
/* You need to have the DirectX SDK installed for the following dx headers */
#include <dinput.h>
#include "DLLMainInputDriverDI8.h"
#ifndef GUCEFINPUT_MACROS_H
#include "gucefINPUT_macros.h" /* gucefINPUT macros, used here for the export and callspec macros */
#define GUCEFINPUT_MACROS_H
#endif /* GUCEFINPUT_MACROS_H ? */
/*-------------------------------------------------------------------------//
// //
// NAMESPACE //
// //
//-------------------------------------------------------------------------*/
#ifdef __cplusplus
namespace GUCEF {
namespace INPUT {
#endif /* __cplusplus */
/*-------------------------------------------------------------------------//
// //
// CONSTANTS //
// //
//-------------------------------------------------------------------------*/
static const TVersion version = { 1, 0, 0, 0 };
#define DRIVER_NAME "DirectInput8\0"
#define DRIVER_COPYRIGHT "Copyright (C) Dinand Vanvelzen. 2002 - 2005. All rights reserved.\0"
#define MOUSE_BUFFERSIZE 128 // number or DINPUT_BUFFERSIZE
#define KEYBOARD_BUFFERSIZE 64 // number or DINPUT_BUFFERSIZE
/*-------------------------------------------------------------------------//
// //
// MACROS //
// //
//-------------------------------------------------------------------------*/
#define BUTTONBOOL( data ) ( ( ( (data) & 0x80 ) ? 1 : 0 ) )
#define KEYBOOL( data ) ( ( ( (data) & 0x80 ) ? 1 : 0 ) )
#define BUTTONINDEX( id ) ( ( (id)-DIMOFS_BUTTON0 ) )
/*-------------------------------------------------------------------------//
// //
// TYPES //
// //
//-------------------------------------------------------------------------*/
struct SDI8Data
{
/* system data */
HWND hWnd;
HINSTANCE hInstance;
/* DI Object */
LPDIRECTINPUT8 pDI;
/* DI Device Capabilities */
DIDEVCAPS DIDevCaps;
/* 8 Element Array, TRUE if Button [n] is up */
// BOOL* bMouseUp;
/* Mouse vars */
POINT* pMousePos;
Int32 mouseWheelVar;
/* Cursor HotSpot */
POINT* pHotSpot;
/* Mouse Handle */
HANDLE hMouse;
HRESULT hr;
/* DI Device Objects */
LPDIRECTINPUTDEVICE8 pDIJoy;
LPDIRECTINPUTDEVICE8 pDIKeybrd;
LPDIRECTINPUTDEVICE8 pDIMouse;
/* Device event buffers */
DIDEVICEOBJECTDATA mouseBuffer[ MOUSE_BUFFERSIZE ];
DIDEVICEOBJECTDATA keyboardBuffer[ KEYBOARD_BUFFERSIZE ];
/* Device State Buffers */
DIJOYSTATE2 js;
UInt8 keybuffer[ 256 ];
UInt8 keystatebuffer[ 256 ];
UInt32 keyModState;
DWORD dwElements;
/* context event callbacks */
TInputCallbacks callbacks;
};
typedef struct SDI8Data TDI8Data;
/*-------------------------------------------------------------------------//
// //
// UTILITIES //
// //
//-------------------------------------------------------------------------*/
HRESULT InitDI8( TDI8Data* data );
void ShutdownDI8( TDI8Data* data );
BOOL __stdcall EnumAxesCallback( const DIDEVICEOBJECTINSTANCE* pdidoi, VOID* pContext );
BOOL __stdcall EnumJoysticksCallback( const DIDEVICEINSTANCE* pdidInstance, VOID* pContext );
const char*
GetArgListItem( const int argc ,
const char** argv ,
const char* key )
{
int i;
for ( i=0; i<argc-1; ++i )
{
if ( strcmp( argv[ i ], key ) == 0 )
{
return argv[ i+1 ];
}
++i;
}
return 0;
}
/*--------------------------------------------------------------------------*/
UInt32
ParseArgListItemUInt32( const int argc ,
const char** argv ,
const char* key )
{
const char* value = GetArgListItem( argc, argv, key );
if ( NULL != value )
{
UInt32 result = 0UL;
sscanf( value, "%d", &result );
return result;
}
return 0;
}
/*--------------------------------------------------------------------------*/
void*
ParseArgListItemPointer( const int argc ,
const char** argv ,
const char* key )
{
const char* value = GetArgListItem( argc, argv, key );
if ( NULL != value )
{
void* result = NULL;
sscanf( value, "%p", &result );
return result;
}
return 0;
}
/*---------------------------------------------------------------------------*/
BOOL __stdcall
EnumAxesCallback( const DIDEVICEOBJECTINSTANCE* pdidoi ,
VOID* pContext )
{
TDI8Data* data = (TDI8Data*) pContext;
DIPROPRANGE diprg;
diprg.diph.dwSize = sizeof(DIPROPRANGE);
diprg.diph.dwHeaderSize = sizeof(DIPROPHEADER);
diprg.diph.dwHow = DIPH_BYID;
diprg.diph.dwObj = pdidoi->dwType; // Specify the enumerated axis
diprg.lMin = -1000;
diprg.lMax = +1000;
// Set the range for the axis
if( FAILED( data->pDIJoy->SetProperty( DIPROP_RANGE, &diprg.diph ) ) )
{
return DIENUM_STOP;
}
return DIENUM_CONTINUE;
}
/*---------------------------------------------------------------------------*/
BOOL __stdcall
EnumJoysticksCallback( const DIDEVICEINSTANCE* pdidInstance ,
VOID* pContext )
{
TDI8Data* data = (TDI8Data*) pContext;
HRESULT hr;
hr = data->pDI->CreateDevice( pdidInstance->guidInstance, &data->pDIJoy, NULL );
if ( FAILED( hr ) )
{
return DIENUM_CONTINUE;
}
return DIENUM_STOP;
}
/*---------------------------------------------------------------------------*/
HRESULT
InitDI8( TDI8Data* data )
{
DIPROPDWORD dipdw;
dipdw.diph.dwSize = sizeof(DIPROPDWORD);
dipdw.diph.dwHeaderSize = sizeof(DIPROPHEADER);
dipdw.diph.dwObj = 0;
dipdw.diph.dwHow = DIPH_DEVICE;
dipdw.dwData = MOUSE_BUFFERSIZE;
/* Create The DI Object */
if( DI_OK != DirectInput8Create( data->hInstance ,
DIRECTINPUT_VERSION ,
((REFIID)IID_IDirectInput8) ,
((void**)&data->pDI) ,
NULL ) )
{
return E_FAIL;
}
/* Set up keyboard input */
if( FAILED( data->pDI->CreateDevice( GUID_SysKeyboard ,
&data->pDIKeybrd ,
NULL ) ) )
{
return E_FAIL;
}
if( FAILED( data->pDIKeybrd->SetDataFormat( &c_dfDIKeyboard ) ) )
{
return E_FAIL;
}
dipdw.dwData = KEYBOARD_BUFFERSIZE;
if( FAILED( data->pDIKeybrd->SetProperty( DIPROP_BUFFERSIZE, &dipdw.diph ) ) )
{
return E_FAIL;
}
if( FAILED( data->pDIKeybrd->SetCooperativeLevel( data->hWnd ,
DISCL_FOREGROUND | DISCL_NONEXCLUSIVE ) ) )
{
return E_FAIL;
}
if ( data->pDIKeybrd )
{
data->pDIKeybrd->Acquire();
}
/* Set up mouse input */
if( FAILED( data->pDI->CreateDevice( GUID_SysMouse ,
&data->pDIMouse ,
NULL ) ) )
{
return E_FAIL;
}
if( FAILED( data->pDIMouse->SetDataFormat( &c_dfDIMouse2 ) ) )
{
return E_FAIL;
}
dipdw.dwData = MOUSE_BUFFERSIZE;
if( FAILED( data->pDIMouse->SetProperty( DIPROP_BUFFERSIZE, &dipdw.diph ) ) )
{
return E_FAIL;
}
if( FAILED( data->pDIMouse->SetCooperativeLevel( data->hWnd ,
DISCL_FOREGROUND | DISCL_EXCLUSIVE ) ) )
{
return E_FAIL;
}
data->hMouse = CreateEvent( 0, 0, 0, 0 );
if ( data->hMouse == NULL )
{
ShutdownDI8( data );
return 0;
}
data->hr = data->pDIMouse->SetEventNotification( data->hMouse );
if ( FAILED( data->hr ) )
{
ShutdownDI8( data );
return 0;
}
if ( FAILED( data->hr ) )
{
ShutdownDI8( data );
return 0;
}
if ( data->pDIMouse )
{
data->pDIMouse->Acquire();
}
/*Set up Joystick input (Only the first joy) */
/*
if( FAILED( data->pDI->EnumDevices( DI8DEVCLASS_GAMECTRL ,
EnumJoysticksCallback ,
(VOID*) data ,
DIEDFL_ATTACHEDONLY ) ) )
{
return E_FAIL;
}
if( FAILED( data->pDIJoy->SetDataFormat( &c_dfDIJoystick2 ) ) )
{
return E_FAIL;
}
if( FAILED( data->pDIJoy->SetCooperativeLevel( data->hWnd ,
DISCL_EXCLUSIVE | DISCL_FOREGROUND ) ) )
{
return E_FAIL;
}
data->DIDevCaps.dwSize = sizeof( DIDEVCAPS );
if ( FAILED( data->pDIJoy->GetCapabilities( &data->DIDevCaps ) ) )
{
return E_FAIL;
}
if ( FAILED( data->pDIJoy->EnumObjects( EnumAxesCallback ,
(VOID*) data ,
DIDFT_AXIS ) ) )
{
return E_FAIL;
}
if( data->pDIJoy )
{
data->pDIJoy->Acquire();
}
*/
return S_OK;
}
/*---------------------------------------------------------------------------*/
void
ShutdownDI8( TDI8Data* data )
{
if ( data->pDI )
{
if ( data->pDIKeybrd )
{
data->pDIKeybrd->Unacquire();
data->pDIKeybrd->Release();
data->pDIKeybrd = NULL;
}
if ( data->pDIMouse )
{
data->pDIMouse->Unacquire();
data->pDIMouse->Release();
data->pDIMouse = NULL;
}
if ( data->pDIJoy )
{
data->pDIJoy->Unacquire();
data->pDIJoy->Release();
data->pDIJoy = NULL;
}
data->pDI->Release();
data->pDI = NULL;
}
}
/*---------------------------------------------------------------------------*/
HRESULT
ProcessMouseDI8( TDI8Data* data )
{
DIDEVICEOBJECTDATA* eventptr;
UInt32 i=0;
data->hr = data->pDIMouse->Acquire();
/* Check for mouse input and fill buffer */
DWORD dwItems( MOUSE_BUFFERSIZE );
data->hr = data->pDIMouse->GetDeviceData( sizeof( DIDEVICEOBJECTDATA ) ,
&data->mouseBuffer[ 0 ] , /* our event buffer */
&dwItems , /* in the buffer size, out the read count */
0 ); /* remove items when read */
if ( data->hr == DIERR_INPUTLOST )
{
/* aquire the mouse, we may have lost our connection since the last call */
data->hr = data->pDIMouse->Acquire();
/* Check for mouse input and fill buffer */
DWORD dwItems( MOUSE_BUFFERSIZE );
data->hr = data->pDIMouse->GetDeviceData( sizeof( DIDEVICEOBJECTDATA ) ,
&data->mouseBuffer[ 0 ] , /* our event buffer */
&dwItems , /* in the buffer size, out the read count */
0 ); /* remove items when read */
}
if ( SUCCEEDED( data->hr ) )
{
for ( i=0; i<dwItems; ++i )
{
eventptr = &data->mouseBuffer[ i ];
switch ( eventptr->dwOfs )
{
case DIMOFS_X :
{
data->pMousePos->x += eventptr->dwData;
data->callbacks.onMouseMove( data->callbacks.userData, i, data->pMousePos->x, data->pMousePos->y, eventptr->dwData, 0 );
break;
}
case DIMOFS_Y :
{
data->pMousePos->y += eventptr->dwData;
data->callbacks.onMouseMove( data->callbacks.userData, i, data->pMousePos->x, data->pMousePos->y, 0, eventptr->dwData );
break;
}
case DIMOFS_Z : /* mousewheel */
{
Int32 delta( 0 );
if ( BUTTONBOOL( eventptr->dwData ) )
{
++data->mouseWheelVar;
delta = 1;
}
else
{
--data->mouseWheelVar;
delta = -1;
}
data->callbacks.onMouseVarChanged( data->callbacks.userData, i, 0, data->mouseWheelVar, delta );
}
case DIMOFS_BUTTON0 :
case DIMOFS_BUTTON1 :
case DIMOFS_BUTTON2 :
case DIMOFS_BUTTON3 :
case DIMOFS_BUTTON4 :
case DIMOFS_BUTTON5 :
case DIMOFS_BUTTON6 :
case DIMOFS_BUTTON7 :
{
if ( BUTTONBOOL( eventptr->dwData ) )
{
data->callbacks.onMouseButtonDown( data->callbacks.userData, i, BUTTONINDEX( (int) eventptr->dwOfs ) );
}
else
{
data->callbacks.onMouseButtonUp( data->callbacks.userData, i, BUTTONINDEX( (int) eventptr->dwOfs ) );
}
}
}
}
return S_OK;
}
else
{
if ( data->hr == DIERR_INPUTLOST )
{
data->hr = data->pDIMouse->Acquire();
}
return E_FAIL;
}
}
/*---------------------------------------------------------------------------*/
/**
* Utility function for converting from virtual DI key values into
* keyboard scancodes.
*
* @return 0 on failure 1 on success
*/
UInt32
MapDIKeyToScancode( UINT keyCode ,
UINT *scanCode )
{
HKL hklKeyboardLayout = GetKeyboardLayout(0); // 0 means current thread
// This seemingly cannot fail
// If this value is cached then the application must respond to WM_INPUTLANGCHANGE
/*
* Notes on second arg beeing 0:
* uCode is a virtual-key code and is translated into a scan code.
* If it is a virtual-key code that does not distinguish between left- and right-hand keys,
* the left-hand scan code is returned. If there is no translation, the function returns 0.
*/
UINT uiScanCode = MapVirtualKeyEx( keyCode ,
0 , // Convert DIK_ code to scan code
hklKeyboardLayout );
if( 0 == uiScanCode )
{
// Error converting to a scancode
return 0;
}
*scanCode = uiScanCode;
return 1;
}
/*---------------------------------------------------------------------------*/
UInt32
MapScanCodeToChar( UINT scanCode ,
BYTE *charCode )
{
HKL hklKeyboardLayout = GetKeyboardLayout(0); // 0 means current thread
// This seemingly cannot fail
// If this value is cached then the application must respond to WM_INPUTLANGCHANGE
/*
* Notes on second arg beeing 2:
* uCode is a virtual-key code and is translated into an unshifted character value in
* the low-order word of the return value. Dead keys (diacritics) are indicated by
* setting the top bit of the return value. If there is no translation, the function returns 0.
*/
UINT uiCharCode = MapVirtualKeyEx( scanCode ,
2 , // Convert scan code to char code
hklKeyboardLayout );
if( 0 == uiCharCode )
{
// Error converting to a char
return 0;
}
*charCode = ((BYTE)uiCharCode);
return 1;
}
/*---------------------------------------------------------------------------*/
HRESULT
ProcessKeyboardDI8( TDI8Data* data )
{
DIDEVICEOBJECTDATA* eventptr;
UInt32 i=0;
/* Check for keyboard input and fill buffer */
DWORD dwItems( KEYBOARD_BUFFERSIZE );
data->hr = data->pDIKeybrd->GetDeviceData( sizeof( DIDEVICEOBJECTDATA ) ,
&data->keyboardBuffer[ 0 ] , /* our event buffer */
&dwItems , /* in the buffer size, out the read count */
0 ); /* remove items when read */
data->hr = data->pDIKeybrd->Acquire();
if ( SUCCEEDED( data->hr ) )
{
for ( i=0; i<dwItems; ++i )
{
UINT scanCode(0);
eventptr = &data->keyboardBuffer[ i ];
MapDIKeyToScancode( eventptr->dwOfs, &scanCode );
if ( KEYBOOL( eventptr->dwData ) )
{
// data->callbacks.onKeyboardKeyDown( data->callbacks.userData, scanCode );
/* UINT scanCode(0);
BYTE charCode(0);
if ( 0 != MapDIKeyToScancode( eventptr->dwOfs, &scanCode ) )
{
if ( 0 != MapScanCodeToChar( scanCode, &charCode ) )
{
data->callbacks.onKeyboardKeyDown( data->callbacks.userData, charCode );
}
} */
data->callbacks.onKeyboardKeyDown( data->callbacks.userData, 0, (KeyCode)scanCode, data->keyModState );
}
else
{
// UINT scanCode(0);
// MapDIKeyToScancode( eventptr->dwOfs, &scanCode );
// data->callbacks.onKeyboardKeyUp( data->callbacks.userData, scanCode );
data->callbacks.onKeyboardKeyUp( data->callbacks.userData, 0, (KeyCode)scanCode, data->keyModState );
}
}
return S_OK;
}
else
{
if ( data->hr == DIERR_INPUTLOST )
{
// we lost contact with the device, attempt to recover
data->hr = data->pDIKeybrd->Acquire();
while( data->hr == DIERR_INPUTLOST )
{
data->hr = data->pDIKeybrd->Acquire();
}
}
else
if ( data->hr == DI_BUFFEROVERFLOW )
{
/* Check for keyboard input and fill buffer */
UInt8 keystatebuffer[ 256 ];
data->hr = data->pDIKeybrd->GetDeviceState( 256 ,
(LPVOID) &keystatebuffer );
if ( SUCCEEDED( data->hr ) )
{
/* compare the current state with our buffered state and attempt to compensate event wise */
UInt32 i;
for ( i=0; i<256; ++i )
{
if ( keystatebuffer[ i ] != data->keystatebuffer[ i ] )
{
if ( KEYBOOL( keystatebuffer[ i ] ) )
{
data->keybuffer[ i ] = 1;
data->callbacks.onKeyboardKeyDown( data->callbacks.userData, 0, (KeyCode)i, data->keyModState );
}
else
{
data->keybuffer[ i ] = 0;
data->callbacks.onKeyboardKeyUp( data->callbacks.userData, 0, (KeyCode)i, data->keyModState );
}
}
}
}
}
return E_FAIL;
}
}
/*---------------------------------------------------------------------------*/
HRESULT
ProcessJoystickDI8( TDI8Data* data )
{
/* Get joystick state and fill buffer */
/* if( FAILED( data->pDIJoy->Poll() ) )
{
while( data->pDIJoy->Acquire() == DIERR_INPUTLOST )
{}
return E_FAIL;
}
if ( FAILED( data->pDIJoy->GetDeviceState( sizeof(DIJOYSTATE2) ,
&data->js ) ) )
{
return E_FAIL;
} */
return S_OK;
}
/*---------------------------------------------------------------------------*/
UInt32 GUCEF_PLUGIN_CALLSPEC_PREFIX
INPUTDRIVERPLUG_Init( void** plugdata ,
const char*** args ) GUCEF_PLUGIN_CALLSPEC_SUFFIX
{
*plugdata = NULL;
return 1;
}
/*---------------------------------------------------------------------------*/
UInt32 GUCEF_PLUGIN_CALLSPEC_PREFIX
INPUTDRIVERPLUG_Shutdown( void* plugdata ) GUCEF_PLUGIN_CALLSPEC_SUFFIX
{
return 1;
}
/*---------------------------------------------------------------------------*/
const char* GUCEF_PLUGIN_CALLSPEC_PREFIX
INPUTDRIVERPLUG_Name( void* plugdata ) GUCEF_PLUGIN_CALLSPEC_SUFFIX
{
return DRIVER_NAME;
}
/*---------------------------------------------------------------------------*/
const char* GUCEF_PLUGIN_CALLSPEC_PREFIX
INPUTDRIVERPLUG_Copyright( void* plugdata ) GUCEF_PLUGIN_CALLSPEC_SUFFIX
{
return DRIVER_COPYRIGHT;
}
/*---------------------------------------------------------------------------*/
const TVersion* GUCEF_PLUGIN_CALLSPEC_PREFIX
INPUTDRIVERPLUG_Version( void* plugdata ) GUCEF_PLUGIN_CALLSPEC_SUFFIX
{
return &version;
}
/*---------------------------------------------------------------------------*/
UInt32 GUCEF_PLUGIN_CALLSPEC_PREFIX
INPUTDRIVERPLUG_Update( void* plugdata ,
void* contextdata ) GUCEF_PLUGIN_CALLSPEC_SUFFIX
{
TDI8Data* data = (TDI8Data*) contextdata;
if ( FAILED( ProcessMouseDI8( data ) ) ||
FAILED( ProcessKeyboardDI8( data ) ) ||
FAILED( ProcessJoystickDI8( data ) ) )
{
return 0;
}
return 1;
}
/*---------------------------------------------------------------------------*/
UInt32 GUCEF_PLUGIN_CALLSPEC_PREFIX
INPUTDRIVERPLUG_CreateContext( void* plugdata ,
void** contextdata ,
int argc ,
const char** argv ,
const TInputCallbacks* callbacks ) GUCEF_PLUGIN_CALLSPEC_SUFFIX
{
TDI8Data* data = (TDI8Data*) malloc( sizeof( TDI8Data ) );
*contextdata = data;
#pragma warning( disable: 4312 )
data->hWnd = (HWND) ParseArgListItemUInt32( argc, argv, "HWND" );
data->hInstance = (HINSTANCE) ParseArgListItemUInt32( argc, argv, "HINSTANCE" );
data->pDI = NULL;
data->pDIKeybrd = NULL;
data->pDIMouse = NULL;
data->pDIJoy = NULL;
data->pMousePos = (POINT*) malloc( sizeof( POINT ) );
data->pMousePos->x = 0l;
data->pMousePos->y = 0l;
data->mouseWheelVar = 0;
data->pHotSpot = (POINT*) malloc( sizeof( POINT ) );
data->pHotSpot->x = 0l;
data->pHotSpot->y = 0l;
data->dwElements = 16;
data->callbacks = *callbacks;
if ( FAILED( InitDI8( data ) ) )
{
free( data );
*contextdata = NULL;
return 0;
}
// initialize the keyboard key buffers
memset( data->keystatebuffer, 0, 256 );
memset( data->keybuffer, 0, 256 );
INPUTDRIVERPLUG_GetKeyBoardKeyStates( plugdata, data );
return 1;
}
/*---------------------------------------------------------------------------*/
UInt32 GUCEF_PLUGIN_CALLSPEC_PREFIX
INPUTDRIVERPLUG_DestroyContext( void* plugdata ,
void* contextdata ) GUCEF_PLUGIN_CALLSPEC_SUFFIX
{
TDI8Data* data = (TDI8Data*) contextdata;
ShutdownDI8( data );
free( data->pMousePos );
free( data->pHotSpot );
free( data );
return 1;
}
/*---------------------------------------------------------------------------*/
UInt32 GUCEF_PLUGIN_CALLSPEC_PREFIX
INPUTDRIVERPLUG_GetMousePos( void* plugdata ,
void* contextdata ,
UInt32* xpos ,
UInt32* ypos ) GUCEF_PLUGIN_CALLSPEC_SUFFIX
{
TDI8Data* data = (TDI8Data*) contextdata;
*xpos = data->pMousePos->x;
*ypos = data->pMousePos->y;
/* normalized window coords:
RECT rect;
GetWindowRect( data->hWnd , &rect );
*xpos = 1.0f - ( rect.right / data->pMousePos->x );
*ypos = 1.0f - ( rect.bottom / data->pMousePos->y ); */
return 1;
}
/*---------------------------------------------------------------------------*/
UInt8* GUCEF_PLUGIN_CALLSPEC_PREFIX
INPUTDRIVERPLUG_GetKeyBoardKeyStates( void* plugdata ,
void* contextdata ) GUCEF_PLUGIN_CALLSPEC_SUFFIX
{
TDI8Data* data = (TDI8Data*) contextdata;
/* Check for keyboard input and fill buffer */
data->hr = data->pDIKeybrd->GetDeviceState( 256 ,
(LPVOID) &data->keystatebuffer );
if ( FAILED( data->hr ) )
{
data->pDIKeybrd->Acquire();
return NULL;
}
for ( UInt32 i=0; i<256; ++i )
{
// convert binary mask into a simple 0 or 1 flag,
// this assures independance of the DX implementation.
data->keybuffer[ i ] = KEYBOOL( data->keystatebuffer[ i ] );
}
return data->keybuffer;
}
/*---------------------------------------------------------------------------*/
UInt32 GUCEF_PLUGIN_CALLSPEC_PREFIX
INPUTDRIVERPLUG_GetMouseButtonPressedState( void* plugdata ,
void* contextdata ,
const UInt32 buttonindex ) GUCEF_PLUGIN_CALLSPEC_SUFFIX
{
if ( buttonindex < 8 )
{
TDI8Data* data = (TDI8Data*) contextdata;
DIMOUSESTATE2 dims2;
ZeroMemory( &dims2, sizeof(DIMOUSESTATE2) );
data->hr = data->pDIMouse->GetDeviceState( sizeof(DIMOUSESTATE2), &dims2 );
if ( FAILED( data->hr ) )
{
data->pDIMouse->Acquire();
return 0;
}
return dims2.rgbButtons[ buttonindex ];
}
return FALSE;
}
/*---------------------------------------------------------------------------*/
UInt32 GUCEF_PLUGIN_CALLSPEC_PREFIX
INPUTDRIVERPLUG_GetKeyboardKeyPressedState( void* plugdata ,
void* contextdata ,
const UInt32 keyindex ) GUCEF_PLUGIN_CALLSPEC_SUFFIX
{
if ( keyindex < 256 )
{
return ( (TDI8Data*) contextdata )->keybuffer[ keyindex ] != 0;
}
return 0;
}
/*---------------------------------------------------------------------------*/
UInt32 GUCEF_PLUGIN_CALLSPEC_PREFIX
INPUTDRIVERPLUG_GetDeviceBoolState( void* plugdata ,
void* contextdata ,
const UInt32 deviceid ,
const UInt32 stateindex ) GUCEF_PLUGIN_CALLSPEC_SUFFIX
{
return 1;
}
/*---------------------------------------------------------------------------*/
UInt32 GUCEF_PLUGIN_CALLSPEC_PREFIX
INPUTDRIVERPLUG_GetDeviceVarState( void* plugdata ,
void* contextdata ,
const UInt32 deviceid ,
const UInt32 stateindex ) GUCEF_PLUGIN_CALLSPEC_SUFFIX
{
return 1;
}
/*-------------------------------------------------------------------------//
// //
// NAMESPACE //
// //
//-------------------------------------------------------------------------*/
#ifdef __cplusplus
}; /* namespace INPUT */
}; /* namespace GUCEF */
#endif /* __cplusplus */
/*-------------------------------------------------------------------------*/
/*
-----------------------------
IDirectInputDevice8::GetDeviceData Method
Retrieves buffered data from the device.
Syntax
HRESULT GetDeviceData(
DWORD cbObjectData,
LPDIDEVICEOBJECTDATA rgdod,
LPDWORD pdwInOut,
DWORD dwFlags
);
Parameters
cbObjectData
Size of the DIDEVICEOBJECTDATA structure, in bytes.
rgdod
Array of DIDEVICEOBJECTDATA structures to receive the buffered data. The number of elements in this array must be equal to the value of the pdwInOut parameter. If this parameter is NULL, the buffered data is not stored anywhere, but all other side effects take place.
pdwInOut
On entry, the number of elements in the array pointed to by the rgdod parameter. On exit, the number of elements actually obtained.
dwFlags
Flags that control the manner in which data is obtained. This value can be 0 or the following flag.
DIGDD_PEEK
Do not remove the items from the buffer. A subsequent IDirectInputDevice8::GetDeviceData call will read the same data. Normally, data is removed from the buffer after it is read.
Return Value
If the method succeeds, the return value is DI_OK or DI_BUFFEROVERFLOW.
If the method fails, the return value can be one of the following error values.
DIERR_INPUTLOST Access to the input device has been lost. It must be reacquired.
DIERR_INVALIDPARAM An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard Component Object Model (COM) return value.
DIERR_NOTACQUIRED The operation cannot be performed unless the device is acquired.
DIERR_NOTBUFFERED The device is not buffered. Set the DIPROP_BUFFERSIZE property to enable buffering.
DIERR_NOTINITIALIZED The object has not been initialized.
--------------------------------
IDirectInputDevice8::Acquire Method
Obtains access to the input device.
Syntax
HRESULT Acquire(VOID);
Return Value
If the method succeeds, the return value is DI_OK, or S_FALSE if the device was already acquired.
If the method fails, the return value can be one of the following error values.
DIERR_INVALIDPARAM An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard Component Object Model (COM) return value.
DIERR_NOTINITIALIZED The object has not been initialized.
DIERR_OTHERAPPHASPRIO Another application has a higher priority level, preventing this call from succeeding. This value is equal to the E_ACCESSDENIED standard COM return value. This error can be returned when an application has only foreground access to a device but is attempting to acquire the device while in the background.
Remarks
Before a device can be acquired, a data format must be set by using the IDirectInputDevice8::SetDataFormat method or IDirectInputDevice8::SetActionMap method. If the data format has not been set, IDirectInputDevice8::Acquire returns DIERR_INVALIDPARAM.
Devices must be acquired before calling the IDirectInputDevice8::GetDeviceState or IDirectInputDevice8::GetDeviceData methods for that device.
Device acquisition does not use a reference count. Therefore, if an application calls the IDirectInputDevice8::Acquire method twice, then calls the IDirectInputDevice8::Unacquire method once, the device is unacquired.
If IDirectInputDevice8::BuildActionMap succeeds but no actions have been mapped, a subsequent call to IDirectInputDevice8::SetActionMap will return DI_OK but a call to IDirectInputDevice8::Acquire will fail with DIERR_INVALIDPARAM.
*/ | [
"liberatorusa@9712d391-321d-0410-84f4-d6a0ebf28296"
] | liberatorusa@9712d391-321d-0410-84f4-d6a0ebf28296 |
109417d8547ae2b52fa4e6bbf35aaa9d4d985814 | 22e6cc55fad6290d964014f6be948cbff0270ae6 | /3 lab/pugixml.cpp | 244e0dd2f7125297394f1c47fa53381cf20bef95 | [] | no_license | georgesh08/2sem-labs | eff0b1e16b91d0ae7013b69d29eeb8246a5ca431 | e3f2a61a974e65d22f4d68f77deae1dbcbc7afc5 | refs/heads/master | 2023-06-03T14:34:48.630082 | 2021-06-23T09:32:06 | 2021-06-23T09:32:06 | 343,753,466 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 470,839 | cpp | /**
* pugixml parser - version 1.11
* --------------------------------------------------------
* Copyright (C) 2006-2020, by Arseny Kapoulkine (arseny.kapoulkine@gmail.com)
* Report bugs and download new versions at https://pugixml.org/
*
* This library is distributed under the MIT License. See notice at the end
* of this file.
*
* This work is based on the pugxml parser, which is:
* Copyright (C) 2003, by Kristen Wegner (kristen@tima.net)
*/
#ifndef SOURCE_PUGIXML_CPP
#define SOURCE_PUGIXML_CPP
#include "pugixml.hpp"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <limits.h>
#ifdef PUGIXML_WCHAR_MODE
# include <wchar.h>
#endif
#ifndef PUGIXML_NO_XPATH
# include <math.h>
# include <float.h>
#endif
#ifndef PUGIXML_NO_STL
# include <istream>
# include <ostream>
# include <string>
#endif
// For placement new
#include <new>
#ifdef _MSC_VER
# pragma warning(push)
# pragma warning(disable: 4127) // conditional expression is constant
# pragma warning(disable: 4324) // structure was padded due to __declspec(align())
# pragma warning(disable: 4702) // unreachable code
# pragma warning(disable: 4996) // this function or variable may be unsafe
#endif
#if defined(_MSC_VER) && defined(__c2__)
# pragma clang diagnostic push
# pragma clang diagnostic ignored "-Wdeprecated" // this function or variable may be unsafe
#endif
#ifdef __INTEL_COMPILER
# pragma warning(disable: 177) // function was declared but never referenced
# pragma warning(disable: 279) // controlling expression is constant
# pragma warning(disable: 1478 1786) // function was declared "deprecated"
# pragma warning(disable: 1684) // conversion from pointer to same-sized integral type
#endif
#if defined(__BORLANDC__) && defined(PUGIXML_HEADER_ONLY)
# pragma warn -8080 // symbol is declared but never used; disabling this inside push/pop bracket does not make the warning go away
#endif
#ifdef __BORLANDC__
# pragma option push
# pragma warn -8008 // condition is always false
# pragma warn -8066 // unreachable code
#endif
#ifdef __SNC__
// Using diag_push/diag_pop does not disable the warnings inside templates due to a compiler bug
# pragma diag_suppress=178 // function was declared but never referenced
# pragma diag_suppress=237 // controlling expression is constant
#endif
#ifdef __TI_COMPILER_VERSION__
# pragma diag_suppress 179 // function was declared but never referenced
#endif
// Inlining controls
#if defined(_MSC_VER) && _MSC_VER >= 1300
# define PUGI__NO_INLINE __declspec(noinline)
#elif defined(__GNUC__)
# define PUGI__NO_INLINE __attribute__((noinline))
#else
# define PUGI__NO_INLINE
#endif
// Branch weight controls
#if defined(__GNUC__) && !defined(__c2__)
# define PUGI__UNLIKELY(cond) __builtin_expect(cond, 0)
#else
# define PUGI__UNLIKELY(cond) (cond)
#endif
// Simple static assertion
#define PUGI__STATIC_ASSERT(cond) { static const char condition_failed[(cond) ? 1 : -1] = {0}; (void)condition_failed[0]; }
// Digital Mars C++ bug workaround for passing char loaded from memory via stack
#ifdef __DMC__
# define PUGI__DMC_VOLATILE volatile
#else
# define PUGI__DMC_VOLATILE
#endif
// Integer sanitizer workaround; we only apply this for clang since gcc8 has no_sanitize but not unsigned-integer-overflow and produces "attribute directive ignored" warnings
#if defined(__clang__) && defined(__has_attribute)
# if __has_attribute(no_sanitize)
# define PUGI__UNSIGNED_OVERFLOW __attribute__((no_sanitize("unsigned-integer-overflow")))
# else
# define PUGI__UNSIGNED_OVERFLOW
# endif
#else
# define PUGI__UNSIGNED_OVERFLOW
#endif
// Borland C++ bug workaround for not defining ::memcpy depending on header include order (can't always use std::memcpy because some compilers don't have it at all)
#if defined(__BORLANDC__) && !defined(__MEM_H_USING_LIST)
using std::memcpy;
using std::memmove;
using std::memset;
#endif
// Some MinGW/GCC versions have headers that erroneously omit LLONG_MIN/LLONG_MAX/ULLONG_MAX definitions from limits.h in some configurations
#if defined(PUGIXML_HAS_LONG_LONG) && defined(__GNUC__) && !defined(LLONG_MAX) && !defined(LLONG_MIN) && !defined(ULLONG_MAX)
# define LLONG_MIN (-LLONG_MAX - 1LL)
# define LLONG_MAX __LONG_LONG_MAX__
# define ULLONG_MAX (LLONG_MAX * 2ULL + 1ULL)
#endif
// In some environments MSVC is a compiler but the CRT lacks certain MSVC-specific features
#if defined(_MSC_VER) && !defined(__S3E__)
# define PUGI__MSVC_CRT_VERSION _MSC_VER
#endif
// Not all platforms have snprintf; we define a wrapper that uses snprintf if possible. This only works with buffers with a known size.
#if __cplusplus >= 201103
# define PUGI__SNPRINTF(buf, ...) snprintf(buf, sizeof(buf), __VA_ARGS__)
#elif defined(PUGI__MSVC_CRT_VERSION) && PUGI__MSVC_CRT_VERSION >= 1400
# define PUGI__SNPRINTF(buf, ...) _snprintf_s(buf, _countof(buf), _TRUNCATE, __VA_ARGS__)
#else
# define PUGI__SNPRINTF sprintf
#endif
// We put implementation details into an anonymous namespace in source mode, but have to keep it in non-anonymous namespace in header-only mode to prevent binary bloat.
#ifdef PUGIXML_HEADER_ONLY
# define PUGI__NS_BEGIN namespace pugi { namespace impl {
# define PUGI__NS_END } }
# define PUGI__FN inline
# define PUGI__FN_NO_INLINE inline
#else
# if defined(_MSC_VER) && _MSC_VER < 1300 // MSVC6 seems to have an amusing bug with anonymous namespaces inside namespaces
# define PUGI__NS_BEGIN namespace pugi { namespace impl {
# define PUGI__NS_END } }
# else
# define PUGI__NS_BEGIN namespace pugi { namespace impl { namespace {
# define PUGI__NS_END } } }
# endif
# define PUGI__FN
# define PUGI__FN_NO_INLINE PUGI__NO_INLINE
#endif
// uintptr_t
#if (defined(_MSC_VER) && _MSC_VER < 1600) || (defined(__BORLANDC__) && __BORLANDC__ < 0x561)
namespace pugi
{
# ifndef _UINTPTR_T_DEFINED
typedef size_t uintptr_t;
# endif
typedef unsigned __int8 uint8_t;
typedef unsigned __int16 uint16_t;
typedef unsigned __int32 uint32_t;
}
#else
# include <stdint.h>
#endif
// Memory allocation
PUGI__NS_BEGIN
PUGI__FN void* default_allocate(size_t size)
{
return malloc(size);
}
PUGI__FN void default_deallocate(void* ptr)
{
free(ptr);
}
template <typename T>
struct xml_memory_management_function_storage
{
static allocation_function allocate;
static deallocation_function deallocate;
};
// Global allocation functions are stored in class statics so that in header mode linker deduplicates them
// Without a template<> we'll get multiple definitions of the same static
template <typename T> allocation_function xml_memory_management_function_storage<T>::allocate = default_allocate;
template <typename T> deallocation_function xml_memory_management_function_storage<T>::deallocate = default_deallocate;
typedef xml_memory_management_function_storage<int> xml_memory;
PUGI__NS_END
// String utilities
PUGI__NS_BEGIN
// Get string length
PUGI__FN size_t strlength(const char_t* s)
{
assert(s);
#ifdef PUGIXML_WCHAR_MODE
return wcslen(s);
#else
return strlen(s);
#endif
}
// Compare two strings
PUGI__FN bool strequal(const char_t* src, const char_t* dst)
{
assert(src && dst);
#ifdef PUGIXML_WCHAR_MODE
return wcscmp(src, dst) == 0;
#else
return strcmp(src, dst) == 0;
#endif
}
// Compare lhs with [rhs_begin, rhs_end)
PUGI__FN bool strequalrange(const char_t* lhs, const char_t* rhs, size_t count)
{
for (size_t i = 0; i < count; ++i)
if (lhs[i] != rhs[i])
return false;
return lhs[count] == 0;
}
// Get length of wide string, even if CRT lacks wide character support
PUGI__FN size_t strlength_wide(const wchar_t* s)
{
assert(s);
#ifdef PUGIXML_WCHAR_MODE
return wcslen(s);
#else
const wchar_t* end = s;
while (*end) end++;
return static_cast<size_t>(end - s);
#endif
}
PUGI__NS_END
// auto_ptr-like object for exception recovery
PUGI__NS_BEGIN
template <typename T> struct auto_deleter
{
typedef void (*D)(T*);
T* data;
D deleter;
auto_deleter(T* data_, D deleter_): data(data_), deleter(deleter_)
{
}
~auto_deleter()
{
if (data) deleter(data);
}
T* release()
{
T* result = data;
data = 0;
return result;
}
};
PUGI__NS_END
#ifdef PUGIXML_COMPACT
PUGI__NS_BEGIN
class compact_hash_table
{
public:
compact_hash_table(): _items(0), _capacity(0), _count(0)
{
}
void clear()
{
if (_items)
{
xml_memory::deallocate(_items);
_items = 0;
_capacity = 0;
_count = 0;
}
}
void* find(const void* key)
{
if (_capacity == 0) return 0;
item_t* item = get_item(key);
assert(item);
assert(item->key == key || (item->key == 0 && item->value == 0));
return item->value;
}
void insert(const void* key, void* value)
{
assert(_capacity != 0 && _count < _capacity - _capacity / 4);
item_t* item = get_item(key);
assert(item);
if (item->key == 0)
{
_count++;
item->key = key;
}
item->value = value;
}
bool reserve(size_t extra = 16)
{
if (_count + extra >= _capacity - _capacity / 4)
return rehash(_count + extra);
return true;
}
private:
struct item_t
{
const void* key;
void* value;
};
item_t* _items;
size_t _capacity;
size_t _count;
bool rehash(size_t count);
item_t* get_item(const void* key)
{
assert(key);
assert(_capacity > 0);
size_t hashmod = _capacity - 1;
size_t bucket = hash(key) & hashmod;
for (size_t probe = 0; probe <= hashmod; ++probe)
{
item_t& probe_item = _items[bucket];
if (probe_item.key == key || probe_item.key == 0)
return &probe_item;
// hash collision, quadratic probing
bucket = (bucket + probe + 1) & hashmod;
}
assert(false && "Hash table is full"); // unreachable
return 0;
}
static PUGI__UNSIGNED_OVERFLOW unsigned int hash(const void* key)
{
unsigned int h = static_cast<unsigned int>(reinterpret_cast<uintptr_t>(key) & 0xffffffff);
// MurmurHash3 32-bit finalizer
h ^= h >> 16;
h *= 0x85ebca6bu;
h ^= h >> 13;
h *= 0xc2b2ae35u;
h ^= h >> 16;
return h;
}
};
PUGI__FN_NO_INLINE bool compact_hash_table::rehash(size_t count)
{
size_t capacity = 32;
while (count >= capacity - capacity / 4)
capacity *= 2;
compact_hash_table rt;
rt._capacity = capacity;
rt._items = static_cast<item_t*>(xml_memory::allocate(sizeof(item_t) * capacity));
if (!rt._items)
return false;
memset(rt._items, 0, sizeof(item_t) * capacity);
for (size_t i = 0; i < _capacity; ++i)
if (_items[i].key)
rt.insert(_items[i].key, _items[i].value);
if (_items)
xml_memory::deallocate(_items);
_capacity = capacity;
_items = rt._items;
assert(_count == rt._count);
return true;
}
PUGI__NS_END
#endif
PUGI__NS_BEGIN
#ifdef PUGIXML_COMPACT
static const uintptr_t xml_memory_block_alignment = 4;
#else
static const uintptr_t xml_memory_block_alignment = sizeof(void*);
#endif
// extra metadata bits
static const uintptr_t xml_memory_page_contents_shared_mask = 64;
static const uintptr_t xml_memory_page_name_allocated_mask = 32;
static const uintptr_t xml_memory_page_value_allocated_mask = 16;
static const uintptr_t xml_memory_page_type_mask = 15;
// combined masks for string uniqueness
static const uintptr_t xml_memory_page_name_allocated_or_shared_mask = xml_memory_page_name_allocated_mask | xml_memory_page_contents_shared_mask;
static const uintptr_t xml_memory_page_value_allocated_or_shared_mask = xml_memory_page_value_allocated_mask | xml_memory_page_contents_shared_mask;
#ifdef PUGIXML_COMPACT
#define PUGI__GETHEADER_IMPL(object, page, flags) // unused
#define PUGI__GETPAGE_IMPL(header) (header).get_page()
#else
#define PUGI__GETHEADER_IMPL(object, page, flags) (((reinterpret_cast<char*>(object) - reinterpret_cast<char*>(page)) << 8) | (flags))
// this macro casts pointers through void* to avoid 'cast increases required alignment of target type' warnings
#define PUGI__GETPAGE_IMPL(header) static_cast<impl::xml_memory_page*>(const_cast<void*>(static_cast<const void*>(reinterpret_cast<const char*>(&header) - (header >> 8))))
#endif
#define PUGI__GETPAGE(n) PUGI__GETPAGE_IMPL((n)->header)
#define PUGI__NODETYPE(n) static_cast<xml_node_type>((n)->header & impl::xml_memory_page_type_mask)
struct xml_allocator;
struct xml_memory_page
{
static xml_memory_page* construct(void* memory)
{
xml_memory_page* result = static_cast<xml_memory_page*>(memory);
result->allocator = 0;
result->prev = 0;
result->next = 0;
result->busy_size = 0;
result->freed_size = 0;
#ifdef PUGIXML_COMPACT
result->compact_string_base = 0;
result->compact_shared_parent = 0;
result->compact_page_marker = 0;
#endif
return result;
}
xml_allocator* allocator;
xml_memory_page* prev;
xml_memory_page* next;
size_t busy_size;
size_t freed_size;
#ifdef PUGIXML_COMPACT
char_t* compact_string_base;
void* compact_shared_parent;
uint32_t* compact_page_marker;
#endif
};
static const size_t xml_memory_page_size =
#ifdef PUGIXML_MEMORY_PAGE_SIZE
(PUGIXML_MEMORY_PAGE_SIZE)
#else
32768
#endif
- sizeof(xml_memory_page);
struct xml_memory_string_header
{
uint16_t page_offset; // offset from page->data
uint16_t full_size; // 0 if string occupies whole page
};
struct xml_allocator
{
xml_allocator(xml_memory_page* root): _root(root), _busy_size(root->busy_size)
{
#ifdef PUGIXML_COMPACT
_hash = 0;
#endif
}
xml_memory_page* allocate_page(size_t data_size)
{
size_t size = sizeof(xml_memory_page) + data_size;
// allocate block with some alignment, leaving memory for worst-case padding
void* memory = xml_memory::allocate(size);
if (!memory) return 0;
// prepare page structure
xml_memory_page* page = xml_memory_page::construct(memory);
assert(page);
page->allocator = _root->allocator;
return page;
}
static void deallocate_page(xml_memory_page* page)
{
xml_memory::deallocate(page);
}
void* allocate_memory_oob(size_t size, xml_memory_page*& out_page);
void* allocate_memory(size_t size, xml_memory_page*& out_page)
{
if (PUGI__UNLIKELY(_busy_size + size > xml_memory_page_size))
return allocate_memory_oob(size, out_page);
void* buf = reinterpret_cast<char*>(_root) + sizeof(xml_memory_page) + _busy_size;
_busy_size += size;
out_page = _root;
return buf;
}
#ifdef PUGIXML_COMPACT
void* allocate_object(size_t size, xml_memory_page*& out_page)
{
void* result = allocate_memory(size + sizeof(uint32_t), out_page);
if (!result) return 0;
// adjust for marker
ptrdiff_t offset = static_cast<char*>(result) - reinterpret_cast<char*>(out_page->compact_page_marker);
if (PUGI__UNLIKELY(static_cast<uintptr_t>(offset) >= 256 * xml_memory_block_alignment))
{
// insert new marker
uint32_t* marker = static_cast<uint32_t*>(result);
*marker = static_cast<uint32_t>(reinterpret_cast<char*>(marker) - reinterpret_cast<char*>(out_page));
out_page->compact_page_marker = marker;
// since we don't reuse the page space until we reallocate it, we can just pretend that we freed the marker block
// this will make sure deallocate_memory correctly tracks the size
out_page->freed_size += sizeof(uint32_t);
return marker + 1;
}
else
{
// roll back uint32_t part
_busy_size -= sizeof(uint32_t);
return result;
}
}
#else
void* allocate_object(size_t size, xml_memory_page*& out_page)
{
return allocate_memory(size, out_page);
}
#endif
void deallocate_memory(void* ptr, size_t size, xml_memory_page* page)
{
if (page == _root) page->busy_size = _busy_size;
assert(ptr >= reinterpret_cast<char*>(page) + sizeof(xml_memory_page) && ptr < reinterpret_cast<char*>(page) + sizeof(xml_memory_page) + page->busy_size);
(void)!ptr;
page->freed_size += size;
assert(page->freed_size <= page->busy_size);
if (page->freed_size == page->busy_size)
{
if (page->next == 0)
{
assert(_root == page);
// top page freed, just reset sizes
page->busy_size = 0;
page->freed_size = 0;
#ifdef PUGIXML_COMPACT
// reset compact state to maximize efficiency
page->compact_string_base = 0;
page->compact_shared_parent = 0;
page->compact_page_marker = 0;
#endif
_busy_size = 0;
}
else
{
assert(_root != page);
assert(page->prev);
// remove from the list
page->prev->next = page->next;
page->next->prev = page->prev;
// deallocate
deallocate_page(page);
}
}
}
char_t* allocate_string(size_t length)
{
static const size_t max_encoded_offset = (1 << 16) * xml_memory_block_alignment;
PUGI__STATIC_ASSERT(xml_memory_page_size <= max_encoded_offset);
// allocate memory for string and header block
size_t size = sizeof(xml_memory_string_header) + length * sizeof(char_t);
// round size up to block alignment boundary
size_t full_size = (size + (xml_memory_block_alignment - 1)) & ~(xml_memory_block_alignment - 1);
xml_memory_page* page;
xml_memory_string_header* header = static_cast<xml_memory_string_header*>(allocate_memory(full_size, page));
if (!header) return 0;
// setup header
ptrdiff_t page_offset = reinterpret_cast<char*>(header) - reinterpret_cast<char*>(page) - sizeof(xml_memory_page);
assert(page_offset % xml_memory_block_alignment == 0);
assert(page_offset >= 0 && static_cast<size_t>(page_offset) < max_encoded_offset);
header->page_offset = static_cast<uint16_t>(static_cast<size_t>(page_offset) / xml_memory_block_alignment);
// full_size == 0 for large strings that occupy the whole page
assert(full_size % xml_memory_block_alignment == 0);
assert(full_size < max_encoded_offset || (page->busy_size == full_size && page_offset == 0));
header->full_size = static_cast<uint16_t>(full_size < max_encoded_offset ? full_size / xml_memory_block_alignment : 0);
// round-trip through void* to avoid 'cast increases required alignment of target type' warning
// header is guaranteed a pointer-sized alignment, which should be enough for char_t
return static_cast<char_t*>(static_cast<void*>(header + 1));
}
void deallocate_string(char_t* string)
{
// this function casts pointers through void* to avoid 'cast increases required alignment of target type' warnings
// we're guaranteed the proper (pointer-sized) alignment on the input string if it was allocated via allocate_string
// get header
xml_memory_string_header* header = static_cast<xml_memory_string_header*>(static_cast<void*>(string)) - 1;
assert(header);
// deallocate
size_t page_offset = sizeof(xml_memory_page) + header->page_offset * xml_memory_block_alignment;
xml_memory_page* page = reinterpret_cast<xml_memory_page*>(static_cast<void*>(reinterpret_cast<char*>(header) - page_offset));
// if full_size == 0 then this string occupies the whole page
size_t full_size = header->full_size == 0 ? page->busy_size : header->full_size * xml_memory_block_alignment;
deallocate_memory(header, full_size, page);
}
bool reserve()
{
#ifdef PUGIXML_COMPACT
return _hash->reserve();
#else
return true;
#endif
}
xml_memory_page* _root;
size_t _busy_size;
#ifdef PUGIXML_COMPACT
compact_hash_table* _hash;
#endif
};
PUGI__FN_NO_INLINE void* xml_allocator::allocate_memory_oob(size_t size, xml_memory_page*& out_page)
{
const size_t large_allocation_threshold = xml_memory_page_size / 4;
xml_memory_page* page = allocate_page(size <= large_allocation_threshold ? xml_memory_page_size : size);
out_page = page;
if (!page) return 0;
if (size <= large_allocation_threshold)
{
_root->busy_size = _busy_size;
// insert page at the end of linked list
page->prev = _root;
_root->next = page;
_root = page;
_busy_size = size;
}
else
{
// insert page before the end of linked list, so that it is deleted as soon as possible
// the last page is not deleted even if it's empty (see deallocate_memory)
assert(_root->prev);
page->prev = _root->prev;
page->next = _root;
_root->prev->next = page;
_root->prev = page;
page->busy_size = size;
}
return reinterpret_cast<char*>(page) + sizeof(xml_memory_page);
}
PUGI__NS_END
#ifdef PUGIXML_COMPACT
PUGI__NS_BEGIN
static const uintptr_t compact_alignment_log2 = 2;
static const uintptr_t compact_alignment = 1 << compact_alignment_log2;
class compact_header
{
public:
compact_header(xml_memory_page* page, unsigned int flags)
{
PUGI__STATIC_ASSERT(xml_memory_block_alignment == compact_alignment);
ptrdiff_t offset = (reinterpret_cast<char*>(this) - reinterpret_cast<char*>(page->compact_page_marker));
assert(offset % compact_alignment == 0 && static_cast<uintptr_t>(offset) < 256 * compact_alignment);
_page = static_cast<unsigned char>(offset >> compact_alignment_log2);
_flags = static_cast<unsigned char>(flags);
}
void operator&=(uintptr_t mod)
{
_flags &= static_cast<unsigned char>(mod);
}
void operator|=(uintptr_t mod)
{
_flags |= static_cast<unsigned char>(mod);
}
uintptr_t operator&(uintptr_t mod) const
{
return _flags & mod;
}
xml_memory_page* get_page() const
{
// round-trip through void* to silence 'cast increases required alignment of target type' warnings
const char* page_marker = reinterpret_cast<const char*>(this) - (_page << compact_alignment_log2);
const char* page = page_marker - *reinterpret_cast<const uint32_t*>(static_cast<const void*>(page_marker));
return const_cast<xml_memory_page*>(reinterpret_cast<const xml_memory_page*>(static_cast<const void*>(page)));
}
private:
unsigned char _page;
unsigned char _flags;
};
PUGI__FN xml_memory_page* compact_get_page(const void* object, int header_offset)
{
const compact_header* header = reinterpret_cast<const compact_header*>(static_cast<const char*>(object) - header_offset);
return header->get_page();
}
template <int header_offset, typename T> PUGI__FN_NO_INLINE T* compact_get_value(const void* object)
{
return static_cast<T*>(compact_get_page(object, header_offset)->allocator->_hash->find(object));
}
template <int header_offset, typename T> PUGI__FN_NO_INLINE void compact_set_value(const void* object, T* value)
{
compact_get_page(object, header_offset)->allocator->_hash->insert(object, value);
}
template <typename T, int header_offset, int start = -126> class compact_pointer
{
public:
compact_pointer(): _data(0)
{
}
void operator=(const compact_pointer& rhs)
{
*this = rhs + 0;
}
void operator=(T* value)
{
if (value)
{
// value is guaranteed to be compact-aligned; 'this' is not
// our decoding is based on 'this' aligned to compact alignment downwards (see operator T*)
// so for negative offsets (e.g. -3) we need to adjust the diff by compact_alignment - 1 to
// compensate for arithmetic shift rounding for negative values
ptrdiff_t diff = reinterpret_cast<char*>(value) - reinterpret_cast<char*>(this);
ptrdiff_t offset = ((diff + int(compact_alignment - 1)) >> compact_alignment_log2) - start;
if (static_cast<uintptr_t>(offset) <= 253)
_data = static_cast<unsigned char>(offset + 1);
else
{
compact_set_value<header_offset>(this, value);
_data = 255;
}
}
else
_data = 0;
}
operator T*() const
{
if (_data)
{
if (_data < 255)
{
uintptr_t base = reinterpret_cast<uintptr_t>(this) & ~(compact_alignment - 1);
return reinterpret_cast<T*>(base + (_data - 1 + start) * compact_alignment);
}
else
return compact_get_value<header_offset, T>(this);
}
else
return 0;
}
T* operator->() const
{
return *this;
}
private:
unsigned char _data;
};
template <typename T, int header_offset> class compact_pointer_parent
{
public:
compact_pointer_parent(): _data(0)
{
}
void operator=(const compact_pointer_parent& rhs)
{
*this = rhs + 0;
}
void operator=(T* value)
{
if (value)
{
// value is guaranteed to be compact-aligned; 'this' is not
// our decoding is based on 'this' aligned to compact alignment downwards (see operator T*)
// so for negative offsets (e.g. -3) we need to adjust the diff by compact_alignment - 1 to
// compensate for arithmetic shift behavior for negative values
ptrdiff_t diff = reinterpret_cast<char*>(value) - reinterpret_cast<char*>(this);
ptrdiff_t offset = ((diff + int(compact_alignment - 1)) >> compact_alignment_log2) + 65533;
if (static_cast<uintptr_t>(offset) <= 65533)
{
_data = static_cast<unsigned short>(offset + 1);
}
else
{
xml_memory_page* page = compact_get_page(this, header_offset);
if (PUGI__UNLIKELY(page->compact_shared_parent == 0))
page->compact_shared_parent = value;
if (page->compact_shared_parent == value)
{
_data = 65534;
}
else
{
compact_set_value<header_offset>(this, value);
_data = 65535;
}
}
}
else
{
_data = 0;
}
}
operator T*() const
{
if (_data)
{
if (_data < 65534)
{
uintptr_t base = reinterpret_cast<uintptr_t>(this) & ~(compact_alignment - 1);
return reinterpret_cast<T*>(base + (_data - 1 - 65533) * compact_alignment);
}
else if (_data == 65534)
return static_cast<T*>(compact_get_page(this, header_offset)->compact_shared_parent);
else
return compact_get_value<header_offset, T>(this);
}
else
return 0;
}
T* operator->() const
{
return *this;
}
private:
uint16_t _data;
};
template <int header_offset, int base_offset> class compact_string
{
public:
compact_string(): _data(0)
{
}
void operator=(const compact_string& rhs)
{
*this = rhs + 0;
}
void operator=(char_t* value)
{
if (value)
{
xml_memory_page* page = compact_get_page(this, header_offset);
if (PUGI__UNLIKELY(page->compact_string_base == 0))
page->compact_string_base = value;
ptrdiff_t offset = value - page->compact_string_base;
if (static_cast<uintptr_t>(offset) < (65535 << 7))
{
// round-trip through void* to silence 'cast increases required alignment of target type' warnings
uint16_t* base = reinterpret_cast<uint16_t*>(static_cast<void*>(reinterpret_cast<char*>(this) - base_offset));
if (*base == 0)
{
*base = static_cast<uint16_t>((offset >> 7) + 1);
_data = static_cast<unsigned char>((offset & 127) + 1);
}
else
{
ptrdiff_t remainder = offset - ((*base - 1) << 7);
if (static_cast<uintptr_t>(remainder) <= 253)
{
_data = static_cast<unsigned char>(remainder + 1);
}
else
{
compact_set_value<header_offset>(this, value);
_data = 255;
}
}
}
else
{
compact_set_value<header_offset>(this, value);
_data = 255;
}
}
else
{
_data = 0;
}
}
operator char_t*() const
{
if (_data)
{
if (_data < 255)
{
xml_memory_page* page = compact_get_page(this, header_offset);
// round-trip through void* to silence 'cast increases required alignment of target type' warnings
const uint16_t* base = reinterpret_cast<const uint16_t*>(static_cast<const void*>(reinterpret_cast<const char*>(this) - base_offset));
assert(*base);
ptrdiff_t offset = ((*base - 1) << 7) + (_data - 1);
return page->compact_string_base + offset;
}
else
{
return compact_get_value<header_offset, char_t>(this);
}
}
else
return 0;
}
private:
unsigned char _data;
};
PUGI__NS_END
#endif
#ifdef PUGIXML_COMPACT
namespace pugi
{
struct xml_attribute_struct
{
xml_attribute_struct(impl::xml_memory_page* page): header(page, 0), namevalue_base(0)
{
PUGI__STATIC_ASSERT(sizeof(xml_attribute_struct) == 8);
}
impl::compact_header header;
uint16_t namevalue_base;
impl::compact_string<4, 2> name;
impl::compact_string<5, 3> value;
impl::compact_pointer<xml_attribute_struct, 6> prev_attribute_c;
impl::compact_pointer<xml_attribute_struct, 7, 0> next_attribute;
};
struct xml_node_struct
{
xml_node_struct(impl::xml_memory_page* page, xml_node_type type): header(page, type), namevalue_base(0)
{
PUGI__STATIC_ASSERT(sizeof(xml_node_struct) == 12);
}
impl::compact_header header;
uint16_t namevalue_base;
impl::compact_string<4, 2> name;
impl::compact_string<5, 3> value;
impl::compact_pointer_parent<xml_node_struct, 6> parent;
impl::compact_pointer<xml_node_struct, 8, 0> first_child;
impl::compact_pointer<xml_node_struct, 9> prev_sibling_c;
impl::compact_pointer<xml_node_struct, 10, 0> next_sibling;
impl::compact_pointer<xml_attribute_struct, 11, 0> first_attribute;
};
}
#else
namespace pugi
{
struct xml_attribute_struct
{
xml_attribute_struct(impl::xml_memory_page* page): name(0), value(0), prev_attribute_c(0), next_attribute(0)
{
header = PUGI__GETHEADER_IMPL(this, page, 0);
}
uintptr_t header;
char_t* name;
char_t* value;
xml_attribute_struct* prev_attribute_c;
xml_attribute_struct* next_attribute;
};
struct xml_node_struct
{
xml_node_struct(impl::xml_memory_page* page, xml_node_type type): name(0), value(0), parent(0), first_child(0), prev_sibling_c(0), next_sibling(0), first_attribute(0)
{
header = PUGI__GETHEADER_IMPL(this, page, type);
}
uintptr_t header;
char_t* name;
char_t* value;
xml_node_struct* parent;
xml_node_struct* first_child;
xml_node_struct* prev_sibling_c;
xml_node_struct* next_sibling;
xml_attribute_struct* first_attribute;
};
}
#endif
PUGI__NS_BEGIN
struct xml_extra_buffer
{
char_t* buffer;
xml_extra_buffer* next;
};
struct xml_document_struct: public xml_node_struct, public xml_allocator
{
xml_document_struct(xml_memory_page* page): xml_node_struct(page, node_document), xml_allocator(page), buffer(0), extra_buffers(0)
{
}
const char_t* buffer;
xml_extra_buffer* extra_buffers;
#ifdef PUGIXML_COMPACT
compact_hash_table hash;
#endif
};
template <typename Object> inline xml_allocator& get_allocator(const Object* object)
{
assert(object);
return *PUGI__GETPAGE(object)->allocator;
}
template <typename Object> inline xml_document_struct& get_document(const Object* object)
{
assert(object);
return *static_cast<xml_document_struct*>(PUGI__GETPAGE(object)->allocator);
}
PUGI__NS_END
// Low-level DOM operations
PUGI__NS_BEGIN
inline xml_attribute_struct* allocate_attribute(xml_allocator& alloc)
{
xml_memory_page* page;
void* memory = alloc.allocate_object(sizeof(xml_attribute_struct), page);
if (!memory) return 0;
return new (memory) xml_attribute_struct(page);
}
inline xml_node_struct* allocate_node(xml_allocator& alloc, xml_node_type type)
{
xml_memory_page* page;
void* memory = alloc.allocate_object(sizeof(xml_node_struct), page);
if (!memory) return 0;
return new (memory) xml_node_struct(page, type);
}
inline void destroy_attribute(xml_attribute_struct* a, xml_allocator& alloc)
{
if (a->header & impl::xml_memory_page_name_allocated_mask)
alloc.deallocate_string(a->name);
if (a->header & impl::xml_memory_page_value_allocated_mask)
alloc.deallocate_string(a->value);
alloc.deallocate_memory(a, sizeof(xml_attribute_struct), PUGI__GETPAGE(a));
}
inline void destroy_node(xml_node_struct* n, xml_allocator& alloc)
{
if (n->header & impl::xml_memory_page_name_allocated_mask)
alloc.deallocate_string(n->name);
if (n->header & impl::xml_memory_page_value_allocated_mask)
alloc.deallocate_string(n->value);
for (xml_attribute_struct* attr = n->first_attribute; attr; )
{
xml_attribute_struct* next = attr->next_attribute;
destroy_attribute(attr, alloc);
attr = next;
}
for (xml_node_struct* child = n->first_child; child; )
{
xml_node_struct* next = child->next_sibling;
destroy_node(child, alloc);
child = next;
}
alloc.deallocate_memory(n, sizeof(xml_node_struct), PUGI__GETPAGE(n));
}
inline void append_node(xml_node_struct* child, xml_node_struct* node)
{
child->parent = node;
xml_node_struct* head = node->first_child;
if (head)
{
xml_node_struct* tail = head->prev_sibling_c;
tail->next_sibling = child;
child->prev_sibling_c = tail;
head->prev_sibling_c = child;
}
else
{
node->first_child = child;
child->prev_sibling_c = child;
}
}
inline void prepend_node(xml_node_struct* child, xml_node_struct* node)
{
child->parent = node;
xml_node_struct* head = node->first_child;
if (head)
{
child->prev_sibling_c = head->prev_sibling_c;
head->prev_sibling_c = child;
}
else
child->prev_sibling_c = child;
child->next_sibling = head;
node->first_child = child;
}
inline void insert_node_after(xml_node_struct* child, xml_node_struct* node)
{
xml_node_struct* parent = node->parent;
child->parent = parent;
if (node->next_sibling)
node->next_sibling->prev_sibling_c = child;
else
parent->first_child->prev_sibling_c = child;
child->next_sibling = node->next_sibling;
child->prev_sibling_c = node;
node->next_sibling = child;
}
inline void insert_node_before(xml_node_struct* child, xml_node_struct* node)
{
xml_node_struct* parent = node->parent;
child->parent = parent;
if (node->prev_sibling_c->next_sibling)
node->prev_sibling_c->next_sibling = child;
else
parent->first_child = child;
child->prev_sibling_c = node->prev_sibling_c;
child->next_sibling = node;
node->prev_sibling_c = child;
}
inline void remove_node(xml_node_struct* node)
{
xml_node_struct* parent = node->parent;
if (node->next_sibling)
node->next_sibling->prev_sibling_c = node->prev_sibling_c;
else
parent->first_child->prev_sibling_c = node->prev_sibling_c;
if (node->prev_sibling_c->next_sibling)
node->prev_sibling_c->next_sibling = node->next_sibling;
else
parent->first_child = node->next_sibling;
node->parent = 0;
node->prev_sibling_c = 0;
node->next_sibling = 0;
}
inline void append_attribute(xml_attribute_struct* attr, xml_node_struct* node)
{
xml_attribute_struct* head = node->first_attribute;
if (head)
{
xml_attribute_struct* tail = head->prev_attribute_c;
tail->next_attribute = attr;
attr->prev_attribute_c = tail;
head->prev_attribute_c = attr;
}
else
{
node->first_attribute = attr;
attr->prev_attribute_c = attr;
}
}
inline void prepend_attribute(xml_attribute_struct* attr, xml_node_struct* node)
{
xml_attribute_struct* head = node->first_attribute;
if (head)
{
attr->prev_attribute_c = head->prev_attribute_c;
head->prev_attribute_c = attr;
}
else
attr->prev_attribute_c = attr;
attr->next_attribute = head;
node->first_attribute = attr;
}
inline void insert_attribute_after(xml_attribute_struct* attr, xml_attribute_struct* place, xml_node_struct* node)
{
if (place->next_attribute)
place->next_attribute->prev_attribute_c = attr;
else
node->first_attribute->prev_attribute_c = attr;
attr->next_attribute = place->next_attribute;
attr->prev_attribute_c = place;
place->next_attribute = attr;
}
inline void insert_attribute_before(xml_attribute_struct* attr, xml_attribute_struct* place, xml_node_struct* node)
{
if (place->prev_attribute_c->next_attribute)
place->prev_attribute_c->next_attribute = attr;
else
node->first_attribute = attr;
attr->prev_attribute_c = place->prev_attribute_c;
attr->next_attribute = place;
place->prev_attribute_c = attr;
}
inline void remove_attribute(xml_attribute_struct* attr, xml_node_struct* node)
{
if (attr->next_attribute)
attr->next_attribute->prev_attribute_c = attr->prev_attribute_c;
else
node->first_attribute->prev_attribute_c = attr->prev_attribute_c;
if (attr->prev_attribute_c->next_attribute)
attr->prev_attribute_c->next_attribute = attr->next_attribute;
else
node->first_attribute = attr->next_attribute;
attr->prev_attribute_c = 0;
attr->next_attribute = 0;
}
PUGI__FN_NO_INLINE xml_node_struct* append_new_node(xml_node_struct* node, xml_allocator& alloc, xml_node_type type = node_element)
{
if (!alloc.reserve()) return 0;
xml_node_struct* child = allocate_node(alloc, type);
if (!child) return 0;
append_node(child, node);
return child;
}
PUGI__FN_NO_INLINE xml_attribute_struct* append_new_attribute(xml_node_struct* node, xml_allocator& alloc)
{
if (!alloc.reserve()) return 0;
xml_attribute_struct* attr = allocate_attribute(alloc);
if (!attr) return 0;
append_attribute(attr, node);
return attr;
}
PUGI__NS_END
// Helper classes for code generation
PUGI__NS_BEGIN
struct opt_false
{
enum { value = 0 };
};
struct opt_true
{
enum { value = 1 };
};
PUGI__NS_END
// Unicode utilities
PUGI__NS_BEGIN
inline uint16_t endian_swap(uint16_t value)
{
return static_cast<uint16_t>(((value & 0xff) << 8) | (value >> 8));
}
inline uint32_t endian_swap(uint32_t value)
{
return ((value & 0xff) << 24) | ((value & 0xff00) << 8) | ((value & 0xff0000) >> 8) | (value >> 24);
}
struct utf8_counter
{
typedef size_t value_type;
static value_type low(value_type result, uint32_t ch)
{
// U+0000..U+007F
if (ch < 0x80) return result + 1;
// U+0080..U+07FF
else if (ch < 0x800) return result + 2;
// U+0800..U+FFFF
else return result + 3;
}
static value_type high(value_type result, uint32_t)
{
// U+10000..U+10FFFF
return result + 4;
}
};
struct utf8_writer
{
typedef uint8_t* value_type;
static value_type low(value_type result, uint32_t ch)
{
// U+0000..U+007F
if (ch < 0x80)
{
*result = static_cast<uint8_t>(ch);
return result + 1;
}
// U+0080..U+07FF
else if (ch < 0x800)
{
result[0] = static_cast<uint8_t>(0xC0 | (ch >> 6));
result[1] = static_cast<uint8_t>(0x80 | (ch & 0x3F));
return result + 2;
}
// U+0800..U+FFFF
else
{
result[0] = static_cast<uint8_t>(0xE0 | (ch >> 12));
result[1] = static_cast<uint8_t>(0x80 | ((ch >> 6) & 0x3F));
result[2] = static_cast<uint8_t>(0x80 | (ch & 0x3F));
return result + 3;
}
}
static value_type high(value_type result, uint32_t ch)
{
// U+10000..U+10FFFF
result[0] = static_cast<uint8_t>(0xF0 | (ch >> 18));
result[1] = static_cast<uint8_t>(0x80 | ((ch >> 12) & 0x3F));
result[2] = static_cast<uint8_t>(0x80 | ((ch >> 6) & 0x3F));
result[3] = static_cast<uint8_t>(0x80 | (ch & 0x3F));
return result + 4;
}
static value_type any(value_type result, uint32_t ch)
{
return (ch < 0x10000) ? low(result, ch) : high(result, ch);
}
};
struct utf16_counter
{
typedef size_t value_type;
static value_type low(value_type result, uint32_t)
{
return result + 1;
}
static value_type high(value_type result, uint32_t)
{
return result + 2;
}
};
struct utf16_writer
{
typedef uint16_t* value_type;
static value_type low(value_type result, uint32_t ch)
{
*result = static_cast<uint16_t>(ch);
return result + 1;
}
static value_type high(value_type result, uint32_t ch)
{
uint32_t msh = static_cast<uint32_t>(ch - 0x10000) >> 10;
uint32_t lsh = static_cast<uint32_t>(ch - 0x10000) & 0x3ff;
result[0] = static_cast<uint16_t>(0xD800 + msh);
result[1] = static_cast<uint16_t>(0xDC00 + lsh);
return result + 2;
}
static value_type any(value_type result, uint32_t ch)
{
return (ch < 0x10000) ? low(result, ch) : high(result, ch);
}
};
struct utf32_counter
{
typedef size_t value_type;
static value_type low(value_type result, uint32_t)
{
return result + 1;
}
static value_type high(value_type result, uint32_t)
{
return result + 1;
}
};
struct utf32_writer
{
typedef uint32_t* value_type;
static value_type low(value_type result, uint32_t ch)
{
*result = ch;
return result + 1;
}
static value_type high(value_type result, uint32_t ch)
{
*result = ch;
return result + 1;
}
static value_type any(value_type result, uint32_t ch)
{
*result = ch;
return result + 1;
}
};
struct latin1_writer
{
typedef uint8_t* value_type;
static value_type low(value_type result, uint32_t ch)
{
*result = static_cast<uint8_t>(ch > 255 ? '?' : ch);
return result + 1;
}
static value_type high(value_type result, uint32_t ch)
{
(void)ch;
*result = '?';
return result + 1;
}
};
struct utf8_decoder
{
typedef uint8_t type;
template <typename Traits> static inline typename Traits::value_type process(const uint8_t* data, size_t size, typename Traits::value_type result, Traits)
{
const uint8_t utf8_byte_mask = 0x3f;
while (size)
{
uint8_t lead = *data;
// 0xxxxxxx -> U+0000..U+007F
if (lead < 0x80)
{
result = Traits::low(result, lead);
data += 1;
size -= 1;
// process aligned single-byte (ascii) blocks
if ((reinterpret_cast<uintptr_t>(data) & 3) == 0)
{
// round-trip through void* to silence 'cast increases required alignment of target type' warnings
while (size >= 4 && (*static_cast<const uint32_t*>(static_cast<const void*>(data)) & 0x80808080) == 0)
{
result = Traits::low(result, data[0]);
result = Traits::low(result, data[1]);
result = Traits::low(result, data[2]);
result = Traits::low(result, data[3]);
data += 4;
size -= 4;
}
}
}
// 110xxxxx -> U+0080..U+07FF
else if (static_cast<unsigned int>(lead - 0xC0) < 0x20 && size >= 2 && (data[1] & 0xc0) == 0x80)
{
result = Traits::low(result, ((lead & ~0xC0) << 6) | (data[1] & utf8_byte_mask));
data += 2;
size -= 2;
}
// 1110xxxx -> U+0800-U+FFFF
else if (static_cast<unsigned int>(lead - 0xE0) < 0x10 && size >= 3 && (data[1] & 0xc0) == 0x80 && (data[2] & 0xc0) == 0x80)
{
result = Traits::low(result, ((lead & ~0xE0) << 12) | ((data[1] & utf8_byte_mask) << 6) | (data[2] & utf8_byte_mask));
data += 3;
size -= 3;
}
// 11110xxx -> U+10000..U+10FFFF
else if (static_cast<unsigned int>(lead - 0xF0) < 0x08 && size >= 4 && (data[1] & 0xc0) == 0x80 && (data[2] & 0xc0) == 0x80 && (data[3] & 0xc0) == 0x80)
{
result = Traits::high(result, ((lead & ~0xF0) << 18) | ((data[1] & utf8_byte_mask) << 12) | ((data[2] & utf8_byte_mask) << 6) | (data[3] & utf8_byte_mask));
data += 4;
size -= 4;
}
// 10xxxxxx or 11111xxx -> invalid
else
{
data += 1;
size -= 1;
}
}
return result;
}
};
template <typename opt_swap> struct utf16_decoder
{
typedef uint16_t type;
template <typename Traits> static inline typename Traits::value_type process(const uint16_t* data, size_t size, typename Traits::value_type result, Traits)
{
while (size)
{
uint16_t lead = opt_swap::value ? endian_swap(*data) : *data;
// U+0000..U+D7FF
if (lead < 0xD800)
{
result = Traits::low(result, lead);
data += 1;
size -= 1;
}
// U+E000..U+FFFF
else if (static_cast<unsigned int>(lead - 0xE000) < 0x2000)
{
result = Traits::low(result, lead);
data += 1;
size -= 1;
}
// surrogate pair lead
else if (static_cast<unsigned int>(lead - 0xD800) < 0x400 && size >= 2)
{
uint16_t next = opt_swap::value ? endian_swap(data[1]) : data[1];
if (static_cast<unsigned int>(next - 0xDC00) < 0x400)
{
result = Traits::high(result, 0x10000 + ((lead & 0x3ff) << 10) + (next & 0x3ff));
data += 2;
size -= 2;
}
else
{
data += 1;
size -= 1;
}
}
else
{
data += 1;
size -= 1;
}
}
return result;
}
};
template <typename opt_swap> struct utf32_decoder
{
typedef uint32_t type;
template <typename Traits> static inline typename Traits::value_type process(const uint32_t* data, size_t size, typename Traits::value_type result, Traits)
{
while (size)
{
uint32_t lead = opt_swap::value ? endian_swap(*data) : *data;
// U+0000..U+FFFF
if (lead < 0x10000)
{
result = Traits::low(result, lead);
data += 1;
size -= 1;
}
// U+10000..U+10FFFF
else
{
result = Traits::high(result, lead);
data += 1;
size -= 1;
}
}
return result;
}
};
struct latin1_decoder
{
typedef uint8_t type;
template <typename Traits> static inline typename Traits::value_type process(const uint8_t* data, size_t size, typename Traits::value_type result, Traits)
{
while (size)
{
result = Traits::low(result, *data);
data += 1;
size -= 1;
}
return result;
}
};
template <size_t size> struct wchar_selector;
template <> struct wchar_selector<2>
{
typedef uint16_t type;
typedef utf16_counter counter;
typedef utf16_writer writer;
typedef utf16_decoder<opt_false> decoder;
};
template <> struct wchar_selector<4>
{
typedef uint32_t type;
typedef utf32_counter counter;
typedef utf32_writer writer;
typedef utf32_decoder<opt_false> decoder;
};
typedef wchar_selector<sizeof(wchar_t)>::counter wchar_counter;
typedef wchar_selector<sizeof(wchar_t)>::writer wchar_writer;
struct wchar_decoder
{
typedef wchar_t type;
template <typename Traits> static inline typename Traits::value_type process(const wchar_t* data, size_t size, typename Traits::value_type result, Traits traits)
{
typedef wchar_selector<sizeof(wchar_t)>::decoder decoder;
return decoder::process(reinterpret_cast<const typename decoder::type*>(data), size, result, traits);
}
};
#ifdef PUGIXML_WCHAR_MODE
PUGI__FN void convert_wchar_endian_swap(wchar_t* result, const wchar_t* data, size_t length)
{
for (size_t i = 0; i < length; ++i)
result[i] = static_cast<wchar_t>(endian_swap(static_cast<wchar_selector<sizeof(wchar_t)>::type>(data[i])));
}
#endif
PUGI__NS_END
PUGI__NS_BEGIN
enum chartype_t
{
ct_parse_pcdata = 1, // \0, &, \r, <
ct_parse_attr = 2, // \0, &, \r, ', "
ct_parse_attr_ws = 4, // \0, &, \r, ', ", \n, tab
ct_space = 8, // \r, \n, space, tab
ct_parse_cdata = 16, // \0, ], >, \r
ct_parse_comment = 32, // \0, -, >, \r
ct_symbol = 64, // Any symbol > 127, a-z, A-Z, 0-9, _, :, -, .
ct_start_symbol = 128 // Any symbol > 127, a-z, A-Z, _, :
};
static const unsigned char chartype_table[256] =
{
55, 0, 0, 0, 0, 0, 0, 0, 0, 12, 12, 0, 0, 63, 0, 0, // 0-15
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16-31
8, 0, 6, 0, 0, 0, 7, 6, 0, 0, 0, 0, 0, 96, 64, 0, // 32-47
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 192, 0, 1, 0, 48, 0, // 48-63
0, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, // 64-79
192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 0, 0, 16, 0, 192, // 80-95
0, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, // 96-111
192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 0, 0, 0, 0, 0, // 112-127
192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, // 128+
192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192,
192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192,
192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192,
192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192,
192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192,
192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192,
192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192
};
enum chartypex_t
{
ctx_special_pcdata = 1, // Any symbol >= 0 and < 32 (except \t, \r, \n), &, <, >
ctx_special_attr = 2, // Any symbol >= 0 and < 32, &, <, ", '
ctx_start_symbol = 4, // Any symbol > 127, a-z, A-Z, _
ctx_digit = 8, // 0-9
ctx_symbol = 16 // Any symbol > 127, a-z, A-Z, 0-9, _, -, .
};
static const unsigned char chartypex_table[256] =
{
3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3, // 0-15
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, // 16-31
0, 0, 2, 0, 0, 0, 3, 2, 0, 0, 0, 0, 0, 16, 16, 0, // 32-47
24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 0, 0, 3, 0, 1, 0, // 48-63
0, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, // 64-79
20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 0, 0, 0, 0, 20, // 80-95
0, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, // 96-111
20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 0, 0, 0, 0, 0, // 112-127
20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, // 128+
20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20
};
#ifdef PUGIXML_WCHAR_MODE
#define PUGI__IS_CHARTYPE_IMPL(c, ct, table) ((static_cast<unsigned int>(c) < 128 ? table[static_cast<unsigned int>(c)] : table[128]) & (ct))
#else
#define PUGI__IS_CHARTYPE_IMPL(c, ct, table) (table[static_cast<unsigned char>(c)] & (ct))
#endif
#define PUGI__IS_CHARTYPE(c, ct) PUGI__IS_CHARTYPE_IMPL(c, ct, chartype_table)
#define PUGI__IS_CHARTYPEX(c, ct) PUGI__IS_CHARTYPE_IMPL(c, ct, chartypex_table)
PUGI__FN bool is_little_endian()
{
unsigned int ui = 1;
return *reinterpret_cast<unsigned char*>(&ui) == 1;
}
PUGI__FN xml_encoding get_wchar_encoding()
{
PUGI__STATIC_ASSERT(sizeof(wchar_t) == 2 || sizeof(wchar_t) == 4);
if (sizeof(wchar_t) == 2)
return is_little_endian() ? encoding_utf16_le : encoding_utf16_be;
else
return is_little_endian() ? encoding_utf32_le : encoding_utf32_be;
}
PUGI__FN bool parse_declaration_encoding(const uint8_t* data, size_t size, const uint8_t*& out_encoding, size_t& out_length)
{
#define PUGI__SCANCHAR(ch) { if (offset >= size || data[offset] != ch) return false; offset++; }
#define PUGI__SCANCHARTYPE(ct) { while (offset < size && PUGI__IS_CHARTYPE(data[offset], ct)) offset++; }
// check if we have a non-empty XML declaration
if (size < 6 || !((data[0] == '<') & (data[1] == '?') & (data[2] == 'x') & (data[3] == 'm') & (data[4] == 'l') && PUGI__IS_CHARTYPE(data[5], ct_space)))
return false;
// scan XML declaration until the encoding field
for (size_t i = 6; i + 1 < size; ++i)
{
// declaration can not contain ? in quoted values
if (data[i] == '?')
return false;
if (data[i] == 'e' && data[i + 1] == 'n')
{
size_t offset = i;
// encoding follows the version field which can't contain 'en' so this has to be the encoding if XML is well formed
PUGI__SCANCHAR('e'); PUGI__SCANCHAR('n'); PUGI__SCANCHAR('c'); PUGI__SCANCHAR('o');
PUGI__SCANCHAR('d'); PUGI__SCANCHAR('i'); PUGI__SCANCHAR('n'); PUGI__SCANCHAR('g');
// S? = S?
PUGI__SCANCHARTYPE(ct_space);
PUGI__SCANCHAR('=');
PUGI__SCANCHARTYPE(ct_space);
// the only two valid delimiters are ' and "
uint8_t delimiter = (offset < size && data[offset] == '"') ? '"' : '\'';
PUGI__SCANCHAR(delimiter);
size_t start = offset;
out_encoding = data + offset;
PUGI__SCANCHARTYPE(ct_symbol);
out_length = offset - start;
PUGI__SCANCHAR(delimiter);
return true;
}
}
return false;
#undef PUGI__SCANCHAR
#undef PUGI__SCANCHARTYPE
}
PUGI__FN xml_encoding guess_buffer_encoding(const uint8_t* data, size_t size)
{
// skip encoding autodetection if input buffer is too small
if (size < 4) return encoding_utf8;
uint8_t d0 = data[0], d1 = data[1], d2 = data[2], d3 = data[3];
// look for BOM in first few bytes
if (d0 == 0 && d1 == 0 && d2 == 0xfe && d3 == 0xff) return encoding_utf32_be;
if (d0 == 0xff && d1 == 0xfe && d2 == 0 && d3 == 0) return encoding_utf32_le;
if (d0 == 0xfe && d1 == 0xff) return encoding_utf16_be;
if (d0 == 0xff && d1 == 0xfe) return encoding_utf16_le;
if (d0 == 0xef && d1 == 0xbb && d2 == 0xbf) return encoding_utf8;
// look for <, <? or <?xm in various encodings
if (d0 == 0 && d1 == 0 && d2 == 0 && d3 == 0x3c) return encoding_utf32_be;
if (d0 == 0x3c && d1 == 0 && d2 == 0 && d3 == 0) return encoding_utf32_le;
if (d0 == 0 && d1 == 0x3c && d2 == 0 && d3 == 0x3f) return encoding_utf16_be;
if (d0 == 0x3c && d1 == 0 && d2 == 0x3f && d3 == 0) return encoding_utf16_le;
// look for utf16 < followed by node name (this may fail, but is better than utf8 since it's zero terminated so early)
if (d0 == 0 && d1 == 0x3c) return encoding_utf16_be;
if (d0 == 0x3c && d1 == 0) return encoding_utf16_le;
// no known BOM detected; parse declaration
const uint8_t* enc = 0;
size_t enc_length = 0;
if (d0 == 0x3c && d1 == 0x3f && d2 == 0x78 && d3 == 0x6d && parse_declaration_encoding(data, size, enc, enc_length))
{
// iso-8859-1 (case-insensitive)
if (enc_length == 10
&& (enc[0] | ' ') == 'i' && (enc[1] | ' ') == 's' && (enc[2] | ' ') == 'o'
&& enc[3] == '-' && enc[4] == '8' && enc[5] == '8' && enc[6] == '5' && enc[7] == '9'
&& enc[8] == '-' && enc[9] == '1')
return encoding_latin1;
// latin1 (case-insensitive)
if (enc_length == 6
&& (enc[0] | ' ') == 'l' && (enc[1] | ' ') == 'a' && (enc[2] | ' ') == 't'
&& (enc[3] | ' ') == 'i' && (enc[4] | ' ') == 'n'
&& enc[5] == '1')
return encoding_latin1;
}
return encoding_utf8;
}
PUGI__FN xml_encoding get_buffer_encoding(xml_encoding encoding, const void* contents, size_t size)
{
// replace wchar encoding with utf implementation
if (encoding == encoding_wchar) return get_wchar_encoding();
// replace utf16 encoding with utf16 with specific endianness
if (encoding == encoding_utf16) return is_little_endian() ? encoding_utf16_le : encoding_utf16_be;
// replace utf32 encoding with utf32 with specific endianness
if (encoding == encoding_utf32) return is_little_endian() ? encoding_utf32_le : encoding_utf32_be;
// only do autodetection if no explicit encoding is requested
if (encoding != encoding_auto) return encoding;
// try to guess encoding (based on XML specification, Appendix F.1)
const uint8_t* data = static_cast<const uint8_t*>(contents);
return guess_buffer_encoding(data, size);
}
PUGI__FN bool get_mutable_buffer(char_t*& out_buffer, size_t& out_length, const void* contents, size_t size, bool is_mutable)
{
size_t length = size / sizeof(char_t);
if (is_mutable)
{
out_buffer = static_cast<char_t*>(const_cast<void*>(contents));
out_length = length;
}
else
{
char_t* buffer = static_cast<char_t*>(xml_memory::allocate((length + 1) * sizeof(char_t)));
if (!buffer) return false;
if (contents)
memcpy(buffer, contents, length * sizeof(char_t));
else
assert(length == 0);
buffer[length] = 0;
out_buffer = buffer;
out_length = length + 1;
}
return true;
}
#ifdef PUGIXML_WCHAR_MODE
PUGI__FN bool need_endian_swap_utf(xml_encoding le, xml_encoding re)
{
return (le == encoding_utf16_be && re == encoding_utf16_le) || (le == encoding_utf16_le && re == encoding_utf16_be) ||
(le == encoding_utf32_be && re == encoding_utf32_le) || (le == encoding_utf32_le && re == encoding_utf32_be);
}
PUGI__FN bool convert_buffer_endian_swap(char_t*& out_buffer, size_t& out_length, const void* contents, size_t size, bool is_mutable)
{
const char_t* data = static_cast<const char_t*>(contents);
size_t length = size / sizeof(char_t);
if (is_mutable)
{
char_t* buffer = const_cast<char_t*>(data);
convert_wchar_endian_swap(buffer, data, length);
out_buffer = buffer;
out_length = length;
}
else
{
char_t* buffer = static_cast<char_t*>(xml_memory::allocate((length + 1) * sizeof(char_t)));
if (!buffer) return false;
convert_wchar_endian_swap(buffer, data, length);
buffer[length] = 0;
out_buffer = buffer;
out_length = length + 1;
}
return true;
}
template <typename D> PUGI__FN bool convert_buffer_generic(char_t*& out_buffer, size_t& out_length, const void* contents, size_t size, D)
{
const typename D::type* data = static_cast<const typename D::type*>(contents);
size_t data_length = size / sizeof(typename D::type);
// first pass: get length in wchar_t units
size_t length = D::process(data, data_length, 0, wchar_counter());
// allocate buffer of suitable length
char_t* buffer = static_cast<char_t*>(xml_memory::allocate((length + 1) * sizeof(char_t)));
if (!buffer) return false;
// second pass: convert utf16 input to wchar_t
wchar_writer::value_type obegin = reinterpret_cast<wchar_writer::value_type>(buffer);
wchar_writer::value_type oend = D::process(data, data_length, obegin, wchar_writer());
assert(oend == obegin + length);
*oend = 0;
out_buffer = buffer;
out_length = length + 1;
return true;
}
PUGI__FN bool convert_buffer(char_t*& out_buffer, size_t& out_length, xml_encoding encoding, const void* contents, size_t size, bool is_mutable)
{
// get native encoding
xml_encoding wchar_encoding = get_wchar_encoding();
// fast path: no conversion required
if (encoding == wchar_encoding)
return get_mutable_buffer(out_buffer, out_length, contents, size, is_mutable);
// only endian-swapping is required
if (need_endian_swap_utf(encoding, wchar_encoding))
return convert_buffer_endian_swap(out_buffer, out_length, contents, size, is_mutable);
// source encoding is utf8
if (encoding == encoding_utf8)
return convert_buffer_generic(out_buffer, out_length, contents, size, utf8_decoder());
// source encoding is utf16
if (encoding == encoding_utf16_be || encoding == encoding_utf16_le)
{
xml_encoding native_encoding = is_little_endian() ? encoding_utf16_le : encoding_utf16_be;
return (native_encoding == encoding) ?
convert_buffer_generic(out_buffer, out_length, contents, size, utf16_decoder<opt_false>()) :
convert_buffer_generic(out_buffer, out_length, contents, size, utf16_decoder<opt_true>());
}
// source encoding is utf32
if (encoding == encoding_utf32_be || encoding == encoding_utf32_le)
{
xml_encoding native_encoding = is_little_endian() ? encoding_utf32_le : encoding_utf32_be;
return (native_encoding == encoding) ?
convert_buffer_generic(out_buffer, out_length, contents, size, utf32_decoder<opt_false>()) :
convert_buffer_generic(out_buffer, out_length, contents, size, utf32_decoder<opt_true>());
}
// source encoding is latin1
if (encoding == encoding_latin1)
return convert_buffer_generic(out_buffer, out_length, contents, size, latin1_decoder());
assert(false && "Invalid encoding"); // unreachable
return false;
}
#else
template <typename D> PUGI__FN bool convert_buffer_generic(char_t*& out_buffer, size_t& out_length, const void* contents, size_t size, D)
{
const typename D::type* data = static_cast<const typename D::type*>(contents);
size_t data_length = size / sizeof(typename D::type);
// first pass: get length in utf8 units
size_t length = D::process(data, data_length, 0, utf8_counter());
// allocate buffer of suitable length
char_t* buffer = static_cast<char_t*>(xml_memory::allocate((length + 1) * sizeof(char_t)));
if (!buffer) return false;
// second pass: convert utf16 input to utf8
uint8_t* obegin = reinterpret_cast<uint8_t*>(buffer);
uint8_t* oend = D::process(data, data_length, obegin, utf8_writer());
assert(oend == obegin + length);
*oend = 0;
out_buffer = buffer;
out_length = length + 1;
return true;
}
PUGI__FN size_t get_latin1_7bit_prefix_length(const uint8_t* data, size_t size)
{
for (size_t i = 0; i < size; ++i)
if (data[i] > 127)
return i;
return size;
}
PUGI__FN bool convert_buffer_latin1(char_t*& out_buffer, size_t& out_length, const void* contents, size_t size, bool is_mutable)
{
const uint8_t* data = static_cast<const uint8_t*>(contents);
size_t data_length = size;
// get size of prefix that does not need utf8 conversion
size_t prefix_length = get_latin1_7bit_prefix_length(data, data_length);
assert(prefix_length <= data_length);
const uint8_t* postfix = data + prefix_length;
size_t postfix_length = data_length - prefix_length;
// if no conversion is needed, just return the original buffer
if (postfix_length == 0) return get_mutable_buffer(out_buffer, out_length, contents, size, is_mutable);
// first pass: get length in utf8 units
size_t length = prefix_length + latin1_decoder::process(postfix, postfix_length, 0, utf8_counter());
// allocate buffer of suitable length
char_t* buffer = static_cast<char_t*>(xml_memory::allocate((length + 1) * sizeof(char_t)));
if (!buffer) return false;
// second pass: convert latin1 input to utf8
memcpy(buffer, data, prefix_length);
uint8_t* obegin = reinterpret_cast<uint8_t*>(buffer);
uint8_t* oend = latin1_decoder::process(postfix, postfix_length, obegin + prefix_length, utf8_writer());
assert(oend == obegin + length);
*oend = 0;
out_buffer = buffer;
out_length = length + 1;
return true;
}
PUGI__FN bool convert_buffer(char_t*& out_buffer, size_t& out_length, xml_encoding encoding, const void* contents, size_t size, bool is_mutable)
{
// fast path: no conversion required
if (encoding == encoding_utf8)
return get_mutable_buffer(out_buffer, out_length, contents, size, is_mutable);
// source encoding is utf16
if (encoding == encoding_utf16_be || encoding == encoding_utf16_le)
{
xml_encoding native_encoding = is_little_endian() ? encoding_utf16_le : encoding_utf16_be;
return (native_encoding == encoding) ?
convert_buffer_generic(out_buffer, out_length, contents, size, utf16_decoder<opt_false>()) :
convert_buffer_generic(out_buffer, out_length, contents, size, utf16_decoder<opt_true>());
}
// source encoding is utf32
if (encoding == encoding_utf32_be || encoding == encoding_utf32_le)
{
xml_encoding native_encoding = is_little_endian() ? encoding_utf32_le : encoding_utf32_be;
return (native_encoding == encoding) ?
convert_buffer_generic(out_buffer, out_length, contents, size, utf32_decoder<opt_false>()) :
convert_buffer_generic(out_buffer, out_length, contents, size, utf32_decoder<opt_true>());
}
// source encoding is latin1
if (encoding == encoding_latin1)
return convert_buffer_latin1(out_buffer, out_length, contents, size, is_mutable);
assert(false && "Invalid encoding"); // unreachable
return false;
}
#endif
PUGI__FN size_t as_utf8_begin(const wchar_t* str, size_t length)
{
// get length in utf8 characters
return wchar_decoder::process(str, length, 0, utf8_counter());
}
PUGI__FN void as_utf8_end(char* buffer, size_t size, const wchar_t* str, size_t length)
{
// convert to utf8
uint8_t* begin = reinterpret_cast<uint8_t*>(buffer);
uint8_t* end = wchar_decoder::process(str, length, begin, utf8_writer());
assert(begin + size == end);
(void)!end;
(void)!size;
}
#ifndef PUGIXML_NO_STL
PUGI__FN std::string as_utf8_impl(const wchar_t* str, size_t length)
{
// first pass: get length in utf8 characters
size_t size = as_utf8_begin(str, length);
// allocate resulting string
std::string result;
result.resize(size);
// second pass: convert to utf8
if (size > 0) as_utf8_end(&result[0], size, str, length);
return result;
}
PUGI__FN std::basic_string<wchar_t> as_wide_impl(const char* str, size_t size)
{
const uint8_t* data = reinterpret_cast<const uint8_t*>(str);
// first pass: get length in wchar_t units
size_t length = utf8_decoder::process(data, size, 0, wchar_counter());
// allocate resulting string
std::basic_string<wchar_t> result;
result.resize(length);
// second pass: convert to wchar_t
if (length > 0)
{
wchar_writer::value_type begin = reinterpret_cast<wchar_writer::value_type>(&result[0]);
wchar_writer::value_type end = utf8_decoder::process(data, size, begin, wchar_writer());
assert(begin + length == end);
(void)!end;
}
return result;
}
#endif
template <typename Header>
inline bool strcpy_insitu_allow(size_t length, const Header& header, uintptr_t header_mask, char_t* target)
{
// never reuse shared memory
if (header & xml_memory_page_contents_shared_mask) return false;
size_t target_length = strlength(target);
// always reuse document buffer memory if possible
if ((header & header_mask) == 0) return target_length >= length;
// reuse heap memory if waste is not too great
const size_t reuse_threshold = 32;
return target_length >= length && (target_length < reuse_threshold || target_length - length < target_length / 2);
}
template <typename String, typename Header>
PUGI__FN bool strcpy_insitu(String& dest, Header& header, uintptr_t header_mask, const char_t* source, size_t source_length)
{
if (source_length == 0)
{
// empty string and null pointer are equivalent, so just deallocate old memory
xml_allocator* alloc = PUGI__GETPAGE_IMPL(header)->allocator;
if (header & header_mask) alloc->deallocate_string(dest);
// mark the string as not allocated
dest = 0;
header &= ~header_mask;
return true;
}
else if (dest && strcpy_insitu_allow(source_length, header, header_mask, dest))
{
// we can reuse old buffer, so just copy the new data (including zero terminator)
memcpy(dest, source, source_length * sizeof(char_t));
dest[source_length] = 0;
return true;
}
else
{
xml_allocator* alloc = PUGI__GETPAGE_IMPL(header)->allocator;
if (!alloc->reserve()) return false;
// allocate new buffer
char_t* buf = alloc->allocate_string(source_length + 1);
if (!buf) return false;
// copy the string (including zero terminator)
memcpy(buf, source, source_length * sizeof(char_t));
buf[source_length] = 0;
// deallocate old buffer (*after* the above to protect against overlapping memory and/or allocation failures)
if (header & header_mask) alloc->deallocate_string(dest);
// the string is now allocated, so set the flag
dest = buf;
header |= header_mask;
return true;
}
}
struct gap
{
char_t* end;
size_t size;
gap(): end(0), size(0)
{
}
// Push new gap, move s count bytes further (skipping the gap).
// Collapse previous gap.
void push(char_t*& s, size_t count)
{
if (end) // there was a gap already; collapse it
{
// Move [old_gap_end, new_gap_start) to [old_gap_start, ...)
assert(s >= end);
memmove(end - size, end, reinterpret_cast<char*>(s) - reinterpret_cast<char*>(end));
}
s += count; // end of current gap
// "merge" two gaps
end = s;
size += count;
}
// Collapse all gaps, return past-the-end pointer
char_t* flush(char_t* s)
{
if (end)
{
// Move [old_gap_end, current_pos) to [old_gap_start, ...)
assert(s >= end);
memmove(end - size, end, reinterpret_cast<char*>(s) - reinterpret_cast<char*>(end));
return s - size;
}
else return s;
}
};
PUGI__FN char_t* strconv_escape(char_t* s, gap& g)
{
char_t* stre = s + 1;
switch (*stre)
{
case '#': // &#...
{
unsigned int ucsc = 0;
if (stre[1] == 'x') // &#x... (hex code)
{
stre += 2;
char_t ch = *stre;
if (ch == ';') return stre;
for (;;)
{
if (static_cast<unsigned int>(ch - '0') <= 9)
ucsc = 16 * ucsc + (ch - '0');
else if (static_cast<unsigned int>((ch | ' ') - 'a') <= 5)
ucsc = 16 * ucsc + ((ch | ' ') - 'a' + 10);
else if (ch == ';')
break;
else // cancel
return stre;
ch = *++stre;
}
++stre;
}
else // &#... (dec code)
{
char_t ch = *++stre;
if (ch == ';') return stre;
for (;;)
{
if (static_cast<unsigned int>(ch - '0') <= 9)
ucsc = 10 * ucsc + (ch - '0');
else if (ch == ';')
break;
else // cancel
return stre;
ch = *++stre;
}
++stre;
}
#ifdef PUGIXML_WCHAR_MODE
s = reinterpret_cast<char_t*>(wchar_writer::any(reinterpret_cast<wchar_writer::value_type>(s), ucsc));
#else
s = reinterpret_cast<char_t*>(utf8_writer::any(reinterpret_cast<uint8_t*>(s), ucsc));
#endif
g.push(s, stre - s);
return stre;
}
case 'a': // &a
{
++stre;
if (*stre == 'm') // &am
{
if (*++stre == 'p' && *++stre == ';') // &
{
*s++ = '&';
++stre;
g.push(s, stre - s);
return stre;
}
}
else if (*stre == 'p') // &ap
{
if (*++stre == 'o' && *++stre == 's' && *++stre == ';') // '
{
*s++ = '\'';
++stre;
g.push(s, stre - s);
return stre;
}
}
break;
}
case 'g': // &g
{
if (*++stre == 't' && *++stre == ';') // >
{
*s++ = '>';
++stre;
g.push(s, stre - s);
return stre;
}
break;
}
case 'l': // &l
{
if (*++stre == 't' && *++stre == ';') // <
{
*s++ = '<';
++stre;
g.push(s, stre - s);
return stre;
}
break;
}
case 'q': // &q
{
if (*++stre == 'u' && *++stre == 'o' && *++stre == 't' && *++stre == ';') // "
{
*s++ = '"';
++stre;
g.push(s, stre - s);
return stre;
}
break;
}
default:
break;
}
return stre;
}
// Parser utilities
#define PUGI__ENDSWITH(c, e) ((c) == (e) || ((c) == 0 && endch == (e)))
#define PUGI__SKIPWS() { while (PUGI__IS_CHARTYPE(*s, ct_space)) ++s; }
#define PUGI__OPTSET(OPT) ( optmsk & (OPT) )
#define PUGI__PUSHNODE(TYPE) { cursor = append_new_node(cursor, *alloc, TYPE); if (!cursor) PUGI__THROW_ERROR(status_out_of_memory, s); }
#define PUGI__POPNODE() { cursor = cursor->parent; }
#define PUGI__SCANFOR(X) { while (*s != 0 && !(X)) ++s; }
#define PUGI__SCANWHILE(X) { while (X) ++s; }
#define PUGI__SCANWHILE_UNROLL(X) { for (;;) { char_t ss = s[0]; if (PUGI__UNLIKELY(!(X))) { break; } ss = s[1]; if (PUGI__UNLIKELY(!(X))) { s += 1; break; } ss = s[2]; if (PUGI__UNLIKELY(!(X))) { s += 2; break; } ss = s[3]; if (PUGI__UNLIKELY(!(X))) { s += 3; break; } s += 4; } }
#define PUGI__ENDSEG() { ch = *s; *s = 0; ++s; }
#define PUGI__THROW_ERROR(err, m) return error_offset = m, error_status = err, static_cast<char_t*>(0)
#define PUGI__CHECK_ERROR(err, m) { if (*s == 0) PUGI__THROW_ERROR(err, m); }
PUGI__FN char_t* strconv_comment(char_t* s, char_t endch)
{
gap g;
while (true)
{
PUGI__SCANWHILE_UNROLL(!PUGI__IS_CHARTYPE(ss, ct_parse_comment));
if (*s == '\r') // Either a single 0x0d or 0x0d 0x0a pair
{
*s++ = '\n'; // replace first one with 0x0a
if (*s == '\n') g.push(s, 1);
}
else if (s[0] == '-' && s[1] == '-' && PUGI__ENDSWITH(s[2], '>')) // comment ends here
{
*g.flush(s) = 0;
return s + (s[2] == '>' ? 3 : 2);
}
else if (*s == 0)
{
return 0;
}
else ++s;
}
}
PUGI__FN char_t* strconv_cdata(char_t* s, char_t endch)
{
gap g;
while (true)
{
PUGI__SCANWHILE_UNROLL(!PUGI__IS_CHARTYPE(ss, ct_parse_cdata));
if (*s == '\r') // Either a single 0x0d or 0x0d 0x0a pair
{
*s++ = '\n'; // replace first one with 0x0a
if (*s == '\n') g.push(s, 1);
}
else if (s[0] == ']' && s[1] == ']' && PUGI__ENDSWITH(s[2], '>')) // CDATA ends here
{
*g.flush(s) = 0;
return s + 1;
}
else if (*s == 0)
{
return 0;
}
else ++s;
}
}
typedef char_t* (*strconv_pcdata_t)(char_t*);
template <typename opt_trim, typename opt_eol, typename opt_escape> struct strconv_pcdata_impl
{
static char_t* parse(char_t* s)
{
gap g;
char_t* begin = s;
while (true)
{
PUGI__SCANWHILE_UNROLL(!PUGI__IS_CHARTYPE(ss, ct_parse_pcdata));
if (*s == '<') // PCDATA ends here
{
char_t* end = g.flush(s);
if (opt_trim::value)
while (end > begin && PUGI__IS_CHARTYPE(end[-1], ct_space))
--end;
*end = 0;
return s + 1;
}
else if (opt_eol::value && *s == '\r') // Either a single 0x0d or 0x0d 0x0a pair
{
*s++ = '\n'; // replace first one with 0x0a
if (*s == '\n') g.push(s, 1);
}
else if (opt_escape::value && *s == '&')
{
s = strconv_escape(s, g);
}
else if (*s == 0)
{
char_t* end = g.flush(s);
if (opt_trim::value)
while (end > begin && PUGI__IS_CHARTYPE(end[-1], ct_space))
--end;
*end = 0;
return s;
}
else ++s;
}
}
};
PUGI__FN strconv_pcdata_t get_strconv_pcdata(unsigned int optmask)
{
PUGI__STATIC_ASSERT(parse_escapes == 0x10 && parse_eol == 0x20 && parse_trim_pcdata == 0x0800);
switch (((optmask >> 4) & 3) | ((optmask >> 9) & 4)) // get bitmask for flags (trim eol escapes); this simultaneously checks 3 options from assertion above
{
case 0: return strconv_pcdata_impl<opt_false, opt_false, opt_false>::parse;
case 1: return strconv_pcdata_impl<opt_false, opt_false, opt_true>::parse;
case 2: return strconv_pcdata_impl<opt_false, opt_true, opt_false>::parse;
case 3: return strconv_pcdata_impl<opt_false, opt_true, opt_true>::parse;
case 4: return strconv_pcdata_impl<opt_true, opt_false, opt_false>::parse;
case 5: return strconv_pcdata_impl<opt_true, opt_false, opt_true>::parse;
case 6: return strconv_pcdata_impl<opt_true, opt_true, opt_false>::parse;
case 7: return strconv_pcdata_impl<opt_true, opt_true, opt_true>::parse;
default: assert(false); return 0; // unreachable
}
}
typedef char_t* (*strconv_attribute_t)(char_t*, char_t);
template <typename opt_escape> struct strconv_attribute_impl
{
static char_t* parse_wnorm(char_t* s, char_t end_quote)
{
gap g;
// trim leading whitespaces
if (PUGI__IS_CHARTYPE(*s, ct_space))
{
char_t* str = s;
do ++str;
while (PUGI__IS_CHARTYPE(*str, ct_space));
g.push(s, str - s);
}
while (true)
{
PUGI__SCANWHILE_UNROLL(!PUGI__IS_CHARTYPE(ss, ct_parse_attr_ws | ct_space));
if (*s == end_quote)
{
char_t* str = g.flush(s);
do *str-- = 0;
while (PUGI__IS_CHARTYPE(*str, ct_space));
return s + 1;
}
else if (PUGI__IS_CHARTYPE(*s, ct_space))
{
*s++ = ' ';
if (PUGI__IS_CHARTYPE(*s, ct_space))
{
char_t* str = s + 1;
while (PUGI__IS_CHARTYPE(*str, ct_space)) ++str;
g.push(s, str - s);
}
}
else if (opt_escape::value && *s == '&')
{
s = strconv_escape(s, g);
}
else if (!*s)
{
return 0;
}
else ++s;
}
}
static char_t* parse_wconv(char_t* s, char_t end_quote)
{
gap g;
while (true)
{
PUGI__SCANWHILE_UNROLL(!PUGI__IS_CHARTYPE(ss, ct_parse_attr_ws));
if (*s == end_quote)
{
*g.flush(s) = 0;
return s + 1;
}
else if (PUGI__IS_CHARTYPE(*s, ct_space))
{
if (*s == '\r')
{
*s++ = ' ';
if (*s == '\n') g.push(s, 1);
}
else *s++ = ' ';
}
else if (opt_escape::value && *s == '&')
{
s = strconv_escape(s, g);
}
else if (!*s)
{
return 0;
}
else ++s;
}
}
static char_t* parse_eol(char_t* s, char_t end_quote)
{
gap g;
while (true)
{
PUGI__SCANWHILE_UNROLL(!PUGI__IS_CHARTYPE(ss, ct_parse_attr));
if (*s == end_quote)
{
*g.flush(s) = 0;
return s + 1;
}
else if (*s == '\r')
{
*s++ = '\n';
if (*s == '\n') g.push(s, 1);
}
else if (opt_escape::value && *s == '&')
{
s = strconv_escape(s, g);
}
else if (!*s)
{
return 0;
}
else ++s;
}
}
static char_t* parse_simple(char_t* s, char_t end_quote)
{
gap g;
while (true)
{
PUGI__SCANWHILE_UNROLL(!PUGI__IS_CHARTYPE(ss, ct_parse_attr));
if (*s == end_quote)
{
*g.flush(s) = 0;
return s + 1;
}
else if (opt_escape::value && *s == '&')
{
s = strconv_escape(s, g);
}
else if (!*s)
{
return 0;
}
else ++s;
}
}
};
PUGI__FN strconv_attribute_t get_strconv_attribute(unsigned int optmask)
{
PUGI__STATIC_ASSERT(parse_escapes == 0x10 && parse_eol == 0x20 && parse_wconv_attribute == 0x40 && parse_wnorm_attribute == 0x80);
switch ((optmask >> 4) & 15) // get bitmask for flags (wnorm wconv eol escapes); this simultaneously checks 4 options from assertion above
{
case 0: return strconv_attribute_impl<opt_false>::parse_simple;
case 1: return strconv_attribute_impl<opt_true>::parse_simple;
case 2: return strconv_attribute_impl<opt_false>::parse_eol;
case 3: return strconv_attribute_impl<opt_true>::parse_eol;
case 4: return strconv_attribute_impl<opt_false>::parse_wconv;
case 5: return strconv_attribute_impl<opt_true>::parse_wconv;
case 6: return strconv_attribute_impl<opt_false>::parse_wconv;
case 7: return strconv_attribute_impl<opt_true>::parse_wconv;
case 8: return strconv_attribute_impl<opt_false>::parse_wnorm;
case 9: return strconv_attribute_impl<opt_true>::parse_wnorm;
case 10: return strconv_attribute_impl<opt_false>::parse_wnorm;
case 11: return strconv_attribute_impl<opt_true>::parse_wnorm;
case 12: return strconv_attribute_impl<opt_false>::parse_wnorm;
case 13: return strconv_attribute_impl<opt_true>::parse_wnorm;
case 14: return strconv_attribute_impl<opt_false>::parse_wnorm;
case 15: return strconv_attribute_impl<opt_true>::parse_wnorm;
default: assert(false); return 0; // unreachable
}
}
inline xml_parse_result make_parse_result(xml_parse_status status, ptrdiff_t offset = 0)
{
xml_parse_result result;
result.status = status;
result.offset = offset;
return result;
}
struct xml_parser
{
xml_allocator* alloc;
char_t* error_offset;
xml_parse_status error_status;
xml_parser(xml_allocator* alloc_): alloc(alloc_), error_offset(0), error_status(status_ok)
{
}
// DOCTYPE consists of nested sections of the following possible types:
// <!-- ... -->, <? ... ?>, "...", '...'
// <![...]]>
// <!...>
// First group can not contain nested groups
// Second group can contain nested groups of the same type
// Third group can contain all other groups
char_t* parse_doctype_primitive(char_t* s)
{
if (*s == '"' || *s == '\'')
{
// quoted string
char_t ch = *s++;
PUGI__SCANFOR(*s == ch);
if (!*s) PUGI__THROW_ERROR(status_bad_doctype, s);
s++;
}
else if (s[0] == '<' && s[1] == '?')
{
// <? ... ?>
s += 2;
PUGI__SCANFOR(s[0] == '?' && s[1] == '>'); // no need for ENDSWITH because ?> can't terminate proper doctype
if (!*s) PUGI__THROW_ERROR(status_bad_doctype, s);
s += 2;
}
else if (s[0] == '<' && s[1] == '!' && s[2] == '-' && s[3] == '-')
{
s += 4;
PUGI__SCANFOR(s[0] == '-' && s[1] == '-' && s[2] == '>'); // no need for ENDSWITH because --> can't terminate proper doctype
if (!*s) PUGI__THROW_ERROR(status_bad_doctype, s);
s += 3;
}
else PUGI__THROW_ERROR(status_bad_doctype, s);
return s;
}
char_t* parse_doctype_ignore(char_t* s)
{
size_t depth = 0;
assert(s[0] == '<' && s[1] == '!' && s[2] == '[');
s += 3;
while (*s)
{
if (s[0] == '<' && s[1] == '!' && s[2] == '[')
{
// nested ignore section
s += 3;
depth++;
}
else if (s[0] == ']' && s[1] == ']' && s[2] == '>')
{
// ignore section end
s += 3;
if (depth == 0)
return s;
depth--;
}
else s++;
}
PUGI__THROW_ERROR(status_bad_doctype, s);
}
char_t* parse_doctype_group(char_t* s, char_t endch)
{
size_t depth = 0;
assert((s[0] == '<' || s[0] == 0) && s[1] == '!');
s += 2;
while (*s)
{
if (s[0] == '<' && s[1] == '!' && s[2] != '-')
{
if (s[2] == '[')
{
// ignore
s = parse_doctype_ignore(s);
if (!s) return s;
}
else
{
// some control group
s += 2;
depth++;
}
}
else if (s[0] == '<' || s[0] == '"' || s[0] == '\'')
{
// unknown tag (forbidden), or some primitive group
s = parse_doctype_primitive(s);
if (!s) return s;
}
else if (*s == '>')
{
if (depth == 0)
return s;
depth--;
s++;
}
else s++;
}
if (depth != 0 || endch != '>') PUGI__THROW_ERROR(status_bad_doctype, s);
return s;
}
char_t* parse_exclamation(char_t* s, xml_node_struct* cursor, unsigned int optmsk, char_t endch)
{
// parse node contents, starting with exclamation mark
++s;
if (*s == '-') // '<!-...'
{
++s;
if (*s == '-') // '<!--...'
{
++s;
if (PUGI__OPTSET(parse_comments))
{
PUGI__PUSHNODE(node_comment); // Append a new node on the tree.
cursor->value = s; // Save the offset.
}
if (PUGI__OPTSET(parse_eol) && PUGI__OPTSET(parse_comments))
{
s = strconv_comment(s, endch);
if (!s) PUGI__THROW_ERROR(status_bad_comment, cursor->value);
}
else
{
// Scan for terminating '-->'.
PUGI__SCANFOR(s[0] == '-' && s[1] == '-' && PUGI__ENDSWITH(s[2], '>'));
PUGI__CHECK_ERROR(status_bad_comment, s);
if (PUGI__OPTSET(parse_comments))
*s = 0; // Zero-terminate this segment at the first terminating '-'.
s += (s[2] == '>' ? 3 : 2); // Step over the '\0->'.
}
}
else PUGI__THROW_ERROR(status_bad_comment, s);
}
else if (*s == '[')
{
// '<![CDATA[...'
if (*++s=='C' && *++s=='D' && *++s=='A' && *++s=='T' && *++s=='A' && *++s == '[')
{
++s;
if (PUGI__OPTSET(parse_cdata))
{
PUGI__PUSHNODE(node_cdata); // Append a new node on the tree.
cursor->value = s; // Save the offset.
if (PUGI__OPTSET(parse_eol))
{
s = strconv_cdata(s, endch);
if (!s) PUGI__THROW_ERROR(status_bad_cdata, cursor->value);
}
else
{
// Scan for terminating ']]>'.
PUGI__SCANFOR(s[0] == ']' && s[1] == ']' && PUGI__ENDSWITH(s[2], '>'));
PUGI__CHECK_ERROR(status_bad_cdata, s);
*s++ = 0; // Zero-terminate this segment.
}
}
else // Flagged for discard, but we still have to scan for the terminator.
{
// Scan for terminating ']]>'.
PUGI__SCANFOR(s[0] == ']' && s[1] == ']' && PUGI__ENDSWITH(s[2], '>'));
PUGI__CHECK_ERROR(status_bad_cdata, s);
++s;
}
s += (s[1] == '>' ? 2 : 1); // Step over the last ']>'.
}
else PUGI__THROW_ERROR(status_bad_cdata, s);
}
else if (s[0] == 'D' && s[1] == 'O' && s[2] == 'C' && s[3] == 'T' && s[4] == 'Y' && s[5] == 'P' && PUGI__ENDSWITH(s[6], 'E'))
{
s -= 2;
if (cursor->parent) PUGI__THROW_ERROR(status_bad_doctype, s);
char_t* mark = s + 9;
s = parse_doctype_group(s, endch);
if (!s) return s;
assert((*s == 0 && endch == '>') || *s == '>');
if (*s) *s++ = 0;
if (PUGI__OPTSET(parse_doctype))
{
while (PUGI__IS_CHARTYPE(*mark, ct_space)) ++mark;
PUGI__PUSHNODE(node_doctype);
cursor->value = mark;
}
}
else if (*s == 0 && endch == '-') PUGI__THROW_ERROR(status_bad_comment, s);
else if (*s == 0 && endch == '[') PUGI__THROW_ERROR(status_bad_cdata, s);
else PUGI__THROW_ERROR(status_unrecognized_tag, s);
return s;
}
char_t* parse_question(char_t* s, xml_node_struct*& ref_cursor, unsigned int optmsk, char_t endch)
{
// load into registers
xml_node_struct* cursor = ref_cursor;
char_t ch = 0;
// parse node contents, starting with question mark
++s;
// read PI target
char_t* target = s;
if (!PUGI__IS_CHARTYPE(*s, ct_start_symbol)) PUGI__THROW_ERROR(status_bad_pi, s);
PUGI__SCANWHILE(PUGI__IS_CHARTYPE(*s, ct_symbol));
PUGI__CHECK_ERROR(status_bad_pi, s);
// determine node type; stricmp / strcasecmp is not portable
bool declaration = (target[0] | ' ') == 'x' && (target[1] | ' ') == 'm' && (target[2] | ' ') == 'l' && target + 3 == s;
if (declaration ? PUGI__OPTSET(parse_declaration) : PUGI__OPTSET(parse_pi))
{
if (declaration)
{
// disallow non top-level declarations
if (cursor->parent) PUGI__THROW_ERROR(status_bad_pi, s);
PUGI__PUSHNODE(node_declaration);
}
else
{
PUGI__PUSHNODE(node_pi);
}
cursor->name = target;
PUGI__ENDSEG();
// parse value/attributes
if (ch == '?')
{
// empty node
if (!PUGI__ENDSWITH(*s, '>')) PUGI__THROW_ERROR(status_bad_pi, s);
s += (*s == '>');
PUGI__POPNODE();
}
else if (PUGI__IS_CHARTYPE(ch, ct_space))
{
PUGI__SKIPWS();
// scan for tag end
char_t* value = s;
PUGI__SCANFOR(s[0] == '?' && PUGI__ENDSWITH(s[1], '>'));
PUGI__CHECK_ERROR(status_bad_pi, s);
if (declaration)
{
// replace ending ? with / so that 'element' terminates properly
*s = '/';
// we exit from this function with cursor at node_declaration, which is a signal to parse() to go to LOC_ATTRIBUTES
s = value;
}
else
{
// store value and step over >
cursor->value = value;
PUGI__POPNODE();
PUGI__ENDSEG();
s += (*s == '>');
}
}
else PUGI__THROW_ERROR(status_bad_pi, s);
}
else
{
// scan for tag end
PUGI__SCANFOR(s[0] == '?' && PUGI__ENDSWITH(s[1], '>'));
PUGI__CHECK_ERROR(status_bad_pi, s);
s += (s[1] == '>' ? 2 : 1);
}
// store from registers
ref_cursor = cursor;
return s;
}
char_t* parse_tree(char_t* s, xml_node_struct* root, unsigned int optmsk, char_t endch)
{
strconv_attribute_t strconv_attribute = get_strconv_attribute(optmsk);
strconv_pcdata_t strconv_pcdata = get_strconv_pcdata(optmsk);
char_t ch = 0;
xml_node_struct* cursor = root;
char_t* mark = s;
while (*s != 0)
{
if (*s == '<')
{
++s;
LOC_TAG:
if (PUGI__IS_CHARTYPE(*s, ct_start_symbol)) // '<#...'
{
PUGI__PUSHNODE(node_element); // Append a new node to the tree.
cursor->name = s;
PUGI__SCANWHILE_UNROLL(PUGI__IS_CHARTYPE(ss, ct_symbol)); // Scan for a terminator.
PUGI__ENDSEG(); // Save char in 'ch', terminate & step over.
if (ch == '>')
{
// end of tag
}
else if (PUGI__IS_CHARTYPE(ch, ct_space))
{
LOC_ATTRIBUTES:
while (true)
{
PUGI__SKIPWS(); // Eat any whitespace.
if (PUGI__IS_CHARTYPE(*s, ct_start_symbol)) // <... #...
{
xml_attribute_struct* a = append_new_attribute(cursor, *alloc); // Make space for this attribute.
if (!a) PUGI__THROW_ERROR(status_out_of_memory, s);
a->name = s; // Save the offset.
PUGI__SCANWHILE_UNROLL(PUGI__IS_CHARTYPE(ss, ct_symbol)); // Scan for a terminator.
PUGI__ENDSEG(); // Save char in 'ch', terminate & step over.
if (PUGI__IS_CHARTYPE(ch, ct_space))
{
PUGI__SKIPWS(); // Eat any whitespace.
ch = *s;
++s;
}
if (ch == '=') // '<... #=...'
{
PUGI__SKIPWS(); // Eat any whitespace.
if (*s == '"' || *s == '\'') // '<... #="...'
{
ch = *s; // Save quote char to avoid breaking on "''" -or- '""'.
++s; // Step over the quote.
a->value = s; // Save the offset.
s = strconv_attribute(s, ch);
if (!s) PUGI__THROW_ERROR(status_bad_attribute, a->value);
// After this line the loop continues from the start;
// Whitespaces, / and > are ok, symbols and EOF are wrong,
// everything else will be detected
if (PUGI__IS_CHARTYPE(*s, ct_start_symbol)) PUGI__THROW_ERROR(status_bad_attribute, s);
}
else PUGI__THROW_ERROR(status_bad_attribute, s);
}
else PUGI__THROW_ERROR(status_bad_attribute, s);
}
else if (*s == '/')
{
++s;
if (*s == '>')
{
PUGI__POPNODE();
s++;
break;
}
else if (*s == 0 && endch == '>')
{
PUGI__POPNODE();
break;
}
else PUGI__THROW_ERROR(status_bad_start_element, s);
}
else if (*s == '>')
{
++s;
break;
}
else if (*s == 0 && endch == '>')
{
break;
}
else PUGI__THROW_ERROR(status_bad_start_element, s);
}
// !!!
}
else if (ch == '/') // '<#.../'
{
if (!PUGI__ENDSWITH(*s, '>')) PUGI__THROW_ERROR(status_bad_start_element, s);
PUGI__POPNODE(); // Pop.
s += (*s == '>');
}
else if (ch == 0)
{
// we stepped over null terminator, backtrack & handle closing tag
--s;
if (endch != '>') PUGI__THROW_ERROR(status_bad_start_element, s);
}
else PUGI__THROW_ERROR(status_bad_start_element, s);
}
else if (*s == '/')
{
++s;
mark = s;
char_t* name = cursor->name;
if (!name) PUGI__THROW_ERROR(status_end_element_mismatch, mark);
while (PUGI__IS_CHARTYPE(*s, ct_symbol))
{
if (*s++ != *name++) PUGI__THROW_ERROR(status_end_element_mismatch, mark);
}
if (*name)
{
if (*s == 0 && name[0] == endch && name[1] == 0) PUGI__THROW_ERROR(status_bad_end_element, s);
else PUGI__THROW_ERROR(status_end_element_mismatch, mark);
}
PUGI__POPNODE(); // Pop.
PUGI__SKIPWS();
if (*s == 0)
{
if (endch != '>') PUGI__THROW_ERROR(status_bad_end_element, s);
}
else
{
if (*s != '>') PUGI__THROW_ERROR(status_bad_end_element, s);
++s;
}
}
else if (*s == '?') // '<?...'
{
s = parse_question(s, cursor, optmsk, endch);
if (!s) return s;
assert(cursor);
if (PUGI__NODETYPE(cursor) == node_declaration) goto LOC_ATTRIBUTES;
}
else if (*s == '!') // '<!...'
{
s = parse_exclamation(s, cursor, optmsk, endch);
if (!s) return s;
}
else if (*s == 0 && endch == '?') PUGI__THROW_ERROR(status_bad_pi, s);
else PUGI__THROW_ERROR(status_unrecognized_tag, s);
}
else
{
mark = s; // Save this offset while searching for a terminator.
PUGI__SKIPWS(); // Eat whitespace if no genuine PCDATA here.
if (*s == '<' || !*s)
{
// We skipped some whitespace characters because otherwise we would take the tag branch instead of PCDATA one
assert(mark != s);
if (!PUGI__OPTSET(parse_ws_pcdata | parse_ws_pcdata_single) || PUGI__OPTSET(parse_trim_pcdata))
{
continue;
}
else if (PUGI__OPTSET(parse_ws_pcdata_single))
{
if (s[0] != '<' || s[1] != '/' || cursor->first_child) continue;
}
}
if (!PUGI__OPTSET(parse_trim_pcdata))
s = mark;
if (cursor->parent || PUGI__OPTSET(parse_fragment))
{
if (PUGI__OPTSET(parse_embed_pcdata) && cursor->parent && !cursor->first_child && !cursor->value)
{
cursor->value = s; // Save the offset.
}
else
{
PUGI__PUSHNODE(node_pcdata); // Append a new node on the tree.
cursor->value = s; // Save the offset.
PUGI__POPNODE(); // Pop since this is a standalone.
}
s = strconv_pcdata(s);
if (!*s) break;
}
else
{
PUGI__SCANFOR(*s == '<'); // '...<'
if (!*s) break;
++s;
}
// We're after '<'
goto LOC_TAG;
}
}
// check that last tag is closed
if (cursor != root) PUGI__THROW_ERROR(status_end_element_mismatch, s);
return s;
}
#ifdef PUGIXML_WCHAR_MODE
static char_t* parse_skip_bom(char_t* s)
{
unsigned int bom = 0xfeff;
return (s[0] == static_cast<wchar_t>(bom)) ? s + 1 : s;
}
#else
static char_t* parse_skip_bom(char_t* s)
{
return (s[0] == '\xef' && s[1] == '\xbb' && s[2] == '\xbf') ? s + 3 : s;
}
#endif
static bool has_element_node_siblings(xml_node_struct* node)
{
while (node)
{
if (PUGI__NODETYPE(node) == node_element) return true;
node = node->next_sibling;
}
return false;
}
static xml_parse_result parse(char_t* buffer, size_t length, xml_document_struct* xmldoc, xml_node_struct* root, unsigned int optmsk)
{
// early-out for empty documents
if (length == 0)
return make_parse_result(PUGI__OPTSET(parse_fragment) ? status_ok : status_no_document_element);
// get last child of the root before parsing
xml_node_struct* last_root_child = root->first_child ? root->first_child->prev_sibling_c + 0 : 0;
// create parser on stack
xml_parser parser(static_cast<xml_allocator*>(xmldoc));
// save last character and make buffer zero-terminated (speeds up parsing)
char_t endch = buffer[length - 1];
buffer[length - 1] = 0;
// skip BOM to make sure it does not end up as part of parse output
char_t* buffer_data = parse_skip_bom(buffer);
// perform actual parsing
parser.parse_tree(buffer_data, root, optmsk, endch);
xml_parse_result result = make_parse_result(parser.error_status, parser.error_offset ? parser.error_offset - buffer : 0);
assert(result.offset >= 0 && static_cast<size_t>(result.offset) <= length);
if (result)
{
// since we removed last character, we have to handle the only possible false positive (stray <)
if (endch == '<')
return make_parse_result(status_unrecognized_tag, length - 1);
// check if there are any element nodes parsed
xml_node_struct* first_root_child_parsed = last_root_child ? last_root_child->next_sibling + 0 : root->first_child+ 0;
if (!PUGI__OPTSET(parse_fragment) && !has_element_node_siblings(first_root_child_parsed))
return make_parse_result(status_no_document_element, length - 1);
}
else
{
// roll back offset if it occurs on a null terminator in the source buffer
if (result.offset > 0 && static_cast<size_t>(result.offset) == length - 1 && endch == 0)
result.offset--;
}
return result;
}
};
// Output facilities
PUGI__FN xml_encoding get_write_native_encoding()
{
#ifdef PUGIXML_WCHAR_MODE
return get_wchar_encoding();
#else
return encoding_utf8;
#endif
}
PUGI__FN xml_encoding get_write_encoding(xml_encoding encoding)
{
// replace wchar encoding with utf implementation
if (encoding == encoding_wchar) return get_wchar_encoding();
// replace utf16 encoding with utf16 with specific endianness
if (encoding == encoding_utf16) return is_little_endian() ? encoding_utf16_le : encoding_utf16_be;
// replace utf32 encoding with utf32 with specific endianness
if (encoding == encoding_utf32) return is_little_endian() ? encoding_utf32_le : encoding_utf32_be;
// only do autodetection if no explicit encoding is requested
if (encoding != encoding_auto) return encoding;
// assume utf8 encoding
return encoding_utf8;
}
template <typename D, typename T> PUGI__FN size_t convert_buffer_output_generic(typename T::value_type dest, const char_t* data, size_t length, D, T)
{
PUGI__STATIC_ASSERT(sizeof(char_t) == sizeof(typename D::type));
typename T::value_type end = D::process(reinterpret_cast<const typename D::type*>(data), length, dest, T());
return static_cast<size_t>(end - dest) * sizeof(*dest);
}
template <typename D, typename T> PUGI__FN size_t convert_buffer_output_generic(typename T::value_type dest, const char_t* data, size_t length, D, T, bool opt_swap)
{
PUGI__STATIC_ASSERT(sizeof(char_t) == sizeof(typename D::type));
typename T::value_type end = D::process(reinterpret_cast<const typename D::type*>(data), length, dest, T());
if (opt_swap)
{
for (typename T::value_type i = dest; i != end; ++i)
*i = endian_swap(*i);
}
return static_cast<size_t>(end - dest) * sizeof(*dest);
}
#ifdef PUGIXML_WCHAR_MODE
PUGI__FN size_t get_valid_length(const char_t* data, size_t length)
{
if (length < 1) return 0;
// discard last character if it's the lead of a surrogate pair
return (sizeof(wchar_t) == 2 && static_cast<unsigned int>(static_cast<uint16_t>(data[length - 1]) - 0xD800) < 0x400) ? length - 1 : length;
}
PUGI__FN size_t convert_buffer_output(char_t* r_char, uint8_t* r_u8, uint16_t* r_u16, uint32_t* r_u32, const char_t* data, size_t length, xml_encoding encoding)
{
// only endian-swapping is required
if (need_endian_swap_utf(encoding, get_wchar_encoding()))
{
convert_wchar_endian_swap(r_char, data, length);
return length * sizeof(char_t);
}
// convert to utf8
if (encoding == encoding_utf8)
return convert_buffer_output_generic(r_u8, data, length, wchar_decoder(), utf8_writer());
// convert to utf16
if (encoding == encoding_utf16_be || encoding == encoding_utf16_le)
{
xml_encoding native_encoding = is_little_endian() ? encoding_utf16_le : encoding_utf16_be;
return convert_buffer_output_generic(r_u16, data, length, wchar_decoder(), utf16_writer(), native_encoding != encoding);
}
// convert to utf32
if (encoding == encoding_utf32_be || encoding == encoding_utf32_le)
{
xml_encoding native_encoding = is_little_endian() ? encoding_utf32_le : encoding_utf32_be;
return convert_buffer_output_generic(r_u32, data, length, wchar_decoder(), utf32_writer(), native_encoding != encoding);
}
// convert to latin1
if (encoding == encoding_latin1)
return convert_buffer_output_generic(r_u8, data, length, wchar_decoder(), latin1_writer());
assert(false && "Invalid encoding"); // unreachable
return 0;
}
#else
PUGI__FN size_t get_valid_length(const char_t* data, size_t length)
{
if (length < 5) return 0;
for (size_t i = 1; i <= 4; ++i)
{
uint8_t ch = static_cast<uint8_t>(data[length - i]);
// either a standalone character or a leading one
if ((ch & 0xc0) != 0x80) return length - i;
}
// there are four non-leading characters at the end, sequence tail is broken so might as well process the whole chunk
return length;
}
PUGI__FN size_t convert_buffer_output(char_t* /* r_char */, uint8_t* r_u8, uint16_t* r_u16, uint32_t* r_u32, const char_t* data, size_t length, xml_encoding encoding)
{
if (encoding == encoding_utf16_be || encoding == encoding_utf16_le)
{
xml_encoding native_encoding = is_little_endian() ? encoding_utf16_le : encoding_utf16_be;
return convert_buffer_output_generic(r_u16, data, length, utf8_decoder(), utf16_writer(), native_encoding != encoding);
}
if (encoding == encoding_utf32_be || encoding == encoding_utf32_le)
{
xml_encoding native_encoding = is_little_endian() ? encoding_utf32_le : encoding_utf32_be;
return convert_buffer_output_generic(r_u32, data, length, utf8_decoder(), utf32_writer(), native_encoding != encoding);
}
if (encoding == encoding_latin1)
return convert_buffer_output_generic(r_u8, data, length, utf8_decoder(), latin1_writer());
assert(false && "Invalid encoding"); // unreachable
return 0;
}
#endif
class xml_buffered_writer
{
xml_buffered_writer(const xml_buffered_writer&);
xml_buffered_writer& operator=(const xml_buffered_writer&);
public:
xml_buffered_writer(xml_writer& writer_, xml_encoding user_encoding): writer(writer_), bufsize(0), encoding(get_write_encoding(user_encoding))
{
PUGI__STATIC_ASSERT(bufcapacity >= 8);
}
size_t flush()
{
flush(buffer, bufsize);
bufsize = 0;
return 0;
}
void flush(const char_t* data, size_t size)
{
if (size == 0) return;
// fast path, just write data
if (encoding == get_write_native_encoding())
writer.write(data, size * sizeof(char_t));
else
{
// convert chunk
size_t result = convert_buffer_output(scratch.data_char, scratch.data_u8, scratch.data_u16, scratch.data_u32, data, size, encoding);
assert(result <= sizeof(scratch));
// write data
writer.write(scratch.data_u8, result);
}
}
void write_direct(const char_t* data, size_t length)
{
// flush the remaining buffer contents
flush();
// handle large chunks
if (length > bufcapacity)
{
if (encoding == get_write_native_encoding())
{
// fast path, can just write data chunk
writer.write(data, length * sizeof(char_t));
return;
}
// need to convert in suitable chunks
while (length > bufcapacity)
{
// get chunk size by selecting such number of characters that are guaranteed to fit into scratch buffer
// and form a complete codepoint sequence (i.e. discard start of last codepoint if necessary)
size_t chunk_size = get_valid_length(data, bufcapacity);
assert(chunk_size);
// convert chunk and write
flush(data, chunk_size);
// iterate
data += chunk_size;
length -= chunk_size;
}
// small tail is copied below
bufsize = 0;
}
memcpy(buffer + bufsize, data, length * sizeof(char_t));
bufsize += length;
}
void write_buffer(const char_t* data, size_t length)
{
size_t offset = bufsize;
if (offset + length <= bufcapacity)
{
memcpy(buffer + offset, data, length * sizeof(char_t));
bufsize = offset + length;
}
else
{
write_direct(data, length);
}
}
void write_string(const char_t* data)
{
// write the part of the string that fits in the buffer
size_t offset = bufsize;
while (*data && offset < bufcapacity)
buffer[offset++] = *data++;
// write the rest
if (offset < bufcapacity)
{
bufsize = offset;
}
else
{
// backtrack a bit if we have split the codepoint
size_t length = offset - bufsize;
size_t extra = length - get_valid_length(data - length, length);
bufsize = offset - extra;
write_direct(data - extra, strlength(data) + extra);
}
}
void write(char_t d0)
{
size_t offset = bufsize;
if (offset > bufcapacity - 1) offset = flush();
buffer[offset + 0] = d0;
bufsize = offset + 1;
}
void write(char_t d0, char_t d1)
{
size_t offset = bufsize;
if (offset > bufcapacity - 2) offset = flush();
buffer[offset + 0] = d0;
buffer[offset + 1] = d1;
bufsize = offset + 2;
}
void write(char_t d0, char_t d1, char_t d2)
{
size_t offset = bufsize;
if (offset > bufcapacity - 3) offset = flush();
buffer[offset + 0] = d0;
buffer[offset + 1] = d1;
buffer[offset + 2] = d2;
bufsize = offset + 3;
}
void write(char_t d0, char_t d1, char_t d2, char_t d3)
{
size_t offset = bufsize;
if (offset > bufcapacity - 4) offset = flush();
buffer[offset + 0] = d0;
buffer[offset + 1] = d1;
buffer[offset + 2] = d2;
buffer[offset + 3] = d3;
bufsize = offset + 4;
}
void write(char_t d0, char_t d1, char_t d2, char_t d3, char_t d4)
{
size_t offset = bufsize;
if (offset > bufcapacity - 5) offset = flush();
buffer[offset + 0] = d0;
buffer[offset + 1] = d1;
buffer[offset + 2] = d2;
buffer[offset + 3] = d3;
buffer[offset + 4] = d4;
bufsize = offset + 5;
}
void write(char_t d0, char_t d1, char_t d2, char_t d3, char_t d4, char_t d5)
{
size_t offset = bufsize;
if (offset > bufcapacity - 6) offset = flush();
buffer[offset + 0] = d0;
buffer[offset + 1] = d1;
buffer[offset + 2] = d2;
buffer[offset + 3] = d3;
buffer[offset + 4] = d4;
buffer[offset + 5] = d5;
bufsize = offset + 6;
}
// utf8 maximum expansion: x4 (-> utf32)
// utf16 maximum expansion: x2 (-> utf32)
// utf32 maximum expansion: x1
enum
{
bufcapacitybytes =
#ifdef PUGIXML_MEMORY_OUTPUT_STACK
PUGIXML_MEMORY_OUTPUT_STACK
#else
10240
#endif
,
bufcapacity = bufcapacitybytes / (sizeof(char_t) + 4)
};
char_t buffer[bufcapacity];
union
{
uint8_t data_u8[4 * bufcapacity];
uint16_t data_u16[2 * bufcapacity];
uint32_t data_u32[bufcapacity];
char_t data_char[bufcapacity];
} scratch;
xml_writer& writer;
size_t bufsize;
xml_encoding encoding;
};
PUGI__FN void text_output_escaped(xml_buffered_writer& writer, const char_t* s, chartypex_t type, unsigned int flags)
{
while (*s)
{
const char_t* prev = s;
// While *s is a usual symbol
PUGI__SCANWHILE_UNROLL(!PUGI__IS_CHARTYPEX(ss, type));
writer.write_buffer(prev, static_cast<size_t>(s - prev));
switch (*s)
{
case 0: break;
case '&':
writer.write('&', 'a', 'm', 'p', ';');
++s;
break;
case '<':
writer.write('&', 'l', 't', ';');
++s;
break;
case '>':
writer.write('&', 'g', 't', ';');
++s;
break;
case '"':
if (flags & format_attribute_single_quote)
writer.write('"');
else
writer.write('&', 'q', 'u', 'o', 't', ';');
++s;
break;
case '\'':
if (flags & format_attribute_single_quote)
writer.write('&', 'a', 'p', 'o', 's', ';');
else
writer.write('\'');
++s;
break;
default: // s is not a usual symbol
{
unsigned int ch = static_cast<unsigned int>(*s++);
assert(ch < 32);
if (!(flags & format_skip_control_chars))
writer.write('&', '#', static_cast<char_t>((ch / 10) + '0'), static_cast<char_t>((ch % 10) + '0'), ';');
}
}
}
}
PUGI__FN void text_output(xml_buffered_writer& writer, const char_t* s, chartypex_t type, unsigned int flags)
{
if (flags & format_no_escapes)
writer.write_string(s);
else
text_output_escaped(writer, s, type, flags);
}
PUGI__FN void text_output_cdata(xml_buffered_writer& writer, const char_t* s)
{
do
{
writer.write('<', '!', '[', 'C', 'D');
writer.write('A', 'T', 'A', '[');
const char_t* prev = s;
// look for ]]> sequence - we can't output it as is since it terminates CDATA
while (*s && !(s[0] == ']' && s[1] == ']' && s[2] == '>')) ++s;
// skip ]] if we stopped at ]]>, > will go to the next CDATA section
if (*s) s += 2;
writer.write_buffer(prev, static_cast<size_t>(s - prev));
writer.write(']', ']', '>');
}
while (*s);
}
PUGI__FN void text_output_indent(xml_buffered_writer& writer, const char_t* indent, size_t indent_length, unsigned int depth)
{
switch (indent_length)
{
case 1:
{
for (unsigned int i = 0; i < depth; ++i)
writer.write(indent[0]);
break;
}
case 2:
{
for (unsigned int i = 0; i < depth; ++i)
writer.write(indent[0], indent[1]);
break;
}
case 3:
{
for (unsigned int i = 0; i < depth; ++i)
writer.write(indent[0], indent[1], indent[2]);
break;
}
case 4:
{
for (unsigned int i = 0; i < depth; ++i)
writer.write(indent[0], indent[1], indent[2], indent[3]);
break;
}
default:
{
for (unsigned int i = 0; i < depth; ++i)
writer.write_buffer(indent, indent_length);
}
}
}
PUGI__FN void node_output_comment(xml_buffered_writer& writer, const char_t* s)
{
writer.write('<', '!', '-', '-');
while (*s)
{
const char_t* prev = s;
// look for -\0 or -- sequence - we can't output it since -- is illegal in comment body
while (*s && !(s[0] == '-' && (s[1] == '-' || s[1] == 0))) ++s;
writer.write_buffer(prev, static_cast<size_t>(s - prev));
if (*s)
{
assert(*s == '-');
writer.write('-', ' ');
++s;
}
}
writer.write('-', '-', '>');
}
PUGI__FN void node_output_pi_value(xml_buffered_writer& writer, const char_t* s)
{
while (*s)
{
const char_t* prev = s;
// look for ?> sequence - we can't output it since ?> terminates PI
while (*s && !(s[0] == '?' && s[1] == '>')) ++s;
writer.write_buffer(prev, static_cast<size_t>(s - prev));
if (*s)
{
assert(s[0] == '?' && s[1] == '>');
writer.write('?', ' ', '>');
s += 2;
}
}
}
PUGI__FN void node_output_attributes(xml_buffered_writer& writer, xml_node_struct* node, const char_t* indent, size_t indent_length, unsigned int flags, unsigned int depth)
{
const char_t* default_name = PUGIXML_TEXT(":anonymous");
const char_t enquotation_char = (flags & format_attribute_single_quote) ? '\'' : '"';
for (xml_attribute_struct* a = node->first_attribute; a; a = a->next_attribute)
{
if ((flags & (format_indent_attributes | format_raw)) == format_indent_attributes)
{
writer.write('\n');
text_output_indent(writer, indent, indent_length, depth + 1);
}
else
{
writer.write(' ');
}
writer.write_string(a->name ? a->name + 0 : default_name);
writer.write('=', enquotation_char);
if (a->value)
text_output(writer, a->value, ctx_special_attr, flags);
writer.write(enquotation_char);
}
}
PUGI__FN bool node_output_start(xml_buffered_writer& writer, xml_node_struct* node, const char_t* indent, size_t indent_length, unsigned int flags, unsigned int depth)
{
const char_t* default_name = PUGIXML_TEXT(":anonymous");
const char_t* name = node->name ? node->name + 0 : default_name;
writer.write('<');
writer.write_string(name);
if (node->first_attribute)
node_output_attributes(writer, node, indent, indent_length, flags, depth);
// element nodes can have value if parse_embed_pcdata was used
if (!node->value)
{
if (!node->first_child)
{
if (flags & format_no_empty_element_tags)
{
writer.write('>', '<', '/');
writer.write_string(name);
writer.write('>');
return false;
}
else
{
if ((flags & format_raw) == 0)
writer.write(' ');
writer.write('/', '>');
return false;
}
}
else
{
writer.write('>');
return true;
}
}
else
{
writer.write('>');
text_output(writer, node->value, ctx_special_pcdata, flags);
if (!node->first_child)
{
writer.write('<', '/');
writer.write_string(name);
writer.write('>');
return false;
}
else
{
return true;
}
}
}
PUGI__FN void node_output_end(xml_buffered_writer& writer, xml_node_struct* node)
{
const char_t* default_name = PUGIXML_TEXT(":anonymous");
const char_t* name = node->name ? node->name + 0 : default_name;
writer.write('<', '/');
writer.write_string(name);
writer.write('>');
}
PUGI__FN void node_output_simple(xml_buffered_writer& writer, xml_node_struct* node, unsigned int flags)
{
const char_t* default_name = PUGIXML_TEXT(":anonymous");
switch (PUGI__NODETYPE(node))
{
case node_pcdata:
text_output(writer, node->value ? node->value + 0 : PUGIXML_TEXT(""), ctx_special_pcdata, flags);
break;
case node_cdata:
text_output_cdata(writer, node->value ? node->value + 0 : PUGIXML_TEXT(""));
break;
case node_comment:
node_output_comment(writer, node->value ? node->value + 0 : PUGIXML_TEXT(""));
break;
case node_pi:
writer.write('<', '?');
writer.write_string(node->name ? node->name + 0 : default_name);
if (node->value)
{
writer.write(' ');
node_output_pi_value(writer, node->value);
}
writer.write('?', '>');
break;
case node_declaration:
writer.write('<', '?');
writer.write_string(node->name ? node->name + 0 : default_name);
node_output_attributes(writer, node, PUGIXML_TEXT(""), 0, flags | format_raw, 0);
writer.write('?', '>');
break;
case node_doctype:
writer.write('<', '!', 'D', 'O', 'C');
writer.write('T', 'Y', 'P', 'E');
if (node->value)
{
writer.write(' ');
writer.write_string(node->value);
}
writer.write('>');
break;
default:
assert(false && "Invalid node type"); // unreachable
}
}
enum indent_flags_t
{
indent_newline = 1,
indent_indent = 2
};
PUGI__FN void node_output(xml_buffered_writer& writer, xml_node_struct* root, const char_t* indent, unsigned int flags, unsigned int depth)
{
size_t indent_length = ((flags & (format_indent | format_indent_attributes)) && (flags & format_raw) == 0) ? strlength(indent) : 0;
unsigned int indent_flags = indent_indent;
xml_node_struct* node = root;
do
{
assert(node);
// begin writing current node
if (PUGI__NODETYPE(node) == node_pcdata || PUGI__NODETYPE(node) == node_cdata)
{
node_output_simple(writer, node, flags);
indent_flags = 0;
}
else
{
if ((indent_flags & indent_newline) && (flags & format_raw) == 0)
writer.write('\n');
if ((indent_flags & indent_indent) && indent_length)
text_output_indent(writer, indent, indent_length, depth);
if (PUGI__NODETYPE(node) == node_element)
{
indent_flags = indent_newline | indent_indent;
if (node_output_start(writer, node, indent, indent_length, flags, depth))
{
// element nodes can have value if parse_embed_pcdata was used
if (node->value)
indent_flags = 0;
node = node->first_child;
depth++;
continue;
}
}
else if (PUGI__NODETYPE(node) == node_document)
{
indent_flags = indent_indent;
if (node->first_child)
{
node = node->first_child;
continue;
}
}
else
{
node_output_simple(writer, node, flags);
indent_flags = indent_newline | indent_indent;
}
}
// continue to the next node
while (node != root)
{
if (node->next_sibling)
{
node = node->next_sibling;
break;
}
node = node->parent;
// write closing node
if (PUGI__NODETYPE(node) == node_element)
{
depth--;
if ((indent_flags & indent_newline) && (flags & format_raw) == 0)
writer.write('\n');
if ((indent_flags & indent_indent) && indent_length)
text_output_indent(writer, indent, indent_length, depth);
node_output_end(writer, node);
indent_flags = indent_newline | indent_indent;
}
}
}
while (node != root);
if ((indent_flags & indent_newline) && (flags & format_raw) == 0)
writer.write('\n');
}
PUGI__FN bool has_declaration(xml_node_struct* node)
{
for (xml_node_struct* child = node->first_child; child; child = child->next_sibling)
{
xml_node_type type = PUGI__NODETYPE(child);
if (type == node_declaration) return true;
if (type == node_element) return false;
}
return false;
}
PUGI__FN bool is_attribute_of(xml_attribute_struct* attr, xml_node_struct* node)
{
for (xml_attribute_struct* a = node->first_attribute; a; a = a->next_attribute)
if (a == attr)
return true;
return false;
}
PUGI__FN bool allow_insert_attribute(xml_node_type parent)
{
return parent == node_element || parent == node_declaration;
}
PUGI__FN bool allow_insert_child(xml_node_type parent, xml_node_type child)
{
if (parent != node_document && parent != node_element) return false;
if (child == node_document || child == node_null) return false;
if (parent != node_document && (child == node_declaration || child == node_doctype)) return false;
return true;
}
PUGI__FN bool allow_move(xml_node parent, xml_node child)
{
// check that child can be a child of parent
if (!allow_insert_child(parent.type(), child.type()))
return false;
// check that node is not moved between documents
if (parent.root() != child.root())
return false;
// check that new parent is not in the child subtree
xml_node cur = parent;
while (cur)
{
if (cur == child)
return false;
cur = cur.parent();
}
return true;
}
template <typename String, typename Header>
PUGI__FN void node_copy_string(String& dest, Header& header, uintptr_t header_mask, char_t* source, Header& source_header, xml_allocator* alloc)
{
assert(!dest && (header & header_mask) == 0);
if (source)
{
if (alloc && (source_header & header_mask) == 0)
{
dest = source;
// since strcpy_insitu can reuse document buffer memory we need to mark both source and dest as shared
header |= xml_memory_page_contents_shared_mask;
source_header |= xml_memory_page_contents_shared_mask;
}
else
strcpy_insitu(dest, header, header_mask, source, strlength(source));
}
}
PUGI__FN void node_copy_contents(xml_node_struct* dn, xml_node_struct* sn, xml_allocator* shared_alloc)
{
node_copy_string(dn->name, dn->header, xml_memory_page_name_allocated_mask, sn->name, sn->header, shared_alloc);
node_copy_string(dn->value, dn->header, xml_memory_page_value_allocated_mask, sn->value, sn->header, shared_alloc);
for (xml_attribute_struct* sa = sn->first_attribute; sa; sa = sa->next_attribute)
{
xml_attribute_struct* da = append_new_attribute(dn, get_allocator(dn));
if (da)
{
node_copy_string(da->name, da->header, xml_memory_page_name_allocated_mask, sa->name, sa->header, shared_alloc);
node_copy_string(da->value, da->header, xml_memory_page_value_allocated_mask, sa->value, sa->header, shared_alloc);
}
}
}
PUGI__FN void node_copy_tree(xml_node_struct* dn, xml_node_struct* sn)
{
xml_allocator& alloc = get_allocator(dn);
xml_allocator* shared_alloc = (&alloc == &get_allocator(sn)) ? &alloc : 0;
node_copy_contents(dn, sn, shared_alloc);
xml_node_struct* dit = dn;
xml_node_struct* sit = sn->first_child;
while (sit && sit != sn)
{
// loop invariant: dit is inside the subtree rooted at dn
assert(dit);
// when a tree is copied into one of the descendants, we need to skip that subtree to avoid an infinite loop
if (sit != dn)
{
xml_node_struct* copy = append_new_node(dit, alloc, PUGI__NODETYPE(sit));
if (copy)
{
node_copy_contents(copy, sit, shared_alloc);
if (sit->first_child)
{
dit = copy;
sit = sit->first_child;
continue;
}
}
}
// continue to the next node
do
{
if (sit->next_sibling)
{
sit = sit->next_sibling;
break;
}
sit = sit->parent;
dit = dit->parent;
// loop invariant: dit is inside the subtree rooted at dn while sit is inside sn
assert(sit == sn || dit);
}
while (sit != sn);
}
assert(!sit || dit == dn->parent);
}
PUGI__FN void node_copy_attribute(xml_attribute_struct* da, xml_attribute_struct* sa)
{
xml_allocator& alloc = get_allocator(da);
xml_allocator* shared_alloc = (&alloc == &get_allocator(sa)) ? &alloc : 0;
node_copy_string(da->name, da->header, xml_memory_page_name_allocated_mask, sa->name, sa->header, shared_alloc);
node_copy_string(da->value, da->header, xml_memory_page_value_allocated_mask, sa->value, sa->header, shared_alloc);
}
inline bool is_text_node(xml_node_struct* node)
{
xml_node_type type = PUGI__NODETYPE(node);
return type == node_pcdata || type == node_cdata;
}
// get value with conversion functions
template <typename U> PUGI__FN PUGI__UNSIGNED_OVERFLOW U string_to_integer(const char_t* value, U minv, U maxv)
{
U result = 0;
const char_t* s = value;
while (PUGI__IS_CHARTYPE(*s, ct_space))
s++;
bool negative = (*s == '-');
s += (*s == '+' || *s == '-');
bool overflow = false;
if (s[0] == '0' && (s[1] | ' ') == 'x')
{
s += 2;
// since overflow detection relies on length of the sequence skip leading zeros
while (*s == '0')
s++;
const char_t* start = s;
for (;;)
{
if (static_cast<unsigned>(*s - '0') < 10)
result = result * 16 + (*s - '0');
else if (static_cast<unsigned>((*s | ' ') - 'a') < 6)
result = result * 16 + ((*s | ' ') - 'a' + 10);
else
break;
s++;
}
size_t digits = static_cast<size_t>(s - start);
overflow = digits > sizeof(U) * 2;
}
else
{
// since overflow detection relies on length of the sequence skip leading zeros
while (*s == '0')
s++;
const char_t* start = s;
for (;;)
{
if (static_cast<unsigned>(*s - '0') < 10)
result = result * 10 + (*s - '0');
else
break;
s++;
}
size_t digits = static_cast<size_t>(s - start);
PUGI__STATIC_ASSERT(sizeof(U) == 8 || sizeof(U) == 4 || sizeof(U) == 2);
const size_t max_digits10 = sizeof(U) == 8 ? 20 : sizeof(U) == 4 ? 10 : 5;
const char_t max_lead = sizeof(U) == 8 ? '1' : sizeof(U) == 4 ? '4' : '6';
const size_t high_bit = sizeof(U) * 8 - 1;
overflow = digits >= max_digits10 && !(digits == max_digits10 && (*start < max_lead || (*start == max_lead && result >> high_bit)));
}
if (negative)
{
// Workaround for crayc++ CC-3059: Expected no overflow in routine.
#ifdef _CRAYC
return (overflow || result > ~minv + 1) ? minv : ~result + 1;
#else
return (overflow || result > 0 - minv) ? minv : 0 - result;
#endif
}
else
return (overflow || result > maxv) ? maxv : result;
}
PUGI__FN int get_value_int(const char_t* value)
{
return string_to_integer<unsigned int>(value, static_cast<unsigned int>(INT_MIN), INT_MAX);
}
PUGI__FN unsigned int get_value_uint(const char_t* value)
{
return string_to_integer<unsigned int>(value, 0, UINT_MAX);
}
PUGI__FN double get_value_double(const char_t* value)
{
#ifdef PUGIXML_WCHAR_MODE
return wcstod(value, 0);
#else
return strtod(value, 0);
#endif
}
PUGI__FN float get_value_float(const char_t* value)
{
#ifdef PUGIXML_WCHAR_MODE
return static_cast<float>(wcstod(value, 0));
#else
return static_cast<float>(strtod(value, 0));
#endif
}
PUGI__FN bool get_value_bool(const char_t* value)
{
// only look at first char
char_t first = *value;
// 1*, t* (true), T* (True), y* (yes), Y* (YES)
return (first == '1' || first == 't' || first == 'T' || first == 'y' || first == 'Y');
}
#ifdef PUGIXML_HAS_LONG_LONG
PUGI__FN long long get_value_llong(const char_t* value)
{
return string_to_integer<unsigned long long>(value, static_cast<unsigned long long>(LLONG_MIN), LLONG_MAX);
}
PUGI__FN unsigned long long get_value_ullong(const char_t* value)
{
return string_to_integer<unsigned long long>(value, 0, ULLONG_MAX);
}
#endif
template <typename U> PUGI__FN PUGI__UNSIGNED_OVERFLOW char_t* integer_to_string(char_t* begin, char_t* end, U value, bool negative)
{
char_t* result = end - 1;
U rest = negative ? 0 - value : value;
do
{
*result-- = static_cast<char_t>('0' + (rest % 10));
rest /= 10;
}
while (rest);
assert(result >= begin);
(void)begin;
*result = '-';
return result + !negative;
}
// set value with conversion functions
template <typename String, typename Header>
PUGI__FN bool set_value_ascii(String& dest, Header& header, uintptr_t header_mask, char* buf)
{
#ifdef PUGIXML_WCHAR_MODE
char_t wbuf[128];
assert(strlen(buf) < sizeof(wbuf) / sizeof(wbuf[0]));
size_t offset = 0;
for (; buf[offset]; ++offset) wbuf[offset] = buf[offset];
return strcpy_insitu(dest, header, header_mask, wbuf, offset);
#else
return strcpy_insitu(dest, header, header_mask, buf, strlen(buf));
#endif
}
template <typename U, typename String, typename Header>
PUGI__FN bool set_value_integer(String& dest, Header& header, uintptr_t header_mask, U value, bool negative)
{
char_t buf[64];
char_t* end = buf + sizeof(buf) / sizeof(buf[0]);
char_t* begin = integer_to_string(buf, end, value, negative);
return strcpy_insitu(dest, header, header_mask, begin, end - begin);
}
template <typename String, typename Header>
PUGI__FN bool set_value_convert(String& dest, Header& header, uintptr_t header_mask, float value, int precision)
{
char buf[128];
PUGI__SNPRINTF(buf, "%.*g", precision, double(value));
return set_value_ascii(dest, header, header_mask, buf);
}
template <typename String, typename Header>
PUGI__FN bool set_value_convert(String& dest, Header& header, uintptr_t header_mask, double value, int precision)
{
char buf[128];
PUGI__SNPRINTF(buf, "%.*g", precision, value);
return set_value_ascii(dest, header, header_mask, buf);
}
template <typename String, typename Header>
PUGI__FN bool set_value_bool(String& dest, Header& header, uintptr_t header_mask, bool value)
{
return strcpy_insitu(dest, header, header_mask, value ? PUGIXML_TEXT("true") : PUGIXML_TEXT("false"), value ? 4 : 5);
}
PUGI__FN xml_parse_result load_buffer_impl(xml_document_struct* doc, xml_node_struct* root, void* contents, size_t size, unsigned int options, xml_encoding encoding, bool is_mutable, bool own, char_t** out_buffer)
{
// check input buffer
if (!contents && size) return make_parse_result(status_io_error);
// get actual encoding
xml_encoding buffer_encoding = impl::get_buffer_encoding(encoding, contents, size);
// get private buffer
char_t* buffer = 0;
size_t length = 0;
// coverity[var_deref_model]
if (!impl::convert_buffer(buffer, length, buffer_encoding, contents, size, is_mutable)) return impl::make_parse_result(status_out_of_memory);
// delete original buffer if we performed a conversion
if (own && buffer != contents && contents) impl::xml_memory::deallocate(contents);
// grab onto buffer if it's our buffer, user is responsible for deallocating contents himself
if (own || buffer != contents) *out_buffer = buffer;
// store buffer for offset_debug
doc->buffer = buffer;
// parse
xml_parse_result res = impl::xml_parser::parse(buffer, length, doc, root, options);
// remember encoding
res.encoding = buffer_encoding;
return res;
}
// we need to get length of entire file to load it in memory; the only (relatively) sane way to do it is via seek/tell trick
PUGI__FN xml_parse_status get_file_size(FILE* file, size_t& out_result)
{
#if defined(PUGI__MSVC_CRT_VERSION) && PUGI__MSVC_CRT_VERSION >= 1400 && !defined(_WIN32_WCE)
// there are 64-bit versions of fseek/ftell, let's use them
typedef __int64 length_type;
_fseeki64(file, 0, SEEK_END);
length_type length = _ftelli64(file);
_fseeki64(file, 0, SEEK_SET);
#elif defined(__MINGW32__) && !defined(__NO_MINGW_LFS) && (!defined(__STRICT_ANSI__) || defined(__MINGW64_VERSION_MAJOR))
// there are 64-bit versions of fseek/ftell, let's use them
typedef off64_t length_type;
fseeko64(file, 0, SEEK_END);
length_type length = ftello64(file);
fseeko64(file, 0, SEEK_SET);
#else
// if this is a 32-bit OS, long is enough; if this is a unix system, long is 64-bit, which is enough; otherwise we can't do anything anyway.
typedef long length_type;
fseek(file, 0, SEEK_END);
length_type length = ftell(file);
fseek(file, 0, SEEK_SET);
#endif
// check for I/O errors
if (length < 0) return status_io_error;
// check for overflow
size_t result = static_cast<size_t>(length);
if (static_cast<length_type>(result) != length) return status_out_of_memory;
// finalize
out_result = result;
return status_ok;
}
// This function assumes that buffer has extra sizeof(char_t) writable bytes after size
PUGI__FN size_t zero_terminate_buffer(void* buffer, size_t size, xml_encoding encoding)
{
// We only need to zero-terminate if encoding conversion does not do it for us
#ifdef PUGIXML_WCHAR_MODE
xml_encoding wchar_encoding = get_wchar_encoding();
if (encoding == wchar_encoding || need_endian_swap_utf(encoding, wchar_encoding))
{
size_t length = size / sizeof(char_t);
static_cast<char_t*>(buffer)[length] = 0;
return (length + 1) * sizeof(char_t);
}
#else
if (encoding == encoding_utf8)
{
static_cast<char*>(buffer)[size] = 0;
return size + 1;
}
#endif
return size;
}
PUGI__FN xml_parse_result load_file_impl(xml_document_struct* doc, FILE* file, unsigned int options, xml_encoding encoding, char_t** out_buffer)
{
if (!file) return make_parse_result(status_file_not_found);
// get file size (can result in I/O errors)
size_t size = 0;
xml_parse_status size_status = get_file_size(file, size);
if (size_status != status_ok) return make_parse_result(size_status);
size_t max_suffix_size = sizeof(char_t);
// allocate buffer for the whole file
char* contents = static_cast<char*>(xml_memory::allocate(size + max_suffix_size));
if (!contents) return make_parse_result(status_out_of_memory);
// read file in memory
size_t read_size = fread(contents, 1, size, file);
if (read_size != size)
{
xml_memory::deallocate(contents);
return make_parse_result(status_io_error);
}
xml_encoding real_encoding = get_buffer_encoding(encoding, contents, size);
return load_buffer_impl(doc, doc, contents, zero_terminate_buffer(contents, size, real_encoding), options, real_encoding, true, true, out_buffer);
}
PUGI__FN void close_file(FILE* file)
{
fclose(file);
}
#ifndef PUGIXML_NO_STL
template <typename T> struct xml_stream_chunk
{
static xml_stream_chunk* create()
{
void* memory = xml_memory::allocate(sizeof(xml_stream_chunk));
if (!memory) return 0;
return new (memory) xml_stream_chunk();
}
static void destroy(xml_stream_chunk* chunk)
{
// free chunk chain
while (chunk)
{
xml_stream_chunk* next_ = chunk->next;
xml_memory::deallocate(chunk);
chunk = next_;
}
}
xml_stream_chunk(): next(0), size(0)
{
}
xml_stream_chunk* next;
size_t size;
T data[xml_memory_page_size / sizeof(T)];
};
template <typename T> PUGI__FN xml_parse_status load_stream_data_noseek(std::basic_istream<T>& stream, void** out_buffer, size_t* out_size)
{
auto_deleter<xml_stream_chunk<T> > chunks(0, xml_stream_chunk<T>::destroy);
// read file to a chunk list
size_t total = 0;
xml_stream_chunk<T>* last = 0;
while (!stream.eof())
{
// allocate new chunk
xml_stream_chunk<T>* chunk = xml_stream_chunk<T>::create();
if (!chunk) return status_out_of_memory;
// append chunk to list
if (last) last = last->next = chunk;
else chunks.data = last = chunk;
// read data to chunk
stream.read(chunk->data, static_cast<std::streamsize>(sizeof(chunk->data) / sizeof(T)));
chunk->size = static_cast<size_t>(stream.gcount()) * sizeof(T);
// read may set failbit | eofbit in case gcount() is less than read length, so check for other I/O errors
if (stream.bad() || (!stream.eof() && stream.fail())) return status_io_error;
// guard against huge files (chunk size is small enough to make this overflow check work)
if (total + chunk->size < total) return status_out_of_memory;
total += chunk->size;
}
size_t max_suffix_size = sizeof(char_t);
// copy chunk list to a contiguous buffer
char* buffer = static_cast<char*>(xml_memory::allocate(total + max_suffix_size));
if (!buffer) return status_out_of_memory;
char* write = buffer;
for (xml_stream_chunk<T>* chunk = chunks.data; chunk; chunk = chunk->next)
{
assert(write + chunk->size <= buffer + total);
memcpy(write, chunk->data, chunk->size);
write += chunk->size;
}
assert(write == buffer + total);
// return buffer
*out_buffer = buffer;
*out_size = total;
return status_ok;
}
template <typename T> PUGI__FN xml_parse_status load_stream_data_seek(std::basic_istream<T>& stream, void** out_buffer, size_t* out_size)
{
// get length of remaining data in stream
typename std::basic_istream<T>::pos_type pos = stream.tellg();
stream.seekg(0, std::ios::end);
std::streamoff length = stream.tellg() - pos;
stream.seekg(pos);
if (stream.fail() || pos < 0) return status_io_error;
// guard against huge files
size_t read_length = static_cast<size_t>(length);
if (static_cast<std::streamsize>(read_length) != length || length < 0) return status_out_of_memory;
size_t max_suffix_size = sizeof(char_t);
// read stream data into memory (guard against stream exceptions with buffer holder)
auto_deleter<void> buffer(xml_memory::allocate(read_length * sizeof(T) + max_suffix_size), xml_memory::deallocate);
if (!buffer.data) return status_out_of_memory;
stream.read(static_cast<T*>(buffer.data), static_cast<std::streamsize>(read_length));
// read may set failbit | eofbit in case gcount() is less than read_length (i.e. line ending conversion), so check for other I/O errors
if (stream.bad() || (!stream.eof() && stream.fail())) return status_io_error;
// return buffer
size_t actual_length = static_cast<size_t>(stream.gcount());
assert(actual_length <= read_length);
*out_buffer = buffer.release();
*out_size = actual_length * sizeof(T);
return status_ok;
}
template <typename T> PUGI__FN xml_parse_result load_stream_impl(xml_document_struct* doc, std::basic_istream<T>& stream, unsigned int options, xml_encoding encoding, char_t** out_buffer)
{
void* buffer = 0;
size_t size = 0;
xml_parse_status status = status_ok;
// if stream has an error bit set, bail out (otherwise tellg() can fail and we'll clear error bits)
if (stream.fail()) return make_parse_result(status_io_error);
// load stream to memory (using seek-based implementation if possible, since it's faster and takes less memory)
if (stream.tellg() < 0)
{
stream.clear(); // clear error flags that could be set by a failing tellg
status = load_stream_data_noseek(stream, &buffer, &size);
}
else
status = load_stream_data_seek(stream, &buffer, &size);
if (status != status_ok) return make_parse_result(status);
xml_encoding real_encoding = get_buffer_encoding(encoding, buffer, size);
return load_buffer_impl(doc, doc, buffer, zero_terminate_buffer(buffer, size, real_encoding), options, real_encoding, true, true, out_buffer);
}
#endif
#if defined(PUGI__MSVC_CRT_VERSION) || defined(__BORLANDC__) || (defined(__MINGW32__) && (!defined(__STRICT_ANSI__) || defined(__MINGW64_VERSION_MAJOR)))
PUGI__FN FILE* open_file_wide(const wchar_t* path, const wchar_t* mode)
{
#if defined(PUGI__MSVC_CRT_VERSION) && PUGI__MSVC_CRT_VERSION >= 1400
FILE* file = 0;
return _wfopen_s(&file, path, mode) == 0 ? file : 0;
#else
return _wfopen(path, mode);
#endif
}
#else
PUGI__FN char* convert_path_heap(const wchar_t* str)
{
assert(str);
// first pass: get length in utf8 characters
size_t length = strlength_wide(str);
size_t size = as_utf8_begin(str, length);
// allocate resulting string
char* result = static_cast<char*>(xml_memory::allocate(size + 1));
if (!result) return 0;
// second pass: convert to utf8
as_utf8_end(result, size, str, length);
// zero-terminate
result[size] = 0;
return result;
}
PUGI__FN FILE* open_file_wide(const wchar_t* path, const wchar_t* mode)
{
// there is no standard function to open wide paths, so our best bet is to try utf8 path
char* path_utf8 = convert_path_heap(path);
if (!path_utf8) return 0;
// convert mode to ASCII (we mirror _wfopen interface)
char mode_ascii[4] = {0};
for (size_t i = 0; mode[i]; ++i) mode_ascii[i] = static_cast<char>(mode[i]);
// try to open the utf8 path
FILE* result = fopen(path_utf8, mode_ascii);
// free dummy buffer
xml_memory::deallocate(path_utf8);
return result;
}
#endif
PUGI__FN FILE* open_file(const char* path, const char* mode)
{
#if defined(PUGI__MSVC_CRT_VERSION) && PUGI__MSVC_CRT_VERSION >= 1400
FILE* file = 0;
return fopen_s(&file, path, mode) == 0 ? file : 0;
#else
return fopen(path, mode);
#endif
}
PUGI__FN bool save_file_impl(const xml_document& doc, FILE* file, const char_t* indent, unsigned int flags, xml_encoding encoding)
{
if (!file) return false;
xml_writer_file writer(file);
doc.save(writer, indent, flags, encoding);
return ferror(file) == 0;
}
struct name_null_sentry
{
xml_node_struct* node;
char_t* name;
name_null_sentry(xml_node_struct* node_): node(node_), name(node_->name)
{
node->name = 0;
}
~name_null_sentry()
{
node->name = name;
}
};
PUGI__NS_END
namespace pugi
{
PUGI__FN xml_writer_file::xml_writer_file(void* file_): file(file_)
{
}
PUGI__FN void xml_writer_file::write(const void* data, size_t size)
{
size_t result = fwrite(data, 1, size, static_cast<FILE*>(file));
(void)!result; // unfortunately we can't do proper error handling here
}
#ifndef PUGIXML_NO_STL
PUGI__FN xml_writer_stream::xml_writer_stream(std::basic_ostream<char, std::char_traits<char> >& stream): narrow_stream(&stream), wide_stream(0)
{
}
PUGI__FN xml_writer_stream::xml_writer_stream(std::basic_ostream<wchar_t, std::char_traits<wchar_t> >& stream): narrow_stream(0), wide_stream(&stream)
{
}
PUGI__FN void xml_writer_stream::write(const void* data, size_t size)
{
if (narrow_stream)
{
assert(!wide_stream);
narrow_stream->write(reinterpret_cast<const char*>(data), static_cast<std::streamsize>(size));
}
else
{
assert(wide_stream);
assert(size % sizeof(wchar_t) == 0);
wide_stream->write(reinterpret_cast<const wchar_t*>(data), static_cast<std::streamsize>(size / sizeof(wchar_t)));
}
}
#endif
PUGI__FN xml_tree_walker::xml_tree_walker(): _depth(0)
{
}
PUGI__FN xml_tree_walker::~xml_tree_walker()
{
}
PUGI__FN int xml_tree_walker::depth() const
{
return _depth;
}
PUGI__FN bool xml_tree_walker::begin(xml_node&)
{
return true;
}
PUGI__FN bool xml_tree_walker::end(xml_node&)
{
return true;
}
PUGI__FN xml_attribute::xml_attribute(): _attr(0)
{
}
PUGI__FN xml_attribute::xml_attribute(xml_attribute_struct* attr): _attr(attr)
{
}
PUGI__FN static void unspecified_bool_xml_attribute(xml_attribute***)
{
}
PUGI__FN xml_attribute::operator xml_attribute::unspecified_bool_type() const
{
return _attr ? unspecified_bool_xml_attribute : 0;
}
PUGI__FN bool xml_attribute::operator!() const
{
return !_attr;
}
PUGI__FN bool xml_attribute::operator==(const xml_attribute& r) const
{
return (_attr == r._attr);
}
PUGI__FN bool xml_attribute::operator!=(const xml_attribute& r) const
{
return (_attr != r._attr);
}
PUGI__FN bool xml_attribute::operator<(const xml_attribute& r) const
{
return (_attr < r._attr);
}
PUGI__FN bool xml_attribute::operator>(const xml_attribute& r) const
{
return (_attr > r._attr);
}
PUGI__FN bool xml_attribute::operator<=(const xml_attribute& r) const
{
return (_attr <= r._attr);
}
PUGI__FN bool xml_attribute::operator>=(const xml_attribute& r) const
{
return (_attr >= r._attr);
}
PUGI__FN xml_attribute xml_attribute::next_attribute() const
{
return _attr ? xml_attribute(_attr->next_attribute) : xml_attribute();
}
PUGI__FN xml_attribute xml_attribute::previous_attribute() const
{
return _attr && _attr->prev_attribute_c->next_attribute ? xml_attribute(_attr->prev_attribute_c) : xml_attribute();
}
PUGI__FN const char_t* xml_attribute::as_string(const char_t* def) const
{
return (_attr && _attr->value) ? _attr->value + 0 : def;
}
PUGI__FN int xml_attribute::as_int(int def) const
{
return (_attr && _attr->value) ? impl::get_value_int(_attr->value) : def;
}
PUGI__FN unsigned int xml_attribute::as_uint(unsigned int def) const
{
return (_attr && _attr->value) ? impl::get_value_uint(_attr->value) : def;
}
PUGI__FN double xml_attribute::as_double(double def) const
{
return (_attr && _attr->value) ? impl::get_value_double(_attr->value) : def;
}
PUGI__FN float xml_attribute::as_float(float def) const
{
return (_attr && _attr->value) ? impl::get_value_float(_attr->value) : def;
}
PUGI__FN bool xml_attribute::as_bool(bool def) const
{
return (_attr && _attr->value) ? impl::get_value_bool(_attr->value) : def;
}
#ifdef PUGIXML_HAS_LONG_LONG
PUGI__FN long long xml_attribute::as_llong(long long def) const
{
return (_attr && _attr->value) ? impl::get_value_llong(_attr->value) : def;
}
PUGI__FN unsigned long long xml_attribute::as_ullong(unsigned long long def) const
{
return (_attr && _attr->value) ? impl::get_value_ullong(_attr->value) : def;
}
#endif
PUGI__FN bool xml_attribute::empty() const
{
return !_attr;
}
PUGI__FN const char_t* xml_attribute::name() const
{
return (_attr && _attr->name) ? _attr->name + 0 : PUGIXML_TEXT("");
}
PUGI__FN const char_t* xml_attribute::value() const
{
return (_attr && _attr->value) ? _attr->value + 0 : PUGIXML_TEXT("");
}
PUGI__FN size_t xml_attribute::hash_value() const
{
return static_cast<size_t>(reinterpret_cast<uintptr_t>(_attr) / sizeof(xml_attribute_struct));
}
PUGI__FN xml_attribute_struct* xml_attribute::internal_object() const
{
return _attr;
}
PUGI__FN xml_attribute& xml_attribute::operator=(const char_t* rhs)
{
set_value(rhs);
return *this;
}
PUGI__FN xml_attribute& xml_attribute::operator=(int rhs)
{
set_value(rhs);
return *this;
}
PUGI__FN xml_attribute& xml_attribute::operator=(unsigned int rhs)
{
set_value(rhs);
return *this;
}
PUGI__FN xml_attribute& xml_attribute::operator=(long rhs)
{
set_value(rhs);
return *this;
}
PUGI__FN xml_attribute& xml_attribute::operator=(unsigned long rhs)
{
set_value(rhs);
return *this;
}
PUGI__FN xml_attribute& xml_attribute::operator=(double rhs)
{
set_value(rhs);
return *this;
}
PUGI__FN xml_attribute& xml_attribute::operator=(float rhs)
{
set_value(rhs);
return *this;
}
PUGI__FN xml_attribute& xml_attribute::operator=(bool rhs)
{
set_value(rhs);
return *this;
}
#ifdef PUGIXML_HAS_LONG_LONG
PUGI__FN xml_attribute& xml_attribute::operator=(long long rhs)
{
set_value(rhs);
return *this;
}
PUGI__FN xml_attribute& xml_attribute::operator=(unsigned long long rhs)
{
set_value(rhs);
return *this;
}
#endif
PUGI__FN bool xml_attribute::set_name(const char_t* rhs)
{
if (!_attr) return false;
return impl::strcpy_insitu(_attr->name, _attr->header, impl::xml_memory_page_name_allocated_mask, rhs, impl::strlength(rhs));
}
PUGI__FN bool xml_attribute::set_value(const char_t* rhs)
{
if (!_attr) return false;
return impl::strcpy_insitu(_attr->value, _attr->header, impl::xml_memory_page_value_allocated_mask, rhs, impl::strlength(rhs));
}
PUGI__FN bool xml_attribute::set_value(int rhs)
{
if (!_attr) return false;
return impl::set_value_integer<unsigned int>(_attr->value, _attr->header, impl::xml_memory_page_value_allocated_mask, rhs, rhs < 0);
}
PUGI__FN bool xml_attribute::set_value(unsigned int rhs)
{
if (!_attr) return false;
return impl::set_value_integer<unsigned int>(_attr->value, _attr->header, impl::xml_memory_page_value_allocated_mask, rhs, false);
}
PUGI__FN bool xml_attribute::set_value(long rhs)
{
if (!_attr) return false;
return impl::set_value_integer<unsigned long>(_attr->value, _attr->header, impl::xml_memory_page_value_allocated_mask, rhs, rhs < 0);
}
PUGI__FN bool xml_attribute::set_value(unsigned long rhs)
{
if (!_attr) return false;
return impl::set_value_integer<unsigned long>(_attr->value, _attr->header, impl::xml_memory_page_value_allocated_mask, rhs, false);
}
PUGI__FN bool xml_attribute::set_value(double rhs)
{
if (!_attr) return false;
return impl::set_value_convert(_attr->value, _attr->header, impl::xml_memory_page_value_allocated_mask, rhs, default_double_precision);
}
PUGI__FN bool xml_attribute::set_value(double rhs, int precision)
{
if (!_attr) return false;
return impl::set_value_convert(_attr->value, _attr->header, impl::xml_memory_page_value_allocated_mask, rhs, precision);
}
PUGI__FN bool xml_attribute::set_value(float rhs)
{
if (!_attr) return false;
return impl::set_value_convert(_attr->value, _attr->header, impl::xml_memory_page_value_allocated_mask, rhs, default_float_precision);
}
PUGI__FN bool xml_attribute::set_value(float rhs, int precision)
{
if (!_attr) return false;
return impl::set_value_convert(_attr->value, _attr->header, impl::xml_memory_page_value_allocated_mask, rhs, precision);
}
PUGI__FN bool xml_attribute::set_value(bool rhs)
{
if (!_attr) return false;
return impl::set_value_bool(_attr->value, _attr->header, impl::xml_memory_page_value_allocated_mask, rhs);
}
#ifdef PUGIXML_HAS_LONG_LONG
PUGI__FN bool xml_attribute::set_value(long long rhs)
{
if (!_attr) return false;
return impl::set_value_integer<unsigned long long>(_attr->value, _attr->header, impl::xml_memory_page_value_allocated_mask, rhs, rhs < 0);
}
PUGI__FN bool xml_attribute::set_value(unsigned long long rhs)
{
if (!_attr) return false;
return impl::set_value_integer<unsigned long long>(_attr->value, _attr->header, impl::xml_memory_page_value_allocated_mask, rhs, false);
}
#endif
#ifdef __BORLANDC__
PUGI__FN bool operator&&(const xml_attribute& lhs, bool rhs)
{
return (bool)lhs && rhs;
}
PUGI__FN bool operator||(const xml_attribute& lhs, bool rhs)
{
return (bool)lhs || rhs;
}
#endif
PUGI__FN xml_node::xml_node(): _root(0)
{
}
PUGI__FN xml_node::xml_node(xml_node_struct* p): _root(p)
{
}
PUGI__FN static void unspecified_bool_xml_node(xml_node***)
{
}
PUGI__FN xml_node::operator xml_node::unspecified_bool_type() const
{
return _root ? unspecified_bool_xml_node : 0;
}
PUGI__FN bool xml_node::operator!() const
{
return !_root;
}
PUGI__FN xml_node::iterator xml_node::begin() const
{
return iterator(_root ? _root->first_child + 0 : 0, _root);
}
PUGI__FN xml_node::iterator xml_node::end() const
{
return iterator(0, _root);
}
PUGI__FN xml_node::attribute_iterator xml_node::attributes_begin() const
{
return attribute_iterator(_root ? _root->first_attribute + 0 : 0, _root);
}
PUGI__FN xml_node::attribute_iterator xml_node::attributes_end() const
{
return attribute_iterator(0, _root);
}
PUGI__FN xml_object_range<xml_node_iterator> xml_node::children() const
{
return xml_object_range<xml_node_iterator>(begin(), end());
}
PUGI__FN xml_object_range<xml_named_node_iterator> xml_node::children(const char_t* name_) const
{
return xml_object_range<xml_named_node_iterator>(xml_named_node_iterator(child(name_)._root, _root, name_), xml_named_node_iterator(0, _root, name_));
}
PUGI__FN xml_object_range<xml_attribute_iterator> xml_node::attributes() const
{
return xml_object_range<xml_attribute_iterator>(attributes_begin(), attributes_end());
}
PUGI__FN bool xml_node::operator==(const xml_node& r) const
{
return (_root == r._root);
}
PUGI__FN bool xml_node::operator!=(const xml_node& r) const
{
return (_root != r._root);
}
PUGI__FN bool xml_node::operator<(const xml_node& r) const
{
return (_root < r._root);
}
PUGI__FN bool xml_node::operator>(const xml_node& r) const
{
return (_root > r._root);
}
PUGI__FN bool xml_node::operator<=(const xml_node& r) const
{
return (_root <= r._root);
}
PUGI__FN bool xml_node::operator>=(const xml_node& r) const
{
return (_root >= r._root);
}
PUGI__FN bool xml_node::empty() const
{
return !_root;
}
PUGI__FN const char_t* xml_node::name() const
{
return (_root && _root->name) ? _root->name + 0 : PUGIXML_TEXT("");
}
PUGI__FN xml_node_type xml_node::type() const
{
return _root ? PUGI__NODETYPE(_root) : node_null;
}
PUGI__FN const char_t* xml_node::value() const
{
return (_root && _root->value) ? _root->value + 0 : PUGIXML_TEXT("");
}
PUGI__FN xml_node xml_node::child(const char_t* name_) const
{
if (!_root) return xml_node();
for (xml_node_struct* i = _root->first_child; i; i = i->next_sibling)
if (i->name && impl::strequal(name_, i->name)) return xml_node(i);
return xml_node();
}
PUGI__FN xml_attribute xml_node::attribute(const char_t* name_) const
{
if (!_root) return xml_attribute();
for (xml_attribute_struct* i = _root->first_attribute; i; i = i->next_attribute)
if (i->name && impl::strequal(name_, i->name))
return xml_attribute(i);
return xml_attribute();
}
PUGI__FN xml_node xml_node::next_sibling(const char_t* name_) const
{
if (!_root) return xml_node();
for (xml_node_struct* i = _root->next_sibling; i; i = i->next_sibling)
if (i->name && impl::strequal(name_, i->name)) return xml_node(i);
return xml_node();
}
PUGI__FN xml_node xml_node::next_sibling() const
{
return _root ? xml_node(_root->next_sibling) : xml_node();
}
PUGI__FN xml_node xml_node::previous_sibling(const char_t* name_) const
{
if (!_root) return xml_node();
for (xml_node_struct* i = _root->prev_sibling_c; i->next_sibling; i = i->prev_sibling_c)
if (i->name && impl::strequal(name_, i->name)) return xml_node(i);
return xml_node();
}
PUGI__FN xml_attribute xml_node::attribute(const char_t* name_, xml_attribute& hint_) const
{
xml_attribute_struct* hint = hint_._attr;
// if hint is not an attribute of node, behavior is not defined
assert(!hint || (_root && impl::is_attribute_of(hint, _root)));
if (!_root) return xml_attribute();
// optimistically search from hint up until the end
for (xml_attribute_struct* i = hint; i; i = i->next_attribute)
if (i->name && impl::strequal(name_, i->name))
{
// update hint to maximize efficiency of searching for consecutive attributes
hint_._attr = i->next_attribute;
return xml_attribute(i);
}
// wrap around and search from the first attribute until the hint
// 'j' null pointer check is technically redundant, but it prevents a crash in case the assertion above fails
for (xml_attribute_struct* j = _root->first_attribute; j && j != hint; j = j->next_attribute)
if (j->name && impl::strequal(name_, j->name))
{
// update hint to maximize efficiency of searching for consecutive attributes
hint_._attr = j->next_attribute;
return xml_attribute(j);
}
return xml_attribute();
}
PUGI__FN xml_node xml_node::previous_sibling() const
{
if (!_root) return xml_node();
if (_root->prev_sibling_c->next_sibling) return xml_node(_root->prev_sibling_c);
else return xml_node();
}
PUGI__FN xml_node xml_node::parent() const
{
return _root ? xml_node(_root->parent) : xml_node();
}
PUGI__FN xml_node xml_node::root() const
{
return _root ? xml_node(&impl::get_document(_root)) : xml_node();
}
PUGI__FN xml_text xml_node::text() const
{
return xml_text(_root);
}
PUGI__FN const char_t* xml_node::child_value() const
{
if (!_root) return PUGIXML_TEXT("");
// element nodes can have value if parse_embed_pcdata was used
if (PUGI__NODETYPE(_root) == node_element && _root->value)
return _root->value;
for (xml_node_struct* i = _root->first_child; i; i = i->next_sibling)
if (impl::is_text_node(i) && i->value)
return i->value;
return PUGIXML_TEXT("");
}
PUGI__FN const char_t* xml_node::child_value(const char_t* name_) const
{
return child(name_).child_value();
}
PUGI__FN xml_attribute xml_node::first_attribute() const
{
return _root ? xml_attribute(_root->first_attribute) : xml_attribute();
}
PUGI__FN xml_attribute xml_node::last_attribute() const
{
return _root && _root->first_attribute ? xml_attribute(_root->first_attribute->prev_attribute_c) : xml_attribute();
}
PUGI__FN xml_node xml_node::first_child() const
{
return _root ? xml_node(_root->first_child) : xml_node();
}
PUGI__FN xml_node xml_node::last_child() const
{
return _root && _root->first_child ? xml_node(_root->first_child->prev_sibling_c) : xml_node();
}
PUGI__FN bool xml_node::set_name(const char_t* rhs)
{
xml_node_type type_ = _root ? PUGI__NODETYPE(_root) : node_null;
if (type_ != node_element && type_ != node_pi && type_ != node_declaration)
return false;
return impl::strcpy_insitu(_root->name, _root->header, impl::xml_memory_page_name_allocated_mask, rhs, impl::strlength(rhs));
}
PUGI__FN bool xml_node::set_value(const char_t* rhs)
{
xml_node_type type_ = _root ? PUGI__NODETYPE(_root) : node_null;
if (type_ != node_pcdata && type_ != node_cdata && type_ != node_comment && type_ != node_pi && type_ != node_doctype)
return false;
return impl::strcpy_insitu(_root->value, _root->header, impl::xml_memory_page_value_allocated_mask, rhs, impl::strlength(rhs));
}
PUGI__FN xml_attribute xml_node::append_attribute(const char_t* name_)
{
if (!impl::allow_insert_attribute(type())) return xml_attribute();
impl::xml_allocator& alloc = impl::get_allocator(_root);
if (!alloc.reserve()) return xml_attribute();
xml_attribute a(impl::allocate_attribute(alloc));
if (!a) return xml_attribute();
impl::append_attribute(a._attr, _root);
a.set_name(name_);
return a;
}
PUGI__FN xml_attribute xml_node::prepend_attribute(const char_t* name_)
{
if (!impl::allow_insert_attribute(type())) return xml_attribute();
impl::xml_allocator& alloc = impl::get_allocator(_root);
if (!alloc.reserve()) return xml_attribute();
xml_attribute a(impl::allocate_attribute(alloc));
if (!a) return xml_attribute();
impl::prepend_attribute(a._attr, _root);
a.set_name(name_);
return a;
}
PUGI__FN xml_attribute xml_node::insert_attribute_after(const char_t* name_, const xml_attribute& attr)
{
if (!impl::allow_insert_attribute(type())) return xml_attribute();
if (!attr || !impl::is_attribute_of(attr._attr, _root)) return xml_attribute();
impl::xml_allocator& alloc = impl::get_allocator(_root);
if (!alloc.reserve()) return xml_attribute();
xml_attribute a(impl::allocate_attribute(alloc));
if (!a) return xml_attribute();
impl::insert_attribute_after(a._attr, attr._attr, _root);
a.set_name(name_);
return a;
}
PUGI__FN xml_attribute xml_node::insert_attribute_before(const char_t* name_, const xml_attribute& attr)
{
if (!impl::allow_insert_attribute(type())) return xml_attribute();
if (!attr || !impl::is_attribute_of(attr._attr, _root)) return xml_attribute();
impl::xml_allocator& alloc = impl::get_allocator(_root);
if (!alloc.reserve()) return xml_attribute();
xml_attribute a(impl::allocate_attribute(alloc));
if (!a) return xml_attribute();
impl::insert_attribute_before(a._attr, attr._attr, _root);
a.set_name(name_);
return a;
}
PUGI__FN xml_attribute xml_node::append_copy(const xml_attribute& proto)
{
if (!proto) return xml_attribute();
if (!impl::allow_insert_attribute(type())) return xml_attribute();
impl::xml_allocator& alloc = impl::get_allocator(_root);
if (!alloc.reserve()) return xml_attribute();
xml_attribute a(impl::allocate_attribute(alloc));
if (!a) return xml_attribute();
impl::append_attribute(a._attr, _root);
impl::node_copy_attribute(a._attr, proto._attr);
return a;
}
PUGI__FN xml_attribute xml_node::prepend_copy(const xml_attribute& proto)
{
if (!proto) return xml_attribute();
if (!impl::allow_insert_attribute(type())) return xml_attribute();
impl::xml_allocator& alloc = impl::get_allocator(_root);
if (!alloc.reserve()) return xml_attribute();
xml_attribute a(impl::allocate_attribute(alloc));
if (!a) return xml_attribute();
impl::prepend_attribute(a._attr, _root);
impl::node_copy_attribute(a._attr, proto._attr);
return a;
}
PUGI__FN xml_attribute xml_node::insert_copy_after(const xml_attribute& proto, const xml_attribute& attr)
{
if (!proto) return xml_attribute();
if (!impl::allow_insert_attribute(type())) return xml_attribute();
if (!attr || !impl::is_attribute_of(attr._attr, _root)) return xml_attribute();
impl::xml_allocator& alloc = impl::get_allocator(_root);
if (!alloc.reserve()) return xml_attribute();
xml_attribute a(impl::allocate_attribute(alloc));
if (!a) return xml_attribute();
impl::insert_attribute_after(a._attr, attr._attr, _root);
impl::node_copy_attribute(a._attr, proto._attr);
return a;
}
PUGI__FN xml_attribute xml_node::insert_copy_before(const xml_attribute& proto, const xml_attribute& attr)
{
if (!proto) return xml_attribute();
if (!impl::allow_insert_attribute(type())) return xml_attribute();
if (!attr || !impl::is_attribute_of(attr._attr, _root)) return xml_attribute();
impl::xml_allocator& alloc = impl::get_allocator(_root);
if (!alloc.reserve()) return xml_attribute();
xml_attribute a(impl::allocate_attribute(alloc));
if (!a) return xml_attribute();
impl::insert_attribute_before(a._attr, attr._attr, _root);
impl::node_copy_attribute(a._attr, proto._attr);
return a;
}
PUGI__FN xml_node xml_node::append_child(xml_node_type type_)
{
if (!impl::allow_insert_child(type(), type_)) return xml_node();
impl::xml_allocator& alloc = impl::get_allocator(_root);
if (!alloc.reserve()) return xml_node();
xml_node n(impl::allocate_node(alloc, type_));
if (!n) return xml_node();
impl::append_node(n._root, _root);
if (type_ == node_declaration) n.set_name(PUGIXML_TEXT("xml"));
return n;
}
PUGI__FN xml_node xml_node::prepend_child(xml_node_type type_)
{
if (!impl::allow_insert_child(type(), type_)) return xml_node();
impl::xml_allocator& alloc = impl::get_allocator(_root);
if (!alloc.reserve()) return xml_node();
xml_node n(impl::allocate_node(alloc, type_));
if (!n) return xml_node();
impl::prepend_node(n._root, _root);
if (type_ == node_declaration) n.set_name(PUGIXML_TEXT("xml"));
return n;
}
PUGI__FN xml_node xml_node::insert_child_before(xml_node_type type_, const xml_node& node)
{
if (!impl::allow_insert_child(type(), type_)) return xml_node();
if (!node._root || node._root->parent != _root) return xml_node();
impl::xml_allocator& alloc = impl::get_allocator(_root);
if (!alloc.reserve()) return xml_node();
xml_node n(impl::allocate_node(alloc, type_));
if (!n) return xml_node();
impl::insert_node_before(n._root, node._root);
if (type_ == node_declaration) n.set_name(PUGIXML_TEXT("xml"));
return n;
}
PUGI__FN xml_node xml_node::insert_child_after(xml_node_type type_, const xml_node& node)
{
if (!impl::allow_insert_child(type(), type_)) return xml_node();
if (!node._root || node._root->parent != _root) return xml_node();
impl::xml_allocator& alloc = impl::get_allocator(_root);
if (!alloc.reserve()) return xml_node();
xml_node n(impl::allocate_node(alloc, type_));
if (!n) return xml_node();
impl::insert_node_after(n._root, node._root);
if (type_ == node_declaration) n.set_name(PUGIXML_TEXT("xml"));
return n;
}
PUGI__FN xml_node xml_node::append_child(const char_t* name_)
{
xml_node result = append_child(node_element);
result.set_name(name_);
return result;
}
PUGI__FN xml_node xml_node::prepend_child(const char_t* name_)
{
xml_node result = prepend_child(node_element);
result.set_name(name_);
return result;
}
PUGI__FN xml_node xml_node::insert_child_after(const char_t* name_, const xml_node& node)
{
xml_node result = insert_child_after(node_element, node);
result.set_name(name_);
return result;
}
PUGI__FN xml_node xml_node::insert_child_before(const char_t* name_, const xml_node& node)
{
xml_node result = insert_child_before(node_element, node);
result.set_name(name_);
return result;
}
PUGI__FN xml_node xml_node::append_copy(const xml_node& proto)
{
xml_node_type type_ = proto.type();
if (!impl::allow_insert_child(type(), type_)) return xml_node();
impl::xml_allocator& alloc = impl::get_allocator(_root);
if (!alloc.reserve()) return xml_node();
xml_node n(impl::allocate_node(alloc, type_));
if (!n) return xml_node();
impl::append_node(n._root, _root);
impl::node_copy_tree(n._root, proto._root);
return n;
}
PUGI__FN xml_node xml_node::prepend_copy(const xml_node& proto)
{
xml_node_type type_ = proto.type();
if (!impl::allow_insert_child(type(), type_)) return xml_node();
impl::xml_allocator& alloc = impl::get_allocator(_root);
if (!alloc.reserve()) return xml_node();
xml_node n(impl::allocate_node(alloc, type_));
if (!n) return xml_node();
impl::prepend_node(n._root, _root);
impl::node_copy_tree(n._root, proto._root);
return n;
}
PUGI__FN xml_node xml_node::insert_copy_after(const xml_node& proto, const xml_node& node)
{
xml_node_type type_ = proto.type();
if (!impl::allow_insert_child(type(), type_)) return xml_node();
if (!node._root || node._root->parent != _root) return xml_node();
impl::xml_allocator& alloc = impl::get_allocator(_root);
if (!alloc.reserve()) return xml_node();
xml_node n(impl::allocate_node(alloc, type_));
if (!n) return xml_node();
impl::insert_node_after(n._root, node._root);
impl::node_copy_tree(n._root, proto._root);
return n;
}
PUGI__FN xml_node xml_node::insert_copy_before(const xml_node& proto, const xml_node& node)
{
xml_node_type type_ = proto.type();
if (!impl::allow_insert_child(type(), type_)) return xml_node();
if (!node._root || node._root->parent != _root) return xml_node();
impl::xml_allocator& alloc = impl::get_allocator(_root);
if (!alloc.reserve()) return xml_node();
xml_node n(impl::allocate_node(alloc, type_));
if (!n) return xml_node();
impl::insert_node_before(n._root, node._root);
impl::node_copy_tree(n._root, proto._root);
return n;
}
PUGI__FN xml_node xml_node::append_move(const xml_node& moved)
{
if (!impl::allow_move(*this, moved)) return xml_node();
impl::xml_allocator& alloc = impl::get_allocator(_root);
if (!alloc.reserve()) return xml_node();
// disable document_buffer_order optimization since moving nodes around changes document order without changing buffer pointers
impl::get_document(_root).header |= impl::xml_memory_page_contents_shared_mask;
impl::remove_node(moved._root);
impl::append_node(moved._root, _root);
return moved;
}
PUGI__FN xml_node xml_node::prepend_move(const xml_node& moved)
{
if (!impl::allow_move(*this, moved)) return xml_node();
impl::xml_allocator& alloc = impl::get_allocator(_root);
if (!alloc.reserve()) return xml_node();
// disable document_buffer_order optimization since moving nodes around changes document order without changing buffer pointers
impl::get_document(_root).header |= impl::xml_memory_page_contents_shared_mask;
impl::remove_node(moved._root);
impl::prepend_node(moved._root, _root);
return moved;
}
PUGI__FN xml_node xml_node::insert_move_after(const xml_node& moved, const xml_node& node)
{
if (!impl::allow_move(*this, moved)) return xml_node();
if (!node._root || node._root->parent != _root) return xml_node();
if (moved._root == node._root) return xml_node();
impl::xml_allocator& alloc = impl::get_allocator(_root);
if (!alloc.reserve()) return xml_node();
// disable document_buffer_order optimization since moving nodes around changes document order without changing buffer pointers
impl::get_document(_root).header |= impl::xml_memory_page_contents_shared_mask;
impl::remove_node(moved._root);
impl::insert_node_after(moved._root, node._root);
return moved;
}
PUGI__FN xml_node xml_node::insert_move_before(const xml_node& moved, const xml_node& node)
{
if (!impl::allow_move(*this, moved)) return xml_node();
if (!node._root || node._root->parent != _root) return xml_node();
if (moved._root == node._root) return xml_node();
impl::xml_allocator& alloc = impl::get_allocator(_root);
if (!alloc.reserve()) return xml_node();
// disable document_buffer_order optimization since moving nodes around changes document order without changing buffer pointers
impl::get_document(_root).header |= impl::xml_memory_page_contents_shared_mask;
impl::remove_node(moved._root);
impl::insert_node_before(moved._root, node._root);
return moved;
}
PUGI__FN bool xml_node::remove_attribute(const char_t* name_)
{
return remove_attribute(attribute(name_));
}
PUGI__FN bool xml_node::remove_attribute(const xml_attribute& a)
{
if (!_root || !a._attr) return false;
if (!impl::is_attribute_of(a._attr, _root)) return false;
impl::xml_allocator& alloc = impl::get_allocator(_root);
if (!alloc.reserve()) return false;
impl::remove_attribute(a._attr, _root);
impl::destroy_attribute(a._attr, alloc);
return true;
}
PUGI__FN bool xml_node::remove_attributes()
{
if (!_root) return false;
impl::xml_allocator& alloc = impl::get_allocator(_root);
if (!alloc.reserve()) return false;
for (xml_attribute_struct* attr = _root->first_attribute; attr; )
{
xml_attribute_struct* next = attr->next_attribute;
impl::destroy_attribute(attr, alloc);
attr = next;
}
_root->first_attribute = 0;
return true;
}
PUGI__FN bool xml_node::remove_child(const char_t* name_)
{
return remove_child(child(name_));
}
PUGI__FN bool xml_node::remove_child(const xml_node& n)
{
if (!_root || !n._root || n._root->parent != _root) return false;
impl::xml_allocator& alloc = impl::get_allocator(_root);
if (!alloc.reserve()) return false;
impl::remove_node(n._root);
impl::destroy_node(n._root, alloc);
return true;
}
PUGI__FN bool xml_node::remove_children()
{
if (!_root) return false;
impl::xml_allocator& alloc = impl::get_allocator(_root);
if (!alloc.reserve()) return false;
for (xml_node_struct* cur = _root->first_child; cur; )
{
xml_node_struct* next = cur->next_sibling;
impl::destroy_node(cur, alloc);
cur = next;
}
_root->first_child = 0;
return true;
}
PUGI__FN xml_parse_result xml_node::append_buffer(const void* contents, size_t size, unsigned int options, xml_encoding encoding)
{
// append_buffer is only valid for elements/documents
if (!impl::allow_insert_child(type(), node_element)) return impl::make_parse_result(status_append_invalid_root);
// get document node
impl::xml_document_struct* doc = &impl::get_document(_root);
// disable document_buffer_order optimization since in a document with multiple buffers comparing buffer pointers does not make sense
doc->header |= impl::xml_memory_page_contents_shared_mask;
// get extra buffer element (we'll store the document fragment buffer there so that we can deallocate it later)
impl::xml_memory_page* page = 0;
impl::xml_extra_buffer* extra = static_cast<impl::xml_extra_buffer*>(doc->allocate_memory(sizeof(impl::xml_extra_buffer) + sizeof(void*), page));
(void)page;
if (!extra) return impl::make_parse_result(status_out_of_memory);
#ifdef PUGIXML_COMPACT
// align the memory block to a pointer boundary; this is required for compact mode where memory allocations are only 4b aligned
// note that this requires up to sizeof(void*)-1 additional memory, which the allocation above takes into account
extra = reinterpret_cast<impl::xml_extra_buffer*>((reinterpret_cast<uintptr_t>(extra) + (sizeof(void*) - 1)) & ~(sizeof(void*) - 1));
#endif
// add extra buffer to the list
extra->buffer = 0;
extra->next = doc->extra_buffers;
doc->extra_buffers = extra;
// name of the root has to be NULL before parsing - otherwise closing node mismatches will not be detected at the top level
impl::name_null_sentry sentry(_root);
return impl::load_buffer_impl(doc, _root, const_cast<void*>(contents), size, options, encoding, false, false, &extra->buffer);
}
PUGI__FN xml_node xml_node::find_child_by_attribute(const char_t* name_, const char_t* attr_name, const char_t* attr_value) const
{
if (!_root) return xml_node();
for (xml_node_struct* i = _root->first_child; i; i = i->next_sibling)
if (i->name && impl::strequal(name_, i->name))
{
for (xml_attribute_struct* a = i->first_attribute; a; a = a->next_attribute)
if (a->name && impl::strequal(attr_name, a->name) && impl::strequal(attr_value, a->value ? a->value + 0 : PUGIXML_TEXT("")))
return xml_node(i);
}
return xml_node();
}
PUGI__FN xml_node xml_node::find_child_by_attribute(const char_t* attr_name, const char_t* attr_value) const
{
if (!_root) return xml_node();
for (xml_node_struct* i = _root->first_child; i; i = i->next_sibling)
for (xml_attribute_struct* a = i->first_attribute; a; a = a->next_attribute)
if (a->name && impl::strequal(attr_name, a->name) && impl::strequal(attr_value, a->value ? a->value + 0 : PUGIXML_TEXT("")))
return xml_node(i);
return xml_node();
}
#ifndef PUGIXML_NO_STL
PUGI__FN string_t xml_node::path(char_t delimiter) const
{
if (!_root) return string_t();
size_t offset = 0;
for (xml_node_struct* i = _root; i; i = i->parent)
{
offset += (i != _root);
offset += i->name ? impl::strlength(i->name) : 0;
}
string_t result;
result.resize(offset);
for (xml_node_struct* j = _root; j; j = j->parent)
{
if (j != _root)
result[--offset] = delimiter;
if (j->name)
{
size_t length = impl::strlength(j->name);
offset -= length;
memcpy(&result[offset], j->name, length * sizeof(char_t));
}
}
assert(offset == 0);
return result;
}
#endif
PUGI__FN xml_node xml_node::first_element_by_path(const char_t* path_, char_t delimiter) const
{
xml_node context = path_[0] == delimiter ? root() : *this;
if (!context._root) return xml_node();
const char_t* path_segment = path_;
while (*path_segment == delimiter) ++path_segment;
const char_t* path_segment_end = path_segment;
while (*path_segment_end && *path_segment_end != delimiter) ++path_segment_end;
if (path_segment == path_segment_end) return context;
const char_t* next_segment = path_segment_end;
while (*next_segment == delimiter) ++next_segment;
if (*path_segment == '.' && path_segment + 1 == path_segment_end)
return context.first_element_by_path(next_segment, delimiter);
else if (*path_segment == '.' && *(path_segment+1) == '.' && path_segment + 2 == path_segment_end)
return context.parent().first_element_by_path(next_segment, delimiter);
else
{
for (xml_node_struct* j = context._root->first_child; j; j = j->next_sibling)
{
if (j->name && impl::strequalrange(j->name, path_segment, static_cast<size_t>(path_segment_end - path_segment)))
{
xml_node subsearch = xml_node(j).first_element_by_path(next_segment, delimiter);
if (subsearch) return subsearch;
}
}
return xml_node();
}
}
PUGI__FN bool xml_node::traverse(xml_tree_walker& walker)
{
walker._depth = -1;
xml_node arg_begin(_root);
if (!walker.begin(arg_begin)) return false;
xml_node_struct* cur = _root ? _root->first_child + 0 : 0;
if (cur)
{
++walker._depth;
do
{
xml_node arg_for_each(cur);
if (!walker.for_each(arg_for_each))
return false;
if (cur->first_child)
{
++walker._depth;
cur = cur->first_child;
}
else if (cur->next_sibling)
cur = cur->next_sibling;
else
{
while (!cur->next_sibling && cur != _root && cur->parent)
{
--walker._depth;
cur = cur->parent;
}
if (cur != _root)
cur = cur->next_sibling;
}
}
while (cur && cur != _root);
}
assert(walker._depth == -1);
xml_node arg_end(_root);
return walker.end(arg_end);
}
PUGI__FN size_t xml_node::hash_value() const
{
return static_cast<size_t>(reinterpret_cast<uintptr_t>(_root) / sizeof(xml_node_struct));
}
PUGI__FN xml_node_struct* xml_node::internal_object() const
{
return _root;
}
PUGI__FN void xml_node::print(xml_writer& writer, const char_t* indent, unsigned int flags, xml_encoding encoding, unsigned int depth) const
{
if (!_root) return;
impl::xml_buffered_writer buffered_writer(writer, encoding);
impl::node_output(buffered_writer, _root, indent, flags, depth);
buffered_writer.flush();
}
#ifndef PUGIXML_NO_STL
PUGI__FN void xml_node::print(std::basic_ostream<char, std::char_traits<char> >& stream, const char_t* indent, unsigned int flags, xml_encoding encoding, unsigned int depth) const
{
xml_writer_stream writer(stream);
print(writer, indent, flags, encoding, depth);
}
PUGI__FN void xml_node::print(std::basic_ostream<wchar_t, std::char_traits<wchar_t> >& stream, const char_t* indent, unsigned int flags, unsigned int depth) const
{
xml_writer_stream writer(stream);
print(writer, indent, flags, encoding_wchar, depth);
}
#endif
PUGI__FN ptrdiff_t xml_node::offset_debug() const
{
if (!_root) return -1;
impl::xml_document_struct& doc = impl::get_document(_root);
// we can determine the offset reliably only if there is exactly once parse buffer
if (!doc.buffer || doc.extra_buffers) return -1;
switch (type())
{
case node_document:
return 0;
case node_element:
case node_declaration:
case node_pi:
return _root->name && (_root->header & impl::xml_memory_page_name_allocated_or_shared_mask) == 0 ? _root->name - doc.buffer : -1;
case node_pcdata:
case node_cdata:
case node_comment:
case node_doctype:
return _root->value && (_root->header & impl::xml_memory_page_value_allocated_or_shared_mask) == 0 ? _root->value - doc.buffer : -1;
default:
assert(false && "Invalid node type"); // unreachable
return -1;
}
}
#ifdef __BORLANDC__
PUGI__FN bool operator&&(const xml_node& lhs, bool rhs)
{
return (bool)lhs && rhs;
}
PUGI__FN bool operator||(const xml_node& lhs, bool rhs)
{
return (bool)lhs || rhs;
}
#endif
PUGI__FN xml_text::xml_text(xml_node_struct* root): _root(root)
{
}
PUGI__FN xml_node_struct* xml_text::_data() const
{
if (!_root || impl::is_text_node(_root)) return _root;
// element nodes can have value if parse_embed_pcdata was used
if (PUGI__NODETYPE(_root) == node_element && _root->value)
return _root;
for (xml_node_struct* node = _root->first_child; node; node = node->next_sibling)
if (impl::is_text_node(node))
return node;
return 0;
}
PUGI__FN xml_node_struct* xml_text::_data_new()
{
xml_node_struct* d = _data();
if (d) return d;
return xml_node(_root).append_child(node_pcdata).internal_object();
}
PUGI__FN xml_text::xml_text(): _root(0)
{
}
PUGI__FN static void unspecified_bool_xml_text(xml_text***)
{
}
PUGI__FN xml_text::operator xml_text::unspecified_bool_type() const
{
return _data() ? unspecified_bool_xml_text : 0;
}
PUGI__FN bool xml_text::operator!() const
{
return !_data();
}
PUGI__FN bool xml_text::empty() const
{
return _data() == 0;
}
PUGI__FN const char_t* xml_text::get() const
{
xml_node_struct* d = _data();
return (d && d->value) ? d->value + 0 : PUGIXML_TEXT("");
}
PUGI__FN const char_t* xml_text::as_string(const char_t* def) const
{
xml_node_struct* d = _data();
return (d && d->value) ? d->value + 0 : def;
}
PUGI__FN int xml_text::as_int(int def) const
{
xml_node_struct* d = _data();
return (d && d->value) ? impl::get_value_int(d->value) : def;
}
PUGI__FN unsigned int xml_text::as_uint(unsigned int def) const
{
xml_node_struct* d = _data();
return (d && d->value) ? impl::get_value_uint(d->value) : def;
}
PUGI__FN double xml_text::as_double(double def) const
{
xml_node_struct* d = _data();
return (d && d->value) ? impl::get_value_double(d->value) : def;
}
PUGI__FN float xml_text::as_float(float def) const
{
xml_node_struct* d = _data();
return (d && d->value) ? impl::get_value_float(d->value) : def;
}
PUGI__FN bool xml_text::as_bool(bool def) const
{
xml_node_struct* d = _data();
return (d && d->value) ? impl::get_value_bool(d->value) : def;
}
#ifdef PUGIXML_HAS_LONG_LONG
PUGI__FN long long xml_text::as_llong(long long def) const
{
xml_node_struct* d = _data();
return (d && d->value) ? impl::get_value_llong(d->value) : def;
}
PUGI__FN unsigned long long xml_text::as_ullong(unsigned long long def) const
{
xml_node_struct* d = _data();
return (d && d->value) ? impl::get_value_ullong(d->value) : def;
}
#endif
PUGI__FN bool xml_text::set(const char_t* rhs)
{
xml_node_struct* dn = _data_new();
return dn ? impl::strcpy_insitu(dn->value, dn->header, impl::xml_memory_page_value_allocated_mask, rhs, impl::strlength(rhs)) : false;
}
PUGI__FN bool xml_text::set(int rhs)
{
xml_node_struct* dn = _data_new();
return dn ? impl::set_value_integer<unsigned int>(dn->value, dn->header, impl::xml_memory_page_value_allocated_mask, rhs, rhs < 0) : false;
}
PUGI__FN bool xml_text::set(unsigned int rhs)
{
xml_node_struct* dn = _data_new();
return dn ? impl::set_value_integer<unsigned int>(dn->value, dn->header, impl::xml_memory_page_value_allocated_mask, rhs, false) : false;
}
PUGI__FN bool xml_text::set(long rhs)
{
xml_node_struct* dn = _data_new();
return dn ? impl::set_value_integer<unsigned long>(dn->value, dn->header, impl::xml_memory_page_value_allocated_mask, rhs, rhs < 0) : false;
}
PUGI__FN bool xml_text::set(unsigned long rhs)
{
xml_node_struct* dn = _data_new();
return dn ? impl::set_value_integer<unsigned long>(dn->value, dn->header, impl::xml_memory_page_value_allocated_mask, rhs, false) : false;
}
PUGI__FN bool xml_text::set(float rhs)
{
xml_node_struct* dn = _data_new();
return dn ? impl::set_value_convert(dn->value, dn->header, impl::xml_memory_page_value_allocated_mask, rhs, default_float_precision) : false;
}
PUGI__FN bool xml_text::set(float rhs, int precision)
{
xml_node_struct* dn = _data_new();
return dn ? impl::set_value_convert(dn->value, dn->header, impl::xml_memory_page_value_allocated_mask, rhs, precision) : false;
}
PUGI__FN bool xml_text::set(double rhs)
{
xml_node_struct* dn = _data_new();
return dn ? impl::set_value_convert(dn->value, dn->header, impl::xml_memory_page_value_allocated_mask, rhs, default_double_precision) : false;
}
PUGI__FN bool xml_text::set(double rhs, int precision)
{
xml_node_struct* dn = _data_new();
return dn ? impl::set_value_convert(dn->value, dn->header, impl::xml_memory_page_value_allocated_mask, rhs, precision) : false;
}
PUGI__FN bool xml_text::set(bool rhs)
{
xml_node_struct* dn = _data_new();
return dn ? impl::set_value_bool(dn->value, dn->header, impl::xml_memory_page_value_allocated_mask, rhs) : false;
}
#ifdef PUGIXML_HAS_LONG_LONG
PUGI__FN bool xml_text::set(long long rhs)
{
xml_node_struct* dn = _data_new();
return dn ? impl::set_value_integer<unsigned long long>(dn->value, dn->header, impl::xml_memory_page_value_allocated_mask, rhs, rhs < 0) : false;
}
PUGI__FN bool xml_text::set(unsigned long long rhs)
{
xml_node_struct* dn = _data_new();
return dn ? impl::set_value_integer<unsigned long long>(dn->value, dn->header, impl::xml_memory_page_value_allocated_mask, rhs, false) : false;
}
#endif
PUGI__FN xml_text& xml_text::operator=(const char_t* rhs)
{
set(rhs);
return *this;
}
PUGI__FN xml_text& xml_text::operator=(int rhs)
{
set(rhs);
return *this;
}
PUGI__FN xml_text& xml_text::operator=(unsigned int rhs)
{
set(rhs);
return *this;
}
PUGI__FN xml_text& xml_text::operator=(long rhs)
{
set(rhs);
return *this;
}
PUGI__FN xml_text& xml_text::operator=(unsigned long rhs)
{
set(rhs);
return *this;
}
PUGI__FN xml_text& xml_text::operator=(double rhs)
{
set(rhs);
return *this;
}
PUGI__FN xml_text& xml_text::operator=(float rhs)
{
set(rhs);
return *this;
}
PUGI__FN xml_text& xml_text::operator=(bool rhs)
{
set(rhs);
return *this;
}
#ifdef PUGIXML_HAS_LONG_LONG
PUGI__FN xml_text& xml_text::operator=(long long rhs)
{
set(rhs);
return *this;
}
PUGI__FN xml_text& xml_text::operator=(unsigned long long rhs)
{
set(rhs);
return *this;
}
#endif
PUGI__FN xml_node xml_text::data() const
{
return xml_node(_data());
}
#ifdef __BORLANDC__
PUGI__FN bool operator&&(const xml_text& lhs, bool rhs)
{
return (bool)lhs && rhs;
}
PUGI__FN bool operator||(const xml_text& lhs, bool rhs)
{
return (bool)lhs || rhs;
}
#endif
PUGI__FN xml_node_iterator::xml_node_iterator()
{
}
PUGI__FN xml_node_iterator::xml_node_iterator(const xml_node& node): _wrap(node), _parent(node.parent())
{
}
PUGI__FN xml_node_iterator::xml_node_iterator(xml_node_struct* ref, xml_node_struct* parent): _wrap(ref), _parent(parent)
{
}
PUGI__FN bool xml_node_iterator::operator==(const xml_node_iterator& rhs) const
{
return _wrap._root == rhs._wrap._root && _parent._root == rhs._parent._root;
}
PUGI__FN bool xml_node_iterator::operator!=(const xml_node_iterator& rhs) const
{
return _wrap._root != rhs._wrap._root || _parent._root != rhs._parent._root;
}
PUGI__FN xml_node& xml_node_iterator::operator*() const
{
assert(_wrap._root);
return _wrap;
}
PUGI__FN xml_node* xml_node_iterator::operator->() const
{
assert(_wrap._root);
return const_cast<xml_node*>(&_wrap); // BCC5 workaround
}
PUGI__FN const xml_node_iterator& xml_node_iterator::operator++()
{
assert(_wrap._root);
_wrap._root = _wrap._root->next_sibling;
return *this;
}
PUGI__FN xml_node_iterator xml_node_iterator::operator++(int)
{
xml_node_iterator temp = *this;
++*this;
return temp;
}
PUGI__FN const xml_node_iterator& xml_node_iterator::operator--()
{
_wrap = _wrap._root ? _wrap.previous_sibling() : _parent.last_child();
return *this;
}
PUGI__FN xml_node_iterator xml_node_iterator::operator--(int)
{
xml_node_iterator temp = *this;
--*this;
return temp;
}
PUGI__FN xml_attribute_iterator::xml_attribute_iterator()
{
}
PUGI__FN xml_attribute_iterator::xml_attribute_iterator(const xml_attribute& attr, const xml_node& parent): _wrap(attr), _parent(parent)
{
}
PUGI__FN xml_attribute_iterator::xml_attribute_iterator(xml_attribute_struct* ref, xml_node_struct* parent): _wrap(ref), _parent(parent)
{
}
PUGI__FN bool xml_attribute_iterator::operator==(const xml_attribute_iterator& rhs) const
{
return _wrap._attr == rhs._wrap._attr && _parent._root == rhs._parent._root;
}
PUGI__FN bool xml_attribute_iterator::operator!=(const xml_attribute_iterator& rhs) const
{
return _wrap._attr != rhs._wrap._attr || _parent._root != rhs._parent._root;
}
PUGI__FN xml_attribute& xml_attribute_iterator::operator*() const
{
assert(_wrap._attr);
return _wrap;
}
PUGI__FN xml_attribute* xml_attribute_iterator::operator->() const
{
assert(_wrap._attr);
return const_cast<xml_attribute*>(&_wrap); // BCC5 workaround
}
PUGI__FN const xml_attribute_iterator& xml_attribute_iterator::operator++()
{
assert(_wrap._attr);
_wrap._attr = _wrap._attr->next_attribute;
return *this;
}
PUGI__FN xml_attribute_iterator xml_attribute_iterator::operator++(int)
{
xml_attribute_iterator temp = *this;
++*this;
return temp;
}
PUGI__FN const xml_attribute_iterator& xml_attribute_iterator::operator--()
{
_wrap = _wrap._attr ? _wrap.previous_attribute() : _parent.last_attribute();
return *this;
}
PUGI__FN xml_attribute_iterator xml_attribute_iterator::operator--(int)
{
xml_attribute_iterator temp = *this;
--*this;
return temp;
}
PUGI__FN xml_named_node_iterator::xml_named_node_iterator(): _name(0)
{
}
PUGI__FN xml_named_node_iterator::xml_named_node_iterator(const xml_node& node, const char_t* name): _wrap(node), _parent(node.parent()), _name(name)
{
}
PUGI__FN xml_named_node_iterator::xml_named_node_iterator(xml_node_struct* ref, xml_node_struct* parent, const char_t* name): _wrap(ref), _parent(parent), _name(name)
{
}
PUGI__FN bool xml_named_node_iterator::operator==(const xml_named_node_iterator& rhs) const
{
return _wrap._root == rhs._wrap._root && _parent._root == rhs._parent._root;
}
PUGI__FN bool xml_named_node_iterator::operator!=(const xml_named_node_iterator& rhs) const
{
return _wrap._root != rhs._wrap._root || _parent._root != rhs._parent._root;
}
PUGI__FN xml_node& xml_named_node_iterator::operator*() const
{
assert(_wrap._root);
return _wrap;
}
PUGI__FN xml_node* xml_named_node_iterator::operator->() const
{
assert(_wrap._root);
return const_cast<xml_node*>(&_wrap); // BCC5 workaround
}
PUGI__FN const xml_named_node_iterator& xml_named_node_iterator::operator++()
{
assert(_wrap._root);
_wrap = _wrap.next_sibling(_name);
return *this;
}
PUGI__FN xml_named_node_iterator xml_named_node_iterator::operator++(int)
{
xml_named_node_iterator temp = *this;
++*this;
return temp;
}
PUGI__FN const xml_named_node_iterator& xml_named_node_iterator::operator--()
{
if (_wrap._root)
_wrap = _wrap.previous_sibling(_name);
else
{
_wrap = _parent.last_child();
if (!impl::strequal(_wrap.name(), _name))
_wrap = _wrap.previous_sibling(_name);
}
return *this;
}
PUGI__FN xml_named_node_iterator xml_named_node_iterator::operator--(int)
{
xml_named_node_iterator temp = *this;
--*this;
return temp;
}
PUGI__FN xml_parse_result::xml_parse_result(): status(status_internal_error), offset(0), encoding(encoding_auto)
{
}
PUGI__FN xml_parse_result::operator bool() const
{
return status == status_ok;
}
PUGI__FN const char* xml_parse_result::description() const
{
switch (status)
{
case status_ok: return "No error";
case status_file_not_found: return "File was not found";
case status_io_error: return "Error reading from file/stream";
case status_out_of_memory: return "Could not allocate memory";
case status_internal_error: return "Internal error occurred";
case status_unrecognized_tag: return "Could not determine tag type";
case status_bad_pi: return "Error parsing document declaration/processing instruction";
case status_bad_comment: return "Error parsing comment";
case status_bad_cdata: return "Error parsing CDATA section";
case status_bad_doctype: return "Error parsing document type declaration";
case status_bad_pcdata: return "Error parsing PCDATA section";
case status_bad_start_element: return "Error parsing start element tag";
case status_bad_attribute: return "Error parsing element attribute";
case status_bad_end_element: return "Error parsing end element tag";
case status_end_element_mismatch: return "Start-end tags mismatch";
case status_append_invalid_root: return "Unable to append nodes: root is not an element or document";
case status_no_document_element: return "No document element found";
default: return "Unknown error";
}
}
PUGI__FN xml_document::xml_document(): _buffer(0)
{
_create();
}
PUGI__FN xml_document::~xml_document()
{
_destroy();
}
#ifdef PUGIXML_HAS_MOVE
PUGI__FN xml_document::xml_document(xml_document&& rhs) PUGIXML_NOEXCEPT_IF_NOT_COMPACT: _buffer(0)
{
_create();
_move(rhs);
}
PUGI__FN xml_document& xml_document::operator=(xml_document&& rhs) PUGIXML_NOEXCEPT_IF_NOT_COMPACT
{
if (this == &rhs) return *this;
_destroy();
_create();
_move(rhs);
return *this;
}
#endif
PUGI__FN void xml_document::reset()
{
_destroy();
_create();
}
PUGI__FN void xml_document::reset(const xml_document& proto)
{
reset();
impl::node_copy_tree(_root, proto._root);
}
PUGI__FN void xml_document::_create()
{
assert(!_root);
#ifdef PUGIXML_COMPACT
// space for page marker for the first page (uint32_t), rounded up to pointer size; assumes pointers are at least 32-bit
const size_t page_offset = sizeof(void*);
#else
const size_t page_offset = 0;
#endif
// initialize sentinel page
PUGI__STATIC_ASSERT(sizeof(impl::xml_memory_page) + sizeof(impl::xml_document_struct) + page_offset <= sizeof(_memory));
// prepare page structure
impl::xml_memory_page* page = impl::xml_memory_page::construct(_memory);
assert(page);
page->busy_size = impl::xml_memory_page_size;
// setup first page marker
#ifdef PUGIXML_COMPACT
// round-trip through void* to avoid 'cast increases required alignment of target type' warning
page->compact_page_marker = reinterpret_cast<uint32_t*>(static_cast<void*>(reinterpret_cast<char*>(page) + sizeof(impl::xml_memory_page)));
*page->compact_page_marker = sizeof(impl::xml_memory_page);
#endif
// allocate new root
_root = new (reinterpret_cast<char*>(page) + sizeof(impl::xml_memory_page) + page_offset) impl::xml_document_struct(page);
_root->prev_sibling_c = _root;
// setup sentinel page
page->allocator = static_cast<impl::xml_document_struct*>(_root);
// setup hash table pointer in allocator
#ifdef PUGIXML_COMPACT
page->allocator->_hash = &static_cast<impl::xml_document_struct*>(_root)->hash;
#endif
// verify the document allocation
assert(reinterpret_cast<char*>(_root) + sizeof(impl::xml_document_struct) <= _memory + sizeof(_memory));
}
PUGI__FN void xml_document::_destroy()
{
assert(_root);
// destroy static storage
if (_buffer)
{
impl::xml_memory::deallocate(_buffer);
_buffer = 0;
}
// destroy extra buffers (note: no need to destroy linked list nodes, they're allocated using document allocator)
for (impl::xml_extra_buffer* extra = static_cast<impl::xml_document_struct*>(_root)->extra_buffers; extra; extra = extra->next)
{
if (extra->buffer) impl::xml_memory::deallocate(extra->buffer);
}
// destroy dynamic storage, leave sentinel page (it's in static memory)
impl::xml_memory_page* root_page = PUGI__GETPAGE(_root);
assert(root_page && !root_page->prev);
assert(reinterpret_cast<char*>(root_page) >= _memory && reinterpret_cast<char*>(root_page) < _memory + sizeof(_memory));
for (impl::xml_memory_page* page = root_page->next; page; )
{
impl::xml_memory_page* next = page->next;
impl::xml_allocator::deallocate_page(page);
page = next;
}
#ifdef PUGIXML_COMPACT
// destroy hash table
static_cast<impl::xml_document_struct*>(_root)->hash.clear();
#endif
_root = 0;
}
#ifdef PUGIXML_HAS_MOVE
PUGI__FN void xml_document::_move(xml_document& rhs) PUGIXML_NOEXCEPT_IF_NOT_COMPACT
{
impl::xml_document_struct* doc = static_cast<impl::xml_document_struct*>(_root);
impl::xml_document_struct* other = static_cast<impl::xml_document_struct*>(rhs._root);
// save first child pointer for later; this needs hash access
xml_node_struct* other_first_child = other->first_child;
#ifdef PUGIXML_COMPACT
// reserve space for the hash table up front; this is the only operation that can fail
// if it does, we have no choice but to throw (if we have exceptions)
if (other_first_child)
{
size_t other_children = 0;
for (xml_node_struct* node = other_first_child; node; node = node->next_sibling)
other_children++;
// in compact mode, each pointer assignment could result in a hash table request
// during move, we have to relocate document first_child and parents of all children
// normally there's just one child and its parent has a pointerless encoding but
// we assume the worst here
if (!other->_hash->reserve(other_children + 1))
{
#ifdef PUGIXML_NO_EXCEPTIONS
return;
#else
throw std::bad_alloc();
#endif
}
}
#endif
// move allocation state
doc->_root = other->_root;
doc->_busy_size = other->_busy_size;
// move buffer state
doc->buffer = other->buffer;
doc->extra_buffers = other->extra_buffers;
_buffer = rhs._buffer;
#ifdef PUGIXML_COMPACT
// move compact hash; note that the hash table can have pointers to other but they will be "inactive", similarly to nodes removed with remove_child
doc->hash = other->hash;
doc->_hash = &doc->hash;
// make sure we don't access other hash up until the end when we reinitialize other document
other->_hash = 0;
#endif
// move page structure
impl::xml_memory_page* doc_page = PUGI__GETPAGE(doc);
assert(doc_page && !doc_page->prev && !doc_page->next);
impl::xml_memory_page* other_page = PUGI__GETPAGE(other);
assert(other_page && !other_page->prev);
// relink pages since root page is embedded into xml_document
if (impl::xml_memory_page* page = other_page->next)
{
assert(page->prev == other_page);
page->prev = doc_page;
doc_page->next = page;
other_page->next = 0;
}
// make sure pages point to the correct document state
for (impl::xml_memory_page* page = doc_page->next; page; page = page->next)
{
assert(page->allocator == other);
page->allocator = doc;
#ifdef PUGIXML_COMPACT
// this automatically migrates most children between documents and prevents ->parent assignment from allocating
if (page->compact_shared_parent == other)
page->compact_shared_parent = doc;
#endif
}
// move tree structure
assert(!doc->first_child);
doc->first_child = other_first_child;
for (xml_node_struct* node = other_first_child; node; node = node->next_sibling)
{
#ifdef PUGIXML_COMPACT
// most children will have migrated when we reassigned compact_shared_parent
assert(node->parent == other || node->parent == doc);
node->parent = doc;
#else
assert(node->parent == other);
node->parent = doc;
#endif
}
// reset other document
new (other) impl::xml_document_struct(PUGI__GETPAGE(other));
rhs._buffer = 0;
}
#endif
#ifndef PUGIXML_NO_STL
PUGI__FN xml_parse_result xml_document::load(std::basic_istream<char, std::char_traits<char> >& stream, unsigned int options, xml_encoding encoding)
{
reset();
return impl::load_stream_impl(static_cast<impl::xml_document_struct*>(_root), stream, options, encoding, &_buffer);
}
PUGI__FN xml_parse_result xml_document::load(std::basic_istream<wchar_t, std::char_traits<wchar_t> >& stream, unsigned int options)
{
reset();
return impl::load_stream_impl(static_cast<impl::xml_document_struct*>(_root), stream, options, encoding_wchar, &_buffer);
}
#endif
PUGI__FN xml_parse_result xml_document::load_string(const char_t* contents, unsigned int options)
{
// Force native encoding (skip autodetection)
#ifdef PUGIXML_WCHAR_MODE
xml_encoding encoding = encoding_wchar;
#else
xml_encoding encoding = encoding_utf8;
#endif
return load_buffer(contents, impl::strlength(contents) * sizeof(char_t), options, encoding);
}
PUGI__FN xml_parse_result xml_document::load(const char_t* contents, unsigned int options)
{
return load_string(contents, options);
}
PUGI__FN xml_parse_result xml_document::load_file(const char* path_, unsigned int options, xml_encoding encoding)
{
reset();
using impl::auto_deleter; // MSVC7 workaround
auto_deleter<FILE> file(impl::open_file(path_, "rb"), impl::close_file);
return impl::load_file_impl(static_cast<impl::xml_document_struct*>(_root), file.data, options, encoding, &_buffer);
}
PUGI__FN xml_parse_result xml_document::load_file(const wchar_t* path_, unsigned int options, xml_encoding encoding)
{
reset();
using impl::auto_deleter; // MSVC7 workaround
auto_deleter<FILE> file(impl::open_file_wide(path_, L"rb"), impl::close_file);
return impl::load_file_impl(static_cast<impl::xml_document_struct*>(_root), file.data, options, encoding, &_buffer);
}
PUGI__FN xml_parse_result xml_document::load_buffer(const void* contents, size_t size, unsigned int options, xml_encoding encoding)
{
reset();
return impl::load_buffer_impl(static_cast<impl::xml_document_struct*>(_root), _root, const_cast<void*>(contents), size, options, encoding, false, false, &_buffer);
}
PUGI__FN xml_parse_result xml_document::load_buffer_inplace(void* contents, size_t size, unsigned int options, xml_encoding encoding)
{
reset();
return impl::load_buffer_impl(static_cast<impl::xml_document_struct*>(_root), _root, contents, size, options, encoding, true, false, &_buffer);
}
PUGI__FN xml_parse_result xml_document::load_buffer_inplace_own(void* contents, size_t size, unsigned int options, xml_encoding encoding)
{
reset();
return impl::load_buffer_impl(static_cast<impl::xml_document_struct*>(_root), _root, contents, size, options, encoding, true, true, &_buffer);
}
PUGI__FN void xml_document::save(xml_writer& writer, const char_t* indent, unsigned int flags, xml_encoding encoding) const
{
impl::xml_buffered_writer buffered_writer(writer, encoding);
if ((flags & format_write_bom) && encoding != encoding_latin1)
{
// BOM always represents the codepoint U+FEFF, so just write it in native encoding
#ifdef PUGIXML_WCHAR_MODE
unsigned int bom = 0xfeff;
buffered_writer.write(static_cast<wchar_t>(bom));
#else
buffered_writer.write('\xef', '\xbb', '\xbf');
#endif
}
if (!(flags & format_no_declaration) && !impl::has_declaration(_root))
{
buffered_writer.write_string(PUGIXML_TEXT("<?xml version=\"1.0\""));
if (encoding == encoding_latin1) buffered_writer.write_string(PUGIXML_TEXT(" encoding=\"ISO-8859-1\""));
buffered_writer.write('?', '>');
if (!(flags & format_raw)) buffered_writer.write('\n');
}
impl::node_output(buffered_writer, _root, indent, flags, 0);
buffered_writer.flush();
}
#ifndef PUGIXML_NO_STL
PUGI__FN void xml_document::save(std::basic_ostream<char, std::char_traits<char> >& stream, const char_t* indent, unsigned int flags, xml_encoding encoding) const
{
xml_writer_stream writer(stream);
save(writer, indent, flags, encoding);
}
PUGI__FN void xml_document::save(std::basic_ostream<wchar_t, std::char_traits<wchar_t> >& stream, const char_t* indent, unsigned int flags) const
{
xml_writer_stream writer(stream);
save(writer, indent, flags, encoding_wchar);
}
#endif
PUGI__FN bool xml_document::save_file(const char* path_, const char_t* indent, unsigned int flags, xml_encoding encoding) const
{
using impl::auto_deleter; // MSVC7 workaround
auto_deleter<FILE> file(impl::open_file(path_, (flags & format_save_file_text) ? "w" : "wb"), impl::close_file);
return impl::save_file_impl(*this, file.data, indent, flags, encoding);
}
PUGI__FN bool xml_document::save_file(const wchar_t* path_, const char_t* indent, unsigned int flags, xml_encoding encoding) const
{
using impl::auto_deleter; // MSVC7 workaround
auto_deleter<FILE> file(impl::open_file_wide(path_, (flags & format_save_file_text) ? L"w" : L"wb"), impl::close_file);
return impl::save_file_impl(*this, file.data, indent, flags, encoding);
}
PUGI__FN xml_node xml_document::document_element() const
{
assert(_root);
for (xml_node_struct* i = _root->first_child; i; i = i->next_sibling)
if (PUGI__NODETYPE(i) == node_element)
return xml_node(i);
return xml_node();
}
#ifndef PUGIXML_NO_STL
PUGI__FN std::string PUGIXML_FUNCTION as_utf8(const wchar_t* str)
{
assert(str);
return impl::as_utf8_impl(str, impl::strlength_wide(str));
}
PUGI__FN std::string PUGIXML_FUNCTION as_utf8(const std::basic_string<wchar_t>& str)
{
return impl::as_utf8_impl(str.c_str(), str.size());
}
PUGI__FN std::basic_string<wchar_t> PUGIXML_FUNCTION as_wide(const char* str)
{
assert(str);
return impl::as_wide_impl(str, strlen(str));
}
PUGI__FN std::basic_string<wchar_t> PUGIXML_FUNCTION as_wide(const std::string& str)
{
return impl::as_wide_impl(str.c_str(), str.size());
}
#endif
PUGI__FN void PUGIXML_FUNCTION set_memory_management_functions(allocation_function allocate, deallocation_function deallocate)
{
impl::xml_memory::allocate = allocate;
impl::xml_memory::deallocate = deallocate;
}
PUGI__FN allocation_function PUGIXML_FUNCTION get_memory_allocation_function()
{
return impl::xml_memory::allocate;
}
PUGI__FN deallocation_function PUGIXML_FUNCTION get_memory_deallocation_function()
{
return impl::xml_memory::deallocate;
}
}
#if !defined(PUGIXML_NO_STL) && (defined(_MSC_VER) || defined(__ICC))
namespace std
{
// Workarounds for (non-standard) iterator category detection for older versions (MSVC7/IC8 and earlier)
PUGI__FN std::bidirectional_iterator_tag _Iter_cat(const pugi::xml_node_iterator&)
{
return std::bidirectional_iterator_tag();
}
PUGI__FN std::bidirectional_iterator_tag _Iter_cat(const pugi::xml_attribute_iterator&)
{
return std::bidirectional_iterator_tag();
}
PUGI__FN std::bidirectional_iterator_tag _Iter_cat(const pugi::xml_named_node_iterator&)
{
return std::bidirectional_iterator_tag();
}
}
#endif
#if !defined(PUGIXML_NO_STL) && defined(__SUNPRO_CC)
namespace std
{
// Workarounds for (non-standard) iterator category detection
PUGI__FN std::bidirectional_iterator_tag __iterator_category(const pugi::xml_node_iterator&)
{
return std::bidirectional_iterator_tag();
}
PUGI__FN std::bidirectional_iterator_tag __iterator_category(const pugi::xml_attribute_iterator&)
{
return std::bidirectional_iterator_tag();
}
PUGI__FN std::bidirectional_iterator_tag __iterator_category(const pugi::xml_named_node_iterator&)
{
return std::bidirectional_iterator_tag();
}
}
#endif
#ifndef PUGIXML_NO_XPATH
// STL replacements
PUGI__NS_BEGIN
struct equal_to
{
template <typename T> bool operator()(const T& lhs, const T& rhs) const
{
return lhs == rhs;
}
};
struct not_equal_to
{
template <typename T> bool operator()(const T& lhs, const T& rhs) const
{
return lhs != rhs;
}
};
struct less
{
template <typename T> bool operator()(const T& lhs, const T& rhs) const
{
return lhs < rhs;
}
};
struct less_equal
{
template <typename T> bool operator()(const T& lhs, const T& rhs) const
{
return lhs <= rhs;
}
};
template <typename T> inline void swap(T& lhs, T& rhs)
{
T temp = lhs;
lhs = rhs;
rhs = temp;
}
template <typename I, typename Pred> PUGI__FN I min_element(I begin, I end, const Pred& pred)
{
I result = begin;
for (I it = begin + 1; it != end; ++it)
if (pred(*it, *result))
result = it;
return result;
}
template <typename I> PUGI__FN void reverse(I begin, I end)
{
while (end - begin > 1)
swap(*begin++, *--end);
}
template <typename I> PUGI__FN I unique(I begin, I end)
{
// fast skip head
while (end - begin > 1 && *begin != *(begin + 1))
begin++;
if (begin == end)
return begin;
// last written element
I write = begin++;
// merge unique elements
while (begin != end)
{
if (*begin != *write)
*++write = *begin++;
else
begin++;
}
// past-the-end (write points to live element)
return write + 1;
}
template <typename T, typename Pred> PUGI__FN void insertion_sort(T* begin, T* end, const Pred& pred)
{
if (begin == end)
return;
for (T* it = begin + 1; it != end; ++it)
{
T val = *it;
T* hole = it;
// move hole backwards
while (hole > begin && pred(val, *(hole - 1)))
{
*hole = *(hole - 1);
hole--;
}
// fill hole with element
*hole = val;
}
}
template <typename I, typename Pred> inline I median3(I first, I middle, I last, const Pred& pred)
{
if (pred(*middle, *first))
swap(middle, first);
if (pred(*last, *middle))
swap(last, middle);
if (pred(*middle, *first))
swap(middle, first);
return middle;
}
template <typename T, typename Pred> PUGI__FN void partition3(T* begin, T* end, T pivot, const Pred& pred, T** out_eqbeg, T** out_eqend)
{
// invariant: array is split into 4 groups: = < ? > (each variable denotes the boundary between the groups)
T* eq = begin;
T* lt = begin;
T* gt = end;
while (lt < gt)
{
if (pred(*lt, pivot))
lt++;
else if (*lt == pivot)
swap(*eq++, *lt++);
else
swap(*lt, *--gt);
}
// we now have just 4 groups: = < >; move equal elements to the middle
T* eqbeg = gt;
for (T* it = begin; it != eq; ++it)
swap(*it, *--eqbeg);
*out_eqbeg = eqbeg;
*out_eqend = gt;
}
template <typename I, typename Pred> PUGI__FN void sort(I begin, I end, const Pred& pred)
{
// sort large chunks
while (end - begin > 16)
{
// find median element
I middle = begin + (end - begin) / 2;
I median = median3(begin, middle, end - 1, pred);
// partition in three chunks (< = >)
I eqbeg, eqend;
partition3(begin, end, *median, pred, &eqbeg, &eqend);
// loop on larger half
if (eqbeg - begin > end - eqend)
{
sort(eqend, end, pred);
end = eqbeg;
}
else
{
sort(begin, eqbeg, pred);
begin = eqend;
}
}
// insertion sort small chunk
insertion_sort(begin, end, pred);
}
PUGI__FN bool hash_insert(const void** table, size_t size, const void* key)
{
assert(key);
unsigned int h = static_cast<unsigned int>(reinterpret_cast<uintptr_t>(key));
// MurmurHash3 32-bit finalizer
h ^= h >> 16;
h *= 0x85ebca6bu;
h ^= h >> 13;
h *= 0xc2b2ae35u;
h ^= h >> 16;
size_t hashmod = size - 1;
size_t bucket = h & hashmod;
for (size_t probe = 0; probe <= hashmod; ++probe)
{
if (table[bucket] == 0)
{
table[bucket] = key;
return true;
}
if (table[bucket] == key)
return false;
// hash collision, quadratic probing
bucket = (bucket + probe + 1) & hashmod;
}
assert(false && "Hash table is full"); // unreachable
return false;
}
PUGI__NS_END
// Allocator used for AST and evaluation stacks
PUGI__NS_BEGIN
static const size_t xpath_memory_page_size =
#ifdef PUGIXML_MEMORY_XPATH_PAGE_SIZE
PUGIXML_MEMORY_XPATH_PAGE_SIZE
#else
4096
#endif
;
static const uintptr_t xpath_memory_block_alignment = sizeof(double) > sizeof(void*) ? sizeof(double) : sizeof(void*);
struct xpath_memory_block
{
xpath_memory_block* next;
size_t capacity;
union
{
char data[xpath_memory_page_size];
double alignment;
};
};
struct xpath_allocator
{
xpath_memory_block* _root;
size_t _root_size;
bool* _error;
xpath_allocator(xpath_memory_block* root, bool* error = 0): _root(root), _root_size(0), _error(error)
{
}
void* allocate(size_t size)
{
// round size up to block alignment boundary
size = (size + xpath_memory_block_alignment - 1) & ~(xpath_memory_block_alignment - 1);
if (_root_size + size <= _root->capacity)
{
void* buf = &_root->data[0] + _root_size;
_root_size += size;
return buf;
}
else
{
// make sure we have at least 1/4th of the page free after allocation to satisfy subsequent allocation requests
size_t block_capacity_base = sizeof(_root->data);
size_t block_capacity_req = size + block_capacity_base / 4;
size_t block_capacity = (block_capacity_base > block_capacity_req) ? block_capacity_base : block_capacity_req;
size_t block_size = block_capacity + offsetof(xpath_memory_block, data);
xpath_memory_block* block = static_cast<xpath_memory_block*>(xml_memory::allocate(block_size));
if (!block)
{
if (_error) *_error = true;
return 0;
}
block->next = _root;
block->capacity = block_capacity;
_root = block;
_root_size = size;
return block->data;
}
}
void* reallocate(void* ptr, size_t old_size, size_t new_size)
{
// round size up to block alignment boundary
old_size = (old_size + xpath_memory_block_alignment - 1) & ~(xpath_memory_block_alignment - 1);
new_size = (new_size + xpath_memory_block_alignment - 1) & ~(xpath_memory_block_alignment - 1);
// we can only reallocate the last object
assert(ptr == 0 || static_cast<char*>(ptr) + old_size == &_root->data[0] + _root_size);
// try to reallocate the object inplace
if (ptr && _root_size - old_size + new_size <= _root->capacity)
{
_root_size = _root_size - old_size + new_size;
return ptr;
}
// allocate a new block
void* result = allocate(new_size);
if (!result) return 0;
// we have a new block
if (ptr)
{
// copy old data (we only support growing)
assert(new_size >= old_size);
memcpy(result, ptr, old_size);
// free the previous page if it had no other objects
assert(_root->data == result);
assert(_root->next);
if (_root->next->data == ptr)
{
// deallocate the whole page, unless it was the first one
xpath_memory_block* next = _root->next->next;
if (next)
{
xml_memory::deallocate(_root->next);
_root->next = next;
}
}
}
return result;
}
void revert(const xpath_allocator& state)
{
// free all new pages
xpath_memory_block* cur = _root;
while (cur != state._root)
{
xpath_memory_block* next = cur->next;
xml_memory::deallocate(cur);
cur = next;
}
// restore state
_root = state._root;
_root_size = state._root_size;
}
void release()
{
xpath_memory_block* cur = _root;
assert(cur);
while (cur->next)
{
xpath_memory_block* next = cur->next;
xml_memory::deallocate(cur);
cur = next;
}
}
};
struct xpath_allocator_capture
{
xpath_allocator_capture(xpath_allocator* alloc): _target(alloc), _state(*alloc)
{
}
~xpath_allocator_capture()
{
_target->revert(_state);
}
xpath_allocator* _target;
xpath_allocator _state;
};
struct xpath_stack
{
xpath_allocator* result;
xpath_allocator* temp;
};
struct xpath_stack_data
{
xpath_memory_block blocks[2];
xpath_allocator result;
xpath_allocator temp;
xpath_stack stack;
bool oom;
xpath_stack_data(): result(blocks + 0, &oom), temp(blocks + 1, &oom), oom(false)
{
blocks[0].next = blocks[1].next = 0;
blocks[0].capacity = blocks[1].capacity = sizeof(blocks[0].data);
stack.result = &result;
stack.temp = &temp;
}
~xpath_stack_data()
{
result.release();
temp.release();
}
};
PUGI__NS_END
// String class
PUGI__NS_BEGIN
class xpath_string
{
const char_t* _buffer;
bool _uses_heap;
size_t _length_heap;
static char_t* duplicate_string(const char_t* string, size_t length, xpath_allocator* alloc)
{
char_t* result = static_cast<char_t*>(alloc->allocate((length + 1) * sizeof(char_t)));
if (!result) return 0;
memcpy(result, string, length * sizeof(char_t));
result[length] = 0;
return result;
}
xpath_string(const char_t* buffer, bool uses_heap_, size_t length_heap): _buffer(buffer), _uses_heap(uses_heap_), _length_heap(length_heap)
{
}
public:
static xpath_string from_const(const char_t* str)
{
return xpath_string(str, false, 0);
}
static xpath_string from_heap_preallocated(const char_t* begin, const char_t* end)
{
assert(begin <= end && *end == 0);
return xpath_string(begin, true, static_cast<size_t>(end - begin));
}
static xpath_string from_heap(const char_t* begin, const char_t* end, xpath_allocator* alloc)
{
assert(begin <= end);
if (begin == end)
return xpath_string();
size_t length = static_cast<size_t>(end - begin);
const char_t* data = duplicate_string(begin, length, alloc);
return data ? xpath_string(data, true, length) : xpath_string();
}
xpath_string(): _buffer(PUGIXML_TEXT("")), _uses_heap(false), _length_heap(0)
{
}
void append(const xpath_string& o, xpath_allocator* alloc)
{
// skip empty sources
if (!*o._buffer) return;
// fast append for constant empty target and constant source
if (!*_buffer && !_uses_heap && !o._uses_heap)
{
_buffer = o._buffer;
}
else
{
// need to make heap copy
size_t target_length = length();
size_t source_length = o.length();
size_t result_length = target_length + source_length;
// allocate new buffer
char_t* result = static_cast<char_t*>(alloc->reallocate(_uses_heap ? const_cast<char_t*>(_buffer) : 0, (target_length + 1) * sizeof(char_t), (result_length + 1) * sizeof(char_t)));
if (!result) return;
// append first string to the new buffer in case there was no reallocation
if (!_uses_heap) memcpy(result, _buffer, target_length * sizeof(char_t));
// append second string to the new buffer
memcpy(result + target_length, o._buffer, source_length * sizeof(char_t));
result[result_length] = 0;
// finalize
_buffer = result;
_uses_heap = true;
_length_heap = result_length;
}
}
const char_t* c_str() const
{
return _buffer;
}
size_t length() const
{
return _uses_heap ? _length_heap : strlength(_buffer);
}
char_t* data(xpath_allocator* alloc)
{
// make private heap copy
if (!_uses_heap)
{
size_t length_ = strlength(_buffer);
const char_t* data_ = duplicate_string(_buffer, length_, alloc);
if (!data_) return 0;
_buffer = data_;
_uses_heap = true;
_length_heap = length_;
}
return const_cast<char_t*>(_buffer);
}
bool empty() const
{
return *_buffer == 0;
}
bool operator==(const xpath_string& o) const
{
return strequal(_buffer, o._buffer);
}
bool operator!=(const xpath_string& o) const
{
return !strequal(_buffer, o._buffer);
}
bool uses_heap() const
{
return _uses_heap;
}
};
PUGI__NS_END
PUGI__NS_BEGIN
PUGI__FN bool starts_with(const char_t* string, const char_t* pattern)
{
while (*pattern && *string == *pattern)
{
string++;
pattern++;
}
return *pattern == 0;
}
PUGI__FN const char_t* find_char(const char_t* s, char_t c)
{
#ifdef PUGIXML_WCHAR_MODE
return wcschr(s, c);
#else
return strchr(s, c);
#endif
}
PUGI__FN const char_t* find_substring(const char_t* s, const char_t* p)
{
#ifdef PUGIXML_WCHAR_MODE
// MSVC6 wcsstr bug workaround (if s is empty it always returns 0)
return (*p == 0) ? s : wcsstr(s, p);
#else
return strstr(s, p);
#endif
}
// Converts symbol to lower case, if it is an ASCII one
PUGI__FN char_t tolower_ascii(char_t ch)
{
return static_cast<unsigned int>(ch - 'A') < 26 ? static_cast<char_t>(ch | ' ') : ch;
}
PUGI__FN xpath_string string_value(const xpath_node& na, xpath_allocator* alloc)
{
if (na.attribute())
return xpath_string::from_const(na.attribute().value());
else
{
xml_node n = na.node();
switch (n.type())
{
case node_pcdata:
case node_cdata:
case node_comment:
case node_pi:
return xpath_string::from_const(n.value());
case node_document:
case node_element:
{
xpath_string result;
// element nodes can have value if parse_embed_pcdata was used
if (n.value()[0])
result.append(xpath_string::from_const(n.value()), alloc);
xml_node cur = n.first_child();
while (cur && cur != n)
{
if (cur.type() == node_pcdata || cur.type() == node_cdata)
result.append(xpath_string::from_const(cur.value()), alloc);
if (cur.first_child())
cur = cur.first_child();
else if (cur.next_sibling())
cur = cur.next_sibling();
else
{
while (!cur.next_sibling() && cur != n)
cur = cur.parent();
if (cur != n) cur = cur.next_sibling();
}
}
return result;
}
default:
return xpath_string();
}
}
}
PUGI__FN bool node_is_before_sibling(xml_node_struct* ln, xml_node_struct* rn)
{
assert(ln->parent == rn->parent);
// there is no common ancestor (the shared parent is null), nodes are from different documents
if (!ln->parent) return ln < rn;
// determine sibling order
xml_node_struct* ls = ln;
xml_node_struct* rs = rn;
while (ls && rs)
{
if (ls == rn) return true;
if (rs == ln) return false;
ls = ls->next_sibling;
rs = rs->next_sibling;
}
// if rn sibling chain ended ln must be before rn
return !rs;
}
PUGI__FN bool node_is_before(xml_node_struct* ln, xml_node_struct* rn)
{
// find common ancestor at the same depth, if any
xml_node_struct* lp = ln;
xml_node_struct* rp = rn;
while (lp && rp && lp->parent != rp->parent)
{
lp = lp->parent;
rp = rp->parent;
}
// parents are the same!
if (lp && rp) return node_is_before_sibling(lp, rp);
// nodes are at different depths, need to normalize heights
bool left_higher = !lp;
while (lp)
{
lp = lp->parent;
ln = ln->parent;
}
while (rp)
{
rp = rp->parent;
rn = rn->parent;
}
// one node is the ancestor of the other
if (ln == rn) return left_higher;
// find common ancestor... again
while (ln->parent != rn->parent)
{
ln = ln->parent;
rn = rn->parent;
}
return node_is_before_sibling(ln, rn);
}
PUGI__FN bool node_is_ancestor(xml_node_struct* parent, xml_node_struct* node)
{
while (node && node != parent) node = node->parent;
return parent && node == parent;
}
PUGI__FN const void* document_buffer_order(const xpath_node& xnode)
{
xml_node_struct* node = xnode.node().internal_object();
if (node)
{
if ((get_document(node).header & xml_memory_page_contents_shared_mask) == 0)
{
if (node->name && (node->header & impl::xml_memory_page_name_allocated_or_shared_mask) == 0) return node->name;
if (node->value && (node->header & impl::xml_memory_page_value_allocated_or_shared_mask) == 0) return node->value;
}
return 0;
}
xml_attribute_struct* attr = xnode.attribute().internal_object();
if (attr)
{
if ((get_document(attr).header & xml_memory_page_contents_shared_mask) == 0)
{
if ((attr->header & impl::xml_memory_page_name_allocated_or_shared_mask) == 0) return attr->name;
if ((attr->header & impl::xml_memory_page_value_allocated_or_shared_mask) == 0) return attr->value;
}
return 0;
}
return 0;
}
struct document_order_comparator
{
bool operator()(const xpath_node& lhs, const xpath_node& rhs) const
{
// optimized document order based check
const void* lo = document_buffer_order(lhs);
const void* ro = document_buffer_order(rhs);
if (lo && ro) return lo < ro;
// slow comparison
xml_node ln = lhs.node(), rn = rhs.node();
// compare attributes
if (lhs.attribute() && rhs.attribute())
{
// shared parent
if (lhs.parent() == rhs.parent())
{
// determine sibling order
for (xml_attribute a = lhs.attribute(); a; a = a.next_attribute())
if (a == rhs.attribute())
return true;
return false;
}
// compare attribute parents
ln = lhs.parent();
rn = rhs.parent();
}
else if (lhs.attribute())
{
// attributes go after the parent element
if (lhs.parent() == rhs.node()) return false;
ln = lhs.parent();
}
else if (rhs.attribute())
{
// attributes go after the parent element
if (rhs.parent() == lhs.node()) return true;
rn = rhs.parent();
}
if (ln == rn) return false;
if (!ln || !rn) return ln < rn;
return node_is_before(ln.internal_object(), rn.internal_object());
}
};
PUGI__FN double gen_nan()
{
#if defined(__STDC_IEC_559__) || ((FLT_RADIX - 0 == 2) && (FLT_MAX_EXP - 0 == 128) && (FLT_MANT_DIG - 0 == 24))
PUGI__STATIC_ASSERT(sizeof(float) == sizeof(uint32_t));
typedef uint32_t UI; // BCC5 workaround
union { float f; UI i; } u;
u.i = 0x7fc00000;
return double(u.f);
#else
// fallback
const volatile double zero = 0.0;
return zero / zero;
#endif
}
PUGI__FN bool is_nan(double value)
{
#if defined(PUGI__MSVC_CRT_VERSION) || defined(__BORLANDC__)
return !!_isnan(value);
#elif defined(fpclassify) && defined(FP_NAN)
return fpclassify(value) == FP_NAN;
#else
// fallback
const volatile double v = value;
return v != v;
#endif
}
PUGI__FN const char_t* convert_number_to_string_special(double value)
{
#if defined(PUGI__MSVC_CRT_VERSION) || defined(__BORLANDC__)
if (_finite(value)) return (value == 0) ? PUGIXML_TEXT("0") : 0;
if (_isnan(value)) return PUGIXML_TEXT("NaN");
return value > 0 ? PUGIXML_TEXT("Infinity") : PUGIXML_TEXT("-Infinity");
#elif defined(fpclassify) && defined(FP_NAN) && defined(FP_INFINITE) && defined(FP_ZERO)
switch (fpclassify(value))
{
case FP_NAN:
return PUGIXML_TEXT("NaN");
case FP_INFINITE:
return value > 0 ? PUGIXML_TEXT("Infinity") : PUGIXML_TEXT("-Infinity");
case FP_ZERO:
return PUGIXML_TEXT("0");
default:
return 0;
}
#else
// fallback
const volatile double v = value;
if (v == 0) return PUGIXML_TEXT("0");
if (v != v) return PUGIXML_TEXT("NaN");
if (v * 2 == v) return value > 0 ? PUGIXML_TEXT("Infinity") : PUGIXML_TEXT("-Infinity");
return 0;
#endif
}
PUGI__FN bool convert_number_to_boolean(double value)
{
return (value != 0 && !is_nan(value));
}
PUGI__FN void truncate_zeros(char* begin, char* end)
{
while (begin != end && end[-1] == '0') end--;
*end = 0;
}
// gets mantissa digits in the form of 0.xxxxx with 0. implied and the exponent
#if defined(PUGI__MSVC_CRT_VERSION) && PUGI__MSVC_CRT_VERSION >= 1400 && !defined(_WIN32_WCE)
PUGI__FN void convert_number_to_mantissa_exponent(double value, char (&buffer)[32], char** out_mantissa, int* out_exponent)
{
// get base values
int sign, exponent;
_ecvt_s(buffer, sizeof(buffer), value, DBL_DIG + 1, &exponent, &sign);
// truncate redundant zeros
truncate_zeros(buffer, buffer + strlen(buffer));
// fill results
*out_mantissa = buffer;
*out_exponent = exponent;
}
#else
PUGI__FN void convert_number_to_mantissa_exponent(double value, char (&buffer)[32], char** out_mantissa, int* out_exponent)
{
// get a scientific notation value with IEEE DBL_DIG decimals
PUGI__SNPRINTF(buffer, "%.*e", DBL_DIG, value);
// get the exponent (possibly negative)
char* exponent_string = strchr(buffer, 'e');
assert(exponent_string);
int exponent = atoi(exponent_string + 1);
// extract mantissa string: skip sign
char* mantissa = buffer[0] == '-' ? buffer + 1 : buffer;
assert(mantissa[0] != '0' && mantissa[1] == '.');
// divide mantissa by 10 to eliminate integer part
mantissa[1] = mantissa[0];
mantissa++;
exponent++;
// remove extra mantissa digits and zero-terminate mantissa
truncate_zeros(mantissa, exponent_string);
// fill results
*out_mantissa = mantissa;
*out_exponent = exponent;
}
#endif
PUGI__FN xpath_string convert_number_to_string(double value, xpath_allocator* alloc)
{
// try special number conversion
const char_t* special = convert_number_to_string_special(value);
if (special) return xpath_string::from_const(special);
// get mantissa + exponent form
char mantissa_buffer[32];
char* mantissa;
int exponent;
convert_number_to_mantissa_exponent(value, mantissa_buffer, &mantissa, &exponent);
// allocate a buffer of suitable length for the number
size_t result_size = strlen(mantissa_buffer) + (exponent > 0 ? exponent : -exponent) + 4;
char_t* result = static_cast<char_t*>(alloc->allocate(sizeof(char_t) * result_size));
if (!result) return xpath_string();
// make the number!
char_t* s = result;
// sign
if (value < 0) *s++ = '-';
// integer part
if (exponent <= 0)
{
*s++ = '0';
}
else
{
while (exponent > 0)
{
assert(*mantissa == 0 || static_cast<unsigned int>(*mantissa - '0') <= 9);
*s++ = *mantissa ? *mantissa++ : '0';
exponent--;
}
}
// fractional part
if (*mantissa)
{
// decimal point
*s++ = '.';
// extra zeroes from negative exponent
while (exponent < 0)
{
*s++ = '0';
exponent++;
}
// extra mantissa digits
while (*mantissa)
{
assert(static_cast<unsigned int>(*mantissa - '0') <= 9);
*s++ = *mantissa++;
}
}
// zero-terminate
assert(s < result + result_size);
*s = 0;
return xpath_string::from_heap_preallocated(result, s);
}
PUGI__FN bool check_string_to_number_format(const char_t* string)
{
// parse leading whitespace
while (PUGI__IS_CHARTYPE(*string, ct_space)) ++string;
// parse sign
if (*string == '-') ++string;
if (!*string) return false;
// if there is no integer part, there should be a decimal part with at least one digit
if (!PUGI__IS_CHARTYPEX(string[0], ctx_digit) && (string[0] != '.' || !PUGI__IS_CHARTYPEX(string[1], ctx_digit))) return false;
// parse integer part
while (PUGI__IS_CHARTYPEX(*string, ctx_digit)) ++string;
// parse decimal part
if (*string == '.')
{
++string;
while (PUGI__IS_CHARTYPEX(*string, ctx_digit)) ++string;
}
// parse trailing whitespace
while (PUGI__IS_CHARTYPE(*string, ct_space)) ++string;
return *string == 0;
}
PUGI__FN double convert_string_to_number(const char_t* string)
{
// check string format
if (!check_string_to_number_format(string)) return gen_nan();
// parse string
#ifdef PUGIXML_WCHAR_MODE
return wcstod(string, 0);
#else
return strtod(string, 0);
#endif
}
PUGI__FN bool convert_string_to_number_scratch(char_t (&buffer)[32], const char_t* begin, const char_t* end, double* out_result)
{
size_t length = static_cast<size_t>(end - begin);
char_t* scratch = buffer;
if (length >= sizeof(buffer) / sizeof(buffer[0]))
{
// need to make dummy on-heap copy
scratch = static_cast<char_t*>(xml_memory::allocate((length + 1) * sizeof(char_t)));
if (!scratch) return false;
}
// copy string to zero-terminated buffer and perform conversion
memcpy(scratch, begin, length * sizeof(char_t));
scratch[length] = 0;
*out_result = convert_string_to_number(scratch);
// free dummy buffer
if (scratch != buffer) xml_memory::deallocate(scratch);
return true;
}
PUGI__FN double round_nearest(double value)
{
return floor(value + 0.5);
}
PUGI__FN double round_nearest_nzero(double value)
{
// same as round_nearest, but returns -0 for [-0.5, -0]
// ceil is used to differentiate between +0 and -0 (we return -0 for [-0.5, -0] and +0 for +0)
return (value >= -0.5 && value <= 0) ? ceil(value) : floor(value + 0.5);
}
PUGI__FN const char_t* qualified_name(const xpath_node& node)
{
return node.attribute() ? node.attribute().name() : node.node().name();
}
PUGI__FN const char_t* local_name(const xpath_node& node)
{
const char_t* name = qualified_name(node);
const char_t* p = find_char(name, ':');
return p ? p + 1 : name;
}
struct namespace_uri_predicate
{
const char_t* prefix;
size_t prefix_length;
namespace_uri_predicate(const char_t* name)
{
const char_t* pos = find_char(name, ':');
prefix = pos ? name : 0;
prefix_length = pos ? static_cast<size_t>(pos - name) : 0;
}
bool operator()(xml_attribute a) const
{
const char_t* name = a.name();
if (!starts_with(name, PUGIXML_TEXT("xmlns"))) return false;
return prefix ? name[5] == ':' && strequalrange(name + 6, prefix, prefix_length) : name[5] == 0;
}
};
PUGI__FN const char_t* namespace_uri(xml_node node)
{
namespace_uri_predicate pred = node.name();
xml_node p = node;
while (p)
{
xml_attribute a = p.find_attribute(pred);
if (a) return a.value();
p = p.parent();
}
return PUGIXML_TEXT("");
}
PUGI__FN const char_t* namespace_uri(xml_attribute attr, xml_node parent)
{
namespace_uri_predicate pred = attr.name();
// Default namespace does not apply to attributes
if (!pred.prefix) return PUGIXML_TEXT("");
xml_node p = parent;
while (p)
{
xml_attribute a = p.find_attribute(pred);
if (a) return a.value();
p = p.parent();
}
return PUGIXML_TEXT("");
}
PUGI__FN const char_t* namespace_uri(const xpath_node& node)
{
return node.attribute() ? namespace_uri(node.attribute(), node.parent()) : namespace_uri(node.node());
}
PUGI__FN char_t* normalize_space(char_t* buffer)
{
char_t* write = buffer;
for (char_t* it = buffer; *it; )
{
char_t ch = *it++;
if (PUGI__IS_CHARTYPE(ch, ct_space))
{
// replace whitespace sequence with single space
while (PUGI__IS_CHARTYPE(*it, ct_space)) it++;
// avoid leading spaces
if (write != buffer) *write++ = ' ';
}
else *write++ = ch;
}
// remove trailing space
if (write != buffer && PUGI__IS_CHARTYPE(write[-1], ct_space)) write--;
// zero-terminate
*write = 0;
return write;
}
PUGI__FN char_t* translate(char_t* buffer, const char_t* from, const char_t* to, size_t to_length)
{
char_t* write = buffer;
while (*buffer)
{
PUGI__DMC_VOLATILE char_t ch = *buffer++;
const char_t* pos = find_char(from, ch);
if (!pos)
*write++ = ch; // do not process
else if (static_cast<size_t>(pos - from) < to_length)
*write++ = to[pos - from]; // replace
}
// zero-terminate
*write = 0;
return write;
}
PUGI__FN unsigned char* translate_table_generate(xpath_allocator* alloc, const char_t* from, const char_t* to)
{
unsigned char table[128] = {0};
while (*from)
{
unsigned int fc = static_cast<unsigned int>(*from);
unsigned int tc = static_cast<unsigned int>(*to);
if (fc >= 128 || tc >= 128)
return 0;
// code=128 means "skip character"
if (!table[fc])
table[fc] = static_cast<unsigned char>(tc ? tc : 128);
from++;
if (tc) to++;
}
for (int i = 0; i < 128; ++i)
if (!table[i])
table[i] = static_cast<unsigned char>(i);
void* result = alloc->allocate(sizeof(table));
if (!result) return 0;
memcpy(result, table, sizeof(table));
return static_cast<unsigned char*>(result);
}
PUGI__FN char_t* translate_table(char_t* buffer, const unsigned char* table)
{
char_t* write = buffer;
while (*buffer)
{
char_t ch = *buffer++;
unsigned int index = static_cast<unsigned int>(ch);
if (index < 128)
{
unsigned char code = table[index];
// code=128 means "skip character" (table size is 128 so 128 can be a special value)
// this code skips these characters without extra branches
*write = static_cast<char_t>(code);
write += 1 - (code >> 7);
}
else
{
*write++ = ch;
}
}
// zero-terminate
*write = 0;
return write;
}
inline bool is_xpath_attribute(const char_t* name)
{
return !(starts_with(name, PUGIXML_TEXT("xmlns")) && (name[5] == 0 || name[5] == ':'));
}
struct xpath_variable_boolean: xpath_variable
{
xpath_variable_boolean(): xpath_variable(xpath_type_boolean), value(false)
{
}
bool value;
char_t name[1];
};
struct xpath_variable_number: xpath_variable
{
xpath_variable_number(): xpath_variable(xpath_type_number), value(0)
{
}
double value;
char_t name[1];
};
struct xpath_variable_string: xpath_variable
{
xpath_variable_string(): xpath_variable(xpath_type_string), value(0)
{
}
~xpath_variable_string()
{
if (value) xml_memory::deallocate(value);
}
char_t* value;
char_t name[1];
};
struct xpath_variable_node_set: xpath_variable
{
xpath_variable_node_set(): xpath_variable(xpath_type_node_set)
{
}
xpath_node_set value;
char_t name[1];
};
static const xpath_node_set dummy_node_set;
PUGI__FN PUGI__UNSIGNED_OVERFLOW unsigned int hash_string(const char_t* str)
{
// Jenkins one-at-a-time hash (http://en.wikipedia.org/wiki/Jenkins_hash_function#one-at-a-time)
unsigned int result = 0;
while (*str)
{
result += static_cast<unsigned int>(*str++);
result += result << 10;
result ^= result >> 6;
}
result += result << 3;
result ^= result >> 11;
result += result << 15;
return result;
}
template <typename T> PUGI__FN T* new_xpath_variable(const char_t* name)
{
size_t length = strlength(name);
if (length == 0) return 0; // empty variable names are invalid
// $$ we can't use offsetof(T, name) because T is non-POD, so we just allocate additional length characters
void* memory = xml_memory::allocate(sizeof(T) + length * sizeof(char_t));
if (!memory) return 0;
T* result = new (memory) T();
memcpy(result->name, name, (length + 1) * sizeof(char_t));
return result;
}
PUGI__FN xpath_variable* new_xpath_variable(xpath_value_type type, const char_t* name)
{
switch (type)
{
case xpath_type_node_set:
return new_xpath_variable<xpath_variable_node_set>(name);
case xpath_type_number:
return new_xpath_variable<xpath_variable_number>(name);
case xpath_type_string:
return new_xpath_variable<xpath_variable_string>(name);
case xpath_type_boolean:
return new_xpath_variable<xpath_variable_boolean>(name);
default:
return 0;
}
}
template <typename T> PUGI__FN void delete_xpath_variable(T* var)
{
var->~T();
xml_memory::deallocate(var);
}
PUGI__FN void delete_xpath_variable(xpath_value_type type, xpath_variable* var)
{
switch (type)
{
case xpath_type_node_set:
delete_xpath_variable(static_cast<xpath_variable_node_set*>(var));
break;
case xpath_type_number:
delete_xpath_variable(static_cast<xpath_variable_number*>(var));
break;
case xpath_type_string:
delete_xpath_variable(static_cast<xpath_variable_string*>(var));
break;
case xpath_type_boolean:
delete_xpath_variable(static_cast<xpath_variable_boolean*>(var));
break;
default:
assert(false && "Invalid variable type"); // unreachable
}
}
PUGI__FN bool copy_xpath_variable(xpath_variable* lhs, const xpath_variable* rhs)
{
switch (rhs->type())
{
case xpath_type_node_set:
return lhs->set(static_cast<const xpath_variable_node_set*>(rhs)->value);
case xpath_type_number:
return lhs->set(static_cast<const xpath_variable_number*>(rhs)->value);
case xpath_type_string:
return lhs->set(static_cast<const xpath_variable_string*>(rhs)->value);
case xpath_type_boolean:
return lhs->set(static_cast<const xpath_variable_boolean*>(rhs)->value);
default:
assert(false && "Invalid variable type"); // unreachable
return false;
}
}
PUGI__FN bool get_variable_scratch(char_t (&buffer)[32], xpath_variable_set* set, const char_t* begin, const char_t* end, xpath_variable** out_result)
{
size_t length = static_cast<size_t>(end - begin);
char_t* scratch = buffer;
if (length >= sizeof(buffer) / sizeof(buffer[0]))
{
// need to make dummy on-heap copy
scratch = static_cast<char_t*>(xml_memory::allocate((length + 1) * sizeof(char_t)));
if (!scratch) return false;
}
// copy string to zero-terminated buffer and perform lookup
memcpy(scratch, begin, length * sizeof(char_t));
scratch[length] = 0;
*out_result = set->get(scratch);
// free dummy buffer
if (scratch != buffer) xml_memory::deallocate(scratch);
return true;
}
PUGI__NS_END
// Internal node set class
PUGI__NS_BEGIN
PUGI__FN xpath_node_set::type_t xpath_get_order(const xpath_node* begin, const xpath_node* end)
{
if (end - begin < 2)
return xpath_node_set::type_sorted;
document_order_comparator cmp;
bool first = cmp(begin[0], begin[1]);
for (const xpath_node* it = begin + 1; it + 1 < end; ++it)
if (cmp(it[0], it[1]) != first)
return xpath_node_set::type_unsorted;
return first ? xpath_node_set::type_sorted : xpath_node_set::type_sorted_reverse;
}
PUGI__FN xpath_node_set::type_t xpath_sort(xpath_node* begin, xpath_node* end, xpath_node_set::type_t type, bool rev)
{
xpath_node_set::type_t order = rev ? xpath_node_set::type_sorted_reverse : xpath_node_set::type_sorted;
if (type == xpath_node_set::type_unsorted)
{
xpath_node_set::type_t sorted = xpath_get_order(begin, end);
if (sorted == xpath_node_set::type_unsorted)
{
sort(begin, end, document_order_comparator());
type = xpath_node_set::type_sorted;
}
else
type = sorted;
}
if (type != order) reverse(begin, end);
return order;
}
PUGI__FN xpath_node xpath_first(const xpath_node* begin, const xpath_node* end, xpath_node_set::type_t type)
{
if (begin == end) return xpath_node();
switch (type)
{
case xpath_node_set::type_sorted:
return *begin;
case xpath_node_set::type_sorted_reverse:
return *(end - 1);
case xpath_node_set::type_unsorted:
return *min_element(begin, end, document_order_comparator());
default:
assert(false && "Invalid node set type"); // unreachable
return xpath_node();
}
}
class xpath_node_set_raw
{
xpath_node_set::type_t _type;
xpath_node* _begin;
xpath_node* _end;
xpath_node* _eos;
public:
xpath_node_set_raw(): _type(xpath_node_set::type_unsorted), _begin(0), _end(0), _eos(0)
{
}
xpath_node* begin() const
{
return _begin;
}
xpath_node* end() const
{
return _end;
}
bool empty() const
{
return _begin == _end;
}
size_t size() const
{
return static_cast<size_t>(_end - _begin);
}
xpath_node first() const
{
return xpath_first(_begin, _end, _type);
}
void push_back_grow(const xpath_node& node, xpath_allocator* alloc);
void push_back(const xpath_node& node, xpath_allocator* alloc)
{
if (_end != _eos)
*_end++ = node;
else
push_back_grow(node, alloc);
}
void append(const xpath_node* begin_, const xpath_node* end_, xpath_allocator* alloc)
{
if (begin_ == end_) return;
size_t size_ = static_cast<size_t>(_end - _begin);
size_t capacity = static_cast<size_t>(_eos - _begin);
size_t count = static_cast<size_t>(end_ - begin_);
if (size_ + count > capacity)
{
// reallocate the old array or allocate a new one
xpath_node* data = static_cast<xpath_node*>(alloc->reallocate(_begin, capacity * sizeof(xpath_node), (size_ + count) * sizeof(xpath_node)));
if (!data) return;
// finalize
_begin = data;
_end = data + size_;
_eos = data + size_ + count;
}
memcpy(_end, begin_, count * sizeof(xpath_node));
_end += count;
}
void sort_do()
{
_type = xpath_sort(_begin, _end, _type, false);
}
void truncate(xpath_node* pos)
{
assert(_begin <= pos && pos <= _end);
_end = pos;
}
void remove_duplicates(xpath_allocator* alloc)
{
if (_type == xpath_node_set::type_unsorted && _end - _begin > 2)
{
xpath_allocator_capture cr(alloc);
size_t size_ = static_cast<size_t>(_end - _begin);
size_t hash_size = 1;
while (hash_size < size_ + size_ / 2) hash_size *= 2;
const void** hash_data = static_cast<const void**>(alloc->allocate(hash_size * sizeof(void**)));
if (!hash_data) return;
memset(hash_data, 0, hash_size * sizeof(const void**));
xpath_node* write = _begin;
for (xpath_node* it = _begin; it != _end; ++it)
{
const void* attr = it->attribute().internal_object();
const void* node = it->node().internal_object();
const void* key = attr ? attr : node;
if (key && hash_insert(hash_data, hash_size, key))
{
*write++ = *it;
}
}
_end = write;
}
else
{
_end = unique(_begin, _end);
}
}
xpath_node_set::type_t type() const
{
return _type;
}
void set_type(xpath_node_set::type_t value)
{
_type = value;
}
};
PUGI__FN_NO_INLINE void xpath_node_set_raw::push_back_grow(const xpath_node& node, xpath_allocator* alloc)
{
size_t capacity = static_cast<size_t>(_eos - _begin);
// get new capacity (1.5x rule)
size_t new_capacity = capacity + capacity / 2 + 1;
// reallocate the old array or allocate a new one
xpath_node* data = static_cast<xpath_node*>(alloc->reallocate(_begin, capacity * sizeof(xpath_node), new_capacity * sizeof(xpath_node)));
if (!data) return;
// finalize
_begin = data;
_end = data + capacity;
_eos = data + new_capacity;
// push
*_end++ = node;
}
PUGI__NS_END
PUGI__NS_BEGIN
struct xpath_context
{
xpath_node n;
size_t position, size;
xpath_context(const xpath_node& n_, size_t position_, size_t size_): n(n_), position(position_), size(size_)
{
}
};
enum lexeme_t
{
lex_none = 0,
lex_equal,
lex_not_equal,
lex_less,
lex_greater,
lex_less_or_equal,
lex_greater_or_equal,
lex_plus,
lex_minus,
lex_multiply,
lex_union,
lex_var_ref,
lex_open_brace,
lex_close_brace,
lex_quoted_string,
lex_number,
lex_slash,
lex_double_slash,
lex_open_square_brace,
lex_close_square_brace,
lex_string,
lex_comma,
lex_axis_attribute,
lex_dot,
lex_double_dot,
lex_double_colon,
lex_eof
};
struct xpath_lexer_string
{
const char_t* begin;
const char_t* end;
xpath_lexer_string(): begin(0), end(0)
{
}
bool operator==(const char_t* other) const
{
size_t length = static_cast<size_t>(end - begin);
return strequalrange(other, begin, length);
}
};
class xpath_lexer
{
const char_t* _cur;
const char_t* _cur_lexeme_pos;
xpath_lexer_string _cur_lexeme_contents;
lexeme_t _cur_lexeme;
public:
explicit xpath_lexer(const char_t* query): _cur(query)
{
next();
}
const char_t* state() const
{
return _cur;
}
void next()
{
const char_t* cur = _cur;
while (PUGI__IS_CHARTYPE(*cur, ct_space)) ++cur;
// save lexeme position for error reporting
_cur_lexeme_pos = cur;
switch (*cur)
{
case 0:
_cur_lexeme = lex_eof;
break;
case '>':
if (*(cur+1) == '=')
{
cur += 2;
_cur_lexeme = lex_greater_or_equal;
}
else
{
cur += 1;
_cur_lexeme = lex_greater;
}
break;
case '<':
if (*(cur+1) == '=')
{
cur += 2;
_cur_lexeme = lex_less_or_equal;
}
else
{
cur += 1;
_cur_lexeme = lex_less;
}
break;
case '!':
if (*(cur+1) == '=')
{
cur += 2;
_cur_lexeme = lex_not_equal;
}
else
{
_cur_lexeme = lex_none;
}
break;
case '=':
cur += 1;
_cur_lexeme = lex_equal;
break;
case '+':
cur += 1;
_cur_lexeme = lex_plus;
break;
case '-':
cur += 1;
_cur_lexeme = lex_minus;
break;
case '*':
cur += 1;
_cur_lexeme = lex_multiply;
break;
case '|':
cur += 1;
_cur_lexeme = lex_union;
break;
case '$':
cur += 1;
if (PUGI__IS_CHARTYPEX(*cur, ctx_start_symbol))
{
_cur_lexeme_contents.begin = cur;
while (PUGI__IS_CHARTYPEX(*cur, ctx_symbol)) cur++;
if (cur[0] == ':' && PUGI__IS_CHARTYPEX(cur[1], ctx_symbol)) // qname
{
cur++; // :
while (PUGI__IS_CHARTYPEX(*cur, ctx_symbol)) cur++;
}
_cur_lexeme_contents.end = cur;
_cur_lexeme = lex_var_ref;
}
else
{
_cur_lexeme = lex_none;
}
break;
case '(':
cur += 1;
_cur_lexeme = lex_open_brace;
break;
case ')':
cur += 1;
_cur_lexeme = lex_close_brace;
break;
case '[':
cur += 1;
_cur_lexeme = lex_open_square_brace;
break;
case ']':
cur += 1;
_cur_lexeme = lex_close_square_brace;
break;
case ',':
cur += 1;
_cur_lexeme = lex_comma;
break;
case '/':
if (*(cur+1) == '/')
{
cur += 2;
_cur_lexeme = lex_double_slash;
}
else
{
cur += 1;
_cur_lexeme = lex_slash;
}
break;
case '.':
if (*(cur+1) == '.')
{
cur += 2;
_cur_lexeme = lex_double_dot;
}
else if (PUGI__IS_CHARTYPEX(*(cur+1), ctx_digit))
{
_cur_lexeme_contents.begin = cur; // .
++cur;
while (PUGI__IS_CHARTYPEX(*cur, ctx_digit)) cur++;
_cur_lexeme_contents.end = cur;
_cur_lexeme = lex_number;
}
else
{
cur += 1;
_cur_lexeme = lex_dot;
}
break;
case '@':
cur += 1;
_cur_lexeme = lex_axis_attribute;
break;
case '"':
case '\'':
{
char_t terminator = *cur;
++cur;
_cur_lexeme_contents.begin = cur;
while (*cur && *cur != terminator) cur++;
_cur_lexeme_contents.end = cur;
if (!*cur)
_cur_lexeme = lex_none;
else
{
cur += 1;
_cur_lexeme = lex_quoted_string;
}
break;
}
case ':':
if (*(cur+1) == ':')
{
cur += 2;
_cur_lexeme = lex_double_colon;
}
else
{
_cur_lexeme = lex_none;
}
break;
default:
if (PUGI__IS_CHARTYPEX(*cur, ctx_digit))
{
_cur_lexeme_contents.begin = cur;
while (PUGI__IS_CHARTYPEX(*cur, ctx_digit)) cur++;
if (*cur == '.')
{
cur++;
while (PUGI__IS_CHARTYPEX(*cur, ctx_digit)) cur++;
}
_cur_lexeme_contents.end = cur;
_cur_lexeme = lex_number;
}
else if (PUGI__IS_CHARTYPEX(*cur, ctx_start_symbol))
{
_cur_lexeme_contents.begin = cur;
while (PUGI__IS_CHARTYPEX(*cur, ctx_symbol)) cur++;
if (cur[0] == ':')
{
if (cur[1] == '*') // namespace test ncname:*
{
cur += 2; // :*
}
else if (PUGI__IS_CHARTYPEX(cur[1], ctx_symbol)) // namespace test qname
{
cur++; // :
while (PUGI__IS_CHARTYPEX(*cur, ctx_symbol)) cur++;
}
}
_cur_lexeme_contents.end = cur;
_cur_lexeme = lex_string;
}
else
{
_cur_lexeme = lex_none;
}
}
_cur = cur;
}
lexeme_t current() const
{
return _cur_lexeme;
}
const char_t* current_pos() const
{
return _cur_lexeme_pos;
}
const xpath_lexer_string& contents() const
{
assert(_cur_lexeme == lex_var_ref || _cur_lexeme == lex_number || _cur_lexeme == lex_string || _cur_lexeme == lex_quoted_string);
return _cur_lexeme_contents;
}
};
enum ast_type_t
{
ast_unknown,
ast_op_or, // left or right
ast_op_and, // left and right
ast_op_equal, // left = right
ast_op_not_equal, // left != right
ast_op_less, // left < right
ast_op_greater, // left > right
ast_op_less_or_equal, // left <= right
ast_op_greater_or_equal, // left >= right
ast_op_add, // left + right
ast_op_subtract, // left - right
ast_op_multiply, // left * right
ast_op_divide, // left / right
ast_op_mod, // left % right
ast_op_negate, // left - right
ast_op_union, // left | right
ast_predicate, // apply predicate to set; next points to next predicate
ast_filter, // select * from left where right
ast_string_constant, // string constant
ast_number_constant, // number constant
ast_variable, // variable
ast_func_last, // last()
ast_func_position, // position()
ast_func_count, // count(left)
ast_func_id, // id(left)
ast_func_local_name_0, // local-name()
ast_func_local_name_1, // local-name(left)
ast_func_namespace_uri_0, // namespace-uri()
ast_func_namespace_uri_1, // namespace-uri(left)
ast_func_name_0, // name()
ast_func_name_1, // name(left)
ast_func_string_0, // string()
ast_func_string_1, // string(left)
ast_func_concat, // concat(left, right, siblings)
ast_func_starts_with, // starts_with(left, right)
ast_func_contains, // contains(left, right)
ast_func_substring_before, // substring-before(left, right)
ast_func_substring_after, // substring-after(left, right)
ast_func_substring_2, // substring(left, right)
ast_func_substring_3, // substring(left, right, third)
ast_func_string_length_0, // string-length()
ast_func_string_length_1, // string-length(left)
ast_func_normalize_space_0, // normalize-space()
ast_func_normalize_space_1, // normalize-space(left)
ast_func_translate, // translate(left, right, third)
ast_func_boolean, // boolean(left)
ast_func_not, // not(left)
ast_func_true, // true()
ast_func_false, // false()
ast_func_lang, // lang(left)
ast_func_number_0, // number()
ast_func_number_1, // number(left)
ast_func_sum, // sum(left)
ast_func_floor, // floor(left)
ast_func_ceiling, // ceiling(left)
ast_func_round, // round(left)
ast_step, // process set left with step
ast_step_root, // select root node
ast_opt_translate_table, // translate(left, right, third) where right/third are constants
ast_opt_compare_attribute // @name = 'string'
};
enum axis_t
{
axis_ancestor,
axis_ancestor_or_self,
axis_attribute,
axis_child,
axis_descendant,
axis_descendant_or_self,
axis_following,
axis_following_sibling,
axis_namespace,
axis_parent,
axis_preceding,
axis_preceding_sibling,
axis_self
};
enum nodetest_t
{
nodetest_none,
nodetest_name,
nodetest_type_node,
nodetest_type_comment,
nodetest_type_pi,
nodetest_type_text,
nodetest_pi,
nodetest_all,
nodetest_all_in_namespace
};
enum predicate_t
{
predicate_default,
predicate_posinv,
predicate_constant,
predicate_constant_one
};
enum nodeset_eval_t
{
nodeset_eval_all,
nodeset_eval_any,
nodeset_eval_first
};
template <axis_t N> struct axis_to_type
{
static const axis_t axis;
};
template <axis_t N> const axis_t axis_to_type<N>::axis = N;
class xpath_ast_node
{
private:
// node type
char _type;
char _rettype;
// for ast_step
char _axis;
// for ast_step/ast_predicate/ast_filter
char _test;
// tree node structure
xpath_ast_node* _left;
xpath_ast_node* _right;
xpath_ast_node* _next;
union
{
// value for ast_string_constant
const char_t* string;
// value for ast_number_constant
double number;
// variable for ast_variable
xpath_variable* variable;
// node test for ast_step (node name/namespace/node type/pi target)
const char_t* nodetest;
// table for ast_opt_translate_table
const unsigned char* table;
} _data;
xpath_ast_node(const xpath_ast_node&);
xpath_ast_node& operator=(const xpath_ast_node&);
template <class Comp> static bool compare_eq(xpath_ast_node* lhs, xpath_ast_node* rhs, const xpath_context& c, const xpath_stack& stack, const Comp& comp)
{
xpath_value_type lt = lhs->rettype(), rt = rhs->rettype();
if (lt != xpath_type_node_set && rt != xpath_type_node_set)
{
if (lt == xpath_type_boolean || rt == xpath_type_boolean)
return comp(lhs->eval_boolean(c, stack), rhs->eval_boolean(c, stack));
else if (lt == xpath_type_number || rt == xpath_type_number)
return comp(lhs->eval_number(c, stack), rhs->eval_number(c, stack));
else if (lt == xpath_type_string || rt == xpath_type_string)
{
xpath_allocator_capture cr(stack.result);
xpath_string ls = lhs->eval_string(c, stack);
xpath_string rs = rhs->eval_string(c, stack);
return comp(ls, rs);
}
}
else if (lt == xpath_type_node_set && rt == xpath_type_node_set)
{
xpath_allocator_capture cr(stack.result);
xpath_node_set_raw ls = lhs->eval_node_set(c, stack, nodeset_eval_all);
xpath_node_set_raw rs = rhs->eval_node_set(c, stack, nodeset_eval_all);
for (const xpath_node* li = ls.begin(); li != ls.end(); ++li)
for (const xpath_node* ri = rs.begin(); ri != rs.end(); ++ri)
{
xpath_allocator_capture cri(stack.result);
if (comp(string_value(*li, stack.result), string_value(*ri, stack.result)))
return true;
}
return false;
}
else
{
if (lt == xpath_type_node_set)
{
swap(lhs, rhs);
swap(lt, rt);
}
if (lt == xpath_type_boolean)
return comp(lhs->eval_boolean(c, stack), rhs->eval_boolean(c, stack));
else if (lt == xpath_type_number)
{
xpath_allocator_capture cr(stack.result);
double l = lhs->eval_number(c, stack);
xpath_node_set_raw rs = rhs->eval_node_set(c, stack, nodeset_eval_all);
for (const xpath_node* ri = rs.begin(); ri != rs.end(); ++ri)
{
xpath_allocator_capture cri(stack.result);
if (comp(l, convert_string_to_number(string_value(*ri, stack.result).c_str())))
return true;
}
return false;
}
else if (lt == xpath_type_string)
{
xpath_allocator_capture cr(stack.result);
xpath_string l = lhs->eval_string(c, stack);
xpath_node_set_raw rs = rhs->eval_node_set(c, stack, nodeset_eval_all);
for (const xpath_node* ri = rs.begin(); ri != rs.end(); ++ri)
{
xpath_allocator_capture cri(stack.result);
if (comp(l, string_value(*ri, stack.result)))
return true;
}
return false;
}
}
assert(false && "Wrong types"); // unreachable
return false;
}
static bool eval_once(xpath_node_set::type_t type, nodeset_eval_t eval)
{
return type == xpath_node_set::type_sorted ? eval != nodeset_eval_all : eval == nodeset_eval_any;
}
template <class Comp> static bool compare_rel(xpath_ast_node* lhs, xpath_ast_node* rhs, const xpath_context& c, const xpath_stack& stack, const Comp& comp)
{
xpath_value_type lt = lhs->rettype(), rt = rhs->rettype();
if (lt != xpath_type_node_set && rt != xpath_type_node_set)
return comp(lhs->eval_number(c, stack), rhs->eval_number(c, stack));
else if (lt == xpath_type_node_set && rt == xpath_type_node_set)
{
xpath_allocator_capture cr(stack.result);
xpath_node_set_raw ls = lhs->eval_node_set(c, stack, nodeset_eval_all);
xpath_node_set_raw rs = rhs->eval_node_set(c, stack, nodeset_eval_all);
for (const xpath_node* li = ls.begin(); li != ls.end(); ++li)
{
xpath_allocator_capture cri(stack.result);
double l = convert_string_to_number(string_value(*li, stack.result).c_str());
for (const xpath_node* ri = rs.begin(); ri != rs.end(); ++ri)
{
xpath_allocator_capture crii(stack.result);
if (comp(l, convert_string_to_number(string_value(*ri, stack.result).c_str())))
return true;
}
}
return false;
}
else if (lt != xpath_type_node_set && rt == xpath_type_node_set)
{
xpath_allocator_capture cr(stack.result);
double l = lhs->eval_number(c, stack);
xpath_node_set_raw rs = rhs->eval_node_set(c, stack, nodeset_eval_all);
for (const xpath_node* ri = rs.begin(); ri != rs.end(); ++ri)
{
xpath_allocator_capture cri(stack.result);
if (comp(l, convert_string_to_number(string_value(*ri, stack.result).c_str())))
return true;
}
return false;
}
else if (lt == xpath_type_node_set && rt != xpath_type_node_set)
{
xpath_allocator_capture cr(stack.result);
xpath_node_set_raw ls = lhs->eval_node_set(c, stack, nodeset_eval_all);
double r = rhs->eval_number(c, stack);
for (const xpath_node* li = ls.begin(); li != ls.end(); ++li)
{
xpath_allocator_capture cri(stack.result);
if (comp(convert_string_to_number(string_value(*li, stack.result).c_str()), r))
return true;
}
return false;
}
else
{
assert(false && "Wrong types"); // unreachable
return false;
}
}
static void apply_predicate_boolean(xpath_node_set_raw& ns, size_t first, xpath_ast_node* expr, const xpath_stack& stack, bool once)
{
assert(ns.size() >= first);
assert(expr->rettype() != xpath_type_number);
size_t i = 1;
size_t size = ns.size() - first;
xpath_node* last = ns.begin() + first;
// remove_if... or well, sort of
for (xpath_node* it = last; it != ns.end(); ++it, ++i)
{
xpath_context c(*it, i, size);
if (expr->eval_boolean(c, stack))
{
*last++ = *it;
if (once) break;
}
}
ns.truncate(last);
}
static void apply_predicate_number(xpath_node_set_raw& ns, size_t first, xpath_ast_node* expr, const xpath_stack& stack, bool once)
{
assert(ns.size() >= first);
assert(expr->rettype() == xpath_type_number);
size_t i = 1;
size_t size = ns.size() - first;
xpath_node* last = ns.begin() + first;
// remove_if... or well, sort of
for (xpath_node* it = last; it != ns.end(); ++it, ++i)
{
xpath_context c(*it, i, size);
if (expr->eval_number(c, stack) == static_cast<double>(i))
{
*last++ = *it;
if (once) break;
}
}
ns.truncate(last);
}
static void apply_predicate_number_const(xpath_node_set_raw& ns, size_t first, xpath_ast_node* expr, const xpath_stack& stack)
{
assert(ns.size() >= first);
assert(expr->rettype() == xpath_type_number);
size_t size = ns.size() - first;
xpath_node* last = ns.begin() + first;
xpath_context c(xpath_node(), 1, size);
double er = expr->eval_number(c, stack);
if (er >= 1.0 && er <= static_cast<double>(size))
{
size_t eri = static_cast<size_t>(er);
if (er == static_cast<double>(eri))
{
xpath_node r = last[eri - 1];
*last++ = r;
}
}
ns.truncate(last);
}
void apply_predicate(xpath_node_set_raw& ns, size_t first, const xpath_stack& stack, bool once)
{
if (ns.size() == first) return;
assert(_type == ast_filter || _type == ast_predicate);
if (_test == predicate_constant || _test == predicate_constant_one)
apply_predicate_number_const(ns, first, _right, stack);
else if (_right->rettype() == xpath_type_number)
apply_predicate_number(ns, first, _right, stack, once);
else
apply_predicate_boolean(ns, first, _right, stack, once);
}
void apply_predicates(xpath_node_set_raw& ns, size_t first, const xpath_stack& stack, nodeset_eval_t eval)
{
if (ns.size() == first) return;
bool last_once = eval_once(ns.type(), eval);
for (xpath_ast_node* pred = _right; pred; pred = pred->_next)
pred->apply_predicate(ns, first, stack, !pred->_next && last_once);
}
bool step_push(xpath_node_set_raw& ns, xml_attribute_struct* a, xml_node_struct* parent, xpath_allocator* alloc)
{
assert(a);
const char_t* name = a->name ? a->name + 0 : PUGIXML_TEXT("");
switch (_test)
{
case nodetest_name:
if (strequal(name, _data.nodetest) && is_xpath_attribute(name))
{
ns.push_back(xpath_node(xml_attribute(a), xml_node(parent)), alloc);
return true;
}
break;
case nodetest_type_node:
case nodetest_all:
if (is_xpath_attribute(name))
{
ns.push_back(xpath_node(xml_attribute(a), xml_node(parent)), alloc);
return true;
}
break;
case nodetest_all_in_namespace:
if (starts_with(name, _data.nodetest) && is_xpath_attribute(name))
{
ns.push_back(xpath_node(xml_attribute(a), xml_node(parent)), alloc);
return true;
}
break;
default:
;
}
return false;
}
bool step_push(xpath_node_set_raw& ns, xml_node_struct* n, xpath_allocator* alloc)
{
assert(n);
xml_node_type type = PUGI__NODETYPE(n);
switch (_test)
{
case nodetest_name:
if (type == node_element && n->name && strequal(n->name, _data.nodetest))
{
ns.push_back(xml_node(n), alloc);
return true;
}
break;
case nodetest_type_node:
ns.push_back(xml_node(n), alloc);
return true;
case nodetest_type_comment:
if (type == node_comment)
{
ns.push_back(xml_node(n), alloc);
return true;
}
break;
case nodetest_type_text:
if (type == node_pcdata || type == node_cdata)
{
ns.push_back(xml_node(n), alloc);
return true;
}
break;
case nodetest_type_pi:
if (type == node_pi)
{
ns.push_back(xml_node(n), alloc);
return true;
}
break;
case nodetest_pi:
if (type == node_pi && n->name && strequal(n->name, _data.nodetest))
{
ns.push_back(xml_node(n), alloc);
return true;
}
break;
case nodetest_all:
if (type == node_element)
{
ns.push_back(xml_node(n), alloc);
return true;
}
break;
case nodetest_all_in_namespace:
if (type == node_element && n->name && starts_with(n->name, _data.nodetest))
{
ns.push_back(xml_node(n), alloc);
return true;
}
break;
default:
assert(false && "Unknown axis"); // unreachable
}
return false;
}
template <class T> void step_fill(xpath_node_set_raw& ns, xml_node_struct* n, xpath_allocator* alloc, bool once, T)
{
const axis_t axis = T::axis;
switch (axis)
{
case axis_attribute:
{
for (xml_attribute_struct* a = n->first_attribute; a; a = a->next_attribute)
if (step_push(ns, a, n, alloc) & once)
return;
break;
}
case axis_child:
{
for (xml_node_struct* c = n->first_child; c; c = c->next_sibling)
if (step_push(ns, c, alloc) & once)
return;
break;
}
case axis_descendant:
case axis_descendant_or_self:
{
if (axis == axis_descendant_or_self)
if (step_push(ns, n, alloc) & once)
return;
xml_node_struct* cur = n->first_child;
while (cur)
{
if (step_push(ns, cur, alloc) & once)
return;
if (cur->first_child)
cur = cur->first_child;
else
{
while (!cur->next_sibling)
{
cur = cur->parent;
if (cur == n) return;
}
cur = cur->next_sibling;
}
}
break;
}
case axis_following_sibling:
{
for (xml_node_struct* c = n->next_sibling; c; c = c->next_sibling)
if (step_push(ns, c, alloc) & once)
return;
break;
}
case axis_preceding_sibling:
{
for (xml_node_struct* c = n->prev_sibling_c; c->next_sibling; c = c->prev_sibling_c)
if (step_push(ns, c, alloc) & once)
return;
break;
}
case axis_following:
{
xml_node_struct* cur = n;
// exit from this node so that we don't include descendants
while (!cur->next_sibling)
{
cur = cur->parent;
if (!cur) return;
}
cur = cur->next_sibling;
while (cur)
{
if (step_push(ns, cur, alloc) & once)
return;
if (cur->first_child)
cur = cur->first_child;
else
{
while (!cur->next_sibling)
{
cur = cur->parent;
if (!cur) return;
}
cur = cur->next_sibling;
}
}
break;
}
case axis_preceding:
{
xml_node_struct* cur = n;
// exit from this node so that we don't include descendants
while (!cur->prev_sibling_c->next_sibling)
{
cur = cur->parent;
if (!cur) return;
}
cur = cur->prev_sibling_c;
while (cur)
{
if (cur->first_child)
cur = cur->first_child->prev_sibling_c;
else
{
// leaf node, can't be ancestor
if (step_push(ns, cur, alloc) & once)
return;
while (!cur->prev_sibling_c->next_sibling)
{
cur = cur->parent;
if (!cur) return;
if (!node_is_ancestor(cur, n))
if (step_push(ns, cur, alloc) & once)
return;
}
cur = cur->prev_sibling_c;
}
}
break;
}
case axis_ancestor:
case axis_ancestor_or_self:
{
if (axis == axis_ancestor_or_self)
if (step_push(ns, n, alloc) & once)
return;
xml_node_struct* cur = n->parent;
while (cur)
{
if (step_push(ns, cur, alloc) & once)
return;
cur = cur->parent;
}
break;
}
case axis_self:
{
step_push(ns, n, alloc);
break;
}
case axis_parent:
{
if (n->parent)
step_push(ns, n->parent, alloc);
break;
}
default:
assert(false && "Unimplemented axis"); // unreachable
}
}
template <class T> void step_fill(xpath_node_set_raw& ns, xml_attribute_struct* a, xml_node_struct* p, xpath_allocator* alloc, bool once, T v)
{
const axis_t axis = T::axis;
switch (axis)
{
case axis_ancestor:
case axis_ancestor_or_self:
{
if (axis == axis_ancestor_or_self && _test == nodetest_type_node) // reject attributes based on principal node type test
if (step_push(ns, a, p, alloc) & once)
return;
xml_node_struct* cur = p;
while (cur)
{
if (step_push(ns, cur, alloc) & once)
return;
cur = cur->parent;
}
break;
}
case axis_descendant_or_self:
case axis_self:
{
if (_test == nodetest_type_node) // reject attributes based on principal node type test
step_push(ns, a, p, alloc);
break;
}
case axis_following:
{
xml_node_struct* cur = p;
while (cur)
{
if (cur->first_child)
cur = cur->first_child;
else
{
while (!cur->next_sibling)
{
cur = cur->parent;
if (!cur) return;
}
cur = cur->next_sibling;
}
if (step_push(ns, cur, alloc) & once)
return;
}
break;
}
case axis_parent:
{
step_push(ns, p, alloc);
break;
}
case axis_preceding:
{
// preceding:: axis does not include attribute nodes and attribute ancestors (they are the same as parent's ancestors), so we can reuse node preceding
step_fill(ns, p, alloc, once, v);
break;
}
default:
assert(false && "Unimplemented axis"); // unreachable
}
}
template <class T> void step_fill(xpath_node_set_raw& ns, const xpath_node& xn, xpath_allocator* alloc, bool once, T v)
{
const axis_t axis = T::axis;
const bool axis_has_attributes = (axis == axis_ancestor || axis == axis_ancestor_or_self || axis == axis_descendant_or_self || axis == axis_following || axis == axis_parent || axis == axis_preceding || axis == axis_self);
if (xn.node())
step_fill(ns, xn.node().internal_object(), alloc, once, v);
else if (axis_has_attributes && xn.attribute() && xn.parent())
step_fill(ns, xn.attribute().internal_object(), xn.parent().internal_object(), alloc, once, v);
}
template <class T> xpath_node_set_raw step_do(const xpath_context& c, const xpath_stack& stack, nodeset_eval_t eval, T v)
{
const axis_t axis = T::axis;
const bool axis_reverse = (axis == axis_ancestor || axis == axis_ancestor_or_self || axis == axis_preceding || axis == axis_preceding_sibling);
const xpath_node_set::type_t axis_type = axis_reverse ? xpath_node_set::type_sorted_reverse : xpath_node_set::type_sorted;
bool once =
(axis == axis_attribute && _test == nodetest_name) ||
(!_right && eval_once(axis_type, eval)) ||
// coverity[mixed_enums]
(_right && !_right->_next && _right->_test == predicate_constant_one);
xpath_node_set_raw ns;
ns.set_type(axis_type);
if (_left)
{
xpath_node_set_raw s = _left->eval_node_set(c, stack, nodeset_eval_all);
// self axis preserves the original order
if (axis == axis_self) ns.set_type(s.type());
for (const xpath_node* it = s.begin(); it != s.end(); ++it)
{
size_t size = ns.size();
// in general, all axes generate elements in a particular order, but there is no order guarantee if axis is applied to two nodes
if (axis != axis_self && size != 0) ns.set_type(xpath_node_set::type_unsorted);
step_fill(ns, *it, stack.result, once, v);
if (_right) apply_predicates(ns, size, stack, eval);
}
}
else
{
step_fill(ns, c.n, stack.result, once, v);
if (_right) apply_predicates(ns, 0, stack, eval);
}
// child, attribute and self axes always generate unique set of nodes
// for other axis, if the set stayed sorted, it stayed unique because the traversal algorithms do not visit the same node twice
if (axis != axis_child && axis != axis_attribute && axis != axis_self && ns.type() == xpath_node_set::type_unsorted)
ns.remove_duplicates(stack.temp);
return ns;
}
public:
xpath_ast_node(ast_type_t type, xpath_value_type rettype_, const char_t* value):
_type(static_cast<char>(type)), _rettype(static_cast<char>(rettype_)), _axis(0), _test(0), _left(0), _right(0), _next(0)
{
assert(type == ast_string_constant);
_data.string = value;
}
xpath_ast_node(ast_type_t type, xpath_value_type rettype_, double value):
_type(static_cast<char>(type)), _rettype(static_cast<char>(rettype_)), _axis(0), _test(0), _left(0), _right(0), _next(0)
{
assert(type == ast_number_constant);
_data.number = value;
}
xpath_ast_node(ast_type_t type, xpath_value_type rettype_, xpath_variable* value):
_type(static_cast<char>(type)), _rettype(static_cast<char>(rettype_)), _axis(0), _test(0), _left(0), _right(0), _next(0)
{
assert(type == ast_variable);
_data.variable = value;
}
xpath_ast_node(ast_type_t type, xpath_value_type rettype_, xpath_ast_node* left = 0, xpath_ast_node* right = 0):
_type(static_cast<char>(type)), _rettype(static_cast<char>(rettype_)), _axis(0), _test(0), _left(left), _right(right), _next(0)
{
}
xpath_ast_node(ast_type_t type, xpath_ast_node* left, axis_t axis, nodetest_t test, const char_t* contents):
_type(static_cast<char>(type)), _rettype(xpath_type_node_set), _axis(static_cast<char>(axis)), _test(static_cast<char>(test)), _left(left), _right(0), _next(0)
{
assert(type == ast_step);
_data.nodetest = contents;
}
xpath_ast_node(ast_type_t type, xpath_ast_node* left, xpath_ast_node* right, predicate_t test):
_type(static_cast<char>(type)), _rettype(xpath_type_node_set), _axis(0), _test(static_cast<char>(test)), _left(left), _right(right), _next(0)
{
assert(type == ast_filter || type == ast_predicate);
}
void set_next(xpath_ast_node* value)
{
_next = value;
}
void set_right(xpath_ast_node* value)
{
_right = value;
}
bool eval_boolean(const xpath_context& c, const xpath_stack& stack)
{
switch (_type)
{
case ast_op_or:
return _left->eval_boolean(c, stack) || _right->eval_boolean(c, stack);
case ast_op_and:
return _left->eval_boolean(c, stack) && _right->eval_boolean(c, stack);
case ast_op_equal:
return compare_eq(_left, _right, c, stack, equal_to());
case ast_op_not_equal:
return compare_eq(_left, _right, c, stack, not_equal_to());
case ast_op_less:
return compare_rel(_left, _right, c, stack, less());
case ast_op_greater:
return compare_rel(_right, _left, c, stack, less());
case ast_op_less_or_equal:
return compare_rel(_left, _right, c, stack, less_equal());
case ast_op_greater_or_equal:
return compare_rel(_right, _left, c, stack, less_equal());
case ast_func_starts_with:
{
xpath_allocator_capture cr(stack.result);
xpath_string lr = _left->eval_string(c, stack);
xpath_string rr = _right->eval_string(c, stack);
return starts_with(lr.c_str(), rr.c_str());
}
case ast_func_contains:
{
xpath_allocator_capture cr(stack.result);
xpath_string lr = _left->eval_string(c, stack);
xpath_string rr = _right->eval_string(c, stack);
return find_substring(lr.c_str(), rr.c_str()) != 0;
}
case ast_func_boolean:
return _left->eval_boolean(c, stack);
case ast_func_not:
return !_left->eval_boolean(c, stack);
case ast_func_true:
return true;
case ast_func_false:
return false;
case ast_func_lang:
{
if (c.n.attribute()) return false;
xpath_allocator_capture cr(stack.result);
xpath_string lang = _left->eval_string(c, stack);
for (xml_node n = c.n.node(); n; n = n.parent())
{
xml_attribute a = n.attribute(PUGIXML_TEXT("xml:lang"));
if (a)
{
const char_t* value = a.value();
// strnicmp / strncasecmp is not portable
for (const char_t* lit = lang.c_str(); *lit; ++lit)
{
if (tolower_ascii(*lit) != tolower_ascii(*value)) return false;
++value;
}
return *value == 0 || *value == '-';
}
}
return false;
}
case ast_opt_compare_attribute:
{
const char_t* value = (_right->_type == ast_string_constant) ? _right->_data.string : _right->_data.variable->get_string();
xml_attribute attr = c.n.node().attribute(_left->_data.nodetest);
return attr && strequal(attr.value(), value) && is_xpath_attribute(attr.name());
}
case ast_variable:
{
assert(_rettype == _data.variable->type());
if (_rettype == xpath_type_boolean)
return _data.variable->get_boolean();
// variable needs to be converted to the correct type, this is handled by the fallthrough block below
break;
}
default:
;
}
// none of the ast types that return the value directly matched, we need to perform type conversion
switch (_rettype)
{
case xpath_type_number:
return convert_number_to_boolean(eval_number(c, stack));
case xpath_type_string:
{
xpath_allocator_capture cr(stack.result);
return !eval_string(c, stack).empty();
}
case xpath_type_node_set:
{
xpath_allocator_capture cr(stack.result);
return !eval_node_set(c, stack, nodeset_eval_any).empty();
}
default:
assert(false && "Wrong expression for return type boolean"); // unreachable
return false;
}
}
double eval_number(const xpath_context& c, const xpath_stack& stack)
{
switch (_type)
{
case ast_op_add:
return _left->eval_number(c, stack) + _right->eval_number(c, stack);
case ast_op_subtract:
return _left->eval_number(c, stack) - _right->eval_number(c, stack);
case ast_op_multiply:
return _left->eval_number(c, stack) * _right->eval_number(c, stack);
case ast_op_divide:
return _left->eval_number(c, stack) / _right->eval_number(c, stack);
case ast_op_mod:
return fmod(_left->eval_number(c, stack), _right->eval_number(c, stack));
case ast_op_negate:
return -_left->eval_number(c, stack);
case ast_number_constant:
return _data.number;
case ast_func_last:
return static_cast<double>(c.size);
case ast_func_position:
return static_cast<double>(c.position);
case ast_func_count:
{
xpath_allocator_capture cr(stack.result);
return static_cast<double>(_left->eval_node_set(c, stack, nodeset_eval_all).size());
}
case ast_func_string_length_0:
{
xpath_allocator_capture cr(stack.result);
return static_cast<double>(string_value(c.n, stack.result).length());
}
case ast_func_string_length_1:
{
xpath_allocator_capture cr(stack.result);
return static_cast<double>(_left->eval_string(c, stack).length());
}
case ast_func_number_0:
{
xpath_allocator_capture cr(stack.result);
return convert_string_to_number(string_value(c.n, stack.result).c_str());
}
case ast_func_number_1:
return _left->eval_number(c, stack);
case ast_func_sum:
{
xpath_allocator_capture cr(stack.result);
double r = 0;
xpath_node_set_raw ns = _left->eval_node_set(c, stack, nodeset_eval_all);
for (const xpath_node* it = ns.begin(); it != ns.end(); ++it)
{
xpath_allocator_capture cri(stack.result);
r += convert_string_to_number(string_value(*it, stack.result).c_str());
}
return r;
}
case ast_func_floor:
{
double r = _left->eval_number(c, stack);
return r == r ? floor(r) : r;
}
case ast_func_ceiling:
{
double r = _left->eval_number(c, stack);
return r == r ? ceil(r) : r;
}
case ast_func_round:
return round_nearest_nzero(_left->eval_number(c, stack));
case ast_variable:
{
assert(_rettype == _data.variable->type());
if (_rettype == xpath_type_number)
return _data.variable->get_number();
// variable needs to be converted to the correct type, this is handled by the fallthrough block below
break;
}
default:
;
}
// none of the ast types that return the value directly matched, we need to perform type conversion
switch (_rettype)
{
case xpath_type_boolean:
return eval_boolean(c, stack) ? 1 : 0;
case xpath_type_string:
{
xpath_allocator_capture cr(stack.result);
return convert_string_to_number(eval_string(c, stack).c_str());
}
case xpath_type_node_set:
{
xpath_allocator_capture cr(stack.result);
return convert_string_to_number(eval_string(c, stack).c_str());
}
default:
assert(false && "Wrong expression for return type number"); // unreachable
return 0;
}
}
xpath_string eval_string_concat(const xpath_context& c, const xpath_stack& stack)
{
assert(_type == ast_func_concat);
xpath_allocator_capture ct(stack.temp);
// count the string number
size_t count = 1;
for (xpath_ast_node* nc = _right; nc; nc = nc->_next) count++;
// allocate a buffer for temporary string objects
xpath_string* buffer = static_cast<xpath_string*>(stack.temp->allocate(count * sizeof(xpath_string)));
if (!buffer) return xpath_string();
// evaluate all strings to temporary stack
xpath_stack swapped_stack = {stack.temp, stack.result};
buffer[0] = _left->eval_string(c, swapped_stack);
size_t pos = 1;
for (xpath_ast_node* n = _right; n; n = n->_next, ++pos) buffer[pos] = n->eval_string(c, swapped_stack);
assert(pos == count);
// get total length
size_t length = 0;
for (size_t i = 0; i < count; ++i) length += buffer[i].length();
// create final string
char_t* result = static_cast<char_t*>(stack.result->allocate((length + 1) * sizeof(char_t)));
if (!result) return xpath_string();
char_t* ri = result;
for (size_t j = 0; j < count; ++j)
for (const char_t* bi = buffer[j].c_str(); *bi; ++bi)
*ri++ = *bi;
*ri = 0;
return xpath_string::from_heap_preallocated(result, ri);
}
xpath_string eval_string(const xpath_context& c, const xpath_stack& stack)
{
switch (_type)
{
case ast_string_constant:
return xpath_string::from_const(_data.string);
case ast_func_local_name_0:
{
xpath_node na = c.n;
return xpath_string::from_const(local_name(na));
}
case ast_func_local_name_1:
{
xpath_allocator_capture cr(stack.result);
xpath_node_set_raw ns = _left->eval_node_set(c, stack, nodeset_eval_first);
xpath_node na = ns.first();
return xpath_string::from_const(local_name(na));
}
case ast_func_name_0:
{
xpath_node na = c.n;
return xpath_string::from_const(qualified_name(na));
}
case ast_func_name_1:
{
xpath_allocator_capture cr(stack.result);
xpath_node_set_raw ns = _left->eval_node_set(c, stack, nodeset_eval_first);
xpath_node na = ns.first();
return xpath_string::from_const(qualified_name(na));
}
case ast_func_namespace_uri_0:
{
xpath_node na = c.n;
return xpath_string::from_const(namespace_uri(na));
}
case ast_func_namespace_uri_1:
{
xpath_allocator_capture cr(stack.result);
xpath_node_set_raw ns = _left->eval_node_set(c, stack, nodeset_eval_first);
xpath_node na = ns.first();
return xpath_string::from_const(namespace_uri(na));
}
case ast_func_string_0:
return string_value(c.n, stack.result);
case ast_func_string_1:
return _left->eval_string(c, stack);
case ast_func_concat:
return eval_string_concat(c, stack);
case ast_func_substring_before:
{
xpath_allocator_capture cr(stack.temp);
xpath_stack swapped_stack = {stack.temp, stack.result};
xpath_string s = _left->eval_string(c, swapped_stack);
xpath_string p = _right->eval_string(c, swapped_stack);
const char_t* pos = find_substring(s.c_str(), p.c_str());
return pos ? xpath_string::from_heap(s.c_str(), pos, stack.result) : xpath_string();
}
case ast_func_substring_after:
{
xpath_allocator_capture cr(stack.temp);
xpath_stack swapped_stack = {stack.temp, stack.result};
xpath_string s = _left->eval_string(c, swapped_stack);
xpath_string p = _right->eval_string(c, swapped_stack);
const char_t* pos = find_substring(s.c_str(), p.c_str());
if (!pos) return xpath_string();
const char_t* rbegin = pos + p.length();
const char_t* rend = s.c_str() + s.length();
return s.uses_heap() ? xpath_string::from_heap(rbegin, rend, stack.result) : xpath_string::from_const(rbegin);
}
case ast_func_substring_2:
{
xpath_allocator_capture cr(stack.temp);
xpath_stack swapped_stack = {stack.temp, stack.result};
xpath_string s = _left->eval_string(c, swapped_stack);
size_t s_length = s.length();
double first = round_nearest(_right->eval_number(c, stack));
if (is_nan(first)) return xpath_string(); // NaN
else if (first >= static_cast<double>(s_length + 1)) return xpath_string();
size_t pos = first < 1 ? 1 : static_cast<size_t>(first);
assert(1 <= pos && pos <= s_length + 1);
const char_t* rbegin = s.c_str() + (pos - 1);
const char_t* rend = s.c_str() + s.length();
return s.uses_heap() ? xpath_string::from_heap(rbegin, rend, stack.result) : xpath_string::from_const(rbegin);
}
case ast_func_substring_3:
{
xpath_allocator_capture cr(stack.temp);
xpath_stack swapped_stack = {stack.temp, stack.result};
xpath_string s = _left->eval_string(c, swapped_stack);
size_t s_length = s.length();
double first = round_nearest(_right->eval_number(c, stack));
double last = first + round_nearest(_right->_next->eval_number(c, stack));
if (is_nan(first) || is_nan(last)) return xpath_string();
else if (first >= static_cast<double>(s_length + 1)) return xpath_string();
else if (first >= last) return xpath_string();
else if (last < 1) return xpath_string();
size_t pos = first < 1 ? 1 : static_cast<size_t>(first);
size_t end = last >= static_cast<double>(s_length + 1) ? s_length + 1 : static_cast<size_t>(last);
assert(1 <= pos && pos <= end && end <= s_length + 1);
const char_t* rbegin = s.c_str() + (pos - 1);
const char_t* rend = s.c_str() + (end - 1);
return (end == s_length + 1 && !s.uses_heap()) ? xpath_string::from_const(rbegin) : xpath_string::from_heap(rbegin, rend, stack.result);
}
case ast_func_normalize_space_0:
{
xpath_string s = string_value(c.n, stack.result);
char_t* begin = s.data(stack.result);
if (!begin) return xpath_string();
char_t* end = normalize_space(begin);
return xpath_string::from_heap_preallocated(begin, end);
}
case ast_func_normalize_space_1:
{
xpath_string s = _left->eval_string(c, stack);
char_t* begin = s.data(stack.result);
if (!begin) return xpath_string();
char_t* end = normalize_space(begin);
return xpath_string::from_heap_preallocated(begin, end);
}
case ast_func_translate:
{
xpath_allocator_capture cr(stack.temp);
xpath_stack swapped_stack = {stack.temp, stack.result};
xpath_string s = _left->eval_string(c, stack);
xpath_string from = _right->eval_string(c, swapped_stack);
xpath_string to = _right->_next->eval_string(c, swapped_stack);
char_t* begin = s.data(stack.result);
if (!begin) return xpath_string();
char_t* end = translate(begin, from.c_str(), to.c_str(), to.length());
return xpath_string::from_heap_preallocated(begin, end);
}
case ast_opt_translate_table:
{
xpath_string s = _left->eval_string(c, stack);
char_t* begin = s.data(stack.result);
if (!begin) return xpath_string();
char_t* end = translate_table(begin, _data.table);
return xpath_string::from_heap_preallocated(begin, end);
}
case ast_variable:
{
assert(_rettype == _data.variable->type());
if (_rettype == xpath_type_string)
return xpath_string::from_const(_data.variable->get_string());
// variable needs to be converted to the correct type, this is handled by the fallthrough block below
break;
}
default:
;
}
// none of the ast types that return the value directly matched, we need to perform type conversion
switch (_rettype)
{
case xpath_type_boolean:
return xpath_string::from_const(eval_boolean(c, stack) ? PUGIXML_TEXT("true") : PUGIXML_TEXT("false"));
case xpath_type_number:
return convert_number_to_string(eval_number(c, stack), stack.result);
case xpath_type_node_set:
{
xpath_allocator_capture cr(stack.temp);
xpath_stack swapped_stack = {stack.temp, stack.result};
xpath_node_set_raw ns = eval_node_set(c, swapped_stack, nodeset_eval_first);
return ns.empty() ? xpath_string() : string_value(ns.first(), stack.result);
}
default:
assert(false && "Wrong expression for return type string"); // unreachable
return xpath_string();
}
}
xpath_node_set_raw eval_node_set(const xpath_context& c, const xpath_stack& stack, nodeset_eval_t eval)
{
switch (_type)
{
case ast_op_union:
{
xpath_allocator_capture cr(stack.temp);
xpath_stack swapped_stack = {stack.temp, stack.result};
xpath_node_set_raw ls = _left->eval_node_set(c, stack, eval);
xpath_node_set_raw rs = _right->eval_node_set(c, swapped_stack, eval);
// we can optimize merging two sorted sets, but this is a very rare operation, so don't bother
ls.set_type(xpath_node_set::type_unsorted);
ls.append(rs.begin(), rs.end(), stack.result);
ls.remove_duplicates(stack.temp);
return ls;
}
case ast_filter:
{
xpath_node_set_raw set = _left->eval_node_set(c, stack, _test == predicate_constant_one ? nodeset_eval_first : nodeset_eval_all);
// either expression is a number or it contains position() call; sort by document order
if (_test != predicate_posinv) set.sort_do();
bool once = eval_once(set.type(), eval);
apply_predicate(set, 0, stack, once);
return set;
}
case ast_func_id:
return xpath_node_set_raw();
case ast_step:
{
switch (_axis)
{
case axis_ancestor:
return step_do(c, stack, eval, axis_to_type<axis_ancestor>());
case axis_ancestor_or_self:
return step_do(c, stack, eval, axis_to_type<axis_ancestor_or_self>());
case axis_attribute:
return step_do(c, stack, eval, axis_to_type<axis_attribute>());
case axis_child:
return step_do(c, stack, eval, axis_to_type<axis_child>());
case axis_descendant:
return step_do(c, stack, eval, axis_to_type<axis_descendant>());
case axis_descendant_or_self:
return step_do(c, stack, eval, axis_to_type<axis_descendant_or_self>());
case axis_following:
return step_do(c, stack, eval, axis_to_type<axis_following>());
case axis_following_sibling:
return step_do(c, stack, eval, axis_to_type<axis_following_sibling>());
case axis_namespace:
// namespaced axis is not supported
return xpath_node_set_raw();
case axis_parent:
return step_do(c, stack, eval, axis_to_type<axis_parent>());
case axis_preceding:
return step_do(c, stack, eval, axis_to_type<axis_preceding>());
case axis_preceding_sibling:
return step_do(c, stack, eval, axis_to_type<axis_preceding_sibling>());
case axis_self:
return step_do(c, stack, eval, axis_to_type<axis_self>());
default:
assert(false && "Unknown axis"); // unreachable
return xpath_node_set_raw();
}
}
case ast_step_root:
{
assert(!_right); // root step can't have any predicates
xpath_node_set_raw ns;
ns.set_type(xpath_node_set::type_sorted);
if (c.n.node()) ns.push_back(c.n.node().root(), stack.result);
else if (c.n.attribute()) ns.push_back(c.n.parent().root(), stack.result);
return ns;
}
case ast_variable:
{
assert(_rettype == _data.variable->type());
if (_rettype == xpath_type_node_set)
{
const xpath_node_set& s = _data.variable->get_node_set();
xpath_node_set_raw ns;
ns.set_type(s.type());
ns.append(s.begin(), s.end(), stack.result);
return ns;
}
// variable needs to be converted to the correct type, this is handled by the fallthrough block below
break;
}
default:
;
}
// none of the ast types that return the value directly matched, but conversions to node set are invalid
assert(false && "Wrong expression for return type node set"); // unreachable
return xpath_node_set_raw();
}
void optimize(xpath_allocator* alloc)
{
if (_left)
_left->optimize(alloc);
if (_right)
_right->optimize(alloc);
if (_next)
_next->optimize(alloc);
// coverity[var_deref_model]
optimize_self(alloc);
}
void optimize_self(xpath_allocator* alloc)
{
// Rewrite [position()=expr] with [expr]
// Note that this step has to go before classification to recognize [position()=1]
if ((_type == ast_filter || _type == ast_predicate) &&
_right && // workaround for clang static analyzer (_right is never null for ast_filter/ast_predicate)
_right->_type == ast_op_equal && _right->_left->_type == ast_func_position && _right->_right->_rettype == xpath_type_number)
{
_right = _right->_right;
}
// Classify filter/predicate ops to perform various optimizations during evaluation
if ((_type == ast_filter || _type == ast_predicate) && _right) // workaround for clang static analyzer (_right is never null for ast_filter/ast_predicate)
{
assert(_test == predicate_default);
if (_right->_type == ast_number_constant && _right->_data.number == 1.0)
_test = predicate_constant_one;
else if (_right->_rettype == xpath_type_number && (_right->_type == ast_number_constant || _right->_type == ast_variable || _right->_type == ast_func_last))
_test = predicate_constant;
else if (_right->_rettype != xpath_type_number && _right->is_posinv_expr())
_test = predicate_posinv;
}
// Rewrite descendant-or-self::node()/child::foo with descendant::foo
// The former is a full form of //foo, the latter is much faster since it executes the node test immediately
// Do a similar kind of rewrite for self/descendant/descendant-or-self axes
// Note that we only rewrite positionally invariant steps (//foo[1] != /descendant::foo[1])
if (_type == ast_step && (_axis == axis_child || _axis == axis_self || _axis == axis_descendant || _axis == axis_descendant_or_self) &&
_left && _left->_type == ast_step && _left->_axis == axis_descendant_or_self && _left->_test == nodetest_type_node && !_left->_right &&
is_posinv_step())
{
if (_axis == axis_child || _axis == axis_descendant)
_axis = axis_descendant;
else
_axis = axis_descendant_or_self;
_left = _left->_left;
}
// Use optimized lookup table implementation for translate() with constant arguments
if (_type == ast_func_translate &&
_right && // workaround for clang static analyzer (_right is never null for ast_func_translate)
_right->_type == ast_string_constant && _right->_next->_type == ast_string_constant)
{
unsigned char* table = translate_table_generate(alloc, _right->_data.string, _right->_next->_data.string);
if (table)
{
_type = ast_opt_translate_table;
_data.table = table;
}
}
// Use optimized path for @attr = 'value' or @attr = $value
if (_type == ast_op_equal &&
_left && _right && // workaround for clang static analyzer and Coverity (_left and _right are never null for ast_op_equal)
// coverity[mixed_enums]
_left->_type == ast_step && _left->_axis == axis_attribute && _left->_test == nodetest_name && !_left->_left && !_left->_right &&
(_right->_type == ast_string_constant || (_right->_type == ast_variable && _right->_rettype == xpath_type_string)))
{
_type = ast_opt_compare_attribute;
}
}
bool is_posinv_expr() const
{
switch (_type)
{
case ast_func_position:
case ast_func_last:
return false;
case ast_string_constant:
case ast_number_constant:
case ast_variable:
return true;
case ast_step:
case ast_step_root:
return true;
case ast_predicate:
case ast_filter:
return true;
default:
if (_left && !_left->is_posinv_expr()) return false;
for (xpath_ast_node* n = _right; n; n = n->_next)
if (!n->is_posinv_expr()) return false;
return true;
}
}
bool is_posinv_step() const
{
assert(_type == ast_step);
for (xpath_ast_node* n = _right; n; n = n->_next)
{
assert(n->_type == ast_predicate);
if (n->_test != predicate_posinv)
return false;
}
return true;
}
xpath_value_type rettype() const
{
return static_cast<xpath_value_type>(_rettype);
}
};
static const size_t xpath_ast_depth_limit =
#ifdef PUGIXML_XPATH_DEPTH_LIMIT
PUGIXML_XPATH_DEPTH_LIMIT
#else
1024
#endif
;
struct xpath_parser
{
xpath_allocator* _alloc;
xpath_lexer _lexer;
const char_t* _query;
xpath_variable_set* _variables;
xpath_parse_result* _result;
char_t _scratch[32];
size_t _depth;
xpath_ast_node* error(const char* message)
{
_result->error = message;
_result->offset = _lexer.current_pos() - _query;
return 0;
}
xpath_ast_node* error_oom()
{
assert(_alloc->_error);
*_alloc->_error = true;
return 0;
}
xpath_ast_node* error_rec()
{
return error("Exceeded maximum allowed query depth");
}
void* alloc_node()
{
return _alloc->allocate(sizeof(xpath_ast_node));
}
xpath_ast_node* alloc_node(ast_type_t type, xpath_value_type rettype, const char_t* value)
{
void* memory = alloc_node();
return memory ? new (memory) xpath_ast_node(type, rettype, value) : 0;
}
xpath_ast_node* alloc_node(ast_type_t type, xpath_value_type rettype, double value)
{
void* memory = alloc_node();
return memory ? new (memory) xpath_ast_node(type, rettype, value) : 0;
}
xpath_ast_node* alloc_node(ast_type_t type, xpath_value_type rettype, xpath_variable* value)
{
void* memory = alloc_node();
return memory ? new (memory) xpath_ast_node(type, rettype, value) : 0;
}
xpath_ast_node* alloc_node(ast_type_t type, xpath_value_type rettype, xpath_ast_node* left = 0, xpath_ast_node* right = 0)
{
void* memory = alloc_node();
return memory ? new (memory) xpath_ast_node(type, rettype, left, right) : 0;
}
xpath_ast_node* alloc_node(ast_type_t type, xpath_ast_node* left, axis_t axis, nodetest_t test, const char_t* contents)
{
void* memory = alloc_node();
return memory ? new (memory) xpath_ast_node(type, left, axis, test, contents) : 0;
}
xpath_ast_node* alloc_node(ast_type_t type, xpath_ast_node* left, xpath_ast_node* right, predicate_t test)
{
void* memory = alloc_node();
return memory ? new (memory) xpath_ast_node(type, left, right, test) : 0;
}
const char_t* alloc_string(const xpath_lexer_string& value)
{
if (!value.begin)
return PUGIXML_TEXT("");
size_t length = static_cast<size_t>(value.end - value.begin);
char_t* c = static_cast<char_t*>(_alloc->allocate((length + 1) * sizeof(char_t)));
if (!c) return 0;
memcpy(c, value.begin, length * sizeof(char_t));
c[length] = 0;
return c;
}
xpath_ast_node* parse_function(const xpath_lexer_string& name, size_t argc, xpath_ast_node* args[2])
{
switch (name.begin[0])
{
case 'b':
if (name == PUGIXML_TEXT("boolean") && argc == 1)
return alloc_node(ast_func_boolean, xpath_type_boolean, args[0]);
break;
case 'c':
if (name == PUGIXML_TEXT("count") && argc == 1)
{
if (args[0]->rettype() != xpath_type_node_set) return error("Function has to be applied to node set");
return alloc_node(ast_func_count, xpath_type_number, args[0]);
}
else if (name == PUGIXML_TEXT("contains") && argc == 2)
return alloc_node(ast_func_contains, xpath_type_boolean, args[0], args[1]);
else if (name == PUGIXML_TEXT("concat") && argc >= 2)
return alloc_node(ast_func_concat, xpath_type_string, args[0], args[1]);
else if (name == PUGIXML_TEXT("ceiling") && argc == 1)
return alloc_node(ast_func_ceiling, xpath_type_number, args[0]);
break;
case 'f':
if (name == PUGIXML_TEXT("false") && argc == 0)
return alloc_node(ast_func_false, xpath_type_boolean);
else if (name == PUGIXML_TEXT("floor") && argc == 1)
return alloc_node(ast_func_floor, xpath_type_number, args[0]);
break;
case 'i':
if (name == PUGIXML_TEXT("id") && argc == 1)
return alloc_node(ast_func_id, xpath_type_node_set, args[0]);
break;
case 'l':
if (name == PUGIXML_TEXT("last") && argc == 0)
return alloc_node(ast_func_last, xpath_type_number);
else if (name == PUGIXML_TEXT("lang") && argc == 1)
return alloc_node(ast_func_lang, xpath_type_boolean, args[0]);
else if (name == PUGIXML_TEXT("local-name") && argc <= 1)
{
if (argc == 1 && args[0]->rettype() != xpath_type_node_set) return error("Function has to be applied to node set");
return alloc_node(argc == 0 ? ast_func_local_name_0 : ast_func_local_name_1, xpath_type_string, args[0]);
}
break;
case 'n':
if (name == PUGIXML_TEXT("name") && argc <= 1)
{
if (argc == 1 && args[0]->rettype() != xpath_type_node_set) return error("Function has to be applied to node set");
return alloc_node(argc == 0 ? ast_func_name_0 : ast_func_name_1, xpath_type_string, args[0]);
}
else if (name == PUGIXML_TEXT("namespace-uri") && argc <= 1)
{
if (argc == 1 && args[0]->rettype() != xpath_type_node_set) return error("Function has to be applied to node set");
return alloc_node(argc == 0 ? ast_func_namespace_uri_0 : ast_func_namespace_uri_1, xpath_type_string, args[0]);
}
else if (name == PUGIXML_TEXT("normalize-space") && argc <= 1)
return alloc_node(argc == 0 ? ast_func_normalize_space_0 : ast_func_normalize_space_1, xpath_type_string, args[0], args[1]);
else if (name == PUGIXML_TEXT("not") && argc == 1)
return alloc_node(ast_func_not, xpath_type_boolean, args[0]);
else if (name == PUGIXML_TEXT("number") && argc <= 1)
return alloc_node(argc == 0 ? ast_func_number_0 : ast_func_number_1, xpath_type_number, args[0]);
break;
case 'p':
if (name == PUGIXML_TEXT("position") && argc == 0)
return alloc_node(ast_func_position, xpath_type_number);
break;
case 'r':
if (name == PUGIXML_TEXT("round") && argc == 1)
return alloc_node(ast_func_round, xpath_type_number, args[0]);
break;
case 's':
if (name == PUGIXML_TEXT("string") && argc <= 1)
return alloc_node(argc == 0 ? ast_func_string_0 : ast_func_string_1, xpath_type_string, args[0]);
else if (name == PUGIXML_TEXT("string-length") && argc <= 1)
return alloc_node(argc == 0 ? ast_func_string_length_0 : ast_func_string_length_1, xpath_type_number, args[0]);
else if (name == PUGIXML_TEXT("starts-with") && argc == 2)
return alloc_node(ast_func_starts_with, xpath_type_boolean, args[0], args[1]);
else if (name == PUGIXML_TEXT("substring-before") && argc == 2)
return alloc_node(ast_func_substring_before, xpath_type_string, args[0], args[1]);
else if (name == PUGIXML_TEXT("substring-after") && argc == 2)
return alloc_node(ast_func_substring_after, xpath_type_string, args[0], args[1]);
else if (name == PUGIXML_TEXT("substring") && (argc == 2 || argc == 3))
return alloc_node(argc == 2 ? ast_func_substring_2 : ast_func_substring_3, xpath_type_string, args[0], args[1]);
else if (name == PUGIXML_TEXT("sum") && argc == 1)
{
if (args[0]->rettype() != xpath_type_node_set) return error("Function has to be applied to node set");
return alloc_node(ast_func_sum, xpath_type_number, args[0]);
}
break;
case 't':
if (name == PUGIXML_TEXT("translate") && argc == 3)
return alloc_node(ast_func_translate, xpath_type_string, args[0], args[1]);
else if (name == PUGIXML_TEXT("true") && argc == 0)
return alloc_node(ast_func_true, xpath_type_boolean);
break;
default:
break;
}
return error("Unrecognized function or wrong parameter count");
}
axis_t parse_axis_name(const xpath_lexer_string& name, bool& specified)
{
specified = true;
switch (name.begin[0])
{
case 'a':
if (name == PUGIXML_TEXT("ancestor"))
return axis_ancestor;
else if (name == PUGIXML_TEXT("ancestor-or-self"))
return axis_ancestor_or_self;
else if (name == PUGIXML_TEXT("attribute"))
return axis_attribute;
break;
case 'c':
if (name == PUGIXML_TEXT("child"))
return axis_child;
break;
case 'd':
if (name == PUGIXML_TEXT("descendant"))
return axis_descendant;
else if (name == PUGIXML_TEXT("descendant-or-self"))
return axis_descendant_or_self;
break;
case 'f':
if (name == PUGIXML_TEXT("following"))
return axis_following;
else if (name == PUGIXML_TEXT("following-sibling"))
return axis_following_sibling;
break;
case 'n':
if (name == PUGIXML_TEXT("namespace"))
return axis_namespace;
break;
case 'p':
if (name == PUGIXML_TEXT("parent"))
return axis_parent;
else if (name == PUGIXML_TEXT("preceding"))
return axis_preceding;
else if (name == PUGIXML_TEXT("preceding-sibling"))
return axis_preceding_sibling;
break;
case 's':
if (name == PUGIXML_TEXT("self"))
return axis_self;
break;
default:
break;
}
specified = false;
return axis_child;
}
nodetest_t parse_node_test_type(const xpath_lexer_string& name)
{
switch (name.begin[0])
{
case 'c':
if (name == PUGIXML_TEXT("comment"))
return nodetest_type_comment;
break;
case 'n':
if (name == PUGIXML_TEXT("node"))
return nodetest_type_node;
break;
case 'p':
if (name == PUGIXML_TEXT("processing-instruction"))
return nodetest_type_pi;
break;
case 't':
if (name == PUGIXML_TEXT("text"))
return nodetest_type_text;
break;
default:
break;
}
return nodetest_none;
}
// PrimaryExpr ::= VariableReference | '(' Expr ')' | Literal | Number | FunctionCall
xpath_ast_node* parse_primary_expression()
{
switch (_lexer.current())
{
case lex_var_ref:
{
xpath_lexer_string name = _lexer.contents();
if (!_variables)
return error("Unknown variable: variable set is not provided");
xpath_variable* var = 0;
if (!get_variable_scratch(_scratch, _variables, name.begin, name.end, &var))
return error_oom();
if (!var)
return error("Unknown variable: variable set does not contain the given name");
_lexer.next();
return alloc_node(ast_variable, var->type(), var);
}
case lex_open_brace:
{
_lexer.next();
xpath_ast_node* n = parse_expression();
if (!n) return 0;
if (_lexer.current() != lex_close_brace)
return error("Expected ')' to match an opening '('");
_lexer.next();
return n;
}
case lex_quoted_string:
{
const char_t* value = alloc_string(_lexer.contents());
if (!value) return 0;
_lexer.next();
return alloc_node(ast_string_constant, xpath_type_string, value);
}
case lex_number:
{
double value = 0;
if (!convert_string_to_number_scratch(_scratch, _lexer.contents().begin, _lexer.contents().end, &value))
return error_oom();
_lexer.next();
return alloc_node(ast_number_constant, xpath_type_number, value);
}
case lex_string:
{
xpath_ast_node* args[2] = {0};
size_t argc = 0;
xpath_lexer_string function = _lexer.contents();
_lexer.next();
xpath_ast_node* last_arg = 0;
if (_lexer.current() != lex_open_brace)
return error("Unrecognized function call");
_lexer.next();
size_t old_depth = _depth;
while (_lexer.current() != lex_close_brace)
{
if (argc > 0)
{
if (_lexer.current() != lex_comma)
return error("No comma between function arguments");
_lexer.next();
}
if (++_depth > xpath_ast_depth_limit)
return error_rec();
xpath_ast_node* n = parse_expression();
if (!n) return 0;
if (argc < 2) args[argc] = n;
else last_arg->set_next(n);
argc++;
last_arg = n;
}
_lexer.next();
_depth = old_depth;
return parse_function(function, argc, args);
}
default:
return error("Unrecognizable primary expression");
}
}
// FilterExpr ::= PrimaryExpr | FilterExpr Predicate
// Predicate ::= '[' PredicateExpr ']'
// PredicateExpr ::= Expr
xpath_ast_node* parse_filter_expression()
{
xpath_ast_node* n = parse_primary_expression();
if (!n) return 0;
size_t old_depth = _depth;
while (_lexer.current() == lex_open_square_brace)
{
_lexer.next();
if (++_depth > xpath_ast_depth_limit)
return error_rec();
if (n->rettype() != xpath_type_node_set)
return error("Predicate has to be applied to node set");
xpath_ast_node* expr = parse_expression();
if (!expr) return 0;
n = alloc_node(ast_filter, n, expr, predicate_default);
if (!n) return 0;
if (_lexer.current() != lex_close_square_brace)
return error("Expected ']' to match an opening '['");
_lexer.next();
}
_depth = old_depth;
return n;
}
// Step ::= AxisSpecifier NodeTest Predicate* | AbbreviatedStep
// AxisSpecifier ::= AxisName '::' | '@'?
// NodeTest ::= NameTest | NodeType '(' ')' | 'processing-instruction' '(' Literal ')'
// NameTest ::= '*' | NCName ':' '*' | QName
// AbbreviatedStep ::= '.' | '..'
xpath_ast_node* parse_step(xpath_ast_node* set)
{
if (set && set->rettype() != xpath_type_node_set)
return error("Step has to be applied to node set");
bool axis_specified = false;
axis_t axis = axis_child; // implied child axis
if (_lexer.current() == lex_axis_attribute)
{
axis = axis_attribute;
axis_specified = true;
_lexer.next();
}
else if (_lexer.current() == lex_dot)
{
_lexer.next();
if (_lexer.current() == lex_open_square_brace)
return error("Predicates are not allowed after an abbreviated step");
return alloc_node(ast_step, set, axis_self, nodetest_type_node, 0);
}
else if (_lexer.current() == lex_double_dot)
{
_lexer.next();
if (_lexer.current() == lex_open_square_brace)
return error("Predicates are not allowed after an abbreviated step");
return alloc_node(ast_step, set, axis_parent, nodetest_type_node, 0);
}
nodetest_t nt_type = nodetest_none;
xpath_lexer_string nt_name;
if (_lexer.current() == lex_string)
{
// node name test
nt_name = _lexer.contents();
_lexer.next();
// was it an axis name?
if (_lexer.current() == lex_double_colon)
{
// parse axis name
if (axis_specified)
return error("Two axis specifiers in one step");
axis = parse_axis_name(nt_name, axis_specified);
if (!axis_specified)
return error("Unknown axis");
// read actual node test
_lexer.next();
if (_lexer.current() == lex_multiply)
{
nt_type = nodetest_all;
nt_name = xpath_lexer_string();
_lexer.next();
}
else if (_lexer.current() == lex_string)
{
nt_name = _lexer.contents();
_lexer.next();
}
else
{
return error("Unrecognized node test");
}
}
if (nt_type == nodetest_none)
{
// node type test or processing-instruction
if (_lexer.current() == lex_open_brace)
{
_lexer.next();
if (_lexer.current() == lex_close_brace)
{
_lexer.next();
nt_type = parse_node_test_type(nt_name);
if (nt_type == nodetest_none)
return error("Unrecognized node type");
nt_name = xpath_lexer_string();
}
else if (nt_name == PUGIXML_TEXT("processing-instruction"))
{
if (_lexer.current() != lex_quoted_string)
return error("Only literals are allowed as arguments to processing-instruction()");
nt_type = nodetest_pi;
nt_name = _lexer.contents();
_lexer.next();
if (_lexer.current() != lex_close_brace)
return error("Unmatched brace near processing-instruction()");
_lexer.next();
}
else
{
return error("Unmatched brace near node type test");
}
}
// QName or NCName:*
else
{
if (nt_name.end - nt_name.begin > 2 && nt_name.end[-2] == ':' && nt_name.end[-1] == '*') // NCName:*
{
nt_name.end--; // erase *
nt_type = nodetest_all_in_namespace;
}
else
{
nt_type = nodetest_name;
}
}
}
}
else if (_lexer.current() == lex_multiply)
{
nt_type = nodetest_all;
_lexer.next();
}
else
{
return error("Unrecognized node test");
}
const char_t* nt_name_copy = alloc_string(nt_name);
if (!nt_name_copy) return 0;
xpath_ast_node* n = alloc_node(ast_step, set, axis, nt_type, nt_name_copy);
if (!n) return 0;
size_t old_depth = _depth;
xpath_ast_node* last = 0;
while (_lexer.current() == lex_open_square_brace)
{
_lexer.next();
if (++_depth > xpath_ast_depth_limit)
return error_rec();
xpath_ast_node* expr = parse_expression();
if (!expr) return 0;
xpath_ast_node* pred = alloc_node(ast_predicate, 0, expr, predicate_default);
if (!pred) return 0;
if (_lexer.current() != lex_close_square_brace)
return error("Expected ']' to match an opening '['");
_lexer.next();
if (last) last->set_next(pred);
else n->set_right(pred);
last = pred;
}
_depth = old_depth;
return n;
}
// RelativeLocationPath ::= Step | RelativeLocationPath '/' Step | RelativeLocationPath '//' Step
xpath_ast_node* parse_relative_location_path(xpath_ast_node* set)
{
xpath_ast_node* n = parse_step(set);
if (!n) return 0;
size_t old_depth = _depth;
while (_lexer.current() == lex_slash || _lexer.current() == lex_double_slash)
{
lexeme_t l = _lexer.current();
_lexer.next();
if (++_depth > xpath_ast_depth_limit)
return error_rec();
if (l == lex_double_slash)
{
n = alloc_node(ast_step, n, axis_descendant_or_self, nodetest_type_node, 0);
if (!n) return 0;
}
n = parse_step(n);
if (!n) return 0;
}
_depth = old_depth;
return n;
}
// LocationPath ::= RelativeLocationPath | AbsoluteLocationPath
// AbsoluteLocationPath ::= '/' RelativeLocationPath? | '//' RelativeLocationPath
xpath_ast_node* parse_location_path()
{
if (_lexer.current() == lex_slash)
{
_lexer.next();
xpath_ast_node* n = alloc_node(ast_step_root, xpath_type_node_set);
if (!n) return 0;
// relative location path can start from axis_attribute, dot, double_dot, multiply and string lexemes; any other lexeme means standalone root path
lexeme_t l = _lexer.current();
if (l == lex_string || l == lex_axis_attribute || l == lex_dot || l == lex_double_dot || l == lex_multiply)
return parse_relative_location_path(n);
else
return n;
}
else if (_lexer.current() == lex_double_slash)
{
_lexer.next();
xpath_ast_node* n = alloc_node(ast_step_root, xpath_type_node_set);
if (!n) return 0;
n = alloc_node(ast_step, n, axis_descendant_or_self, nodetest_type_node, 0);
if (!n) return 0;
return parse_relative_location_path(n);
}
// else clause moved outside of if because of bogus warning 'control may reach end of non-void function being inlined' in gcc 4.0.1
return parse_relative_location_path(0);
}
// PathExpr ::= LocationPath
// | FilterExpr
// | FilterExpr '/' RelativeLocationPath
// | FilterExpr '//' RelativeLocationPath
// UnionExpr ::= PathExpr | UnionExpr '|' PathExpr
// UnaryExpr ::= UnionExpr | '-' UnaryExpr
xpath_ast_node* parse_path_or_unary_expression()
{
// Clarification.
// PathExpr begins with either LocationPath or FilterExpr.
// FilterExpr begins with PrimaryExpr
// PrimaryExpr begins with '$' in case of it being a variable reference,
// '(' in case of it being an expression, string literal, number constant or
// function call.
if (_lexer.current() == lex_var_ref || _lexer.current() == lex_open_brace ||
_lexer.current() == lex_quoted_string || _lexer.current() == lex_number ||
_lexer.current() == lex_string)
{
if (_lexer.current() == lex_string)
{
// This is either a function call, or not - if not, we shall proceed with location path
const char_t* state = _lexer.state();
while (PUGI__IS_CHARTYPE(*state, ct_space)) ++state;
if (*state != '(')
return parse_location_path();
// This looks like a function call; however this still can be a node-test. Check it.
if (parse_node_test_type(_lexer.contents()) != nodetest_none)
return parse_location_path();
}
xpath_ast_node* n = parse_filter_expression();
if (!n) return 0;
if (_lexer.current() == lex_slash || _lexer.current() == lex_double_slash)
{
lexeme_t l = _lexer.current();
_lexer.next();
if (l == lex_double_slash)
{
if (n->rettype() != xpath_type_node_set)
return error("Step has to be applied to node set");
n = alloc_node(ast_step, n, axis_descendant_or_self, nodetest_type_node, 0);
if (!n) return 0;
}
// select from location path
return parse_relative_location_path(n);
}
return n;
}
else if (_lexer.current() == lex_minus)
{
_lexer.next();
// precedence 7+ - only parses union expressions
xpath_ast_node* n = parse_expression(7);
if (!n) return 0;
return alloc_node(ast_op_negate, xpath_type_number, n);
}
else
{
return parse_location_path();
}
}
struct binary_op_t
{
ast_type_t asttype;
xpath_value_type rettype;
int precedence;
binary_op_t(): asttype(ast_unknown), rettype(xpath_type_none), precedence(0)
{
}
binary_op_t(ast_type_t asttype_, xpath_value_type rettype_, int precedence_): asttype(asttype_), rettype(rettype_), precedence(precedence_)
{
}
static binary_op_t parse(xpath_lexer& lexer)
{
switch (lexer.current())
{
case lex_string:
if (lexer.contents() == PUGIXML_TEXT("or"))
return binary_op_t(ast_op_or, xpath_type_boolean, 1);
else if (lexer.contents() == PUGIXML_TEXT("and"))
return binary_op_t(ast_op_and, xpath_type_boolean, 2);
else if (lexer.contents() == PUGIXML_TEXT("div"))
return binary_op_t(ast_op_divide, xpath_type_number, 6);
else if (lexer.contents() == PUGIXML_TEXT("mod"))
return binary_op_t(ast_op_mod, xpath_type_number, 6);
else
return binary_op_t();
case lex_equal:
return binary_op_t(ast_op_equal, xpath_type_boolean, 3);
case lex_not_equal:
return binary_op_t(ast_op_not_equal, xpath_type_boolean, 3);
case lex_less:
return binary_op_t(ast_op_less, xpath_type_boolean, 4);
case lex_greater:
return binary_op_t(ast_op_greater, xpath_type_boolean, 4);
case lex_less_or_equal:
return binary_op_t(ast_op_less_or_equal, xpath_type_boolean, 4);
case lex_greater_or_equal:
return binary_op_t(ast_op_greater_or_equal, xpath_type_boolean, 4);
case lex_plus:
return binary_op_t(ast_op_add, xpath_type_number, 5);
case lex_minus:
return binary_op_t(ast_op_subtract, xpath_type_number, 5);
case lex_multiply:
return binary_op_t(ast_op_multiply, xpath_type_number, 6);
case lex_union:
return binary_op_t(ast_op_union, xpath_type_node_set, 7);
default:
return binary_op_t();
}
}
};
xpath_ast_node* parse_expression_rec(xpath_ast_node* lhs, int limit)
{
binary_op_t op = binary_op_t::parse(_lexer);
while (op.asttype != ast_unknown && op.precedence >= limit)
{
_lexer.next();
if (++_depth > xpath_ast_depth_limit)
return error_rec();
xpath_ast_node* rhs = parse_path_or_unary_expression();
if (!rhs) return 0;
binary_op_t nextop = binary_op_t::parse(_lexer);
while (nextop.asttype != ast_unknown && nextop.precedence > op.precedence)
{
rhs = parse_expression_rec(rhs, nextop.precedence);
if (!rhs) return 0;
nextop = binary_op_t::parse(_lexer);
}
if (op.asttype == ast_op_union && (lhs->rettype() != xpath_type_node_set || rhs->rettype() != xpath_type_node_set))
return error("Union operator has to be applied to node sets");
lhs = alloc_node(op.asttype, op.rettype, lhs, rhs);
if (!lhs) return 0;
op = binary_op_t::parse(_lexer);
}
return lhs;
}
// Expr ::= OrExpr
// OrExpr ::= AndExpr | OrExpr 'or' AndExpr
// AndExpr ::= EqualityExpr | AndExpr 'and' EqualityExpr
// EqualityExpr ::= RelationalExpr
// | EqualityExpr '=' RelationalExpr
// | EqualityExpr '!=' RelationalExpr
// RelationalExpr ::= AdditiveExpr
// | RelationalExpr '<' AdditiveExpr
// | RelationalExpr '>' AdditiveExpr
// | RelationalExpr '<=' AdditiveExpr
// | RelationalExpr '>=' AdditiveExpr
// AdditiveExpr ::= MultiplicativeExpr
// | AdditiveExpr '+' MultiplicativeExpr
// | AdditiveExpr '-' MultiplicativeExpr
// MultiplicativeExpr ::= UnaryExpr
// | MultiplicativeExpr '*' UnaryExpr
// | MultiplicativeExpr 'div' UnaryExpr
// | MultiplicativeExpr 'mod' UnaryExpr
xpath_ast_node* parse_expression(int limit = 0)
{
size_t old_depth = _depth;
if (++_depth > xpath_ast_depth_limit)
return error_rec();
xpath_ast_node* n = parse_path_or_unary_expression();
if (!n) return 0;
n = parse_expression_rec(n, limit);
_depth = old_depth;
return n;
}
xpath_parser(const char_t* query, xpath_variable_set* variables, xpath_allocator* alloc, xpath_parse_result* result): _alloc(alloc), _lexer(query), _query(query), _variables(variables), _result(result), _depth(0)
{
}
xpath_ast_node* parse()
{
xpath_ast_node* n = parse_expression();
if (!n) return 0;
assert(_depth == 0);
// check if there are unparsed tokens left
if (_lexer.current() != lex_eof)
return error("Incorrect query");
return n;
}
static xpath_ast_node* parse(const char_t* query, xpath_variable_set* variables, xpath_allocator* alloc, xpath_parse_result* result)
{
xpath_parser parser(query, variables, alloc, result);
return parser.parse();
}
};
struct xpath_query_impl
{
static xpath_query_impl* create()
{
void* memory = xml_memory::allocate(sizeof(xpath_query_impl));
if (!memory) return 0;
return new (memory) xpath_query_impl();
}
static void destroy(xpath_query_impl* impl)
{
// free all allocated pages
impl->alloc.release();
// free allocator memory (with the first page)
xml_memory::deallocate(impl);
}
xpath_query_impl(): root(0), alloc(&block, &oom), oom(false)
{
block.next = 0;
block.capacity = sizeof(block.data);
}
xpath_ast_node* root;
xpath_allocator alloc;
xpath_memory_block block;
bool oom;
};
PUGI__FN impl::xpath_ast_node* evaluate_node_set_prepare(xpath_query_impl* impl)
{
if (!impl) return 0;
if (impl->root->rettype() != xpath_type_node_set)
{
#ifdef PUGIXML_NO_EXCEPTIONS
return 0;
#else
xpath_parse_result res;
res.error = "Expression does not evaluate to node set";
throw xpath_exception(res);
#endif
}
return impl->root;
}
PUGI__NS_END
namespace pugi
{
#ifndef PUGIXML_NO_EXCEPTIONS
PUGI__FN xpath_exception::xpath_exception(const xpath_parse_result& result_): _result(result_)
{
assert(_result.error);
}
PUGI__FN const char* xpath_exception::what() const throw()
{
return _result.error;
}
PUGI__FN const xpath_parse_result& xpath_exception::result() const
{
return _result;
}
#endif
PUGI__FN xpath_node::xpath_node()
{
}
PUGI__FN xpath_node::xpath_node(const xml_node& node_): _node(node_)
{
}
PUGI__FN xpath_node::xpath_node(const xml_attribute& attribute_, const xml_node& parent_): _node(attribute_ ? parent_ : xml_node()), _attribute(attribute_)
{
}
PUGI__FN xml_node xpath_node::node() const
{
return _attribute ? xml_node() : _node;
}
PUGI__FN xml_attribute xpath_node::attribute() const
{
return _attribute;
}
PUGI__FN xml_node xpath_node::parent() const
{
return _attribute ? _node : _node.parent();
}
PUGI__FN static void unspecified_bool_xpath_node(xpath_node***)
{
}
PUGI__FN xpath_node::operator xpath_node::unspecified_bool_type() const
{
return (_node || _attribute) ? unspecified_bool_xpath_node : 0;
}
PUGI__FN bool xpath_node::operator!() const
{
return !(_node || _attribute);
}
PUGI__FN bool xpath_node::operator==(const xpath_node& n) const
{
return _node == n._node && _attribute == n._attribute;
}
PUGI__FN bool xpath_node::operator!=(const xpath_node& n) const
{
return _node != n._node || _attribute != n._attribute;
}
#ifdef __BORLANDC__
PUGI__FN bool operator&&(const xpath_node& lhs, bool rhs)
{
return (bool)lhs && rhs;
}
PUGI__FN bool operator||(const xpath_node& lhs, bool rhs)
{
return (bool)lhs || rhs;
}
#endif
PUGI__FN void xpath_node_set::_assign(const_iterator begin_, const_iterator end_, type_t type_)
{
assert(begin_ <= end_);
size_t size_ = static_cast<size_t>(end_ - begin_);
// use internal buffer for 0 or 1 elements, heap buffer otherwise
xpath_node* storage = (size_ <= 1) ? _storage : static_cast<xpath_node*>(impl::xml_memory::allocate(size_ * sizeof(xpath_node)));
if (!storage)
{
#ifdef PUGIXML_NO_EXCEPTIONS
return;
#else
throw std::bad_alloc();
#endif
}
// deallocate old buffer
if (_begin != _storage)
impl::xml_memory::deallocate(_begin);
// size check is necessary because for begin_ = end_ = nullptr, memcpy is UB
if (size_)
memcpy(storage, begin_, size_ * sizeof(xpath_node));
_begin = storage;
_end = storage + size_;
_type = type_;
}
#ifdef PUGIXML_HAS_MOVE
PUGI__FN void xpath_node_set::_move(xpath_node_set& rhs) PUGIXML_NOEXCEPT
{
_type = rhs._type;
_storage[0] = rhs._storage[0];
_begin = (rhs._begin == rhs._storage) ? _storage : rhs._begin;
_end = _begin + (rhs._end - rhs._begin);
rhs._type = type_unsorted;
rhs._begin = rhs._storage;
rhs._end = rhs._storage;
}
#endif
PUGI__FN xpath_node_set::xpath_node_set(): _type(type_unsorted), _begin(_storage), _end(_storage)
{
}
PUGI__FN xpath_node_set::xpath_node_set(const_iterator begin_, const_iterator end_, type_t type_): _type(type_unsorted), _begin(_storage), _end(_storage)
{
_assign(begin_, end_, type_);
}
PUGI__FN xpath_node_set::~xpath_node_set()
{
if (_begin != _storage)
impl::xml_memory::deallocate(_begin);
}
PUGI__FN xpath_node_set::xpath_node_set(const xpath_node_set& ns): _type(type_unsorted), _begin(_storage), _end(_storage)
{
_assign(ns._begin, ns._end, ns._type);
}
PUGI__FN xpath_node_set& xpath_node_set::operator=(const xpath_node_set& ns)
{
if (this == &ns) return *this;
_assign(ns._begin, ns._end, ns._type);
return *this;
}
#ifdef PUGIXML_HAS_MOVE
PUGI__FN xpath_node_set::xpath_node_set(xpath_node_set&& rhs) PUGIXML_NOEXCEPT: _type(type_unsorted), _begin(_storage), _end(_storage)
{
_move(rhs);
}
PUGI__FN xpath_node_set& xpath_node_set::operator=(xpath_node_set&& rhs) PUGIXML_NOEXCEPT
{
if (this == &rhs) return *this;
if (_begin != _storage)
impl::xml_memory::deallocate(_begin);
_move(rhs);
return *this;
}
#endif
PUGI__FN xpath_node_set::type_t xpath_node_set::type() const
{
return _type;
}
PUGI__FN size_t xpath_node_set::size() const
{
return _end - _begin;
}
PUGI__FN bool xpath_node_set::empty() const
{
return _begin == _end;
}
PUGI__FN const xpath_node& xpath_node_set::operator[](size_t index) const
{
assert(index < size());
return _begin[index];
}
PUGI__FN xpath_node_set::const_iterator xpath_node_set::begin() const
{
return _begin;
}
PUGI__FN xpath_node_set::const_iterator xpath_node_set::end() const
{
return _end;
}
PUGI__FN void xpath_node_set::sort(bool reverse)
{
_type = impl::xpath_sort(_begin, _end, _type, reverse);
}
PUGI__FN xpath_node xpath_node_set::first() const
{
return impl::xpath_first(_begin, _end, _type);
}
PUGI__FN xpath_parse_result::xpath_parse_result(): error("Internal error"), offset(0)
{
}
PUGI__FN xpath_parse_result::operator bool() const
{
return error == 0;
}
PUGI__FN const char* xpath_parse_result::description() const
{
return error ? error : "No error";
}
PUGI__FN xpath_variable::xpath_variable(xpath_value_type type_): _type(type_), _next(0)
{
}
PUGI__FN const char_t* xpath_variable::name() const
{
switch (_type)
{
case xpath_type_node_set:
return static_cast<const impl::xpath_variable_node_set*>(this)->name;
case xpath_type_number:
return static_cast<const impl::xpath_variable_number*>(this)->name;
case xpath_type_string:
return static_cast<const impl::xpath_variable_string*>(this)->name;
case xpath_type_boolean:
return static_cast<const impl::xpath_variable_boolean*>(this)->name;
default:
assert(false && "Invalid variable type"); // unreachable
return 0;
}
}
PUGI__FN xpath_value_type xpath_variable::type() const
{
return _type;
}
PUGI__FN bool xpath_variable::get_boolean() const
{
return (_type == xpath_type_boolean) ? static_cast<const impl::xpath_variable_boolean*>(this)->value : false;
}
PUGI__FN double xpath_variable::get_number() const
{
return (_type == xpath_type_number) ? static_cast<const impl::xpath_variable_number*>(this)->value : impl::gen_nan();
}
PUGI__FN const char_t* xpath_variable::get_string() const
{
const char_t* value = (_type == xpath_type_string) ? static_cast<const impl::xpath_variable_string*>(this)->value : 0;
return value ? value : PUGIXML_TEXT("");
}
PUGI__FN const xpath_node_set& xpath_variable::get_node_set() const
{
return (_type == xpath_type_node_set) ? static_cast<const impl::xpath_variable_node_set*>(this)->value : impl::dummy_node_set;
}
PUGI__FN bool xpath_variable::set(bool value)
{
if (_type != xpath_type_boolean) return false;
static_cast<impl::xpath_variable_boolean*>(this)->value = value;
return true;
}
PUGI__FN bool xpath_variable::set(double value)
{
if (_type != xpath_type_number) return false;
static_cast<impl::xpath_variable_number*>(this)->value = value;
return true;
}
PUGI__FN bool xpath_variable::set(const char_t* value)
{
if (_type != xpath_type_string) return false;
impl::xpath_variable_string* var = static_cast<impl::xpath_variable_string*>(this);
// duplicate string
size_t size = (impl::strlength(value) + 1) * sizeof(char_t);
char_t* copy = static_cast<char_t*>(impl::xml_memory::allocate(size));
if (!copy) return false;
memcpy(copy, value, size);
// replace old string
if (var->value) impl::xml_memory::deallocate(var->value);
var->value = copy;
return true;
}
PUGI__FN bool xpath_variable::set(const xpath_node_set& value)
{
if (_type != xpath_type_node_set) return false;
static_cast<impl::xpath_variable_node_set*>(this)->value = value;
return true;
}
PUGI__FN xpath_variable_set::xpath_variable_set()
{
for (size_t i = 0; i < sizeof(_data) / sizeof(_data[0]); ++i)
_data[i] = 0;
}
PUGI__FN xpath_variable_set::~xpath_variable_set()
{
for (size_t i = 0; i < sizeof(_data) / sizeof(_data[0]); ++i)
_destroy(_data[i]);
}
PUGI__FN xpath_variable_set::xpath_variable_set(const xpath_variable_set& rhs)
{
for (size_t i = 0; i < sizeof(_data) / sizeof(_data[0]); ++i)
_data[i] = 0;
_assign(rhs);
}
PUGI__FN xpath_variable_set& xpath_variable_set::operator=(const xpath_variable_set& rhs)
{
if (this == &rhs) return *this;
_assign(rhs);
return *this;
}
#ifdef PUGIXML_HAS_MOVE
PUGI__FN xpath_variable_set::xpath_variable_set(xpath_variable_set&& rhs) PUGIXML_NOEXCEPT
{
for (size_t i = 0; i < sizeof(_data) / sizeof(_data[0]); ++i)
{
_data[i] = rhs._data[i];
rhs._data[i] = 0;
}
}
PUGI__FN xpath_variable_set& xpath_variable_set::operator=(xpath_variable_set&& rhs) PUGIXML_NOEXCEPT
{
for (size_t i = 0; i < sizeof(_data) / sizeof(_data[0]); ++i)
{
_destroy(_data[i]);
_data[i] = rhs._data[i];
rhs._data[i] = 0;
}
return *this;
}
#endif
PUGI__FN void xpath_variable_set::_assign(const xpath_variable_set& rhs)
{
xpath_variable_set temp;
for (size_t i = 0; i < sizeof(_data) / sizeof(_data[0]); ++i)
if (rhs._data[i] && !_clone(rhs._data[i], &temp._data[i]))
return;
_swap(temp);
}
PUGI__FN void xpath_variable_set::_swap(xpath_variable_set& rhs)
{
for (size_t i = 0; i < sizeof(_data) / sizeof(_data[0]); ++i)
{
xpath_variable* chain = _data[i];
_data[i] = rhs._data[i];
rhs._data[i] = chain;
}
}
PUGI__FN xpath_variable* xpath_variable_set::_find(const char_t* name) const
{
const size_t hash_size = sizeof(_data) / sizeof(_data[0]);
size_t hash = impl::hash_string(name) % hash_size;
// look for existing variable
for (xpath_variable* var = _data[hash]; var; var = var->_next)
if (impl::strequal(var->name(), name))
return var;
return 0;
}
PUGI__FN bool xpath_variable_set::_clone(xpath_variable* var, xpath_variable** out_result)
{
xpath_variable* last = 0;
while (var)
{
// allocate storage for new variable
xpath_variable* nvar = impl::new_xpath_variable(var->_type, var->name());
if (!nvar) return false;
// link the variable to the result immediately to handle failures gracefully
if (last)
last->_next = nvar;
else
*out_result = nvar;
last = nvar;
// copy the value; this can fail due to out-of-memory conditions
if (!impl::copy_xpath_variable(nvar, var)) return false;
var = var->_next;
}
return true;
}
PUGI__FN void xpath_variable_set::_destroy(xpath_variable* var)
{
while (var)
{
xpath_variable* next = var->_next;
impl::delete_xpath_variable(var->_type, var);
var = next;
}
}
PUGI__FN xpath_variable* xpath_variable_set::add(const char_t* name, xpath_value_type type)
{
const size_t hash_size = sizeof(_data) / sizeof(_data[0]);
size_t hash = impl::hash_string(name) % hash_size;
// look for existing variable
for (xpath_variable* var = _data[hash]; var; var = var->_next)
if (impl::strequal(var->name(), name))
return var->type() == type ? var : 0;
// add new variable
xpath_variable* result = impl::new_xpath_variable(type, name);
if (result)
{
result->_next = _data[hash];
_data[hash] = result;
}
return result;
}
PUGI__FN bool xpath_variable_set::set(const char_t* name, bool value)
{
xpath_variable* var = add(name, xpath_type_boolean);
return var ? var->set(value) : false;
}
PUGI__FN bool xpath_variable_set::set(const char_t* name, double value)
{
xpath_variable* var = add(name, xpath_type_number);
return var ? var->set(value) : false;
}
PUGI__FN bool xpath_variable_set::set(const char_t* name, const char_t* value)
{
xpath_variable* var = add(name, xpath_type_string);
return var ? var->set(value) : false;
}
PUGI__FN bool xpath_variable_set::set(const char_t* name, const xpath_node_set& value)
{
xpath_variable* var = add(name, xpath_type_node_set);
return var ? var->set(value) : false;
}
PUGI__FN xpath_variable* xpath_variable_set::get(const char_t* name)
{
return _find(name);
}
PUGI__FN const xpath_variable* xpath_variable_set::get(const char_t* name) const
{
return _find(name);
}
PUGI__FN xpath_query::xpath_query(const char_t* query, xpath_variable_set* variables): _impl(0)
{
impl::xpath_query_impl* qimpl = impl::xpath_query_impl::create();
if (!qimpl)
{
#ifdef PUGIXML_NO_EXCEPTIONS
_result.error = "Out of memory";
#else
throw std::bad_alloc();
#endif
}
else
{
using impl::auto_deleter; // MSVC7 workaround
auto_deleter<impl::xpath_query_impl> impl(qimpl, impl::xpath_query_impl::destroy);
qimpl->root = impl::xpath_parser::parse(query, variables, &qimpl->alloc, &_result);
if (qimpl->root)
{
qimpl->root->optimize(&qimpl->alloc);
_impl = impl.release();
_result.error = 0;
}
else
{
#ifdef PUGIXML_NO_EXCEPTIONS
if (qimpl->oom) _result.error = "Out of memory";
#else
if (qimpl->oom) throw std::bad_alloc();
throw xpath_exception(_result);
#endif
}
}
}
PUGI__FN xpath_query::xpath_query(): _impl(0)
{
}
PUGI__FN xpath_query::~xpath_query()
{
if (_impl)
impl::xpath_query_impl::destroy(static_cast<impl::xpath_query_impl*>(_impl));
}
#ifdef PUGIXML_HAS_MOVE
PUGI__FN xpath_query::xpath_query(xpath_query&& rhs) PUGIXML_NOEXCEPT
{
_impl = rhs._impl;
_result = rhs._result;
rhs._impl = 0;
rhs._result = xpath_parse_result();
}
PUGI__FN xpath_query& xpath_query::operator=(xpath_query&& rhs) PUGIXML_NOEXCEPT
{
if (this == &rhs) return *this;
if (_impl)
impl::xpath_query_impl::destroy(static_cast<impl::xpath_query_impl*>(_impl));
_impl = rhs._impl;
_result = rhs._result;
rhs._impl = 0;
rhs._result = xpath_parse_result();
return *this;
}
#endif
PUGI__FN xpath_value_type xpath_query::return_type() const
{
if (!_impl) return xpath_type_none;
return static_cast<impl::xpath_query_impl*>(_impl)->root->rettype();
}
PUGI__FN bool xpath_query::evaluate_boolean(const xpath_node& n) const
{
if (!_impl) return false;
impl::xpath_context c(n, 1, 1);
impl::xpath_stack_data sd;
bool r = static_cast<impl::xpath_query_impl*>(_impl)->root->eval_boolean(c, sd.stack);
if (sd.oom)
{
#ifdef PUGIXML_NO_EXCEPTIONS
return false;
#else
throw std::bad_alloc();
#endif
}
return r;
}
PUGI__FN double xpath_query::evaluate_number(const xpath_node& n) const
{
if (!_impl) return impl::gen_nan();
impl::xpath_context c(n, 1, 1);
impl::xpath_stack_data sd;
double r = static_cast<impl::xpath_query_impl*>(_impl)->root->eval_number(c, sd.stack);
if (sd.oom)
{
#ifdef PUGIXML_NO_EXCEPTIONS
return impl::gen_nan();
#else
throw std::bad_alloc();
#endif
}
return r;
}
#ifndef PUGIXML_NO_STL
PUGI__FN string_t xpath_query::evaluate_string(const xpath_node& n) const
{
if (!_impl) return string_t();
impl::xpath_context c(n, 1, 1);
impl::xpath_stack_data sd;
impl::xpath_string r = static_cast<impl::xpath_query_impl*>(_impl)->root->eval_string(c, sd.stack);
if (sd.oom)
{
#ifdef PUGIXML_NO_EXCEPTIONS
return string_t();
#else
throw std::bad_alloc();
#endif
}
return string_t(r.c_str(), r.length());
}
#endif
PUGI__FN size_t xpath_query::evaluate_string(char_t* buffer, size_t capacity, const xpath_node& n) const
{
impl::xpath_context c(n, 1, 1);
impl::xpath_stack_data sd;
impl::xpath_string r = _impl ? static_cast<impl::xpath_query_impl*>(_impl)->root->eval_string(c, sd.stack) : impl::xpath_string();
if (sd.oom)
{
#ifdef PUGIXML_NO_EXCEPTIONS
r = impl::xpath_string();
#else
throw std::bad_alloc();
#endif
}
size_t full_size = r.length() + 1;
if (capacity > 0)
{
size_t size = (full_size < capacity) ? full_size : capacity;
assert(size > 0);
memcpy(buffer, r.c_str(), (size - 1) * sizeof(char_t));
buffer[size - 1] = 0;
}
return full_size;
}
PUGI__FN xpath_node_set xpath_query::evaluate_node_set(const xpath_node& n) const
{
impl::xpath_ast_node* root = impl::evaluate_node_set_prepare(static_cast<impl::xpath_query_impl*>(_impl));
if (!root) return xpath_node_set();
impl::xpath_context c(n, 1, 1);
impl::xpath_stack_data sd;
impl::xpath_node_set_raw r = root->eval_node_set(c, sd.stack, impl::nodeset_eval_all);
if (sd.oom)
{
#ifdef PUGIXML_NO_EXCEPTIONS
return xpath_node_set();
#else
throw std::bad_alloc();
#endif
}
return xpath_node_set(r.begin(), r.end(), r.type());
}
PUGI__FN xpath_node xpath_query::evaluate_node(const xpath_node& n) const
{
impl::xpath_ast_node* root = impl::evaluate_node_set_prepare(static_cast<impl::xpath_query_impl*>(_impl));
if (!root) return xpath_node();
impl::xpath_context c(n, 1, 1);
impl::xpath_stack_data sd;
impl::xpath_node_set_raw r = root->eval_node_set(c, sd.stack, impl::nodeset_eval_first);
if (sd.oom)
{
#ifdef PUGIXML_NO_EXCEPTIONS
return xpath_node();
#else
throw std::bad_alloc();
#endif
}
return r.first();
}
PUGI__FN const xpath_parse_result& xpath_query::result() const
{
return _result;
}
PUGI__FN static void unspecified_bool_xpath_query(xpath_query***)
{
}
PUGI__FN xpath_query::operator xpath_query::unspecified_bool_type() const
{
return _impl ? unspecified_bool_xpath_query : 0;
}
PUGI__FN bool xpath_query::operator!() const
{
return !_impl;
}
PUGI__FN xpath_node xml_node::select_node(const char_t* query, xpath_variable_set* variables) const
{
xpath_query q(query, variables);
return q.evaluate_node(*this);
}
PUGI__FN xpath_node xml_node::select_node(const xpath_query& query) const
{
return query.evaluate_node(*this);
}
PUGI__FN xpath_node_set xml_node::select_nodes(const char_t* query, xpath_variable_set* variables) const
{
xpath_query q(query, variables);
return q.evaluate_node_set(*this);
}
PUGI__FN xpath_node_set xml_node::select_nodes(const xpath_query& query) const
{
return query.evaluate_node_set(*this);
}
PUGI__FN xpath_node xml_node::select_single_node(const char_t* query, xpath_variable_set* variables) const
{
xpath_query q(query, variables);
return q.evaluate_node(*this);
}
PUGI__FN xpath_node xml_node::select_single_node(const xpath_query& query) const
{
return query.evaluate_node(*this);
}
}
#endif
#ifdef __BORLANDC__
# pragma option pop
#endif
// Intel C++ does not properly keep warning state for function templates,
// so popping warning state at the end of translation unit leads to warnings in the middle.
#if defined(_MSC_VER) && !defined(__INTEL_COMPILER)
# pragma warning(pop)
#endif
#if defined(_MSC_VER) && defined(__c2__)
# pragma clang diagnostic pop
#endif
// Undefine all local macros (makes sure we're not leaking macros in header-only mode)
#undef PUGI__NO_INLINE
#undef PUGI__UNLIKELY
#undef PUGI__STATIC_ASSERT
#undef PUGI__DMC_VOLATILE
#undef PUGI__UNSIGNED_OVERFLOW
#undef PUGI__MSVC_CRT_VERSION
#undef PUGI__SNPRINTF
#undef PUGI__NS_BEGIN
#undef PUGI__NS_END
#undef PUGI__FN
#undef PUGI__FN_NO_INLINE
#undef PUGI__GETHEADER_IMPL
#undef PUGI__GETPAGE_IMPL
#undef PUGI__GETPAGE
#undef PUGI__NODETYPE
#undef PUGI__IS_CHARTYPE_IMPL
#undef PUGI__IS_CHARTYPE
#undef PUGI__IS_CHARTYPEX
#undef PUGI__ENDSWITH
#undef PUGI__SKIPWS
#undef PUGI__OPTSET
#undef PUGI__PUSHNODE
#undef PUGI__POPNODE
#undef PUGI__SCANFOR
#undef PUGI__SCANWHILE
#undef PUGI__SCANWHILE_UNROLL
#undef PUGI__ENDSEG
#undef PUGI__THROW_ERROR
#undef PUGI__CHECK_ERROR
#endif
/**
* Copyright (c) 2006-2020 Arseny Kapoulkine
*
* 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.
*/
| [
"georgiyshulyak@gmail.com"
] | georgiyshulyak@gmail.com |
3d09b9abed1f289ea3c58c6a8399285fad7b467d | 4e686b6c01e3f9eb74f4707a344e915521cf6ba8 | /c++/stl/4030/ecourse_stl.hpp | ac8381d408d6839221fbbbdf0af99fb8ef7b5030 | [] | no_license | venesus86/awesome | 5c93ebccd750b920868936ff45e1780320edf7b5 | e82c08a8f022eca82d6b55e214ea619fd31ed1d9 | refs/heads/master | 2022-11-29T20:29:18.389990 | 2020-08-06T15:19:26 | 2020-08-06T15:19:26 | 236,432,995 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,442 | hpp | /*
* HOME : ecourse.co.kr
* EMAIL : smkang@codenuri.co.kr
* COURSENAME : C++ STL Programming
* MODULE : ecourse_stl.hpp
* Copyright (C) 2018 CODENURI Inc. All rights reserved.
*/
#include <iostream>
#include <string>
#include <functional>
#include <chrono>
#include <iterator>
#include <algorithm>
using namespace std::literals;
class stop_watch
{
std::string message;
std::chrono::high_resolution_clock::time_point start;
public:
inline stop_watch(std::string msg = "") : message(msg) { start = std::chrono::high_resolution_clock::now(); }
inline ~stop_watch()
{
std::chrono::high_resolution_clock::time_point end =
std::chrono::high_resolution_clock::now();
std::chrono::duration<double> time_span = std::chrono::duration_cast<std::chrono::duration<double>>(end - start);
std::cout << message << " " << time_span.count()
<< " seconds." << std::endl;;
}
};
template<typename F, typename ... A>
decltype(auto) chronometry(F&& f, A&& ... args)
{
stop_watch sw;
return std::invoke(std::forward<F>(f),
std::forward<A>(args)...);
}
template<typename Container> void show(Container&& c)
{
for (const auto& n : c)
std::cout << n << ", ";
std::cout << std::endl;
}
template<typename InputIter>
void show(InputIter first, InputIter last )
{
std::copy(first, last,
std::ostream_iterator<typename std::iterator_traits<InputIter>::value_type>(std::cout, ", "));
std::cout << std::endl;
}
| [
"wjdgusx2@gmail.com"
] | wjdgusx2@gmail.com |
1efb1c435b7fb1d2dda641c14576429ae4893e58 | 2f826d31f423fd50c705c7980e86b7a440cc182c | /UIClasses/UI/srdialog.cpp | 44b91ef5b0a16b0c9382e945b476fd27c2280024 | [] | no_license | SeraphRobotics/SR-Archive | ce3e0c6a3728abbedbb221b657b1b4585de42337 | 7bb44c4b5b6b47a0a3adb899d99d74f78f67d80d | refs/heads/master | 2021-03-27T16:12:51.628023 | 2015-06-03T20:07:59 | 2015-06-03T20:07:59 | 33,962,353 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 201 | cpp | #include "srdialog.h"
#include "ui_srdialog.h"
SRDialog::SRDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::SRDialog)
{
ui->setupUi(this);
}
SRDialog::~SRDialog()
{
delete ui;
}
| [
"jeffreyilipton@gmail.com"
] | jeffreyilipton@gmail.com |
6bd9778dea23ce65706bb6089279dd6934f717e2 | 2af943fbfff74744b29e4a899a6e62e19dc63256 | /IntelligentSI/Communication/otigtl/libs/ace/os_include/os_signal.h | 2bc2fc636fa6b8ef40146e860cefb21d67afb329 | [] | no_license | lheckemann/namic-sandbox | c308ec3ebb80021020f98cf06ee4c3e62f125ad9 | 0c7307061f58c9d915ae678b7a453876466d8bf8 | refs/heads/master | 2021-08-24T12:40:01.331229 | 2014-02-07T21:59:29 | 2014-02-07T21:59:29 | 113,701,721 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 9,132 | h | // -*- C++ -*-
//=============================================================================
/**
* @file os_signal.h
*
* signals
*
* os_signal.h,v 1.19 2006/01/03 13:01:59 jwillemsen Exp
*
* @author Don Hinton <dhinton@dresystems.com>
* @author This code was originally in various places including ace/OS.h.
*/
//=============================================================================
#ifndef ACE_OS_INCLUDE_OS_SIGNAL_H
#define ACE_OS_INCLUDE_OS_SIGNAL_H
#include /**/ "ace/pre.h"
#include "ace/config-lite.h"
#if !defined (ACE_LACKS_PRAGMA_ONCE)
# pragma once
#endif /* ACE_LACKS_PRAGMA_ONCE */
#include "ace/os_include/sys/os_types.h"
#if !defined (ACE_LACKS_SIGNAL_H)
extern "C" {
# include /**/ <signal.h>
}
#endif /* !ACE_LACKS_SIGNAL_H */
// This must come after signal.h is #included.
#if defined (SCO)
# define SIGIO SIGPOLL
# include /**/ <sys/regset.h>
#endif /* SCO */
#if defined (ACE_HAS_SIGINFO_T)
# if !defined (ACE_LACKS_SIGINFO_H)
# if defined (__QNX__) || defined (__OpenBSD__) || defined (__INTERIX)
# include /**/ <sys/siginfo.h>
# else /* __QNX__ || __OpenBSD__ */
# include /**/ <siginfo.h>
# endif /* __QNX__ || __OpenBSD__ */
# endif /* ACE_LACKS_SIGINFO_H */
#endif /* ACE_HAS_SIGINFO_T */
#if defined (ACE_VXWORKS) && (ACE_VXWORKS < 0x620) && !defined (__RTP__)
# include /**/ <sigLib.h>
#endif /* ACE_VXWORKS */
// should this be extern "C" {}?
#if defined (CHORUS)
# if !defined(CHORUS_4)
typedef void (*__sighandler_t)(int); // keep Signal compilation happy
# endif
#endif /* CHORUS */
// Place all additions (especially function declarations) within extern "C" {}
#ifdef __cplusplus
extern "C"
{
#endif /* __cplusplus */
#if defined (ACE_SIGINFO_IS_SIGINFO_T)
typedef struct siginfo siginfo_t;
#endif /* ACE_LACKS_SIGINFO_H */
#if defined (ACE_LACKS_SIGSET)
typedef u_int sigset_t;
#endif /* ACE_LACKS_SIGSET */
#if defined (ACE_HAS_SIG_MACROS)
# undef sigemptyset
# undef sigfillset
# undef sigaddset
# undef sigdelset
# undef sigismember
#endif /* ACE_HAS_SIG_MACROS */
// This must come after signal.h is #included. It's to counteract
// the sigemptyset and sigfillset #defines, which only happen
// when __OPTIMIZE__ is #defined (really!) on Linux.
#if defined (linux) && defined (__OPTIMIZE__)
# undef sigemptyset
# undef sigfillset
#endif /* linux && __OPTIMIZE__ */
#if !defined (ACE_HAS_SIG_ATOMIC_T)
typedef int sig_atomic_t;
#endif /* !ACE_HAS_SIG_ATOMIC_T */
# if !defined (SA_SIGINFO)
# define SA_SIGINFO 0
# endif /* SA_SIGINFO */
# if !defined (SA_RESTART)
# define SA_RESTART 0
# endif /* SA_RESTART */
#if !defined (SIGHUP)
# define SIGHUP 0
#endif /* SIGHUP */
#if !defined (SIGINT)
# define SIGINT 0
#endif /* SIGINT */
#if !defined (SIGSEGV)
# define SIGSEGV 0
#endif /* SIGSEGV */
#if !defined (SIGIO)
# define SIGIO 0
#endif /* SIGSEGV */
#if !defined (SIGUSR1)
# define SIGUSR1 0
#endif /* SIGUSR1 */
#if !defined (SIGUSR2)
# define SIGUSR2 0
#endif /* SIGUSR2 */
#if !defined (SIGCHLD)
# define SIGCHLD 0
#endif /* SIGCHLD */
#if !defined (SIGCLD)
# define SIGCLD SIGCHLD
#endif /* SIGCLD */
#if !defined (SIGQUIT)
# define SIGQUIT 0
#endif /* SIGQUIT */
#if !defined (SIGPIPE)
# define SIGPIPE 0
#endif /* SIGPIPE */
#if !defined (SIGALRM)
# define SIGALRM 0
#endif /* SIGALRM */
#if !defined (SIG_DFL)
# if defined (ACE_PSOS_DIAB_MIPS) || defined (ACE_PSOS_DIAB_PPC)
# define SIG_DFL ((void *) 0)
# else
# define SIG_DFL ((__sighandler_t) 0)
# endif
#endif /* SIG_DFL */
#if !defined (SIG_IGN)
# if defined (ACE_PSOS_DIAB_MIPS) || defined (ACE_PSOS_DIAB_PPC)
# define SIG_IGN ((void *) 1) /* ignore signal */
# else
# define SIG_IGN ((__sighandler_t) 1) /* ignore signal */
# endif
#endif /* SIG_IGN */
#if !defined (SIG_ERR)
# if defined (ACE_PSOS_DIAB_MIPS) || defined (ACE_PSOS_DIAB_PPC)
# define SIG_ERR ((void *) -1) /* error return from signal */
# else
# define SIG_ERR ((__sighandler_t) -1) /* error return from signal */
# endif
#endif /* SIG_ERR */
// These are used by the <ACE_IPC_SAP::enable> and
// <ACE_IPC_SAP::disable> methods. They must be unique and cannot
// conflict with the value of <ACE_NONBLOCK>. We make the numbers
// negative here so they won't conflict with other values like SIGIO,
// etc.
# define ACE_SIGIO -1
# define ACE_SIGURG -2
# define ACE_CLOEXEC -3
#if defined (ACE_PSOS)
# if !defined (ACE_PSOSIM)
typedef void (* ACE_SignalHandler) (void);
typedef void (* ACE_SignalHandlerV) (void);
# if !defined(SIG_DFL)
# define SIG_DFL (ACE_SignalHandler) 0
# endif /* philabs */
# endif /* !ACE_PSOSIM */
# if ! defined (NSIG)
# define NSIG 32
# endif /* NSIG */
#endif /* ACE_PSOS && !ACE_PSOSIM */
#if defined (VXWORKS)
# define ACE_NSIG (_NSIGS + 1)
#elif defined (__Lynx__)
// LynxOS Neutrino sets NSIG to the highest-numbered signal.
# define ACE_NSIG (NSIG + 1)
#elif defined (__rtems__)
# define ACE_NSIG (SIGRTMAX)
#elif defined(__BORLANDC__) && (__BORLANDC__ >= 0x600)
# define ACE_NSIG _NSIG
#else
// All other platforms set NSIG to one greater than the
// highest-numbered signal.
# define ACE_NSIG NSIG
#endif /* __Lynx__ */
#if defined (ACE_HAS_CONSISTENT_SIGNAL_PROTOTYPES)
// Prototypes for both signal() and struct sigaction are consistent..
//# if defined (ACE_HAS_SIG_C_FUNC)
// extern "C" {
//# endif /* ACE_HAS_SIG_C_FUNC */
# if !defined (ACE_PSOS)
typedef void (*ACE_SignalHandler)(int);
typedef void (*ACE_SignalHandlerV)(int);
# endif /* !defined (ACE_PSOS) */
//# if defined (ACE_HAS_SIG_C_FUNC)
// }
//# endif /* ACE_HAS_SIG_C_FUNC */
#elif defined (ACE_HAS_LYNXOS_SIGNALS)
typedef void (*ACE_SignalHandler)(...);
typedef void (*ACE_SignalHandlerV)(...);
#elif defined (ACE_HAS_TANDEM_SIGNALS)
typedef void (*ACE_SignalHandler)(...);
typedef void (*ACE_SignalHandlerV)(...);
#elif defined (ACE_HAS_IRIX_53_SIGNALS)
typedef void (*ACE_SignalHandler)(...);
typedef void (*ACE_SignalHandlerV)(...);
#elif defined (ACE_HAS_SPARCWORKS_401_SIGNALS)
typedef void (*ACE_SignalHandler)(int, ...);
typedef void (*ACE_SignalHandlerV)(int,...);
#elif defined (ACE_HAS_SUNOS4_SIGNAL_T)
typedef void (*ACE_SignalHandler)(...);
typedef void (*ACE_SignalHandlerV)(...);
#elif defined (ACE_HAS_SVR4_SIGNAL_T)
// SVR4 Signals are inconsistent (e.g., see struct sigaction)..
typedef void (*ACE_SignalHandler)(int);
# if !defined (m88k) /* with SVR4_SIGNAL_T */
typedef void (*ACE_SignalHandlerV)(void);
# else
typedef void (*ACE_SignalHandlerV)(int);
# endif /* m88k */ /* with SVR4_SIGNAL_T */
#elif defined (ACE_WIN32)
typedef void (__cdecl *ACE_SignalHandler)(int);
typedef void (__cdecl *ACE_SignalHandlerV)(int);
#elif defined (ACE_HAS_UNIXWARE_SVR4_SIGNAL_T)
typedef void (*ACE_SignalHandler)(int);
typedef void (*ACE_SignalHandlerV)(...);
#elif defined (INTEGRITY)
typedef void (*ACE_SignalHandler)();
typedef void (*ACE_SignalHandlerV)(int);
#else /* This is necessary for some older broken version of cfront */
# if defined (SIG_PF)
# define ACE_SignalHandler SIG_PF
# else
typedef void (*ACE_SignalHandler)(int);
# endif /* SIG_PF */
typedef void (*ACE_SignalHandlerV)(...);
#endif /* ACE_HAS_CONSISTENT_SIGNAL_PROTOTYPES */
#if defined (ACE_LACKS_SIGACTION)
struct sigaction
{
int sa_flags;
ACE_SignalHandlerV sa_handler;
sigset_t sa_mask;
};
#endif /* ACE_LACKS_SIGACTION */
// Defining POSIX4 real-time signal range.
#if defined(ACE_HAS_POSIX_REALTIME_SIGNALS)
#define ACE_SIGRTMIN SIGRTMIN
#define ACE_SIGRTMAX SIGRTMAX
#else /* !ACE_HAS_POSIX_REALTIME_SIGNALS */
#ifndef ACE_SIGRTMIN
#define ACE_SIGRTMIN 0
#endif /* ACE_SIGRTMIN */
#ifndef ACE_SIGRTMAX
#define ACE_SIGRTMAX 0
#endif /* ACE_SIGRTMAX */
#endif /* ACE_HAS_POSIX_REALTIME_SIGNALS */
#if defined (DIGITAL_UNIX)
// sigwait is yet another macro on Digital UNIX 4.0, just causing
// trouble when introducing member functions with the same name.
// Thanks to Thilo Kielmann" <kielmann@informatik.uni-siegen.de> for
// this fix.
# if defined (__DECCXX_VER)
# undef sigwait
// cxx on Digital Unix 4.0 needs this declaration. With it,
// <::_Psigwait> works with cxx -pthread. g++ does _not_ need
// it.
int _Psigwait __((const sigset_t *set, int *sig));
# elif defined (__KCC)
# undef sigwait
inline int sigwait (const sigset_t* set, int* sig)
{ return _Psigwait (set, sig); }
# endif /* __DECCXX_VER */
#elif !defined (ACE_HAS_SIGWAIT)
# if defined(__rtems__)
int sigwait (const sigset_t *set, int *sig);
# else
int sigwait (sigset_t *set);
# endif /* __rtems__ */
#endif /* ! DIGITAL_UNIX && ! ACE_HAS_SIGWAIT */
#if !defined (ACE_HAS_PTHREAD_SIGMASK_PROTO)
int pthread_sigmask(int, const sigset_t *, sigset_t *);
#endif /*!ACE_HAS_PTHREAD_SIGMASK_PROTO */
#ifdef __cplusplus
}
#endif /* __cplusplus */
#include "ace/os_include/os_ucontext.h"
#include /**/ "ace/post.h"
#endif /* ACE_OS_INCLUDE_OS_SIGNAL_H */
| [
"tokuda@5e132c66-7cf4-0310-b4ca-cd4a7079c2d8"
] | tokuda@5e132c66-7cf4-0310-b4ca-cd4a7079c2d8 |
6c3c803a5e825c4aaf74bb372184d2668841cacb | 36ffb87f8b6d8f1f672cd09618f654536f0284eb | /msmp/RuleEngine1/Client2/MyREClient2.h | 0907ef5e17dea0ffc97b6867b53b07937a7752b0 | [] | no_license | Programming-Systems-Lab/archived-metaparser | 577a1db1e044dce55dee60b07d2dfd71b63fca25 | ff940a4917fec9580a0c47b7ced064bf65267795 | refs/heads/master | 2020-07-10T20:34:17.946651 | 2004-03-25T19:41:06 | 2004-03-25T19:41:06 | 67,139,968 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 672 | h | // MyREClient2.h : Declaration of the CMyREClient2
#ifndef __MYRECLIENT2_H_
#define __MYRECLIENT2_H_
#include "resource.h" // main symbols
/////////////////////////////////////////////////////////////////////////////
// CMyREClient2
class ATL_NO_VTABLE CMyREClient2 :
public CComObjectRootEx<CComSingleThreadModel>,
public CComCoClass<CMyREClient2, &CLSID_MyREClient2>,
public IMyREClient2
{
public:
CMyREClient2()
{
}
DECLARE_REGISTRY_RESOURCEID(IDR_MYRECLIENT2)
DECLARE_PROTECT_FINAL_CONSTRUCT()
BEGIN_COM_MAP(CMyREClient2)
COM_INTERFACE_ENTRY(IMyREClient2)
END_COM_MAP()
// IMyREClient2
public:
STDMETHOD(Process)();
};
#endif //__MYRECLIENT2_H_
| [
"phil"
] | phil |
5bc005abab67f5221232bde1ecca331dd7677155 | 1c6152512f2b0f48460db7d3b5f22e001ece4fdf | /AutoPHSDoc.h | b672c0b5ccea4d15588e21046e022029a430c526 | [] | no_license | presscad/uesoft-AutoPHS | 9190f5fbadc214077d66e6b7d4535f8bff88dd54 | 838ad4b162d097df50556420de92584eba933ad6 | refs/heads/master | 2020-08-26T23:12:04.229290 | 2014-01-26T03:22:52 | 2014-01-26T03:22:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,046 | h | // AutoPHSDoc.h : interface of the CAutoPHSDoc class
//
/////////////////////////////////////////////////////////////////////////////
#if !defined(AFX_AUTOPHSDOC_H__95F51F78_0A4C_4B00_8DBE_971B596A50FF__INCLUDED_)
#define AFX_AUTOPHSDOC_H__95F51F78_0A4C_4B00_8DBE_971B596A50FF__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
class CAutoPHSDoc : public CDocument
{
protected: // create from serialization only
CAutoPHSDoc();
DECLARE_DYNCREATE(CAutoPHSDoc)
// Attributes
public:
ULONG m_ulID;
// Operations
public:
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CAutoPHSDoc)
public:
virtual BOOL OnNewDocument();
virtual void Serialize(CArchive& ar);
virtual void OnFinalRelease();
//}}AFX_VIRTUAL
// Implementation
public:
HACCEL m_hAccelData;
virtual ~CAutoPHSDoc();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
protected:
// Generated message map functions
protected:
//{{AFX_MSG(CAutoPHSDoc)
// NOTE - the ClassWizard will add and remove member functions here.
// DO NOT EDIT what you see in these blocks of generated code !
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
// Generated OLE dispatch map functions
//{{AFX_DISPATCH(CAutoPHSDoc)
afx_msg LPDISPATCH GetCalculate();
afx_msg void SetCalculate(LPDISPATCH newValue);
afx_msg LPDISPATCH GetDataInput();
afx_msg void SetDataInput(LPDISPATCH newValue);
afx_msg LPDISPATCH GetFiles();
afx_msg void SetFiles(LPDISPATCH newValue);
afx_msg LPDISPATCH GetFormat();
afx_msg void SetFormat(LPDISPATCH newValue);
afx_msg LPDISPATCH GetSumStuff();
afx_msg void SetSumStuff(LPDISPATCH newValue);
//}}AFX_DISPATCH
DECLARE_DISPATCH_MAP()
DECLARE_INTERFACE_MAP()
};
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_AUTOPHSDOC_H__95F51F78_0A4C_4B00_8DBE_971B596A50FF__INCLUDED_)
| [
"uesoft@163.com"
] | uesoft@163.com |
b33aa5f1dec1dd8e434e3f1e9932773961dc1a55 | c4fceeb1f0adf7dc67480df898f48d7fe886070e | /kaldi/src/nnet3/decodable-simple-looped.h | 76aaa5521e22bf9ae4e050f9a844092c00970529 | [
"Apache-2.0",
"LicenseRef-scancode-public-domain"
] | permissive | NitinShuklaML/another-repo | dcc8e7f657bf259012a86e6a404fc578a0c382d7 | 6c1a4b5f7f5025302e4b4d5d48513ebdf65b5fe2 | refs/heads/master | 2020-12-02T17:32:30.480098 | 2019-12-31T10:34:17 | 2019-12-31T10:34:17 | 231,075,476 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,478 | h | // nnet3/decodable-simple-looped.h
// Copyright 2016 Johns Hopkins University (author: Daniel Povey)
// See ../../COPYING for clarification regarding multiple authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
// See the Apache 2 License for the specific language governing permissions and
// limitations under the License.
#ifndef KALDI_NNET3_DECODABLE_SIMPLE_LOOPED_H_
#define KALDI_NNET3_DECODABLE_SIMPLE_LOOPED_H_
#include <vector>
#include "base/kaldi-common.h"
#include "gmm/am-diag-gmm.h"
#include "hmm/transition-model.h"
#include "itf/decodable-itf.h"
#include "nnet3/nnet-optimize.h"
#include "nnet3/nnet-compute.h"
#include "nnet3/am-nnet-simple.h"
namespace kaldi {
namespace nnet3 {
// See also nnet-am-decodable-simple.h, which is a decodable object that's based
// on breaking up the input into fixed chunks. The decodable object defined here is based on
// 'looped' computations, which naturally handle infinite left-context (but are
// only ideal for systems that have only recurrence in the forward direction,
// i.e. not BLSTMs... because there isn't a natural way to enforce extra right
// context for each chunk.)
// Note: the 'simple' in the name means it applies to networks for which
// IsSimpleNnet(nnet) would return true. 'looped' means we use looped
// computations, with a kGotoLabel statement at the end of it.
struct NnetSimpleLoopedComputationOptions {
int32 extra_left_context_initial;
int32 frame_subsampling_factor;
int32 frames_per_chunk;
BaseFloat acoustic_scale;
bool debug_computation;
NnetOptimizeOptions optimize_config;
NnetComputeOptions compute_config;
NnetSimpleLoopedComputationOptions():
extra_left_context_initial(0),
frame_subsampling_factor(1),
frames_per_chunk(20),
acoustic_scale(0.1),
debug_computation(false) { }
void Check() const {
KALDI_ASSERT(extra_left_context_initial >= 0 &&
frame_subsampling_factor > 0 && frames_per_chunk > 0 &&
acoustic_scale > 0.0);
}
void Register(OptionsItf *opts) {
opts->Register("extra-left-context-initial", &extra_left_context_initial,
"Extra left context to use at the first frame of an utterance (note: "
"this will just consist of repeats of the first frame, and should not "
"usually be necessary.");
opts->Register("frame-subsampling-factor", &frame_subsampling_factor,
"Required if the frame-rate of the output (e.g. in 'chain' "
"models) is less than the frame-rate of the original "
"alignment.");
opts->Register("acoustic-scale", &acoustic_scale,
"Scaling factor for acoustic log-likelihoods");
opts->Register("frames-per-chunk", &frames_per_chunk,
"Number of frames in each chunk that is separately evaluated "
"by the neural net. Measured before any subsampling, if the "
"--frame-subsampling-factor options is used (i.e. counts "
"input frames. This is only advisory (may be rounded up "
"if needed.");
opts->Register("debug-computation", &debug_computation, "If true, turn on "
"debug for the actual computation (very verbose!)");
// register the optimization options with the prefix "optimization".
ParseOptions optimization_opts("optimization", opts);
optimize_config.Register(&optimization_opts);
// register the compute options with the prefix "computation".
ParseOptions compute_opts("computation", opts);
compute_config.Register(&compute_opts);
}
};
/**
When you instantiate class DecodableNnetSimpleLooped, you should give it
a const reference to this class, that has been previously initialized.
*/
class DecodableNnetSimpleLoopedInfo {
public:
// The constructor takes a non-const pointer to 'nnet' because it may have to
// modify it to be able to take multiple iVectors.
DecodableNnetSimpleLoopedInfo(const NnetSimpleLoopedComputationOptions &opts,
Nnet *nnet);
// This constructor takes the priors from class AmNnetSimple (so it can divide by
// them).
DecodableNnetSimpleLoopedInfo(const NnetSimpleLoopedComputationOptions &opts,
AmNnetSimple *nnet);
// this constructor is for use in testing.
DecodableNnetSimpleLoopedInfo(const NnetSimpleLoopedComputationOptions &opts,
const Vector<BaseFloat> &priors,
Nnet *nnet);
void Init(const NnetSimpleLoopedComputationOptions &opts,
Nnet *nnet);
const NnetSimpleLoopedComputationOptions &opts;
const Nnet &nnet;
// the log priors (or the empty vector if the priors are not set in the model)
CuVector<BaseFloat> log_priors;
// frames_left_context equals the model left context plus the value of the
// --extra-left-context-initial option.
int32 frames_left_context;
// frames_right_context is the same as the right-context of the model.
int32 frames_right_context;
// The frames_per_chunk_ equals the number of input frames we need for each
// chunk (except for the first chunk). This divided by
// opts_.frame_subsampling_factor gives the number of output frames.
int32 frames_per_chunk;
// The output dimension of the neural network.
int32 output_dim;
// True if the neural net accepts iVectors. If so, the neural net will have been modified
// to accept the iVectors
bool has_ivectors;
// The 3 computation requests that are used to create the looped
// computation are stored in the class, as we need them to work out
// exactly shich iVectors are needed.
ComputationRequest request1, request2, request3;
// The compiled, 'looped' computation.
NnetComputation computation;
};
/*
This class handles the neural net computation; it's mostly accessed
via other wrapper classes.
It can accept just input features, or input features plus iVectors. */
class DecodableNnetSimpleLooped {
public:
/**
This constructor takes features as input, and you can either supply a
single iVector input, estimated in batch-mode ('ivector'), or 'online'
iVectors ('online_ivectors' and 'online_ivector_period', or none at all.
Note: it stores references to all arguments to the constructor, so don't
delete them till this goes out of scope.
@param [in] info This helper class contains all the static pre-computed information
this class needs, and contains a pointer to the neural net.
@param [in] feats The input feature matrix.
@param [in] ivector If you are using iVectors estimated in batch mode,
a pointer to the iVector, else NULL.
@param [in] ivector If you are using iVectors estimated in batch mode,
a pointer to the iVector, else NULL.
@param [in] online_ivectors
If you are using iVectors estimated 'online'
a pointer to the iVectors, else NULL.
@param [in] online_ivector_period If you are using iVectors estimated 'online'
(i.e. if online_ivectors != NULL) gives the periodicity
(in frames) with which the iVectors are estimated.
*/
DecodableNnetSimpleLooped(const DecodableNnetSimpleLoopedInfo &info,
const MatrixBase<BaseFloat> &feats,
const VectorBase<BaseFloat> *ivector = NULL,
const MatrixBase<BaseFloat> *online_ivectors = NULL,
int32 online_ivector_period = 1);
// returns the number of frames of likelihoods. The same as feats_.NumRows()
// in the normal case (but may be less if opts_.frame_subsampling_factor !=
// 1).
inline int32 NumFrames() const { return num_subsampled_frames_; }
inline int32 OutputDim() const { return info_.output_dim; }
// Gets the output for a particular frame, with 0 <= frame < NumFrames().
// 'output' must be correctly sized (with dimension OutputDim()). Note:
// you're expected to call this, and GetOutput(), in an order of increasing
// frames. If you deviate from this, one of these calls may crash.
void GetOutputForFrame(int32 subsampled_frame,
VectorBase<BaseFloat> *output);
// Gets the output for a particular frame and pdf_id, with
// 0 <= subsampled_frame < NumFrames(),
// and 0 <= pdf_id < OutputDim().
inline BaseFloat GetOutput(int32 subsampled_frame, int32 pdf_id) {
KALDI_ASSERT(subsampled_frame >= current_log_post_subsampled_offset_ &&
"Frames must be accessed in order.");
while (subsampled_frame >= current_log_post_subsampled_offset_ +
current_log_post_.NumRows())
AdvanceChunk();
return current_log_post_(subsampled_frame -
current_log_post_subsampled_offset_,
pdf_id);
}
private:
KALDI_DISALLOW_COPY_AND_ASSIGN(DecodableNnetSimpleLooped);
// This function does the computation for the next chunk.
void AdvanceChunk();
void AdvanceChunkInternal(const MatrixBase<BaseFloat> &input_feats,
const VectorBase<BaseFloat> &ivector);
// Gets the iVector for the specified frame., if we are
// using iVectors (else does nothing).
void GetCurrentIvector(int32 input_frame,
Vector<BaseFloat> *ivector);
// returns dimension of the provided iVectors if supplied, or 0 otherwise.
int32 GetIvectorDim() const;
const DecodableNnetSimpleLoopedInfo &info_;
NnetComputer computer_;
const MatrixBase<BaseFloat> &feats_;
// note: num_subsampled_frames_ will equal feats_.NumRows() in the normal case
// when opts_.frame_subsampling_factor == 1.
int32 num_subsampled_frames_;
// ivector_ is the iVector if we're using iVectors that are estimated in batch
// mode.
const VectorBase<BaseFloat> *ivector_;
// online_ivector_feats_ is the iVectors if we're using online-estimated ones.
const MatrixBase<BaseFloat> *online_ivector_feats_;
// online_ivector_period_ helps us interpret online_ivector_feats_; it's the
// number of frames the rows of ivector_feats are separated by.
int32 online_ivector_period_;
// The current log-posteriors that we got from the last time we
// ran the computation.
Matrix<BaseFloat> current_log_post_;
// The number of chunks we have computed so far.
int32 num_chunks_computed_;
// The time-offset of the current log-posteriors, equals
// (num_chunks_computed_ - 1) *
// (info_.frames_per_chunk_ / info_.opts_.frame_subsampling_factor).
int32 current_log_post_subsampled_offset_;
};
class DecodableAmNnetSimpleLooped: public DecodableInterface {
public:
/**
This constructor takes features as input, and you can either supply a
single iVector input, estimated in batch-mode ('ivector'), or 'online'
iVectors ('online_ivectors' and 'online_ivector_period', or none at all.
Note: it stores references to all arguments to the constructor, so don't
delete them till this goes out of scope.
@param [in] info This helper class contains all the static pre-computed information
this class needs, and contains a pointer to the neural net. If
you want prior subtraction to be done, you should have initialized
this with the constructor that takes class AmNnetSimple.
@param [in] trans_model The transition model to use. This takes care of the
mapping from transition-id (which is an arg to
LogLikelihood()) to pdf-id (which is used internally).
@param [in] feats A pointer to the input feature matrix; must be non-NULL.
We
@param [in] ivector If you are using iVectors estimated in batch mode,
a pointer to the iVector, else NULL.
@param [in] ivector If you are using iVectors estimated in batch mode,
a pointer to the iVector, else NULL.
@param [in] online_ivectors
If you are using iVectors estimated 'online'
a pointer to the iVectors, else NULL.
@param [in] online_ivector_period If you are using iVectors estimated 'online'
(i.e. if online_ivectors != NULL) gives the periodicity
(in frames) with which the iVectors are estimated.
*/
DecodableAmNnetSimpleLooped(const DecodableNnetSimpleLoopedInfo &info,
const TransitionModel &trans_model,
const MatrixBase<BaseFloat> &feats,
const VectorBase<BaseFloat> *ivector = NULL,
const MatrixBase<BaseFloat> *online_ivectors = NULL,
int32 online_ivector_period = 1);
virtual BaseFloat LogLikelihood(int32 frame, int32 transition_id);
virtual inline int32 NumFramesReady() const {
return decodable_nnet_.NumFrames();
}
virtual int32 NumIndices() const { return trans_model_.NumTransitionIds(); }
virtual bool IsLastFrame(int32 frame) const {
KALDI_ASSERT(frame < NumFramesReady());
return (frame == NumFramesReady() - 1);
}
private:
KALDI_DISALLOW_COPY_AND_ASSIGN(DecodableAmNnetSimpleLooped);
DecodableNnetSimpleLooped decodable_nnet_;
const TransitionModel &trans_model_;
};
} // namespace nnet3
} // namespace kaldi
#endif // KALDI_NNET3_DECODABLE_SIMPLE_LOOPED_H_
| [
"nitin.shukla2014@gmail.com"
] | nitin.shukla2014@gmail.com |
356344e9af8ee116052dbca323033a49669d76d6 | 16fc9ac361cd98fcd77ce21b9338488f19590525 | /src/CryptoNoteCore/BlockIndex.h | 76497f2456562d83482d4d6cdd2cfd753ba843a5 | [] | no_license | akcay0/fantomcoin | bdb159e21770777a9dcd4d912e8fc8c6ff8acd51 | 2665aba252a72c3b3449742e233ab3ec3728a3af | refs/heads/master | 2020-12-03T09:20:15.378882 | 2017-05-19T16:03:35 | 2017-05-19T16:03:35 | 95,615,929 | 1 | 0 | null | 2017-06-28T01:29:52 | 2017-06-28T01:29:52 | null | UTF-8 | C++ | false | false | 2,101 | h | // Copyright (c) 2011-2016 The Cryptonote developers
// Copyright (c) 2016-2017 XDN-project developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/hashed_index.hpp>
#include <boost/multi_index/random_access_index.hpp>
#include "crypto/hash.h"
#include <vector>
namespace CryptoNote
{
class ISerializer;
class BlockIndex {
public:
BlockIndex() :
m_index(m_container.get<1>()) {}
void pop() {
m_container.pop_back();
}
// returns true if new element was inserted, false if already exists
bool push(const Crypto::Hash& h) {
auto result = m_container.push_back(h);
return result.second;
}
bool hasBlock(const Crypto::Hash& h) const {
return m_index.find(h) != m_index.end();
}
bool getBlockHeight(const Crypto::Hash& h, uint32_t& height) const {
auto hi = m_index.find(h);
if (hi == m_index.end())
return false;
height = static_cast<uint32_t>(std::distance(m_container.begin(), m_container.project<0>(hi)));
return true;
}
uint32_t size() const {
return static_cast<uint32_t>(m_container.size());
}
void clear() {
m_container.clear();
}
Crypto::Hash getBlockId(uint32_t height) const;
std::vector<Crypto::Hash> getBlockIds(uint32_t startBlockIndex, uint32_t maxCount) const;
bool findSupplement(const std::vector<Crypto::Hash>& ids, uint32_t& offset) const;
std::vector<Crypto::Hash> buildSparseChain(const Crypto::Hash& startBlockId) const;
Crypto::Hash getTailId() const;
void serialize(ISerializer& s);
private:
typedef boost::multi_index_container <
Crypto::Hash,
boost::multi_index::indexed_by<
boost::multi_index::random_access<>,
boost::multi_index::hashed_unique<boost::multi_index::identity<Crypto::Hash>>
>
> ContainerT;
ContainerT m_container;
ContainerT::nth_index<1>::type& m_index;
};
}
| [
"xdnproject@tutanota.com"
] | xdnproject@tutanota.com |
9abe0630e43904cd99bf424bfe5f4d1efc95e1a9 | d77d11ece3b3241e7660005a8d499955dcac35b4 | /c++/Interviewbit/Strings/MultiplyStrings.hpp | 010d33eb7e36c427bdc6676152e4b3cd970b14db | [] | no_license | dshevchyk/interviewbit | aa8c98159bd66c1589f9f9de7debed2894ed572a | 8dcb6362f3927b8795b428811b5e230f0209893c | refs/heads/master | 2020-03-23T16:26:06.457563 | 2018-08-12T11:10:02 | 2018-08-12T11:10:02 | 141,809,218 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 357 | hpp | //
// MultiplyStrings.hpp
// Interviewbit
//
// Created by Shevchyk Dmytro on 05.08.2018.
// Copyright © 2018 Shevchyk Dmytro. All rights reserved.
//
#ifndef MultiplyStrings_hpp
#define MultiplyStrings_hpp
#include <string>
using std::string;
class Solution {
public:
string multiply(string A, string B);
};
#endif /* MultiplyStrings_hpp */
| [
"shevchykdmytro@gmail.com"
] | shevchykdmytro@gmail.com |
e423dec83463efc627c5e5695a23c5cfae3e8881 | 7321b91961ae8a8ca71862444230642707de7049 | /src/qt/sendcoinsdialog.cpp | 33bfadaeba270eddd101054ba289e1a06798cd16 | [
"MIT"
] | permissive | NiCoIn/NiCoIn | e90867463975b5a6756304a1d3fd0e7fdee7a15c | c6cddaa49b8abe1e60fa450235cb56de910f116f | refs/heads/master | 2020-06-08T11:14:20.730481 | 2014-08-01T18:40:38 | 2014-08-01T18:40:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,000 | cpp | #include "sendcoinsdialog.h"
#include "ui_sendcoinsdialog.h"
#include "walletmodel.h"
#include "nicoinunits.h"
#include "addressbookpage.h"
#include "optionsmodel.h"
#include "sendcoinsentry.h"
#include "guiutil.h"
#include "askpassphrasedialog.h"
#include "base58.h"
#include "main.h"
#include <QMessageBox>
#include <QLocale>
#include <QTextDocument>
#include <QScrollBar>
SendCoinsDialog::SendCoinsDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::SendCoinsDialog),
model(0)
{
ui->setupUi(this);
#ifdef Q_OS_MAC // Icons on push buttons are very uncommon on Mac
ui->addButton->setIcon(QIcon());
ui->clearButton->setIcon(QIcon());
ui->sendButton->setIcon(QIcon());
#endif
addEntry();
connect(ui->addButton, SIGNAL(clicked()), this, SLOT(addEntry()));
connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear()));
fNewRecipientAllowed = true;
}
void SendCoinsDialog::setModel(WalletModel *model)
{
this->model = model;
int nBlockheight = nBestHeight;
for(int i = 0; i < ui->entries->count(); ++i)
{
SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
if(entry)
{
entry->setModel(model);
}
}
if(model && model->getOptionsModel())
{
setBalance(model->getBalance(nBlockheight), model->getUnconfirmedBalance(nBlockheight), model->getImmatureBalance(nBlockheight));
connect(model, SIGNAL(balanceChanged(const mpq&, const mpq&, const mpq&)), this, SLOT(setBalance(const mpq&, const mpq&, const mpq&)));
connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
}
}
SendCoinsDialog::~SendCoinsDialog()
{
delete ui;
}
void SendCoinsDialog::on_sendButton_clicked()
{
QList<SendCoinsRecipient> recipients;
bool valid = true;
if(!model)
return;
for(int i = 0; i < ui->entries->count(); ++i)
{
SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
if(entry)
{
if(entry->validate())
{
recipients.append(entry->getValue());
}
else
{
valid = false;
}
}
}
if(!valid || recipients.isEmpty())
{
return;
}
// Format confirmation message
QStringList formatted;
foreach(const SendCoinsRecipient &rcp, recipients)
{
formatted.append(tr("<b>%1</b> to %2 (%3)").arg(NiCoInUnits::formatWithUnit(NiCoInUnits::NCI, rcp.amount), Qt::escape(rcp.label), rcp.address));
}
fNewRecipientAllowed = false;
QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm send coins"),
tr("Are you sure you want to send %1?").arg(formatted.join(tr(" and "))),
QMessageBox::Yes|QMessageBox::Cancel,
QMessageBox::Cancel);
if(retval != QMessageBox::Yes)
{
fNewRecipientAllowed = true;
return;
}
WalletModel::UnlockContext ctx(model->requestUnlock());
if(!ctx.isValid())
{
// Unlock wallet was cancelled
fNewRecipientAllowed = true;
return;
}
WalletModel::SendCoinsReturn sendstatus = model->sendCoins(recipients);
switch(sendstatus.status)
{
case WalletModel::InvalidAddress:
QMessageBox::warning(this, tr("Send Coins"),
tr("The recipient address is not valid, please recheck."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::InvalidAmount:
QMessageBox::warning(this, tr("Send Coins"),
tr("The amount to pay must be larger than 0."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::AmountExceedsBalance:
QMessageBox::warning(this, tr("Send Coins"),
tr("The amount exceeds your balance."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::AmountWithFeeExceedsBalance:
QMessageBox::warning(this, tr("Send Coins"),
tr("The total exceeds your balance when the %1 transaction fee is included.").
arg(NiCoInUnits::formatWithUnit(NiCoInUnits::NCI, sendstatus.fee)),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::DuplicateAddress:
QMessageBox::warning(this, tr("Send Coins"),
tr("Duplicate address found, can only send to each address once per send operation."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::TransactionCreationFailed:
QMessageBox::warning(this, tr("Send Coins"),
tr("Error: Transaction creation failed."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::TransactionCommitFailed:
QMessageBox::warning(this, tr("Send Coins"),
tr("Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::Aborted: // User aborted, nothing to do
break;
case WalletModel::OK:
accept();
break;
}
fNewRecipientAllowed = true;
}
void SendCoinsDialog::clear()
{
// Remove entries until only one left
while(ui->entries->count())
{
delete ui->entries->takeAt(0)->widget();
}
addEntry();
updateRemoveEnabled();
ui->sendButton->setDefault(true);
}
void SendCoinsDialog::reject()
{
clear();
}
void SendCoinsDialog::accept()
{
clear();
}
SendCoinsEntry *SendCoinsDialog::addEntry()
{
SendCoinsEntry *entry = new SendCoinsEntry(this);
entry->setModel(model);
ui->entries->addWidget(entry);
connect(entry, SIGNAL(removeEntry(SendCoinsEntry*)), this, SLOT(removeEntry(SendCoinsEntry*)));
updateRemoveEnabled();
// Focus the field, so that entry can start immediately
entry->clear();
entry->setFocus();
ui->scrollAreaWidgetContents->resize(ui->scrollAreaWidgetContents->sizeHint());
QCoreApplication::instance()->processEvents();
QScrollBar* bar = ui->scrollArea->verticalScrollBar();
if(bar)
bar->setSliderPosition(bar->maximum());
return entry;
}
void SendCoinsDialog::updateRemoveEnabled()
{
// Remove buttons are enabled as soon as there is more than one send-entry
bool enabled = (ui->entries->count() > 1);
for(int i = 0; i < ui->entries->count(); ++i)
{
SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
if(entry)
{
entry->setRemoveEnabled(enabled);
}
}
setupTabChain(0);
}
void SendCoinsDialog::removeEntry(SendCoinsEntry* entry)
{
delete entry;
updateRemoveEnabled();
}
QWidget *SendCoinsDialog::setupTabChain(QWidget *prev)
{
for(int i = 0; i < ui->entries->count(); ++i)
{
SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
if(entry)
{
prev = entry->setupTabChain(prev);
}
}
QWidget::setTabOrder(prev, ui->addButton);
QWidget::setTabOrder(ui->addButton, ui->sendButton);
return ui->sendButton;
}
void SendCoinsDialog::pasteEntry(const SendCoinsRecipient &rv)
{
if(!fNewRecipientAllowed)
return;
SendCoinsEntry *entry = 0;
// Replace the first entry if it is still unused
if(ui->entries->count() == 1)
{
SendCoinsEntry *first = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(0)->widget());
if(first->isClear())
{
entry = first;
}
}
if(!entry)
{
entry = addEntry();
}
entry->setValue(rv);
}
bool SendCoinsDialog::handleURI(const QString &uri)
{
SendCoinsRecipient rv;
// URI has to be valid
if (GUIUtil::parseNiCoInURI(uri, &rv))
{
CNiCoInAddress address(rv.address.toStdString());
if (!address.IsValid())
return false;
pasteEntry(rv);
return true;
}
return false;
}
void SendCoinsDialog::setBalance(const mpq& balance, const mpq& unconfirmedBalance, const mpq& immatureBalance)
{
Q_UNUSED(unconfirmedBalance);
Q_UNUSED(immatureBalance);
if(!model || !model->getOptionsModel())
return;
int unit = model->getOptionsModel()->getDisplayUnit();
ui->labelBalance->setText(NiCoInUnits::formatWithUnit(unit, RoundAbsolute(balance, ROUND_TOWARDS_ZERO)));
}
void SendCoinsDialog::updateDisplayUnit()
{
if(model && model->getOptionsModel())
{
// Update labelBalance with the current balance and the current unit
ui->labelBalance->setText(NiCoInUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), RoundAbsolute(model->getBalance(nBestHeight), ROUND_TOWARDS_ZERO)));
}
}
| [
"nicoin@ggtm.eu"
] | nicoin@ggtm.eu |
3a26731895dd902e9457ab399cb402b6173256e4 | 6ede8ffb96aabbe03feb7e739b645878abd7bc6d | /tensorflow/lite/delegates/gpu/cl/gl_interop.cc | eaeff2cda0706ca94556fd93b6cf72561dfd0830 | [
"Apache-2.0"
] | permissive | AzureMentor/tensorflow | fea99d031494642b414e15e4e1f9b34cf0353a76 | 9f8fc1e945817428be0555a985d79073d713bce0 | refs/heads/master | 2021-08-22T04:43:04.739158 | 2020-05-20T02:24:52 | 2020-05-20T02:24:52 | 184,843,536 | 2 | 0 | Apache-2.0 | 2020-05-20T02:24:53 | 2019-05-04T02:29:27 | C++ | UTF-8 | C++ | false | false | 11,573 | cc | /* Copyright 2019 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/lite/delegates/gpu/cl/gl_interop.h"
#include "absl/strings/str_cat.h"
#include "tensorflow/lite/delegates/gpu/cl/cl_errors.h"
#include "tensorflow/lite/delegates/gpu/gl/gl_call.h"
#include "tensorflow/lite/delegates/gpu/gl/gl_sync.h"
namespace tflite {
namespace gpu {
namespace cl {
namespace {
#ifndef EGL_VERSION_1_5
typedef void* EGLSync;
#define EGL_SYNC_CL_EVENT 0x30FE
#define EGL_CL_EVENT_HANDLE 0x309C
#define EGL_NO_SYNC 0
#endif /* EGL_VERSION_1_5 */
// TODO(b/131897059): replace with 64 version when EGL 1.5 is available.
// it should use KHR_cl_event2 extension. More details are in b/129974818.
using PFNEGLCREATESYNCPROC = EGLSync(EGLAPIENTRYP)(
EGLDisplay dpy, EGLenum type, const EGLAttrib* attrib_list);
PFNEGLCREATESYNCPROC g_eglCreateSync = nullptr;
} // namespace
absl::Status CreateEglSyncFromClEvent(cl_event event, EGLDisplay display,
EglSync* sync) {
if (!IsEglSyncFromClEventSupported()) {
return absl::UnimplementedError(
"CreateEglSyncFromClEvent is not supported");
}
EGLSync egl_sync;
const EGLAttrib attributes[] = {EGL_CL_EVENT_HANDLE,
reinterpret_cast<EGLAttrib>(event), EGL_NONE};
RETURN_IF_ERROR(TFLITE_GPU_CALL_EGL(g_eglCreateSync, &egl_sync, display,
EGL_SYNC_CL_EVENT, attributes));
if (egl_sync == EGL_NO_SYNC) {
return absl::InternalError("Returned empty EGL sync");
}
*sync = EglSync(display, egl_sync);
return absl::OkStatus();
}
bool IsEglSyncFromClEventSupported() {
// In C++11, static initializers are guaranteed to be evaluated only once.
static bool supported = []() -> bool {
// This function requires EGL 1.5 to work
g_eglCreateSync = reinterpret_cast<PFNEGLCREATESYNCPROC>(
eglGetProcAddress("eglCreateSync"));
// eglQueryString accepts EGL_NO_DISPLAY only starting EGL 1.5
if (!eglQueryString(EGL_NO_DISPLAY, EGL_EXTENSIONS)) {
g_eglCreateSync = nullptr;
}
return (g_eglCreateSync != nullptr);
}();
return supported;
}
absl::Status CreateClEventFromEglSync(cl_context context,
const EglSync& egl_sync, CLEvent* event) {
cl_int error_code;
cl_event new_event = clCreateEventFromEGLSyncKHR(
context, egl_sync.sync(), egl_sync.display(), &error_code);
if (error_code != CL_SUCCESS) {
return absl::InternalError(
absl::StrCat("Unable to create CL sync from EGL sync. ",
CLErrorCodeToString(error_code)));
}
*event = CLEvent(new_event);
return absl::OkStatus();
}
bool IsClEventFromEglSyncSupported(const CLDevice& device) {
return device.SupportsExtension("cl_khr_egl_event");
}
absl::Status CreateClMemoryFromGlBuffer(GLuint gl_ssbo_id,
AccessType access_type,
CLContext* context, CLMemory* memory) {
cl_int error_code;
auto mem = clCreateFromGLBuffer(context->context(), ToClMemFlags(access_type),
gl_ssbo_id, &error_code);
if (error_code != CL_SUCCESS) {
return absl::InternalError(
absl::StrCat("Unable to acquire CL buffer from GL buffer. ",
CLErrorCodeToString(error_code)));
}
*memory = CLMemory(mem, true);
return absl::OkStatus();
}
absl::Status CreateClMemoryFromGlTexture(GLenum texture_target,
GLuint texture_id,
AccessType access_type,
CLContext* context, CLMemory* memory) {
cl_int error_code;
auto mem =
clCreateFromGLTexture(context->context(), ToClMemFlags(access_type),
texture_target, 0, texture_id, &error_code);
if (error_code != CL_SUCCESS) {
return absl::InternalError(
absl::StrCat("Unable to create CL buffer from GL texture. ",
CLErrorCodeToString(error_code)));
}
*memory = CLMemory(mem, true);
return absl::OkStatus();
}
bool IsGlSharingSupported(const CLDevice& device) {
return clCreateFromGLBuffer && clCreateFromGLTexture &&
device.SupportsExtension("cl_khr_gl_sharing");
}
AcquiredGlObjects::~AcquiredGlObjects() { Release({}, nullptr).IgnoreError(); }
absl::Status AcquiredGlObjects::Acquire(
const std::vector<cl_mem>& memory, cl_command_queue queue,
const std::vector<cl_event>& wait_events, CLEvent* acquire_event,
AcquiredGlObjects* objects) {
if (!memory.empty()) {
cl_event new_event;
cl_int error_code = clEnqueueAcquireGLObjects(
queue, memory.size(), memory.data(), wait_events.size(),
wait_events.data(), acquire_event ? &new_event : nullptr);
if (error_code != CL_SUCCESS) {
return absl::InternalError(absl::StrCat("Unable to acquire GL object. ",
CLErrorCodeToString(error_code)));
}
if (acquire_event) {
*acquire_event = CLEvent(new_event);
}
clFlush(queue);
}
*objects = AcquiredGlObjects(memory, queue);
return absl::OkStatus();
}
absl::Status AcquiredGlObjects::Release(
const std::vector<cl_event>& wait_events, CLEvent* release_event) {
if (queue_ && !memory_.empty()) {
cl_event new_event;
cl_int error_code = clEnqueueReleaseGLObjects(
queue_, memory_.size(), memory_.data(), wait_events.size(),
wait_events.data(), release_event ? &new_event : nullptr);
if (error_code != CL_SUCCESS) {
return absl::InternalError(absl::StrCat("Unable to release GL object. ",
CLErrorCodeToString(error_code)));
}
if (release_event) {
*release_event = CLEvent(new_event);
}
clFlush(queue_);
queue_ = nullptr;
}
return absl::OkStatus();
}
GlInteropFabric::GlInteropFabric(EGLDisplay egl_display,
Environment* environment)
: is_egl_sync_supported_(true),
is_egl_to_cl_mapping_supported_(
IsClEventFromEglSyncSupported(environment->device())),
is_cl_to_egl_mapping_supported_(IsEglSyncFromClEventSupported()),
egl_display_(egl_display),
context_(environment->context().context()),
queue_(environment->queue()->queue()) {}
void GlInteropFabric::RegisterMemory(cl_mem memory) {
memory_.push_back(memory);
}
void GlInteropFabric::UnregisterMemory(cl_mem memory) {
auto it = std::find(memory_.begin(), memory_.end(), memory);
if (it != memory_.end()) {
memory_.erase(it);
}
}
absl::Status GlInteropFabric::Start() {
if (!is_enabled()) {
return absl::OkStatus();
}
// In GL-CL interoperability, we need to make sure GL finished processing of
// all commands that might affect GL objects. There are a few ways:
// a) glFinish
// slow, but portable
// b) EglSync + ClientWait
// faster alternative for glFinish, but still slow as it stalls GPU
// pipeline.
// c) EglSync->CLEvent or GlSync->CLEvent mapping
// Fast, as it allows to map sync to CL event and use it as a dependency
// later without stalling GPU pipeline.
if (is_egl_sync_supported_) {
EglSync sync;
RETURN_IF_ERROR(EglSync::NewFence(egl_display_, &sync));
if (is_egl_to_cl_mapping_supported_) {
// (c) EglSync->CLEvent or GlSync->CLEvent mapping
glFlush();
RETURN_IF_ERROR(
CreateClEventFromEglSync(context_, sync, &inbound_event_));
} else {
// (b) EglSync + ClientWait
RETURN_IF_ERROR(sync.ClientWait());
}
} else {
// (a) glFinish / GL fence sync
RETURN_IF_ERROR(gl::GlActiveSyncWait());
}
// Acquire all GL objects needed while processing.
auto make_acquire_wait = [&]() -> std::vector<cl_event> {
if (inbound_event_.is_valid()) {
return {inbound_event_.event()};
}
return {};
};
return AcquiredGlObjects::Acquire(memory_, queue_, make_acquire_wait(),
nullptr, &gl_objects_);
}
absl::Status GlInteropFabric::Finish() {
if (!is_enabled()) {
return absl::OkStatus();
}
RETURN_IF_ERROR(gl_objects_.Release({}, &outbound_event_));
// if (is_egl_sync_supported_ && is_cl_to_egl_mapping_supported_) {
// EglSync egl_outbound_sync;
// RETURN_IF_ERROR(CreateEglSyncFromClEvent(outbound_event_.event(),
// egl_display_,
// &egl_outbound_sync));
// // Instruct GL pipeline to wait until corresponding CL event is signaled.
// RETURN_IF_ERROR(egl_outbound_sync.ServerWait());
// glFlush();
// } else {
// // Slower option if proper sync is not supported. It is equivalent to
// // clFinish, but, hopefully, faster.
// outbound_event_.Wait();
// }
// This slow sync is the only working solution right now. We have to debug why
// above version is not working fast and reliable.
outbound_event_.Wait();
return absl::OkStatus();
}
GlClBufferCopier::GlClBufferCopier(const TensorObjectDef& input_def,
const TensorObjectDef& output_def,
Environment* environment) {
queue_ = environment->queue();
size_in_bytes_ =
NumElements(input_def) * SizeOf(input_def.object_def.data_type);
}
absl::Status GlClBufferCopier::Convert(const TensorObject& input_obj,
const TensorObject& output_obj) {
if (absl::get_if<OpenGlBuffer>(&input_obj)) {
auto ssbo = absl::get_if<OpenGlBuffer>(&input_obj);
auto cl_mem = absl::get_if<OpenClBuffer>(&output_obj);
RETURN_IF_ERROR(
TFLITE_GPU_CALL_GL(glBindBuffer, GL_SHADER_STORAGE_BUFFER, ssbo->id));
void* ptr;
RETURN_IF_ERROR(TFLITE_GPU_CALL_GL(glMapBufferRange, &ptr,
GL_SHADER_STORAGE_BUFFER, 0,
size_in_bytes_, GL_MAP_READ_BIT));
RETURN_IF_ERROR(
queue_->EnqueueWriteBuffer(cl_mem->memobj, size_in_bytes_, ptr));
RETURN_IF_ERROR(
TFLITE_GPU_CALL_GL(glUnmapBuffer, GL_SHADER_STORAGE_BUFFER));
} else {
auto cl_mem = absl::get_if<OpenClBuffer>(&input_obj);
auto ssbo = absl::get_if<OpenGlBuffer>(&output_obj);
RETURN_IF_ERROR(
TFLITE_GPU_CALL_GL(glBindBuffer, GL_SHADER_STORAGE_BUFFER, ssbo->id));
void* ptr;
RETURN_IF_ERROR(TFLITE_GPU_CALL_GL(glMapBufferRange, &ptr,
GL_SHADER_STORAGE_BUFFER, 0,
size_in_bytes_, GL_MAP_WRITE_BIT));
RETURN_IF_ERROR(
queue_->EnqueueReadBuffer(cl_mem->memobj, size_in_bytes_, ptr));
RETURN_IF_ERROR(
TFLITE_GPU_CALL_GL(glUnmapBuffer, GL_SHADER_STORAGE_BUFFER));
}
return absl::OkStatus();
}
} // namespace cl
} // namespace gpu
} // namespace tflite
| [
"gardener@tensorflow.org"
] | gardener@tensorflow.org |
3a723ecc2aaf374134d4a6ab31a59ebb5a0315a0 | c221ffced934caf0316b953b910b0c93dd092ca2 | /CashRegister/RegisterStates.ino | 3285e299d24ce18f1cd07c7d1e6735ee9ee26442 | [] | no_license | SwanPyaeSone/Point-of-sales | 2c800366ca1e99240a3ad6723d4328f1e14e1833 | b91a8ee720cb041845aaf5afc12d0e081abbc57e | refs/heads/master | 2022-04-14T19:18:59.679717 | 2012-12-04T05:24:23 | 2012-12-04T05:24:23 | 255,106,528 | 0 | 0 | null | 2020-04-12T14:59:14 | 2020-04-12T14:59:13 | null | UTF-8 | C++ | false | false | 11,482 | ino | /* State machine for cash register.
TODO: add a "start over" button (that resets the cart and everything else)
*/
enum registerStates {
stateInputCashierName,
stateInputCustomerName,
stateInputtingItemIDs,
stateIEEEMember,
stateConfirmOrder,
statePrintingReceipt,
statePromptAnotherReceipt,
statePrintTestReceipt
};
int registerState = stateInputCashierName;
boolean registerTransistion = true;
void registerSM() {
static unsigned char itemQuantity = 1;
/* Transitions:
(do once upon entering state */
if(registerTransistion){
#if DEBUG >= 2
Serial << "S: " << registerState << endl;
Serial << F("Free memory: ") << freeMemory() << endl;
#endif
switch (registerState) {
case stateInputCashierName:
lcd.setCursor(0, 1);
lcd.print(F("Enter cashier name: "));
LCDinputPrompt(3);
break;
case stateInputCustomerName:
lcd.clear();
lcd.setCursor(0, 1);
lcd.print(F("Enter customer name:"));
LCDinputPrompt(3);
break;
case stateInputtingItemIDs:
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(F("Enter item ID "));
lcd.write(1); /* Left arrow */
lcd.write(2); /* Right arrow */
lcd.print(F(":qty "));
lcd.setCursor(0, 1);
lcd.print(F("+:add item "));
lcd.write(5); /* Enter */
lcd.print(F(":done"));
printQuantity(itemQuantity);
LCDinputPrompt(3);
lcd.setCursor(textBuffer.length(), 3);
break;
case stateIEEEMember: {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(F("Apply IEEE member"));
lcd.setCursor(0, 1);
lcd.print(F("discount? (y/n):"));
LCDinputPrompt(3);
}
break;
case stateConfirmOrder:
/* TODO: confirm order showing all products ordered */
#if DEBUG >= 1
Serial << currentCartCount <<" items in cart: " << endl;
for(byte b = 0; b < currentCartCount; b++){
Serial << cart[b].quantity << "x "
<< cart[b].name << endl;
}
#endif
// lcd.clear();
// lcd.setCursor(0, 0);
// lcd.print(F("First 3 items"));
// lcd.setCursor(0, 1);
// lcd.print(F("discount? (y/n):"));
// LCDinputPrompt(3);
break;
case statePrintingReceipt:
lcd.clear();
lcd.setCursor(0, 1);
lcd.print(F("Printing receipt.."));
total = sumUpParts();
// lcd.setCursor(0, 2);
// lcd.print(F("Total: "));
// lcd.print(String(total, 2));
printReceipt(customerName, cashierName);
break;
case statePromptAnotherReceipt: {
lcd.clear();
lcd.setCursor(0, 1);
lcd.print(F("Reprint receipt?(n):"));
LCDinputPrompt(3);
}
break;
default:
Serial.println(F("Invalid case"));
delay(1000);
break;
}
registerTransistion = false;
}
/* Actions: */
switch (registerState) {
case stateInputCashierName:
if(LCDinputPrompt(-1) == 1){
cashierName = textBuffer;
Serial.println(cashierName);
changeRegisterState(stateInputCustomerName);
}
break;
case stateInputCustomerName:
/* Look for special keys */
for(unsigned char i = 0; i < specialCharBuffer.length(); i++){
char c = specialCharBuffer[i];
if(c == PS2_ESC){
changeRegisterState(stateInputCashierName);
specialCharBuffer[i] = ERASED_SPECIAL_CHARACTER;
}
}
if(LCDinputPrompt(-1) == 1){
customerName = textBuffer;
changeRegisterState(stateInputtingItemIDs);
}
break;
case stateInputtingItemIDs:{
boolean returnPressed = false;
/* Look for special keys */
for(unsigned char i = 0; i < specialCharBuffer.length(); i++){
char c = specialCharBuffer[i];
/* Increment or decrement quantity */
if(c == PS2_LEFTARROW || c == PS2_RIGHTARROW){
if(c == PS2_RIGHTARROW){
itemQuantity++;
}
else if(c == PS2_LEFTARROW){
itemQuantity--;
}
/* Print new quantity */
printQuantity(itemQuantity);
lcd.setCursor(textBuffer.length(), 3);
specialCharBuffer[i] = ERASED_SPECIAL_CHARACTER;
}
else if(c == PS2_ESC){
changeRegisterState(stateInputCustomerName);
specialCharBuffer[i] = ERASED_SPECIAL_CHARACTER;
}
// else if(c == PS2_ENTER){
// returnPressed = true;
// specialCharBuffer[i] = ERASED_SPECIAL_CHARACTER;
// }
}
boolean plusEntered = false;
if (textBufferChanged) {
/* Erase line and print quantity */
lcd.setCursor(0, 2);
lcd.print(F(" "));
printQuantity(itemQuantity);
if(textBuffer.length() > 0){
/* Reject all input besides numbers */
char c = textBuffer[textBuffer.length() - 1];
if(!(c >= '0' && c <= '9')){
if(c == '+'){
plusEntered = true;
}
/* Remove last character */
textBuffer = textBuffer.substring(0, textBuffer.length() - 1);
}
}
if(textBuffer.length() > 0){
/* Look up entered item ID in items array */
char idStr[textBuffer.length() + 1]; /* Don't understand why I need this "+ 1" */
textBuffer.toCharArray(idStr, textBuffer.length() + 1);
int id = atoi(idStr);
// Serial << "textBuffer: " << textBuffer << " idStr: " << idStr << " Converted: " << id << endl;
for(byte i = 0; i < NUM_ITEMS; i++){
/* If match found then print the name beside the quantity */
if(items[i].id == id){
/* If the return button was entered then add the item to cart */
// if(returnPressed){
if(plusEntered){
if(currentCartCount < MAX_CART_ITEMS){
cart[currentCartCount] = items[i];
cart[currentCartCount].quantity = itemQuantity;
#if DEBUG >= 1
Serial << "Item added: " << itemQuantity << "x "
<< cart[currentCartCount].name << endl;
#endif
currentCartCount++;
/* Clear text buffer and reset quantity */
textBuffer = "";
itemQuantity = 1;
changeRegisterState(stateInputtingItemIDs);
}
}
/* Else print the name of the item to screen */
else {
#if DEBUG >= 1
Serial.print(F("match found: "));
Serial.println(items[i].name);
#endif
String toPrint = items[i].name.substring(0, 16);
#if DEBUG >= 2
// Serial << toPrint << endl;
#endif
lcd.setCursor(4, 2);
lcd.print(toPrint);
}
}
}
}
}
// LCDinputPrompt(-1); /* "Enter key" was handled earlier in the state */
// if(plusEntered){
if(LCDinputPrompt(-1) == 1){
/* Continue if cart is not empty */
if(currentCartCount > 0){
changeRegisterState(stateIEEEMember);
}
else {
lcd.setCursor(0, 0);
lcd.print(F("Cart is empty"));
lcd.setCursor(textBuffer.length(), 3);
}
}
break;
}
case stateIEEEMember:
/* Look for special keys */
for(unsigned char i = 0; i < specialCharBuffer.length(); i++){
char c = specialCharBuffer[i];
if(c == PS2_ESC){
changeRegisterState(stateInputtingItemIDs);
specialCharBuffer[i] = ERASED_SPECIAL_CHARACTER;
}
}
/* y/n prompt for IEEE member discount */
if(LCDinputPrompt(-1) == 1){
if(LCDpromptYN() == 1){
applyMemberDiscount = true;
changeRegisterState(stateConfirmOrder);
}
else if(LCDpromptYN() == 0){
changeRegisterState(stateConfirmOrder);
}
else {
/* Prompt again. */
changeRegisterState(stateIEEEMember);
}
}
break;
case stateConfirmOrder:
changeRegisterState(statePrintingReceipt);
break;
case statePrintingReceipt:
changeRegisterState(statePromptAnotherReceipt);
break;
case statePromptAnotherReceipt:
if(LCDinputPrompt(-1) == 1){
if(LCDpromptYN() == 1){
/* Print another receipt. */
changeRegisterState(statePrintingReceipt);
}
else {
/* Reset everything */
itemQuantity = 1;
customerName = "";
currentCartCount = 0;
applyMemberDiscount = false;
total = 0;
changeRegisterState(stateInputCustomerName);
}
}
break;
default:
Serial.println(F("Invalid case"));
delay(1000);
break;
}
}
/* Changes state with registerTransistion true assignment. */
void changeRegisterState(int state){
registerState = state;
registerTransistion = true;
}
/* Prints a quantity and an x, for example 3x */
void printQuantity(byte quantity){
lcd.setCursor(0, 2);
lcd.print(" ");
lcd.setCursor(0, 2);
lcd.print(quantity);
lcd.print('x');
}
/* Checkout by adding together cost of all parts */
float sumUpParts(){
float currentTotal = 0;
for(byte b = 0; b < currentCartCount; b++){
currentTotal += cart[b].price * cart[b].quantity;
/* IEEE discount */
if(applyMemberDiscount){
currentTotal -= cart[b].discount * cart[b].quantity;
}
}
return currentTotal;
}
| [
"i.am.andrew.ong@gmail.com"
] | i.am.andrew.ong@gmail.com |
e909f087c85559d123e0827fee1c0028bcb4f7f8 | e06afe53bd78756f5f8cce455306ce1c93b44cf7 | /test/headers/particle.cpp | 946dc8e2ec7a083ae835cefd605d81b04f556a6f | [
"BSD-3-Clause"
] | permissive | twesterhout/percolation | 4ffb5f2bac80935fa3c1e8ea01a73da850b69a5b | f82358ce628c2b48cf7f8435673af17eab08c527 | refs/heads/master | 2020-04-01T23:57:40.622579 | 2019-09-04T22:48:26 | 2019-09-04T22:48:26 | 153,781,493 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 123 | cpp | #include "detail/particle.hpp"
#if defined(TCM_TEST_FULL)
# include "detail/particle.ipp"
#endif
auto main() -> int {}
| [
"t.westerhout@student.ru.nl"
] | t.westerhout@student.ru.nl |
7a72d17d858a17767049ec371b85939cd37424a8 | 837ad5d3e9ce779c910c54f3eb68f295a5774b42 | /src/main/mainwindow.h | f4b75df3746df0e549610f92eb76e9f918082fc6 | [] | no_license | Gris87/SystemAnalyzer | 8a29bf6d7576f4123be2f984e456de796d3260f1 | 92b5033ea872e90e2a83297b06ce350f1b792d27 | refs/heads/master | 2021-01-17T15:31:49.383065 | 2016-05-17T20:17:58 | 2016-05-17T20:17:58 | 30,556,802 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,380 | h | #ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QSystemTrayIcon>
#include <QCloseEvent>
#include "rules.h"
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
protected:
void closeEvent(QCloseEvent *event);
bool eventFilter(QObject *object, QEvent *event);
private:
void closeWindow();
void updateRulesRow(int row);
void addRulesRow();
void saveWindowState();
void loadWindowState();
void loadRules();
Ui::MainWindow *ui;
bool mAllowClose;
QList<Rules *> mRulesList;
QIcon mPauseIcon;
QIcon mStartIcon;
public slots:
void trayIconClicked(QSystemTrayIcon::ActivationReason reason);
void trayIconShowClicked();
void trayIconExitClicked();
private slots:
void rulesStarted();
void rulesFinished(bool isReportCreated);
void on_actionExit_triggered();
void on_actionAbout_triggered();
void on_actionAdd_triggered();
void on_actionEdit_triggered();
void on_actionRemove_triggered();
void on_actionStart_triggered();
void on_actionReports_triggered();
void on_rulesTableWidget_itemSelectionChanged();
void on_rulesTableWidget_cellDoubleClicked(int row, int column);
};
#endif // MAINWINDOW_H
| [
"Gris87@yandex.ru"
] | Gris87@yandex.ru |
c37a1e2cfb01ae205981b10c1e9c1ee261950a9d | 7d42f88d0621bcdf41cfd5400b5672e8c36746d7 | /mumble/mumble-server/prebuild/src/mumble/mumble_autogen/include/ui_VoiceRecorderDialog.h | 3a39bd4407643ddd8f96688ca7c3764fd43f26ac | [] | no_license | kiesel-cyber/dockers | aeb0972ea681dbd2d47202a22172b0a333957948 | 31f82be92132d84ccf16f936fb3169f1ffe749eb | refs/heads/main | 2023-08-06T11:06:14.776094 | 2021-09-06T17:46:01 | 2021-09-06T17:46:01 | 405,122,484 | 0 | 0 | null | 2021-09-10T15:13:20 | 2021-09-10T15:13:20 | null | UTF-8 | C++ | false | false | 8,318 | h | /********************************************************************************
** Form generated from reading UI file 'VoiceRecorderDialog.ui'
**
** Created by: Qt User Interface Compiler version 5.12.8
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_VOICERECORDERDIALOG_H
#define UI_VOICERECORDERDIALOG_H
#include <QtCore/QVariant>
#include <QtGui/QIcon>
#include <QtWidgets/QApplication>
#include <QtWidgets/QDialog>
#include <QtWidgets/QFormLayout>
#include <QtWidgets/QGridLayout>
#include <QtWidgets/QGroupBox>
#include <QtWidgets/QHBoxLayout>
#include <QtWidgets/QLabel>
#include <QtWidgets/QLineEdit>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QRadioButton>
#include <QtWidgets/QSpacerItem>
#include <QtWidgets/QVBoxLayout>
#include "widgets/MUComboBox.h"
QT_BEGIN_NAMESPACE
class Ui_VoiceRecorderDialog
{
public:
QGridLayout *gridLayout_2;
QGroupBox *qgbControl;
QHBoxLayout *horizontalLayout_2;
QLabel *qlTime;
QSpacerItem *horizontalSpacer;
QPushButton *qpbStart;
QPushButton *qpbStop;
QGroupBox *qgbMode;
QVBoxLayout *verticalLayout;
QRadioButton *qrbDownmix;
QRadioButton *qrbMultichannel;
QSpacerItem *verticalSpacer;
QGroupBox *qgbOutput;
QFormLayout *formLayout;
QLabel *qlOutputFormat;
MUComboBox *qcbFormat;
QLabel *qlTargetDirectory;
QLabel *qlFilename;
QHBoxLayout *qhblTargetDirectory;
QLineEdit *qleTargetDirectory;
QPushButton *qpbTargetDirectoryBrowse;
QLineEdit *qleFilename;
void setupUi(QDialog *VoiceRecorderDialog)
{
if (VoiceRecorderDialog->objectName().isEmpty())
VoiceRecorderDialog->setObjectName(QString::fromUtf8("VoiceRecorderDialog"));
VoiceRecorderDialog->resize(450, 255);
QIcon icon;
icon.addFile(QString::fromUtf8(":/actions/media-record.svg"), QSize(), QIcon::Normal, QIcon::Off);
VoiceRecorderDialog->setWindowIcon(icon);
gridLayout_2 = new QGridLayout(VoiceRecorderDialog);
gridLayout_2->setObjectName(QString::fromUtf8("gridLayout_2"));
qgbControl = new QGroupBox(VoiceRecorderDialog);
qgbControl->setObjectName(QString::fromUtf8("qgbControl"));
horizontalLayout_2 = new QHBoxLayout(qgbControl);
horizontalLayout_2->setObjectName(QString::fromUtf8("horizontalLayout_2"));
qlTime = new QLabel(qgbControl);
qlTime->setObjectName(QString::fromUtf8("qlTime"));
QFont font;
font.setPointSize(20);
font.setBold(false);
font.setUnderline(false);
font.setWeight(50);
qlTime->setFont(font);
qlTime->setAlignment(Qt::AlignCenter);
horizontalLayout_2->addWidget(qlTime);
horizontalSpacer = new QSpacerItem(20, 20, QSizePolicy::Minimum, QSizePolicy::Minimum);
horizontalLayout_2->addItem(horizontalSpacer);
qpbStart = new QPushButton(qgbControl);
qpbStart->setObjectName(QString::fromUtf8("qpbStart"));
QSizePolicy sizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
sizePolicy.setHorizontalStretch(0);
sizePolicy.setVerticalStretch(0);
sizePolicy.setHeightForWidth(qpbStart->sizePolicy().hasHeightForWidth());
qpbStart->setSizePolicy(sizePolicy);
horizontalLayout_2->addWidget(qpbStart);
qpbStop = new QPushButton(qgbControl);
qpbStop->setObjectName(QString::fromUtf8("qpbStop"));
qpbStop->setEnabled(false);
sizePolicy.setHeightForWidth(qpbStop->sizePolicy().hasHeightForWidth());
qpbStop->setSizePolicy(sizePolicy);
horizontalLayout_2->addWidget(qpbStop);
gridLayout_2->addWidget(qgbControl, 0, 0, 1, 2);
qgbMode = new QGroupBox(VoiceRecorderDialog);
qgbMode->setObjectName(QString::fromUtf8("qgbMode"));
verticalLayout = new QVBoxLayout(qgbMode);
verticalLayout->setObjectName(QString::fromUtf8("verticalLayout"));
qrbDownmix = new QRadioButton(qgbMode);
qrbDownmix->setObjectName(QString::fromUtf8("qrbDownmix"));
qrbDownmix->setEnabled(true);
qrbDownmix->setCheckable(true);
qrbDownmix->setChecked(true);
verticalLayout->addWidget(qrbDownmix);
qrbMultichannel = new QRadioButton(qgbMode);
qrbMultichannel->setObjectName(QString::fromUtf8("qrbMultichannel"));
verticalLayout->addWidget(qrbMultichannel);
verticalSpacer = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding);
verticalLayout->addItem(verticalSpacer);
gridLayout_2->addWidget(qgbMode, 1, 1, 1, 1);
qgbOutput = new QGroupBox(VoiceRecorderDialog);
qgbOutput->setObjectName(QString::fromUtf8("qgbOutput"));
formLayout = new QFormLayout(qgbOutput);
formLayout->setObjectName(QString::fromUtf8("formLayout"));
qlOutputFormat = new QLabel(qgbOutput);
qlOutputFormat->setObjectName(QString::fromUtf8("qlOutputFormat"));
formLayout->setWidget(0, QFormLayout::LabelRole, qlOutputFormat);
qcbFormat = new MUComboBox(qgbOutput);
qcbFormat->setObjectName(QString::fromUtf8("qcbFormat"));
formLayout->setWidget(0, QFormLayout::FieldRole, qcbFormat);
qlTargetDirectory = new QLabel(qgbOutput);
qlTargetDirectory->setObjectName(QString::fromUtf8("qlTargetDirectory"));
formLayout->setWidget(2, QFormLayout::LabelRole, qlTargetDirectory);
qlFilename = new QLabel(qgbOutput);
qlFilename->setObjectName(QString::fromUtf8("qlFilename"));
formLayout->setWidget(4, QFormLayout::LabelRole, qlFilename);
qhblTargetDirectory = new QHBoxLayout();
qhblTargetDirectory->setObjectName(QString::fromUtf8("qhblTargetDirectory"));
qleTargetDirectory = new QLineEdit(qgbOutput);
qleTargetDirectory->setObjectName(QString::fromUtf8("qleTargetDirectory"));
qhblTargetDirectory->addWidget(qleTargetDirectory);
qpbTargetDirectoryBrowse = new QPushButton(qgbOutput);
qpbTargetDirectoryBrowse->setObjectName(QString::fromUtf8("qpbTargetDirectoryBrowse"));
qhblTargetDirectory->addWidget(qpbTargetDirectoryBrowse);
formLayout->setLayout(2, QFormLayout::FieldRole, qhblTargetDirectory);
qleFilename = new QLineEdit(qgbOutput);
qleFilename->setObjectName(QString::fromUtf8("qleFilename"));
formLayout->setWidget(4, QFormLayout::FieldRole, qleFilename);
gridLayout_2->addWidget(qgbOutput, 1, 0, 1, 1);
retranslateUi(VoiceRecorderDialog);
QMetaObject::connectSlotsByName(VoiceRecorderDialog);
} // setupUi
void retranslateUi(QDialog *VoiceRecorderDialog)
{
VoiceRecorderDialog->setWindowTitle(QApplication::translate("VoiceRecorderDialog", "Recorder", nullptr));
qgbControl->setTitle(QApplication::translate("VoiceRecorderDialog", "Control", nullptr));
qlTime->setText(QApplication::translate("VoiceRecorderDialog", "00:00:00", nullptr));
qpbStart->setText(QApplication::translate("VoiceRecorderDialog", "&Start", nullptr));
qpbStop->setText(QApplication::translate("VoiceRecorderDialog", "S&top", nullptr));
qgbMode->setTitle(QApplication::translate("VoiceRecorderDialog", "Mode", nullptr));
qrbDownmix->setText(QApplication::translate("VoiceRecorderDialog", "Downmix", nullptr));
qrbMultichannel->setText(QApplication::translate("VoiceRecorderDialog", "Multichannel", nullptr));
qgbOutput->setTitle(QApplication::translate("VoiceRecorderDialog", "Output", nullptr));
qlOutputFormat->setText(QApplication::translate("VoiceRecorderDialog", "Output format", nullptr));
qlTargetDirectory->setText(QApplication::translate("VoiceRecorderDialog", "Target directory", nullptr));
qlFilename->setText(QApplication::translate("VoiceRecorderDialog", "Filename", nullptr));
qpbTargetDirectoryBrowse->setText(QApplication::translate("VoiceRecorderDialog", "&Browse...", nullptr));
} // retranslateUi
};
namespace Ui {
class VoiceRecorderDialog: public Ui_VoiceRecorderDialog {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_VOICERECORDERDIALOG_H
| [
"JanErWi@aol.com"
] | JanErWi@aol.com |
26f4db4d14858031a5f782ec389326c8f9b02c08 | c8c7c332f794300894cddac3bb4b60db5b72e935 | /Src-rtt/user_main.cpp | d7126215829cefdd6252cbc3d36263724a5b1629 | [] | no_license | SuWeipeng/firedragon_rc_rtt | 16c3702a678a4b9dcb0395c83f55330ee5d3681d | ac69d5238cca7bb6442b917a2e811fb23d9423da | refs/heads/master | 2020-09-07T00:43:57.762299 | 2019-11-29T15:26:39 | 2019-11-29T15:26:39 | 220,605,932 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 297 | cpp | #include "RC_Channel.h"
extern vel_target vel;
RC_Channel* rc;
#if defined(__cplusplus)
extern "C" {
#endif
void setup(void)
{
rc = new RC_Channel();
}
void loop(void)
{
vel.vel_x = rc->vel_x();
vel.vel_y = rc->vel_y();
vel.rad_z = rc->rad_z(-1);
}
#if defined(__cplusplus)
}
#endif
| [
"weipeng.su@outlook.com"
] | weipeng.su@outlook.com |
05a3c54ab3e65413d805ddd7cc52664e75292172 | e7a7edadc2ab9f28c93b8638ae68795148566f96 | /T1_ComplejidadComputacional/examples/ejemplo3.cpp | 5bc3adaf55b67887652492d3cbd74a52ef73c961 | [
"Apache-2.0"
] | permissive | tec-csf/tc2017-t1-primavera-2020-equipo-2-1 | 6349535a70dc6690abd3ea7a4dcec5f54b966b8b | 6010c3a71770bc936fababac34762d38a75d3dc2 | refs/heads/master | 2021-01-08T21:20:11.659466 | 2020-03-16T20:31:35 | 2020-03-16T20:31:35 | 242,146,367 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 257 | cpp | void bubble(vector<int> * a1) {
for (int i = 0; i < 5; ++i) {
for (int j = 0; j < 5 - 1; ++j) {
if (a1[j] > a1[j + 1]) {
int temp = a1[j];
a1[j] = a1[j + 1];
a1[j + 1] = temp;
}
}
}
}
| [
"gerangmac@GerAng-Air.local"
] | gerangmac@GerAng-Air.local |
02cfb1c98beacf084d6b753a16c76cac879d9b72 | 09fa2dd63ce3a0017df8a1ceded0c3083e713395 | /src/Target.cpp | baa6088caa3b54646e18cc1d2045a17711737961 | [] | no_license | megazeroxzvk/GAME2005-Assignment-3 | 02c525535f32116692b61749ea603ca35ce535d6 | 46163adc5f7f255622b7faf5627b51663962c0db | refs/heads/main | 2023-01-19T21:03:35.838369 | 2020-11-27T07:01:34 | 2020-11-27T07:01:34 | 314,080,386 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,152 | cpp | #include "Target.h"
#include "SoundManager.h"
#include "TextureManager.h"
#include "Util.h"
Target::Target()
{
TextureManager::Instance()->load("../Assets/sprites/targetCircle.png","targetCircle");
TextureManager::Instance()->load("../Assets/sprites/targetSquare.png","targetSquare");
SoundManager::Instance().load("../Assets/audio/ballwall.wav", "ballwall", SOUND_SFX);
SoundManager::Instance().load("../Assets/audio/goal.wav", "goal", SOUND_SFX);
// Set to circle as default
const auto size = TextureManager::Instance()->getTextureSize("targetCircle");
setWidth(size.x);
setHeight(size.y);
std::cout << "Width of Target = " << getWidth() <<std::endl << "Height of Target = "<< getHeight() << std::endl;
getTransform()->position = glm::vec2(100.0f, 100.0f);
getRigidBody()->velocity = glm::vec2(10, 10);
getRigidBody()->acceleration = glm::vec2(10, 10);
getRigidBody()->isColliding = false;
m_friction = 0.8f;
m_mass = 5.0f;
setType(TARGET);
}
Target::~Target()
= default;
void Target::draw()
{
// alias for x and y
const auto x = getTransform()->position.x;
const auto y = getTransform()->position.y;
// draw the target
switch (m_shape)
{
case CIRCLE:
TextureManager::Instance()->draw("targetCircle", x, y, 0, 255, true);
if(debugView)
{
Util::DrawCircle(getTransform()->position, std::max(getWidth() * 0.5f, getHeight() * 0.5f), { 1,0,0,1 });
}
break;
case RECTANGLE:
TextureManager::Instance()->draw("targetSquare", x, y, 0, 255, true);
if(debugView)
{
Util::DrawRect({ getTransform()->position.x - getWidth() * 0.5f, getTransform()->position.y - getHeight() * 0.5f },
getWidth(), getHeight(), { 1,0,0,1 });
}
break;
default:
TextureManager::Instance()->draw("targetCircle", x, y, 0, 255, true);
if(debugView)
{
Util::DrawCircle(getTransform()->position, std::max(getWidth() * 0.5f, getHeight() * 0.5f),
{ 1,0,0,1 });
}
break;
}
}
void Target::update()
{
// ------------- UPDATE THE TARGET VELOCITY AND ACCELERATION WITH A COEFFECIENT OF FRICTION
// Try different variations
//getRigidBody()->velocity += getRigidBody()->acceleration * deltaTime;
//if(abs(getRigidBody()->velocity.x) <= 0.05)
//{
// getRigidBody()->velocity.x = 0;
// getRigidBody()->acceleration.x = 0;
//}
//if(abs(getRigidBody()->velocity.y) <= 0.05)
//{
// getRigidBody()->velocity.y = 0;
//}
//std::cout << "Velocity.X = " << getRigidBody()->velocity.x <<
// " Velocity.Y = " << getRigidBody()->velocity.y << std::endl;
m_move();
m_checkBounds();
}
void Target::clean()
{
}
void Target::m_move()
{
getTransform()->position += getRigidBody()->velocity;
//std::cout << Util::magnitude(getRigidBody()->velocity) << std::endl;
if(Util::magnitude(getRigidBody()->velocity) < 0.5f)
{
getRigidBody()->velocity = { 0,0 };
}
}
// keep the puck in the window
void Target::m_checkBounds()
{
// base
if (getTransform()->position.y + (getHeight() * 0.5) >= 600.0f )
{
getTransform()->position.y = 600.0f - (getHeight() * 0.5f);
getRigidBody()->velocity = { getRigidBody()->velocity.x,-getRigidBody()->velocity.y };
getRigidBody()->velocity *= m_friction;
SoundManager::Instance().playSound("ballwall", 0, 1);
}
// top
if(getTransform()->position.y - (getHeight() * 0.5f) <= 0.0f)
{
getTransform()->position.y = getHeight() * 0.5f;
getRigidBody()->velocity = { getRigidBody()->velocity.x,-getRigidBody()->velocity.y };
getRigidBody()->velocity *= m_friction;
SoundManager::Instance().playSound("ballwall", 0, 1);
}
// right
if(getTransform()->position.x + (getWidth() * 0.5f) >= 800.0f)
{
getTransform()->position.x = 800.0f - (getWidth() * 0.5f);
getRigidBody()->velocity = { -getRigidBody()->velocity.x,getRigidBody()->velocity.y };
getRigidBody()->velocity *= m_friction;
if (getTransform()->position.y >= 240 && getTransform()->position.y <= (380))
{
pointsScored <= 0 ? 0 : pointsScored--;
SoundManager::Instance().playSound("goal", 0, 1);
}
else
{
SoundManager::Instance().playSound("ballwall", 0, 1);
}
}
//left
if(getTransform()->position.x - (getWidth() * 0.5f) <= 0.0f)
{
getTransform()->position.x = (getWidth() * 0.5f);
getRigidBody()->velocity = { -getRigidBody()->velocity.x,getRigidBody()->velocity.y };
getRigidBody()->velocity *= m_friction;
if(getTransform()->position.y >= 240 && getTransform()->position.y <= (380))
{
pointsScored++;
SoundManager::Instance().playSound("goal", 0, 1);
}
else
{
SoundManager::Instance().playSound("ballwall", 0, 1);
}
}
//std::cout << "Points Scored = " << pointsScored << std::endl;
//std::cout << "Velocity X = " << getRigidBody()->velocity.x << "\nVelocity Y = " << getRigidBody()->velocity.y << std::endl;
}
void Target::m_reset()
{
}
CollisionShape Target::getCollisionShape()
{
return m_shape;
}
void Target::setCollisionShape(CollisionShape CircleOrSquare)
{
m_shape = CircleOrSquare;
}
float Target::getFriction()
{
return m_friction;
}
void Target::setFriction(float friction)
{
m_friction = friction;
}
float Target::getMass()
{
return m_mass;
}
void Target::setMass(float mass)
{
m_mass = mass;
}
| [
"vineet.z91@gmail.com"
] | vineet.z91@gmail.com |
4b84b97ecc751fa39498c5a3dc8d3313f36e6ae7 | caacd3af3a33cd99fe0e5eab2babb6df7207f59c | /ConsoleApplication3/ConsoleApplication3/ConsoleApplication3.cpp | cd8dd0c9180afab0830713da2a4956997580dec8 | [] | no_license | irizarryam5/CPP-Classwork | 9df76679e463655709e0a77840b821c72ad5bbcf | 5841cd71704163273f631fb33bc03ff34467d028 | refs/heads/master | 2021-05-06T10:25:29.044884 | 2017-12-13T12:44:56 | 2017-12-13T12:44:56 | 114,120,374 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,014 | cpp | #include "stdafx.h"
#include <iostream>
#include <string>
#include <iomanip>
#include <vector>
using namespace std;
const int SIZE = 5;
int main()
{
vector<string> aniNames(SIZE);
vector<int> aniAges(SIZE);
int count = 0;
for (count = 0; count < SIZE; count++)
{
cout << "Enter animal " << (count + 1) << " name:" << endl;
getline(cin, aniNames[count]);
if (aniNames[count] == "Stop" || aniNames[count] == "STOP" || aniNames[count] == "stop")
{
aniNames[count] = " ";
break;
}
else
{
cout << "Enter animal " << (count + 1) << " age:" << endl;
cin >> aniAges[count];
cin.ignore(1000, '\n');
}
}
cout << '\n' << "Lab 01 By: Alex Irizarry" << endl;
cout << '\n' << "Animal" << endl;
cout << "#" << setw(10) << "Name" << setw(15) << "Age" << endl;
for (count = 0; count < SIZE; count++)
{
if (aniNames[count].length() > 1)
cout << (count + 1) << setw(10) << aniNames[count] << setw(15) << aniAges[count] << endl;
else
break;
}
system("pause");
return 0;
}
| [
"irizarryam5@gmail.com"
] | irizarryam5@gmail.com |
1927e86d54bbd14b872290cf0f089d93e2d2ef3b | f8ac68742868df027fde3923b83255855a52252e | /libsnn/include/snn/initializer.hpp | 04d7a6b1e131cd51c00b314e44e972f9a0a88ed0 | [
"MIT"
] | permissive | rahulsrma26/simpleAI | a64e36cbed0556b9d710b455c38034bebeed892e | 4a8858df503336ce5cf00850d89015e93e07cb36 | refs/heads/master | 2022-11-17T08:14:13.391967 | 2020-07-10T18:48:50 | 2020-07-10T18:48:50 | 104,486,616 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 500 | hpp | #pragma once
#include <memory>
#include "snn/initializer/base_initializer.hpp"
#include "snn/initializer/zeros.hpp"
#include "snn/initializer/normal.hpp"
#include "snn/initializer/xavier.hpp"
namespace snn {
class initializer : public initializers::base_initializer {
std::unique_ptr<initializers::base_initializer> initializer_m;
public:
void create(const kwargs&);
std::string name() const override;
void init(tensor<real>&) override;
};
} // namespace snn | [
"rahulsrma26@gmail.com"
] | rahulsrma26@gmail.com |
34d8cdd7d20314236562b3193468fb1692c05176 | 8def71a7a8d8a4aa0c0ed8d910f3a405c44ba617 | /QAtask2_simplewordembedding/QAtask2_simplewordembedding/SimpleWordembedding.cpp | 7b0c2baf6f924a10e80cd4dc4dd3dafa90c4a99a | [] | no_license | lrank/QA_task | bff96496f4fab7fca3352abc1c5883a968c12b3f | bdc6cd99de4658254922113d88b2a26f39ef364b | refs/heads/master | 2021-01-10T08:16:49.391120 | 2015-12-19T06:35:11 | 2015-12-19T06:35:11 | 47,236,032 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,207 | cpp | #include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <array>
#include <map>
#include <cmath>
#include <boost/tokenizer.hpp>
#include <random>
#define _DEBUG 0;
#define TRAIN 0;
typedef int LABEL;
const int emb_dim = 200;
std::array<double, emb_dim> UNKNOWN;
void LoadDict(
std::map<std::string, std::array<double, emb_dim>>& dict
)
{
fprintf(stderr, "Reading word embedding...\n");
dict.clear();
#if _DEBUG
const char File_Embedding[] = "c:\\data\\word_embedding_simple.txt"; // for debug
#else
const char File_Embedding[] = "c:\\data\\word_embedding_size_200.txt";
#endif
std::ifstream fin(File_Embedding);
std::string new_word;
#if _DEBUG
int it = 0;
#endif
//Read *UNKNOWN*
fin >> new_word;
UNKNOWN.fill(0);
for (int i = 0; i < emb_dim; ++i)
{
fin >> UNKNOWN[i];
}
while (!fin.eof())
{
#if _DEBUG
if (it % 1000 == 0)
fprintf(stderr, "%d\n", it);
++it;
#endif
fin >> new_word;
std::array<double, emb_dim> v;
v.fill(0);
for (int i = 0; i < emb_dim; ++i)
{
fin >> v[i];
}
dict[new_word] = v;
}
fin.close();
}
double ComputeAngel(
const std::array<double, emb_dim>& v1,
const std::array<double, emb_dim>& v2
)
{
double dot = 0, l1 = 0, l2 = 0;
for (int i = 0; i < emb_dim; ++i)
{
dot += v1[i] * v2[i];
l1 += v1[i] * v1[i];
l2 += v2[i] * v2[i];
}
return dot / sqrt(l1 * l2);
}
const std::uniform_real_distribution<> dist(0, 1);
std::random_device rd;
std::mt19937 gen(rd());
bool LookUp(
const std::map<std::string, std::array<double, emb_dim>>& dict,
const std::string& word,
std::array<double, emb_dim>& v
)
{
auto search = dict.find(word);
if (search == dict.end())
{
//for (int i = 0; i < emb_dim; ++i)
// v[i] = dist(gen);
v = UNKNOWN;
return false;
}
else
{
v = search->second;
return true;
}
}
void LoadSentence(
const std::map<std::string, std::array<double, emb_dim>>& dict,
std::vector<double>& thetas,
std::vector<LABEL>& target
)
{
fprintf(stderr, "Load Sentences...\n");
#if TRAIN
const char Train_data[] = "C:\\Data\\msr_train.txt";
#else
const char Train_data[] = "C:\\Data\\msr_test.txt";
#endif
std::ifstream fin(Train_data);
int total_sentence = 0;
while (!fin.eof())
{
++total_sentence;
LABEL label;
int s_id1, s_id2;
fin >> label >> s_id1 >> s_id2;
target.push_back(label);
#if _DEBUG
fprintf(stderr, "%d %d %d\n", label, s_id1, s_id2);
#endif
std::array<double, emb_dim> v1, v2, v;
v1.fill(0);
char ch;
fin.get(ch);
std::string sentence;
getline(fin, sentence);
//boost::char_separator<char> sep{ " \t.,\'?"};
boost::char_separator<char> sep{ " \t" };
boost::tokenizer<boost::char_separator<char>> tok1(sentence, sep);
int len = 0;
int c_unknown = 0;
for (const auto& it : tok1)
{
#if _DEBUG
fprintf(stderr, "%s\n", it);
#endif
if (!LookUp(dict, it, v))
++c_unknown;
for (int i = 0; i < emb_dim; ++i)
{
v1[i] += v[i];
}
++len;
}
for (int i = 0; i < emb_dim; ++i)
{
v1[i] /= len;
}
fprintf(stderr, "Sentence %d S1: UNKNOWN / LENGTH = %d / %d\n", total_sentence, c_unknown, len);
v2.fill(0);
getline(fin, sentence);
boost::tokenizer<boost::char_separator<char>> tok2(sentence, sep);
len = 0;
c_unknown = 0;
for (const auto& it : tok2)
{
if (!LookUp(dict, it, v))
++c_unknown;
for (int i = 0; i < emb_dim; ++i)
{
v2[i] += v[i];
}
++len;
}
for (int i = 0; i < emb_dim; ++i)
{
v2[i] /= len;
}
fprintf(stderr, "Sentence %d S2: UNKNOWN / LENGTH = %d / %d\n", total_sentence, c_unknown, len);
thetas.push_back(ComputeAngel(v1, v2));
}
fprintf(stderr, "total sentences = %d\n", total_sentence);
}
int main()
{
std::map<std::string, std::array<double, emb_dim>> dict;
LoadDict(dict);
std::vector<double> thetas;
thetas.clear();
std::vector<LABEL> target;
target.clear();
LoadSentence(dict, thetas, target);
//TODO:
//SVM();
//print
{
#if TRAIN
std::ofstream fout("train.txt");
#else
std::ofstream fout("test.txt");
#endif
for (auto i = 0; i < target.size(); ++i)
fout << target[i] << "\t1:" << thetas[i] << '\n';
fout.close();
}
system("pause");
return 0;
} | [
"f.w.lrank@gmail.com"
] | f.w.lrank@gmail.com |
4591c4198d71a8944c90c4c56343b5c697e33c84 | ebdbc6c7de4114d44d9faa73f16c1cd075702cda | /src/particleSystem.cpp | 4d0ef190e6893b9945f65fcd6b92562204d0afd7 | [] | no_license | SirDifferential/Captain | 6915f3cd4b4bb2f4be89d9a87dc21fe5fe41fc1d | 0ecd7945113c6f2a57190d9ca6e3421c41ce8af3 | refs/heads/master | 2021-01-18T16:36:13.140367 | 2012-04-21T09:09:02 | 2012-04-21T09:09:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,907 | cpp | #include "particleSystem.hpp"
#include <GL/glew.h>
#include <stdio.h>
ParticleSystem::ParticleSystem(int n, float h, float w, Vector3 loc, float colorVariance, float color1, float color2, float color3)
{
fprintf(stderr, "ParticleSystem constructing\n");
numOfParticles = n;
height = h;
width = w;
location = loc;
for (unsigned int i = 0; i < numOfParticles; i++)
particles.push_back(Particle(this));
for (std::vector<Particle>::iterator iter = particles.begin(); iter != particles.end(); iter++)
{
Vector3 temp;
// Random location within the bounds of the system
temp.x = loc.x + width - (double(rand())/RAND_MAX)*width;
temp.y = loc.y + height - (double(rand())/RAND_MAX)*height;
temp.z = -1;
iter->setLocation(temp);
iter->setSize(1.0f);
// High color variance == random component appears more
// Color variance of 0 == completely defined color
// Color variance of 1 == completely random color
iter->setColorR(color1 - (double(rand())/RAND_MAX) * colorVariance);
iter->setColorG(color2 - (double(rand())/RAND_MAX) * colorVariance);
iter->setColorB(color3 - (double(rand())/RAND_MAX) * colorVariance);
}
}
ParticleSystem::~ParticleSystem()
{
fprintf(stderr, "ParticleSystem destructing\n");
}
void ParticleSystem::update(Vector3 vel)
{
velocity = vel;
location += velocity;
for (std::vector<Particle>::iterator iter = particles.begin(); iter != particles.end(); iter++)
{
iter->update(velocity);
}
}
void ParticleSystem::render()
{
glDisable(GL_TEXTURE_2D);
glDisable(GL_LIGHTING);
glDisable(GL_BLEND);
glEnable(GL_POINT_SMOOTH);
glBegin(GL_POINTS);
for (std::vector<Particle>::iterator iter = particles.begin(); iter != particles.end(); iter++)
{
iter->render();
}
glEnd();
}
| [
"jesse.kaukonen@gmail.com"
] | jesse.kaukonen@gmail.com |
dd2200463fa0f320768ce96f5e8f5bfe9ab13331 | fa8db2bf9d4be984fb53d84a79b2e26e4336e9ec | /AccountOwner.cpp | 2a0ffb82b5216b641867b731e9fb3ccca7a7ac66 | [] | no_license | EslamFawzyMahmoud/Bank-Mangement-System | 3fac977a2387a37016a897f27a5cd46ba76480f5 | 0e7d7a62376a0357c4aa76c1912469c80c04e252 | refs/heads/master | 2023-02-22T18:44:13.498680 | 2021-01-22T11:52:18 | 2021-01-22T11:52:18 | 331,931,245 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 499 | cpp | //
// Created by we on 1/22/2021.
//
#include "AccountOwner.h"
#include <bits/stdc++.h>
using namespace std;
//
// Created by Yosef Sayed on 2020-06-06.
//
#include "AccountOwner.h"
using namespace std;
AccountOwner::AccountOwner()
{
FullName=' ';
PhoneNumber = ' ';
NationalID = ' ';
}//empty constructor
AccountOwner::AccountOwner(string fname, string lname, string phone, string id)
{
FullName = fname + lname;
PhoneNumber=phone;
NationalID=id;
}//parameter constructor
| [
"eslamfawzy103@gmail.com"
] | eslamfawzy103@gmail.com |
8397b4e0313b890689e63cc9179c013fcc40646d | a782e8b77eb9a32ffb2c3f417125553693eaee86 | /src/devices/cpu/drivers/aml-cpu/aml-cpu.cc | e70b8383d714c4e34181ad4be8aa6fd3ceca4e53 | [
"BSD-3-Clause"
] | permissive | xyuan/fuchsia | 9e5251517e88447d3e4df12cf530d2c3068af290 | db9b631cda844d7f1a1b18cefed832a66f46d56c | refs/heads/master | 2022-06-30T17:53:09.241350 | 2020-05-13T12:28:17 | 2020-05-13T12:28:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,221 | cc | // Copyright 2019 The Fuchsia 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 "aml-cpu.h"
#include <memory>
#include <ddk/binding.h>
#include <ddk/debug.h>
#include <ddk/driver.h>
#include <ddk/platform-defs.h>
#include <ddktl/fidl.h>
#include <ddktl/protocol/composite.h>
#include <ddktl/protocol/thermal.h>
namespace {
using llcpp::fuchsia::device::MAX_DEVICE_PERFORMANCE_STATES;
using llcpp::fuchsia::hardware::thermal::PowerDomain;
__UNUSED constexpr size_t kFragmentPdev = 0;
constexpr size_t kFragmentThermal = 1;
constexpr size_t kFragmentCount = 2;
uint16_t PstateToOperatingPoint(const uint32_t pstate, const size_t n_operating_points) {
ZX_ASSERT(pstate < n_operating_points);
ZX_ASSERT(n_operating_points < MAX_DEVICE_PERFORMANCE_STATES);
// Operating points are indexed 0 to N-1.
return static_cast<uint16_t>(n_operating_points - pstate - 1);
}
} // namespace
namespace amlogic_cpu {
zx_status_t AmlCpu::Create(void* context, zx_device_t* parent) {
zx_status_t status;
ddk::CompositeProtocolClient composite(parent);
if (!composite.is_valid()) {
zxlogf(ERROR, "%s: failed to get composite protocol", __func__);
return ZX_ERR_INTERNAL;
}
zx_device_t* devices[kFragmentCount];
size_t actual;
composite.GetFragments(devices, kFragmentCount, &actual);
if (actual != kFragmentCount) {
zxlogf(ERROR, "%s: Expected to get %lu fragments, actually got %lu", __func__,
kFragmentCount, actual);
return ZX_ERR_INTERNAL;
}
// Initialize an array with the maximum possible number of PStates since we
// determine the actual number of PStates at runtime by querying the thermal
// driver.
device_performance_state_info_t perf_states[MAX_DEVICE_PERFORMANCE_STATES];
for (size_t i = 0; i < MAX_DEVICE_PERFORMANCE_STATES; i++) {
perf_states[i].state_id = static_cast<uint8_t>(i);
perf_states[i].restore_latency = 0;
}
// The Thermal Driver is our parent and it exports an interface with one
// method (Connect) which allows us to connect to its FIDL interface.
zx_device_t* device = devices[kFragmentThermal];
ddk::ThermalProtocolClient thermal_client;
status = ddk::ThermalProtocolClient::CreateFromDevice(device, &thermal_client);
if (status != ZX_OK) {
zxlogf(ERROR, "aml-cpu: Failed to get thermal protocol client, st = %d", status);
return status;
}
// This channel pair will be used to talk to the Thermal Device's FIDL
// interface.
zx::channel channel_local, channel_remote;
status = zx::channel::create(0, &channel_local, &channel_remote);
if (status != ZX_OK) {
zxlogf(ERROR, "aml-cpu: Failed to create channel pair, st = %d", status);
return status;
}
// Pass one end of the channel to the Thermal driver. The thermal driver will
// serve its FIDL interface over this channel.
status = thermal_client.Connect(std::move(channel_remote));
if (status != ZX_OK) {
zxlogf(ERROR, "aml-cpu: failed to connect to thermal driver, st = %d", status);
return status;
}
fuchsia_thermal::Device::SyncClient thermal_fidl_client(std::move(channel_local));
auto device_info = thermal_fidl_client.GetDeviceInfo();
if (device_info.status() != ZX_OK) {
zxlogf(ERROR, "aml-cpu: failed to get device info, st = %d", device_info.status());
return device_info.status();
}
const fuchsia_thermal::ThermalDeviceInfo* info = device_info->info.get();
// Hack: Only support one DVFS domain in this driver. When only one domain is
// supported, it is published as the "Big" domain, so we check that the Little
// domain is unpopulated.
constexpr size_t kLittleDomainIndex = 1u;
static_assert(static_cast<size_t>(PowerDomain::LITTLE_CLUSTER_POWER_DOMAIN) ==
kLittleDomainIndex);
if (info->opps[kLittleDomainIndex].count != 0) {
zxlogf(ERROR, "aml-cpu: this driver only supports one dvfs domain.");
return ZX_ERR_INTERNAL;
}
// Make sure we don't have more operating points than available performance states.
const fuchsia_thermal::OperatingPoint& opps = info->opps[0];
if (opps.count > MAX_DEVICE_PERFORMANCE_STATES) {
zxlogf(ERROR, "aml-cpu: cpu device has more operating points than we support");
return ZX_ERR_INTERNAL;
}
const uint8_t perf_state_count = static_cast<uint8_t>(opps.count);
zxlogf(INFO, "aml-cpu: Creating CPU Device with %u operating poitns", opps.count);
auto cpu_device = std::make_unique<AmlCpu>(device, std::move(thermal_fidl_client));
status = cpu_device->DdkAdd("cpu", // name
DEVICE_ADD_NON_BINDABLE, // flags
nullptr, 0, // props & propcount
ZX_PROTOCOL_CPU_CTRL, // protocol id
nullptr, // proxy_args
ZX_HANDLE_INVALID, // client remote
nullptr, 0, // Power states & count
perf_states, perf_state_count // Perf states & count
);
if (status != ZX_OK) {
zxlogf(ERROR, "aml-cpu: Failed to add cpu device, st = %d", status);
return status;
}
// Intentionally leak this device because it's owned by the driver framework.
__UNUSED auto unused = cpu_device.release();
return ZX_OK;
}
zx_status_t AmlCpu::DdkMessage(fidl_msg_t* msg, fidl_txn_t* txn) {
DdkTransaction transaction(txn);
fuchsia_cpuctrl::Device::Dispatch(this, msg, &transaction);
return transaction.Status();
}
void AmlCpu::DdkRelease() { delete this; }
zx_status_t AmlCpu::DdkSetPerformanceState(uint32_t requested_state, uint32_t* out_state) {
zx_status_t status;
fuchsia_thermal::OperatingPoint opps;
status = GetThermalOperatingPoints(&opps);
if (status != ZX_OK) {
zxlogf(ERROR, "%s: Failed to get Thermal operating poitns, st = %d", __func__, status);
return status;
}
if (requested_state >= opps.count) {
zxlogf(ERROR, "%s: Requested device performance state is out of bounds", __func__);
return ZX_ERR_OUT_OF_RANGE;
}
const uint16_t pstate = PstateToOperatingPoint(requested_state, opps.count);
const auto result =
thermal_client_.SetDvfsOperatingPoint(pstate, PowerDomain::BIG_CLUSTER_POWER_DOMAIN);
if (!result.ok() || result->status != ZX_OK) {
zxlogf(ERROR, "%s: failed to set dvfs operating point.", __func__);
return ZX_ERR_INTERNAL;
}
*out_state = requested_state;
return ZX_OK;
}
zx_status_t AmlCpu::DdkConfigureAutoSuspend(bool enable, uint8_t requested_sleep_state) {
return ZX_ERR_NOT_SUPPORTED;
}
void AmlCpu::GetPerformanceStateInfo(uint32_t state,
GetPerformanceStateInfoCompleter::Sync completer) {
// Get all performance states.
zx_status_t status;
fuchsia_thermal::OperatingPoint opps;
status = GetThermalOperatingPoints(&opps);
if (status != ZX_OK) {
zxlogf(ERROR, "%s: Failed to get Thermal operating poitns, st = %d", __func__, status);
completer.ReplyError(status);
}
// Make sure that the state is in bounds?
if (state >= opps.count) {
zxlogf(ERROR, "%s: requested pstate index out of bounds, requested = %u, count = %u",
__func__, state, opps.count);
completer.ReplyError(ZX_ERR_OUT_OF_RANGE);
return;
}
const uint16_t pstate = PstateToOperatingPoint(state, opps.count);
llcpp::fuchsia::hardware::cpu::ctrl::CpuPerformanceStateInfo result;
result.frequency_hz = opps.opp[pstate].freq_hz;
result.voltage_uv = opps.opp[pstate].volt_uv;
completer.ReplySuccess(result);
}
zx_status_t AmlCpu::GetThermalOperatingPoints(fuchsia_thermal::OperatingPoint* out) {
auto result = thermal_client_.GetDeviceInfo();
if (!result.ok() || result->status != ZX_OK) {
zxlogf(ERROR, "%s: Failed to get thermal device info", __func__);
return ZX_ERR_INTERNAL;
}
fuchsia_thermal::ThermalDeviceInfo* info = result->info.get();
// We only support one DVFS cluster on Astro.
if (info->opps[1].count != 0) {
zxlogf(ERROR, "%s: thermal driver reported more than one dvfs domain?", __func__);
return ZX_ERR_INTERNAL;
}
memcpy(out, &info->opps[0], sizeof(*out));
return ZX_OK;
}
void AmlCpu::GetNumLogicalCores(GetNumLogicalCoresCompleter::Sync completer) {
unsigned int result = zx_system_get_num_cpus();
completer.Reply(result);
}
void AmlCpu::GetLogicalCoreId(uint64_t index, GetLogicalCoreIdCompleter::Sync completer) {
// Placeholder.
completer.Reply(0);
}
} // namespace amlogic_cpu
static constexpr zx_driver_ops_t aml_cpu_driver_ops = []() {
zx_driver_ops_t result = {};
result.version = DRIVER_OPS_VERSION;
result.bind = amlogic_cpu::AmlCpu::Create;
return result;
}();
// clang-format off
ZIRCON_DRIVER_BEGIN(aml_cpu, aml_cpu_driver_ops, "zircon", "0.1", 4)
BI_ABORT_IF(NE, BIND_PROTOCOL, ZX_PROTOCOL_COMPOSITE),
BI_ABORT_IF(NE, BIND_PLATFORM_DEV_VID, PDEV_VID_AMLOGIC),
BI_ABORT_IF(NE, BIND_PLATFORM_DEV_PID, PDEV_PID_AMLOGIC_S905D2),
BI_MATCH_IF(EQ, BIND_PLATFORM_DEV_DID, PDEV_DID_AMLOGIC_CPU),
ZIRCON_DRIVER_END(aml_cpu)
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
0e3ee6c10a6000fb575563431f6346673c5598eb | 270f6259756f29cd26dd75e46682ff0dfa9ddeb8 | /AthLinks/AthLinks/tools/.svn/text-base/DefaultIndexingPolicy.h.svn-base | 19941b9721ef6c8d6b8ae68f4051da8e29d32d39 | [] | no_license | atlas-control/control | 79066de6c24dc754808d5cecc11e679520957e00 | 8631c6b8edb576caf247c459c34e158c1b531f50 | refs/heads/master | 2016-08-12T03:03:51.372028 | 2016-02-28T22:29:15 | 2016-02-28T22:29:15 | 52,747,234 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,089 | /***************************************************************************
type generator that associates a container with an IndexingPolicy.
Used by ElementLink
Please define a (partial) specialization for your container:
the default value provided here generates a compiler error.
The specializations for the STL containers are available in StoreGate/tools
----------------------------------------------------------------
ATLAS Collaboration
***************************************************************************/
// $Id: DefaultIndexingPolicy.h,v 1.1 2003-04-07 23:58:32 calaf Exp $
#ifndef ATHLINKS_TOOLS_DEFAULTINDEXINGPOLICY_H
# define ATHLINKS_TOOLS_DEFAULTINDEXINGPOLICY_H
template <class Foo> class ERROR_PLEASE_ADD_ONE_OF_THE_PREDEFINED_POLICY_INCLUDE_FILES_OR_DEFINE_A_DEFAULT_INDEXING_POLICY_FOR_THIS_TYPE;
template <typename STORABLE>
struct DefaultIndexingPolicy {
typedef ERROR_PLEASE_ADD_ONE_OF_THE_PREDEFINED_POLICY_INCLUDE_FILES_OR_DEFINE_A_DEFAULT_INDEXING_POLICY_FOR_THIS_TYPE<STORABLE> type;
};
#endif // ATHLINKS_TOOLS_DEFAULTINDEXINGPOLICY_H
| [
"dguest@cern.ch"
] | dguest@cern.ch | |
5770226c1be522391009321d7b94b3f393c179df | e44143f9c414193afc563971f73bd00e86b6ac69 | /ABC159/A.cpp | 0331a4260fe27164788a72393c4d96412833ebbe | [] | no_license | Kotaro666-dev/atcoder | 88b1452e43ee7ed0fa67d6e531d72012bbd995fb | 91b23815e2b1d48edd9390b2b7c666ac2f23946e | refs/heads/master | 2021-10-10T09:32:19.545393 | 2021-10-09T03:38:29 | 2021-10-09T03:38:29 | 240,242,377 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,229 | cpp | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* A.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: kotaro666 <kotaro0726@gmail.com> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/03/22 20:28:06 by kotaro666 #+# #+# */
/* Updated: 2020/03/22 21:08:04 by kotaro666 ### ########.fr */
/* */
/* ************************************************************************** */
#include <bits/stdc++.h>
#define PI 3.1415926535897
using namespace std;
typedef long long ll;
int main(void)
{
int N, M;
cin >> N >> M;
int ans = 0;
while (N > 0)
{
ans += N - 1;
N--;
}
while (M > 0)
{
ans += M - 1;
M--;
}
cout << ans << endl;
return (0);
} | [
"kotarokamashima1@Macbook-Air.local"
] | kotarokamashima1@Macbook-Air.local |
b14703346f78a00fa32eaee24267b95ec5bf2195 | 87ddf73f189b8b4dedbe409c815f77b5b8a8c95a | /src/CapaLogica/HashExtensible/ElementKey.h | 53492cde31fc2d894e19ac09d50666b1efda3499 | [] | no_license | marianorodriguez/tp-datos-dkt | cbba7db9fe5fd8e9434dabd9cbe3fbc0e2c666d9 | 5f7200e23a8e7d9c6155d37ec9bf7657ea4d87c9 | refs/heads/master | 2020-12-25T19:04:10.584604 | 2013-12-08T02:21:49 | 2013-12-08T02:21:49 | 32,226,683 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,375 | h | #ifndef ELEMENTKEY_H_
#define ELEMENTKEY_H_
#include <string>
#include "Serializable.h"
#include <sstream>
#include <iostream>
#include <fstream>
using namespace std;
template <typename T>
class ElementKey: public Serializable {
protected:
T valor;
public:
ElementKey(T valor, bool desSerializar);
//ElementKey(const string aDesSerializar);
ElementKey(const ElementKey& elCopia); //Constructor copia
~ElementKey();
bool operator == (const ElementKey<T>& other) const;
bool operator != (const ElementKey<T>& other) const;
ElementKey<T>& operator=(const ElementKey<T>& elem);
T& operator=(const T& elem);
const T& getValor()const;
virtual string serializar()const;
friend ostream& operator<< (ostream& os, const ElementKey<T>& ptrObj){
os << ptrObj.valor;
return os;
}
protected:
virtual void desSerializar(const string aDesSerializar);
};
//Implementacion...
template <typename T>
ElementKey<T>::ElementKey(T nValor, bool desSerializar){
valor = nValor;
}
template <typename T>
ElementKey<T>::ElementKey(const ElementKey<T>& elCopia){
valor = elCopia.valor;
}
//template <typename T>
//ElementKey<T>::ElementKey(const string aDesSerializar){
// valor = NULL;
// desSerializar(aDesSerializar);
//}
template <typename T>
ElementKey<T>::~ElementKey(){
}
template <typename T>
bool ElementKey<T>::operator == (const ElementKey<T>& other) const{
return valor == other.valor;
}
template <typename T>
bool ElementKey<T>::operator != (const ElementKey<T>& other) const{
return !operator ==(other);
}
template <typename T>
ElementKey<T>& ElementKey<T>::operator=(const ElementKey<T>& elem){
if (&elem != this) {
valor = elem.valor;
}
return *this;
}
template <typename T>
T& ElementKey<T>::operator=(const T& elem){
valor = elem.valor;
return *this;
}
template <typename T>
const T& ElementKey<T>::getValor()const{
return valor;
}
template <typename T>
string ElementKey<T>::serializar()const{
if (valor == "") {
//No deberia poder pasar esto
return "NULL";
}
string strRetorno;
ostringstream retorno;
retorno << (T)valor;
strRetorno = retorno.str();
return strRetorno;
}
template <typename T>
void ElementKey<T>::desSerializar(const string aDesSerializar){
T intermedio;
istringstream stream;
stream.str(aDesSerializar);
stream >> intermedio;
valor = (intermedio);
}
#endif /* ELEMENTKEY_H_ */
| [
"quimey.funes@gmail.com@583faab1-8ff4-330b-46ab-0f14db74188c"
] | quimey.funes@gmail.com@583faab1-8ff4-330b-46ab-0f14db74188c |
dda08b74a41ff72f22f4b2d9660f9f3d6e395bf1 | 492976adfdf031252c85de91a185bfd625738a0c | /src/Game/AI/Action/actionPlayerLadderUpStart.h | 969401e355407f212a5e43a4ebefb35691d124d6 | [] | no_license | zeldaret/botw | 50ccb72c6d3969c0b067168f6f9124665a7f7590 | fd527f92164b8efdb746cffcf23c4f033fbffa76 | refs/heads/master | 2023-07-21T13:12:24.107437 | 2023-07-01T20:29:40 | 2023-07-01T20:29:40 | 288,736,599 | 1,350 | 117 | null | 2023-09-03T14:45:38 | 2020-08-19T13:16:30 | C++ | UTF-8 | C++ | false | false | 578 | h | #pragma once
#include "Game/AI/Action/actionPlayerAction.h"
#include "KingSystem/ActorSystem/actAiAction.h"
namespace uking::action {
class PlayerLadderUpStart : public PlayerAction {
SEAD_RTTI_OVERRIDE(PlayerLadderUpStart, PlayerAction)
public:
explicit PlayerLadderUpStart(const InitArg& arg);
void enter_(ksys::act::ai::InlineParamPack* params) override;
void leave_() override;
void loadParams_() override;
protected:
void calc_() override;
// static_param at offset 0x20
const float* mJumpHeight_s{};
};
} // namespace uking::action
| [
"leo@leolam.fr"
] | leo@leolam.fr |
233f76856342740d2deae9468a980870e3f633c3 | a81c5b9f19b8bb68d8aad5ca006a3211ba50484b | /data/1010/answer.cpp | ea2a448091f0c2be818da9ffe04376c0806e2cae | [] | no_license | weizengke/oj-data | 1d30fdf81368ff07780b09f3da0a71ef783241fe | efd712bec48f647d0329ecc3b6da5e4d927c1ab9 | refs/heads/master | 2020-06-10T23:37:48.198362 | 2016-12-10T11:54:19 | 2016-12-10T11:54:19 | 75,842,330 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,320 | cpp | #include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <queue>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <string>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
using namespace std;
typedef struct {
char name[20];
int gold;
int silver;
int bronze;
}CONUTRY;
int comp(const void *a,const void *b)
{
if((*(CONUTRY *)a).gold!=(*(CONUTRY *)b).gold) return (*(CONUTRY *)b).gold-(*(CONUTRY *)a).gold;
if((*(CONUTRY *)a).silver!=(*(CONUTRY *)b).silver) return (*(CONUTRY *)b).silver-(*(CONUTRY *)a).silver;
if((*(CONUTRY *)a).bronze!=(*(CONUTRY *)b).bronze) return (*(CONUTRY *)b).bronze-(*(CONUTRY *)a).bronze;
return strcmp((*(CONUTRY *)a).name,(*(CONUTRY *)b).name);
}
int main(){
int n;
CONUTRY a[21];
int i;
//freopen("data.in","r",stdin);
while(cin>>n){
for(i=0;i<n;i++) {
cin>>a[i].name>>a[i].gold>>a[i].silver>>a[i].bronze;
}
qsort(a,n,sizeof(a[0]),comp);
for(i=0;i<n;i++) {
cout<<a[i].name<<endl;
}
}
return 0;
}
| [
"weizengke@users.noreply.github.com"
] | weizengke@users.noreply.github.com |
a97ff729032e268d8dd35e8ee7bb6e97dda2c957 | 9030ce2789a58888904d0c50c21591632eddffd7 | /SDK/ARKSurvivalEvolved_WorldSettingsEventOverrides_Ragnarok_functions.cpp | 8a5d05d570b5ff0183f6a7e626639647ec72b902 | [
"MIT"
] | permissive | 2bite/ARK-SDK | 8ce93f504b2e3bd4f8e7ced184980b13f127b7bf | ce1f4906ccf82ed38518558c0163c4f92f5f7b14 | refs/heads/master | 2022-09-19T06:28:20.076298 | 2022-09-03T17:21:00 | 2022-09-03T17:21:00 | 232,411,353 | 14 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 1,225 | cpp | // ARKSurvivalEvolved (332.8) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "ARKSurvivalEvolved_WorldSettingsEventOverrides_Ragnarok_parameters.hpp"
namespace sdk
{
//---------------------------------------------------------------------------
//Functions
//---------------------------------------------------------------------------
// Function WorldSettingsEventOverrides_Ragnarok.WorldSettingsEventOverrides_Ragnarok_C.ExecuteUbergraph_WorldSettingsEventOverrides_Ragnarok
// ()
// Parameters:
// int EntryPoint (Parm, ZeroConstructor, IsPlainOldData)
void UWorldSettingsEventOverrides_Ragnarok_C::ExecuteUbergraph_WorldSettingsEventOverrides_Ragnarok(int EntryPoint)
{
static auto fn = UObject::FindObject<UFunction>("Function WorldSettingsEventOverrides_Ragnarok.WorldSettingsEventOverrides_Ragnarok_C.ExecuteUbergraph_WorldSettingsEventOverrides_Ragnarok");
UWorldSettingsEventOverrides_Ragnarok_C_ExecuteUbergraph_WorldSettingsEventOverrides_Ragnarok_Params params;
params.EntryPoint = EntryPoint;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"sergey.2bite@gmail.com"
] | sergey.2bite@gmail.com |
8f5202ca240cf44fb7dd54d766af85953595573b | 4f63be3e3611466511742491cb18797ebcfd9f57 | /shouyou/common/LibHNLobby/HNLobby/GameMenu/GameLandLayer.cpp | 4de0bb526aa5bf6f9f6f1f71cca5ee8d35db03f2 | [] | no_license | xubingyue/wulejiu | 0a9083c08270b453dff316cc827d943908572559 | ee71a1e299b700436f01c3acab7e4617826b9f85 | refs/heads/master | 2020-05-24T06:38:40.276805 | 2017-03-30T05:54:12 | 2017-03-30T05:54:12 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 6,705 | cpp | #include "HNLobby/GameMenu/GameLandLayer.h"
#include "HNLobby/PlatformDefine.h"
#include "HNLobby/GamePrompt.h"
static const char* LANDUI_PATH = "platform/LoginorRegistUi/Login/loginUI.csb";
#define Word_Empty_Name GBKToUtf8("账号不能为空!")
#define Word_Empty_Pass GBKToUtf8("密码不能为空!")
LandLayer::LandLayer()
: onLoginCallBack(nullptr)
, onCloseCallBack(nullptr)
, onRegistCallBack(nullptr)
, _isGetPassWord(false)
, _isOpenLayer(true)
{
memset(&_landUI, 0x0, sizeof(_landUI));
}
LandLayer::~LandLayer()
{
}
void LandLayer::closeLand()
{
_landUI.backGround->runAction(Sequence::create(ScaleTo::create(0.1f, 0.1f), CCCallFunc::create([&]()
{
if (nullptr != onCloseCallBack)
{
onCloseCallBack();
}
this->removeFromParent();
}), nullptr));
}
bool LandLayer::init()
{
if (!HNLayer::init()) return false;
//屏蔽后面的层
colorLayer = LayerColor::create( Color4B( 0, 0, 0, 100));
addChild(colorLayer);
auto listener = EventListenerTouchOneByOne::create();
listener->setSwallowTouches(true);
listener->onTouchBegan = [&](Touch* touch, Event* event)
{
auto target = dynamic_cast<LandLayer*>(event->getCurrentTarget());
Point locationInNode = target->convertToNodeSpace(touch->getLocation());
Size s = target->getContentSize();
Rect rect = Rect( 0, 0, s.width, s.height);
if (rect.containsPoint(locationInNode))
{
return true;
}
else
{
return false;
}
};
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
Size winSize = Director::getInstance()->getWinSize();
// 登录界面ui
_landUI.landUI = CSLoader::createNode(LANDUI_PATH);
_landUI.landUI->setPosition(Vec2(winSize / 2));
addChild(_landUI.landUI, 2, 2);
auto landlayout = _landUI.landUI->getChildByName("Panel_1");
//登录背景
_landUI.backGround =(ImageView*)landlayout->getChildByName("Image_BG");
// 关闭按钮
Button* Btn_close = (Button*)_landUI.backGround->getChildByName("Button_close");
Btn_close->addTouchEventListener(CC_CALLBACK_2(LandLayer::closeEventCallback, this));
// 登陆按钮
Button* Btn_land = (Button*)_landUI.backGround->getChildByName("Button_land");
Btn_land->addTouchEventListener(CC_CALLBACK_2(LandLayer::landEventCallback, this));
// 注册帐号按钮
Button* Btn_regist = (Button*)_landUI.backGround->getChildByName("Button_regist");
Btn_regist->addTouchEventListener(CC_CALLBACK_2(LandLayer::registEventCallback, this));
auto userDefault = UserDefault::getInstance();
std::string username = userDefault->getStringForKey(USERNAME_TEXT);
std::string password = userDefault->getStringForKey(PASSWORD_TEXT);
bool save = userDefault->getBoolForKey(SAVE_TEXT);
// 账号输入框
auto TextField_userName = (TextField*)_landUI.backGround->getChildByName("TextField_userName");
TextField_userName->setVisible(false);
// 账号输入框
_landUI.editBoxUserName = HNEditBox::createEditBox(TextField_userName, this);
_landUI.editBoxUserName->setString(username);
// 保存密码复选框
_landUI.checkBoxSave = (CheckBox*)_landUI.backGround->getChildByName("CheckBox_save");
_landUI.checkBoxSave->setSelected(save);
_landUI.checkBoxSave->addEventListener(CheckBox::ccCheckBoxCallback(CC_CALLBACK_2( LandLayer::checkBoxCallback, this)));
// 密码输入框
auto textField_PassWord = (TextField* )_landUI.backGround->getChildByName("TextField_passWord");
textField_PassWord->setVisible(false);
// 密码输入框
_landUI.editBoxPassWord = HNEditBox::createEditBox(textField_PassWord, this);
_landUI.editBoxPassWord->setInputFlag(cocos2d::ui::EditBox::InputFlag::PASSWORD);
if (_landUI.checkBoxSave->isSelected())
{
_isGetPassWord = true;
_landUI.editBoxPassWord->setString("******");
}
return true;
}
void LandLayer::landEventCallback(Ref* pSender, Widget::TouchEventType type)
{
if (Widget::TouchEventType::ENDED != type) return;
auto btn = (Button*)pSender;
HNAudioEngine::getInstance()->playEffect(GAME_SOUND_BUTTON);
do
{
// 获取输入框账号
std::string userName = _landUI.editBoxUserName->getString();
if (userName.empty())
{
GamePromptLayer::create()->showPrompt(Word_Empty_Name);
break;
}
// 获取输入框密码
std::string passWord = _landUI.editBoxPassWord->getString();
if (passWord.empty())
{
GamePromptLayer::create()->showPrompt(Word_Empty_Pass);
break;
}
auto userdefault = UserDefault::getInstance();
std::string savePassWord = userdefault->getStringForKey(PASSWORD_TEXT);
if (nullptr != onLoginCallBack)
{
if (_isGetPassWord)
{
onLoginCallBack(userName, savePassWord);
}
else
{
passWord = MD5_CTX::MD5String(passWord);
onLoginCallBack(userName, passWord);
}
}
} while (0);
}
void LandLayer::closeEventCallback(Ref* pSender, Widget::TouchEventType type)
{
Button* selectedBtn = (Button*)pSender;
switch (type)
{
case cocos2d::ui::Widget::TouchEventType::BEGAN:
selectedBtn->setColor(Color3B(170,170,170));
break;
case cocos2d::ui::Widget::TouchEventType::ENDED:
{
HNAudioEngine::getInstance()->playEffect(GAME_SOUND_CLOSE);
selectedBtn->setColor(Color3B(255,255,255));
closeLand();
}
break;
case cocos2d::ui::Widget::TouchEventType::CANCELED:
selectedBtn->setColor(Color3B(255,255,255));
break;
default:
break;
}
}
void LandLayer::checkBoxCallback(Ref* pSender, CheckBox::EventType type)
{
auto userDefault = UserDefault::getInstance();
switch (type)
{
case cocos2d::ui::CheckBox::EventType::SELECTED:
userDefault->setBoolForKey(SAVE_TEXT, true);
break;
case cocos2d::ui::CheckBox::EventType::UNSELECTED:
userDefault->setBoolForKey(SAVE_TEXT, false);
_landUI.editBoxPassWord->setText("");
break;
default:
break;
}
userDefault->flush();
}
// 注册按钮回调函数
void LandLayer::registEventCallback(Ref* pSender, Widget::TouchEventType type)
{
if (Widget::TouchEventType::ENDED != type) return;
auto btn = (Button*)pSender;
auto winSize = Director::getInstance()->getWinSize();
HNAudioEngine::getInstance()->playEffect(GAME_SOUND_CLOSE);
_landUI.backGround->runAction(Sequence::create(ScaleTo::create(0.1f, 0.1f), CCCallFunc::create([&](){
if (nullptr != onRegistCallBack)
{
onRegistCallBack();
}
this->removeFromParent();
}), nullptr));
}
void LandLayer::editBoxEditingDidBegin(EditBox* editBox)
{
_isOpenLayer = false;
}
void LandLayer::editBoxTextChanged(ui::EditBox* editBox, const std::string& text)
{
if (!_isOpenLayer)
{
if (editBox == _landUI.editBoxPassWord && text != "******")
{
if (_isGetPassWord)
{
UserDefault::getInstance()->setStringForKey(PASSWORD_TEXT, "0");
_isGetPassWord = false;
}
}
}
}
| [
"zhifeng.zhang@ericsson.com"
] | zhifeng.zhang@ericsson.com |
d4e367374ce52ea361fa93117889f301b16f8e2a | d364d54a2085ce7d6566fc5c7241657c693f7392 | /IPS_UWB/IU_KalmanFiltercpp.cpp | 1f9fbc620c0e9dce0c58c95a80a476f093a3f0df | [] | no_license | yongwoojung90/IPS_UWB-IU- | 0790fba74665ef23661ce97a1587fc10c6ea4e03 | 3b6fbc585dafd6536ce98c0fa15995ea32953574 | refs/heads/master | 2020-05-18T18:45:40.974849 | 2015-08-23T09:57:47 | 2015-08-23T09:57:47 | 39,962,593 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 799 | cpp |
float KalmanFilter(int AnchorNumber, float distance, float Q = 0.0071f, float R = 0.608f)
{
static float xhat[4] = { 0.0f, };
static float P[4] = { 0.0f, };
static float xhatbar[4] = { 0.0f, };
static float Pbar[4] = { 0.0f, };
static float K[4] = { 0.0f, };
static float xhat_last[4] = { 0.0f, };
static float P_last[4] = { 1, 1, 1, 1 };
xhatbar[AnchorNumber] = xhat_last[AnchorNumber];
Pbar[AnchorNumber] = P_last[AnchorNumber] + Q;
K[AnchorNumber] = Pbar[AnchorNumber] / (Pbar[AnchorNumber] + R);
xhat[AnchorNumber] = xhatbar[AnchorNumber] + (K[AnchorNumber] * (distance - xhatbar[AnchorNumber]));
P[AnchorNumber] = (1 - K[AnchorNumber]) * Pbar[AnchorNumber];
xhat_last[AnchorNumber] = xhat[AnchorNumber];
P_last[AnchorNumber] = P[AnchorNumber];
return xhat[AnchorNumber];
} | [
"loyyd03@gmail.com"
] | loyyd03@gmail.com |
ee3d66c22a6dc5cae406b70f962e11b920763c96 | 9a3b9d80afd88e1fa9a24303877d6e130ce22702 | /src/Providers/UNIXProviders/ComputerSystemMappedIO/UNIX_ComputerSystemMappedIO_LINUX.hxx | d547973352c259ca75996eb9e770981130a2b389 | [
"MIT"
] | permissive | brunolauze/openpegasus-providers | 3244b76d075bc66a77e4ed135893437a66dd769f | f24c56acab2c4c210a8d165bb499cd1b3a12f222 | refs/heads/master | 2020-04-17T04:27:14.970917 | 2015-01-04T22:08:09 | 2015-01-04T22:08:09 | 19,707,296 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,829 | hxx | //%LICENSE////////////////////////////////////////////////////////////////
//
// Licensed to The Open Group (TOG) under one or more contributor license
// agreements. Refer to the OpenPegasusNOTICE.txt file distributed with
// this work for additional information regarding copyright ownership.
// Each contributor licenses this file to you under the OpenPegasus Open
// Source License; you may not use this file except in compliance with the
// License.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//////////////////////////////////////////////////////////////////////////
//
//%/////////////////////////////////////////////////////////////////////////
#ifdef PEGASUS_OS_LINUX
#ifndef __UNIX_COMPUTERSYSTEMMAPPEDIO_PRIVATE_H
#define __UNIX_COMPUTERSYSTEMMAPPEDIO_PRIVATE_H
#endif
#endif
| [
"brunolauze@msn.com"
] | brunolauze@msn.com |
9345f32510a54e57af649dbb7c0547d609286bcf | 356f993d63c9944b2c513e83b8f8a83b2aea5aab | /src/bufferManager.h | fa1b6876143e663409dcdb383d791c56e68abc17 | [
"MIT"
] | permissive | kuruvajayakrishna/SimpleRA | 9fc1ef133da32cad8aa37c416b89a874fab37eb9 | e4cc10dc533f5ee8855000a53e0c7dd49588bf11 | refs/heads/master | 2023-01-02T23:19:23.526608 | 2020-11-02T06:36:54 | 2020-11-02T06:36:54 | 308,888,499 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,696 | h | #include"page.h"
/**
* @brief The BufferManager is responsible for reading pages to the main memory.
* Recall that large files are broken and stored as blocks in the hard disk. The
* minimum amount of memory that can be read from the disk is a block whose size
* is indicated by BLOCK_SIZE. within this system we simulate blocks by
* splitting and storing the file as multiple files each of one BLOCK_SIZE,
* although this isn't traditionally how it's done. You can alternatively just
* random access to the point where a block begins within the same
* file. In this system we assume that the the sizes of blocks and pages are the
* same.
*
* <p>
* The buffer can hold multiple pages quantified by BLOCK_COUNT. The
* buffer manager follows the FIFO replacement policy i.e. the first block to be
* read in is replaced by the new incoming block. This replacement policy should
* be transparent to the executors i.e. the executor should not know if a block
* was previously present in the buffer or was read in from the disk.
* </p>
*
*/
class BufferManager{
deque<Page> pages;
bool inPool(string pageName);
Page getFromPool(string pageName);
Page insertIntoPool(string tableName, int pageIndex,int entityType);
public:
BufferManager();
Page getPage(string tableName, int pageIndex,int entityType);
//void writePage(string pageName, vector<vector<int>> rows);
void deleteFile(string tableName, int pageIndex);
void deleteFile(string fileName);
void writePage(string tableName, int pageIndex, vector<vector<int>> rows, int rowCount);
void writePage(string tableName, int pageIndex, vector<int> rows, int elementCount);
}; | [
"jaya.krishna@students.iiit.ac.in"
] | jaya.krishna@students.iiit.ac.in |
62c81d208e03f710740801450369e31a1a395359 | 550ddc3654e88a1c014d467176ed6c1ec6512c5c | /tests/test-fox-host-3c.cpp | 4b18ead6e0538ddcbc4c6ef44c693b4e3592af5d | [
"MIT"
] | permissive | raultron/elementary-plotlib | 9af495f74cce86f553f423d39d6e216db120787b | 7e1c27c06eae98e3bf0fd0e56ae4c2beafa115f7 | refs/heads/master | 2022-06-02T19:40:18.738996 | 2020-04-29T21:59:50 | 2020-04-29T21:59:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,800 | cpp | #include <cmath>
#include <thread>
#include "elem/elem.h"
#include "elem/elem_fox.h"
#include "elem/elem_utils.h"
using namespace elem;
class PlotWindow : public FXMainWindow {
FXDECLARE(PlotWindow)
protected:
PlotWindow() { }
private:
PlotWindow(const PlotWindow&);
PlotWindow &operator=(const PlotWindow&);
public:
PlotWindow(FXApp* a, const FXString& name, FXIcon *ic=NULL, FXIcon *mi=NULL, FXuint opts=DECOR_ALL,FXint x=0,FXint y=0,FXint w=0,FXint h=0,FXint pl=0,FXint pr=0,FXint pt=0,FXint pb=0,FXint hs=0,FXint vs=0):
FXMainWindow(a, name, ic, mi, opts, x, y, w, h, pl, pr, pt, pb, hs, vs) {
start_signal = new FXGUISignal(a, this, ID_PLOT_WINDOW_START, nullptr);
frame = new FXVerticalFrame(this, LAYOUT_FILL_X|LAYOUT_FILL_Y);
new FXLabel(frame, "Window Plot demonstrator");
}
~PlotWindow() {
delete start_signal;
}
long onElemWindowStart(FXObject *, FXSelector, void *);
enum {
ID_PLOT_WINDOW_START = FXApp::ID_LAST,
ID_LAST,
};
FXVerticalFrame *frame;
FXGUISignal *start_signal;
};
FXDEFMAP(PlotWindow) PlotWindowMap[] = {
FXMAPFUNC(SEL_IO_READ, PlotWindow::ID_PLOT_WINDOW_START, PlotWindow::onElemWindowStart),
};
FXIMPLEMENT(PlotWindow, FXMainWindow, PlotWindowMap, ARRAYNUMBER(PlotWindowMap))
long PlotWindow::onElemWindowStart(FXObject *, FXSelector, void *ptr) {
FXElemStartMessage *message = (FXElemStartMessage *) ptr;
if (!message) {
fprintf(stderr, "internal error: no message data with window's start signal\n");
return 1;
}
FXElemBuildWindow(this->frame, LAYOUT_FILL_X | LAYOUT_FILL_Y, message, ELEM_CREATE_NOW);
return 1;
}
Plot CreateNewPlot() {
Plot plot;
const double x0 = 0.0001, x1 = 8 * math::Tau();
plot.AddStroke(FxLine(x0, x1, [](double x) { return std::sin(x) / x; }), color::Blue, 1.5);
plot.SetTitle("Function plot example");
plot.SetXAxisTitle("x variable");
return plot;
}
void WorkerThreadStart() {
utils::Sleep(3);
Window win;
Plot plot = CreateNewPlot();
win.Attach(plot, "");
win.Start(640, 480, WindowResize);
utils::Sleep(1);
const double x0 = 0.8, x1 = 8 * math::Tau();
plot.AddStroke(FxLine(x0, x1, [](double x) { return std::cos(x) / x; }), color::Red, 1.5);
win.Wait();
}
int main(int argc, char *argv[]) {
FXApp app("Plot Windows", "elem_plot");
app.init(argc, argv);
auto main_window = new PlotWindow(&app, "FOX Window host example", nullptr, nullptr, DECOR_ALL, 0, 0, 640, 480);
InitializeFonts();
SetFoxWindowSystem(main_window->start_signal);
std::thread worker_thread(WorkerThreadStart);
app.create();
main_window->show(PLACEMENT_SCREEN);
app.run();
worker_thread.join();
return 0;
}
| [
"francesco.bbt@gmail.com"
] | francesco.bbt@gmail.com |
2d02478c7bd177d5ca3ea0a9bf7fc12d3ddb996e | b23eb2466e6062343fac925f947eef61e3f41e41 | /mace/ops/opencl/image/lstm_cell.h | 265f2e10f9f536db9a692bf15d966153c05949e6 | [
"Apache-2.0"
] | permissive | lee-bin/mace | 9c7486a53fcb491727f45a404d14f5dd728ae54b | aca4c5e2a3496cca955d45460eb976fe765d6f14 | refs/heads/master | 2021-07-16T02:58:04.406458 | 2018-12-24T10:40:56 | 2018-12-24T10:40:56 | 138,960,617 | 0 | 0 | Apache-2.0 | 2018-06-28T03:16:42 | 2018-06-28T03:16:42 | null | UTF-8 | C++ | false | false | 4,917 | h | // Copyright 2018 Xiaomi, Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef MACE_OPS_OPENCL_IMAGE_LSTM_CELL_H_
#define MACE_OPS_OPENCL_IMAGE_LSTM_CELL_H_
#include "mace/ops/opencl/lstm_cell.h"
#include <memory>
#include <vector>
#include <set>
#include <string>
#include "mace/core/op_context.h"
#include "mace/core/tensor.h"
#include "mace/ops/opencl/helper.h"
namespace mace {
namespace ops {
namespace opencl {
namespace image {
template <typename T>
class LSTMCellKernel : public OpenCLLSTMCellKernel {
public:
explicit LSTMCellKernel(
const T forget_bias)
: forget_bias_(forget_bias) {}
MaceStatus Compute(
OpContext *context,
const Tensor *input,
const Tensor *pre_output,
const Tensor *weight,
const Tensor *bias,
const Tensor *pre_cell,
Tensor *cell,
Tensor *output) override;
private:
T forget_bias_;
cl::Kernel kernel_;
uint32_t kwg_size_;
std::vector<index_t> input_shape_;
};
template <typename T>
MaceStatus LSTMCellKernel<T>::Compute(
OpContext *context,
const Tensor *input,
const Tensor *pre_output,
const Tensor *weight,
const Tensor *bias,
const Tensor *pre_cell,
Tensor *cell,
Tensor *output) {
MACE_CHECK(pre_output->dim_size() == 2 && pre_output->dim(1) % 4 == 0,
"LSTM hidden units should be a multiple of 4");
const index_t height = input->dim(0);
const index_t width = input->dim(1);
const index_t hidden_units = pre_output->dim(1);
const index_t w_blocks = hidden_units >> 2;
auto runtime = context->device()->gpu_runtime()->opencl_runtime();
MACE_OUT_OF_RANGE_DEFINITION;
if (kernel_.get() == nullptr) {
std::set<std::string> built_options;
MACE_OUT_OF_RANGE_CONFIG;
MACE_NON_UNIFORM_WG_CONFIG;
auto dt = DataTypeToEnum<T>::value;
std::string kernel_name = MACE_OBFUSCATE_SYMBOL("lstmcell");
built_options.emplace("-Dlstmcell=" + kernel_name);
built_options.emplace("-DDATA_TYPE=" + DtToUpCompatibleCLDt(dt));
built_options.emplace("-DCMD_DATA_TYPE=" + DtToUpCompatibleCLCMDDt(dt));
MACE_RETURN_IF_ERROR(runtime->BuildKernel("lstmcell", kernel_name,
built_options, &kernel_));
kwg_size_ =
static_cast<uint32_t>(runtime->GetKernelMaxWorkGroupSize(kernel_));
}
const uint32_t gws[2] = {static_cast<uint32_t>(w_blocks),
static_cast<uint32_t>(height)};
MACE_OUT_OF_RANGE_INIT(kernel_);
if (!IsVecEqual(input_shape_, input->shape())) {
std::vector<index_t> output_shape_padded = {height, 1, 1, hidden_units};
std::vector<size_t> output_image_shape;
OpenCLUtil::CalImage2DShape(output_shape_padded,
OpenCLBufferType::IN_OUT_CHANNEL,
&output_image_shape);
MACE_RETURN_IF_ERROR(output->ResizeImage(pre_output->shape(),
output_image_shape));
MACE_RETURN_IF_ERROR(cell->ResizeImage(pre_cell->shape(),
output_image_shape));
uint32_t idx = 0;
MACE_OUT_OF_RANGE_SET_ARGS(kernel_);
MACE_SET_2D_GWS_ARGS(kernel_, gws);
kernel_.setArg(idx++, *(input->opencl_image()));
kernel_.setArg(idx++, *(pre_output->opencl_image()));
kernel_.setArg(idx++, *(weight->opencl_image()));
kernel_.setArg(idx++, *(bias->opencl_image()));
kernel_.setArg(idx++, *(pre_cell->opencl_image()));
kernel_.setArg(idx++, static_cast<float>(forget_bias_));
kernel_.setArg(idx++, static_cast<int32_t>(width));
kernel_.setArg(idx++, static_cast<int32_t>(hidden_units));
kernel_.setArg(idx++, static_cast<int32_t>(RoundUpDiv4(width)));
kernel_.setArg(idx++, *(cell->opencl_image()));
kernel_.setArg(idx++, *(output->opencl_image()));
input_shape_ = input->shape();
}
const std::vector<uint32_t> lws = {kwg_size_ / 16, 16, 0};
std::string tuning_key =
Concat("lstmcell_opencl_kernel", output->dim(0), output->dim(1));
MACE_RETURN_IF_ERROR(TuningOrRun2DKernel(runtime, kernel_, tuning_key,
gws, lws, context->future()));
MACE_OUT_OF_RANGE_VALIDATION;
return MaceStatus::MACE_SUCCESS;
}
} // namespace image
} // namespace opencl
} // namespace ops
} // namespace mace
#endif // MACE_OPS_OPENCL_IMAGE_LSTM_CELL_H_
| [
"liuqi10@xiaomi.com"
] | liuqi10@xiaomi.com |
66e44bd6975af4651c0350cb7cf3d9f2c0bd364b | bd44a0828f1819117f3848f57d5d1a8116d89f0c | /mainwindow.cpp | d0ec3f0140cc7f320034ba90dc4ec7c7412091cf | [] | no_license | MilletWorkStation/MilletPaint | 6568ea9a34de3af220730a320c92b45be68f8a96 | 07d531525a98c3870a7da6ec6cafc7fb49ff9c3d | refs/heads/main | 2023-05-13T08:09:44.411059 | 2021-06-08T08:24:22 | 2021-06-08T08:24:22 | 374,930,725 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,908 | cpp | #include "drawscene.h"
#include "drawtool.h"
#include "drawview.h"
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDockWidget>
#include <QGraphicsRectItem>
#include <QGraphicsScene>
#include <QGraphicsView>
#include <QMenu>
#include <QMessageBox>
#include <QSignalMapper>
#include <QtMath>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
// QDockWidget *dock = new QDockWidget(this);
// addDockWidget(Qt::RightDockWidgetArea, dock);
m_pMdiArea = new QMdiArea(this);
m_pMdiArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
m_pMdiArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
setCentralWidget(m_pMdiArea);
setWindowTitle(tr("Millet Paint"));
CreateMenuBar();
CreateToolBar();
New();
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::CreateAction()
{
m_pFileNew = new QAction("&New", this);
m_pFileNew->setShortcut(QKeySequence::New);
m_pFileNew->setStatusTip("Create a new file");
connect(m_pFileNew, SIGNAL(triggered()), this, SLOT(New()));
m_pFileOpen = new QAction("&Open", this);
m_pFileOpen->setShortcut(QKeySequence::Open);
m_pFileOpen->setStatusTip("Open file");
connect(m_pFileOpen, SIGNAL(triggered()), this, SLOT(Open()));
m_pFileSave = new QAction("&Save", this);
m_pFileSave->setShortcut(QKeySequence::Save);
m_pFileSave->setStatusTip("Save file");
m_pFileSave->setEnabled(false);
connect(m_pFileSave, SIGNAL(triggered()), this, SLOT(Save()));
m_pFileQuit = new QAction("&Quit", this);
m_pFileQuit->setShortcut(QKeySequence::Quit);
m_pFileQuit->setStatusTip("Quit App");
connect(m_pFileQuit, SIGNAL(triggered()), this, SLOT(Quit()));
// Edit
m_pEditUndo = new QAction("&Undo", this);
m_pEditUndo->setShortcut(QKeySequence::Undo);
m_pEditUndo->setStatusTip("Undo");
m_pEditUndo->setEnabled(false);
m_pEditUndo->setIcon(QIcon(":icons/undo.png"));
m_pEditRedo = new QAction("&Redo", this);
m_pEditRedo->setShortcut(QKeySequence::Redo);
m_pEditRedo->setStatusTip("Redo");
m_pEditRedo->setEnabled(false);
m_pEditRedo->setIcon(QIcon(":icons/redo.png"));
m_pEditCut = new QAction("&Cut", this);
m_pEditCut->setShortcut(QKeySequence::Cut);
m_pEditCut->setStatusTip("Cut");
m_pEditCut->setEnabled(false);
m_pEditCut->setIcon(QIcon(":icons/cut.png"));
m_pEditCopy = new QAction("&Copy", this);
m_pEditCopy->setShortcut(QKeySequence::Copy);
m_pEditCopy->setStatusTip("Copy");
m_pEditCopy->setEnabled(false);
m_pEditCopy->setIcon(QIcon(":icons/copy.png"));
m_pEditPaste = new QAction("&Paste", this);
m_pEditPaste->setShortcut(QKeySequence::Paste);
m_pEditPaste->setStatusTip("Paste");
m_pEditPaste->setEnabled(false);
m_pEditPaste->setIcon(QIcon(":icons/paste.png"));
m_pEditDelete = new QAction("&Delete", this);
m_pEditDelete->setShortcut(QKeySequence::Delete);
m_pEditDelete->setStatusTip("Delete");
m_pEditDelete->setEnabled(false);
m_pEditDelete->setIcon(QIcon(":icons/delete.png"));
// View
m_pViewZoomIn = new QAction("&Zoom In", this);
m_pViewZoomIn->setIcon(QIcon(":icons/zoomin.png"));
connect(m_pViewZoomIn, SIGNAL(triggered()), this, SLOT(ZoomIn()));
m_pViewZoomOut = new QAction("&Zoom Out", this);
m_pViewZoomOut->setIcon(QIcon(":icons/zoomout.png"));
connect(m_pViewZoomOut, SIGNAL(triggered()), this, SLOT(ZoomOut()));
// tool
m_pToolsShapeSelect = new QAction("&Select", this);
m_pToolsShapeSelect->setIcon(QIcon(":icons/arrow.png"));
// shape
m_pToolsShapeLine = new QAction("&Line", this);
m_pToolsShapeLine->setIcon(QIcon(":icons/line.png"));
connect(m_pToolsShapeLine, SIGNAL(triggered()), this, SLOT(AddShape()));
m_pToolsShapeRect = new QAction("&Rect", this);
m_pToolsShapeRect->setIcon(QIcon(":icons/rectangle.png"));
// 根据发送者去判定需要添加什么类型的图形
connect(m_pToolsShapeRect, SIGNAL(triggered()), this, SLOT(AddShape()));
m_pToolsShapeRoundRect = new QAction("&Round Rect", this);
m_pToolsShapeRoundRect->setIcon(QIcon(":icons/roundrect.png"));
connect(m_pToolsShapeRect, SIGNAL(triggered()), this, SLOT(AddShape()));
m_pToolsShapeEllipse = new QAction("&Ellipse", this);
m_pToolsShapeEllipse->setIcon(QIcon(":icons/ellipse.png"));
connect(m_pToolsShapeEllipse, SIGNAL(triggered()), this, SLOT(AddShape()));
m_pToolsShapePolygon = new QAction("&Ploygon", this);
m_pToolsShapePolygon->setIcon(QIcon(":icons/polygon.png"));
connect(m_pToolsShapePolygon, SIGNAL(triggered()), this, SLOT(AddShape()));
m_pToolsShapePolyline = new QAction("&Polyline", this);
m_pToolsShapePolyline->setIcon(QIcon(":icons/polyline.png"));
connect(m_pToolsShapePolyline, SIGNAL(triggered()), this, SLOT(AddShape()));
m_pToolsShapeBezier = new QAction("&Bezier", this);
m_pToolsShapeBezier->setIcon(QIcon(":icons/bezier.png"));
connect(m_pToolsShapeBezier, SIGNAL(triggered()), this, SLOT(AddShape()));
m_pToolsShapeRotate = new QAction("&Rotate", this);
m_pToolsShapeRotate->setIcon(QIcon(":icons/rotate.png"));
connect(m_pToolsShapeRotate, SIGNAL(triggered()), this, SLOT(AddShape()));
// align
m_pToolsAlignRight = new QAction("&Right", this);
m_pToolsAlignRight->setIcon(QIcon(":icons/align_right.png"));
m_pToolsAlignLeft = new QAction("&Left", this);
m_pToolsAlignLeft->setIcon(QIcon(":icons/align_left.png"));
m_pToolsAlignHCenter = new QAction("&H Center", this);
m_pToolsAlignHCenter->setIcon(QIcon(":icons/align_hcenter.png"));
m_pToolsAlignVCenter = new QAction("&V Center", this);
m_pToolsAlignVCenter->setIcon(QIcon(":icons/align_vcenter.png"));
m_pToolsAlignTop = new QAction("&Top", this);
m_pToolsAlignTop->setIcon(QIcon(":icons/align_top.png"));
m_pToolsAlignBottom = new QAction("&Bottom", this);
m_pToolsAlignBottom->setIcon(QIcon(":icons/align_bottom.png"));
m_pToolsAlignHorizontal = new QAction("&Horizontal", this);
m_pToolsAlignHorizontal->setIcon(QIcon(":icons/align_horzeven.png"));
m_pToolsAlignVertical = new QAction("&Vertical", this);
m_pToolsAlignVertical->setIcon(QIcon(":icons/align_verteven.png"));
m_pToolsAlignHeight = new QAction("&Height", this);
m_pToolsAlignHeight->setIcon(QIcon(":icons/align_height.png"));
m_pToolsAlignWidth = new QAction("&Width", this);
m_pToolsAlignWidth->setIcon(QIcon(":icons/align_width.png"));
m_pToolsAlignWidthAndHeight = new QAction("&Width And Height", this);
m_pToolsAlignWidthAndHeight->setIcon(QIcon(":icons/align_all.png"));
// window
m_pWindowClose = new QAction("&Close", this);
m_pWindowCloseAll = new QAction("&Close All", this);
m_pWindowTitle = new QAction("&Title", this);
m_pWindowCascade = new QAction("&Cascade", this);
m_pWindowNext = new QAction("&Next", this);
m_pWindowPrevious = new QAction("&Previous", this);
// help
m_pHelpAbout = new QAction("&About", this);
m_pHelpAboutQt = new QAction("&About Qt", this);
m_pHelpFuncTest = new QAction("&Func Test", this);
}
void MainWindow::CreateMenuBar()
{
CreateAction();
QMenu * pMenu = nullptr;
// File
pMenu = new QMenu("&File", this);
pMenu->addAction(m_pFileNew);
pMenu->addAction(m_pFileOpen);
pMenu->addAction(m_pFileSave);
pMenu->addSeparator();
pMenu->addAction(m_pFileQuit);
ui->menubar->addMenu(pMenu);
// Edit
pMenu = new QMenu("&Edit", this);
pMenu->addAction(m_pEditUndo);
pMenu->addAction(m_pEditRedo);
pMenu->addAction(m_pEditCut);
pMenu->addAction(m_pEditCopy);
pMenu->addAction(m_pEditPaste);
pMenu->addAction(m_pEditDelete);
ui->menubar->addMenu(pMenu);
// View
pMenu = new QMenu("&View", this);
pMenu->addAction(m_pViewZoomIn);
pMenu->addAction(m_pViewZoomOut);
ui->menubar->addMenu(pMenu);
// Tools
pMenu = new QMenu("&Tools", this);
pMenu->addAction(m_pToolsShapeSelect);
QMenu * pShape = new QMenu("Shape", this);
pShape->addAction(m_pToolsShapeLine);
pShape->addAction(m_pToolsShapeRect);
pShape->addAction(m_pToolsShapeRoundRect);
pShape->addAction(m_pToolsShapeEllipse);
pShape->addAction(m_pToolsShapePolygon);
pShape->addAction(m_pToolsShapePolyline);
pShape->addAction(m_pToolsShapeBezier);
pShape->addAction(m_pToolsShapeRotate);
pMenu->addMenu(pShape);
QMenu * pAlign = new QMenu("Align", this);
pAlign->addAction(m_pToolsAlignRight);
pAlign->addAction(m_pToolsAlignLeft);
pAlign->addAction(m_pToolsAlignHCenter);
pAlign->addAction(m_pToolsAlignVCenter);
pAlign->addAction(m_pToolsAlignTop);
pAlign->addAction(m_pToolsAlignBottom);
pAlign->addAction(m_pToolsAlignHorizontal);
pAlign->addAction(m_pToolsAlignVertical);
pAlign->addAction(m_pToolsAlignHeight);
pAlign->addAction(m_pToolsAlignWidth);
pAlign->addAction(m_pToolsAlignWidthAndHeight);
pMenu->addMenu(pAlign);
ui->menubar->addMenu(pMenu);
pMenu = new QMenu("&Window", this);
m_pWindowMenu = pMenu;
pMenu->addAction(m_pWindowClose);
pMenu->addAction(m_pWindowCloseAll);
pMenu->addSeparator();
pMenu->addAction(m_pWindowTitle);
pMenu->addAction(m_pWindowCascade);
pMenu->addSeparator();
pMenu->addAction(m_pWindowNext);
pMenu->addAction(m_pWindowPrevious);
pMenu->addSeparator();
ui->menubar->addMenu(pMenu);
pMenu = new QMenu("&Help", this);
pMenu->addAction(m_pHelpAbout);
pMenu->addAction(m_pHelpAboutQt);
pMenu->addAction(m_pHelpFuncTest);
ui->menubar->addMenu(pMenu);
}
void MainWindow::CreateToolBar()
{
// tool edit
m_pEditToolBar = addToolBar("Edit");
m_pEditToolBar->setIconSize(QSize(24, 24));
m_pEditToolBar->addAction(m_pEditUndo);
m_pEditToolBar->addAction(m_pEditRedo);
m_pEditToolBar->addAction(m_pEditCut);
m_pEditToolBar->addAction(m_pEditCopy);
m_pEditToolBar->addAction(m_pEditPaste);
// tool view
m_pViewToolBar = addToolBar("View");
m_pViewToolBar->addAction(m_pViewZoomIn);
m_pViewToolBar->addAction(m_pViewZoomOut);
// tool-Shape
m_pShapeToolBar = addToolBar("Shape");
m_pShapeToolBar->setIconSize(QSize(24, 24));
m_pShapeToolBar->addAction(m_pToolsShapeSelect);
m_pShapeToolBar->addAction(m_pToolsShapeLine);
m_pShapeToolBar->addAction(m_pToolsShapeRect);
m_pShapeToolBar->addAction(m_pToolsShapeRoundRect);
m_pShapeToolBar->addAction(m_pToolsShapeEllipse);
m_pShapeToolBar->addAction(m_pToolsShapePolygon);
m_pShapeToolBar->addAction(m_pToolsShapePolyline);
m_pShapeToolBar->addAction(m_pToolsShapeBezier);
m_pShapeToolBar->addAction(m_pToolsShapeRotate);
// tool-align
m_pAlignToolBar = addToolBar("Align");
m_pAlignToolBar->setIconSize(QSize(24, 24));
m_pAlignToolBar->addAction(m_pToolsAlignRight);
m_pAlignToolBar->addAction(m_pToolsAlignLeft);
m_pAlignToolBar->addAction(m_pToolsAlignHCenter);
m_pAlignToolBar->addAction(m_pToolsAlignVCenter);
m_pAlignToolBar->addAction(m_pToolsAlignTop);
m_pAlignToolBar->addAction(m_pToolsAlignBottom);
m_pAlignToolBar->addAction(m_pToolsAlignHorizontal);
m_pAlignToolBar->addAction(m_pToolsAlignVertical);
m_pAlignToolBar->addAction(m_pToolsAlignHeight);
m_pAlignToolBar->addAction(m_pToolsAlignWidth);
m_pAlignToolBar->addAction(m_pToolsAlignWidthAndHeight);
}
DrawView *MainWindow::CreateMdiChild()
{
DrawScene *scene = new DrawScene();
QRectF rc = this->rect();
scene->setSceneRect(rc);
scene->setBackgroundBrush(Qt::darkGray);
DrawView *view = new DrawView(scene);
connect(view,SIGNAL(PositionChanged(const int, const int)),this,SLOT(PositionChanged(const int, const int)));
// move orign point to leftbottom
view->setTransform(view->transform().scale(1,-1));
scene->setView(view);
m_pMdiArea->addSubWindow(view);
view->showMaximized();
return view;
}
void MainWindow::Open()
{
QMessageBox::information(this, "Open", "Open");
}
void MainWindow::New()
{
m_pView = CreateMdiChild();
}
void MainWindow::Save()
{
QMessageBox::information(this, "Save", "Save");
}
void MainWindow::Quit()
{
this->close();
}
void MainWindow::ZoomIn()
{
m_pView->zoomIn();
}
void MainWindow::ZoomOut()
{
m_pView->zoomOut();
}
void MainWindow::PositionChanged(const int x, const int y)
{
statusBar()->showMessage(QString("%1,%2").arg(x).arg(y));
}
void MainWindow::AddShape()
{
if ( sender() == m_pToolsShapeSelect )
DrawTool::c_drawShape = DS_Selection;
else if (sender() == m_pToolsShapeLine )
DrawTool::c_drawShape = DS_Line;
else if ( sender() == m_pToolsShapeRect )
DrawTool::c_drawShape = DS_Rectangle;
else if ( sender() == m_pToolsShapeRoundRect )
DrawTool::c_drawShape = DS_Roundrect;
else if ( sender() == m_pToolsShapeEllipse )
DrawTool::c_drawShape = DS_Ellipse ;
else if ( sender() == m_pToolsShapePolygon )
DrawTool::c_drawShape = DS_Polygon;
else if (sender() == m_pToolsShapePolyline )
DrawTool::c_drawShape = DS_Polyline;
else if ( sender() == m_pToolsShapeBezier )
DrawTool::c_drawShape = DS_Bezier ;
else if (sender() == m_pToolsShapeRotate )
DrawTool::c_drawShape = DS_Rotation;
// 非选中和旋转的情况下,清除选中的状态
if ( sender() != m_pToolsShapeSelect &&
sender() != m_pToolsShapeRotate )
{
m_pView->scene()->clearSelection();
}
}
| [
"15823159025@163.com"
] | 15823159025@163.com |
c1eb2b4526c2fc110b386e6d7062a7f835375503 | e39f12aa7a48639acfb61815403106c81dba925d | /Cxx11/dgemm.cc | 8b1560e55ec1fa4c7aacdeb37cad82d222c8ef73 | [
"BSD-3-Clause",
"LicenseRef-scancode-stream-benchmark"
] | permissive | illuhad/Kernels | e526ea97510d794432897c220f117cb3253e5028 | 8726a7543355fbbb9a0e187949fa87211bf59aed | refs/heads/master | 2020-07-09T01:50:36.399471 | 2019-08-08T23:55:09 | 2019-08-08T23:59:02 | 203,841,261 | 1 | 0 | NOASSERTION | 2019-08-22T17:22:04 | 2019-08-22T17:22:03 | null | UTF-8 | C++ | false | false | 7,687 | cc | ///
/// Copyright (c) 2017, Intel Corporation
///
/// 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 Intel Corporation nor the names of its
/// contributors may be used to endorse or promote products
/// derived from this software without specific prior written
/// permission.
///
/// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
/// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
/// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
/// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
/// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
/// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
/// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
/// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
/// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
/// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
/// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
/// POSSIBILITY OF SUCH DAMAGE.
//////////////////////////////////////////////////////////////////////
///
/// NAME: dgemm
///
/// PURPOSE: This program tests the efficiency with which a dense matrix
/// dense multiplication is carried out
///
/// USAGE: The program takes as input the matrix order,
/// the number of times the matrix-matrix multiplication
/// is carried out, and, optionally, a tile size for matrix
/// blocking
///
/// <progname> <# iterations> <matrix order> [<tile size>]
///
/// The output consists of diagnostics to make sure the
/// algorithm worked, and of timing statistics.
///
/// FUNCTIONS CALLED:
///
/// Other than OpenMP or standard C functions, the following
/// functions are used in this program:
///
/// wtime()
///
/// HISTORY: Written by Rob Van der Wijngaart, February 2009.
/// Converted to C++11 by Jeff Hammond, December, 2017.
///
//////////////////////////////////////////////////////////////////////
#include "prk_util.h"
void prk_dgemm(const int order,
const prk::vector<double> & A,
const prk::vector<double> & B,
prk::vector<double> & C)
{
PRAGMA_SIMD
for (auto i=0; i<order; ++i) {
PRAGMA_SIMD
for (auto k=0; k<order; ++k) {
PRAGMA_SIMD
for (auto j=0; j<order; ++j) {
C[i*order+j] += A[i*order+k] * B[k*order+j];
}
}
}
}
void prk_dgemm(const int order, const int tile_size,
const prk::vector<double> & A,
const prk::vector<double> & B,
prk::vector<double> & C)
{
for (auto it=0; it<order; it+=tile_size) {
for (auto jt=0; jt<order; jt+=tile_size) {
for (auto kt=0; kt<order; kt+=tile_size) {
// ICC will not hoist these on its own...
auto iend = std::min(order,it+tile_size);
auto jend = std::min(order,jt+tile_size);
auto kend = std::min(order,kt+tile_size);
PRAGMA_SIMD
for (auto i=it; i<iend; ++i) {
PRAGMA_SIMD
for (auto k=kt; k<kend; ++k) {
PRAGMA_SIMD
for (auto j=jt; j<jend; ++j) {
C[i*order+j] += A[i*order+k] * B[k*order+j];
}
}
}
}
}
}
}
int main(int argc, char * argv[])
{
//////////////////////////////////////////////////////////////////////
/// Read and test input parameters
//////////////////////////////////////////////////////////////////////
std::cout << "Parallel Research Kernels version " << PRKVERSION << std::endl;
std::cout << "C++11 Dense matrix-matrix multiplication: C += A x B" << std::endl;
int iterations;
int order;
int tile_size;
try {
if (argc < 3) {
throw "Usage: <# iterations> <matrix order> [tile size]";
}
iterations = std::atoi(argv[1]);
if (iterations < 1) {
throw "ERROR: iterations must be >= 1";
}
order = std::atoi(argv[2]);
if (order <= 0) {
throw "ERROR: Matrix Order must be greater than 0";
} else if (order > std::floor(std::sqrt(INT_MAX))) {
throw "ERROR: matrix dimension too large - overflow risk";
}
tile_size = (argc>3) ? std::atoi(argv[3]) : 32;
if (tile_size <= 0) tile_size = order;
}
catch (const char * e) {
std::cout << e << std::endl;
return 1;
}
std::cout << "Number of iterations = " << iterations << std::endl;
std::cout << "Matrix order = " << order << std::endl;
if (tile_size < order) {
std::cout << "Tile size = " << tile_size << std::endl;
} else {
std::cout << "Untiled (IKJ loop order)" << std::endl;
}
//////////////////////////////////////////////////////////////////////
/// Allocate space for matrices
//////////////////////////////////////////////////////////////////////
double dgemm_time(0);
prk::vector<double> A(order*order);
prk::vector<double> B(order*order);
prk::vector<double> C(order*order,0.0);
for (auto i=0; i<order; ++i) {
for (auto j=0; j<order; ++j) {
A[i*order+j] = i;
B[i*order+j] = i;
}
}
{
for (auto iter = 0; iter<=iterations; iter++) {
if (iter==1) dgemm_time = prk::wtime();
if (tile_size < order) {
prk_dgemm(order, tile_size, A, B, C);
} else {
prk_dgemm(order, A, B, C);
}
}
dgemm_time = prk::wtime() - dgemm_time;
}
//////////////////////////////////////////////////////////////////////
/// Analyze and output results
//////////////////////////////////////////////////////////////////////
const auto forder = static_cast<double>(order);
const auto reference = 0.25 * std::pow(forder,3) * std::pow(forder-1.0,2) * (iterations+1);
const auto checksum = prk::reduce(C.begin(), C.end(), 0.0);
const auto epsilon = 1.0e-8;
const auto residuum = std::abs(checksum-reference)/reference;
if (residuum < epsilon) {
#if VERBOSE
std::cout << "Reference checksum = " << reference << "\n"
<< "Actual checksum = " << checksum << std::endl;
#endif
std::cout << "Solution validates" << std::endl;
auto avgtime = dgemm_time/iterations;
auto nflops = 2.0 * std::pow(forder,3);
std::cout << "Rate (MF/s): " << 1.0e-6 * nflops/avgtime
<< " Avg time (s): " << avgtime << std::endl;
} else {
std::cout << "Reference checksum = " << reference << "\n"
<< "Actual checksum = " << checksum << std::endl;
#if VERBOSE
for (auto i=0; i<order; ++i)
for (auto j=0; j<order; ++j)
std::cout << "A(" << i << "," << j << ") = " << A[i*order+j] << "\n";
for (auto i=0; i<order; ++i)
for (auto j=0; j<order; ++j)
std::cout << "B(" << i << "," << j << ") = " << B[i*order+j] << "\n";
for (auto i=0; i<order; ++i)
for (auto j=0; j<order; ++j)
std::cout << "C(" << i << "," << j << ") = " << C[i*order+j] << "\n";
std::cout << std::endl;
#endif
return 1;
}
return 0;
}
| [
"jeff.science@gmail.com"
] | jeff.science@gmail.com |
293386200c57224e3fe509e512ade06341648653 | 5c0f282a4e3e8fec68b20317c9a07247bd8b4616 | /src/core/hw/gfxip/gfx9/gfx9MetaEq.cpp | 2a652c6b96afa1ab411cc9beb704842bac0815ae | [
"MIT"
] | permissive | PetarKirov/pal | b3baabdccb5df38e711fa3641d450e9c34f877ea | d535f5dc4179fc14249a5eb41e59aa96a5cd318f | refs/heads/master | 2021-08-31T19:50:18.201096 | 2017-12-21T13:40:00 | 2017-12-22T08:06:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 38,596 | cpp | /*
*******************************************************************************
*
* Copyright (c) 2015-2017 Advanced Micro Devices, Inc. All rights reserved.
*
* 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 "pal.h"
#include "palInlineFuncs.h"
#include "core/hw/gfxip/gfx9/gfx9CmdStream.h"
#include "core/hw/gfxip/gfx9/gfx9Device.h"
#include "core/hw/gfxip/gfx9/gfx9Image.h"
#include "core/hw/gfxip/gfx9/gfx9MetaEq.h"
#include "core/hw/gfxip/gfx9/g_gfx9PalSettings.h"
using namespace Util;
namespace Pal
{
namespace Gfx9
{
//=============== Implementation for MetaDataAddrEquation: =============================================================
// =====================================================================================================================
MetaDataAddrEquation::MetaDataAddrEquation(
uint32 maxEquationBits, // maximum number of bits this equation could possibly have
const char* pName) // a identifier for this equation, only used for debug prints. Can be NULL
:
m_maxBits(maxEquationBits)
{
PAL_ASSERT (maxEquationBits < MaxNumMetaDataAddrBits);
#if PAL_ENABLE_PRINTS_ASSERTS
Strncpy(m_equationName, ((pName != nullptr) ? pName : ""), MaxEquationNameLength);
#endif
Reset();
}
// =====================================================================================================================
void MetaDataAddrEquation::ClearBits(
uint32 bitPos, // the bit position of the equation to look at
uint32 compType, // one of MetaDataAddrCompType enumerations
uint32 keepMask) // set bits in the mask are *kept*
{
ValidateInput(bitPos, compType);
m_equation[bitPos][compType] &= keepMask;
}
// =====================================================================================================================
// Returns the result of "pair0 compareType pair1"
bool MetaDataAddrEquation::CompareCompPair(
const CompPair& pair0,
const CompPair& pair1,
MetaDataAddrCompareTypes compareType)
{
const int8 s0CompPos = static_cast<int8>(pair0.compPos);
const int8 s1CompPos = static_cast<int8>(pair1.compPos);
bool bRetVal = false;
switch (compareType)
{
case MetaDataAddrCompareLt:
// SEE: COORD::operator<
if (pair0.compType == pair1.compType)
{
bRetVal = (s0CompPos < s1CompPos);
}
else if ((pair0.compType == MetaDataAddrCompS) || (pair1.compType == MetaDataAddrCompM))
{
bRetVal = true;
}
else if ((pair1.compType == MetaDataAddrCompS) || (pair0.compType == MetaDataAddrCompM))
{
bRetVal = false;
}
else if (pair0.compPos == pair1.compPos)
{
bRetVal = (pair0.compType < pair1.compType);
}
else
{
bRetVal = (s0CompPos < s1CompPos);
}
break;
case MetaDataAddrCompareEq:
// SEE: COORD::operator==
bRetVal = ((pair0.compType == pair1.compType) && (pair0.compPos == pair1.compPos));
break;
case MetaDataAddrCompareGt:
// SEE: COORD::operator>
bRetVal = ((CompareCompPair(pair0, pair1, MetaDataAddrCompareLt) == false) &&
(CompareCompPair(pair0, pair1, MetaDataAddrCompareEq) == false));
break;
default:
PAL_NOT_IMPLEMENTED();
break;
}
return bRetVal;
}
// =====================================================================================================================
void MetaDataAddrEquation::Copy(
MetaDataAddrEquation* pDst,
uint32 startBitPos,
int32 copySize
) const
{
const uint32 numBitsToCopy = (copySize == -1) ? m_maxBits : copySize;
pDst->SetEquationSize(numBitsToCopy);
for(uint32 bitPosIndex = 0; bitPosIndex < numBitsToCopy; bitPosIndex++)
{
for (uint32 compType = 0; compType < MetaDataAddrCompNumTypes; compType++)
{
pDst->ClearBits(bitPosIndex, compType, 0);
pDst->SetMask(bitPosIndex, compType, Get(startBitPos + bitPosIndex, compType));
}
}
}
// =====================================================================================================================
// Uses the CPU to solve the meta-equation given the specified inputs. The return value is always in terms of nibbles
uint32 MetaDataAddrEquation::CpuSolve(
uint32 x, // cartesian coordinates
uint32 y,
uint32 z, // which slice of either a 2d array or 3d volume
uint32 sample, // which msaa sample
uint32 metaBlock // which metablock
) const
{
uint32 metaOffset = 0;
for (uint32 bitPos = 0; bitPos < GetNumValidBits(); bitPos++)
{
uint32 b =
(CountSetBits(Get(bitPos, MetaDataAddrCompX) & x) & 0x1);
b ^= (CountSetBits(Get(bitPos, MetaDataAddrCompY) & y) & 0x1);
b ^= (CountSetBits(Get(bitPos, MetaDataAddrCompZ) & z) & 0x1);
b ^= (CountSetBits(Get(bitPos, MetaDataAddrCompS) & sample) & 0x1);
b ^= (CountSetBits(Get(bitPos, MetaDataAddrCompM) & metaBlock) & 0x1);
metaOffset |= (b << bitPos);
} // end loop through all the bits in the equation
return metaOffset;
}
// =====================================================================================================================
// Returns true if the specified compType / data pair appears anywhere in this equation. Otherwise, this returns
// false
bool MetaDataAddrEquation::Exists(
uint32 compType,
uint32 inputMask
) const
{
bool allBitsFound = true;
uint32 lowPos = 0;
// "inputMask" might have multiple bits set in it (i.e., x3 ^ x5); we have to look for every one. Extract each
// set bit in "inputMask"
while ((allBitsFound == true) && (BitMaskScanForward(&lowPos, inputMask) == true))
{
const uint32 lowPosMask = 1 << lowPos;
bool localFound = false;
// Look through all the bits in this equation for the "lowPos" bit. Once (if...) it's found, just quit.
for (uint32 eqBitPos = 0; ((localFound == false) && (eqBitPos < m_maxBits)); eqBitPos++)
{
const uint32 eqData = Get(eqBitPos, compType);
localFound = TestAnyFlagSet(eqData, lowPosMask);
}
// We need to find all the bits, so stop at the first non-found bit from "inputMask".
allBitsFound &= localFound;
// And remove the just searched-for bit from the inputMask so that we don't look for it again.
inputMask &= ~lowPosMask;
}
return allBitsFound;
}
// =====================================================================================================================
//
// Essentially, this function is comparing the data at the equations's "eqBitPos / compType" with "compPair", using
// "compareFunc" and eliminating any bits that fail the test.
void MetaDataAddrEquation::FilterOneCompType(
MetaDataAddrCompareTypes compareFunc,
const CompPair& compPair,
uint32 eqBitPos, // bit of the equation we're interested in
MetaDataAddrComponentType compType, // the component type we're interested in
MetaDataAddrComponentType axis)
{
if ((axis == MetaDataAddrCompNumTypes) || (axis == compType))
{
uint32 dataBitPos = 0;
uint32 eqData = Get(eqBitPos, compType);
while (BitMaskScanForward(&dataBitPos, eqData))
{
const CompPair eqCompPair = SetCompPair(compType, dataBitPos);
const uint32 dataBitMask = ~(1 << dataBitPos);
if (CompareCompPair(eqCompPair, compPair, compareFunc))
{
ClearBits(eqBitPos, compType, dataBitMask);
}
// Don't test against this bit again
eqData &= dataBitMask;
}
} // end check for anything to do
}
// =====================================================================================================================
// Filter looks at the equation and removes anything from the equation that passes the comparison test.
// i.e., if the equation was:
// eq[0] = x4 ^ y3
// eq[1] = x7 ^ y7 ^ z3
//
// and "compPair = x5" and "compareFunc" was "<"
//
// then we 'd be left with:
// eq[0] = y3
// eq[1] = x7 ^ y7 ^ z3
//
// Another pass with "compPair = y3" and "compareFunc" being "==" would produce:
// eq[0] = x7 ^ y7 ^ z3
//
void MetaDataAddrEquation::Filter(
const CompPair& compPair,
MetaDataAddrCompareTypes compareFunc,
uint32 startBit,
MetaDataAddrComponentType axis)
{
uint32 bitPos = startBit;
while (bitPos < GetNumValidBits())
{
// This loop is the equivalent of:
// m = eq[i].Filter( f, co, 0, axis );
//
// where:
// 'f' is compareFunc
// 'co' is compPair
// 'axis' is axis
// 'eq[i]' is a single bit of the equation. i.e., x5 ^ x3 ^ y3 ^ z4. We have to filter the components
// one at a time.
//
// 'm' is the number of components left in eq[i] after the filtering. All that matters though is if
// eq[i] is now empty though.
for (uint32 compType = 0; compType < MetaDataAddrCompNumTypes; compType++)
{
FilterOneCompType(compareFunc,
compPair,
bitPos,
static_cast<MetaDataAddrComponentType>(compType),
axis);
}
if (IsEmpty(bitPos))
{
// This bit in the equation is now empty. If there are still more significant valid bits to go,
// then go ahead and shift everything down.
const uint32 numBitsToGo = GetNumValidBits() - (bitPos + 1);
if (numBitsToGo != 0)
{
// Shift everything above this position down
memmove(&m_equation[bitPos][0],
&m_equation[bitPos + 1][0],
sizeof(uint32) * numBitsToGo * MetaDataAddrCompNumTypes);
}
// don't increment "bitPos" here since we just re-used that slot!
// but do decrement the number of valid bits associated with this equation since there is
// now one less
m_maxBits--;
}
else
{
bitPos++;
}
} // end loop through all the bits in this equation
}
// =====================================================================================================================
// pEq is one bit of the meta-data equations; it will be indexed by this routine via the MetaDataAddrType enumerations.
// i.e., pEq[] = x5 ^ y4
//
// This function will find and return the lowest coordinate that contributes to the supplied equation. In this
// example:
// pCompPair->type = MetaDataAddrCompY
// pCompPair->pos = 4;
//
// If pCompPair is valid, then this function will return true, otherwise, it will return false.
bool MetaDataAddrEquation::FindSmallComponent(
uint32 bitPos, // the bit position of the equation to look at
CompPair* pCompPair // [out] the found small component
) const
{
const uint32* pEq = m_equation[bitPos];
pCompPair->compType = MetaDataAddrCompNumTypes;
pCompPair->compPos = 0xFF;
for (uint32 compType = 0; compType < MetaDataAddrCompNumTypes; compType++)
{
// Iterate through each pipe bits from lsb to msb, and remove the smallest coordinate contributing
// to that bit's equation
uint32 lowCompPos = 0;
if (BitMaskScanForward(&lowCompPos, pEq[compType]))
{
if (lowCompPos < pCompPair->compPos)
{
*pCompPair = SetCompPair(compType, lowCompPos);
}
}
}
return (pCompPair->compType != MetaDataAddrCompNumTypes);
}
// =====================================================================================================================
// This function returns the component associated with the specified bit. i.e., if you have:
// eq[0] = y3
// eq[1] = x2
//
// it would return "y3" for bitPos==0.
//
// This assumes that there is only one component per bit. i.e., these situations will assert:
// eq[0] = y3 ^ y2
// eq[0] = y3 ^ x2
CompPair MetaDataAddrEquation::Get(
uint32 bitPos
) const
{
bool foundValidComp = false;
CompPair retPair = {};
for (uint32 compType = 0; compType < MetaDataAddrCompNumTypes; compType++)
{
const uint32 data = Get(bitPos, compType);
// Data of zero means that no components exist
if (data != 0)
{
PAL_ASSERT (IsPowerOfTwo(data));
PAL_ASSERT (foundValidComp == false);
retPair = SetCompPair(compType, Log2(data));
foundValidComp = true;
}
}
// The requested bitPosition is empty?
PAL_ASSERT (foundValidComp);
return retPair;
}
// =====================================================================================================================
// This function returns the data associated with the specified equation bit and component
uint32 MetaDataAddrEquation::Get(
uint32 bitPos, // the bit position of the equation to look at
uint32 compType // one of MetaDataAddrCompType enumerations
) const
{
ValidateInput(bitPos, compType);
return m_equation[bitPos][compType];
}
// =====================================================================================================================
// Returns the number of bytes required to store this equation in GPU memory.
gpusize MetaDataAddrEquation::GetGpuSize() const
{
return m_maxBits * MetaDataAddrCompNumTypes * sizeof (uint32);
}
// =====================================================================================================================
// Returns the number of samples that actually affect the final value of this equation. Returns one if samples
// don't affect this equation's formula.
uint32 MetaDataAddrEquation::GetNumSamples() const
{
uint32 highSampleBit = 0;
for (uint32 bitPos = 0; bitPos < GetNumValidBits(); bitPos++)
{
const uint32 eqData = Get(bitPos, MetaDataAddrCompS);
uint32 index = 0;
if (BitMaskScanForward(&index, eqData))
{
// If this ever trips (which I would find to be very unlikely... that would mean that two sample bits are
// used in the same equation bit). we would need to do a "BitMaskScanBackwards" to make sure we got the
// highest sample position affecting this equation bit. But that function doesn't exist.
//
// Note that "IsPowerOfTwo" will cause an assert if eqData==0 (which is the normal case), which is why
// this assert is inside the "if" statement, not outside.
PAL_ASSERT (IsPowerOfTwo(eqData));
// Say the high reference in this equation is "s2". This would be returned by this function as "1 << 2"
// (which equals 4), but we really need to loop through the first seven samples in this case (i.e., up to
// (1 << (2 + 1)) == 8 to ensure we catch all possibilities where s2 would be set. i.e.,:
// 0100
// 0101
// 0110
// 0111
//
// Thus, we add "+ 1" here to the discovered index.
highSampleBit = Max(highSampleBit, index + 1);
}
}
return 1 << highSampleBit;
}
// =====================================================================================================================
// Returns true if the specified bit of this equation is empty.
bool MetaDataAddrEquation::IsEmpty(
uint32 bitPos
) const
{
return (GetNumComponents(bitPos) == 0);
}
// =====================================================================================================================
bool MetaDataAddrEquation::IsSet(
uint32 bitPos, // the bit position of the equation to look at
uint32 compType, // one of MetaDataAddrCompType enumerations
uint32 mask // the bit pattern to test for
) const
{
return TestAnyFlagSet(Get(bitPos, compType), mask);
}
// =====================================================================================================================
void MetaDataAddrEquation::Mort2d(
CompPair* pPair0,
CompPair* pPair1,
uint32 start,
uint32 end)
{
if (end == 0)
{
end = m_maxBits - 1;
}
for (uint32 i = start; i <= end; i++)
{
CompPair* pChosen = pPair0;
if (((i - start) % 2) != 0)
{
pChosen = pPair1;
}
SetBit(i, pChosen->compType, pChosen->compPos);
pChosen->compPos++;
}
}
// =====================================================================================================================
void MetaDataAddrEquation::Mort3d(
CompPair* pC0,
CompPair* pC1,
CompPair* pC2,
uint32 start,
uint32 end)
{
if (end == 0)
{
end = GetNumValidBits() - 1;
}
for(uint32 i = start; i <= end; i++)
{
const uint32 select = (i - start) % 3;
auto*const pC = ((select == 0) ? pC0 : ((select==1) ? pC1 : pC2));
SetBit(i, pC->compType, pC->compPos);
pC->compPos++;
}
}
// =====================================================================================================================
void MetaDataAddrEquation::PrintEquation(
const Pal::Device* pDevice
) const
{
#if PAL_ENABLE_PRINTS_ASSERTS
const Gfx9PalSettings& settings = GetGfx9Settings(*pDevice);
if (TestAnyFlagSet(settings.printMetaEquationInfo, Gfx9PrintMetaEquationInfoEquations))
{
PAL_DPINFO("%s equation\n", m_equationName);
for (uint32 bit = 0; bit < GetNumValidBits(); bit++)
{
static const char CompNames[MetaDataAddrCompNumTypes] = { 'x', 'y', 'z', 's', 'm' };
// Guessing? I hope 256 is long enough. :-)
char printMe[256] = {};
for (uint32 compType = 0; compType < MetaDataAddrCompNumTypes; compType++)
{
uint32 data = m_equation[bit][compType];
uint32 lowSetBit = 0;
while (BitMaskScanForward(&lowSetBit, data))
{
static const uint32 CompNameSize = 16;
char compName[CompNameSize] = {};
Snprintf(compName, CompNameSize, "%c%u ^ ", CompNames[compType], lowSetBit);
strcat (printMe, compName);
// Don't find this bit again
data &= ~(1 << lowSetBit);
}
}
// We wind up with one extra '^' character, so find it and remove it so the printout looks nicer
char* pChar = strrchr(printMe, '^');
if (pChar)
{
*pChar = ' ';
}
PAL_DPINFO("\teq[%2d] = %s\n", bit, printMe);
}
}
#endif // PAL_ENABLE_PRINTS_ASSERTS
}
// =====================================================================================================================
bool MetaDataAddrEquation::Remove(
const CompPair& compPair)
{
const uint32 mask = 1 << compPair.compPos;
bool dataRemoved = false;
for (uint32 bitPos = 0; bitPos < GetNumValidBits(); bitPos++)
{
if (TestAnyFlagSet(Get(bitPos, compPair.compType), mask))
{
ClearBits(bitPos, compPair.compType, ~mask);
dataRemoved = true;
}
}
return dataRemoved;
}
// =====================================================================================================================
void MetaDataAddrEquation::Reset()
{
memset(m_equation, 0, sizeof(m_equation));
}
// =====================================================================================================================
void MetaDataAddrEquation::Reverse(
uint32 start,
int32 num)
{
const uint32 n = (num == -1) ? GetNumValidBits() : num;
for(uint32 bitPos = 0; bitPos < n/2; bitPos++)
{
for (uint32 compType = 0; compType < MetaDataAddrCompNumTypes; compType++)
{
const uint32 temp = Get(start + bitPos, compType);
const uint32 otherBitPos = start + n - 1 - bitPos;
ClearBits(start + bitPos, compType, 0);
SetMask(start + bitPos, compType, Get(otherBitPos, compType));
ClearBits(otherBitPos, compType, 0);
SetMask(otherBitPos, compType, temp);
}
}
}
// =====================================================================================================================
void MetaDataAddrEquation::SetBit(
uint32 bitPos,
MetaDataAddrComponentType compType,
uint32 compPos)
{
SetMask(bitPos, compType, 1 << compPos);
}
// =====================================================================================================================
void MetaDataAddrEquation::SetEquationSize(
uint32 numBits,
bool clearBits)
{
// This could conceivably trip for PRT images which can be ridiculously ginormous. If so, we need to bump up
// the MaxNumMetaDataAddrBits value. Theoretically everything would simply "go along for the ride" with the
// increased size.
PAL_ASSERT(numBits <= MaxNumMetaDataAddrBits);
// Only clear if caller requests it.
if (clearBits)
{
// If there is anything leftover after the current equation finishes, then remove it
for (uint32 bitPos = m_maxBits; bitPos < numBits; bitPos++)
{
for (uint32 compType = 0; compType < MetaDataAddrCompNumTypes; compType++)
{
ClearBits(bitPos, compType, 0);
}
}
}
m_maxBits = numBits;
}
// =====================================================================================================================
void MetaDataAddrEquation::GenerateMetaEqParamConst(
const Image& image,
uint32 maxCompFrag,
uint32 firstUploadBit,
MetaEquationParam* pMetaEqParam)
{
const Pal::Image* pParent = image.Parent();
const Pal::Device* pDevice = pParent->GetDevice();
const auto* pCreateInfo = &pParent->GetImageCreateInfo();
const Gfx9PalSettings& settings = GetGfx9Settings(*pDevice);
const bool optimizedFastClearDepth = ((pParent->IsDepthStencil()) &&
TestAnyFlagSet(settings.optimizedFastClear,
Gfx9OptimizedFastClearDepth));
const bool optimizedFastClearDcc = ((pParent->IsRenderTarget()) &&
TestAnyFlagSet(settings.optimizedFastClear,
Gfx9OptimizedFastClearColorDcc));
const bool optimizedFastClearCmask = ((pParent->IsRenderTarget()) &&
TestAnyFlagSet(settings.optimizedFastClear,
Gfx9OptimizedFastClearColorCmask));
// check if optimized fast clear is on.
if (optimizedFastClearDepth || optimizedFastClearDcc || optimizedFastClearCmask)
{
// Meta Equation must have non zero bits
PAL_ASSERT(m_maxBits);
uint32 sampleHi = 0;
uint32 sampleHiBitsLength = 0;
uint32 metablkIdxLoBitsOffset = 0;
uint32 metablkIdxLoBitsLength = 0;
uint32 metablkIdxHiBitsOffset = 0;
// Loop Over entire meta equation and find out SampleHi and MetaBlockHi and Lo bits
for (uint32 bitPos = firstUploadBit; ((bitPos < MaxNumMetaDataAddrBits) && (bitPos < m_maxBits)); bitPos++)
{
// First check if any of bitPos has any sample bits.
const uint32 sampleData = m_equation[bitPos][MetaDataAddrCompS];
uint32 lowSetSampleBit = 0;
// if sampleHi Bits haven't been found and a nonzero data has been found then
// it must be lower bits of high sample bits. But its lsb must have a 1 which is
// not at position 0 since s0 will come under compressed fragments
if (sampleHi == 0)
{
if (BitMaskScanForward(&lowSetSampleBit, sampleData) && (lowSetSampleBit >= maxCompFrag))
{
sampleHi = bitPos;
// If this is bitPos = m_maxBits - 1, meaning last valid bit in the equation
// then our below logic to find sampleHiBitsLength won't work so just update
// it here.
if (bitPos == (m_maxBits - 1))
{
sampleHiBitsLength = 1;
}
}
}
else if ((sampleHi != 0) && (sampleData == 0) && (sampleHiBitsLength == 0))
{
sampleHiBitsLength = bitPos - sampleHi;
}
else if ((sampleHi != 0) && (sampleHiBitsLength == 0) && (bitPos == (m_maxBits - 1)))
{
sampleHiBitsLength = (bitPos - sampleHi) + 1;
}
// Now Find Metablock Lo and Hi bits
const uint32 metaBlockData = m_equation[bitPos][MetaDataAddrCompM];
uint32 lowSetMetaBlockBit = 0;
if (metablkIdxLoBitsOffset == 0)
{
// The first occurance of any metablock bits in equation is what we want.
if (BitMaskScanForward(&lowSetMetaBlockBit, metaBlockData) && (lowSetMetaBlockBit == 0))
{
metablkIdxLoBitsOffset = bitPos;
}
}
else if ((metaBlockData == 0) && (metablkIdxLoBitsLength == 0))
{
// After metablock low bits has been found first non-occurance of any meta block bits
// tell us about how many Low bits are present in the equation.
metablkIdxLoBitsLength = bitPos - metablkIdxLoBitsOffset;
}
if ((metaBlockData != 0) && (metablkIdxLoBitsLength > 0) && (metablkIdxHiBitsOffset == 0))
{
// Find metablock hi bits offset
metablkIdxHiBitsOffset = bitPos;
}
}
if (sampleHiBitsLength == 0)
{
sampleHi = 0;
}
else
{
sampleHi--;
}
// if equation doesn't contain any metablock hi bits for example:-
// x5 ^ y6,x6 ^ y5,x4 ^ y7, x7 ^ y4,x4 ^ y4 ^ z0,x5 ^ y3 ^ z1,x3 ^ y5 ^ z2, x6 ^ y2 ^ z3,m1,m0,y9,x8,y8,y7,x6,y6
// then just assume that metablkIdxHiBitsOffset is at m_maxBits
if (metablkIdxHiBitsOffset == 0)
{
metablkIdxHiBitsOffset = m_maxBits;
}
if (metablkIdxLoBitsLength == 0)
{
if (metablkIdxLoBitsOffset != 0)
{
metablkIdxHiBitsOffset = metablkIdxLoBitsOffset;
metablkIdxLoBitsOffset = 0;
}
else
{
// Our trimming logic of meta equation see calcMetaEquation() may also sometime trim all metablock
// bits even though actual meta equation will always contain atleast one bit of metablock. In this
// case metablkIdxLoBitsOffset will come as 0, so handle it here. Assume it will sit just above the
// last valid bit in the equation. If that is not the case something bad may happen.
PAL_ASSERT(IsSet(m_maxBits, MetaDataAddrCompM, 1));
metablkIdxHiBitsOffset = m_maxBits;
metablkIdxLoBitsOffset = 0;
}
}
else
{
metablkIdxLoBitsOffset--;
}
if (metablkIdxHiBitsOffset != 0)
{
metablkIdxHiBitsOffset--;
}
uint32 metaBlockFastClearSize = metablkIdxHiBitsOffset - metablkIdxLoBitsLength - sampleHiBitsLength;
// Some sanity checks since we Convert uint from bytes to 16 bytes.
PAL_ASSERT(metaBlockFastClearSize > 4);
PAL_ASSERT(metablkIdxHiBitsOffset > 4);
if ((sampleHiBitsLength > 0) && (sampleHi <= 4))
{
PAL_ASSERT_ALWAYS();
}
if ((metablkIdxLoBitsLength > 0) && (metablkIdxLoBitsOffset <= 4))
{
PAL_ASSERT_ALWAYS();
}
// Convert uint from bytes to 16 bytes
pMetaEqParam->metaBlkSizeLog2 = metaBlockFastClearSize - 4;
if (sampleHiBitsLength > 0)
{
pMetaEqParam->sampleHiBitsOffset = sampleHi - 4;
}
else
{
pMetaEqParam->sampleHiBitsOffset = 0;
}
pMetaEqParam->sampleHiBitsLength = sampleHiBitsLength;
if (metablkIdxLoBitsLength > 0)
{
pMetaEqParam->metablkIdxLoBitsOffset = metablkIdxLoBitsOffset - 4;
}
else
{
pMetaEqParam->metablkIdxLoBitsOffset = 0;
}
pMetaEqParam->metablkIdxLoBitsLength = metablkIdxLoBitsLength;
pMetaEqParam->metablkIdxHiBitsOffset = metablkIdxHiBitsOffset - 4;
if ((pMetaEqParam->metaBlkSizeLog2 + pMetaEqParam->sampleHiBitsLength + pMetaEqParam->metablkIdxLoBitsLength) !=
pMetaEqParam->metablkIdxHiBitsOffset)
{
PAL_ASSERT_ALWAYS();
}
}
}
// =====================================================================================================================
CompPair MetaDataAddrEquation::SetCompPair(
MetaDataAddrComponentType compType,
uint32 compPos)
{
// Make sure our "compPos" is not out of range. We use uint32's to store the equation, so any component
// (i.e., x7) of the equation shouldn't reference more than the 32nd bit.
if (compType == MetaDataAddrCompZ)
{
// Note that for Z, the compPos can be negative as part of the equation involves "metaBlkDepth - 1", and
// the metablkDepth will be zero for 2D images.
PAL_ASSERT ((static_cast<int32>(compPos) == -1) || (compPos < 32));
}
else
{
PAL_ASSERT (compPos < 32);
}
CompPair compPair =
{
compType,
static_cast<uint8>(compPos)
};
return compPair;
}
// =====================================================================================================================
CompPair MetaDataAddrEquation::SetCompPair(
uint32 compType,
uint32 compPos)
{
return SetCompPair(static_cast<MetaDataAddrComponentType>(compType), compPos);
}
// =====================================================================================================================
void MetaDataAddrEquation::SetMask(
uint32 bitPos,
uint32 compType,
uint32 mask)
{
ValidateInput(bitPos, compType);
// Set the requested bit(s) in the equation
m_equation[bitPos][compType] |= mask;
}
// =====================================================================================================================
void MetaDataAddrEquation::Shift(
int32 amount, // the number of equation bits to shift, negative values are a left shift
int32 start) // right-shifts only, the first bit to move
{
if (amount != 0)
{
amount = -amount;
const int32 inc = (amount < 0) ? -1 : 1;
const int32 end = (amount < 0) ? start - 1 : GetNumValidBits();
for (int32 bitPos = (amount < 0) ? GetNumValidBits() - 1 : start;
(inc > 0) ? bitPos < end : bitPos > end;
bitPos += inc)
{
if ((bitPos + amount < start) || (bitPos + amount >= static_cast<int32>(GetNumValidBits())))
{
memset (m_equation[bitPos], 0, sizeof(uint32) * MetaDataAddrCompNumTypes);
}
else
{
memcpy (m_equation[bitPos], m_equation[bitPos + amount], sizeof(uint32) * MetaDataAddrCompNumTypes);
}
}
}
}
// =====================================================================================================================
// Uploads this objects equation to GPU-accessible memory
void MetaDataAddrEquation::Upload(
const Pal::Device* pDevice,
CmdBuffer* pCmdBuffer,
const GpuMemory& dstMem, // Mem object that the equation is written into
gpusize offset, // Offset from dstMem to which the equation gets written
uint32 firstbit // [in] the LSB of the equation that we actually care about
) const
{
// Make sure all the bits that we're NOT uploading will always be zero.
for (uint32 bitPos = 0; bitPos < firstbit; bitPos++)
{
PAL_ASSERT(IsEmpty(bitPos));
}
// Always write all possible components for each bit of the equation (even if they're empty)
pCmdBuffer->CmdUpdateMemory(dstMem,
offset,
MetaDataAddrCompNumTypes * (GetNumValidBits() - firstbit) * sizeof(uint32),
&m_equation[firstbit][0]);
if (pCmdBuffer->GetEngineType() != EngineTypeDma)
{
const auto* pGfxDevice = static_cast<const Device*>(pDevice->GetGfxDevice());
auto* pGfxCmdBuffer = static_cast<GfxCmdBuffer*>(pCmdBuffer);
auto* pCmdStream = pGfxCmdBuffer->GetCmdStreamByEngine(CmdBufferEngineSupport::CpDma);
auto* pGfxCmdStream = static_cast<CmdStream*>(pCmdStream);
PAL_ASSERT(pCmdStream != nullptr);
// The following code assumes that the above CmdUpdateMemory() call utilized the CPDMA engine.
//
// We have to guarantee that the CPDMA operation has completed as the texture pipe will (conceivably) be
// using this equation "real soon now". See the RPM "InitMaskRam" implementation for details.
SyncReqs syncReqs = {};
syncReqs.syncCpDma = 1;
// Dummy BarrierOperations used in Device::IssueSyncs()
Developer::BarrierOperations barrierOps = {};
pGfxDevice->IssueSyncs(pGfxCmdBuffer,
pGfxCmdStream,
syncReqs,
HwPipePoint::HwPipePreCs,
FullSyncBaseAddr,
FullSyncSize,
&barrierOps);
}
else
{
// For SDMA-based uploads, the PAL client is responsible for issuing barrier calls that ensure the completion
// of the SDMA engine prior to the texture pipe getting involved so there's nothing we need to do.
}
}
// =====================================================================================================================
void MetaDataAddrEquation::ValidateInput(
uint32 bitPos,
uint32 compType
) const
{
PAL_ASSERT (bitPos < MaxNumMetaDataAddrBits);
PAL_ASSERT (compType < MetaDataAddrCompNumTypes);
}
// =====================================================================================================================
// Adds everything from pEq into "this"
void MetaDataAddrEquation::XorIn(
const MetaDataAddrEquation* pEq,
uint32 start)
{
const uint32 numBits = (GetNumValidBits() - start < pEq->GetNumValidBits())
? GetNumValidBits() - start
: pEq->GetNumValidBits();
for (uint32 bitPos = 0; bitPos < numBits; bitPos++)
{
for (uint32 compType = 0; compType < MetaDataAddrCompNumTypes; compType++)
{
this->SetMask(bitPos, compType, pEq->Get(bitPos, compType));
}
}
}
// =====================================================================================================================
// Returns true if the meta equation bit specified by the "this" object's "thisBit" is equivalent to the
// metaEq's "metaBit"
bool MetaDataAddrEquation::IsEqual(
const MetaDataAddrEquation& metaEq,
uint32 thisBit,
uint32 metaBit
) const
{
bool isEqual = true;
for (uint32 compType = 0; isEqual && (compType < MetaDataAddrCompNumTypes); compType++)
{
isEqual = (metaEq.Get(metaBit, compType) == Get(thisBit, compType));
}
return isEqual;
}
// =====================================================================================================================
// Returns the number of components referenced by the specified bit.
uint32 MetaDataAddrEquation::GetNumComponents(
uint32 bitPos
) const
{
uint32 numComponents = 0;
for (uint32 compType = 0; compType < MetaDataAddrCompNumTypes; compType++)
{
const uint32 data = Get(bitPos, compType);
if (data != 0)
{
numComponents++;
}
}
return numComponents;
}
} // Gfx9
} // Pal
| [
"jacob.he@amd.com"
] | jacob.he@amd.com |
46f6390a8ced54d4a641a51f774992d60db71a62 | 103ce1aef509e106396687667c855f6c17d671ef | /src/noncopyable.h | ae49c3e73cc66d05aff69b849ede6c546f490eef | [] | no_license | lxlyh/gude | 3f5fc11790f3b8189357cbaa0d556d83587e0c43 | 9dfa8755d1d24c563576dce53c088447cbeedb89 | refs/heads/main | 2023-05-01T17:53:59.823982 | 2021-05-05T02:05:57 | 2021-05-05T02:05:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 303 | h | #ifndef __GUDE_NONCOPYABLE_H
#define __GUDE_NONCOPYABLE_H
namespace gude
{
struct Noncopyable
{
Noncopyable() = default;
~Noncopyable() = default;
Noncopyable(const Noncopyable&) = delete;
Noncopyable& operator=(const Noncopyable&) = delete;
};
}
#endif /*__GUDE_NONCOPYABLE_H*/
| [
"1125498083@qq.com"
] | 1125498083@qq.com |
b6d8d8368dbae389ec8526af3400e87cfd6871b7 | d1ece2ce8414c1d60501d7cf63b9624a6a305234 | /PC/Project-FW/TextureManager.h | dfab52aca6a6762de9e893c568d3478ae1311699 | [] | no_license | Nickchooshin/HUGP2_1week | 82ba96690896f8eee689acd6f945d374a983b1b9 | 4cf4129e17eeb21df1adcd8abe890dc19aebaa28 | refs/heads/master | 2021-01-22T01:06:07.556131 | 2015-04-14T20:26:41 | 2015-04-14T20:27:05 | 32,618,675 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 523 | h | #pragma once
#include "Singleton.h"
#include <d3dx9.h>
#include <string>
#include <map>
using namespace std ;
class TextureManager : public Singleton<TextureManager>
{
private :
map<string, LPDIRECT3DTEXTURE9> m_Texture ;
map<string, D3DXIMAGE_INFO> m_TexInfo ;
public :
TextureManager() ;
~TextureManager() ;
LPDIRECT3DTEXTURE9 GetTexture(string texfile, D3DXIMAGE_INFO **pTexInfo) ;
D3DXIMAGE_INFO GetTexInfo(string texfile) ;
void ClearTexture() ;
} ;
#define g_TextureManager TextureManager::GetInstance() | [
"gustncjswp95@gmail.com"
] | gustncjswp95@gmail.com |
6392cd01f970f234682c4d62a7b2a2701a9d594e | e7f74d5683701e9552f3d476dc8f57775128f90f | /hackerrank.com/find-median.cpp | 43d818400b7512c33944999f3d9b7976d21cb12b | [
"MIT"
] | permissive | bolatov/contests | 89463675ea3114115bd921973b54eb64620c19a2 | 39654ec36e1b7ff62052e324428141a9564fd576 | refs/heads/master | 2021-01-24T11:19:53.864281 | 2018-07-12T05:37:09 | 2018-07-12T05:37:09 | 21,923,806 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,965 | cpp | #include <iostream>
#include <vector>
#include <cstdio>
#include <algorithm>
using namespace std;
int partition(std::vector<int> &v, int l, int r) {
// printf("partition: lo=%d, hi=%d\n", l, r);
int p = r - 1;
int index = l;
for (int i = l; i < r; ++i) {
if (v[i] < v[p]) {
int t = v[i];
v[i] = v[index];
v[index] = t;
index++;
}
}
int t = v[index];
v[index] = v[p];
v[p] = t;
p = index;
return p;
}
void printArray(std::vector<int> &v) {
for (int i : v) {
printf("%d ", i);
}
printf("\n");
}
void printArrayPivot(std::vector<int> &v, int k) {
for (int i = 0; i < v.size(); i++) {
if (i == k)
printf("[%d] ", i);
else
printf("%d ", i);
}
printf("\n");
}
int bruteForce(std::vector<int> v, int k) {
sort(v.begin(), v.end());
return v[k];
}
int main(int argc, char const *argv[]) {
freopen("input.txt", "r", stdin);
int t;
cin >> t;
for (int itest = 1; itest <= t; itest++) {
int n;
cin >> n;
std::vector<int> v(n);
for (int i = 0; i < n; ++i) {
cin >> v[i];
}
int mid = (n % 2 == 0) ? n / 2 - 1 : n / 2;
int lo = 0, hi = n;
int runs = 0;
while (hi - lo > 1) {
runs++;
int p = partition(v, lo, hi);
if (p == mid)
break;
// printArrayPivot(v, p);
if (mid < p)
hi = p;
else
lo = p + 1;
}
printf("%d\n", v[mid]);
int pb = bruteForce(v, mid);
if (v[mid] != pb) {
printf("FAILED, expected: %d\n", pb);
sort(v.begin(), v.end());
printArray(v);
} else {
printf("%d PASSED, runs=%d\n", itest, runs);
// printArrayPivot(v, mid);
}
}
return 0;
}
| [
"almer.bolatov@gmail.com"
] | almer.bolatov@gmail.com |
cabf4d246047e4fc190d4194307664c4a19bc6e1 | 7d968f35283cd64b80c3e18eae3f140040a0498e | /Sorting-Basic/insertionsort.h | 2bbe1b8ac656d2f9ce647983bbce82a8e9f620b6 | [] | no_license | Mhaoyuan/Algorithms- | 9e47d3236c74f4e0f1d76a1b85b6e2518cf5f77a | cffe5ae510d1eb233a63d0036a6b561b6c589ec4 | refs/heads/master | 2020-03-26T11:40:31.109393 | 2018-08-18T03:34:24 | 2018-08-18T03:34:24 | 144,854,062 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 938 | h | //
// Created by genius on 18-8-15.
//
#ifndef ALGORITHMS_INSERTIONSORT_H
#define ALGORITHMS_INSERTIONSORT_H
#include <vector>
using namespace std;
template <typename T>
void insertionsort(vector <T> &vec,int n){
for(int i =1;i < n;i++){
for(int j = i; j > 0 && vec[j] < vec[j-1]; j--){
swap(vec[j], vec[j-1]);
}
}
return;
}
template <typename T>
void insertionsort1(vector<T> &vec,int n){
for (int i =i; i< n; i++)
{
T e = vec[i];
int j;
for(j = i;j < n && vec[j-1] >e ;j--)
{
vec[j] = vec[j-1];
}
vec[j] = e;
}
return;
}
template <typename T>
void insertionsort1(vector<T> &vec, int l, int r){
for(int i = l+1;i <=r; i++){
T e = vec[i];
int j;
for (j = i;j > l&& vec[j-1]>e;j--)
vec[j] = vec[j-1];
vec[j] = e;
}
return;
}
#endif //ALGORITHMS_INSERTIONSORT_H
| [
"410463229@qq.com"
] | 410463229@qq.com |
48d83e53523473bfb4e50fd287e38ac13db196ac | 493ac26ce835200f4844e78d8319156eae5b21f4 | /flow_simulation/ideal_flow/processor2/0.4/k | cebc2ab6485d5595231a9c4f7d507a2092820ab5 | [] | no_license | mohan-padmanabha/worm_project | 46f65090b06a2659a49b77cbde3844410c978954 | 7a39f9384034e381d5f71191122457a740de3ff0 | refs/heads/master | 2022-12-14T14:41:21.237400 | 2020-08-21T13:33:10 | 2020-08-21T13:33:10 | 289,277,792 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,497 | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: v1912 |
| \\ / A nd | Website: www.openfoam.com |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class volScalarField;
location "0.4";
object k;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [0 2 -2 0 0 0 0];
internalField nonuniform List<scalar>
1466
(
0.107271
0.113343
0.0812091
0.132749
0.466172
0.22573
0.0831942
0.774325
0.30298
0.34398
0.021133
0.226096
0.021523
0.0740532
0.0884092
0.118197
0.048269
0.188794
0.285408
0.0649142
0.121952
0.201948
0.182525
0.105755
0.0778028
0.0730662
0.124125
0.304116
0.114829
0.462976
0.551005
0.394902
0.230527
0.595113
0.157876
0.0886091
0.0564684
0.0985394
0.423083
0.218341
0.271909
0.226965
0.278872
0.584091
0.308459
0.32241
0.0819682
0.156966
0.192265
0.119742
0.0553618
0.309563
0.376178
0.194054
0.147272
0.309803
0.0885262
0.0847366
0.0672785
0.332376
0.100722
0.415701
0.576231
0.303117
0.144943
0.0842602
0.2605
0.122293
0.115077
0.183832
0.0349888
0.125617
0.10117
0.106311
0.0285745
0.52968
0.111768
0.132998
0.136259
0.334314
0.0515522
0.0919756
0.0924229
0.162058
0.100173
0.104682
0.0922068
0.125008
0.0743722
0.151344
0.110611
0.0636719
0.335778
0.13241
0.0514578
0.115137
0.110966
0.151735
0.148096
0.107237
0.0805123
0.278611
0.0922466
0.0609047
0.0862726
0.302691
0.11883
0.0919899
0.145583
0.0881846
0.0250826
0.0600139
0.202621
0.0988386
0.0245654
0.314301
0.0552742
0.0633236
0.153205
0.0744827
0.103484
0.128131
0.0399126
0.100645
0.0715518
0.12611
0.0866134
0.064448
0.299888
0.243639
0.0811108
0.117645
0.0953456
0.220747
0.0527408
0.335991
0.257187
0.0780165
0.345645
0.10017
0.283823
0.0623623
0.229353
0.274768
0.332551
0.0631079
0.0443671
0.0740492
0.212375
0.102317
0.22881
0.122749
0.150513
0.114033
0.0985464
0.0374168
0.124251
0.329306
0.0543666
0.0778327
0.282663
0.0943558
0.145759
0.110429
0.289001
0.333466
0.281378
0.135029
0.0752111
0.159724
0.109267
0.095181
0.10048
0.214151
0.107327
0.116292
0.300084
0.327656
0.0878536
0.335989
0.130493
0.0926733
0.099715
0.0734154
0.113318
0.0660315
0.102905
0.432697
0.0960795
0.0590295
0.0678624
0.068345
0.0874567
0.145904
0.0854029
0.122088
0.344847
0.0983408
0.0803576
0.0752789
0.219522
0.0553725
0.0897076
0.0759837
0.130255
0.252064
0.0992771
0.38839
0.0821466
0.156326
0.134864
0.217057
0.069311
0.0866475
0.151919
0.101704
0.0423547
0.028536
0.0659338
0.114822
0.151421
0.147874
0.0779076
0.0831496
0.205032
0.082155
0.0703251
0.118651
0.0737005
0.326545
0.076809
0.116891
0.0783627
0.0297381
0.0907252
0.12763
0.0361272
0.642696
0.0477193
0.0921745
0.323242
0.0570586
0.0626567
0.280889
0.301007
0.0468523
0.0274528
0.0591773
0.0357141
0.0510933
0.0892264
0.168641
0.203559
0.0964942
0.0723577
0.18379
0.077407
0.252596
0.502509
0.467087
0.0829171
0.0922223
0.221658
0.0817297
0.205923
0.114843
0.295526
0.221573
0.0511188
0.118744
0.231596
0.125944
0.0654535
0.0773852
0.097917
0.0992903
0.0712359
0.0728578
0.0701609
0.285561
0.111458
0.0417545
0.0549276
0.0744036
0.0639042
0.0458312
0.0869883
0.0615485
0.130371
0.0945554
0.080907
0.26889
0.0950694
0.407007
0.173499
0.080733
0.367129
0.335267
0.0777629
0.0588797
0.0586801
0.245657
0.0880189
0.0995336
0.121399
0.0753232
0.0722186
0.0637507
0.0505035
0.670495
0.338903
0.0499247
0.0513302
0.204856
0.142473
0.0491081
0.210458
0.0573313
0.448377
0.108408
0.0842393
0.298108
0.0951215
0.0583697
0.0443378
0.0543285
0.0293685
0.061856
0.0186682
0.059839
0.0740062
0.0562964
0.0234872
0.0871275
0.0561171
0.0582454
0.0144624
0.0483371
0.120712
0.0400097
0.0846056
0.0558176
0.0415487
0.0337492
0.0588411
0.0161124
0.112197
0.0462496
0.0514875
0.237539
0.247189
0.0760348
0.296874
0.0605787
0.0536621
0.0489033
0.209359
0.0630644
0.63262
0.0947502
0.0966263
0.299489
0.29681
0.0944094
0.109008
0.0622646
0.0328783
0.0191669
0.0527475
0.103828
0.0204193
0.0353902
0.123064
0.0574305
0.0759645
0.0652509
0.0487049
0.482655
0.0970727
0.0415428
0.0615212
0.204794
0.126565
0.0546875
0.184249
0.09393
0.0872442
0.0494112
0.0436776
0.0431326
0.0626325
0.200185
0.209001
0.378282
0.0666112
0.0787995
0.247224
0.0313761
0.0841288
0.0112156
0.104257
0.0320435
0.221198
0.0676496
0.432578
0.064875
0.265576
0.526562
0.0759272
0.111363
0.060404
0.205587
0.052864
0.123877
0.445007
0.164571
0.224527
0.0850868
0.0585402
0.11048
0.0860223
0.0300002
0.202143
0.19113
0.189113
0.181771
0.202944
0.211509
0.154702
0.143957
0.222029
0.0629033
0.209723
0.489826
0.238103
0.551442
0.503629
0.589131
0.168886
0.263975
0.141969
0.0428773
0.332388
0.0647095
0.218222
0.47587
0.235666
0.252405
0.389856
0.0733091
0.370318
0.453812
0.058941
0.117035
0.507976
0.104875
0.280933
0.400742
0.0532694
0.0651529
0.459992
0.181463
0.134977
0.0740938
0.348295
0.0810793
0.54731
0.0652159
0.215995
0.0643618
0.497385
0.0963459
0.0668806
0.0719341
0.576197
0.537542
0.0349196
0.0391403
0.378109
0.473606
0.196954
0.0621865
0.52854
0.0687213
0.499415
0.145367
0.0717675
0.0564291
0.795074
0.47212
0.433008
0.0915274
0.0821686
0.0504232
0.184411
0.327564
0.684944
0.460386
0.119007
0.146755
0.0830481
0.0790933
0.134262
0.18682
0.04474
0.243047
0.59192
0.0734762
0.115826
0.121024
0.249295
0.343217
0.250738
0.0627305
0.0610323
0.202083
0.0684975
0.0820823
0.0959935
0.0826509
0.108891
0.431176
0.294753
0.154668
0.166815
0.0470717
0.340676
0.229548
0.035574
0.0452454
0.06936
0.292013
0.0801189
0.0906287
0.062064
0.35705
0.241102
0.475063
0.114033
0.0479901
0.420381
0.524872
0.241529
0.501516
0.126949
0.0725504
0.0326201
0.329884
0.495989
0.072271
0.0819593
0.0901183
0.533384
0.273324
0.322234
0.307728
0.216051
0.0636211
0.182952
0.237951
0.0716999
0.0586584
0.323942
0.26865
0.531756
0.311671
0.0862107
0.134615
0.134128
0.298728
0.0962601
0.103747
0.154804
0.288309
0.0407598
0.137841
0.181438
0.0372809
0.186917
0.174104
0.0669911
0.152506
0.230946
0.250797
0.0838523
0.45869
0.291205
0.0815817
0.337136
0.254383
0.03323
0.0592998
0.455552
0.0736809
0.0601948
0.0838792
0.245392
0.22513
0.411227
0.280298
0.360634
0.070114
0.0817145
0.0473074
0.0386732
0.231757
0.190543
0.0538019
0.440932
0.257995
0.294978
0.266838
0.275592
0.473149
0.0691211
0.0306289
0.369324
0.0806631
0.0772406
0.0717011
0.0738164
0.0910243
0.197521
0.212372
0.0737292
0.0989254
0.0364369
0.142507
0.103331
0.517018
0.204548
0.252348
0.0626195
0.114276
0.244881
0.279823
0.244441
0.529877
0.0610181
0.0794334
0.111583
0.288446
0.0885975
0.251067
0.0306376
0.250979
0.0496692
0.185962
0.24383
0.115369
0.147776
0.416088
0.253327
0.404198
0.0792205
0.242669
0.295024
0.235824
0.112083
0.0515751
0.124366
0.482195
0.256313
0.19187
0.298355
0.533626
0.16364
0.0545864
0.459363
0.158348
0.103708
0.0701526
0.017709
0.0422489
0.032777
0.0582425
0.285986
0.507274
0.0670677
0.0522356
0.0731739
0.0687349
0.0311881
0.0552974
0.119967
0.0412296
0.364144
0.0512388
0.0248997
0.157098
0.0920803
0.0934111
0.211146
0.0533354
0.417869
0.0786626
0.316282
0.0643152
0.102912
0.221676
0.225587
0.0563613
0.284625
0.399006
0.165798
0.155578
0.24356
0.496589
0.196697
0.0664897
0.0735852
0.032804
0.285887
0.0705651
0.0792134
0.1321
0.32307
0.283824
0.084186
0.0984919
0.249016
0.157343
0.0858557
0.29246
0.397098
0.0797967
0.24402
0.110608
0.174989
0.308312
0.225306
0.151127
0.0674266
0.0106104
0.00972021
0.376705
0.0133053
0.0101594
0.0668293
0.406761
0.102808
0.0193753
0.0103294
0.0429338
0.0943639
0.094182
0.0879565
0.0699249
0.0491071
0.280421
0.036364
0.139675
0.0495953
0.143701
0.300767
0.140166
0.571429
0.304146
0.0431027
0.0704973
0.0953437
0.102987
0.119244
0.0639886
0.0662755
0.290872
0.136962
0.117849
0.0386804
0.0385607
0.233537
0.271409
0.167045
0.0355732
0.187043
0.056574
0.118106
0.307933
0.139362
0.258875
0.551388
0.301833
0.0364334
0.0823226
0.209916
0.11568
0.0708999
0.115158
0.0363085
0.0598855
0.0841895
0.065422
0.0717551
0.0772895
0.0735948
0.289808
0.430008
0.0645431
0.201354
0.0496457
0.0979899
0.266817
0.078274
0.0442647
0.0468657
0.0215497
0.216865
0.0868403
0.0634415
0.236425
0.552611
0.0246518
0.095579
0.185578
0.0752706
0.268901
0.109738
0.0277471
0.0846348
0.259563
0.666135
0.0639656
0.151807
0.202239
0.0820262
0.0865577
0.109996
0.0758482
0.0704814
0.0689454
0.0742615
0.117355
0.0581665
0.020745
0.0697622
0.0735733
0.238207
0.134279
0.0657451
0.0964035
0.0209761
0.0642518
0.393294
0.241262
0.0202842
0.160604
0.321321
0.288403
0.135768
0.175159
0.364308
0.0724836
0.301574
0.292259
0.0335527
0.0502175
0.100879
0.0583021
0.0369813
0.0714261
0.258024
0.0224121
0.430196
0.113284
0.08069
0.0774558
0.107346
0.0849798
0.238107
0.0501969
0.0743176
0.0626789
0.141155
0.522477
0.0346506
0.0877899
0.0838551
0.115644
0.483299
0.102697
0.0850005
0.0467674
0.0354539
0.0679079
0.10513
0.0328325
0.101962
0.246048
0.130943
0.460734
0.0622337
0.0919555
0.0540085
0.133918
0.081393
0.294711
0.0311549
0.0510904
0.136553
0.286161
0.159426
0.0708276
0.0550084
0.0719544
0.225169
0.0429434
0.0986972
0.100124
0.245517
0.0735483
0.130034
0.0290435
0.223775
0.0950806
0.0759294
0.0363526
0.270306
0.0826521
0.143529
0.140066
0.0855787
0.0731946
0.236463
0.282061
0.315435
0.0733759
0.123455
0.0636933
0.0732994
0.124691
0.0773689
0.102569
0.104154
0.121746
0.024856
0.262477
0.105099
0.18378
0.0975529
0.0273142
0.0249439
0.0267048
0.0246428
0.0930526
0.0924722
0.0918489
0.0903549
0.0313784
0.0895512
0.0902238
0.0348174
0.0369336
0.0364689
0.158046
0.0369514
0.0372495
0.343203
0.0280505
0.215284
0.0576433
0.0911949
0.50584
0.10171
0.130065
0.105479
0.0216553
0.247749
0.119445
0.0623236
0.105939
0.0960376
0.253019
0.0550828
0.0520136
0.103682
0.0959212
0.0819382
0.0845168
0.0922231
0.102454
0.228148
0.25701
0.473922
0.354215
0.120902
0.0521328
0.266084
0.154208
0.0626338
0.0821771
0.116976
0.178823
0.0956896
0.0932833
0.207528
0.0446771
0.0695942
0.347863
0.249083
0.257489
0.0950804
0.0941495
0.200807
0.11802
0.222795
0.0836189
0.0891207
0.289732
0.118562
0.114835
0.110011
0.088582
0.0807613
0.140774
0.0252439
0.295327
0.0795653
0.0899304
0.0262464
0.256245
0.0866736
0.136475
0.290938
0.14817
0.429791
0.294962
0.13532
0.205221
0.379399
0.303798
0.114571
0.0505113
0.411808
0.180692
0.0531776
0.228386
0.249324
0.0152349
0.0503701
0.234571
0.417413
0.0146637
0.0667783
0.212675
0.153116
0.239764
0.124499
0.0230318
0.222816
0.0771776
0.0986626
0.0607163
0.0320268
0.328326
0.0480364
0.106683
0.54649
0.0483249
0.0338202
0.143149
0.283833
0.129114
0.0502512
0.034254
0.0605634
0.160635
0.0917735
0.354871
0.308522
0.259707
0.0226029
0.182018
0.0706498
0.122102
0.461013
0.0642095
0.303052
0.788921
0.0688587
0.0767152
0.188259
0.102182
0.170824
0.153746
0.0721794
0.315467
0.341739
0.344729
0.0388879
0.0812925
0.0591569
0.24159
0.080885
0.242488
0.127233
0.0618878
0.0783272
0.0487372
0.209755
0.0825602
0.0704956
0.178148
0.0933044
0.213571
0.0742415
0.0372874
0.0305661
0.155477
0.300691
0.0950312
0.0799087
0.237041
0.0704245
0.137218
0.193549
0.0642761
0.0693316
0.117401
0.0635613
0.290521
0.0467891
0.0301575
0.125689
0.0585309
0.0723803
0.0300269
0.148414
0.0512664
0.166469
0.195824
0.0232696
0.166432
0.0539472
0.151846
0.0270437
0.167832
0.137702
0.0517187
0.45634
0.0312631
0.0927933
0.106495
0.0604657
0.110216
0.092069
0.51513
0.0259532
0.106289
0.207014
0.0426193
0.111147
0.0556651
0.091929
0.114114
0.101366
0.0929554
0.105801
0.0301933
0.165593
0.0626333
0.0423417
0.186376
0.307754
0.174837
0.164899
0.086805
0.135275
0.109731
0.0528557
0.0407209
0.0526169
0.0770763
0.314655
0.0566861
0.0821139
0.555433
0.332203
0.135398
0.0903095
0.0666751
0.0488477
0.298304
0.125557
0.0846535
0.0918957
0.0549925
0.0925197
0.106446
0.230978
0.113237
0.0852361
0.0594337
0.104548
0.0565409
0.0648398
0.479872
0.266361
0.149208
0.0477348
0.194712
0.0432759
0.0352292
0.334031
0.0740026
0.0740246
0.0901373
0.0966536
0.271923
0.0274209
0.27199
0.0632331
0.0641947
0.0382951
0.112568
0.253586
0.0951204
0.233105
0.143534
0.245985
0.145688
0.193653
0.0771008
0.11288
0.0580975
0.0288948
0.136382
0.0504515
0.403595
0.266567
0.125278
0.0661216
0.211186
0.0465633
0.116925
0.0597966
0.153561
0.0599516
0.478812
0.0934763
0.07482
0.189109
0.101332
0.306225
0.302779
0.175243
0.349009
0.0632919
0.0803984
0.0645275
0.0594115
0.244161
0.436606
0.0597711
0.479372
0.104694
0.135286
0.058763
0.212634
0.137204
0.0320273
0.175024
0.0189266
0.0834678
0.274931
0.233047
0.131531
0.0836196
0.22638
0.0915525
0.0317257
0.0625966
0.20272
0.337417
0.0367662
0.479922
0.304738
0.346642
0.0403462
0.0875595
0.124897
0.0543826
0.200608
0.148364
0.386196
0.0761533
0.0714046
0.245747
0.239828
0.114696
0.0658675
0.294939
0.550528
0.304884
0.0802459
0.401424
0.371739
0.22831
0.0215114
0.20408
0.189719
0.218297
0.468992
0.02087
0.187554
0.0308043
0.209908
0.0995754
0.363277
0.0103784
0.067459
0.226311
0.117167
0.167861
0.073548
0.0342981
0.171987
0.0952399
0.195061
0.0424082
0.367129
0.0394951
0.196282
0.228341
0.105756
0.215762
0.122427
0.0542695
0.105879
0.0379924
0.235877
0.149377
0.328299
0.060135
0.196759
0.194242
0.0306396
0.058498
0.0770625
0.0884338
0.116115
0.124976
0.0657282
0.0620385
0.0710217
0.113069
0.0774619
0.0337471
0.0555558
0.0789338
0.0764718
0.121679
0.0794237
0.194327
0.0731253
0.100951
0.127462
0.116009
0.202911
0.0379786
0.148516
0.0615946
0.186572
0.0638891
0.0849563
0.0667333
0.107914
0.0540624
0.153076
0.50826
0.0224752
0.0538389
0.202532
0.062578
0.194328
0.0659705
0.082871
0.102193
0.112707
0.0693789
0.0690731
0.0973971
0.0906998
0.232408
0.0815219
0.127844
0.124056
0.0806897
0.304852
0.0506763
0.266977
0.101683
0.131725
0.0974985
0.135493
0.0806352
0.0389354
0.0671961
0.0729561
0.23964
0.0301405
0.347498
0.34652
0.271418
0.061411
0.188736
0.221461
0.0196798
0.120692
0.103831
0.194706
0.123344
0.0672998
0.153396
0.0842264
0.109872
0.107427
0.0739294
0.218481
0.430819
0.266673
0.437722
0.0681817
0.0819255
0.0695974
0.107494
0.224681
0.204086
0.121319
0.0632486
0.075432
0.107701
0.113867
0.0727671
0.0739001
0.118531
0.114646
0.100406
0.0654696
0.0931824
0.0784866
0.112053
0.275012
0.103412
0.228376
0.241948
0.0752272
0.147825
0.286522
0.131108
0.0462621
0.213722
0.0235248
0.130927
0.363172
0.340244
0.068811
0.243195
0.329258
0.0694994
0.271687
0.34689
0.353578
0.126443
0.0676996
0.15906
0.201233
)
;
boundaryField
{
frontAndBack
{
type empty;
}
wallOuter
{
type kqRWallFunction;
value nonuniform List<scalar>
102
(
0.021523
0.021523
0.182525
0.0285745
0.0245654
0.0505035
0.0666112
0.0311881
0.0106104
0.00972021
0.0133053
0.0101594
0.0193753
0.0103294
0.0429338
0.0943639
0.0879565
0.139675
0.0953437
0.117849
0.0355732
0.0364334
0.0823226
0.0496457
0.0979899
0.0820262
0.0865577
0.0335527
0.0714261
0.0950806
0.0363526
0.0273142
0.0249439
0.0267048
0.0246428
0.0930526
0.0924722
0.0918489
0.0903549
0.0313784
0.0895512
0.0902238
0.0348174
0.0369336
0.0364689
0.0369514
0.0372495
0.0576433
0.0911949
0.0960376
0.0550828
0.0959212
0.0922231
0.0956896
0.0932833
0.0695942
0.0950804
0.0941495
0.088582
0.0807613
0.180692
0.0152349
0.0146637
0.0230318
0.0480364
0.034254
0.182018
0.102182
0.170824
0.0618878
0.0704956
0.178148
0.0305661
0.155477
0.0950312
0.0642761
0.0467891
0.0723803
0.166469
0.0517187
0.0927933
0.0259532
0.101366
0.105801
0.174837
0.0526169
0.0821139
0.0918957
0.0565409
0.0504515
0.0915525
0.0317257
0.0215114
0.02087
0.0103784
0.073548
0.0306396
0.0620385
0.0774619
0.0224752
0.0659705
0.102193
)
;
}
inlet
{
type fixedValue;
value nonuniform 0();
}
outlet
{
type zeroGradient;
}
wallInner
{
type kqRWallFunction;
value nonuniform List<scalar>
138
(
0.021133
0.048269
0.114829
0.462976
0.309563
0.376178
0.194054
0.147272
0.415701
0.0636719
0.0805123
0.0609047
0.0399126
0.283823
0.0623623
0.0631079
0.0443671
0.135029
0.0590295
0.0678624
0.068345
0.028536
0.0626567
0.0468523
0.0274528
0.0591773
0.0357141
0.0510933
0.205923
0.0417545
0.0549276
0.0615485
0.0583697
0.0443378
0.0543285
0.0293685
0.061856
0.0186682
0.059839
0.0740062
0.0562964
0.0234872
0.0871275
0.0561171
0.0582454
0.0144624
0.0483371
0.120712
0.0400097
0.0846056
0.0558176
0.0415487
0.0337492
0.0588411
0.0161124
0.112197
0.0462496
0.0630644
0.0944094
0.109008
0.0622646
0.0328783
0.0191669
0.0527475
0.103828
0.0204193
0.0353902
0.123064
0.0574305
0.0759645
0.0652509
0.0487049
0.0415428
0.0112156
0.104257
0.052864
0.123877
0.0300002
0.238103
0.141969
0.0532694
0.0810793
0.0643618
0.0349196
0.0391403
0.184411
0.119007
0.146755
0.134262
0.154668
0.166815
0.035574
0.0326201
0.181438
0.03323
0.0592998
0.197521
0.114276
0.19187
0.032777
0.0582425
0.0248997
0.032804
0.0668293
0.102808
0.167045
0.0598855
0.0215497
0.0246518
0.0277471
0.020745
0.0964035
0.0209761
0.0583021
0.0626789
0.0429434
0.024856
0.0280505
0.0216553
0.114835
0.290938
0.14817
0.0531776
0.0767152
0.127233
0.0301575
0.0426193
0.0556651
0.135275
0.0488477
0.145688
0.120692
0.271687
0.34689
0.126443
0.0676996
0.15906
0.201233
)
;
}
procBoundary2to0
{
type processor;
value nonuniform List<scalar>
42
(
0.623865
0.623865
0.164198
0.14624
0.231126
0.799911
0.140645
0.140645
0.23195
0.217336
0.311792
0.311792
0.243578
0.383632
0.443663
0.755126
0.419304
0.199669
0.226595
0.708122
0.803628
0.164185
0.164185
0.906286
0.803628
0.101574
0.831547
0.0648051
0.831547
0.581496
0.448947
0.0564254
0.0593415
0.065999
0.0738538
0.14624
0.419304
0.094957
0.785409
0.0960456
0.0960456
0.0780814
)
;
}
procBoundary2to1
{
type processor;
value uniform 0.582011;
}
procBoundary2to3
{
type processor;
value nonuniform List<scalar>
29
(
0.824945
0.641666
0.174735
0.121364
0.235826
0.49376
0.360708
0.549389
0.220684
0.225199
0.545214
0.336558
0.565319
0.634272
0.346345
0.522059
0.196393
0.196393
0.641666
0.634272
0.475718
0.19653
0.158459
0.213799
0.259967
0.195371
0.220684
0.504264
0.336558
)
;
}
}
// ************************************************************************* //
| [
"mohan.2611@gmail.com"
] | mohan.2611@gmail.com | |
397036ef5f2ad1414dfec3113ce3ee385f5af827 | eac12609b6506d033e2efbc22ac7b4a09f3f004d | /T_TronNtcElectWidget.hpp | 33eb5105d72bc9dfe6dd062954eb2eb927527672 | [] | no_license | JulesDoc/TerRaTron | 7fca80b52dad075249ebdab92cbea60490cf53cf | 475441a3cce7b01dd499e6f4ab96336087ce7848 | refs/heads/master | 2020-11-25T00:57:24.517021 | 2020-01-07T13:52:53 | 2020-01-07T13:52:53 | 228,419,287 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,569 | hpp | #pragma once
#include <QWidget>
#include <QPointer>
#include <QIcon>
#include <QTreeWidgetItem>
#include <QComboBox>
#include "T_NtcElect.hpp"
#include "T_NtcElectMessageContainer.hpp"
#include "T_NtcElectHighlighter.hpp"
class Ui_tronNtcElectWidget;
class T_TronNtcElectWidget : public QWidget
{
Q_OBJECT
public:
T_TronNtcElectWidget(QWidget* parent = nullptr);
virtual ~T_TronNtcElectWidget();
QWidget* getBrowser() const;
QComboBox* getComboBox() const;
private:
void initializeGUI();
public:
void fillTreeWidget();
void fillFileStatus();
void fillMessages(const T_NtcElectMessageContainer::T_WritableOptions& writeOptions = T_NtcElectMessageContainer::T_WritableOptions());
const QIcon &correspondingIcon(const int& numErr, const int& numWar);
void highlightErrorLine(const int& line);
T_NtcElect &getNtcElect();
//const T_NtcElect &getNtcElect() const;
public slots:
void setRunCheckResult(const T_NtcElect& rcNtcElect);
void handleClicked(QTreeWidgetItem* item);
void handleAlertFileNotUpdated();
void onAnchorClicked(const QUrl& link);
void clearAll();
void showNotices(QString);
signals:
void setResultCompleted();
private:
void setNtcElect(const T_NtcElect& rcNtcElect);
private slots:
private:
Ui_tronNtcElectWidget* m_ui;
T_NtcElect m_NtcElect;
QPointer<T_NtcElectHighlighter> m_highlighter1;
QVector<QTreeWidgetItem*> m_treeWidgetItemsVector{};
bool m_fileUpdated = true;
enum {
SectionNameRole = Qt::UserRole,
NoticeIndexRole
};
enum BrowserDisplayOption {
ShowAll,
ShowMessages,
ShowErrors
};
}; | [
"julio.calvo@itu.int"
] | julio.calvo@itu.int |
cbb9d646580b15544d0408285c49901ae16e1e5b | 7fd5e6156d6a42b305809f474659f641450cea81 | /boost/mpi/detail/packed_iprimitive.hpp | 3a1e1661839fe5c596550d1c230f46134fad0bd7 | [] | no_license | imos/icfpc2015 | 5509b6cfc060108c9e5df8093c5bc5421c8480ea | e998055c0456c258aa86e8379180fad153878769 | refs/heads/master | 2020-04-11T04:30:08.777739 | 2015-08-10T11:53:12 | 2015-08-10T11:53:12 | 40,011,767 | 8 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,982 | hpp | // (C) Copyright 2005 Matthias Troyer
// Use, modification and distribution is subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// Authors: Matthias Troyer
#ifndef BOOST_MPI_PACKED_IPRIMITIVE_HPP
#define BOOST_MPI_PACKED_IPRIMITIVE_HPP
#include "boost/mpi/config.hpp"
#include <cstddef> // size_t
#include "boost/config.hpp"
#include "boost/mpi/datatype.hpp"
#include "boost/mpi/exception.hpp"
#include "boost/assert.hpp"
#include "boost/serialization/array.hpp"
#include "boost/serialization/detail/get_data.hpp"
#include <vector>
#include "boost/mpi/allocator.hpp"
namespace boost { namespace mpi {
/// deserialization using MPI_Unpack
class BOOST_MPI_DECL packed_iprimitive
{
public:
/// the type of the buffer from which the data is unpacked upon deserialization
typedef std::vector<char, allocator<char> > buffer_type;
packed_iprimitive(buffer_type & b, MPI_Comm const & comm, int position = 0)
: buffer_(b),
comm(comm),
position(position)
{
}
void* address ()
{
return &buffer_[0];
}
void const* address () const
{
return &buffer_[0];
}
const std::size_t& size() const
{
return size_ = buffer_.size();
}
void resize(std::size_t s)
{
buffer_.resize(s);
}
void load_binary(void *address, std::size_t count)
{
load_impl(address,MPI_BYTE,count);
}
// fast saving of arrays of fundamental types
template<class T>
void load_array(serialization::array<T> const& x, unsigned int /* file_version */)
{
if (x.count())
load_impl(x.address(), get_mpi_datatype(*x.address()), x.count());
}
/*
template<class T>
void load(serialization::array<T> const& x)
{
load_array(x,0u);
}
*/
typedef is_mpi_datatype<mpl::_1> use_array_optimization;
// default saving of primitives.
template<class T>
void load( T & t)
{
load_impl(&t, get_mpi_datatype(t), 1);
}
template<class CharType>
void load(std::basic_string<CharType> & s)
{
unsigned int l;
load(l);
s.resize(l);
// note breaking a rule here - could be a problem on some platform
if (l)
load_impl(const_cast<CharType *>(s.data()),
get_mpi_datatype(CharType()),l);
}
private:
void load_impl(void * p, MPI_Datatype t, int l)
{
BOOST_MPI_CHECK_RESULT(MPI_Unpack,
(const_cast<char*>(boost::serialization::detail::get_data(buffer_)), buffer_.size(), &position, p, l, t, comm));
}
buffer_type & buffer_;
mutable std::size_t size_;
MPI_Comm comm;
int position;
};
} } // end namespace boost::mpi
#endif // BOOST_MPI_PACKED_IPRIMITIVE_HPP
| [
"git@imoz.jp"
] | git@imoz.jp |
76b745be4dd441d4fa7c49bac18a3d17d231ca71 | 12743a1ea5a22ab2e2393f52933d801d3396e1cf | /Engine/InputRangeConverter.cpp | b03b2eb3875fb3aebd78c1e24611df4c60227647 | [] | no_license | artulec88/GameEngine | 70e52ad8123774d8c4382b4b31d811a571379db7 | 82d95dbe4a94d63d9c901cb14ea14cc8713268d4 | refs/heads/master | 2021-01-23T10:43:16.753071 | 2019-01-03T16:01:45 | 2019-01-03T16:01:45 | 16,595,311 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,974 | cpp | #include "stdafx.h"
#include "InputRangeConverter.h"
#include "Utility/ILogger.h"
#include "Utility/IConfig.h"
#include "Utility/FileManager.h"
#include <fstream>
engine::input::InputRangeConverter::InputRangeConverter(const std::string& inputContextName)
{
const auto convertersCount = GET_CONFIG_VALUE_ENGINE(inputContextName + "ConvertersCount", 0);
for (auto i = 0; i < convertersCount; ++i)
{
std::stringstream ss("");
ss << convertersCount + 1;
const auto range = static_cast<ranges::Range>(GET_CONFIG_VALUE_ENGINE(inputContextName + "Range_" + ss.str(), 0));
Converter converter(GET_CONFIG_VALUE_ENGINE(inputContextName + "ConverterMinInput_" + ss.str(), 0.0f), GET_CONFIG_VALUE_ENGINE(inputContextName + "ConverterMaxInput_" + ss.str(), 0.0f),
GET_CONFIG_VALUE_ENGINE(inputContextName + "ConverterMinOutput_" + ss.str(), 0.0f), GET_CONFIG_VALUE_ENGINE(inputContextName + "ConverterMaxOutput_" + ss.str(), 0.0f));
CHECK_CONDITION_EXIT_ALWAYS_ENGINE(converter.maxInput >= converter.minInput, utility::logging::ERR,
"Invalid input range. Max input range (", converter.maxInput, ") must not be less than min input range (", converter.minInput, ")");
CHECK_CONDITION_EXIT_ALWAYS_ENGINE(converter.maxOutput >= converter.minOutput, utility::logging::ERR,
"Invalid output range. Max output range (", converter.maxOutput, ") must not be less than min output range (", converter.minOutput, ")");
m_convertersMap.insert(std::make_pair(range, converter));
}
}
engine::input::InputRangeConverter::InputRangeConverter(std::ifstream& inFileStream)
{
if (!inFileStream)
{
EMERGENCY_LOG_ENGINE("Invalid file provided to RangeConverter constructor");
}
const auto convertersCount = utility::FileManager::AttemptRead<unsigned>(inFileStream);
for (auto i = 0; i < convertersCount; ++i)
{
ranges::Range range;
Converter converter;
range = static_cast<ranges::Range>(utility::FileManager::AttemptRead<unsigned>(inFileStream));
converter.minInput = utility::FileManager::AttemptRead<math::Real>(inFileStream);
converter.maxInput = utility::FileManager::AttemptRead<math::Real>(inFileStream);
converter.minOutput = utility::FileManager::AttemptRead<math::Real>(inFileStream);
converter.maxOutput = utility::FileManager::AttemptRead<math::Real>(inFileStream);
CHECK_CONDITION_EXIT_ALWAYS_ENGINE(converter.maxInput >= converter.minInput, utility::logging::ERR,
"Invalid input range. Max input range (", converter.maxInput, ") must not be less than min input range (", converter.minInput, ")");
CHECK_CONDITION_EXIT_ALWAYS_ENGINE(converter.maxOutput >= converter.minOutput, utility::logging::ERR,
"Invalid output range. Max output range (", converter.maxOutput, ") must not be less than min output range (", converter.minOutput, ")");
m_convertersMap.insert(std::make_pair(range, converter));
}
}
engine::input::InputRangeConverter::~InputRangeConverter()
{
}
| [
"artulec88@gmail.com"
] | artulec88@gmail.com |
f978468bba391f79180a1ae7d6fe52b300c1a23f | f60f62d0b915df9dbea9564ae696372d47874667 | /URI/Fuel spent.cpp | 47e99706dd249776e0ed59090813dfb37f0c681b | [] | no_license | AbdelrahmanRadwan/Competitive-Programming-Staff | 1256d8615f7b445a17c9f2c53ba1461dbc385d2a | f2010a11aba7c524099a7066bebee16b29c6cd41 | refs/heads/master | 2021-01-02T09:06:48.755299 | 2017-12-15T18:50:08 | 2017-12-15T18:50:08 | 99,144,416 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 173 | cpp | #include<iostream>
#include<iomanip>
using namespace std;
int main ()
{
int a,b;
while(cin>>a>>b)
{
cout<<fixed<<setprecision(3)<<(a*b)/12.00<<endl;
}
return 0;
} | [
"abdelrahman_hamdy_radwan@yahoo.com"
] | abdelrahman_hamdy_radwan@yahoo.com |
3f2d7dbdca61388c9fc8cb56a0c51667319779bb | 0996894e0cdecd2f220974cb2017e389250a57c9 | /practices/cpp/level1/p05_Canvas/Canvas/include/Circle.h | a0b28fab72e5b3c4a19f01c25134f9f5135f5eb8 | [] | no_license | HELLHELLO/CCpp2016 | 2f26c139a1b7d0c12792f1b049582c14d4d594f0 | f609e40e68c6e6b0a5e1dbd97adb7fac738eb1ec | refs/heads/master | 2021-01-20T11:19:21.720323 | 2016-06-15T15:46:45 | 2016-06-15T15:46:45 | 52,769,461 | 0 | 0 | null | 2016-02-29T06:30:30 | 2016-02-29T06:30:30 | null | UTF-8 | C++ | false | false | 251 | h | #ifndef CIRCLE_H
#define CIRCLE_H
#include "Shape.h"
class Circle:public Shape
{
public:
Circle(int x,int y,int r);
virtual void show();
virtual ~Circle();
protected:
private:
int r;
};
#endif // CIRCLE_H
| [
"498523614@qq.com"
] | 498523614@qq.com |
8cf863b1d33d591698626c748e39b6036d62e4fe | 3a4e2d550cabad0cd7a6951c8da8e9afe877a20c | /ofxFX/src/generative/ofxTint.h | eb63a2f06ce145ed8c2f8479f9a3d6dc8d6235a2 | [
"MIT"
] | permissive | Hiroki11x/ofxCustomAddons | cc792c0718ee487d66e97331d0039fd9e14e2b87 | 7949d05ca2cb5615671567a4bb3fc4c637b6e885 | refs/heads/master | 2020-12-25T09:08:57.995731 | 2016-08-06T10:20:48 | 2016-08-06T10:20:48 | 59,759,850 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,835 | h | //
// ofxTint.h
//
// Created by Patricio Gonzalez Vivo on 4/12/12.
// Copyright (c) 2012 http://www.PatricioGonzalezVivo.com. All rights reserved.
//
#pragma once
#include "ofMain.h"
#include "ofxFXObject.h"
#define STRINGIFY(A) #A
class ofxTint : public ofxFXObject {
public:
ofxTint(){
zoom = 9.0;
fade = 1.0;
speed = 0.5;
internalFormat = GL_RGBA;
fragmentShader = STRINGIFY(uniform float zoom;
uniform float time;
uniform float fade;
uniform float speed;
uniform vec2 resolution;
uniform sampler2DRect backbuffer;
uniform sampler2DRect tex0;
float rand(vec2 co){
return fract(sin(dot(co.xy ,vec2(12.9898,78.233))) * 43758.5453);
}
float noise2f( in vec2 p ){
vec2 ip = vec2(floor(p));
vec2 u = fract(p);
u = u*u*(3.0-2.0*u);
float res = mix(mix(rand(ip),
rand(ip+vec2(1.0,0.0)),u.x),
mix(rand(ip+vec2(0.0,1.0)),
rand(ip+vec2(1.0,1.0)),u.x),
u.y);
return res*res;
}
float fbm(vec2 c) {
float f = 0.0;
float w = 1.0;
for (int i = 0; i < 8; i++) {
f += w*noise2f(c);
c *=2.0;
w*=0.5;
}
return f;
}
vec2 cMul(vec2 a, vec2 b) {
return vec2( a.x*b.x - a.y*b.y,a.x*b.y + a.y * b.x);
}
float pattern( vec2 p, out vec2 q, out vec2 r ){
q.x = fbm( p +0.00*time);
q.y = fbm( p + vec2(1.0));
r.x = fbm( p +1.0*q + vec2(1.7,9.2)+0.15*time );
r.y = fbm( p+ 1.0*q + vec2(8.3,2.8)+0.126*time);
return fbm(p +1.0*r + speed* time);
}
void main() {
vec2 q;
vec2 r;
vec2 c = zoom*100.0 * gl_FragCoord.xy / resolution.xy;
float f = pattern( c * 0.01, q, r);
vec4 prev = texture2DRect(backbuffer,gl_FragCoord.xy);
vec4 text = texture2DRect(tex0,gl_FragCoord.xy);
float darker = min(mix(prev.r,
1.0-f,
fade),
prev.r);
gl_FragColor = vec4( vec3( mix(1.0, darker, text.r )), 1.0);
}
);
};
void setZoom(float _zoom){zoom = _zoom;};
void setFade(float _fade){fade = _fade;};
void clear(){
for(int i = 0; i < 2; i++){
pingPong[i].begin();
ofClear(255,255);
pingPong[i].end();
}
}
void update(){
pingPong.dst->begin();
ofClear(0,0);
shader.begin();
shader.setUniform1f("time", ofGetElapsedTimef());
shader.setUniform1f("zoom", zoom);
shader.setUniform1f("fade", fade);
shader.setUniform1f("speed", speed);
shader.setUniform2f("resolution", (float)width, (float)height);
shader.setUniformTexture("backbuffer", pingPong.src->getTextureReference(), 0 );
for( int i = 0; i < nTextures; i++){
string texName = "tex" + ofToString(i);
shader.setUniformTexture(texName.c_str(), textures[i].getTextureReference(), i+1 );
}
pingPong.src->draw(0,0);
shader.end();
pingPong.dst->end();
pingPong.swap();
};
void draw(int _x = 0, int _y = 0, float _width = -1, float _height = -1){
if (_width == -1) _width = width;
if (_height == -1) _height = height;
getTextureReference().draw(_x, _y, _width, _height);
}
float zoom, fade, speed;
};
| [
"hiroki11x@gmail.com"
] | hiroki11x@gmail.com |
4c1aea5867dd3bcf43b85430f9574ada0152e094 | 6a2d591e19136f38ea41fd522376ed8dd7ea3595 | /gameSource/Button.h | 76bc6247a3557828ff20ff8175d81f0c0607d791 | [] | no_license | tomberek/OneLife | 1a67d8e2dd68cc32e6b15bf85b99a4833403efee | 6fc973ae478875c9ca194591cb2bb61a414cede1 | refs/heads/master | 2021-09-03T02:24:37.676660 | 2017-12-29T19:52:48 | 2017-12-29T19:52:48 | 115,839,080 | 0 | 1 | null | 2017-12-31T03:04:32 | 2017-12-31T03:04:31 | null | UTF-8 | C++ | false | false | 4,476 | h | #ifndef BUTTON_INCLUDED
#define BUTTON_INCLUDED
#include "PageComponent.h"
#include "minorGems/game/Font.h"
#include "minorGems/ui/event/ActionListenerList.h"
// button superclass that draws a 1-pixel border and handles events
// fires actionPerformed whenever button pressed
class Button : public PageComponent, public ActionListenerList {
public:
// centered on inX, inY
Button( double inX, double inY,
double inWide, double inHigh,
double inPixelSize );
virtual ~Button();
virtual void setPixelSize( double inPixelSize );
// set the tool tip that will be passed up the parent chain
// when this button is moused over
// NULL disables tip display for this button
// copied internally
virtual void setMouseOverTip( const char *inTipMessage );
// overrides to clear state when made invisible
virtual void setVisible( char inIsVible );
virtual double getWidth();
virtual double getHeight();
virtual void setSize( double inWide, double inHigh );
// defaults to
// ( 0.828, 0.647, 0.212, 1 ) for drag-over
// ( 0.886, 0.764, 0.475, 1 ) for hover and
// white for non-hover
virtual void setDragOverColor( float r, float g, float b, float a );
virtual void setNoHoverColor( float r, float g, float b, float a );
virtual void setHoverColor( float r, float g, float b, float a );
// defaults to
// ( 0.25, 0.25, 0.25, 1 );
virtual void setFillColor( float r, float g, float b, float a );
// defaults to
// ( 0.1, 0.1, 0.1, 1 );
virtual void setDragOverFillColor(
float r, float g, float b, float a );
// defaults to
// ( 0.75, 0.75, 0.75, 1 );
virtual void setHoverBorderColor(
float r, float g, float b, float a );
// if we think about the button border as being
// made of two brackets, like this: [button]
// this is the horizontal length that is enclosed
// in the brackets (above and below the button text), or how
// far the top and bottom arms of the brackets reach
// Defaults to -1, which is a complete, unbroken border
virtual void setBracketCoverLength( double inLength );
// deftaults to 0,0
// sets a shift that is applied before drawing subclass contents
// (for example, to shift a font baseline)
virtual void setContentsShift( doublePair inShift );
// should button border and fill be drawn?
// if not, only button contents (from sub class) is drawn
virtual void setDrawBackground( char inDraw );
virtual char isMouseOver();
virtual char isMouseDragOver();
virtual void setActive( char inActive );
virtual char isActive();
protected:
virtual void clearState();
virtual void step();
virtual void draw();
virtual void pointerMove( float inX, float inY );
virtual void pointerDown( float inX, float inY );
virtual void pointerDrag( float inX, float inY );
// fires action performed to listener list
virtual void pointerUp( float inX, float inY );
char mActive;
char mHover;
char mDragOver;
double mWide, mHigh, mPixWidth;
char *mMouseOverTip;
char isInside( float inX, float inY );
// draw the contents of the button
// should be overridden by subclasses
// Button class sets the draw color before calling drawContents
// (default implementation draws nothing)
virtual void drawContents();
// draws the border of the button
// default is just a rectangle
// Button class sets the draw color before calling drawBorder
virtual void drawBorder();
FloatColor mDragOverColor;
FloatColor mHoverColor;
FloatColor mNoHoverColor;
FloatColor mFillColor;
FloatColor mDragOverFillColor;
FloatColor mHoverBorderColor;
double mBracketCoverLength;
doublePair mContentsShift;
char mDrawBackground;
};
#endif
| [
"jasonrohrer@fastmail.fm"
] | jasonrohrer@fastmail.fm |
978f735794f1387b0aadc243c5352ffa351ac45a | 7e7367a799646ad504f1e8a38bc87d5491f21300 | /ScriptManager/CompiledScript.h | fa42eee5111182696036709b7c09a03ef8445d4f | [] | no_license | OJETeam/Opportunity | 709fa5f56f7ba0d35bf25d45a2625f762405c9c3 | ebcaa5a8950a180ec04b87c16488fa1277618b30 | refs/heads/master | 2020-03-27T09:15:03.909981 | 2019-12-13T01:57:30 | 2019-12-13T01:57:30 | 146,325,335 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 429 | h | #pragma once
#include "IEventReceiver.h"
using namespace System;
using namespace System::Reflection;
namespace ScriptManager
{
public ref class CompiledScript
{
internal:
delegate ScriptManager::IEventReceiver^ Create(void* unit);
static MethodInfo^ methodCreate;
Assembly^ assembly;
Type^ scriptType;
public:
CompiledScript(Type^ scriptType, Assembly^ assembly);
IEventReceiver^ CreateScript(void* unit);
};
} | [
"eugen1344@gmail.com"
] | eugen1344@gmail.com |
d2db1663626988823eb08d1d6ce8907e1b2027d6 | 018c518d17d8c9ff86eb027761dd11002974c17a | /Map/src/main.cpp | 4f542bfda71306252d94606935693011203ea0d4 | [] | no_license | jameschristianto/cpp | bab6275c17738e33993d9fa526537704be9ef177 | df802a2917b3b21b837c5fd6953a0d3f77e0ba0b | refs/heads/master | 2022-05-17T01:14:27.714938 | 2022-04-08T21:27:53 | 2022-04-08T21:27:53 | 237,221,457 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,632 | cpp | #include <iostream>
#include <fstream>
#include <string>
#include <map>
#include <utility> //make_pair
using namespace std;
string filePath = "assets/file.txt";
void findValue(map<int, string> &myMap);
void print(map<int, string> myMap);
void getSize(map<int, string> myMap);
void insert(map<int, string> &myMap);
void erase(map<int, string> &myMap);
void clear(map<int, string> &myMap);
int main()
{
map<int, string> myMap;
pair<int, string> myPair;
int key;
string value;
string line;
ifstream inFile(filePath);
int select;
if (inFile.is_open())
{
cout << "File opened..." << endl;
while (getline(inFile, line))
{
//cout << "ID : " << line.substr(0, line.find(":"));
//cout << " , Value : " << line.substr(line.find(":") + 1) << endl;
key = stoi(line.substr(0, line.find(":")));
value = line.substr(line.find(":") + 1);
//method 1
myMap.insert({key, value});
//method 2
//myMap.insert(make_pair(key, value));
//method 3
//myMap[key] = value;
}
inFile.close();
}
else
cout << "Unable to open file..." << endl;
do
{
cout << "1. Print" << endl;
cout << "2. Find" << endl;
cout << "3. Size" << endl;
cout << "4. Insert" << endl;
cout << "5. Erase" << endl;
cout << "6. Clear" << endl;
cout << endl;
cout << "Select command : ";
cin >> select;
switch (select)
{
case 1:
print(myMap);
break;
case 2:
findValue(myMap);
break;
case 3:
getSize(myMap);
break;
case 4:
insert(myMap);
break;
case 5:
erase(myMap);
break;
case 6:
clear(myMap);
break;
default:
break;
}
} while (1);
system("pause");
return 0;
}
void findValue(map<int, string> &myMap)
{
int selectKey;
cout << endl;
cout << "Input key : ";
cin >> selectKey;
if (myMap.find(selectKey) != myMap.end())
{
cout << "Value of key " << selectKey << " : " << myMap.find(selectKey)->second << endl;
cout << endl;
return;
}
cout << "Key not found..." << endl;
cout << endl;
}
void print(map<int, string> myMap)
{
map<int, string>::iterator itr;
cout << endl;
if (!myMap.empty())
{
for (itr = myMap.begin(); itr != myMap.end(); ++itr)
{
cout << itr->first << " -> " << itr->second << endl;
}
}
else
cout << "No data found..." << endl;
cout << endl;
}
void getSize(map<int, string> myMap)
{
cout << endl;
cout << "There is " << myMap.size() << " data" << endl;
cout << endl;
}
void insert(map<int, string> &myMap)
{
int key;
string value;
cout << endl;
cout << "Input key : ";
cin >> key;
cout << "Input value : ";
cin >> value;
if (myMap.find(key) == myMap.end())
myMap.insert({key, value});
else
myMap.find(key)->second = value;
cout << endl;
}
void erase(map<int, string> &myMap)
{
int key;
string value;
map<int, string>::iterator itr;
cout << endl;
cout << "Input key : ";
cin >> key;
//method 1
myMap.erase(key);
//method 2
//itr = myMap.find(key);
//myMap.erase(itr);
cout << endl;
}
void clear(map<int, string> &myMap)
{
myMap.clear();
cout << endl;
} | [
"jameschrist0000@gmail.com"
] | jameschrist0000@gmail.com |
4109b4c0a120b122e76cce91449167a7d402e5de | 74e61d81147002ce75c52a81e56ab00ccb90ab41 | /frameworks/resmgr/include/utils/locale_data.h | 586215579813d92268f5871f2b3a959ac0647e26 | [
"Apache-2.0"
] | permissive | openharmony/global_resmgr_standard | 23967f6716200e49ddd86dd6bd6b9052e62a8cf3 | e691f7c360f262bc253b1aa974599459c5577319 | refs/heads/master | 2023-08-23T22:53:17.245919 | 2021-09-18T08:57:50 | 2021-09-18T08:57:50 | 400,082,547 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 70,924 | h | /*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef RESOURCE_MANAGER_LOCALE_DATA_H
#define RESOURCE_MANAGER_LOCALE_DATA_H
#include <cstdint>
namespace OHOS {
namespace Global {
namespace Resource {
const uint16_t NEW_LANGUAGES_CODES[] = {
static_cast<uint16_t>(0x6977), /* iw */
static_cast<uint16_t>(0x746c), /* tl */
static_cast<uint16_t>(0x6a69), /* ji */
static_cast<uint16_t>(0x6a77), /* jw */
static_cast<uint16_t>(0x696e), /* in */
};
const uint16_t OLD_LANGUAGES_CODES[] = {
static_cast<uint16_t>(0x6865), /* he */
static_cast<uint16_t>(0x950b), /* fil */
static_cast<uint16_t>(0x7969), /* yi */
static_cast<uint16_t>(0x6a76), /* jv */
static_cast<uint16_t>(0x6964), /* id */
};
const uint64_t LOCALE_PARENTS_KEY[] = {
static_cast<uint64_t>(0x656e0000000084a0), /* en-150 */
static_cast<uint64_t>(0x656e000000004147), /* en-AG */
static_cast<uint64_t>(0x656e000000004149), /* en-AI */
static_cast<uint64_t>(0x656e000000004155), /* en-AU */
static_cast<uint64_t>(0x656e000000004242), /* en-BB */
static_cast<uint64_t>(0x656e00000000424d), /* en-BM */
static_cast<uint64_t>(0x656e000000004253), /* en-BS */
static_cast<uint64_t>(0x656e000000004257), /* en-BW */
static_cast<uint64_t>(0x656e00000000425a), /* en-BZ */
static_cast<uint64_t>(0x656e000000004343), /* en-CC */
static_cast<uint64_t>(0x656e00000000434b), /* en-CK */
static_cast<uint64_t>(0x656e00000000434d), /* en-CM */
static_cast<uint64_t>(0x656e000000004358), /* en-CX */
static_cast<uint64_t>(0x656e000000004359), /* en-CY */
static_cast<uint64_t>(0x656e000000004447), /* en-DG */
static_cast<uint64_t>(0x656e00000000444d), /* en-DM */
static_cast<uint64_t>(0x656e000000004552), /* en-ER */
static_cast<uint64_t>(0x656e00000000464a), /* en-FJ */
static_cast<uint64_t>(0x656e00000000464b), /* en-FK */
static_cast<uint64_t>(0x656e00000000464d), /* en-FM */
static_cast<uint64_t>(0x656e000000004742), /* en-GB */
static_cast<uint64_t>(0x656e000000004744), /* en-GD */
static_cast<uint64_t>(0x656e000000004747), /* en-GG */
static_cast<uint64_t>(0x656e000000004748), /* en-GH */
static_cast<uint64_t>(0x656e000000004749), /* en-GI */
static_cast<uint64_t>(0x656e00000000474d), /* en-GM */
static_cast<uint64_t>(0x656e000000004759), /* en-GY */
static_cast<uint64_t>(0x656e00000000484b), /* en-HK */
static_cast<uint64_t>(0x656e000000004945), /* en-IE */
static_cast<uint64_t>(0x656e00000000494c), /* en-IL */
static_cast<uint64_t>(0x656e00000000494d), /* en-IM */
static_cast<uint64_t>(0x656e00000000494e), /* en-IN */
static_cast<uint64_t>(0x656e00000000494f), /* en-IO */
static_cast<uint64_t>(0x656e000000004a45), /* en-JE */
static_cast<uint64_t>(0x656e000000004a4d), /* en-JM */
static_cast<uint64_t>(0x656e000000004b45), /* en-KE */
static_cast<uint64_t>(0x656e000000004b49), /* en-KI */
static_cast<uint64_t>(0x656e000000004b4e), /* en-KN */
static_cast<uint64_t>(0x656e000000004b59), /* en-KY */
static_cast<uint64_t>(0x656e000000004c43), /* en-LC */
static_cast<uint64_t>(0x656e000000004c52), /* en-LR */
static_cast<uint64_t>(0x656e000000004c53), /* en-LS */
static_cast<uint64_t>(0x656e000000004d47), /* en-MG */
static_cast<uint64_t>(0x656e000000004d4f), /* en-MO */
static_cast<uint64_t>(0x656e000000004d53), /* en-MS */
static_cast<uint64_t>(0x656e000000004d54), /* en-MT */
static_cast<uint64_t>(0x656e000000004d55), /* en-MU */
static_cast<uint64_t>(0x656e000000004d57), /* en-MW */
static_cast<uint64_t>(0x656e000000004d59), /* en-MY */
static_cast<uint64_t>(0x656e000000004e41), /* en-NA */
static_cast<uint64_t>(0x656e000000004e46), /* en-NF */
static_cast<uint64_t>(0x656e000000004e47), /* en-NG */
static_cast<uint64_t>(0x656e000000004e52), /* en-NR */
static_cast<uint64_t>(0x656e000000004e55), /* en-NU */
static_cast<uint64_t>(0x656e000000004e5a), /* en-NZ */
static_cast<uint64_t>(0x656e000000005047), /* en-PG */
static_cast<uint64_t>(0x656e000000005048), /* en-PH */
static_cast<uint64_t>(0x656e00000000504b), /* en-PK */
static_cast<uint64_t>(0x656e00000000504e), /* en-PN */
static_cast<uint64_t>(0x656e000000005057), /* en-PW */
static_cast<uint64_t>(0x656e000000005257), /* en-RW */
static_cast<uint64_t>(0x656e000000005342), /* en-SB */
static_cast<uint64_t>(0x656e000000005343), /* en-SC */
static_cast<uint64_t>(0x656e000000005344), /* en-SD */
static_cast<uint64_t>(0x656e000000005347), /* en-SG */
static_cast<uint64_t>(0x656e000000005348), /* en-SH */
static_cast<uint64_t>(0x656e00000000534c), /* en-SL */
static_cast<uint64_t>(0x656e000000005353), /* en-SS */
static_cast<uint64_t>(0x656e000000005358), /* en-SX */
static_cast<uint64_t>(0x656e00000000535a), /* en-SZ */
static_cast<uint64_t>(0x656e000000005443), /* en-TC */
static_cast<uint64_t>(0x656e00000000544b), /* en-TK */
static_cast<uint64_t>(0x656e00000000544f), /* en-TO */
static_cast<uint64_t>(0x656e000000005454), /* en-TT */
static_cast<uint64_t>(0x656e000000005456), /* en-TV */
static_cast<uint64_t>(0x656e00000000545a), /* en-TZ */
static_cast<uint64_t>(0x656e000000005547), /* en-UG */
static_cast<uint64_t>(0x656e000000005643), /* en-VC */
static_cast<uint64_t>(0x656e000000005647), /* en-VG */
static_cast<uint64_t>(0x656e000000005655), /* en-VU */
static_cast<uint64_t>(0x656e000000005753), /* en-WS */
static_cast<uint64_t>(0x656e000000005a41), /* en-ZA */
static_cast<uint64_t>(0x656e000000005a4d), /* en-ZM */
static_cast<uint64_t>(0x656e000000005a57), /* en-ZW */
static_cast<uint64_t>(0x656e000000004154), /* en-AT */
static_cast<uint64_t>(0x656e000000004245), /* en-BE */
static_cast<uint64_t>(0x656e000000004348), /* en-CH */
static_cast<uint64_t>(0x656e000000004445), /* en-DE */
static_cast<uint64_t>(0x656e00000000444b), /* en-DK */
static_cast<uint64_t>(0x656e000000004649), /* en-FI */
static_cast<uint64_t>(0x656e000000004e4c), /* en-NL */
static_cast<uint64_t>(0x656e000000005345), /* en-SE */
static_cast<uint64_t>(0x656e000000005349), /* en-SI */
static_cast<uint64_t>(0x6573000000004152), /* es-AR */
static_cast<uint64_t>(0x657300000000424f), /* es-BO */
static_cast<uint64_t>(0x6573000000004252), /* es-BR */
static_cast<uint64_t>(0x657300000000425a), /* es-BZ */
static_cast<uint64_t>(0x657300000000434c), /* es-CL */
static_cast<uint64_t>(0x657300000000434f), /* es-CO */
static_cast<uint64_t>(0x6573000000004352), /* es-CR */
static_cast<uint64_t>(0x6573000000004355), /* es-CU */
static_cast<uint64_t>(0x657300000000444f), /* es-DO */
static_cast<uint64_t>(0x6573000000004543), /* es-EC */
static_cast<uint64_t>(0x6573000000004754), /* es-GT */
static_cast<uint64_t>(0x657300000000484e), /* es-HN */
static_cast<uint64_t>(0x6573000000004d58), /* es-MX */
static_cast<uint64_t>(0x6573000000004e49), /* es-NI */
static_cast<uint64_t>(0x6573000000005041), /* es-PA */
static_cast<uint64_t>(0x6573000000005045), /* es-PE */
static_cast<uint64_t>(0x6573000000005052), /* es-PR */
static_cast<uint64_t>(0x6573000000005059), /* es-PY */
static_cast<uint64_t>(0x6573000000005356), /* es-SV */
static_cast<uint64_t>(0x6573000000005553), /* es-US */
static_cast<uint64_t>(0x6573000000005559), /* es-UY */
static_cast<uint64_t>(0x6573000000005645), /* es-VE */
static_cast<uint64_t>(0x707400000000414f), /* pt-AO */
static_cast<uint64_t>(0x7074000000004348), /* pt-CH */
static_cast<uint64_t>(0x7074000000004356), /* pt-CV */
static_cast<uint64_t>(0x7074000000004652), /* pt-FR */
static_cast<uint64_t>(0x7074000000004751), /* pt-GQ */
static_cast<uint64_t>(0x7074000000004757), /* pt-GW */
static_cast<uint64_t>(0x7074000000004c55), /* pt-LU */
static_cast<uint64_t>(0x7074000000004d4f), /* pt-MO */
static_cast<uint64_t>(0x7074000000004d5a), /* pt-MZ */
static_cast<uint64_t>(0x7074000000005354), /* pt-ST */
static_cast<uint64_t>(0x707400000000544c), /* pt-TL */
static_cast<uint64_t>(0x617a417261620000), /* az-Arab */
static_cast<uint64_t>(0x617a4379726c0000), /* az-Cyrl */
static_cast<uint64_t>(0x85734c61746e0000), /* blt-Latn */
static_cast<uint64_t>(0x626d4e6b6f6f0000), /* bm-Nkoo */
static_cast<uint64_t>(0x62734379726c0000), /* bs-Cyrl */
static_cast<uint64_t>(0x870d4c61746e0000), /* byn-Latn */
static_cast<uint64_t>(0x6375476c61670000), /* cu-Glag */
static_cast<uint64_t>(0x8d24417261620000), /* dje-Arab */
static_cast<uint64_t>(0x8f0e417261620000), /* dyo-Arab */
static_cast<uint64_t>(0x656e447372740000), /* en-Dsrt */
static_cast<uint64_t>(0x656e536861770000), /* en-Shaw */
static_cast<uint64_t>(0x666641646c6d0000), /* ff-Adlm */
static_cast<uint64_t>(0x6666417261620000), /* ff-Arab */
static_cast<uint64_t>(0x6861417261620000), /* ha-Arab */
static_cast<uint64_t>(0x68694c61746e0000), /* hi-Latn */
static_cast<uint64_t>(0x69754c61746e0000), /* iu-Latn */
static_cast<uint64_t>(0x6b6b417261620000), /* kk-Arab */
static_cast<uint64_t>(0x6b73446576610000), /* ks-Deva */
static_cast<uint64_t>(0x6b75417261620000), /* ku-Arab */
static_cast<uint64_t>(0x6b79417261620000), /* ky-Arab */
static_cast<uint64_t>(0x6b794c61746e0000), /* ky-Latn */
static_cast<uint64_t>(0x6d6c417261620000), /* ml-Arab */
static_cast<uint64_t>(0x6d6e4d6f6e670000), /* mn-Mong */
static_cast<uint64_t>(0xb1a84d7465690000), /* mni-Mtei */
static_cast<uint64_t>(0x6d73417261620000), /* ms-Arab */
static_cast<uint64_t>(0x7061417261620000), /* pa-Arab */
static_cast<uint64_t>(0xc813446576610000), /* sat-Deva */
static_cast<uint64_t>(0x7364446576610000), /* sd-Deva */
static_cast<uint64_t>(0x73644b686f6a0000), /* sd-Khoj */
static_cast<uint64_t>(0x736453696e640000), /* sd-Sind */
static_cast<uint64_t>(0xc8e84c61746e0000), /* shi-Latn */
static_cast<uint64_t>(0x736f417261620000), /* so-Arab */
static_cast<uint64_t>(0x73724c61746e0000), /* sr-Latn */
static_cast<uint64_t>(0x7377417261620000), /* sw-Arab */
static_cast<uint64_t>(0x7467417261620000), /* tg-Arab */
static_cast<uint64_t>(0x75674379726c0000), /* ug-Cyrl */
static_cast<uint64_t>(0x757a417261620000), /* uz-Arab */
static_cast<uint64_t>(0x757a4379726c0000), /* uz-Cyrl */
static_cast<uint64_t>(0xd4084c61746e0000), /* vai-Latn */
static_cast<uint64_t>(0x776f417261620000), /* wo-Arab */
static_cast<uint64_t>(0x796f417261620000), /* yo-Arab */
static_cast<uint64_t>(0xe28448616e730000), /* yue-Hans */
static_cast<uint64_t>(0x7a6848616e740000), /* zh-Hant */
static_cast<uint64_t>(0x7a6848616e744d4f), /* zh-Hant-MO */
static_cast<uint64_t>(0x617200000000445a), /* ar-DZ */
static_cast<uint64_t>(0x6172000000004548), /* ar-EH */
static_cast<uint64_t>(0x6172000000004c59), /* ar-LY */
static_cast<uint64_t>(0x6172000000004d41), /* ar-MA */
static_cast<uint64_t>(0x617200000000544e), /* ar-TN */
};
const uint64_t LOCALE_PARENTS_VALUE[] = {
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e000000008001), /* en-001 */
static_cast<uint64_t>(0x656e0000000084a0), /* en-150 */
static_cast<uint64_t>(0x656e0000000084a0), /* en-150 */
static_cast<uint64_t>(0x656e0000000084a0), /* en-150 */
static_cast<uint64_t>(0x656e0000000084a0), /* en-150 */
static_cast<uint64_t>(0x656e0000000084a0), /* en-150 */
static_cast<uint64_t>(0x656e0000000084a0), /* en-150 */
static_cast<uint64_t>(0x656e0000000084a0), /* en-150 */
static_cast<uint64_t>(0x656e0000000084a0), /* en-150 */
static_cast<uint64_t>(0x656e0000000084a0), /* en-150 */
static_cast<uint64_t>(0x6573000000009029), /* es-419 */
static_cast<uint64_t>(0x6573000000009029), /* es-419 */
static_cast<uint64_t>(0x6573000000009029), /* es-419 */
static_cast<uint64_t>(0x6573000000009029), /* es-419 */
static_cast<uint64_t>(0x6573000000009029), /* es-419 */
static_cast<uint64_t>(0x6573000000009029), /* es-419 */
static_cast<uint64_t>(0x6573000000009029), /* es-419 */
static_cast<uint64_t>(0x6573000000009029), /* es-419 */
static_cast<uint64_t>(0x6573000000009029), /* es-419 */
static_cast<uint64_t>(0x6573000000009029), /* es-419 */
static_cast<uint64_t>(0x6573000000009029), /* es-419 */
static_cast<uint64_t>(0x6573000000009029), /* es-419 */
static_cast<uint64_t>(0x6573000000009029), /* es-419 */
static_cast<uint64_t>(0x6573000000009029), /* es-419 */
static_cast<uint64_t>(0x6573000000009029), /* es-419 */
static_cast<uint64_t>(0x6573000000009029), /* es-419 */
static_cast<uint64_t>(0x6573000000009029), /* es-419 */
static_cast<uint64_t>(0x6573000000009029), /* es-419 */
static_cast<uint64_t>(0x6573000000009029), /* es-419 */
static_cast<uint64_t>(0x6573000000009029), /* es-419 */
static_cast<uint64_t>(0x6573000000009029), /* es-419 */
static_cast<uint64_t>(0x6573000000009029), /* es-419 */
static_cast<uint64_t>(0x7074000000005054), /* pt-PT */
static_cast<uint64_t>(0x7074000000005054), /* pt-PT */
static_cast<uint64_t>(0x7074000000005054), /* pt-PT */
static_cast<uint64_t>(0x7074000000005054), /* pt-PT */
static_cast<uint64_t>(0x7074000000005054), /* pt-PT */
static_cast<uint64_t>(0x7074000000005054), /* pt-PT */
static_cast<uint64_t>(0x7074000000005054), /* pt-PT */
static_cast<uint64_t>(0x7074000000005054), /* pt-PT */
static_cast<uint64_t>(0x7074000000005054), /* pt-PT */
static_cast<uint64_t>(0x7074000000005054), /* pt-PT */
static_cast<uint64_t>(0x7074000000005054), /* pt-PT */
static_cast<uint64_t>(0x0), /* ROOT Locale */
static_cast<uint64_t>(0x0), /* ROOT Locale */
static_cast<uint64_t>(0x0), /* ROOT Locale */
static_cast<uint64_t>(0x0), /* ROOT Locale */
static_cast<uint64_t>(0x0), /* ROOT Locale */
static_cast<uint64_t>(0x0), /* ROOT Locale */
static_cast<uint64_t>(0x0), /* ROOT Locale */
static_cast<uint64_t>(0x0), /* ROOT Locale */
static_cast<uint64_t>(0x0), /* ROOT Locale */
static_cast<uint64_t>(0x0), /* ROOT Locale */
static_cast<uint64_t>(0x0), /* ROOT Locale */
static_cast<uint64_t>(0x0), /* ROOT Locale */
static_cast<uint64_t>(0x0), /* ROOT Locale */
static_cast<uint64_t>(0x0), /* ROOT Locale */
static_cast<uint64_t>(0x0), /* ROOT Locale */
static_cast<uint64_t>(0x0), /* ROOT Locale */
static_cast<uint64_t>(0x0), /* ROOT Locale */
static_cast<uint64_t>(0x0), /* ROOT Locale */
static_cast<uint64_t>(0x0), /* ROOT Locale */
static_cast<uint64_t>(0x0), /* ROOT Locale */
static_cast<uint64_t>(0x0), /* ROOT Locale */
static_cast<uint64_t>(0x0), /* ROOT Locale */
static_cast<uint64_t>(0x0), /* ROOT Locale */
static_cast<uint64_t>(0x0), /* ROOT Locale */
static_cast<uint64_t>(0x0), /* ROOT Locale */
static_cast<uint64_t>(0x0), /* ROOT Locale */
static_cast<uint64_t>(0x0), /* ROOT Locale */
static_cast<uint64_t>(0x0), /* ROOT Locale */
static_cast<uint64_t>(0x0), /* ROOT Locale */
static_cast<uint64_t>(0x0), /* ROOT Locale */
static_cast<uint64_t>(0x0), /* ROOT Locale */
static_cast<uint64_t>(0x0), /* ROOT Locale */
static_cast<uint64_t>(0x0), /* ROOT Locale */
static_cast<uint64_t>(0x0), /* ROOT Locale */
static_cast<uint64_t>(0x0), /* ROOT Locale */
static_cast<uint64_t>(0x0), /* ROOT Locale */
static_cast<uint64_t>(0x0), /* ROOT Locale */
static_cast<uint64_t>(0x0), /* ROOT Locale */
static_cast<uint64_t>(0x0), /* ROOT Locale */
static_cast<uint64_t>(0x0), /* ROOT Locale */
static_cast<uint64_t>(0x0), /* ROOT Locale */
static_cast<uint64_t>(0x0), /* ROOT Locale */
static_cast<uint64_t>(0x0), /* ROOT Locale */
static_cast<uint64_t>(0x7a6848616e74484b), /* zh-Hant-HK */
static_cast<uint64_t>(0x6172000000008025), /* ar-015 */
static_cast<uint64_t>(0x6172000000008025), /* ar-015 */
static_cast<uint64_t>(0x6172000000008025), /* ar-015 */
static_cast<uint64_t>(0x6172000000008025), /* ar-015 */
static_cast<uint64_t>(0x6172000000008025), /* ar-015 */
};
const uint64_t TYPICAL_CODES_VALUE[] = {
static_cast<uint64_t>(0x61614c61746e4554), /* aa-Latn-ET */
static_cast<uint64_t>(0x61624379726c4745), /* ab-Cyrl-GE */
static_cast<uint64_t>(0x80314c61746e4748), /* abr-Latn-GH */
static_cast<uint64_t>(0x80444c61746e4944), /* ace-Latn-ID */
static_cast<uint64_t>(0x80474c61746e5547), /* ach-Latn-UG */
static_cast<uint64_t>(0x80604c61746e4748), /* ada-Latn-GH */
static_cast<uint64_t>(0x806f546962744254), /* adp-Tibt-BT */
static_cast<uint64_t>(0x80784379726c5255), /* ady-Cyrl-RU */
static_cast<uint64_t>(0x6165417673744952), /* ae-Avst-IR */
static_cast<uint64_t>(0x808141726162544e), /* aeb-Arab-TN */
static_cast<uint64_t>(0x61664c61746e5a41), /* af-Latn-ZA */
static_cast<uint64_t>(0x80d04c61746e434d), /* agq-Latn-CM */
static_cast<uint64_t>(0x80ee41686f6d494e), /* aho-Ahom-IN */
static_cast<uint64_t>(0x616b4c61746e4748), /* ak-Latn-GH */
static_cast<uint64_t>(0x814a587375784951), /* akk-Xsux-IQ */
static_cast<uint64_t>(0x816d4c61746e584b), /* aln-Latn-XK */
static_cast<uint64_t>(0x81734379726c5255), /* alt-Cyrl-RU */
static_cast<uint64_t>(0x616d457468694554), /* am-Ethi-ET */
static_cast<uint64_t>(0x818e4c61746e4e47), /* amo-Latn-NG */
static_cast<uint64_t>(0x616e4c61746e4553), /* an-Latn-ES */
static_cast<uint64_t>(0x81d94c61746e4944), /* aoz-Latn-ID */
static_cast<uint64_t>(0x81e3417261625447), /* apd-Arab-TG */
static_cast<uint64_t>(0x6172417261624547), /* ar-Arab-EG */
static_cast<uint64_t>(0x822241726d694952), /* arc-Armi-IR */
static_cast<uint64_t>(0x82224e6261744a4f), /* arc-Nbat-JO */
static_cast<uint64_t>(0x822250616c6d5359), /* arc-Palm-SY */
static_cast<uint64_t>(0x822d4c61746e434c), /* arn-Latn-CL */
static_cast<uint64_t>(0x822e4c61746e424f), /* aro-Latn-BO */
static_cast<uint64_t>(0x823041726162445a), /* arq-Arab-DZ */
static_cast<uint64_t>(0x8232417261625341), /* ars-Arab-SA */
static_cast<uint64_t>(0x8238417261624d41), /* ary-Arab-MA */
static_cast<uint64_t>(0x8239417261624547), /* arz-Arab-EG */
static_cast<uint64_t>(0x617342656e67494e), /* as-Beng-IN */
static_cast<uint64_t>(0x82404c61746e545a), /* asa-Latn-TZ */
static_cast<uint64_t>(0x824453676e775553), /* ase-Sgnw-US */
static_cast<uint64_t>(0x82534c61746e4553), /* ast-Latn-ES */
static_cast<uint64_t>(0x82694c61746e4341), /* atj-Latn-CA */
static_cast<uint64_t>(0x61764379726c5255), /* av-Cyrl-RU */
static_cast<uint64_t>(0x82c044657661494e), /* awa-Deva-IN */
static_cast<uint64_t>(0x61794c61746e424f), /* ay-Latn-BO */
static_cast<uint64_t>(0x617a4c61746e415a), /* az-Latn-AZ */
static_cast<uint64_t>(0x617a417261624952), /* az-Arab-IR */
static_cast<uint64_t>(0x62614379726c5255), /* ba-Cyrl-RU */
static_cast<uint64_t>(0x840b41726162504b), /* bal-Arab-PK */
static_cast<uint64_t>(0x840d4c61746e4944), /* ban-Latn-ID */
static_cast<uint64_t>(0x840f446576614e50), /* bap-Deva-NP */
static_cast<uint64_t>(0x84114c61746e4154), /* bar-Latn-AT */
static_cast<uint64_t>(0x84124c61746e434d), /* bas-Latn-CM */
static_cast<uint64_t>(0x841742616d75434d), /* bax-Bamu-CM */
static_cast<uint64_t>(0x84224c61746e4944), /* bbc-Latn-ID */
static_cast<uint64_t>(0x84294c61746e434d), /* bbj-Latn-CM */
static_cast<uint64_t>(0x84484c61746e4349), /* bci-Latn-CI */
static_cast<uint64_t>(0x62654379726c4259), /* be-Cyrl-BY */
static_cast<uint64_t>(0x8489417261625344), /* bej-Arab-SD */
static_cast<uint64_t>(0x848c4c61746e5a4d), /* bem-Latn-ZM */
static_cast<uint64_t>(0x84964c61746e4944), /* bew-Latn-ID */
static_cast<uint64_t>(0x84994c61746e545a), /* bez-Latn-TZ */
static_cast<uint64_t>(0x84a34c61746e434d), /* bfd-Latn-CM */
static_cast<uint64_t>(0x84b054616d6c494e), /* bfq-Taml-IN */
static_cast<uint64_t>(0x84b341726162504b), /* bft-Arab-PK */
static_cast<uint64_t>(0x84b844657661494e), /* bfy-Deva-IN */
static_cast<uint64_t>(0x62674379726c4247), /* bg-Cyrl-BG */
static_cast<uint64_t>(0x84c244657661494e), /* bgc-Deva-IN */
static_cast<uint64_t>(0x84cd41726162504b), /* bgn-Arab-PK */
static_cast<uint64_t>(0x84d74772656b5452), /* bgx-Grek-TR */
static_cast<uint64_t>(0x84e144657661494e), /* bhb-Deva-IN */
static_cast<uint64_t>(0x84e844657661494e), /* bhi-Deva-IN */
static_cast<uint64_t>(0x84ee44657661494e), /* bho-Deva-IN */
static_cast<uint64_t>(0x62694c61746e5655), /* bi-Latn-VU */
static_cast<uint64_t>(0x850a4c61746e5048), /* bik-Latn-PH */
static_cast<uint64_t>(0x850d4c61746e4e47), /* bin-Latn-NG */
static_cast<uint64_t>(0x852944657661494e), /* bjj-Deva-IN */
static_cast<uint64_t>(0x852d4c61746e4944), /* bjn-Latn-ID */
static_cast<uint64_t>(0x85334c61746e534e), /* bjt-Latn-SN */
static_cast<uint64_t>(0x854c4c61746e434d), /* bkm-Latn-CM */
static_cast<uint64_t>(0x85544c61746e5048), /* bku-Latn-PH */
static_cast<uint64_t>(0x857354617674564e), /* blt-Tavt-VN */
static_cast<uint64_t>(0x626d4c61746e4d4c), /* bm-Latn-ML */
static_cast<uint64_t>(0x85904c61746e4d4c), /* bmq-Latn-ML */
static_cast<uint64_t>(0x626e42656e674244), /* bn-Beng-BD */
static_cast<uint64_t>(0x626f54696274434e), /* bo-Tibt-CN */
static_cast<uint64_t>(0x85f842656e67494e), /* bpy-Beng-IN */
static_cast<uint64_t>(0x8608417261624952), /* bqi-Arab-IR */
static_cast<uint64_t>(0x86154c61746e4349), /* bqv-Latn-CI */
static_cast<uint64_t>(0x62724c61746e4652), /* br-Latn-FR */
static_cast<uint64_t>(0x862044657661494e), /* bra-Deva-IN */
static_cast<uint64_t>(0x862741726162504b), /* brh-Arab-PK */
static_cast<uint64_t>(0x863744657661494e), /* brx-Deva-IN */
static_cast<uint64_t>(0x62734c61746e4241), /* bs-Latn-BA */
static_cast<uint64_t>(0x8650426173734c52), /* bsq-Bass-LR */
static_cast<uint64_t>(0x86524c61746e434d), /* bss-Latn-CM */
static_cast<uint64_t>(0x866e4c61746e5048), /* bto-Latn-PH */
static_cast<uint64_t>(0x867544657661504b), /* btv-Deva-PK */
static_cast<uint64_t>(0x86804379726c5255), /* bua-Cyrl-RU */
static_cast<uint64_t>(0x86824c61746e5954), /* buc-Latn-YT */
static_cast<uint64_t>(0x86864c61746e4944), /* bug-Latn-ID */
static_cast<uint64_t>(0x868c4c61746e434d), /* bum-Latn-CM */
static_cast<uint64_t>(0x86a14c61746e4751), /* bvb-Latn-GQ */
static_cast<uint64_t>(0x870d457468694552), /* byn-Ethi-ER */
static_cast<uint64_t>(0x87154c61746e434d), /* byv-Latn-CM */
static_cast<uint64_t>(0x87244c61746e4d4c), /* bze-Latn-ML */
static_cast<uint64_t>(0x63614c61746e4553), /* ca-Latn-ES */
static_cast<uint64_t>(0x88034c61746e5553), /* cad-Latn-US */
static_cast<uint64_t>(0x88474c61746e4e47), /* cch-Latn-NG */
static_cast<uint64_t>(0x884f43616b6d4244), /* ccp-Cakm-BD */
static_cast<uint64_t>(0x63654379726c5255), /* ce-Cyrl-RU */
static_cast<uint64_t>(0x88814c61746e5048), /* ceb-Latn-PH */
static_cast<uint64_t>(0x88c64c61746e5547), /* cgg-Latn-UG */
static_cast<uint64_t>(0x63684c61746e4755), /* ch-Latn-GU */
static_cast<uint64_t>(0x88ea4c61746e464d), /* chk-Latn-FM */
static_cast<uint64_t>(0x88ec4379726c5255), /* chm-Cyrl-RU */
static_cast<uint64_t>(0x88ee4c61746e5553), /* cho-Latn-US */
static_cast<uint64_t>(0x88ef4c61746e4341), /* chp-Latn-CA */
static_cast<uint64_t>(0x88f1436865725553), /* chr-Cher-US */
static_cast<uint64_t>(0x89024c61746e5553), /* cic-Latn-US */
static_cast<uint64_t>(0x8920417261624b48), /* cja-Arab-KH */
static_cast<uint64_t>(0x892c4368616d564e), /* cjm-Cham-VN */
static_cast<uint64_t>(0x8941417261624951), /* ckb-Arab-IQ */
static_cast<uint64_t>(0x8986536f796f4d4e), /* cmg-Soyo-MN */
static_cast<uint64_t>(0x636f4c61746e4652), /* co-Latn-FR */
static_cast<uint64_t>(0x89cf436f70744547), /* cop-Copt-EG */
static_cast<uint64_t>(0x89f24c61746e5048), /* cps-Latn-PH */
static_cast<uint64_t>(0x637243616e734341), /* cr-Cans-CA */
static_cast<uint64_t>(0x8a274379726c5541), /* crh-Cyrl-UA */
static_cast<uint64_t>(0x8a2943616e734341), /* crj-Cans-CA */
static_cast<uint64_t>(0x8a2a43616e734341), /* crk-Cans-CA */
static_cast<uint64_t>(0x8a2b43616e734341), /* crl-Cans-CA */
static_cast<uint64_t>(0x8a2c43616e734341), /* crm-Cans-CA */
static_cast<uint64_t>(0x8a324c61746e5343), /* crs-Latn-SC */
static_cast<uint64_t>(0x63734c61746e435a), /* cs-Latn-CZ */
static_cast<uint64_t>(0x8a414c61746e504c), /* csb-Latn-PL */
static_cast<uint64_t>(0x8a5643616e734341), /* csw-Cans-CA */
static_cast<uint64_t>(0x8a63506175634d4d), /* ctd-Pauc-MM */
static_cast<uint64_t>(0x63754379726c5255), /* cu-Cyrl-RU */
static_cast<uint64_t>(0x6375476c61674247), /* cu-Glag-BG */
static_cast<uint64_t>(0x63764379726c5255), /* cv-Cyrl-RU */
static_cast<uint64_t>(0x63794c61746e4742), /* cy-Latn-GB */
static_cast<uint64_t>(0x64614c61746e444b), /* da-Latn-DK */
static_cast<uint64_t>(0x8c054c61746e4349), /* daf-Latn-CI */
static_cast<uint64_t>(0x8c0a4c61746e5553), /* dak-Latn-US */
static_cast<uint64_t>(0x8c114379726c5255), /* dar-Cyrl-RU */
static_cast<uint64_t>(0x8c154c61746e4b45), /* dav-Latn-KE */
static_cast<uint64_t>(0x8c4241726162494e), /* dcc-Arab-IN */
static_cast<uint64_t>(0x64654c61746e4445), /* de-Latn-DE */
static_cast<uint64_t>(0x8c8d4c61746e4341), /* den-Latn-CA */
static_cast<uint64_t>(0x8cd14c61746e4341), /* dgr-Latn-CA */
static_cast<uint64_t>(0x8d244c61746e4e45), /* dje-Latn-NE */
static_cast<uint64_t>(0x8da94c61746e4349), /* dnj-Latn-CI */
static_cast<uint64_t>(0x8dc844657661494e), /* doi-Deva-IN */
static_cast<uint64_t>(0x8e274d6f6e67434e), /* drh-Mong-CN */
static_cast<uint64_t>(0x8e414c61746e4445), /* dsb-Latn-DE */
static_cast<uint64_t>(0x8e6c4c61746e4d4c), /* dtm-Latn-ML */
static_cast<uint64_t>(0x8e6f4c61746e4d59), /* dtp-Latn-MY */
static_cast<uint64_t>(0x8e78446576614e50), /* dty-Deva-NP */
static_cast<uint64_t>(0x8e804c61746e434d), /* dua-Latn-CM */
static_cast<uint64_t>(0x6476546861614d56), /* dv-Thaa-MV */
static_cast<uint64_t>(0x8f0e4c61746e534e), /* dyo-Latn-SN */
static_cast<uint64_t>(0x8f144c61746e4246), /* dyu-Latn-BF */
static_cast<uint64_t>(0x647a546962744254), /* dz-Tibt-BT */
static_cast<uint64_t>(0x90344c61746e4b45), /* ebu-Latn-KE */
static_cast<uint64_t>(0x65654c61746e4748), /* ee-Latn-GH */
static_cast<uint64_t>(0x90a84c61746e4e47), /* efi-Latn-NG */
static_cast<uint64_t>(0x90cb4c61746e4954), /* egl-Latn-IT */
static_cast<uint64_t>(0x90d8456779704547), /* egy-Egyp-EG */
static_cast<uint64_t>(0x91584b616c694d4d), /* eky-Kali-MM */
static_cast<uint64_t>(0x656c4772656b4752), /* el-Grek-GR */
static_cast<uint64_t>(0x656e4c61746e5553), /* en-Latn-US */
static_cast<uint64_t>(0x656e536861774742), /* en-Shaw-GB */
static_cast<uint64_t>(0x65734c61746e4553), /* es-Latn-ES */
static_cast<uint64_t>(0x9246476f6e6d494e), /* esg-Gonm-IN */
static_cast<uint64_t>(0x92544c61746e5553), /* esu-Latn-US */
static_cast<uint64_t>(0x65744c61746e4545), /* et-Latn-EE */
static_cast<uint64_t>(0x92734974616c4954), /* ett-Ital-IT */
static_cast<uint64_t>(0x65754c61746e4553), /* eu-Latn-ES */
static_cast<uint64_t>(0x92ce4c61746e434d), /* ewo-Latn-CM */
static_cast<uint64_t>(0x92f34c61746e4553), /* ext-Latn-ES */
static_cast<uint64_t>(0x6661417261624952), /* fa-Arab-IR */
static_cast<uint64_t>(0x940d4c61746e4751), /* fan-Latn-GQ */
static_cast<uint64_t>(0x66664c61746e534e), /* ff-Latn-SN */
static_cast<uint64_t>(0x666641646c6d474e), /* ff-Adlm-GN */
static_cast<uint64_t>(0x94ac4c61746e4d4c), /* ffm-Latn-ML */
static_cast<uint64_t>(0x66694c61746e4649), /* fi-Latn-FI */
static_cast<uint64_t>(0x9500417261625344), /* fia-Arab-SD */
static_cast<uint64_t>(0x950b4c61746e5048), /* fil-Latn-PH */
static_cast<uint64_t>(0x95134c61746e5345), /* fit-Latn-SE */
static_cast<uint64_t>(0x666a4c61746e464a), /* fj-Latn-FJ */
static_cast<uint64_t>(0x666f4c61746e464f), /* fo-Latn-FO */
static_cast<uint64_t>(0x95cd4c61746e424a), /* fon-Latn-BJ */
static_cast<uint64_t>(0x66724c61746e4652), /* fr-Latn-FR */
static_cast<uint64_t>(0x96224c61746e5553), /* frc-Latn-US */
static_cast<uint64_t>(0x962f4c61746e4652), /* frp-Latn-FR */
static_cast<uint64_t>(0x96314c61746e4445), /* frr-Latn-DE */
static_cast<uint64_t>(0x96324c61746e4445), /* frs-Latn-DE */
static_cast<uint64_t>(0x968141726162434d), /* fub-Arab-CM */
static_cast<uint64_t>(0x96834c61746e5746), /* fud-Latn-WF */
static_cast<uint64_t>(0x96854c61746e474e), /* fuf-Latn-GN */
static_cast<uint64_t>(0x96904c61746e4e45), /* fuq-Latn-NE */
static_cast<uint64_t>(0x96914c61746e4954), /* fur-Latn-IT */
static_cast<uint64_t>(0x96954c61746e4e47), /* fuv-Latn-NG */
static_cast<uint64_t>(0x96b14c61746e5344), /* fvr-Latn-SD */
static_cast<uint64_t>(0x66794c61746e4e4c), /* fy-Latn-NL */
static_cast<uint64_t>(0x67614c61746e4945), /* ga-Latn-IE */
static_cast<uint64_t>(0x98004c61746e4748), /* gaa-Latn-GH */
static_cast<uint64_t>(0x98064c61746e4d44), /* gag-Latn-MD */
static_cast<uint64_t>(0x980d48616e73434e), /* gan-Hans-CN */
static_cast<uint64_t>(0x98184c61746e4944), /* gay-Latn-ID */
static_cast<uint64_t>(0x982c44657661494e), /* gbm-Deva-IN */
static_cast<uint64_t>(0x9839417261624952), /* gbz-Arab-IR */
static_cast<uint64_t>(0x98514c61746e4746), /* gcr-Latn-GF */
static_cast<uint64_t>(0x67644c61746e4742), /* gd-Latn-GB */
static_cast<uint64_t>(0x9899457468694554), /* gez-Ethi-ET */
static_cast<uint64_t>(0x98cd446576614e50), /* ggn-Deva-NP */
static_cast<uint64_t>(0x990b4c61746e4b49), /* gil-Latn-KI */
static_cast<uint64_t>(0x992a41726162504b), /* gjk-Arab-PK */
static_cast<uint64_t>(0x993441726162504b), /* gju-Arab-PK */
static_cast<uint64_t>(0x676c4c61746e4553), /* gl-Latn-ES */
static_cast<uint64_t>(0x996a417261624952), /* glk-Arab-IR */
static_cast<uint64_t>(0x676e4c61746e5059), /* gn-Latn-PY */
static_cast<uint64_t>(0x99cc44657661494e), /* gom-Deva-IN */
static_cast<uint64_t>(0x99cd54656c75494e), /* gon-Telu-IN */
static_cast<uint64_t>(0x99d14c61746e4944), /* gor-Latn-ID */
static_cast<uint64_t>(0x99d24c61746e4e4c), /* gos-Latn-NL */
static_cast<uint64_t>(0x99d3476f74685541), /* got-Goth-UA */
static_cast<uint64_t>(0x9a22437072744359), /* grc-Cprt-CY */
static_cast<uint64_t>(0x9a224c696e624752), /* grc-Linb-GR */
static_cast<uint64_t>(0x9a3342656e67494e), /* grt-Beng-IN */
static_cast<uint64_t>(0x9a564c61746e4348), /* gsw-Latn-CH */
static_cast<uint64_t>(0x677547756a72494e), /* gu-Gujr-IN */
static_cast<uint64_t>(0x9a814c61746e4252), /* gub-Latn-BR */
static_cast<uint64_t>(0x9a824c61746e434f), /* guc-Latn-CO */
static_cast<uint64_t>(0x9a914c61746e4748), /* gur-Latn-GH */
static_cast<uint64_t>(0x9a994c61746e4b45), /* guz-Latn-KE */
static_cast<uint64_t>(0x67764c61746e494d), /* gv-Latn-IM */
static_cast<uint64_t>(0x9ab1446576614e50), /* gvr-Deva-NP */
static_cast<uint64_t>(0x9ac84c61746e4341), /* gwi-Latn-CA */
static_cast<uint64_t>(0x68614c61746e4e47), /* ha-Latn-NG */
static_cast<uint64_t>(0x9c0a48616e73434e), /* hak-Hans-CN */
static_cast<uint64_t>(0x9c164c61746e5553), /* haw-Latn-US */
static_cast<uint64_t>(0x9c19417261624146), /* haz-Arab-AF */
static_cast<uint64_t>(0x686548656272494c), /* he-Hebr-IL */
static_cast<uint64_t>(0x686944657661494e), /* hi-Deva-IN */
static_cast<uint64_t>(0x9d054c61746e464a), /* hif-Latn-FJ */
static_cast<uint64_t>(0x9d0b4c61746e5048), /* hil-Latn-PH */
static_cast<uint64_t>(0x9d74486c75775452), /* hlu-Hluw-TR */
static_cast<uint64_t>(0x9d83506c7264434e), /* hmd-Plrd-CN */
static_cast<uint64_t>(0x9da341726162504b), /* hnd-Arab-PK */
static_cast<uint64_t>(0x9da444657661494e), /* hne-Deva-IN */
static_cast<uint64_t>(0x9da9486d6e674c41), /* hnj-Hmng-LA */
static_cast<uint64_t>(0x9dad4c61746e5048), /* hnn-Latn-PH */
static_cast<uint64_t>(0x9dae41726162504b), /* hno-Arab-PK */
static_cast<uint64_t>(0x686f4c61746e5047), /* ho-Latn-PG */
static_cast<uint64_t>(0x9dc244657661494e), /* hoc-Deva-IN */
static_cast<uint64_t>(0x9dc944657661494e), /* hoj-Deva-IN */
static_cast<uint64_t>(0x68724c61746e4852), /* hr-Latn-HR */
static_cast<uint64_t>(0x9e414c61746e4445), /* hsb-Latn-DE */
static_cast<uint64_t>(0x9e4d48616e73434e), /* hsn-Hans-CN */
static_cast<uint64_t>(0x68744c61746e4854), /* ht-Latn-HT */
static_cast<uint64_t>(0x68754c61746e4855), /* hu-Latn-HU */
static_cast<uint64_t>(0x687941726d6e414d), /* hy-Armn-AM */
static_cast<uint64_t>(0x687a4c61746e4e41), /* hz-Latn-NA */
static_cast<uint64_t>(0xa0204c61746e4d59), /* iba-Latn-MY */
static_cast<uint64_t>(0xa0214c61746e4e47), /* ibb-Latn-NG */
static_cast<uint64_t>(0x69644c61746e4944), /* id-Latn-ID */
static_cast<uint64_t>(0xa0a44c61746e5447), /* ife-Latn-TG */
static_cast<uint64_t>(0x69674c61746e4e47), /* ig-Latn-NG */
static_cast<uint64_t>(0x696959696969434e), /* ii-Yiii-CN */
static_cast<uint64_t>(0x696b4c61746e5553), /* ik-Latn-US */
static_cast<uint64_t>(0xa1534c61746e4341), /* ikt-Latn-CA */
static_cast<uint64_t>(0xa16e4c61746e5048), /* ilo-Latn-PH */
static_cast<uint64_t>(0x696e4c61746e4944), /* in-Latn-ID */
static_cast<uint64_t>(0xa1a74379726c5255), /* inh-Cyrl-RU */
static_cast<uint64_t>(0x69734c61746e4953), /* is-Latn-IS */
static_cast<uint64_t>(0x69744c61746e4954), /* it-Latn-IT */
static_cast<uint64_t>(0x697543616e734341), /* iu-Cans-CA */
static_cast<uint64_t>(0x697748656272494c), /* iw-Hebr-IL */
static_cast<uint64_t>(0xa3274c61746e5255), /* izh-Latn-RU */
static_cast<uint64_t>(0x6a614a70616e4a50), /* ja-Jpan-JP */
static_cast<uint64_t>(0xa40c4c61746e4a4d), /* jam-Latn-JM */
static_cast<uint64_t>(0xa4ce4c61746e434d), /* jgo-Latn-CM */
static_cast<uint64_t>(0x6a69486562725541), /* ji-Hebr-UA */
static_cast<uint64_t>(0xa5824c61746e545a), /* jmc-Latn-TZ */
static_cast<uint64_t>(0xa58b446576614e50), /* jml-Deva-NP */
static_cast<uint64_t>(0xa6934c61746e444b), /* jut-Latn-DK */
static_cast<uint64_t>(0x6a764c61746e4944), /* jv-Latn-ID */
static_cast<uint64_t>(0x6a774c61746e4944), /* jw-Latn-ID */
static_cast<uint64_t>(0x6b6147656f724745), /* ka-Geor-GE */
static_cast<uint64_t>(0xa8004379726c555a), /* kaa-Cyrl-UZ */
static_cast<uint64_t>(0xa8014c61746e445a), /* kab-Latn-DZ */
static_cast<uint64_t>(0xa8024c61746e4d4d), /* kac-Latn-MM */
static_cast<uint64_t>(0xa8094c61746e4e47), /* kaj-Latn-NG */
static_cast<uint64_t>(0xa80c4c61746e4b45), /* kam-Latn-KE */
static_cast<uint64_t>(0xa80e4c61746e4d4c), /* kao-Latn-ML */
static_cast<uint64_t>(0xa8234379726c5255), /* kbd-Cyrl-RU */
static_cast<uint64_t>(0xa838417261624e45), /* kby-Arab-NE */
static_cast<uint64_t>(0xa8464c61746e4e47), /* kcg-Latn-NG */
static_cast<uint64_t>(0xa84a4c61746e5a57), /* kck-Latn-ZW */
static_cast<uint64_t>(0xa8644c61746e545a), /* kde-Latn-TZ */
static_cast<uint64_t>(0xa867417261625447), /* kdh-Arab-TG */
static_cast<uint64_t>(0xa873546861695448), /* kdt-Thai-TH */
static_cast<uint64_t>(0xa8804c61746e4356), /* kea-Latn-CV */
static_cast<uint64_t>(0xa88d4c61746e434d), /* ken-Latn-CM */
static_cast<uint64_t>(0xa8ae4c61746e4349), /* kfo-Latn-CI */
static_cast<uint64_t>(0xa8b144657661494e), /* kfr-Deva-IN */
static_cast<uint64_t>(0xa8b844657661494e), /* kfy-Deva-IN */
static_cast<uint64_t>(0x6b674c61746e4344), /* kg-Latn-CD */
static_cast<uint64_t>(0xa8c44c61746e4944), /* kge-Latn-ID */
static_cast<uint64_t>(0xa8cf4c61746e4252), /* kgp-Latn-BR */
static_cast<uint64_t>(0xa8e04c61746e494e), /* kha-Latn-IN */
static_cast<uint64_t>(0xa8e154616c75434e), /* khb-Talu-CN */
static_cast<uint64_t>(0xa8ed44657661494e), /* khn-Deva-IN */
static_cast<uint64_t>(0xa8f04c61746e4d4c), /* khq-Latn-ML */
static_cast<uint64_t>(0xa8f34d796d72494e), /* kht-Mymr-IN */
static_cast<uint64_t>(0xa8f641726162504b), /* khw-Arab-PK */
static_cast<uint64_t>(0x6b694c61746e4b45), /* ki-Latn-KE */
static_cast<uint64_t>(0xa9144c61746e5452), /* kiu-Latn-TR */
static_cast<uint64_t>(0x6b6a4c61746e4e41), /* kj-Latn-NA */
static_cast<uint64_t>(0xa9264c616f6f4c41), /* kjg-Laoo-LA */
static_cast<uint64_t>(0x6b6b4379726c4b5a), /* kk-Cyrl-KZ */
static_cast<uint64_t>(0x6b6b41726162434e), /* kk-Arab-CN */
static_cast<uint64_t>(0xa9494c61746e434d), /* kkj-Latn-CM */
static_cast<uint64_t>(0x6b6c4c61746e474c), /* kl-Latn-GL */
static_cast<uint64_t>(0xa96d4c61746e4b45), /* kln-Latn-KE */
static_cast<uint64_t>(0x6b6d4b686d724b48), /* km-Khmr-KH */
static_cast<uint64_t>(0xa9814c61746e414f), /* kmb-Latn-AO */
static_cast<uint64_t>(0x6b6e4b6e6461494e), /* kn-Knda-IN */
static_cast<uint64_t>(0xa9a54c61746e4757), /* knf-Latn-GW */
static_cast<uint64_t>(0x6b6f4b6f72654b52), /* ko-Kore-KR */
static_cast<uint64_t>(0xa9c84379726c5255), /* koi-Cyrl-RU */
static_cast<uint64_t>(0xa9ca44657661494e), /* kok-Deva-IN */
static_cast<uint64_t>(0xa9d24c61746e464d), /* kos-Latn-FM */
static_cast<uint64_t>(0xa9e44c61746e4c52), /* kpe-Latn-LR */
static_cast<uint64_t>(0xaa224379726c5255), /* krc-Cyrl-RU */
static_cast<uint64_t>(0xaa284c61746e534c), /* kri-Latn-SL */
static_cast<uint64_t>(0xaa294c61746e5048), /* krj-Latn-PH */
static_cast<uint64_t>(0xaa2b4c61746e5255), /* krl-Latn-RU */
static_cast<uint64_t>(0xaa3444657661494e), /* kru-Deva-IN */
static_cast<uint64_t>(0x6b7341726162494e), /* ks-Arab-IN */
static_cast<uint64_t>(0xaa414c61746e545a), /* ksb-Latn-TZ */
static_cast<uint64_t>(0xaa454c61746e434d), /* ksf-Latn-CM */
static_cast<uint64_t>(0xaa474c61746e4445), /* ksh-Latn-DE */
static_cast<uint64_t>(0xaa714c61746e4d59), /* ktr-Latn-MY */
static_cast<uint64_t>(0x6b754c61746e5452), /* ku-Latn-TR */
static_cast<uint64_t>(0x6b75417261624951), /* ku-Arab-IQ */
static_cast<uint64_t>(0x6b7559657a694745), /* ku-Yezi-GE */
static_cast<uint64_t>(0xaa8c4379726c5255), /* kum-Cyrl-RU */
static_cast<uint64_t>(0x6b764379726c5255), /* kv-Cyrl-RU */
static_cast<uint64_t>(0xaab14c61746e4944), /* kvr-Latn-ID */
static_cast<uint64_t>(0xaab741726162504b), /* kvx-Arab-PK */
static_cast<uint64_t>(0x6b774c61746e4742), /* kw-Latn-GB */
static_cast<uint64_t>(0xaaeb44657661494e), /* kxl-Deva-IN */
static_cast<uint64_t>(0xaaec546861695448), /* kxm-Thai-TH */
static_cast<uint64_t>(0xaaef41726162504b), /* kxp-Arab-PK */
static_cast<uint64_t>(0x6b794379726c4b47), /* ky-Cyrl-KG */
static_cast<uint64_t>(0x6b7941726162434e), /* ky-Arab-CN */
static_cast<uint64_t>(0x6b794c61746e5452), /* ky-Latn-TR */
static_cast<uint64_t>(0xab294c61746e4d59), /* kzj-Latn-MY */
static_cast<uint64_t>(0xab334c61746e4d59), /* kzt-Latn-MY */
static_cast<uint64_t>(0x6c614c61746e5641), /* la-Latn-VA */
static_cast<uint64_t>(0xac014c696e614752), /* lab-Lina-GR */
static_cast<uint64_t>(0xac0348656272494c), /* lad-Hebr-IL */
static_cast<uint64_t>(0xac064c61746e545a), /* lag-Latn-TZ */
static_cast<uint64_t>(0xac0741726162504b), /* lah-Arab-PK */
static_cast<uint64_t>(0xac094c61746e5547), /* laj-Latn-UG */
static_cast<uint64_t>(0x6c624c61746e4c55), /* lb-Latn-LU */
static_cast<uint64_t>(0xac244379726c5255), /* lbe-Cyrl-RU */
static_cast<uint64_t>(0xac364c61746e4944), /* lbw-Latn-ID */
static_cast<uint64_t>(0xac4f54686169434e), /* lcp-Thai-CN */
static_cast<uint64_t>(0xac8f4c657063494e), /* lep-Lepc-IN */
static_cast<uint64_t>(0xac994379726c5255), /* lez-Cyrl-RU */
static_cast<uint64_t>(0x6c674c61746e5547), /* lg-Latn-UG */
static_cast<uint64_t>(0x6c694c61746e4e4c), /* li-Latn-NL */
static_cast<uint64_t>(0xad05446576614e50), /* lif-Deva-NP */
static_cast<uint64_t>(0xad054c696d62494e), /* lif-Limb-IN */
static_cast<uint64_t>(0xad094c61746e4954), /* lij-Latn-IT */
static_cast<uint64_t>(0xad124c697375434e), /* lis-Lisu-CN */
static_cast<uint64_t>(0xad2f4c61746e4944), /* ljp-Latn-ID */
static_cast<uint64_t>(0xad48417261624952), /* lki-Arab-IR */
static_cast<uint64_t>(0xad534c61746e5553), /* lkt-Latn-US */
static_cast<uint64_t>(0xad8d54656c75494e), /* lmn-Telu-IN */
static_cast<uint64_t>(0xad8e4c61746e4954), /* lmo-Latn-IT */
static_cast<uint64_t>(0x6c6e4c61746e4344), /* ln-Latn-CD */
static_cast<uint64_t>(0x6c6f4c616f6f4c41), /* lo-Laoo-LA */
static_cast<uint64_t>(0xadcb4c61746e4344), /* lol-Latn-CD */
static_cast<uint64_t>(0xadd94c61746e5a4d), /* loz-Latn-ZM */
static_cast<uint64_t>(0xae22417261624952), /* lrc-Arab-IR */
static_cast<uint64_t>(0x6c744c61746e4c54), /* lt-Latn-LT */
static_cast<uint64_t>(0xae664c61746e4c56), /* ltg-Latn-LV */
static_cast<uint64_t>(0x6c754c61746e4344), /* lu-Latn-CD */
static_cast<uint64_t>(0xae804c61746e4344), /* lua-Latn-CD */
static_cast<uint64_t>(0xae8e4c61746e4b45), /* luo-Latn-KE */
static_cast<uint64_t>(0xae984c61746e4b45), /* luy-Latn-KE */
static_cast<uint64_t>(0xae99417261624952), /* luz-Arab-IR */
static_cast<uint64_t>(0x6c764c61746e4c56), /* lv-Latn-LV */
static_cast<uint64_t>(0xaecb546861695448), /* lwl-Thai-TH */
static_cast<uint64_t>(0xaf2748616e73434e), /* lzh-Hans-CN */
static_cast<uint64_t>(0xaf394c61746e5452), /* lzz-Latn-TR */
static_cast<uint64_t>(0xb0034c61746e4944), /* mad-Latn-ID */
static_cast<uint64_t>(0xb0054c61746e434d), /* maf-Latn-CM */
static_cast<uint64_t>(0xb00644657661494e), /* mag-Deva-IN */
static_cast<uint64_t>(0xb00844657661494e), /* mai-Deva-IN */
static_cast<uint64_t>(0xb00a4c61746e4944), /* mak-Latn-ID */
static_cast<uint64_t>(0xb00d4c61746e474d), /* man-Latn-GM */
static_cast<uint64_t>(0xb00d4e6b6f6f474e), /* man-Nkoo-GN */
static_cast<uint64_t>(0xb0124c61746e4b45), /* mas-Latn-KE */
static_cast<uint64_t>(0xb0194c61746e4d58), /* maz-Latn-MX */
static_cast<uint64_t>(0xb0654379726c5255), /* mdf-Cyrl-RU */
static_cast<uint64_t>(0xb0674c61746e5048), /* mdh-Latn-PH */
static_cast<uint64_t>(0xb0714c61746e4944), /* mdr-Latn-ID */
static_cast<uint64_t>(0xb08d4c61746e534c), /* men-Latn-SL */
static_cast<uint64_t>(0xb0914c61746e4b45), /* mer-Latn-KE */
static_cast<uint64_t>(0xb0a0417261625448), /* mfa-Arab-TH */
static_cast<uint64_t>(0xb0a44c61746e4d55), /* mfe-Latn-MU */
static_cast<uint64_t>(0x6d674c61746e4d47), /* mg-Latn-MG */
static_cast<uint64_t>(0xb0c74c61746e4d5a), /* mgh-Latn-MZ */
static_cast<uint64_t>(0xb0ce4c61746e434d), /* mgo-Latn-CM */
static_cast<uint64_t>(0xb0cf446576614e50), /* mgp-Deva-NP */
static_cast<uint64_t>(0xb0d84c61746e545a), /* mgy-Latn-TZ */
static_cast<uint64_t>(0x6d684c61746e4d48), /* mh-Latn-MH */
static_cast<uint64_t>(0x6d694c61746e4e5a), /* mi-Latn-NZ */
static_cast<uint64_t>(0xb10d4c61746e4944), /* min-Latn-ID */
static_cast<uint64_t>(0xb112486174724951), /* mis-Hatr-IQ */
static_cast<uint64_t>(0xb1124d6564664e47), /* mis-Medf-NG */
static_cast<uint64_t>(0x6d6b4379726c4d4b), /* mk-Cyrl-MK */
static_cast<uint64_t>(0x6d6c4d6c796d494e), /* ml-Mlym-IN */
static_cast<uint64_t>(0xb1724c61746e5344), /* mls-Latn-SD */
static_cast<uint64_t>(0x6d6e4379726c4d4e), /* mn-Cyrl-MN */
static_cast<uint64_t>(0x6d6e4d6f6e67434e), /* mn-Mong-CN */
static_cast<uint64_t>(0xb1a842656e67494e), /* mni-Beng-IN */
static_cast<uint64_t>(0xb1b64d796d724d4d), /* mnw-Mymr-MM */
static_cast<uint64_t>(0x6d6f4c61746e524f), /* mo-Latn-RO */
static_cast<uint64_t>(0xb1c44c61746e4341), /* moe-Latn-CA */
static_cast<uint64_t>(0xb1c74c61746e4341), /* moh-Latn-CA */
static_cast<uint64_t>(0xb1d24c61746e4246), /* mos-Latn-BF */
static_cast<uint64_t>(0x6d7244657661494e), /* mr-Deva-IN */
static_cast<uint64_t>(0xb223446576614e50), /* mrd-Deva-NP */
static_cast<uint64_t>(0xb2294379726c5255), /* mrj-Cyrl-RU */
static_cast<uint64_t>(0xb22e4d726f6f4244), /* mro-Mroo-BD */
static_cast<uint64_t>(0x6d734c61746e4d59), /* ms-Latn-MY */
static_cast<uint64_t>(0x6d744c61746e4d54), /* mt-Latn-MT */
static_cast<uint64_t>(0xb27144657661494e), /* mtr-Deva-IN */
static_cast<uint64_t>(0xb2804c61746e434d), /* mua-Latn-CM */
static_cast<uint64_t>(0xb2924c61746e5553), /* mus-Latn-US */
static_cast<uint64_t>(0xb2b841726162504b), /* mvy-Arab-PK */
static_cast<uint64_t>(0xb2ca4c61746e4d4c), /* mwk-Latn-ML */
static_cast<uint64_t>(0xb2d144657661494e), /* mwr-Deva-IN */
static_cast<uint64_t>(0xb2d54c61746e4944), /* mwv-Latn-ID */
static_cast<uint64_t>(0xb2d6486d6e705553), /* mww-Hmnp-US */
static_cast<uint64_t>(0xb2e24c61746e5a57), /* mxc-Latn-ZW */
static_cast<uint64_t>(0x6d794d796d724d4d), /* my-Mymr-MM */
static_cast<uint64_t>(0xb3154379726c5255), /* myv-Cyrl-RU */
static_cast<uint64_t>(0xb3174c61746e5547), /* myx-Latn-UG */
static_cast<uint64_t>(0xb3194d616e644952), /* myz-Mand-IR */
static_cast<uint64_t>(0xb32d417261624952), /* mzn-Arab-IR */
static_cast<uint64_t>(0x6e614c61746e4e52), /* na-Latn-NR */
static_cast<uint64_t>(0xb40d48616e73434e), /* nan-Hans-CN */
static_cast<uint64_t>(0xb40f4c61746e4954), /* nap-Latn-IT */
static_cast<uint64_t>(0xb4104c61746e4e41), /* naq-Latn-NA */
static_cast<uint64_t>(0x6e624c61746e4e4f), /* nb-Latn-NO */
static_cast<uint64_t>(0xb4474c61746e4d58), /* nch-Latn-MX */
static_cast<uint64_t>(0x6e644c61746e5a57), /* nd-Latn-ZW */
static_cast<uint64_t>(0xb4624c61746e4d5a), /* ndc-Latn-MZ */
static_cast<uint64_t>(0xb4724c61746e4445), /* nds-Latn-DE */
static_cast<uint64_t>(0x6e65446576614e50), /* ne-Deva-NP */
static_cast<uint64_t>(0xb496446576614e50), /* new-Deva-NP */
static_cast<uint64_t>(0x6e674c61746e4e41), /* ng-Latn-NA */
static_cast<uint64_t>(0xb4cb4c61746e4d5a), /* ngl-Latn-MZ */
static_cast<uint64_t>(0xb4e44c61746e4d58), /* nhe-Latn-MX */
static_cast<uint64_t>(0xb4f64c61746e4d58), /* nhw-Latn-MX */
static_cast<uint64_t>(0xb5094c61746e4944), /* nij-Latn-ID */
static_cast<uint64_t>(0xb5144c61746e4e55), /* niu-Latn-NU */
static_cast<uint64_t>(0xb52e4c61746e494e), /* njo-Latn-IN */
static_cast<uint64_t>(0x6e6c4c61746e4e4c), /* nl-Latn-NL */
static_cast<uint64_t>(0xb5864c61746e434d), /* nmg-Latn-CM */
static_cast<uint64_t>(0x6e6e4c61746e4e4f), /* nn-Latn-NO */
static_cast<uint64_t>(0xb5a74c61746e434d), /* nnh-Latn-CM */
static_cast<uint64_t>(0xb5af5763686f494e), /* nnp-Wcho-IN */
static_cast<uint64_t>(0x6e6f4c61746e4e4f), /* no-Latn-NO */
static_cast<uint64_t>(0xb5c34c616e615448), /* nod-Lana-TH */
static_cast<uint64_t>(0xb5c444657661494e), /* noe-Deva-IN */
static_cast<uint64_t>(0xb5cd52756e725345), /* non-Runr-SE */
static_cast<uint64_t>(0xb60e4e6b6f6f474e), /* nqo-Nkoo-GN */
static_cast<uint64_t>(0x6e724c61746e5a41), /* nr-Latn-ZA */
static_cast<uint64_t>(0xb64a43616e734341), /* nsk-Cans-CA */
static_cast<uint64_t>(0xb64e4c61746e5a41), /* nso-Latn-ZA */
static_cast<uint64_t>(0xb6924c61746e5353), /* nus-Latn-SS */
static_cast<uint64_t>(0x6e764c61746e5553), /* nv-Latn-US */
static_cast<uint64_t>(0xb6f04c61746e434e), /* nxq-Latn-CN */
static_cast<uint64_t>(0x6e794c61746e4d57), /* ny-Latn-MW */
static_cast<uint64_t>(0xb70c4c61746e545a), /* nym-Latn-TZ */
static_cast<uint64_t>(0xb70d4c61746e5547), /* nyn-Latn-UG */
static_cast<uint64_t>(0xb7284c61746e4748), /* nzi-Latn-GH */
static_cast<uint64_t>(0x6f634c61746e4652), /* oc-Latn-FR */
static_cast<uint64_t>(0x6f6d4c61746e4554), /* om-Latn-ET */
static_cast<uint64_t>(0x6f724f727961494e), /* or-Orya-IN */
static_cast<uint64_t>(0x6f734379726c4745), /* os-Cyrl-GE */
static_cast<uint64_t>(0xba404f7367655553), /* osa-Osge-US */
static_cast<uint64_t>(0xba6a4f726b684d4e), /* otk-Orkh-MN */
static_cast<uint64_t>(0x706147757275494e), /* pa-Guru-IN */
static_cast<uint64_t>(0x706141726162504b), /* pa-Arab-PK */
static_cast<uint64_t>(0xbc064c61746e5048), /* pag-Latn-PH */
static_cast<uint64_t>(0xbc0b50686c694952), /* pal-Phli-IR */
static_cast<uint64_t>(0xbc0b50686c70434e), /* pal-Phlp-CN */
static_cast<uint64_t>(0xbc0c4c61746e5048), /* pam-Latn-PH */
static_cast<uint64_t>(0xbc0f4c61746e4157), /* pap-Latn-AW */
static_cast<uint64_t>(0xbc144c61746e5057), /* pau-Latn-PW */
static_cast<uint64_t>(0xbc434c61746e4652), /* pcd-Latn-FR */
static_cast<uint64_t>(0xbc4c4c61746e4e47), /* pcm-Latn-NG */
static_cast<uint64_t>(0xbc624c61746e5553), /* pdc-Latn-US */
static_cast<uint64_t>(0xbc734c61746e4341), /* pdt-Latn-CA */
static_cast<uint64_t>(0xbc8e5870656f4952), /* peo-Xpeo-IR */
static_cast<uint64_t>(0xbcab4c61746e4445), /* pfl-Latn-DE */
static_cast<uint64_t>(0xbced50686e784c42), /* phn-Phnx-LB */
static_cast<uint64_t>(0xbd4042726168494e), /* pka-Brah-IN */
static_cast<uint64_t>(0xbd4e4c61746e4b45), /* pko-Latn-KE */
static_cast<uint64_t>(0x706c4c61746e504c), /* pl-Latn-PL */
static_cast<uint64_t>(0xbd924c61746e4954), /* pms-Latn-IT */
static_cast<uint64_t>(0xbdb34772656b4752), /* pnt-Grek-GR */
static_cast<uint64_t>(0xbdcd4c61746e464d), /* pon-Latn-FM */
static_cast<uint64_t>(0xbde044657661494e), /* ppa-Deva-IN */
static_cast<uint64_t>(0xbe204b686172504b), /* pra-Khar-PK */
static_cast<uint64_t>(0xbe23417261624952), /* prd-Arab-IR */
static_cast<uint64_t>(0x7073417261624146), /* ps-Arab-AF */
static_cast<uint64_t>(0x70744c61746e4252), /* pt-Latn-BR */
static_cast<uint64_t>(0xbe944c61746e4741), /* puu-Latn-GA */
static_cast<uint64_t>(0x71754c61746e5045), /* qu-Latn-PE */
static_cast<uint64_t>(0xc2824c61746e4754), /* quc-Latn-GT */
static_cast<uint64_t>(0xc2864c61746e4543), /* qug-Latn-EC */
static_cast<uint64_t>(0xc40944657661494e), /* raj-Deva-IN */
static_cast<uint64_t>(0xc4454c61746e5245), /* rcf-Latn-RE */
static_cast<uint64_t>(0xc4894c61746e4944), /* rej-Latn-ID */
static_cast<uint64_t>(0xc4cd4c61746e4954), /* rgn-Latn-IT */
static_cast<uint64_t>(0xc4e6417261624d4d), /* rhg-Arab-MM */
static_cast<uint64_t>(0xc5004c61746e494e), /* ria-Latn-IN */
static_cast<uint64_t>(0xc50554666e674d41), /* rif-Tfng-MA */
static_cast<uint64_t>(0xc532446576614e50), /* rjs-Deva-NP */
static_cast<uint64_t>(0xc55342656e674244), /* rkt-Beng-BD */
static_cast<uint64_t>(0x726d4c61746e4348), /* rm-Latn-CH */
static_cast<uint64_t>(0xc5854c61746e4649), /* rmf-Latn-FI */
static_cast<uint64_t>(0xc58e4c61746e4348), /* rmo-Latn-CH */
static_cast<uint64_t>(0xc593417261624952), /* rmt-Arab-IR */
static_cast<uint64_t>(0xc5944c61746e5345), /* rmu-Latn-SE */
static_cast<uint64_t>(0x726e4c61746e4249), /* rn-Latn-BI */
static_cast<uint64_t>(0xc5a64c61746e4d5a), /* rng-Latn-MZ */
static_cast<uint64_t>(0x726f4c61746e524f), /* ro-Latn-RO */
static_cast<uint64_t>(0xc5c14c61746e4944), /* rob-Latn-ID */
static_cast<uint64_t>(0xc5c54c61746e545a), /* rof-Latn-TZ */
static_cast<uint64_t>(0xc66c4c61746e464a), /* rtm-Latn-FJ */
static_cast<uint64_t>(0x72754379726c5255), /* ru-Cyrl-RU */
static_cast<uint64_t>(0xc6844379726c5541), /* rue-Cyrl-UA */
static_cast<uint64_t>(0xc6864c61746e5342), /* rug-Latn-SB */
static_cast<uint64_t>(0x72774c61746e5257), /* rw-Latn-RW */
static_cast<uint64_t>(0xc6ca4c61746e545a), /* rwk-Latn-TZ */
static_cast<uint64_t>(0xc7144b616e614a50), /* ryu-Kana-JP */
static_cast<uint64_t>(0x736144657661494e), /* sa-Deva-IN */
static_cast<uint64_t>(0xc8054c61746e4748), /* saf-Latn-GH */
static_cast<uint64_t>(0xc8074379726c5255), /* sah-Cyrl-RU */
static_cast<uint64_t>(0xc8104c61746e4b45), /* saq-Latn-KE */
static_cast<uint64_t>(0xc8124c61746e4944), /* sas-Latn-ID */
static_cast<uint64_t>(0xc8134f6c636b494e), /* sat-Olck-IN */
static_cast<uint64_t>(0xc8154c61746e534e), /* sav-Latn-SN */
static_cast<uint64_t>(0xc81953617572494e), /* saz-Saur-IN */
static_cast<uint64_t>(0xc82f4c61746e545a), /* sbp-Latn-TZ */
static_cast<uint64_t>(0x73634c61746e4954), /* sc-Latn-IT */
static_cast<uint64_t>(0xc84a44657661494e), /* sck-Deva-IN */
static_cast<uint64_t>(0xc84d4c61746e4954), /* scn-Latn-IT */
static_cast<uint64_t>(0xc84e4c61746e4742), /* sco-Latn-GB */
static_cast<uint64_t>(0xc8524c61746e4341), /* scs-Latn-CA */
static_cast<uint64_t>(0x736441726162504b), /* sd-Arab-PK */
static_cast<uint64_t>(0x736444657661494e), /* sd-Deva-IN */
static_cast<uint64_t>(0x73644b686f6a494e), /* sd-Khoj-IN */
static_cast<uint64_t>(0x736453696e64494e), /* sd-Sind-IN */
static_cast<uint64_t>(0xc8624c61746e4954), /* sdc-Latn-IT */
static_cast<uint64_t>(0xc867417261624952), /* sdh-Arab-IR */
static_cast<uint64_t>(0x73654c61746e4e4f), /* se-Latn-NO */
static_cast<uint64_t>(0xc8854c61746e4349), /* sef-Latn-CI */
static_cast<uint64_t>(0xc8874c61746e4d5a), /* seh-Latn-MZ */
static_cast<uint64_t>(0xc8884c61746e4d58), /* sei-Latn-MX */
static_cast<uint64_t>(0xc8924c61746e4d4c), /* ses-Latn-ML */
static_cast<uint64_t>(0x73674c61746e4346), /* sg-Latn-CF */
static_cast<uint64_t>(0xc8c04f67616d4945), /* sga-Ogam-IE */
static_cast<uint64_t>(0xc8d24c61746e4c54), /* sgs-Latn-LT */
static_cast<uint64_t>(0xc8e854666e674d41), /* shi-Tfng-MA */
static_cast<uint64_t>(0xc8ed4d796d724d4d), /* shn-Mymr-MM */
static_cast<uint64_t>(0x736953696e684c4b), /* si-Sinh-LK */
static_cast<uint64_t>(0xc9034c61746e4554), /* sid-Latn-ET */
static_cast<uint64_t>(0x736b4c61746e534b), /* sk-Latn-SK */
static_cast<uint64_t>(0xc95141726162504b), /* skr-Arab-PK */
static_cast<uint64_t>(0x736c4c61746e5349), /* sl-Latn-SI */
static_cast<uint64_t>(0xc9684c61746e504c), /* sli-Latn-PL */
static_cast<uint64_t>(0xc9784c61746e4944), /* sly-Latn-ID */
static_cast<uint64_t>(0x736d4c61746e5753), /* sm-Latn-WS */
static_cast<uint64_t>(0xc9804c61746e5345), /* sma-Latn-SE */
static_cast<uint64_t>(0xc9894c61746e5345), /* smj-Latn-SE */
static_cast<uint64_t>(0xc98d4c61746e4649), /* smn-Latn-FI */
static_cast<uint64_t>(0xc98f53616d72494c), /* smp-Samr-IL */
static_cast<uint64_t>(0xc9924c61746e4649), /* sms-Latn-FI */
static_cast<uint64_t>(0x736e4c61746e5a57), /* sn-Latn-ZW */
static_cast<uint64_t>(0xc9aa4c61746e4d4c), /* snk-Latn-ML */
static_cast<uint64_t>(0x736f4c61746e534f), /* so-Latn-SO */
static_cast<uint64_t>(0xc9c6536f6764555a), /* sog-Sogd-UZ */
static_cast<uint64_t>(0xc9d4546861695448), /* sou-Thai-TH */
static_cast<uint64_t>(0x73714c61746e414c), /* sq-Latn-AL */
static_cast<uint64_t>(0x73724379726c5253), /* sr-Cyrl-RS */
static_cast<uint64_t>(0xca21536f7261494e), /* srb-Sora-IN */
static_cast<uint64_t>(0xca2d4c61746e5352), /* srn-Latn-SR */
static_cast<uint64_t>(0xca314c61746e534e), /* srr-Latn-SN */
static_cast<uint64_t>(0xca3744657661494e), /* srx-Deva-IN */
static_cast<uint64_t>(0x73734c61746e5a41), /* ss-Latn-ZA */
static_cast<uint64_t>(0xca584c61746e4552), /* ssy-Latn-ER */
static_cast<uint64_t>(0x73744c61746e5a41), /* st-Latn-ZA */
static_cast<uint64_t>(0xca704c61746e4445), /* stq-Latn-DE */
static_cast<uint64_t>(0x73754c61746e4944), /* su-Latn-ID */
static_cast<uint64_t>(0xca8a4c61746e545a), /* suk-Latn-TZ */
static_cast<uint64_t>(0xca924c61746e474e), /* sus-Latn-GN */
static_cast<uint64_t>(0x73764c61746e5345), /* sv-Latn-SE */
static_cast<uint64_t>(0x73774c61746e545a), /* sw-Latn-TZ */
static_cast<uint64_t>(0xcac1417261625954), /* swb-Arab-YT */
static_cast<uint64_t>(0xcac24c61746e4344), /* swc-Latn-CD */
static_cast<uint64_t>(0xcac64c61746e4445), /* swg-Latn-DE */
static_cast<uint64_t>(0xcad544657661494e), /* swv-Deva-IN */
static_cast<uint64_t>(0xcaed4c61746e4944), /* sxn-Latn-ID */
static_cast<uint64_t>(0xcb0b42656e674244), /* syl-Beng-BD */
static_cast<uint64_t>(0xcb11537972634951), /* syr-Syrc-IQ */
static_cast<uint64_t>(0xcb2b4c61746e504c), /* szl-Latn-PL */
static_cast<uint64_t>(0x746154616d6c494e), /* ta-Taml-IN */
static_cast<uint64_t>(0xcc09446576614e50), /* taj-Deva-NP */
static_cast<uint64_t>(0xcc364c61746e5048), /* tbw-Latn-PH */
static_cast<uint64_t>(0xcc584b6e6461494e), /* tcy-Knda-IN */
static_cast<uint64_t>(0xcc6354616c65434e), /* tdd-Tale-CN */
static_cast<uint64_t>(0xcc66446576614e50), /* tdg-Deva-NP */
static_cast<uint64_t>(0xcc67446576614e50), /* tdh-Deva-NP */
static_cast<uint64_t>(0xcc744c61746e4d59), /* tdu-Latn-MY */
static_cast<uint64_t>(0x746554656c75494e), /* te-Telu-IN */
static_cast<uint64_t>(0xcc8c4c61746e534c), /* tem-Latn-SL */
static_cast<uint64_t>(0xcc8e4c61746e5547), /* teo-Latn-UG */
static_cast<uint64_t>(0xcc934c61746e544c), /* tet-Latn-TL */
static_cast<uint64_t>(0x74674379726c544a), /* tg-Cyrl-TJ */
static_cast<uint64_t>(0x746741726162504b), /* tg-Arab-PK */
static_cast<uint64_t>(0x7468546861695448), /* th-Thai-TH */
static_cast<uint64_t>(0xcceb446576614e50), /* thl-Deva-NP */
static_cast<uint64_t>(0xccf0446576614e50), /* thq-Deva-NP */
static_cast<uint64_t>(0xccf1446576614e50), /* thr-Deva-NP */
static_cast<uint64_t>(0x7469457468694554), /* ti-Ethi-ET */
static_cast<uint64_t>(0xcd06457468694552), /* tig-Ethi-ER */
static_cast<uint64_t>(0xcd154c61746e4e47), /* tiv-Latn-NG */
static_cast<uint64_t>(0x746b4c61746e544d), /* tk-Latn-TM */
static_cast<uint64_t>(0xcd4b4c61746e544b), /* tkl-Latn-TK */
static_cast<uint64_t>(0xcd514c61746e415a), /* tkr-Latn-AZ */
static_cast<uint64_t>(0xcd53446576614e50), /* tkt-Deva-NP */
static_cast<uint64_t>(0x746c4c61746e5048), /* tl-Latn-PH */
static_cast<uint64_t>(0xcd784c61746e415a), /* tly-Latn-AZ */
static_cast<uint64_t>(0xcd874c61746e4e45), /* tmh-Latn-NE */
static_cast<uint64_t>(0x746e4c61746e5a41), /* tn-Latn-ZA */
static_cast<uint64_t>(0x746f4c61746e544f), /* to-Latn-TO */
static_cast<uint64_t>(0xcdc64c61746e4d57), /* tog-Latn-MW */
static_cast<uint64_t>(0xcde84c61746e5047), /* tpi-Latn-PG */
static_cast<uint64_t>(0x74724c61746e5452), /* tr-Latn-TR */
static_cast<uint64_t>(0xce344c61746e5452), /* tru-Latn-TR */
static_cast<uint64_t>(0xce354c61746e5457), /* trv-Latn-TW */
static_cast<uint64_t>(0xce3641726162504b), /* trw-Arab-PK */
static_cast<uint64_t>(0x74734c61746e5a41), /* ts-Latn-ZA */
static_cast<uint64_t>(0xce434772656b4752), /* tsd-Grek-GR */
static_cast<uint64_t>(0xce45446576614e50), /* tsf-Deva-NP */
static_cast<uint64_t>(0xce464c61746e5048), /* tsg-Latn-PH */
static_cast<uint64_t>(0xce49546962744254), /* tsj-Tibt-BT */
static_cast<uint64_t>(0x74744379726c5255), /* tt-Cyrl-RU */
static_cast<uint64_t>(0xce694c61746e5547), /* ttj-Latn-UG */
static_cast<uint64_t>(0xce72546861695448), /* tts-Thai-TH */
static_cast<uint64_t>(0xce734c61746e415a), /* ttt-Latn-AZ */
static_cast<uint64_t>(0xce8c4c61746e4d57), /* tum-Latn-MW */
static_cast<uint64_t>(0xceab4c61746e5456), /* tvl-Latn-TV */
static_cast<uint64_t>(0xced04c61746e4e45), /* twq-Latn-NE */
static_cast<uint64_t>(0xcee654616e67434e), /* txg-Tang-CN */
static_cast<uint64_t>(0x74794c61746e5046), /* ty-Latn-PF */
static_cast<uint64_t>(0xcf154379726c5255), /* tyv-Cyrl-RU */
static_cast<uint64_t>(0xcf2c4c61746e4d41), /* tzm-Latn-MA */
static_cast<uint64_t>(0xd06c4379726c5255), /* udm-Cyrl-RU */
static_cast<uint64_t>(0x756741726162434e), /* ug-Arab-CN */
static_cast<uint64_t>(0x75674379726c4b5a), /* ug-Cyrl-KZ */
static_cast<uint64_t>(0xd0c0556761725359), /* uga-Ugar-SY */
static_cast<uint64_t>(0x756b4379726c5541), /* uk-Cyrl-UA */
static_cast<uint64_t>(0xd1684c61746e464d), /* uli-Latn-FM */
static_cast<uint64_t>(0xd1814c61746e414f), /* umb-Latn-AO */
static_cast<uint64_t>(0xd1b142656e67494e), /* unr-Beng-IN */
static_cast<uint64_t>(0xd1b1446576614e50), /* unr-Deva-NP */
static_cast<uint64_t>(0xd1b742656e67494e), /* unx-Beng-IN */
static_cast<uint64_t>(0x757241726162504b), /* ur-Arab-PK */
static_cast<uint64_t>(0x757a4c61746e555a), /* uz-Latn-UZ */
static_cast<uint64_t>(0x757a417261624146), /* uz-Arab-AF */
static_cast<uint64_t>(0xd408566169694c52), /* vai-Vaii-LR */
static_cast<uint64_t>(0x76654c61746e5a41), /* ve-Latn-ZA */
static_cast<uint64_t>(0xd4824c61746e4954), /* vec-Latn-IT */
static_cast<uint64_t>(0xd48f4c61746e5255), /* vep-Latn-RU */
static_cast<uint64_t>(0x76694c61746e564e), /* vi-Latn-VN */
static_cast<uint64_t>(0xd5024c61746e5358), /* vic-Latn-SX */
static_cast<uint64_t>(0xd5724c61746e4245), /* vls-Latn-BE */
static_cast<uint64_t>(0xd5854c61746e4445), /* vmf-Latn-DE */
static_cast<uint64_t>(0xd5964c61746e4d5a), /* vmw-Latn-MZ */
static_cast<uint64_t>(0xd5d34c61746e5255), /* vot-Latn-RU */
static_cast<uint64_t>(0xd62e4c61746e4545), /* vro-Latn-EE */
static_cast<uint64_t>(0xd68d4c61746e545a), /* vun-Latn-TZ */
static_cast<uint64_t>(0x77614c61746e4245), /* wa-Latn-BE */
static_cast<uint64_t>(0xd8044c61746e4348), /* wae-Latn-CH */
static_cast<uint64_t>(0xd80b457468694554), /* wal-Ethi-ET */
static_cast<uint64_t>(0xd8114c61746e5048), /* war-Latn-PH */
static_cast<uint64_t>(0xd82f4c61746e4155), /* wbp-Latn-AU */
static_cast<uint64_t>(0xd83054656c75494e), /* wbq-Telu-IN */
static_cast<uint64_t>(0xd83144657661494e), /* wbr-Deva-IN */
static_cast<uint64_t>(0xd9724c61746e5746), /* wls-Latn-WF */
static_cast<uint64_t>(0xd9a8417261624b4d), /* wni-Arab-KM */
static_cast<uint64_t>(0x776f4c61746e534e), /* wo-Latn-SN */
static_cast<uint64_t>(0xda46476f6e67494e), /* wsg-Gong-IN */
static_cast<uint64_t>(0xda6c44657661494e), /* wtm-Deva-IN */
static_cast<uint64_t>(0xda9448616e73434e), /* wuu-Hans-CN */
static_cast<uint64_t>(0xdc154c61746e4252), /* xav-Latn-BR */
static_cast<uint64_t>(0xdc4e43687273555a), /* xco-Chrs-UZ */
static_cast<uint64_t>(0xdc51436172695452), /* xcr-Cari-TR */
static_cast<uint64_t>(0x78684c61746e5a41), /* xh-Latn-ZA */
static_cast<uint64_t>(0xdd624c7963695452), /* xlc-Lyci-TR */
static_cast<uint64_t>(0xdd634c7964695452), /* xld-Lydi-TR */
static_cast<uint64_t>(0xdd8547656f724745), /* xmf-Geor-GE */
static_cast<uint64_t>(0xdd8d4d616e69434e), /* xmn-Mani-CN */
static_cast<uint64_t>(0xdd914d6572635344), /* xmr-Merc-SD */
static_cast<uint64_t>(0xdda04e6172625341), /* xna-Narb-SA */
static_cast<uint64_t>(0xddb144657661494e), /* xnr-Deva-IN */
static_cast<uint64_t>(0xddc64c61746e5547), /* xog-Latn-UG */
static_cast<uint64_t>(0xddf1507274694952), /* xpr-Prti-IR */
static_cast<uint64_t>(0xde40536172625945), /* xsa-Sarb-YE */
static_cast<uint64_t>(0xde51446576614e50), /* xsr-Deva-NP */
static_cast<uint64_t>(0xe00e4c61746e4d5a), /* yao-Latn-MZ */
static_cast<uint64_t>(0xe00f4c61746e464d), /* yap-Latn-FM */
static_cast<uint64_t>(0xe0154c61746e434d), /* yav-Latn-CM */
static_cast<uint64_t>(0xe0214c61746e434d), /* ybb-Latn-CM */
static_cast<uint64_t>(0x796f4c61746e4e47), /* yo-Latn-NG */
static_cast<uint64_t>(0xe22b4c61746e4252), /* yrl-Latn-BR */
static_cast<uint64_t>(0xe2804c61746e4d58), /* yua-Latn-MX */
static_cast<uint64_t>(0xe28448616e74484b), /* yue-Hant-HK */
static_cast<uint64_t>(0xe28448616e73434e), /* yue-Hans-CN */
static_cast<uint64_t>(0x7a614c61746e434e), /* za-Latn-CN */
static_cast<uint64_t>(0xe4064c61746e5344), /* zag-Latn-SD */
static_cast<uint64_t>(0xe469417261624b4d), /* zdj-Arab-KM */
static_cast<uint64_t>(0xe4804c61746e4e4c), /* zea-Latn-NL */
static_cast<uint64_t>(0xe4c754666e674d41), /* zgh-Tfng-MA */
static_cast<uint64_t>(0x7a6848616e73434e), /* zh-Hans-CN */
static_cast<uint64_t>(0x7a68426f706f5457), /* zh-Bopo-TW */
static_cast<uint64_t>(0x7a6848616e625457), /* zh-Hanb-TW */
static_cast<uint64_t>(0x7a6848616e745457), /* zh-Hant-TW */
static_cast<uint64_t>(0xe4f74e736875434e), /* zhx-Nshu-CN */
static_cast<uint64_t>(0xe5534b697473434e), /* zkt-Kits-CN */
static_cast<uint64_t>(0xe56c4c61746e5447), /* zlm-Latn-TG */
static_cast<uint64_t>(0xe5884c61746e4d59), /* zmi-Latn-MY */
static_cast<uint64_t>(0x7a754c61746e5a41), /* zu-Latn-ZA */
static_cast<uint64_t>(0xe7204c61746e5452), /* zza-Latn-TR */
static_cast<uint64_t>(0x656e4c61746e4742), /* en-Latn-GB */
static_cast<uint64_t>(0x65734c61746e4d58), /* es-Latn-MX */
static_cast<uint64_t>(0x65734c61746e5553), /* es-Latn-US */
};
} // namespace Resource
} // namespace Global
} // namespace OHOS
#endif | [
"mamingshuai1@huawei.com"
] | mamingshuai1@huawei.com |
66e37daa7f35654645ff45670771b6c53f203a6c | 339261bea4044688f85d49eb7c7fc344ff8ac773 | /src/tnf_main.cc | e0df2d6d80ac2673b0ce31c092c30195ae1a54c0 | [] | no_license | jiangyong27/tnf | 64392e9c65cfd0e796c9adb027887daf93b87219 | 7e045b651f3256226e8813b145835855aeefd036 | refs/heads/master | 2021-01-18T18:30:38.877214 | 2016-08-01T15:38:49 | 2016-08-01T15:38:49 | 64,679,518 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,013 | cc | #include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include "so_loader.h"
#include "net/net_conf.h"
const char *version = "1.0.0";
const char *get_version()
{
return version;
}
int tnf_main(int argc, char **argv)
{
if (argc < 2) {
printf("usage: %s conf.ini\n", argv[0]);
return -1;
}
std::string conf_file = argv[1];
std::string so_file;
CNetConf net_conf;
if (!net_conf.OpenIniFile(conf_file)) {
printf("open conf[%s] failed!\n", conf_file.c_str());
return -2;
}
net_conf.GetFiledValue("main", "app_so", "", &so_file);
CSoLoader so_loader;
if (!so_loader.Open(so_file)) {
printf("open so_file[%s] failed!\n", so_file.c_str());
return -3;
}
typedef int (*app_run_func)(int argc, char **argv);
app_run_func app_run = (app_run_func) so_loader.GetFunc("app_run");
if (app_run == NULL) {
printf("get func app_run failed!\n");
return -2;
}
return app_run(argc, argv);
}
| [
"jiangyong@jiangyongdeMacBook-Pro.local"
] | jiangyong@jiangyongdeMacBook-Pro.local |
680b783a22fe6bc72cd29da3b529095031f525c2 | 57de2dcd6a3ae07a9a34e72f4c55b8cba9dcec93 | /Lab5/1-Stacks/main.cpp | 34cbbd2da41d4642273fc559fe617ed478a05564 | [] | no_license | devyetii/Data-Structures-LabSolutions | dc41002a84cfb07ce39efa6fb04d3b278b210c88 | b7db2e287d0f53cf31701e2578af5cf4f62ec679 | refs/heads/master | 2021-10-24T18:37:45.534848 | 2019-03-27T16:43:31 | 2019-03-27T16:43:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,354 | cpp |
#include "ArrayStack.h"
#include <iostream> //To use C++ console I/O functionality
//, we need to include iostream which contains necessary declarations.
using namespace std; //This statement enables us to use classes and objects in the standard C++ library
//without prefixing them with "std::"
// This caod has 1 checkpoint [CheckPoint 1]
//Follow the provided instructions at each check point
//This is the program starting point.
int main()
{
//Declare a Stack of integers named "S" and with max size = 10 elements
ArrayStack<int,10> S;
int i,x,n;
cout<<"\nEnter no. of values to push into stack:";
cin>>n;
//Test the 1st stack by pushing n values then poping
cout << "Testing stack S......" << endl;
cout << "Pushing "<<n<<" values into S:" << endl;
cout<<"Please Enter the "<<n<<" values to push in S :";
for(i = 0; i < n; i++)
{
cin>>x;
S.push(x); //pushing x to S
}
cout << endl<<"Popping: ";
while(S.pop(x)) //as long as pop returns true, so x contains a valid value
cout << x << " ";
/// ==> [CheckPoint 1]
//After 1st run, comment the above while loop and uncomment the while loop below
//while(S.peek(x)) //as long as peek returns true, so x contains a valid value
//cout << x << " ";
cout<<endl;
cout<<"is S Empty?? ==>"<<boolalpha<<S.isEmpty();
cout<<endl;
return 0;
}
| [
"ebrahim.gomaa.hg@gmail.com"
] | ebrahim.gomaa.hg@gmail.com |
43d0071275b7831514a0569452a033c10d90cdec | 8bc8e4e20ed523dd8dfc50bc9daff54448d5ed05 | /Array Problems/Transition Point.cpp | bbebca94ac2171ded0e1e8b8cafcbe22e23b6e0a | [] | no_license | shruti01052002/Data-Structures-Problems | 64f46c8955fc82d58548d74d0c18507279f826f4 | 2f5a8513d48b38a01000626f2bed229459de1db3 | refs/heads/master | 2023-02-28T14:22:41.637964 | 2021-01-22T14:14:15 | 2021-01-22T14:14:15 | 296,275,937 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 553 | cpp | #include <bits/stdc++.h>
using namespace std;
int transitionPoint(int arr[], int n);
int main() {
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
int a[n], i;
for (i = 0; i < n; i++) {
cin >> a[i];
}
cout << transitionPoint(a, n) << endl;
}
return 0;
}
int transitionPoint(int arr[], int n) {
int s=-1;
for(int i=0;i<n;i++)
{
if(arr[i]==0)
continue;
else
{
s = i;
break;
}
}
return s;
} | [
"shrutiyadav26072002@gmail.com"
] | shrutiyadav26072002@gmail.com |
88028c50b8972f7f4a2c3b36710cf00626c0e649 | 90d1ab796d404462e3eb84929acf4cb00d6d6af6 | /View/Capture/CaptureThread.cpp | 730e582844279d8335ff2617168f2a5fb1008daf | [] | no_license | BobDeng1974/panorama_streamer | f7b23a85fdcde228cbd15b714cdb36c364de2944 | 7bfbdc08004626d92bbb0b0e97974fd305eccb12 | refs/heads/master | 2022-04-23T16:23:42.634535 | 2020-04-26T17:59:47 | 2020-04-26T17:59:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 17,412 | cpp |
#include <iomanip>
#include <sstream>
#include <QFile>
#include <QDir>
#include "SharedImageBuffer.h"
#include "CaptureThread.h"
#include "CaptureProp.h"
#include "D360Stitcher.h"
#include "D360Parser.h"
#include "QmlMainWindow.h"
#include "define.h"
#include <QDateTime>
extern QmlMainWindow* g_mainWindow;
CaptureThread::CaptureThread(SharedImageBuffer *sharedImageBuffer,
int deviceNumber,
CaptureType captureType,
int width, int height) : sharedImageBuffer(sharedImageBuffer),
m_Name("CaptureThread"),
m_grabbedFrame(ImageBufferData::NONE)
{
//
// Save passed parameters
//
this->m_deviceNumber = deviceNumber;
this->width = width;
this->height = height;
this->m_captureType = captureType;
//
// Initialize variables(s)
//
doStop = false;
doPause = false;
doSnapshot = false;
doCalibrate = false;
sampleNumber = 0;
fpsSum = 0;
fps.clear();
cap = NULL;
statsData.averageFPS = 0;
statsData.nFramesProcessed = 0;
statsData.nAudioFrames = 0;
m_streamer = sharedImageBuffer->getStreamer();
m_isCanGrab = false;
}
CaptureThread::~CaptureThread()
{
disconnect();
}
void CaptureThread::run()
{
m_grabbedFrame.clear();
cap->start();
cap->reset(m_grabbedFrame);
GlobalAnimSettings* gasettings = sharedImageBuffer->getGlobalAnimSettings();
CameraInput& camSettings = gasettings->cameraSettingsList()[m_deviceNumber];
int intervalms = 1000 / gasettings->m_fps;
QDir dir(camSettings.fileDir);
bool dirExists = false;
if (camSettings.fileDir != "" && dir.exists()) {
dirExists = true;
}
PANO_DEVICE_DLOG("Cam Dir : " + camSettings.fileDir + " " + (dirExists?"true":"false"));
// wonder if this has effect: we don't need sync now for this mode,
// and this won't make things work with subset cameras working
//sharedImageBuffer->sync( m_deviceNumber );
// Start timer (used to calculate capture rate)
t.start();
// 50fps test
float fps = gasettings->m_fps; // full speed
if (gasettings->m_captureType == D360::Capture::CAPTURE_DSHOW)
fps = fps * 2;
QDateTime *curTime = new QDateTime;
qint64 nFirstMS = 0, nSecondMS = 0, nDiffMS = 0;
bool singleFrameMode = false;
if (gasettings->m_startFrame == -1 && gasettings->m_endFrame == -1)
singleFrameMode = true;
bool bIsFirstFrame = true;
while (1)
{
nFirstMS = curTime->currentMSecsSinceEpoch();
if (QThread::currentThread()->isInterruptionRequested())
{
std::cout << "Got signal to terminate" << std::endl;
doStop = true;
}
//
// Stop thread if doStop = TRUE
//
doStopMutex.lock();
if (doStop)
{
std::cout << "Stop" << std::endl;
doStop = false;
doStopMutex.unlock();
break;
}
if (!singleFrameMode &&
(gasettings->m_endFrame != -1 && statsData.nFramesProcessed > gasettings->m_endFrame)
)
{
PANO_DEVICE_LOG("Reading Frame Sequence is done!");
m_isCanGrab = false;
doStopMutex.unlock();
break;
}
doStopMutex.unlock();
//
// Pause thread if doPause = TRUE
//
doPauseMutex.lock();
if (doPause)
{
if ((doSnapshot || doCalibrate) && statsData.nFramesProcessed > 0) {
SharedImageBuffer::ImageDataPtr outImage = cap->convertToRGB888(m_grabbedFrame);
QImage snapshotImg(outImage.mImageY.buffer, outImage.mImageY.width, outImage.mImageY.height, QImage::Format::Format_RGB888);
QString imgName = QString(sharedImageBuffer->getGlobalAnimSettings()->m_snapshotDir + "/cam%1_%2_%3.bmp").ARGN(m_deviceNumber).arg(statsData.nFramesProcessed).arg(CUR_TIME_H);
if (doCalibrate)
imgName = QString("cam%1_%2_%3.bmp").ARGN(m_deviceNumber).arg(statsData.nFramesProcessed).arg(CUR_TIME_H);
snapshotImg.save(imgName, NULL, 100);
if (doSnapshot ) doSnapshot = false;
else {
doCalibrate = false;
emit snapshoted(m_deviceNumber);
}
}
doPauseMutex.unlock();
QThread::msleep(intervalms);
continue;
}
doPauseMutex.unlock();
#if 1
if (bIsFirstFrame && m_grabbedFrame.mImageY.buffer) { // For calibrating when loading...
SharedImageBuffer::ImageDataPtr outImage = cap->convertToRGB888(m_grabbedFrame);
QImage snapshotImg(outImage.mImageY.buffer, outImage.mImageY.width, outImage.mImageY.height, QImage::Format::Format_RGB888);
QString imgName = QString("cam%1_%2_%3.bmp").ARGN(m_deviceNumber).arg(statsData.nFramesProcessed).arg(CUR_TIME_H);
snapshotImg.save(imgName, NULL, 100);
emit snapshoted(m_deviceNumber);
}
#endif
#if 1
sharedImageBuffer->syncForVideoProcessing(statsData.nFramesProcessed);
#endif
// Capture frame (if available)
while (cap->getIncomingType() != D360::Capture::IncomingFrameType::Video)
{
if (!cap->grabFrame(m_grabbedFrame))
{
m_isCanGrab = false;
break;
}
//if (m_deviceNumber == nFirstViewId)
{
if (cap->getIncomingType() == D360::Capture::IncomingFrameType::Audio)
{
if (gasettings->m_offlineVideo != "" || gasettings->m_wowzaServer != "")
sharedImageBuffer->syncForAudioProcessing(statsData.nAudioFrames);
void* frame = cap->retrieveAudioFrame();
if (frame) {
sharedImageBuffer->setAudioFrame(frame);
//emit newAudioFrameReady((void*)frame);
if (sharedImageBuffer->getStreamer())
sharedImageBuffer->getStreamer()->streamAudio(m_deviceNumber, frame);
statsData.nAudioFrames++;
}
}
}
}
if (m_isCanGrab == false) {
break;
}
if (cap->getIncomingType() == D360::Capture::IncomingFrameType::Video)
{
sharedImageBuffer->sync(m_deviceNumber);
cap->retrieveFrame(0, m_grabbedFrame);
//gasettings->m_xres = m_grabbedFrame.mImageData->width();
//gasettings->m_yres = m_grabbedFrame.mImageData->height();
}
else {
QThread::msleep(intervalms);
continue;
}
// It should delay if second frame is captured faster than 1000/fps
nDiffMS = nFirstMS - nSecondMS; // nFirstMS is the next Milliseconds of nSecondMS
if (nFirstMS != 0 && nSecondMS != 0 && nDiffMS < 1000 / fps)
{
if (nDiffMS >= 0)
{
// If the second frame is captured faster than normal (1000/fps)
//Sleep(1000 / fps - nDiffMS);
QThread::msleep(1);
}
}
GlobalState& state = sharedImageBuffer->getState(m_deviceNumber);
//std::cout << "Current Frame " << state.m_curFrame << std::endl;
cap->setCurFrame(state.m_curFrame);
if (!singleFrameMode)
state.m_curFrame++;
//SharedImageBuffer::ImageDataPtr qgrabbedframe;
//qgrabbedframe = m_grabbedFrame.mImageData->clone();
SharedImageBuffer::ImageDataPtr d = m_grabbedFrame;
d.mFrame = statsData.nFramesProcessed;
d.msToWait = cap->msToWait();
statsData.nFramesProcessed++;
if (statsData.nFramesProcessed >= 0)
{
//if( handler->write( statsData.nFramesProcessed, *m_grabbedFrame.mImageData, m_deviceNumber ) == false )
{
}
}
//
// Add frame to buffer
//
//sharedImageBuffer->getByDeviceNumber( deviceNumber )->add( m_grabbedFrame, dropFrameIfBufferFull );
//sharedImageBuffer->getByDeviceNumber( deviceNumber )->add( qgrabbedframe, dropFrameIfBufferFull );
//sharedImageBuffer->getByDeviceNumber( deviceNumber )->add( d, dropFrameIfBufferFull );
//sharedImageBuffer->getByDeviceNumber( m_deviceNumber )->add( d, dropFrameIfBufferFull );
sharedImageBuffer->setRawImage(m_deviceNumber, d);
#ifdef REMOVE_PROCESSING_THREAD_IN_CAMERAVIEW /* Porting from ProcessingThread by B*/
int camIndex = 0;
//
// If its a file device (input) - the camera index should be set to the appropriate value since for
// file devices device number is offset by D360_FILEDEVICESTART
//
if (m_deviceNumber >= D360_FILEDEVICESTART)
{
camIndex = m_deviceNumber - D360_FILEDEVICESTART;
}
else
{
//
// Camera input
//
camIndex = m_deviceNumber;
}
if (gasettings->m_ui == true)
{
{
//
ImageBufferData newMat = d;
//int imageLength = currentFrame.mImageData->cols * currentFrame.mImageData->rows * 3;
//memcpy(buffer, currentFrame.mImageData->data, imageLength);
//currentFrame.mImageData->copyTo(*newMat);
if (gasettings->m_stitch == true)
{
std::shared_ptr< D360Sticher> stitcher = sharedImageBuffer->getStitcher();
if (stitcher)
{
stitcher->updateStitchFrameMat(newMat, camIndex, statsData.nFramesProcessed);
}
//emit newFrameMat( MatBufferPtr( newMat ), deviceNumber, statsData.nFramesProcessed );
}
else
{
//emit newFrameMat( MatBufferPtr( newMat ), deviceNumber, statsData.nFramesProcessed );
}
//std::this_thread::sleep_for( std::chrono::milliseconds( currentFrame.msToWait ) );
//emit newFrameMat( MatBufferPtr( currentFrame.mImageData ), deviceNumber, statsData.nFramesProcessed );
}
}
#endif
// Pause if first frame is captured
if (bIsFirstFrame && statsData.nFramesProcessed >= 2) {
playAndPause(true);
bIsFirstFrame = false;
}
//std::cout << "Grabbed Frame " << m_grabbedFrame << " - data " << std::endl;
if (gasettings->m_oculus) continue;
//
// Save capture time
//
captureTime = t.elapsed();
t.start();
//
// Update statistics
//
updateFPS(captureTime);
if (state.m_curFrame > gasettings->m_endFrame && gasettings->m_endFrame != -1)
{
m_isCanGrab = true;
// for loop,
//state.m_curFrame = gasettings->m_startFrame;
}
//
// Inform GUI of updated statistics
//
if (statsData.nFramesProcessed % 10 == 0 && gasettings->m_ui == true)
{
emit updateStatisticsInGUI(statsData);
}
// nSecondMS is the final MS of ONE frame.
nSecondMS = curTime->currentMSecsSinceEpoch();
}
//disconnect();
//delete m_grabbedFrame.mImageData;
PANO_DEVICE_LOG("Capture thread running is finished...");
}
void CaptureThread::process()
{
m_finished = false;
emit started(THREAD_TYPE_CAPTURE, "", m_deviceNumber);
run();
if (m_isCanGrab == false) {
PANO_DEVICE_N_WARN("Reading frame has been finished.");
emit report(THREAD_TYPE_CAPTURE, "EOF", m_deviceNumber);
}
else
{
PANO_DLOG("Emit finished signal");
emit finished(THREAD_TYPE_CAPTURE, "", m_deviceNumber);
}
finishWC.wakeAll();
m_finished = true;
}
bool CaptureThread::connect(int dupIndex)
{
if (m_captureType == CAPTUREXIMEA)
{
CaptureXimea* capture = new CaptureXimea;
if (!capture->open(m_deviceNumber))
{
PANO_LOG("Can't Open Camera!");
emit report(THREAD_TYPE_CAPTURE, "Can't Open XMIEA Camera.", m_deviceNumber);
delete capture;
return false;
}
GlobalAnimSettings* gasettings = sharedImageBuffer->getGlobalAnimSettings();
//
// Set resolution
//
/*if (width != -1)
capture->setProperty(CV_CAP_PROP_FRAME_WIDTH, width);
else*/
{
width = capture->getProperty(CV_CAP_PROP_FRAME_WIDTH);
}
/*if (height != -1)
{
capture->setProperty(CV_CAP_PROP_FRAME_HEIGHT, height);
}
else*/
{
height = capture->getProperty(CV_CAP_PROP_FRAME_HEIGHT);
}
cap = capture;
int trigsource = (int)capture->getProperty(CV_CAP_PROP_XI_TRG_SOURCE);
int selector = (int)capture->getProperty(CV_CAP_PROP_XI_GPI_SELECTOR);
int mode = (int)capture->getProperty(CV_CAP_PROP_XI_GPI_MODE);
std::cout << "Mode " << mode << " Selector " << selector << " TrgSource " << trigsource << std::endl;
}
if (m_captureType == CAPTUREDSHOW || m_captureType == CAPTUREVIDEO)
{
GlobalAnimSettings* gasettings = sharedImageBuffer->getGlobalAnimSettings();
QString cameraName = gasettings->cameraSettingsList()[m_deviceNumber].name;
CaptureDShow* capture = new CaptureDShow;
//if (!capture->open(m_deviceNumber, cameraName, gasettings->m_fps))
if (!capture->open(m_deviceNumber, cameraName, gasettings->m_fps, m_captureType == CAPTUREDSHOW, dupIndex))
{
std::cout << "Can't Open Camera" << std::endl;
emit report(THREAD_TYPE_CAPTURE, "Can't Open DirectShow device.", m_deviceNumber);
delete capture;
return false;
}
capture->setAudio(gasettings->cameraSettingsList()[m_deviceNumber].audioType);
//
// Set resolution
//
if (width != -1)
capture->setProperty(CV_CAP_PROP_FRAME_WIDTH, width);
else
{
width = capture->getProperty(CV_CAP_PROP_FRAME_WIDTH);
}
if (height != -1)
{
capture->setProperty(CV_CAP_PROP_FRAME_HEIGHT, height);
}
else
{
height = capture->getProperty(CV_CAP_PROP_FRAME_HEIGHT);
}
PANO_DEVICE_LOG(QString("Device resolution (Width: %1, Height: %2)").ARGN(width).ARGN(height));
cap = capture;
}
if (m_captureType == CAPTUREFILE)
{
CaptureImageFile *capture = new CaptureImageFile;
GlobalState &state = sharedImageBuffer->getState(m_deviceNumber);
GlobalAnimSettings* gasettings = sharedImageBuffer->getGlobalAnimSettings();
state.m_curFrame = gasettings->m_startFrame;
//Buffer< cv::Mat >* imageBuffer = sharedImageBuffer->getByDeviceNumber( deviceNumber );
CameraInput & camSettings = gasettings->cameraSettingsList()[m_deviceNumber];
capture->setImageFileDir(camSettings.fileDir);
capture->setImageFilePrefix(camSettings.filePrefix);
capture->setImageFileExt(camSettings.fileExt);
capture->setCurFrame(state.m_curFrame);
std::cout << "Capturing From Image " << state.m_curFrame << std::endl;
if (!capture->open(m_deviceNumber))
{
std::cout << "Can't Open File " << std::endl;
//emit report(THREAD_TYPE_CAPTURE, "Can't Open image file.", m_deviceNumber);
g_mainWindow->reportError(THREAD_TYPE_CAPTURE, "Can't Open image file.", m_deviceNumber);
delete capture;
return false;
}
capture->setProperty(CV_CAP_PROP_FPS, gasettings->m_fps);
//
// Set resolution
//
width = capture->getProperty(CV_CAP_PROP_FRAME_WIDTH);
height = capture->getProperty(CV_CAP_PROP_FRAME_HEIGHT);
//float fps = capture->getProperty(CV_CAP_PROP_FPS);
gasettings->m_xres = width;
gasettings->m_yres = height;
//gasettings->m_fps = fps;
cap = capture;
}
cap->setSnapshotPath(sharedImageBuffer->getGlobalAnimSettings()->m_snapshotDir);
m_isCanGrab = true;
//
//
//
return true;
}
bool CaptureThread::disconnect()
{
//
// Camera is connected
//
if (cap)
{
PANO_DEVICE_LOG("Disconnecting Camera...");
//
// Disconnect camera
//
delete cap;
cap = 0;
return true;
}
//
// Camera is NOT connected
//
else
return false;
}
void CaptureThread::updateFPS(int timeElapsed)
{
//
// Add instantaneous FPS value to queue
//
if (timeElapsed > 0)
{
fps.enqueue((int)1000 / timeElapsed);
//
// Increment sample number
//
sampleNumber++;
}
statsData.instantFPS = (1000.0 / timeElapsed);
//
// Maximum size of queue is DEFAULT_CAPTURE_FPS_STAT_QUEUE_LENGTH
//
if (fps.size() > CAPTURE_FPS_STAT_QUEUE_LENGTH)
fps.dequeue();
//
// Update FPS value every DEFAULT_CAPTURE_FPS_STAT_QUEUE_LENGTH samples
//
if ((fps.size() == CAPTURE_FPS_STAT_QUEUE_LENGTH) && (sampleNumber == CAPTURE_FPS_STAT_QUEUE_LENGTH))
{
//
// Empty queue and store sum
//
while (!fps.empty())
fpsSum += fps.dequeue();
//
// Calculate average FPS
//
statsData.averageFPS = fpsSum / CAPTURE_FPS_STAT_QUEUE_LENGTH;
//statsData.averageFPS = cap->getProperty( CV_CAP_PROP_FPS );
//std::cout << statsData.averageFPS << std::endl;
//
// Reset sum
//
fpsSum = 0;
//
// Reset sample number
//
sampleNumber = 0;
}
float fps = 0;
if (timeElapsed > 0)
fps = 1000 / timeElapsed;
GlobalAnimSettings* gasettings = sharedImageBuffer->getGlobalAnimSettings();
//
// Adjust frame playback speed if its loading from file
//
/*
if( m_captureType == CAPTUREFILE )
{
if( gasettings->m_playbackfps < fps )
{
float sleepms = (1.0/gasettings->m_playbackfps)*1000.0f - timeElapsed ;
//std::cout << "Ms " << sleepms << std::endl;
#ifdef _WIN32
Sleep( sleepms );
#else
usleep( sleepms );
#endif
}
}
*/
}
void CaptureThread::stop()
{
QMutexLocker locker(&doStopMutex);
doStop = true;
}
void CaptureThread::playAndPause(bool isPause)
{
QMutexLocker locker(&doPauseMutex);
doPause = isPause;
sharedImageBuffer->getStitcher()->playAndPause(isPause);
if (sharedImageBuffer->getStreamer())
sharedImageBuffer->getStreamer()->playAndPause(isPause);
}
void CaptureThread::snapshot(bool isCalibrate)
{
QMutexLocker locker(&doPauseMutex);
if (!doPause) return;
if (isCalibrate)
doCalibrate = true;
else
doSnapshot = true;
}
bool CaptureThread::isConnected()
{
return !cap;
}
int CaptureThread::getInputSourceWidth()
{
return cap->getProperty(CV_CAP_PROP_FRAME_WIDTH);
}
int CaptureThread::getInputSourceHeight()
{
return cap->getProperty(CV_CAP_PROP_FRAME_HEIGHT);
}
#if 0 // Original snapshot function
void CaptureThread::snapshot()
{
cap->snapshot();
}
#endif
AudioInput * CaptureThread::getMic()
{
return (AudioInput*)((CaptureDShow*)cap);
}
void CaptureThread::waitForFinish()
{
finishMutex.lock();
finishWC.wait(&finishMutex);
finishMutex.unlock();
}
bool CaptureThread::isFinished()
{
return m_finished;
} | [
"alisahheer1008@gmail.com"
] | alisahheer1008@gmail.com |
26c6bdda590bd8e94628f4d4cf27c01a195f24d1 | 6b6b239bf6bbc782c798b33f89722dee40007de9 | /rating-1000/codeforces339B.cpp | 3ec6863697f73f20ca8f1bc100de060625325e31 | [] | no_license | chemistry-sourabh/codeforces | 9e25086b717775ef0d656646ca828fa610186ed2 | 982e2a6aa869153e88d5a78da0f13a919eb33623 | refs/heads/master | 2022-11-12T12:21:46.575703 | 2020-07-06T01:22:33 | 2020-07-06T01:22:33 | 269,541,539 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 495 | cpp | // Problem Link https://codeforces.com/problemset/problem/339/B
#include <iostream>
using namespace std;
int main() {
long long n, m;
cin >> n >> m;
long long a[m];
for (long long i = 0; i < m; i++) {
cin >> a[i];
}
long long cur = 0;
long long t = 0;
for (long long i = 0; i < m; i++) {
long long d = a[i] - cur - 1;
if (d < 0) {
t += n;
}
t += d;
cur = a[i] - 1;
}
cout << t << "\n";
} | [
"chemistry_sourabh@yahoo.co.in"
] | chemistry_sourabh@yahoo.co.in |
8ee6caebc12ccec53874b6673a84589a0007191f | 9b05ff8107e8ad69d94c8bfa13599ab640f1aabc | /Day 2 - Varijable - operatori - stringovi/Varijable/Zadatak - Varijable.cpp | 51e3729decb278ed10e4c7411e011c2c7eed6b9c | [] | no_license | antonioscardovi/BootcampIT-1 | e34359fd4bfa96dd79c0e2a5c2c2a6b504773f41 | 6a1f37e8bcfcc0ec22290ea1a1d3158b2d03ef6b | refs/heads/master | 2020-04-26T23:46:14.268613 | 2019-03-28T19:33:07 | 2019-03-28T19:33:07 | 173,913,192 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,276 | cpp |
#include "pch.h"
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
// treci zadatak (globalna varijabla)
float PI = 3.14;
int main()
{
// prvi zadatak
/*int a = 1;
char b = 'B';
float c = 2.1;
double d = 4.23847956254;
bool e = 1;
cout << a << "\n" << b << "\n" << c << "\n" << d << "\n" << e << endl;
cout << "\n -----------------------------\n\n";*/
// KRAJ
// drugi zadatak
/*
cout << "Unesi broj: ";
cin >> a;
cout << "Unesi slovo: ";
cin >> b;
cout << "Unesi decimalni broj: ";
cin >> c;
cout << "Unesi veliki decimalni broj: ";
cin >> d;
cout << "Unesi 1 ili 0: " << endl;
*/
// KRAJ
// cetvrti zadatak
/*
int x, y, z;
cout << "Prvi broj: ";
cin >> x;
cout << "Drugi broj: ";
cin >> y;
cout << x << " " << y << endl;
z = x;
x = y;
y = z;
// bez dodatne varijable
x = x - y;
y = x - y;
x = y - x;
cout << x << " " << y << endl;
*/
// KRAJ
// Peti zadatak
/*
float a, b;
int c;
cout << "Prvi broj: ";
cin >> a;
cout << "Drugi broj: ";
cin >> b;
cout << "Zbroj: " << a + b << endl;
cout << "Razlika: " << a - b << endl;
cout << "Produkt: " << a * b << endl;
cout << setprecision(2) << fixed << "Kvocijent: " << a / b << endl;
cout << "Cetveroznamenkasti broj: ";
cin >> c;
cout << "Tisucice: " << c / 1000 << endl;
cout << "Stotice: " << ( c % 1000 ) / 100 << endl;
cout << "Desetice: " << ((c % 1000)%100)/10 << endl;
cout << "Jedinice: " << (((c % 1000)%100)%10)<< endl;
*/
// KRAJ
// Sesti zadatak
/*
cout << "(5 < 3 || (7 / 2) > !(6 == 6)) && !!true || false = ";
cout << (5 < 3 || (7 / 2) > !(6 == 6)) && !!true || false;
cout << "!((!(true && false) && !(true || false)) && (!(false && true) || !(false || true))) = ";
cout << !((!(true && false) && !(true || false)) && (!(false && true) || !(false || true)));
cout << "!(!(1 > 2 || 3 < 4) && (5 == 6 && 7 <= 8) || 9 >= 0) = ";
cout << !(!(1 > 2 || 3 < 4) && (5 == 6 && 7 <= 8) || 9 >= 0);
*/
// KRAJ
// Sedmi zadatak
/*
int a, b;
cout << "Prvi broj: ";
cin >> a;
cout << "Drugi broj: ";
cin >> b;
a += b;
cout << "a += b -> " << a << endl;
a -= b;
cout << "a -= b -> " << b << endl;
a *= b;
cout << "a *= b -> " << a << endl;
a /= b;
cout << "a /= b -> " << b << endl;
*/
// KRAJ
// Osmi zadatak
string a = "welcome";
string b = "w3resource";
string sen;
cout << "Duljina:\n";
cout << "welcome: " << a.size() << endl;
cout << "w3resource: " << b.size() << endl;
cout << "Znak na poziciji 3:\n";
cout << "welcome: " << a.at(3) << endl;
cout << "w3resource: " << b.at(3) << endl;
cout << "Je li string prazan:\n";
cout << "welcome: " << a.empty() << endl;
cout << "w3resource: " << b.empty() << endl;
cout << "4 znaka od 3. indeksa:\n";
cout << "welcome: " << a.substr(3) << endl;
cout << "w3resource: " << b.substr(3, 4) << endl;
cout << "Zamijenite \"come\" s \"went\" u \"wlecome\" stringu :\n";
cout << a.replace(3, 4, "went") << endl;
cout << "Dodajte neki string po zelji na kraj svakog stringa:\n";
cout << a.append(" home") << endl;
cout << b.append(".com") << endl;
cout << "Ubacite string \"ubacivanje\" na 3. indeks\n";
cout << a.insert(3, "ubacivanje") << endl;
cout << "Upisi recenicu:\n";
cin >> sen;
// KRAJ
}
| [
""
] | |
1f211bc43c929b22e6a3a47ae4b46c6dcfd79a97 | 46f7cb7150697037d4b5f434dde423a1eeb8e422 | /ncnn-20210525-full-source/src/layer/pooling.cpp | d5ac2148772cf29d4cd25b300ae9d4c8f9a8aa6f | [
"BSD-3-Clause",
"Zlib",
"BSD-2-Clause",
"MIT"
] | permissive | MirrorYuChen/ncnn_example | d856f732e031b0e069fed7e30759e1c6c7947aaf | 82a84d79c96e908f46b7e7cac6c8365c83b0f896 | refs/heads/master | 2023-08-18T06:31:06.113775 | 2022-05-14T17:38:01 | 2022-05-14T17:38:01 | 183,336,202 | 362 | 108 | MIT | 2022-06-22T04:17:14 | 2019-04-25T01:53:37 | C++ | UTF-8 | C++ | false | false | 12,781 | cpp | // Tencent is pleased to support the open source community by making ncnn available.
//
// Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// 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 "pooling.h"
#include "layer_type.h"
#include <float.h>
namespace ncnn {
Pooling::Pooling()
{
one_blob_only = true;
support_inplace = false;
}
int Pooling::load_param(const ParamDict& pd)
{
pooling_type = pd.get(0, 0);
kernel_w = pd.get(1, 0);
kernel_h = pd.get(11, kernel_w);
stride_w = pd.get(2, 1);
stride_h = pd.get(12, stride_w);
pad_left = pd.get(3, 0);
pad_right = pd.get(14, pad_left);
pad_top = pd.get(13, pad_left);
pad_bottom = pd.get(15, pad_top);
global_pooling = pd.get(4, 0);
pad_mode = pd.get(5, 0);
avgpool_count_include_pad = pd.get(6, 0);
adaptive_pooling = pd.get(7, 0);
out_w = pd.get(8, 0);
out_h = pd.get(18, out_w);
return 0;
}
int Pooling::forward(const Mat& bottom_blob, Mat& top_blob, const Option& opt) const
{
// max value in NxN window
// avg value in NxN window
int w = bottom_blob.w;
int h = bottom_blob.h;
int channels = bottom_blob.c;
size_t elemsize = bottom_blob.elemsize;
// NCNN_LOGE("Pooling input %d x %d pad = %d %d %d %d ksize=%d %d stride=%d %d", w, h, pad_left, pad_right, pad_top, pad_bottom, kernel_w, kernel_h, stride_w, stride_h);
if (global_pooling)
{
top_blob.create(channels, elemsize, opt.blob_allocator);
if (top_blob.empty())
return -100;
int size = w * h;
if (pooling_type == PoolMethod_MAX)
{
#pragma omp parallel for num_threads(opt.num_threads)
for (int q = 0; q < channels; q++)
{
const float* ptr = bottom_blob.channel(q);
float max = ptr[0];
for (int i = 0; i < size; i++)
{
max = std::max(max, ptr[i]);
}
top_blob[q] = max;
}
}
else if (pooling_type == PoolMethod_AVE)
{
#pragma omp parallel for num_threads(opt.num_threads)
for (int q = 0; q < channels; q++)
{
const float* ptr = bottom_blob.channel(q);
float sum = 0.f;
for (int i = 0; i < size; i++)
{
sum += ptr[i];
}
top_blob[q] = sum / size;
}
}
return 0;
}
if (adaptive_pooling)
{
top_blob.create(out_w, out_h, channels, elemsize, opt.blob_allocator);
if (top_blob.empty())
return -100;
if (pooling_type == PoolMethod_MAX)
{
#pragma omp parallel for num_threads(opt.num_threads)
for (int q = 0; q < channels; q++)
{
const float* inptr = bottom_blob.channel(q);
float* outptr = top_blob.channel(q);
for (int i = 0; i < out_h; i++)
{
int ih0 = floor((float)(i * h) / out_h);
int ih1 = ceil((float)((i + 1) * h) / out_h);
for (int j = 0; j < out_w; j++)
{
int iw0 = floor((float)(j * w) / out_w);
int iw1 = ceil((float)((j + 1) * w) / out_w);
float max = inptr[ih0 * w + iw0];
for (int ih = ih0; ih < ih1; ih++)
{
for (int iw = iw0; iw < iw1; iw++)
{
max = std::max(max, inptr[ih * w + iw]);
}
}
outptr[j] = max;
}
outptr += out_w;
}
}
}
else if (pooling_type == PoolMethod_AVE)
{
#pragma omp parallel for num_threads(opt.num_threads)
for (int q = 0; q < channels; q++)
{
const float* inptr = bottom_blob.channel(q);
float* outptr = top_blob.channel(q);
for (int i = 0; i < out_h; i++)
{
int ih0 = floor((float)(i * h) / out_h);
int ih1 = ceil((float)((i + 1) * h) / out_h);
int hk = ih1 - ih0;
for (int j = 0; j < out_w; j++)
{
int iw0 = floor((float)(j * w) / out_w);
int iw1 = ceil((float)((j + 1) * w) / out_w);
int wk = iw1 - iw0;
float sum = 0;
for (int ih = ih0; ih < ih1; ih++)
{
for (int iw = iw0; iw < iw1; iw++)
{
sum += inptr[ih * w + iw];
}
}
outptr[j] = sum / hk / wk;
}
outptr += out_w;
}
}
}
return 0;
}
Mat bottom_blob_bordered;
make_padding(bottom_blob, bottom_blob_bordered, opt);
if (bottom_blob_bordered.empty())
return -100;
w = bottom_blob_bordered.w;
h = bottom_blob_bordered.h;
int outw = (w - kernel_w) / stride_w + 1;
int outh = (h - kernel_h) / stride_h + 1;
top_blob.create(outw, outh, channels, elemsize, opt.blob_allocator);
if (top_blob.empty())
return -100;
const int maxk = kernel_w * kernel_h;
// kernel offsets
std::vector<int> _space_ofs(maxk);
int* space_ofs = &_space_ofs[0];
{
int p1 = 0;
int p2 = 0;
int gap = w - kernel_w;
for (int i = 0; i < kernel_h; i++)
{
for (int j = 0; j < kernel_w; j++)
{
space_ofs[p1] = p2;
p1++;
p2++;
}
p2 += gap;
}
}
if (pooling_type == PoolMethod_MAX)
{
#pragma omp parallel for num_threads(opt.num_threads)
for (int q = 0; q < channels; q++)
{
const Mat m = bottom_blob_bordered.channel(q);
float* outptr = top_blob.channel(q);
for (int i = 0; i < outh; i++)
{
for (int j = 0; j < outw; j++)
{
const float* sptr = m.row(i * stride_h) + j * stride_w;
float max = sptr[0];
for (int k = 0; k < maxk; k++)
{
float val = sptr[space_ofs[k]];
max = std::max(max, val);
}
outptr[j] = max;
}
outptr += outw;
}
}
}
else if (pooling_type == PoolMethod_AVE)
{
if (avgpool_count_include_pad == 0)
{
int wtailpad = 0;
int htailpad = 0;
if (pad_mode == 0) // full padding
{
wtailpad = bottom_blob_bordered.w - bottom_blob.w - pad_left - pad_right;
htailpad = bottom_blob_bordered.h - bottom_blob.h - pad_top - pad_bottom;
}
#pragma omp parallel for num_threads(opt.num_threads)
for (int q = 0; q < channels; q++)
{
const Mat m = bottom_blob_bordered.channel(q);
float* outptr = top_blob.channel(q);
for (int i = 0; i < outh; i++)
{
int sy0 = i * stride_h;
for (int j = 0; j < outw; j++)
{
int sx0 = j * stride_w;
float sum = 0;
int area = 0;
for (int ki = 0; ki < kernel_h; ki++)
{
int sy = sy0 + ki;
if (sy < pad_top)
continue;
if (sy >= h - pad_bottom - htailpad)
break;
for (int kj = 0; kj < kernel_w; kj++)
{
int sx = sx0 + kj;
if (sx < pad_left)
continue;
if (sx >= w - pad_right - wtailpad)
break;
float val = m.row(sy)[sx];
sum += val;
area += 1;
}
}
outptr[j] = sum / area;
}
outptr += outw;
}
}
}
else // if (avgpool_count_include_pad == 1)
{
#pragma omp parallel for num_threads(opt.num_threads)
for (int q = 0; q < channels; q++)
{
const Mat m = bottom_blob_bordered.channel(q);
float* outptr = top_blob.channel(q);
for (int i = 0; i < outh; i++)
{
for (int j = 0; j < outw; j++)
{
const float* sptr = m.row(i * stride_h) + j * stride_w;
float sum = 0;
for (int k = 0; k < maxk; k++)
{
float val = sptr[space_ofs[k]];
sum += val;
}
outptr[j] = sum / maxk;
}
outptr += outw;
}
}
}
}
return 0;
}
void Pooling::make_padding(const Mat& bottom_blob, Mat& bottom_blob_bordered, const Option& opt) const
{
int w = bottom_blob.w;
int h = bottom_blob.h;
bottom_blob_bordered = bottom_blob;
float pad_value = 0.f;
if (pooling_type == PoolMethod_MAX)
{
pad_value = bottom_blob.elemsize == 1 ? -128.f : -FLT_MAX;
}
else if (pooling_type == PoolMethod_AVE)
{
pad_value = 0.f;
}
int wtailpad = 0;
int htailpad = 0;
if (pad_mode == 0) // full padding
{
int wtail = (w + pad_left + pad_right - kernel_w) % stride_w;
int htail = (h + pad_top + pad_bottom - kernel_h) % stride_h;
if (wtail != 0)
wtailpad = stride_w - wtail;
if (htail != 0)
htailpad = stride_h - htail;
Option opt_b = opt;
opt_b.blob_allocator = opt.workspace_allocator;
copy_make_border(bottom_blob, bottom_blob_bordered, pad_top, pad_bottom + htailpad, pad_left, pad_right + wtailpad, BORDER_CONSTANT, pad_value, opt_b);
}
else if (pad_mode == 1) // valid padding
{
Option opt_b = opt;
opt_b.blob_allocator = opt.workspace_allocator;
copy_make_border(bottom_blob, bottom_blob_bordered, pad_top, pad_bottom, pad_left, pad_right, BORDER_CONSTANT, pad_value, opt_b);
}
else if (pad_mode == 2) // tensorflow padding=SAME or onnx padding=SAME_UPPER
{
int wpad = kernel_w + (w - 1) / stride_w * stride_w - w;
int hpad = kernel_h + (h - 1) / stride_h * stride_h - h;
if (wpad > 0 || hpad > 0)
{
Option opt_b = opt;
opt_b.blob_allocator = opt.workspace_allocator;
copy_make_border(bottom_blob, bottom_blob_bordered, hpad / 2, hpad - hpad / 2, wpad / 2, wpad - wpad / 2, BORDER_CONSTANT, pad_value, opt_b);
}
}
else if (pad_mode == 3) // onnx padding=SAME_LOWER
{
int wpad = kernel_w + (w - 1) / stride_w * stride_w - w;
int hpad = kernel_h + (h - 1) / stride_h * stride_h - h;
if (wpad > 0 || hpad > 0)
{
Option opt_b = opt;
opt_b.blob_allocator = opt.workspace_allocator;
copy_make_border(bottom_blob, bottom_blob_bordered, hpad - hpad / 2, hpad / 2, wpad - wpad / 2, wpad / 2, BORDER_CONSTANT, pad_value, opt_b);
}
}
}
} // namespace ncnn
| [
"2458006366@qq.com"
] | 2458006366@qq.com |
07861d52c33a3ad6f75216e0ce4b4dcae3e03510 | e43a2530ffe372741c38b4ced424867e613e5f28 | /Homework/2.cpp | f2d06d26bb7428751a22daf218d6f92a404e431b | [] | no_license | kidneyweakx/ndhu-cpp-hw | 1f8afe1ce58f41f6c29272514f416b2b05fd6c48 | a8e86214bdfed9982493058376a3698052fccff1 | refs/heads/master | 2020-07-25T08:24:54.109332 | 2019-09-13T09:02:15 | 2019-09-13T09:02:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 520 | cpp | #include <iostream>
#include <string>
using namespace std;
int main()
{
string str1, str2,str3;
cout << "Enter str1 and str2\n";
getline(cin,str1);
getline(cin,str2);
if(str1==str2)
cout << "Equal\n";
else
cout << "Not Equal\n";
int n=str1.find(str2);
if(n>=0&&n<str1.length())
cout <<"The first string contains the second string\n";
else
cout <<"The first string does not contain the second string\n";
str3=str2;
str1+=str3;
cout << "The concatenated string is " << str1 << endl;
return 0;
}
| [
"kidneyweakx@g-mail.nsysu.edu.tw"
] | kidneyweakx@g-mail.nsysu.edu.tw |
733fa68d6dccedfee51a015070e99990b19275c3 | 3de210d8e5b92de8234305438059e91fc83c952b | /Tutorials/Particles/ElectromagneticPIC/Exec/OpenACC/EMParticleContainer.H | b495758bf846b44bf12f895fa957d6f913468e1f | [
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | stevenireeves/amrex_with_GP | 69bd560587676a73a93e0baa6c4354c8fc90b92d | e2e4bff90b9687ba490b919848c887481288cdd4 | refs/heads/master | 2022-12-25T00:00:46.324381 | 2018-12-24T18:56:29 | 2018-12-24T18:56:29 | 111,460,541 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,889 | h | #ifndef EM_PARTICLE_CONTAINER_H_
#define EM_PARTICLE_CONTAINER_H_
#include <AMReX_Particles.H>
struct PIdx
{
enum {
ux = 0,
uy, uz, w, Ex, Ey, Ez, Bx, By, Bz, ginv,
nattribs
};
};
class EMParIter
: public amrex::ParIter<0,0,PIdx::nattribs,0>
{
public:
using amrex::ParIter<0,0,PIdx::nattribs,0>::ParIter;
// EMParIter (ContainerType& pc, int level);
const std::array<RealVector, PIdx::nattribs>& GetAttribs () const {
return GetStructOfArrays().GetRealData();
}
std::array<RealVector, PIdx::nattribs>& GetAttribs () {
return GetStructOfArrays().GetRealData();
}
const RealVector& GetAttribs (int comp) const {
return GetStructOfArrays().GetRealData(comp);
}
RealVector& GetAttribs (int comp) {
return GetStructOfArrays().GetRealData(comp);
}
};
class EMParticleContainer
: public amrex::ParticleContainer<0, 0, PIdx::nattribs, 0>
{
public:
EMParticleContainer (const amrex::Geometry & a_geom,
const amrex::DistributionMapping & a_dmap,
const amrex::BoxArray & a_ba,
const int a_species_id,
const amrex::Real a_charge,
const amrex::Real a_mass);
void InitParticles(const amrex::IntVect& a_num_particles_per_cell,
const amrex::Real a_thermal_momentum_std,
const amrex::Real a_thermal_momentum_mean,
const amrex::Real a_density,
const amrex::RealBox& a_bounds,
const int a_problem);
void PushAndDeposeParticles(const amrex::MultiFab& Ex,
const amrex::MultiFab& Ey,
const amrex::MultiFab& Ez,
const amrex::MultiFab& Bx,
const amrex::MultiFab& By,
const amrex::MultiFab& Bz,
amrex::MultiFab& jx,
amrex::MultiFab& jy,
amrex::MultiFab& jz,
amrex::Real dt);
void PushParticleMomenta(const amrex::MultiFab& Ex,
const amrex::MultiFab& Ey,
const amrex::MultiFab& Ez,
const amrex::MultiFab& Bx,
const amrex::MultiFab& By,
const amrex::MultiFab& Bz,
amrex::Real dt);
void PushParticlePositions(amrex::Real dt);
protected:
int m_species_id;
amrex::Real m_charge;
amrex::Real m_mass;
};
#endif
| [
"atmyers2@gmail.com"
] | atmyers2@gmail.com |
8aa84e4e11b33ca2493e1e4902f7bfdff8ea614e | cda5b2a60af8d66063b93c712e019e8888fa3d27 | /main.cpp | 81c5ea16883f0952cff3396d3448d816e9920d72 | [] | no_license | axdabola/Person-Relationship-Manager | f68354423a75cb3b4cc1f79a2f6ec01f6ad3aa5e | 6daccb6201d3bfbec3b7268a3a17a32be2c55d70 | refs/heads/master | 2023-03-07T01:03:59.585128 | 2021-02-18T23:08:08 | 2021-02-18T23:08:08 | 323,149,753 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,825 | cpp | #define _CRT_SECURE_NO_WARNINGS 1
#include <iostream>
#include <string>
#include <cstdlib>
#include "defcls.hpp"
#include "defdata.hpp"
#include "datavector.hpp"
#include "scrman.hpp"
int main()
{
int esc = 0;
defcls::Funcs f;
defcls::Enums e;
datavector::pessoa_col pcol;
defdata::vcdata_t vdata;
std::vector<defdata::pessoa_t>::iterator it;
std::vector<defdata::pessoa_t>::iterator itM;
size_t sz = 0;
size_t szM = 0;
int szInt;
int szIntmin;
int szIntM;
int tema = e.Escuro;
scrman::DarkMode();
while (true)
{
scrman::Menu();
std::cin >> esc;
switch (esc)
{
case 1:
defdata::Pessoa p;
std::system("cls");
p = scrman::Opc1();
if (pcol.AdicionarPessoa(p))
std::cout << "Pessoa adicionada com sucesso" << std::endl;
else
std::cout << "Pessoa nao adicionada!" << std::endl;
std::system("pause");
break;
case 2:
std::system("cls");
std::cout << "Insira localizacao da pessoa no vector: ";
std::cin >> sz;
scrman::ImprimirInfoClassePessoa();
scrman::ImprimirVector(pcol.pessoaVector, sz);
std::system("pause");
break;
case 3:
std::system("cls");
vdata = pcol.VectorInfo();
scrman::ImprimirInfoClassePessoa();
for (sz = 0; sz < vdata.size; sz++)
{
scrman::ImprimirVector(pcol.pessoaVector, sz);
}
std::system("pause");
break;
case 4:
std::system("cls");
vdata = pcol.VectorInfo();
std::cout << "Tamanho atual do vector: " << vdata.size << std::endl;
std::cout << "Tamanho maximo do vector: " << vdata.maxSize << std::endl;
std::system("pause");
break;
case 5:
std::system("cls");
std::cout << "Insira indice da pessoa a apagar: ";
std::cin >> sz;
szInt = static_cast<int>(sz);
it = pcol.pessoaVector.begin();
std::advance(it, szInt);
pcol.RemoverPessoa(it);
std::system("pause");
break;
case 6:
std::system("cls");
std::cout << "Insira indice da pessoa a apagar (Min): ";
std::cin >> sz;
std::cout << "Insira indice da pessoa a apagar (Max): ";
std::cin >> szM;
szIntmin = static_cast<int>(sz);
it = pcol.pessoaVector.begin();
std::advance(it, szIntmin);
szIntM = static_cast<int>(szM);
itM = pcol.pessoaVector.begin();
std::advance(itM, szIntM);
pcol.RemoverPessoa(it, itM);
std::system("pause");
break;
case 7:
std::system("cls");
std::cout << "Insira novo tamanho para o vector: ";
std::cin >> sz;
pcol.AlterarTamanhoVector(sz);
std::system("pause");
break;
case 8:
std::system("cls");
if (tema == defcls::Enums::ConsTheme::Escuro)
{
scrman::LightMode();
tema = e.Claro;
}
else
{
scrman::DarkMode();
tema = e.Escuro;
}
std::cout << "Tema alterado." << std::endl;
std::system("pause");
break;
case 9:
std::exit(0);
default:
std::system("cls");
std::cout << "Opcao errada!" << std::endl;
std::system("pause");
}
}
return 0;
} | [
"36107529+axdabola@users.noreply.github.com"
] | 36107529+axdabola@users.noreply.github.com |
be222f0c1dc6e6af6d3b08dd27ade6265d219f6d | d24975c1f4cc7553936f90a032696857237a681d | /USACO Training/hamming.cpp | 04c5158897519e2b7c93eb788f539c33598388f2 | [
"Apache-2.0"
] | permissive | SamanKhamesian/ACM-ICPC-Problems | 304b5cfe6e227cce2d63209711bee7c2982620cd | c68c04bee4de9ba9f30e665cd108484e0fcae4d7 | refs/heads/master | 2020-04-29T08:42:58.942037 | 2019-03-21T20:11:57 | 2019-03-21T20:11:57 | 175,996,101 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,110 | cpp | #include <iostream>
#include <algorithm>
#include <fstream>
#include <vector>
#include <cmath>
using namespace std;
int d, n, b;
vector<int> ans;
ifstream fin("hamming.in");
ofstream fout("hamming.out");
bool hammingDistance(int x, int y)
{
int diff = 0;
while (x != 0 || y != 0)
{
if (((x % 2) ^ (y % 2)))
{
diff++;
}
x /= 2;
y /= 2;
}
return diff >= d;
}
bool hammingDistanceIsOK(int x)
{
for (int i = 0; i < ans.size(); ++i)
{
if (!hammingDistance(x, ans[i]))
{
return false;
}
}
return true;
}
int main()
{
fin >> n >> b >> d;
ans.push_back(0);
for (int i = 1; i < (int)pow(2.0, b * 1.0) && ans.size() < n; ++i)
{
if (hammingDistanceIsOK(i))
{
ans.push_back(i);
}
}
int j, i = 0;
while (i < ans.size())
{
fout << ans[i];
i++;
for (j = i; j < ans.size() && i + 9 > j; ++j)
{
fout << " " << ans[j];
}
i = j;
fout << endl;
}
}
| [
"saman.khamesian@gmail.com"
] | saman.khamesian@gmail.com |
7f6ec739fa1a20037c694541eb69a762d59c7760 | d8db27c5e7d8f82e9de20f1e4fca2b0efa2ce327 | /morpheus/plugins/motility/haptotaxis.h | 524f3aca2f2b84d170b44f2c5743466c727afc61 | [
"BSD-3-Clause"
] | permissive | lacdr-tox/morpheus-pseudopodia | 5217dcb3664b371d5c661e7ed1896ac9f0c0b161 | 8d4e09863067195f6ddc0aa84d62bf25289abbfd | refs/heads/master | 2023-04-15T01:14:10.949236 | 2017-07-30T17:52:00 | 2017-07-30T17:52:00 | 404,118,882 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,444 | h | //////
//
// This file is part of the modelling and simulation framework 'Morpheus',
// and is made available under the terms of the BSD 3-clause license (see LICENSE
// file that comes with the distribution or https://opensource.org/licenses/BSD-3-Clause).
//
// Authors: Joern Starruss and Walter de Back
// Copyright 2009-2016, Technische Universität Dresden, Germany
//
//////
#include "core/simulation.h"
#include "core/interfaces.h"
#include "core/cell.h"
#include "core/pde_layer.h"
#include "core/plugin_parameter.h"
/** \defgroup Haptotaxis
\ingroup motility_plugins
\ingroup CPM_EnergyPlugins
\section Description
Haptotaxis is an Energy that puts an energetic bias in the hamiltonian depending on the gradient of an underlying PDE_Layer.
\section Example
\verbatim
<Haptotaxis [layer="agent1" saturation="0.1"]>
<Layer symbol="agent1" />
<Strength [symbol="S" | value="0.1"] />
</Haptotaxis>
\endverbatim
*/
class Haptotaxis : virtual public CPM_Energy
{
private:
PluginParameter2<double,XMLEvaluator,RequiredPolicy> attractant;
PluginParameter2<double,XMLEvaluator,RequiredPolicy> strength;
public:
DECLARE_PLUGIN("Haptotaxis");
Haptotaxis(); // default values
void init(const Scope* scope) override;
void loadFromXML(const XMLNode node) override;
double delta(const SymbolFocus& cell_focus, const CPM::UPDATE& update, CPM::UPDATE_TODO todo) const;
double hamiltonian(CPM::CELL_ID cell_id) const;
};
| [
"joern.starruss@tu-dresden.de"
] | joern.starruss@tu-dresden.de |
41c2d5fc2e60ac5c56da965fd0f4ef7a2709dff8 | f62072e737805aa9156040a699365aace14140f1 | /aws-cpp-sdk-compute-optimizer/include/aws/compute-optimizer/model/ProjectedMetric.h | 09bdd5812b58c27b1c8d917479fa62df04f9145a | [
"Apache-2.0",
"MIT",
"JSON"
] | permissive | neil-b/aws-sdk-cpp | 07e8e4e197cefff2ae60ab7d1b84bdb65be2c8f9 | 1602b75abbca880b770c12788f6d2bac0c87176a | refs/heads/master | 2022-11-20T16:50:19.236474 | 2020-07-08T19:05:34 | 2020-07-08T19:05:34 | 278,437,421 | 0 | 0 | Apache-2.0 | 2020-07-09T18:10:14 | 2020-07-09T18:10:14 | null | UTF-8 | C++ | false | false | 7,402 | h | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/compute-optimizer/ComputeOptimizer_EXPORTS.h>
#include <aws/compute-optimizer/model/MetricName.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/core/utils/DateTime.h>
#include <utility>
namespace Aws
{
namespace Utils
{
namespace Json
{
class JsonValue;
class JsonView;
} // namespace Json
} // namespace Utils
namespace ComputeOptimizer
{
namespace Model
{
/**
* <p>Describes a projected utilization metric of a recommendation option, such as
* an Amazon EC2 instance.</p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/compute-optimizer-2019-11-01/ProjectedMetric">AWS
* API Reference</a></p>
*/
class AWS_COMPUTEOPTIMIZER_API ProjectedMetric
{
public:
ProjectedMetric();
ProjectedMetric(Aws::Utils::Json::JsonView jsonValue);
ProjectedMetric& operator=(Aws::Utils::Json::JsonView jsonValue);
Aws::Utils::Json::JsonValue Jsonize() const;
/**
* <p>The name of the projected utilization metric.</p> <note> <p>Memory metrics
* are only returned for resources that have the unified CloudWatch agent installed
* on them. For more information, see <a
* href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/Install-CloudWatch-Agent.html">Enabling
* Memory Utilization with the CloudWatch Agent</a>.</p> </note>
*/
inline const MetricName& GetName() const{ return m_name; }
/**
* <p>The name of the projected utilization metric.</p> <note> <p>Memory metrics
* are only returned for resources that have the unified CloudWatch agent installed
* on them. For more information, see <a
* href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/Install-CloudWatch-Agent.html">Enabling
* Memory Utilization with the CloudWatch Agent</a>.</p> </note>
*/
inline bool NameHasBeenSet() const { return m_nameHasBeenSet; }
/**
* <p>The name of the projected utilization metric.</p> <note> <p>Memory metrics
* are only returned for resources that have the unified CloudWatch agent installed
* on them. For more information, see <a
* href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/Install-CloudWatch-Agent.html">Enabling
* Memory Utilization with the CloudWatch Agent</a>.</p> </note>
*/
inline void SetName(const MetricName& value) { m_nameHasBeenSet = true; m_name = value; }
/**
* <p>The name of the projected utilization metric.</p> <note> <p>Memory metrics
* are only returned for resources that have the unified CloudWatch agent installed
* on them. For more information, see <a
* href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/Install-CloudWatch-Agent.html">Enabling
* Memory Utilization with the CloudWatch Agent</a>.</p> </note>
*/
inline void SetName(MetricName&& value) { m_nameHasBeenSet = true; m_name = std::move(value); }
/**
* <p>The name of the projected utilization metric.</p> <note> <p>Memory metrics
* are only returned for resources that have the unified CloudWatch agent installed
* on them. For more information, see <a
* href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/Install-CloudWatch-Agent.html">Enabling
* Memory Utilization with the CloudWatch Agent</a>.</p> </note>
*/
inline ProjectedMetric& WithName(const MetricName& value) { SetName(value); return *this;}
/**
* <p>The name of the projected utilization metric.</p> <note> <p>Memory metrics
* are only returned for resources that have the unified CloudWatch agent installed
* on them. For more information, see <a
* href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/Install-CloudWatch-Agent.html">Enabling
* Memory Utilization with the CloudWatch Agent</a>.</p> </note>
*/
inline ProjectedMetric& WithName(MetricName&& value) { SetName(std::move(value)); return *this;}
/**
* <p>The time stamps of the projected utilization metric.</p>
*/
inline const Aws::Vector<Aws::Utils::DateTime>& GetTimestamps() const{ return m_timestamps; }
/**
* <p>The time stamps of the projected utilization metric.</p>
*/
inline bool TimestampsHasBeenSet() const { return m_timestampsHasBeenSet; }
/**
* <p>The time stamps of the projected utilization metric.</p>
*/
inline void SetTimestamps(const Aws::Vector<Aws::Utils::DateTime>& value) { m_timestampsHasBeenSet = true; m_timestamps = value; }
/**
* <p>The time stamps of the projected utilization metric.</p>
*/
inline void SetTimestamps(Aws::Vector<Aws::Utils::DateTime>&& value) { m_timestampsHasBeenSet = true; m_timestamps = std::move(value); }
/**
* <p>The time stamps of the projected utilization metric.</p>
*/
inline ProjectedMetric& WithTimestamps(const Aws::Vector<Aws::Utils::DateTime>& value) { SetTimestamps(value); return *this;}
/**
* <p>The time stamps of the projected utilization metric.</p>
*/
inline ProjectedMetric& WithTimestamps(Aws::Vector<Aws::Utils::DateTime>&& value) { SetTimestamps(std::move(value)); return *this;}
/**
* <p>The time stamps of the projected utilization metric.</p>
*/
inline ProjectedMetric& AddTimestamps(const Aws::Utils::DateTime& value) { m_timestampsHasBeenSet = true; m_timestamps.push_back(value); return *this; }
/**
* <p>The time stamps of the projected utilization metric.</p>
*/
inline ProjectedMetric& AddTimestamps(Aws::Utils::DateTime&& value) { m_timestampsHasBeenSet = true; m_timestamps.push_back(std::move(value)); return *this; }
/**
* <p>The values of the projected utilization metrics.</p>
*/
inline const Aws::Vector<double>& GetValues() const{ return m_values; }
/**
* <p>The values of the projected utilization metrics.</p>
*/
inline bool ValuesHasBeenSet() const { return m_valuesHasBeenSet; }
/**
* <p>The values of the projected utilization metrics.</p>
*/
inline void SetValues(const Aws::Vector<double>& value) { m_valuesHasBeenSet = true; m_values = value; }
/**
* <p>The values of the projected utilization metrics.</p>
*/
inline void SetValues(Aws::Vector<double>&& value) { m_valuesHasBeenSet = true; m_values = std::move(value); }
/**
* <p>The values of the projected utilization metrics.</p>
*/
inline ProjectedMetric& WithValues(const Aws::Vector<double>& value) { SetValues(value); return *this;}
/**
* <p>The values of the projected utilization metrics.</p>
*/
inline ProjectedMetric& WithValues(Aws::Vector<double>&& value) { SetValues(std::move(value)); return *this;}
/**
* <p>The values of the projected utilization metrics.</p>
*/
inline ProjectedMetric& AddValues(double value) { m_valuesHasBeenSet = true; m_values.push_back(value); return *this; }
private:
MetricName m_name;
bool m_nameHasBeenSet;
Aws::Vector<Aws::Utils::DateTime> m_timestamps;
bool m_timestampsHasBeenSet;
Aws::Vector<double> m_values;
bool m_valuesHasBeenSet;
};
} // namespace Model
} // namespace ComputeOptimizer
} // namespace Aws
| [
"aws-sdk-cpp-automation@github.com"
] | aws-sdk-cpp-automation@github.com |
94cbc44df302b5461aa993ea2d81a20ee28c272f | 831b714d97e68e34f18ada861b7c9b19902fdaae | /libsource/include/Oculus/Util/Util_SystemInfo.h | c64689f7cbb73d1411adcd9255ea9d0d698deef9 | [] | no_license | anosnowhong/phantom | 05f9bb292f65ad7501fe855d3efa94e61395f8a0 | 7d20ce9672e1d9f37ca5b656c56eb81751da7304 | refs/heads/master | 2021-01-10T13:52:28.920575 | 2016-09-16T23:41:00 | 2016-09-16T23:41:00 | 52,229,681 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,626 | h | /************************************************************************************
Filename : Util_SystemInfo.h
Content : Various operations to get information about the system
Created : September 26, 2014
Author : Kevin Jenkins
Copyright : Copyright 2014 Oculus VR, LLC All Rights reserved.
Licensed under the Oculus VR Rift SDK License Version 3.2 (the "License");
you may not use the Oculus VR Rift SDK except in compliance with the License,
which is provided at the time of installation or download, or which
otherwise accompanies this software in either electronic or hard copy form.
You may obtain a copy of the License at
http://www.oculusvr.com/licenses/LICENSE-3.2
Unless required by applicable law or agreed to in writing, the Oculus VR SDK
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
************************************************************************************/
#ifndef OVR_Util_SystemInfo_h
#define OVR_Util_SystemInfo_h
#include "../Kernel/OVR_String.h"
#include "../Kernel/OVR_Types.h"
#include "../Kernel/OVR_Array.h"
namespace OVR { namespace Util {
bool Is64BitWindows();
const char * OSAsString();
String OSVersionAsString();
uint64_t GetGuidInt();
String GetGuidString();
const char * GetProcessInfo();
String GetDisplayDriverVersion();
String GetCameraDriverVersion();
void GetGraphicsCardList(OVR::Array< OVR::String > &gpus);
String GetProcessorInfo();
//Retrives the root of the Oculus install directory
bool GetOVRRuntimePath(OVR::String &runtimePath);
//Retrives the root of the Oculus install directory and from there finds the firmware bundle relative.
//On Windows this is defined as a registry key. On Mac and Linux this is set as an environment variable.
//For Development builds with no key set, we at 10 directories for (DIR)/Firmware/FirmwareBundle.json .
//Iterating DIR as "..//" * maxSearchDirs concatenated.
bool GetFirmwarePathFromService(OVR::String &runtimePath, int numSearchDirs = 10);
#ifdef OVR_OS_MS
//Retrives the root of the Oculus install directory
bool GetOVRRuntimePathW(wchar_t out[MAX_PATH]);
// Returns true if a string-type registry key of the given name is present, else sets out to empty and returns false.
// The output string will always be 0-terminated, but may be empty.
// If wow64value is true then KEY_WOW64_32KEY is used in the registry lookup.
// If currentUser is true then HKEY_CURRENT_USER root is used instead of HKEY_LOCAL_MACHINE
bool GetRegistryStringW(const wchar_t* pSubKey, const wchar_t* stringName, wchar_t out[MAX_PATH], bool wow64value = false, bool currentUser = false);
// Returns true if a DWORD-type registry key of the given name is present, else sets out to 0 and returns false.
// If wow64value is true then KEY_WOW64_32KEY is used in the registry lookup.
// If currentUser is true then HKEY_CURRENT_USER root is used instead of HKEY_LOCAL_MACHINE
bool GetRegistryDwordW(const wchar_t* pSubKey, const wchar_t* stringName, DWORD& out, bool wow64value = false, bool currentUser = false);
// Returns true if a BINARY-type registry key of the given name is present, else sets out to 0 and returns false.
// Size must be set to max size of out buffer on way in. Will be set to size actually read into the buffer on way out.
// If wow64value is true then KEY_WOW64_32KEY is used in the registry lookup.
// If currentUser is true then HKEY_CURRENT_USER root is used instead of HKEY_LOCAL_MACHINE
bool GetRegistryBinaryW(const wchar_t* pSubKey, const wchar_t* stringName, LPBYTE out, DWORD* size, bool wow64value = false, bool currentUser = false);
// Returns true if a registry key of the given type is present and can be interpreted as a boolean, otherwise
// returns defaultValue. It's not possible to tell from a single call to this function if the given registry key
// was present. For Strings, boolean means (atoi(str) != 0). For DWORDs, boolean means (dw != 0).
// If currentUser is true then HKEY_CURRENT_USER root is used instead of HKEY_LOCAL_MACHINE
bool GetRegistryBoolW(const wchar_t* pSubKey, const wchar_t* stringName, bool defaultValue, bool wow64value = false, bool currentUser = false);
// Returns true if the value could be successfully written to the registry.
// If wow64value is true then KEY_WOW64_32KEY is used in the registry write.
// If currentUser is true then HKEY_CURRENT_USER root is used instead of HKEY_LOCAL_MACHINE
bool SetRegistryBinaryW(const wchar_t* pSubKey, const wchar_t* stringName, const LPBYTE value, DWORD size, bool wow64value = false, bool currentUser = false);
// Returns true if the value could be successfully deleted from the registry.
// If wow64value is true then KEY_WOW64_32KEY is used.
// If currentUser is true then HKEY_CURRENT_USER root is used instead of HKEY_LOCAL_MACHINE
bool DeleteRegistryValue(const wchar_t* pSubKey, const wchar_t* stringName, bool wow64value = false, bool currentUser = false);
//Mac + Linux equivelants are not implemented
String GetFileVersionStringW(wchar_t filePath[MAX_PATH]);
String GetSystemFileVersionStringW(wchar_t filePath[MAX_PATH]);
#endif // OVR_OS_MS
//-----------------------------------------------------------------------------
// Get the path for local app data.
String GetBaseOVRPath(bool create_dir);
} } // namespace OVR { namespace Util {
#endif // OVR_Util_SystemInfo_h
| [
"hong@Snows-MacBook-Pro.local"
] | hong@Snows-MacBook-Pro.local |
53d2de39b7151808ee511979f70781608b4e0910 | b92769dda6c8b7e9bf79c48df810a702bfdf872f | /9.MemoryModels&Namespaces/9.10.newplace.cpp | 5cea7285bd314777433f5bd381b6d10523438b85 | [
"MIT"
] | permissive | HuangStomach/Cpp-primer-plus | 4276e0a24887ef6d48f202107b7b4c448230cd20 | c8b2b90f10057e72da3ab570da7cc39220c88f70 | refs/heads/master | 2021-06-25T07:22:15.405581 | 2021-02-28T06:55:23 | 2021-02-28T06:55:23 | 209,192,905 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,556 | cpp | #include <iostream>
#include <new>
const int BUF = 512;
const int N = 5;
char buffer[BUF];
int main(int argc, char const *argv[]) {
using namespace std;
double *pd1, *pd2;
int i;
cout << "Calling new and placement new :\n";
pd1 = new double[N];
pd2 = new (buffer) double[N];
for (int i = 0; i < N; i++) {
pd2[i] = pd1[i] = 1000 * 20.0 * i;
}
cout << "Memory addresses:\n" << " heap: " << pd1
<< " static: " << (void*) buffer << endl;
cout << "Memory contents:\n";
for (int i = 0; i < N; i++) {
cout << pd1[i] << " at " << &pd1[i] << "; ";
cout << pd2[i] << " at " << &pd2[i] << endl;
}
cout << "\nCalling new and placement new a second time:\n";
double *pd3, *pd4;
pd3 = new double[N];
pd4 = new (buffer) double[N];
for (i = 0; i < N; i++) {
pd4[i] = pd3[i] = 1000 * 40.0 * i;
}
cout << "Memory contents:\n";
for (int i = 0; i < N; i++) {
cout << pd3[i] << " at " << &pd3[i] << "; ";
cout << pd4[i] << " at " << &pd4[i] << endl;
}
cout << "\nCalling new and placement new a third time:\n";
delete [] pd1;
pd1 = new double[N];
pd2 = new (buffer + N * sizeof(double)) double[N];
for (i = 0; i < N; i++) {
pd2[i] = pd1[i] = 1000 * 60.0 * i;
}
cout << "Memory contents:\n";
for (i = 0; i < N; i++) {
cout << pd1[i] << " at " << &pd1[i] << "; ";
cout << pd2[i] << " at " << &pd2[i] << endl;
}
delete [] pd1;
delete [] pd3;
return 0;
}
| [
"nxmbest@qq.com"
] | nxmbest@qq.com |
faea32c79f37064f2f8f4b4f11d0e73d877473b5 | ee5824d3c041ce25f4f05dd9d95a30e0bbbabe69 | /1123.cpp | bd3951c159591022ee37c93f4871698e2cd98c38 | [] | no_license | Lisltria/PAT-Advanced-Level-Practice- | bcc3703116fd9387e4c406ef4b99b75ed94b7a06 | 529657db963bbd47cd7ad338a5f61b67e3bda9a2 | refs/heads/master | 2020-03-31T19:51:00.168002 | 2018-12-10T13:26:29 | 2018-12-10T13:26:29 | 152,514,436 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,314 | cpp | #include <iostream>
#include <vector>
#include <cstdio>
#include <queue>
using namespace std;
int insertQuery[20];
int N;
typedef struct node
{
int data;
node *lc, *rc;
} treeNode;
vector<treeNode> aTree;
int nodeCount = 0;
int ROOT=0;
int getDeepth(treeNode *r)
{
int l, rr;
if(r==NULL)
return 0;
l = getDeepth(r->lc);
rr = getDeepth(r->rc);
return (l > rr ? l : rr)+1;
}
treeNode *RotationRight(treeNode *r)
{
treeNode *temp = r->lc;
r->lc = temp->rc;
temp->rc = r;
return temp;
}
treeNode *RotationLeft(treeNode *r)
{
treeNode *temp = r -> rc;
r -> rc = temp->lc;
temp->lc = r;
return temp;
}
treeNode *RotationLeftRight(treeNode *r)
{
r->lc = RotationLeft(r->lc);
r = RotationRight(r);
return r;
}
treeNode *RotationRightLeft(treeNode *r)
{
r->rc = RotationRight(r -> rc);
r = RotationLeft(r);
return r;
}
treeNode *insertNode(int num,treeNode *r)
{
if(r==NULL)
{
r = new treeNode();
r->data = num;
return r;
}
else
{
if(num<r->data)
{
int ll, rr;
r->lc = insertNode(num, r->lc);
ll = getDeepth(r->lc);
rr = getDeepth(r->rc);
if(ll-rr>=2)
{
if(num<r->lc->data)
{
r = RotationRight(r);
}
else
{
r = RotationLeftRight(r);
}
}
}
else
{
int ll, rr;
r->rc = insertNode(num, r->rc);
ll = getDeepth(r->lc);
rr = getDeepth(r->rc);
if(rr-ll>=2)
{
if(num>r->rc->data)
{
r = RotationLeft(r);
}
else
{
r = RotationRightLeft(r);
}
}
}
return r;
}
}
int main(int argc, char const *argv[])
{
/* code */
cin >> N;
for (int i = 0; i < N; i++)
{
cin >> insertQuery[i];
}
treeNode *root;
root = NULL;
for (int i = 0; i < N; i++)
{
root = insertNode(insertQuery[i], root);
}
bool flag = false;
bool isComplete = true;
bool leftLeaf=false;
queue<treeNode> q;
q.push(*root);
while(!q.empty())
{
treeNode t = q.front();
q.pop();
if(flag)
cout << " ";
else
flag = true;
cout << t.data;
if(t.lc!=NULL)
q.push(*t.lc);
if(t.rc!=NULL)
q.push(*t.rc);
if(leftLeaf)
{
if(t.rc!=NULL||t.lc!=NULL)
{
isComplete = false;
}
}
if(t.rc==NULL||t.lc==NULL)
{
if(t.rc==NULL&&t.lc!=NULL)
{
leftLeaf = true;
}
else if(t.rc==NULL&&t.lc==NULL)
{
leftLeaf = true;
}
else if(t.rc!=NULL&&t.lc==NULL)
{
isComplete = false;
}
}
}
cout << endl;
if(isComplete)
cout << "YES" << endl;
else
cout << "NO" << endl;
return 0;
}
| [
"jingbang.liu@outlook.com"
] | jingbang.liu@outlook.com |
3ab827d704f8003e2f8c87c29ee6c1517ed37515 | a0f889f7bbe0117433c0a47069e466ad8b8f5323 | /gpu/occa/src/HSA.cpp | 550dc2c9a47ee907fdd5a9ec3d20d499d2ff06cc | [
"MIT"
] | permissive | hlim88/ATPESC18 | b8432915ed425b0bbc08df23db25bf2515dd5c30 | b7298cf38f8f79326adf81b8c154498cf9533631 | refs/heads/master | 2020-03-26T17:11:42.988656 | 2018-08-17T17:46:43 | 2018-08-17T17:46:43 | 145,147,190 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,050 | cpp | #if OCCA_HSA_ENABLED
#include "occa/HSA.hpp"
namespace occa {
//---[ Helper Functions ]-----------
namespace hsa {
bool initialized = false;
void init(){
if(initialized)
return;
// 1) make sure that HSA is initialized
OCCA_HSA_CHECK("Initializing HSA",
hsa_init());
initialized = true;
}
hsa_status_t getDeviceCount_h(hsa_agent_t agent, void *count_){
OCCA_CHECK(count_ != NULL,
"HSA : getDeviceCount argument [count] is NULL");
int &count = *((int*) count_);
++count;
return HSA_STATUS_SUCCESS;
}
hsa_status_t getDevice_h(hsa_agent_t agent, void *data_){
OCCA_CHECK(data_ != NULL,
"HSA : getDevice argument [data] is NULL");
getDeviceInfo_t &data = *((getDeviceInfo_t*) data_);
if(chosenID
// hsa_device_type_t deviceType;
// OCCA_HSA_CHECK(hsa_agent_get_info(agent,
// HSA_AGENT_INFO_DEVICE,
// &deviceType),
// "Getting device type");
hsa_agent_t *agent2 = (hsa_agent_t*) data;
if(type == (HSA_DEVICE_TYPE_CPU |
HSA_DEVICE_TYPE_GPU |
HSA_DEVICE_TYPE_DSP)
}
};
//==================================
//---[ Kernel ]---------------------
template <>
kernel_t<HSA>::kernel_t(){}
template <>
kernel_t<HSA>::kernel_t(const kernel_t<HSA> &k){}
template <>
kernel_t<HSA>& kernel_t<HSA>::operator = (const kernel_t<HSA> &k){}
template <>
kernel_t<HSA>::~kernel_t(){}
template <>
std::string kernel_t<HSA>::fixBinaryName(const std::string &filename){
return filename;
}
template <>
std::string kernel_t<HSA>::getCachedBinaryName(const std::string &filename,
kernelInfo &info_){}
template <>
kernel_t<HSA>* kernel_t<HSA>::buildFromSource(const std::string &filename,
const std::string &functionName,
const kernelInfo &info_){}
template <>
kernel_t<HSA>* kernel_t<HSA>::buildFromBinary(const std::string &filename,
const std::string &functionName){}
template <>
kernel_t<HSA>* kernel_t<HSA>::loadFromLibrary(const char *cache,
const std::string &functionName){}
template <>
uintptr_t kernel_t<HSA>::maximumInnerDimSize(){
}
template <>
int kernel_t<HSA>::preferredDimSize(){}
#include "operators/occaHSAKernelOperators.cpp"
template <>
void kernel_t<HSA>::free(){}
//==================================
//---[ Memory ]---------------------
template <>
memory_t<HSA>::memory_t(){}
template <>
memory_t<HSA>::memory_t(const memory_t<HSA> &m){}
template <>
memory_t<HSA>& memory_t<HSA>::operator = (const memory_t<HSA> &m){}
template <>
memory_t<HSA>::~memory_t(){}
template <>
void* memory_t<HSA>::getMemoryHandle(){ return NULL; }
template <>
void* memory_t<HSA>::getTextureHandle(){ return NULL; }
template <>
void memory_t<HSA>::copyFrom(const void *src,
const uintptr_t bytes,
const uintptr_t offset){}
template <>
void memory_t<HSA>::copyFrom(const memory_v *src,
const uintptr_t bytes,
const uintptr_t destOffset,
const uintptr_t srcOffset){}
template <>
void memory_t<HSA>::copyTo(void *dest,
const uintptr_t bytes,
const uintptr_t offset){}
template <>
void memory_t<HSA>::copyTo(memory_v *dest,
const uintptr_t bytes,
const uintptr_t destOffset,
const uintptr_t srcOffset){}
template <>
void memory_t<HSA>::asyncCopyFrom(const void *src,
const uintptr_t bytes,
const uintptr_t offset){}
template <>
void memory_t<HSA>::asyncCopyFrom(const memory_v *src,
const uintptr_t bytes,
const uintptr_t destOffset,
const uintptr_t srcOffset){}
template <>
void memory_t<HSA>::asyncCopyTo(void *dest,
const uintptr_t bytes,
const uintptr_t offset){}
template <>
void memory_t<HSA>::asyncCopyTo(memory_v *dest,
const uintptr_t bytes,
const uintptr_t destOffset,
const uintptr_t srcOffset){}
template <>
void memory_t<HSA>::mappedFree(){}
template <>
void memory_t<HSA>::mappedDetach(){}
template <>
void memory_t<HSA>::free(){}
template <>
void memory_t<HSA>::detach(){}
//==================================
//---[ Device ]---------------------
template <>
device_t<HSA>::device_t() {}
template <>
device_t<HSA>::device_t(const device_t<HSA> &d){}
template <>
device_t<HSA>& device_t<HSA>::operator = (const device_t<HSA> &d){}
template <>
void device_t<HSA>::setup(argInfoMap &aim){}
template <>
void device_t<HSA>::addOccaHeadersToInfo(kernelInfo &info_){
info_.mode = HSA;
}
template <>
std::string device_t<HSA>::getInfoSalt(const kernelInfo &info_){}
template <>
deviceIdentifier device_t<HSA>::getIdentifier() const {}
template <>
void device_t<HSA>::getEnvironmentVariables(){}
template <>
void device_t<HSA>::appendAvailableDevices(std::vector<device> &dList){}
template <>
void device_t<HSA>::setCompiler(const std::string &compiler_){}
template <>
void device_t<HSA>::setCompilerEnvScript(const std::string &compilerEnvScript_){}
template <>
void device_t<HSA>::setCompilerFlags(const std::string &compilerFlags_){}
template <>
void device_t<HSA>::flush(){}
template <>
void device_t<HSA>::finish(){}
template <>
bool device_t<HSA>::fakesUva(){}
template <>
void device_t<HSA>::waitFor(streamTag tag){}
template <>
stream_t device_t<HSA>::createStream(){}
template <>
void device_t<HSA>::freeStream(stream_t s){}
template <>
stream_t device_t<HSA>::wrapStream(void *handle_){}
template <>
streamTag device_t<HSA>::tagStream(){}
template <>
double device_t<HSA>::timeBetween(const streamTag &startTag, const streamTag &endTag){}
template <>
kernel_v* device_t<HSA>::buildKernelFromSource(const std::string &filename,
const std::string &functionName,
const kernelInfo &info_){}
template <>
kernel_v* device_t<HSA>::buildKernelFromBinary(const std::string &filename,
const std::string &functionName){}
template <>
void device_t<HSA>::cacheKernelInLibrary(const std::string &filename,
const std::string &functionName,
const kernelInfo &info_){}
template <>
kernel_v* device_t<HSA>::loadKernelFromLibrary(const char *cache,
const std::string &functionName){}
template <>
memory_v* device_t<HSA>::wrapMemory(void *handle_,
const uintptr_t bytes){}
template <>
memory_v* device_t<HSA>::wrapTexture(void *handle_,
const int dim, const occa::dim &dims,
occa::formatType type, const int permissions){}
template <>
memory_v* device_t<HSA>::malloc(const uintptr_t bytes,
void *src){}
template <>
memory_v* device_t<HSA>::textureAlloc(const int dim, const occa::dim &dims,
void *src,
occa::formatType type, const int permissions){}
template <>
memory_v* device_t<HSA>::mappedAlloc(const uintptr_t bytes,
void *src){}
template <>
void device_t<HSA>::free(){}
template <>
int device_t<HSA>::simdWidth(){}
//==================================
//---[ Error Handling ]-------------
std::string hsaError(hsa_status_t s){
switch(s){
case HSA_STATUS_SUCCESS: return "HSA_STATUS_SUCCESS";
case HSA_STATUS_INFO_BREAK: return "HSA_STATUS_INFO_BREAK";
case HSA_STATUS_ERROR: return "HSA_STATUS_ERROR";
case HSA_STATUS_ERROR_INVALID_ARGUMENT: return "HSA_STATUS_ERROR_INVALID_ARGUMENT";
case HSA_STATUS_ERROR_INVALID_QUEUE_CREATION: return "HSA_STATUS_ERROR_INVALID_QUEUE_CREATION";
case HSA_STATUS_ERROR_INVALID_ALLOCATION: return "HSA_STATUS_ERROR_INVALID_ALLOCATION";
case HSA_STATUS_ERROR_INVALID_AGENT: return "HSA_STATUS_ERROR_INVALID_AGENT";
case HSA_STATUS_ERROR_INVALID_REGION: return "HSA_STATUS_ERROR_INVALID_REGION";
case HSA_STATUS_ERROR_INVALID_SIGNAL: return "HSA_STATUS_ERROR_INVALID_SIGNAL";
case HSA_STATUS_ERROR_INVALID_QUEUE: return "HSA_STATUS_ERROR_INVALID_QUEUE";
case HSA_STATUS_ERROR_OUT_OF_RESOURCES: return "HSA_STATUS_ERROR_OUT_OF_RESOURCES";
case HSA_STATUS_ERROR_INVALID_PACKET_FORMAT: return "HSA_STATUS_ERROR_INVALID_PACKET_FORMAT";
case HSA_STATUS_ERROR_RESOURCE_FREE: return "HSA_STATUS_ERROR_RESOURCE_FREE";
case HSA_STATUS_ERROR_NOT_INITIALIZED: return "HSA_STATUS_ERROR_NOT_INITIALIZED";
case HSA_STATUS_ERROR_REFCOUNT_OVERFLOW: return "HSA_STATUS_ERROR_REFCOUNT_OVERFLOW";
case HSA_STATUS_ERROR_INCOMPATIBLE_ARGUMENTS: return "HSA_STATUS_ERROR_INCOMPATIBLE_ARGUMENTS";
case HSA_STATUS_ERROR_INVALID_INDEX: return "HSA_STATUS_ERROR_INVALID_INDEX";
case HSA_STATUS_ERROR_INVALID_ISA: return "HSA_STATUS_ERROR_INVALID_ISA";
case HSA_STATUS_ERROR_INVALID_ISA_NAME: return "HSA_STATUS_ERROR_INVALID_ISA_NAME";
case HSA_STATUS_ERROR_INVALID_CODE_OBJECT: return "HSA_STATUS_ERROR_INVALID_CODE_OBJECT";
case HSA_STATUS_ERROR_INVALID_EXECUTABLE: return "HSA_STATUS_ERROR_INVALID_EXECUTABLE";
case HSA_STATUS_ERROR_FROZEN_EXECUTABLE: return "HSA_STATUS_ERROR_FROZEN_EXECUTABLE";
case HSA_STATUS_ERROR_INVALID_SYMBOL_NAME: return "HSA_STATUS_ERROR_INVALID_SYMBOL_NAME";
case HSA_STATUS_ERROR_VARIABLE_ALREADY_DEFINED: return "HSA_STATUS_ERROR_VARIABLE_ALREADY_DEFINED";
case HSA_STATUS_ERROR_VARIABLE_UNDEFINED: return "HSA_STATUS_ERROR_VARIABLE_UNDEFINED";
default: return "UNKNOWN ERROR";
};
}
//==================================
};
#endif
| [
"hylim1988@gmail.com"
] | hylim1988@gmail.com |
d645de7c66445cfed2dcda44b46ae2955567de13 | 4db98caa3fc67688e8663a05bbf74e2abdd329db | /llvm-novt/lib/Passes/PassBuilder.cpp | 09ec16152f61203c0a769ad3431482477d3a4fa6 | [
"NCSA",
"LLVM-exception",
"Apache-2.0"
] | permissive | novt-vtable-less-compiler/novt-llvm | aacce412476787031ad824656f19056f07b24c9c | c3c2ba97943c4ffbe7f2a7a21aa4642502dcc1ce | refs/heads/master | 2022-10-01T12:58:39.316589 | 2022-09-29T14:42:41 | 2022-09-29T14:42:41 | 271,642,922 | 46 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 99,762 | cpp | //===- Parsing, selection, and construction of pass pipelines -------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
/// \file
///
/// This file provides the implementation of the PassBuilder based on our
/// static pass registry as well as related functionality. It also provides
/// helpers to aid in analyzing, debugging, and testing passes and pass
/// pipelines.
///
//===----------------------------------------------------------------------===//
#include <llvm/Transforms/IPO/NoVTAbiBuilder.h>
#include "llvm/Passes/PassBuilder.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/Analysis/AliasAnalysisEvaluator.h"
#include "llvm/Analysis/AssumptionCache.h"
#include "llvm/Analysis/BasicAliasAnalysis.h"
#include "llvm/Analysis/BlockFrequencyInfo.h"
#include "llvm/Analysis/BranchProbabilityInfo.h"
#include "llvm/Analysis/CFGPrinter.h"
#include "llvm/Analysis/CFLAndersAliasAnalysis.h"
#include "llvm/Analysis/CFLSteensAliasAnalysis.h"
#include "llvm/Analysis/CGSCCPassManager.h"
#include "llvm/Analysis/CallGraph.h"
#include "llvm/Analysis/DDG.h"
#include "llvm/Analysis/DemandedBits.h"
#include "llvm/Analysis/DependenceAnalysis.h"
#include "llvm/Analysis/DominanceFrontier.h"
#include "llvm/Analysis/GlobalsModRef.h"
#include "llvm/Analysis/IVUsers.h"
#include "llvm/Analysis/LazyCallGraph.h"
#include "llvm/Analysis/LazyValueInfo.h"
#include "llvm/Analysis/LoopAccessAnalysis.h"
#include "llvm/Analysis/LoopCacheAnalysis.h"
#include "llvm/Analysis/LoopInfo.h"
#include "llvm/Analysis/MemoryDependenceAnalysis.h"
#include "llvm/Analysis/MemorySSA.h"
#include "llvm/Analysis/ModuleSummaryAnalysis.h"
#include "llvm/Analysis/OptimizationRemarkEmitter.h"
#include "llvm/Analysis/PhiValues.h"
#include "llvm/Analysis/PostDominators.h"
#include "llvm/Analysis/ProfileSummaryInfo.h"
#include "llvm/Analysis/RegionInfo.h"
#include "llvm/Analysis/ScalarEvolution.h"
#include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
#include "llvm/Analysis/ScopedNoAliasAA.h"
#include "llvm/Analysis/StackSafetyAnalysis.h"
#include "llvm/Analysis/TargetLibraryInfo.h"
#include "llvm/Analysis/TargetTransformInfo.h"
#include "llvm/Analysis/TypeBasedAliasAnalysis.h"
#include "llvm/CodeGen/MachineModuleInfo.h"
#include "llvm/CodeGen/PreISelIntrinsicLowering.h"
#include "llvm/CodeGen/UnreachableBlockElim.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/IRPrintingPasses.h"
#include "llvm/IR/PassManager.h"
#include "llvm/IR/SafepointIRVerifier.h"
#include "llvm/IR/Verifier.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/FormatVariadic.h"
#include "llvm/Support/Regex.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Transforms/AggressiveInstCombine/AggressiveInstCombine.h"
#include "llvm/Transforms/IPO/AlwaysInliner.h"
#include "llvm/Transforms/IPO/ArgumentPromotion.h"
#include "llvm/Transforms/IPO/Attributor.h"
#include "llvm/Transforms/IPO/CalledValuePropagation.h"
#include "llvm/Transforms/IPO/ConstantMerge.h"
#include "llvm/Transforms/IPO/CrossDSOCFI.h"
#include "llvm/Transforms/IPO/DeadArgumentElimination.h"
#include "llvm/Transforms/IPO/ElimAvailExtern.h"
#include "llvm/Transforms/IPO/ForceFunctionAttrs.h"
#include "llvm/Transforms/IPO/FunctionAttrs.h"
#include "llvm/Transforms/IPO/FunctionImport.h"
#include "llvm/Transforms/IPO/GlobalDCE.h"
#include "llvm/Transforms/IPO/GlobalOpt.h"
#include "llvm/Transforms/IPO/GlobalSplit.h"
#include "llvm/Transforms/IPO/HotColdSplitting.h"
#include "llvm/Transforms/IPO/InferFunctionAttrs.h"
#include "llvm/Transforms/IPO/Inliner.h"
#include "llvm/Transforms/IPO/Internalize.h"
#include "llvm/Transforms/IPO/LowerTypeTests.h"
#include "llvm/Transforms/IPO/MergeFunctions.h"
#include "llvm/Transforms/IPO/PartialInlining.h"
#include "llvm/Transforms/IPO/SCCP.h"
#include "llvm/Transforms/IPO/SampleProfile.h"
#include "llvm/Transforms/IPO/StripDeadPrototypes.h"
#include "llvm/Transforms/IPO/SyntheticCountsPropagation.h"
#include "llvm/Transforms/IPO/WholeProgramDevirt.h"
#include "llvm/Transforms/InstCombine/InstCombine.h"
#include "llvm/Transforms/Instrumentation.h"
#include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
#include "llvm/Transforms/Instrumentation/BoundsChecking.h"
#include "llvm/Transforms/Instrumentation/CGProfile.h"
#include "llvm/Transforms/Instrumentation/ControlHeightReduction.h"
#include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
#include "llvm/Transforms/Instrumentation/HWAddressSanitizer.h"
#include "llvm/Transforms/Instrumentation/InstrOrderFile.h"
#include "llvm/Transforms/Instrumentation/InstrProfiling.h"
#include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
#include "llvm/Transforms/Instrumentation/PGOInstrumentation.h"
#include "llvm/Transforms/Instrumentation/PoisonChecking.h"
#include "llvm/Transforms/Instrumentation/SanitizerCoverage.h"
#include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
#include "llvm/Transforms/Scalar/ADCE.h"
#include "llvm/Transforms/Scalar/AlignmentFromAssumptions.h"
#include "llvm/Transforms/Scalar/BDCE.h"
#include "llvm/Transforms/Scalar/CallSiteSplitting.h"
#include "llvm/Transforms/Scalar/ConstantHoisting.h"
#include "llvm/Transforms/Scalar/CorrelatedValuePropagation.h"
#include "llvm/Transforms/Scalar/DCE.h"
#include "llvm/Transforms/Scalar/DeadStoreElimination.h"
#include "llvm/Transforms/Scalar/DivRemPairs.h"
#include "llvm/Transforms/Scalar/EarlyCSE.h"
#include "llvm/Transforms/Scalar/Float2Int.h"
#include "llvm/Transforms/Scalar/GVN.h"
#include "llvm/Transforms/Scalar/GuardWidening.h"
#include "llvm/Transforms/Scalar/IVUsersPrinter.h"
#include "llvm/Transforms/Scalar/IndVarSimplify.h"
#include "llvm/Transforms/Scalar/InductiveRangeCheckElimination.h"
#include "llvm/Transforms/Scalar/InstSimplifyPass.h"
#include "llvm/Transforms/Scalar/JumpThreading.h"
#include "llvm/Transforms/Scalar/LICM.h"
#include "llvm/Transforms/Scalar/LoopAccessAnalysisPrinter.h"
#include "llvm/Transforms/Scalar/LoopDataPrefetch.h"
#include "llvm/Transforms/Scalar/LoopDeletion.h"
#include "llvm/Transforms/Scalar/LoopDistribute.h"
#include "llvm/Transforms/Scalar/LoopFuse.h"
#include "llvm/Transforms/Scalar/LoopIdiomRecognize.h"
#include "llvm/Transforms/Scalar/LoopInstSimplify.h"
#include "llvm/Transforms/Scalar/LoopLoadElimination.h"
#include "llvm/Transforms/Scalar/LoopPassManager.h"
#include "llvm/Transforms/Scalar/LoopPredication.h"
#include "llvm/Transforms/Scalar/LoopRotation.h"
#include "llvm/Transforms/Scalar/LoopSimplifyCFG.h"
#include "llvm/Transforms/Scalar/LoopSink.h"
#include "llvm/Transforms/Scalar/LoopStrengthReduce.h"
#include "llvm/Transforms/Scalar/LoopUnrollAndJamPass.h"
#include "llvm/Transforms/Scalar/LoopUnrollPass.h"
#include "llvm/Transforms/Scalar/LowerAtomic.h"
#include "llvm/Transforms/Scalar/LowerConstantIntrinsics.h"
#include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h"
#include "llvm/Transforms/Scalar/LowerGuardIntrinsic.h"
#include "llvm/Transforms/Scalar/LowerMatrixIntrinsics.h"
#include "llvm/Transforms/Scalar/LowerWidenableCondition.h"
#include "llvm/Transforms/Scalar/MakeGuardsExplicit.h"
#include "llvm/Transforms/Scalar/MemCpyOptimizer.h"
#include "llvm/Transforms/Scalar/MergeICmps.h"
#include "llvm/Transforms/Scalar/MergedLoadStoreMotion.h"
#include "llvm/Transforms/Scalar/NaryReassociate.h"
#include "llvm/Transforms/Scalar/NewGVN.h"
#include "llvm/Transforms/Scalar/PartiallyInlineLibCalls.h"
#include "llvm/Transforms/Scalar/Reassociate.h"
#include "llvm/Transforms/Scalar/RewriteStatepointsForGC.h"
#include "llvm/Transforms/Scalar/SCCP.h"
#include "llvm/Transforms/Scalar/SROA.h"
#include "llvm/Transforms/Scalar/Scalarizer.h"
#include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
#include "llvm/Transforms/Scalar/SimplifyCFG.h"
#include "llvm/Transforms/Scalar/Sink.h"
#include "llvm/Transforms/Scalar/SpeculateAroundPHIs.h"
#include "llvm/Transforms/Scalar/SpeculativeExecution.h"
#include "llvm/Transforms/Scalar/TailRecursionElimination.h"
#include "llvm/Transforms/Scalar/WarnMissedTransforms.h"
#include "llvm/Transforms/Utils/AddDiscriminators.h"
#include "llvm/Transforms/Utils/BreakCriticalEdges.h"
#include "llvm/Transforms/Utils/CanonicalizeAliases.h"
#include "llvm/Transforms/Utils/EntryExitInstrumenter.h"
#include "llvm/Transforms/Utils/InjectTLIMappings.h"
#include "llvm/Transforms/Utils/LCSSA.h"
#include "llvm/Transforms/Utils/LibCallsShrinkWrap.h"
#include "llvm/Transforms/Utils/LoopSimplify.h"
#include "llvm/Transforms/Utils/LowerInvoke.h"
#include "llvm/Transforms/Utils/Mem2Reg.h"
#include "llvm/Transforms/Utils/NameAnonGlobals.h"
#include "llvm/Transforms/Utils/SymbolRewriter.h"
#include "llvm/Transforms/Vectorize/LoadStoreVectorizer.h"
#include "llvm/Transforms/Vectorize/LoopVectorize.h"
#include "llvm/Transforms/Vectorize/SLPVectorizer.h"
using namespace llvm;
static cl::opt<unsigned> MaxDevirtIterations("pm-max-devirt-iterations",
cl::ReallyHidden, cl::init(4));
static cl::opt<bool>
RunPartialInlining("enable-npm-partial-inlining", cl::init(false),
cl::Hidden, cl::ZeroOrMore,
cl::desc("Run Partial inlinining pass"));
static cl::opt<int> PreInlineThreshold(
"npm-preinline-threshold", cl::Hidden, cl::init(75), cl::ZeroOrMore,
cl::desc("Control the amount of inlining in pre-instrumentation inliner "
"(default = 75)"));
static cl::opt<bool>
RunNewGVN("enable-npm-newgvn", cl::init(false),
cl::Hidden, cl::ZeroOrMore,
cl::desc("Run NewGVN instead of GVN"));
static cl::opt<bool> EnableGVNHoist(
"enable-npm-gvn-hoist", cl::init(false), cl::Hidden,
cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
static cl::opt<bool> EnableGVNSink(
"enable-npm-gvn-sink", cl::init(false), cl::Hidden,
cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
static cl::opt<bool> EnableUnrollAndJam(
"enable-npm-unroll-and-jam", cl::init(false), cl::Hidden,
cl::desc("Enable the Unroll and Jam pass for the new PM (default = off)"));
static cl::opt<bool> EnableSyntheticCounts(
"enable-npm-synthetic-counts", cl::init(false), cl::Hidden, cl::ZeroOrMore,
cl::desc("Run synthetic function entry count generation "
"pass"));
static const Regex DefaultAliasRegex(
"^(default|thinlto-pre-link|thinlto|lto-pre-link|lto)<(O[0123sz])>$");
// This option is used in simplifying testing SampleFDO optimizations for
// profile loading.
static cl::opt<bool>
EnableCHR("enable-chr-npm", cl::init(true), cl::Hidden,
cl::desc("Enable control height reduction optimization (CHR)"));
PipelineTuningOptions::PipelineTuningOptions() {
LoopInterleaving = EnableLoopInterleaving;
LoopVectorization = EnableLoopVectorization;
SLPVectorization = RunSLPVectorization;
LoopUnrolling = true;
ForgetAllSCEVInLoopUnroll = ForgetSCEVInLoopUnroll;
LicmMssaOptCap = SetLicmMssaOptCap;
LicmMssaNoAccForPromotionCap = SetLicmMssaNoAccForPromotionCap;
}
extern cl::opt<bool> EnableHotColdSplit;
extern cl::opt<bool> EnableOrderFileInstrumentation;
extern cl::opt<bool> FlattenedProfileUsed;
static bool isOptimizingForSize(PassBuilder::OptimizationLevel Level) {
switch (Level) {
case PassBuilder::O0:
case PassBuilder::O1:
case PassBuilder::O2:
case PassBuilder::O3:
return false;
case PassBuilder::Os:
case PassBuilder::Oz:
return true;
}
llvm_unreachable("Invalid optimization level!");
}
namespace {
/// No-op module pass which does nothing.
struct NoOpModulePass {
PreservedAnalyses run(Module &M, ModuleAnalysisManager &) {
return PreservedAnalyses::all();
}
static StringRef name() { return "NoOpModulePass"; }
};
/// No-op module analysis.
class NoOpModuleAnalysis : public AnalysisInfoMixin<NoOpModuleAnalysis> {
friend AnalysisInfoMixin<NoOpModuleAnalysis>;
static AnalysisKey Key;
public:
struct Result {};
Result run(Module &, ModuleAnalysisManager &) { return Result(); }
static StringRef name() { return "NoOpModuleAnalysis"; }
};
/// No-op CGSCC pass which does nothing.
struct NoOpCGSCCPass {
PreservedAnalyses run(LazyCallGraph::SCC &C, CGSCCAnalysisManager &,
LazyCallGraph &, CGSCCUpdateResult &UR) {
return PreservedAnalyses::all();
}
static StringRef name() { return "NoOpCGSCCPass"; }
};
/// No-op CGSCC analysis.
class NoOpCGSCCAnalysis : public AnalysisInfoMixin<NoOpCGSCCAnalysis> {
friend AnalysisInfoMixin<NoOpCGSCCAnalysis>;
static AnalysisKey Key;
public:
struct Result {};
Result run(LazyCallGraph::SCC &, CGSCCAnalysisManager &, LazyCallGraph &G) {
return Result();
}
static StringRef name() { return "NoOpCGSCCAnalysis"; }
};
/// No-op function pass which does nothing.
struct NoOpFunctionPass {
PreservedAnalyses run(Function &F, FunctionAnalysisManager &) {
return PreservedAnalyses::all();
}
static StringRef name() { return "NoOpFunctionPass"; }
};
/// No-op function analysis.
class NoOpFunctionAnalysis : public AnalysisInfoMixin<NoOpFunctionAnalysis> {
friend AnalysisInfoMixin<NoOpFunctionAnalysis>;
static AnalysisKey Key;
public:
struct Result {};
Result run(Function &, FunctionAnalysisManager &) { return Result(); }
static StringRef name() { return "NoOpFunctionAnalysis"; }
};
/// No-op loop pass which does nothing.
struct NoOpLoopPass {
PreservedAnalyses run(Loop &L, LoopAnalysisManager &,
LoopStandardAnalysisResults &, LPMUpdater &) {
return PreservedAnalyses::all();
}
static StringRef name() { return "NoOpLoopPass"; }
};
/// No-op loop analysis.
class NoOpLoopAnalysis : public AnalysisInfoMixin<NoOpLoopAnalysis> {
friend AnalysisInfoMixin<NoOpLoopAnalysis>;
static AnalysisKey Key;
public:
struct Result {};
Result run(Loop &, LoopAnalysisManager &, LoopStandardAnalysisResults &) {
return Result();
}
static StringRef name() { return "NoOpLoopAnalysis"; }
};
AnalysisKey NoOpModuleAnalysis::Key;
AnalysisKey NoOpCGSCCAnalysis::Key;
AnalysisKey NoOpFunctionAnalysis::Key;
AnalysisKey NoOpLoopAnalysis::Key;
} // End anonymous namespace.
void PassBuilder::invokePeepholeEPCallbacks(
FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
for (auto &C : PeepholeEPCallbacks)
C(FPM, Level);
}
void PassBuilder::registerModuleAnalyses(ModuleAnalysisManager &MAM) {
#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
MAM.registerPass([&] { return CREATE_PASS; });
#include "PassRegistry.def"
for (auto &C : ModuleAnalysisRegistrationCallbacks)
C(MAM);
}
void PassBuilder::registerCGSCCAnalyses(CGSCCAnalysisManager &CGAM) {
#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
CGAM.registerPass([&] { return CREATE_PASS; });
#include "PassRegistry.def"
for (auto &C : CGSCCAnalysisRegistrationCallbacks)
C(CGAM);
}
void PassBuilder::registerFunctionAnalyses(FunctionAnalysisManager &FAM) {
#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
FAM.registerPass([&] { return CREATE_PASS; });
#include "PassRegistry.def"
for (auto &C : FunctionAnalysisRegistrationCallbacks)
C(FAM);
}
void PassBuilder::registerLoopAnalyses(LoopAnalysisManager &LAM) {
#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
LAM.registerPass([&] { return CREATE_PASS; });
#include "PassRegistry.def"
for (auto &C : LoopAnalysisRegistrationCallbacks)
C(LAM);
}
FunctionPassManager
PassBuilder::buildFunctionSimplificationPipeline(OptimizationLevel Level,
ThinLTOPhase Phase,
bool DebugLogging) {
assert(Level != O0 && "Must request optimizations!");
FunctionPassManager FPM(DebugLogging);
// Form SSA out of local memory accesses after breaking apart aggregates into
// scalars.
FPM.addPass(SROA());
// Catch trivial redundancies
FPM.addPass(EarlyCSEPass(true /* Enable mem-ssa. */));
// Hoisting of scalars and load expressions.
if (Level > O1) {
if (EnableGVNHoist)
FPM.addPass(GVNHoistPass());
// Global value numbering based sinking.
if (EnableGVNSink) {
FPM.addPass(GVNSinkPass());
FPM.addPass(SimplifyCFGPass());
}
}
// Speculative execution if the target has divergent branches; otherwise nop.
if (Level > O1) {
FPM.addPass(SpeculativeExecutionPass());
// Optimize based on known information about branches, and cleanup afterward.
FPM.addPass(JumpThreadingPass());
FPM.addPass(CorrelatedValuePropagationPass());
}
FPM.addPass(SimplifyCFGPass());
if (Level == O3)
FPM.addPass(AggressiveInstCombinePass());
FPM.addPass(InstCombinePass());
if (!isOptimizingForSize(Level))
FPM.addPass(LibCallsShrinkWrapPass());
invokePeepholeEPCallbacks(FPM, Level);
// For PGO use pipeline, try to optimize memory intrinsics such as memcpy
// using the size value profile. Don't perform this when optimizing for size.
if (PGOOpt && PGOOpt->Action == PGOOptions::IRUse &&
!isOptimizingForSize(Level) && Level > O1)
FPM.addPass(PGOMemOPSizeOpt());
// TODO: Investigate the cost/benefit of tail call elimination on debugging.
if (Level > O1)
FPM.addPass(TailCallElimPass());
FPM.addPass(SimplifyCFGPass());
// Form canonically associated expression trees, and simplify the trees using
// basic mathematical properties. For example, this will form (nearly)
// minimal multiplication trees.
FPM.addPass(ReassociatePass());
// Add the primary loop simplification pipeline.
// FIXME: Currently this is split into two loop pass pipelines because we run
// some function passes in between them. These can and should be removed
// and/or replaced by scheduling the loop pass equivalents in the correct
// positions. But those equivalent passes aren't powerful enough yet.
// Specifically, `SimplifyCFGPass` and `InstCombinePass` are currently still
// used. We have `LoopSimplifyCFGPass` which isn't yet powerful enough yet to
// fully replace `SimplifyCFGPass`, and the closest to the other we have is
// `LoopInstSimplify`.
LoopPassManager LPM1(DebugLogging), LPM2(DebugLogging);
// Simplify the loop body. We do this initially to clean up after other loop
// passes run, either when iterating on a loop or on inner loops with
// implications on the outer loop.
LPM1.addPass(LoopInstSimplifyPass());
LPM1.addPass(LoopSimplifyCFGPass());
// Rotate Loop - disable header duplication at -Oz
LPM1.addPass(LoopRotatePass(Level != Oz));
// TODO: Investigate promotion cap for O1.
LPM1.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap));
LPM1.addPass(SimpleLoopUnswitchPass());
LPM2.addPass(IndVarSimplifyPass());
LPM2.addPass(LoopIdiomRecognizePass());
for (auto &C : LateLoopOptimizationsEPCallbacks)
C(LPM2, Level);
LPM2.addPass(LoopDeletionPass());
// Do not enable unrolling in PreLinkThinLTO phase during sample PGO
// because it changes IR to makes profile annotation in back compile
// inaccurate.
if ((Phase != ThinLTOPhase::PreLink || !PGOOpt ||
PGOOpt->Action != PGOOptions::SampleUse) &&
PTO.LoopUnrolling)
LPM2.addPass(LoopFullUnrollPass(Level, /*OnlyWhenForced=*/false,
PTO.ForgetAllSCEVInLoopUnroll));
for (auto &C : LoopOptimizerEndEPCallbacks)
C(LPM2, Level);
// We provide the opt remark emitter pass for LICM to use. We only need to do
// this once as it is immutable.
FPM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
FPM.addPass(createFunctionToLoopPassAdaptor(
std::move(LPM1), EnableMSSALoopDependency, DebugLogging));
FPM.addPass(SimplifyCFGPass());
FPM.addPass(InstCombinePass());
// The loop passes in LPM2 (IndVarSimplifyPass, LoopIdiomRecognizePass,
// LoopDeletionPass and LoopFullUnrollPass) do not preserve MemorySSA.
// *All* loop passes must preserve it, in order to be able to use it.
FPM.addPass(createFunctionToLoopPassAdaptor(
std::move(LPM2), /*UseMemorySSA=*/false, DebugLogging));
// Delete small array after loop unroll.
FPM.addPass(SROA());
// Eliminate redundancies.
if (Level != O1) {
// These passes add substantial compile time so skip them at O1.
FPM.addPass(MergedLoadStoreMotionPass());
if (RunNewGVN)
FPM.addPass(NewGVNPass());
else
FPM.addPass(GVN());
}
// Specially optimize memory movement as it doesn't look like dataflow in SSA.
FPM.addPass(MemCpyOptPass());
// Sparse conditional constant propagation.
// FIXME: It isn't clear why we do this *after* loop passes rather than
// before...
FPM.addPass(SCCPPass());
// Delete dead bit computations (instcombine runs after to fold away the dead
// computations, and then ADCE will run later to exploit any new DCE
// opportunities that creates).
FPM.addPass(BDCEPass());
// Run instcombine after redundancy and dead bit elimination to exploit
// opportunities opened up by them.
FPM.addPass(InstCombinePass());
invokePeepholeEPCallbacks(FPM, Level);
// Re-consider control flow based optimizations after redundancy elimination,
// redo DCE, etc.
if (Level > O1) {
FPM.addPass(JumpThreadingPass());
FPM.addPass(CorrelatedValuePropagationPass());
FPM.addPass(DSEPass());
FPM.addPass(createFunctionToLoopPassAdaptor(
LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap),
EnableMSSALoopDependency, DebugLogging));
}
for (auto &C : ScalarOptimizerLateEPCallbacks)
C(FPM, Level);
// Finally, do an expensive DCE pass to catch all the dead code exposed by
// the simplifications and basic cleanup after all the simplifications.
// TODO: Investigate if this is too expensive.
FPM.addPass(ADCEPass());
FPM.addPass(SimplifyCFGPass());
FPM.addPass(InstCombinePass());
invokePeepholeEPCallbacks(FPM, Level);
if (EnableCHR && Level == O3 && PGOOpt &&
(PGOOpt->Action == PGOOptions::IRUse ||
PGOOpt->Action == PGOOptions::SampleUse))
FPM.addPass(ControlHeightReductionPass());
return FPM;
}
void PassBuilder::addPGOInstrPasses(ModulePassManager &MPM, bool DebugLogging,
PassBuilder::OptimizationLevel Level,
bool RunProfileGen, bool IsCS,
std::string ProfileFile,
std::string ProfileRemappingFile) {
assert(Level != O0 && "Not expecting O0 here!");
// Generally running simplification passes and the inliner with an high
// threshold results in smaller executables, but there may be cases where
// the size grows, so let's be conservative here and skip this simplification
// at -Os/Oz. We will not do this inline for context sensistive PGO (when
// IsCS is true).
if (!isOptimizingForSize(Level) && !IsCS) {
InlineParams IP;
IP.DefaultThreshold = PreInlineThreshold;
// FIXME: The hint threshold has the same value used by the regular inliner.
// This should probably be lowered after performance testing.
// FIXME: this comment is cargo culted from the old pass manager, revisit).
IP.HintThreshold = 325;
CGSCCPassManager CGPipeline(DebugLogging);
CGPipeline.addPass(InlinerPass(IP));
FunctionPassManager FPM;
FPM.addPass(SROA());
FPM.addPass(EarlyCSEPass()); // Catch trivial redundancies.
FPM.addPass(SimplifyCFGPass()); // Merge & remove basic blocks.
FPM.addPass(InstCombinePass()); // Combine silly sequences.
invokePeepholeEPCallbacks(FPM, Level);
CGPipeline.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPipeline)));
// Delete anything that is now dead to make sure that we don't instrument
// dead code. Instrumentation can end up keeping dead code around and
// dramatically increase code size.
MPM.addPass(GlobalDCEPass());
}
if (!RunProfileGen) {
assert(!ProfileFile.empty() && "Profile use expecting a profile file!");
MPM.addPass(PGOInstrumentationUse(ProfileFile, ProfileRemappingFile, IsCS));
// Cache ProfileSummaryAnalysis once to avoid the potential need to insert
// RequireAnalysisPass for PSI before subsequent non-module passes.
MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
return;
}
// Perform PGO instrumentation.
MPM.addPass(PGOInstrumentationGen(IsCS));
FunctionPassManager FPM;
FPM.addPass(createFunctionToLoopPassAdaptor(
LoopRotatePass(), EnableMSSALoopDependency, DebugLogging));
MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
// Add the profile lowering pass.
InstrProfOptions Options;
if (!ProfileFile.empty())
Options.InstrProfileOutput = ProfileFile;
// Do counter promotion at Level greater than O0.
Options.DoCounterPromotion = true;
Options.UseBFIInPromotion = IsCS;
MPM.addPass(InstrProfiling(Options, IsCS));
}
void PassBuilder::addPGOInstrPassesForO0(ModulePassManager &MPM,
bool DebugLogging, bool RunProfileGen,
bool IsCS, std::string ProfileFile,
std::string ProfileRemappingFile) {
if (!RunProfileGen) {
assert(!ProfileFile.empty() && "Profile use expecting a profile file!");
MPM.addPass(PGOInstrumentationUse(ProfileFile, ProfileRemappingFile, IsCS));
// Cache ProfileSummaryAnalysis once to avoid the potential need to insert
// RequireAnalysisPass for PSI before subsequent non-module passes.
MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
return;
}
// Perform PGO instrumentation.
MPM.addPass(PGOInstrumentationGen(IsCS));
// Add the profile lowering pass.
InstrProfOptions Options;
if (!ProfileFile.empty())
Options.InstrProfileOutput = ProfileFile;
// Do not do counter promotion at O0.
Options.DoCounterPromotion = false;
Options.UseBFIInPromotion = IsCS;
MPM.addPass(InstrProfiling(Options, IsCS));
}
static InlineParams
getInlineParamsFromOptLevel(PassBuilder::OptimizationLevel Level) {
auto O3 = PassBuilder::O3;
unsigned OptLevel = Level > O3 ? 2 : Level;
unsigned SizeLevel = Level > O3 ? Level - O3 : 0;
return getInlineParams(OptLevel, SizeLevel);
}
ModulePassManager
PassBuilder::buildModuleSimplificationPipeline(OptimizationLevel Level,
ThinLTOPhase Phase,
bool DebugLogging) {
ModulePassManager MPM(DebugLogging);
bool HasSampleProfile = PGOOpt && (PGOOpt->Action == PGOOptions::SampleUse);
// In ThinLTO mode, when flattened profile is used, all the available
// profile information will be annotated in PreLink phase so there is
// no need to load the profile again in PostLink.
bool LoadSampleProfile =
HasSampleProfile &&
!(FlattenedProfileUsed && Phase == ThinLTOPhase::PostLink);
// During the ThinLTO backend phase we perform early indirect call promotion
// here, before globalopt. Otherwise imported available_externally functions
// look unreferenced and are removed. If we are going to load the sample
// profile then defer until later.
// TODO: See if we can move later and consolidate with the location where
// we perform ICP when we are loading a sample profile.
// TODO: We pass HasSampleProfile (whether there was a sample profile file
// passed to the compile) to the SamplePGO flag of ICP. This is used to
// determine whether the new direct calls are annotated with prof metadata.
// Ideally this should be determined from whether the IR is annotated with
// sample profile, and not whether the a sample profile was provided on the
// command line. E.g. for flattened profiles where we will not be reloading
// the sample profile in the ThinLTO backend, we ideally shouldn't have to
// provide the sample profile file.
if (Phase == ThinLTOPhase::PostLink && !LoadSampleProfile)
MPM.addPass(PGOIndirectCallPromotion(true /* InLTO */, HasSampleProfile));
// Do basic inference of function attributes from known properties of system
// libraries and other oracles.
MPM.addPass(InferFunctionAttrsPass());
// Create an early function pass manager to cleanup the output of the
// frontend.
FunctionPassManager EarlyFPM(DebugLogging);
EarlyFPM.addPass(SimplifyCFGPass());
EarlyFPM.addPass(SROA());
EarlyFPM.addPass(EarlyCSEPass());
EarlyFPM.addPass(LowerExpectIntrinsicPass());
if (Level == O3)
EarlyFPM.addPass(CallSiteSplittingPass());
// In SamplePGO ThinLTO backend, we need instcombine before profile annotation
// to convert bitcast to direct calls so that they can be inlined during the
// profile annotation prepration step.
// More details about SamplePGO design can be found in:
// https://research.google.com/pubs/pub45290.html
// FIXME: revisit how SampleProfileLoad/Inliner/ICP is structured.
if (LoadSampleProfile)
EarlyFPM.addPass(InstCombinePass());
MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
if (LoadSampleProfile) {
// Annotate sample profile right after early FPM to ensure freshness of
// the debug info.
MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile,
PGOOpt->ProfileRemappingFile,
Phase == ThinLTOPhase::PreLink));
// Cache ProfileSummaryAnalysis once to avoid the potential need to insert
// RequireAnalysisPass for PSI before subsequent non-module passes.
MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
// Do not invoke ICP in the ThinLTOPrelink phase as it makes it hard
// for the profile annotation to be accurate in the ThinLTO backend.
if (Phase != ThinLTOPhase::PreLink)
// We perform early indirect call promotion here, before globalopt.
// This is important for the ThinLTO backend phase because otherwise
// imported available_externally functions look unreferenced and are
// removed.
MPM.addPass(PGOIndirectCallPromotion(Phase == ThinLTOPhase::PostLink,
true /* SamplePGO */));
}
// Interprocedural constant propagation now that basic cleanup has occurred
// and prior to optimizing globals.
// FIXME: This position in the pipeline hasn't been carefully considered in
// years, it should be re-analyzed.
MPM.addPass(IPSCCPPass());
// Attach metadata to indirect call sites indicating the set of functions
// they may target at run-time. This should follow IPSCCP.
MPM.addPass(CalledValuePropagationPass());
// Optimize globals to try and fold them into constants.
MPM.addPass(GlobalOptPass());
// Promote any localized globals to SSA registers.
// FIXME: Should this instead by a run of SROA?
// FIXME: We should probably run instcombine and simplify-cfg afterward to
// delete control flows that are dead once globals have been folded to
// constants.
MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
// Remove any dead arguments exposed by cleanups and constand folding
// globals.
MPM.addPass(DeadArgumentEliminationPass());
// Create a small function pass pipeline to cleanup after all the global
// optimizations.
FunctionPassManager GlobalCleanupPM(DebugLogging);
GlobalCleanupPM.addPass(InstCombinePass());
invokePeepholeEPCallbacks(GlobalCleanupPM, Level);
GlobalCleanupPM.addPass(SimplifyCFGPass());
MPM.addPass(createModuleToFunctionPassAdaptor(std::move(GlobalCleanupPM)));
// Add all the requested passes for instrumentation PGO, if requested.
if (PGOOpt && Phase != ThinLTOPhase::PostLink &&
(PGOOpt->Action == PGOOptions::IRInstr ||
PGOOpt->Action == PGOOptions::IRUse)) {
addPGOInstrPasses(MPM, DebugLogging, Level,
/* RunProfileGen */ PGOOpt->Action == PGOOptions::IRInstr,
/* IsCS */ false, PGOOpt->ProfileFile,
PGOOpt->ProfileRemappingFile);
MPM.addPass(PGOIndirectCallPromotion(false, false));
}
if (PGOOpt && Phase != ThinLTOPhase::PostLink &&
PGOOpt->CSAction == PGOOptions::CSIRInstr)
MPM.addPass(PGOInstrumentationGenCreateVar(PGOOpt->CSProfileGenFile));
// Synthesize function entry counts for non-PGO compilation.
if (EnableSyntheticCounts && !PGOOpt)
MPM.addPass(SyntheticCountsPropagation());
// Require the GlobalsAA analysis for the module so we can query it within
// the CGSCC pipeline.
MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
// Require the ProfileSummaryAnalysis for the module so we can query it within
// the inliner pass.
MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
// Now begin the main postorder CGSCC pipeline.
// FIXME: The current CGSCC pipeline has its origins in the legacy pass
// manager and trying to emulate its precise behavior. Much of this doesn't
// make a lot of sense and we should revisit the core CGSCC structure.
CGSCCPassManager MainCGPipeline(DebugLogging);
// Note: historically, the PruneEH pass was run first to deduce nounwind and
// generally clean up exception handling overhead. It isn't clear this is
// valuable as the inliner doesn't currently care whether it is inlining an
// invoke or a call.
// Run the inliner first. The theory is that we are walking bottom-up and so
// the callees have already been fully optimized, and we want to inline them
// into the callers so that our optimizations can reflect that.
// For PreLinkThinLTO pass, we disable hot-caller heuristic for sample PGO
// because it makes profile annotation in the backend inaccurate.
InlineParams IP = getInlineParamsFromOptLevel(Level);
if (Phase == ThinLTOPhase::PreLink && PGOOpt &&
PGOOpt->Action == PGOOptions::SampleUse)
IP.HotCallSiteThreshold = 0;
MainCGPipeline.addPass(InlinerPass(IP));
// Now deduce any function attributes based in the current code.
MainCGPipeline.addPass(PostOrderFunctionAttrsPass());
// When at O3 add argument promotion to the pass pipeline.
// FIXME: It isn't at all clear why this should be limited to O3.
if (Level == O3)
MainCGPipeline.addPass(ArgumentPromotionPass());
// Lastly, add the core function simplification pipeline nested inside the
// CGSCC walk.
MainCGPipeline.addPass(createCGSCCToFunctionPassAdaptor(
buildFunctionSimplificationPipeline(Level, Phase, DebugLogging)));
for (auto &C : CGSCCOptimizerLateEPCallbacks)
C(MainCGPipeline, Level);
// We wrap the CGSCC pipeline in a devirtualization repeater. This will try
// to detect when we devirtualize indirect calls and iterate the SCC passes
// in that case to try and catch knock-on inlining or function attrs
// opportunities. Then we add it to the module pipeline by walking the SCCs
// in postorder (or bottom-up).
MPM.addPass(
createModuleToPostOrderCGSCCPassAdaptor(createDevirtSCCRepeatedPass(
std::move(MainCGPipeline), MaxDevirtIterations)));
return MPM;
}
ModulePassManager PassBuilder::buildModuleOptimizationPipeline(
OptimizationLevel Level, bool DebugLogging, bool LTOPreLink) {
ModulePassManager MPM(DebugLogging);
// Optimize globals now that the module is fully simplified.
MPM.addPass(GlobalOptPass());
MPM.addPass(GlobalDCEPass());
// Run partial inlining pass to partially inline functions that have
// large bodies.
if (RunPartialInlining)
MPM.addPass(PartialInlinerPass());
// Remove avail extern fns and globals definitions since we aren't compiling
// an object file for later LTO. For LTO we want to preserve these so they
// are eligible for inlining at link-time. Note if they are unreferenced they
// will be removed by GlobalDCE later, so this only impacts referenced
// available externally globals. Eventually they will be suppressed during
// codegen, but eliminating here enables more opportunity for GlobalDCE as it
// may make globals referenced by available external functions dead and saves
// running remaining passes on the eliminated functions. These should be
// preserved during prelinking for link-time inlining decisions.
if (!LTOPreLink)
MPM.addPass(EliminateAvailableExternallyPass());
if (EnableOrderFileInstrumentation)
MPM.addPass(InstrOrderFilePass());
// Do RPO function attribute inference across the module to forward-propagate
// attributes where applicable.
// FIXME: Is this really an optimization rather than a canonicalization?
MPM.addPass(ReversePostOrderFunctionAttrsPass());
// Do a post inline PGO instrumentation and use pass. This is a context
// sensitive PGO pass. We don't want to do this in LTOPreLink phrase as
// cross-module inline has not been done yet. The context sensitive
// instrumentation is after all the inlines are done.
if (!LTOPreLink && PGOOpt) {
if (PGOOpt->CSAction == PGOOptions::CSIRInstr)
addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ true,
/* IsCS */ true, PGOOpt->CSProfileGenFile,
PGOOpt->ProfileRemappingFile);
else if (PGOOpt->CSAction == PGOOptions::CSIRUse)
addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ false,
/* IsCS */ true, PGOOpt->ProfileFile,
PGOOpt->ProfileRemappingFile);
}
// Re-require GloblasAA here prior to function passes. This is particularly
// useful as the above will have inlined, DCE'ed, and function-attr
// propagated everything. We should at this point have a reasonably minimal
// and richly annotated call graph. By computing aliasing and mod/ref
// information for all local globals here, the late loop passes and notably
// the vectorizer will be able to use them to help recognize vectorizable
// memory operations.
MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
FunctionPassManager OptimizePM(DebugLogging);
OptimizePM.addPass(Float2IntPass());
OptimizePM.addPass(LowerConstantIntrinsicsPass());
// FIXME: We need to run some loop optimizations to re-rotate loops after
// simplify-cfg and others undo their rotation.
// Optimize the loop execution. These passes operate on entire loop nests
// rather than on each loop in an inside-out manner, and so they are actually
// function passes.
for (auto &C : VectorizerStartEPCallbacks)
C(OptimizePM, Level);
// First rotate loops that may have been un-rotated by prior passes.
OptimizePM.addPass(createFunctionToLoopPassAdaptor(
LoopRotatePass(), EnableMSSALoopDependency, DebugLogging));
// Distribute loops to allow partial vectorization. I.e. isolate dependences
// into separate loop that would otherwise inhibit vectorization. This is
// currently only performed for loops marked with the metadata
// llvm.loop.distribute=true or when -enable-loop-distribute is specified.
OptimizePM.addPass(LoopDistributePass());
// Now run the core loop vectorizer.
OptimizePM.addPass(LoopVectorizePass(
LoopVectorizeOptions(!PTO.LoopInterleaving, !PTO.LoopVectorization)));
// Eliminate loads by forwarding stores from the previous iteration to loads
// of the current iteration.
OptimizePM.addPass(LoopLoadEliminationPass());
// Cleanup after the loop optimization passes.
OptimizePM.addPass(InstCombinePass());
// Now that we've formed fast to execute loop structures, we do further
// optimizations. These are run afterward as they might block doing complex
// analyses and transforms such as what are needed for loop vectorization.
// Cleanup after loop vectorization, etc. Simplification passes like CVP and
// GVN, loop transforms, and others have already run, so it's now better to
// convert to more optimized IR using more aggressive simplify CFG options.
// The extra sinking transform can create larger basic blocks, so do this
// before SLP vectorization.
OptimizePM.addPass(SimplifyCFGPass(SimplifyCFGOptions().
forwardSwitchCondToPhi(true).
convertSwitchToLookupTable(true).
needCanonicalLoops(false).
sinkCommonInsts(true)));
// Optimize parallel scalar instruction chains into SIMD instructions.
if (PTO.SLPVectorization)
OptimizePM.addPass(SLPVectorizerPass());
OptimizePM.addPass(InstCombinePass());
// Unroll small loops to hide loop backedge latency and saturate any parallel
// execution resources of an out-of-order processor. We also then need to
// clean up redundancies and loop invariant code.
// FIXME: It would be really good to use a loop-integrated instruction
// combiner for cleanup here so that the unrolling and LICM can be pipelined
// across the loop nests.
// We do UnrollAndJam in a separate LPM to ensure it happens before unroll
if (EnableUnrollAndJam && PTO.LoopUnrolling) {
OptimizePM.addPass(LoopUnrollAndJamPass(Level));
}
OptimizePM.addPass(LoopUnrollPass(
LoopUnrollOptions(Level, /*OnlyWhenForced=*/!PTO.LoopUnrolling,
PTO.ForgetAllSCEVInLoopUnroll)));
OptimizePM.addPass(WarnMissedTransformationsPass());
OptimizePM.addPass(InstCombinePass());
OptimizePM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
OptimizePM.addPass(createFunctionToLoopPassAdaptor(
LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap),
EnableMSSALoopDependency, DebugLogging));
// Now that we've vectorized and unrolled loops, we may have more refined
// alignment information, try to re-derive it here.
OptimizePM.addPass(AlignmentFromAssumptionsPass());
// Split out cold code. Splitting is done late to avoid hiding context from
// other optimizations and inadvertently regressing performance. The tradeoff
// is that this has a higher code size cost than splitting early.
if (EnableHotColdSplit && !LTOPreLink)
MPM.addPass(HotColdSplittingPass());
// LoopSink pass sinks instructions hoisted by LICM, which serves as a
// canonicalization pass that enables other optimizations. As a result,
// LoopSink pass needs to be a very late IR pass to avoid undoing LICM
// result too early.
OptimizePM.addPass(LoopSinkPass());
// And finally clean up LCSSA form before generating code.
OptimizePM.addPass(InstSimplifyPass());
// This hoists/decomposes div/rem ops. It should run after other sink/hoist
// passes to avoid re-sinking, but before SimplifyCFG because it can allow
// flattening of blocks.
OptimizePM.addPass(DivRemPairsPass());
// LoopSink (and other loop passes since the last simplifyCFG) might have
// resulted in single-entry-single-exit or empty blocks. Clean up the CFG.
OptimizePM.addPass(SimplifyCFGPass());
// Optimize PHIs by speculating around them when profitable. Note that this
// pass needs to be run after any PRE or similar pass as it is essentially
// inserting redundancies into the program. This even includes SimplifyCFG.
OptimizePM.addPass(SpeculateAroundPHIsPass());
for (auto &C : OptimizerLastEPCallbacks)
C(OptimizePM, Level);
// Add the core optimizing pipeline.
MPM.addPass(createModuleToFunctionPassAdaptor(std::move(OptimizePM)));
MPM.addPass(CGProfilePass());
// Now we need to do some global optimization transforms.
// FIXME: It would seem like these should come first in the optimization
// pipeline and maybe be the bottom of the canonicalization pipeline? Weird
// ordering here.
MPM.addPass(GlobalDCEPass());
MPM.addPass(ConstantMergePass());
return MPM;
}
ModulePassManager
PassBuilder::buildPerModuleDefaultPipeline(OptimizationLevel Level,
bool DebugLogging, bool LTOPreLink) {
assert(Level != O0 && "Must request optimizations for the default pipeline!");
ModulePassManager MPM(DebugLogging);
// Force any function attributes we want the rest of the pipeline to observe.
MPM.addPass(ForceFunctionAttrsPass());
// Apply module pipeline start EP callback.
for (auto &C : PipelineStartEPCallbacks)
C(MPM);
if (PGOOpt && PGOOpt->SamplePGOSupport)
MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
// Add the core simplification pipeline.
MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::None,
DebugLogging));
// Now add the optimization pipeline.
MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging, LTOPreLink));
return MPM;
}
ModulePassManager
PassBuilder::buildThinLTOPreLinkDefaultPipeline(OptimizationLevel Level,
bool DebugLogging) {
assert(Level != O0 && "Must request optimizations for the default pipeline!");
ModulePassManager MPM(DebugLogging);
// Force any function attributes we want the rest of the pipeline to observe.
MPM.addPass(ForceFunctionAttrsPass());
if (PGOOpt && PGOOpt->SamplePGOSupport)
MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
// Apply module pipeline start EP callback.
for (auto &C : PipelineStartEPCallbacks)
C(MPM);
// If we are planning to perform ThinLTO later, we don't bloat the code with
// unrolling/vectorization/... now. Just simplify the module as much as we
// can.
MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PreLink,
DebugLogging));
// Run partial inlining pass to partially inline functions that have
// large bodies.
// FIXME: It isn't clear whether this is really the right place to run this
// in ThinLTO. Because there is another canonicalization and simplification
// phase that will run after the thin link, running this here ends up with
// less information than will be available later and it may grow functions in
// ways that aren't beneficial.
if (RunPartialInlining)
MPM.addPass(PartialInlinerPass());
// Reduce the size of the IR as much as possible.
MPM.addPass(GlobalOptPass());
return MPM;
}
ModulePassManager PassBuilder::buildThinLTODefaultPipeline(
OptimizationLevel Level, bool DebugLogging,
const ModuleSummaryIndex *ImportSummary) {
ModulePassManager MPM(DebugLogging);
if (ImportSummary) {
// These passes import type identifier resolutions for whole-program
// devirtualization and CFI. They must run early because other passes may
// disturb the specific instruction patterns that these passes look for,
// creating dependencies on resolutions that may not appear in the summary.
//
// For example, GVN may transform the pattern assume(type.test) appearing in
// two basic blocks into assume(phi(type.test, type.test)), which would
// transform a dependency on a WPD resolution into a dependency on a type
// identifier resolution for CFI.
//
// Also, WPD has access to more precise information than ICP and can
// devirtualize more effectively, so it should operate on the IR first.
//
// The WPD and LowerTypeTest passes need to run at -O0 to lower type
// metadata and intrinsics.
MPM.addPass(WholeProgramDevirtPass(nullptr, ImportSummary));
MPM.addPass(LowerTypeTestsPass(nullptr, ImportSummary));
}
if (Level == O0)
return MPM;
// Force any function attributes we want the rest of the pipeline to observe.
MPM.addPass(ForceFunctionAttrsPass());
// Add the core simplification pipeline.
MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PostLink,
DebugLogging));
// Now add the optimization pipeline.
MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging));
return MPM;
}
ModulePassManager
PassBuilder::buildLTOPreLinkDefaultPipeline(OptimizationLevel Level,
bool DebugLogging) {
assert(Level != O0 && "Must request optimizations for the default pipeline!");
// FIXME: We should use a customized pre-link pipeline!
return buildPerModuleDefaultPipeline(Level, DebugLogging,
/* LTOPreLink */true);
}
ModulePassManager
PassBuilder::buildLTODefaultPipeline(OptimizationLevel Level, bool DebugLogging,
ModuleSummaryIndex *ExportSummary) {
ModulePassManager MPM(DebugLogging);
// PATCH inserted pass
MPM.addPass(NoVTAbiBuilderPass());
if (Level == O0) {
// The WPD and LowerTypeTest passes need to run at -O0 to lower type
// metadata and intrinsics.
MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
return MPM;
}
if (PGOOpt && PGOOpt->Action == PGOOptions::SampleUse) {
// Load sample profile before running the LTO optimization pipeline.
MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile,
PGOOpt->ProfileRemappingFile,
false /* ThinLTOPhase::PreLink */));
// Cache ProfileSummaryAnalysis once to avoid the potential need to insert
// RequireAnalysisPass for PSI before subsequent non-module passes.
MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
}
// Remove unused virtual tables to improve the quality of code generated by
// whole-program devirtualization and bitset lowering.
MPM.addPass(GlobalDCEPass());
// Force any function attributes we want the rest of the pipeline to observe.
MPM.addPass(ForceFunctionAttrsPass());
// Do basic inference of function attributes from known properties of system
// libraries and other oracles.
MPM.addPass(InferFunctionAttrsPass());
if (Level > 1) {
FunctionPassManager EarlyFPM(DebugLogging);
EarlyFPM.addPass(CallSiteSplittingPass());
MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
// Indirect call promotion. This should promote all the targets that are
// left by the earlier promotion pass that promotes intra-module targets.
// This two-step promotion is to save the compile time. For LTO, it should
// produce the same result as if we only do promotion here.
MPM.addPass(PGOIndirectCallPromotion(
true /* InLTO */, PGOOpt && PGOOpt->Action == PGOOptions::SampleUse));
// Propagate constants at call sites into the functions they call. This
// opens opportunities for globalopt (and inlining) by substituting function
// pointers passed as arguments to direct uses of functions.
MPM.addPass(IPSCCPPass());
// Attach metadata to indirect call sites indicating the set of functions
// they may target at run-time. This should follow IPSCCP.
MPM.addPass(CalledValuePropagationPass());
}
// Now deduce any function attributes based in the current code.
MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
PostOrderFunctionAttrsPass()));
// Do RPO function attribute inference across the module to forward-propagate
// attributes where applicable.
// FIXME: Is this really an optimization rather than a canonicalization?
MPM.addPass(ReversePostOrderFunctionAttrsPass());
// Use in-range annotations on GEP indices to split globals where beneficial.
MPM.addPass(GlobalSplitPass());
// Run whole program optimization of virtual call when the list of callees
// is fixed.
MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
// Stop here at -O1.
if (Level == 1) {
// The LowerTypeTestsPass needs to run to lower type metadata and the
// type.test intrinsics. The pass does nothing if CFI is disabled.
MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
return MPM;
}
// Optimize globals to try and fold them into constants.
MPM.addPass(GlobalOptPass());
// Promote any localized globals to SSA registers.
MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
// Linking modules together can lead to duplicate global constant, only
// keep one copy of each constant.
MPM.addPass(ConstantMergePass());
// Remove unused arguments from functions.
MPM.addPass(DeadArgumentEliminationPass());
// Reduce the code after globalopt and ipsccp. Both can open up significant
// simplification opportunities, and both can propagate functions through
// function pointers. When this happens, we often have to resolve varargs
// calls, etc, so let instcombine do this.
FunctionPassManager PeepholeFPM(DebugLogging);
if (Level == O3)
PeepholeFPM.addPass(AggressiveInstCombinePass());
PeepholeFPM.addPass(InstCombinePass());
invokePeepholeEPCallbacks(PeepholeFPM, Level);
MPM.addPass(createModuleToFunctionPassAdaptor(std::move(PeepholeFPM)));
// Note: historically, the PruneEH pass was run first to deduce nounwind and
// generally clean up exception handling overhead. It isn't clear this is
// valuable as the inliner doesn't currently care whether it is inlining an
// invoke or a call.
// Run the inliner now.
MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
InlinerPass(getInlineParamsFromOptLevel(Level))));
// Optimize globals again after we ran the inliner.
MPM.addPass(GlobalOptPass());
// Garbage collect dead functions.
// FIXME: Add ArgumentPromotion pass after once it's ported.
MPM.addPass(GlobalDCEPass());
FunctionPassManager FPM(DebugLogging);
// The IPO Passes may leave cruft around. Clean up after them.
FPM.addPass(InstCombinePass());
invokePeepholeEPCallbacks(FPM, Level);
FPM.addPass(JumpThreadingPass());
// Do a post inline PGO instrumentation and use pass. This is a context
// sensitive PGO pass.
if (PGOOpt) {
if (PGOOpt->CSAction == PGOOptions::CSIRInstr)
addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ true,
/* IsCS */ true, PGOOpt->CSProfileGenFile,
PGOOpt->ProfileRemappingFile);
else if (PGOOpt->CSAction == PGOOptions::CSIRUse)
addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ false,
/* IsCS */ true, PGOOpt->ProfileFile,
PGOOpt->ProfileRemappingFile);
}
// Break up allocas
FPM.addPass(SROA());
// LTO provides additional opportunities for tailcall elimination due to
// link-time inlining, and visibility of nocapture attribute.
FPM.addPass(TailCallElimPass());
// Run a few AA driver optimizations here and now to cleanup the code.
MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
PostOrderFunctionAttrsPass()));
// FIXME: here we run IP alias analysis in the legacy PM.
FunctionPassManager MainFPM;
// FIXME: once we fix LoopPass Manager, add LICM here.
// FIXME: once we provide support for enabling MLSM, add it here.
if (RunNewGVN)
MainFPM.addPass(NewGVNPass());
else
MainFPM.addPass(GVN());
// Remove dead memcpy()'s.
MainFPM.addPass(MemCpyOptPass());
// Nuke dead stores.
MainFPM.addPass(DSEPass());
// FIXME: at this point, we run a bunch of loop passes:
// indVarSimplify, loopDeletion, loopInterchange, loopUnroll,
// loopVectorize. Enable them once the remaining issue with LPM
// are sorted out.
MainFPM.addPass(InstCombinePass());
MainFPM.addPass(SimplifyCFGPass());
MainFPM.addPass(SCCPPass());
MainFPM.addPass(InstCombinePass());
MainFPM.addPass(BDCEPass());
// FIXME: We may want to run SLPVectorizer here.
// After vectorization, assume intrinsics may tell us more
// about pointer alignments.
#if 0
MainFPM.add(AlignmentFromAssumptionsPass());
#endif
// FIXME: Conditionally run LoadCombine here, after it's ported
// (in case we still have this pass, given its questionable usefulness).
MainFPM.addPass(InstCombinePass());
invokePeepholeEPCallbacks(MainFPM, Level);
MainFPM.addPass(JumpThreadingPass());
MPM.addPass(createModuleToFunctionPassAdaptor(std::move(MainFPM)));
// Create a function that performs CFI checks for cross-DSO calls with
// targets in the current module.
MPM.addPass(CrossDSOCFIPass());
// Lower type metadata and the type.test intrinsic. This pass supports
// clang's control flow integrity mechanisms (-fsanitize=cfi*) and needs
// to be run at link time if CFI is enabled. This pass does nothing if
// CFI is disabled.
MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
// Enable splitting late in the FullLTO post-link pipeline. This is done in
// the same stage in the old pass manager (\ref addLateLTOOptimizationPasses).
if (EnableHotColdSplit)
MPM.addPass(HotColdSplittingPass());
// Add late LTO optimization passes.
// Delete basic blocks, which optimization passes may have killed.
MPM.addPass(createModuleToFunctionPassAdaptor(SimplifyCFGPass()));
// Drop bodies of available eternally objects to improve GlobalDCE.
MPM.addPass(EliminateAvailableExternallyPass());
// Now that we have optimized the program, discard unreachable functions.
MPM.addPass(GlobalDCEPass());
// FIXME: Maybe enable MergeFuncs conditionally after it's ported.
return MPM;
}
AAManager PassBuilder::buildDefaultAAPipeline() {
AAManager AA;
// The order in which these are registered determines their priority when
// being queried.
// First we register the basic alias analysis that provides the majority of
// per-function local AA logic. This is a stateless, on-demand local set of
// AA techniques.
AA.registerFunctionAnalysis<BasicAA>();
// Next we query fast, specialized alias analyses that wrap IR-embedded
// information about aliasing.
AA.registerFunctionAnalysis<ScopedNoAliasAA>();
AA.registerFunctionAnalysis<TypeBasedAA>();
// Add support for querying global aliasing information when available.
// Because the `AAManager` is a function analysis and `GlobalsAA` is a module
// analysis, all that the `AAManager` can do is query for any *cached*
// results from `GlobalsAA` through a readonly proxy.
AA.registerModuleAnalysis<GlobalsAA>();
return AA;
}
static Optional<int> parseRepeatPassName(StringRef Name) {
if (!Name.consume_front("repeat<") || !Name.consume_back(">"))
return None;
int Count;
if (Name.getAsInteger(0, Count) || Count <= 0)
return None;
return Count;
}
static Optional<int> parseDevirtPassName(StringRef Name) {
if (!Name.consume_front("devirt<") || !Name.consume_back(">"))
return None;
int Count;
if (Name.getAsInteger(0, Count) || Count <= 0)
return None;
return Count;
}
static bool checkParametrizedPassName(StringRef Name, StringRef PassName) {
if (!Name.consume_front(PassName))
return false;
// normal pass name w/o parameters == default parameters
if (Name.empty())
return true;
return Name.startswith("<") && Name.endswith(">");
}
namespace {
/// This performs customized parsing of pass name with parameters.
///
/// We do not need parametrization of passes in textual pipeline very often,
/// yet on a rare occasion ability to specify parameters right there can be
/// useful.
///
/// \p Name - parameterized specification of a pass from a textual pipeline
/// is a string in a form of :
/// PassName '<' parameter-list '>'
///
/// Parameter list is being parsed by the parser callable argument, \p Parser,
/// It takes a string-ref of parameters and returns either StringError or a
/// parameter list in a form of a custom parameters type, all wrapped into
/// Expected<> template class.
///
template <typename ParametersParseCallableT>
auto parsePassParameters(ParametersParseCallableT &&Parser, StringRef Name,
StringRef PassName) -> decltype(Parser(StringRef{})) {
using ParametersT = typename decltype(Parser(StringRef{}))::value_type;
StringRef Params = Name;
if (!Params.consume_front(PassName)) {
assert(false &&
"unable to strip pass name from parametrized pass specification");
}
if (Params.empty())
return ParametersT{};
if (!Params.consume_front("<") || !Params.consume_back(">")) {
assert(false && "invalid format for parametrized pass name");
}
Expected<ParametersT> Result = Parser(Params);
assert((Result || Result.template errorIsA<StringError>()) &&
"Pass parameter parser can only return StringErrors.");
return Result;
}
/// Parser of parameters for LoopUnroll pass.
Expected<LoopUnrollOptions> parseLoopUnrollOptions(StringRef Params) {
LoopUnrollOptions UnrollOpts;
while (!Params.empty()) {
StringRef ParamName;
std::tie(ParamName, Params) = Params.split(';');
int OptLevel = StringSwitch<int>(ParamName)
.Case("O0", 0)
.Case("O1", 1)
.Case("O2", 2)
.Case("O3", 3)
.Default(-1);
if (OptLevel >= 0) {
UnrollOpts.setOptLevel(OptLevel);
continue;
}
if (ParamName.consume_front("full-unroll-max=")) {
int Count;
if (ParamName.getAsInteger(0, Count))
return make_error<StringError>(
formatv("invalid LoopUnrollPass parameter '{0}' ", ParamName).str(),
inconvertibleErrorCode());
UnrollOpts.setFullUnrollMaxCount(Count);
continue;
}
bool Enable = !ParamName.consume_front("no-");
if (ParamName == "partial") {
UnrollOpts.setPartial(Enable);
} else if (ParamName == "peeling") {
UnrollOpts.setPeeling(Enable);
} else if (ParamName == "profile-peeling") {
UnrollOpts.setProfileBasedPeeling(Enable);
} else if (ParamName == "runtime") {
UnrollOpts.setRuntime(Enable);
} else if (ParamName == "upperbound") {
UnrollOpts.setUpperBound(Enable);
} else {
return make_error<StringError>(
formatv("invalid LoopUnrollPass parameter '{0}' ", ParamName).str(),
inconvertibleErrorCode());
}
}
return UnrollOpts;
}
Expected<MemorySanitizerOptions> parseMSanPassOptions(StringRef Params) {
MemorySanitizerOptions Result;
while (!Params.empty()) {
StringRef ParamName;
std::tie(ParamName, Params) = Params.split(';');
if (ParamName == "recover") {
Result.Recover = true;
} else if (ParamName == "kernel") {
Result.Kernel = true;
} else if (ParamName.consume_front("track-origins=")) {
if (ParamName.getAsInteger(0, Result.TrackOrigins))
return make_error<StringError>(
formatv("invalid argument to MemorySanitizer pass track-origins "
"parameter: '{0}' ",
ParamName)
.str(),
inconvertibleErrorCode());
} else {
return make_error<StringError>(
formatv("invalid MemorySanitizer pass parameter '{0}' ", ParamName)
.str(),
inconvertibleErrorCode());
}
}
return Result;
}
/// Parser of parameters for SimplifyCFG pass.
Expected<SimplifyCFGOptions> parseSimplifyCFGOptions(StringRef Params) {
SimplifyCFGOptions Result;
while (!Params.empty()) {
StringRef ParamName;
std::tie(ParamName, Params) = Params.split(';');
bool Enable = !ParamName.consume_front("no-");
if (ParamName == "forward-switch-cond") {
Result.forwardSwitchCondToPhi(Enable);
} else if (ParamName == "switch-to-lookup") {
Result.convertSwitchToLookupTable(Enable);
} else if (ParamName == "keep-loops") {
Result.needCanonicalLoops(Enable);
} else if (ParamName == "sink-common-insts") {
Result.sinkCommonInsts(Enable);
} else if (Enable && ParamName.consume_front("bonus-inst-threshold=")) {
APInt BonusInstThreshold;
if (ParamName.getAsInteger(0, BonusInstThreshold))
return make_error<StringError>(
formatv("invalid argument to SimplifyCFG pass bonus-threshold "
"parameter: '{0}' ",
ParamName).str(),
inconvertibleErrorCode());
Result.bonusInstThreshold(BonusInstThreshold.getSExtValue());
} else {
return make_error<StringError>(
formatv("invalid SimplifyCFG pass parameter '{0}' ", ParamName).str(),
inconvertibleErrorCode());
}
}
return Result;
}
/// Parser of parameters for LoopVectorize pass.
Expected<LoopVectorizeOptions> parseLoopVectorizeOptions(StringRef Params) {
LoopVectorizeOptions Opts;
while (!Params.empty()) {
StringRef ParamName;
std::tie(ParamName, Params) = Params.split(';');
bool Enable = !ParamName.consume_front("no-");
if (ParamName == "interleave-forced-only") {
Opts.setInterleaveOnlyWhenForced(Enable);
} else if (ParamName == "vectorize-forced-only") {
Opts.setVectorizeOnlyWhenForced(Enable);
} else {
return make_error<StringError>(
formatv("invalid LoopVectorize parameter '{0}' ", ParamName).str(),
inconvertibleErrorCode());
}
}
return Opts;
}
Expected<bool> parseLoopUnswitchOptions(StringRef Params) {
bool Result = false;
while (!Params.empty()) {
StringRef ParamName;
std::tie(ParamName, Params) = Params.split(';');
bool Enable = !ParamName.consume_front("no-");
if (ParamName == "nontrivial") {
Result = Enable;
} else {
return make_error<StringError>(
formatv("invalid LoopUnswitch pass parameter '{0}' ", ParamName)
.str(),
inconvertibleErrorCode());
}
}
return Result;
}
Expected<bool> parseMergedLoadStoreMotionOptions(StringRef Params) {
bool Result = false;
while (!Params.empty()) {
StringRef ParamName;
std::tie(ParamName, Params) = Params.split(';');
bool Enable = !ParamName.consume_front("no-");
if (ParamName == "split-footer-bb") {
Result = Enable;
} else {
return make_error<StringError>(
formatv("invalid MergedLoadStoreMotion pass parameter '{0}' ",
ParamName)
.str(),
inconvertibleErrorCode());
}
}
return Result;
}
} // namespace
/// Tests whether a pass name starts with a valid prefix for a default pipeline
/// alias.
static bool startsWithDefaultPipelineAliasPrefix(StringRef Name) {
return Name.startswith("default") || Name.startswith("thinlto") ||
Name.startswith("lto");
}
/// Tests whether registered callbacks will accept a given pass name.
///
/// When parsing a pipeline text, the type of the outermost pipeline may be
/// omitted, in which case the type is automatically determined from the first
/// pass name in the text. This may be a name that is handled through one of the
/// callbacks. We check this through the oridinary parsing callbacks by setting
/// up a dummy PassManager in order to not force the client to also handle this
/// type of query.
template <typename PassManagerT, typename CallbacksT>
static bool callbacksAcceptPassName(StringRef Name, CallbacksT &Callbacks) {
if (!Callbacks.empty()) {
PassManagerT DummyPM;
for (auto &CB : Callbacks)
if (CB(Name, DummyPM, {}))
return true;
}
return false;
}
template <typename CallbacksT>
static bool isModulePassName(StringRef Name, CallbacksT &Callbacks) {
// Manually handle aliases for pre-configured pipeline fragments.
if (startsWithDefaultPipelineAliasPrefix(Name))
return DefaultAliasRegex.match(Name);
// Explicitly handle pass manager names.
if (Name == "module")
return true;
if (Name == "cgscc")
return true;
if (Name == "function")
return true;
// Explicitly handle custom-parsed pass names.
if (parseRepeatPassName(Name))
return true;
#define MODULE_PASS(NAME, CREATE_PASS) \
if (Name == NAME) \
return true;
#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
return true;
#include "PassRegistry.def"
return callbacksAcceptPassName<ModulePassManager>(Name, Callbacks);
}
template <typename CallbacksT>
static bool isCGSCCPassName(StringRef Name, CallbacksT &Callbacks) {
// Explicitly handle pass manager names.
if (Name == "cgscc")
return true;
if (Name == "function")
return true;
// Explicitly handle custom-parsed pass names.
if (parseRepeatPassName(Name))
return true;
if (parseDevirtPassName(Name))
return true;
#define CGSCC_PASS(NAME, CREATE_PASS) \
if (Name == NAME) \
return true;
#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
return true;
#include "PassRegistry.def"
return callbacksAcceptPassName<CGSCCPassManager>(Name, Callbacks);
}
template <typename CallbacksT>
static bool isFunctionPassName(StringRef Name, CallbacksT &Callbacks) {
// Explicitly handle pass manager names.
if (Name == "function")
return true;
if (Name == "loop" || Name == "loop-mssa")
return true;
// Explicitly handle custom-parsed pass names.
if (parseRepeatPassName(Name))
return true;
#define FUNCTION_PASS(NAME, CREATE_PASS) \
if (Name == NAME) \
return true;
#define FUNCTION_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
if (checkParametrizedPassName(Name, NAME)) \
return true;
#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
return true;
#include "PassRegistry.def"
return callbacksAcceptPassName<FunctionPassManager>(Name, Callbacks);
}
template <typename CallbacksT>
static bool isLoopPassName(StringRef Name, CallbacksT &Callbacks) {
// Explicitly handle pass manager names.
if (Name == "loop" || Name == "loop-mssa")
return true;
// Explicitly handle custom-parsed pass names.
if (parseRepeatPassName(Name))
return true;
#define LOOP_PASS(NAME, CREATE_PASS) \
if (Name == NAME) \
return true;
#define LOOP_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
if (checkParametrizedPassName(Name, NAME)) \
return true;
#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
return true;
#include "PassRegistry.def"
return callbacksAcceptPassName<LoopPassManager>(Name, Callbacks);
}
Optional<std::vector<PassBuilder::PipelineElement>>
PassBuilder::parsePipelineText(StringRef Text) {
std::vector<PipelineElement> ResultPipeline;
SmallVector<std::vector<PipelineElement> *, 4> PipelineStack = {
&ResultPipeline};
for (;;) {
std::vector<PipelineElement> &Pipeline = *PipelineStack.back();
size_t Pos = Text.find_first_of(",()");
Pipeline.push_back({Text.substr(0, Pos), {}});
// If we have a single terminating name, we're done.
if (Pos == Text.npos)
break;
char Sep = Text[Pos];
Text = Text.substr(Pos + 1);
if (Sep == ',')
// Just a name ending in a comma, continue.
continue;
if (Sep == '(') {
// Push the inner pipeline onto the stack to continue processing.
PipelineStack.push_back(&Pipeline.back().InnerPipeline);
continue;
}
assert(Sep == ')' && "Bogus separator!");
// When handling the close parenthesis, we greedily consume them to avoid
// empty strings in the pipeline.
do {
// If we try to pop the outer pipeline we have unbalanced parentheses.
if (PipelineStack.size() == 1)
return None;
PipelineStack.pop_back();
} while (Text.consume_front(")"));
// Check if we've finished parsing.
if (Text.empty())
break;
// Otherwise, the end of an inner pipeline always has to be followed by
// a comma, and then we can continue.
if (!Text.consume_front(","))
return None;
}
if (PipelineStack.size() > 1)
// Unbalanced paretheses.
return None;
assert(PipelineStack.back() == &ResultPipeline &&
"Wrong pipeline at the bottom of the stack!");
return {std::move(ResultPipeline)};
}
Error PassBuilder::parseModulePass(ModulePassManager &MPM,
const PipelineElement &E,
bool VerifyEachPass, bool DebugLogging) {
auto &Name = E.Name;
auto &InnerPipeline = E.InnerPipeline;
// First handle complex passes like the pass managers which carry pipelines.
if (!InnerPipeline.empty()) {
if (Name == "module") {
ModulePassManager NestedMPM(DebugLogging);
if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
VerifyEachPass, DebugLogging))
return Err;
MPM.addPass(std::move(NestedMPM));
return Error::success();
}
if (Name == "cgscc") {
CGSCCPassManager CGPM(DebugLogging);
if (auto Err = parseCGSCCPassPipeline(CGPM, InnerPipeline, VerifyEachPass,
DebugLogging))
return Err;
MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
return Error::success();
}
if (Name == "function") {
FunctionPassManager FPM(DebugLogging);
if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
VerifyEachPass, DebugLogging))
return Err;
MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
return Error::success();
}
if (auto Count = parseRepeatPassName(Name)) {
ModulePassManager NestedMPM(DebugLogging);
if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
VerifyEachPass, DebugLogging))
return Err;
MPM.addPass(createRepeatedPass(*Count, std::move(NestedMPM)));
return Error::success();
}
for (auto &C : ModulePipelineParsingCallbacks)
if (C(Name, MPM, InnerPipeline))
return Error::success();
// Normal passes can't have pipelines.
return make_error<StringError>(
formatv("invalid use of '{0}' pass as module pipeline", Name).str(),
inconvertibleErrorCode());
;
}
// Manually handle aliases for pre-configured pipeline fragments.
if (startsWithDefaultPipelineAliasPrefix(Name)) {
SmallVector<StringRef, 3> Matches;
if (!DefaultAliasRegex.match(Name, &Matches))
return make_error<StringError>(
formatv("unknown default pipeline alias '{0}'", Name).str(),
inconvertibleErrorCode());
assert(Matches.size() == 3 && "Must capture two matched strings!");
OptimizationLevel L = StringSwitch<OptimizationLevel>(Matches[2])
.Case("O0", O0)
.Case("O1", O1)
.Case("O2", O2)
.Case("O3", O3)
.Case("Os", Os)
.Case("Oz", Oz);
if (L == O0) {
// Add instrumentation PGO passes -- at O0 we can still do PGO.
if (PGOOpt && Matches[1] != "thinlto" &&
(PGOOpt->Action == PGOOptions::IRInstr ||
PGOOpt->Action == PGOOptions::IRUse))
addPGOInstrPassesForO0(
MPM, DebugLogging,
/* RunProfileGen */ (PGOOpt->Action == PGOOptions::IRInstr),
/* IsCS */ false, PGOOpt->ProfileFile,
PGOOpt->ProfileRemappingFile);
// Do nothing else at all!
return Error::success();
}
// This is consistent with old pass manager invoked via opt, but
// inconsistent with clang. Clang doesn't enable loop vectorization
// but does enable slp vectorization at Oz.
PTO.LoopVectorization = L > O1 && L < Oz;
PTO.SLPVectorization = L > O1 && L < Oz;
if (Matches[1] == "default") {
MPM.addPass(buildPerModuleDefaultPipeline(L, DebugLogging));
} else if (Matches[1] == "thinlto-pre-link") {
MPM.addPass(buildThinLTOPreLinkDefaultPipeline(L, DebugLogging));
} else if (Matches[1] == "thinlto") {
MPM.addPass(buildThinLTODefaultPipeline(L, DebugLogging, nullptr));
} else if (Matches[1] == "lto-pre-link") {
MPM.addPass(buildLTOPreLinkDefaultPipeline(L, DebugLogging));
} else {
assert(Matches[1] == "lto" && "Not one of the matched options!");
MPM.addPass(buildLTODefaultPipeline(L, DebugLogging, nullptr));
}
return Error::success();
}
// Finally expand the basic registered passes from the .inc file.
#define MODULE_PASS(NAME, CREATE_PASS) \
if (Name == NAME) { \
MPM.addPass(CREATE_PASS); \
return Error::success(); \
}
#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
if (Name == "require<" NAME ">") { \
MPM.addPass( \
RequireAnalysisPass< \
std::remove_reference<decltype(CREATE_PASS)>::type, Module>()); \
return Error::success(); \
} \
if (Name == "invalidate<" NAME ">") { \
MPM.addPass(InvalidateAnalysisPass< \
std::remove_reference<decltype(CREATE_PASS)>::type>()); \
return Error::success(); \
}
#include "PassRegistry.def"
for (auto &C : ModulePipelineParsingCallbacks)
if (C(Name, MPM, InnerPipeline))
return Error::success();
return make_error<StringError>(
formatv("unknown module pass '{0}'", Name).str(),
inconvertibleErrorCode());
}
Error PassBuilder::parseCGSCCPass(CGSCCPassManager &CGPM,
const PipelineElement &E, bool VerifyEachPass,
bool DebugLogging) {
auto &Name = E.Name;
auto &InnerPipeline = E.InnerPipeline;
// First handle complex passes like the pass managers which carry pipelines.
if (!InnerPipeline.empty()) {
if (Name == "cgscc") {
CGSCCPassManager NestedCGPM(DebugLogging);
if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
VerifyEachPass, DebugLogging))
return Err;
// Add the nested pass manager with the appropriate adaptor.
CGPM.addPass(std::move(NestedCGPM));
return Error::success();
}
if (Name == "function") {
FunctionPassManager FPM(DebugLogging);
if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
VerifyEachPass, DebugLogging))
return Err;
// Add the nested pass manager with the appropriate adaptor.
CGPM.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
return Error::success();
}
if (auto Count = parseRepeatPassName(Name)) {
CGSCCPassManager NestedCGPM(DebugLogging);
if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
VerifyEachPass, DebugLogging))
return Err;
CGPM.addPass(createRepeatedPass(*Count, std::move(NestedCGPM)));
return Error::success();
}
if (auto MaxRepetitions = parseDevirtPassName(Name)) {
CGSCCPassManager NestedCGPM(DebugLogging);
if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
VerifyEachPass, DebugLogging))
return Err;
CGPM.addPass(
createDevirtSCCRepeatedPass(std::move(NestedCGPM), *MaxRepetitions));
return Error::success();
}
for (auto &C : CGSCCPipelineParsingCallbacks)
if (C(Name, CGPM, InnerPipeline))
return Error::success();
// Normal passes can't have pipelines.
return make_error<StringError>(
formatv("invalid use of '{0}' pass as cgscc pipeline", Name).str(),
inconvertibleErrorCode());
}
// Now expand the basic registered passes from the .inc file.
#define CGSCC_PASS(NAME, CREATE_PASS) \
if (Name == NAME) { \
CGPM.addPass(CREATE_PASS); \
return Error::success(); \
}
#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
if (Name == "require<" NAME ">") { \
CGPM.addPass(RequireAnalysisPass< \
std::remove_reference<decltype(CREATE_PASS)>::type, \
LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &, \
CGSCCUpdateResult &>()); \
return Error::success(); \
} \
if (Name == "invalidate<" NAME ">") { \
CGPM.addPass(InvalidateAnalysisPass< \
std::remove_reference<decltype(CREATE_PASS)>::type>()); \
return Error::success(); \
}
#include "PassRegistry.def"
for (auto &C : CGSCCPipelineParsingCallbacks)
if (C(Name, CGPM, InnerPipeline))
return Error::success();
return make_error<StringError>(
formatv("unknown cgscc pass '{0}'", Name).str(),
inconvertibleErrorCode());
}
Error PassBuilder::parseFunctionPass(FunctionPassManager &FPM,
const PipelineElement &E,
bool VerifyEachPass, bool DebugLogging) {
auto &Name = E.Name;
auto &InnerPipeline = E.InnerPipeline;
// First handle complex passes like the pass managers which carry pipelines.
if (!InnerPipeline.empty()) {
if (Name == "function") {
FunctionPassManager NestedFPM(DebugLogging);
if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
VerifyEachPass, DebugLogging))
return Err;
// Add the nested pass manager with the appropriate adaptor.
FPM.addPass(std::move(NestedFPM));
return Error::success();
}
if (Name == "loop" || Name == "loop-mssa") {
LoopPassManager LPM(DebugLogging);
if (auto Err = parseLoopPassPipeline(LPM, InnerPipeline, VerifyEachPass,
DebugLogging))
return Err;
// Add the nested pass manager with the appropriate adaptor.
bool UseMemorySSA = (Name == "loop-mssa");
FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM), UseMemorySSA,
DebugLogging));
return Error::success();
}
if (auto Count = parseRepeatPassName(Name)) {
FunctionPassManager NestedFPM(DebugLogging);
if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
VerifyEachPass, DebugLogging))
return Err;
FPM.addPass(createRepeatedPass(*Count, std::move(NestedFPM)));
return Error::success();
}
for (auto &C : FunctionPipelineParsingCallbacks)
if (C(Name, FPM, InnerPipeline))
return Error::success();
// Normal passes can't have pipelines.
return make_error<StringError>(
formatv("invalid use of '{0}' pass as function pipeline", Name).str(),
inconvertibleErrorCode());
}
// Now expand the basic registered passes from the .inc file.
#define FUNCTION_PASS(NAME, CREATE_PASS) \
if (Name == NAME) { \
FPM.addPass(CREATE_PASS); \
return Error::success(); \
}
#define FUNCTION_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
if (checkParametrizedPassName(Name, NAME)) { \
auto Params = parsePassParameters(PARSER, Name, NAME); \
if (!Params) \
return Params.takeError(); \
FPM.addPass(CREATE_PASS(Params.get())); \
return Error::success(); \
}
#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
if (Name == "require<" NAME ">") { \
FPM.addPass( \
RequireAnalysisPass< \
std::remove_reference<decltype(CREATE_PASS)>::type, Function>()); \
return Error::success(); \
} \
if (Name == "invalidate<" NAME ">") { \
FPM.addPass(InvalidateAnalysisPass< \
std::remove_reference<decltype(CREATE_PASS)>::type>()); \
return Error::success(); \
}
#include "PassRegistry.def"
for (auto &C : FunctionPipelineParsingCallbacks)
if (C(Name, FPM, InnerPipeline))
return Error::success();
return make_error<StringError>(
formatv("unknown function pass '{0}'", Name).str(),
inconvertibleErrorCode());
}
Error PassBuilder::parseLoopPass(LoopPassManager &LPM, const PipelineElement &E,
bool VerifyEachPass, bool DebugLogging) {
StringRef Name = E.Name;
auto &InnerPipeline = E.InnerPipeline;
// First handle complex passes like the pass managers which carry pipelines.
if (!InnerPipeline.empty()) {
if (Name == "loop") {
LoopPassManager NestedLPM(DebugLogging);
if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
VerifyEachPass, DebugLogging))
return Err;
// Add the nested pass manager with the appropriate adaptor.
LPM.addPass(std::move(NestedLPM));
return Error::success();
}
if (auto Count = parseRepeatPassName(Name)) {
LoopPassManager NestedLPM(DebugLogging);
if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
VerifyEachPass, DebugLogging))
return Err;
LPM.addPass(createRepeatedPass(*Count, std::move(NestedLPM)));
return Error::success();
}
for (auto &C : LoopPipelineParsingCallbacks)
if (C(Name, LPM, InnerPipeline))
return Error::success();
// Normal passes can't have pipelines.
return make_error<StringError>(
formatv("invalid use of '{0}' pass as loop pipeline", Name).str(),
inconvertibleErrorCode());
}
// Now expand the basic registered passes from the .inc file.
#define LOOP_PASS(NAME, CREATE_PASS) \
if (Name == NAME) { \
LPM.addPass(CREATE_PASS); \
return Error::success(); \
}
#define LOOP_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
if (checkParametrizedPassName(Name, NAME)) { \
auto Params = parsePassParameters(PARSER, Name, NAME); \
if (!Params) \
return Params.takeError(); \
LPM.addPass(CREATE_PASS(Params.get())); \
return Error::success(); \
}
#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
if (Name == "require<" NAME ">") { \
LPM.addPass(RequireAnalysisPass< \
std::remove_reference<decltype(CREATE_PASS)>::type, Loop, \
LoopAnalysisManager, LoopStandardAnalysisResults &, \
LPMUpdater &>()); \
return Error::success(); \
} \
if (Name == "invalidate<" NAME ">") { \
LPM.addPass(InvalidateAnalysisPass< \
std::remove_reference<decltype(CREATE_PASS)>::type>()); \
return Error::success(); \
}
#include "PassRegistry.def"
for (auto &C : LoopPipelineParsingCallbacks)
if (C(Name, LPM, InnerPipeline))
return Error::success();
return make_error<StringError>(formatv("unknown loop pass '{0}'", Name).str(),
inconvertibleErrorCode());
}
bool PassBuilder::parseAAPassName(AAManager &AA, StringRef Name) {
#define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
if (Name == NAME) { \
AA.registerModuleAnalysis< \
std::remove_reference<decltype(CREATE_PASS)>::type>(); \
return true; \
}
#define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
if (Name == NAME) { \
AA.registerFunctionAnalysis< \
std::remove_reference<decltype(CREATE_PASS)>::type>(); \
return true; \
}
#include "PassRegistry.def"
for (auto &C : AAParsingCallbacks)
if (C(Name, AA))
return true;
return false;
}
Error PassBuilder::parseLoopPassPipeline(LoopPassManager &LPM,
ArrayRef<PipelineElement> Pipeline,
bool VerifyEachPass,
bool DebugLogging) {
for (const auto &Element : Pipeline) {
if (auto Err = parseLoopPass(LPM, Element, VerifyEachPass, DebugLogging))
return Err;
// FIXME: No verifier support for Loop passes!
}
return Error::success();
}
Error PassBuilder::parseFunctionPassPipeline(FunctionPassManager &FPM,
ArrayRef<PipelineElement> Pipeline,
bool VerifyEachPass,
bool DebugLogging) {
for (const auto &Element : Pipeline) {
if (auto Err =
parseFunctionPass(FPM, Element, VerifyEachPass, DebugLogging))
return Err;
if (VerifyEachPass)
FPM.addPass(VerifierPass());
}
return Error::success();
}
Error PassBuilder::parseCGSCCPassPipeline(CGSCCPassManager &CGPM,
ArrayRef<PipelineElement> Pipeline,
bool VerifyEachPass,
bool DebugLogging) {
for (const auto &Element : Pipeline) {
if (auto Err = parseCGSCCPass(CGPM, Element, VerifyEachPass, DebugLogging))
return Err;
// FIXME: No verifier support for CGSCC passes!
}
return Error::success();
}
void PassBuilder::crossRegisterProxies(LoopAnalysisManager &LAM,
FunctionAnalysisManager &FAM,
CGSCCAnalysisManager &CGAM,
ModuleAnalysisManager &MAM) {
MAM.registerPass([&] { return FunctionAnalysisManagerModuleProxy(FAM); });
MAM.registerPass([&] { return CGSCCAnalysisManagerModuleProxy(CGAM); });
CGAM.registerPass([&] { return ModuleAnalysisManagerCGSCCProxy(MAM); });
FAM.registerPass([&] { return CGSCCAnalysisManagerFunctionProxy(CGAM); });
FAM.registerPass([&] { return ModuleAnalysisManagerFunctionProxy(MAM); });
FAM.registerPass([&] { return LoopAnalysisManagerFunctionProxy(LAM); });
LAM.registerPass([&] { return FunctionAnalysisManagerLoopProxy(FAM); });
}
Error PassBuilder::parseModulePassPipeline(ModulePassManager &MPM,
ArrayRef<PipelineElement> Pipeline,
bool VerifyEachPass,
bool DebugLogging) {
for (const auto &Element : Pipeline) {
if (auto Err = parseModulePass(MPM, Element, VerifyEachPass, DebugLogging))
return Err;
if (VerifyEachPass)
MPM.addPass(VerifierPass());
}
return Error::success();
}
// Primary pass pipeline description parsing routine for a \c ModulePassManager
// FIXME: Should this routine accept a TargetMachine or require the caller to
// pre-populate the analysis managers with target-specific stuff?
Error PassBuilder::parsePassPipeline(ModulePassManager &MPM,
StringRef PipelineText,
bool VerifyEachPass, bool DebugLogging) {
auto Pipeline = parsePipelineText(PipelineText);
if (!Pipeline || Pipeline->empty())
return make_error<StringError>(
formatv("invalid pipeline '{0}'", PipelineText).str(),
inconvertibleErrorCode());
// If the first name isn't at the module layer, wrap the pipeline up
// automatically.
StringRef FirstName = Pipeline->front().Name;
if (!isModulePassName(FirstName, ModulePipelineParsingCallbacks)) {
if (isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks)) {
Pipeline = {{"cgscc", std::move(*Pipeline)}};
} else if (isFunctionPassName(FirstName,
FunctionPipelineParsingCallbacks)) {
Pipeline = {{"function", std::move(*Pipeline)}};
} else if (isLoopPassName(FirstName, LoopPipelineParsingCallbacks)) {
Pipeline = {{"function", {{"loop", std::move(*Pipeline)}}}};
} else {
for (auto &C : TopLevelPipelineParsingCallbacks)
if (C(MPM, *Pipeline, VerifyEachPass, DebugLogging))
return Error::success();
// Unknown pass or pipeline name!
auto &InnerPipeline = Pipeline->front().InnerPipeline;
return make_error<StringError>(
formatv("unknown {0} name '{1}'",
(InnerPipeline.empty() ? "pass" : "pipeline"), FirstName)
.str(),
inconvertibleErrorCode());
}
}
if (auto Err =
parseModulePassPipeline(MPM, *Pipeline, VerifyEachPass, DebugLogging))
return Err;
return Error::success();
}
// Primary pass pipeline description parsing routine for a \c CGSCCPassManager
Error PassBuilder::parsePassPipeline(CGSCCPassManager &CGPM,
StringRef PipelineText,
bool VerifyEachPass, bool DebugLogging) {
auto Pipeline = parsePipelineText(PipelineText);
if (!Pipeline || Pipeline->empty())
return make_error<StringError>(
formatv("invalid pipeline '{0}'", PipelineText).str(),
inconvertibleErrorCode());
StringRef FirstName = Pipeline->front().Name;
if (!isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks))
return make_error<StringError>(
formatv("unknown cgscc pass '{0}' in pipeline '{1}'", FirstName,
PipelineText)
.str(),
inconvertibleErrorCode());
if (auto Err =
parseCGSCCPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
return Err;
return Error::success();
}
// Primary pass pipeline description parsing routine for a \c
// FunctionPassManager
Error PassBuilder::parsePassPipeline(FunctionPassManager &FPM,
StringRef PipelineText,
bool VerifyEachPass, bool DebugLogging) {
auto Pipeline = parsePipelineText(PipelineText);
if (!Pipeline || Pipeline->empty())
return make_error<StringError>(
formatv("invalid pipeline '{0}'", PipelineText).str(),
inconvertibleErrorCode());
StringRef FirstName = Pipeline->front().Name;
if (!isFunctionPassName(FirstName, FunctionPipelineParsingCallbacks))
return make_error<StringError>(
formatv("unknown function pass '{0}' in pipeline '{1}'", FirstName,
PipelineText)
.str(),
inconvertibleErrorCode());
if (auto Err = parseFunctionPassPipeline(FPM, *Pipeline, VerifyEachPass,
DebugLogging))
return Err;
return Error::success();
}
// Primary pass pipeline description parsing routine for a \c LoopPassManager
Error PassBuilder::parsePassPipeline(LoopPassManager &CGPM,
StringRef PipelineText,
bool VerifyEachPass, bool DebugLogging) {
auto Pipeline = parsePipelineText(PipelineText);
if (!Pipeline || Pipeline->empty())
return make_error<StringError>(
formatv("invalid pipeline '{0}'", PipelineText).str(),
inconvertibleErrorCode());
if (auto Err =
parseLoopPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
return Err;
return Error::success();
}
Error PassBuilder::parseAAPipeline(AAManager &AA, StringRef PipelineText) {
// If the pipeline just consists of the word 'default' just replace the AA
// manager with our default one.
if (PipelineText == "default") {
AA = buildDefaultAAPipeline();
return Error::success();
}
while (!PipelineText.empty()) {
StringRef Name;
std::tie(Name, PipelineText) = PipelineText.split(',');
if (!parseAAPassName(AA, Name))
return make_error<StringError>(
formatv("unknown alias analysis name '{0}'", Name).str(),
inconvertibleErrorCode());
}
return Error::success();
}
| [
"66802431+novt-vtable-less-compiler@users.noreply.github.com"
] | 66802431+novt-vtable-less-compiler@users.noreply.github.com |
242236f973b8888bff34a2d6fccb8b833022b030 | 9cffee1d6394db14d38f6c8f3bdab689ccd83018 | /Week05/solutions/pdfSolutions/task06_v2.cpp | 37283cc35b9b9ec0cc3b610d863187592ef4688a | [] | no_license | lachaka/IS-Introduction-to-Programming-2018 | 2f4a203a40b3e8533546f77dc5a20dee4c007efd | 55967828af13cfc9498248a0bdcb259d39415b30 | refs/heads/master | 2020-04-01T18:01:20.194000 | 2018-12-18T15:11:59 | 2018-12-18T15:11:59 | 153,466,286 | 0 | 0 | null | 2018-10-17T13:58:23 | 2018-10-17T13:58:22 | null | UTF-8 | C++ | false | false | 348 | cpp | #include <iostream>
#include <math.h>
using namespace std;
int main(int argc, char const *argv[]) {
int num = 0, temp = 0, digits = 0;
cin >> num;
temp = num;
for (; temp > 0; digits++, temp /= 10);
if (digits > 3) {
for (int i = 0; i < num; i++) {
if (i % 2 == 0) {
cout << i << " ";
}
}
cout << endl;
}
return 0;
} | [
"lachomladenov@gmail.com"
] | lachomladenov@gmail.com |
893a754c7e49886ef60d6981b38cd9e2766ae896 | 509af65f6549bc49ccca6417ef43da10cccb579d | /modules/front/src/front/mvc/view.cpp | 0ddda05bd7094432632e965ebd79f23de8beccad | [] | no_license | guoyu07/crails | 082bb36e888bb41a33f9170644431f958e3cb9a6 | 97ca4c50420e9c8b85cb537a9fb1055224745f08 | refs/heads/master | 2021-06-25T00:14:23.580295 | 2017-08-20T13:47:01 | 2017-08-20T13:47:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,509 | cpp | #include <crails/front/mvc/view.hpp>
using namespace std;
using namespace Crails::Front;
View::View()
{}
View::~View()
{
clear_connected_listeners();
empty();
}
void View::empty()
{
if (el->get_parentNode())
el->get_parentNode()->removeChild(*el);
}
void View::attach(Element& el)
{
this->el.append_to(*el);
}
void View::add_event_listener(const string& selector, const string& name, DomEventListener::JsCallback callback)
{
DomEventListener event_listener;
event_listener.selector = selector;
event_listener.event = name;
event_listener.callback = callback;
event_listeners.push_back(event_listener);
}
void View::delegate_events()
{
clear_connected_listeners();
for (auto event_listener : event_listeners)
{
vector<Element> elements;
elements = el.find(event_listener.selector);
for (auto element : elements)
{
client::EventListener* callback = cheerp::Callback(event_listener.callback);
pair<string, client::EventListener*> tmp(event_listener.event, callback);
element->addEventListener(event_listener.event.c_str(), callback);
connected_listeners.push_back(
ConnectedListeners::value_type(*element, tmp)
);
}
}
}
void View::clear_connected_listeners()
{
for (auto connected_listener : connected_listeners)
{
auto listener_data = connected_listener.second;
connected_listener.first->removeEventListener(listener_data.first.c_str(), listener_data.second);
}
connected_listeners.clear();
}
| [
"michael@unetresgrossebite.com"
] | michael@unetresgrossebite.com |
3bec3e20b39a4c678b8062d53dd5d17e263de503 | 987329320d9b229a950594d0b22dfd66ef633d04 | /inpres-PFM-chat/Chat_C/Librairie/socket/socketClient.h | 327a8851eba9ee8a94882ecfe4b837f1b202d92c | [] | no_license | Jefidev/Reseau | 8ec64e07fb39a36b8bf001f2d542a75507388982 | 125d72fd5b91a991498229603f13964191bae44c | refs/heads/master | 2021-05-31T09:27:10.736465 | 2016-04-17T11:51:57 | 2016-04-17T11:51:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 232 | h | #ifndef SOCKETCLIENT_H_INCLUDED
#define SOCKETCLIENT_H_INCLUDED
class SocketClient: public Socket
{
public :
SocketClient(string host, int port, bool isIP);
~SocketClient();
/* METHODES */
void connecter();
};
#endif
| [
"jeromefink@hotmail.com"
] | jeromefink@hotmail.com |
61ad592af1e89b4957bc87a015219ca6b80ba300 | 8b1912896f00fb47ca67d05d422b14c393faf440 | /include/LCTopologicalAssociation/BackscatteredTracksAlgorithm.h | 8ce9d053f5e59847970e65f932eec22175710128 | [] | no_license | lgray/LCContent | 4dbdeb7fdb2e67bba8cf553b1dddb62b5fb6d3d0 | ae0a5fb6c96919096c168aeddada62ead04f1764 | refs/heads/master | 2021-01-16T20:31:55.747823 | 2015-03-11T22:40:45 | 2015-03-11T22:40:45 | 29,965,231 | 0 | 2 | null | 2015-02-23T01:12:02 | 2015-01-28T11:50:31 | C++ | UTF-8 | C++ | false | false | 2,311 | h | /**
* @file LCContent/include/LCTopologicalAssociation/BackscatteredTracksAlgorithm.h
*
* @brief Header file for the backscattered tracks algorithm class.
*
* $Log: $
*/
#ifndef LC_BACKSCATTERED_TRACKS_ALGORITHM_H
#define LC_BACKSCATTERED_TRACKS_ALGORITHM_H 1
#include "Pandora/Algorithm.h"
namespace lc_content
{
/**
* @brief BackscatteredTracksAlgorithm class
*/
class BackscatteredTracksAlgorithm : public pandora::Algorithm
{
public:
/**
* @brief Factory class for instantiating algorithm
*/
class Factory : public pandora::AlgorithmFactory
{
public:
pandora::Algorithm *CreateAlgorithm() const;
};
/**
* @brief Default constructor
*/
BackscatteredTracksAlgorithm();
private:
pandora::StatusCode Run();
pandora::StatusCode ReadSettings(const pandora::TiXmlHandle xmlHandle);
float m_canMergeMinMipFraction; ///< The min mip fraction for clusters (flagged as photons) to be merged
float m_canMergeMaxRms; ///< The max all hit fit rms for clusters (flagged as photons) to be merged
unsigned int m_minCaloHitsPerCluster; ///< The min number of calo hits for cluster to be used as a daughter cluster
float m_fitToAllHitsRmsCut; ///< The max rms value (for the fit to all hits) to use cluster as a daughter
unsigned int m_nOuterFitExclusionLayers; ///< The number of outer layers to exclude from the daughter cluster fit
unsigned int m_nFitProjectionLayers; ///< The number of layers to project daughter fit for comparison with parent clusters
float m_maxFitDistanceToClosestHit; ///< Max distance between daughter cluster fit and hits in parent cluster
float m_maxCentroidDistance; ///< Max value of closest layer centroid distance between parent/daughter clusters
};
//------------------------------------------------------------------------------------------------------------------------------------------
inline pandora::Algorithm *BackscatteredTracksAlgorithm::Factory::CreateAlgorithm() const
{
return new BackscatteredTracksAlgorithm();
}
} // namespace lc_content
#endif // #ifndef LC_BACKSCATTERED_TRACKS_ALGORITHM_H
| [
"marshall@hep.phy.cam.ac.uk"
] | marshall@hep.phy.cam.ac.uk |
22fbfdf42b4649a801e47bb16c41c189d0351cd6 | 7e7df719fb91221be5ecbb02dcdeafe8fb784960 | /Lab11/Lab11/Lab11.cpp | 73e1c624f80a39cdf2eefc162fac43cab1642669 | [] | no_license | A-men007/CS-1037 | d92507dd80bb1fec04e0106d2a8cbeb9a75884e1 | 6b37375f9a53eb174d0f99657f31a6f56fd3ba3f | refs/heads/main | 2023-06-02T19:44:32.562902 | 2021-06-24T23:37:29 | 2021-06-24T23:37:29 | 380,074,218 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,588 | cpp | #include <iostream>
#include <string>
using namespace std;
#include "DoublyLinkedList.h"
void quit(string msg = "") {
cout << msg << endl;
char z;
cin >> z;
exit(0);
}
int main(int argc, char *argv[]) {
DoublyLinkedList<int> dll;
//Instruction 10
cout << "Constructor" << endl;
if (!dll.validate(0)) quit();
//Instruction 11
cout << "Add head to empty list" << endl;
dll.addHead(1);
if (!dll.validate(1,1)) quit();
cout << "Add head to non-empty list" << endl;
dll.addHead(2);
if (!dll.validate(2,2,1)) quit();
//Instruction 12
cout << "Remove head from 2 node list" << endl;
if (dll.removeHead()!=2) quit("Failed to return correct value");
if (!dll.validate(1,1)) quit();
cout << "Remove head from 1 node list" << endl;
if (dll.removeHead()!=1) quit("Failed to return correct value");
if (!dll.validate(0)) quit();
//Instruction 13
cout << "Add tail to empty list" << endl;
dll.addTail(1);
if (!dll.validate(1,1)) quit();
cout << "Add tail to non-empty list" << endl;
dll.addTail(2);
if (!dll.validate(2,1,2)) quit();
cout << "Remove tail from 2 node list" << endl;
if (dll.removeTail()!=2) quit("Failed to return correct value");
if (!dll.validate(1,1)) quit();
cout << "Remove tail from 1 node list" << endl;
if (dll.removeTail()!=1) quit("Failed to return correct value");
if (!dll.validate(0)) quit();
//Instruction 14
cout << "Replace middle node value" << endl;
dll.addTail(2);
dll.addTail(4);
dll.addTail(6);
if (dll.replace(2,9)!=4) quit("Failed to return correct value");
if (!dll.validate(3,2,9,6)) quit();
//Instruction 15
cout << "test retrieve methods" << endl;
dll.addTail(10);
dll.addTail(11);
if (dll.retrieveHead()!=2) quit("Failed to retrieve head value");
if (dll.retrieveTail()!=11) quit("Failed to retrieve tail value");
int tarr[]={2,9,6,10,11};
for (unsigned x=0;x<5;x++)
if (dll.retrieve(x+1)!=tarr[x]) quit("Failed to retrieve pos value");
//Instruction 16
cout << "test remove methods" << endl;
if (dll.remove(2)!=9) quit("Failed to remove pos 2 value");
if (!dll.validate(4,2,6,10,11)) quit();
if (dll.remove(3)!=10) quit("Failed to remove pos 3 value");
if (!dll.validate(3,2,6,11)) quit();
//Instruction 17
cout << "test add methods" << endl;
dll.add(2,88);
if (!dll.validate(4,2,88,6,11)) quit();
dll.add(4,99);
if (!dll.validate(5,2,88,6,99,11)) quit();
//Instruction 18
cout << "test find method" << endl;
if (dll.find(88)!=2) quit("Failed to find 88 value");
if (dll.find(2)!=1) quit("Failed to find 2 value");
if (dll.find(11)!=5) quit("Failed to find 11 value");
//Instruction 21
int x,farr[]={2,88,6,99,11};
cout << "test iterators" << endl;
DoublyLinkedList<int>::Iterator start=dll.begin(),last=dll.last();
for (x=0;x<5;x++){
if (start.getValue()!=farr[x]) quit("Failed forward iterator");
++start;
}
for (x=4;x>=0;x--){
if (last.getValue()!=farr[x]) quit("Failed backward iterator");
--last;
}
x=0;
for (DoublyLinkedList<int>::Iterator curr=dll.begin();curr!=dll.end();++curr){
if (curr.getValue()!=farr[x]) quit("Failed forloop iterator");
x++;
}
x=4;
for (DoublyLinkedList<int>::Iterator curr=dll.last();curr!=dll.end();--curr){
if (curr.getValue()!=farr[x]) quit("Failed forloop-reverse iterator");
x--;
}
cout << "test unchanged" << endl;
if (!dll.validate(5,2,88,6,99,11)) quit();
cout << "PASS!!!";
char z;
cin >> z;
return(0);
}
| [
"amanpreetg100@gmail.com"
] | amanpreetg100@gmail.com |
6932bc2a620a43c1dca55140dfa0325fc51a7d38 | 2d8d53db5113693f275b839b27c6c51aed7801df | /oop_exercise_06/quenue.h | a46adc6be355521668d2a2dd308f95a869616714 | [] | no_license | poisoned-monkey/OOP_labs4_6_7 | a89869fe50de0d6491f39d6b2e72bf43900ce6f8 | b12adaa64f24dee479208399f805dda9ef098284 | refs/heads/master | 2022-09-07T19:23:57.532165 | 2020-05-24T22:27:04 | 2020-05-24T22:27:04 | 266,622,907 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,130 | h | #pragma once
#include <memory>
#include "allocators.h"
namespace oop
{
template<typename Q>
class queue_forward_iterator
{
};
template <typename T, typename TBaseAllocator = std::allocator<T>>
class queue
{
struct node;
using allocator = typename std::allocator_traits<TBaseAllocator>::template rebind_alloc<node>;
struct deleter
{
explicit deleter(allocator& al) noexcept
: al_(al)
{}
void operator()(node* ptr)
{
std::allocator_traits<allocator>::destroy(al_, ptr);
al_.deallocate(ptr, 1);
}
private:
allocator& al_;
};
struct node
{
T value;
std::shared_ptr<node> next;
explicit node(const T& v, deleter& d) noexcept
: value(v)
, next(nullptr, d)
{}
};
public:
queue()
: deleter_(al_)
, first_(nullptr, deleter_)
, last_(nullptr)
, size_(0)
{}
void pop()
{
if (first_)
{
first_ = std::move(first_->next);
}
--size_;
}
void push(const T& v)
{
node* obj = al_.allocate(1);
std::allocator_traits<allocator>::construct(al_, obj, v, deleter_);
if (last_)
{
last_->next.reset(obj);
}
else
{
first_.reset(obj);
}
last_ = obj;
++size_;
}
[[nodiscard]] T& top()
{
return first_->value;
}
[[nodiscard]] size_t size() const noexcept
{
return size_;
}
private:
allocator al_;
deleter deleter_;
std::shared_ptr<node> first_;
node* last_;
size_t size_;
friend struct node;
};
} | [
"alcuzmichev@yandex.ru"
] | alcuzmichev@yandex.ru |
58f9778ac43eee0d9bf20becf4b66a748a8b05be | cbbe70ce827e09fa81cc00df7b133b6a5508d923 | /tests/statement_semi_block.cc | 15b56219a0123b986656579faf33c0afaa2ea50b | [
"Apache-2.0"
] | permissive | libattachsql/libattachsql | cc9cbaac4903b2104b7eede53eb9d254f16acfd8 | 7b82164efd09292a62f086a05bd6401ce8c23167 | refs/heads/master | 2021-05-19T02:20:05.170030 | 2018-03-28T16:23:33 | 2018-03-28T16:23:33 | 22,472,706 | 25 | 16 | Apache-2.0 | 2020-08-28T05:53:49 | 2014-07-31T14:43:08 | C++ | UTF-8 | C++ | false | false | 3,361 | cc | /* vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
* Copyright 2014 Hewlett-Packard Development Company, L.P.
*
* 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 <yatl/lite.h>
#include "version.h"
#include <libattachsql2/attachsql.h>
int main(int argc, char *argv[])
{
(void) argc;
(void) argv;
attachsql_connect_t *con;
attachsql_error_t *error= NULL;
const char *data= "SELECT ? as a, ? as b, CONVERT_TZ(FROM_UNIXTIME(1196440219),@@session.time_zone,'+00:00') as c";
const char *data2= "hello world";
attachsql_return_t aret= ATTACHSQL_RETURN_NONE;
uint16_t columns;
con= attachsql_connect_create("localhost", 3306, "test", "test", "", NULL);
attachsql_connect_set_option(con, ATTACHSQL_OPTION_SEMI_BLOCKING, NULL);
attachsql_statement_prepare(con, strlen(data), data, &error);
ASSERT_FALSE_(error, "Statement creation error");
while(aret != ATTACHSQL_RETURN_EOF)
{
aret= attachsql_connect_poll(con, &error);
if (error && (attachsql_error_code(error) == 2002))
{
SKIP_IF_(true, "No MYSQL server");
}
else if (error)
{
ASSERT_FALSE_(true, "Error exists: %d", attachsql_error_code(error));
}
}
ASSERT_EQ_(2, attachsql_statement_get_param_count(con), "Wrong number of params");
attachsql_statement_set_string(con, 0, 11, data2, NULL);
attachsql_statement_set_int(con, 1, 123456, NULL);
attachsql_statement_execute(con, &error);
aret= ATTACHSQL_RETURN_NONE;
while(aret != ATTACHSQL_RETURN_EOF)
{
aret= attachsql_connect_poll(con, &error);
if (aret == ATTACHSQL_RETURN_ROW_READY)
{
columns= attachsql_statement_get_column_count(con);
attachsql_statement_row_get(con, &error);
printf("Got %d columns\n", columns);
size_t len;
char *col_data= attachsql_statement_get_char(con, 0, &len, &error);
printf("Column 0: %.*s\n", (int)len, col_data);
printf("Column 1: %d\n", attachsql_statement_get_int(con, 1, &error));
ASSERT_EQ_(123456, attachsql_statement_get_int(con, 1, &error), "Column 1 result match fail");
ASSERT_EQ_(ATTACHSQL_COLUMN_TYPE_LONG, attachsql_statement_get_column_type(con, 1), "Column 1 type match fail");
ASSERT_STREQL_("hello world", col_data, len, "Column 0 result match fail");
col_data= attachsql_statement_get_char(con, 1, &len, &error);
ASSERT_STREQL_("123456", col_data, len, "Column 0 str conversion fail");
col_data= attachsql_statement_get_char(con, 2, &len, &error);
printf("Column 2: %.*s\n", (int)len, col_data);
ASSERT_STREQL_("2007-11-30 16:30:19", col_data, len, "Column 2 str conversion fail");
attachsql_statement_row_next(con);
}
if (error)
{
ASSERT_FALSE_(true, "Error exists: %d", attachsql_error_code(error));
}
}
attachsql_statement_close(con);
attachsql_connect_destroy(con);
}
| [
"andrew@linuxjedi.co.uk"
] | andrew@linuxjedi.co.uk |
84909134610a8b306632a0aae0eff1d43a8f8114 | 57bfbaf998d51dc9a862a0cf5bc462b452e02dca | /pitendo.cpp | 8aafdfb92ecd0a84d0a7006823d1398e965cded0 | [] | no_license | startbit96/pitendo | 5f11d82a699a80b9a4c1754348bdb1f4df420a80 | 5a111f1594b2357047539157f0970681871de433 | refs/heads/master | 2022-04-12T04:36:43.761323 | 2020-03-19T20:06:32 | 2020-03-19T20:06:32 | 235,193,852 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,922 | cpp | #include <iostream>
#include "pitendo_game_engine.h"
// Spiele koennen hier eingeladen werden.
#include "template.h"
#include "flappy_bird.h"
using namespace std;
int main(int argc, char** argv) {
// ##############################################################################
// ##### PITENDO-SETUP #####
// ##############################################################################
// Bildschirm initialisieren.
if (argc == 1) {
// Dies ist der Aufruf durch den Nutzer.
// Initialisiere Pitendo (ueberpruefe Abhaengigkeiten und starte Pitendo in einem eigenen
// Terminal erneut).
if (pitendoInit() == true) {
cout << "Pitendo erfolgreich initialisiert." << endl;
cout << "Pitendo wird in einem separaten Fenster gestartet." << endl;
return 1;
}
else {
cout << "Pitendo konnte nicht initialisiert werden." << endl;
return -1;
}
}
// Pitendo final vorbereiten und einrichten.
if (pitendoSetup() == true) {
cout << "Pitendo erfolgreich eingerichtet." << endl;
}
else {
cout << "Pitendo konnte nicht eingerichtet werden." << endl;
cout << "Zum Beenden ENTER druecken ..." << endl;
cin.get(); // Nutzereingabe abwarten, damit Nutzer Zeit hat, Fehlermeldung zu lesen.
return -1;
}
// ##############################################################################
// ##### SPIELE-REGISTRIERUNG #####
// ##############################################################################
// Spiele befinden sich spaeter in umgekehrter Reihenfolge im Menue.
pitendoGE->addGame("Vorlage-Spiel", &gameTemplate::gameStart);
pitendoGE->addGame("Flappy Bird", &flappyBird::gameStart);
// ##############################################################################
// ##### PITENDO-DAUERSCHLEIFE #####
// ##############################################################################
// Willkommens-Bildschirm.
pitendoStartScreen();
// Dauerschleife.
while(pitendoGE->isRunning == true) {
// Die der Game-Engine hinterlegte Funktion ausfuehren.
pitendoGE->gameEngineFunction();
// Display aktualisieren.
cout << flush;
// System pausieren (fps einstellen).
pitendoGE->adjustFPS();
}
// ##############################################################################
// ##### ABSCHLIESSENDE HANDLUNGEN #####
// ##############################################################################
// Dauerschleife wurde verlassen. Pitendo soll beendet werden.
pitendoDestroy();
return 1;
} | [
"timschwarzbrunn2@googlemail.com"
] | timschwarzbrunn2@googlemail.com |
31e084bc357a75b86e74500acee655b883cff467 | 2af943fbfff74744b29e4a899a6e62e19dc63256 | /IGTLoadableModules/IGTWizard/Wizard/vtkIGTWizardSecondStep.h | 9d1affaca31abc56f57fd80f7286dc17701489a1 | [] | no_license | lheckemann/namic-sandbox | c308ec3ebb80021020f98cf06ee4c3e62f125ad9 | 0c7307061f58c9d915ae678b7a453876466d8bf8 | refs/heads/master | 2021-08-24T12:40:01.331229 | 2014-02-07T21:59:29 | 2014-02-07T21:59:29 | 113,701,721 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,680 | h | /*==========================================================================
Portions (c) Copyright 2008 Brigham and Women's Hospital (BWH) All Rights Reserved.
See Doc/copyright/copyright.txt
or http://www.slicer.org/copyright/copyright.txt for details.
Program: 3D Slicer
Module: $HeadURL: $
Date: $Date: $
Version: $Revision: $
==========================================================================*/
#ifndef __vtkIGTWizardSecondStep_h
#define __vtkIGTWizardSecondStep_h
#include "vtkIGTWizardStepBase.h"
#include "vtkCommand.h"
class vtkKWLoadSaveButtonWithLabel;
class vtkKWFrame;
class vtkKWEntry;
class vtkKWCheckButton;
class vtkKWPushButton;
class vtkKWLabel;
class VTK_IGTWIZARD_EXPORT vtkIGTWizardSecondStep :
public vtkIGTWizardStepBase
{
public:
static vtkIGTWizardSecondStep *New();
vtkTypeRevisionMacro(vtkIGTWizardSecondStep,vtkIGTWizardStepBase);
void PrintSelf(ostream& os, vtkIndent indent);
virtual void ShowUserInterface();
virtual void ProcessGUIEvents(vtkObject *caller, unsigned long event, void *callData);
protected:
vtkIGTWizardSecondStep();
~vtkIGTWizardSecondStep();
// GUI Widgets
vtkKWFrame *RobotFrame;
vtkKWLabel *RobotLabel1;
vtkKWLabel *RobotLabel2;
vtkKWEntry *RobotAddressEntry;
vtkKWEntry *RobotPortEntry;
vtkKWPushButton *RobotConnectButton;
vtkKWFrame *ScannerFrame;
vtkKWLabel *ScannerLabel1;
vtkKWLabel *ScannerLabel2;
vtkKWEntry *ScannerAddressEntry;
vtkKWEntry *ScannerPortEntry;
vtkKWPushButton *ScannerConnectButton;
private:
vtkIGTWizardSecondStep(const vtkIGTWizardSecondStep&);
void operator=(const vtkIGTWizardSecondStep&);
};
#endif
| [
"tokuda@5e132c66-7cf4-0310-b4ca-cd4a7079c2d8"
] | tokuda@5e132c66-7cf4-0310-b4ca-cd4a7079c2d8 |
855693335de792dc5921b1bc120e0800a87b3e32 | 8a2e417c772eba9cf4653d0c688dd3ac96590964 | /prop-src/timespace.cc | 913ff1c57368f1f3bc9d1a2ec6069a0ec76d3c28 | [
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | romix/prop-cc | 1a190ba6ed8922428352826de38efb736e464f50 | 3f7f2e4a4d0b717f4e4f3dbd4c7f9d1f35572f8f | refs/heads/master | 2023-08-30T12:55:00.192286 | 2011-07-19T20:56:39 | 2011-07-19T20:56:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,693 | cc | ///////////////////////////////////////////////////////////////////////////////
// This file is generated automatically using Prop (version 2.4.0),
// last updated on Jul 1, 2011.
// The original source file is "..\..\prop-src\timespace.pcc".
///////////////////////////////////////////////////////////////////////////////
#define PROP_REWRITING_USED
#define PROP_QUARK_USED
#include <propdefs.h>
#line 1 "../../prop-src/timespace.pcc"
///////////////////////////////////////////////////////////////////////////////
//
// This file implements the time and space complexity
// datatypes. These datatypes are used to represent time and space
// complexity in the SETL-like extension language.
//
///////////////////////////////////////////////////////////////////////////////
#include <math.h>
#include <iostream>
#include "basics.h"
#include "timespace.h"
///////////////////////////////////////////////////////////////////////////////
//
// Instantiate the time and space datatypes
//
///////////////////////////////////////////////////////////////////////////////
#line 21 "../../prop-src/timespace.pcc"
#line 21 "../../prop-src/timespace.pcc"
///////////////////////////////////////////////////////////////////////////////
//
// Interface specification of datatype Complexity
//
///////////////////////////////////////////////////////////////////////////////
#line 21 "../../prop-src/timespace.pcc"
///////////////////////////////////////////////////////////////////////////////
//
// Interface specification of datatype Time
//
///////////////////////////////////////////////////////////////////////////////
#line 21 "../../prop-src/timespace.pcc"
///////////////////////////////////////////////////////////////////////////////
//
// Interface specification of datatype Space
//
///////////////////////////////////////////////////////////////////////////////
#line 21 "../../prop-src/timespace.pcc"
///////////////////////////////////////////////////////////////////////////////
//
// Instantiation of datatype Complexity
//
///////////////////////////////////////////////////////////////////////////////
#line 21 "../../prop-src/timespace.pcc"
///////////////////////////////////////////////////////////////////////////////
//
// Instantiation of datatype Time
//
///////////////////////////////////////////////////////////////////////////////
#line 21 "../../prop-src/timespace.pcc"
///////////////////////////////////////////////////////////////////////////////
//
// Instantiation of datatype Space
//
///////////////////////////////////////////////////////////////////////////////
#line 21 "../../prop-src/timespace.pcc"
#line 21 "../../prop-src/timespace.pcc"
#line 21 "../../prop-src/timespace.pcc"
///////////////////////////////////////////////////////////////////////////////
//
// Pretty print the complexity
//
///////////////////////////////////////////////////////////////////////////////
std::ostream& operator << (std::ostream& f, Complexity c)
{
#line 31 "../../prop-src/timespace.pcc"
#line 42 "../../prop-src/timespace.pcc"
{
switch (c->tag__) {
case a_Complexity::tag_Var: {
#line 33 "../../prop-src/timespace.pcc"
f << _Var(c)->Var;
#line 33 "../../prop-src/timespace.pcc"
} break;
case a_Complexity::tag_Add: {
#line 34 "../../prop-src/timespace.pcc"
f << '(' << _Add(c)->_1 << " + " << _Add(c)->_2 << ')';
#line 34 "../../prop-src/timespace.pcc"
} break;
case a_Complexity::tag_Mul: {
#line 35 "../../prop-src/timespace.pcc"
f << '(' << _Mul(c)->_1 << " * " << _Mul(c)->_2 << ')';
#line 35 "../../prop-src/timespace.pcc"
} break;
case a_Complexity::tag_Div: {
#line 36 "../../prop-src/timespace.pcc"
f << '(' << _Div(c)->_1 << " / " << _Div(c)->_2 << ')';
#line 36 "../../prop-src/timespace.pcc"
} break;
case a_Complexity::tag_Power: {
#line 37 "../../prop-src/timespace.pcc"
f << '(' << _Power(c)->_1 << " ^ " << _Power(c)->_2 << ')';
#line 37 "../../prop-src/timespace.pcc"
} break;
case a_Complexity::tag_Log: {
#line 38 "../../prop-src/timespace.pcc"
f << "log " << _Log(c)->Log;
#line 38 "../../prop-src/timespace.pcc"
} break;
case a_Complexity::tag_Const: {
#line 39 "../../prop-src/timespace.pcc"
f << _Const(c)->Const;
#line 39 "../../prop-src/timespace.pcc"
} break;
case a_Complexity::tag_BigOh: {
#line 40 "../../prop-src/timespace.pcc"
f << "O(" << _BigOh(c)->BigOh << ')';
#line 40 "../../prop-src/timespace.pcc"
} break;
case a_Complexity::tag_Omega: {
#line 41 "../../prop-src/timespace.pcc"
f << "Omega(" << _Omega(c)->Omega << ')';
#line 41 "../../prop-src/timespace.pcc"
} break;
default: {
#line 42 "../../prop-src/timespace.pcc"
f << "o(" << _LittleOh(c)->LittleOh << ')';
#line 42 "../../prop-src/timespace.pcc"
} break;
}
}
#line 43 "../../prop-src/timespace.pcc"
#line 43 "../../prop-src/timespace.pcc"
return f;
}
///////////////////////////////////////////////////////////////////////////////
//
// Pretty print the time complexity
//
///////////////////////////////////////////////////////////////////////////////
std::ostream& operator << (std::ostream& f, Time t)
{ return f << "Time(" << t << ")"; }
///////////////////////////////////////////////////////////////////////////////
//
// Pretty print the space complexity
//
///////////////////////////////////////////////////////////////////////////////
std::ostream& operator << (std::ostream& f, Space s)
{ return f << "Space(" << s << ")"; }
///////////////////////////////////////////////////////////////////////////////
//
// Function to simplify a complexity expression
//
///////////////////////////////////////////////////////////////////////////////
Complexity simplify (Complexity c)
{
#line 73 "../../prop-src/timespace.pcc"
#line 79 "../../prop-src/timespace.pcc"
extern void cocofmcocofm_p_r_o_pcn_s_r_cfm_t_i_m_e_s_p_a_c_eco_X1_rewrite(Complexity & );
cocofmcocofm_p_r_o_pcn_s_r_cfm_t_i_m_e_s_p_a_c_eco_X1_rewrite(c);
#line 79 "../../prop-src/timespace.pcc"
#line 79 "../../prop-src/timespace.pcc"
return c;
}
#line 82 "../../prop-src/timespace.pcc"
class cocofmcocofm_p_r_o_pcn_s_r_cfm_t_i_m_e_s_p_a_c_eco_X1 : public BURS {
private:
cocofmcocofm_p_r_o_pcn_s_r_cfm_t_i_m_e_s_p_a_c_eco_X1(const cocofmcocofm_p_r_o_pcn_s_r_cfm_t_i_m_e_s_p_a_c_eco_X1&); // no copy constructor
void operator = (const cocofmcocofm_p_r_o_pcn_s_r_cfm_t_i_m_e_s_p_a_c_eco_X1&); // no assignment
public:
struct cocofmcocofm_p_r_o_pcn_s_r_cfm_t_i_m_e_s_p_a_c_eco_X1_StateRec * stack__, * stack_top__;
public:
void labeler(const char *, int&, int);
void labeler(Quark, int&, int);
void labeler(Complexity & redex, int&, int);
inline virtual void operator () (Complexity & redex) { int s; labeler(redex,s,0); }
private:
public:
inline cocofmcocofm_p_r_o_pcn_s_r_cfm_t_i_m_e_s_p_a_c_eco_X1() {}
};
void cocofmcocofm_p_r_o_pcn_s_r_cfm_t_i_m_e_s_p_a_c_eco_X1_rewrite(Complexity & _x_)
{ cocofmcocofm_p_r_o_pcn_s_r_cfm_t_i_m_e_s_p_a_c_eco_X1 _r_;
_r_(_x_);
}
///////////////////////////////////////////////////////////////////////////////
//
// This macro can be redefined by the user for debugging
//
///////////////////////////////////////////////////////////////////////////////
#ifndef DEBUG_cocofmcocofm_p_r_o_pcn_s_r_cfm_t_i_m_e_s_p_a_c_eco_X1
#define DEBUG_cocofmcocofm_p_r_o_pcn_s_r_cfm_t_i_m_e_s_p_a_c_eco_X1(repl,redex,file,line,rule) repl
#else
static const char * cocofmcocofm_p_r_o_pcn_s_r_cfm_t_i_m_e_s_p_a_c_eco_X1_file_name = "..\..\prop-src\timespace.pcc";
#endif
static const TreeTables::ShortState cocofmcocofm_p_r_o_pcn_s_r_cfm_t_i_m_e_s_p_a_c_eco_X1_theta_1[2][2] = {
{ 0, 0 },
{ 0, 2 }
};
static const TreeTables::ShortState cocofmcocofm_p_r_o_pcn_s_r_cfm_t_i_m_e_s_p_a_c_eco_X1_theta_2[2][2] = {
{ 0, 0 },
{ 0, 3 }
};
static const TreeTables::ShortState cocofmcocofm_p_r_o_pcn_s_r_cfm_t_i_m_e_s_p_a_c_eco_X1_theta_3[2][2] = {
{ 0, 0 },
{ 0, 4 }
};
static const TreeTables::ShortState cocofmcocofm_p_r_o_pcn_s_r_cfm_t_i_m_e_s_p_a_c_eco_X1_theta_4[2][2] = {
{ 0, 0 },
{ 0, 5 }
};
static const TreeTables::ShortState cocofmcocofm_p_r_o_pcn_s_r_cfm_t_i_m_e_s_p_a_c_eco_X1_theta_5[2] = {
0, 6
};
static const TreeTables::ShortState cocofmcocofm_p_r_o_pcn_s_r_cfm_t_i_m_e_s_p_a_c_eco_X1_mu_1_0[7] = {
0, 1, 0, 0, 0, 0, 0
};
static const TreeTables::ShortState cocofmcocofm_p_r_o_pcn_s_r_cfm_t_i_m_e_s_p_a_c_eco_X1_mu_1_1[7] = {
0, 1, 0, 0, 0, 0, 0
};
static const TreeTables::ShortState cocofmcocofm_p_r_o_pcn_s_r_cfm_t_i_m_e_s_p_a_c_eco_X1_mu_2_0[7] = {
0, 1, 0, 0, 0, 0, 0
};
static const TreeTables::ShortState cocofmcocofm_p_r_o_pcn_s_r_cfm_t_i_m_e_s_p_a_c_eco_X1_mu_2_1[7] = {
0, 1, 0, 0, 0, 0, 0
};
static const TreeTables::ShortState cocofmcocofm_p_r_o_pcn_s_r_cfm_t_i_m_e_s_p_a_c_eco_X1_mu_3_0[7] = {
0, 1, 0, 0, 0, 0, 0
};
static const TreeTables::ShortState cocofmcocofm_p_r_o_pcn_s_r_cfm_t_i_m_e_s_p_a_c_eco_X1_mu_3_1[7] = {
0, 1, 0, 0, 0, 0, 0
};
static const TreeTables::ShortState cocofmcocofm_p_r_o_pcn_s_r_cfm_t_i_m_e_s_p_a_c_eco_X1_mu_4_0[7] = {
0, 1, 0, 0, 0, 0, 0
};
static const TreeTables::ShortState cocofmcocofm_p_r_o_pcn_s_r_cfm_t_i_m_e_s_p_a_c_eco_X1_mu_4_1[7] = {
0, 1, 0, 0, 0, 0, 0
};
static const TreeTables::ShortState cocofmcocofm_p_r_o_pcn_s_r_cfm_t_i_m_e_s_p_a_c_eco_X1_mu_5_0[7] = {
0, 1, 0, 0, 0, 0, 0
};
inline void cocofmcocofm_p_r_o_pcn_s_r_cfm_t_i_m_e_s_p_a_c_eco_X1::labeler(char const * redex,int& s__,int)
{
{
s__ = 0;
}
}
inline void cocofmcocofm_p_r_o_pcn_s_r_cfm_t_i_m_e_s_p_a_c_eco_X1::labeler(Quark redex,int& s__,int)
{
{
s__ = 0;
}
}
void cocofmcocofm_p_r_o_pcn_s_r_cfm_t_i_m_e_s_p_a_c_eco_X1::labeler (Complexity & redex, int& s__, int r__)
{
replacement__:
switch(redex->tag__) {
case a_Complexity::tag_Var: {
int s0__;
labeler(_Var(redex)->Var, s0__, r__);
s__ = 0;} break;
case a_Complexity::tag_Add: {
int s0__;
int s1__;
labeler(_Add(redex)->_1, s0__, r__);
labeler(_Add(redex)->_2, s1__, r__);
s__ = cocofmcocofm_p_r_o_pcn_s_r_cfm_t_i_m_e_s_p_a_c_eco_X1_theta_1[cocofmcocofm_p_r_o_pcn_s_r_cfm_t_i_m_e_s_p_a_c_eco_X1_mu_1_0[s0__]][cocofmcocofm_p_r_o_pcn_s_r_cfm_t_i_m_e_s_p_a_c_eco_X1_mu_1_1[s1__]]; } break;
case a_Complexity::tag_Mul: {
int s0__;
int s1__;
labeler(_Mul(redex)->_1, s0__, r__);
labeler(_Mul(redex)->_2, s1__, r__);
s__ = cocofmcocofm_p_r_o_pcn_s_r_cfm_t_i_m_e_s_p_a_c_eco_X1_theta_2[cocofmcocofm_p_r_o_pcn_s_r_cfm_t_i_m_e_s_p_a_c_eco_X1_mu_2_0[s0__]][cocofmcocofm_p_r_o_pcn_s_r_cfm_t_i_m_e_s_p_a_c_eco_X1_mu_2_1[s1__]]; } break;
case a_Complexity::tag_Div: {
int s0__;
int s1__;
labeler(_Div(redex)->_1, s0__, r__);
labeler(_Div(redex)->_2, s1__, r__);
s__ = cocofmcocofm_p_r_o_pcn_s_r_cfm_t_i_m_e_s_p_a_c_eco_X1_theta_3[cocofmcocofm_p_r_o_pcn_s_r_cfm_t_i_m_e_s_p_a_c_eco_X1_mu_3_0[s0__]][cocofmcocofm_p_r_o_pcn_s_r_cfm_t_i_m_e_s_p_a_c_eco_X1_mu_3_1[s1__]]; } break;
case a_Complexity::tag_Power: {
int s0__;
int s1__;
labeler(_Power(redex)->_1, s0__, r__);
labeler(_Power(redex)->_2, s1__, r__);
s__ = cocofmcocofm_p_r_o_pcn_s_r_cfm_t_i_m_e_s_p_a_c_eco_X1_theta_4[cocofmcocofm_p_r_o_pcn_s_r_cfm_t_i_m_e_s_p_a_c_eco_X1_mu_4_0[s0__]][cocofmcocofm_p_r_o_pcn_s_r_cfm_t_i_m_e_s_p_a_c_eco_X1_mu_4_1[s1__]]; } break;
case a_Complexity::tag_Log: {
int s0__;
labeler(_Log(redex)->Log, s0__, r__);
s__ = cocofmcocofm_p_r_o_pcn_s_r_cfm_t_i_m_e_s_p_a_c_eco_X1_theta_5[cocofmcocofm_p_r_o_pcn_s_r_cfm_t_i_m_e_s_p_a_c_eco_X1_mu_5_0[s0__]]; } break;
case a_Complexity::tag_Const: {
int s0__;
s0__ = 0; // double
s__ = 1;} break;
case a_Complexity::tag_BigOh: {
int s0__;
labeler(_BigOh(redex)->BigOh, s0__, r__);
s__ = 0;} break;
case a_Complexity::tag_Omega: {
int s0__;
labeler(_Omega(redex)->Omega, s0__, r__);
s__ = 0;} break;
default: {
int s0__;
labeler(_LittleOh(redex)->LittleOh, s0__, r__);
s__ = 0;} break;
}
switch (s__) {
case 6: {
#line 78 "../../prop-src/timespace.pcc"
{ redex = DEBUG_cocofmcocofm_p_r_o_pcn_s_r_cfm_t_i_m_e_s_p_a_c_eco_X1(Const(log(_Const(_Log(redex)->Log)->Const)),redex,cocofmcocofm_p_r_o_pcn_s_r_cfm_t_i_m_e_s_p_a_c_eco_X1_file_name,78,"Log Const i: ...");
r__ = 1; goto replacement__; }
#line 79 "../../prop-src/timespace.pcc"
} break;
case 5: {
#line 77 "../../prop-src/timespace.pcc"
{ redex = DEBUG_cocofmcocofm_p_r_o_pcn_s_r_cfm_t_i_m_e_s_p_a_c_eco_X1(Const(exp((log(_Const(_Power(redex)->_1)->Const) * _Const(_Power(redex)->_2)->Const))),redex,cocofmcocofm_p_r_o_pcn_s_r_cfm_t_i_m_e_s_p_a_c_eco_X1_file_name,77,"Power (Const i, Const j): ...");
r__ = 1; goto replacement__; }
#line 78 "../../prop-src/timespace.pcc"
} break;
case 4: {
#line 76 "../../prop-src/timespace.pcc"
{ redex = DEBUG_cocofmcocofm_p_r_o_pcn_s_r_cfm_t_i_m_e_s_p_a_c_eco_X1(Const((_Const(_Div(redex)->_1)->Const / _Const(_Div(redex)->_2)->Const)),redex,cocofmcocofm_p_r_o_pcn_s_r_cfm_t_i_m_e_s_p_a_c_eco_X1_file_name,76,"Div (Const i, Const j): ...");
r__ = 1; goto replacement__; }
#line 77 "../../prop-src/timespace.pcc"
} break;
case 3: {
#line 75 "../../prop-src/timespace.pcc"
{ redex = DEBUG_cocofmcocofm_p_r_o_pcn_s_r_cfm_t_i_m_e_s_p_a_c_eco_X1(Const((_Const(_Mul(redex)->_1)->Const * _Const(_Mul(redex)->_2)->Const)),redex,cocofmcocofm_p_r_o_pcn_s_r_cfm_t_i_m_e_s_p_a_c_eco_X1_file_name,75,"Mul (Const i, Const j): ...");
r__ = 1; goto replacement__; }
#line 76 "../../prop-src/timespace.pcc"
} break;
case 2: {
#line 74 "../../prop-src/timespace.pcc"
{ redex = DEBUG_cocofmcocofm_p_r_o_pcn_s_r_cfm_t_i_m_e_s_p_a_c_eco_X1(Const((_Const(_Add(redex)->_1)->Const + _Const(_Add(redex)->_2)->Const)),redex,cocofmcocofm_p_r_o_pcn_s_r_cfm_t_i_m_e_s_p_a_c_eco_X1_file_name,74,"Add (Const i, Const j): ...");
r__ = 1; goto replacement__; }
#line 75 "../../prop-src/timespace.pcc"
} break;
}
}
/*
------------------------------- Statistics -------------------------------
Merge matching rules = yes
Number of DFA nodes merged = 0
Number of ifs generated = 0
Number of switches generated = 1
Number of labels = 0
Number of gotos = 0
Adaptive matching = disabled
Fast string matching = disabled
Inline downcasts = disabled
--------------------------------------------------------------------------
*/
| [
"aaronngray@gmail.com"
] | aaronngray@gmail.com |
f82424aa1b87860be7ca196a3390b54288c3b194 | c9fbc8dbb291988b71ccab46d15c6c7640b50a99 | /gameboy/src/harucar/LuaCommandViewer.cpp | 8af2d89b5a52efc264df5851264851c7046575bc | [
"MIT"
] | permissive | wooksong/study_emu | b209026f1d36484737f07fa10658878d778fb480 | 985ce70e260a3a7dd5e238376a2303017f3355d9 | refs/heads/master | 2023-07-13T10:25:18.812404 | 2021-08-30T15:41:40 | 2021-08-30T15:41:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 463 | cpp | //
// Created by nhy20 on 2020-11-01.
//
#include "LuaCommandViewer.h"
#include "imgui.h"
void LuaCommandViewer::Render(std::shared_ptr<Base::Interface::Provider> provider_ptr,
std::shared_ptr<UI::Structure::UIEventProtocol> protocol_ptr)
{
ImGui::Begin("Lua Command Viewer");
if (ImGui::Button("Reload"))
{
protocol_ptr->AddEvent("Lua:Reload");
}
if (ImGui::Button("Execute"))
{
protocol_ptr->AddEvent("Lua:Execute");
}
ImGui::End();
}
| [
"ffdd270@gmail.com"
] | ffdd270@gmail.com |
e527e00175dbc48a4039d13959ea572c47071f4d | 3c3139c68605c030bf0a16b9b42712c5561bc211 | /build-BibliotecaQT-Desktop_Qt_5_6_0_MinGW_32bit-Debug/ui_mainwindow.h | c5f4d62a1d8dbef378057a09330b2259712469f4 | [] | no_license | douglasrz/SiGORB | 8a2b6d983da5c92a3064ccb5e60550f979a620e4 | 2204c0209eb5942fa168b0e9574ee28d119e51d6 | refs/heads/master | 2021-06-30T09:55:06.997777 | 2017-09-20T02:57:21 | 2017-09-20T02:57:21 | 104,156,799 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 21,022 | h | /********************************************************************************
** Form generated from reading UI file 'mainwindow.ui'
**
** Created by: Qt User Interface Compiler version 5.6.0
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_MAINWINDOW_H
#define UI_MAINWINDOW_H
#include <QtCore/QVariant>
#include <QtWidgets/QAction>
#include <QtWidgets/QApplication>
#include <QtWidgets/QButtonGroup>
#include <QtWidgets/QComboBox>
#include <QtWidgets/QHBoxLayout>
#include <QtWidgets/QHeaderView>
#include <QtWidgets/QLabel>
#include <QtWidgets/QLineEdit>
#include <QtWidgets/QMainWindow>
#include <QtWidgets/QMenu>
#include <QtWidgets/QMenuBar>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QSpacerItem>
#include <QtWidgets/QStackedWidget>
#include <QtWidgets/QStatusBar>
#include <QtWidgets/QTableView>
#include <QtWidgets/QToolBar>
#include <QtWidgets/QVBoxLayout>
#include <QtWidgets/QWidget>
QT_BEGIN_NAMESPACE
class Ui_MainWindow
{
public:
QAction *actionFuncionario;
QAction *actionPublicacao;
QAction *actionAlunoCad;
QAction *actionProfessorCad;
QAction *actionAlunoEmp;
QAction *actionProfessorEmp;
QAction *actionUsuario;
QAction *actionExemplar;
QWidget *centralWidget;
QHBoxLayout *horizontalLayout;
QVBoxLayout *verticalLayout;
QPushButton *usuariosCadastradosBTN;
QPushButton *publicacoesBTN;
QPushButton *emprestimosBTN;
QStackedWidget *paginas;
QWidget *inicialPG;
QWidget *usuariosPG;
QVBoxLayout *verticalLayout_3;
QVBoxLayout *verticalLayout_2;
QLabel *label;
QHBoxLayout *horizontalLayout_2;
QSpacerItem *horizontalSpacer_3;
QLabel *buscarPorLB;
QComboBox *tipoDeBuscaUsuarioCB;
QSpacerItem *horizontalSpacer_2;
QHBoxLayout *horizontalLayout_3;
QLabel *restricaoDeBuscaUsuarioLB;
QLineEdit *pesquisaUsuarioLE;
QPushButton *buscarUsuarioBTN;
QTableView *usuarioTable;
QWidget *publicacoesPG;
QVBoxLayout *verticalLayout_4;
QLabel *label_2;
QHBoxLayout *horizontalLayout_5;
QSpacerItem *horizontalSpacer_5;
QLabel *label_5;
QComboBox *tipoDeBuscaPublicacaoCB;
QSpacerItem *horizontalSpacer_4;
QHBoxLayout *horizontalLayout_6;
QLabel *buscarPublicacaoLB;
QLineEdit *pesquisaPublicacaoLE;
QPushButton *buscarPublicacoesBTN;
QTableView *publicacoesTable;
QWidget *emprestimoPG;
QVBoxLayout *verticalLayout_5;
QLabel *label_3;
QHBoxLayout *horizontalLayout_8;
QSpacerItem *horizontalSpacer_6;
QLabel *label_4;
QComboBox *tipoDeBuscaEmprestimoCB;
QSpacerItem *horizontalSpacer_7;
QHBoxLayout *horizontalLayout_9;
QLabel *restricaoPesquisaEmprestimoLB;
QLineEdit *pesquisaEmprestimoLE;
QPushButton *buscarEmprestimosBTN;
QTableView *emprestimoTable;
QMenuBar *menuBar;
QMenu *menuCadastro;
QMenu *menuEmprestimo;
QMenu *menuDevolucao;
QMenu *menuAjuda;
QMenu *Renovar;
QToolBar *mainToolBar;
QStatusBar *statusBar;
void setupUi(QMainWindow *MainWindow)
{
if (MainWindow->objectName().isEmpty())
MainWindow->setObjectName(QStringLiteral("MainWindow"));
MainWindow->resize(514, 389);
actionFuncionario = new QAction(MainWindow);
actionFuncionario->setObjectName(QStringLiteral("actionFuncionario"));
actionPublicacao = new QAction(MainWindow);
actionPublicacao->setObjectName(QStringLiteral("actionPublicacao"));
actionAlunoCad = new QAction(MainWindow);
actionAlunoCad->setObjectName(QStringLiteral("actionAlunoCad"));
actionProfessorCad = new QAction(MainWindow);
actionProfessorCad->setObjectName(QStringLiteral("actionProfessorCad"));
actionAlunoEmp = new QAction(MainWindow);
actionAlunoEmp->setObjectName(QStringLiteral("actionAlunoEmp"));
actionProfessorEmp = new QAction(MainWindow);
actionProfessorEmp->setObjectName(QStringLiteral("actionProfessorEmp"));
actionUsuario = new QAction(MainWindow);
actionUsuario->setObjectName(QStringLiteral("actionUsuario"));
actionExemplar = new QAction(MainWindow);
actionExemplar->setObjectName(QStringLiteral("actionExemplar"));
centralWidget = new QWidget(MainWindow);
centralWidget->setObjectName(QStringLiteral("centralWidget"));
horizontalLayout = new QHBoxLayout(centralWidget);
horizontalLayout->setSpacing(6);
horizontalLayout->setContentsMargins(11, 11, 11, 11);
horizontalLayout->setObjectName(QStringLiteral("horizontalLayout"));
verticalLayout = new QVBoxLayout();
verticalLayout->setSpacing(6);
verticalLayout->setObjectName(QStringLiteral("verticalLayout"));
usuariosCadastradosBTN = new QPushButton(centralWidget);
usuariosCadastradosBTN->setObjectName(QStringLiteral("usuariosCadastradosBTN"));
QSizePolicy sizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);
sizePolicy.setHorizontalStretch(0);
sizePolicy.setVerticalStretch(0);
sizePolicy.setHeightForWidth(usuariosCadastradosBTN->sizePolicy().hasHeightForWidth());
usuariosCadastradosBTN->setSizePolicy(sizePolicy);
verticalLayout->addWidget(usuariosCadastradosBTN);
publicacoesBTN = new QPushButton(centralWidget);
publicacoesBTN->setObjectName(QStringLiteral("publicacoesBTN"));
sizePolicy.setHeightForWidth(publicacoesBTN->sizePolicy().hasHeightForWidth());
publicacoesBTN->setSizePolicy(sizePolicy);
verticalLayout->addWidget(publicacoesBTN);
emprestimosBTN = new QPushButton(centralWidget);
emprestimosBTN->setObjectName(QStringLiteral("emprestimosBTN"));
sizePolicy.setHeightForWidth(emprestimosBTN->sizePolicy().hasHeightForWidth());
emprestimosBTN->setSizePolicy(sizePolicy);
verticalLayout->addWidget(emprestimosBTN);
horizontalLayout->addLayout(verticalLayout);
paginas = new QStackedWidget(centralWidget);
paginas->setObjectName(QStringLiteral("paginas"));
paginas->setEnabled(true);
inicialPG = new QWidget();
inicialPG->setObjectName(QStringLiteral("inicialPG"));
paginas->addWidget(inicialPG);
usuariosPG = new QWidget();
usuariosPG->setObjectName(QStringLiteral("usuariosPG"));
verticalLayout_3 = new QVBoxLayout(usuariosPG);
verticalLayout_3->setSpacing(6);
verticalLayout_3->setContentsMargins(11, 11, 11, 11);
verticalLayout_3->setObjectName(QStringLiteral("verticalLayout_3"));
verticalLayout_2 = new QVBoxLayout();
verticalLayout_2->setSpacing(6);
verticalLayout_2->setObjectName(QStringLiteral("verticalLayout_2"));
label = new QLabel(usuariosPG);
label->setObjectName(QStringLiteral("label"));
label->setAlignment(Qt::AlignCenter);
verticalLayout_2->addWidget(label);
horizontalLayout_2 = new QHBoxLayout();
horizontalLayout_2->setSpacing(6);
horizontalLayout_2->setObjectName(QStringLiteral("horizontalLayout_2"));
horizontalSpacer_3 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
horizontalLayout_2->addItem(horizontalSpacer_3);
buscarPorLB = new QLabel(usuariosPG);
buscarPorLB->setObjectName(QStringLiteral("buscarPorLB"));
horizontalLayout_2->addWidget(buscarPorLB);
tipoDeBuscaUsuarioCB = new QComboBox(usuariosPG);
tipoDeBuscaUsuarioCB->setObjectName(QStringLiteral("tipoDeBuscaUsuarioCB"));
horizontalLayout_2->addWidget(tipoDeBuscaUsuarioCB);
horizontalSpacer_2 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
horizontalLayout_2->addItem(horizontalSpacer_2);
verticalLayout_2->addLayout(horizontalLayout_2);
horizontalLayout_3 = new QHBoxLayout();
horizontalLayout_3->setSpacing(6);
horizontalLayout_3->setObjectName(QStringLiteral("horizontalLayout_3"));
restricaoDeBuscaUsuarioLB = new QLabel(usuariosPG);
restricaoDeBuscaUsuarioLB->setObjectName(QStringLiteral("restricaoDeBuscaUsuarioLB"));
horizontalLayout_3->addWidget(restricaoDeBuscaUsuarioLB);
pesquisaUsuarioLE = new QLineEdit(usuariosPG);
pesquisaUsuarioLE->setObjectName(QStringLiteral("pesquisaUsuarioLE"));
horizontalLayout_3->addWidget(pesquisaUsuarioLE);
buscarUsuarioBTN = new QPushButton(usuariosPG);
buscarUsuarioBTN->setObjectName(QStringLiteral("buscarUsuarioBTN"));
horizontalLayout_3->addWidget(buscarUsuarioBTN);
verticalLayout_2->addLayout(horizontalLayout_3);
verticalLayout_3->addLayout(verticalLayout_2);
usuarioTable = new QTableView(usuariosPG);
usuarioTable->setObjectName(QStringLiteral("usuarioTable"));
verticalLayout_3->addWidget(usuarioTable);
paginas->addWidget(usuariosPG);
publicacoesPG = new QWidget();
publicacoesPG->setObjectName(QStringLiteral("publicacoesPG"));
verticalLayout_4 = new QVBoxLayout(publicacoesPG);
verticalLayout_4->setSpacing(6);
verticalLayout_4->setContentsMargins(11, 11, 11, 11);
verticalLayout_4->setObjectName(QStringLiteral("verticalLayout_4"));
label_2 = new QLabel(publicacoesPG);
label_2->setObjectName(QStringLiteral("label_2"));
label_2->setAlignment(Qt::AlignCenter);
verticalLayout_4->addWidget(label_2);
horizontalLayout_5 = new QHBoxLayout();
horizontalLayout_5->setSpacing(6);
horizontalLayout_5->setObjectName(QStringLiteral("horizontalLayout_5"));
horizontalSpacer_5 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
horizontalLayout_5->addItem(horizontalSpacer_5);
label_5 = new QLabel(publicacoesPG);
label_5->setObjectName(QStringLiteral("label_5"));
horizontalLayout_5->addWidget(label_5);
tipoDeBuscaPublicacaoCB = new QComboBox(publicacoesPG);
tipoDeBuscaPublicacaoCB->setObjectName(QStringLiteral("tipoDeBuscaPublicacaoCB"));
horizontalLayout_5->addWidget(tipoDeBuscaPublicacaoCB);
horizontalSpacer_4 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
horizontalLayout_5->addItem(horizontalSpacer_4);
verticalLayout_4->addLayout(horizontalLayout_5);
horizontalLayout_6 = new QHBoxLayout();
horizontalLayout_6->setSpacing(6);
horizontalLayout_6->setObjectName(QStringLiteral("horizontalLayout_6"));
buscarPublicacaoLB = new QLabel(publicacoesPG);
buscarPublicacaoLB->setObjectName(QStringLiteral("buscarPublicacaoLB"));
horizontalLayout_6->addWidget(buscarPublicacaoLB);
pesquisaPublicacaoLE = new QLineEdit(publicacoesPG);
pesquisaPublicacaoLE->setObjectName(QStringLiteral("pesquisaPublicacaoLE"));
horizontalLayout_6->addWidget(pesquisaPublicacaoLE);
buscarPublicacoesBTN = new QPushButton(publicacoesPG);
buscarPublicacoesBTN->setObjectName(QStringLiteral("buscarPublicacoesBTN"));
horizontalLayout_6->addWidget(buscarPublicacoesBTN);
verticalLayout_4->addLayout(horizontalLayout_6);
publicacoesTable = new QTableView(publicacoesPG);
publicacoesTable->setObjectName(QStringLiteral("publicacoesTable"));
verticalLayout_4->addWidget(publicacoesTable);
paginas->addWidget(publicacoesPG);
emprestimoPG = new QWidget();
emprestimoPG->setObjectName(QStringLiteral("emprestimoPG"));
verticalLayout_5 = new QVBoxLayout(emprestimoPG);
verticalLayout_5->setSpacing(6);
verticalLayout_5->setContentsMargins(11, 11, 11, 11);
verticalLayout_5->setObjectName(QStringLiteral("verticalLayout_5"));
label_3 = new QLabel(emprestimoPG);
label_3->setObjectName(QStringLiteral("label_3"));
label_3->setAlignment(Qt::AlignCenter);
verticalLayout_5->addWidget(label_3);
horizontalLayout_8 = new QHBoxLayout();
horizontalLayout_8->setSpacing(6);
horizontalLayout_8->setObjectName(QStringLiteral("horizontalLayout_8"));
horizontalSpacer_6 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
horizontalLayout_8->addItem(horizontalSpacer_6);
label_4 = new QLabel(emprestimoPG);
label_4->setObjectName(QStringLiteral("label_4"));
horizontalLayout_8->addWidget(label_4);
tipoDeBuscaEmprestimoCB = new QComboBox(emprestimoPG);
tipoDeBuscaEmprestimoCB->setObjectName(QStringLiteral("tipoDeBuscaEmprestimoCB"));
horizontalLayout_8->addWidget(tipoDeBuscaEmprestimoCB);
horizontalSpacer_7 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
horizontalLayout_8->addItem(horizontalSpacer_7);
verticalLayout_5->addLayout(horizontalLayout_8);
horizontalLayout_9 = new QHBoxLayout();
horizontalLayout_9->setSpacing(6);
horizontalLayout_9->setObjectName(QStringLiteral("horizontalLayout_9"));
restricaoPesquisaEmprestimoLB = new QLabel(emprestimoPG);
restricaoPesquisaEmprestimoLB->setObjectName(QStringLiteral("restricaoPesquisaEmprestimoLB"));
horizontalLayout_9->addWidget(restricaoPesquisaEmprestimoLB);
pesquisaEmprestimoLE = new QLineEdit(emprestimoPG);
pesquisaEmprestimoLE->setObjectName(QStringLiteral("pesquisaEmprestimoLE"));
horizontalLayout_9->addWidget(pesquisaEmprestimoLE);
buscarEmprestimosBTN = new QPushButton(emprestimoPG);
buscarEmprestimosBTN->setObjectName(QStringLiteral("buscarEmprestimosBTN"));
horizontalLayout_9->addWidget(buscarEmprestimosBTN);
verticalLayout_5->addLayout(horizontalLayout_9);
emprestimoTable = new QTableView(emprestimoPG);
emprestimoTable->setObjectName(QStringLiteral("emprestimoTable"));
verticalLayout_5->addWidget(emprestimoTable);
paginas->addWidget(emprestimoPG);
horizontalLayout->addWidget(paginas);
MainWindow->setCentralWidget(centralWidget);
menuBar = new QMenuBar(MainWindow);
menuBar->setObjectName(QStringLiteral("menuBar"));
menuBar->setGeometry(QRect(0, 0, 514, 21));
menuCadastro = new QMenu(menuBar);
menuCadastro->setObjectName(QStringLiteral("menuCadastro"));
menuEmprestimo = new QMenu(menuBar);
menuEmprestimo->setObjectName(QStringLiteral("menuEmprestimo"));
menuDevolucao = new QMenu(menuBar);
menuDevolucao->setObjectName(QStringLiteral("menuDevolucao"));
menuAjuda = new QMenu(menuBar);
menuAjuda->setObjectName(QStringLiteral("menuAjuda"));
Renovar = new QMenu(menuBar);
Renovar->setObjectName(QStringLiteral("Renovar"));
MainWindow->setMenuBar(menuBar);
mainToolBar = new QToolBar(MainWindow);
mainToolBar->setObjectName(QStringLiteral("mainToolBar"));
MainWindow->addToolBar(Qt::TopToolBarArea, mainToolBar);
statusBar = new QStatusBar(MainWindow);
statusBar->setObjectName(QStringLiteral("statusBar"));
MainWindow->setStatusBar(statusBar);
QWidget::setTabOrder(pesquisaUsuarioLE, buscarUsuarioBTN);
QWidget::setTabOrder(buscarUsuarioBTN, tipoDeBuscaUsuarioCB);
QWidget::setTabOrder(tipoDeBuscaUsuarioCB, usuarioTable);
QWidget::setTabOrder(usuarioTable, usuariosCadastradosBTN);
QWidget::setTabOrder(usuariosCadastradosBTN, publicacoesBTN);
QWidget::setTabOrder(publicacoesBTN, emprestimosBTN);
QWidget::setTabOrder(emprestimosBTN, tipoDeBuscaPublicacaoCB);
QWidget::setTabOrder(tipoDeBuscaPublicacaoCB, pesquisaPublicacaoLE);
QWidget::setTabOrder(pesquisaPublicacaoLE, buscarPublicacoesBTN);
QWidget::setTabOrder(buscarPublicacoesBTN, publicacoesTable);
QWidget::setTabOrder(publicacoesTable, tipoDeBuscaEmprestimoCB);
QWidget::setTabOrder(tipoDeBuscaEmprestimoCB, pesquisaEmprestimoLE);
QWidget::setTabOrder(pesquisaEmprestimoLE, buscarEmprestimosBTN);
QWidget::setTabOrder(buscarEmprestimosBTN, emprestimoTable);
menuBar->addAction(menuCadastro->menuAction());
menuBar->addAction(menuEmprestimo->menuAction());
menuBar->addAction(menuDevolucao->menuAction());
menuBar->addAction(menuAjuda->menuAction());
menuBar->addAction(Renovar->menuAction());
menuCadastro->addAction(actionUsuario);
menuCadastro->addAction(actionPublicacao);
menuCadastro->addAction(actionExemplar);
menuEmprestimo->addAction(actionAlunoEmp);
menuEmprestimo->addAction(actionProfessorEmp);
retranslateUi(MainWindow);
paginas->setCurrentIndex(1);
QMetaObject::connectSlotsByName(MainWindow);
} // setupUi
void retranslateUi(QMainWindow *MainWindow)
{
MainWindow->setWindowTitle(QApplication::translate("MainWindow", "Biblioteca", 0));
actionFuncionario->setText(QApplication::translate("MainWindow", "Funcion\303\241rio", 0));
actionPublicacao->setText(QApplication::translate("MainWindow", "Publica\303\247\303\243o", 0));
actionAlunoCad->setText(QApplication::translate("MainWindow", "Aluno", 0));
actionProfessorCad->setText(QApplication::translate("MainWindow", "Professor", 0));
actionAlunoEmp->setText(QApplication::translate("MainWindow", "Aluno", 0));
actionProfessorEmp->setText(QApplication::translate("MainWindow", "Professor", 0));
actionUsuario->setText(QApplication::translate("MainWindow", "Usu\303\241rio", 0));
actionExemplar->setText(QApplication::translate("MainWindow", "Exemplar", 0));
usuariosCadastradosBTN->setText(QApplication::translate("MainWindow", "Usu\303\241rios", 0));
publicacoesBTN->setText(QApplication::translate("MainWindow", "Publicac\303\265es", 0));
emprestimosBTN->setText(QApplication::translate("MainWindow", "Emprestimos", 0));
label->setText(QApplication::translate("MainWindow", "Pagina de Usu\303\241rios", 0));
buscarPorLB->setText(QApplication::translate("MainWindow", "Busca por", 0));
tipoDeBuscaUsuarioCB->clear();
tipoDeBuscaUsuarioCB->insertItems(0, QStringList()
<< QApplication::translate("MainWindow", "Todos", 0)
<< QApplication::translate("MainWindow", "Nome", 0)
<< QApplication::translate("MainWindow", "E-mail", 0)
);
restricaoDeBuscaUsuarioLB->setText(QApplication::translate("MainWindow", "Todos", 0));
buscarUsuarioBTN->setText(QApplication::translate("MainWindow", "Buscar", 0));
label_2->setText(QApplication::translate("MainWindow", "Pagina de publia\303\247\303\265es", 0));
label_5->setText(QApplication::translate("MainWindow", "Bucar por", 0));
tipoDeBuscaPublicacaoCB->clear();
tipoDeBuscaPublicacaoCB->insertItems(0, QStringList()
<< QApplication::translate("MainWindow", "Todas", 0)
<< QApplication::translate("MainWindow", "T\303\255tulo", 0)
<< QApplication::translate("MainWindow", "Editora", 0)
<< QApplication::translate("MainWindow", "G\303\252nero", 0)
);
buscarPublicacaoLB->setText(QApplication::translate("MainWindow", "Tudo", 0));
buscarPublicacoesBTN->setText(QApplication::translate("MainWindow", "Buscar", 0));
label_3->setText(QApplication::translate("MainWindow", "Pagina Emprestimos", 0));
label_4->setText(QApplication::translate("MainWindow", "Pesquisar por", 0));
tipoDeBuscaEmprestimoCB->clear();
tipoDeBuscaEmprestimoCB->insertItems(0, QStringList()
<< QApplication::translate("MainWindow", "Tudo", 0)
<< QApplication::translate("MainWindow", "Nome do usu\303\241rio", 0)
<< QApplication::translate("MainWindow", "Id do exemplar", 0)
<< QApplication::translate("MainWindow", "T\303\255tulo do Livro", 0)
);
restricaoPesquisaEmprestimoLB->setText(QApplication::translate("MainWindow", "Tudo", 0));
buscarEmprestimosBTN->setText(QApplication::translate("MainWindow", "Buscar", 0));
menuCadastro->setTitle(QApplication::translate("MainWindow", "Cadastro", 0));
menuEmprestimo->setTitle(QApplication::translate("MainWindow", "Emprestimo", 0));
menuDevolucao->setTitle(QApplication::translate("MainWindow", "Devolu\303\247\303\243o", 0));
menuAjuda->setTitle(QApplication::translate("MainWindow", "Ajuda", 0));
Renovar->setTitle(QApplication::translate("MainWindow", "Renovar", 0));
} // retranslateUi
};
namespace Ui {
class MainWindow: public Ui_MainWindow {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_MAINWINDOW_H
| [
"douglasrz22@gmail.com"
] | douglasrz22@gmail.com |
9ed3fed0f78bd28ef23e30e51338513865dc9480 | 3767786a73bb7d1fff378619e5e2f43e17b5088c | /gps/framework/native/framework-glue/inc/Subscription.h | ce5ff732b91544b21354408564881394b758299f | [
"Apache-2.0",
"LicenseRef-scancode-unicode"
] | permissive | fwonly123/vendor_qcom_proprietary-msm8909go | 7e02a4a9a444ba5f12cfe519f95c25eb13d086bc | 419849623d8804bc666a34c675c238d56480cc6a | refs/heads/master | 2022-04-07T05:19:00.295669 | 2020-01-10T13:43:48 | 2020-01-10T13:46:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,272 | h | /*====*====*====*====*====*====*====*====*====*====*====*====*====*====*====*
GENERAL DESCRIPTION
loc service module
Copyright (c) 2015-2017 Qualcomm Technologies, Inc.
All Rights Reserved.
Confidential and Proprietary - Qualcomm Technologies, Inc.
=============================================================================*/
#ifndef __SUBSCRIPTION_H__
#define __SUBSCRIPTION_H__
#include <IDataItemSubscription.h>
#include <IDataItemObserver.h>
#include <DataItemId.h>
#include <platform_lib_includes.h>
#ifdef USE_GLIB
#include "LocNetIface.h"
#endif
using loc_core::IDataItemObserver;
using loc_core::IDataItemSubscription;
struct SubscriptionCallbackIface {
virtual ~SubscriptionCallbackIface() = default;
virtual void updateSubscribe(const std::list<DataItemId> & l, bool subscribe);
virtual void requestData(const std::list<DataItemId> & l);
virtual void unsubscribeAll();
virtual void turnOnModule(DataItemId dit,int timeOut);
virtual void turnOffModule(DataItemId dit);
};
class Subscription : public IDataItemSubscription {
public:
static IDataItemObserver *mObserverObj;
static Subscription* getSubscriptionObj();
static void destroyInstance();
// IDataItemSubscription overrides
void subscribe(const std::list<DataItemId> & l, IDataItemObserver * observerObj = NULL);
void updateSubscription(const std::list<DataItemId> & l, IDataItemObserver * observerObj = NULL);
void requestData(const std::list <DataItemId> & l, IDataItemObserver * client = NULL);
void unsubscribe(const std::list<DataItemId> & l, IDataItemObserver * observerObj = NULL);
void unsubscribeAll(IDataItemObserver * observerObj = NULL);
static void setSubscriptionCallback(SubscriptionCallbackIface* cb);
static SubscriptionCallbackIface* getSubscriptionCallback();
protected:
private:
static Subscription *mSubscriptionObj;
#ifdef USE_GLIB
static LocNetIface* mLocNetIfaceObj;
#endif
Subscription() {
mObserverObj = NULL;
}
~Subscription() {}
static SubscriptionCallbackIface* sSubscriptionCb;
#ifdef USE_GLIB
static void locNetIfaceCallback(
void* userDataPtr, std::list<IDataItemCore*>& itemList);
#endif
};
#endif // #ifndef __SUBSCRIPTION_H__
| [
"sumant@lyft.com"
] | sumant@lyft.com |
43d6487b0e2dbb9bccc8dce9f9c4490c38e3401b | 34feae779c9654223fb11a5f2a3f442e08f7346e | /tab.cpp | 8fd65349640a44ca6b414b67fc99d15a23e90284 | [] | no_license | PXke/KFet | bf2e5545a5707def53b65b057fb4465693217cd9 | c4ecc37af2312c49958a005ca95738fe9bdb3163 | refs/heads/master | 2021-01-16T22:42:23.407575 | 2011-10-28T15:51:44 | 2011-10-28T15:51:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 35 | cpp | #include "tab.h"
CTab::CTab()
{
}
| [
"jakoneill@gmail.com"
] | jakoneill@gmail.com |
d7ccd2ea7d75125649e1f7402990c5b7d9c0821b | 34aa58efb0bd2908b6a89b97e02947f6ab5523f2 | /server/系统模块/服务器组件/聊天服务器/AttemperEngineSink.cpp | a831a14221f24dd460b2d327f7ce77a9595e9401 | [] | no_license | aywlcn/whdlm | 8e6c9901aed369658f0a7bb657f04fd13df5802e | 86d0d2edb98ce8a8a09378cabfda4fc357c7cdd2 | refs/heads/main | 2023-05-28T14:12:50.150854 | 2021-06-11T10:50:58 | 2021-06-11T10:50:58 | 380,582,203 | 1 | 0 | null | 2021-06-26T19:31:50 | 2021-06-26T19:31:49 | null | GB18030 | C++ | false | false | 128,148 | cpp | #include "StdAfx.h"
#include "ServiceUnits.h"
#include "ControlPacket.h"
#include "AttemperEngineSink.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
//////////////////////////////////////////////////////////////////////////////////
//常量定义
#define TEMP_MESSAGE_ID INVALID_DWORD
//时间标识
#define IDI_CONNECT_CORRESPOND 1 //连接时间
#define IDI_LOAD_SYSTEM_MESSAGE 2 //系统消息
#define IDI_SEND_SYSTEM_MESSAGE 3 //系统消息
#define IDI_TEST_LOG_MESSAGE 4 //系统消息
#define IDI_CONNECT_LOG_SERVER 5 //系统消息时间
#define IDI_PERSONAL_ROOM 6 //定时连接约战服务器
//间隔时间
#define MIN_INTERVAL_TIME 10 //间隔时间
#define MAX_INTERVAL_TIME 1*60 //临时标识
#define TIME_LOAD_SYSTEM_MESSAGE 600L //系统消息时间
#define TIME_SEND_SYSTEM_MESSAGE 10L //系统消息时间
#define TIME_TEST_LOG_MESSAGE 11L //系统消息时间
//////////////////////////////////////////////////////////////////////////////////
//构造函数
CAttemperEngineSink::CAttemperEngineSink()
{
//状态变量
m_bCollectUser=false;
m_bNeekCorrespond=true;
m_bNeekLogServer = true;
//控制变量
m_dwIntervalTime=0;
m_dwLastDisposeTime=0;
//绑定数据
m_pNormalParameter=NULL;
//状态变量
m_pInitParameter=NULL;
//组件变量
m_pITimerEngine=NULL;
m_pIAttemperEngine=NULL;
m_pITCPSocketService=NULL;
m_pITCPNetworkEngine=NULL;
m_pIDataBaseEngine=NULL;
m_pLogServerTCPSocketService = NULL;
m_pPrsnlRmITCPSocketService = NULL;
//判断是否有约战组件
HINSTANCE hInstLibrary = NULL;
#ifdef _DEBUG
hInstLibrary = LoadLibrary(TEXT("PersonalRoomServiceD.dll"));
#else
hInstLibrary = LoadLibrary(TEXT("PersonalRoomService.dll"));
#endif
if (hInstLibrary == NULL)
{
FreeLibrary(hInstLibrary);
}
else
{
m_bHasPrsnlRM = true;
FreeLibrary(hInstLibrary);
}
return;
}
//析构函数
CAttemperEngineSink::~CAttemperEngineSink()
{
//删除数据
SafeDeleteArray(m_pNormalParameter);
//删除消息
m_SystemMessageBuffer.Append(m_SystemMessageActive);
for (INT_PTR i = 0; i<m_SystemMessageBuffer.GetCount(); i++)
{
SafeDelete(m_SystemMessageBuffer[i]);
}
//清空数组
m_SystemMessageActive.RemoveAll();
m_SystemMessageBuffer.RemoveAll();
return;
}
//接口查询
VOID * CAttemperEngineSink::QueryInterface(REFGUID Guid, DWORD dwQueryVer)
{
QUERYINTERFACE(IAttemperEngineSink,Guid,dwQueryVer);
QUERYINTERFACE_IUNKNOWNEX(IAttemperEngineSink,Guid,dwQueryVer);
return NULL;
}
//启动事件
bool CAttemperEngineSink::OnAttemperEngineStart(IUnknownEx * pIUnknownEx)
{
//绑定信息
m_pNormalParameter=new tagBindParameter[m_pInitParameter->m_wMaxPlayer];
ZeroMemory(m_pNormalParameter,sizeof(tagBindParameter)*m_pInitParameter->m_wMaxPlayer);
return true;
}
//停止事件
bool CAttemperEngineSink::OnAttemperEngineConclude(IUnknownEx * pIUnknownEx)
{
//状态变量
m_bCollectUser=false;
m_bNeekCorrespond=true;
//配置信息
m_pInitParameter=NULL;
//组件变量
m_pITimerEngine=NULL;
m_pITCPSocketService=NULL;
m_pITCPNetworkEngine=NULL;
m_pIDataBaseEngine=NULL;
m_pPrsnlRmITCPSocketService = NULL;
m_pLogServerTCPSocketService = NULL;
//移除消息
RemoveSystemMessage();
//绑定数据
SafeDeleteArray(m_pNormalParameter);
//删除用户
m_FriendGroupManager.DeleteFriendGroup();
m_ServerUserManager.DeleteUserItem();
m_MatchServerManager.ResetMatchData();
return true;
}
//控制事件
bool CAttemperEngineSink::OnEventControl(WORD wIdentifier, VOID * pData, WORD wDataSize)
{
switch (wIdentifier)
{
case CT_CONNECT_CORRESPOND: //连接协调
{
//发起连接
tagAddressInfo * pCorrespondAddress=&m_pInitParameter->m_CorrespondAddress;
m_pITCPSocketService->Connect(pCorrespondAddress->szAddress,m_pInitParameter->m_wCorrespondPort);
//构造提示
TCHAR szString[512]=TEXT("");
_sntprintf(szString,CountArray(szString),TEXT("正在连接协调服务器 [ %s:%d ]"),pCorrespondAddress->szAddress,m_pInitParameter->m_wCorrespondPort);
//提示消息
CTraceService::TraceString(szString,TraceLevel_Normal);
return true;
}
case CT_LOAD_SERVICE_CONFIG: //加载配置
{
//事件通知
CP_ControlResult ControlResult;
ControlResult.cbSuccess=ER_SUCCESS;
SendUIControlPacket(UI_SERVICE_CONFIG_RESULT,&ControlResult,sizeof(ControlResult));
return true;
}
case CT_CONNECT_PERSONAL_ROOM_CORRESPOND: //连接约战
{
//是否有约战服务器
if (!m_bHasPrsnlRM)
{
return true;
}
//发起连接
tagAddressInfo * pPrsnlRmCorrespondAddress = &m_pInitParameter->m_PrsnlRmCorrespondAddress;
//发送数据
if (m_pPrsnlRmITCPSocketService)
{
m_pPrsnlRmITCPSocketService->Connect(pPrsnlRmCorrespondAddress->szAddress, m_pInitParameter->m_wPrsnlRmCorrespondPort);
}
//构造提示
TCHAR szString[512] = TEXT("");
_sntprintf(szString, CountArray(szString), TEXT("正在连接约战服务器 [ %s:%d ]"), pPrsnlRmCorrespondAddress->szAddress, m_pInitParameter->m_wCorrespondPort);
//提示消息
CTraceService::TraceString(szString, TraceLevel_Normal);
return true;
}
case CT_CONNECT_LOG_SERVER:
{
//发起连接
tagAddressInfo * pLogServerAddress = &m_pInitParameter->m_LogServerAddress;
//发送数据
m_pLogServerTCPSocketService->Connect(pLogServerAddress->szAddress, m_pInitParameter->m_wLogServerPort);
//构造提示
TCHAR szString[512] = TEXT("");
_sntprintf(szString, CountArray(szString), TEXT("正在连接日志服务器 [ %s:%d ]"), pLogServerAddress->szAddress, m_pInitParameter->m_wLogServerPort);
//提示消息
CTraceService::TraceString(szString, TraceLevel_Normal);
return true;
}
}
return false;
}
//调度事件
bool CAttemperEngineSink::OnEventAttemperData(WORD wRequestID, VOID * pData, WORD wDataSize)
{
return false;
}
//时间事件
bool CAttemperEngineSink::OnEventTimer(DWORD dwTimerID, WPARAM wBindParam)
{
switch (dwTimerID)
{
case IDI_CONNECT_CORRESPOND:
{
//发起连接
tagAddressInfo * pCorrespondAddress=&m_pInitParameter->m_CorrespondAddress;
m_pITCPSocketService->Connect(pCorrespondAddress->szAddress,m_pInitParameter->m_wCorrespondPort);
//构造提示
TCHAR szString[512]=TEXT("");
_sntprintf(szString,CountArray(szString),TEXT("正在连接协调服务器 [ %s:%d ]"),pCorrespondAddress->szAddress,m_pInitParameter->m_wCorrespondPort);
//提示消息
CTraceService::TraceString(szString,TraceLevel_Normal);
return true;
}
case IDI_PERSONAL_ROOM:
{
//是否有约战
if (!m_bHasPrsnlRM)
{
return true;
}
//发起连接
tagAddressInfo * pPrsnlRmCorrespondAddress = &m_pInitParameter->m_PrsnlRmCorrespondAddress;
if (m_pPrsnlRmITCPSocketService)
{
m_pPrsnlRmITCPSocketService->Connect(pPrsnlRmCorrespondAddress->szAddress, m_pInitParameter->m_wPrsnlRmCorrespondPort);
}
//构造提示
TCHAR szString[512] = TEXT("");
_sntprintf(szString, CountArray(szString), TEXT("正在连接约战服务器 [ %s:%d ]"), pPrsnlRmCorrespondAddress->szAddress, m_pInitParameter->m_wCorrespondPort);
//提示消息
CTraceService::TraceString(szString, TraceLevel_Normal);
return true;
}
case IDI_LOAD_SYSTEM_MESSAGE:
{
//清除消息数据
RemoveSystemMessage();
//加载消息
m_pIDataBaseEngine->PostDataBaseRequest(DBR_GR_LOAD_SYSTEM_MESSAGE, 0L, NULL, 0L);
return true;
}
case IDI_SEND_SYSTEM_MESSAGE:
{
//数量判断
if (m_SystemMessageActive.GetCount() == 0) return true;
//时效判断
DWORD dwCurrTime = (DWORD)time(NULL);
for (INT_PTR nIndex = m_SystemMessageActive.GetCount() - 1; nIndex >= 0; nIndex--)
{
tagSystemMessage *pTagSystemMessage = m_SystemMessageActive[nIndex];
//时效判断
if (pTagSystemMessage->SystemMessage.tConcludeTime < dwCurrTime)
{
m_SystemMessageActive.RemoveAt(nIndex);
SafeDelete(pTagSystemMessage);
continue;
}
//间隔判断
if (pTagSystemMessage->dwLastTime + pTagSystemMessage->SystemMessage.dwTimeRate < dwCurrTime)
{
//更新数据
pTagSystemMessage->dwLastTime = dwCurrTime;
//构造消息
CMD_GR_SendMessage SendMessage = {};
SendMessage.cbAllRoom = (pTagSystemMessage->SystemMessage.dwMessageID == TEMP_MESSAGE_ID) ? TRUE : FALSE;
SendMessage.cbGame = (pTagSystemMessage->SystemMessage.cbMessageType == 1) ? TRUE : FALSE;
SendMessage.cbRoom = (pTagSystemMessage->SystemMessage.cbMessageType == 2) ? TRUE : FALSE;
if (pTagSystemMessage->SystemMessage.cbMessageType == 3)
{
SendMessage.cbGame = TRUE;
SendMessage.cbRoom = TRUE;
}
lstrcpyn(SendMessage.szSystemMessage, pTagSystemMessage->SystemMessage.szSystemMessage, CountArray(SendMessage.szSystemMessage));
SendMessage.wChatLength = lstrlen(SendMessage.szSystemMessage) + 1;
//发送消息
WORD wSendSize = sizeof(SendMessage) - sizeof(SendMessage.szSystemMessage) + CountStringBuffer(SendMessage.szSystemMessage);
//SendSystemMessage(&SendMessage, wSendSize);
SendSystemMessage(SendMessage.szSystemMessage,0);
}
}
return true;
}
case IDI_CONNECT_LOG_SERVER://日志服务器重连
{
//发起连接
tagAddressInfo * pLogServerAddress = &m_pInitParameter->m_LogServerAddress;
//发送数据
m_pLogServerTCPSocketService->Connect(pLogServerAddress->szAddress, m_pInitParameter->m_wLogServerPort);
return true;
}
case IDI_TEST_LOG_MESSAGE:
{
SendLogData(TEXT("聊天服务器日志控制"));
return true;
}
}
return false;
}
//连接事件
bool CAttemperEngineSink::OnEventTCPSocketLink(WORD wServiceID, INT nErrorCode)
{
//协调连接
if (wServiceID==NETWORK_CORRESPOND)
{
//错误判断
if (nErrorCode!=0)
{
//构造提示
TCHAR szDescribe[128]=TEXT("");
_sntprintf(szDescribe,CountArray(szDescribe),TEXT("协调服务器连接失败 [ %ld ],%ld 秒后将重新连接"),
nErrorCode,m_pInitParameter->m_wConnectTime);
//提示消息
CTraceService::TraceString(szDescribe,TraceLevel_Warning);
//设置时间
//ASSERT(m_pITimerEngine!=NULL);
m_pITimerEngine->SetTimer(IDI_CONNECT_CORRESPOND,m_pInitParameter->m_wConnectTime*1000L,1,0);
return false;
}
#ifdef _DEBUG
m_pITimerEngine->SetTimer(IDI_LOAD_SYSTEM_MESSAGE, 15 * 1000L, TIMES_INFINITY, NULL);
m_pITimerEngine->SetTimer(IDI_SEND_SYSTEM_MESSAGE, 5 * 1000L, TIMES_INFINITY, NULL);
#else
m_pITimerEngine->SetTimer(IDI_LOAD_SYSTEM_MESSAGE, TIME_LOAD_SYSTEM_MESSAGE * 1000L, TIMES_INFINITY, NULL);
m_pITimerEngine->SetTimer(IDI_SEND_SYSTEM_MESSAGE, TIME_SEND_SYSTEM_MESSAGE * 1000L, TIMES_INFINITY, NULL);
#endif
//提示消息
CTraceService::TraceString(TEXT("正在注册游戏聊天服务器..."),TraceLevel_Normal);
//注册聊天
m_pITCPSocketService->SendData(MDM_CS_REGISTER, SUB_CS_C_REGISTER_CHAT);
return true;
}
else if (wServiceID == NETWORK_PERSONAL_ROOM_CORRESPOND)
{
//错误判断
if (nErrorCode != 0)
{
//构造提示
TCHAR szDescribe[128] = TEXT("");
_sntprintf(szDescribe, CountArray(szDescribe), TEXT("约战服务器连接失败 [ %ld ],%ld 秒后将重新连接"),
nErrorCode, m_pInitParameter->m_wConnectTime);
//提示消息
CTraceService::TraceString(szDescribe, TraceLevel_Warning);
//设置时间
//ASSERT(m_pITimerEngine != NULL);
m_pITimerEngine->SetTimer(IDI_PERSONAL_ROOM, m_pInitParameter->m_wConnectTime * 1000L, 1, 0);
return false;
}
//提示消息
CTraceService::TraceString(TEXT("正在向约战服务器注册游戏聊天服务器..."), TraceLevel_Normal);
//注册聊天
m_pPrsnlRmITCPSocketService->SendData(MDM_CS_REGISTER, SUB_CS_C_REGISTER_CHAT);
return true;
}
else if (wServiceID == NETWORK_LOG_SERVER)
{
//错误判断
if (nErrorCode != 0)
{
//设置时间
//ASSERT(m_pITimerEngine != NULL);
m_pITimerEngine->SetTimer(IDI_CONNECT_LOG_SERVER, m_pInitParameter->m_wConnectTime * 1000L, 1, 0);
return false;
}
//启动日志测试定时器
m_pITimerEngine->SetTimer(IDI_TEST_LOG_MESSAGE, 5 * 1000L, TIMES_INFINITY, NULL);
}
return false;
}
//关闭事件
bool CAttemperEngineSink::OnEventTCPSocketShut(WORD wServiceID, BYTE cbShutReason)
{
//协调连接
if (wServiceID==NETWORK_CORRESPOND)
{
//设置变量
m_bCollectUser=false;
//删除时间
m_pITimerEngine->KillTimer(IDI_CONNECT_CORRESPOND);
//重连判断
if (m_bNeekCorrespond==true)
{
//构造提示
TCHAR szDescribe[128]=TEXT("");
_sntprintf(szDescribe,CountArray(szDescribe),TEXT("与协调服务器的连接关闭了,%ld 秒后将重新连接"),m_pInitParameter->m_wConnectTime);
//提示消息
CTraceService::TraceString(szDescribe,TraceLevel_Warning);
//设置时间
//ASSERT(m_pITimerEngine!=NULL);
m_pITimerEngine->SetTimer(IDI_CONNECT_CORRESPOND,m_pInitParameter->m_wConnectTime*1000L,1,0);
}
return true;
}
else if (wServiceID == NETWORK_PERSONAL_ROOM_CORRESPOND)
{
//构造提示
TCHAR szDescribe[128] = TEXT("");
_sntprintf(szDescribe, CountArray(szDescribe), TEXT("与约战服务器的连接关闭了,%ld 秒后将重新连接"), m_pInitParameter->m_wConnectTime);
//提示消息
CTraceService::TraceString(szDescribe, TraceLevel_Warning);
//设置时间
//ASSERT(m_pITimerEngine != NULL);
m_pITimerEngine->SetTimer(IDI_PERSONAL_ROOM, m_pInitParameter->m_wConnectTime * 1000L, 1, 0);
return true;
}
//日志连接
else if (wServiceID == NETWORK_LOG_SERVER)
{
//重连判断
if (m_bNeekLogServer)
{
//设置时间
//ASSERT(m_pITimerEngine != NULL);
m_pITimerEngine->SetTimer(IDI_CONNECT_LOG_SERVER, m_pInitParameter->m_wConnectTime * 1000L, 1, 0);
return true;
}
}
return false;
}
//读取事件
bool CAttemperEngineSink::OnEventTCPSocketRead(WORD wServiceID, TCP_Command Command, VOID * pData, WORD wDataSize)
{
//协调连接
if (wServiceID==NETWORK_CORRESPOND)
{
switch (Command.wMainCmdID)
{
case MDM_CS_SERVICE_INFO: //服务信息
{
return OnEventTCPSocketMainServiceInfo(Command.wSubCmdID,pData,wDataSize);
}
case MDM_CS_USER_COLLECT: //用户信息
{
return OnEventTCPSocketMainUserCollect(Command.wSubCmdID,pData,wDataSize);
}
case MDM_CS_MANAGER_SERVICE: //管理服务
{
return OnTCPSocketMainManagerService(Command.wSubCmdID,pData,wDataSize);
}
}
}
else if (wServiceID == NETWORK_PERSONAL_ROOM_CORRESPOND)
{
if (Command.wMainCmdID == MDM_CS_USER_COLLECT)
{
return OnEventTCPSocketPersonalRoomInfoCollect(Command.wSubCmdID, pData, wDataSize);
}
else if (Command.wMainCmdID == MDM_CS_SERVICE_INFO)
{
return OnEventTCPSocketMainServicePersonalRoomInfo(Command.wSubCmdID, pData, wDataSize);
}
return true;
}
return true;
}
bool CAttemperEngineSink::OnTCPSocketMainManagerService(WORD wSubCmdID, VOID * pData, WORD wDataSize)
{
switch (wSubCmdID)
{
case SUB_CS_S_SYSTEM_MESSAGE:
{
//效验数据
CMD_GR_SendMessage* pSendMessage = (CMD_GR_SendMessage*)pData;
//效验数据
//ASSERT(wDataSize == sizeof(CMD_GR_SendMessage)-sizeof(pSendMessage->szSystemMessage) + sizeof(TCHAR)*pSendMessage->wChatLength);
if (wDataSize != sizeof(CMD_GR_SendMessage)-sizeof(pSendMessage->szSystemMessage) + sizeof(TCHAR)*pSendMessage->wChatLength)
{
return false;
}
SendSystemMessage(pSendMessage->szSystemMessage, 0);
return true;
}
case SUB_CS_S_PROPERTY_TRUMPET: //喇叭消息
{
//广播数据
m_pITCPNetworkEngine->SendDataBatch(MDM_GC_USER,SUB_GC_TRUMPET_NOTIFY,pData,wDataSize,0xFF);
return true;
}
}
return true;
}
bool CAttemperEngineSink::OnEventTCPSocketMainServiceInfo(WORD wSubCmdID, VOID * pData, WORD wDataSize)
{
switch (wSubCmdID)
{
case SUB_CS_S_CHAT_INSERT: //聊天服务
{
//事件通知
CP_ControlResult ControlResult;
ControlResult.cbSuccess=ER_SUCCESS;
SendUIControlPacket(UI_CORRESPOND_RESULT,&ControlResult,sizeof(ControlResult));
return true;
}
case SUB_CS_S_SIGNUP_COUNT: //报名人数
{
//效验数据
//ASSERT(wDataSize == sizeof(CMD_CS_C_MatchSignUpCount));
if (wDataSize != sizeof(CMD_CS_C_MatchSignUpCount))
{
return false;
}
//消息定义
CMD_CS_C_MatchSignUpCount *pMatchSignUp = (CMD_CS_C_MatchSignUpCount *)pData;
//查找房间
CMatchOptionItem *pGlobalServerItem = m_MatchServerManager.SearchMatchOption(pMatchSignUp->wServerID);
//房间修改
if (pGlobalServerItem != NULL)
{
//设置变量
pGlobalServerItem->m_GameMatchOption.dwMatchCount = pMatchSignUp->dwMatchCount;
}
else
{
//变量定义
tagMatchSignUpCount MatchSignUpCount;
MatchSignUpCount.lMatchNo = pMatchSignUp->lMatchNo;
MatchSignUpCount.dwMatchCount = pMatchSignUp->dwMatchCount;
MatchSignUpCount.wServerID = pMatchSignUp->wServerID;
m_MatchServerManager.InsertMatchOption(&MatchSignUpCount);
}
//变量定义
CMD_GS_S_MatchSignUpCount MatchSignUp;
//构造数据
MatchSignUp.lMatchNo = pMatchSignUp->lMatchNo;
MatchSignUp.dwMatchCount = pMatchSignUp->dwMatchCount;
MatchSignUp.wServerID = pMatchSignUp->wServerID;
CServerUserItem *pServerUserItem = NULL;
//枚举数据
for (INT i = 0; i < (int)m_ServerUserManager.GetUserItemCount(); i++)
{
//获取数据
pServerUserItem = m_ServerUserManager.EnumUserItem(i);
if (pServerUserItem == NULL)
{
break;
}
//获取对象
CLocalUserItem *pLocalUserItem = (CLocalUserItem *)pServerUserItem;
//发送数据
m_pITCPNetworkEngine->SendData(pLocalUserItem->GetSocketID(), MDM_GC_MATCH, SUB_GC_MY_MATCH_PLAYER_COUNT, &MatchSignUp, sizeof(CMD_GS_S_MatchSignUpCount));
}
break;
}
case SUB_CS_S_MATCH_OPTION: //比赛配置
return true;
}
return true;
}
bool CAttemperEngineSink::OnEventTCPSocketMainServicePersonalRoomInfo(WORD wSubCmdID, VOID * pData, WORD wDataSize)
{
switch (wSubCmdID)
{
case SUB_CS_S_CHAT_INSERT: //聊天服务
{
//事件通知
CP_ControlResult ControlResult;
ControlResult.cbSuccess = ER_SUCCESS;
SendUIControlPacket(UI_PERSONAL_ROOM_RESULT, &ControlResult, sizeof(ControlResult));
//OutputDebugString(TEXT("ptdt *** 聊天服务器 SUB_CS_S_CHAT_INSERT"));
return true;
}
}
return true;
}
bool CAttemperEngineSink::OnEventTCPSocketMainUserCollect(WORD wSubCmdID, VOID * pData, WORD wDataSize)
{
switch (wSubCmdID)
{
case SUB_CS_S_USER_GAMESTATE: //聊天服务
{
return OnEventTCPSocketSubUserStatus(pData,wDataSize);
}
}
return true;
}
bool CAttemperEngineSink::OnEventTCPSocketPersonalRoomInfoCollect(WORD wSubCmdID, VOID * pData, WORD wDataSize)
{
switch (wSubCmdID)
{
case SUB_CS_S_PERSONAL_INFO: //约战房信息
{
return OnEventTCPSocketSubPersonalInfo(pData, wDataSize);
}
case SUB_CS_S_PERSONAL_INFO_UPDATE: //更新约战房信息
{
return OnEventTCPSocketSubPersonalInfoUpdate(pData, wDataSize);
}
case SUB_CS_S_DELETE_PERSONAL: //更新约战房信息
{
return OnEventTCPSocketSubDeletePersonalInfo(pData, wDataSize);
}
}
return true;
}
bool CAttemperEngineSink::OnEventTCPSocketSubUserStatus(VOID * pData, WORD wDataSize)
{
//参数验证
//ASSERT(wDataSize==sizeof(CMD_CS_S_UserGameStatus));
if(wDataSize!=sizeof(CMD_CS_S_UserGameStatus)) return false;
//提取数据
CMD_CS_S_UserGameStatus * pUserGameStatus = (CMD_CS_S_UserGameStatus *)pData;
//ASSERT(pUserGameStatus!=NULL);
if(pUserGameStatus==NULL) return false;
//查找用户
CServerUserItem * pServerUserItem = m_ServerUserManager.SearchUserItem(pUserGameStatus->dwUserID);
if(pServerUserItem==NULL ) return true;
//获取对象
CLocalUserItem * pLocalUserItem = (CLocalUserItem *)pServerUserItem;
//重包判断
if((pUserGameStatus->cbGameStatus==pLocalUserItem->GetGameStatus()) &&
(pUserGameStatus->wServerID==pLocalUserItem->GetServerID()) &&
(pUserGameStatus->wTableID==pLocalUserItem->GetTableID()) )
{
return true;
}
//更改状态
tagFriendUserInfo* pUserInfo=pLocalUserItem->GetUserInfo();
pUserInfo->cbGameStatus=pUserGameStatus->cbGameStatus;
pUserInfo->wKindID = pUserGameStatus->wKindID;
pUserInfo->wServerID=pUserGameStatus->wServerID;
pUserInfo->wTableID=pUserGameStatus->wTableID;
pUserInfo->wChairID=pUserGameStatus->wChairID;
lstrcpyn(pUserInfo->szServerName,pUserGameStatus->szServerName,CountArray(pUserInfo->szServerName));
//广播状态
CMD_GC_UserGameStatusNotify UserGameStatusNotify;
UserGameStatusNotify.dwUserID=pUserGameStatus->dwUserID;
UserGameStatusNotify.cbGameStatus=pUserGameStatus->cbGameStatus;
UserGameStatusNotify.wKindID = pUserGameStatus->wKindID;
UserGameStatusNotify.wServerID=pUserGameStatus->wServerID;
UserGameStatusNotify.wTableID=pUserGameStatus->wTableID;
lstrcpyn(UserGameStatusNotify.szServerName,pUserGameStatus->szServerName,CountArray(UserGameStatusNotify.szServerName));
//广播给好友
SendDataToUserFriend(pUserGameStatus->dwUserID,MDM_GC_USER,SUB_GC_GAME_STATUS_NOTIFY,&UserGameStatusNotify,sizeof(UserGameStatusNotify));
return true;
}
//约战房间信息
bool CAttemperEngineSink::OnEventTCPSocketSubPersonalInfo(VOID * pData, WORD wDataSize)
{
//参数验证
//ASSERT(wDataSize == sizeof(tagPersonalTableInfoEx));
if (wDataSize != sizeof(tagPersonalTableInfoEx)) return false;
//提取数据
tagPersonalTableInfoEx * pPersonalTableInfoEx = (tagPersonalTableInfoEx *)pData;
//ASSERT(pPersonalTableInfoEx != NULL);
if (pPersonalTableInfoEx == NULL) return false;
m_PersonalRoomManager.InsertPersonalTableItem(pPersonalTableInfoEx);
//变量定义
CMD_SC_C_PersonalGoldRoomListResult PersonalGoldRoomListResult;
PersonalGoldRoomListResult.dwServerID = pPersonalTableInfoEx->dwServerID;
PersonalGoldRoomListResult.dwKindID = pPersonalTableInfoEx->dwKindID;
PersonalGoldRoomListResult.dwTableID = pPersonalTableInfoEx->dwTableID;
PersonalGoldRoomListResult.dwUserID = pPersonalTableInfoEx->dwUserID;
PersonalGoldRoomListResult.lCellScore = pPersonalTableInfoEx->lCellScore;
PersonalGoldRoomListResult.dwPersonalRoomID = pPersonalTableInfoEx->dwPersonalRoomID;
PersonalGoldRoomListResult.dwRoomTax = pPersonalTableInfoEx->dwRoomTax;
PersonalGoldRoomListResult.cbPlayMode = pPersonalTableInfoEx->cbPlayMode;
PersonalGoldRoomListResult.wJoinGamePeopleCount = pPersonalTableInfoEx->wJoinGamePeopleCount;
PersonalGoldRoomListResult.lEnterScoreLimit = pPersonalTableInfoEx->lEnterScoreLimit;
PersonalGoldRoomListResult.lLeaveScoreLimit = pPersonalTableInfoEx->lLeaveScoreLimit;
PersonalGoldRoomListResult.bGameStart = pPersonalTableInfoEx->bGameStart;
memcpy_s(PersonalGoldRoomListResult.cbGameRule, sizeof(PersonalGoldRoomListResult.cbGameRule), pPersonalTableInfoEx->cbGameRule, sizeof(pPersonalTableInfoEx->cbGameRule));
memcpy_s(PersonalGoldRoomListResult.szNickName, sizeof(PersonalGoldRoomListResult.szNickName), pPersonalTableInfoEx->szNickName, sizeof(pPersonalTableInfoEx->szNickName));
memcpy_s(PersonalGoldRoomListResult.dwJoinUserID, sizeof(PersonalGoldRoomListResult.dwJoinUserID), pPersonalTableInfoEx->dwJoinUserID, sizeof(pPersonalTableInfoEx->dwJoinUserID));
memcpy_s(PersonalGoldRoomListResult.dwFaceID, sizeof(PersonalGoldRoomListResult.dwFaceID), pPersonalTableInfoEx->dwFaceID, sizeof(pPersonalTableInfoEx->dwFaceID));
memcpy_s(PersonalGoldRoomListResult.dwCustomID, sizeof(PersonalGoldRoomListResult.dwCustomID), pPersonalTableInfoEx->dwCustomID, sizeof(pPersonalTableInfoEx->dwCustomID));
memcpy_s(PersonalGoldRoomListResult.szJoinUserNickName, sizeof(PersonalGoldRoomListResult.szJoinUserNickName), pPersonalTableInfoEx->szJoinUserNickName, sizeof(pPersonalTableInfoEx->szJoinUserNickName));
//发送数据
m_pITCPNetworkEngine->SendDataBatch(MDM_CS_PERSONAL, CMD_CS_C_INSERT_TABLE_INFO, &PersonalGoldRoomListResult, sizeof(PersonalGoldRoomListResult), 0xFF);
//OutputDebugString(TEXT("ptdt *** 聊天服务器 收到消息"));
return true;
}
//更新私人房信息
bool CAttemperEngineSink::OnEventTCPSocketSubPersonalInfoUpdate(VOID * pData, WORD wDataSize)
{
//参数验证
//ASSERT(wDataSize == sizeof(CMD_CS_S_UpdateTable));
if (wDataSize != sizeof(CMD_CS_S_UpdateTable)) return false;
//提取数据
CMD_CS_S_UpdateTable * pUpdateTable = (CMD_CS_S_UpdateTable *)pData;
//ASSERT(pUpdateTable != NULL);
if (pUpdateTable == NULL) return false;
//获取同种类型游戏房间数量
int nCount = m_PersonalRoomManager.GetPersonalTableCount(pUpdateTable->dwKindID);
TCHAR szInfo[260] = {0};
wsprintf(szInfo, TEXT("ptdt *** OnEventTCPSocketSubPersonalInfoUpdate 房间数量 kindid = %d pUpdateTable->dwUserID = %d"), pUpdateTable->dwKindID, pUpdateTable->dwUserID);
//OutputDebugString(szInfo);
//遍历所有房间
for (int i = 0; i < nCount; i++)
{
tagPersonalTableInfoEx * pPersonalTableInfoEx = m_PersonalRoomManager.EnumPersonalTableItem(pUpdateTable->dwKindID, 1, i);
if (pPersonalTableInfoEx->dwPersonalRoomID == pUpdateTable->dwPersonalRoomID)
{
pPersonalTableInfoEx->bGameStart = pUpdateTable->bGameStart;
//构建更新信息
CMD_SC_C_PersonalGoldRoomUpdate PersonalGoldRoomUpdate;
ZeroMemory(&PersonalGoldRoomUpdate, sizeof(PersonalGoldRoomUpdate));
PersonalGoldRoomUpdate.bGameStart = pUpdateTable->bGameStart;
PersonalGoldRoomUpdate.dwServerID = pUpdateTable->dwServerID;
PersonalGoldRoomUpdate.dwKindID = pUpdateTable->dwKindID;
PersonalGoldRoomUpdate.dwTableID = pUpdateTable->wTableID;
PersonalGoldRoomUpdate.dwPersonalRoomID = pUpdateTable->dwPersonalRoomID;
if (PersonalGoldRoomUpdate.bGameStart)
{
PersonalGoldRoomUpdate.cbStatus = 4;
wsprintf(szInfo, TEXT("ptdt *** OnEventTCPSocketSubPersonalInfoUpdate 房间数量 kindid = %d pUpdateTable->dwUserID = %d cbStatus = %d"), pUpdateTable->dwKindID, pUpdateTable->dwUserID, PersonalGoldRoomUpdate.cbStatus);
//OutputDebugString(szInfo);
//发送数据
m_pITCPNetworkEngine->SendDataBatch(MDM_CS_PERSONAL, CMD_CS_C_UPDATE_TABLE_INFO, &PersonalGoldRoomUpdate, sizeof(PersonalGoldRoomUpdate), 0xFF);
return true;
}
else
{
if (!PersonalGoldRoomUpdate.bGameStart && pUpdateTable->dwUserID == 0)
{
PersonalGoldRoomUpdate.cbStatus = 5;
wsprintf(szInfo, TEXT("ptdt *** OnEventTCPSocketSubPersonalInfoUpdate 房间数量 kindid = %d pUpdateTable->dwUserID = %d cbStatus = %d"), pUpdateTable->dwKindID, pUpdateTable->dwUserID, PersonalGoldRoomUpdate.cbStatus);
//OutputDebugString(szInfo);
//发送数据
m_pITCPNetworkEngine->SendDataBatch(MDM_CS_PERSONAL, CMD_CS_C_UPDATE_TABLE_INFO, &PersonalGoldRoomUpdate, sizeof(PersonalGoldRoomUpdate), 0xFF);
}
}
//查找用户
CServerUserItem * pServerUserItem = m_ServerUserManager.SearchUserItem(pUpdateTable->dwUserID);
if (pServerUserItem == NULL) return true;
//获取对象
CLocalUserItem * pLocalUserItem = (CLocalUserItem *)pServerUserItem;
tagFriendUserInfo * pUserInfo = pLocalUserItem->GetUserInfo();
pPersonalTableInfoEx->dwJoinUserID[pUpdateTable->wChairID] = pUpdateTable->dwUserID;
if (pUpdateTable->bSit)
{
PersonalGoldRoomUpdate.cbStatus = 0;
pPersonalTableInfoEx->dwCustomID[pUpdateTable->wChairID] = pUserInfo->dwCustomID;
pPersonalTableInfoEx->dwFaceID[pUpdateTable->wChairID] = pUserInfo->dwFaceID;
//获取玩家昵称
lstrcpyn(pPersonalTableInfoEx->szJoinUserNickName[pUpdateTable->wChairID], pLocalUserItem->GetNickName(), LEN_NICKNAME * 2);
lstrcpyn(PersonalGoldRoomUpdate.szNickName, pLocalUserItem->GetNickName(), LEN_NICKNAME * 2);
}
else
{
PersonalGoldRoomUpdate.cbStatus = 1;
pPersonalTableInfoEx->dwCustomID[pUpdateTable->wChairID] = -1;
pPersonalTableInfoEx->dwFaceID[pUpdateTable->wChairID] = -1;
pPersonalTableInfoEx->dwJoinUserID[pUpdateTable->wChairID] = 0;
//获取玩家昵称
ZeroMemory(pPersonalTableInfoEx->szJoinUserNickName[pUpdateTable->wChairID], LEN_NICKNAME * 2);
}
wsprintf(szInfo, TEXT("ptdt *** OnEventTCPSocketSubPersonalInfoUpdate 房间数量 kindid = %d pUpdateTable->dwUserID = %d cbStatus = %d"), pUpdateTable->dwKindID, pUpdateTable->dwUserID, PersonalGoldRoomUpdate.cbStatus);
//OutputDebugString(szInfo);
PersonalGoldRoomUpdate.dwUserID = pUpdateTable->dwUserID;
PersonalGoldRoomUpdate.wChairID = pUpdateTable->wChairID;
PersonalGoldRoomUpdate.dwCustomID = pUserInfo->dwCustomID;
PersonalGoldRoomUpdate.dwFaceID = pUserInfo->dwFaceID;
//发送数据
m_pITCPNetworkEngine->SendDataBatch(MDM_CS_PERSONAL, CMD_CS_C_UPDATE_TABLE_INFO, &PersonalGoldRoomUpdate, sizeof(PersonalGoldRoomUpdate), 0xFF);
}
}
return true;
}
//约战房间信息
bool CAttemperEngineSink::OnEventTCPSocketSubDeletePersonalInfo(VOID * pData, WORD wDataSize)
{
//参数验证
//ASSERT(wDataSize == sizeof(tagPersonalTableInfoEx));
if (wDataSize != sizeof(tagPersonalTableInfoEx)) return false;
//提取数据
tagPersonalTableInfoEx * pPersonalTableInfoEx = (tagPersonalTableInfoEx *)pData;
//ASSERT(pPersonalTableInfoEx != NULL);
if (pPersonalTableInfoEx == NULL) return false;
//删除约战
m_PersonalRoomManager.DeletePersonalTableItem(pPersonalTableInfoEx->dwKindID, pPersonalTableInfoEx->dwServerID, pPersonalTableInfoEx->dwPersonalRoomID);
CMD_SC_C_PersonalGoldRoomUpdate PersonalGoldRoomUpdate;
ZeroMemory(&PersonalGoldRoomUpdate, sizeof(PersonalGoldRoomUpdate));
PersonalGoldRoomUpdate.cbStatus = 2;
PersonalGoldRoomUpdate.dwServerID = pPersonalTableInfoEx->dwServerID;
PersonalGoldRoomUpdate.dwKindID = pPersonalTableInfoEx->dwKindID;
PersonalGoldRoomUpdate.dwTableID = pPersonalTableInfoEx->dwTableID;
PersonalGoldRoomUpdate.dwPersonalRoomID = pPersonalTableInfoEx->dwPersonalRoomID;
//发送数据
m_pITCPNetworkEngine->SendDataBatch(MDM_CS_PERSONAL, CMD_CS_C_UPDATE_TABLE_INFO, &PersonalGoldRoomUpdate, sizeof(PersonalGoldRoomUpdate), 0xFF);
return true;
}
//发送请求
bool CAttemperEngineSink::SendUIControlPacket(WORD wRequestID, VOID * pData, WORD wDataSize)
{
//发送数据
CServiceUnits * pServiceUnits=CServiceUnits::g_pServiceUnits;
pServiceUnits->PostControlRequest(wRequestID,pData,wDataSize);
return true;
}
//应答事件
bool CAttemperEngineSink::OnEventTCPNetworkBind(DWORD dwClientAddr, DWORD dwSocketID)
{
//变量定义
WORD wBindIndex=LOWORD(dwSocketID);
tagBindParameter * pBindParameter=GetBindParameter(wBindIndex);
//设置变量
if (pBindParameter!=NULL)
{
pBindParameter->dwSocketID=dwSocketID;
pBindParameter->dwClientAddr=dwClientAddr;
pBindParameter->dwActiveTime=(DWORD)time(NULL);
return true;
}
//错误断言
//ASSERT(FALSE);
return false;
}
//关闭事件
bool CAttemperEngineSink::OnEventTCPNetworkShut(DWORD dwClientAddr, DWORD dwActiveTime, DWORD dwSocketID)
{
//变量定义
WORD wBindIndex=LOWORD(dwSocketID);
tagBindParameter * pBindParameter=GetBindParameter(wBindIndex);
if(pBindParameter==NULL) return false;
//获取用户
CServerUserItem * pServerUserItem =pBindParameter->pServerUserItem;
try
{
//用户处理
if (pServerUserItem!=NULL)
{
//状态判断
if(pServerUserItem->GetMainStatus()==FRIEND_US_OFFLINE) return true;
//更改状态
CLocalUserItem * pLocalUserItem = (CLocalUserItem *)pServerUserItem;
tagFriendUserInfo * pUserInfo = pLocalUserItem->GetUserInfo();
pUserInfo->cbMainStatus=FRIEND_US_OFFLINE;
pUserInfo->cbGameStatus=US_NULL;
pUserInfo->wKindID=INVALID_KIND;
pUserInfo->wServerID=INVALID_SERVER;
pUserInfo->wTableID=INVALID_TABLE;
pUserInfo->wChairID=INVALID_CHAIR;
ZeroMemory(pUserInfo->szServerName,CountArray(pUserInfo->szServerName));
//TCHAR szMessage[256]=TEXT("");
//_sntprintf(szMessage,CountArray(szMessage),TEXT("%d-----下线通知"),pServerUserItem->GetUserID());
//CTraceService::TraceString(szMessage,TraceLevel_Normal);
//用户离线
CMD_GC_UserOnlineStatusNotify UserOnLine;
UserOnLine.dwUserID=pServerUserItem->GetUserID();
UserOnLine.cbMainStatus=pServerUserItem->GetMainStatus();
SendDataToUserFriend(UserOnLine.dwUserID,MDM_GC_USER,SUB_GC_USER_STATUS_NOTIFY,&UserOnLine,sizeof(UserOnLine));
}
}
catch(...)
{
TCHAR szMessage[128]=TEXT("");
_sntprintf(szMessage,CountArray(szMessage),TEXT("关闭连接异常: dwSocketID=%d"),dwSocketID);
CTraceService::TraceString(szMessage,TraceLevel_Normal);
}
//清除信息
ZeroMemory(pBindParameter,sizeof(tagBindParameter));
return false;
}
//读取事件
bool CAttemperEngineSink::OnEventTCPNetworkRead(TCP_Command Command, VOID * pData, WORD wDataSize, DWORD dwSocketID)
{
switch (Command.wMainCmdID)
{
case MDM_GC_LOGON: //登录命令
{
return OnTCPNetworkMainLogon(Command.wSubCmdID,pData,wDataSize,dwSocketID);
}
case MDM_GC_USER: //用户命令
{
return OnTCPNetworkMainUser(Command.wSubCmdID,pData,wDataSize,dwSocketID);
}
case MDM_GC_MATCH:
{
return OnTCPNetworkMainMatch(Command.wSubCmdID, pData, wDataSize, dwSocketID);
}
case MDM_CS_PERSONAL:
{
return OnTCPNetworkMainPersonal(Command.wSubCmdID, pData, wDataSize, dwSocketID);
}
}
return true;
}
//发送数据
bool CAttemperEngineSink::SendData(DWORD dwSocketID, WORD wMainCmdID, WORD wSubCmdID, VOID * pData, WORD wDataSize)
{
//发送数据MAX_CONTENT
m_pITCPNetworkEngine->SendData(dwSocketID, wMainCmdID, wSubCmdID, pData, wDataSize);
return true;
}
//发送配置
bool CAttemperEngineSink::SendChatServerConfig(DWORD dwUserID)
{
CMD_GC_ConfigServer ConfigServer;
ZeroMemory(&ConfigServer,sizeof(ConfigServer));
ConfigServer.wMaxPlayer=m_pInitParameter->m_wMaxPlayer;
ConfigServer.dwServiceRule=m_pInitParameter->m_dwServiceRule;
ConfigServer.cbMinOrder=m_pInitParameter->m_cbMinOrder;
//SendData(pIServerUserItem,MDM_GC_CONFIG,SUB_GC_CONFIG_SERVER,&ConfigServer,sizeof(ConfigServer));
return true;
}
//发送数据
bool CAttemperEngineSink::SendSystemMessage(LPCTSTR lpszMessage, WORD wType)
{
//变量定义
CMD_GC_S_SystemMessage SystemMessage;
ZeroMemory(&SystemMessage,sizeof(SystemMessage));
//构造数据
SystemMessage.wType=wType;
SystemMessage.wLength=lstrlen(lpszMessage)+1;
lstrcpyn(SystemMessage.szString,lpszMessage,CountArray(SystemMessage.szString));
//数据属性
WORD wHeadSize=sizeof(SystemMessage)-sizeof(SystemMessage.szString);
WORD wSendSize=wHeadSize+CountStringBuffer(SystemMessage.szString);
//发送数据
m_pITCPNetworkEngine->SendDataBatch(MDM_GC_USER,SUB_GC_SYSTEM_MESSAGE,&SystemMessage,wSendSize,0xFF);
return true;
}
//发送数据
bool CAttemperEngineSink::SendSystemMessage(DWORD dwSocketID, LPCTSTR lpszMessage, WORD wType)
{
//变量定义
CMD_GC_S_SystemMessage SystemMessage;
ZeroMemory(&SystemMessage,sizeof(SystemMessage));
//构造数据
SystemMessage.wType=wType;
SystemMessage.wLength=lstrlen(lpszMessage)+1;
lstrcpyn(SystemMessage.szString,lpszMessage,CountArray(SystemMessage.szString));
//数据属性
WORD wHeadSize=sizeof(SystemMessage)-sizeof(SystemMessage.szString);
WORD wSendSize=wHeadSize+CountStringBuffer(SystemMessage.szString);
//发送数据
m_pITCPNetworkEngine->SendData(dwSocketID,MDM_GC_USER,SUB_GC_SYSTEM_MESSAGE,&SystemMessage,wSendSize);
return true;
}
//登录失败
bool CAttemperEngineSink::OnDBLogonFailure(DWORD dwContextID, VOID * pData, WORD wDataSize)
{
//发送错误
DBO_GR_LogonFailure * pLogonFailure=(DBO_GR_LogonFailure *)pData;
SendLogonFailure(pLogonFailure->szDescribeString,pLogonFailure->lResultCode,dwContextID);
return true;
}
//登录处理
bool CAttemperEngineSink::OnTCPNetworkMainLogon(WORD wSubCmdID, VOID * pData, WORD wDataSize, DWORD dwSocketID)
{
switch (wSubCmdID)
{
case SUB_GC_PC_LOGON_USERID: //I D 登录
case SUB_GC_MB_LOGON_USERID: //I D 登录
{
return OnTCPNetworkSubMBLogonByUserID(pData,wDataSize,dwSocketID);
}
}
return true;
}
//用户处理
bool CAttemperEngineSink::OnTCPNetworkMainUser(WORD wSubCmdID, VOID * pData, WORD wDataSize, DWORD dwSocketID)
{
switch (wSubCmdID)
{
case SUB_GC_APPLYFOR_FRIEND: //好友申请
{
return OnTCPNetworkSubApplyForFriend(pData,wDataSize,dwSocketID);
}
case SUB_GC_RESPOND_FRIEND: //好友回应
{
return OnTCPNetworkSubRespondFriend(pData,wDataSize,dwSocketID);
}
case SUB_GC_INVITE_GAME: //邀请游戏
{
return OnTCPNetworkSubRoomInvite(pData,wDataSize,dwSocketID);
}
case SUB_GC_INVITE_PERSONAL:
{
return OnTCPNetworkSubInvitePersonal(pData,wDataSize,dwSocketID);
}
case SUB_GC_USER_CHAT: //用户聊天
{
return OnTCPNetworkSubUserChat(pData,wDataSize,dwSocketID);
}
case SUB_GC_SEARCH_USER: //查找用户
{
return OnTCPNetworkSubSearchUser(pData,wDataSize,dwSocketID);
}
case SUB_GC_TRUMPET: //喇叭消息
{
return OnTCPNetworkSubTrumpet(pData,wDataSize,dwSocketID);
}
case SUB_GC_DELETE_FRIEND: //删除好友
{
return OnTCPNetworkDeleteFriend(pData,wDataSize,dwSocketID);
}
case SUB_GC_UPDATE_COORDINATE:
{
return OnTCPNetworkUpdateCoordinate(pData,wDataSize,dwSocketID);
}
case SUB_GC_GET_NEARUSER:
{
return OnTCPNetworkGetNearuser(pData,wDataSize,dwSocketID);
}
case SUB_GC_QUERY_NEARUSER:
{
return OnTCPNetworkQueryNearuser(pData,wDataSize,dwSocketID);
}
case SUB_GC_USER_SHARE:
{
return OnTCPNetworkSubUserShare(pData,wDataSize,dwSocketID);
}
}
return false;
}
//比赛处理
bool CAttemperEngineSink::OnTCPNetworkMainMatch(WORD wSubCmdID, VOID *pData, WORD wDataSize, DWORD dwSocketID)
{
switch (wSubCmdID)
{
case SUB_GC_SIGN_UP: //申请报名
return OnTCPNetworkSubSignUp(pData, wDataSize, dwSocketID);
case SUB_GC_UN_SIGNUP: //取消报名
return OnTCPNetworkSubUnSignUp(pData, wDataSize, dwSocketID);
case SUB_GC_MY_MATCH_HISTORY: //我的比赛
return OnTCPNetworkMyMatchHistory(pData, wDataSize, dwSocketID);
case SUB_GC_MY_MATCH_PLAYER_COUNT: //比赛人数
return OnTCPNetworkMatchPlayerCount(pData, wDataSize, dwSocketID);
}
return true;
}
//约战处理
bool CAttemperEngineSink::OnTCPNetworkMainPersonal(WORD wSubCmdID, VOID *pData, WORD wDataSize, DWORD dwSocketID)
{
switch (wSubCmdID)
{
case CMD_CS_C_GET_GOLD_LIST: //请求约战金币场房间列表信息
return OnTCPNetworkSubPersonalGoldRoomList(pData, wDataSize, dwSocketID);
}
return true;
}
//I D 登录
bool CAttemperEngineSink::OnTCPNetworkSubMBLogonByUserID(VOID * pData, WORD wDataSize, DWORD dwSocketID)
{
//效验参数
//ASSERT(wDataSize<=sizeof(CMD_GC_MB_LogonByUserID));
if (wDataSize>sizeof(CMD_GC_MB_LogonByUserID)) return false;
//变量定义
WORD wBindIndex=LOWORD(dwSocketID);
tagBindParameter * pBindParameter=GetBindParameter(wBindIndex);
//处理消息
CMD_GC_MB_LogonByUserID * pLogonUserID=(CMD_GC_MB_LogonByUserID *)pData;
pLogonUserID->szPassword[CountArray(pLogonUserID->szPassword)-1]=0;
//变量定义
DBR_GR_LogonUserID LogonUserID;
ZeroMemory(&LogonUserID,sizeof(LogonUserID));
//构造数据
LogonUserID.dwUserID=pLogonUserID->dwUserID;
LogonUserID.dwClientAddr=pBindParameter->dwClientAddr;
LogonUserID.wLogonComand=LOGON_COMMAND_USERINFO|LOGON_COMMAND_GROUPINFO|LOGON_COMMAND_FRIENDS;
lstrcpyn(LogonUserID.szPassword,pLogonUserID->szPassword,CountArray(LogonUserID.szPassword));
lstrcpyn(LogonUserID.szPhoneMode,pLogonUserID->szPhoneMode,CountArray(LogonUserID.szPhoneMode));
//查找用户
CServerUserItem * pServerUserItem = m_ServerUserManager.SearchUserItem(pLogonUserID->dwUserID);
if(pServerUserItem!=NULL)
{
//本地用户
if(pServerUserItem->GetUserItemKind()==enLocalKind)
{
//变量定义
CLocalUserItem * pLocalUserItem = (CLocalUserItem *)pServerUserItem;
//校验密码
if(pLocalUserItem->ContrastLogonPass(pLogonUserID->szPassword)==false)
{
SendLogonFailure(TEXT("您输入的账号或密码不正确,请确认后重新登录!"),0,dwSocketID);
return true;
}
//重包判断
if(pLocalUserItem->GetMainStatus()!=FRIEND_US_OFFLINE)
{
if(GetTickCount()-pLocalUserItem->GetLogonTime()< LOGON_TIME_SPACE)
{
return true;
}
}
//发送下线消息
//if(pLocalUserItem->GetMainStatus()!=FRIEND_US_OFFLINE)//&& (pServerUserItem->GetClientAddr()!=pBindParameter->dwClientAddr ))
{
if(pLocalUserItem->GetSocketID()!=dwSocketID)
{
//TCHAR szMessage[256]=TEXT("");
//_sntprintf(szMessage,CountArray(szMessage),TEXT("dwSocketID0=%d,Address0=%d,dwSocketID1=%d,Address1=%d"),
// pLocalUserItem->GetSocketID(),pLocalUserItem->GetClientAddr(),dwSocketID,pBindParameter->dwClientAddr);
////错误信息
//CTraceService::TraceString(szMessage,TraceLevel_Normal);
//构造结构
CMD_GC_UserLogonAfresh UserLogonAfresh;
_sntprintf(UserLogonAfresh.wNotifyMessage,CountArray(UserLogonAfresh.wNotifyMessage),TEXT("您的账号在别处登录,您被迫下线!"));
//发送数据
WORD wSize = sizeof(UserLogonAfresh)-sizeof(UserLogonAfresh.wNotifyMessage)+CountStringBuffer(UserLogonAfresh.wNotifyMessage);
SendData(pLocalUserItem->GetSocketID(),MDM_GC_LOGON,SUB_S_LOGON_AFRESH,&UserLogonAfresh,wSize);
}
}
//修改用户状态
pLocalUserItem->SetSocketID(dwSocketID);
pLocalUserItem->SetLogonTime(GetTickCount());
pLocalUserItem->GetUserInfo()->cbMainStatus=FRIEND_US_ONLINE;
pLocalUserItem->GetUserInfo()->dwClientAddr=pBindParameter->dwClientAddr;
}
}
//投递请求
m_pIDataBaseEngine->PostDataBaseRequest(DBR_GR_LOGON_USERID,dwSocketID,&LogonUserID,sizeof(LogonUserID));
return true;
}
//好友申请
bool CAttemperEngineSink::OnTCPNetworkSubApplyForFriend(VOID * pData, WORD wDataSize, DWORD dwSocketID)
{
//效验参数
//ASSERT(wDataSize==sizeof(CMD_GC_ApplyForFriend));
if (wDataSize!=sizeof(CMD_GC_ApplyForFriend)) return false;
//处理消息
CMD_GC_ApplyForFriend * pApplyForFriend=(CMD_GC_ApplyForFriend *)pData;
//ASSERT(pApplyForFriend!=NULL);
//查找对象
CUserFriendGroup * pUserFriendGroup = m_FriendGroupManager.SearchGroupItem(pApplyForFriend->dwUserID);
if(pUserFriendGroup!=NULL)
{
tagServerFriendInfo * pServerFriendInfo = pUserFriendGroup->SearchFriendItem(pApplyForFriend->dwFriendID);
if(pServerFriendInfo!=NULL && pServerFriendInfo->cbGroupID!=0)
{
//申请反馈
CMD_GC_ApplyForFriendEcho ApplyForFriend;
ZeroMemory(&ApplyForFriend,sizeof(ApplyForFriend));
ApplyForFriend.lErrorCode=CHAT_MSG_ERR;
lstrcpyn(ApplyForFriend.szDescribeString,_T("已经是好友,无需申请"),CountArray(ApplyForFriend.szDescribeString));
WORD wDataSize2=CountStringBuffer(ApplyForFriend.szDescribeString);
WORD wHeadSize=sizeof(ApplyForFriend)-sizeof(ApplyForFriend.szDescribeString);
SendData(dwSocketID,MDM_GC_USER,SUB_GC_APPLYFOR_FRIEND_ECHO,&ApplyForFriend,wHeadSize+wDataSize2);
return true;
}
}
//查找用户
CServerUserItem * pFriendUserItem = m_ServerUserManager.SearchUserItem(pApplyForFriend->dwFriendID);
//变量定义
bool bBufferMessage=false;
if(pFriendUserItem==NULL) bBufferMessage=true;
if(pFriendUserItem && pFriendUserItem->GetMainStatus()==FRIEND_US_OFFLINE) bBufferMessage=true;
if(pFriendUserItem!=NULL)
{
//TCHAR szMessage[256]=TEXT("");
//_sntprintf(szMessage,CountArray(szMessage),TEXT(".........%d申请加%d为好友,%d当前状态为%d"),pApplyForFriend->dwUserID,pApplyForFriend->dwFriendID,pApplyForFriend->dwFriendID,pFriendUserItem->GetMainStatus());
////错误信息
//CTraceService::TraceString(szMessage,TraceLevel_Normal);
}
//查找用户
CServerUserItem * pServerUserItem = m_ServerUserManager.SearchUserItem(pApplyForFriend->dwUserID);
if(pServerUserItem==NULL || pServerUserItem->GetUserItemKind()!=enLocalKind) return false;
//构造结构
CMD_GC_ApplyForNotify ApplyForNotify;
ApplyForNotify.dwRequestID = pApplyForFriend->dwUserID;
ApplyForNotify.cbGroupID=pApplyForFriend->cbGroupID;
lstrcpyn(ApplyForNotify.szNickName,((CLocalUserItem *)pServerUserItem)->GetNickName(),CountArray(ApplyForNotify.szNickName));
//缓冲判断
if(bBufferMessage==true)
{
SaveOfflineMessage(pApplyForFriend->dwFriendID,SUB_GC_APPLYFOR_NOTIFY,&ApplyForNotify,sizeof(ApplyForNotify),dwSocketID);
}
else
{
if(pFriendUserItem->GetUserItemKind()==enLocalKind)
{
SendData(((CLocalUserItem *)pFriendUserItem)->GetSocketID(),MDM_GC_USER,SUB_GC_APPLYFOR_NOTIFY,&ApplyForNotify,sizeof(ApplyForNotify));
}
}
//申请反馈
CMD_GC_ApplyForFriendEcho ApplyForFriend;
ZeroMemory(&ApplyForFriend,sizeof(ApplyForFriend));
ApplyForFriend.lErrorCode=CHAT_MSG_OK;
lstrcpyn(ApplyForFriend.szDescribeString,_T(""),CountArray(ApplyForFriend.szDescribeString));
WORD wDataSize2=CountStringBuffer(ApplyForFriend.szDescribeString);
WORD wHeadSize=sizeof(ApplyForFriend)-sizeof(ApplyForFriend.szDescribeString);
SendData(dwSocketID,MDM_GC_USER,SUB_GC_APPLYFOR_FRIEND_ECHO,&ApplyForFriend,wHeadSize+wDataSize2);
return true;
}
//好友回应
bool CAttemperEngineSink::OnTCPNetworkSubRespondFriend(VOID * pData, WORD wDataSize, DWORD dwSocketID)
{
//效验参数
//ASSERT(wDataSize==sizeof(CMD_GC_RespondFriend));
if (wDataSize!=sizeof(CMD_GC_RespondFriend)) return false;
//处理消息
CMD_GC_RespondFriend * pRespondFriend=(CMD_GC_RespondFriend *)pData;
//ASSERT(pRespondFriend!=NULL);
//查找用户
CServerUserItem * pServerUserItem = m_ServerUserManager.SearchUserItem(pRespondFriend->dwUserID);
CServerUserItem * pRequestUserItem = m_ServerUserManager.SearchUserItem(pRespondFriend->dwRequestID);
if(pServerUserItem==NULL )
{
//回应反馈
CMD_GC_RespondFriendEcho RespondFriendEcho;
ZeroMemory(&RespondFriendEcho,sizeof(RespondFriendEcho));
RespondFriendEcho.lErrorCode=CHAT_MSG_ERR;
lstrcpyn(RespondFriendEcho.szDescribeString,_T("未找到此用户"),CountArray(RespondFriendEcho.szDescribeString));
WORD wDataSize2=CountStringBuffer(RespondFriendEcho.szDescribeString);
WORD wHeadSize=sizeof(RespondFriendEcho)-sizeof(RespondFriendEcho.szDescribeString);
SendData(dwSocketID,MDM_GC_USER,SUB_GC_RESPOND_FRIEND_ECHO,&RespondFriendEcho,wHeadSize+wDataSize2);
return true;
}
//查找对象
CUserFriendGroup * pUserFriendGroup = m_FriendGroupManager.SearchGroupItem(pRespondFriend->dwRequestID);
if(pUserFriendGroup!=NULL)
{
if(pUserFriendGroup->SearchFriendItem(pRespondFriend->dwUserID)!=NULL)
{
//回应反馈
CMD_GC_RespondFriendEcho RespondFriendEcho;
ZeroMemory(&RespondFriendEcho,sizeof(RespondFriendEcho));
RespondFriendEcho.lErrorCode=CHAT_MSG_ERR;
lstrcpyn(RespondFriendEcho.szDescribeString,_T("已经是好友"),CountArray(RespondFriendEcho.szDescribeString));
WORD wDataSize2=CountStringBuffer(RespondFriendEcho.szDescribeString);
WORD wHeadSize=sizeof(RespondFriendEcho)-sizeof(RespondFriendEcho.szDescribeString);
SendData(dwSocketID,MDM_GC_USER,SUB_GC_RESPOND_FRIEND_ECHO,&RespondFriendEcho,wHeadSize+wDataSize2);
return true;
}
}
//接受申请
if(pRespondFriend->bAccepted==true)
{
//构造结构
DBR_GR_AddFriend AddFriend;
AddFriend.bLoadUserInfo = false;
AddFriend.dwRequestUserID = pRespondFriend->dwRequestID;
AddFriend.dwUserID = pRespondFriend->dwUserID;
AddFriend.cbRequestGroupID = pRespondFriend->cbRequestGroupID;
AddFriend.cbGroupID = pRespondFriend->cbGroupID;
if(pRequestUserItem==NULL )
{
AddFriend.bLoadUserInfo = true;
}
//投递请求
m_pIDataBaseEngine->PostDataBaseRequest(DBR_GR_ADD_FRIEND,dwSocketID,&AddFriend,sizeof(AddFriend));
}
else
{
//变量定义
bool bBufferMessage=false;
if(pRequestUserItem==NULL) bBufferMessage=true;
if(pRequestUserItem && pRequestUserItem->GetMainStatus()==FRIEND_US_OFFLINE) bBufferMessage=true;
//构造结构
CMD_GC_RespondNotify RespondNotify;
_sntprintf(RespondNotify.szNotifyContent,CountArray(RespondNotify.szNotifyContent),TEXT("%s 拒绝了您的好友申请!"),((CLocalUserItem *)pServerUserItem)->GetNickName());
//缓存消息
if(bBufferMessage==true)
{
WORD wSize = sizeof(RespondNotify)-sizeof(RespondNotify.szNotifyContent)+CountStringBuffer(RespondNotify.szNotifyContent);
SaveOfflineMessage(pRespondFriend->dwRequestID,SUB_GC_RESPOND_NOTIFY,&RespondNotify,wSize,dwSocketID);
}
else
{
if(pRequestUserItem->GetUserItemKind()==enLocalKind)
{
SendData(((CLocalUserItem*)pRequestUserItem)->GetSocketID(),MDM_GC_USER,SUB_GC_RESPOND_NOTIFY,&RespondNotify,sizeof(RespondNotify));
}
}
}
//回应反馈
CMD_GC_RespondFriendEcho RespondFriendEcho;
ZeroMemory(&RespondFriendEcho,sizeof(RespondFriendEcho));
RespondFriendEcho.lErrorCode=CHAT_MSG_OK;
lstrcpyn(RespondFriendEcho.szDescribeString,_T(""),CountArray(RespondFriendEcho.szDescribeString));
WORD wDataSize2=CountStringBuffer(RespondFriendEcho.szDescribeString);
WORD wHeadSize=sizeof(RespondFriendEcho)-sizeof(RespondFriendEcho.szDescribeString);
SendData(dwSocketID,MDM_GC_USER,SUB_GC_RESPOND_FRIEND_ECHO,&RespondFriendEcho,wHeadSize+wDataSize2);
return true;
}
//邀请游戏
bool CAttemperEngineSink::OnTCPNetworkSubRoomInvite(VOID * pData, WORD wDataSize, DWORD dwSocketID)
{
//效验参数
//ASSERT(wDataSize<=sizeof(CMD_GC_InviteGame));
if (wDataSize>sizeof(CMD_GC_InviteGame)) return false;
//处理消息
CMD_GC_InviteGame * pVipRoomInvite=(CMD_GC_InviteGame *)pData;
//ASSERT(pVipRoomInvite!=NULL);
pVipRoomInvite->szInviteMsg[128]='\0';
//查找用户
CServerUserItem * pServerUserItem = m_ServerUserManager.SearchUserItem(pVipRoomInvite->dwUserID);
//ASSERT(pServerUserItem!=NULL);
if(pServerUserItem==NULL )
{
//邀请反馈
CMD_GC_InviteGameEcho InviteGameEcho;
ZeroMemory(&InviteGameEcho,sizeof(InviteGameEcho));
InviteGameEcho.lErrorCode=CHAT_MSG_ERR;
lstrcpyn(InviteGameEcho.szDescribeString,_T("信息超时"),CountArray(InviteGameEcho.szDescribeString));
WORD wDataSize=CountStringBuffer(InviteGameEcho.szDescribeString);
WORD wHeadSize=sizeof(InviteGameEcho)-sizeof(InviteGameEcho.szDescribeString);
SendData(dwSocketID,MDM_GC_USER,SUB_GC_INVITE_GAME_ECHO,&InviteGameEcho,wHeadSize+wDataSize);
return false;
}
//查找用户
CServerUserItem * pInvitedUserItem = m_ServerUserManager.SearchUserItem(pVipRoomInvite->dwInvitedUserID);
if(pInvitedUserItem==NULL )
{
//邀请反馈
CMD_GC_InviteGameEcho InviteGameEcho;
ZeroMemory(&InviteGameEcho,sizeof(InviteGameEcho));
InviteGameEcho.lErrorCode=CHAT_MSG_ERR;
lstrcpyn(InviteGameEcho.szDescribeString,_T("未找到此用户"),CountArray(InviteGameEcho.szDescribeString));
WORD wDataSize=CountStringBuffer(InviteGameEcho.szDescribeString);
WORD wHeadSize=sizeof(InviteGameEcho)-sizeof(InviteGameEcho.szDescribeString);
SendData(dwSocketID,MDM_GC_USER,SUB_GC_INVITE_GAME_ECHO,&InviteGameEcho,wHeadSize+wDataSize);
return true;
}
//离线检查
if(pInvitedUserItem->GetMainStatus()==FRIEND_US_OFFLINE)
{
//邀请反馈
CMD_GC_InviteGameEcho InviteGameEcho;
ZeroMemory(&InviteGameEcho,sizeof(InviteGameEcho));
InviteGameEcho.lErrorCode=CHAT_MSG_ERR;
lstrcpyn(InviteGameEcho.szDescribeString,_T("用户已经离线"),CountArray(InviteGameEcho.szDescribeString));
WORD wDataSize=CountStringBuffer(InviteGameEcho.szDescribeString);
WORD wHeadSize=sizeof(InviteGameEcho)-sizeof(InviteGameEcho.szDescribeString);
SendData(dwSocketID,MDM_GC_USER,SUB_GC_INVITE_GAME_ECHO,&InviteGameEcho,wHeadSize+wDataSize);
return true;
}
//发送邀请
CMD_GC_InviteGameNotify VipRoomInviteNotify;
VipRoomInviteNotify.dwInviteUserID=pVipRoomInvite->dwUserID;
VipRoomInviteNotify.wKindID = pVipRoomInvite->wKindID;
VipRoomInviteNotify.wServerID=pVipRoomInvite->wServerID;
VipRoomInviteNotify.wTableID=pVipRoomInvite->wTableID;
lstrcpyn(VipRoomInviteNotify.szInviteMsg,pVipRoomInvite->szInviteMsg,CountArray(VipRoomInviteNotify.szInviteMsg));
//发送数据
WORD wSize = sizeof(VipRoomInviteNotify);
SendData(((CLocalUserItem *)pInvitedUserItem)->GetSocketID(),MDM_GC_USER,SUB_GC_INVITE_GAME_NOTIFY,&VipRoomInviteNotify,wSize);
//回应反馈
CMD_GC_InviteGameEcho InviteGameEcho;
ZeroMemory(&InviteGameEcho,sizeof(InviteGameEcho));
InviteGameEcho.lErrorCode=CHAT_MSG_OK;
lstrcpyn(InviteGameEcho.szDescribeString,_T(""),CountArray(InviteGameEcho.szDescribeString));
WORD wDataSize2=CountStringBuffer(InviteGameEcho.szDescribeString);
WORD wHeadSize=sizeof(InviteGameEcho)-sizeof(InviteGameEcho.szDescribeString);
SendData(dwSocketID,MDM_GC_USER,SUB_GC_INVITE_GAME_ECHO,&InviteGameEcho,wHeadSize+wDataSize2);
return true;
}
//邀请游戏
bool CAttemperEngineSink::OnTCPNetworkSubInvitePersonal(VOID * pData, WORD wDataSize, DWORD dwSocketID)
{
//效验参数
//ASSERT(wDataSize<=sizeof(CMD_GC_InvitePersonalGame));
if (wDataSize>sizeof(CMD_GC_InvitePersonalGame)) return false;
//处理消息
CMD_GC_InvitePersonalGame * pVipRoomInvite=(CMD_GC_InvitePersonalGame *)pData;
//ASSERT(pVipRoomInvite!=NULL);
pVipRoomInvite->szInviteMsg[128]='\0';
//查找用户
CServerUserItem * pServerUserItem = m_ServerUserManager.SearchUserItem(pVipRoomInvite->dwUserID);
//ASSERT(pServerUserItem!=NULL);
if(pServerUserItem==NULL )
{
//邀请反馈
CMD_GC_InvitePersonalGameEcho InviteGameEcho;
ZeroMemory(&InviteGameEcho,sizeof(InviteGameEcho));
InviteGameEcho.lErrorCode=CHAT_MSG_ERR;
lstrcpyn(InviteGameEcho.szDescribeString,_T("信息超时"),CountArray(InviteGameEcho.szDescribeString));
WORD wDataSize=CountStringBuffer(InviteGameEcho.szDescribeString);
WORD wHeadSize=sizeof(InviteGameEcho)-sizeof(InviteGameEcho.szDescribeString);
SendData(dwSocketID,MDM_GC_USER,SUB_GC_INVITE_PERSONAL_ECHO,&InviteGameEcho,wHeadSize+wDataSize);
return false;
}
//查找用户
CServerUserItem * pInvitedUserItem = m_ServerUserManager.SearchUserItem(pVipRoomInvite->dwInvitedUserID);
if(pInvitedUserItem==NULL )
{
//邀请反馈
CMD_GC_InvitePersonalGameEcho InviteGameEcho;
ZeroMemory(&InviteGameEcho,sizeof(InviteGameEcho));
InviteGameEcho.lErrorCode=CHAT_MSG_ERR;
lstrcpyn(InviteGameEcho.szDescribeString,_T("未找到此用户"),CountArray(InviteGameEcho.szDescribeString));
WORD wDataSize=CountStringBuffer(InviteGameEcho.szDescribeString);
WORD wHeadSize=sizeof(InviteGameEcho)-sizeof(InviteGameEcho.szDescribeString);
SendData(dwSocketID,MDM_GC_USER,SUB_GC_INVITE_PERSONAL_ECHO,&InviteGameEcho,wHeadSize+wDataSize);
return true;
}
//离线检查
if(pInvitedUserItem->GetMainStatus()==FRIEND_US_OFFLINE)
{
//邀请反馈
CMD_GC_InvitePersonalGameEcho InviteGameEcho;
ZeroMemory(&InviteGameEcho,sizeof(InviteGameEcho));
InviteGameEcho.lErrorCode=CHAT_MSG_ERR;
lstrcpyn(InviteGameEcho.szDescribeString,_T("用户已经离线"),CountArray(InviteGameEcho.szDescribeString));
WORD wDataSize=CountStringBuffer(InviteGameEcho.szDescribeString);
WORD wHeadSize=sizeof(InviteGameEcho)-sizeof(InviteGameEcho.szDescribeString);
SendData(dwSocketID,MDM_GC_USER,SUB_GC_INVITE_PERSONAL_ECHO,&InviteGameEcho,wHeadSize+wDataSize);
return true;
}
//发送邀请
CMD_GC_InvitePersonalGameNotify VipRoomInviteNotify;
VipRoomInviteNotify.dwInviteUserID=pVipRoomInvite->dwUserID;
VipRoomInviteNotify.wKindID = pVipRoomInvite->wKindID;
VipRoomInviteNotify.dwServerNumber=pVipRoomInvite->dwServerNumber;
VipRoomInviteNotify.wTableID=pVipRoomInvite->wTableID;
lstrcpyn(VipRoomInviteNotify.szInviteMsg,pVipRoomInvite->szInviteMsg,CountArray(VipRoomInviteNotify.szInviteMsg));
//发送数据
WORD wSize = sizeof(VipRoomInviteNotify);
SendData(((CLocalUserItem *)pInvitedUserItem)->GetSocketID(),MDM_GC_USER,SUB_GC_INVITE_PERSONAL_NOTIFY,&VipRoomInviteNotify,wSize);
//回应反馈
CMD_GC_InvitePersonalGameEcho InviteGameEcho;
ZeroMemory(&InviteGameEcho,sizeof(InviteGameEcho));
InviteGameEcho.lErrorCode=CHAT_MSG_OK;
lstrcpyn(InviteGameEcho.szDescribeString,_T(""),CountArray(InviteGameEcho.szDescribeString));
WORD wDataSize2=CountStringBuffer(InviteGameEcho.szDescribeString);
WORD wHeadSize=sizeof(InviteGameEcho)-sizeof(InviteGameEcho.szDescribeString);
SendData(dwSocketID,MDM_GC_USER,SUB_GC_INVITE_PERSONAL_ECHO,&InviteGameEcho,wHeadSize+wDataSize2);
return true;
}
//用户聊天
bool CAttemperEngineSink::OnTCPNetworkSubUserChat(VOID * pData, WORD wDataSize, DWORD dwSocketID)
{
//效验参数
//ASSERT(wDataSize<=sizeof(CMD_GC_UserChat));
if (wDataSize>sizeof(CMD_GC_UserChat)) return false;
//处理消息
CMD_GC_UserChat * pUserChat=(CMD_GC_UserChat *)pData;
//ASSERT(pUserChat!=NULL);
//查找用户
CServerUserItem * pServerUserItem = m_ServerUserManager.SearchUserItem(pUserChat->dwSenderID);
//ASSERT(pServerUserItem!=NULL);
if(pServerUserItem==NULL )
{
//聊天反馈
CMD_GC_UserChatEcho UserChatEcho;
ZeroMemory(&UserChatEcho,sizeof(UserChatEcho));
UserChatEcho.lErrorCode=CHAT_MSG_ERR;
lstrcpyn(UserChatEcho.szDescribeString,_T("信息超时"),CountArray(UserChatEcho.szDescribeString));
WORD wDataSize=CountStringBuffer(UserChatEcho.szDescribeString);
WORD wHeadSize=sizeof(UserChatEcho)-sizeof(UserChatEcho.szDescribeString);
SendData(dwSocketID,MDM_GC_USER,SUB_GC_USER_CHAT_ECHO,&UserChatEcho,wHeadSize+wDataSize);
return false;
}
//查找用户
CServerUserItem * pTargetUserItem = m_ServerUserManager.SearchUserItem(pUserChat->dwTargetUserID);
if(pTargetUserItem!=NULL)
{
CLocalUserItem * pLocalUerItem = (CLocalUserItem *)pTargetUserItem;
SendData(pLocalUerItem->GetSocketID(),MDM_GC_USER,SUB_GC_USER_CHAT_NOTIFY,pData,wDataSize);
//聊天反馈
CMD_GC_UserChatEcho UserChatEcho;
ZeroMemory(&UserChatEcho,sizeof(UserChatEcho));
UserChatEcho.lErrorCode=CHAT_MSG_OK;
lstrcpyn(UserChatEcho.szDescribeString,_T(""),CountArray(UserChatEcho.szDescribeString));
WORD wDataSize=CountStringBuffer(UserChatEcho.szDescribeString);
WORD wHeadSize=sizeof(UserChatEcho)-sizeof(UserChatEcho.szDescribeString);
SendData(dwSocketID,MDM_GC_USER,SUB_GC_USER_CHAT_ECHO,&UserChatEcho,wHeadSize+wDataSize);
}
else if(pTargetUserItem==NULL)
{
//聊天反馈
CMD_GC_UserChatEcho UserChatEcho;
ZeroMemory(&UserChatEcho,sizeof(UserChatEcho));
UserChatEcho.lErrorCode=CHAT_MSG_ERR;
lstrcpyn(UserChatEcho.szDescribeString,_T("发送失败,对方已经离线"),CountArray(UserChatEcho.szDescribeString));
WORD wDataSize=CountStringBuffer(UserChatEcho.szDescribeString);
WORD wHeadSize=sizeof(UserChatEcho)-sizeof(UserChatEcho.szDescribeString);
SendData(dwSocketID,MDM_GC_USER,SUB_GC_USER_CHAT_ECHO,&UserChatEcho,wHeadSize+wDataSize);
////保存消息
//SaveOfflineMessage(pUserChat->dwTargetUserID,SUB_GC_USER_CHAT_NOTIFY,pData,wDataSize,dwSocketID);
}
return true;
}
//查找用户
bool CAttemperEngineSink::OnTCPNetworkSubSearchUser(VOID * pData, WORD wDataSize, DWORD dwSocketID)
{
//效验参数
//ASSERT(wDataSize<=sizeof(CMD_GC_SearchByGameID));
if (wDataSize>sizeof(CMD_GC_SearchByGameID)) return false;
//处理消息
CMD_GC_SearchByGameID * pSearchUser=(CMD_GC_SearchByGameID *)pData;
//ASSERT(pSearchUser!=NULL);
//变量定义
DBR_GR_SearchUser SearchUser;
SearchUser.dwSearchByGameID = pSearchUser->dwSearchByGameID;
//投递请求
m_pIDataBaseEngine->PostDataBaseRequest(DBR_GR_SEARCH_USER,dwSocketID,&SearchUser,sizeof(SearchUser));
return true;
}
//发送喇叭
bool CAttemperEngineSink::OnTCPNetworkSubTrumpet(VOID * pData, WORD wDataSize, DWORD dwSocketID)
{
//效验参数
//ASSERT(wDataSize<=sizeof(CMD_GC_Trumpet));
if (wDataSize>sizeof(CMD_GC_Trumpet)) return false;
//处理消息
CMD_GC_Trumpet * pUserChat=(CMD_GC_Trumpet *)pData;
//ASSERT(pUserChat!=NULL);
//变量定义
WORD wBindIndex=LOWORD(dwSocketID);
tagBindParameter * pBindParameter=GetBindParameter(wBindIndex);
//查找用户
CServerUserItem * pServerUserItem = m_ServerUserManager.SearchUserItem(pUserChat->dwSendUserID);
if(pServerUserItem==NULL )
{
//喇叭反馈
CMD_GC_TrumpetEcho TrumpetEcho;
ZeroMemory(&TrumpetEcho,sizeof(TrumpetEcho));
TrumpetEcho.lErrorCode=CHAT_MSG_ERR;
lstrcpyn(TrumpetEcho.szDescribeString,_T("信息超时"),CountArray(TrumpetEcho.szDescribeString));
WORD wDataSize=CountStringBuffer(TrumpetEcho.szDescribeString);
WORD wHeadSize=sizeof(TrumpetEcho)-sizeof(TrumpetEcho.szDescribeString);
SendData(dwSocketID,MDM_GC_USER,SUB_GC_TRUMPET_ECHO,&TrumpetEcho,wHeadSize+wDataSize);
return false;
}
DBR_GR_Trumpet Trumpet;
Trumpet.wPropertyID = pUserChat->wPropertyID;
Trumpet.dwSendUserID = pUserChat->dwSendUserID;
Trumpet.TrumpetColor = pUserChat->TrumpetColor;
Trumpet.dwClientAddr =pBindParameter->dwClientAddr;
lstrcpyn(Trumpet.szSendNickName, pUserChat->szSendNickName, CountArray(Trumpet.szSendNickName));
lstrcpyn(Trumpet.szTrumpetContent, pUserChat->szTrumpetContent, CountArray(Trumpet.szTrumpetContent));
//投递数据
m_pIDataBaseEngine->PostDataBaseRequest(DBR_GR_TRUMPET, dwSocketID, &Trumpet, sizeof(Trumpet));
return true;
}
bool CAttemperEngineSink::OnTCPNetworkDeleteFriend(VOID * pData, WORD wDataSize, DWORD dwSocketID)
{
//效验参数
//ASSERT(wDataSize<=sizeof(CMD_GC_DeleteFriend));
if (wDataSize>sizeof(CMD_GC_DeleteFriend)) return false;
//处理消息
CMD_GC_DeleteFriend * pDeleteFriend=(CMD_GC_DeleteFriend *)pData;
//ASSERT(pDeleteFriend!=NULL);
//查找用户
CServerUserItem * pServerUserItem = m_ServerUserManager.SearchUserItem(pDeleteFriend->dwUserID);
if(pServerUserItem==NULL )
{
//删除反馈
CMD_GC_DeleteFriendEcho DeleteEcho;
ZeroMemory(&DeleteEcho,sizeof(DeleteEcho));
DeleteEcho.lErrorCode=CHAT_MSG_ERR;
lstrcpyn(DeleteEcho.szDescribeString,_T("信息超时"),CountArray(DeleteEcho.szDescribeString));
WORD wDataSize=CountStringBuffer(DeleteEcho.szDescribeString);
WORD wHeadSize=sizeof(DeleteEcho)-sizeof(DeleteEcho.szDescribeString);
SendData(dwSocketID,MDM_GC_USER,SUB_GC_DELETE_FRIEND_ECHO,&DeleteEcho,wHeadSize+wDataSize);
return false;
}
//构造结构
DBR_GR_DeleteFriend DeleteFriend;
DeleteFriend.dwUserID=pDeleteFriend->dwUserID;
DeleteFriend.dwFriendUserID=pDeleteFriend->dwFriendUserID;
DeleteFriend.cbGroupID=pDeleteFriend->cbGroupID;
//投递请求
m_pIDataBaseEngine->PostDataBaseRequest(DBR_GR_DELETE_FRIEND,dwSocketID,&DeleteFriend,sizeof(DeleteFriend));
return true;
}
bool CAttemperEngineSink::OnTCPNetworkUpdateCoordinate(VOID * pData, WORD wDataSize, DWORD dwSocketID)
{
//效验参数
//ASSERT(wDataSize<=sizeof(CMD_GC_Update_Coordinate));
if (wDataSize>sizeof(CMD_GC_Update_Coordinate)) return false;
//处理消息
CMD_GC_Update_Coordinate * pUpdateCoordinate=(CMD_GC_Update_Coordinate *)pData;
//ASSERT(pUpdateCoordinate!=NULL);
//查找用户
CServerUserItem * pServerUserItem = m_ServerUserManager.SearchUserItem(pUpdateCoordinate->dwUserID);
if(pServerUserItem==NULL )
{
//更新反馈
CMD_GC_Update_CoordinateEcho Echo;
ZeroMemory(&Echo,sizeof(Echo));
Echo.lErrorCode=CHAT_MSG_ERR;
lstrcpyn(Echo.szDescribeString,_T("信息超时"),CountArray(Echo.szDescribeString));
WORD wDataSize=CountStringBuffer(Echo.szDescribeString);
WORD wHeadSize=sizeof(Echo)-sizeof(Echo.szDescribeString);
SendData(dwSocketID,MDM_GC_USER,SUB_GC_UPDATE_COORDINATE_ECHO,&Echo,wHeadSize+wDataSize);
return false;
}
if (pUpdateCoordinate->dLatitude>180 || pUpdateCoordinate->dLongitude>180)
{
//更新反馈
CMD_GC_Update_CoordinateEcho Echo;
ZeroMemory(&Echo,sizeof(Echo));
Echo.lErrorCode=CHAT_MSG_ERR;
lstrcpyn(Echo.szDescribeString,_T("坐标错误"),CountArray(Echo.szDescribeString));
WORD wDataSize=CountStringBuffer(Echo.szDescribeString);
WORD wHeadSize=sizeof(Echo)-sizeof(Echo.szDescribeString);
SendData(dwSocketID,MDM_GC_USER,SUB_GC_UPDATE_COORDINATE_ECHO,&Echo,wHeadSize+wDataSize);
return true;
}
//更新定位
WORD wBindIndex=LOWORD(dwSocketID);
tagBindParameter * pBindParameter=GetBindParameter(wBindIndex);
tagFriendUserInfo * pUserInfo = ((CLocalUserItem *)pServerUserItem)->GetUserInfo();
pUserInfo->dwClientAddr = pBindParameter->dwClientAddr;
pUserInfo->dLongitude = pUpdateCoordinate->dLongitude;
pUserInfo->dLatitude = pUpdateCoordinate->dLatitude;
lstrcpyn(pUserInfo->szPlaceName, pUpdateCoordinate->szPlaceName, CountArray(pUpdateCoordinate->szPlaceName));
pUserInfo->cbCoordinate = 1;
//CMD_GC_Update_CoordinateNotify Notify;
//Notify.dLatitude = pUserInfo->dLatitude;
//Notify.dLongitude = pUserInfo->dLongitude;
//Notify.cbCoordinate = 1;
//Notify.dwClientAddr = pUserInfo->dwClientAddr;
//SendData(dwSocketID,MDM_GC_USER,SUB_GC_UPDATE_COORDINATE_NOTIFY,&Notify,sizeof(Notify));
{
CMD_GC_Update_CoordinateEcho Echo;
ZeroMemory(&Echo,sizeof(Echo));
Echo.lErrorCode=CHAT_MSG_OK;
lstrcpyn(Echo.szDescribeString,_T(""),CountArray(Echo.szDescribeString));
WORD wDataSize=CountStringBuffer(Echo.szDescribeString);
WORD wHeadSize=sizeof(Echo)-sizeof(Echo.szDescribeString);
SendData(dwSocketID,MDM_GC_USER,SUB_GC_UPDATE_COORDINATE_ECHO,&Echo,wHeadSize+wDataSize);
}
//构造结构
DBR_GR_UpdatePlaceName placeName;
placeName.dwUserID = pUpdateCoordinate->dwUserID;
lstrcpyn(placeName.szPlaceName, pUpdateCoordinate->szPlaceName, CountArray(placeName.szPlaceName));
//投递请求
m_pIDataBaseEngine->PostDataBaseRequest(DBR_GR_UPDATE_PLACENAME, dwSocketID, &placeName, sizeof(placeName));
return true;
}
bool CAttemperEngineSink::OnTCPNetworkGetNearuser(VOID * pData, WORD wDataSize, DWORD dwSocketID)
{
//效验参数
//ASSERT(wDataSize<=sizeof(CMD_GC_Get_Nearuser));
if (wDataSize>sizeof(CMD_GC_Get_Nearuser)) return false;
//处理消息
CMD_GC_Get_Nearuser * pGetNearuser=(CMD_GC_Get_Nearuser *)pData;
//ASSERT(pGetNearuser!=NULL);
//查找用户
CServerUserItem * pServerUserItem = m_ServerUserManager.SearchUserItem(pGetNearuser->dwUserID);
if(pServerUserItem==NULL )
{
CMD_GC_Get_NearuserEcho Echo;
ZeroMemory(&Echo,sizeof(Echo));
Echo.lErrorCode=CHAT_MSG_ERR;
lstrcpyn(Echo.szDescribeString,_T("信息超时"),CountArray(Echo.szDescribeString));
WORD wDataSize=CountStringBuffer(Echo.szDescribeString);
WORD wHeadSize=sizeof(Echo)-sizeof(Echo.szDescribeString);
SendData(dwSocketID,MDM_GC_USER,SUB_GC_GET_NEARUSER_ECHO,&Echo,wHeadSize+wDataSize);
return false;
}
//获取附近
CNearUserManager NearUserManager;
m_ServerUserManager.GetNearUserItem(pGetNearuser->dwUserID,NearUserManager);
CMD_GC_Get_NearuserResult Nearuser;
BYTE cbTotalUserCount = (BYTE)(NearUserManager.GetUserItemCount());
Nearuser.cbUserCount = cbTotalUserCount;
ZeroMemory(&Nearuser.NearUserInfo,sizeof(Nearuser.NearUserInfo));
if (cbTotalUserCount !=0)
{
int nIndex = 0;
for (INT i = 0;i<cbTotalUserCount;i++)
{
tagNearUserInfo * pUserInfo = NearUserManager.EnumUserItem(i);
//距离超过忽略
if((m_pInitParameter->m_dwDistance!=0)&&(pUserInfo->dwDistance>m_pInitParameter->m_dwDistance)) continue;
CopyMemory(&(Nearuser.NearUserInfo[nIndex++]),pUserInfo,sizeof(tagNearUserInfo));
if (nIndex == MAX_FRIEND_TRANSFER)
{
Nearuser.cbUserCount = nIndex;
SendData(dwSocketID,MDM_GC_USER,SUB_GC_GET_NEARUSER_RESULT,&Nearuser,sizeof(Nearuser));
nIndex = 0;
}
}
if (nIndex !=0)
{
Nearuser.cbUserCount = nIndex;
SendData(dwSocketID,MDM_GC_USER,SUB_GC_GET_NEARUSER_RESULT,&Nearuser,sizeof(Nearuser));
nIndex = 0;
}
}
else
{
SendData(dwSocketID,MDM_GC_USER,SUB_GC_GET_NEARUSER_RESULT,&Nearuser,sizeof(Nearuser));
}
{
CMD_GC_Get_NearuserEcho Echo;
ZeroMemory(&Echo,sizeof(Echo));
Echo.lErrorCode=CHAT_MSG_OK;
lstrcpyn(Echo.szDescribeString,_T(""),CountArray(Echo.szDescribeString));
WORD wDataSize=CountStringBuffer(Echo.szDescribeString);
WORD wHeadSize=sizeof(Echo)-sizeof(Echo.szDescribeString);
SendData(dwSocketID,MDM_GC_USER,SUB_GC_GET_NEARUSER_ECHO,&Echo,wHeadSize+wDataSize);
}
return true;
}
bool CAttemperEngineSink::OnTCPNetworkQueryNearuser(VOID * pData, WORD wDataSize, DWORD dwSocketID)
{
//效验参数
//ASSERT(wDataSize<=sizeof(CMD_GC_Query_Nearuser));
if (wDataSize>sizeof(CMD_GC_Query_Nearuser)) return false;
//处理消息
CMD_GC_Query_Nearuser * pQueryNearuser=(CMD_GC_Query_Nearuser *)pData;
//ASSERT(pQueryNearuser!=NULL);
//查找用户
CServerUserItem * pServerUserItem = m_ServerUserManager.SearchUserItem(pQueryNearuser->dwUserID);
//ASSERT(pServerUserItem!=NULL);
if(pServerUserItem==NULL )
{
CMD_GC_Query_NearuserEcho Echo;
ZeroMemory(&Echo,sizeof(Echo));
Echo.lErrorCode=CHAT_MSG_ERR;
lstrcpyn(Echo.szDescribeString,_T("信息超时"),CountArray(Echo.szDescribeString));
WORD wDataSize=CountStringBuffer(Echo.szDescribeString);
WORD wHeadSize=sizeof(Echo)-sizeof(Echo.szDescribeString);
SendData(dwSocketID,MDM_GC_USER,SUB_GC_QUERY_NEARUSER_ECHO,&Echo,wHeadSize+wDataSize);
return false;
}
CServerUserItem * pNearuserUserItem = m_ServerUserManager.SearchUserItem(pQueryNearuser->dwNearuserUserID);
if(pNearuserUserItem==NULL )
{
CMD_GC_Query_NearuserEcho Echo;
ZeroMemory(&Echo,sizeof(Echo));
Echo.lErrorCode=CHAT_MSG_ERR;
lstrcpyn(Echo.szDescribeString,_T("请求失败,对方已经离线"),CountArray(Echo.szDescribeString));
WORD wDataSize=CountStringBuffer(Echo.szDescribeString);
WORD wHeadSize=sizeof(Echo)-sizeof(Echo.szDescribeString);
SendData(dwSocketID,MDM_GC_USER,SUB_GC_QUERY_NEARUSER_ECHO,&Echo,wHeadSize+wDataSize);
return true;
}
//获取附近
CNearUserManager NearUserManager;
m_ServerUserManager.QueryNearUserItem(pQueryNearuser->dwUserID,pQueryNearuser->dwNearuserUserID,NearUserManager);
CMD_GC_Query_NearuserResult Nearuser;
Nearuser.cbUserCount = (BYTE)(NearUserManager.GetUserItemCount());
ZeroMemory(&Nearuser.NearUserInfo,sizeof(Nearuser.NearUserInfo));
if (Nearuser.cbUserCount !=0)
{
tagNearUserInfo * pUserInfo = NearUserManager.EnumUserItem(0);
CopyMemory(&Nearuser.NearUserInfo,pUserInfo,sizeof(tagNearUserInfo));
}
SendData(dwSocketID,MDM_GC_USER,SUB_GC_QUERY_NEARUSER_RESULT,&Nearuser,sizeof(Nearuser));
{
CMD_GC_Query_NearuserEcho Echo;
ZeroMemory(&Echo,sizeof(Echo));
Echo.lErrorCode=CHAT_MSG_OK;
lstrcpyn(Echo.szDescribeString,_T(""),CountArray(Echo.szDescribeString));
WORD wDataSize=CountStringBuffer(Echo.szDescribeString);
WORD wHeadSize=sizeof(Echo)-sizeof(Echo.szDescribeString);
SendData(dwSocketID,MDM_GC_USER,SUB_GC_QUERY_NEARUSER_ECHO,&Echo,wHeadSize+wDataSize);
}
return true;
}
//分享消息
bool CAttemperEngineSink::OnTCPNetworkSubUserShare(VOID * pData, WORD wDataSize, DWORD dwSocketID)
{
//效验参数
//ASSERT(wDataSize<=sizeof(CMD_GC_UserShare));
if (wDataSize>sizeof(CMD_GC_UserShare)) return false;
//处理消息
CMD_GC_UserShare * pUserShare=(CMD_GC_UserShare *)pData;
//ASSERT(pUserShare!=NULL);
//查找用户
CServerUserItem * pServerUserItem = m_ServerUserManager.SearchUserItem(pUserShare->dwUserID);
//ASSERT(pServerUserItem!=NULL);
if(pServerUserItem==NULL )
{
//邀请反馈
CMD_GC_UserShareEcho InviteGameEcho;
ZeroMemory(&InviteGameEcho,sizeof(InviteGameEcho));
InviteGameEcho.lErrorCode=CHAT_MSG_ERR;
lstrcpyn(InviteGameEcho.szDescribeString,_T("信息超时"),CountArray(InviteGameEcho.szDescribeString));
WORD wDataSize=CountStringBuffer(InviteGameEcho.szDescribeString);
WORD wHeadSize=sizeof(InviteGameEcho)-sizeof(InviteGameEcho.szDescribeString);
SendData(dwSocketID,MDM_GC_USER,SUB_GC_USER_SHARE_ECHO,&InviteGameEcho,wHeadSize+wDataSize);
return false;
}
//查找用户
CServerUserItem * pSharedUserItem = m_ServerUserManager.SearchUserItem(pUserShare->dwSharedUserID);
if(pSharedUserItem==NULL )
{
//邀请反馈
CMD_GC_UserShareEcho InviteGameEcho;
ZeroMemory(&InviteGameEcho,sizeof(InviteGameEcho));
InviteGameEcho.lErrorCode=CHAT_MSG_ERR;
lstrcpyn(InviteGameEcho.szDescribeString,_T("未找到此用户"),CountArray(InviteGameEcho.szDescribeString));
WORD wDataSize=CountStringBuffer(InviteGameEcho.szDescribeString);
WORD wHeadSize=sizeof(InviteGameEcho)-sizeof(InviteGameEcho.szDescribeString);
SendData(dwSocketID,MDM_GC_USER,SUB_GC_USER_SHARE_ECHO,&InviteGameEcho,wHeadSize+wDataSize);
return true;
}
//离线检查
if(pSharedUserItem->GetMainStatus()==FRIEND_US_OFFLINE)
{
//邀请反馈
CMD_GC_UserShareEcho InviteGameEcho;
ZeroMemory(&InviteGameEcho,sizeof(InviteGameEcho));
InviteGameEcho.lErrorCode=CHAT_MSG_ERR;
lstrcpyn(InviteGameEcho.szDescribeString,_T("用户已经离线"),CountArray(InviteGameEcho.szDescribeString));
WORD wDataSize=CountStringBuffer(InviteGameEcho.szDescribeString);
WORD wHeadSize=sizeof(InviteGameEcho)-sizeof(InviteGameEcho.szDescribeString);
SendData(dwSocketID,MDM_GC_USER,SUB_GC_USER_SHARE_ECHO,&InviteGameEcho,wHeadSize+wDataSize);
return true;
}
//发送邀请
CMD_GC_UserShareNotify UserShareNotify;
UserShareNotify.dwShareUserID=pUserShare->dwUserID;
lstrcpyn(UserShareNotify.szShareImageAddr,pUserShare->szShareImageAddr,CountArray(UserShareNotify.szShareImageAddr));
lstrcpyn(UserShareNotify.szMessageContent,pUserShare->szMessageContent,CountArray(UserShareNotify.szMessageContent));
//发送数据
SendData(((CLocalUserItem *)pSharedUserItem)->GetSocketID(),MDM_GC_USER,SUB_GC_USER_SHARE_NOTIFY,&UserShareNotify,sizeof(UserShareNotify));
//回应反馈
CMD_GC_UserShareEcho InviteGameEcho;
ZeroMemory(&InviteGameEcho,sizeof(InviteGameEcho));
InviteGameEcho.lErrorCode=CHAT_MSG_OK;
lstrcpyn(InviteGameEcho.szDescribeString,_T(""),CountArray(InviteGameEcho.szDescribeString));
WORD wDataSize2=CountStringBuffer(InviteGameEcho.szDescribeString);
WORD wHeadSize=sizeof(InviteGameEcho)-sizeof(InviteGameEcho.szDescribeString);
SendData(dwSocketID,MDM_GC_USER,SUB_GC_USER_SHARE_ECHO,&InviteGameEcho,wHeadSize+wDataSize2);
return true;
}
//比赛报名
bool CAttemperEngineSink::OnTCPNetworkSubSignUp(VOID *pData, WORD wDataSize, DWORD dwSocketID)
{
//效验参数
//ASSERT(wDataSize == sizeof(CMD_GC_MatchSignup));
if (wDataSize != sizeof(CMD_GC_MatchSignup)) return false;
//处理消息
CMD_GC_MatchSignup * pMatchSignup = (CMD_GC_MatchSignup *)pData;
pMatchSignup->szPassword[CountArray(pMatchSignup->szPassword) - 1] = 0;
pMatchSignup->szMachineID[CountArray(pMatchSignup->szMachineID) - 1] = 0;
//查找房间
CMatchServerItem * pGameServerItem = m_MatchServerManager.SearchMatchServer(pMatchSignup->wServerID);
if (pGameServerItem == NULL)
{
//发送失败
SendOperateFailure(TEXT("抱歉,您报名的比赛不存在或者已经结束!"), 0, 0, dwSocketID);
return true;
}
//构造结构
DBR_GR_MatchSignup MatchSignup;
//比赛信息
MatchSignup.wServerID = pMatchSignup->wServerID;
MatchSignup.dwMatchID = pMatchSignup->dwMatchID;
MatchSignup.lMatchNo = pMatchSignup->dwMatchNO;
//用户信息
MatchSignup.dwUserID = pMatchSignup->dwUserID;
// lstrcpyn(MatchSignup.szPassword, pMatchSignup->szPassword, CountArray(MatchSignup.szPassword));
//机器信息
//MatchSignup.dwClientAddr = (m_pBindParameter + LOWORD(dwSocketID))->dwClientAddr;
lstrcpyn(MatchSignup.szMachineID, pMatchSignup->szMachineID, CountArray(MatchSignup.szMachineID));
//投递请求
m_pIDataBaseEngine->PostDataBaseRequest(DBR_GR_MATCH_SIGNUP, dwSocketID, &MatchSignup, sizeof(MatchSignup));
return true;
}
//取消报名
bool CAttemperEngineSink::OnTCPNetworkSubUnSignUp(VOID *pData, WORD wDataSize, DWORD dwSocketID)
{
//效验参数
//ASSERT(wDataSize == sizeof(CMD_GC_MatchUnSignup));
if (wDataSize != sizeof(CMD_GC_MatchUnSignup)) return false;
//处理消息
CMD_GC_MatchUnSignup * pMatchUnSignup = (CMD_GC_MatchUnSignup *)pData;
pMatchUnSignup->szPassword[CountArray(pMatchUnSignup->szPassword) - 1] = 0;
pMatchUnSignup->szMachineID[CountArray(pMatchUnSignup->szMachineID) - 1] = 0;
//构造结构
DBR_GR_MatchUnSignup MatchUnSignup;
//比赛信息
MatchUnSignup.wServerID = pMatchUnSignup->wServerID;
MatchUnSignup.dwMatchID = pMatchUnSignup->dwMatchID;
MatchUnSignup.lMatchNo = pMatchUnSignup->dwMatchNO;
//用户信息
MatchUnSignup.dwUserID = pMatchUnSignup->dwUserID;
// lstrcpyn(MatchUnSignup.szPassword, pMatchUnSignup->szPassword, CountArray(MatchUnSignup.szPassword));
//机器信息
//MatchUnSignup.dwClientAddr = (m_pBindParameter + LOWORD(dwSocketID))->dwClientAddr;
lstrcpyn(MatchUnSignup.szMachineID, pMatchUnSignup->szMachineID, CountArray(MatchUnSignup.szMachineID));
//投递请求
m_pIDataBaseEngine->PostDataBaseRequest(DBR_GR_MATCH_UNSIGNUP, dwSocketID, &MatchUnSignup, sizeof(MatchUnSignup));
return true;
}
//我的比赛
bool CAttemperEngineSink::OnTCPNetworkMyMatchHistory(VOID *pData, WORD wDataSize, DWORD dwSocketID)
{
//效验参数
//ASSERT(wDataSize == sizeof(CMD_GC_MyMatchHistory));
if (wDataSize != sizeof(CMD_GC_MyMatchHistory)) return false;
//处理消息
CMD_GC_MyMatchHistory * pMyMatch = (CMD_GC_MyMatchHistory *)pData;
pMyMatch->szPassword[CountArray(pMyMatch->szPassword) - 1] = 0;
//构造结构
DBO_GR_MyMatchHistory MyMatch;
//用户信息
MyMatch.dwUserID = pMyMatch->dwUserID;
lstrcpyn(MyMatch.szPassword, pMyMatch->szPassword, CountArray(MyMatch.szPassword));
//投递请求
m_pIDataBaseEngine->PostDataBaseRequest(DBO_GR_MY_MATCH_HISTORY, dwSocketID, &MyMatch, sizeof(MyMatch));
return true;
}
//比赛人数
bool CAttemperEngineSink::OnTCPNetworkMatchPlayerCount(VOID *pData, WORD wDataSize, DWORD dwSocketID)
{
//变量定义
CMD_GS_S_MatchSignUpCount MatchSignUp;
CMatchOptionItem *pGlobalServerItem = NULL;
//枚举数据
POSITION Position = NULL;
do
{
pGlobalServerItem = m_MatchServerManager.EmunMatchOptionItem(Position);
if (pGlobalServerItem == NULL)
{
break;
}
//构造数据
MatchSignUp.lMatchNo = pGlobalServerItem->m_GameMatchOption.lMatchNo;
MatchSignUp.dwMatchCount = pGlobalServerItem->m_GameMatchOption.dwMatchCount;
MatchSignUp.wServerID = pGlobalServerItem->m_GameMatchOption.wServerID;
//发送数据
m_pITCPNetworkEngine->SendData(dwSocketID, MDM_GC_MATCH, SUB_GC_MY_MATCH_PLAYER_COUNT, &MatchSignUp, sizeof(CMD_GS_S_MatchSignUpCount));
} while(Position != NULL);
return true;
}
//登录失败
bool CAttemperEngineSink::SendLogonFailure(LPCTSTR pszString, LONG lErrorCode, DWORD dwSocketID)
{
//变量定义
CMD_GC_LogonEcho LogonFailure;
ZeroMemory(&LogonFailure,sizeof(LogonFailure));
//构造数据
LogonFailure.lErrorCode=lErrorCode;
lstrcpyn(LogonFailure.szDescribeString,pszString,CountArray(LogonFailure.szDescribeString));
//数据属性
WORD wDataSize=CountStringBuffer(LogonFailure.szDescribeString);
WORD wHeadSize=sizeof(LogonFailure)-sizeof(LogonFailure.szDescribeString);
//发送数据
SendData(dwSocketID,MDM_GC_LOGON,SUB_GC_LOGON_FAILURE,&LogonFailure,wHeadSize+wDataSize);
return true;
}
//操作结果
bool CAttemperEngineSink::SendOperateFailure(LPCTSTR pszString, LONG lErrorCode,LONG lOperateCode,DWORD dwSocketID)
{
//变量定义
CMD_GC_OperateFailure OperateFailure;
OperateFailure.lErrorCode=lErrorCode;
OperateFailure.lResultCode=lOperateCode;
lstrcpyn(OperateFailure.szDescribeString,pszString,CountArray(OperateFailure.szDescribeString));
//发送数据
SendData(dwSocketID,MDM_GC_USER,SUB_GP_OPERATE_FAILURE,&OperateFailure,sizeof(OperateFailure));
return true;
}
//操作结果
bool CAttemperEngineSink::SendOperateSuccess(LPCTSTR pszString,LONG lOperateCode,DWORD dwSocketID)
{
//构造结构
CMD_GC_OperateSuccess OperateSuccess;
OperateSuccess.lResultCode=lOperateCode;
lstrcpyn(OperateSuccess.szDescribeString,pszString,CountArray(OperateSuccess.szDescribeString));
//发送数据
WORD wSize = sizeof(OperateSuccess)-sizeof(OperateSuccess.szDescribeString)+CountStringBuffer(OperateSuccess.szDescribeString);
SendData(dwSocketID,MDM_GC_USER,SUB_GC_OPERATE_SUCCESS,&OperateSuccess,wSize);
return true;
}
//发送数据
bool CAttemperEngineSink::SendDataToUserFriend(DWORD dwUserID,WORD wMainCmdID, WORD wSubCmdID,VOID * pData,WORD wDataSize)
{
//移除用户
CServerUserItem * pServerUserItem = m_ServerUserManager.SearchUserItem(dwUserID);
//ASSERT(pServerUserItem!=NULL);
if(pServerUserItem!=NULL)
{
//获取好友
CUserFriendGroup * pUserFriendGroup = m_FriendGroupManager.SearchGroupItem(dwUserID);
if(pUserFriendGroup!=NULL)
{
//枚举用户
WORD wEnumIndex=0;
tagServerFriendInfo * pServerFriendInfo = pUserFriendGroup->EnumFriendItem(wEnumIndex);
while(pServerFriendInfo!=NULL)
{
//查找本地用户
CServerUserItem * pServerUserItem = m_ServerUserManager.SearchUserItem(pServerFriendInfo->dwUserID);
if(pServerUserItem!=NULL )
{
CLocalUserItem * pLocalUerItem = (CLocalUserItem *)pServerUserItem;
if(pLocalUerItem->GetMainStatus()!=FRIEND_US_OFFLINE)
{
SendData(pLocalUerItem->GetSocketID(),wMainCmdID,wSubCmdID,pData,wDataSize);
}
}
//枚举好友
pServerFriendInfo = pUserFriendGroup->EnumFriendItem(++wEnumIndex);
}
}
}
return true;
}
//存储离线消息
bool CAttemperEngineSink::SaveOfflineMessage(DWORD dwUserID,WORD wMessageType,VOID * pData,WORD wDataSize,DWORD dwSocketID)
{
//变量定义
DBR_GR_SaveOfflineMessage OfflineMessage;
OfflineMessage.dwUserID = dwUserID;
OfflineMessage.wMessageType = wMessageType;
OfflineMessage.wDataSize = wDataSize;
OfflineMessage.szOfflineData[0]=0;
//变量定义
TCHAR szOffLineData[CountArray(OfflineMessage.szOfflineData)+1]=TEXT("");
BYTE cbOffLineData[CountArray(OfflineMessage.szOfflineData)/2];
ZeroMemory(cbOffLineData,sizeof(cbOffLineData));
CopyMemory(cbOffLineData,pData,wDataSize);
//离线消息
for (INT i=0;i<CountArray(cbOffLineData);i++)
{
_stprintf(&szOffLineData[i * 2], TEXT("%02X"), cbOffLineData[i]);
}
//设置变量
lstrcpyn(OfflineMessage.szOfflineData,szOffLineData,CountArray(OfflineMessage.szOfflineData));
//投递请求
m_pIDataBaseEngine->PostDataBaseRequest(DBR_GR_SAVE_OFFLINEMESSAGE,dwSocketID,&OfflineMessage,sizeof(OfflineMessage));
return true;
}
//绑定用户
CServerUserItem * CAttemperEngineSink::GetBindUserItem(WORD wBindIndex)
{
//获取参数
tagBindParameter * pBindParameter=GetBindParameter(wBindIndex);
//获取用户
if (pBindParameter!=NULL)
{
return pBindParameter->pServerUserItem;
}
//错误断言
//ASSERT(FALSE);
return NULL;
}
//绑定参数
tagBindParameter * CAttemperEngineSink::GetBindParameter(WORD wBindIndex)
{
//无效连接
if (wBindIndex==INVALID_WORD) return NULL;
//常规连接
if (wBindIndex<m_pInitParameter->m_wMaxPlayer)
{
return m_pNormalParameter+wBindIndex;
}
//错误断言
//ASSERT(FALSE);
return NULL;
}
//////////////////////////////////////////////////////////////////////////
//数据库事件
bool CAttemperEngineSink::OnEventDataBase(WORD wRequestID, DWORD dwContextID, VOID * pData, WORD wDataSize)
{
try
{
switch (wRequestID)
{
case DBO_GR_LOGON_SUCCESS: //登录成功
{
return OnDBLogonSuccess(dwContextID,pData,wDataSize);
}
case DBO_GR_LOGON_FAILURE: //登录失败
{
return OnDBLogonFailure(dwContextID,pData,wDataSize);
}
case DBO_GR_USER_GROUPINFO: //加载分组
{
return OnDBLoadUserGroup(dwContextID,pData,wDataSize);
}
case DBO_GR_USER_FRIENDINFO: //加载好友
{
return OnDBLoadUserFriend(dwContextID,pData,wDataSize);
}
case DBO_GR_USER_SINDIVIDUAL: //简易资料
{
return OnDBLoadUserSimpleIndividual(dwContextID,pData,wDataSize);
}
case DBO_GR_USER_REMARKS: //用户备注
{
return OnDBLoadUserRemarksInfo(dwContextID,pData,wDataSize);
}
case DBO_GR_LOAD_OFFLINEMESSAGE: //离线消息
{
return OnDBLoadUserOfflineMessage(dwContextID,pData,wDataSize);
}
case DBO_GR_SEARCH_USER_RESULT: //查找结果
{
return OnDBSearchUserResult(dwContextID,pData,wDataSize);
}
case DBO_GR_ADD_FRIEND: //添加好友
{
return OnDBUserAddFriend(dwContextID,pData,wDataSize);
}
case DBO_GR_DELETE_FRIEND: //删除好友
{
return OnDBLoadDeleteFriend(dwContextID,pData,wDataSize);
}
case DBO_GR_OPERATE_RESULT: //操作结果
{
return OnDBUserOperateResult(dwContextID,pData,wDataSize);
}
case DBO_GR_TRUMPET_RESULT:
{
return OnDBTrumpetResult(dwContextID,pData,wDataSize);
}
case DBO_GR_SYSTEM_MESSAGE_RESULT: //系统消息
{
return OnDBSystemMessage(dwContextID, pData, wDataSize);
}
case DBO_GR_SYSTEM_MESSAGE_FINISH: //加载完成
{
return OnDBSystemMessageFinish(dwContextID, pData, wDataSize);
}
case DBO_GR_MATCH_SIGNUP_RESULT: //报名结果
{
return OnDBPCUserMatchSignupResult(dwContextID, pData, wDataSize);
}
case DBO_GR_MATCH_HISTORY_RESULT_T:
{
return OnDBUserMatchHistoryResult_T(dwContextID, pData, wDataSize);
}
case DBO_GR_MATCH_HISTORY_RESULT_F:
{
return OnDBUserMyMatchHistoryResult(dwContextID, pData, wDataSize);
}
}
}catch(...)
{
TCHAR szMessage[256]=TEXT("");
_sntprintf(szMessage,CountArray(szMessage),TEXT("OnEventDataBase-wRequestID=%d"),wRequestID);
//错误信息
CTraceService::TraceString(szMessage,TraceLevel_Exception);
}
return false;
}
bool CAttemperEngineSink::OnDBLogonSuccess(DWORD dwContextID, VOID * pData, WORD wDataSize)
{
//参数校验
//ASSERT(wDataSize<=sizeof(DBO_GR_LogonSuccess));
if(wDataSize>sizeof(DBO_GR_LogonSuccess)) return false;
//变量定义
DBO_GR_LogonSuccess * pDBOLogonSuccess=(DBO_GR_LogonSuccess *)pData;
//重复登录
CServerUserItem * pServerUserItem = m_ServerUserManager.SearchUserItem(pDBOLogonSuccess->dwUserID);
if(pServerUserItem!=NULL)
{
m_ServerUserManager.DeleteUserItem(pDBOLogonSuccess->dwUserID);
}
//用户变量
tagFriendUserInfo UserInfo;
ZeroMemory(&UserInfo,sizeof(UserInfo));
//基本资料
UserInfo.dwUserID=pDBOLogonSuccess->dwUserID;
UserInfo.dwGameID = pDBOLogonSuccess->dwGameID;
lstrcpyn(UserInfo.szNickName,pDBOLogonSuccess->szNickName,CountArray(UserInfo.szNickName));
lstrcpyn(UserInfo.szPassword,pDBOLogonSuccess->szPassword,CountArray(UserInfo.szPassword));
UserInfo.cbGender=pDBOLogonSuccess->cbGender;
UserInfo.dwFaceID =pDBOLogonSuccess->dwFaceID;
UserInfo.dwCustomID =pDBOLogonSuccess->dwCustomID;
UserInfo.wMemberOrder = pDBOLogonSuccess->wMemberOrder;
UserInfo.wGrowLevel =pDBOLogonSuccess->wGrowLevel;
lstrcpyn(UserInfo.szUnderWrite,pDBOLogonSuccess->szUnderWrite,CountArray(UserInfo.szUnderWrite));
lstrcpyn(UserInfo.szCompellation,pDBOLogonSuccess->szCompellation,CountArray(UserInfo.szCompellation));
//用户状态
UserInfo.cbMainStatus=FRIEND_US_ONLINE;
UserInfo.cbGameStatus=US_NULL;
UserInfo.wKindID=INVALID_KIND;
UserInfo.wServerID=INVALID_SERVER;
UserInfo.wTableID=INVALID_TABLE;
UserInfo.wChairID=INVALID_CHAIR;
ZeroMemory(UserInfo.szServerName,CountArray(UserInfo.szServerName));
UserInfo.dwClientAddr=pDBOLogonSuccess->dwClientAddr;
lstrcpyn(UserInfo.szPhoneMode,pDBOLogonSuccess->szPhoneMode,CountArray(UserInfo.szPhoneMode));
//用户资料
lstrcpyn(UserInfo.szQQ,pDBOLogonSuccess->szQQ,CountArray(UserInfo.szQQ));
lstrcpyn(UserInfo.szEMail,pDBOLogonSuccess->szEMail,CountArray(UserInfo.szEMail));
lstrcpyn(UserInfo.szSeatPhone,pDBOLogonSuccess->szSeatPhone,CountArray(UserInfo.szSeatPhone));
lstrcpyn(UserInfo.szMobilePhone,pDBOLogonSuccess->szMobilePhone,CountArray(UserInfo.szMobilePhone));
lstrcpyn(UserInfo.szDwellingPlace,pDBOLogonSuccess->szDwellingPlace,CountArray(UserInfo.szDwellingPlace));
lstrcpyn(UserInfo.szPostalCode,pDBOLogonSuccess->szPostalCode,CountArray(UserInfo.szPostalCode));
//变量定义
tagInsertLocalUserInfo InsertLocalUserInfo;
InsertLocalUserInfo.dwSocketID=dwContextID;
InsertLocalUserInfo.dwLogonTime=GetTickCount();
//激活用户
m_ServerUserManager.InsertLocalUserItem(InsertLocalUserInfo,UserInfo,pDBOLogonSuccess->szPassword);
//CLocalUserItem *
//发送数据
CMD_GC_LogonEcho LogonSuccess;
ZeroMemory(&LogonSuccess,sizeof(LogonSuccess));
WORD wLogonDataSize = sizeof(LogonSuccess);
SendData(dwContextID,MDM_GC_LOGON,SUB_GC_LOGON_SUCCESS,&LogonSuccess,wLogonDataSize);
//设置用户
WORD wBindIndex=LOWORD(dwContextID);
tagBindParameter * pBindParameter=GetBindParameter(wBindIndex);
pServerUserItem = m_ServerUserManager.SearchUserItem(pDBOLogonSuccess->dwUserID);
pBindParameter->pServerUserItem=pServerUserItem;
//设置头像地址
CLocalUserItem * pLocalUserItem = (CLocalUserItem *)pServerUserItem;
pLocalUserItem->SetFaceUrl(pDBOLogonSuccess->szFaceUrl);
//用户上线
CMD_GC_UserOnlineStatusNotify UserOnLine;
UserOnLine.dwUserID=pServerUserItem->GetUserID();
UserOnLine.cbMainStatus=pServerUserItem->GetMainStatus();
SendDataToUserFriend(UserOnLine.dwUserID,MDM_GC_USER,SUB_GC_USER_STATUS_NOTIFY,&UserOnLine,sizeof(UserOnLine));
//TCHAR szMessage[256]=TEXT("");
//_sntprintf(szMessage,CountArray(szMessage),TEXT("%d-----上线通知"),UserOnLine.dwUserID);
//CTraceService::TraceString(szMessage,TraceLevel_Normal);
//允许群发
m_pITCPNetworkEngine->AllowBatchSend(dwContextID,true,0xFF);
return true;
}
//加载分组
bool CAttemperEngineSink::OnDBLoadUserGroup(DWORD dwContextID, VOID * pData, WORD wDataSize)
{
//参数校验
//ASSERT(wDataSize<=sizeof(DBO_GR_UserGroupInfo));
if(wDataSize>sizeof(DBO_GR_UserGroupInfo)) return false;
//提取数据
DBO_GR_UserGroupInfo * pDBOUserGroupInfo = (DBO_GR_UserGroupInfo *)pData;
//ASSERT(pDBOUserGroupInfo);
//变量定义
tagClientGroupInfo * pTempGroupInfo=NULL;
BYTE cbSendBuffer[SOCKET_TCP_PACKET];
BYTE cbDataBuffer[sizeof(tagClientGroupInfo)];
WORD wDataIndex=0,wPacketSize=0;
//循环发送
for(int nIndex=0;nIndex<pDBOUserGroupInfo->wGroupCount;++nIndex)
{
//设置变量
pTempGroupInfo = &pDBOUserGroupInfo->GroupInfo[nIndex];
//变量定义
tagClientGroupInfo * pSendGroupInfo=(tagClientGroupInfo *)&cbDataBuffer;
//设置变量
pSendGroupInfo->cbGroupIndex=pTempGroupInfo->cbGroupIndex;
lstrcpyn(pSendGroupInfo->szGroupName,pTempGroupInfo->szGroupName,CountArray(pSendGroupInfo->szGroupName));
//设置变量
wPacketSize = sizeof(tagClientGroupInfo)-sizeof(pSendGroupInfo->szGroupName)+CountStringBuffer(pSendGroupInfo->szGroupName);
//发送判断
if(wDataIndex+wPacketSize+sizeof(BYTE)>CountArray(cbSendBuffer))
{
//发送消息
SendData(dwContextID,MDM_GC_LOGON,SUB_S_USER_GROUP,cbSendBuffer,wDataIndex);
//设置变量
ZeroMemory(cbSendBuffer,sizeof(cbSendBuffer));
wDataIndex = 0;
}
//拷贝数据
CopyMemory(&cbSendBuffer[wDataIndex],&wPacketSize,sizeof(BYTE));
CopyMemory(&cbSendBuffer[wDataIndex+sizeof(BYTE)],cbDataBuffer,wPacketSize);
//设置变量
wDataIndex += sizeof(BYTE)+wPacketSize;
}
//剩余发送
if(wDataIndex>0)
{
//发送消息
SendData(dwContextID,MDM_GC_LOGON,SUB_S_USER_GROUP,cbSendBuffer,wDataIndex);
}
return true;
}
//加载好友
bool CAttemperEngineSink::OnDBLoadUserFriend(DWORD dwContextID, VOID * pData, WORD wDataSize)
{
//参数校验
//ASSERT(wDataSize<=sizeof(DBO_GR_UserFriendInfo));
if(wDataSize>sizeof(DBO_GR_UserFriendInfo)) return false;
//提取数据
DBO_GR_UserFriendInfo * pUserFriendInfo = (DBO_GR_UserFriendInfo *)pData;
//ASSERT(pUserFriendInfo);
//在线信息
for(WORD wIndex=0;wIndex<pUserFriendInfo->wFriendCount;++wIndex)
{
//查找用户
CServerUserItem * pServerUserItem=m_ServerUserManager.SearchUserItem(pUserFriendInfo->FriendInfo[wIndex].dwUserID);
if(pServerUserItem==NULL)
{
//设置状态
pUserFriendInfo->FriendInfo[wIndex].cbMainStatus=FRIEND_US_OFFLINE;
pUserFriendInfo->FriendInfo[wIndex].cbGameStatus=US_NULL;
pUserFriendInfo->FriendInfo[wIndex].wKindID=INVALID_KIND;
pUserFriendInfo->FriendInfo[wIndex].wServerID=INVALID_SERVER;
pUserFriendInfo->FriendInfo[wIndex].wTableID=INVALID_TABLE;
pUserFriendInfo->FriendInfo[wIndex].wChairID=INVALID_CHAIR;
ZeroMemory(pUserFriendInfo->FriendInfo[wIndex].szServerName,CountArray(pUserFriendInfo->FriendInfo[wIndex].szServerName));
ZeroMemory(pUserFriendInfo->FriendInfo[wIndex].szPhoneMode,CountArray(pUserFriendInfo->FriendInfo[wIndex].szPhoneMode));
continue;
}
CLocalUserItem * pLocalUserItem = (CLocalUserItem *)pServerUserItem;
tagFriendUserInfo * pUserInfo = pLocalUserItem->GetUserInfo();
//设置变量
pUserFriendInfo->FriendInfo[wIndex].cbMainStatus=pServerUserItem->GetMainStatus();
pUserFriendInfo->FriendInfo[wIndex].cbGameStatus=pServerUserItem->GetGameStatus();
pUserFriendInfo->FriendInfo[wIndex].wKindID=pUserInfo->wKindID;
pUserFriendInfo->FriendInfo[wIndex].wServerID=pUserInfo->wServerID;
pUserFriendInfo->FriendInfo[wIndex].wTableID=pUserInfo->wTableID;
pUserFriendInfo->FriendInfo[wIndex].wChairID=pUserInfo->wChairID;
lstrcpyn(pUserFriendInfo->FriendInfo[wIndex].szServerName,pUserInfo->szServerName,CountArray(pUserFriendInfo->FriendInfo[wIndex].szServerName));
lstrcpyn(pUserFriendInfo->FriendInfo[wIndex].szPhoneMode,pUserInfo->szPhoneMode,CountArray(pUserFriendInfo->FriendInfo[wIndex].szPhoneMode));
}
//变量定义
WORD wFriendCount=pUserFriendInfo->wFriendCount;
CMD_GC_UserFriendInfo IPCUserFriendInfo;
//循环发送
while(wFriendCount>CountArray(IPCUserFriendInfo.FriendInfo))
{
//拷贝数据
IPCUserFriendInfo.wFriendCount=CountArray(IPCUserFriendInfo.FriendInfo);
CopyMemory(IPCUserFriendInfo.FriendInfo,&pUserFriendInfo->FriendInfo[pUserFriendInfo->wFriendCount-wFriendCount],sizeof(tagClientFriendInfo)*IPCUserFriendInfo.wFriendCount);
//发送数据
SendData(dwContextID,MDM_GC_LOGON,SUB_S_USER_FRIEND,&IPCUserFriendInfo,sizeof(IPCUserFriendInfo));
//设置变量
wFriendCount -= CountArray(IPCUserFriendInfo.FriendInfo);
}
//剩余发送
if(wFriendCount>0)
{
//拷贝数据
IPCUserFriendInfo.wFriendCount=wFriendCount;
CopyMemory(IPCUserFriendInfo.FriendInfo,&pUserFriendInfo->FriendInfo[pUserFriendInfo->wFriendCount-wFriendCount],sizeof(tagClientFriendInfo)*wFriendCount);
//发送数据
WORD wPacketDataSize = sizeof(IPCUserFriendInfo)-sizeof(IPCUserFriendInfo.FriendInfo)+sizeof(tagClientFriendInfo)*wFriendCount;
SendData(dwContextID,MDM_GC_LOGON,SUB_S_USER_FRIEND,&IPCUserFriendInfo,wPacketDataSize);
}
if(pUserFriendInfo->bLogonFlag==true)
{
//登录完成
SendData(dwContextID,MDM_GC_LOGON,SUB_S_LOGON_FINISH);
////提示信息
//CTraceService::TraceString(TEXT("发送上线同步信息"),TraceLevel_Normal);
}
//变量定义
tagServerFriendInfo ServerFriendInfo;
//插入好友
CUserFriendGroup * pUserFriendGroup = m_FriendGroupManager.SearchGroupItem(pUserFriendInfo->dwUserID);
if(pUserFriendGroup==NULL)
{
//激活分组
pUserFriendGroup = m_FriendGroupManager.ActiveFriendGroup(pUserFriendInfo->wFriendCount);
m_FriendGroupManager.InsertFriendGroup(pUserFriendInfo->dwUserID,pUserFriendGroup);
}
if(pUserFriendGroup!=NULL)
{
//重置分组
if(pUserFriendInfo->bLogonFlag==true)
{
pUserFriendGroup->ResetFriendGroup();
pUserFriendGroup->SetOwnerUserID(pUserFriendInfo->dwUserID);
}
for(WORD wIndex=0;wIndex<pUserFriendInfo->wFriendCount;++wIndex)
{
ServerFriendInfo.dwUserID=pUserFriendInfo->FriendInfo[wIndex].dwUserID;
ServerFriendInfo.cbMainStatus=pUserFriendInfo->FriendInfo[wIndex].cbMainStatus;
ServerFriendInfo.cbGameStatus=pUserFriendInfo->FriendInfo[wIndex].cbGameStatus;
ServerFriendInfo.cbGroupID=pUserFriendInfo->FriendInfo[wIndex].cbGroupID;
pUserFriendGroup->AppendFriendInfo(ServerFriendInfo);
}
}
return true;
}
//好友备注
bool CAttemperEngineSink::OnDBLoadUserRemarksInfo(DWORD dwContextID, VOID * pData, WORD wDataSize)
{
//参数校验
//ASSERT(wDataSize<=sizeof(DBO_GR_UserRemarksInfo));
if(wDataSize>sizeof(DBO_GR_UserRemarksInfo)) return false;
//提取数据
DBO_GR_UserRemarksInfo * pDBOUserRemarksInfo = (DBO_GR_UserRemarksInfo *)pData;
//ASSERT(pDBOUserRemarksInfo);
//变量定义
tagUserRemarksInfo * pUserRemarksInfo=NULL;
BYTE cbSendBuffer[SOCKET_TCP_PACKET];
BYTE cbDataBuffer[sizeof(tagUserRemarksInfo)];
WORD wDataIndex=0,wPacketSize=0;
//循环发送
for(int nIndex=0;nIndex<pDBOUserRemarksInfo->wFriendCount;++nIndex)
{
//设置变量
pUserRemarksInfo = &pDBOUserRemarksInfo->RemarksInfo[nIndex];
//变量定义
tagUserRemarksInfo * pSendUserRemarksInfo=(tagUserRemarksInfo *)&cbDataBuffer;
//设置变量
pSendUserRemarksInfo->dwFriendUserID=pUserRemarksInfo->dwFriendUserID;
lstrcpyn(pSendUserRemarksInfo->szRemarksInfo,pUserRemarksInfo->szRemarksInfo,CountArray(pSendUserRemarksInfo->szRemarksInfo));
//设置变量
wPacketSize = sizeof(tagUserRemarksInfo)-sizeof(pSendUserRemarksInfo->szRemarksInfo)+CountStringBuffer(pSendUserRemarksInfo->szRemarksInfo);
//发送判断
if(wDataIndex+wPacketSize+sizeof(BYTE)>CountArray(cbSendBuffer))
{
//发送消息
SendData(dwContextID,MDM_GC_LOGON,SUB_S_USER_REMARKS,cbSendBuffer,wDataIndex);
//设置变量
ZeroMemory(cbSendBuffer,sizeof(cbSendBuffer));
wDataIndex = 0;
}
//拷贝数据
CopyMemory(&cbSendBuffer[wDataIndex],&wPacketSize,sizeof(BYTE));
CopyMemory(&cbSendBuffer[wDataIndex+sizeof(BYTE)],cbDataBuffer,wPacketSize);
//设置变量
wDataIndex += sizeof(BYTE)+wPacketSize;
}
//剩余发送
if(wDataIndex>0)
{
//发送消息
SendData(dwContextID,MDM_GC_LOGON,SUB_S_USER_REMARKS,cbSendBuffer,wDataIndex);
}
return true;
}
//好友资料
bool CAttemperEngineSink::OnDBLoadUserSimpleIndividual(DWORD dwContextID, VOID * pData, WORD wDataSize)
{
//参数校验
//ASSERT(wDataSize<=sizeof(DBO_GR_UserIndividual));
if(wDataSize>sizeof(DBO_GR_UserIndividual)) return false;
//提取数据
DBO_GR_UserIndividual * pDBOUserSimpleIndividual = (DBO_GR_UserIndividual *)pData;
//ASSERT(pDBOUserSimpleIndividual);
//变量定义
tagUserIndividual * pUserSimpleIndividual=NULL;
BYTE cbSendBuffer[SOCKET_TCP_PACKET];
BYTE cbDataBuffer[SOCKET_TCP_PACKET];
WORD wDataIndex=0,wPacketSize=0;
//循环发送
for(int nIndex=0;nIndex<pDBOUserSimpleIndividual->wUserCount;++nIndex)
{
//设置变量
pUserSimpleIndividual = &pDBOUserSimpleIndividual->UserIndividual[nIndex];
//变量定义
CMD_GC_UserIndividual * pUserIndividual=(CMD_GC_UserIndividual *)&cbDataBuffer;
CSendPacketHelper SendPacket(pUserIndividual+1,sizeof(cbDataBuffer)-sizeof(CMD_GC_UserIndividual));
//构造结构
pUserIndividual->dwUserID = pUserSimpleIndividual->dwUserID;
//设置变量
wPacketSize = sizeof(CMD_GC_UserIndividual);
//QQ号码
if (pUserSimpleIndividual->szQQ[0]!=0)
{
WORD wBufferSize=CountStringBuffer(pUserSimpleIndividual->szQQ);
SendPacket.AddPacket(pUserSimpleIndividual->szQQ,wBufferSize,DTP_GP_UI_QQ);
}
//Email
if (pUserSimpleIndividual->szEMail[0]!=0)
{
WORD wBufferSize=CountStringBuffer(pUserSimpleIndividual->szEMail);
SendPacket.AddPacket(pUserSimpleIndividual->szEMail,wBufferSize,DTP_GP_UI_EMAIL);
}
//固定电话
if (pUserSimpleIndividual->szSeatPhone[0]!=0)
{
WORD wBufferSize=CountStringBuffer(pUserSimpleIndividual->szSeatPhone);
SendPacket.AddPacket(pUserSimpleIndividual->szSeatPhone,wBufferSize,DTP_GP_UI_SEATPHOHE);
}
//手机号码
if (pUserSimpleIndividual->szMobilePhone[0]!=0)
{
WORD wBufferSize=CountStringBuffer(pUserSimpleIndividual->szMobilePhone);
SendPacket.AddPacket(pUserSimpleIndividual->szMobilePhone,wBufferSize,DTP_GP_UI_MOBILEPHONE);
}
//联系地址
if (pUserSimpleIndividual->szDwellingPlace[0]!=0)
{
WORD wBufferSize=CountStringBuffer(pUserSimpleIndividual->szDwellingPlace);
SendPacket.AddPacket(pUserSimpleIndividual->szDwellingPlace,wBufferSize,DTP_GP_UI_DWELLINGPLACE);
}
//邮政编码
if (pUserSimpleIndividual->szPostalCode[0]!=0)
{
WORD wBufferSize=CountStringBuffer(pUserSimpleIndividual->szPostalCode);
SendPacket.AddPacket(pUserSimpleIndividual->szPostalCode,wBufferSize,DTP_GP_UI_POSTALCODE);
}
//设置变量
wPacketSize += SendPacket.GetDataSize();
//发送判断
if(wDataIndex+wPacketSize+sizeof(WORD)>CountArray(cbSendBuffer))
{
//发送消息
SendData(dwContextID,MDM_GC_LOGON,SUB_S_USER_SINDIVIDUAL,cbSendBuffer,wDataIndex);
//设置变量
ZeroMemory(cbSendBuffer,sizeof(cbSendBuffer));
wDataIndex = 0;
}
//拷贝数据
CopyMemory(&cbSendBuffer[wDataIndex],&wPacketSize,sizeof(WORD));
CopyMemory(&cbSendBuffer[wDataIndex+sizeof(WORD)],cbDataBuffer,wPacketSize);
//设置变量
wDataIndex += sizeof(WORD)+wPacketSize;
}
//剩余发送
if(wDataIndex>0)
{
//发送消息
SendData(dwContextID,MDM_GC_LOGON,SUB_S_USER_SINDIVIDUAL,cbSendBuffer,wDataIndex);
}
return true;
}
//离线消息
bool CAttemperEngineSink::OnDBLoadUserOfflineMessage(DWORD dwContextID, VOID * pData, WORD wDataSize)
{
//参数校验
//ASSERT(wDataSize<=sizeof(DBO_GR_UserOfflineMessage));
if(wDataSize>sizeof(DBO_GR_UserOfflineMessage)) return false;
//提取数据
DBO_GR_UserOfflineMessage * pUserUserOfflineMessage = (DBO_GR_UserOfflineMessage *)pData;
//ASSERT(pUserUserOfflineMessage);
//变量定义
BYTE cbOfflineData[CountArray(pUserUserOfflineMessage->szOfflineData)];
ZeroMemory(cbOfflineData,sizeof(cbOfflineData));
//解析数据
if (pUserUserOfflineMessage->szOfflineData[0]!=0)
{
//获取长度
INT nCustomRuleSize=lstrlen(pUserUserOfflineMessage->szOfflineData)/2;
//转换字符
for (INT i=0;i<nCustomRuleSize;i++)
{
//获取字符
TCHAR cbChar1=pUserUserOfflineMessage->szOfflineData[i*2];
TCHAR cbChar2=pUserUserOfflineMessage->szOfflineData[i*2+1];
//效验字符
//ASSERT((cbChar1>=TEXT('0'))&&(cbChar1<=TEXT('9'))||(cbChar1>=TEXT('A'))&&(cbChar1<=TEXT('F')));
//ASSERT((cbChar2>=TEXT('0'))&&(cbChar2<=TEXT('9'))||(cbChar2>=TEXT('A'))&&(cbChar2<=TEXT('F')));
//生成结果
if ((cbChar2>=TEXT('0'))&&(cbChar2<=TEXT('9'))) cbOfflineData[i]+=(cbChar2-TEXT('0'));
if ((cbChar2>=TEXT('A'))&&(cbChar2<=TEXT('F'))) cbOfflineData[i]+=(cbChar2-TEXT('A')+0x0A);
//生成结果
if ((cbChar1>=TEXT('0'))&&(cbChar1<=TEXT('9'))) cbOfflineData[i]+=(cbChar1-TEXT('0'))*0x10;
if ((cbChar1>=TEXT('A'))&&(cbChar1<=TEXT('F'))) cbOfflineData[i]+=(cbChar1-TEXT('A')+0x0A)*0x10;
}
}
//发送消息
SendData(dwContextID,MDM_GC_USER,pUserUserOfflineMessage->wMessageType,&cbOfflineData,pUserUserOfflineMessage->wDataSize);
return true;
}
bool CAttemperEngineSink::OnDBLoadDeleteFriend(DWORD dwContextID, VOID * pData, WORD wDataSize)
{
//参数校验
//ASSERT(wDataSize<=sizeof(DBO_GR_DeleteFriend));
if(wDataSize>sizeof(DBO_GR_DeleteFriend)) return false;
//提取数据
DBO_GR_DeleteFriend * pDeleteFriend = (DBO_GR_DeleteFriend *)pData;
//ASSERT(pDeleteFriend);
//获取用户
CServerUserItem * pServerUserItem = m_ServerUserManager.SearchUserItem(pDeleteFriend->dwUserID);
if(pServerUserItem!=NULL)
{
CUserFriendGroup * pFriendGroup = m_FriendGroupManager.SearchGroupItem(pDeleteFriend->dwUserID);
if(pFriendGroup!=NULL)
{
//移除好友
pFriendGroup->RemoveFriendInfo(pDeleteFriend->dwFriendUserID);
pFriendGroup->RemoveFriendInfo(pDeleteFriend->dwUserID);
}
//获取好友
CUserFriendGroup * pUserFriendGroup = m_FriendGroupManager.SearchGroupItem(pDeleteFriend->dwUserID);
if(pUserFriendGroup==NULL)
{
pUserFriendGroup = m_FriendGroupManager.ActiveFriendGroup(MIN_FRIEND_CONTENT);
}
if(pUserFriendGroup!=NULL)
{
//获取好友分组
CUserFriendGroup * pDestFriendGroup = m_FriendGroupManager.SearchGroupItem(pDeleteFriend->dwFriendUserID);
if(pDestFriendGroup!=NULL)
{
//移除好友
pUserFriendGroup->RemoveFriendInfo(pDeleteFriend->dwFriendUserID);
pDestFriendGroup->RemoveFriendInfo(pDeleteFriend->dwUserID);
}
CServerUserItem * pFriendUserItem = m_ServerUserManager.SearchUserItem(pDeleteFriend->dwFriendUserID);
if(pFriendUserItem!=NULL&&pFriendUserItem->GetMainStatus()==FRIEND_US_ONLINE)
{
//构造结构
CMD_GC_DeleteFriendNotify DeleteFriendNotify;
DeleteFriendNotify.dwFriendUserID=pDeleteFriend->dwUserID;
//发送数据
SendData(((CLocalUserItem *)pFriendUserItem)->GetSocketID(),MDM_GC_USER,SUB_GC_DELETE_FRIEND_NOTIFY,&DeleteFriendNotify,sizeof(DeleteFriendNotify));
}
}
}
//构造结构
CMD_GC_DeleteFriendNotify DeleteFriendNotify;
DeleteFriendNotify.dwFriendUserID=pDeleteFriend->dwFriendUserID;
//发送数据
SendData(dwContextID,MDM_GC_USER,SUB_GC_DELETE_FRIEND_NOTIFY,&DeleteFriendNotify,sizeof(DeleteFriendNotify));
return true;
}
//查找用户
bool CAttemperEngineSink::OnDBSearchUserResult(DWORD dwContextID, VOID * pData, WORD wDataSize)
{
//参数校验
//ASSERT(wDataSize<=sizeof(DBO_GR_SearchUserResult));
if(wDataSize>sizeof(DBO_GR_SearchUserResult)) return false;
//提取数据
DBO_GR_SearchUserResult * pSearchUserResult = (DBO_GR_SearchUserResult *)pData;
//ASSERT(pSearchUserResult);
//填充数据
CServerUserItem * pServerUserItem=m_ServerUserManager.SearchUserItem(pSearchUserResult->FriendInfo.dwUserID);
if(pServerUserItem==NULL)
{
pSearchUserResult->FriendInfo.cbMainStatus=FRIEND_US_OFFLINE;
pSearchUserResult->FriendInfo.cbGameStatus=US_NULL;
pSearchUserResult->FriendInfo.wKindID=INVALID_KIND;
pSearchUserResult->FriendInfo.wServerID=INVALID_SERVER;
pSearchUserResult->FriendInfo.wTableID=INVALID_TABLE;
pSearchUserResult->FriendInfo.wChairID=INVALID_CHAIR;
ZeroMemory(pSearchUserResult->FriendInfo.szServerName,CountArray(pSearchUserResult->FriendInfo.szServerName));
ZeroMemory(pSearchUserResult->FriendInfo.szPhoneMode,CountArray(pSearchUserResult->FriendInfo.szPhoneMode));
}
else
{
CLocalUserItem * pLocalUserItem = (CLocalUserItem *)pServerUserItem;
tagFriendUserInfo * pUserInfo = pLocalUserItem->GetUserInfo();
pSearchUserResult->FriendInfo.cbMainStatus=pServerUserItem->GetMainStatus();
pSearchUserResult->FriendInfo.cbGameStatus=pServerUserItem->GetGameStatus();
pSearchUserResult->FriendInfo.wKindID=pUserInfo->wKindID;
pSearchUserResult->FriendInfo.wServerID=pUserInfo->wServerID;
pSearchUserResult->FriendInfo.wTableID=pUserInfo->wTableID;
pSearchUserResult->FriendInfo.wChairID=pUserInfo->wChairID;
lstrcpyn(pSearchUserResult->FriendInfo.szServerName,pUserInfo->szServerName,CountArray(pSearchUserResult->FriendInfo.szServerName));
lstrcpyn(pSearchUserResult->FriendInfo.szPhoneMode,pUserInfo->szPhoneMode,CountArray(pSearchUserResult->FriendInfo.szPhoneMode));
}
//变量定义
CMD_GC_SearchByGameIDResult SearchUserResult;
ZeroMemory(&SearchUserResult,sizeof(SearchUserResult));
SearchUserResult.cbUserCount =pSearchUserResult->cbUserCount;
BYTE cbUserCount=pSearchUserResult->cbUserCount;
if(cbUserCount>0)
{
CopyMemory(&(SearchUserResult.FriendInfo),&(pSearchUserResult->FriendInfo),sizeof(tagClientFriendInfo)*(pSearchUserResult->cbUserCount));
SendData(dwContextID,MDM_GC_USER,SUB_GC_SEARCH_USER_RESULT,&SearchUserResult,sizeof(SearchUserResult));
}
else
{
//回应反馈
CMD_GC_SearchByGameIDEcho SearchUserEcho;
ZeroMemory(&SearchUserEcho,sizeof(SearchUserEcho));
SearchUserEcho.lErrorCode=CHAT_MSG_ERR;
lstrcpyn(SearchUserEcho.szDescribeString,_T("查询不到用户"),CountArray(SearchUserEcho.szDescribeString));
WORD wDataSize=CountStringBuffer(SearchUserEcho.szDescribeString);
WORD wHeadSize=sizeof(SearchUserEcho)-sizeof(SearchUserEcho.szDescribeString);
SendData(dwContextID,MDM_GC_USER,SUB_GC_SEARCH_USER_ECHO,&SearchUserEcho,wHeadSize+wDataSize);
}
return true;
}
//添加好友
bool CAttemperEngineSink::OnDBUserAddFriend(DWORD dwContextID, VOID * pData, WORD wDataSize)
{
//参数校验
//ASSERT(wDataSize==sizeof(DBO_GR_AddFriend));
if(wDataSize!=sizeof(DBO_GR_AddFriend)) return false;
//提取数据
DBO_GR_AddFriend * pAddFriend = (DBO_GR_AddFriend *)pData;
//ASSERT(pAddFriend);
//查找用户
CServerUserItem * pServerUserItem = m_ServerUserManager.SearchUserItem(pAddFriend->dwUserID);
CServerUserItem * pRequestUserItem = m_ServerUserManager.SearchUserItem(pAddFriend->dwRequestUserID);
if(pServerUserItem==NULL || pServerUserItem->GetUserItemKind()!=enLocalKind) return false;
//处理用户
if(pServerUserItem!=NULL)
{
if(pAddFriend->bLoadUserInfo==false && pRequestUserItem && pRequestUserItem->GetUserItemKind()==enLocalKind)
{
//变量定义
CLocalUserItem * pRequestLocalInfo = (CLocalUserItem *)pRequestUserItem;
//获取好友
CUserFriendGroup * pUserFriendGroup = m_FriendGroupManager.SearchGroupItem(pAddFriend->dwUserID);
if(pUserFriendGroup==NULL)
{
pUserFriendGroup = m_FriendGroupManager.ActiveFriendGroup(MIN_FRIEND_CONTENT);
}
//变量定义
tagServerFriendInfo ServerFriendInfo;
ZeroMemory(&ServerFriendInfo,sizeof(ServerFriendInfo));
//设置变量
ServerFriendInfo.dwUserID=pAddFriend->dwRequestUserID;
ServerFriendInfo.cbGroupID=pAddFriend->cbGroupID;
ServerFriendInfo.cbMainStatus=FRIEND_US_OFFLINE;
ServerFriendInfo.cbGameStatus=US_OFFLINE;
//获取用户
if(pRequestUserItem!=NULL)
{
ServerFriendInfo.cbMainStatus=pRequestUserItem->GetMainStatus();
ServerFriendInfo.cbGameStatus=pRequestUserItem->GetGameStatus();
}
//添加好友
pUserFriendGroup->AppendFriendInfo(ServerFriendInfo);
//变量定义
CMD_GC_UserFriendInfo UserFriendInfo;
ZeroMemory(&UserFriendInfo.FriendInfo,sizeof(tagClientFriendInfo)*MAX_FRIEND_TRANSFER);
//构造结构
UserFriendInfo.wFriendCount = 1;
//基本信息
UserFriendInfo.FriendInfo[0].dwUserID=pRequestLocalInfo->GetUserID();
UserFriendInfo.FriendInfo[0].dwGameID= pRequestLocalInfo->GetGameID();
UserFriendInfo.FriendInfo[0].cbGroupID =pAddFriend->cbGroupID;
UserFriendInfo.FriendInfo[0].dwFaceID =pRequestLocalInfo->GetUserInfo()->dwFaceID;
UserFriendInfo.FriendInfo[0].cbGender =pRequestLocalInfo->GetUserInfo()->cbGender;
UserFriendInfo.FriendInfo[0].dwCustomID =pRequestLocalInfo->GetUserInfo()->dwCustomID;
UserFriendInfo.FriendInfo[0].wMemberOrder =pRequestLocalInfo->GetUserInfo()->wMemberOrder;
UserFriendInfo.FriendInfo[0].wGrowLevel =pRequestLocalInfo->GetUserInfo()->wGrowLevel;
lstrcpyn(UserFriendInfo.FriendInfo[0].szNickName,pRequestLocalInfo->GetNickName(),CountArray(UserFriendInfo.FriendInfo[0].szNickName));
lstrcpyn(UserFriendInfo.FriendInfo[0].szUnderWrite,pRequestLocalInfo->GetUserInfo()->szUnderWrite,CountArray(UserFriendInfo.FriendInfo[0].szUnderWrite));
lstrcpyn(UserFriendInfo.FriendInfo[0].szCompellation,pRequestLocalInfo->GetUserInfo()->szCompellation,CountArray(UserFriendInfo.FriendInfo[0].szCompellation));
lstrcpyn(UserFriendInfo.FriendInfo[0].szPhoneMode,pRequestLocalInfo->GetUserInfo()->szPhoneMode,CountArray(UserFriendInfo.FriendInfo[0].szPhoneMode));
//在线信息
UserFriendInfo.FriendInfo[0].cbMainStatus=pRequestLocalInfo->GetMainStatus();
UserFriendInfo.FriendInfo[0].cbGameStatus=pRequestLocalInfo->GetGameStatus();
UserFriendInfo.FriendInfo[0].wServerID=pRequestLocalInfo->GetServerID();
UserFriendInfo.FriendInfo[0].wTableID = pRequestLocalInfo->GetTableID();
//发送数据
WORD wSize = sizeof(UserFriendInfo)-sizeof(UserFriendInfo.FriendInfo)+sizeof(tagClientFriendInfo)*UserFriendInfo.wFriendCount;
SendData(((CLocalUserItem *)pServerUserItem)->GetSocketID(),MDM_GC_LOGON,SUB_S_USER_FRIEND,&UserFriendInfo,wSize);
}
}
//处理用户
if(pRequestUserItem!=NULL)
{
if(pRequestUserItem->GetUserItemKind()==enLocalKind)
{
//变量定义
CLocalUserItem * pServerLocalInfo = (CLocalUserItem *)pServerUserItem;
//获取好友
CUserFriendGroup * pUserFriendGroup = m_FriendGroupManager.SearchGroupItem(pAddFriend->dwRequestUserID);
if(pUserFriendGroup==NULL)
{
pUserFriendGroup = m_FriendGroupManager.ActiveFriendGroup(MIN_FRIEND_CONTENT);
}
//变量定义
tagServerFriendInfo ServerFriendInfo;
ZeroMemory(&ServerFriendInfo,sizeof(ServerFriendInfo));
//设置变量
ServerFriendInfo.dwUserID=pAddFriend->dwUserID;
ServerFriendInfo.cbGroupID=pAddFriend->cbRequestGroupID;
ServerFriendInfo.cbMainStatus=FRIEND_US_OFFLINE;
ServerFriendInfo.cbGameStatus=US_OFFLINE;
//获取用户
if(pServerUserItem!=NULL)
{
ServerFriendInfo.cbMainStatus=pServerUserItem->GetMainStatus();
ServerFriendInfo.cbGameStatus=pServerUserItem->GetGameStatus();
}
//添加好友
pUserFriendGroup->AppendFriendInfo(ServerFriendInfo);
if(pRequestUserItem->GetMainStatus()!=FRIEND_US_OFFLINE)
{
//变量定义
CMD_GC_UserFriendInfo UserFriendInfo;
ZeroMemory(&UserFriendInfo.FriendInfo,sizeof(tagClientFriendInfo)*MAX_FRIEND_TRANSFER);
//构造结构
UserFriendInfo.wFriendCount = 1;
//基本信息
UserFriendInfo.FriendInfo[0].dwUserID=pServerLocalInfo->GetUserID();
UserFriendInfo.FriendInfo[0].dwGameID= pServerLocalInfo->GetGameID();
UserFriendInfo.FriendInfo[0].cbGroupID =pAddFriend->cbRequestGroupID;
UserFriendInfo.FriendInfo[0].dwFaceID =pServerLocalInfo->GetUserInfo()->dwFaceID;
UserFriendInfo.FriendInfo[0].dwCustomID =pServerLocalInfo->GetUserInfo()->dwCustomID;
UserFriendInfo.FriendInfo[0].cbGender =pServerLocalInfo->GetUserInfo()->cbGender;
UserFriendInfo.FriendInfo[0].wMemberOrder =pServerLocalInfo->GetUserInfo()->wMemberOrder;
UserFriendInfo.FriendInfo[0].wGrowLevel =pServerLocalInfo->GetUserInfo()->wGrowLevel;
lstrcpyn(UserFriendInfo.FriendInfo[0].szNickName,pServerLocalInfo->GetNickName(),CountArray(UserFriendInfo.FriendInfo[0].szNickName));
lstrcpyn(UserFriendInfo.FriendInfo[0].szUnderWrite,pServerLocalInfo->GetUserInfo()->szUnderWrite,CountArray(UserFriendInfo.FriendInfo[0].szUnderWrite));
lstrcpyn(UserFriendInfo.FriendInfo[0].szCompellation,pServerLocalInfo->GetUserInfo()->szCompellation,CountArray(UserFriendInfo.FriendInfo[0].szCompellation));
lstrcpyn(UserFriendInfo.FriendInfo[0].szPhoneMode,pServerLocalInfo->GetUserInfo()->szPhoneMode,CountArray(UserFriendInfo.FriendInfo[0].szPhoneMode));
//在线信息
UserFriendInfo.FriendInfo[0].cbMainStatus=pServerLocalInfo->GetMainStatus();
UserFriendInfo.FriendInfo[0].cbGameStatus=pServerLocalInfo->GetGameStatus();
UserFriendInfo.FriendInfo[0].wServerID=pServerLocalInfo->GetServerID();
UserFriendInfo.FriendInfo[0].wTableID = pServerLocalInfo->GetTableID();
//发送数据
WORD wSize = sizeof(UserFriendInfo)-sizeof(UserFriendInfo.FriendInfo)+sizeof(tagClientFriendInfo)*UserFriendInfo.wFriendCount;
SendData(((CLocalUserItem *)pRequestUserItem)->GetSocketID(),MDM_GC_LOGON,SUB_S_USER_FRIEND,&UserFriendInfo,wSize);
}
//消息提醒
CMD_GC_RespondNotify RespondNotify;
_sntprintf(RespondNotify.szNotifyContent,CountArray(RespondNotify.szNotifyContent),TEXT("%s 同意了您的好友申请!"),pServerLocalInfo->GetNickName());
if(pRequestUserItem->GetMainStatus()==FRIEND_US_OFFLINE)
{
SaveOfflineMessage(pRequestUserItem->GetUserID(),SUB_GC_RESPOND_NOTIFY,&RespondNotify,sizeof(RespondNotify),dwContextID);
}
else
{
//发送数据
SendData(((CLocalUserItem *)pRequestUserItem)->GetSocketID(),MDM_GC_USER,SUB_GC_RESPOND_NOTIFY,&RespondNotify,sizeof(RespondNotify));
}
}
}
return true;
}
bool CAttemperEngineSink::OnDBTrumpetResult(DWORD dwContextID, VOID * pData, WORD wDataSize)
{
//参数校验
//ASSERT(wDataSize==sizeof(DBO_GR_TrumpetResult));
if(wDataSize!=sizeof(DBO_GR_TrumpetResult)) return false;
//提取数据
DBO_GR_TrumpetResult * pTrumpetResult = (DBO_GR_TrumpetResult *)pData;
//ASSERT(pTrumpetResult);
if (pTrumpetResult->lResult == 0)
{
//喇叭反馈
CMD_GC_TrumpetEcho TrumpetEcho;
ZeroMemory(&TrumpetEcho,sizeof(TrumpetEcho));
TrumpetEcho.lErrorCode=CHAT_MSG_OK;
lstrcpyn(TrumpetEcho.szDescribeString,pTrumpetResult->szNotifyContent,CountArray(TrumpetEcho.szDescribeString));
WORD wDataSize2=CountStringBuffer(TrumpetEcho.szDescribeString);
WORD wHeadSize=sizeof(TrumpetEcho)-sizeof(TrumpetEcho.szDescribeString);
SendData(dwContextID,MDM_GC_USER,SUB_GC_TRUMPET_ECHO,&TrumpetEcho,wHeadSize+wDataSize2);
CMD_GC_Trumpet Trumpet;
ZeroMemory(&Trumpet, sizeof(Trumpet));
Trumpet.wPropertyID = pTrumpetResult->wPropertyID;
Trumpet.dwSendUserID = pTrumpetResult->dwSendUserID;
Trumpet.TrumpetColor = pTrumpetResult->TrumpetColor;
lstrcpyn(Trumpet.szSendNickName, pTrumpetResult->szSendNickName, CountArray(Trumpet.szSendNickName));
lstrcpyn(Trumpet.szTrumpetContent, pTrumpetResult->szTrumpetContent, CountArray(Trumpet.szTrumpetContent));
m_pITCPSocketService->SendData(MDM_CS_MANAGER_SERVICE,SUB_CS_C_PROPERTY_TRUMPET,&Trumpet,sizeof(Trumpet));
}
else
{
//喇叭反馈
CMD_GC_TrumpetEcho TrumpetEcho;
ZeroMemory(&TrumpetEcho,sizeof(TrumpetEcho));
TrumpetEcho.lErrorCode=CHAT_MSG_ERR;
lstrcpyn(TrumpetEcho.szDescribeString,pTrumpetResult->szNotifyContent,CountArray(TrumpetEcho.szDescribeString));
WORD wDataSize=CountStringBuffer(TrumpetEcho.szDescribeString);
WORD wHeadSize=sizeof(TrumpetEcho)-sizeof(TrumpetEcho.szDescribeString);
SendData(dwContextID,MDM_GC_USER,SUB_GC_TRUMPET_ECHO,&TrumpetEcho,wHeadSize+wDataSize);
}
return true;
}
//操作结果
bool CAttemperEngineSink::OnDBUserOperateResult(DWORD dwContextID, VOID * pData, WORD wDataSize)
{
//参数校验
//ASSERT(wDataSize<=sizeof(DBO_GR_OperateResult));
if(wDataSize>sizeof(DBO_GR_OperateResult)) return false;
//提取数据
DBO_GR_OperateResult * pUserOperateResult = (DBO_GR_OperateResult *)pData;
//ASSERT(pUserOperateResult);
//获取用户
if(pUserOperateResult->bModifySucesss==true)
{
//发送成功
SendOperateSuccess(pUserOperateResult->szDescribeString,pUserOperateResult->wOperateCode,dwContextID);
}
else
{
//发送失败
SendOperateFailure(pUserOperateResult->szDescribeString,pUserOperateResult->dwErrorCode,pUserOperateResult->wOperateCode,dwContextID);
}
return true;
}
//移除消息
void CAttemperEngineSink::RemoveSystemMessage()
{
//缓存消息
m_SystemMessageBuffer.Append(m_SystemMessageActive);
m_SystemMessageActive.RemoveAll();
}
//系统消息
bool CAttemperEngineSink::OnDBSystemMessage(DWORD dwContextID, VOID * pData, WORD wDataSize)
{
//参数校验
//ASSERT(wDataSize == sizeof(tag_GR_SystemMessage));
if (wDataSize != sizeof(tag_GR_SystemMessage)) return false;
//提取数据
tag_GR_SystemMessage * pSystemMessage = (tag_GR_SystemMessage *)pData;
if (pSystemMessage == NULL) return false;
for (INT_PTR nIndex = m_SystemMessageBuffer.GetCount() - 1; nIndex >= 0; nIndex--)
{
tagSystemMessage *pTagSystemMessage = m_SystemMessageBuffer[nIndex];
if (pTagSystemMessage && pTagSystemMessage->SystemMessage.dwMessageID == pSystemMessage->dwMessageID)
{
CopyMemory(&pTagSystemMessage->SystemMessage, pSystemMessage, sizeof(tag_GR_SystemMessage));
m_SystemMessageActive.Add(pTagSystemMessage);
m_SystemMessageBuffer.RemoveAt(nIndex);
return true;
}
}
//定义变量
tagSystemMessage *pSendMessage = new tagSystemMessage;
ZeroMemory(pSendMessage, sizeof(tagSystemMessage));
//设置变量
pSendMessage->dwLastTime = (DWORD)pSystemMessage->tStartTime;
CopyMemory(&pSendMessage->SystemMessage, pSystemMessage, sizeof(tag_GR_SystemMessage));
//记录消息
m_SystemMessageActive.Add(pSendMessage);
return true;
}
//加载完成
bool CAttemperEngineSink::OnDBSystemMessageFinish(DWORD dwContextID, VOID * pData, WORD wDataSize)
{
//处理临时消息
if (m_SystemMessageBuffer.GetCount()>0)
{
//变量定义
tagSystemMessage *pTagSystemMessage = NULL;
for (INT_PTR nIndex = m_SystemMessageBuffer.GetCount() - 1; nIndex >= 0; nIndex--)
{
pTagSystemMessage = m_SystemMessageBuffer[nIndex];
if (pTagSystemMessage && pTagSystemMessage->SystemMessage.dwMessageID == TEMP_MESSAGE_ID)
{
m_SystemMessageActive.Add(pTagSystemMessage);
m_SystemMessageBuffer.RemoveAt(nIndex);
}
}
}
return true;
}
//报名结果
bool CAttemperEngineSink::OnDBPCUserMatchSignupResult(DWORD dwContextID, VOID * pData, WORD wDataSize)
{
//判断在线
// //ASSERT(LOWORD(dwContextID) < m_pInitParameter->m_wMaxConnect);
// if ((m_pBindParameter + LOWORD(dwContextID))->dwSocketID != dwContextID) return true;
//变量定义
DBO_GR_MatchSingupResult * pMatchSignupResult = (DBO_GR_MatchSingupResult *)pData;
//变量定义
CMD_GC_MatchSignupResult MatchSignupResult;
ZeroMemory(&MatchSignupResult, sizeof(MatchSignupResult));
//构造结构
MatchSignupResult.bSuccessed = pMatchSignupResult->bSuccessed;
MatchSignupResult.wServerID = pMatchSignupResult->wServerID;
MatchSignupResult.lCurrScore = pMatchSignupResult->lCurrScore;
lstrcpyn(MatchSignupResult.szDescribeString, pMatchSignupResult->szDescribeString, CountArray(MatchSignupResult.szDescribeString));
//发送数据
WORD wSendSize = sizeof(MatchSignupResult)-sizeof(MatchSignupResult.szDescribeString) + CountStringBuffer(MatchSignupResult.szDescribeString);
m_pITCPNetworkEngine->SendData(dwContextID, MDM_GC_MATCH, SUB_GC_MATCH_SIGNUP_RESULT, &MatchSignupResult, sizeof(MatchSignupResult));
return true;
}
//我的比赛结果
bool CAttemperEngineSink::OnDBUserMatchHistoryResult_T(DWORD dwContextID, VOID * pData, WORD wDataSize)
{
//发送数据
m_pITCPNetworkEngine->SendData(dwContextID, MDM_GC_MATCH, SUB_GC_MY_MATCH_HISTORY_RESULT_T, pData, wDataSize);
return true;
}
//我的比赛结果
bool CAttemperEngineSink::OnDBUserMyMatchHistoryResult(DWORD dwContextID, VOID * pData, WORD wDataSize)
{
//判断在线
// //ASSERT(LOWORD(dwContextID) < m_pInitParameter->m_wMaxConnect);
// if ((m_pBindParameter + LOWORD(dwContextID))->dwSocketID != dwContextID) return true;
//变量定义
DBO_GR_MyMatchHistoryResult * pMyMatchResult = (DBO_GR_MyMatchHistoryResult *)pData;
//变量定义
CMD_GC_MyMatchHistoryResult MyMatchResult;
ZeroMemory(&MyMatchResult, sizeof(MyMatchResult));
//构造结构
MyMatchResult.bResultCode = pMyMatchResult->bResultCode;
lstrcpyn(MyMatchResult.szMatchName, pMyMatchResult->szMatchName, CountArray(MyMatchResult.szMatchName));
MyMatchResult.wKindID = pMyMatchResult->wKindID;
MyMatchResult.wRandID = pMyMatchResult->wRandID;
lstrcpyn(MyMatchResult.szDescribeString, pMyMatchResult->szDescribeString, CountArray(MyMatchResult.szDescribeString));
//发送数据
m_pITCPNetworkEngine->SendData(dwContextID, MDM_GC_MATCH, SUB_GC_MY_MATCH_HISTORY_RESULT_F, &MyMatchResult, sizeof(MyMatchResult));
return true;
}
//请求约战房间列表
bool CAttemperEngineSink::OnTCPNetworkSubPersonalGoldRoomList(VOID * pData, WORD wDataSize, DWORD dwSocketID)
{
//效验参数
//ASSERT(wDataSize == sizeof(CMD_SC_C_PersonalGoldRoomList));
if (wDataSize != sizeof(CMD_SC_C_PersonalGoldRoomList)) return false;
CMD_SC_C_PersonalGoldRoomList * pPersonalGoldRoomList = (CMD_SC_C_PersonalGoldRoomList *)pData;
if (pPersonalGoldRoomList == NULL)
{
return false;
}
//变量定义
CMD_SC_C_PersonalGoldRoomListResult PersonalGoldRoomListResult;
BYTE cbDataBuffer[SOCKET_TCP_PACKET] = { 0 };
ZeroMemory(cbDataBuffer, sizeof(cbDataBuffer));
CMD_SC_C_PersonalGoldRoomListResult * pPersonalGoldRoomListResult = (CMD_SC_C_PersonalGoldRoomListResult*)cbDataBuffer;
int cbPacketSize = 0;
//获取同种类型游戏房间数量
int nCount = m_PersonalRoomManager.GetPersonalTableCount(pPersonalGoldRoomList->dwKindID);
TCHAR szInfo[260] = { 0 };
wsprintf(szInfo, TEXT("ptdt *** OnTCPNetworkSubPersonalGoldRoomList 房间数量nCount = %d kindid = %d cbPacketSize = %d"), nCount, pPersonalGoldRoomList->dwKindID, cbPacketSize );
//OutputDebugString(szInfo);
//遍历所有房间
for (int i = 0; i < nCount; i++)
{
//发送判断
if (cbPacketSize + sizeof(CMD_SC_C_PersonalGoldRoomListResult) > sizeof(cbDataBuffer))
{
//发送数据
m_pITCPNetworkEngine->SendDataBatch(MDM_CS_PERSONAL, CMD_CS_C_GET_GOLD_LIST_RESLUT, pPersonalGoldRoomListResult, cbPacketSize, 0xFF);
//重置变量
cbPacketSize = 0;
ZeroMemory(cbDataBuffer, sizeof(cbDataBuffer));
pPersonalGoldRoomListResult = (CMD_SC_C_PersonalGoldRoomListResult*)cbDataBuffer;
}
tagPersonalTableInfoEx * pPersonalTableInfoEx = m_PersonalRoomManager.EnumPersonalTableItem(pPersonalGoldRoomList->dwKindID, 1, i);
if (!pPersonalTableInfoEx)
{
continue;
}
PersonalGoldRoomListResult.dwServerID = pPersonalTableInfoEx->dwServerID;
PersonalGoldRoomListResult.dwKindID = pPersonalTableInfoEx->dwKindID;
PersonalGoldRoomListResult.dwTableID = pPersonalTableInfoEx->dwTableID;
PersonalGoldRoomListResult.dwUserID = pPersonalTableInfoEx->dwUserID;
PersonalGoldRoomListResult.lCellScore = pPersonalTableInfoEx->lCellScore;
PersonalGoldRoomListResult.dwPersonalRoomID = pPersonalTableInfoEx->dwPersonalRoomID;
PersonalGoldRoomListResult.dwRoomTax = pPersonalTableInfoEx->dwRoomTax;
PersonalGoldRoomListResult.cbPlayMode = pPersonalTableInfoEx->cbPlayMode;
PersonalGoldRoomListResult.wJoinGamePeopleCount = pPersonalTableInfoEx->wJoinGamePeopleCount;
PersonalGoldRoomListResult.lEnterScoreLimit = pPersonalTableInfoEx->lEnterScoreLimit;
PersonalGoldRoomListResult.lLeaveScoreLimit = pPersonalTableInfoEx->lLeaveScoreLimit;
PersonalGoldRoomListResult.bGameStart = pPersonalTableInfoEx->bGameStart;
memcpy_s(PersonalGoldRoomListResult.cbGameRule, sizeof(PersonalGoldRoomListResult.cbGameRule), pPersonalTableInfoEx->cbGameRule, sizeof(pPersonalTableInfoEx->cbGameRule));
memcpy_s(PersonalGoldRoomListResult.szNickName, sizeof(PersonalGoldRoomListResult.szNickName), pPersonalTableInfoEx->szNickName, sizeof(pPersonalTableInfoEx->szNickName));
memcpy_s(PersonalGoldRoomListResult.dwJoinUserID, sizeof(PersonalGoldRoomListResult.dwJoinUserID), pPersonalTableInfoEx->dwJoinUserID, sizeof(pPersonalTableInfoEx->dwJoinUserID));
memcpy_s(PersonalGoldRoomListResult.dwFaceID, sizeof(PersonalGoldRoomListResult.dwFaceID), pPersonalTableInfoEx->dwFaceID, sizeof(pPersonalTableInfoEx->dwFaceID));
memcpy_s(PersonalGoldRoomListResult.dwCustomID, sizeof(PersonalGoldRoomListResult.dwCustomID), pPersonalTableInfoEx->dwCustomID, sizeof(pPersonalTableInfoEx->dwCustomID));
memcpy_s(PersonalGoldRoomListResult.szJoinUserNickName, sizeof(PersonalGoldRoomListResult.szJoinUserNickName), pPersonalTableInfoEx->szJoinUserNickName, sizeof(pPersonalTableInfoEx->szJoinUserNickName));
memcpy(&cbDataBuffer[cbPacketSize], &PersonalGoldRoomListResult, sizeof(CMD_SC_C_PersonalGoldRoomListResult));
cbPacketSize += sizeof(CMD_SC_C_PersonalGoldRoomListResult);
}
if (cbPacketSize > 0)
{
wsprintf(szInfo, TEXT("ptdt *** OnTCPNetworkSubPersonalGoldRoomList 房间数量nCount = %d kindid = %d cbPacketSize = %d"), nCount, pPersonalGoldRoomList->dwKindID, cbPacketSize);
//OutputDebugString(szInfo);
//发送数据
if (!m_pITCPNetworkEngine->SendData(dwSocketID, MDM_CS_PERSONAL, CMD_CS_C_GET_GOLD_LIST_RESLUT, pPersonalGoldRoomListResult, cbPacketSize))
{
wsprintf(szInfo, TEXT("ptdt *** OnTCPNetworkSubPersonalGoldRoomList 房间数量nCount = %d kindid = %d cbPacketSize = %d 批量发送失败"), nCount, pPersonalGoldRoomList->dwKindID, cbPacketSize);
//OutputDebugString(szInfo);
}
}
wsprintf(szInfo, TEXT("ptdt *** OnTCPNetworkSubPersonalGoldRoomList 房间数量nCount = %d kindid = %d cbPacketSize = %d 发送列表完成消息"), nCount, pPersonalGoldRoomList->dwKindID, cbPacketSize);
//OutputDebugString(szInfo);
//发送数据
m_pITCPNetworkEngine->SendData(dwSocketID, MDM_CS_PERSONAL, CMD_CS_C_GET_GOLD_LIST_RESLUT_END, NULL, 0);
return true;
}
//发送日志
void CAttemperEngineSink::SendLogData(TCHAR * szLogContent)
{
tagLogUserInfo LogUserInfo;
ZeroMemory(&LogUserInfo, sizeof(LogUserInfo));
wsprintf(LogUserInfo.szLogContent, TEXT("%s"), szLogContent);
wsprintf(LogUserInfo.szServerName, TEXT("%s"), TEXT("聊天服务器"));
LogUserInfo.wKindID = 0;
LogUserInfo.wServerID = 0;
LogUserInfo.cbServerSign = 4;
GetLocalTime(&LogUserInfo.sysTime);
m_pLogServerTCPSocketService->SendData(MDM_S_S_LOG_INFO, SUB_CS_C_SERVER_LOG, &LogUserInfo, sizeof(LogUserInfo));
}
//////////////////////////////////////////////////////////////////////////////////
| [
"494294315@qq.com"
] | 494294315@qq.com |
903f00550e03772dd627646006db7a4f1545b4cf | 7a44170ee385bd67e48fd339a9b53e9dbdf67542 | /src/laserscan_avoidance_node.cpp | 51dcbacec56e51c824a0c000a40789eb909a852f | [
"BSD-3-Clause"
] | permissive | dheera/ros-lidar-avoidance | 56667e7bfc27bc746a275dd0c549f7d12afca816 | e231048555c60e4967eea80ac9f198e2559383c8 | refs/heads/master | 2021-02-11T15:25:01.872627 | 2020-03-04T23:09:55 | 2020-03-04T23:09:55 | 244,504,631 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,091 | cpp | #include <laserscan_avoidance_activity.h>
int main(int argc, char *argv[]) {
ros::NodeHandle *nh = NULL;
ros::NodeHandle *nh_priv = NULL;
LaserScanAvoidanceActivity* activity = NULL;
ros::init(argc, argv, "avoidance_node");
nh = new ros::NodeHandle( );
if(!nh) {
ROS_FATAL("Failed to initialize NodeHanlde");
ros::shutdown( );
return -1;
}
nh_priv = new ros::NodeHandle("~");
if( !nh_priv ) {
ROS_FATAL("Failed to initialize private NodeHanlde");
delete nh;
ros::shutdown( );
return -2;
}
activity = new LaserScanAvoidanceActivity(*nh, *nh_priv);
if(!activity) {
ROS_FATAL("Failed to initialize activity");
delete nh_priv;
delete nh;
ros::shutdown();
return -3;
}
if(!activity->start()) {
ROS_ERROR("failed to start the activity");
}
ros::Rate rate(50);
while(ros::ok()) {
rate.sleep();
ros::spinOnce();
activity->spinOnce();
}
delete activity;
delete nh_priv;
delete nh;
return 0;
}
| [
"dheera@dheera.net"
] | dheera@dheera.net |
73aac63d6fc4f3fe6ed01f4990838b87fbcd8d45 | c58e108e7cf54254dea3f755e7c9a03e2fe64a46 | /src/merkleblock.cpp | cbfae826d760e4ebe126356e8a8e089fea169e15 | [
"MIT"
] | permissive | ORO-mlm/ORO-Core | 9888490355db1ce55b43998086af7dc589d19d10 | 770e4728e1b67023f2f52da2850e058732e7583f | refs/heads/main | 2023-06-17T02:07:47.355318 | 2021-07-13T11:43:51 | 2021-07-13T11:43:51 | 317,410,361 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,952 | cpp | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2015-2020 The PIVX developers
// Copyright (c) 2021- The ORO developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "merkleblock.h"
#include "consensus/consensus.h"
#include "hash.h"
#include "primitives/block.h" // for MAX_BLOCK_SIZE
#include "utilstrencodings.h"
CMerkleBlock::CMerkleBlock(const CBlock& block, CBloomFilter& filter)
{
header = block.GetBlockHeader();
std::vector<bool> vMatch;
std::vector<uint256> vHashes;
vMatch.reserve(block.vtx.size());
vHashes.reserve(block.vtx.size());
for (unsigned int i = 0; i < block.vtx.size(); i++) {
const uint256& hash = block.vtx[i]->GetHash();
if (filter.IsRelevantAndUpdate(*block.vtx[i])) {
vMatch.push_back(true);
vMatchedTxn.emplace_back(i, hash);
} else
vMatch.push_back(false);
vHashes.push_back(hash);
}
txn = CPartialMerkleTree(vHashes, vMatch);
}
uint256 CPartialMerkleTree::CalcHash(int height, unsigned int pos, const std::vector<uint256>& vTxid)
{
if (height == 0) {
// hash at height 0 is the txids themself
return vTxid[pos];
} else {
// calculate left hash
uint256 left = CalcHash(height - 1, pos * 2, vTxid), right;
// calculate right hash if not beyond the end of the array - copy left hash otherwise1
if (pos * 2 + 1 < CalcTreeWidth(height - 1))
right = CalcHash(height - 1, pos * 2 + 1, vTxid);
else
right = left;
// combine subhashes
return Hash(BEGIN(left), END(left), BEGIN(right), END(right));
}
}
void CPartialMerkleTree::TraverseAndBuild(int height, unsigned int pos, const std::vector<uint256>& vTxid, const std::vector<bool>& vMatch)
{
// determine whether this node is the parent of at least one matched txid
bool fParentOfMatch = false;
for (unsigned int p = pos << height; p < (pos + 1) << height && p < nTransactions; p++)
fParentOfMatch |= vMatch[p];
// store as flag bit
vBits.push_back(fParentOfMatch);
if (height == 0 || !fParentOfMatch) {
// if at height 0, or nothing interesting below, store hash and stop
vHash.push_back(CalcHash(height, pos, vTxid));
} else {
// otherwise, don't store any hash, but descend into the subtrees
TraverseAndBuild(height - 1, pos * 2, vTxid, vMatch);
if (pos * 2 + 1 < CalcTreeWidth(height - 1))
TraverseAndBuild(height - 1, pos * 2 + 1, vTxid, vMatch);
}
}
uint256 CPartialMerkleTree::TraverseAndExtract(int height, unsigned int pos, unsigned int& nBitsUsed, unsigned int& nHashUsed, std::vector<uint256>& vMatch)
{
if (nBitsUsed >= vBits.size()) {
// overflowed the bits array - failure
fBad = true;
return UINT256_ZERO;
}
bool fParentOfMatch = vBits[nBitsUsed++];
if (height == 0 || !fParentOfMatch) {
// if at height 0, or nothing interesting below, use stored hash and do not descend
if (nHashUsed >= vHash.size()) {
// overflowed the hash array - failure
fBad = true;
return UINT256_ZERO;
}
const uint256& hash = vHash[nHashUsed++];
if (height == 0 && fParentOfMatch) // in case of height 0, we have a matched txid
vMatch.push_back(hash);
return hash;
} else {
// otherwise, descend into the subtrees to extract matched txids and hashes
uint256 left = TraverseAndExtract(height - 1, pos * 2, nBitsUsed, nHashUsed, vMatch), right;
if (pos * 2 + 1 < CalcTreeWidth(height - 1))
right = TraverseAndExtract(height - 1, pos * 2 + 1, nBitsUsed, nHashUsed, vMatch);
else
right = left;
// and combine them before returning
return Hash(BEGIN(left), END(left), BEGIN(right), END(right));
}
}
CPartialMerkleTree::CPartialMerkleTree(const std::vector<uint256>& vTxid, const std::vector<bool>& vMatch) : nTransactions(vTxid.size()), fBad(false)
{
// reset state
vBits.clear();
vHash.clear();
// calculate height of tree
int nHeight = 0;
while (CalcTreeWidth(nHeight) > 1)
nHeight++;
// traverse the partial tree
TraverseAndBuild(nHeight, 0, vTxid, vMatch);
}
CPartialMerkleTree::CPartialMerkleTree() : nTransactions(0), fBad(true) {}
uint256 CPartialMerkleTree::ExtractMatches(std::vector<uint256>& vMatch)
{
vMatch.clear();
// An empty set will not work
if (nTransactions == 0)
return UINT256_ZERO;
// check for excessively high numbers of transactions
if (nTransactions > MAX_BLOCK_SIZE_CURRENT / 60) // 60 is the lower bound for the size of a serialized CTransaction
return UINT256_ZERO;
// there can never be more hashes provided than one for every txid
if (vHash.size() > nTransactions)
return UINT256_ZERO;
// there must be at least one bit per node in the partial tree, and at least one node per hash
if (vBits.size() < vHash.size())
return UINT256_ZERO;
// calculate height of tree
int nHeight = 0;
while (CalcTreeWidth(nHeight) > 1)
nHeight++;
// traverse the partial tree
unsigned int nBitsUsed = 0, nHashUsed = 0;
uint256 hashMerkleRoot = TraverseAndExtract(nHeight, 0, nBitsUsed, nHashUsed, vMatch);
// verify that no problems occured during the tree traversal
if (fBad)
return UINT256_ZERO;
// verify that all bits were consumed (except for the padding caused by serializing it as a byte sequence)
if ((nBitsUsed + 7) / 8 != (vBits.size() + 7) / 8)
return UINT256_ZERO;
// verify that all hashes were consumed
if (nHashUsed != vHash.size())
return UINT256_ZERO;
return hashMerkleRoot;
}
| [
"brandon2davincci@gmail.com"
] | brandon2davincci@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.