text
stringlengths 5
1.04M
|
|---|
/*
g++ unique_ptr_scalar.cpp -std=c++11 -lpthread
g++ -v
Using built-in specs.
COLLECT_GCC=g++
COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/5/lto-wrapper
Target: x86_64-linux-gnu
Configured with: ../src/configure -v --with-pkgversion='Ubuntu 5.4.0-6ubuntu1~16.04.10' --with-bugurl=file:///usr/share/doc/gcc-5/README.Bugs --enable-languages=c,ada,c++,java,go,d,fortran,objc,obj-c++ --prefix=/usr --program-suffix=-5 --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --libdir=/usr/lib --enable-nls --with-sysroot=/ --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --with-default-libstdcxx-abi=new --enable-gnu-unique-object --disable-vtable-verify --enable-libmpx --enable-plugin --with-system-zlib --disable-browser-plugin --enable-java-awt=gtk --enable-gtk-cairo --with-java-home=/usr/lib/jvm/java-1.5.0-gcj-5-amd64/jre --enable-java-home --with-jvm-root-dir=/usr/lib/jvm/java-1.5.0-gcj-5-amd64 --with-jvm-jar-dir=/usr/lib/jvm-exports/java-1.5.0-gcj-5-amd64 --with-arch-directory=amd64 --with-ecj-jar=/usr/share/java/eclipse-ecj.jar --enable-objc-gc --enable-multiarch --disable-werror --with-arch-32=i686 --with-abi=m64 --with-multilib-list=m32,m64,mx32 --enable-multilib --with-tune=generic --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu
Thread model: posix
gcc version 5.4.0 20160609 (Ubuntu 5.4.0-6ubuntu1~16.04.10)
*/
#include <iostream>
#include <memory>
#include <thread>
// Overloading new and delete to check std::unique_ptr alloc/ dealloc sequences
void* operator new(size_t t)
{
void * p = malloc(t);
std::cout << "Allocating scalar " << t << ' ' << p << std::endl;
return p;
}
void operator delete(void * p)
{
std::cout << "Deallocating scalar " << p << std::endl;
free(p);
}
void UniquePtr_CheckScopeMovement(std::unique_ptr<int> pScalar)
{
std::cout << "Entering " << __FUNCTION__ << std::endl;
std::cout << *pScalar << std::endl;
std::cout << "Exit " << __FUNCTION__ << std::endl;
std::cout << std::endl;
}
void UniquePtr_LocalScopeCheck(void) // All the unique_ptr will be released at exit of this function
{
std::unique_ptr<int> pIScalar(new int(100));
std::cout << *pIScalar << std::endl; // Output: 100
std::cout << std::endl;
}
void UniquePtr_CheckOwnershipMove(void)
{
std::cout << "Entering " << __FUNCTION__ << std::endl;
std::unique_ptr<int> pA(new int(80));
std::unique_ptr<int> pB = std::move(pA);
std::cout << pA.get() << std::endl; // pA will have null
std::cout << pB.get() << std::endl; // 80 should be printed
std::cout << "Exit " << __FUNCTION__ << std::endl;
std::cout << std::endl;
}
void UniquePtr_CheckOwnershipRelease(void)
{
std::cout << "Entering " << __FUNCTION__ << std::endl;
std::unique_ptr<int> pA(new int(30));
std::cout << "unique_ptr object address before release: " << pA.get() << std::endl; // pA will have null
int * pI = pA.release();
// note below that get() is used, if dereferenced it will crash the program
std::cout << "unique_ptr object address after release: " << pA.get() << std::endl; // pA will have null
std::cout << "Value of pI: " << pI << std::endl; // should print the address given by std::unique_ptr
std::cout << "Value @ *pI: " << *pI << std::endl; // 30 should be printed
std::cout << "Exit " << __FUNCTION__ << std::endl;
std::cout << std::endl;
}
void UniquePtr_CheckReset(void)
{
std::cout << "Entering " << __FUNCTION__ << std::endl;
std::unique_ptr<int> pA(new int(30));
std::cout << "unique_ptr object address before release: " << pA.get() << std::endl; // pA will have null
pA.reset();
// note below that get() is used, if dereferenced it will crash the program
std::cout << "unique_ptr object address after release: " << pA.get() << std::endl; // pA will have null
std::cout << "Exit " << __FUNCTION__ << std::endl;
std::cout << std::endl;
}
struct test
{
void print(void)
{
std::cout << "test struct print\n";
}
};
void UniquePtr_ReturningUniquePtr(void)
{
}
int main()
{
{ // Passing to function as argument
std::unique_ptr<int> pIScalar(new int(500));
UniquePtr_CheckScopeMovement(std::move(pIScalar)); // pIScalar will be released after UniquePtr_CheckScalarScopeMovement execution
}
{ // Passing to thread as argument
std::unique_ptr<int> pIScalar(new int(600));
std::thread th(UniquePtr_CheckScopeMovement, std::move(pIScalar));
th.join();
}
{ // Check std::unqie_ptr behaviour when scope is out
UniquePtr_LocalScopeCheck();
}
{ // try to pass ownership to another variable within a scope and see the result
UniquePtr_CheckOwnershipMove();
}
{ // Check release() functionality
UniquePtr_CheckOwnershipRelease();
}
{ // check reset() functionality
UniquePtr_CheckReset();
}
}
/*
Output:
Allocating scalar 4 0x1a43c20
Entering UniquePtr_CheckScalarScopeMovement
500
Exit UniquePtr_CheckScalarScopeMovement
Deallocating scalar 0x1a43c20
Allocating scalar 4 0x1a43c20
Allocating scalar 56 0x1a44050
Entering UniquePtr_CheckScalarScopeMovement
600
Exit UniquePtr_CheckScalarScopeMovement
Deallocating scalar 0x1a43c20
Deallocating scalar 0x1a44050
Allocating scalar 4 0x1a43c20
100
Deallocating scalar 0x1a43c20
Entering UniquePtr_CheckOwnershipMove
Allocating scalar 4 0x1a43c20
0
0x1a43c20
Exit UniquePtr_CheckOwnershipMove
Deallocating scalar 0x1a43c20
Entering UniquePtr_CheckOwnershipRelease
Allocating scalar 4 0x1a43c20
unique_ptr object address before release: 0x1a43c20
unique_ptr object address after release: 0
Value of pI: 0x1a43c20
Value @ *pI: 30
Exit UniquePtr_CheckOwnershipRelease
Entering UniquePtr_CheckReset
Allocating scalar 4 0x1a441c0
unique_ptr object address before release: 0x1a441c0
Deallocating scalar 0x1a441c0
unique_ptr object address after release: 0
Exit UniquePtr_CheckReset
*/
/*
Notes:
*) two kinds of unique_ptr available
*) scalar
eg., std::unique_ptr<int>
*) array
eg., std::unique_ptr<int[]>
*) Creating std:unique_ptr
*) C++14 and above
auto p = std::make_unique<type>(constructor to invoke for that type)
auto p = std::make_unique<type[]>(n)(constructor to invoke for that type)
*) C++11
std::unique_ptr<type> variable(new type(constructor to invoke for that type));
*) < C++11
not supported
*) no copy or assignment constructor
*) only move constructor for moving the ownership
*) memory is owned by std::unique_ptr only
*) Delete
*) on scope exit of std::unique_ptr<> memory will be free'd
*) alternatively p.reset() will release the memory
*/
|
/* file: low_order_moments_csr_sum_online_fpt_cpu.cpp */
/*******************************************************************************
* Copyright 2014-2019 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
/*
//++
// Implementation of low order moments kernel.
//--
*/
#include "low_order_moments_container.h"
#include "low_order_moments_online_impl.i"
namespace daal
{
namespace algorithms
{
namespace low_order_moments
{
namespace interface1
{
template class OnlineContainer<DAAL_FPTYPE, sumCSR, DAAL_CPU>;
}
namespace internal
{
template class LowOrderMomentsOnlineKernel<DAAL_FPTYPE, sumCSR, DAAL_CPU>;
}
} // namespace low_order_moments
} // namespace algorithms
} // namespace daal
|
#include "CTMStack.h"
CTMStack::CTMStack(int intialProgram) {
program = intialProgram;
head = nullptr;
size = 0;
}
void CTMStack::pushMatrix(mat4 matrix) {
CTMNode* newNode = new CTMNode;
newNode->matrix = (head != nullptr ? head->matrix : Angel::identity()) * matrix;
newNode->prev = head;
head = newNode;
size++;
}
//Returns the itentity matrix if the stack is empty
mat4 CTMStack::popMatrix() {
mat4 result = Angel::identity();
if (size != 0) {
result = head->matrix;
//Remove from stack
CTMNode* newPrev = head->prev;
delete head;
head = newPrev;
size--;
}
setUpCTM(result);
return result;
}
mat4 CTMStack::peekMatrix() {
mat4 result = Angel::identity();
if (size != 0) {
result = head->matrix;
}
setUpCTM(result);
return result;
}
void CTMStack::setUpCTM(mat4 ctm) {
//Set up ctm
float CTMf[16];
CTMf[0] = ctm[0][0]; CTMf[4] = ctm[0][1];
CTMf[1] = ctm[1][0]; CTMf[5] = ctm[1][1];
CTMf[2] = ctm[2][0]; CTMf[6] = ctm[2][1];
CTMf[3] = ctm[3][0]; CTMf[7] = ctm[3][1];
CTMf[8] = ctm[0][2]; CTMf[12] = ctm[0][3];
CTMf[9] = ctm[1][2]; CTMf[13] = ctm[1][3];
CTMf[10] = ctm[2][2]; CTMf[14] = ctm[2][3];
CTMf[11] = ctm[3][2]; CTMf[15] = ctm[3][3];
GLuint ctmLocation = glGetUniformLocationARB(program, "modelMatrix");
glUniformMatrix4fv(ctmLocation, 1, GL_FALSE, CTMf);
}
void CTMStack::clear() {
while (head != nullptr) {
CTMNode* temp = head->prev;
delete head;
head = temp;
}
size = 0;
}
void CTMStack::printContents() {
CTMNode* curr = head;
printf("======= SIZE %d ======\n", size);
while (curr != nullptr) {
mat4 mat = curr->matrix;
printf("| %04f %04f %04f %04f |\n", mat[0][0], mat[0][1], mat[0][2], mat[0][3]);
printf("| %04f %04f %04f %04f |\n", mat[1][0], mat[1][1], mat[1][2], mat[1][3]);
printf("| %04f %04f %04f %04f |\n", mat[2][0], mat[2][1], mat[2][2], mat[2][3]);
printf("| %04f %04f %04f %04f |\n", mat[3][0], mat[3][1], mat[3][2], mat[3][3]);
printf("\n");
curr = curr->prev;
}
printf("=======================\n");
}
int CTMStack::getSize() {
return size;
}
|
/*
* Copyright 2016 - 2020 Angelo Matni, Yian Su, Simone Campanoni
*
* 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 "SystemHeaders.hpp"
#include "Util/SVFModule.h"
#include "WPA/Andersen.h"
#include "TalkDown.hpp"
#include "PDGPrinter.hpp"
#include "PDGAnalysis.hpp"
using namespace llvm;
using namespace llvm::noelle;
PDGAnalysis::PDGAnalysis()
: ModulePass{ID}
, M{nullptr}
, programDependenceGraph{nullptr}
, CGUnderMain{}
, dfa{}
, embedPDG{false}
, dumpPDG{false}
, performThePDGComparison{false}
, disableSVF{false}
, disableAllocAA{false}
, disableRA{false}
, printer{}
{
return ;
}
void PDGAnalysis::initializeSVF(Module &M) {
SVFModule svfModule{M};
this->pta = new AndersenWaveDiff();
this->pta->analyze(svfModule);
this->callGraph = this->pta->getPTACallGraph();
this->mssa = new MemSSA((BVDataPTAImpl *)this->pta, false);
return;
}
void PDGAnalysis::releaseMemory () {
if (this->programDependenceGraph) delete this->programDependenceGraph;
this->programDependenceGraph = nullptr;
for (auto functionFDGPair : this->functionToFDGMap) {
auto fdg = functionFDGPair.second;
delete fdg;
}
this->functionToFDGMap.clear();
return ;
}
void PDGAnalysis::printFunctionReachabilityResult() {
/*
* Print internal and unhandled external functions.
*/
errs() << "Internal Functions:\n";
for (auto &internal : this->internalFuncs) {
errs() << "\t" << internal->getName() << "\n";
}
errs() << "Unhandled External Functions:\n";
for (auto &external : this->unhandledExternalFuncs) {
errs() << "\t" << external->getName() << "\n";
}
/*
* Print reachability results.
*/
for (auto &pair : this->reachableUnhandledExternalFuncs) {
errs() << "Reachable external functions of " << pair.first->getName() << "\n";
for (auto &external : pair.second) {
errs() << "\t" << external->getName() << "\n";
}
}
return;
}
PDG * PDGAnalysis::getFunctionPDG (Function &F) {
/*
* If the module PDG has been built, take the subset related to the input function
* Else, construct the function DG from scratch (or from metadata)
*/
PDG *pdg = nullptr;
if (this->programDependenceGraph){
/*
* Check and get/update the function cache
*/
if (this->functionToFDGMap.find(&F) == this->functionToFDGMap.end()) {
pdg = this->programDependenceGraph->createFunctionSubgraph(F);
for (auto edge : pdg->getEdges()) {
assert(!edge->isLoopCarriedDependence() && "Flag was already set");
}
this->functionToFDGMap.insert(std::make_pair(&F, pdg));
} else {
pdg = this->functionToFDGMap.at(&F);
for (auto edge : pdg->getEdges()) {
assert(!edge->isLoopCarriedDependence() && "Flag was already set");
}
}
} else {
/*
* Check and get/update the function cache
*/
if (this->functionToFDGMap.find(&F) == this->functionToFDGMap.end()) {
/*
* Determine whether metadata can be used to construct the graph
*/
if (this->hasPDGAsMetadata(*this->M)) {
pdg = constructFunctionDGFromMetadata(F);
for (auto edge : pdg->getEdges()) {
assert(!edge->isLoopCarriedDependence() && "Flag was already set");
}
} else {
pdg = constructFunctionDGFromAnalysis(F);
for (auto edge : pdg->getEdges()) {
assert(!edge->isLoopCarriedDependence() && "Flag was already set");
}
}
this->functionToFDGMap.insert(std::make_pair(&F, pdg));
} else {
pdg = this->functionToFDGMap.at(&F);
for (auto edge : pdg->getEdges()) {
assert(!edge->isLoopCarriedDependence() && "Flag was already set");
}
}
}
/*
* Print the PDG
*/
if (this->dumpPDG){
this->printer.printGraphsForFunction(F, pdg, getAnalysis<LoopInfoWrapperPass>(F).getLoopInfo());
}
return pdg;
}
PDG * PDGAnalysis::getPDG (void){
/*
* Check if we have already built the PDG.
*/
if (this->programDependenceGraph){
return this->programDependenceGraph;
}
/*
* Construct the PDG
*
* Check if we have already done it and the PDG has been embedded in the IR.
*/
if (this->hasPDGAsMetadata(*this->M)) {
/*
* The PDG has been embedded in the IR.
*
* Load the embedded PDG.
*/
this->programDependenceGraph = constructPDGFromMetadata(*this->M);
if (this->performThePDGComparison){
auto PDGFromAnalysis = constructPDGFromAnalysis(*this->M);
auto arePDGsEquivalent = this->comparePDGs(PDGFromAnalysis, this->programDependenceGraph);
if (!arePDGsEquivalent){
errs() << "PDGAnalysis: Error = PDGs constructed are not the same";
abort();
}
delete PDGFromAnalysis ;
}
} else {
/*
* There is no PDG in the IR.
*
* Compute the PDG using the dependence analyses.
*/
this->programDependenceGraph = constructPDGFromAnalysis(*this->M);
/*
* Check if we should embed the PDG.
*/
if (this->embedPDG){
embedPDGAsMetadata(this->programDependenceGraph);
if (this->performThePDGComparison){
auto PDGFromMetadata = this->constructPDGFromMetadata(*this->M);
auto arePDGsEquivalen = this->comparePDGs(this->programDependenceGraph, PDGFromMetadata);
if (!arePDGsEquivalen){
errs() << "PDGAnalysis: Error = PDGs constructed are not the same";
abort();
}
delete PDGFromMetadata;
}
}
}
return this->programDependenceGraph;
}
bool PDGAnalysis::hasPDGAsMetadata(Module &M) {
if (auto n = M.getNamedMetadata("noelle.module.pdg")) {
if (auto m = dyn_cast<MDNode>(n->getOperand(0))) {
if (cast<MDString>(m->getOperand(0))->getString() == "true") {
return true;
}
}
}
return false;
}
PDG * PDGAnalysis::constructPDGFromAnalysis(Module &M) {
if (verbose >= PDGVerbosity::Maximal) {
errs() << "PDGAnalysis: Construct PDG from Analysis\n";
}
auto pdg = new PDG(M);
constructEdgesFromUseDefs(pdg);
constructEdgesFromAliases(pdg, M);
constructEdgesFromControl(pdg, M);
trimDGUsingCustomAliasAnalysis(pdg);
return pdg;
}
PDG * PDGAnalysis::constructFunctionDGFromAnalysis(Function &F) {
if (verbose >= PDGVerbosity::Maximal) {
errs() << "PDGAnalysis: Construct function DG from Analysis\n";
}
auto pdg = new PDG(F);
constructEdgesFromUseDefs(pdg);
constructEdgesFromAliasesForFunction(pdg, F);
constructEdgesFromControlForFunction(pdg, F);
return pdg;
}
PDG * PDGAnalysis::constructPDGFromMetadata(Module &M) {
if (verbose >= PDGVerbosity::Maximal) {
errs() << "PDGAnalysis: Construct PDG from Metadata\n";
}
/*
* Create the PDG.
*/
auto pdg = new PDG(M);
/*
* Fill up the PDG.
*/
std::unordered_map<MDNode *, Value *> IDNodeMap;
for (auto &F : M) {
constructNodesFromMetadata(pdg, F, IDNodeMap);
constructEdgesFromMetadata(pdg, F, IDNodeMap);
}
return pdg;
}
PDG * PDGAnalysis::constructFunctionDGFromMetadata(Function &F) {
if (verbose >= PDGVerbosity::Maximal) {
errs() << "PDGAnalysis: Construct function DG from Metadata\n";
}
auto pdg = new PDG(F);
std::unordered_map<MDNode *, Value *> IDNodeMap;
constructNodesFromMetadata(pdg, F, IDNodeMap);
constructEdgesFromMetadata(pdg, F, IDNodeMap);
return pdg;
}
void PDGAnalysis::constructNodesFromMetadata(PDG *pdg, Function &F, unordered_map<MDNode *, Value *> &IDNodeMap) {
/*
* Construct id to node map and add nodes of arguments to pdg
*/
if (MDNode *argsM = F.getMetadata("noelle.pdg.args.id")) {
for (auto &arg : F.args()) {
if (MDNode *m = dyn_cast<MDNode>(argsM->getOperand(arg.getArgNo()))) {
IDNodeMap[m] = &arg;
}
}
}
/*
* Construct id to node map and add nodes of instructions to pdg
*/
for (auto &B : F) {
for (auto &I : B) {
if (MDNode *m = I.getMetadata("noelle.pdg.inst.id")) {
IDNodeMap[m] = &I;
}
}
}
return;
}
void PDGAnalysis::constructEdgesFromMetadata(PDG *pdg, Function &F, unordered_map<MDNode *, Value *> &IDNodeMap) {
/*
* Construct edges and set attributes
*/
if (MDNode *edgesM = F.getMetadata("noelle.pdg.edges")) {
for (auto &operand : edgesM->operands()) {
if (MDNode *edgeM = dyn_cast<MDNode>(operand)) {
auto edge = constructEdgeFromMetadata(pdg, edgeM, IDNodeMap);
/*
* Construct subEdges and set attributes
*/
if (MDNode *subEdgesM = dyn_cast<MDNode>(edgeM->getOperand(8))) {
for (auto &subOperand : subEdgesM->operands()) {
if (MDNode *subEdgeM = dyn_cast<MDNode>(subOperand)) {
DGEdge<Value> *subEdge = constructEdgeFromMetadata(pdg, subEdgeM, IDNodeMap);
edge->addSubEdge(subEdge);
}
}
}
/*
* Add edge to pdg
*/
pdg->copyAddEdge(*edge);
/*
* Free the memory.
*/
delete edge;
}
}
}
return;
}
DGEdge<Value> * PDGAnalysis::constructEdgeFromMetadata(PDG *pdg, MDNode *edgeM, unordered_map<MDNode *, Value *> &IDNodeMap) {
DGEdge<Value> *edge = nullptr;
if (MDNode *fromM = dyn_cast<MDNode>(edgeM->getOperand(0))) {
if (MDNode *toM = dyn_cast<MDNode>(edgeM->getOperand(1))) {
Value *from = IDNodeMap[fromM];
Value *to = IDNodeMap[toM];
edge = new DGEdge<Value>(pdg->fetchNode(from), pdg->fetchNode(to));
edge->setEdgeAttributes(
cast<MDString>(cast<MDNode>(edgeM->getOperand(2))->getOperand(0))->getString() == "true",
cast<MDString>(cast<MDNode>(edgeM->getOperand(3))->getOperand(0))->getString() == "true",
cast<MDString>(cast<MDNode>(edgeM->getOperand(4))->getOperand(0))->getString().str(),
cast<MDString>(cast<MDNode>(edgeM->getOperand(5))->getOperand(0))->getString() == "true",
cast<MDString>(cast<MDNode>(edgeM->getOperand(6))->getOperand(0))->getString() == "true",
cast<MDString>(cast<MDNode>(edgeM->getOperand(7))->getOperand(0))->getString() == "true"
);
}
}
return edge;
}
MDNode * PDGAnalysis::getEdgeMetadata(DGEdge<Value> *edge, LLVMContext &C, unordered_map<Value *, MDNode *> &nodeIDMap) {
Metadata *edgeM[] = {
nodeIDMap[edge->getOutgoingT()],
nodeIDMap[edge->getIncomingT()],
MDNode::get(C, MDString::get(C, edge->isMemoryDependence() ? "true" : "false")),
MDNode::get(C, MDString::get(C, edge->isMustDependence() ? "true" : "false")),
MDNode::get(C, MDString::get(C, edge->dataDepToString())),
MDNode::get(C, MDString::get(C, edge->isControlDependence() ? "true" : "false")),
MDNode::get(C, MDString::get(C, edge->isLoopCarriedDependence() ? "true" : "false")),
MDNode::get(C, MDString::get(C, edge->isRemovableDependence() ? "true" : "false")),
getSubEdgesMetadata(edge, C, nodeIDMap)
};
return MDNode::get(C, edgeM);
}
MDNode * PDGAnalysis::getSubEdgesMetadata(DGEdge<Value> *edge, LLVMContext &C, unordered_map<Value *, MDNode *> &nodeIDMap) {
vector<Metadata *> subEdgesVec;
for (auto &subEdge : edge->getSubEdges()) {
Metadata *subEdgeM[] = {
nodeIDMap[subEdge->getOutgoingT()],
nodeIDMap[subEdge->getIncomingT()],
MDNode::get(C, MDString::get(C, edge->isMemoryDependence() ? "true" : "false")),
MDNode::get(C, MDString::get(C, edge->isMustDependence() ? "true" : "false")),
MDNode::get(C, MDString::get(C, edge->dataDepToString())),
MDNode::get(C, MDString::get(C, edge->isControlDependence() ? "true" : "false")),
MDNode::get(C, MDString::get(C, edge->isLoopCarriedDependence() ? "true" : "false")),
MDNode::get(C, MDString::get(C, edge->isRemovableDependence() ? "true" : "false")),
};
subEdgesVec.push_back(MDNode::get(C, subEdgeM));
}
return MDTuple::get(C, subEdgesVec);
}
void PDGAnalysis::trimDGUsingCustomAliasAnalysis (PDG *pdg) {
/*
* Fetch AllocAA
*/
collectCGUnderFunctionMain(*this->M);
this->allocAA = &getAnalysis<AllocAA>();
if (this->disableAllocAA){
return ;
}
/*
* Invoke AllocAA
*/
removeEdgesNotUsedByParSchemes(pdg);
/*
* Invoke the TalkDown
*/
auto& talkDown = getAnalysis<TalkDown>();
//TODO
return ;
}
void PDGAnalysis::collectCGUnderFunctionMain (Module &M) {
auto main = M.getFunction("main");
auto &callGraph = getAnalysis<CallGraphWrapperPass>().getCallGraph();
std::queue<Function *> funcToTraverse;
std::set<Function *> reached;
funcToTraverse.push(main);
reached.insert(main);
while (!funcToTraverse.empty()) {
auto func = funcToTraverse.front();
funcToTraverse.pop();
auto funcCGNode = callGraph[func];
for (auto &callRecord : make_range(funcCGNode->begin(), funcCGNode->end())) {
auto F = callRecord.second->getFunction();
if (!F || F->empty()) continue;
if (reached.find(F) != reached.end()) continue;
reached.insert(F);
funcToTraverse.push(F);
}
}
CGUnderMain.clear();
CGUnderMain.insert(reached.begin(), reached.end());
return ;
}
void PDGAnalysis::constructEdgesFromUseDefs (PDG *pdg){
/*
* Add the dependences due to variables.
*/
for (auto node : make_range(pdg->begin_nodes(), pdg->end_nodes())) {
/*
* Check the current definition has uses.
* If it doesn't, then there is no variable dependence.
*/
auto pdgValue = node->getT();
if (pdgValue->getNumUses() == 0){
continue;
}
/*
* The current definition has uses.
* Add the uses.
*/
for (auto& U : pdgValue->uses()) {
auto user = U.getUser();
if (isa<Instruction>(user) || isa<Argument>(user)) {
auto edge = pdg->addEdge(pdgValue, user);
edge->setMemMustType(false, true, DG_DATA_RAW);
}
}
}
return ;
}
void PDGAnalysis::constructEdgesFromAliases (PDG *pdg, Module &M){
/*
* Use alias analysis on stores, loads, and function calls to construct PDG edges
*/
for (auto &F : M) {
/*
* Check if the function has a body.
*/
if (F.empty()) continue ;
/*
* Add the edges to the PDG.
*/
constructEdgesFromAliasesForFunction(pdg, F);
}
}
void PDGAnalysis::constructEdgesFromAliasesForFunction (PDG *pdg, Function &F){
/*
* Fetch the alias analysis.
*/
auto &AA = getAnalysis<AAResultsWrapperPass>(F).getAAResults();
/*
* Run the reachable analysis.
*/
auto onlyMemoryInstructionFilter = [](Instruction *i) -> bool {
if (isa<LoadInst>(i)){
return true;
}
if (isa<StoreInst>(i)){
return true;
}
if (isa<CallInst>(i)){
return true;
}
if (isa<InvokeInst>(i)){
return true;
}
return false;
};
auto dfr = this->disableRA ? this->dfa.getFullSets(&F) : this->dfa.runReachableAnalysis(&F, onlyMemoryInstructionFilter);
for (auto &B : F) {
for (auto &I : B) {
if (auto store = dyn_cast<StoreInst>(&I)) {
iterateInstForStore(pdg, F, AA, dfr, store);
} else if (auto load = dyn_cast<LoadInst>(&I)) {
iterateInstForLoad(pdg, F, AA, dfr, load);
} else if (auto call = dyn_cast<CallInst>(&I)) {
iterateInstForCall(pdg, F, AA, dfr, call);
}
}
}
/*
* Free the memory.
*/
delete dfr;
}
void PDGAnalysis::iterateInstForCall (PDG *pdg, Function &F, AAResults &AA, DataFlowResult *dfr, CallInst *call) {
for (auto I : dfr->OUT(call)) {
/*
* Check stores.
*/
if (auto store = dyn_cast<StoreInst>(I)) {
addEdgeFromFunctionModRef(pdg, F, AA, call, store, true);
continue ;
}
/*
* Check loads.
*/
if (auto load = dyn_cast<LoadInst>(I)) {
addEdgeFromFunctionModRef(pdg, F, AA, call, load, true);
continue ;
}
/*
* Check calls.
*/
if (auto otherCall = dyn_cast<CallInst>(I)) {
addEdgeFromFunctionModRef(pdg, F, AA, call, otherCall);
continue ;
}
}
return ;
}
void PDGAnalysis::removeEdgesNotUsedByParSchemes (PDG *pdg) {
std::set<DGEdge<Value> *> removeEdges;
/*
* Collect the edges in the PDG that can be safely removed.
*/
for (auto edge : pdg->getEdges()) {
/*
* Fetch the source of the dependence.
*/
auto source = edge->getOutgoingT();
if (!isa<Instruction>(source)) continue;
/*
* Check if the function of the dependence destiation cannot be reached from main.
*/
auto F = cast<Instruction>(source)->getFunction();
if (CGUnderMain.find(F) == CGUnderMain.end()) continue;
if ( false
|| edgeIsNotLoopCarriedMemoryDependency(edge)
|| edgeIsAlongNonMemoryWritingFunctions(edge)
) {
removeEdges.insert(edge);
}
}
/*
* Remove the tagged edges.
*/
for (auto edge : removeEdges) {
pdg->removeEdge(edge);
}
return ;
}
// NOTE: Loads between random parts of separate GVs and both edges between GVs should be removed
bool PDGAnalysis::edgeIsNotLoopCarriedMemoryDependency (DGEdge<Value> *edge) {
/*
* Check if this is a memory dependence.
*/
if (!edge->isMemoryDependence()) {
return false;
}
/*
* Fetch the source and destination of the dependence.
*/
auto outgoingT = edge->getOutgoingT();
auto incomingT = edge->getIncomingT();
/*
* Handle only memory instructions.
*/
if (isa<CallInst>(outgoingT) || isa<CallInst>(incomingT)) {
return false;
}
/*
* Assert: must be a WAR load-store OR a RAW store-load
*/
LoadInst *load = nullptr;
StoreInst *store = nullptr;
if (edge->isWARDependence()) {
assert(isa<StoreInst>(incomingT) && isa<LoadInst>(outgoingT));
load = (LoadInst*)outgoingT;
store = (StoreInst*)incomingT;
} else if (edge->isRAWDependence()) {
assert(isa<LoadInst>(incomingT) && isa<StoreInst>(outgoingT));
store = (StoreInst*)outgoingT;
load = (LoadInst*)incomingT;
}
bool loopCarried = true;
if (isMemoryAccessIntoDifferentArrays(edge) ||
// (store && load && isBackedgeOfLoadStoreIntoSameOffsetOfArray(edge, load, store)) ||
isBackedgeIntoSameGlobal(edge)) {
loopCarried = false;
}
if (!loopCarried) {
// NOTE: We are actually removing must dependencies, but only those that are
// backedges where by the next iteration, the access is at a different memory location
// assert(!edge->isMustDependence()
// && "LLVM AA states load store pair is a must dependence! Bad PDGAnalysis.");
if (verbose >= PDGVerbosity::Maximal) {
errs() << "PDGAnalysis: Memory dependence removed! From - to:\n";
outgoingT->print(errs() << "PDGAnalysis: Outgoing: "); errs() << "\n";
incomingT->print(errs() << "PDGAnalysis: Incoming: "); errs() << "\n";
}
}
return !loopCarried;
}
bool PDGAnalysis::isBackedgeOfLoadStoreIntoSameOffsetOfArray (
DGEdge<Value> *edge,
LoadInst *load,
StoreInst *store
) {
auto access1 = allocAA->getPrimitiveArrayAccess(load);
auto access2 = allocAA->getPrimitiveArrayAccess(store);
auto gep1 = access1.second;
auto gep2 = access2.second;
if (!gep1 || !gep2) return false;
if (!allocAA->areIdenticalGEPAccessesInSameLoop(gep1, gep2)) return false;;
if (!allocAA->areGEPIndicesConstantOrIV(gep1)) return false;
auto outgoingI = (Instruction*)(edge->getOutgoingT());
auto incomingI = (Instruction*)(edge->getIncomingT());
if (canPrecedeInCurrentIteration(outgoingI, incomingI)) {
return false;
}
return true;
}
bool PDGAnalysis::isBackedgeIntoSameGlobal (
DGEdge<Value> *edge
) {
auto access1 = allocAA->getPrimitiveArrayAccess(edge->getOutgoingT());
auto access2 = allocAA->getPrimitiveArrayAccess(edge->getIncomingT());
/*
* Ensure the same global variable is accessed by the edge values
*/
auto array1 = access1.first;
auto array2 = access2.first;
if (!array1 || !isa<GlobalValue>(array1)) return false;
if (array1 != array2) return false;
/*
* Ensure either of the following:
* 1) two load accesses using the same IV governed GEP
* 2) a store into the GEP and a load of the entire GV
*/
auto GEP1 = access1.second;
auto GEP2 = access2.second;
if (GEP1 && !allocAA->areGEPIndicesConstantOrIV(GEP1)) return false;
if (GEP2 && !allocAA->areGEPIndicesConstantOrIV(GEP2)) return false;
if (GEP1 && GEP2) {
if (!allocAA->areIdenticalGEPAccessesInSameLoop(GEP1, GEP2)) return false;
if (!isa<LoadInst>(edge->getOutgoingT()) ||
!isa<LoadInst>(edge->getIncomingT())) return false;
} else if (GEP1) {
if (!isa<StoreInst>(edge->getOutgoingT()) ||
!isa<LoadInst>(edge->getIncomingT())) return false;
} else if (GEP2) {
if (!isa<LoadInst>(edge->getOutgoingT()) ||
!isa<StoreInst>(edge->getIncomingT())) return false;
} else return false;
/*
* Ensure that the edge is a backedge
*/
auto outgoingI = (Instruction*)(edge->getOutgoingT());
auto incomingI = (Instruction*)(edge->getIncomingT());
if (canPrecedeInCurrentIteration(outgoingI, incomingI)) {
return false;
}
return true;
}
bool PDGAnalysis::isMemoryAccessIntoDifferentArrays (DGEdge<Value> *edge) {
Value *array1 = allocAA->getPrimitiveArrayAccess(edge->getOutgoingT()).first;
Value *array2 = allocAA->getPrimitiveArrayAccess(edge->getIncomingT()).first;
return (array1 && array2 && array1 != array2);
}
bool PDGAnalysis::canPrecedeInCurrentIteration (Instruction *from, Instruction *to) {
auto &LI = getAnalysis<LoopInfoWrapperPass>(*from->getFunction()).getLoopInfo();
BasicBlock *fromBB = from->getParent();
BasicBlock *toBB = to->getParent();
auto loop = LI.getLoopFor(fromBB);
BasicBlock *headerBB = nullptr;
if (loop) headerBB = loop->getHeader();
if (fromBB == toBB) {
for (auto &I : *fromBB) {
if (&I == from) return true;
if (&I == to) return false;
}
}
std::queue<BasicBlock *> bbToTraverse;
std::set<BasicBlock *> bbReached;
auto traverseOn = [&](BasicBlock *bb) -> void {
bbToTraverse.push(bb); bbReached.insert(bb);
};
traverseOn(toBB);
while (!bbToTraverse.empty()) {
auto bb = bbToTraverse.front();
bbToTraverse.pop();
if (bb == fromBB) return true;
if (bb == headerBB) continue;
for (auto predBB : make_range(pred_begin(bb), pred_end(bb))) {
if (bbReached.find(predBB) == bbReached.end()) {
traverseOn(predBB);
}
}
}
return false;
}
bool PDGAnalysis::edgeIsAlongNonMemoryWritingFunctions (DGEdge<Value> *edge) {
/*
* Check if this is a memory dependence.
*/
if (!edge->isMemoryDependence()) {
return false;
}
/*
* Fetch the source and destination of the dependence.
*/
auto outgoingT = edge->getOutgoingT();
auto incomingT = edge->getIncomingT();
/*
* Auxiliary code.
*/
auto isFunctionMemoryless = [&](StringRef funcName) -> bool {
auto isMemoryless = allocAA->isMemoryless(funcName);
return isMemoryless;
};
auto isFunctionNonWriting = [&](StringRef funcName) -> bool {
if (isFunctionMemoryless(funcName)){
return true;
}
if (allocAA->isReadOnly(funcName)){
return true;
}
return false;
};
auto getCallFnName = [&](CallInst *call) -> StringRef {
auto func = call->getCalledFunction();
if (func && !func->empty()) {
return func->getName();
}
return call->getCalledValue()->getName();
};
/*
* Handle the case both instructions are calls.
*/
if ( true
&& isa<CallInst>(outgoingT)
&& isa<CallInst>(incomingT)
) {
/*
* If both callees do not write memory, then there is no memory dependence.
*/
if (!isFunctionNonWriting(getCallFnName(cast<CallInst>(outgoingT)))) return false;
if (!isFunctionNonWriting(getCallFnName(cast<CallInst>(incomingT)))) return false;
return true;
}
/*
* Handle the case where both instructions are not call.
*/
if ( true
&& (!isa<CallInst>(outgoingT))
&& (!isa<CallInst>(incomingT))
) {
return false;
}
/*
* Handle the case where just one of the instruction is a call.
*/
CallInst *call;
Value *mem;
if (isa<CallInst>(outgoingT)) {
call = cast<CallInst>(outgoingT);
mem = incomingT;
} else {
assert(isa<CallInst>(incomingT));
call = cast<CallInst>(incomingT);
mem = outgoingT;
}
auto callName = getCallFnName(call);
return isa<LoadInst>(mem) && isFunctionNonWriting(callName)
|| isa<StoreInst>(mem) && isFunctionMemoryless(callName);
}
PDGAnalysis::~PDGAnalysis() {
if (this->programDependenceGraph)
delete this->programDependenceGraph;
for (auto functionFDGPair : this->functionToFDGMap) {
auto fdg = functionFDGPair.second;
delete fdg;
}
this->functionToFDGMap.clear();
}
|
/*
* Copyright (c) 1999, 2020, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
#ifndef SHARE_C1_C1_IR_HPP
#define SHARE_C1_C1_IR_HPP
#include "c1/c1_Instruction.hpp"
#include "ci/ciExceptionHandler.hpp"
#include "ci/ciMethod.hpp"
#include "ci/ciStreams.hpp"
#include "memory/allocation.hpp"
// An XHandler is a C1 internal description for an exception handler
class XHandler: public CompilationResourceObj {
private:
ciExceptionHandler* _desc;
BlockBegin* _entry_block; // Entry block of xhandler
LIR_List* _entry_code; // LIR-operations that must be executed before jumping to entry_block
int _entry_pco; // pco where entry_code (or entry_block if no entry_code) starts
int _phi_operand; // For resolving of phi functions at begin of entry_block
int _scope_count; // for filling ExceptionRangeEntry::scope_count
#ifdef ASSERT
int _lir_op_id; // op_id of the LIR-operation throwing to this handler
#endif
public:
// creation
XHandler(ciExceptionHandler* desc)
: _desc(desc)
, _entry_block(NULL)
, _entry_code(NULL)
, _entry_pco(-1)
, _phi_operand(-1)
, _scope_count(-1)
#ifdef ASSERT
, _lir_op_id(-1)
#endif
{ }
XHandler(XHandler* other)
: _desc(other->_desc)
, _entry_block(other->_entry_block)
, _entry_code(other->_entry_code)
, _entry_pco(other->_entry_pco)
, _phi_operand(other->_phi_operand)
, _scope_count(other->_scope_count)
#ifdef ASSERT
, _lir_op_id(other->_lir_op_id)
#endif
{ }
// accessors for data of ciExceptionHandler
int beg_bci() const { return _desc->start(); }
int end_bci() const { return _desc->limit(); }
int handler_bci() const { return _desc->handler_bci(); }
bool is_catch_all() const { return _desc->is_catch_all(); }
int catch_type() const { return _desc->catch_klass_index(); }
ciInstanceKlass* catch_klass() const { return _desc->catch_klass(); }
bool covers(int bci) const { return beg_bci() <= bci && bci < end_bci(); }
// accessors for additional fields
BlockBegin* entry_block() const { return _entry_block; }
LIR_List* entry_code() const { return _entry_code; }
int entry_pco() const { return _entry_pco; }
int phi_operand() const { assert(_phi_operand != -1, "not set"); return _phi_operand; }
int scope_count() const { assert(_scope_count != -1, "not set"); return _scope_count; }
DEBUG_ONLY(int lir_op_id() const { return _lir_op_id; });
void set_entry_block(BlockBegin* entry_block) {
assert(entry_block->is_set(BlockBegin::exception_entry_flag), "must be an exception handler entry");
assert(entry_block->bci() == handler_bci(), "bci's must correspond");
_entry_block = entry_block;
}
void set_entry_code(LIR_List* entry_code) { _entry_code = entry_code; }
void set_entry_pco(int entry_pco) { _entry_pco = entry_pco; }
void set_phi_operand(int phi_operand) { _phi_operand = phi_operand; }
void set_scope_count(int scope_count) { _scope_count = scope_count; }
DEBUG_ONLY(void set_lir_op_id(int lir_op_id) { _lir_op_id = lir_op_id; });
bool equals(XHandler* other) const;
};
typedef GrowableArray<XHandler*> _XHandlerList;
// XHandlers is the C1 internal list of exception handlers for a method
class XHandlers: public CompilationResourceObj {
private:
_XHandlerList _list;
public:
// creation
XHandlers() : _list() { }
XHandlers(ciMethod* method);
XHandlers(XHandlers* other);
// accessors
int length() const { return _list.length(); }
XHandler* handler_at(int i) const { return _list.at(i); }
bool has_handlers() const { return _list.length() > 0; }
void append(XHandler* h) { _list.append(h); }
XHandler* remove_last() { return _list.pop(); }
bool could_catch(ciInstanceKlass* klass, bool type_is_exact) const;
bool equals(XHandlers* others) const;
};
class IRScope;
typedef GrowableArray<IRScope*> IRScopeList;
class Compilation;
class IRScope: public CompilationResourceObj {
private:
// hierarchy
Compilation* _compilation; // the current compilation
IRScope* _caller; // the caller scope, or NULL
int _level; // the inlining level
ciMethod* _method; // the corresponding method
IRScopeList _callees; // the inlined method scopes
// graph
XHandlers* _xhandlers; // the exception handlers
int _number_of_locks; // the number of monitor lock slots needed
bool _monitor_pairing_ok; // the monitor pairing info
bool _wrote_final; // has written final field
bool _wrote_fields; // has written fields
bool _wrote_volatile; // has written volatile field
BlockBegin* _start; // the start block, successsors are method entries
ResourceBitMap _requires_phi_function; // bit is set if phi functions at loop headers are necessary for a local variable
// helper functions
BlockBegin* build_graph(Compilation* compilation, int osr_bci);
public:
// creation
IRScope(Compilation* compilation, IRScope* caller, int caller_bci, ciMethod* method, int osr_bci, bool create_graph = false);
// accessors
Compilation* compilation() const { return _compilation; }
IRScope* caller() const { return _caller; }
int level() const { return _level; }
ciMethod* method() const { return _method; }
int max_stack() const; // NOTE: expensive
BitMap& requires_phi_function() { return _requires_phi_function; }
// hierarchy
bool is_top_scope() const { return _caller == NULL; }
void add_callee(IRScope* callee) { _callees.append(callee); }
int number_of_callees() const { return _callees.length(); }
IRScope* callee_no(int i) const { return _callees.at(i); }
// accessors, graph
bool is_valid() const { return start() != NULL; }
XHandlers* xhandlers() const { return _xhandlers; }
int number_of_locks() const { return _number_of_locks; }
void set_min_number_of_locks(int n) { if (n > _number_of_locks) _number_of_locks = n; }
bool monitor_pairing_ok() const { return _monitor_pairing_ok; }
BlockBegin* start() const { return _start; }
void set_wrote_final() { _wrote_final = true; }
bool wrote_final () const { return _wrote_final; }
void set_wrote_fields() { _wrote_fields = true; }
bool wrote_fields () const { return _wrote_fields; }
void set_wrote_volatile() { _wrote_volatile = true; }
bool wrote_volatile () const { return _wrote_volatile; }
};
//
// IRScopeDebugInfo records the debug information for a particular IRScope
// in a particular CodeEmitInfo. This allows the information to be computed
// once early enough for the OopMap to be available to the LIR and also to be
// reemited for different pcs using the same CodeEmitInfo without recomputing
// everything.
//
class IRScopeDebugInfo: public CompilationResourceObj {
private:
IRScope* _scope;
int _bci;
GrowableArray<ScopeValue*>* _locals;
GrowableArray<ScopeValue*>* _expressions;
GrowableArray<MonitorValue*>* _monitors;
IRScopeDebugInfo* _caller;
public:
IRScopeDebugInfo(IRScope* scope,
int bci,
GrowableArray<ScopeValue*>* locals,
GrowableArray<ScopeValue*>* expressions,
GrowableArray<MonitorValue*>* monitors,
IRScopeDebugInfo* caller):
_scope(scope)
, _bci(bci)
, _locals(locals)
, _expressions(expressions)
, _monitors(monitors)
, _caller(caller) {}
IRScope* scope() { return _scope; }
int bci() { return _bci; }
GrowableArray<ScopeValue*>* locals() { return _locals; }
GrowableArray<ScopeValue*>* expressions() { return _expressions; }
GrowableArray<MonitorValue*>* monitors() { return _monitors; }
IRScopeDebugInfo* caller() { return _caller; }
//Whether we should reexecute this bytecode for deopt
bool should_reexecute();
void record_debug_info(DebugInformationRecorder* recorder, int pc_offset, bool topmost, bool is_method_handle_invoke = false) {
if (caller() != NULL) {
// Order is significant: Must record caller first.
caller()->record_debug_info(recorder, pc_offset, false/*topmost*/);
}
DebugToken* locvals = recorder->create_scope_values(locals());
DebugToken* expvals = recorder->create_scope_values(expressions());
DebugToken* monvals = recorder->create_monitor_values(monitors());
// reexecute allowed only for the topmost frame
bool reexecute = topmost ? should_reexecute() : false;
bool return_oop = false; // This flag will be ignored since it used only for C2 with escape analysis.
bool rethrow_exception = false;
bool is_opt_native = false;
bool has_ea_local_in_scope = false;
bool arg_escape = false;
recorder->describe_scope(pc_offset, methodHandle(), scope()->method(), bci(),
reexecute, rethrow_exception, is_method_handle_invoke, is_opt_native, return_oop,
has_ea_local_in_scope, arg_escape, locvals, expvals, monvals);
}
};
class CodeEmitInfo: public CompilationResourceObj {
friend class LinearScan;
private:
IRScopeDebugInfo* _scope_debug_info;
IRScope* _scope;
XHandlers* _exception_handlers;
OopMap* _oop_map;
ValueStack* _stack; // used by deoptimization (contains also monitors
bool _is_method_handle_invoke; // true if the associated call site is a MethodHandle call site.
bool _deoptimize_on_exception;
FrameMap* frame_map() const { return scope()->compilation()->frame_map(); }
Compilation* compilation() const { return scope()->compilation(); }
public:
// use scope from ValueStack
CodeEmitInfo(ValueStack* stack, XHandlers* exception_handlers, bool deoptimize_on_exception = false);
// make a copy
CodeEmitInfo(CodeEmitInfo* info, ValueStack* stack = NULL);
// accessors
OopMap* oop_map() { return _oop_map; }
ciMethod* method() const { return _scope->method(); }
IRScope* scope() const { return _scope; }
XHandlers* exception_handlers() const { return _exception_handlers; }
ValueStack* stack() const { return _stack; }
bool deoptimize_on_exception() const { return _deoptimize_on_exception; }
void add_register_oop(LIR_Opr opr);
void record_debug_info(DebugInformationRecorder* recorder, int pc_offset);
bool is_method_handle_invoke() const { return _is_method_handle_invoke; }
void set_is_method_handle_invoke(bool x) { _is_method_handle_invoke = x; }
int interpreter_frame_size() const;
};
class IR: public CompilationResourceObj {
private:
Compilation* _compilation; // the current compilation
IRScope* _top_scope; // the root of the scope hierarchy
int _num_loops; // Total number of loops
BlockList* _code; // the blocks in code generation order w/ use counts
public:
// creation
IR(Compilation* compilation, ciMethod* method, int osr_bci);
// accessors
bool is_valid() const { return top_scope()->is_valid(); }
Compilation* compilation() const { return _compilation; }
IRScope* top_scope() const { return _top_scope; }
int number_of_locks() const { return top_scope()->number_of_locks(); }
ciMethod* method() const { return top_scope()->method(); }
BlockBegin* start() const { return top_scope()->start(); }
BlockBegin* std_entry() const { return start()->end()->as_Base()->std_entry(); }
BlockBegin* osr_entry() const { return start()->end()->as_Base()->osr_entry(); }
BlockList* code() const { return _code; }
int num_loops() const { return _num_loops; }
int max_stack() const { return top_scope()->max_stack(); } // expensive
// ir manipulation
void optimize_blocks();
void eliminate_null_checks();
void compute_predecessors();
void split_critical_edges();
void compute_code();
void compute_use_counts();
// The linear-scan order and the code emission order are equal, but
// this may change in future
BlockList* linear_scan_order() { assert(_code != NULL, "not computed"); return _code; }
// iteration
void iterate_preorder (BlockClosure* closure);
void iterate_postorder (BlockClosure* closure);
void iterate_linear_scan_order(BlockClosure* closure);
// debugging
static void print(BlockBegin* start, bool cfg_only, bool live_only = false) PRODUCT_RETURN;
void print(bool cfg_only, bool live_only = false) PRODUCT_RETURN;
void verify() PRODUCT_RETURN;
};
// Globally do instruction substitution and remove substituted
// instructions from the instruction list.
//
class SubstitutionResolver: public BlockClosure, ValueVisitor {
virtual void visit(Value* v);
public:
SubstitutionResolver(IR* hir) {
hir->iterate_preorder(this);
}
SubstitutionResolver(BlockBegin* block) {
block->iterate_preorder(this);
}
virtual void block_do(BlockBegin* block);
};
#endif // SHARE_C1_C1_IR_HPP
|
#include<iostream>
#include<cstdio>
using namespace std;
int n,m;
int main(){
scanf("%d%d",&n,&m);
return 0;
}
|
/*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 <aws/iot/model/StatisticalThreshold.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace IoT
{
namespace Model
{
StatisticalThreshold::StatisticalThreshold() :
m_statisticHasBeenSet(false)
{
}
StatisticalThreshold::StatisticalThreshold(JsonView jsonValue) :
m_statisticHasBeenSet(false)
{
*this = jsonValue;
}
StatisticalThreshold& StatisticalThreshold::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("statistic"))
{
m_statistic = jsonValue.GetString("statistic");
m_statisticHasBeenSet = true;
}
return *this;
}
JsonValue StatisticalThreshold::Jsonize() const
{
JsonValue payload;
if(m_statisticHasBeenSet)
{
payload.WithString("statistic", m_statistic);
}
return payload;
}
} // namespace Model
} // namespace IoT
} // namespace Aws
|
#include <iostream>
typedef struct {
char name[7];
int score;
} Person;
void printScoreStars(Person* persons, int len) {
for (int i = 0; i < len; ++i) {
std::cout << persons[i].name << ' ';
for (int j = 0; j < persons[i].score / 5; ++j) {
std::cout << '*';
}
std::cout << std::endl;
}
}
int main() {
Person people[3] = { 0, };
for (int i = 0; i < 3; ++i) {
std::cin >> people[i].name >> people[i].score;
}
printScoreStars(people, 3);
}
|
/*
* CoapPacket.cpp
*
* Created on: Nov 17, 2017
* Author: armin
*/
#include <string.h>
#include "CoapPacket.h"
#define COAP_HEADER_SIZE 4
namespace Coap {
static inline void coapOptionDelta(uint32_t v, uint8_t* n) {
v < 13 ? (*n = (0xFF & v)) : (v <= 0xFF + 13 ? (*n = 13) : (*n = 14));
}
size_t packetToBuffer(Packet& packet, uint8_t* buffer, size_t bufferSize) {
uint8_t *p = buffer;
uint16_t running_delta = 0;
size_t packetSize = 0;
// make coap packet base header
*p = 0x01 << 6;
*p |= ((uint8_t)packet.type & 0x03) << 4;
*p++ |= (packet.tokenlen & 0x0F);
*p++ = packet.code;
*p++ = (packet.messageid >> 8);
*p++ = (packet.messageid & 0xFF);
p = buffer + COAP_HEADER_SIZE;
packetSize += 4;
// make token
if (packet.token != nullptr && packet.tokenlen <= 0x0F) {
memcpy(p, packet.token, packet.tokenlen);
p += packet.tokenlen;
packetSize += packet.tokenlen;
}
// make option header
for (int i = 0; i < packet.optionnum; i++) {
uint32_t optdelta;
uint8_t len, delta;
if (packetSize + 5 + packet.options[i].length >= bufferSize) {
return 0;
}
optdelta = (uint8_t)packet.options[i].number - running_delta;
coapOptionDelta(optdelta, &delta);
coapOptionDelta((uint32_t )packet.options[i].length, &len);
*p++ = (0xFF & (delta << 4 | len));
if (delta == 13) {
*p++ = (optdelta - 13);
packetSize++;
} else if (delta == 14) {
*p++ = ((optdelta - 269) >> 8);
*p++ = (0xFF & (optdelta - 269));
packetSize += 2;
}
if (len == 13) {
*p++ = (packet.options[i].length - 13);
packetSize++;
} else if (len == 14) {
*p++ = (packet.options[i].length >> 8);
*p++ = (0xFF & (packet.options[i].length - 269));
packetSize += 2;
}
memcpy(p, packet.options[i].buffer, packet.options[i].length);
p += packet.options[i].length;
packetSize += packet.options[i].length + 1;
running_delta = (uint8_t)packet.options[i].number;
}
// make payload
if (packet.payloadlen > 0) {
if ((packetSize + 1 + packet.payloadlen) >= bufferSize) {
return 0;
}
*p++ = 0xFF;
memcpy(p, packet.payload, packet.payloadlen);
packetSize += 1 + packet.payloadlen;
}
return packetSize;
}
static int parseOption(Option *option, uint16_t *running_delta, uint8_t **buf, size_t buflen) {
uint8_t *p = *buf;
uint8_t headlen = 1;
uint16_t len, delta;
if (buflen < headlen)
return -1;
delta = (p[0] & 0xF0) >> 4;
len = p[0] & 0x0F;
if (delta == 13) {
headlen++;
if (buflen < headlen)
return -1;
delta = p[1] + 13;
p++;
} else if (delta == 14) {
headlen += 2;
if (buflen < headlen)
return -1;
delta = ((p[1] << 8) | p[2]) + 269;
p += 2;
} else if (delta == 15)
return -1;
if (len == 13) {
headlen++;
if (buflen < headlen)
return -1;
len = p[1] + 13;
p++;
} else if (len == 14) {
headlen += 2;
if (buflen < headlen)
return -1;
len = ((p[1] << 8) | p[2]) + 269;
p += 2;
} else if (len == 15)
return -1;
if ((p + 1 + len) > (*buf + buflen))
return -1;
option->number = (Option::Number)(delta + *running_delta);
option->buffer = p + 1;
option->length = len;
*buf = p + 1 + len;
*running_delta += delta;
return 0;
}
bool bufferToPacket(Packet& packet, uint8_t* buffer, size_t bufferSize) {
packet.type = (Coap::Type)((buffer[0] & 0x30) >> 4);
packet.tokenlen = buffer[0] & 0x0F;
packet.code = buffer[1];
packet.messageid = 0xFF00 & (buffer[2] << 8);
packet.messageid |= 0x00FF & buffer[3];
if (packet.tokenlen == 0) {
packet.token = nullptr;
}
else if (packet.tokenlen <= 8) {
packet.token = buffer + 4;
}
else {
return false;
}
// parse packet options/payload
if ((size_t)COAP_HEADER_SIZE + packet.tokenlen < bufferSize) {
int optionIndex = 0;
uint16_t delta = 0;
uint8_t *end = buffer + bufferSize;
uint8_t *p = buffer + COAP_HEADER_SIZE + packet.tokenlen;
while (optionIndex < COAP_MAX_OPTION_NUM && *p != 0xFF && p < end) {
if (0 != parseOption(&packet.options[optionIndex], &delta, &p, end - p)) {
return false;
}
optionIndex++;
}
packet.optionnum = optionIndex;
if (p + 1 < end && *p == 0xFF) {
packet.payload = p + 1;
packet.payloadlen = end - (p + 1);
} else {
packet.payload = nullptr;
packet.payloadlen = 0;
}
}
return true;
}
}
|
/***********************************************************************************************************************
* OpenStudio(R), Copyright (c) 2008-2021, Alliance for Sustainable Energy, LLC, and other contributors. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
* following conditions are met:
*
* (1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following
* disclaimer.
*
* (2) 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.
*
* (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote products
* derived from this software without specific prior written permission from the respective party.
*
* (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative works
* may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without specific prior
* written permission from Alliance for Sustainable Energy, LLC.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND ANY 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 HOLDER(S), ANY CONTRIBUTORS, THE UNITED STATES GOVERNMENT, OR THE UNITED
* STATES DEPARTMENT OF ENERGY, NOR ANY OF THEIR EMPLOYEES, BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
***********************************************************************************************************************/
#include "AvailabilityManagerLowTemperatureTurnOn.hpp"
#include "AvailabilityManagerLowTemperatureTurnOn_Impl.hpp"
#include "Model.hpp"
#include "Node.hpp"
#include "Node_Impl.hpp"
#include <utilities/idd/IddEnums.hxx>
#include <utilities/idd/OS_AvailabilityManager_LowTemperatureTurnOn_FieldEnums.hxx>
#include "../utilities/units/Unit.hpp"
#include "../utilities/core/Assert.hpp"
namespace openstudio {
namespace model {
namespace detail {
AvailabilityManagerLowTemperatureTurnOn_Impl::AvailabilityManagerLowTemperatureTurnOn_Impl(const IdfObject& idfObject, Model_Impl* model,
bool keepHandle)
: AvailabilityManager_Impl(idfObject, model, keepHandle) {
OS_ASSERT(idfObject.iddObject().type() == AvailabilityManagerLowTemperatureTurnOn::iddObjectType());
}
AvailabilityManagerLowTemperatureTurnOn_Impl::AvailabilityManagerLowTemperatureTurnOn_Impl(const openstudio::detail::WorkspaceObject_Impl& other,
Model_Impl* model, bool keepHandle)
: AvailabilityManager_Impl(other, model, keepHandle) {
OS_ASSERT(other.iddObject().type() == AvailabilityManagerLowTemperatureTurnOn::iddObjectType());
}
AvailabilityManagerLowTemperatureTurnOn_Impl::AvailabilityManagerLowTemperatureTurnOn_Impl(
const AvailabilityManagerLowTemperatureTurnOn_Impl& other, Model_Impl* model, bool keepHandle)
: AvailabilityManager_Impl(other, model, keepHandle) {}
const std::vector<std::string>& AvailabilityManagerLowTemperatureTurnOn_Impl::outputVariableNames() const {
static const std::vector<std::string> result{"Availability Manager Low Temperature Turn On Control Status"};
return result;
}
IddObjectType AvailabilityManagerLowTemperatureTurnOn_Impl::iddObjectType() const {
return AvailabilityManagerLowTemperatureTurnOn::iddObjectType();
}
boost::optional<Node> AvailabilityManagerLowTemperatureTurnOn_Impl::sensorNode() const {
return getObject<ModelObject>().getModelObjectTarget<Node>(OS_AvailabilityManager_LowTemperatureTurnOnFields::SensorNodeName);
}
double AvailabilityManagerLowTemperatureTurnOn_Impl::temperature() const {
boost::optional<double> value = getDouble(OS_AvailabilityManager_LowTemperatureTurnOnFields::Temperature, true);
OS_ASSERT(value);
return value.get();
}
bool AvailabilityManagerLowTemperatureTurnOn_Impl::setSensorNode(const Node& node) {
bool result = setPointer(OS_AvailabilityManager_LowTemperatureTurnOnFields::SensorNodeName, node.handle());
return result;
}
void AvailabilityManagerLowTemperatureTurnOn_Impl::resetSensorNode() {
bool result = setString(OS_AvailabilityManager_LowTemperatureTurnOnFields::SensorNodeName, "");
OS_ASSERT(result);
}
bool AvailabilityManagerLowTemperatureTurnOn_Impl::setTemperature(double temperature) {
bool result = setDouble(OS_AvailabilityManager_LowTemperatureTurnOnFields::Temperature, temperature);
OS_ASSERT(result);
return result;
}
} // namespace detail
AvailabilityManagerLowTemperatureTurnOn::AvailabilityManagerLowTemperatureTurnOn(const Model& model)
: AvailabilityManager(AvailabilityManagerLowTemperatureTurnOn::iddObjectType(), model) {
OS_ASSERT(getImpl<detail::AvailabilityManagerLowTemperatureTurnOn_Impl>());
setTemperature(30);
}
IddObjectType AvailabilityManagerLowTemperatureTurnOn::iddObjectType() {
return IddObjectType(IddObjectType::OS_AvailabilityManager_LowTemperatureTurnOn);
}
boost::optional<Node> AvailabilityManagerLowTemperatureTurnOn::sensorNode() const {
return getImpl<detail::AvailabilityManagerLowTemperatureTurnOn_Impl>()->sensorNode();
}
double AvailabilityManagerLowTemperatureTurnOn::temperature() const {
return getImpl<detail::AvailabilityManagerLowTemperatureTurnOn_Impl>()->temperature();
}
bool AvailabilityManagerLowTemperatureTurnOn::setSensorNode(const Node& node) {
return getImpl<detail::AvailabilityManagerLowTemperatureTurnOn_Impl>()->setSensorNode(node);
}
void AvailabilityManagerLowTemperatureTurnOn::resetSensorNode() {
getImpl<detail::AvailabilityManagerLowTemperatureTurnOn_Impl>()->resetSensorNode();
}
bool AvailabilityManagerLowTemperatureTurnOn::setTemperature(double temperature) {
return getImpl<detail::AvailabilityManagerLowTemperatureTurnOn_Impl>()->setTemperature(temperature);
}
/// @cond
AvailabilityManagerLowTemperatureTurnOn::AvailabilityManagerLowTemperatureTurnOn(
std::shared_ptr<detail::AvailabilityManagerLowTemperatureTurnOn_Impl> impl)
: AvailabilityManager(impl) {}
/// @endcond
} // namespace model
} // namespace openstudio
|
//
// Copyright (c) 2013-2021 The SRS Authors
//
// SPDX-License-Identifier: MIT or MulanPSL-2.0
//
#include <srs_app_source.hpp>
#include <sstream>
#include <algorithm>
using namespace std;
#include <srs_kernel_log.hpp>
#include <srs_rtmp_stack.hpp>
#include <srs_protocol_amf0.hpp>
#include <srs_kernel_codec.hpp>
#include <srs_kernel_rtc_rtp.hpp>
#include <srs_app_hls.hpp>
#include <srs_app_forward.hpp>
#include <srs_app_config.hpp>
#include <srs_app_encoder.hpp>
#include <srs_rtmp_stack.hpp>
#include <srs_app_dvr.hpp>
#include <srs_kernel_buffer.hpp>
#include <srs_app_edge.hpp>
#include <srs_kernel_utility.hpp>
#include <srs_kernel_codec.hpp>
#include <srs_rtmp_msg_array.hpp>
#include <srs_app_hds.hpp>
#include <srs_app_statistic.hpp>
#include <srs_core_autofree.hpp>
#include <srs_protocol_utility.hpp>
#include <srs_app_ng_exec.hpp>
#include <srs_app_dash.hpp>
#include <srs_protocol_format.hpp>
#include <srs_app_rtc_source.hpp>
#include <srs_app_http_hooks.hpp>
#define CONST_MAX_JITTER_MS 250
#define CONST_MAX_JITTER_MS_NEG -250
#define DEFAULT_FRAME_TIME_MS 10
// for 26ms per audio packet,
// 115 packets is 3s.
#define SRS_PURE_AUDIO_GUESS_COUNT 115
// when got these videos or audios, pure audio or video, mix ok.
#define SRS_MIX_CORRECT_PURE_AV 10
// the time to cleanup source.
#define SRS_SOURCE_CLEANUP (30 * SRS_UTIME_SECONDS)
int srs_time_jitter_string2int(std::string time_jitter)
{
if (time_jitter == "full") {
return SrsRtmpJitterAlgorithmFULL;
} else if (time_jitter == "zero") {
return SrsRtmpJitterAlgorithmZERO;
} else {
return SrsRtmpJitterAlgorithmOFF;
}
}
SrsRtmpJitter::SrsRtmpJitter()
{
last_pkt_correct_time = -1;
last_pkt_time = 0;
}
SrsRtmpJitter::~SrsRtmpJitter()
{
}
srs_error_t SrsRtmpJitter::correct(SrsSharedPtrMessage* msg, SrsRtmpJitterAlgorithm ag)
{
srs_error_t err = srs_success;
// for performance issue
if (ag != SrsRtmpJitterAlgorithmFULL) {
// all jitter correct features is disabled, ignore.
if (ag == SrsRtmpJitterAlgorithmOFF) {
return err;
}
// start at zero, but donot ensure monotonically increasing.
if (ag == SrsRtmpJitterAlgorithmZERO) {
// for the first time, last_pkt_correct_time is -1.
if (last_pkt_correct_time == -1) {
last_pkt_correct_time = msg->timestamp;
}
msg->timestamp -= last_pkt_correct_time;
return err;
}
// other algorithm, ignore.
return err;
}
// full jitter algorithm, do jitter correct.
// set to 0 for metadata.
if (!msg->is_av()) {
msg->timestamp = 0;
return err;
}
/**
* we use a very simple time jitter detect/correct algorithm:
* 1. delta: ensure the delta is positive and valid,
* we set the delta to DEFAULT_FRAME_TIME_MS,
* if the delta of time is nagative or greater than CONST_MAX_JITTER_MS.
* 2. last_pkt_time: specifies the original packet time,
* is used to detect next jitter.
* 3. last_pkt_correct_time: simply add the positive delta,
* and enforce the time monotonically.
*/
int64_t time = msg->timestamp;
int64_t delta = time - last_pkt_time;
// if jitter detected, reset the delta.
if (delta < CONST_MAX_JITTER_MS_NEG || delta > CONST_MAX_JITTER_MS) {
// use default 10ms to notice the problem of stream.
// @see https://github.com/ossrs/srs/issues/425
delta = DEFAULT_FRAME_TIME_MS;
}
last_pkt_correct_time = srs_max(0, last_pkt_correct_time + delta);
msg->timestamp = last_pkt_correct_time;
last_pkt_time = time;
return err;
}
int64_t SrsRtmpJitter::get_time()
{
return last_pkt_correct_time;
}
#ifdef SRS_PERF_QUEUE_FAST_VECTOR
SrsFastVector::SrsFastVector()
{
count = 0;
nb_msgs = 8;
msgs = new SrsSharedPtrMessage*[nb_msgs];
}
SrsFastVector::~SrsFastVector()
{
free();
srs_freepa(msgs);
}
int SrsFastVector::size()
{
return count;
}
int SrsFastVector::begin()
{
return 0;
}
int SrsFastVector::end()
{
return count;
}
SrsSharedPtrMessage** SrsFastVector::data()
{
return msgs;
}
SrsSharedPtrMessage* SrsFastVector::at(int index)
{
srs_assert(index < count);
return msgs[index];
}
void SrsFastVector::clear()
{
count = 0;
}
void SrsFastVector::erase(int _begin, int _end)
{
srs_assert(_begin < _end);
// move all erased to previous.
for (int i = 0; i < count - _end; i++) {
msgs[_begin + i] = msgs[_end + i];
}
// update the count.
count -= _end - _begin;
}
void SrsFastVector::push_back(SrsSharedPtrMessage* msg)
{
// increase vector.
if (count >= nb_msgs) {
int size = srs_max(SRS_PERF_MW_MSGS * 8, nb_msgs * 2);
SrsSharedPtrMessage** buf = new SrsSharedPtrMessage*[size];
for (int i = 0; i < nb_msgs; i++) {
buf[i] = msgs[i];
}
srs_info("fast vector incrase %d=>%d", nb_msgs, size);
// use new array.
srs_freepa(msgs);
msgs = buf;
nb_msgs = size;
}
msgs[count++] = msg;
}
void SrsFastVector::free()
{
for (int i = 0; i < count; i++) {
SrsSharedPtrMessage* msg = msgs[i];
srs_freep(msg);
}
count = 0;
}
#endif
SrsMessageQueue::SrsMessageQueue(bool ignore_shrink)
{
_ignore_shrink = ignore_shrink;
max_queue_size = 0;
av_start_time = av_end_time = -1;
}
SrsMessageQueue::~SrsMessageQueue()
{
clear();
}
int SrsMessageQueue::size()
{
return (int)msgs.size();
}
srs_utime_t SrsMessageQueue::duration()
{
return (av_end_time - av_start_time);
}
void SrsMessageQueue::set_queue_size(srs_utime_t queue_size)
{
max_queue_size = queue_size;
}
srs_error_t SrsMessageQueue::enqueue(SrsSharedPtrMessage* msg, bool* is_overflow)
{
srs_error_t err = srs_success;
msgs.push_back(msg);
// If jitter is off, the timestamp of first sequence header is zero, which wll cause SRS to shrink and drop the
// keyframes even if there is not overflow packets in queue, so we must ignore the zero timestamps, please
// @see https://github.com/ossrs/srs/pull/2186#issuecomment-953383063
if (msg->is_av() && msg->timestamp != 0) {
if (av_start_time == -1) {
av_start_time = srs_utime_t(msg->timestamp * SRS_UTIME_MILLISECONDS);
}
av_end_time = srs_utime_t(msg->timestamp * SRS_UTIME_MILLISECONDS);
}
if (max_queue_size <= 0) {
return err;
}
while (av_end_time - av_start_time > max_queue_size) {
// notice the caller queue already overflow and shrinked.
if (is_overflow) {
*is_overflow = true;
}
shrink();
}
return err;
}
srs_error_t SrsMessageQueue::dump_packets(int max_count, SrsSharedPtrMessage** pmsgs, int& count)
{
srs_error_t err = srs_success;
int nb_msgs = (int)msgs.size();
if (nb_msgs <= 0) {
return err;
}
srs_assert(max_count > 0);
count = srs_min(max_count, nb_msgs);
SrsSharedPtrMessage** omsgs = msgs.data();
memcpy(pmsgs, omsgs, count * sizeof(SrsSharedPtrMessage*));
SrsSharedPtrMessage* last = omsgs[count - 1];
av_start_time = srs_utime_t(last->timestamp * SRS_UTIME_MILLISECONDS);
if (count >= nb_msgs) {
// the pmsgs is big enough and clear msgs at most time.
msgs.clear();
} else {
// erase some vector elements may cause memory copy,
// maybe can use more efficient vector.swap to avoid copy.
// @remark for the pmsgs is big enough, for instance, SRS_PERF_MW_MSGS 128,
// the rtmp play client will get 128msgs once, so this branch rarely execute.
msgs.erase(msgs.begin(), msgs.begin() + count);
}
return err;
}
srs_error_t SrsMessageQueue::dump_packets(SrsLiveConsumer* consumer, bool atc, SrsRtmpJitterAlgorithm ag)
{
srs_error_t err = srs_success;
int nb_msgs = (int)msgs.size();
if (nb_msgs <= 0) {
return err;
}
SrsSharedPtrMessage** omsgs = msgs.data();
for (int i = 0; i < nb_msgs; i++) {
SrsSharedPtrMessage* msg = omsgs[i];
if ((err = consumer->enqueue(msg, atc, ag)) != srs_success) {
return srs_error_wrap(err, "consume message");
}
}
return err;
}
void SrsMessageQueue::shrink()
{
SrsSharedPtrMessage* video_sh = NULL;
SrsSharedPtrMessage* audio_sh = NULL;
int msgs_size = (int)msgs.size();
// Remove all msgs, mark the sequence headers.
for (int i = 0; i < (int)msgs.size(); i++) {
SrsSharedPtrMessage* msg = msgs.at(i);
if (msg->is_video() && SrsFlvVideo::sh(msg->payload, msg->size)) {
srs_freep(video_sh);
video_sh = msg;
continue;
}
else if (msg->is_audio() && SrsFlvAudio::sh(msg->payload, msg->size)) {
srs_freep(audio_sh);
audio_sh = msg;
continue;
}
srs_freep(msg);
}
msgs.clear();
// Update av_start_time, the start time of queue.
av_start_time = av_end_time;
// Push back sequence headers and update their timestamps.
if (video_sh) {
video_sh->timestamp = srsu2ms(av_end_time);
msgs.push_back(video_sh);
}
if (audio_sh) {
audio_sh->timestamp = srsu2ms(av_end_time);
msgs.push_back(audio_sh);
}
if (!_ignore_shrink) {
srs_trace("shrinking, size=%d, removed=%d, max=%dms", (int)msgs.size(), msgs_size - (int)msgs.size(), srsu2msi(max_queue_size));
}
}
void SrsMessageQueue::clear()
{
#ifndef SRS_PERF_QUEUE_FAST_VECTOR
std::vector<SrsSharedPtrMessage*>::iterator it;
for (it = msgs.begin(); it != msgs.end(); ++it) {
SrsSharedPtrMessage* msg = *it;
srs_freep(msg);
}
#else
msgs.free();
#endif
msgs.clear();
av_start_time = av_end_time = -1;
}
ISrsWakable::ISrsWakable()
{
}
ISrsWakable::~ISrsWakable()
{
}
SrsLiveConsumer::SrsLiveConsumer(SrsLiveSource* s)
{
source = s;
paused = false;
jitter = new SrsRtmpJitter();
queue = new SrsMessageQueue();
should_update_source_id = false;
#ifdef SRS_PERF_QUEUE_COND_WAIT
mw_wait = srs_cond_new();
mw_min_msgs = 0;
mw_duration = 0;
mw_waiting = false;
#endif
}
SrsLiveConsumer::~SrsLiveConsumer()
{
source->on_consumer_destroy(this);
srs_freep(jitter);
srs_freep(queue);
#ifdef SRS_PERF_QUEUE_COND_WAIT
srs_cond_destroy(mw_wait);
#endif
}
void SrsLiveConsumer::set_queue_size(srs_utime_t queue_size)
{
queue->set_queue_size(queue_size);
}
void SrsLiveConsumer::update_source_id()
{
should_update_source_id = true;
}
int64_t SrsLiveConsumer::get_time()
{
return jitter->get_time();
}
srs_error_t SrsLiveConsumer::enqueue(SrsSharedPtrMessage* shared_msg, bool atc, SrsRtmpJitterAlgorithm ag)
{
srs_error_t err = srs_success;
SrsSharedPtrMessage* msg = shared_msg->copy();
if (!atc) {
if ((err = jitter->correct(msg, ag)) != srs_success) {
return srs_error_wrap(err, "consume message");
}
}
if ((err = queue->enqueue(msg, NULL)) != srs_success) {
return srs_error_wrap(err, "enqueue message");
}
#ifdef SRS_PERF_QUEUE_COND_WAIT
// fire the mw when msgs is enough.
if (mw_waiting) {
// For RTMP, we wait for messages and duration.
srs_utime_t duration = queue->duration();
bool match_min_msgs = queue->size() > mw_min_msgs;
// For ATC, maybe the SH timestamp bigger than A/V packet,
// when encoder republish or overflow.
// @see https://github.com/ossrs/srs/pull/749
if (atc && duration < 0) {
srs_cond_signal(mw_wait);
mw_waiting = false;
return err;
}
// when duration ok, signal to flush.
if (match_min_msgs && duration > mw_duration) {
srs_cond_signal(mw_wait);
mw_waiting = false;
return err;
}
}
#endif
return err;
}
srs_error_t SrsLiveConsumer::dump_packets(SrsMessageArray* msgs, int& count)
{
srs_error_t err = srs_success;
srs_assert(count >= 0);
srs_assert(msgs->max > 0);
// the count used as input to reset the max if positive.
int max = count? srs_min(count, msgs->max) : msgs->max;
// the count specifies the max acceptable count,
// here maybe 1+, and we must set to 0 when got nothing.
count = 0;
if (should_update_source_id) {
srs_trace("update source_id=%s/%s", source->source_id().c_str(), source->pre_source_id().c_str());
should_update_source_id = false;
}
// paused, return nothing.
if (paused) {
return err;
}
// pump msgs from queue.
if ((err = queue->dump_packets(max, msgs->msgs, count)) != srs_success) {
return srs_error_wrap(err, "dump packets");
}
return err;
}
#ifdef SRS_PERF_QUEUE_COND_WAIT
void SrsLiveConsumer::wait(int nb_msgs, srs_utime_t msgs_duration)
{
if (paused) {
srs_usleep(SRS_CONSTS_RTMP_PULSE);
return;
}
mw_min_msgs = nb_msgs;
mw_duration = msgs_duration;
srs_utime_t duration = queue->duration();
bool match_min_msgs = queue->size() > mw_min_msgs;
// when duration ok, signal to flush.
if (match_min_msgs && duration > mw_duration) {
return;
}
// the enqueue will notify this cond.
mw_waiting = true;
// use cond block wait for high performance mode.
srs_cond_wait(mw_wait);
}
#endif
srs_error_t SrsLiveConsumer::on_play_client_pause(bool is_pause)
{
srs_error_t err = srs_success;
srs_trace("stream consumer change pause state %d=>%d", paused, is_pause);
paused = is_pause;
return err;
}
void SrsLiveConsumer::wakeup()
{
#ifdef SRS_PERF_QUEUE_COND_WAIT
if (mw_waiting) {
srs_cond_signal(mw_wait);
mw_waiting = false;
}
#endif
}
SrsGopCache::SrsGopCache()
{
cached_video_count = 0;
enable_gop_cache = true;
audio_after_last_video_count = 0;
}
SrsGopCache::~SrsGopCache()
{
clear();
}
void SrsGopCache::dispose()
{
clear();
}
void SrsGopCache::set(bool v)
{
enable_gop_cache = v;
if (!v) {
clear();
return;
}
}
bool SrsGopCache::enabled()
{
return enable_gop_cache;
}
srs_error_t SrsGopCache::cache(SrsSharedPtrMessage* shared_msg)
{
srs_error_t err = srs_success;
if (!enable_gop_cache) {
return err;
}
// the gop cache know when to gop it.
SrsSharedPtrMessage* msg = shared_msg;
// got video, update the video count if acceptable
if (msg->is_video()) {
// drop video when not h.264
if (!SrsFlvVideo::h264(msg->payload, msg->size)) {
return err;
}
cached_video_count++;
audio_after_last_video_count = 0;
}
// no acceptable video or pure audio, disable the cache.
if (pure_audio()) {
return err;
}
// ok, gop cache enabled, and got an audio.
if (msg->is_audio()) {
audio_after_last_video_count++;
}
// clear gop cache when pure audio count overflow
if (audio_after_last_video_count > SRS_PURE_AUDIO_GUESS_COUNT) {
srs_warn("clear gop cache for guess pure audio overflow");
clear();
return err;
}
// clear gop cache when got key frame
if (msg->is_video() && SrsFlvVideo::keyframe(msg->payload, msg->size)) {
clear();
// curent msg is video frame, so we set to 1.
cached_video_count = 1;
}
// cache the frame.
gop_cache.push_back(msg->copy());
return err;
}
void SrsGopCache::clear()
{
std::vector<SrsSharedPtrMessage*>::iterator it;
for (it = gop_cache.begin(); it != gop_cache.end(); ++it) {
SrsSharedPtrMessage* msg = *it;
srs_freep(msg);
}
gop_cache.clear();
cached_video_count = 0;
audio_after_last_video_count = 0;
}
srs_error_t SrsGopCache::dump(SrsLiveConsumer* consumer, bool atc, SrsRtmpJitterAlgorithm jitter_algorithm)
{
srs_error_t err = srs_success;
std::vector<SrsSharedPtrMessage*>::iterator it;
for (it = gop_cache.begin(); it != gop_cache.end(); ++it) {
SrsSharedPtrMessage* msg = *it;
if ((err = consumer->enqueue(msg, atc, jitter_algorithm)) != srs_success) {
return srs_error_wrap(err, "enqueue message");
}
}
srs_trace("dispatch cached gop success. count=%d, duration=%d", (int)gop_cache.size(), consumer->get_time());
return err;
}
bool SrsGopCache::empty()
{
return gop_cache.empty();
}
srs_utime_t SrsGopCache::start_time()
{
if (empty()) {
return 0;
}
SrsSharedPtrMessage* msg = gop_cache[0];
srs_assert(msg);
return srs_utime_t(msg->timestamp * SRS_UTIME_MILLISECONDS);
}
bool SrsGopCache::pure_audio()
{
return cached_video_count == 0;
}
ISrsLiveSourceHandler::ISrsLiveSourceHandler()
{
}
ISrsLiveSourceHandler::~ISrsLiveSourceHandler()
{
}
// TODO: FIXME: Remove it?
bool srs_hls_can_continue(int ret, SrsSharedPtrMessage* sh, SrsSharedPtrMessage* msg)
{
// only continue for decode error.
if (ret != ERROR_HLS_DECODE_ERROR) {
return false;
}
// when video size equals to sequence header,
// the video actually maybe a sequence header,
// continue to make ffmpeg happy.
if (sh && sh->size == msg->size) {
srs_warn("the msg is actually a sequence header, ignore this packet.");
return true;
}
return false;
}
SrsMixQueue::SrsMixQueue()
{
nb_videos = 0;
nb_audios = 0;
}
SrsMixQueue::~SrsMixQueue()
{
clear();
}
void SrsMixQueue::clear()
{
std::multimap<int64_t, SrsSharedPtrMessage*>::iterator it;
for (it = msgs.begin(); it != msgs.end(); ++it) {
SrsSharedPtrMessage* msg = it->second;
srs_freep(msg);
}
msgs.clear();
nb_videos = 0;
nb_audios = 0;
}
void SrsMixQueue::push(SrsSharedPtrMessage* msg)
{
msgs.insert(std::make_pair(msg->timestamp, msg));
if (msg->is_video()) {
nb_videos++;
} else {
nb_audios++;
}
}
SrsSharedPtrMessage* SrsMixQueue::pop()
{
bool mix_ok = false;
// pure video
if (nb_videos >= SRS_MIX_CORRECT_PURE_AV && nb_audios == 0) {
mix_ok = true;
}
// pure audio
if (nb_audios >= SRS_MIX_CORRECT_PURE_AV && nb_videos == 0) {
mix_ok = true;
}
// got 1 video and 1 audio, mix ok.
if (nb_videos >= 1 && nb_audios >= 1) {
mix_ok = true;
}
if (!mix_ok) {
return NULL;
}
// pop the first msg.
std::multimap<int64_t, SrsSharedPtrMessage*>::iterator it = msgs.begin();
SrsSharedPtrMessage* msg = it->second;
msgs.erase(it);
if (msg->is_video()) {
nb_videos--;
} else {
nb_audios--;
}
return msg;
}
SrsOriginHub::SrsOriginHub()
{
source = NULL;
req_ = NULL;
is_active = false;
hls = new SrsHls();
dash = new SrsDash();
dvr = new SrsDvr();
encoder = new SrsEncoder();
#ifdef SRS_HDS
hds = new SrsHds();
#endif
ng_exec = new SrsNgExec();
format = new SrsRtmpFormat();
_srs_config->subscribe(this);
}
SrsOriginHub::~SrsOriginHub()
{
_srs_config->unsubscribe(this);
if (true) {
std::vector<SrsForwarder*>::iterator it;
for (it = forwarders.begin(); it != forwarders.end(); ++it) {
SrsForwarder* forwarder = *it;
srs_freep(forwarder);
}
forwarders.clear();
}
srs_freep(ng_exec);
srs_freep(format);
srs_freep(hls);
srs_freep(dash);
srs_freep(dvr);
srs_freep(encoder);
#ifdef SRS_HDS
srs_freep(hds);
#endif
}
srs_error_t SrsOriginHub::initialize(SrsLiveSource* s, SrsRequest* r)
{
srs_error_t err = srs_success;
req_ = r;
source = s;
if ((err = format->initialize()) != srs_success) {
return srs_error_wrap(err, "format initialize");
}
if ((err = hls->initialize(this, req_)) != srs_success) {
return srs_error_wrap(err, "hls initialize");
}
if ((err = dash->initialize(this, req_)) != srs_success) {
return srs_error_wrap(err, "dash initialize");
}
if ((err = dvr->initialize(this, req_)) != srs_success) {
return srs_error_wrap(err, "dvr initialize");
}
return err;
}
void SrsOriginHub::dispose()
{
hls->dispose();
// TODO: Support dispose DASH.
}
srs_error_t SrsOriginHub::cycle()
{
srs_error_t err = srs_success;
if ((err = hls->cycle()) != srs_success) {
return srs_error_wrap(err, "hls cycle");
}
// TODO: Support cycle DASH.
return err;
}
bool SrsOriginHub::active()
{
return is_active;
}
srs_error_t SrsOriginHub::on_meta_data(SrsSharedPtrMessage* shared_metadata, SrsOnMetaDataPacket* packet)
{
srs_error_t err = srs_success;
if ((err = format->on_metadata(packet)) != srs_success) {
return srs_error_wrap(err, "Format parse metadata");
}
// copy to all forwarders
if (true) {
std::vector<SrsForwarder*>::iterator it;
for (it = forwarders.begin(); it != forwarders.end(); ++it) {
SrsForwarder* forwarder = *it;
if ((err = forwarder->on_meta_data(shared_metadata)) != srs_success) {
return srs_error_wrap(err, "Forwarder consume metadata");
}
}
}
if ((err = dvr->on_meta_data(shared_metadata)) != srs_success) {
return srs_error_wrap(err, "DVR consume metadata");
}
return err;
}
srs_error_t SrsOriginHub::on_audio(SrsSharedPtrMessage* shared_audio)
{
srs_error_t err = srs_success;
SrsSharedPtrMessage* msg = shared_audio;
// TODO: FIXME: Support parsing OPUS for RTC.
if ((err = format->on_audio(msg)) != srs_success) {
return srs_error_wrap(err, "format consume audio");
}
// Ignore if no format->acodec, it means the codec is not parsed, or unsupport/unknown codec
// such as G.711 codec
if (!format->acodec) {
return err;
}
// cache the sequence header if aac
// donot cache the sequence header to gop_cache, return here.
if (format->is_aac_sequence_header()) {
srs_assert(format->acodec);
SrsAudioCodecConfig* c = format->acodec;
static int flv_sample_sizes[] = {8, 16, 0};
static int flv_sound_types[] = {1, 2, 0};
// when got audio stream info.
SrsStatistic* stat = SrsStatistic::instance();
if ((err = stat->on_audio_info(req_, SrsAudioCodecIdAAC, c->sound_rate, c->sound_type, c->aac_object)) != srs_success) {
return srs_error_wrap(err, "stat audio");
}
srs_trace("%dB audio sh, codec(%d, profile=%s, %dchannels, %dkbps, %dHZ), flv(%dbits, %dchannels, %dHZ)",
msg->size, c->id, srs_aac_object2str(c->aac_object).c_str(), c->aac_channels,
c->audio_data_rate / 1000, srs_aac_srates[c->aac_sample_rate],
flv_sample_sizes[c->sound_size], flv_sound_types[c->sound_type],
srs_flv_srates[c->sound_rate]);
}
if ((err = hls->on_audio(msg, format)) != srs_success) {
// apply the error strategy for hls.
// @see https://github.com/ossrs/srs/issues/264
std::string hls_error_strategy = _srs_config->get_hls_on_error(req_->vhost);
if (srs_config_hls_is_on_error_ignore(hls_error_strategy)) {
srs_warn("hls: ignore audio error %s", srs_error_desc(err).c_str());
hls->on_unpublish();
srs_error_reset(err);
} else if (srs_config_hls_is_on_error_continue(hls_error_strategy)) {
if (srs_hls_can_continue(srs_error_code(err), source->meta->ash(), msg)) {
srs_error_reset(err);
} else {
return srs_error_wrap(err, "hls: audio");
}
} else {
return srs_error_wrap(err, "hls: audio");
}
}
if ((err = dash->on_audio(msg, format)) != srs_success) {
srs_warn("dash: ignore audio error %s", srs_error_desc(err).c_str());
srs_error_reset(err);
dash->on_unpublish();
}
if ((err = dvr->on_audio(msg, format)) != srs_success) {
srs_warn("dvr: ignore audio error %s", srs_error_desc(err).c_str());
srs_error_reset(err);
dvr->on_unpublish();
}
#ifdef SRS_HDS
if ((err = hds->on_audio(msg)) != srs_success) {
srs_warn("hds: ignore audio error %s", srs_error_desc(err).c_str());
srs_error_reset(err);
hds->on_unpublish();
}
#endif
// copy to all forwarders.
if (true) {
std::vector<SrsForwarder*>::iterator it;
for (it = forwarders.begin(); it != forwarders.end(); ++it) {
SrsForwarder* forwarder = *it;
if ((err = forwarder->on_audio(msg)) != srs_success) {
return srs_error_wrap(err, "forward: audio");
}
}
}
return err;
}
srs_error_t SrsOriginHub::on_video(SrsSharedPtrMessage* shared_video, bool is_sequence_header)
{
srs_error_t err = srs_success;
SrsSharedPtrMessage* msg = shared_video;
// user can disable the sps parse to workaround when parse sps failed.
// @see https://github.com/ossrs/srs/issues/474
if (is_sequence_header) {
format->avc_parse_sps = _srs_config->get_parse_sps(req_->vhost);
}
if ((err = format->on_video(msg)) != srs_success) {
return srs_error_wrap(err, "format consume video");
}
// Ignore if no format->vcodec, it means the codec is not parsed, or unsupport/unknown codec
// such as H.263 codec
if (!format->vcodec) {
return err;
}
// cache the sequence header if h264
// donot cache the sequence header to gop_cache, return here.
if (format->is_avc_sequence_header()) {
SrsVideoCodecConfig* c = format->vcodec;
srs_assert(c);
// when got video stream info.
SrsStatistic* stat = SrsStatistic::instance();
if ((err = stat->on_video_info(req_, SrsVideoCodecIdAVC, c->avc_profile, c->avc_level, c->width, c->height)) != srs_success) {
return srs_error_wrap(err, "stat video");
}
srs_trace("%dB video sh, codec(%d, profile=%s, level=%s, %dx%d, %dkbps, %.1ffps, %.1fs)",
msg->size, c->id, srs_avc_profile2str(c->avc_profile).c_str(),
srs_avc_level2str(c->avc_level).c_str(), c->width, c->height,
c->video_data_rate / 1000, c->frame_rate, c->duration);
}
// Ignore video data when no sps/pps
// @bug https://github.com/ossrs/srs/issues/703#issuecomment-578393155
if (format->vcodec && !format->vcodec->is_avc_codec_ok()) {
return err;
}
if ((err = hls->on_video(msg, format)) != srs_success) {
// TODO: We should support more strategies.
// apply the error strategy for hls.
// @see https://github.com/ossrs/srs/issues/264
std::string hls_error_strategy = _srs_config->get_hls_on_error(req_->vhost);
if (srs_config_hls_is_on_error_ignore(hls_error_strategy)) {
srs_warn("hls: ignore video error %s", srs_error_desc(err).c_str());
hls->on_unpublish();
srs_error_reset(err);
} else if (srs_config_hls_is_on_error_continue(hls_error_strategy)) {
if (srs_hls_can_continue(srs_error_code(err), source->meta->vsh(), msg)) {
srs_error_reset(err);
} else {
return srs_error_wrap(err, "hls: video");
}
} else {
return srs_error_wrap(err, "hls: video");
}
}
if ((err = dash->on_video(msg, format)) != srs_success) {
srs_warn("dash: ignore video error %s", srs_error_desc(err).c_str());
srs_error_reset(err);
dash->on_unpublish();
}
if ((err = dvr->on_video(msg, format)) != srs_success) {
srs_warn("dvr: ignore video error %s", srs_error_desc(err).c_str());
srs_error_reset(err);
dvr->on_unpublish();
}
#ifdef SRS_HDS
if ((err = hds->on_video(msg)) != srs_success) {
srs_warn("hds: ignore video error %s", srs_error_desc(err).c_str());
srs_error_reset(err);
hds->on_unpublish();
}
#endif
// copy to all forwarders.
if (!forwarders.empty()) {
std::vector<SrsForwarder*>::iterator it;
for (it = forwarders.begin(); it != forwarders.end(); ++it) {
SrsForwarder* forwarder = *it;
if ((err = forwarder->on_video(msg)) != srs_success) {
return srs_error_wrap(err, "forward video");
}
}
}
return err;
}
srs_error_t SrsOriginHub::on_publish()
{
srs_error_t err = srs_success;
// create forwarders
if ((err = create_forwarders()) != srs_success) {
return srs_error_wrap(err, "create forwarders");
}
// TODO: FIXME: use initialize to set req.
if ((err = encoder->on_publish(req_)) != srs_success) {
return srs_error_wrap(err, "encoder publish");
}
if ((err = hls->on_publish()) != srs_success) {
return srs_error_wrap(err, "hls publish");
}
if ((err = dash->on_publish()) != srs_success) {
return srs_error_wrap(err, "dash publish");
}
// @see https://github.com/ossrs/srs/issues/1613#issuecomment-961657927
if ((err = dvr->on_publish(req_)) != srs_success) {
return srs_error_wrap(err, "dvr publish");
}
// TODO: FIXME: use initialize to set req.
#ifdef SRS_HDS
if ((err = hds->on_publish(req)) != srs_success) {
return srs_error_wrap(err, "hds publish");
}
#endif
// TODO: FIXME: use initialize to set req.
if ((err = ng_exec->on_publish(req_)) != srs_success) {
return srs_error_wrap(err, "exec publish");
}
is_active = true;
return err;
}
void SrsOriginHub::on_unpublish()
{
is_active = false;
// destroy all forwarders
destroy_forwarders();
encoder->on_unpublish();
hls->on_unpublish();
dash->on_unpublish();
dvr->on_unpublish();
#ifdef SRS_HDS
hds->on_unpublish();
#endif
ng_exec->on_unpublish();
}
srs_error_t SrsOriginHub::on_forwarder_start(SrsForwarder* forwarder)
{
srs_error_t err = srs_success;
SrsSharedPtrMessage* cache_metadata = source->meta->data();
SrsSharedPtrMessage* cache_sh_video = source->meta->vsh();
SrsSharedPtrMessage* cache_sh_audio = source->meta->ash();
// feed the forwarder the metadata/sequence header,
// when reload to enable the forwarder.
if (cache_metadata && (err = forwarder->on_meta_data(cache_metadata)) != srs_success) {
return srs_error_wrap(err, "forward metadata");
}
if (cache_sh_video && (err = forwarder->on_video(cache_sh_video)) != srs_success) {
return srs_error_wrap(err, "forward video sh");
}
if (cache_sh_audio && (err = forwarder->on_audio(cache_sh_audio)) != srs_success) {
return srs_error_wrap(err, "forward audio sh");
}
return err;
}
srs_error_t SrsOriginHub::on_dvr_request_sh()
{
srs_error_t err = srs_success;
SrsSharedPtrMessage* cache_metadata = source->meta->data();
SrsSharedPtrMessage* cache_sh_video = source->meta->vsh();
SrsSharedPtrMessage* cache_sh_audio = source->meta->ash();
// feed the dvr the metadata/sequence header,
// when reload to start dvr, dvr will never get the sequence header in stream,
// use the SrsLiveSource.on_dvr_request_sh to push the sequence header to DVR.
if (cache_metadata && (err = dvr->on_meta_data(cache_metadata)) != srs_success) {
return srs_error_wrap(err, "dvr metadata");
}
if (cache_sh_video) {
if ((err = dvr->on_video(cache_sh_video, source->meta->vsh_format())) != srs_success) {
return srs_error_wrap(err, "dvr video");
}
}
if (cache_sh_audio) {
if ((err = dvr->on_audio(cache_sh_audio, source->meta->ash_format())) != srs_success) {
return srs_error_wrap(err, "dvr audio");
}
}
return err;
}
srs_error_t SrsOriginHub::on_reload_vhost_forward(string vhost)
{
srs_error_t err = srs_success;
if (req_->vhost != vhost) {
return err;
}
// TODO: FIXME: maybe should ignore when publish already stopped?
// forwarders
destroy_forwarders();
// Don't start forwarders when source is not active.
if (!is_active) {
return err;
}
if ((err = create_forwarders()) != srs_success) {
return srs_error_wrap(err, "create forwarders");
}
srs_trace("vhost %s forwarders reload success", vhost.c_str());
return err;
}
srs_error_t SrsOriginHub::on_reload_vhost_dash(string vhost)
{
srs_error_t err = srs_success;
if (req_->vhost != vhost) {
return err;
}
dash->on_unpublish();
// Don't start DASH when source is not active.
if (!is_active) {
return err;
}
if ((err = dash->on_publish()) != srs_success) {
return srs_error_wrap(err, "dash start publish");
}
SrsSharedPtrMessage* cache_sh_video = source->meta->vsh();
if (cache_sh_video) {
if ((err = format->on_video(cache_sh_video)) != srs_success) {
return srs_error_wrap(err, "format on_video");
}
if ((err = dash->on_video(cache_sh_video, format)) != srs_success) {
return srs_error_wrap(err, "dash on_video");
}
}
SrsSharedPtrMessage* cache_sh_audio = source->meta->ash();
if (cache_sh_audio) {
if ((err = format->on_audio(cache_sh_audio)) != srs_success) {
return srs_error_wrap(err, "format on_audio");
}
if ((err = dash->on_audio(cache_sh_audio, format)) != srs_success) {
return srs_error_wrap(err, "dash on_audio");
}
}
return err;
}
srs_error_t SrsOriginHub::on_reload_vhost_hls(string vhost)
{
srs_error_t err = srs_success;
if (req_->vhost != vhost) {
return err;
}
// TODO: FIXME: maybe should ignore when publish already stopped?
hls->on_unpublish();
// Don't start HLS when source is not active.
if (!is_active) {
return err;
}
if ((err = hls->on_publish()) != srs_success) {
return srs_error_wrap(err, "hls publish failed");
}
srs_trace("vhost %s hls reload success", vhost.c_str());
// when publish, don't need to fetch sequence header, which is old and maybe corrupt.
// when reload, we must fetch the sequence header from source cache.
// notice the source to get the cached sequence header.
// when reload to start hls, hls will never get the sequence header in stream,
// use the SrsLiveSource.on_hls_start to push the sequence header to HLS.
SrsSharedPtrMessage* cache_sh_video = source->meta->vsh();
if (cache_sh_video) {
if ((err = format->on_video(cache_sh_video)) != srs_success) {
return srs_error_wrap(err, "format on_video");
}
if ((err = hls->on_video(cache_sh_video, format)) != srs_success) {
return srs_error_wrap(err, "hls on_video");
}
}
SrsSharedPtrMessage* cache_sh_audio = source->meta->ash();
if (cache_sh_audio) {
if ((err = format->on_audio(cache_sh_audio)) != srs_success) {
return srs_error_wrap(err, "format on_audio");
}
if ((err = hls->on_audio(cache_sh_audio, format)) != srs_success) {
return srs_error_wrap(err, "hls on_audio");
}
}
return err;
}
srs_error_t SrsOriginHub::on_reload_vhost_hds(string vhost)
{
srs_error_t err = srs_success;
if (req_->vhost != vhost) {
return err;
}
// TODO: FIXME: maybe should ignore when publish already stopped?
#ifdef SRS_HDS
hds->on_unpublish();
// Don't start HDS when source is not active.
if (!is_active) {
return err;
}
if ((err = hds->on_publish(req)) != srs_success) {
return srs_error_wrap(err, "hds publish failed");
}
srs_trace("vhost %s hds reload success", vhost.c_str());
#endif
return err;
}
srs_error_t SrsOriginHub::on_reload_vhost_dvr(string vhost)
{
srs_error_t err = srs_success;
if (req_->vhost != vhost) {
return err;
}
// TODO: FIXME: maybe should ignore when publish already stopped?
// cleanup dvr
dvr->on_unpublish();
// Don't start DVR when source is not active.
if (!is_active) {
return err;
}
// reinitialize the dvr, update plan.
if ((err = dvr->initialize(this, req_)) != srs_success) {
return srs_error_wrap(err, "reload dvr");
}
// start to publish by new plan.
if ((err = dvr->on_publish(req_)) != srs_success) {
return srs_error_wrap(err, "dvr publish failed");
}
if ((err = on_dvr_request_sh()) != srs_success) {
return srs_error_wrap(err, "request sh");
}
srs_trace("vhost %s dvr reload success", vhost.c_str());
return err;
}
srs_error_t SrsOriginHub::on_reload_vhost_transcode(string vhost)
{
srs_error_t err = srs_success;
if (req_->vhost != vhost) {
return err;
}
// TODO: FIXME: maybe should ignore when publish already stopped?
encoder->on_unpublish();
// Don't start transcode when source is not active.
if (!is_active) {
return err;
}
if ((err = encoder->on_publish(req_)) != srs_success) {
return srs_error_wrap(err, "start encoder failed");
}
srs_trace("vhost %s transcode reload success", vhost.c_str());
return err;
}
srs_error_t SrsOriginHub::on_reload_vhost_exec(string vhost)
{
srs_error_t err = srs_success;
if (req_->vhost != vhost) {
return err;
}
// TODO: FIXME: maybe should ignore when publish already stopped?
ng_exec->on_unpublish();
// Don't start exec when source is not active.
if (!is_active) {
return err;
}
if ((err = ng_exec->on_publish(req_)) != srs_success) {
return srs_error_wrap(err, "start exec failed");
}
srs_trace("vhost %s exec reload success", vhost.c_str());
return err;
}
srs_error_t SrsOriginHub::create_forwarders()
{
srs_error_t err = srs_success;
if (!_srs_config->get_forward_enabled(req_->vhost)) {
return err;
}
// For backend config
// If backend is enabled and applied, ignore destination.
bool applied_backend_server = false;
if ((err = create_backend_forwarders(applied_backend_server)) != srs_success) {
return srs_error_wrap(err, "create backend applied=%d", applied_backend_server);
}
// Already applied backend server, ignore destination.
if (applied_backend_server) {
return err;
}
// For destanition config
SrsConfDirective* conf = _srs_config->get_forwards(req_->vhost);
for (int i = 0; conf && i < (int)conf->args.size(); i++) {
std::string forward_server = conf->args.at(i);
SrsForwarder* forwarder = new SrsForwarder(this);
forwarders.push_back(forwarder);
// initialize the forwarder with request.
if ((err = forwarder->initialize(req_, forward_server)) != srs_success) {
return srs_error_wrap(err, "init forwarder");
}
srs_utime_t queue_size = _srs_config->get_queue_length(req_->vhost);
forwarder->set_queue_size(queue_size);
if ((err = forwarder->on_publish()) != srs_success) {
return srs_error_wrap(err, "start forwarder failed, vhost=%s, app=%s, stream=%s, forward-to=%s",
req_->vhost.c_str(), req_->app.c_str(), req_->stream.c_str(), forward_server.c_str());
}
}
return err;
}
srs_error_t SrsOriginHub::create_backend_forwarders(bool& applied)
{
srs_error_t err = srs_success;
// default not configure backend service
applied = false;
SrsConfDirective* conf = _srs_config->get_forward_backend(req_->vhost);
if (!conf || conf->arg0().empty()) {
return err;
}
// configure backend service
applied = true;
// only get first backend url
std::string backend_url = conf->arg0();
// get urls on forward backend
std::vector<std::string> urls;
if ((err = SrsHttpHooks::on_forward_backend(backend_url, req_, urls)) != srs_success) {
return srs_error_wrap(err, "get forward backend failed, backend=%s", backend_url.c_str());
}
// create forwarders by urls
std::vector<std::string>::iterator it;
for (it = urls.begin(); it != urls.end(); ++it) {
std::string url = *it;
// create temp Request by url
SrsRequest* req = new SrsRequest();
SrsAutoFree(SrsRequest, req);
srs_parse_rtmp_url(url, req->tcUrl, req->stream);
srs_discovery_tc_url(req->tcUrl, req->schema, req->host, req->vhost, req->app, req->stream, req->port, req->param);
// create forwarder
SrsForwarder* forwarder = new SrsForwarder(this);
forwarders.push_back(forwarder);
std::stringstream forward_server;
forward_server << req->host << ":" << req->port;
// initialize the forwarder with request.
if ((err = forwarder->initialize(req, forward_server.str())) != srs_success) {
return srs_error_wrap(err, "init backend forwarder failed, forward-to=%s", forward_server.str().c_str());
}
srs_utime_t queue_size = _srs_config->get_queue_length(req_->vhost);
forwarder->set_queue_size(queue_size);
if ((err = forwarder->on_publish()) != srs_success) {
return srs_error_wrap(err, "start backend forwarder failed, vhost=%s, app=%s, stream=%s, forward-to=%s",
req_->vhost.c_str(), req_->app.c_str(), req_->stream.c_str(), forward_server.str().c_str());
}
}
return err;
}
void SrsOriginHub::destroy_forwarders()
{
std::vector<SrsForwarder*>::iterator it;
for (it = forwarders.begin(); it != forwarders.end(); ++it) {
SrsForwarder* forwarder = *it;
forwarder->on_unpublish();
srs_freep(forwarder);
}
forwarders.clear();
}
SrsMetaCache::SrsMetaCache()
{
meta = video = audio = NULL;
previous_video = previous_audio = NULL;
vformat = new SrsRtmpFormat();
aformat = new SrsRtmpFormat();
}
SrsMetaCache::~SrsMetaCache()
{
dispose();
srs_freep(vformat);
srs_freep(aformat);
}
void SrsMetaCache::dispose()
{
clear();
srs_freep(previous_video);
srs_freep(previous_audio);
}
void SrsMetaCache::clear()
{
srs_freep(meta);
srs_freep(video);
srs_freep(audio);
}
SrsSharedPtrMessage* SrsMetaCache::data()
{
return meta;
}
SrsSharedPtrMessage* SrsMetaCache::vsh()
{
return video;
}
SrsFormat* SrsMetaCache::vsh_format()
{
return vformat;
}
SrsSharedPtrMessage* SrsMetaCache::ash()
{
return audio;
}
SrsFormat* SrsMetaCache::ash_format()
{
return aformat;
}
srs_error_t SrsMetaCache::dumps(SrsLiveConsumer* consumer, bool atc, SrsRtmpJitterAlgorithm ag, bool dm, bool ds)
{
srs_error_t err = srs_success;
// copy metadata.
if (dm && meta && (err = consumer->enqueue(meta, atc, ag)) != srs_success) {
return srs_error_wrap(err, "enqueue metadata");
}
// copy sequence header
// copy audio sequence first, for hls to fast parse the "right" audio codec.
// @see https://github.com/ossrs/srs/issues/301
if (ds && audio && (err = consumer->enqueue(audio, atc, ag)) != srs_success) {
return srs_error_wrap(err, "enqueue audio sh");
}
if (ds && video && (err = consumer->enqueue(video, atc, ag)) != srs_success) {
return srs_error_wrap(err, "enqueue video sh");
}
return err;
}
SrsSharedPtrMessage* SrsMetaCache::previous_vsh()
{
return previous_video;
}
SrsSharedPtrMessage* SrsMetaCache::previous_ash()
{
return previous_audio;
}
void SrsMetaCache::update_previous_vsh()
{
srs_freep(previous_video);
previous_video = video? video->copy() : NULL;
}
void SrsMetaCache::update_previous_ash()
{
srs_freep(previous_audio);
previous_audio = audio? audio->copy() : NULL;
}
srs_error_t SrsMetaCache::update_data(SrsMessageHeader* header, SrsOnMetaDataPacket* metadata, bool& updated)
{
updated = false;
srs_error_t err = srs_success;
SrsAmf0Any* prop = NULL;
// when exists the duration, remove it to make ExoPlayer happy.
if (metadata->metadata->get_property("duration") != NULL) {
metadata->metadata->remove("duration");
}
// generate metadata info to print
std::stringstream ss;
if ((prop = metadata->metadata->ensure_property_number("width")) != NULL) {
ss << ", width=" << (int)prop->to_number();
}
if ((prop = metadata->metadata->ensure_property_number("height")) != NULL) {
ss << ", height=" << (int)prop->to_number();
}
if ((prop = metadata->metadata->ensure_property_number("videocodecid")) != NULL) {
ss << ", vcodec=" << (int)prop->to_number();
}
if ((prop = metadata->metadata->ensure_property_number("audiocodecid")) != NULL) {
ss << ", acodec=" << (int)prop->to_number();
}
srs_trace("got metadata%s", ss.str().c_str());
// add server info to metadata
metadata->metadata->set("server", SrsAmf0Any::str(RTMP_SIG_SRS_SERVER));
// version, for example, 1.0.0
// add version to metadata, please donot remove it, for debug.
metadata->metadata->set("server_version", SrsAmf0Any::str(RTMP_SIG_SRS_VERSION));
// encode the metadata to payload
int size = 0;
char* payload = NULL;
if ((err = metadata->encode(size, payload)) != srs_success) {
return srs_error_wrap(err, "encode metadata");
}
if (size <= 0) {
srs_warn("ignore the invalid metadata. size=%d", size);
return err;
}
// create a shared ptr message.
srs_freep(meta);
meta = new SrsSharedPtrMessage();
updated = true;
// dump message to shared ptr message.
// the payload/size managed by cache_metadata, user should not free it.
if ((err = meta->create(header, payload, size)) != srs_success) {
return srs_error_wrap(err, "create metadata");
}
return err;
}
srs_error_t SrsMetaCache::update_ash(SrsSharedPtrMessage* msg)
{
srs_freep(audio);
audio = msg->copy();
update_previous_ash();
return aformat->on_audio(msg);
}
srs_error_t SrsMetaCache::update_vsh(SrsSharedPtrMessage* msg)
{
srs_freep(video);
video = msg->copy();
update_previous_vsh();
return vformat->on_video(msg);
}
SrsLiveSourceManager* _srs_sources = NULL;
SrsLiveSourceManager::SrsLiveSourceManager()
{
lock = srs_mutex_new();
timer_ = new SrsHourGlass("sources", this, 1 * SRS_UTIME_SECONDS);
}
SrsLiveSourceManager::~SrsLiveSourceManager()
{
srs_mutex_destroy(lock);
srs_freep(timer_);
}
srs_error_t SrsLiveSourceManager::initialize()
{
return setup_ticks();
}
srs_error_t SrsLiveSourceManager::fetch_or_create(SrsRequest* r, ISrsLiveSourceHandler* h, SrsLiveSource** pps)
{
srs_error_t err = srs_success;
// Use lock to protect coroutine switch.
// @bug https://github.com/ossrs/srs/issues/1230
// TODO: FIXME: Use smaller lock.
SrsLocker(lock);
SrsLiveSource* source = NULL;
if ((source = fetch(r)) != NULL) {
// we always update the request of resource,
// for origin auth is on, the token in request maybe invalid,
// and we only need to update the token of request, it's simple.
source->update_auth(r);
*pps = source;
return err;
}
string stream_url = r->get_stream_url();
string vhost = r->vhost;
// should always not exists for create a source.
srs_assert (pool.find(stream_url) == pool.end());
srs_trace("new source, stream_url=%s", stream_url.c_str());
source = new SrsLiveSource();
if ((err = source->initialize(r, h)) != srs_success) {
err = srs_error_wrap(err, "init source %s", r->get_stream_url().c_str());
goto failed;
}
pool[stream_url] = source;
*pps = source;
return err;
failed:
srs_freep(source);
return err;
}
SrsLiveSource* SrsLiveSourceManager::fetch(SrsRequest* r)
{
SrsLiveSource* source = NULL;
string stream_url = r->get_stream_url();
if (pool.find(stream_url) == pool.end()) {
return NULL;
}
source = pool[stream_url];
return source;
}
void SrsLiveSourceManager::dispose()
{
std::map<std::string, SrsLiveSource*>::iterator it;
for (it = pool.begin(); it != pool.end(); ++it) {
SrsLiveSource* source = it->second;
source->dispose();
}
return;
}
srs_error_t SrsLiveSourceManager::setup_ticks()
{
srs_error_t err = srs_success;
if ((err = timer_->tick(1, 1 * SRS_UTIME_SECONDS)) != srs_success) {
return srs_error_wrap(err, "tick");
}
if ((err = timer_->start()) != srs_success) {
return srs_error_wrap(err, "timer");
}
return err;
}
srs_error_t SrsLiveSourceManager::notify(int event, srs_utime_t interval, srs_utime_t tick)
{
srs_error_t err = srs_success;
std::map<std::string, SrsLiveSource*>::iterator it;
for (it = pool.begin(); it != pool.end();) {
SrsLiveSource* source = it->second;
// Do cycle source to cleanup components, such as hls dispose.
if ((err = source->cycle()) != srs_success) {
return srs_error_wrap(err, "source=%s/%s cycle", source->source_id().c_str(), source->pre_source_id().c_str());
}
// TODO: FIXME: support source cleanup.
// @see https://github.com/ossrs/srs/issues/713
// @see https://github.com/ossrs/srs/issues/714
#if 0
// When source expired, remove it.
if (source->expired()) {
int cid = source->source_id();
if (cid == -1 && source->pre_source_id() > 0) {
cid = source->pre_source_id();
}
if (cid > 0) {
_srs_context->set_id(cid);
}
srs_trace("cleanup die source, total=%d", (int)pool.size());
srs_freep(source);
pool.erase(it++);
} else {
++it;
}
#else
++it;
#endif
}
return err;
}
void SrsLiveSourceManager::destroy()
{
std::map<std::string, SrsLiveSource*>::iterator it;
for (it = pool.begin(); it != pool.end(); ++it) {
SrsLiveSource* source = it->second;
srs_freep(source);
}
pool.clear();
}
ISrsLiveSourceBridger::ISrsLiveSourceBridger()
{
}
ISrsLiveSourceBridger::~ISrsLiveSourceBridger()
{
}
SrsLiveSource::SrsLiveSource()
{
req = NULL;
jitter_algorithm = SrsRtmpJitterAlgorithmOFF;
mix_correct = false;
mix_queue = new SrsMixQueue();
_can_publish = true;
die_at = 0;
handler = NULL;
bridger_ = NULL;
play_edge = new SrsPlayEdge();
publish_edge = new SrsPublishEdge();
gop_cache = new SrsGopCache();
hub = new SrsOriginHub();
meta = new SrsMetaCache();
is_monotonically_increase = false;
last_packet_time = 0;
_srs_config->subscribe(this);
atc = false;
}
SrsLiveSource::~SrsLiveSource()
{
_srs_config->unsubscribe(this);
// never free the consumers,
// for all consumers are auto free.
consumers.clear();
srs_freep(hub);
srs_freep(meta);
srs_freep(mix_queue);
srs_freep(play_edge);
srs_freep(publish_edge);
srs_freep(gop_cache);
srs_freep(req);
srs_freep(bridger_);
}
void SrsLiveSource::dispose()
{
hub->dispose();
meta->dispose();
gop_cache->dispose();
}
srs_error_t SrsLiveSource::cycle()
{
srs_error_t err = hub->cycle();
if (err != srs_success) {
return srs_error_wrap(err, "hub cycle");
}
return srs_success;
}
bool SrsLiveSource::expired()
{
// unknown state?
if (die_at == 0) {
return false;
}
// still publishing?
if (!_can_publish || !publish_edge->can_publish()) {
return false;
}
// has any consumers?
if (!consumers.empty()) {
return false;
}
srs_utime_t now = srs_get_system_time();
if (now > die_at + SRS_SOURCE_CLEANUP) {
return true;
}
return false;
}
srs_error_t SrsLiveSource::initialize(SrsRequest* r, ISrsLiveSourceHandler* h)
{
srs_error_t err = srs_success;
srs_assert(h);
srs_assert(!req);
handler = h;
req = r->copy();
atc = _srs_config->get_atc(req->vhost);
if ((err = hub->initialize(this, req)) != srs_success) {
return srs_error_wrap(err, "hub");
}
if ((err = play_edge->initialize(this, req)) != srs_success) {
return srs_error_wrap(err, "edge(play)");
}
if ((err = publish_edge->initialize(this, req)) != srs_success) {
return srs_error_wrap(err, "edge(publish)");
}
srs_utime_t queue_size = _srs_config->get_queue_length(req->vhost);
publish_edge->set_queue_size(queue_size);
jitter_algorithm = (SrsRtmpJitterAlgorithm)_srs_config->get_time_jitter(req->vhost);
mix_correct = _srs_config->get_mix_correct(req->vhost);
return err;
}
void SrsLiveSource::set_bridger(ISrsLiveSourceBridger* v)
{
srs_freep(bridger_);
bridger_ = v;
}
srs_error_t SrsLiveSource::on_reload_vhost_play(string vhost)
{
srs_error_t err = srs_success;
if (req->vhost != vhost) {
return err;
}
// time_jitter
jitter_algorithm = (SrsRtmpJitterAlgorithm)_srs_config->get_time_jitter(req->vhost);
// mix_correct
if (true) {
bool v = _srs_config->get_mix_correct(req->vhost);
// when changed, clear the mix queue.
if (v != mix_correct) {
mix_queue->clear();
}
mix_correct = v;
}
// atc changed.
if (true) {
bool v = _srs_config->get_atc(vhost);
if (v != atc) {
srs_warn("vhost %s atc changed to %d, connected client may corrupt.", vhost.c_str(), v);
gop_cache->clear();
}
atc = v;
}
// gop cache changed.
if (true) {
bool v = _srs_config->get_gop_cache(vhost);
if (v != gop_cache->enabled()) {
string url = req->get_stream_url();
srs_trace("vhost %s gop_cache changed to %d, source url=%s", vhost.c_str(), v, url.c_str());
gop_cache->set(v);
}
}
// queue length
if (true) {
srs_utime_t v = _srs_config->get_queue_length(req->vhost);
if (true) {
std::vector<SrsLiveConsumer*>::iterator it;
for (it = consumers.begin(); it != consumers.end(); ++it) {
SrsLiveConsumer* consumer = *it;
consumer->set_queue_size(v);
}
srs_trace("consumers reload queue size success.");
}
// TODO: FIXME: https://github.com/ossrs/srs/issues/742#issuecomment-273656897
// TODO: FIXME: support queue size.
#if 0
if (true) {
std::vector<SrsForwarder*>::iterator it;
for (it = forwarders.begin(); it != forwarders.end(); ++it) {
SrsForwarder* forwarder = *it;
forwarder->set_queue_size(v);
}
srs_trace("forwarders reload queue size success.");
}
if (true) {
publish_edge->set_queue_size(v);
srs_trace("publish_edge reload queue size success.");
}
#endif
}
return err;
}
srs_error_t SrsLiveSource::on_source_id_changed(SrsContextId id)
{
srs_error_t err = srs_success;
if (!_source_id.compare(id)) {
return err;
}
if (_pre_source_id.empty()) {
_pre_source_id = id;
}
_source_id = id;
// notice all consumer
std::vector<SrsLiveConsumer*>::iterator it;
for (it = consumers.begin(); it != consumers.end(); ++it) {
SrsLiveConsumer* consumer = *it;
consumer->update_source_id();
}
return err;
}
SrsContextId SrsLiveSource::source_id()
{
return _source_id;
}
SrsContextId SrsLiveSource::pre_source_id()
{
return _pre_source_id;
}
bool SrsLiveSource::inactive()
{
return _can_publish;
}
void SrsLiveSource::update_auth(SrsRequest* r)
{
req->update_auth(r);
}
bool SrsLiveSource::can_publish(bool is_edge)
{
// TODO: FIXME: Should check the status of bridger.
if (is_edge) {
return publish_edge->can_publish();
}
return _can_publish;
}
srs_error_t SrsLiveSource::on_meta_data(SrsCommonMessage* msg, SrsOnMetaDataPacket* metadata)
{
srs_error_t err = srs_success;
// if allow atc_auto and bravo-atc detected, open atc for vhost.
SrsAmf0Any* prop = NULL;
atc = _srs_config->get_atc(req->vhost);
if (_srs_config->get_atc_auto(req->vhost)) {
if ((prop = metadata->metadata->get_property("bravo_atc")) != NULL) {
if (prop->is_string() && prop->to_str() == "true") {
atc = true;
}
}
}
// Update the meta cache.
bool updated = false;
if ((err = meta->update_data(&msg->header, metadata, updated)) != srs_success) {
return srs_error_wrap(err, "update metadata");
}
if (!updated) {
return err;
}
// when already got metadata, drop when reduce sequence header.
bool drop_for_reduce = false;
if (meta->data() && _srs_config->get_reduce_sequence_header(req->vhost)) {
drop_for_reduce = true;
srs_warn("drop for reduce sh metadata, size=%d", msg->size);
}
// copy to all consumer
if (!drop_for_reduce) {
std::vector<SrsLiveConsumer*>::iterator it;
for (it = consumers.begin(); it != consumers.end(); ++it) {
SrsLiveConsumer* consumer = *it;
if ((err = consumer->enqueue(meta->data(), atc, jitter_algorithm)) != srs_success) {
return srs_error_wrap(err, "consume metadata");
}
}
}
// Copy to hub to all utilities.
return hub->on_meta_data(meta->data(), metadata);
}
srs_error_t SrsLiveSource::on_audio(SrsCommonMessage* shared_audio)
{
srs_error_t err = srs_success;
// monotically increase detect.
if (!mix_correct && is_monotonically_increase) {
if (last_packet_time > 0 && shared_audio->header.timestamp < last_packet_time) {
is_monotonically_increase = false;
srs_warn("AUDIO: stream not monotonically increase, please open mix_correct.");
}
}
last_packet_time = shared_audio->header.timestamp;
// convert shared_audio to msg, user should not use shared_audio again.
// the payload is transfer to msg, and set to NULL in shared_audio.
SrsSharedPtrMessage msg;
if ((err = msg.create(shared_audio)) != srs_success) {
return srs_error_wrap(err, "create message");
}
// directly process the audio message.
if (!mix_correct) {
return on_audio_imp(&msg);
}
// insert msg to the queue.
mix_queue->push(msg.copy());
// fetch someone from mix queue.
SrsSharedPtrMessage* m = mix_queue->pop();
if (!m) {
return err;
}
// consume the monotonically increase message.
if (m->is_audio()) {
err = on_audio_imp(m);
} else {
err = on_video_imp(m);
}
srs_freep(m);
return err;
}
srs_error_t SrsLiveSource::on_audio_imp(SrsSharedPtrMessage* msg)
{
srs_error_t err = srs_success;
bool is_aac_sequence_header = SrsFlvAudio::sh(msg->payload, msg->size);
bool is_sequence_header = is_aac_sequence_header;
// whether consumer should drop for the duplicated sequence header.
bool drop_for_reduce = false;
if (is_sequence_header && meta->previous_ash() && _srs_config->get_reduce_sequence_header(req->vhost)) {
if (meta->previous_ash()->size == msg->size) {
drop_for_reduce = srs_bytes_equals(meta->previous_ash()->payload, msg->payload, msg->size);
srs_warn("drop for reduce sh audio, size=%d", msg->size);
}
}
// Copy to hub to all utilities.
if ((err = hub->on_audio(msg)) != srs_success) {
return srs_error_wrap(err, "consume audio");
}
// For bridger to consume the message.
if (bridger_ && (err = bridger_->on_audio(msg)) != srs_success) {
return srs_error_wrap(err, "bridger consume audio");
}
// copy to all consumer
if (!drop_for_reduce) {
for (int i = 0; i < (int)consumers.size(); i++) {
SrsLiveConsumer* consumer = consumers.at(i);
if ((err = consumer->enqueue(msg, atc, jitter_algorithm)) != srs_success) {
return srs_error_wrap(err, "consume message");
}
}
}
// cache the sequence header of aac, or first packet of mp3.
// for example, the mp3 is used for hls to write the "right" audio codec.
// TODO: FIXME: to refine the stream info system.
if (is_aac_sequence_header || !meta->ash()) {
if ((err = meta->update_ash(msg)) != srs_success) {
return srs_error_wrap(err, "meta consume audio");
}
}
// when sequence header, donot push to gop cache and adjust the timestamp.
if (is_sequence_header) {
return err;
}
// cache the last gop packets
if ((err = gop_cache->cache(msg)) != srs_success) {
return srs_error_wrap(err, "gop cache consume audio");
}
// if atc, update the sequence header to abs time.
if (atc) {
if (meta->ash()) {
meta->ash()->timestamp = msg->timestamp;
}
if (meta->data()) {
meta->data()->timestamp = msg->timestamp;
}
}
return err;
}
srs_error_t SrsLiveSource::on_video(SrsCommonMessage* shared_video)
{
srs_error_t err = srs_success;
// monotically increase detect.
if (!mix_correct && is_monotonically_increase) {
if (last_packet_time > 0 && shared_video->header.timestamp < last_packet_time) {
is_monotonically_increase = false;
srs_warn("VIDEO: stream not monotonically increase, please open mix_correct.");
}
}
last_packet_time = shared_video->header.timestamp;
// drop any unknown header video.
// @see https://github.com/ossrs/srs/issues/421
if (!SrsFlvVideo::acceptable(shared_video->payload, shared_video->size)) {
char b0 = 0x00;
if (shared_video->size > 0) {
b0 = shared_video->payload[0];
}
srs_warn("drop unknown header video, size=%d, bytes[0]=%#x", shared_video->size, b0);
return err;
}
// convert shared_video to msg, user should not use shared_video again.
// the payload is transfer to msg, and set to NULL in shared_video.
SrsSharedPtrMessage msg;
if ((err = msg.create(shared_video)) != srs_success) {
return srs_error_wrap(err, "create message");
}
// directly process the video message.
if (!mix_correct) {
return on_video_imp(&msg);
}
// insert msg to the queue.
mix_queue->push(msg.copy());
// fetch someone from mix queue.
SrsSharedPtrMessage* m = mix_queue->pop();
if (!m) {
return err;
}
// consume the monotonically increase message.
if (m->is_audio()) {
err = on_audio_imp(m);
} else {
err = on_video_imp(m);
}
srs_freep(m);
return err;
}
srs_error_t SrsLiveSource::on_video_imp(SrsSharedPtrMessage* msg)
{
srs_error_t err = srs_success;
bool is_sequence_header = SrsFlvVideo::sh(msg->payload, msg->size);
// whether consumer should drop for the duplicated sequence header.
bool drop_for_reduce = false;
if (is_sequence_header && meta->previous_vsh() && _srs_config->get_reduce_sequence_header(req->vhost)) {
if (meta->previous_vsh()->size == msg->size) {
drop_for_reduce = srs_bytes_equals(meta->previous_vsh()->payload, msg->payload, msg->size);
srs_warn("drop for reduce sh video, size=%d", msg->size);
}
}
// cache the sequence header if h264
// donot cache the sequence header to gop_cache, return here.
if (is_sequence_header && (err = meta->update_vsh(msg)) != srs_success) {
return srs_error_wrap(err, "meta update video");
}
// Copy to hub to all utilities.
if ((err = hub->on_video(msg, is_sequence_header)) != srs_success) {
return srs_error_wrap(err, "hub consume video");
}
// For bridger to consume the message.
if (bridger_ && (err = bridger_->on_video(msg)) != srs_success) {
return srs_error_wrap(err, "bridger consume video");
}
// copy to all consumer
if (!drop_for_reduce) {
for (int i = 0; i < (int)consumers.size(); i++) {
SrsLiveConsumer* consumer = consumers.at(i);
if ((err = consumer->enqueue(msg, atc, jitter_algorithm)) != srs_success) {
return srs_error_wrap(err, "consume video");
}
}
}
// when sequence header, donot push to gop cache and adjust the timestamp.
if (is_sequence_header) {
return err;
}
// cache the last gop packets
if ((err = gop_cache->cache(msg)) != srs_success) {
return srs_error_wrap(err, "gop cache consume vdieo");
}
// if atc, update the sequence header to abs time.
if (atc) {
if (meta->vsh()) {
meta->vsh()->timestamp = msg->timestamp;
}
if (meta->data()) {
meta->data()->timestamp = msg->timestamp;
}
}
return err;
}
srs_error_t SrsLiveSource::on_aggregate(SrsCommonMessage* msg)
{
srs_error_t err = srs_success;
SrsBuffer* stream = new SrsBuffer(msg->payload, msg->size);
SrsAutoFree(SrsBuffer, stream);
// the aggregate message always use abs time.
int delta = -1;
while (!stream->empty()) {
if (!stream->require(1)) {
return srs_error_new(ERROR_RTMP_AGGREGATE, "aggregate");
}
int8_t type = stream->read_1bytes();
if (!stream->require(3)) {
return srs_error_new(ERROR_RTMP_AGGREGATE, "aggregate");
}
int32_t data_size = stream->read_3bytes();
if (data_size < 0) {
return srs_error_new(ERROR_RTMP_AGGREGATE, "aggregate size");
}
if (!stream->require(3)) {
return srs_error_new(ERROR_RTMP_AGGREGATE, "aggregate time");
}
int32_t timestamp = stream->read_3bytes();
if (!stream->require(1)) {
return srs_error_new(ERROR_RTMP_AGGREGATE, "aggregate time(high bits)");
}
int32_t time_h = stream->read_1bytes();
timestamp |= time_h<<24;
timestamp &= 0x7FFFFFFF;
// adjust abs timestamp in aggregate msg.
// only -1 means uninitialized delta.
if (delta == -1) {
delta = (int)msg->header.timestamp - (int)timestamp;
}
timestamp += delta;
if (!stream->require(3)) {
return srs_error_new(ERROR_RTMP_AGGREGATE, "aggregate stream id");
}
int32_t stream_id = stream->read_3bytes();
if (data_size > 0 && !stream->require(data_size)) {
return srs_error_new(ERROR_RTMP_AGGREGATE, "aggregate data");
}
// to common message.
SrsCommonMessage o;
o.header.message_type = type;
o.header.payload_length = data_size;
o.header.timestamp_delta = timestamp;
o.header.timestamp = timestamp;
o.header.stream_id = stream_id;
o.header.perfer_cid = msg->header.perfer_cid;
if (data_size > 0) {
o.size = data_size;
o.payload = new char[o.size];
stream->read_bytes(o.payload, o.size);
}
if (!stream->require(4)) {
return srs_error_new(ERROR_RTMP_AGGREGATE, "aggregate previous tag size");
}
stream->read_4bytes();
// process parsed message
if (o.header.is_audio()) {
if ((err = on_audio(&o)) != srs_success) {
return srs_error_wrap(err, "consume audio");
}
} else if (o.header.is_video()) {
if ((err = on_video(&o)) != srs_success) {
return srs_error_wrap(err, "consume video");
}
}
}
return err;
}
srs_error_t SrsLiveSource::on_publish()
{
srs_error_t err = srs_success;
// update the request object.
srs_assert(req);
_can_publish = false;
// whatever, the publish thread is the source or edge source,
// save its id to srouce id.
if ((err = on_source_id_changed(_srs_context->get_id())) != srs_success) {
return srs_error_wrap(err, "source id change");
}
// reset the mix queue.
mix_queue->clear();
// Reset the metadata cache, to make VLC happy when disable/enable stream.
// @see https://github.com/ossrs/srs/issues/1630#issuecomment-597979448
meta->clear();
// detect the monotonically again.
is_monotonically_increase = true;
last_packet_time = 0;
// Notify the hub about the publish event.
if ((err = hub->on_publish()) != srs_success) {
return srs_error_wrap(err, "hub publish");
}
// notify the handler.
srs_assert(handler);
if ((err = handler->on_publish(this, req)) != srs_success) {
return srs_error_wrap(err, "handle publish");
}
if (bridger_ && (err = bridger_->on_publish()) != srs_success) {
return srs_error_wrap(err, "bridger publish");
}
SrsStatistic* stat = SrsStatistic::instance();
stat->on_stream_publish(req, _source_id.c_str());
return err;
}
void SrsLiveSource::on_unpublish()
{
// ignore when already unpublished.
if (_can_publish) {
return;
}
// Notify the hub about the unpublish event.
hub->on_unpublish();
// only clear the gop cache,
// donot clear the sequence header, for it maybe not changed,
// when drop dup sequence header, drop the metadata also.
gop_cache->clear();
// Reset the metadata cache, to make VLC happy when disable/enable stream.
// @see https://github.com/ossrs/srs/issues/1630#issuecomment-597979448
meta->update_previous_vsh();
meta->update_previous_ash();
srs_trace("cleanup when unpublish");
_can_publish = true;
if (!_source_id.empty()) {
_pre_source_id = _source_id;
}
_source_id = SrsContextId();
// notify the handler.
srs_assert(handler);
SrsStatistic* stat = SrsStatistic::instance();
stat->on_stream_close(req);
handler->on_unpublish(this, req);
if (bridger_) {
bridger_->on_unpublish();
srs_freep(bridger_);
}
// no consumer, stream is die.
if (consumers.empty()) {
die_at = srs_get_system_time();
}
}
srs_error_t SrsLiveSource::create_consumer(SrsLiveConsumer*& consumer)
{
srs_error_t err = srs_success;
consumer = new SrsLiveConsumer(this);
consumers.push_back(consumer);
// for edge, when play edge stream, check the state
if (_srs_config->get_vhost_is_edge(req->vhost)) {
// notice edge to start for the first client.
if ((err = play_edge->on_client_play()) != srs_success) {
return srs_error_wrap(err, "play edge");
}
}
return err;
}
srs_error_t SrsLiveSource::consumer_dumps(SrsLiveConsumer* consumer, bool ds, bool dm, bool dg)
{
srs_error_t err = srs_success;
srs_utime_t queue_size = _srs_config->get_queue_length(req->vhost);
consumer->set_queue_size(queue_size);
// if atc, update the sequence header to gop cache time.
if (atc && !gop_cache->empty()) {
if (meta->data()) {
meta->data()->timestamp = srsu2ms(gop_cache->start_time());
}
if (meta->vsh()) {
meta->vsh()->timestamp = srsu2ms(gop_cache->start_time());
}
if (meta->ash()) {
meta->ash()->timestamp = srsu2ms(gop_cache->start_time());
}
}
// If stream is publishing, dumps the sequence header and gop cache.
if (hub->active()) {
// Copy metadata and sequence header to consumer.
if ((err = meta->dumps(consumer, atc, jitter_algorithm, dm, ds)) != srs_success) {
return srs_error_wrap(err, "meta dumps");
}
// copy gop cache to client.
if (dg && (err = gop_cache->dump(consumer, atc, jitter_algorithm)) != srs_success) {
return srs_error_wrap(err, "gop cache dumps");
}
}
// print status.
if (dg) {
srs_trace("create consumer, active=%d, queue_size=%.2f, jitter=%d", hub->active(), queue_size, jitter_algorithm);
} else {
srs_trace("create consumer, active=%d, ignore gop cache, jitter=%d", hub->active(), jitter_algorithm);
}
return err;
}
void SrsLiveSource::on_consumer_destroy(SrsLiveConsumer* consumer)
{
std::vector<SrsLiveConsumer*>::iterator it;
it = std::find(consumers.begin(), consumers.end(), consumer);
if (it != consumers.end()) {
consumers.erase(it);
}
if (consumers.empty()) {
play_edge->on_all_client_stop();
die_at = srs_get_system_time();
}
}
void SrsLiveSource::set_cache(bool enabled)
{
gop_cache->set(enabled);
}
SrsRtmpJitterAlgorithm SrsLiveSource::jitter()
{
return jitter_algorithm;
}
srs_error_t SrsLiveSource::on_edge_start_publish()
{
return publish_edge->on_client_publish();
}
// TODO: FIXME: Use edge strategy pattern.
srs_error_t SrsLiveSource::on_edge_proxy_publish(SrsCommonMessage* msg)
{
return publish_edge->on_proxy_publish(msg);
}
void SrsLiveSource::on_edge_proxy_unpublish()
{
publish_edge->on_proxy_unpublish();
}
string SrsLiveSource::get_curr_origin()
{
return play_edge->get_curr_origin();
}
|
/* Copyright (c) 2014-2017, ARM Limited and Contributors
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge,
* to any person obtaining a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "Shader.h"
#define LOG_TAG "libNative"
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
namespace MaliSDK
{
/* Please see header for the specification. */
void Shader::processShader(GLuint* shaderPtr, const char* shaderSourcePtr, GLint shaderType)
{
GLint compilationStatus = GL_FALSE;
/* Create shader and load into GL. */
*shaderPtr = GL_CHECK(glCreateShader(shaderType));
GL_CHECK(glShaderSource(*shaderPtr, 1, &shaderSourcePtr, NULL));
/* Try compiling the shader. */
GL_CHECK(glCompileShader(*shaderPtr));
GL_CHECK(glGetShaderiv(*shaderPtr, GL_COMPILE_STATUS, &compilationStatus));
/* Dump debug info (source and log) if compilation failed. */
if(compilationStatus != GL_TRUE)
{
GLint length;
char *debugSource = NULL;
char *errorLog = NULL;
/* Get shader source. */
GL_CHECK(glGetShaderiv(*shaderPtr, GL_SHADER_SOURCE_LENGTH, &length));
debugSource = (char *)malloc(length);
GL_CHECK(glGetShaderSource(*shaderPtr, length, NULL, debugSource));
LOGE("Debug source START:\n%s\nDebug source END\n\n", debugSource);
free(debugSource);
/* Now get the info log. */
GL_CHECK(glGetShaderiv(*shaderPtr, GL_INFO_LOG_LENGTH, &length));
errorLog = (char *)malloc(length);
GL_CHECK(glGetShaderInfoLog(*shaderPtr, length, NULL, errorLog));
LOGE("Log START:\n%s\nLog END\n\n", errorLog);
free(errorLog);
LOGE("Compilation FAILED!\n\n");
exit(1);
}
}
}
|
#include "CppML/CppML.hpp"
namespace PackExtractorTest {
void run() {
{
using T = ml::f<
ml::PackExtractor<
ml::Int<0>, ml::Int<1>, ml::Int<2>, ml::Int<3>, ml::Int<4>,
ml::Int<5>, ml::Int<6>, ml::Int<7>, ml::Int<8>, ml::Int<9>,
ml::Int<10>, ml::Int<11>, ml::Int<12>, ml::Int<13>, ml::Int<14>,
ml::Int<15>, ml::Int<16>, ml::Int<17>, ml::Int<18>, ml::Int<19>,
ml::Int<20>, ml::Int<21>, ml::Int<22>, ml::Int<23>, ml::Int<24>,
ml::Int<25>, ml::Int<26>, ml::Int<27>, ml::Int<28>, ml::Int<29>,
ml::Int<30>, ml::Int<31>, ml::Int<32>, ml::Int<33>, ml::Int<34>,
ml::Int<35>, ml::Int<36>, ml::Int<37>, ml::Int<38>>,
ml::Int<37>>;
static_assert(std::is_same<T, ml::Int<37>>::value,
"PackExtractor with a non-empty pack 37");
}
}
}; // namespace PackExtractorTest
|
/**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
#ifndef _TBLENUM_HXX
#define _TBLENUM_HXX
//fuers aendern der Tabellen/Spalten/Zeilen Breiten/Hoehen
typedef sal_uInt16 TblChgWidthHeightType;
namespace nsTblChgWidthHeightType
{
const TblChgWidthHeightType WH_COL_LEFT = 0;
const TblChgWidthHeightType WH_COL_RIGHT = 1;
const TblChgWidthHeightType WH_ROW_TOP = 2;
const TblChgWidthHeightType WH_ROW_BOTTOM = 3;
const TblChgWidthHeightType WH_CELL_LEFT = 4;
const TblChgWidthHeightType WH_CELL_RIGHT = 5;
const TblChgWidthHeightType WH_CELL_TOP = 6;
const TblChgWidthHeightType WH_CELL_BOTTOM = 7;
// folgende koennen hinein verodert werden
const TblChgWidthHeightType WH_FLAG_INSDEL = 0x4000; // Insert/Del-Modus: das Bigger-Flag
// besagt was passiert:
// bBigger -> Box wird entfernt
// !bBigger-> Box wird eingefuegt
const TblChgWidthHeightType WH_FLAG_BIGGER = 0x8000; // Box wird groesser -> sonst kleiner
}
enum TblChgMode
{
TBLFIX_CHGABS, // Tabelle feste Breite, den Nachbar andern
TBLFIX_CHGPROP, // Tabelle feste Breite, alle Nachbarn aendern
TBLVAR_CHGABS // Tabelle variable, alle Nachbarn aendern
};
enum SplitTbl_HeadlineOption
{
HEADLINE_NONE = 0, // lasse alles wie es ist
HEADLINE_BORDERCOPY, // von der davor obere Line der vorhergehen Line
HEADLINE_CNTNTCOPY, // kopiere die 1. Line komplett mit Inhalt
HEADLINE_BOXATTRCOPY, // kopiere von der 1. Line die Box Attribute
HEADLINE_BOXATRCOLLCOPY // kopiere von der 1. Line die Box Attribute
// und die Absatzvorlagen
};
enum TableMergeErr
{
TBLMERGE_OK,
TBLMERGE_NOSELECTION,
TBLMERGE_TOOCOMPLEX
};
#endif
|
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/protobuf/map_unittest.proto
#define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION
#include <google/protobuf/map_unittest.pb.h>
#include <algorithm>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/port.h>
#include <google/protobuf/stubs/once.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/wire_format_lite_inl.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/reflection_ops.h>
#include <google/protobuf/wire_format.h>
// @@protoc_insertion_point(includes)
namespace protobuf_unittest {
namespace {
const ::google::protobuf::Descriptor* TestMap_descriptor_ = NULL;
const ::google::protobuf::internal::GeneratedMessageReflection*
TestMap_reflection_ = NULL;
const ::google::protobuf::Descriptor* TestMap_MapInt32Int32Entry_descriptor_ = NULL;
const ::google::protobuf::Descriptor* TestMap_MapInt64Int64Entry_descriptor_ = NULL;
const ::google::protobuf::Descriptor* TestMap_MapUint32Uint32Entry_descriptor_ = NULL;
const ::google::protobuf::Descriptor* TestMap_MapUint64Uint64Entry_descriptor_ = NULL;
const ::google::protobuf::Descriptor* TestMap_MapSint32Sint32Entry_descriptor_ = NULL;
const ::google::protobuf::Descriptor* TestMap_MapSint64Sint64Entry_descriptor_ = NULL;
const ::google::protobuf::Descriptor* TestMap_MapFixed32Fixed32Entry_descriptor_ = NULL;
const ::google::protobuf::Descriptor* TestMap_MapFixed64Fixed64Entry_descriptor_ = NULL;
const ::google::protobuf::Descriptor* TestMap_MapSfixed32Sfixed32Entry_descriptor_ = NULL;
const ::google::protobuf::Descriptor* TestMap_MapSfixed64Sfixed64Entry_descriptor_ = NULL;
const ::google::protobuf::Descriptor* TestMap_MapInt32FloatEntry_descriptor_ = NULL;
const ::google::protobuf::Descriptor* TestMap_MapInt32DoubleEntry_descriptor_ = NULL;
const ::google::protobuf::Descriptor* TestMap_MapBoolBoolEntry_descriptor_ = NULL;
const ::google::protobuf::Descriptor* TestMap_MapStringStringEntry_descriptor_ = NULL;
const ::google::protobuf::Descriptor* TestMap_MapInt32BytesEntry_descriptor_ = NULL;
const ::google::protobuf::Descriptor* TestMap_MapInt32EnumEntry_descriptor_ = NULL;
const ::google::protobuf::Descriptor* TestMap_MapInt32ForeignMessageEntry_descriptor_ = NULL;
const ::google::protobuf::Descriptor* TestMap_MapStringForeignMessageEntry_descriptor_ = NULL;
const ::google::protobuf::Descriptor* TestMapSubmessage_descriptor_ = NULL;
const ::google::protobuf::internal::GeneratedMessageReflection*
TestMapSubmessage_reflection_ = NULL;
const ::google::protobuf::Descriptor* TestMessageMap_descriptor_ = NULL;
const ::google::protobuf::internal::GeneratedMessageReflection*
TestMessageMap_reflection_ = NULL;
const ::google::protobuf::Descriptor* TestMessageMap_MapInt32MessageEntry_descriptor_ = NULL;
const ::google::protobuf::Descriptor* TestSameTypeMap_descriptor_ = NULL;
const ::google::protobuf::internal::GeneratedMessageReflection*
TestSameTypeMap_reflection_ = NULL;
const ::google::protobuf::Descriptor* TestSameTypeMap_Map1Entry_descriptor_ = NULL;
const ::google::protobuf::Descriptor* TestSameTypeMap_Map2Entry_descriptor_ = NULL;
const ::google::protobuf::Descriptor* TestRequiredMessageMap_descriptor_ = NULL;
const ::google::protobuf::internal::GeneratedMessageReflection*
TestRequiredMessageMap_reflection_ = NULL;
const ::google::protobuf::Descriptor* TestRequiredMessageMap_MapFieldEntry_descriptor_ = NULL;
const ::google::protobuf::Descriptor* TestArenaMap_descriptor_ = NULL;
const ::google::protobuf::internal::GeneratedMessageReflection*
TestArenaMap_reflection_ = NULL;
const ::google::protobuf::Descriptor* TestArenaMap_MapInt32Int32Entry_descriptor_ = NULL;
const ::google::protobuf::Descriptor* TestArenaMap_MapInt64Int64Entry_descriptor_ = NULL;
const ::google::protobuf::Descriptor* TestArenaMap_MapUint32Uint32Entry_descriptor_ = NULL;
const ::google::protobuf::Descriptor* TestArenaMap_MapUint64Uint64Entry_descriptor_ = NULL;
const ::google::protobuf::Descriptor* TestArenaMap_MapSint32Sint32Entry_descriptor_ = NULL;
const ::google::protobuf::Descriptor* TestArenaMap_MapSint64Sint64Entry_descriptor_ = NULL;
const ::google::protobuf::Descriptor* TestArenaMap_MapFixed32Fixed32Entry_descriptor_ = NULL;
const ::google::protobuf::Descriptor* TestArenaMap_MapFixed64Fixed64Entry_descriptor_ = NULL;
const ::google::protobuf::Descriptor* TestArenaMap_MapSfixed32Sfixed32Entry_descriptor_ = NULL;
const ::google::protobuf::Descriptor* TestArenaMap_MapSfixed64Sfixed64Entry_descriptor_ = NULL;
const ::google::protobuf::Descriptor* TestArenaMap_MapInt32FloatEntry_descriptor_ = NULL;
const ::google::protobuf::Descriptor* TestArenaMap_MapInt32DoubleEntry_descriptor_ = NULL;
const ::google::protobuf::Descriptor* TestArenaMap_MapBoolBoolEntry_descriptor_ = NULL;
const ::google::protobuf::Descriptor* TestArenaMap_MapStringStringEntry_descriptor_ = NULL;
const ::google::protobuf::Descriptor* TestArenaMap_MapInt32BytesEntry_descriptor_ = NULL;
const ::google::protobuf::Descriptor* TestArenaMap_MapInt32EnumEntry_descriptor_ = NULL;
const ::google::protobuf::Descriptor* TestArenaMap_MapInt32ForeignMessageEntry_descriptor_ = NULL;
const ::google::protobuf::Descriptor* TestArenaMap_MapInt32ForeignMessageNoArenaEntry_descriptor_ = NULL;
const ::google::protobuf::Descriptor* MessageContainingEnumCalledType_descriptor_ = NULL;
const ::google::protobuf::internal::GeneratedMessageReflection*
MessageContainingEnumCalledType_reflection_ = NULL;
const ::google::protobuf::Descriptor* MessageContainingEnumCalledType_TypeEntry_descriptor_ = NULL;
const ::google::protobuf::EnumDescriptor* MessageContainingEnumCalledType_Type_descriptor_ = NULL;
const ::google::protobuf::Descriptor* MessageContainingMapCalledEntry_descriptor_ = NULL;
const ::google::protobuf::internal::GeneratedMessageReflection*
MessageContainingMapCalledEntry_reflection_ = NULL;
const ::google::protobuf::Descriptor* MessageContainingMapCalledEntry_EntryEntry_descriptor_ = NULL;
const ::google::protobuf::Descriptor* TestRecursiveMapMessage_descriptor_ = NULL;
const ::google::protobuf::internal::GeneratedMessageReflection*
TestRecursiveMapMessage_reflection_ = NULL;
const ::google::protobuf::Descriptor* TestRecursiveMapMessage_AEntry_descriptor_ = NULL;
const ::google::protobuf::EnumDescriptor* MapEnum_descriptor_ = NULL;
} // namespace
void protobuf_AssignDesc_google_2fprotobuf_2fmap_5funittest_2eproto() {
protobuf_AddDesc_google_2fprotobuf_2fmap_5funittest_2eproto();
const ::google::protobuf::FileDescriptor* file =
::google::protobuf::DescriptorPool::generated_pool()->FindFileByName(
"google/protobuf/map_unittest.proto");
GOOGLE_CHECK(file != NULL);
TestMap_descriptor_ = file->message_type(0);
static const int TestMap_offsets_[18] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TestMap, map_int32_int32_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TestMap, map_int64_int64_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TestMap, map_uint32_uint32_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TestMap, map_uint64_uint64_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TestMap, map_sint32_sint32_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TestMap, map_sint64_sint64_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TestMap, map_fixed32_fixed32_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TestMap, map_fixed64_fixed64_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TestMap, map_sfixed32_sfixed32_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TestMap, map_sfixed64_sfixed64_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TestMap, map_int32_float_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TestMap, map_int32_double_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TestMap, map_bool_bool_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TestMap, map_string_string_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TestMap, map_int32_bytes_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TestMap, map_int32_enum_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TestMap, map_int32_foreign_message_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TestMap, map_string_foreign_message_),
};
TestMap_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
TestMap_descriptor_,
TestMap::default_instance_,
TestMap_offsets_,
-1,
-1,
-1,
sizeof(TestMap),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TestMap, _internal_metadata_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TestMap, _is_default_instance_));
TestMap_MapInt32Int32Entry_descriptor_ = TestMap_descriptor_->nested_type(0);
TestMap_MapInt64Int64Entry_descriptor_ = TestMap_descriptor_->nested_type(1);
TestMap_MapUint32Uint32Entry_descriptor_ = TestMap_descriptor_->nested_type(2);
TestMap_MapUint64Uint64Entry_descriptor_ = TestMap_descriptor_->nested_type(3);
TestMap_MapSint32Sint32Entry_descriptor_ = TestMap_descriptor_->nested_type(4);
TestMap_MapSint64Sint64Entry_descriptor_ = TestMap_descriptor_->nested_type(5);
TestMap_MapFixed32Fixed32Entry_descriptor_ = TestMap_descriptor_->nested_type(6);
TestMap_MapFixed64Fixed64Entry_descriptor_ = TestMap_descriptor_->nested_type(7);
TestMap_MapSfixed32Sfixed32Entry_descriptor_ = TestMap_descriptor_->nested_type(8);
TestMap_MapSfixed64Sfixed64Entry_descriptor_ = TestMap_descriptor_->nested_type(9);
TestMap_MapInt32FloatEntry_descriptor_ = TestMap_descriptor_->nested_type(10);
TestMap_MapInt32DoubleEntry_descriptor_ = TestMap_descriptor_->nested_type(11);
TestMap_MapBoolBoolEntry_descriptor_ = TestMap_descriptor_->nested_type(12);
TestMap_MapStringStringEntry_descriptor_ = TestMap_descriptor_->nested_type(13);
TestMap_MapInt32BytesEntry_descriptor_ = TestMap_descriptor_->nested_type(14);
TestMap_MapInt32EnumEntry_descriptor_ = TestMap_descriptor_->nested_type(15);
TestMap_MapInt32ForeignMessageEntry_descriptor_ = TestMap_descriptor_->nested_type(16);
TestMap_MapStringForeignMessageEntry_descriptor_ = TestMap_descriptor_->nested_type(17);
TestMapSubmessage_descriptor_ = file->message_type(1);
static const int TestMapSubmessage_offsets_[1] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TestMapSubmessage, test_map_),
};
TestMapSubmessage_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
TestMapSubmessage_descriptor_,
TestMapSubmessage::default_instance_,
TestMapSubmessage_offsets_,
-1,
-1,
-1,
sizeof(TestMapSubmessage),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TestMapSubmessage, _internal_metadata_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TestMapSubmessage, _is_default_instance_));
TestMessageMap_descriptor_ = file->message_type(2);
static const int TestMessageMap_offsets_[1] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TestMessageMap, map_int32_message_),
};
TestMessageMap_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
TestMessageMap_descriptor_,
TestMessageMap::default_instance_,
TestMessageMap_offsets_,
-1,
-1,
-1,
sizeof(TestMessageMap),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TestMessageMap, _internal_metadata_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TestMessageMap, _is_default_instance_));
TestMessageMap_MapInt32MessageEntry_descriptor_ = TestMessageMap_descriptor_->nested_type(0);
TestSameTypeMap_descriptor_ = file->message_type(3);
static const int TestSameTypeMap_offsets_[2] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TestSameTypeMap, map1_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TestSameTypeMap, map2_),
};
TestSameTypeMap_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
TestSameTypeMap_descriptor_,
TestSameTypeMap::default_instance_,
TestSameTypeMap_offsets_,
-1,
-1,
-1,
sizeof(TestSameTypeMap),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TestSameTypeMap, _internal_metadata_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TestSameTypeMap, _is_default_instance_));
TestSameTypeMap_Map1Entry_descriptor_ = TestSameTypeMap_descriptor_->nested_type(0);
TestSameTypeMap_Map2Entry_descriptor_ = TestSameTypeMap_descriptor_->nested_type(1);
TestRequiredMessageMap_descriptor_ = file->message_type(4);
static const int TestRequiredMessageMap_offsets_[1] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TestRequiredMessageMap, map_field_),
};
TestRequiredMessageMap_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
TestRequiredMessageMap_descriptor_,
TestRequiredMessageMap::default_instance_,
TestRequiredMessageMap_offsets_,
-1,
-1,
-1,
sizeof(TestRequiredMessageMap),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TestRequiredMessageMap, _internal_metadata_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TestRequiredMessageMap, _is_default_instance_));
TestRequiredMessageMap_MapFieldEntry_descriptor_ = TestRequiredMessageMap_descriptor_->nested_type(0);
TestArenaMap_descriptor_ = file->message_type(5);
static const int TestArenaMap_offsets_[18] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TestArenaMap, map_int32_int32_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TestArenaMap, map_int64_int64_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TestArenaMap, map_uint32_uint32_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TestArenaMap, map_uint64_uint64_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TestArenaMap, map_sint32_sint32_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TestArenaMap, map_sint64_sint64_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TestArenaMap, map_fixed32_fixed32_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TestArenaMap, map_fixed64_fixed64_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TestArenaMap, map_sfixed32_sfixed32_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TestArenaMap, map_sfixed64_sfixed64_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TestArenaMap, map_int32_float_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TestArenaMap, map_int32_double_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TestArenaMap, map_bool_bool_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TestArenaMap, map_string_string_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TestArenaMap, map_int32_bytes_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TestArenaMap, map_int32_enum_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TestArenaMap, map_int32_foreign_message_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TestArenaMap, map_int32_foreign_message_no_arena_),
};
TestArenaMap_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
TestArenaMap_descriptor_,
TestArenaMap::default_instance_,
TestArenaMap_offsets_,
-1,
-1,
-1,
sizeof(TestArenaMap),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TestArenaMap, _internal_metadata_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TestArenaMap, _is_default_instance_));
TestArenaMap_MapInt32Int32Entry_descriptor_ = TestArenaMap_descriptor_->nested_type(0);
TestArenaMap_MapInt64Int64Entry_descriptor_ = TestArenaMap_descriptor_->nested_type(1);
TestArenaMap_MapUint32Uint32Entry_descriptor_ = TestArenaMap_descriptor_->nested_type(2);
TestArenaMap_MapUint64Uint64Entry_descriptor_ = TestArenaMap_descriptor_->nested_type(3);
TestArenaMap_MapSint32Sint32Entry_descriptor_ = TestArenaMap_descriptor_->nested_type(4);
TestArenaMap_MapSint64Sint64Entry_descriptor_ = TestArenaMap_descriptor_->nested_type(5);
TestArenaMap_MapFixed32Fixed32Entry_descriptor_ = TestArenaMap_descriptor_->nested_type(6);
TestArenaMap_MapFixed64Fixed64Entry_descriptor_ = TestArenaMap_descriptor_->nested_type(7);
TestArenaMap_MapSfixed32Sfixed32Entry_descriptor_ = TestArenaMap_descriptor_->nested_type(8);
TestArenaMap_MapSfixed64Sfixed64Entry_descriptor_ = TestArenaMap_descriptor_->nested_type(9);
TestArenaMap_MapInt32FloatEntry_descriptor_ = TestArenaMap_descriptor_->nested_type(10);
TestArenaMap_MapInt32DoubleEntry_descriptor_ = TestArenaMap_descriptor_->nested_type(11);
TestArenaMap_MapBoolBoolEntry_descriptor_ = TestArenaMap_descriptor_->nested_type(12);
TestArenaMap_MapStringStringEntry_descriptor_ = TestArenaMap_descriptor_->nested_type(13);
TestArenaMap_MapInt32BytesEntry_descriptor_ = TestArenaMap_descriptor_->nested_type(14);
TestArenaMap_MapInt32EnumEntry_descriptor_ = TestArenaMap_descriptor_->nested_type(15);
TestArenaMap_MapInt32ForeignMessageEntry_descriptor_ = TestArenaMap_descriptor_->nested_type(16);
TestArenaMap_MapInt32ForeignMessageNoArenaEntry_descriptor_ = TestArenaMap_descriptor_->nested_type(17);
MessageContainingEnumCalledType_descriptor_ = file->message_type(6);
static const int MessageContainingEnumCalledType_offsets_[1] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MessageContainingEnumCalledType, type_),
};
MessageContainingEnumCalledType_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
MessageContainingEnumCalledType_descriptor_,
MessageContainingEnumCalledType::default_instance_,
MessageContainingEnumCalledType_offsets_,
-1,
-1,
-1,
sizeof(MessageContainingEnumCalledType),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MessageContainingEnumCalledType, _internal_metadata_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MessageContainingEnumCalledType, _is_default_instance_));
MessageContainingEnumCalledType_TypeEntry_descriptor_ = MessageContainingEnumCalledType_descriptor_->nested_type(0);
MessageContainingEnumCalledType_Type_descriptor_ = MessageContainingEnumCalledType_descriptor_->enum_type(0);
MessageContainingMapCalledEntry_descriptor_ = file->message_type(7);
static const int MessageContainingMapCalledEntry_offsets_[1] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MessageContainingMapCalledEntry, entry_),
};
MessageContainingMapCalledEntry_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
MessageContainingMapCalledEntry_descriptor_,
MessageContainingMapCalledEntry::default_instance_,
MessageContainingMapCalledEntry_offsets_,
-1,
-1,
-1,
sizeof(MessageContainingMapCalledEntry),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MessageContainingMapCalledEntry, _internal_metadata_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MessageContainingMapCalledEntry, _is_default_instance_));
MessageContainingMapCalledEntry_EntryEntry_descriptor_ = MessageContainingMapCalledEntry_descriptor_->nested_type(0);
TestRecursiveMapMessage_descriptor_ = file->message_type(8);
static const int TestRecursiveMapMessage_offsets_[1] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TestRecursiveMapMessage, a_),
};
TestRecursiveMapMessage_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
TestRecursiveMapMessage_descriptor_,
TestRecursiveMapMessage::default_instance_,
TestRecursiveMapMessage_offsets_,
-1,
-1,
-1,
sizeof(TestRecursiveMapMessage),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TestRecursiveMapMessage, _internal_metadata_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TestRecursiveMapMessage, _is_default_instance_));
TestRecursiveMapMessage_AEntry_descriptor_ = TestRecursiveMapMessage_descriptor_->nested_type(0);
MapEnum_descriptor_ = file->enum_type(0);
}
namespace {
GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AssignDescriptors_once_);
inline void protobuf_AssignDescriptorsOnce() {
::google::protobuf::GoogleOnceInit(&protobuf_AssignDescriptors_once_,
&protobuf_AssignDesc_google_2fprotobuf_2fmap_5funittest_2eproto);
}
void protobuf_RegisterTypes(const ::std::string&) {
protobuf_AssignDescriptorsOnce();
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
TestMap_descriptor_, &TestMap::default_instance());
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
TestMap_MapInt32Int32Entry_descriptor_,
::google::protobuf::internal::MapEntry<
::google::protobuf::int32,
::google::protobuf::int32,
::google::protobuf::internal::WireFormatLite::TYPE_INT32,
::google::protobuf::internal::WireFormatLite::TYPE_INT32,
0>::CreateDefaultInstance(
TestMap_MapInt32Int32Entry_descriptor_));
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
TestMap_MapInt64Int64Entry_descriptor_,
::google::protobuf::internal::MapEntry<
::google::protobuf::int64,
::google::protobuf::int64,
::google::protobuf::internal::WireFormatLite::TYPE_INT64,
::google::protobuf::internal::WireFormatLite::TYPE_INT64,
0>::CreateDefaultInstance(
TestMap_MapInt64Int64Entry_descriptor_));
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
TestMap_MapUint32Uint32Entry_descriptor_,
::google::protobuf::internal::MapEntry<
::google::protobuf::uint32,
::google::protobuf::uint32,
::google::protobuf::internal::WireFormatLite::TYPE_UINT32,
::google::protobuf::internal::WireFormatLite::TYPE_UINT32,
0>::CreateDefaultInstance(
TestMap_MapUint32Uint32Entry_descriptor_));
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
TestMap_MapUint64Uint64Entry_descriptor_,
::google::protobuf::internal::MapEntry<
::google::protobuf::uint64,
::google::protobuf::uint64,
::google::protobuf::internal::WireFormatLite::TYPE_UINT64,
::google::protobuf::internal::WireFormatLite::TYPE_UINT64,
0>::CreateDefaultInstance(
TestMap_MapUint64Uint64Entry_descriptor_));
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
TestMap_MapSint32Sint32Entry_descriptor_,
::google::protobuf::internal::MapEntry<
::google::protobuf::int32,
::google::protobuf::int32,
::google::protobuf::internal::WireFormatLite::TYPE_SINT32,
::google::protobuf::internal::WireFormatLite::TYPE_SINT32,
0>::CreateDefaultInstance(
TestMap_MapSint32Sint32Entry_descriptor_));
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
TestMap_MapSint64Sint64Entry_descriptor_,
::google::protobuf::internal::MapEntry<
::google::protobuf::int64,
::google::protobuf::int64,
::google::protobuf::internal::WireFormatLite::TYPE_SINT64,
::google::protobuf::internal::WireFormatLite::TYPE_SINT64,
0>::CreateDefaultInstance(
TestMap_MapSint64Sint64Entry_descriptor_));
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
TestMap_MapFixed32Fixed32Entry_descriptor_,
::google::protobuf::internal::MapEntry<
::google::protobuf::uint32,
::google::protobuf::uint32,
::google::protobuf::internal::WireFormatLite::TYPE_FIXED32,
::google::protobuf::internal::WireFormatLite::TYPE_FIXED32,
0>::CreateDefaultInstance(
TestMap_MapFixed32Fixed32Entry_descriptor_));
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
TestMap_MapFixed64Fixed64Entry_descriptor_,
::google::protobuf::internal::MapEntry<
::google::protobuf::uint64,
::google::protobuf::uint64,
::google::protobuf::internal::WireFormatLite::TYPE_FIXED64,
::google::protobuf::internal::WireFormatLite::TYPE_FIXED64,
0>::CreateDefaultInstance(
TestMap_MapFixed64Fixed64Entry_descriptor_));
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
TestMap_MapSfixed32Sfixed32Entry_descriptor_,
::google::protobuf::internal::MapEntry<
::google::protobuf::int32,
::google::protobuf::int32,
::google::protobuf::internal::WireFormatLite::TYPE_SFIXED32,
::google::protobuf::internal::WireFormatLite::TYPE_SFIXED32,
0>::CreateDefaultInstance(
TestMap_MapSfixed32Sfixed32Entry_descriptor_));
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
TestMap_MapSfixed64Sfixed64Entry_descriptor_,
::google::protobuf::internal::MapEntry<
::google::protobuf::int64,
::google::protobuf::int64,
::google::protobuf::internal::WireFormatLite::TYPE_SFIXED64,
::google::protobuf::internal::WireFormatLite::TYPE_SFIXED64,
0>::CreateDefaultInstance(
TestMap_MapSfixed64Sfixed64Entry_descriptor_));
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
TestMap_MapInt32FloatEntry_descriptor_,
::google::protobuf::internal::MapEntry<
::google::protobuf::int32,
float,
::google::protobuf::internal::WireFormatLite::TYPE_INT32,
::google::protobuf::internal::WireFormatLite::TYPE_FLOAT,
0>::CreateDefaultInstance(
TestMap_MapInt32FloatEntry_descriptor_));
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
TestMap_MapInt32DoubleEntry_descriptor_,
::google::protobuf::internal::MapEntry<
::google::protobuf::int32,
double,
::google::protobuf::internal::WireFormatLite::TYPE_INT32,
::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE,
0>::CreateDefaultInstance(
TestMap_MapInt32DoubleEntry_descriptor_));
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
TestMap_MapBoolBoolEntry_descriptor_,
::google::protobuf::internal::MapEntry<
bool,
bool,
::google::protobuf::internal::WireFormatLite::TYPE_BOOL,
::google::protobuf::internal::WireFormatLite::TYPE_BOOL,
0>::CreateDefaultInstance(
TestMap_MapBoolBoolEntry_descriptor_));
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
TestMap_MapStringStringEntry_descriptor_,
::google::protobuf::internal::MapEntry<
::std::string,
::std::string,
::google::protobuf::internal::WireFormatLite::TYPE_STRING,
::google::protobuf::internal::WireFormatLite::TYPE_STRING,
0>::CreateDefaultInstance(
TestMap_MapStringStringEntry_descriptor_));
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
TestMap_MapInt32BytesEntry_descriptor_,
::google::protobuf::internal::MapEntry<
::google::protobuf::int32,
::std::string,
::google::protobuf::internal::WireFormatLite::TYPE_INT32,
::google::protobuf::internal::WireFormatLite::TYPE_BYTES,
0>::CreateDefaultInstance(
TestMap_MapInt32BytesEntry_descriptor_));
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
TestMap_MapInt32EnumEntry_descriptor_,
::google::protobuf::internal::MapEntry<
::google::protobuf::int32,
::protobuf_unittest::MapEnum,
::google::protobuf::internal::WireFormatLite::TYPE_INT32,
::google::protobuf::internal::WireFormatLite::TYPE_ENUM,
0>::CreateDefaultInstance(
TestMap_MapInt32EnumEntry_descriptor_));
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
TestMap_MapInt32ForeignMessageEntry_descriptor_,
::google::protobuf::internal::MapEntry<
::google::protobuf::int32,
::protobuf_unittest::ForeignMessage,
::google::protobuf::internal::WireFormatLite::TYPE_INT32,
::google::protobuf::internal::WireFormatLite::TYPE_MESSAGE,
0>::CreateDefaultInstance(
TestMap_MapInt32ForeignMessageEntry_descriptor_));
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
TestMap_MapStringForeignMessageEntry_descriptor_,
::google::protobuf::internal::MapEntry<
::std::string,
::protobuf_unittest::ForeignMessage,
::google::protobuf::internal::WireFormatLite::TYPE_STRING,
::google::protobuf::internal::WireFormatLite::TYPE_MESSAGE,
0>::CreateDefaultInstance(
TestMap_MapStringForeignMessageEntry_descriptor_));
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
TestMapSubmessage_descriptor_, &TestMapSubmessage::default_instance());
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
TestMessageMap_descriptor_, &TestMessageMap::default_instance());
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
TestMessageMap_MapInt32MessageEntry_descriptor_,
::google::protobuf::internal::MapEntry<
::google::protobuf::int32,
::protobuf_unittest::TestAllTypes,
::google::protobuf::internal::WireFormatLite::TYPE_INT32,
::google::protobuf::internal::WireFormatLite::TYPE_MESSAGE,
0>::CreateDefaultInstance(
TestMessageMap_MapInt32MessageEntry_descriptor_));
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
TestSameTypeMap_descriptor_, &TestSameTypeMap::default_instance());
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
TestSameTypeMap_Map1Entry_descriptor_,
::google::protobuf::internal::MapEntry<
::google::protobuf::int32,
::google::protobuf::int32,
::google::protobuf::internal::WireFormatLite::TYPE_INT32,
::google::protobuf::internal::WireFormatLite::TYPE_INT32,
0>::CreateDefaultInstance(
TestSameTypeMap_Map1Entry_descriptor_));
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
TestSameTypeMap_Map2Entry_descriptor_,
::google::protobuf::internal::MapEntry<
::google::protobuf::int32,
::google::protobuf::int32,
::google::protobuf::internal::WireFormatLite::TYPE_INT32,
::google::protobuf::internal::WireFormatLite::TYPE_INT32,
0>::CreateDefaultInstance(
TestSameTypeMap_Map2Entry_descriptor_));
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
TestRequiredMessageMap_descriptor_, &TestRequiredMessageMap::default_instance());
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
TestRequiredMessageMap_MapFieldEntry_descriptor_,
::google::protobuf::internal::MapEntry<
::google::protobuf::int32,
::protobuf_unittest::TestRequired,
::google::protobuf::internal::WireFormatLite::TYPE_INT32,
::google::protobuf::internal::WireFormatLite::TYPE_MESSAGE,
0>::CreateDefaultInstance(
TestRequiredMessageMap_MapFieldEntry_descriptor_));
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
TestArenaMap_descriptor_, &TestArenaMap::default_instance());
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
TestArenaMap_MapInt32Int32Entry_descriptor_,
::google::protobuf::internal::MapEntry<
::google::protobuf::int32,
::google::protobuf::int32,
::google::protobuf::internal::WireFormatLite::TYPE_INT32,
::google::protobuf::internal::WireFormatLite::TYPE_INT32,
0>::CreateDefaultInstance(
TestArenaMap_MapInt32Int32Entry_descriptor_));
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
TestArenaMap_MapInt64Int64Entry_descriptor_,
::google::protobuf::internal::MapEntry<
::google::protobuf::int64,
::google::protobuf::int64,
::google::protobuf::internal::WireFormatLite::TYPE_INT64,
::google::protobuf::internal::WireFormatLite::TYPE_INT64,
0>::CreateDefaultInstance(
TestArenaMap_MapInt64Int64Entry_descriptor_));
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
TestArenaMap_MapUint32Uint32Entry_descriptor_,
::google::protobuf::internal::MapEntry<
::google::protobuf::uint32,
::google::protobuf::uint32,
::google::protobuf::internal::WireFormatLite::TYPE_UINT32,
::google::protobuf::internal::WireFormatLite::TYPE_UINT32,
0>::CreateDefaultInstance(
TestArenaMap_MapUint32Uint32Entry_descriptor_));
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
TestArenaMap_MapUint64Uint64Entry_descriptor_,
::google::protobuf::internal::MapEntry<
::google::protobuf::uint64,
::google::protobuf::uint64,
::google::protobuf::internal::WireFormatLite::TYPE_UINT64,
::google::protobuf::internal::WireFormatLite::TYPE_UINT64,
0>::CreateDefaultInstance(
TestArenaMap_MapUint64Uint64Entry_descriptor_));
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
TestArenaMap_MapSint32Sint32Entry_descriptor_,
::google::protobuf::internal::MapEntry<
::google::protobuf::int32,
::google::protobuf::int32,
::google::protobuf::internal::WireFormatLite::TYPE_SINT32,
::google::protobuf::internal::WireFormatLite::TYPE_SINT32,
0>::CreateDefaultInstance(
TestArenaMap_MapSint32Sint32Entry_descriptor_));
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
TestArenaMap_MapSint64Sint64Entry_descriptor_,
::google::protobuf::internal::MapEntry<
::google::protobuf::int64,
::google::protobuf::int64,
::google::protobuf::internal::WireFormatLite::TYPE_SINT64,
::google::protobuf::internal::WireFormatLite::TYPE_SINT64,
0>::CreateDefaultInstance(
TestArenaMap_MapSint64Sint64Entry_descriptor_));
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
TestArenaMap_MapFixed32Fixed32Entry_descriptor_,
::google::protobuf::internal::MapEntry<
::google::protobuf::uint32,
::google::protobuf::uint32,
::google::protobuf::internal::WireFormatLite::TYPE_FIXED32,
::google::protobuf::internal::WireFormatLite::TYPE_FIXED32,
0>::CreateDefaultInstance(
TestArenaMap_MapFixed32Fixed32Entry_descriptor_));
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
TestArenaMap_MapFixed64Fixed64Entry_descriptor_,
::google::protobuf::internal::MapEntry<
::google::protobuf::uint64,
::google::protobuf::uint64,
::google::protobuf::internal::WireFormatLite::TYPE_FIXED64,
::google::protobuf::internal::WireFormatLite::TYPE_FIXED64,
0>::CreateDefaultInstance(
TestArenaMap_MapFixed64Fixed64Entry_descriptor_));
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
TestArenaMap_MapSfixed32Sfixed32Entry_descriptor_,
::google::protobuf::internal::MapEntry<
::google::protobuf::int32,
::google::protobuf::int32,
::google::protobuf::internal::WireFormatLite::TYPE_SFIXED32,
::google::protobuf::internal::WireFormatLite::TYPE_SFIXED32,
0>::CreateDefaultInstance(
TestArenaMap_MapSfixed32Sfixed32Entry_descriptor_));
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
TestArenaMap_MapSfixed64Sfixed64Entry_descriptor_,
::google::protobuf::internal::MapEntry<
::google::protobuf::int64,
::google::protobuf::int64,
::google::protobuf::internal::WireFormatLite::TYPE_SFIXED64,
::google::protobuf::internal::WireFormatLite::TYPE_SFIXED64,
0>::CreateDefaultInstance(
TestArenaMap_MapSfixed64Sfixed64Entry_descriptor_));
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
TestArenaMap_MapInt32FloatEntry_descriptor_,
::google::protobuf::internal::MapEntry<
::google::protobuf::int32,
float,
::google::protobuf::internal::WireFormatLite::TYPE_INT32,
::google::protobuf::internal::WireFormatLite::TYPE_FLOAT,
0>::CreateDefaultInstance(
TestArenaMap_MapInt32FloatEntry_descriptor_));
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
TestArenaMap_MapInt32DoubleEntry_descriptor_,
::google::protobuf::internal::MapEntry<
::google::protobuf::int32,
double,
::google::protobuf::internal::WireFormatLite::TYPE_INT32,
::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE,
0>::CreateDefaultInstance(
TestArenaMap_MapInt32DoubleEntry_descriptor_));
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
TestArenaMap_MapBoolBoolEntry_descriptor_,
::google::protobuf::internal::MapEntry<
bool,
bool,
::google::protobuf::internal::WireFormatLite::TYPE_BOOL,
::google::protobuf::internal::WireFormatLite::TYPE_BOOL,
0>::CreateDefaultInstance(
TestArenaMap_MapBoolBoolEntry_descriptor_));
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
TestArenaMap_MapStringStringEntry_descriptor_,
::google::protobuf::internal::MapEntry<
::std::string,
::std::string,
::google::protobuf::internal::WireFormatLite::TYPE_STRING,
::google::protobuf::internal::WireFormatLite::TYPE_STRING,
0>::CreateDefaultInstance(
TestArenaMap_MapStringStringEntry_descriptor_));
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
TestArenaMap_MapInt32BytesEntry_descriptor_,
::google::protobuf::internal::MapEntry<
::google::protobuf::int32,
::std::string,
::google::protobuf::internal::WireFormatLite::TYPE_INT32,
::google::protobuf::internal::WireFormatLite::TYPE_BYTES,
0>::CreateDefaultInstance(
TestArenaMap_MapInt32BytesEntry_descriptor_));
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
TestArenaMap_MapInt32EnumEntry_descriptor_,
::google::protobuf::internal::MapEntry<
::google::protobuf::int32,
::protobuf_unittest::MapEnum,
::google::protobuf::internal::WireFormatLite::TYPE_INT32,
::google::protobuf::internal::WireFormatLite::TYPE_ENUM,
0>::CreateDefaultInstance(
TestArenaMap_MapInt32EnumEntry_descriptor_));
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
TestArenaMap_MapInt32ForeignMessageEntry_descriptor_,
::google::protobuf::internal::MapEntry<
::google::protobuf::int32,
::protobuf_unittest::ForeignMessage,
::google::protobuf::internal::WireFormatLite::TYPE_INT32,
::google::protobuf::internal::WireFormatLite::TYPE_MESSAGE,
0>::CreateDefaultInstance(
TestArenaMap_MapInt32ForeignMessageEntry_descriptor_));
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
TestArenaMap_MapInt32ForeignMessageNoArenaEntry_descriptor_,
::google::protobuf::internal::MapEntry<
::google::protobuf::int32,
::protobuf_unittest_no_arena::ForeignMessage,
::google::protobuf::internal::WireFormatLite::TYPE_INT32,
::google::protobuf::internal::WireFormatLite::TYPE_MESSAGE,
0>::CreateDefaultInstance(
TestArenaMap_MapInt32ForeignMessageNoArenaEntry_descriptor_));
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
MessageContainingEnumCalledType_descriptor_, &MessageContainingEnumCalledType::default_instance());
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
MessageContainingEnumCalledType_TypeEntry_descriptor_,
::google::protobuf::internal::MapEntry<
::std::string,
::protobuf_unittest::MessageContainingEnumCalledType,
::google::protobuf::internal::WireFormatLite::TYPE_STRING,
::google::protobuf::internal::WireFormatLite::TYPE_MESSAGE,
0>::CreateDefaultInstance(
MessageContainingEnumCalledType_TypeEntry_descriptor_));
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
MessageContainingMapCalledEntry_descriptor_, &MessageContainingMapCalledEntry::default_instance());
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
MessageContainingMapCalledEntry_EntryEntry_descriptor_,
::google::protobuf::internal::MapEntry<
::google::protobuf::int32,
::google::protobuf::int32,
::google::protobuf::internal::WireFormatLite::TYPE_INT32,
::google::protobuf::internal::WireFormatLite::TYPE_INT32,
0>::CreateDefaultInstance(
MessageContainingMapCalledEntry_EntryEntry_descriptor_));
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
TestRecursiveMapMessage_descriptor_, &TestRecursiveMapMessage::default_instance());
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
TestRecursiveMapMessage_AEntry_descriptor_,
::google::protobuf::internal::MapEntry<
::std::string,
::protobuf_unittest::TestRecursiveMapMessage,
::google::protobuf::internal::WireFormatLite::TYPE_STRING,
::google::protobuf::internal::WireFormatLite::TYPE_MESSAGE,
0>::CreateDefaultInstance(
TestRecursiveMapMessage_AEntry_descriptor_));
}
} // namespace
void protobuf_ShutdownFile_google_2fprotobuf_2fmap_5funittest_2eproto() {
delete TestMap::default_instance_;
delete TestMap_reflection_;
delete TestMapSubmessage::default_instance_;
delete TestMapSubmessage_reflection_;
delete TestMessageMap::default_instance_;
delete TestMessageMap_reflection_;
delete TestSameTypeMap::default_instance_;
delete TestSameTypeMap_reflection_;
delete TestRequiredMessageMap::default_instance_;
delete TestRequiredMessageMap_reflection_;
delete TestArenaMap::default_instance_;
delete TestArenaMap_reflection_;
delete MessageContainingEnumCalledType::default_instance_;
delete MessageContainingEnumCalledType_reflection_;
delete MessageContainingMapCalledEntry::default_instance_;
delete MessageContainingMapCalledEntry_reflection_;
delete TestRecursiveMapMessage::default_instance_;
delete TestRecursiveMapMessage_reflection_;
}
void protobuf_AddDesc_google_2fprotobuf_2fmap_5funittest_2eproto() {
static bool already_here = false;
if (already_here) return;
already_here = true;
GOOGLE_PROTOBUF_VERIFY_VERSION;
::protobuf_unittest::protobuf_AddDesc_google_2fprotobuf_2funittest_2eproto();
::protobuf_unittest_no_arena::protobuf_AddDesc_google_2fprotobuf_2funittest_5fno_5farena_2eproto();
::google::protobuf::DescriptorPool::InternalAddGeneratedFile(
"\n\"google/protobuf/map_unittest.proto\022\021pr"
"otobuf_unittest\032\036google/protobuf/unittes"
"t.proto\032\'google/protobuf/unittest_no_are"
"na.proto\"\326\023\n\007TestMap\022F\n\017map_int32_int32\030"
"\001 \003(\0132-.protobuf_unittest.TestMap.MapInt"
"32Int32Entry\022F\n\017map_int64_int64\030\002 \003(\0132-."
"protobuf_unittest.TestMap.MapInt64Int64E"
"ntry\022J\n\021map_uint32_uint32\030\003 \003(\0132/.protob"
"uf_unittest.TestMap.MapUint32Uint32Entry"
"\022J\n\021map_uint64_uint64\030\004 \003(\0132/.protobuf_u"
"nittest.TestMap.MapUint64Uint64Entry\022J\n\021"
"map_sint32_sint32\030\005 \003(\0132/.protobuf_unitt"
"est.TestMap.MapSint32Sint32Entry\022J\n\021map_"
"sint64_sint64\030\006 \003(\0132/.protobuf_unittest."
"TestMap.MapSint64Sint64Entry\022N\n\023map_fixe"
"d32_fixed32\030\007 \003(\01321.protobuf_unittest.Te"
"stMap.MapFixed32Fixed32Entry\022N\n\023map_fixe"
"d64_fixed64\030\010 \003(\01321.protobuf_unittest.Te"
"stMap.MapFixed64Fixed64Entry\022R\n\025map_sfix"
"ed32_sfixed32\030\t \003(\01323.protobuf_unittest."
"TestMap.MapSfixed32Sfixed32Entry\022R\n\025map_"
"sfixed64_sfixed64\030\n \003(\01323.protobuf_unitt"
"est.TestMap.MapSfixed64Sfixed64Entry\022F\n\017"
"map_int32_float\030\013 \003(\0132-.protobuf_unittes"
"t.TestMap.MapInt32FloatEntry\022H\n\020map_int3"
"2_double\030\014 \003(\0132..protobuf_unittest.TestM"
"ap.MapInt32DoubleEntry\022B\n\rmap_bool_bool\030"
"\r \003(\0132+.protobuf_unittest.TestMap.MapBoo"
"lBoolEntry\022J\n\021map_string_string\030\016 \003(\0132/."
"protobuf_unittest.TestMap.MapStringStrin"
"gEntry\022F\n\017map_int32_bytes\030\017 \003(\0132-.protob"
"uf_unittest.TestMap.MapInt32BytesEntry\022D"
"\n\016map_int32_enum\030\020 \003(\0132,.protobuf_unitte"
"st.TestMap.MapInt32EnumEntry\022Y\n\031map_int3"
"2_foreign_message\030\021 \003(\01326.protobuf_unitt"
"est.TestMap.MapInt32ForeignMessageEntry\022"
"[\n\032map_string_foreign_message\030\022 \003(\01327.pr"
"otobuf_unittest.TestMap.MapStringForeign"
"MessageEntry\0324\n\022MapInt32Int32Entry\022\013\n\003ke"
"y\030\001 \001(\005\022\r\n\005value\030\002 \001(\005:\0028\001\0324\n\022MapInt64In"
"t64Entry\022\013\n\003key\030\001 \001(\003\022\r\n\005value\030\002 \001(\003:\0028\001"
"\0326\n\024MapUint32Uint32Entry\022\013\n\003key\030\001 \001(\r\022\r\n"
"\005value\030\002 \001(\r:\0028\001\0326\n\024MapUint64Uint64Entry"
"\022\013\n\003key\030\001 \001(\004\022\r\n\005value\030\002 \001(\004:\0028\001\0326\n\024MapS"
"int32Sint32Entry\022\013\n\003key\030\001 \001(\021\022\r\n\005value\030\002"
" \001(\021:\0028\001\0326\n\024MapSint64Sint64Entry\022\013\n\003key\030"
"\001 \001(\022\022\r\n\005value\030\002 \001(\022:\0028\001\0328\n\026MapFixed32Fi"
"xed32Entry\022\013\n\003key\030\001 \001(\007\022\r\n\005value\030\002 \001(\007:\002"
"8\001\0328\n\026MapFixed64Fixed64Entry\022\013\n\003key\030\001 \001("
"\006\022\r\n\005value\030\002 \001(\006:\0028\001\032:\n\030MapSfixed32Sfixe"
"d32Entry\022\013\n\003key\030\001 \001(\017\022\r\n\005value\030\002 \001(\017:\0028\001"
"\032:\n\030MapSfixed64Sfixed64Entry\022\013\n\003key\030\001 \001("
"\020\022\r\n\005value\030\002 \001(\020:\0028\001\0324\n\022MapInt32FloatEnt"
"ry\022\013\n\003key\030\001 \001(\005\022\r\n\005value\030\002 \001(\002:\0028\001\0325\n\023Ma"
"pInt32DoubleEntry\022\013\n\003key\030\001 \001(\005\022\r\n\005value\030"
"\002 \001(\001:\0028\001\0322\n\020MapBoolBoolEntry\022\013\n\003key\030\001 \001"
"(\010\022\r\n\005value\030\002 \001(\010:\0028\001\0326\n\024MapStringString"
"Entry\022\013\n\003key\030\001 \001(\t\022\r\n\005value\030\002 \001(\t:\0028\001\0324\n"
"\022MapInt32BytesEntry\022\013\n\003key\030\001 \001(\005\022\r\n\005valu"
"e\030\002 \001(\014:\0028\001\032O\n\021MapInt32EnumEntry\022\013\n\003key\030"
"\001 \001(\005\022)\n\005value\030\002 \001(\0162\032.protobuf_unittest"
".MapEnum:\0028\001\032`\n\033MapInt32ForeignMessageEn"
"try\022\013\n\003key\030\001 \001(\005\0220\n\005value\030\002 \001(\0132!.protob"
"uf_unittest.ForeignMessage:\0028\001\032a\n\034MapStr"
"ingForeignMessageEntry\022\013\n\003key\030\001 \001(\t\0220\n\005v"
"alue\030\002 \001(\0132!.protobuf_unittest.ForeignMe"
"ssage:\0028\001\"A\n\021TestMapSubmessage\022,\n\010test_m"
"ap\030\001 \001(\0132\032.protobuf_unittest.TestMap\"\274\001\n"
"\016TestMessageMap\022Q\n\021map_int32_message\030\001 \003"
"(\01326.protobuf_unittest.TestMessageMap.Ma"
"pInt32MessageEntry\032W\n\024MapInt32MessageEnt"
"ry\022\013\n\003key\030\001 \001(\005\022.\n\005value\030\002 \001(\0132\037.protobu"
"f_unittest.TestAllTypes:\0028\001\"\343\001\n\017TestSame"
"TypeMap\022:\n\004map1\030\001 \003(\0132,.protobuf_unittes"
"t.TestSameTypeMap.Map1Entry\022:\n\004map2\030\002 \003("
"\0132,.protobuf_unittest.TestSameTypeMap.Ma"
"p2Entry\032+\n\tMap1Entry\022\013\n\003key\030\001 \001(\005\022\r\n\005val"
"ue\030\002 \001(\005:\0028\001\032+\n\tMap2Entry\022\013\n\003key\030\001 \001(\005\022\r"
"\n\005value\030\002 \001(\005:\0028\001\"\266\001\n\026TestRequiredMessag"
"eMap\022J\n\tmap_field\030\001 \003(\01327.protobuf_unitt"
"est.TestRequiredMessageMap.MapFieldEntry"
"\032P\n\rMapFieldEntry\022\013\n\003key\030\001 \001(\005\022.\n\005value\030"
"\002 \001(\0132\037.protobuf_unittest.TestRequired:\002"
"8\001\"\322\024\n\014TestArenaMap\022K\n\017map_int32_int32\030\001"
" \003(\01322.protobuf_unittest.TestArenaMap.Ma"
"pInt32Int32Entry\022K\n\017map_int64_int64\030\002 \003("
"\01322.protobuf_unittest.TestArenaMap.MapIn"
"t64Int64Entry\022O\n\021map_uint32_uint32\030\003 \003(\013"
"24.protobuf_unittest.TestArenaMap.MapUin"
"t32Uint32Entry\022O\n\021map_uint64_uint64\030\004 \003("
"\01324.protobuf_unittest.TestArenaMap.MapUi"
"nt64Uint64Entry\022O\n\021map_sint32_sint32\030\005 \003"
"(\01324.protobuf_unittest.TestArenaMap.MapS"
"int32Sint32Entry\022O\n\021map_sint64_sint64\030\006 "
"\003(\01324.protobuf_unittest.TestArenaMap.Map"
"Sint64Sint64Entry\022S\n\023map_fixed32_fixed32"
"\030\007 \003(\01326.protobuf_unittest.TestArenaMap."
"MapFixed32Fixed32Entry\022S\n\023map_fixed64_fi"
"xed64\030\010 \003(\01326.protobuf_unittest.TestAren"
"aMap.MapFixed64Fixed64Entry\022W\n\025map_sfixe"
"d32_sfixed32\030\t \003(\01328.protobuf_unittest.T"
"estArenaMap.MapSfixed32Sfixed32Entry\022W\n\025"
"map_sfixed64_sfixed64\030\n \003(\01328.protobuf_u"
"nittest.TestArenaMap.MapSfixed64Sfixed64"
"Entry\022K\n\017map_int32_float\030\013 \003(\01322.protobu"
"f_unittest.TestArenaMap.MapInt32FloatEnt"
"ry\022M\n\020map_int32_double\030\014 \003(\01323.protobuf_"
"unittest.TestArenaMap.MapInt32DoubleEntr"
"y\022G\n\rmap_bool_bool\030\r \003(\01320.protobuf_unit"
"test.TestArenaMap.MapBoolBoolEntry\022O\n\021ma"
"p_string_string\030\016 \003(\01324.protobuf_unittes"
"t.TestArenaMap.MapStringStringEntry\022K\n\017m"
"ap_int32_bytes\030\017 \003(\01322.protobuf_unittest"
".TestArenaMap.MapInt32BytesEntry\022I\n\016map_"
"int32_enum\030\020 \003(\01321.protobuf_unittest.Tes"
"tArenaMap.MapInt32EnumEntry\022^\n\031map_int32"
"_foreign_message\030\021 \003(\0132;.protobuf_unitte"
"st.TestArenaMap.MapInt32ForeignMessageEn"
"try\022n\n\"map_int32_foreign_message_no_aren"
"a\030\022 \003(\0132B.protobuf_unittest.TestArenaMap"
".MapInt32ForeignMessageNoArenaEntry\0324\n\022M"
"apInt32Int32Entry\022\013\n\003key\030\001 \001(\005\022\r\n\005value\030"
"\002 \001(\005:\0028\001\0324\n\022MapInt64Int64Entry\022\013\n\003key\030\001"
" \001(\003\022\r\n\005value\030\002 \001(\003:\0028\001\0326\n\024MapUint32Uint"
"32Entry\022\013\n\003key\030\001 \001(\r\022\r\n\005value\030\002 \001(\r:\0028\001\032"
"6\n\024MapUint64Uint64Entry\022\013\n\003key\030\001 \001(\004\022\r\n\005"
"value\030\002 \001(\004:\0028\001\0326\n\024MapSint32Sint32Entry\022"
"\013\n\003key\030\001 \001(\021\022\r\n\005value\030\002 \001(\021:\0028\001\0326\n\024MapSi"
"nt64Sint64Entry\022\013\n\003key\030\001 \001(\022\022\r\n\005value\030\002 "
"\001(\022:\0028\001\0328\n\026MapFixed32Fixed32Entry\022\013\n\003key"
"\030\001 \001(\007\022\r\n\005value\030\002 \001(\007:\0028\001\0328\n\026MapFixed64F"
"ixed64Entry\022\013\n\003key\030\001 \001(\006\022\r\n\005value\030\002 \001(\006:"
"\0028\001\032:\n\030MapSfixed32Sfixed32Entry\022\013\n\003key\030\001"
" \001(\017\022\r\n\005value\030\002 \001(\017:\0028\001\032:\n\030MapSfixed64Sf"
"ixed64Entry\022\013\n\003key\030\001 \001(\020\022\r\n\005value\030\002 \001(\020:"
"\0028\001\0324\n\022MapInt32FloatEntry\022\013\n\003key\030\001 \001(\005\022\r"
"\n\005value\030\002 \001(\002:\0028\001\0325\n\023MapInt32DoubleEntry"
"\022\013\n\003key\030\001 \001(\005\022\r\n\005value\030\002 \001(\001:\0028\001\0322\n\020MapB"
"oolBoolEntry\022\013\n\003key\030\001 \001(\010\022\r\n\005value\030\002 \001(\010"
":\0028\001\0326\n\024MapStringStringEntry\022\013\n\003key\030\001 \001("
"\t\022\r\n\005value\030\002 \001(\t:\0028\001\0324\n\022MapInt32BytesEnt"
"ry\022\013\n\003key\030\001 \001(\005\022\r\n\005value\030\002 \001(\014:\0028\001\032O\n\021Ma"
"pInt32EnumEntry\022\013\n\003key\030\001 \001(\005\022)\n\005value\030\002 "
"\001(\0162\032.protobuf_unittest.MapEnum:\0028\001\032`\n\033M"
"apInt32ForeignMessageEntry\022\013\n\003key\030\001 \001(\005\022"
"0\n\005value\030\002 \001(\0132!.protobuf_unittest.Forei"
"gnMessage:\0028\001\032p\n\"MapInt32ForeignMessageN"
"oArenaEntry\022\013\n\003key\030\001 \001(\005\0229\n\005value\030\002 \001(\0132"
"*.protobuf_unittest_no_arena.ForeignMess"
"age:\0028\001\"\344\001\n\037MessageContainingEnumCalledT"
"ype\022J\n\004type\030\001 \003(\0132<.protobuf_unittest.Me"
"ssageContainingEnumCalledType.TypeEntry\032"
"_\n\tTypeEntry\022\013\n\003key\030\001 \001(\t\022A\n\005value\030\002 \001(\013"
"22.protobuf_unittest.MessageContainingEn"
"umCalledType:\0028\001\"\024\n\004Type\022\014\n\010TYPE_FOO\020\000\"\235"
"\001\n\037MessageContainingMapCalledEntry\022L\n\005en"
"try\030\001 \003(\0132=.protobuf_unittest.MessageCon"
"tainingMapCalledEntry.EntryEntry\032,\n\nEntr"
"yEntry\022\013\n\003key\030\001 \001(\005\022\r\n\005value\030\002 \001(\005:\0028\001\"\255"
"\001\n\027TestRecursiveMapMessage\022<\n\001a\030\001 \003(\01321."
"protobuf_unittest.TestRecursiveMapMessag"
"e.AEntry\032T\n\006AEntry\022\013\n\003key\030\001 \001(\t\0229\n\005value"
"\030\002 \001(\0132*.protobuf_unittest.TestRecursive"
"MapMessage:\0028\001*\?\n\007MapEnum\022\020\n\014MAP_ENUM_FO"
"O\020\000\022\020\n\014MAP_ENUM_BAR\020\001\022\020\n\014MAP_ENUM_BAZ\020\002B"
"\003\370\001\001b\006proto3", 6612);
::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(
"google/protobuf/map_unittest.proto", &protobuf_RegisterTypes);
TestMap::default_instance_ = new TestMap();
TestMapSubmessage::default_instance_ = new TestMapSubmessage();
TestMessageMap::default_instance_ = new TestMessageMap();
TestSameTypeMap::default_instance_ = new TestSameTypeMap();
TestRequiredMessageMap::default_instance_ = new TestRequiredMessageMap();
TestArenaMap::default_instance_ = new TestArenaMap();
MessageContainingEnumCalledType::default_instance_ = new MessageContainingEnumCalledType();
MessageContainingMapCalledEntry::default_instance_ = new MessageContainingMapCalledEntry();
TestRecursiveMapMessage::default_instance_ = new TestRecursiveMapMessage();
TestMap::default_instance_->InitAsDefaultInstance();
TestMapSubmessage::default_instance_->InitAsDefaultInstance();
TestMessageMap::default_instance_->InitAsDefaultInstance();
TestSameTypeMap::default_instance_->InitAsDefaultInstance();
TestRequiredMessageMap::default_instance_->InitAsDefaultInstance();
TestArenaMap::default_instance_->InitAsDefaultInstance();
MessageContainingEnumCalledType::default_instance_->InitAsDefaultInstance();
MessageContainingMapCalledEntry::default_instance_->InitAsDefaultInstance();
TestRecursiveMapMessage::default_instance_->InitAsDefaultInstance();
::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_google_2fprotobuf_2fmap_5funittest_2eproto);
}
// Force AddDescriptors() to be called at static initialization time.
struct StaticDescriptorInitializer_google_2fprotobuf_2fmap_5funittest_2eproto {
StaticDescriptorInitializer_google_2fprotobuf_2fmap_5funittest_2eproto() {
protobuf_AddDesc_google_2fprotobuf_2fmap_5funittest_2eproto();
}
} static_descriptor_initializer_google_2fprotobuf_2fmap_5funittest_2eproto_;
const ::google::protobuf::EnumDescriptor* MapEnum_descriptor() {
protobuf_AssignDescriptorsOnce();
return MapEnum_descriptor_;
}
bool MapEnum_IsValid(int value) {
switch(value) {
case 0:
case 1:
case 2:
return true;
default:
return false;
}
}
namespace {
static void MergeFromFail(int line) GOOGLE_ATTRIBUTE_COLD;
static void MergeFromFail(int line) {
GOOGLE_CHECK(false) << __FILE__ << ":" << line;
}
} // namespace
// ===================================================================
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int TestMap::kMapInt32Int32FieldNumber;
const int TestMap::kMapInt64Int64FieldNumber;
const int TestMap::kMapUint32Uint32FieldNumber;
const int TestMap::kMapUint64Uint64FieldNumber;
const int TestMap::kMapSint32Sint32FieldNumber;
const int TestMap::kMapSint64Sint64FieldNumber;
const int TestMap::kMapFixed32Fixed32FieldNumber;
const int TestMap::kMapFixed64Fixed64FieldNumber;
const int TestMap::kMapSfixed32Sfixed32FieldNumber;
const int TestMap::kMapSfixed64Sfixed64FieldNumber;
const int TestMap::kMapInt32FloatFieldNumber;
const int TestMap::kMapInt32DoubleFieldNumber;
const int TestMap::kMapBoolBoolFieldNumber;
const int TestMap::kMapStringStringFieldNumber;
const int TestMap::kMapInt32BytesFieldNumber;
const int TestMap::kMapInt32EnumFieldNumber;
const int TestMap::kMapInt32ForeignMessageFieldNumber;
const int TestMap::kMapStringForeignMessageFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
TestMap::TestMap()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
SharedCtor();
// @@protoc_insertion_point(constructor:protobuf_unittest.TestMap)
}
TestMap::TestMap(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena),
map_int32_int32_(arena),
map_int64_int64_(arena),
map_uint32_uint32_(arena),
map_uint64_uint64_(arena),
map_sint32_sint32_(arena),
map_sint64_sint64_(arena),
map_fixed32_fixed32_(arena),
map_fixed64_fixed64_(arena),
map_sfixed32_sfixed32_(arena),
map_sfixed64_sfixed64_(arena),
map_int32_float_(arena),
map_int32_double_(arena),
map_bool_bool_(arena),
map_string_string_(arena),
map_int32_bytes_(arena),
map_int32_enum_(arena),
map_int32_foreign_message_(arena),
map_string_foreign_message_(arena) {
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:protobuf_unittest.TestMap)
}
void TestMap::InitAsDefaultInstance() {
_is_default_instance_ = true;
}
TestMap::TestMap(const TestMap& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
MergeFrom(from);
// @@protoc_insertion_point(copy_constructor:protobuf_unittest.TestMap)
}
void TestMap::SharedCtor() {
_is_default_instance_ = false;
_cached_size_ = 0;
map_int32_int32_.SetAssignDescriptorCallback(
protobuf_AssignDescriptorsOnce);
map_int32_int32_.SetEntryDescriptor(
&::protobuf_unittest::TestMap_MapInt32Int32Entry_descriptor_);
map_int64_int64_.SetAssignDescriptorCallback(
protobuf_AssignDescriptorsOnce);
map_int64_int64_.SetEntryDescriptor(
&::protobuf_unittest::TestMap_MapInt64Int64Entry_descriptor_);
map_uint32_uint32_.SetAssignDescriptorCallback(
protobuf_AssignDescriptorsOnce);
map_uint32_uint32_.SetEntryDescriptor(
&::protobuf_unittest::TestMap_MapUint32Uint32Entry_descriptor_);
map_uint64_uint64_.SetAssignDescriptorCallback(
protobuf_AssignDescriptorsOnce);
map_uint64_uint64_.SetEntryDescriptor(
&::protobuf_unittest::TestMap_MapUint64Uint64Entry_descriptor_);
map_sint32_sint32_.SetAssignDescriptorCallback(
protobuf_AssignDescriptorsOnce);
map_sint32_sint32_.SetEntryDescriptor(
&::protobuf_unittest::TestMap_MapSint32Sint32Entry_descriptor_);
map_sint64_sint64_.SetAssignDescriptorCallback(
protobuf_AssignDescriptorsOnce);
map_sint64_sint64_.SetEntryDescriptor(
&::protobuf_unittest::TestMap_MapSint64Sint64Entry_descriptor_);
map_fixed32_fixed32_.SetAssignDescriptorCallback(
protobuf_AssignDescriptorsOnce);
map_fixed32_fixed32_.SetEntryDescriptor(
&::protobuf_unittest::TestMap_MapFixed32Fixed32Entry_descriptor_);
map_fixed64_fixed64_.SetAssignDescriptorCallback(
protobuf_AssignDescriptorsOnce);
map_fixed64_fixed64_.SetEntryDescriptor(
&::protobuf_unittest::TestMap_MapFixed64Fixed64Entry_descriptor_);
map_sfixed32_sfixed32_.SetAssignDescriptorCallback(
protobuf_AssignDescriptorsOnce);
map_sfixed32_sfixed32_.SetEntryDescriptor(
&::protobuf_unittest::TestMap_MapSfixed32Sfixed32Entry_descriptor_);
map_sfixed64_sfixed64_.SetAssignDescriptorCallback(
protobuf_AssignDescriptorsOnce);
map_sfixed64_sfixed64_.SetEntryDescriptor(
&::protobuf_unittest::TestMap_MapSfixed64Sfixed64Entry_descriptor_);
map_int32_float_.SetAssignDescriptorCallback(
protobuf_AssignDescriptorsOnce);
map_int32_float_.SetEntryDescriptor(
&::protobuf_unittest::TestMap_MapInt32FloatEntry_descriptor_);
map_int32_double_.SetAssignDescriptorCallback(
protobuf_AssignDescriptorsOnce);
map_int32_double_.SetEntryDescriptor(
&::protobuf_unittest::TestMap_MapInt32DoubleEntry_descriptor_);
map_bool_bool_.SetAssignDescriptorCallback(
protobuf_AssignDescriptorsOnce);
map_bool_bool_.SetEntryDescriptor(
&::protobuf_unittest::TestMap_MapBoolBoolEntry_descriptor_);
map_string_string_.SetAssignDescriptorCallback(
protobuf_AssignDescriptorsOnce);
map_string_string_.SetEntryDescriptor(
&::protobuf_unittest::TestMap_MapStringStringEntry_descriptor_);
map_int32_bytes_.SetAssignDescriptorCallback(
protobuf_AssignDescriptorsOnce);
map_int32_bytes_.SetEntryDescriptor(
&::protobuf_unittest::TestMap_MapInt32BytesEntry_descriptor_);
map_int32_enum_.SetAssignDescriptorCallback(
protobuf_AssignDescriptorsOnce);
map_int32_enum_.SetEntryDescriptor(
&::protobuf_unittest::TestMap_MapInt32EnumEntry_descriptor_);
map_int32_foreign_message_.SetAssignDescriptorCallback(
protobuf_AssignDescriptorsOnce);
map_int32_foreign_message_.SetEntryDescriptor(
&::protobuf_unittest::TestMap_MapInt32ForeignMessageEntry_descriptor_);
map_string_foreign_message_.SetAssignDescriptorCallback(
protobuf_AssignDescriptorsOnce);
map_string_foreign_message_.SetEntryDescriptor(
&::protobuf_unittest::TestMap_MapStringForeignMessageEntry_descriptor_);
}
TestMap::~TestMap() {
// @@protoc_insertion_point(destructor:protobuf_unittest.TestMap)
SharedDtor();
}
void TestMap::SharedDtor() {
if (GetArenaNoVirtual() != NULL) {
return;
}
if (this != default_instance_) {
}
}
void TestMap::ArenaDtor(void* object) {
TestMap* _this = reinterpret_cast< TestMap* >(object);
(void)_this;
}
void TestMap::RegisterArenaDtor(::google::protobuf::Arena* arena) {
}
void TestMap::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* TestMap::descriptor() {
protobuf_AssignDescriptorsOnce();
return TestMap_descriptor_;
}
const TestMap& TestMap::default_instance() {
if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2fmap_5funittest_2eproto();
return *default_instance_;
}
TestMap* TestMap::default_instance_ = NULL;
TestMap* TestMap::New(::google::protobuf::Arena* arena) const {
return ::google::protobuf::Arena::CreateMessage<TestMap>(arena);
}
void TestMap::Clear() {
// @@protoc_insertion_point(message_clear_start:protobuf_unittest.TestMap)
map_int32_int32_.Clear();
map_int64_int64_.Clear();
map_uint32_uint32_.Clear();
map_uint64_uint64_.Clear();
map_sint32_sint32_.Clear();
map_sint64_sint64_.Clear();
map_fixed32_fixed32_.Clear();
map_fixed64_fixed64_.Clear();
map_sfixed32_sfixed32_.Clear();
map_sfixed64_sfixed64_.Clear();
map_int32_float_.Clear();
map_int32_double_.Clear();
map_bool_bool_.Clear();
map_string_string_.Clear();
map_int32_bytes_.Clear();
map_int32_enum_.Clear();
map_int32_foreign_message_.Clear();
map_string_foreign_message_.Clear();
}
bool TestMap::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:protobuf_unittest.TestMap)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(16383);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// map<int32, int32> map_int32_int32 = 1;
case 1: {
if (tag == 10) {
DO_(input->IncrementRecursionDepth());
parse_loop_map_int32_int32:
::google::protobuf::scoped_ptr<TestMap_MapInt32Int32Entry> entry(map_int32_int32_.NewEntry());
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, entry.get()));
(*mutable_map_int32_int32())[entry->key()] = *entry->mutable_value();
if (entry->GetArena() != NULL) entry.release();
} else {
goto handle_unusual;
}
if (input->ExpectTag(10)) goto parse_loop_map_int32_int32;
if (input->ExpectTag(18)) goto parse_loop_map_int64_int64;
input->UnsafeDecrementRecursionDepth();
break;
}
// map<int64, int64> map_int64_int64 = 2;
case 2: {
if (tag == 18) {
DO_(input->IncrementRecursionDepth());
parse_loop_map_int64_int64:
::google::protobuf::scoped_ptr<TestMap_MapInt64Int64Entry> entry(map_int64_int64_.NewEntry());
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, entry.get()));
(*mutable_map_int64_int64())[entry->key()] = *entry->mutable_value();
if (entry->GetArena() != NULL) entry.release();
} else {
goto handle_unusual;
}
if (input->ExpectTag(18)) goto parse_loop_map_int64_int64;
if (input->ExpectTag(26)) goto parse_loop_map_uint32_uint32;
input->UnsafeDecrementRecursionDepth();
break;
}
// map<uint32, uint32> map_uint32_uint32 = 3;
case 3: {
if (tag == 26) {
DO_(input->IncrementRecursionDepth());
parse_loop_map_uint32_uint32:
::google::protobuf::scoped_ptr<TestMap_MapUint32Uint32Entry> entry(map_uint32_uint32_.NewEntry());
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, entry.get()));
(*mutable_map_uint32_uint32())[entry->key()] = *entry->mutable_value();
if (entry->GetArena() != NULL) entry.release();
} else {
goto handle_unusual;
}
if (input->ExpectTag(26)) goto parse_loop_map_uint32_uint32;
if (input->ExpectTag(34)) goto parse_loop_map_uint64_uint64;
input->UnsafeDecrementRecursionDepth();
break;
}
// map<uint64, uint64> map_uint64_uint64 = 4;
case 4: {
if (tag == 34) {
DO_(input->IncrementRecursionDepth());
parse_loop_map_uint64_uint64:
::google::protobuf::scoped_ptr<TestMap_MapUint64Uint64Entry> entry(map_uint64_uint64_.NewEntry());
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, entry.get()));
(*mutable_map_uint64_uint64())[entry->key()] = *entry->mutable_value();
if (entry->GetArena() != NULL) entry.release();
} else {
goto handle_unusual;
}
if (input->ExpectTag(34)) goto parse_loop_map_uint64_uint64;
if (input->ExpectTag(42)) goto parse_loop_map_sint32_sint32;
input->UnsafeDecrementRecursionDepth();
break;
}
// map<sint32, sint32> map_sint32_sint32 = 5;
case 5: {
if (tag == 42) {
DO_(input->IncrementRecursionDepth());
parse_loop_map_sint32_sint32:
::google::protobuf::scoped_ptr<TestMap_MapSint32Sint32Entry> entry(map_sint32_sint32_.NewEntry());
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, entry.get()));
(*mutable_map_sint32_sint32())[entry->key()] = *entry->mutable_value();
if (entry->GetArena() != NULL) entry.release();
} else {
goto handle_unusual;
}
if (input->ExpectTag(42)) goto parse_loop_map_sint32_sint32;
if (input->ExpectTag(50)) goto parse_loop_map_sint64_sint64;
input->UnsafeDecrementRecursionDepth();
break;
}
// map<sint64, sint64> map_sint64_sint64 = 6;
case 6: {
if (tag == 50) {
DO_(input->IncrementRecursionDepth());
parse_loop_map_sint64_sint64:
::google::protobuf::scoped_ptr<TestMap_MapSint64Sint64Entry> entry(map_sint64_sint64_.NewEntry());
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, entry.get()));
(*mutable_map_sint64_sint64())[entry->key()] = *entry->mutable_value();
if (entry->GetArena() != NULL) entry.release();
} else {
goto handle_unusual;
}
if (input->ExpectTag(50)) goto parse_loop_map_sint64_sint64;
if (input->ExpectTag(58)) goto parse_loop_map_fixed32_fixed32;
input->UnsafeDecrementRecursionDepth();
break;
}
// map<fixed32, fixed32> map_fixed32_fixed32 = 7;
case 7: {
if (tag == 58) {
DO_(input->IncrementRecursionDepth());
parse_loop_map_fixed32_fixed32:
::google::protobuf::scoped_ptr<TestMap_MapFixed32Fixed32Entry> entry(map_fixed32_fixed32_.NewEntry());
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, entry.get()));
(*mutable_map_fixed32_fixed32())[entry->key()] = *entry->mutable_value();
if (entry->GetArena() != NULL) entry.release();
} else {
goto handle_unusual;
}
if (input->ExpectTag(58)) goto parse_loop_map_fixed32_fixed32;
if (input->ExpectTag(66)) goto parse_loop_map_fixed64_fixed64;
input->UnsafeDecrementRecursionDepth();
break;
}
// map<fixed64, fixed64> map_fixed64_fixed64 = 8;
case 8: {
if (tag == 66) {
DO_(input->IncrementRecursionDepth());
parse_loop_map_fixed64_fixed64:
::google::protobuf::scoped_ptr<TestMap_MapFixed64Fixed64Entry> entry(map_fixed64_fixed64_.NewEntry());
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, entry.get()));
(*mutable_map_fixed64_fixed64())[entry->key()] = *entry->mutable_value();
if (entry->GetArena() != NULL) entry.release();
} else {
goto handle_unusual;
}
if (input->ExpectTag(66)) goto parse_loop_map_fixed64_fixed64;
if (input->ExpectTag(74)) goto parse_loop_map_sfixed32_sfixed32;
input->UnsafeDecrementRecursionDepth();
break;
}
// map<sfixed32, sfixed32> map_sfixed32_sfixed32 = 9;
case 9: {
if (tag == 74) {
DO_(input->IncrementRecursionDepth());
parse_loop_map_sfixed32_sfixed32:
::google::protobuf::scoped_ptr<TestMap_MapSfixed32Sfixed32Entry> entry(map_sfixed32_sfixed32_.NewEntry());
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, entry.get()));
(*mutable_map_sfixed32_sfixed32())[entry->key()] = *entry->mutable_value();
if (entry->GetArena() != NULL) entry.release();
} else {
goto handle_unusual;
}
if (input->ExpectTag(74)) goto parse_loop_map_sfixed32_sfixed32;
if (input->ExpectTag(82)) goto parse_loop_map_sfixed64_sfixed64;
input->UnsafeDecrementRecursionDepth();
break;
}
// map<sfixed64, sfixed64> map_sfixed64_sfixed64 = 10;
case 10: {
if (tag == 82) {
DO_(input->IncrementRecursionDepth());
parse_loop_map_sfixed64_sfixed64:
::google::protobuf::scoped_ptr<TestMap_MapSfixed64Sfixed64Entry> entry(map_sfixed64_sfixed64_.NewEntry());
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, entry.get()));
(*mutable_map_sfixed64_sfixed64())[entry->key()] = *entry->mutable_value();
if (entry->GetArena() != NULL) entry.release();
} else {
goto handle_unusual;
}
if (input->ExpectTag(82)) goto parse_loop_map_sfixed64_sfixed64;
if (input->ExpectTag(90)) goto parse_loop_map_int32_float;
input->UnsafeDecrementRecursionDepth();
break;
}
// map<int32, float> map_int32_float = 11;
case 11: {
if (tag == 90) {
DO_(input->IncrementRecursionDepth());
parse_loop_map_int32_float:
::google::protobuf::scoped_ptr<TestMap_MapInt32FloatEntry> entry(map_int32_float_.NewEntry());
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, entry.get()));
(*mutable_map_int32_float())[entry->key()] = *entry->mutable_value();
if (entry->GetArena() != NULL) entry.release();
} else {
goto handle_unusual;
}
if (input->ExpectTag(90)) goto parse_loop_map_int32_float;
if (input->ExpectTag(98)) goto parse_loop_map_int32_double;
input->UnsafeDecrementRecursionDepth();
break;
}
// map<int32, double> map_int32_double = 12;
case 12: {
if (tag == 98) {
DO_(input->IncrementRecursionDepth());
parse_loop_map_int32_double:
::google::protobuf::scoped_ptr<TestMap_MapInt32DoubleEntry> entry(map_int32_double_.NewEntry());
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, entry.get()));
(*mutable_map_int32_double())[entry->key()] = *entry->mutable_value();
if (entry->GetArena() != NULL) entry.release();
} else {
goto handle_unusual;
}
if (input->ExpectTag(98)) goto parse_loop_map_int32_double;
if (input->ExpectTag(106)) goto parse_loop_map_bool_bool;
input->UnsafeDecrementRecursionDepth();
break;
}
// map<bool, bool> map_bool_bool = 13;
case 13: {
if (tag == 106) {
DO_(input->IncrementRecursionDepth());
parse_loop_map_bool_bool:
::google::protobuf::scoped_ptr<TestMap_MapBoolBoolEntry> entry(map_bool_bool_.NewEntry());
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, entry.get()));
(*mutable_map_bool_bool())[entry->key()] = *entry->mutable_value();
if (entry->GetArena() != NULL) entry.release();
} else {
goto handle_unusual;
}
if (input->ExpectTag(106)) goto parse_loop_map_bool_bool;
if (input->ExpectTag(114)) goto parse_loop_map_string_string;
input->UnsafeDecrementRecursionDepth();
break;
}
// map<string, string> map_string_string = 14;
case 14: {
if (tag == 114) {
DO_(input->IncrementRecursionDepth());
parse_loop_map_string_string:
::google::protobuf::scoped_ptr<TestMap_MapStringStringEntry> entry(map_string_string_.NewEntry());
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, entry.get()));
(*mutable_map_string_string())[entry->key()] = *entry->mutable_value();
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
entry->key().data(), entry->key().length(),
::google::protobuf::internal::WireFormatLite::PARSE,
"protobuf_unittest.TestMap.MapStringStringEntry.key"));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
entry->mutable_value()->data(),
entry->mutable_value()->length(),
::google::protobuf::internal::WireFormatLite::PARSE,
"protobuf_unittest.TestMap.MapStringStringEntry.value"));
if (entry->GetArena() != NULL) entry.release();
} else {
goto handle_unusual;
}
if (input->ExpectTag(114)) goto parse_loop_map_string_string;
if (input->ExpectTag(122)) goto parse_loop_map_int32_bytes;
input->UnsafeDecrementRecursionDepth();
break;
}
// map<int32, bytes> map_int32_bytes = 15;
case 15: {
if (tag == 122) {
DO_(input->IncrementRecursionDepth());
parse_loop_map_int32_bytes:
::google::protobuf::scoped_ptr<TestMap_MapInt32BytesEntry> entry(map_int32_bytes_.NewEntry());
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, entry.get()));
(*mutable_map_int32_bytes())[entry->key()] = *entry->mutable_value();
if (entry->GetArena() != NULL) entry.release();
} else {
goto handle_unusual;
}
if (input->ExpectTag(122)) goto parse_loop_map_int32_bytes;
if (input->ExpectTag(130)) goto parse_loop_map_int32_enum;
input->UnsafeDecrementRecursionDepth();
break;
}
// map<int32, .protobuf_unittest.MapEnum> map_int32_enum = 16;
case 16: {
if (tag == 130) {
DO_(input->IncrementRecursionDepth());
parse_loop_map_int32_enum:
::google::protobuf::scoped_ptr<TestMap_MapInt32EnumEntry> entry(map_int32_enum_.NewEntry());
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, entry.get()));
(*mutable_map_int32_enum())[entry->key()] =
static_cast< ::protobuf_unittest::MapEnum >(*entry->mutable_value());
if (entry->GetArena() != NULL) entry.release();
} else {
goto handle_unusual;
}
if (input->ExpectTag(130)) goto parse_loop_map_int32_enum;
if (input->ExpectTag(138)) goto parse_loop_map_int32_foreign_message;
input->UnsafeDecrementRecursionDepth();
break;
}
// map<int32, .protobuf_unittest.ForeignMessage> map_int32_foreign_message = 17;
case 17: {
if (tag == 138) {
DO_(input->IncrementRecursionDepth());
parse_loop_map_int32_foreign_message:
::google::protobuf::scoped_ptr<TestMap_MapInt32ForeignMessageEntry> entry(map_int32_foreign_message_.NewEntry());
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, entry.get()));
(*mutable_map_int32_foreign_message())[entry->key()].Swap(entry->mutable_value());
if (entry->GetArena() != NULL) entry.release();
} else {
goto handle_unusual;
}
if (input->ExpectTag(138)) goto parse_loop_map_int32_foreign_message;
if (input->ExpectTag(146)) goto parse_loop_map_string_foreign_message;
input->UnsafeDecrementRecursionDepth();
break;
}
// map<string, .protobuf_unittest.ForeignMessage> map_string_foreign_message = 18;
case 18: {
if (tag == 146) {
DO_(input->IncrementRecursionDepth());
parse_loop_map_string_foreign_message:
::google::protobuf::scoped_ptr<TestMap_MapStringForeignMessageEntry> entry(map_string_foreign_message_.NewEntry());
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, entry.get()));
(*mutable_map_string_foreign_message())[entry->key()].Swap(entry->mutable_value());
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
entry->key().data(), entry->key().length(),
::google::protobuf::internal::WireFormatLite::PARSE,
"protobuf_unittest.TestMap.MapStringForeignMessageEntry.key"));
if (entry->GetArena() != NULL) entry.release();
} else {
goto handle_unusual;
}
if (input->ExpectTag(146)) goto parse_loop_map_string_foreign_message;
input->UnsafeDecrementRecursionDepth();
if (input->ExpectAtEnd()) goto success;
break;
}
default: {
handle_unusual:
if (tag == 0 ||
::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
goto success;
}
DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:protobuf_unittest.TestMap)
return true;
failure:
// @@protoc_insertion_point(parse_failure:protobuf_unittest.TestMap)
return false;
#undef DO_
}
void TestMap::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:protobuf_unittest.TestMap)
// map<int32, int32> map_int32_int32 = 1;
{
::google::protobuf::scoped_ptr<TestMap_MapInt32Int32Entry> entry;
for (::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::int32 >::const_iterator
it = this->map_int32_int32().begin();
it != this->map_int32_int32().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_int32_int32_.NewEntryWrapper(it->first, it->second));
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
1, *entry, output);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<int64, int64> map_int64_int64 = 2;
{
::google::protobuf::scoped_ptr<TestMap_MapInt64Int64Entry> entry;
for (::google::protobuf::Map< ::google::protobuf::int64, ::google::protobuf::int64 >::const_iterator
it = this->map_int64_int64().begin();
it != this->map_int64_int64().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_int64_int64_.NewEntryWrapper(it->first, it->second));
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
2, *entry, output);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<uint32, uint32> map_uint32_uint32 = 3;
{
::google::protobuf::scoped_ptr<TestMap_MapUint32Uint32Entry> entry;
for (::google::protobuf::Map< ::google::protobuf::uint32, ::google::protobuf::uint32 >::const_iterator
it = this->map_uint32_uint32().begin();
it != this->map_uint32_uint32().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_uint32_uint32_.NewEntryWrapper(it->first, it->second));
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
3, *entry, output);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<uint64, uint64> map_uint64_uint64 = 4;
{
::google::protobuf::scoped_ptr<TestMap_MapUint64Uint64Entry> entry;
for (::google::protobuf::Map< ::google::protobuf::uint64, ::google::protobuf::uint64 >::const_iterator
it = this->map_uint64_uint64().begin();
it != this->map_uint64_uint64().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_uint64_uint64_.NewEntryWrapper(it->first, it->second));
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
4, *entry, output);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<sint32, sint32> map_sint32_sint32 = 5;
{
::google::protobuf::scoped_ptr<TestMap_MapSint32Sint32Entry> entry;
for (::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::int32 >::const_iterator
it = this->map_sint32_sint32().begin();
it != this->map_sint32_sint32().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_sint32_sint32_.NewEntryWrapper(it->first, it->second));
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
5, *entry, output);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<sint64, sint64> map_sint64_sint64 = 6;
{
::google::protobuf::scoped_ptr<TestMap_MapSint64Sint64Entry> entry;
for (::google::protobuf::Map< ::google::protobuf::int64, ::google::protobuf::int64 >::const_iterator
it = this->map_sint64_sint64().begin();
it != this->map_sint64_sint64().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_sint64_sint64_.NewEntryWrapper(it->first, it->second));
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
6, *entry, output);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<fixed32, fixed32> map_fixed32_fixed32 = 7;
{
::google::protobuf::scoped_ptr<TestMap_MapFixed32Fixed32Entry> entry;
for (::google::protobuf::Map< ::google::protobuf::uint32, ::google::protobuf::uint32 >::const_iterator
it = this->map_fixed32_fixed32().begin();
it != this->map_fixed32_fixed32().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_fixed32_fixed32_.NewEntryWrapper(it->first, it->second));
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
7, *entry, output);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<fixed64, fixed64> map_fixed64_fixed64 = 8;
{
::google::protobuf::scoped_ptr<TestMap_MapFixed64Fixed64Entry> entry;
for (::google::protobuf::Map< ::google::protobuf::uint64, ::google::protobuf::uint64 >::const_iterator
it = this->map_fixed64_fixed64().begin();
it != this->map_fixed64_fixed64().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_fixed64_fixed64_.NewEntryWrapper(it->first, it->second));
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
8, *entry, output);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<sfixed32, sfixed32> map_sfixed32_sfixed32 = 9;
{
::google::protobuf::scoped_ptr<TestMap_MapSfixed32Sfixed32Entry> entry;
for (::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::int32 >::const_iterator
it = this->map_sfixed32_sfixed32().begin();
it != this->map_sfixed32_sfixed32().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_sfixed32_sfixed32_.NewEntryWrapper(it->first, it->second));
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
9, *entry, output);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<sfixed64, sfixed64> map_sfixed64_sfixed64 = 10;
{
::google::protobuf::scoped_ptr<TestMap_MapSfixed64Sfixed64Entry> entry;
for (::google::protobuf::Map< ::google::protobuf::int64, ::google::protobuf::int64 >::const_iterator
it = this->map_sfixed64_sfixed64().begin();
it != this->map_sfixed64_sfixed64().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_sfixed64_sfixed64_.NewEntryWrapper(it->first, it->second));
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
10, *entry, output);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<int32, float> map_int32_float = 11;
{
::google::protobuf::scoped_ptr<TestMap_MapInt32FloatEntry> entry;
for (::google::protobuf::Map< ::google::protobuf::int32, float >::const_iterator
it = this->map_int32_float().begin();
it != this->map_int32_float().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_int32_float_.NewEntryWrapper(it->first, it->second));
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
11, *entry, output);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<int32, double> map_int32_double = 12;
{
::google::protobuf::scoped_ptr<TestMap_MapInt32DoubleEntry> entry;
for (::google::protobuf::Map< ::google::protobuf::int32, double >::const_iterator
it = this->map_int32_double().begin();
it != this->map_int32_double().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_int32_double_.NewEntryWrapper(it->first, it->second));
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
12, *entry, output);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<bool, bool> map_bool_bool = 13;
{
::google::protobuf::scoped_ptr<TestMap_MapBoolBoolEntry> entry;
for (::google::protobuf::Map< bool, bool >::const_iterator
it = this->map_bool_bool().begin();
it != this->map_bool_bool().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_bool_bool_.NewEntryWrapper(it->first, it->second));
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
13, *entry, output);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<string, string> map_string_string = 14;
{
::google::protobuf::scoped_ptr<TestMap_MapStringStringEntry> entry;
for (::google::protobuf::Map< ::std::string, ::std::string >::const_iterator
it = this->map_string_string().begin();
it != this->map_string_string().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_string_string_.NewEntryWrapper(it->first, it->second));
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
14, *entry, output);
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
it->first.data(), it->first.length(),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"protobuf_unittest.TestMap.MapStringStringEntry.key");
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
it->second.data(), it->second.length(),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"protobuf_unittest.TestMap.MapStringStringEntry.value");
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<int32, bytes> map_int32_bytes = 15;
{
::google::protobuf::scoped_ptr<TestMap_MapInt32BytesEntry> entry;
for (::google::protobuf::Map< ::google::protobuf::int32, ::std::string >::const_iterator
it = this->map_int32_bytes().begin();
it != this->map_int32_bytes().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_int32_bytes_.NewEntryWrapper(it->first, it->second));
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
15, *entry, output);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<int32, .protobuf_unittest.MapEnum> map_int32_enum = 16;
{
::google::protobuf::scoped_ptr<TestMap_MapInt32EnumEntry> entry;
for (::google::protobuf::Map< ::google::protobuf::int32, ::protobuf_unittest::MapEnum >::const_iterator
it = this->map_int32_enum().begin();
it != this->map_int32_enum().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_int32_enum_.NewEnumEntryWrapper(it->first, it->second));
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
16, *entry, output);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<int32, .protobuf_unittest.ForeignMessage> map_int32_foreign_message = 17;
{
::google::protobuf::scoped_ptr<TestMap_MapInt32ForeignMessageEntry> entry;
for (::google::protobuf::Map< ::google::protobuf::int32, ::protobuf_unittest::ForeignMessage >::const_iterator
it = this->map_int32_foreign_message().begin();
it != this->map_int32_foreign_message().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_int32_foreign_message_.NewEntryWrapper(it->first, it->second));
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
17, *entry, output);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<string, .protobuf_unittest.ForeignMessage> map_string_foreign_message = 18;
{
::google::protobuf::scoped_ptr<TestMap_MapStringForeignMessageEntry> entry;
for (::google::protobuf::Map< ::std::string, ::protobuf_unittest::ForeignMessage >::const_iterator
it = this->map_string_foreign_message().begin();
it != this->map_string_foreign_message().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_string_foreign_message_.NewEntryWrapper(it->first, it->second));
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
18, *entry, output);
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
it->first.data(), it->first.length(),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"protobuf_unittest.TestMap.MapStringForeignMessageEntry.key");
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// @@protoc_insertion_point(serialize_end:protobuf_unittest.TestMap)
}
::google::protobuf::uint8* TestMap::SerializeWithCachedSizesToArray(
::google::protobuf::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:protobuf_unittest.TestMap)
// map<int32, int32> map_int32_int32 = 1;
{
::google::protobuf::scoped_ptr<TestMap_MapInt32Int32Entry> entry;
for (::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::int32 >::const_iterator
it = this->map_int32_int32().begin();
it != this->map_int32_int32().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_int32_int32_.NewEntryWrapper(it->first, it->second));
target = ::google::protobuf::internal::WireFormatLite::
WriteMessageNoVirtualToArray(
1, *entry, target);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<int64, int64> map_int64_int64 = 2;
{
::google::protobuf::scoped_ptr<TestMap_MapInt64Int64Entry> entry;
for (::google::protobuf::Map< ::google::protobuf::int64, ::google::protobuf::int64 >::const_iterator
it = this->map_int64_int64().begin();
it != this->map_int64_int64().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_int64_int64_.NewEntryWrapper(it->first, it->second));
target = ::google::protobuf::internal::WireFormatLite::
WriteMessageNoVirtualToArray(
2, *entry, target);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<uint32, uint32> map_uint32_uint32 = 3;
{
::google::protobuf::scoped_ptr<TestMap_MapUint32Uint32Entry> entry;
for (::google::protobuf::Map< ::google::protobuf::uint32, ::google::protobuf::uint32 >::const_iterator
it = this->map_uint32_uint32().begin();
it != this->map_uint32_uint32().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_uint32_uint32_.NewEntryWrapper(it->first, it->second));
target = ::google::protobuf::internal::WireFormatLite::
WriteMessageNoVirtualToArray(
3, *entry, target);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<uint64, uint64> map_uint64_uint64 = 4;
{
::google::protobuf::scoped_ptr<TestMap_MapUint64Uint64Entry> entry;
for (::google::protobuf::Map< ::google::protobuf::uint64, ::google::protobuf::uint64 >::const_iterator
it = this->map_uint64_uint64().begin();
it != this->map_uint64_uint64().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_uint64_uint64_.NewEntryWrapper(it->first, it->second));
target = ::google::protobuf::internal::WireFormatLite::
WriteMessageNoVirtualToArray(
4, *entry, target);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<sint32, sint32> map_sint32_sint32 = 5;
{
::google::protobuf::scoped_ptr<TestMap_MapSint32Sint32Entry> entry;
for (::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::int32 >::const_iterator
it = this->map_sint32_sint32().begin();
it != this->map_sint32_sint32().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_sint32_sint32_.NewEntryWrapper(it->first, it->second));
target = ::google::protobuf::internal::WireFormatLite::
WriteMessageNoVirtualToArray(
5, *entry, target);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<sint64, sint64> map_sint64_sint64 = 6;
{
::google::protobuf::scoped_ptr<TestMap_MapSint64Sint64Entry> entry;
for (::google::protobuf::Map< ::google::protobuf::int64, ::google::protobuf::int64 >::const_iterator
it = this->map_sint64_sint64().begin();
it != this->map_sint64_sint64().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_sint64_sint64_.NewEntryWrapper(it->first, it->second));
target = ::google::protobuf::internal::WireFormatLite::
WriteMessageNoVirtualToArray(
6, *entry, target);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<fixed32, fixed32> map_fixed32_fixed32 = 7;
{
::google::protobuf::scoped_ptr<TestMap_MapFixed32Fixed32Entry> entry;
for (::google::protobuf::Map< ::google::protobuf::uint32, ::google::protobuf::uint32 >::const_iterator
it = this->map_fixed32_fixed32().begin();
it != this->map_fixed32_fixed32().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_fixed32_fixed32_.NewEntryWrapper(it->first, it->second));
target = ::google::protobuf::internal::WireFormatLite::
WriteMessageNoVirtualToArray(
7, *entry, target);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<fixed64, fixed64> map_fixed64_fixed64 = 8;
{
::google::protobuf::scoped_ptr<TestMap_MapFixed64Fixed64Entry> entry;
for (::google::protobuf::Map< ::google::protobuf::uint64, ::google::protobuf::uint64 >::const_iterator
it = this->map_fixed64_fixed64().begin();
it != this->map_fixed64_fixed64().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_fixed64_fixed64_.NewEntryWrapper(it->first, it->second));
target = ::google::protobuf::internal::WireFormatLite::
WriteMessageNoVirtualToArray(
8, *entry, target);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<sfixed32, sfixed32> map_sfixed32_sfixed32 = 9;
{
::google::protobuf::scoped_ptr<TestMap_MapSfixed32Sfixed32Entry> entry;
for (::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::int32 >::const_iterator
it = this->map_sfixed32_sfixed32().begin();
it != this->map_sfixed32_sfixed32().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_sfixed32_sfixed32_.NewEntryWrapper(it->first, it->second));
target = ::google::protobuf::internal::WireFormatLite::
WriteMessageNoVirtualToArray(
9, *entry, target);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<sfixed64, sfixed64> map_sfixed64_sfixed64 = 10;
{
::google::protobuf::scoped_ptr<TestMap_MapSfixed64Sfixed64Entry> entry;
for (::google::protobuf::Map< ::google::protobuf::int64, ::google::protobuf::int64 >::const_iterator
it = this->map_sfixed64_sfixed64().begin();
it != this->map_sfixed64_sfixed64().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_sfixed64_sfixed64_.NewEntryWrapper(it->first, it->second));
target = ::google::protobuf::internal::WireFormatLite::
WriteMessageNoVirtualToArray(
10, *entry, target);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<int32, float> map_int32_float = 11;
{
::google::protobuf::scoped_ptr<TestMap_MapInt32FloatEntry> entry;
for (::google::protobuf::Map< ::google::protobuf::int32, float >::const_iterator
it = this->map_int32_float().begin();
it != this->map_int32_float().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_int32_float_.NewEntryWrapper(it->first, it->second));
target = ::google::protobuf::internal::WireFormatLite::
WriteMessageNoVirtualToArray(
11, *entry, target);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<int32, double> map_int32_double = 12;
{
::google::protobuf::scoped_ptr<TestMap_MapInt32DoubleEntry> entry;
for (::google::protobuf::Map< ::google::protobuf::int32, double >::const_iterator
it = this->map_int32_double().begin();
it != this->map_int32_double().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_int32_double_.NewEntryWrapper(it->first, it->second));
target = ::google::protobuf::internal::WireFormatLite::
WriteMessageNoVirtualToArray(
12, *entry, target);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<bool, bool> map_bool_bool = 13;
{
::google::protobuf::scoped_ptr<TestMap_MapBoolBoolEntry> entry;
for (::google::protobuf::Map< bool, bool >::const_iterator
it = this->map_bool_bool().begin();
it != this->map_bool_bool().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_bool_bool_.NewEntryWrapper(it->first, it->second));
target = ::google::protobuf::internal::WireFormatLite::
WriteMessageNoVirtualToArray(
13, *entry, target);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<string, string> map_string_string = 14;
{
::google::protobuf::scoped_ptr<TestMap_MapStringStringEntry> entry;
for (::google::protobuf::Map< ::std::string, ::std::string >::const_iterator
it = this->map_string_string().begin();
it != this->map_string_string().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_string_string_.NewEntryWrapper(it->first, it->second));
target = ::google::protobuf::internal::WireFormatLite::
WriteMessageNoVirtualToArray(
14, *entry, target);
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
it->first.data(), it->first.length(),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"protobuf_unittest.TestMap.MapStringStringEntry.key");
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
it->second.data(), it->second.length(),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"protobuf_unittest.TestMap.MapStringStringEntry.value");
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<int32, bytes> map_int32_bytes = 15;
{
::google::protobuf::scoped_ptr<TestMap_MapInt32BytesEntry> entry;
for (::google::protobuf::Map< ::google::protobuf::int32, ::std::string >::const_iterator
it = this->map_int32_bytes().begin();
it != this->map_int32_bytes().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_int32_bytes_.NewEntryWrapper(it->first, it->second));
target = ::google::protobuf::internal::WireFormatLite::
WriteMessageNoVirtualToArray(
15, *entry, target);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<int32, .protobuf_unittest.MapEnum> map_int32_enum = 16;
{
::google::protobuf::scoped_ptr<TestMap_MapInt32EnumEntry> entry;
for (::google::protobuf::Map< ::google::protobuf::int32, ::protobuf_unittest::MapEnum >::const_iterator
it = this->map_int32_enum().begin();
it != this->map_int32_enum().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_int32_enum_.NewEnumEntryWrapper(it->first, it->second));
target = ::google::protobuf::internal::WireFormatLite::
WriteMessageNoVirtualToArray(
16, *entry, target);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<int32, .protobuf_unittest.ForeignMessage> map_int32_foreign_message = 17;
{
::google::protobuf::scoped_ptr<TestMap_MapInt32ForeignMessageEntry> entry;
for (::google::protobuf::Map< ::google::protobuf::int32, ::protobuf_unittest::ForeignMessage >::const_iterator
it = this->map_int32_foreign_message().begin();
it != this->map_int32_foreign_message().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_int32_foreign_message_.NewEntryWrapper(it->first, it->second));
target = ::google::protobuf::internal::WireFormatLite::
WriteMessageNoVirtualToArray(
17, *entry, target);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<string, .protobuf_unittest.ForeignMessage> map_string_foreign_message = 18;
{
::google::protobuf::scoped_ptr<TestMap_MapStringForeignMessageEntry> entry;
for (::google::protobuf::Map< ::std::string, ::protobuf_unittest::ForeignMessage >::const_iterator
it = this->map_string_foreign_message().begin();
it != this->map_string_foreign_message().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_string_foreign_message_.NewEntryWrapper(it->first, it->second));
target = ::google::protobuf::internal::WireFormatLite::
WriteMessageNoVirtualToArray(
18, *entry, target);
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
it->first.data(), it->first.length(),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"protobuf_unittest.TestMap.MapStringForeignMessageEntry.key");
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// @@protoc_insertion_point(serialize_to_array_end:protobuf_unittest.TestMap)
return target;
}
int TestMap::ByteSize() const {
// @@protoc_insertion_point(message_byte_size_start:protobuf_unittest.TestMap)
int total_size = 0;
// map<int32, int32> map_int32_int32 = 1;
total_size += 1 * this->map_int32_int32_size();
{
::google::protobuf::scoped_ptr<TestMap_MapInt32Int32Entry> entry;
for (::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::int32 >::const_iterator
it = this->map_int32_int32().begin();
it != this->map_int32_int32().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_int32_int32_.NewEntryWrapper(it->first, it->second));
total_size += ::google::protobuf::internal::WireFormatLite::
MessageSizeNoVirtual(*entry);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<int64, int64> map_int64_int64 = 2;
total_size += 1 * this->map_int64_int64_size();
{
::google::protobuf::scoped_ptr<TestMap_MapInt64Int64Entry> entry;
for (::google::protobuf::Map< ::google::protobuf::int64, ::google::protobuf::int64 >::const_iterator
it = this->map_int64_int64().begin();
it != this->map_int64_int64().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_int64_int64_.NewEntryWrapper(it->first, it->second));
total_size += ::google::protobuf::internal::WireFormatLite::
MessageSizeNoVirtual(*entry);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<uint32, uint32> map_uint32_uint32 = 3;
total_size += 1 * this->map_uint32_uint32_size();
{
::google::protobuf::scoped_ptr<TestMap_MapUint32Uint32Entry> entry;
for (::google::protobuf::Map< ::google::protobuf::uint32, ::google::protobuf::uint32 >::const_iterator
it = this->map_uint32_uint32().begin();
it != this->map_uint32_uint32().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_uint32_uint32_.NewEntryWrapper(it->first, it->second));
total_size += ::google::protobuf::internal::WireFormatLite::
MessageSizeNoVirtual(*entry);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<uint64, uint64> map_uint64_uint64 = 4;
total_size += 1 * this->map_uint64_uint64_size();
{
::google::protobuf::scoped_ptr<TestMap_MapUint64Uint64Entry> entry;
for (::google::protobuf::Map< ::google::protobuf::uint64, ::google::protobuf::uint64 >::const_iterator
it = this->map_uint64_uint64().begin();
it != this->map_uint64_uint64().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_uint64_uint64_.NewEntryWrapper(it->first, it->second));
total_size += ::google::protobuf::internal::WireFormatLite::
MessageSizeNoVirtual(*entry);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<sint32, sint32> map_sint32_sint32 = 5;
total_size += 1 * this->map_sint32_sint32_size();
{
::google::protobuf::scoped_ptr<TestMap_MapSint32Sint32Entry> entry;
for (::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::int32 >::const_iterator
it = this->map_sint32_sint32().begin();
it != this->map_sint32_sint32().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_sint32_sint32_.NewEntryWrapper(it->first, it->second));
total_size += ::google::protobuf::internal::WireFormatLite::
MessageSizeNoVirtual(*entry);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<sint64, sint64> map_sint64_sint64 = 6;
total_size += 1 * this->map_sint64_sint64_size();
{
::google::protobuf::scoped_ptr<TestMap_MapSint64Sint64Entry> entry;
for (::google::protobuf::Map< ::google::protobuf::int64, ::google::protobuf::int64 >::const_iterator
it = this->map_sint64_sint64().begin();
it != this->map_sint64_sint64().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_sint64_sint64_.NewEntryWrapper(it->first, it->second));
total_size += ::google::protobuf::internal::WireFormatLite::
MessageSizeNoVirtual(*entry);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<fixed32, fixed32> map_fixed32_fixed32 = 7;
total_size += 1 * this->map_fixed32_fixed32_size();
{
::google::protobuf::scoped_ptr<TestMap_MapFixed32Fixed32Entry> entry;
for (::google::protobuf::Map< ::google::protobuf::uint32, ::google::protobuf::uint32 >::const_iterator
it = this->map_fixed32_fixed32().begin();
it != this->map_fixed32_fixed32().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_fixed32_fixed32_.NewEntryWrapper(it->first, it->second));
total_size += ::google::protobuf::internal::WireFormatLite::
MessageSizeNoVirtual(*entry);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<fixed64, fixed64> map_fixed64_fixed64 = 8;
total_size += 1 * this->map_fixed64_fixed64_size();
{
::google::protobuf::scoped_ptr<TestMap_MapFixed64Fixed64Entry> entry;
for (::google::protobuf::Map< ::google::protobuf::uint64, ::google::protobuf::uint64 >::const_iterator
it = this->map_fixed64_fixed64().begin();
it != this->map_fixed64_fixed64().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_fixed64_fixed64_.NewEntryWrapper(it->first, it->second));
total_size += ::google::protobuf::internal::WireFormatLite::
MessageSizeNoVirtual(*entry);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<sfixed32, sfixed32> map_sfixed32_sfixed32 = 9;
total_size += 1 * this->map_sfixed32_sfixed32_size();
{
::google::protobuf::scoped_ptr<TestMap_MapSfixed32Sfixed32Entry> entry;
for (::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::int32 >::const_iterator
it = this->map_sfixed32_sfixed32().begin();
it != this->map_sfixed32_sfixed32().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_sfixed32_sfixed32_.NewEntryWrapper(it->first, it->second));
total_size += ::google::protobuf::internal::WireFormatLite::
MessageSizeNoVirtual(*entry);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<sfixed64, sfixed64> map_sfixed64_sfixed64 = 10;
total_size += 1 * this->map_sfixed64_sfixed64_size();
{
::google::protobuf::scoped_ptr<TestMap_MapSfixed64Sfixed64Entry> entry;
for (::google::protobuf::Map< ::google::protobuf::int64, ::google::protobuf::int64 >::const_iterator
it = this->map_sfixed64_sfixed64().begin();
it != this->map_sfixed64_sfixed64().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_sfixed64_sfixed64_.NewEntryWrapper(it->first, it->second));
total_size += ::google::protobuf::internal::WireFormatLite::
MessageSizeNoVirtual(*entry);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<int32, float> map_int32_float = 11;
total_size += 1 * this->map_int32_float_size();
{
::google::protobuf::scoped_ptr<TestMap_MapInt32FloatEntry> entry;
for (::google::protobuf::Map< ::google::protobuf::int32, float >::const_iterator
it = this->map_int32_float().begin();
it != this->map_int32_float().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_int32_float_.NewEntryWrapper(it->first, it->second));
total_size += ::google::protobuf::internal::WireFormatLite::
MessageSizeNoVirtual(*entry);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<int32, double> map_int32_double = 12;
total_size += 1 * this->map_int32_double_size();
{
::google::protobuf::scoped_ptr<TestMap_MapInt32DoubleEntry> entry;
for (::google::protobuf::Map< ::google::protobuf::int32, double >::const_iterator
it = this->map_int32_double().begin();
it != this->map_int32_double().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_int32_double_.NewEntryWrapper(it->first, it->second));
total_size += ::google::protobuf::internal::WireFormatLite::
MessageSizeNoVirtual(*entry);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<bool, bool> map_bool_bool = 13;
total_size += 1 * this->map_bool_bool_size();
{
::google::protobuf::scoped_ptr<TestMap_MapBoolBoolEntry> entry;
for (::google::protobuf::Map< bool, bool >::const_iterator
it = this->map_bool_bool().begin();
it != this->map_bool_bool().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_bool_bool_.NewEntryWrapper(it->first, it->second));
total_size += ::google::protobuf::internal::WireFormatLite::
MessageSizeNoVirtual(*entry);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<string, string> map_string_string = 14;
total_size += 1 * this->map_string_string_size();
{
::google::protobuf::scoped_ptr<TestMap_MapStringStringEntry> entry;
for (::google::protobuf::Map< ::std::string, ::std::string >::const_iterator
it = this->map_string_string().begin();
it != this->map_string_string().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_string_string_.NewEntryWrapper(it->first, it->second));
total_size += ::google::protobuf::internal::WireFormatLite::
MessageSizeNoVirtual(*entry);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<int32, bytes> map_int32_bytes = 15;
total_size += 1 * this->map_int32_bytes_size();
{
::google::protobuf::scoped_ptr<TestMap_MapInt32BytesEntry> entry;
for (::google::protobuf::Map< ::google::protobuf::int32, ::std::string >::const_iterator
it = this->map_int32_bytes().begin();
it != this->map_int32_bytes().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_int32_bytes_.NewEntryWrapper(it->first, it->second));
total_size += ::google::protobuf::internal::WireFormatLite::
MessageSizeNoVirtual(*entry);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<int32, .protobuf_unittest.MapEnum> map_int32_enum = 16;
total_size += 2 * this->map_int32_enum_size();
{
::google::protobuf::scoped_ptr<TestMap_MapInt32EnumEntry> entry;
for (::google::protobuf::Map< ::google::protobuf::int32, ::protobuf_unittest::MapEnum >::const_iterator
it = this->map_int32_enum().begin();
it != this->map_int32_enum().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_int32_enum_.NewEnumEntryWrapper(it->first, it->second));
total_size += ::google::protobuf::internal::WireFormatLite::
MessageSizeNoVirtual(*entry);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<int32, .protobuf_unittest.ForeignMessage> map_int32_foreign_message = 17;
total_size += 2 * this->map_int32_foreign_message_size();
{
::google::protobuf::scoped_ptr<TestMap_MapInt32ForeignMessageEntry> entry;
for (::google::protobuf::Map< ::google::protobuf::int32, ::protobuf_unittest::ForeignMessage >::const_iterator
it = this->map_int32_foreign_message().begin();
it != this->map_int32_foreign_message().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_int32_foreign_message_.NewEntryWrapper(it->first, it->second));
total_size += ::google::protobuf::internal::WireFormatLite::
MessageSizeNoVirtual(*entry);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<string, .protobuf_unittest.ForeignMessage> map_string_foreign_message = 18;
total_size += 2 * this->map_string_foreign_message_size();
{
::google::protobuf::scoped_ptr<TestMap_MapStringForeignMessageEntry> entry;
for (::google::protobuf::Map< ::std::string, ::protobuf_unittest::ForeignMessage >::const_iterator
it = this->map_string_foreign_message().begin();
it != this->map_string_foreign_message().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_string_foreign_message_.NewEntryWrapper(it->first, it->second));
total_size += ::google::protobuf::internal::WireFormatLite::
MessageSizeNoVirtual(*entry);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = total_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void TestMap::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:protobuf_unittest.TestMap)
if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
const TestMap* source =
::google::protobuf::internal::DynamicCastToGenerated<const TestMap>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:protobuf_unittest.TestMap)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:protobuf_unittest.TestMap)
MergeFrom(*source);
}
}
void TestMap::MergeFrom(const TestMap& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:protobuf_unittest.TestMap)
if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
map_int32_int32_.MergeFrom(from.map_int32_int32_);
map_int64_int64_.MergeFrom(from.map_int64_int64_);
map_uint32_uint32_.MergeFrom(from.map_uint32_uint32_);
map_uint64_uint64_.MergeFrom(from.map_uint64_uint64_);
map_sint32_sint32_.MergeFrom(from.map_sint32_sint32_);
map_sint64_sint64_.MergeFrom(from.map_sint64_sint64_);
map_fixed32_fixed32_.MergeFrom(from.map_fixed32_fixed32_);
map_fixed64_fixed64_.MergeFrom(from.map_fixed64_fixed64_);
map_sfixed32_sfixed32_.MergeFrom(from.map_sfixed32_sfixed32_);
map_sfixed64_sfixed64_.MergeFrom(from.map_sfixed64_sfixed64_);
map_int32_float_.MergeFrom(from.map_int32_float_);
map_int32_double_.MergeFrom(from.map_int32_double_);
map_bool_bool_.MergeFrom(from.map_bool_bool_);
map_string_string_.MergeFrom(from.map_string_string_);
map_int32_bytes_.MergeFrom(from.map_int32_bytes_);
map_int32_enum_.MergeFrom(from.map_int32_enum_);
map_int32_foreign_message_.MergeFrom(from.map_int32_foreign_message_);
map_string_foreign_message_.MergeFrom(from.map_string_foreign_message_);
}
void TestMap::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:protobuf_unittest.TestMap)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void TestMap::CopyFrom(const TestMap& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:protobuf_unittest.TestMap)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool TestMap::IsInitialized() const {
return true;
}
void TestMap::Swap(TestMap* other) {
if (other == this) return;
if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
InternalSwap(other);
} else {
TestMap temp;
temp.MergeFrom(*this);
CopyFrom(*other);
other->CopyFrom(temp);
}
}
void TestMap::UnsafeArenaSwap(TestMap* other) {
if (other == this) return;
GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
InternalSwap(other);
}
void TestMap::InternalSwap(TestMap* other) {
map_int32_int32_.Swap(&other->map_int32_int32_);
map_int64_int64_.Swap(&other->map_int64_int64_);
map_uint32_uint32_.Swap(&other->map_uint32_uint32_);
map_uint64_uint64_.Swap(&other->map_uint64_uint64_);
map_sint32_sint32_.Swap(&other->map_sint32_sint32_);
map_sint64_sint64_.Swap(&other->map_sint64_sint64_);
map_fixed32_fixed32_.Swap(&other->map_fixed32_fixed32_);
map_fixed64_fixed64_.Swap(&other->map_fixed64_fixed64_);
map_sfixed32_sfixed32_.Swap(&other->map_sfixed32_sfixed32_);
map_sfixed64_sfixed64_.Swap(&other->map_sfixed64_sfixed64_);
map_int32_float_.Swap(&other->map_int32_float_);
map_int32_double_.Swap(&other->map_int32_double_);
map_bool_bool_.Swap(&other->map_bool_bool_);
map_string_string_.Swap(&other->map_string_string_);
map_int32_bytes_.Swap(&other->map_int32_bytes_);
map_int32_enum_.Swap(&other->map_int32_enum_);
map_int32_foreign_message_.Swap(&other->map_int32_foreign_message_);
map_string_foreign_message_.Swap(&other->map_string_foreign_message_);
_internal_metadata_.Swap(&other->_internal_metadata_);
std::swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata TestMap::GetMetadata() const {
protobuf_AssignDescriptorsOnce();
::google::protobuf::Metadata metadata;
metadata.descriptor = TestMap_descriptor_;
metadata.reflection = TestMap_reflection_;
return metadata;
}
#if PROTOBUF_INLINE_NOT_IN_HEADERS
// TestMap
// map<int32, int32> map_int32_int32 = 1;
int TestMap::map_int32_int32_size() const {
return map_int32_int32_.size();
}
void TestMap::clear_map_int32_int32() {
map_int32_int32_.Clear();
}
const ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::int32 >&
TestMap::map_int32_int32() const {
// @@protoc_insertion_point(field_map:protobuf_unittest.TestMap.map_int32_int32)
return map_int32_int32_.GetMap();
}
::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::int32 >*
TestMap::mutable_map_int32_int32() {
// @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestMap.map_int32_int32)
return map_int32_int32_.MutableMap();
}
// map<int64, int64> map_int64_int64 = 2;
int TestMap::map_int64_int64_size() const {
return map_int64_int64_.size();
}
void TestMap::clear_map_int64_int64() {
map_int64_int64_.Clear();
}
const ::google::protobuf::Map< ::google::protobuf::int64, ::google::protobuf::int64 >&
TestMap::map_int64_int64() const {
// @@protoc_insertion_point(field_map:protobuf_unittest.TestMap.map_int64_int64)
return map_int64_int64_.GetMap();
}
::google::protobuf::Map< ::google::protobuf::int64, ::google::protobuf::int64 >*
TestMap::mutable_map_int64_int64() {
// @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestMap.map_int64_int64)
return map_int64_int64_.MutableMap();
}
// map<uint32, uint32> map_uint32_uint32 = 3;
int TestMap::map_uint32_uint32_size() const {
return map_uint32_uint32_.size();
}
void TestMap::clear_map_uint32_uint32() {
map_uint32_uint32_.Clear();
}
const ::google::protobuf::Map< ::google::protobuf::uint32, ::google::protobuf::uint32 >&
TestMap::map_uint32_uint32() const {
// @@protoc_insertion_point(field_map:protobuf_unittest.TestMap.map_uint32_uint32)
return map_uint32_uint32_.GetMap();
}
::google::protobuf::Map< ::google::protobuf::uint32, ::google::protobuf::uint32 >*
TestMap::mutable_map_uint32_uint32() {
// @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestMap.map_uint32_uint32)
return map_uint32_uint32_.MutableMap();
}
// map<uint64, uint64> map_uint64_uint64 = 4;
int TestMap::map_uint64_uint64_size() const {
return map_uint64_uint64_.size();
}
void TestMap::clear_map_uint64_uint64() {
map_uint64_uint64_.Clear();
}
const ::google::protobuf::Map< ::google::protobuf::uint64, ::google::protobuf::uint64 >&
TestMap::map_uint64_uint64() const {
// @@protoc_insertion_point(field_map:protobuf_unittest.TestMap.map_uint64_uint64)
return map_uint64_uint64_.GetMap();
}
::google::protobuf::Map< ::google::protobuf::uint64, ::google::protobuf::uint64 >*
TestMap::mutable_map_uint64_uint64() {
// @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestMap.map_uint64_uint64)
return map_uint64_uint64_.MutableMap();
}
// map<sint32, sint32> map_sint32_sint32 = 5;
int TestMap::map_sint32_sint32_size() const {
return map_sint32_sint32_.size();
}
void TestMap::clear_map_sint32_sint32() {
map_sint32_sint32_.Clear();
}
const ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::int32 >&
TestMap::map_sint32_sint32() const {
// @@protoc_insertion_point(field_map:protobuf_unittest.TestMap.map_sint32_sint32)
return map_sint32_sint32_.GetMap();
}
::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::int32 >*
TestMap::mutable_map_sint32_sint32() {
// @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestMap.map_sint32_sint32)
return map_sint32_sint32_.MutableMap();
}
// map<sint64, sint64> map_sint64_sint64 = 6;
int TestMap::map_sint64_sint64_size() const {
return map_sint64_sint64_.size();
}
void TestMap::clear_map_sint64_sint64() {
map_sint64_sint64_.Clear();
}
const ::google::protobuf::Map< ::google::protobuf::int64, ::google::protobuf::int64 >&
TestMap::map_sint64_sint64() const {
// @@protoc_insertion_point(field_map:protobuf_unittest.TestMap.map_sint64_sint64)
return map_sint64_sint64_.GetMap();
}
::google::protobuf::Map< ::google::protobuf::int64, ::google::protobuf::int64 >*
TestMap::mutable_map_sint64_sint64() {
// @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestMap.map_sint64_sint64)
return map_sint64_sint64_.MutableMap();
}
// map<fixed32, fixed32> map_fixed32_fixed32 = 7;
int TestMap::map_fixed32_fixed32_size() const {
return map_fixed32_fixed32_.size();
}
void TestMap::clear_map_fixed32_fixed32() {
map_fixed32_fixed32_.Clear();
}
const ::google::protobuf::Map< ::google::protobuf::uint32, ::google::protobuf::uint32 >&
TestMap::map_fixed32_fixed32() const {
// @@protoc_insertion_point(field_map:protobuf_unittest.TestMap.map_fixed32_fixed32)
return map_fixed32_fixed32_.GetMap();
}
::google::protobuf::Map< ::google::protobuf::uint32, ::google::protobuf::uint32 >*
TestMap::mutable_map_fixed32_fixed32() {
// @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestMap.map_fixed32_fixed32)
return map_fixed32_fixed32_.MutableMap();
}
// map<fixed64, fixed64> map_fixed64_fixed64 = 8;
int TestMap::map_fixed64_fixed64_size() const {
return map_fixed64_fixed64_.size();
}
void TestMap::clear_map_fixed64_fixed64() {
map_fixed64_fixed64_.Clear();
}
const ::google::protobuf::Map< ::google::protobuf::uint64, ::google::protobuf::uint64 >&
TestMap::map_fixed64_fixed64() const {
// @@protoc_insertion_point(field_map:protobuf_unittest.TestMap.map_fixed64_fixed64)
return map_fixed64_fixed64_.GetMap();
}
::google::protobuf::Map< ::google::protobuf::uint64, ::google::protobuf::uint64 >*
TestMap::mutable_map_fixed64_fixed64() {
// @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestMap.map_fixed64_fixed64)
return map_fixed64_fixed64_.MutableMap();
}
// map<sfixed32, sfixed32> map_sfixed32_sfixed32 = 9;
int TestMap::map_sfixed32_sfixed32_size() const {
return map_sfixed32_sfixed32_.size();
}
void TestMap::clear_map_sfixed32_sfixed32() {
map_sfixed32_sfixed32_.Clear();
}
const ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::int32 >&
TestMap::map_sfixed32_sfixed32() const {
// @@protoc_insertion_point(field_map:protobuf_unittest.TestMap.map_sfixed32_sfixed32)
return map_sfixed32_sfixed32_.GetMap();
}
::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::int32 >*
TestMap::mutable_map_sfixed32_sfixed32() {
// @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestMap.map_sfixed32_sfixed32)
return map_sfixed32_sfixed32_.MutableMap();
}
// map<sfixed64, sfixed64> map_sfixed64_sfixed64 = 10;
int TestMap::map_sfixed64_sfixed64_size() const {
return map_sfixed64_sfixed64_.size();
}
void TestMap::clear_map_sfixed64_sfixed64() {
map_sfixed64_sfixed64_.Clear();
}
const ::google::protobuf::Map< ::google::protobuf::int64, ::google::protobuf::int64 >&
TestMap::map_sfixed64_sfixed64() const {
// @@protoc_insertion_point(field_map:protobuf_unittest.TestMap.map_sfixed64_sfixed64)
return map_sfixed64_sfixed64_.GetMap();
}
::google::protobuf::Map< ::google::protobuf::int64, ::google::protobuf::int64 >*
TestMap::mutable_map_sfixed64_sfixed64() {
// @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestMap.map_sfixed64_sfixed64)
return map_sfixed64_sfixed64_.MutableMap();
}
// map<int32, float> map_int32_float = 11;
int TestMap::map_int32_float_size() const {
return map_int32_float_.size();
}
void TestMap::clear_map_int32_float() {
map_int32_float_.Clear();
}
const ::google::protobuf::Map< ::google::protobuf::int32, float >&
TestMap::map_int32_float() const {
// @@protoc_insertion_point(field_map:protobuf_unittest.TestMap.map_int32_float)
return map_int32_float_.GetMap();
}
::google::protobuf::Map< ::google::protobuf::int32, float >*
TestMap::mutable_map_int32_float() {
// @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestMap.map_int32_float)
return map_int32_float_.MutableMap();
}
// map<int32, double> map_int32_double = 12;
int TestMap::map_int32_double_size() const {
return map_int32_double_.size();
}
void TestMap::clear_map_int32_double() {
map_int32_double_.Clear();
}
const ::google::protobuf::Map< ::google::protobuf::int32, double >&
TestMap::map_int32_double() const {
// @@protoc_insertion_point(field_map:protobuf_unittest.TestMap.map_int32_double)
return map_int32_double_.GetMap();
}
::google::protobuf::Map< ::google::protobuf::int32, double >*
TestMap::mutable_map_int32_double() {
// @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestMap.map_int32_double)
return map_int32_double_.MutableMap();
}
// map<bool, bool> map_bool_bool = 13;
int TestMap::map_bool_bool_size() const {
return map_bool_bool_.size();
}
void TestMap::clear_map_bool_bool() {
map_bool_bool_.Clear();
}
const ::google::protobuf::Map< bool, bool >&
TestMap::map_bool_bool() const {
// @@protoc_insertion_point(field_map:protobuf_unittest.TestMap.map_bool_bool)
return map_bool_bool_.GetMap();
}
::google::protobuf::Map< bool, bool >*
TestMap::mutable_map_bool_bool() {
// @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestMap.map_bool_bool)
return map_bool_bool_.MutableMap();
}
// map<string, string> map_string_string = 14;
int TestMap::map_string_string_size() const {
return map_string_string_.size();
}
void TestMap::clear_map_string_string() {
map_string_string_.Clear();
}
const ::google::protobuf::Map< ::std::string, ::std::string >&
TestMap::map_string_string() const {
// @@protoc_insertion_point(field_map:protobuf_unittest.TestMap.map_string_string)
return map_string_string_.GetMap();
}
::google::protobuf::Map< ::std::string, ::std::string >*
TestMap::mutable_map_string_string() {
// @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestMap.map_string_string)
return map_string_string_.MutableMap();
}
// map<int32, bytes> map_int32_bytes = 15;
int TestMap::map_int32_bytes_size() const {
return map_int32_bytes_.size();
}
void TestMap::clear_map_int32_bytes() {
map_int32_bytes_.Clear();
}
const ::google::protobuf::Map< ::google::protobuf::int32, ::std::string >&
TestMap::map_int32_bytes() const {
// @@protoc_insertion_point(field_map:protobuf_unittest.TestMap.map_int32_bytes)
return map_int32_bytes_.GetMap();
}
::google::protobuf::Map< ::google::protobuf::int32, ::std::string >*
TestMap::mutable_map_int32_bytes() {
// @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestMap.map_int32_bytes)
return map_int32_bytes_.MutableMap();
}
// map<int32, .protobuf_unittest.MapEnum> map_int32_enum = 16;
int TestMap::map_int32_enum_size() const {
return map_int32_enum_.size();
}
void TestMap::clear_map_int32_enum() {
map_int32_enum_.Clear();
}
const ::google::protobuf::Map< ::google::protobuf::int32, ::protobuf_unittest::MapEnum >&
TestMap::map_int32_enum() const {
// @@protoc_insertion_point(field_map:protobuf_unittest.TestMap.map_int32_enum)
return map_int32_enum_.GetMap();
}
::google::protobuf::Map< ::google::protobuf::int32, ::protobuf_unittest::MapEnum >*
TestMap::mutable_map_int32_enum() {
// @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestMap.map_int32_enum)
return map_int32_enum_.MutableMap();
}
// map<int32, .protobuf_unittest.ForeignMessage> map_int32_foreign_message = 17;
int TestMap::map_int32_foreign_message_size() const {
return map_int32_foreign_message_.size();
}
void TestMap::clear_map_int32_foreign_message() {
map_int32_foreign_message_.Clear();
}
const ::google::protobuf::Map< ::google::protobuf::int32, ::protobuf_unittest::ForeignMessage >&
TestMap::map_int32_foreign_message() const {
// @@protoc_insertion_point(field_map:protobuf_unittest.TestMap.map_int32_foreign_message)
return map_int32_foreign_message_.GetMap();
}
::google::protobuf::Map< ::google::protobuf::int32, ::protobuf_unittest::ForeignMessage >*
TestMap::mutable_map_int32_foreign_message() {
// @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestMap.map_int32_foreign_message)
return map_int32_foreign_message_.MutableMap();
}
// map<string, .protobuf_unittest.ForeignMessage> map_string_foreign_message = 18;
int TestMap::map_string_foreign_message_size() const {
return map_string_foreign_message_.size();
}
void TestMap::clear_map_string_foreign_message() {
map_string_foreign_message_.Clear();
}
const ::google::protobuf::Map< ::std::string, ::protobuf_unittest::ForeignMessage >&
TestMap::map_string_foreign_message() const {
// @@protoc_insertion_point(field_map:protobuf_unittest.TestMap.map_string_foreign_message)
return map_string_foreign_message_.GetMap();
}
::google::protobuf::Map< ::std::string, ::protobuf_unittest::ForeignMessage >*
TestMap::mutable_map_string_foreign_message() {
// @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestMap.map_string_foreign_message)
return map_string_foreign_message_.MutableMap();
}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
void TestMapSubmessage::_slow_mutable_test_map() {
test_map_ = ::google::protobuf::Arena::CreateMessage< ::protobuf_unittest::TestMap >(
GetArenaNoVirtual());
}
::protobuf_unittest::TestMap* TestMapSubmessage::_slow_release_test_map() {
if (test_map_ == NULL) {
return NULL;
} else {
::protobuf_unittest::TestMap* temp = new ::protobuf_unittest::TestMap;
temp->MergeFrom(*test_map_);
test_map_ = NULL;
return temp;
}
}
::protobuf_unittest::TestMap* TestMapSubmessage::unsafe_arena_release_test_map() {
// @@protoc_insertion_point(field_unsafe_arena_release:protobuf_unittest.TestMapSubmessage.test_map)
::protobuf_unittest::TestMap* temp = test_map_;
test_map_ = NULL;
return temp;
}
void TestMapSubmessage::_slow_set_allocated_test_map(
::google::protobuf::Arena* message_arena, ::protobuf_unittest::TestMap** test_map) {
if (message_arena != NULL &&
::google::protobuf::Arena::GetArena(*test_map) == NULL) {
message_arena->Own(*test_map);
} else if (message_arena !=
::google::protobuf::Arena::GetArena(*test_map)) {
::protobuf_unittest::TestMap* new_test_map =
::google::protobuf::Arena::CreateMessage< ::protobuf_unittest::TestMap >(
message_arena);
new_test_map->CopyFrom(**test_map);
*test_map = new_test_map;
}
}
void TestMapSubmessage::unsafe_arena_set_allocated_test_map(
::protobuf_unittest::TestMap* test_map) {
if (GetArenaNoVirtual() == NULL) {
delete test_map_;
}
test_map_ = test_map;
if (test_map) {
} else {
}
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:protobuf_unittest.TestMapSubmessage.test_map)
}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int TestMapSubmessage::kTestMapFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
TestMapSubmessage::TestMapSubmessage()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
SharedCtor();
// @@protoc_insertion_point(constructor:protobuf_unittest.TestMapSubmessage)
}
TestMapSubmessage::TestMapSubmessage(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena) {
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:protobuf_unittest.TestMapSubmessage)
}
void TestMapSubmessage::InitAsDefaultInstance() {
_is_default_instance_ = true;
test_map_ = const_cast< ::protobuf_unittest::TestMap*>(&::protobuf_unittest::TestMap::default_instance());
}
TestMapSubmessage::TestMapSubmessage(const TestMapSubmessage& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
MergeFrom(from);
// @@protoc_insertion_point(copy_constructor:protobuf_unittest.TestMapSubmessage)
}
void TestMapSubmessage::SharedCtor() {
_is_default_instance_ = false;
_cached_size_ = 0;
test_map_ = NULL;
}
TestMapSubmessage::~TestMapSubmessage() {
// @@protoc_insertion_point(destructor:protobuf_unittest.TestMapSubmessage)
SharedDtor();
}
void TestMapSubmessage::SharedDtor() {
if (GetArenaNoVirtual() != NULL) {
return;
}
if (this != default_instance_) {
delete test_map_;
}
}
void TestMapSubmessage::ArenaDtor(void* object) {
TestMapSubmessage* _this = reinterpret_cast< TestMapSubmessage* >(object);
(void)_this;
}
void TestMapSubmessage::RegisterArenaDtor(::google::protobuf::Arena* arena) {
}
void TestMapSubmessage::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* TestMapSubmessage::descriptor() {
protobuf_AssignDescriptorsOnce();
return TestMapSubmessage_descriptor_;
}
const TestMapSubmessage& TestMapSubmessage::default_instance() {
if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2fmap_5funittest_2eproto();
return *default_instance_;
}
TestMapSubmessage* TestMapSubmessage::default_instance_ = NULL;
TestMapSubmessage* TestMapSubmessage::New(::google::protobuf::Arena* arena) const {
return ::google::protobuf::Arena::CreateMessage<TestMapSubmessage>(arena);
}
void TestMapSubmessage::Clear() {
// @@protoc_insertion_point(message_clear_start:protobuf_unittest.TestMapSubmessage)
if (GetArenaNoVirtual() == NULL && test_map_ != NULL) delete test_map_;
test_map_ = NULL;
}
bool TestMapSubmessage::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:protobuf_unittest.TestMapSubmessage)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// optional .protobuf_unittest.TestMap test_map = 1;
case 1: {
if (tag == 10) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, mutable_test_map()));
} else {
goto handle_unusual;
}
if (input->ExpectAtEnd()) goto success;
break;
}
default: {
handle_unusual:
if (tag == 0 ||
::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
goto success;
}
DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:protobuf_unittest.TestMapSubmessage)
return true;
failure:
// @@protoc_insertion_point(parse_failure:protobuf_unittest.TestMapSubmessage)
return false;
#undef DO_
}
void TestMapSubmessage::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:protobuf_unittest.TestMapSubmessage)
// optional .protobuf_unittest.TestMap test_map = 1;
if (this->has_test_map()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
1, *this->test_map_, output);
}
// @@protoc_insertion_point(serialize_end:protobuf_unittest.TestMapSubmessage)
}
::google::protobuf::uint8* TestMapSubmessage::SerializeWithCachedSizesToArray(
::google::protobuf::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:protobuf_unittest.TestMapSubmessage)
// optional .protobuf_unittest.TestMap test_map = 1;
if (this->has_test_map()) {
target = ::google::protobuf::internal::WireFormatLite::
WriteMessageNoVirtualToArray(
1, *this->test_map_, target);
}
// @@protoc_insertion_point(serialize_to_array_end:protobuf_unittest.TestMapSubmessage)
return target;
}
int TestMapSubmessage::ByteSize() const {
// @@protoc_insertion_point(message_byte_size_start:protobuf_unittest.TestMapSubmessage)
int total_size = 0;
// optional .protobuf_unittest.TestMap test_map = 1;
if (this->has_test_map()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
*this->test_map_);
}
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = total_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void TestMapSubmessage::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:protobuf_unittest.TestMapSubmessage)
if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
const TestMapSubmessage* source =
::google::protobuf::internal::DynamicCastToGenerated<const TestMapSubmessage>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:protobuf_unittest.TestMapSubmessage)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:protobuf_unittest.TestMapSubmessage)
MergeFrom(*source);
}
}
void TestMapSubmessage::MergeFrom(const TestMapSubmessage& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:protobuf_unittest.TestMapSubmessage)
if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
if (from.has_test_map()) {
mutable_test_map()->::protobuf_unittest::TestMap::MergeFrom(from.test_map());
}
}
void TestMapSubmessage::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:protobuf_unittest.TestMapSubmessage)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void TestMapSubmessage::CopyFrom(const TestMapSubmessage& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:protobuf_unittest.TestMapSubmessage)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool TestMapSubmessage::IsInitialized() const {
return true;
}
void TestMapSubmessage::Swap(TestMapSubmessage* other) {
if (other == this) return;
if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
InternalSwap(other);
} else {
TestMapSubmessage temp;
temp.MergeFrom(*this);
CopyFrom(*other);
other->CopyFrom(temp);
}
}
void TestMapSubmessage::UnsafeArenaSwap(TestMapSubmessage* other) {
if (other == this) return;
GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
InternalSwap(other);
}
void TestMapSubmessage::InternalSwap(TestMapSubmessage* other) {
std::swap(test_map_, other->test_map_);
_internal_metadata_.Swap(&other->_internal_metadata_);
std::swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata TestMapSubmessage::GetMetadata() const {
protobuf_AssignDescriptorsOnce();
::google::protobuf::Metadata metadata;
metadata.descriptor = TestMapSubmessage_descriptor_;
metadata.reflection = TestMapSubmessage_reflection_;
return metadata;
}
#if PROTOBUF_INLINE_NOT_IN_HEADERS
// TestMapSubmessage
// optional .protobuf_unittest.TestMap test_map = 1;
bool TestMapSubmessage::has_test_map() const {
return !_is_default_instance_ && test_map_ != NULL;
}
void TestMapSubmessage::clear_test_map() {
if (GetArenaNoVirtual() == NULL && test_map_ != NULL) delete test_map_;
test_map_ = NULL;
}
const ::protobuf_unittest::TestMap& TestMapSubmessage::test_map() const {
// @@protoc_insertion_point(field_get:protobuf_unittest.TestMapSubmessage.test_map)
return test_map_ != NULL ? *test_map_ : *default_instance_->test_map_;
}
::protobuf_unittest::TestMap* TestMapSubmessage::mutable_test_map() {
if (test_map_ == NULL) {
_slow_mutable_test_map();
}
// @@protoc_insertion_point(field_mutable:protobuf_unittest.TestMapSubmessage.test_map)
return test_map_;
}
::protobuf_unittest::TestMap* TestMapSubmessage::release_test_map() {
// @@protoc_insertion_point(field_release:protobuf_unittest.TestMapSubmessage.test_map)
if (GetArenaNoVirtual() != NULL) {
return _slow_release_test_map();
} else {
::protobuf_unittest::TestMap* temp = test_map_;
test_map_ = NULL;
return temp;
}
}
void TestMapSubmessage::set_allocated_test_map(::protobuf_unittest::TestMap* test_map) {
::google::protobuf::Arena* message_arena = GetArenaNoVirtual();
if (message_arena == NULL) {
delete test_map_;
}
if (test_map != NULL) {
_slow_set_allocated_test_map(message_arena, &test_map);
}
test_map_ = test_map;
if (test_map) {
} else {
}
// @@protoc_insertion_point(field_set_allocated:protobuf_unittest.TestMapSubmessage.test_map)
}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int TestMessageMap::kMapInt32MessageFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
TestMessageMap::TestMessageMap()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
SharedCtor();
// @@protoc_insertion_point(constructor:protobuf_unittest.TestMessageMap)
}
TestMessageMap::TestMessageMap(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena),
map_int32_message_(arena) {
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:protobuf_unittest.TestMessageMap)
}
void TestMessageMap::InitAsDefaultInstance() {
_is_default_instance_ = true;
}
TestMessageMap::TestMessageMap(const TestMessageMap& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
MergeFrom(from);
// @@protoc_insertion_point(copy_constructor:protobuf_unittest.TestMessageMap)
}
void TestMessageMap::SharedCtor() {
_is_default_instance_ = false;
_cached_size_ = 0;
map_int32_message_.SetAssignDescriptorCallback(
protobuf_AssignDescriptorsOnce);
map_int32_message_.SetEntryDescriptor(
&::protobuf_unittest::TestMessageMap_MapInt32MessageEntry_descriptor_);
}
TestMessageMap::~TestMessageMap() {
// @@protoc_insertion_point(destructor:protobuf_unittest.TestMessageMap)
SharedDtor();
}
void TestMessageMap::SharedDtor() {
if (GetArenaNoVirtual() != NULL) {
return;
}
if (this != default_instance_) {
}
}
void TestMessageMap::ArenaDtor(void* object) {
TestMessageMap* _this = reinterpret_cast< TestMessageMap* >(object);
(void)_this;
}
void TestMessageMap::RegisterArenaDtor(::google::protobuf::Arena* arena) {
}
void TestMessageMap::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* TestMessageMap::descriptor() {
protobuf_AssignDescriptorsOnce();
return TestMessageMap_descriptor_;
}
const TestMessageMap& TestMessageMap::default_instance() {
if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2fmap_5funittest_2eproto();
return *default_instance_;
}
TestMessageMap* TestMessageMap::default_instance_ = NULL;
TestMessageMap* TestMessageMap::New(::google::protobuf::Arena* arena) const {
return ::google::protobuf::Arena::CreateMessage<TestMessageMap>(arena);
}
void TestMessageMap::Clear() {
// @@protoc_insertion_point(message_clear_start:protobuf_unittest.TestMessageMap)
map_int32_message_.Clear();
}
bool TestMessageMap::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:protobuf_unittest.TestMessageMap)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// map<int32, .protobuf_unittest.TestAllTypes> map_int32_message = 1;
case 1: {
if (tag == 10) {
DO_(input->IncrementRecursionDepth());
parse_loop_map_int32_message:
::google::protobuf::scoped_ptr<TestMessageMap_MapInt32MessageEntry> entry(map_int32_message_.NewEntry());
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, entry.get()));
(*mutable_map_int32_message())[entry->key()].Swap(entry->mutable_value());
if (entry->GetArena() != NULL) entry.release();
} else {
goto handle_unusual;
}
if (input->ExpectTag(10)) goto parse_loop_map_int32_message;
input->UnsafeDecrementRecursionDepth();
if (input->ExpectAtEnd()) goto success;
break;
}
default: {
handle_unusual:
if (tag == 0 ||
::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
goto success;
}
DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:protobuf_unittest.TestMessageMap)
return true;
failure:
// @@protoc_insertion_point(parse_failure:protobuf_unittest.TestMessageMap)
return false;
#undef DO_
}
void TestMessageMap::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:protobuf_unittest.TestMessageMap)
// map<int32, .protobuf_unittest.TestAllTypes> map_int32_message = 1;
{
::google::protobuf::scoped_ptr<TestMessageMap_MapInt32MessageEntry> entry;
for (::google::protobuf::Map< ::google::protobuf::int32, ::protobuf_unittest::TestAllTypes >::const_iterator
it = this->map_int32_message().begin();
it != this->map_int32_message().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_int32_message_.NewEntryWrapper(it->first, it->second));
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
1, *entry, output);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// @@protoc_insertion_point(serialize_end:protobuf_unittest.TestMessageMap)
}
::google::protobuf::uint8* TestMessageMap::SerializeWithCachedSizesToArray(
::google::protobuf::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:protobuf_unittest.TestMessageMap)
// map<int32, .protobuf_unittest.TestAllTypes> map_int32_message = 1;
{
::google::protobuf::scoped_ptr<TestMessageMap_MapInt32MessageEntry> entry;
for (::google::protobuf::Map< ::google::protobuf::int32, ::protobuf_unittest::TestAllTypes >::const_iterator
it = this->map_int32_message().begin();
it != this->map_int32_message().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_int32_message_.NewEntryWrapper(it->first, it->second));
target = ::google::protobuf::internal::WireFormatLite::
WriteMessageNoVirtualToArray(
1, *entry, target);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// @@protoc_insertion_point(serialize_to_array_end:protobuf_unittest.TestMessageMap)
return target;
}
int TestMessageMap::ByteSize() const {
// @@protoc_insertion_point(message_byte_size_start:protobuf_unittest.TestMessageMap)
int total_size = 0;
// map<int32, .protobuf_unittest.TestAllTypes> map_int32_message = 1;
total_size += 1 * this->map_int32_message_size();
{
::google::protobuf::scoped_ptr<TestMessageMap_MapInt32MessageEntry> entry;
for (::google::protobuf::Map< ::google::protobuf::int32, ::protobuf_unittest::TestAllTypes >::const_iterator
it = this->map_int32_message().begin();
it != this->map_int32_message().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_int32_message_.NewEntryWrapper(it->first, it->second));
total_size += ::google::protobuf::internal::WireFormatLite::
MessageSizeNoVirtual(*entry);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = total_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void TestMessageMap::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:protobuf_unittest.TestMessageMap)
if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
const TestMessageMap* source =
::google::protobuf::internal::DynamicCastToGenerated<const TestMessageMap>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:protobuf_unittest.TestMessageMap)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:protobuf_unittest.TestMessageMap)
MergeFrom(*source);
}
}
void TestMessageMap::MergeFrom(const TestMessageMap& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:protobuf_unittest.TestMessageMap)
if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
map_int32_message_.MergeFrom(from.map_int32_message_);
}
void TestMessageMap::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:protobuf_unittest.TestMessageMap)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void TestMessageMap::CopyFrom(const TestMessageMap& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:protobuf_unittest.TestMessageMap)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool TestMessageMap::IsInitialized() const {
return true;
}
void TestMessageMap::Swap(TestMessageMap* other) {
if (other == this) return;
if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
InternalSwap(other);
} else {
TestMessageMap temp;
temp.MergeFrom(*this);
CopyFrom(*other);
other->CopyFrom(temp);
}
}
void TestMessageMap::UnsafeArenaSwap(TestMessageMap* other) {
if (other == this) return;
GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
InternalSwap(other);
}
void TestMessageMap::InternalSwap(TestMessageMap* other) {
map_int32_message_.Swap(&other->map_int32_message_);
_internal_metadata_.Swap(&other->_internal_metadata_);
std::swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata TestMessageMap::GetMetadata() const {
protobuf_AssignDescriptorsOnce();
::google::protobuf::Metadata metadata;
metadata.descriptor = TestMessageMap_descriptor_;
metadata.reflection = TestMessageMap_reflection_;
return metadata;
}
#if PROTOBUF_INLINE_NOT_IN_HEADERS
// TestMessageMap
// map<int32, .protobuf_unittest.TestAllTypes> map_int32_message = 1;
int TestMessageMap::map_int32_message_size() const {
return map_int32_message_.size();
}
void TestMessageMap::clear_map_int32_message() {
map_int32_message_.Clear();
}
const ::google::protobuf::Map< ::google::protobuf::int32, ::protobuf_unittest::TestAllTypes >&
TestMessageMap::map_int32_message() const {
// @@protoc_insertion_point(field_map:protobuf_unittest.TestMessageMap.map_int32_message)
return map_int32_message_.GetMap();
}
::google::protobuf::Map< ::google::protobuf::int32, ::protobuf_unittest::TestAllTypes >*
TestMessageMap::mutable_map_int32_message() {
// @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestMessageMap.map_int32_message)
return map_int32_message_.MutableMap();
}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int TestSameTypeMap::kMap1FieldNumber;
const int TestSameTypeMap::kMap2FieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
TestSameTypeMap::TestSameTypeMap()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
SharedCtor();
// @@protoc_insertion_point(constructor:protobuf_unittest.TestSameTypeMap)
}
TestSameTypeMap::TestSameTypeMap(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena),
map1_(arena),
map2_(arena) {
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:protobuf_unittest.TestSameTypeMap)
}
void TestSameTypeMap::InitAsDefaultInstance() {
_is_default_instance_ = true;
}
TestSameTypeMap::TestSameTypeMap(const TestSameTypeMap& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
MergeFrom(from);
// @@protoc_insertion_point(copy_constructor:protobuf_unittest.TestSameTypeMap)
}
void TestSameTypeMap::SharedCtor() {
_is_default_instance_ = false;
_cached_size_ = 0;
map1_.SetAssignDescriptorCallback(
protobuf_AssignDescriptorsOnce);
map1_.SetEntryDescriptor(
&::protobuf_unittest::TestSameTypeMap_Map1Entry_descriptor_);
map2_.SetAssignDescriptorCallback(
protobuf_AssignDescriptorsOnce);
map2_.SetEntryDescriptor(
&::protobuf_unittest::TestSameTypeMap_Map2Entry_descriptor_);
}
TestSameTypeMap::~TestSameTypeMap() {
// @@protoc_insertion_point(destructor:protobuf_unittest.TestSameTypeMap)
SharedDtor();
}
void TestSameTypeMap::SharedDtor() {
if (GetArenaNoVirtual() != NULL) {
return;
}
if (this != default_instance_) {
}
}
void TestSameTypeMap::ArenaDtor(void* object) {
TestSameTypeMap* _this = reinterpret_cast< TestSameTypeMap* >(object);
(void)_this;
}
void TestSameTypeMap::RegisterArenaDtor(::google::protobuf::Arena* arena) {
}
void TestSameTypeMap::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* TestSameTypeMap::descriptor() {
protobuf_AssignDescriptorsOnce();
return TestSameTypeMap_descriptor_;
}
const TestSameTypeMap& TestSameTypeMap::default_instance() {
if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2fmap_5funittest_2eproto();
return *default_instance_;
}
TestSameTypeMap* TestSameTypeMap::default_instance_ = NULL;
TestSameTypeMap* TestSameTypeMap::New(::google::protobuf::Arena* arena) const {
return ::google::protobuf::Arena::CreateMessage<TestSameTypeMap>(arena);
}
void TestSameTypeMap::Clear() {
// @@protoc_insertion_point(message_clear_start:protobuf_unittest.TestSameTypeMap)
map1_.Clear();
map2_.Clear();
}
bool TestSameTypeMap::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:protobuf_unittest.TestSameTypeMap)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// map<int32, int32> map1 = 1;
case 1: {
if (tag == 10) {
DO_(input->IncrementRecursionDepth());
parse_loop_map1:
::google::protobuf::scoped_ptr<TestSameTypeMap_Map1Entry> entry(map1_.NewEntry());
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, entry.get()));
(*mutable_map1())[entry->key()] = *entry->mutable_value();
if (entry->GetArena() != NULL) entry.release();
} else {
goto handle_unusual;
}
if (input->ExpectTag(10)) goto parse_loop_map1;
if (input->ExpectTag(18)) goto parse_loop_map2;
input->UnsafeDecrementRecursionDepth();
break;
}
// map<int32, int32> map2 = 2;
case 2: {
if (tag == 18) {
DO_(input->IncrementRecursionDepth());
parse_loop_map2:
::google::protobuf::scoped_ptr<TestSameTypeMap_Map2Entry> entry(map2_.NewEntry());
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, entry.get()));
(*mutable_map2())[entry->key()] = *entry->mutable_value();
if (entry->GetArena() != NULL) entry.release();
} else {
goto handle_unusual;
}
if (input->ExpectTag(18)) goto parse_loop_map2;
input->UnsafeDecrementRecursionDepth();
if (input->ExpectAtEnd()) goto success;
break;
}
default: {
handle_unusual:
if (tag == 0 ||
::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
goto success;
}
DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:protobuf_unittest.TestSameTypeMap)
return true;
failure:
// @@protoc_insertion_point(parse_failure:protobuf_unittest.TestSameTypeMap)
return false;
#undef DO_
}
void TestSameTypeMap::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:protobuf_unittest.TestSameTypeMap)
// map<int32, int32> map1 = 1;
{
::google::protobuf::scoped_ptr<TestSameTypeMap_Map1Entry> entry;
for (::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::int32 >::const_iterator
it = this->map1().begin();
it != this->map1().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map1_.NewEntryWrapper(it->first, it->second));
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
1, *entry, output);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<int32, int32> map2 = 2;
{
::google::protobuf::scoped_ptr<TestSameTypeMap_Map2Entry> entry;
for (::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::int32 >::const_iterator
it = this->map2().begin();
it != this->map2().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map2_.NewEntryWrapper(it->first, it->second));
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
2, *entry, output);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// @@protoc_insertion_point(serialize_end:protobuf_unittest.TestSameTypeMap)
}
::google::protobuf::uint8* TestSameTypeMap::SerializeWithCachedSizesToArray(
::google::protobuf::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:protobuf_unittest.TestSameTypeMap)
// map<int32, int32> map1 = 1;
{
::google::protobuf::scoped_ptr<TestSameTypeMap_Map1Entry> entry;
for (::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::int32 >::const_iterator
it = this->map1().begin();
it != this->map1().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map1_.NewEntryWrapper(it->first, it->second));
target = ::google::protobuf::internal::WireFormatLite::
WriteMessageNoVirtualToArray(
1, *entry, target);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<int32, int32> map2 = 2;
{
::google::protobuf::scoped_ptr<TestSameTypeMap_Map2Entry> entry;
for (::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::int32 >::const_iterator
it = this->map2().begin();
it != this->map2().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map2_.NewEntryWrapper(it->first, it->second));
target = ::google::protobuf::internal::WireFormatLite::
WriteMessageNoVirtualToArray(
2, *entry, target);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// @@protoc_insertion_point(serialize_to_array_end:protobuf_unittest.TestSameTypeMap)
return target;
}
int TestSameTypeMap::ByteSize() const {
// @@protoc_insertion_point(message_byte_size_start:protobuf_unittest.TestSameTypeMap)
int total_size = 0;
// map<int32, int32> map1 = 1;
total_size += 1 * this->map1_size();
{
::google::protobuf::scoped_ptr<TestSameTypeMap_Map1Entry> entry;
for (::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::int32 >::const_iterator
it = this->map1().begin();
it != this->map1().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map1_.NewEntryWrapper(it->first, it->second));
total_size += ::google::protobuf::internal::WireFormatLite::
MessageSizeNoVirtual(*entry);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<int32, int32> map2 = 2;
total_size += 1 * this->map2_size();
{
::google::protobuf::scoped_ptr<TestSameTypeMap_Map2Entry> entry;
for (::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::int32 >::const_iterator
it = this->map2().begin();
it != this->map2().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map2_.NewEntryWrapper(it->first, it->second));
total_size += ::google::protobuf::internal::WireFormatLite::
MessageSizeNoVirtual(*entry);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = total_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void TestSameTypeMap::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:protobuf_unittest.TestSameTypeMap)
if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
const TestSameTypeMap* source =
::google::protobuf::internal::DynamicCastToGenerated<const TestSameTypeMap>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:protobuf_unittest.TestSameTypeMap)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:protobuf_unittest.TestSameTypeMap)
MergeFrom(*source);
}
}
void TestSameTypeMap::MergeFrom(const TestSameTypeMap& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:protobuf_unittest.TestSameTypeMap)
if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
map1_.MergeFrom(from.map1_);
map2_.MergeFrom(from.map2_);
}
void TestSameTypeMap::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:protobuf_unittest.TestSameTypeMap)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void TestSameTypeMap::CopyFrom(const TestSameTypeMap& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:protobuf_unittest.TestSameTypeMap)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool TestSameTypeMap::IsInitialized() const {
return true;
}
void TestSameTypeMap::Swap(TestSameTypeMap* other) {
if (other == this) return;
if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
InternalSwap(other);
} else {
TestSameTypeMap temp;
temp.MergeFrom(*this);
CopyFrom(*other);
other->CopyFrom(temp);
}
}
void TestSameTypeMap::UnsafeArenaSwap(TestSameTypeMap* other) {
if (other == this) return;
GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
InternalSwap(other);
}
void TestSameTypeMap::InternalSwap(TestSameTypeMap* other) {
map1_.Swap(&other->map1_);
map2_.Swap(&other->map2_);
_internal_metadata_.Swap(&other->_internal_metadata_);
std::swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata TestSameTypeMap::GetMetadata() const {
protobuf_AssignDescriptorsOnce();
::google::protobuf::Metadata metadata;
metadata.descriptor = TestSameTypeMap_descriptor_;
metadata.reflection = TestSameTypeMap_reflection_;
return metadata;
}
#if PROTOBUF_INLINE_NOT_IN_HEADERS
// TestSameTypeMap
// map<int32, int32> map1 = 1;
int TestSameTypeMap::map1_size() const {
return map1_.size();
}
void TestSameTypeMap::clear_map1() {
map1_.Clear();
}
const ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::int32 >&
TestSameTypeMap::map1() const {
// @@protoc_insertion_point(field_map:protobuf_unittest.TestSameTypeMap.map1)
return map1_.GetMap();
}
::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::int32 >*
TestSameTypeMap::mutable_map1() {
// @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestSameTypeMap.map1)
return map1_.MutableMap();
}
// map<int32, int32> map2 = 2;
int TestSameTypeMap::map2_size() const {
return map2_.size();
}
void TestSameTypeMap::clear_map2() {
map2_.Clear();
}
const ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::int32 >&
TestSameTypeMap::map2() const {
// @@protoc_insertion_point(field_map:protobuf_unittest.TestSameTypeMap.map2)
return map2_.GetMap();
}
::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::int32 >*
TestSameTypeMap::mutable_map2() {
// @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestSameTypeMap.map2)
return map2_.MutableMap();
}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int TestRequiredMessageMap::kMapFieldFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
TestRequiredMessageMap::TestRequiredMessageMap()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
SharedCtor();
// @@protoc_insertion_point(constructor:protobuf_unittest.TestRequiredMessageMap)
}
TestRequiredMessageMap::TestRequiredMessageMap(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena),
map_field_(arena) {
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:protobuf_unittest.TestRequiredMessageMap)
}
void TestRequiredMessageMap::InitAsDefaultInstance() {
_is_default_instance_ = true;
}
TestRequiredMessageMap::TestRequiredMessageMap(const TestRequiredMessageMap& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
MergeFrom(from);
// @@protoc_insertion_point(copy_constructor:protobuf_unittest.TestRequiredMessageMap)
}
void TestRequiredMessageMap::SharedCtor() {
_is_default_instance_ = false;
_cached_size_ = 0;
map_field_.SetAssignDescriptorCallback(
protobuf_AssignDescriptorsOnce);
map_field_.SetEntryDescriptor(
&::protobuf_unittest::TestRequiredMessageMap_MapFieldEntry_descriptor_);
}
TestRequiredMessageMap::~TestRequiredMessageMap() {
// @@protoc_insertion_point(destructor:protobuf_unittest.TestRequiredMessageMap)
SharedDtor();
}
void TestRequiredMessageMap::SharedDtor() {
if (GetArenaNoVirtual() != NULL) {
return;
}
if (this != default_instance_) {
}
}
void TestRequiredMessageMap::ArenaDtor(void* object) {
TestRequiredMessageMap* _this = reinterpret_cast< TestRequiredMessageMap* >(object);
(void)_this;
}
void TestRequiredMessageMap::RegisterArenaDtor(::google::protobuf::Arena* arena) {
}
void TestRequiredMessageMap::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* TestRequiredMessageMap::descriptor() {
protobuf_AssignDescriptorsOnce();
return TestRequiredMessageMap_descriptor_;
}
const TestRequiredMessageMap& TestRequiredMessageMap::default_instance() {
if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2fmap_5funittest_2eproto();
return *default_instance_;
}
TestRequiredMessageMap* TestRequiredMessageMap::default_instance_ = NULL;
TestRequiredMessageMap* TestRequiredMessageMap::New(::google::protobuf::Arena* arena) const {
return ::google::protobuf::Arena::CreateMessage<TestRequiredMessageMap>(arena);
}
void TestRequiredMessageMap::Clear() {
// @@protoc_insertion_point(message_clear_start:protobuf_unittest.TestRequiredMessageMap)
map_field_.Clear();
}
bool TestRequiredMessageMap::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:protobuf_unittest.TestRequiredMessageMap)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// map<int32, .protobuf_unittest.TestRequired> map_field = 1;
case 1: {
if (tag == 10) {
DO_(input->IncrementRecursionDepth());
parse_loop_map_field:
::google::protobuf::scoped_ptr<TestRequiredMessageMap_MapFieldEntry> entry(map_field_.NewEntry());
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, entry.get()));
(*mutable_map_field())[entry->key()].Swap(entry->mutable_value());
if (entry->GetArena() != NULL) entry.release();
} else {
goto handle_unusual;
}
if (input->ExpectTag(10)) goto parse_loop_map_field;
input->UnsafeDecrementRecursionDepth();
if (input->ExpectAtEnd()) goto success;
break;
}
default: {
handle_unusual:
if (tag == 0 ||
::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
goto success;
}
DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:protobuf_unittest.TestRequiredMessageMap)
return true;
failure:
// @@protoc_insertion_point(parse_failure:protobuf_unittest.TestRequiredMessageMap)
return false;
#undef DO_
}
void TestRequiredMessageMap::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:protobuf_unittest.TestRequiredMessageMap)
// map<int32, .protobuf_unittest.TestRequired> map_field = 1;
{
::google::protobuf::scoped_ptr<TestRequiredMessageMap_MapFieldEntry> entry;
for (::google::protobuf::Map< ::google::protobuf::int32, ::protobuf_unittest::TestRequired >::const_iterator
it = this->map_field().begin();
it != this->map_field().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_field_.NewEntryWrapper(it->first, it->second));
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
1, *entry, output);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// @@protoc_insertion_point(serialize_end:protobuf_unittest.TestRequiredMessageMap)
}
::google::protobuf::uint8* TestRequiredMessageMap::SerializeWithCachedSizesToArray(
::google::protobuf::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:protobuf_unittest.TestRequiredMessageMap)
// map<int32, .protobuf_unittest.TestRequired> map_field = 1;
{
::google::protobuf::scoped_ptr<TestRequiredMessageMap_MapFieldEntry> entry;
for (::google::protobuf::Map< ::google::protobuf::int32, ::protobuf_unittest::TestRequired >::const_iterator
it = this->map_field().begin();
it != this->map_field().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_field_.NewEntryWrapper(it->first, it->second));
target = ::google::protobuf::internal::WireFormatLite::
WriteMessageNoVirtualToArray(
1, *entry, target);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// @@protoc_insertion_point(serialize_to_array_end:protobuf_unittest.TestRequiredMessageMap)
return target;
}
int TestRequiredMessageMap::ByteSize() const {
// @@protoc_insertion_point(message_byte_size_start:protobuf_unittest.TestRequiredMessageMap)
int total_size = 0;
// map<int32, .protobuf_unittest.TestRequired> map_field = 1;
total_size += 1 * this->map_field_size();
{
::google::protobuf::scoped_ptr<TestRequiredMessageMap_MapFieldEntry> entry;
for (::google::protobuf::Map< ::google::protobuf::int32, ::protobuf_unittest::TestRequired >::const_iterator
it = this->map_field().begin();
it != this->map_field().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_field_.NewEntryWrapper(it->first, it->second));
total_size += ::google::protobuf::internal::WireFormatLite::
MessageSizeNoVirtual(*entry);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = total_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void TestRequiredMessageMap::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:protobuf_unittest.TestRequiredMessageMap)
if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
const TestRequiredMessageMap* source =
::google::protobuf::internal::DynamicCastToGenerated<const TestRequiredMessageMap>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:protobuf_unittest.TestRequiredMessageMap)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:protobuf_unittest.TestRequiredMessageMap)
MergeFrom(*source);
}
}
void TestRequiredMessageMap::MergeFrom(const TestRequiredMessageMap& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:protobuf_unittest.TestRequiredMessageMap)
if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
map_field_.MergeFrom(from.map_field_);
}
void TestRequiredMessageMap::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:protobuf_unittest.TestRequiredMessageMap)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void TestRequiredMessageMap::CopyFrom(const TestRequiredMessageMap& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:protobuf_unittest.TestRequiredMessageMap)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool TestRequiredMessageMap::IsInitialized() const {
if (!::google::protobuf::internal::AllAreInitialized(this->map_field())) return false;
return true;
}
void TestRequiredMessageMap::Swap(TestRequiredMessageMap* other) {
if (other == this) return;
if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
InternalSwap(other);
} else {
TestRequiredMessageMap temp;
temp.MergeFrom(*this);
CopyFrom(*other);
other->CopyFrom(temp);
}
}
void TestRequiredMessageMap::UnsafeArenaSwap(TestRequiredMessageMap* other) {
if (other == this) return;
GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
InternalSwap(other);
}
void TestRequiredMessageMap::InternalSwap(TestRequiredMessageMap* other) {
map_field_.Swap(&other->map_field_);
_internal_metadata_.Swap(&other->_internal_metadata_);
std::swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata TestRequiredMessageMap::GetMetadata() const {
protobuf_AssignDescriptorsOnce();
::google::protobuf::Metadata metadata;
metadata.descriptor = TestRequiredMessageMap_descriptor_;
metadata.reflection = TestRequiredMessageMap_reflection_;
return metadata;
}
#if PROTOBUF_INLINE_NOT_IN_HEADERS
// TestRequiredMessageMap
// map<int32, .protobuf_unittest.TestRequired> map_field = 1;
int TestRequiredMessageMap::map_field_size() const {
return map_field_.size();
}
void TestRequiredMessageMap::clear_map_field() {
map_field_.Clear();
}
const ::google::protobuf::Map< ::google::protobuf::int32, ::protobuf_unittest::TestRequired >&
TestRequiredMessageMap::map_field() const {
// @@protoc_insertion_point(field_map:protobuf_unittest.TestRequiredMessageMap.map_field)
return map_field_.GetMap();
}
::google::protobuf::Map< ::google::protobuf::int32, ::protobuf_unittest::TestRequired >*
TestRequiredMessageMap::mutable_map_field() {
// @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestRequiredMessageMap.map_field)
return map_field_.MutableMap();
}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int TestArenaMap::kMapInt32Int32FieldNumber;
const int TestArenaMap::kMapInt64Int64FieldNumber;
const int TestArenaMap::kMapUint32Uint32FieldNumber;
const int TestArenaMap::kMapUint64Uint64FieldNumber;
const int TestArenaMap::kMapSint32Sint32FieldNumber;
const int TestArenaMap::kMapSint64Sint64FieldNumber;
const int TestArenaMap::kMapFixed32Fixed32FieldNumber;
const int TestArenaMap::kMapFixed64Fixed64FieldNumber;
const int TestArenaMap::kMapSfixed32Sfixed32FieldNumber;
const int TestArenaMap::kMapSfixed64Sfixed64FieldNumber;
const int TestArenaMap::kMapInt32FloatFieldNumber;
const int TestArenaMap::kMapInt32DoubleFieldNumber;
const int TestArenaMap::kMapBoolBoolFieldNumber;
const int TestArenaMap::kMapStringStringFieldNumber;
const int TestArenaMap::kMapInt32BytesFieldNumber;
const int TestArenaMap::kMapInt32EnumFieldNumber;
const int TestArenaMap::kMapInt32ForeignMessageFieldNumber;
const int TestArenaMap::kMapInt32ForeignMessageNoArenaFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
TestArenaMap::TestArenaMap()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
SharedCtor();
// @@protoc_insertion_point(constructor:protobuf_unittest.TestArenaMap)
}
TestArenaMap::TestArenaMap(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena),
map_int32_int32_(arena),
map_int64_int64_(arena),
map_uint32_uint32_(arena),
map_uint64_uint64_(arena),
map_sint32_sint32_(arena),
map_sint64_sint64_(arena),
map_fixed32_fixed32_(arena),
map_fixed64_fixed64_(arena),
map_sfixed32_sfixed32_(arena),
map_sfixed64_sfixed64_(arena),
map_int32_float_(arena),
map_int32_double_(arena),
map_bool_bool_(arena),
map_string_string_(arena),
map_int32_bytes_(arena),
map_int32_enum_(arena),
map_int32_foreign_message_(arena),
map_int32_foreign_message_no_arena_(arena) {
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:protobuf_unittest.TestArenaMap)
}
void TestArenaMap::InitAsDefaultInstance() {
_is_default_instance_ = true;
}
TestArenaMap::TestArenaMap(const TestArenaMap& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
MergeFrom(from);
// @@protoc_insertion_point(copy_constructor:protobuf_unittest.TestArenaMap)
}
void TestArenaMap::SharedCtor() {
_is_default_instance_ = false;
_cached_size_ = 0;
map_int32_int32_.SetAssignDescriptorCallback(
protobuf_AssignDescriptorsOnce);
map_int32_int32_.SetEntryDescriptor(
&::protobuf_unittest::TestArenaMap_MapInt32Int32Entry_descriptor_);
map_int64_int64_.SetAssignDescriptorCallback(
protobuf_AssignDescriptorsOnce);
map_int64_int64_.SetEntryDescriptor(
&::protobuf_unittest::TestArenaMap_MapInt64Int64Entry_descriptor_);
map_uint32_uint32_.SetAssignDescriptorCallback(
protobuf_AssignDescriptorsOnce);
map_uint32_uint32_.SetEntryDescriptor(
&::protobuf_unittest::TestArenaMap_MapUint32Uint32Entry_descriptor_);
map_uint64_uint64_.SetAssignDescriptorCallback(
protobuf_AssignDescriptorsOnce);
map_uint64_uint64_.SetEntryDescriptor(
&::protobuf_unittest::TestArenaMap_MapUint64Uint64Entry_descriptor_);
map_sint32_sint32_.SetAssignDescriptorCallback(
protobuf_AssignDescriptorsOnce);
map_sint32_sint32_.SetEntryDescriptor(
&::protobuf_unittest::TestArenaMap_MapSint32Sint32Entry_descriptor_);
map_sint64_sint64_.SetAssignDescriptorCallback(
protobuf_AssignDescriptorsOnce);
map_sint64_sint64_.SetEntryDescriptor(
&::protobuf_unittest::TestArenaMap_MapSint64Sint64Entry_descriptor_);
map_fixed32_fixed32_.SetAssignDescriptorCallback(
protobuf_AssignDescriptorsOnce);
map_fixed32_fixed32_.SetEntryDescriptor(
&::protobuf_unittest::TestArenaMap_MapFixed32Fixed32Entry_descriptor_);
map_fixed64_fixed64_.SetAssignDescriptorCallback(
protobuf_AssignDescriptorsOnce);
map_fixed64_fixed64_.SetEntryDescriptor(
&::protobuf_unittest::TestArenaMap_MapFixed64Fixed64Entry_descriptor_);
map_sfixed32_sfixed32_.SetAssignDescriptorCallback(
protobuf_AssignDescriptorsOnce);
map_sfixed32_sfixed32_.SetEntryDescriptor(
&::protobuf_unittest::TestArenaMap_MapSfixed32Sfixed32Entry_descriptor_);
map_sfixed64_sfixed64_.SetAssignDescriptorCallback(
protobuf_AssignDescriptorsOnce);
map_sfixed64_sfixed64_.SetEntryDescriptor(
&::protobuf_unittest::TestArenaMap_MapSfixed64Sfixed64Entry_descriptor_);
map_int32_float_.SetAssignDescriptorCallback(
protobuf_AssignDescriptorsOnce);
map_int32_float_.SetEntryDescriptor(
&::protobuf_unittest::TestArenaMap_MapInt32FloatEntry_descriptor_);
map_int32_double_.SetAssignDescriptorCallback(
protobuf_AssignDescriptorsOnce);
map_int32_double_.SetEntryDescriptor(
&::protobuf_unittest::TestArenaMap_MapInt32DoubleEntry_descriptor_);
map_bool_bool_.SetAssignDescriptorCallback(
protobuf_AssignDescriptorsOnce);
map_bool_bool_.SetEntryDescriptor(
&::protobuf_unittest::TestArenaMap_MapBoolBoolEntry_descriptor_);
map_string_string_.SetAssignDescriptorCallback(
protobuf_AssignDescriptorsOnce);
map_string_string_.SetEntryDescriptor(
&::protobuf_unittest::TestArenaMap_MapStringStringEntry_descriptor_);
map_int32_bytes_.SetAssignDescriptorCallback(
protobuf_AssignDescriptorsOnce);
map_int32_bytes_.SetEntryDescriptor(
&::protobuf_unittest::TestArenaMap_MapInt32BytesEntry_descriptor_);
map_int32_enum_.SetAssignDescriptorCallback(
protobuf_AssignDescriptorsOnce);
map_int32_enum_.SetEntryDescriptor(
&::protobuf_unittest::TestArenaMap_MapInt32EnumEntry_descriptor_);
map_int32_foreign_message_.SetAssignDescriptorCallback(
protobuf_AssignDescriptorsOnce);
map_int32_foreign_message_.SetEntryDescriptor(
&::protobuf_unittest::TestArenaMap_MapInt32ForeignMessageEntry_descriptor_);
map_int32_foreign_message_no_arena_.SetAssignDescriptorCallback(
protobuf_AssignDescriptorsOnce);
map_int32_foreign_message_no_arena_.SetEntryDescriptor(
&::protobuf_unittest::TestArenaMap_MapInt32ForeignMessageNoArenaEntry_descriptor_);
}
TestArenaMap::~TestArenaMap() {
// @@protoc_insertion_point(destructor:protobuf_unittest.TestArenaMap)
SharedDtor();
}
void TestArenaMap::SharedDtor() {
if (GetArenaNoVirtual() != NULL) {
return;
}
if (this != default_instance_) {
}
}
void TestArenaMap::ArenaDtor(void* object) {
TestArenaMap* _this = reinterpret_cast< TestArenaMap* >(object);
(void)_this;
}
void TestArenaMap::RegisterArenaDtor(::google::protobuf::Arena* arena) {
}
void TestArenaMap::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* TestArenaMap::descriptor() {
protobuf_AssignDescriptorsOnce();
return TestArenaMap_descriptor_;
}
const TestArenaMap& TestArenaMap::default_instance() {
if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2fmap_5funittest_2eproto();
return *default_instance_;
}
TestArenaMap* TestArenaMap::default_instance_ = NULL;
TestArenaMap* TestArenaMap::New(::google::protobuf::Arena* arena) const {
return ::google::protobuf::Arena::CreateMessage<TestArenaMap>(arena);
}
void TestArenaMap::Clear() {
// @@protoc_insertion_point(message_clear_start:protobuf_unittest.TestArenaMap)
map_int32_int32_.Clear();
map_int64_int64_.Clear();
map_uint32_uint32_.Clear();
map_uint64_uint64_.Clear();
map_sint32_sint32_.Clear();
map_sint64_sint64_.Clear();
map_fixed32_fixed32_.Clear();
map_fixed64_fixed64_.Clear();
map_sfixed32_sfixed32_.Clear();
map_sfixed64_sfixed64_.Clear();
map_int32_float_.Clear();
map_int32_double_.Clear();
map_bool_bool_.Clear();
map_string_string_.Clear();
map_int32_bytes_.Clear();
map_int32_enum_.Clear();
map_int32_foreign_message_.Clear();
map_int32_foreign_message_no_arena_.Clear();
}
bool TestArenaMap::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:protobuf_unittest.TestArenaMap)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(16383);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// map<int32, int32> map_int32_int32 = 1;
case 1: {
if (tag == 10) {
DO_(input->IncrementRecursionDepth());
parse_loop_map_int32_int32:
::google::protobuf::scoped_ptr<TestArenaMap_MapInt32Int32Entry> entry(map_int32_int32_.NewEntry());
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, entry.get()));
(*mutable_map_int32_int32())[entry->key()] = *entry->mutable_value();
if (entry->GetArena() != NULL) entry.release();
} else {
goto handle_unusual;
}
if (input->ExpectTag(10)) goto parse_loop_map_int32_int32;
if (input->ExpectTag(18)) goto parse_loop_map_int64_int64;
input->UnsafeDecrementRecursionDepth();
break;
}
// map<int64, int64> map_int64_int64 = 2;
case 2: {
if (tag == 18) {
DO_(input->IncrementRecursionDepth());
parse_loop_map_int64_int64:
::google::protobuf::scoped_ptr<TestArenaMap_MapInt64Int64Entry> entry(map_int64_int64_.NewEntry());
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, entry.get()));
(*mutable_map_int64_int64())[entry->key()] = *entry->mutable_value();
if (entry->GetArena() != NULL) entry.release();
} else {
goto handle_unusual;
}
if (input->ExpectTag(18)) goto parse_loop_map_int64_int64;
if (input->ExpectTag(26)) goto parse_loop_map_uint32_uint32;
input->UnsafeDecrementRecursionDepth();
break;
}
// map<uint32, uint32> map_uint32_uint32 = 3;
case 3: {
if (tag == 26) {
DO_(input->IncrementRecursionDepth());
parse_loop_map_uint32_uint32:
::google::protobuf::scoped_ptr<TestArenaMap_MapUint32Uint32Entry> entry(map_uint32_uint32_.NewEntry());
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, entry.get()));
(*mutable_map_uint32_uint32())[entry->key()] = *entry->mutable_value();
if (entry->GetArena() != NULL) entry.release();
} else {
goto handle_unusual;
}
if (input->ExpectTag(26)) goto parse_loop_map_uint32_uint32;
if (input->ExpectTag(34)) goto parse_loop_map_uint64_uint64;
input->UnsafeDecrementRecursionDepth();
break;
}
// map<uint64, uint64> map_uint64_uint64 = 4;
case 4: {
if (tag == 34) {
DO_(input->IncrementRecursionDepth());
parse_loop_map_uint64_uint64:
::google::protobuf::scoped_ptr<TestArenaMap_MapUint64Uint64Entry> entry(map_uint64_uint64_.NewEntry());
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, entry.get()));
(*mutable_map_uint64_uint64())[entry->key()] = *entry->mutable_value();
if (entry->GetArena() != NULL) entry.release();
} else {
goto handle_unusual;
}
if (input->ExpectTag(34)) goto parse_loop_map_uint64_uint64;
if (input->ExpectTag(42)) goto parse_loop_map_sint32_sint32;
input->UnsafeDecrementRecursionDepth();
break;
}
// map<sint32, sint32> map_sint32_sint32 = 5;
case 5: {
if (tag == 42) {
DO_(input->IncrementRecursionDepth());
parse_loop_map_sint32_sint32:
::google::protobuf::scoped_ptr<TestArenaMap_MapSint32Sint32Entry> entry(map_sint32_sint32_.NewEntry());
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, entry.get()));
(*mutable_map_sint32_sint32())[entry->key()] = *entry->mutable_value();
if (entry->GetArena() != NULL) entry.release();
} else {
goto handle_unusual;
}
if (input->ExpectTag(42)) goto parse_loop_map_sint32_sint32;
if (input->ExpectTag(50)) goto parse_loop_map_sint64_sint64;
input->UnsafeDecrementRecursionDepth();
break;
}
// map<sint64, sint64> map_sint64_sint64 = 6;
case 6: {
if (tag == 50) {
DO_(input->IncrementRecursionDepth());
parse_loop_map_sint64_sint64:
::google::protobuf::scoped_ptr<TestArenaMap_MapSint64Sint64Entry> entry(map_sint64_sint64_.NewEntry());
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, entry.get()));
(*mutable_map_sint64_sint64())[entry->key()] = *entry->mutable_value();
if (entry->GetArena() != NULL) entry.release();
} else {
goto handle_unusual;
}
if (input->ExpectTag(50)) goto parse_loop_map_sint64_sint64;
if (input->ExpectTag(58)) goto parse_loop_map_fixed32_fixed32;
input->UnsafeDecrementRecursionDepth();
break;
}
// map<fixed32, fixed32> map_fixed32_fixed32 = 7;
case 7: {
if (tag == 58) {
DO_(input->IncrementRecursionDepth());
parse_loop_map_fixed32_fixed32:
::google::protobuf::scoped_ptr<TestArenaMap_MapFixed32Fixed32Entry> entry(map_fixed32_fixed32_.NewEntry());
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, entry.get()));
(*mutable_map_fixed32_fixed32())[entry->key()] = *entry->mutable_value();
if (entry->GetArena() != NULL) entry.release();
} else {
goto handle_unusual;
}
if (input->ExpectTag(58)) goto parse_loop_map_fixed32_fixed32;
if (input->ExpectTag(66)) goto parse_loop_map_fixed64_fixed64;
input->UnsafeDecrementRecursionDepth();
break;
}
// map<fixed64, fixed64> map_fixed64_fixed64 = 8;
case 8: {
if (tag == 66) {
DO_(input->IncrementRecursionDepth());
parse_loop_map_fixed64_fixed64:
::google::protobuf::scoped_ptr<TestArenaMap_MapFixed64Fixed64Entry> entry(map_fixed64_fixed64_.NewEntry());
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, entry.get()));
(*mutable_map_fixed64_fixed64())[entry->key()] = *entry->mutable_value();
if (entry->GetArena() != NULL) entry.release();
} else {
goto handle_unusual;
}
if (input->ExpectTag(66)) goto parse_loop_map_fixed64_fixed64;
if (input->ExpectTag(74)) goto parse_loop_map_sfixed32_sfixed32;
input->UnsafeDecrementRecursionDepth();
break;
}
// map<sfixed32, sfixed32> map_sfixed32_sfixed32 = 9;
case 9: {
if (tag == 74) {
DO_(input->IncrementRecursionDepth());
parse_loop_map_sfixed32_sfixed32:
::google::protobuf::scoped_ptr<TestArenaMap_MapSfixed32Sfixed32Entry> entry(map_sfixed32_sfixed32_.NewEntry());
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, entry.get()));
(*mutable_map_sfixed32_sfixed32())[entry->key()] = *entry->mutable_value();
if (entry->GetArena() != NULL) entry.release();
} else {
goto handle_unusual;
}
if (input->ExpectTag(74)) goto parse_loop_map_sfixed32_sfixed32;
if (input->ExpectTag(82)) goto parse_loop_map_sfixed64_sfixed64;
input->UnsafeDecrementRecursionDepth();
break;
}
// map<sfixed64, sfixed64> map_sfixed64_sfixed64 = 10;
case 10: {
if (tag == 82) {
DO_(input->IncrementRecursionDepth());
parse_loop_map_sfixed64_sfixed64:
::google::protobuf::scoped_ptr<TestArenaMap_MapSfixed64Sfixed64Entry> entry(map_sfixed64_sfixed64_.NewEntry());
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, entry.get()));
(*mutable_map_sfixed64_sfixed64())[entry->key()] = *entry->mutable_value();
if (entry->GetArena() != NULL) entry.release();
} else {
goto handle_unusual;
}
if (input->ExpectTag(82)) goto parse_loop_map_sfixed64_sfixed64;
if (input->ExpectTag(90)) goto parse_loop_map_int32_float;
input->UnsafeDecrementRecursionDepth();
break;
}
// map<int32, float> map_int32_float = 11;
case 11: {
if (tag == 90) {
DO_(input->IncrementRecursionDepth());
parse_loop_map_int32_float:
::google::protobuf::scoped_ptr<TestArenaMap_MapInt32FloatEntry> entry(map_int32_float_.NewEntry());
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, entry.get()));
(*mutable_map_int32_float())[entry->key()] = *entry->mutable_value();
if (entry->GetArena() != NULL) entry.release();
} else {
goto handle_unusual;
}
if (input->ExpectTag(90)) goto parse_loop_map_int32_float;
if (input->ExpectTag(98)) goto parse_loop_map_int32_double;
input->UnsafeDecrementRecursionDepth();
break;
}
// map<int32, double> map_int32_double = 12;
case 12: {
if (tag == 98) {
DO_(input->IncrementRecursionDepth());
parse_loop_map_int32_double:
::google::protobuf::scoped_ptr<TestArenaMap_MapInt32DoubleEntry> entry(map_int32_double_.NewEntry());
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, entry.get()));
(*mutable_map_int32_double())[entry->key()] = *entry->mutable_value();
if (entry->GetArena() != NULL) entry.release();
} else {
goto handle_unusual;
}
if (input->ExpectTag(98)) goto parse_loop_map_int32_double;
if (input->ExpectTag(106)) goto parse_loop_map_bool_bool;
input->UnsafeDecrementRecursionDepth();
break;
}
// map<bool, bool> map_bool_bool = 13;
case 13: {
if (tag == 106) {
DO_(input->IncrementRecursionDepth());
parse_loop_map_bool_bool:
::google::protobuf::scoped_ptr<TestArenaMap_MapBoolBoolEntry> entry(map_bool_bool_.NewEntry());
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, entry.get()));
(*mutable_map_bool_bool())[entry->key()] = *entry->mutable_value();
if (entry->GetArena() != NULL) entry.release();
} else {
goto handle_unusual;
}
if (input->ExpectTag(106)) goto parse_loop_map_bool_bool;
if (input->ExpectTag(114)) goto parse_loop_map_string_string;
input->UnsafeDecrementRecursionDepth();
break;
}
// map<string, string> map_string_string = 14;
case 14: {
if (tag == 114) {
DO_(input->IncrementRecursionDepth());
parse_loop_map_string_string:
::google::protobuf::scoped_ptr<TestArenaMap_MapStringStringEntry> entry(map_string_string_.NewEntry());
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, entry.get()));
(*mutable_map_string_string())[entry->key()] = *entry->mutable_value();
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
entry->key().data(), entry->key().length(),
::google::protobuf::internal::WireFormatLite::PARSE,
"protobuf_unittest.TestArenaMap.MapStringStringEntry.key"));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
entry->mutable_value()->data(),
entry->mutable_value()->length(),
::google::protobuf::internal::WireFormatLite::PARSE,
"protobuf_unittest.TestArenaMap.MapStringStringEntry.value"));
if (entry->GetArena() != NULL) entry.release();
} else {
goto handle_unusual;
}
if (input->ExpectTag(114)) goto parse_loop_map_string_string;
if (input->ExpectTag(122)) goto parse_loop_map_int32_bytes;
input->UnsafeDecrementRecursionDepth();
break;
}
// map<int32, bytes> map_int32_bytes = 15;
case 15: {
if (tag == 122) {
DO_(input->IncrementRecursionDepth());
parse_loop_map_int32_bytes:
::google::protobuf::scoped_ptr<TestArenaMap_MapInt32BytesEntry> entry(map_int32_bytes_.NewEntry());
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, entry.get()));
(*mutable_map_int32_bytes())[entry->key()] = *entry->mutable_value();
if (entry->GetArena() != NULL) entry.release();
} else {
goto handle_unusual;
}
if (input->ExpectTag(122)) goto parse_loop_map_int32_bytes;
if (input->ExpectTag(130)) goto parse_loop_map_int32_enum;
input->UnsafeDecrementRecursionDepth();
break;
}
// map<int32, .protobuf_unittest.MapEnum> map_int32_enum = 16;
case 16: {
if (tag == 130) {
DO_(input->IncrementRecursionDepth());
parse_loop_map_int32_enum:
::google::protobuf::scoped_ptr<TestArenaMap_MapInt32EnumEntry> entry(map_int32_enum_.NewEntry());
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, entry.get()));
(*mutable_map_int32_enum())[entry->key()] =
static_cast< ::protobuf_unittest::MapEnum >(*entry->mutable_value());
if (entry->GetArena() != NULL) entry.release();
} else {
goto handle_unusual;
}
if (input->ExpectTag(130)) goto parse_loop_map_int32_enum;
if (input->ExpectTag(138)) goto parse_loop_map_int32_foreign_message;
input->UnsafeDecrementRecursionDepth();
break;
}
// map<int32, .protobuf_unittest.ForeignMessage> map_int32_foreign_message = 17;
case 17: {
if (tag == 138) {
DO_(input->IncrementRecursionDepth());
parse_loop_map_int32_foreign_message:
::google::protobuf::scoped_ptr<TestArenaMap_MapInt32ForeignMessageEntry> entry(map_int32_foreign_message_.NewEntry());
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, entry.get()));
(*mutable_map_int32_foreign_message())[entry->key()].Swap(entry->mutable_value());
if (entry->GetArena() != NULL) entry.release();
} else {
goto handle_unusual;
}
if (input->ExpectTag(138)) goto parse_loop_map_int32_foreign_message;
if (input->ExpectTag(146)) goto parse_loop_map_int32_foreign_message_no_arena;
input->UnsafeDecrementRecursionDepth();
break;
}
// map<int32, .protobuf_unittest_no_arena.ForeignMessage> map_int32_foreign_message_no_arena = 18;
case 18: {
if (tag == 146) {
DO_(input->IncrementRecursionDepth());
parse_loop_map_int32_foreign_message_no_arena:
::google::protobuf::scoped_ptr<TestArenaMap_MapInt32ForeignMessageNoArenaEntry> entry(map_int32_foreign_message_no_arena_.NewEntry());
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, entry.get()));
(*mutable_map_int32_foreign_message_no_arena())[entry->key()].Swap(entry->mutable_value());
if (entry->GetArena() != NULL) entry.release();
} else {
goto handle_unusual;
}
if (input->ExpectTag(146)) goto parse_loop_map_int32_foreign_message_no_arena;
input->UnsafeDecrementRecursionDepth();
if (input->ExpectAtEnd()) goto success;
break;
}
default: {
handle_unusual:
if (tag == 0 ||
::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
goto success;
}
DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:protobuf_unittest.TestArenaMap)
return true;
failure:
// @@protoc_insertion_point(parse_failure:protobuf_unittest.TestArenaMap)
return false;
#undef DO_
}
void TestArenaMap::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:protobuf_unittest.TestArenaMap)
// map<int32, int32> map_int32_int32 = 1;
{
::google::protobuf::scoped_ptr<TestArenaMap_MapInt32Int32Entry> entry;
for (::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::int32 >::const_iterator
it = this->map_int32_int32().begin();
it != this->map_int32_int32().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_int32_int32_.NewEntryWrapper(it->first, it->second));
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
1, *entry, output);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<int64, int64> map_int64_int64 = 2;
{
::google::protobuf::scoped_ptr<TestArenaMap_MapInt64Int64Entry> entry;
for (::google::protobuf::Map< ::google::protobuf::int64, ::google::protobuf::int64 >::const_iterator
it = this->map_int64_int64().begin();
it != this->map_int64_int64().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_int64_int64_.NewEntryWrapper(it->first, it->second));
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
2, *entry, output);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<uint32, uint32> map_uint32_uint32 = 3;
{
::google::protobuf::scoped_ptr<TestArenaMap_MapUint32Uint32Entry> entry;
for (::google::protobuf::Map< ::google::protobuf::uint32, ::google::protobuf::uint32 >::const_iterator
it = this->map_uint32_uint32().begin();
it != this->map_uint32_uint32().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_uint32_uint32_.NewEntryWrapper(it->first, it->second));
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
3, *entry, output);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<uint64, uint64> map_uint64_uint64 = 4;
{
::google::protobuf::scoped_ptr<TestArenaMap_MapUint64Uint64Entry> entry;
for (::google::protobuf::Map< ::google::protobuf::uint64, ::google::protobuf::uint64 >::const_iterator
it = this->map_uint64_uint64().begin();
it != this->map_uint64_uint64().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_uint64_uint64_.NewEntryWrapper(it->first, it->second));
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
4, *entry, output);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<sint32, sint32> map_sint32_sint32 = 5;
{
::google::protobuf::scoped_ptr<TestArenaMap_MapSint32Sint32Entry> entry;
for (::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::int32 >::const_iterator
it = this->map_sint32_sint32().begin();
it != this->map_sint32_sint32().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_sint32_sint32_.NewEntryWrapper(it->first, it->second));
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
5, *entry, output);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<sint64, sint64> map_sint64_sint64 = 6;
{
::google::protobuf::scoped_ptr<TestArenaMap_MapSint64Sint64Entry> entry;
for (::google::protobuf::Map< ::google::protobuf::int64, ::google::protobuf::int64 >::const_iterator
it = this->map_sint64_sint64().begin();
it != this->map_sint64_sint64().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_sint64_sint64_.NewEntryWrapper(it->first, it->second));
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
6, *entry, output);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<fixed32, fixed32> map_fixed32_fixed32 = 7;
{
::google::protobuf::scoped_ptr<TestArenaMap_MapFixed32Fixed32Entry> entry;
for (::google::protobuf::Map< ::google::protobuf::uint32, ::google::protobuf::uint32 >::const_iterator
it = this->map_fixed32_fixed32().begin();
it != this->map_fixed32_fixed32().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_fixed32_fixed32_.NewEntryWrapper(it->first, it->second));
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
7, *entry, output);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<fixed64, fixed64> map_fixed64_fixed64 = 8;
{
::google::protobuf::scoped_ptr<TestArenaMap_MapFixed64Fixed64Entry> entry;
for (::google::protobuf::Map< ::google::protobuf::uint64, ::google::protobuf::uint64 >::const_iterator
it = this->map_fixed64_fixed64().begin();
it != this->map_fixed64_fixed64().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_fixed64_fixed64_.NewEntryWrapper(it->first, it->second));
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
8, *entry, output);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<sfixed32, sfixed32> map_sfixed32_sfixed32 = 9;
{
::google::protobuf::scoped_ptr<TestArenaMap_MapSfixed32Sfixed32Entry> entry;
for (::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::int32 >::const_iterator
it = this->map_sfixed32_sfixed32().begin();
it != this->map_sfixed32_sfixed32().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_sfixed32_sfixed32_.NewEntryWrapper(it->first, it->second));
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
9, *entry, output);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<sfixed64, sfixed64> map_sfixed64_sfixed64 = 10;
{
::google::protobuf::scoped_ptr<TestArenaMap_MapSfixed64Sfixed64Entry> entry;
for (::google::protobuf::Map< ::google::protobuf::int64, ::google::protobuf::int64 >::const_iterator
it = this->map_sfixed64_sfixed64().begin();
it != this->map_sfixed64_sfixed64().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_sfixed64_sfixed64_.NewEntryWrapper(it->first, it->second));
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
10, *entry, output);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<int32, float> map_int32_float = 11;
{
::google::protobuf::scoped_ptr<TestArenaMap_MapInt32FloatEntry> entry;
for (::google::protobuf::Map< ::google::protobuf::int32, float >::const_iterator
it = this->map_int32_float().begin();
it != this->map_int32_float().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_int32_float_.NewEntryWrapper(it->first, it->second));
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
11, *entry, output);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<int32, double> map_int32_double = 12;
{
::google::protobuf::scoped_ptr<TestArenaMap_MapInt32DoubleEntry> entry;
for (::google::protobuf::Map< ::google::protobuf::int32, double >::const_iterator
it = this->map_int32_double().begin();
it != this->map_int32_double().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_int32_double_.NewEntryWrapper(it->first, it->second));
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
12, *entry, output);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<bool, bool> map_bool_bool = 13;
{
::google::protobuf::scoped_ptr<TestArenaMap_MapBoolBoolEntry> entry;
for (::google::protobuf::Map< bool, bool >::const_iterator
it = this->map_bool_bool().begin();
it != this->map_bool_bool().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_bool_bool_.NewEntryWrapper(it->first, it->second));
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
13, *entry, output);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<string, string> map_string_string = 14;
{
::google::protobuf::scoped_ptr<TestArenaMap_MapStringStringEntry> entry;
for (::google::protobuf::Map< ::std::string, ::std::string >::const_iterator
it = this->map_string_string().begin();
it != this->map_string_string().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_string_string_.NewEntryWrapper(it->first, it->second));
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
14, *entry, output);
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
it->first.data(), it->first.length(),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"protobuf_unittest.TestArenaMap.MapStringStringEntry.key");
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
it->second.data(), it->second.length(),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"protobuf_unittest.TestArenaMap.MapStringStringEntry.value");
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<int32, bytes> map_int32_bytes = 15;
{
::google::protobuf::scoped_ptr<TestArenaMap_MapInt32BytesEntry> entry;
for (::google::protobuf::Map< ::google::protobuf::int32, ::std::string >::const_iterator
it = this->map_int32_bytes().begin();
it != this->map_int32_bytes().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_int32_bytes_.NewEntryWrapper(it->first, it->second));
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
15, *entry, output);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<int32, .protobuf_unittest.MapEnum> map_int32_enum = 16;
{
::google::protobuf::scoped_ptr<TestArenaMap_MapInt32EnumEntry> entry;
for (::google::protobuf::Map< ::google::protobuf::int32, ::protobuf_unittest::MapEnum >::const_iterator
it = this->map_int32_enum().begin();
it != this->map_int32_enum().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_int32_enum_.NewEnumEntryWrapper(it->first, it->second));
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
16, *entry, output);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<int32, .protobuf_unittest.ForeignMessage> map_int32_foreign_message = 17;
{
::google::protobuf::scoped_ptr<TestArenaMap_MapInt32ForeignMessageEntry> entry;
for (::google::protobuf::Map< ::google::protobuf::int32, ::protobuf_unittest::ForeignMessage >::const_iterator
it = this->map_int32_foreign_message().begin();
it != this->map_int32_foreign_message().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_int32_foreign_message_.NewEntryWrapper(it->first, it->second));
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
17, *entry, output);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<int32, .protobuf_unittest_no_arena.ForeignMessage> map_int32_foreign_message_no_arena = 18;
{
::google::protobuf::scoped_ptr<TestArenaMap_MapInt32ForeignMessageNoArenaEntry> entry;
for (::google::protobuf::Map< ::google::protobuf::int32, ::protobuf_unittest_no_arena::ForeignMessage >::const_iterator
it = this->map_int32_foreign_message_no_arena().begin();
it != this->map_int32_foreign_message_no_arena().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_int32_foreign_message_no_arena_.NewEntryWrapper(it->first, it->second));
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
18, *entry, output);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// @@protoc_insertion_point(serialize_end:protobuf_unittest.TestArenaMap)
}
::google::protobuf::uint8* TestArenaMap::SerializeWithCachedSizesToArray(
::google::protobuf::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:protobuf_unittest.TestArenaMap)
// map<int32, int32> map_int32_int32 = 1;
{
::google::protobuf::scoped_ptr<TestArenaMap_MapInt32Int32Entry> entry;
for (::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::int32 >::const_iterator
it = this->map_int32_int32().begin();
it != this->map_int32_int32().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_int32_int32_.NewEntryWrapper(it->first, it->second));
target = ::google::protobuf::internal::WireFormatLite::
WriteMessageNoVirtualToArray(
1, *entry, target);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<int64, int64> map_int64_int64 = 2;
{
::google::protobuf::scoped_ptr<TestArenaMap_MapInt64Int64Entry> entry;
for (::google::protobuf::Map< ::google::protobuf::int64, ::google::protobuf::int64 >::const_iterator
it = this->map_int64_int64().begin();
it != this->map_int64_int64().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_int64_int64_.NewEntryWrapper(it->first, it->second));
target = ::google::protobuf::internal::WireFormatLite::
WriteMessageNoVirtualToArray(
2, *entry, target);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<uint32, uint32> map_uint32_uint32 = 3;
{
::google::protobuf::scoped_ptr<TestArenaMap_MapUint32Uint32Entry> entry;
for (::google::protobuf::Map< ::google::protobuf::uint32, ::google::protobuf::uint32 >::const_iterator
it = this->map_uint32_uint32().begin();
it != this->map_uint32_uint32().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_uint32_uint32_.NewEntryWrapper(it->first, it->second));
target = ::google::protobuf::internal::WireFormatLite::
WriteMessageNoVirtualToArray(
3, *entry, target);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<uint64, uint64> map_uint64_uint64 = 4;
{
::google::protobuf::scoped_ptr<TestArenaMap_MapUint64Uint64Entry> entry;
for (::google::protobuf::Map< ::google::protobuf::uint64, ::google::protobuf::uint64 >::const_iterator
it = this->map_uint64_uint64().begin();
it != this->map_uint64_uint64().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_uint64_uint64_.NewEntryWrapper(it->first, it->second));
target = ::google::protobuf::internal::WireFormatLite::
WriteMessageNoVirtualToArray(
4, *entry, target);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<sint32, sint32> map_sint32_sint32 = 5;
{
::google::protobuf::scoped_ptr<TestArenaMap_MapSint32Sint32Entry> entry;
for (::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::int32 >::const_iterator
it = this->map_sint32_sint32().begin();
it != this->map_sint32_sint32().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_sint32_sint32_.NewEntryWrapper(it->first, it->second));
target = ::google::protobuf::internal::WireFormatLite::
WriteMessageNoVirtualToArray(
5, *entry, target);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<sint64, sint64> map_sint64_sint64 = 6;
{
::google::protobuf::scoped_ptr<TestArenaMap_MapSint64Sint64Entry> entry;
for (::google::protobuf::Map< ::google::protobuf::int64, ::google::protobuf::int64 >::const_iterator
it = this->map_sint64_sint64().begin();
it != this->map_sint64_sint64().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_sint64_sint64_.NewEntryWrapper(it->first, it->second));
target = ::google::protobuf::internal::WireFormatLite::
WriteMessageNoVirtualToArray(
6, *entry, target);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<fixed32, fixed32> map_fixed32_fixed32 = 7;
{
::google::protobuf::scoped_ptr<TestArenaMap_MapFixed32Fixed32Entry> entry;
for (::google::protobuf::Map< ::google::protobuf::uint32, ::google::protobuf::uint32 >::const_iterator
it = this->map_fixed32_fixed32().begin();
it != this->map_fixed32_fixed32().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_fixed32_fixed32_.NewEntryWrapper(it->first, it->second));
target = ::google::protobuf::internal::WireFormatLite::
WriteMessageNoVirtualToArray(
7, *entry, target);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<fixed64, fixed64> map_fixed64_fixed64 = 8;
{
::google::protobuf::scoped_ptr<TestArenaMap_MapFixed64Fixed64Entry> entry;
for (::google::protobuf::Map< ::google::protobuf::uint64, ::google::protobuf::uint64 >::const_iterator
it = this->map_fixed64_fixed64().begin();
it != this->map_fixed64_fixed64().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_fixed64_fixed64_.NewEntryWrapper(it->first, it->second));
target = ::google::protobuf::internal::WireFormatLite::
WriteMessageNoVirtualToArray(
8, *entry, target);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<sfixed32, sfixed32> map_sfixed32_sfixed32 = 9;
{
::google::protobuf::scoped_ptr<TestArenaMap_MapSfixed32Sfixed32Entry> entry;
for (::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::int32 >::const_iterator
it = this->map_sfixed32_sfixed32().begin();
it != this->map_sfixed32_sfixed32().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_sfixed32_sfixed32_.NewEntryWrapper(it->first, it->second));
target = ::google::protobuf::internal::WireFormatLite::
WriteMessageNoVirtualToArray(
9, *entry, target);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<sfixed64, sfixed64> map_sfixed64_sfixed64 = 10;
{
::google::protobuf::scoped_ptr<TestArenaMap_MapSfixed64Sfixed64Entry> entry;
for (::google::protobuf::Map< ::google::protobuf::int64, ::google::protobuf::int64 >::const_iterator
it = this->map_sfixed64_sfixed64().begin();
it != this->map_sfixed64_sfixed64().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_sfixed64_sfixed64_.NewEntryWrapper(it->first, it->second));
target = ::google::protobuf::internal::WireFormatLite::
WriteMessageNoVirtualToArray(
10, *entry, target);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<int32, float> map_int32_float = 11;
{
::google::protobuf::scoped_ptr<TestArenaMap_MapInt32FloatEntry> entry;
for (::google::protobuf::Map< ::google::protobuf::int32, float >::const_iterator
it = this->map_int32_float().begin();
it != this->map_int32_float().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_int32_float_.NewEntryWrapper(it->first, it->second));
target = ::google::protobuf::internal::WireFormatLite::
WriteMessageNoVirtualToArray(
11, *entry, target);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<int32, double> map_int32_double = 12;
{
::google::protobuf::scoped_ptr<TestArenaMap_MapInt32DoubleEntry> entry;
for (::google::protobuf::Map< ::google::protobuf::int32, double >::const_iterator
it = this->map_int32_double().begin();
it != this->map_int32_double().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_int32_double_.NewEntryWrapper(it->first, it->second));
target = ::google::protobuf::internal::WireFormatLite::
WriteMessageNoVirtualToArray(
12, *entry, target);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<bool, bool> map_bool_bool = 13;
{
::google::protobuf::scoped_ptr<TestArenaMap_MapBoolBoolEntry> entry;
for (::google::protobuf::Map< bool, bool >::const_iterator
it = this->map_bool_bool().begin();
it != this->map_bool_bool().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_bool_bool_.NewEntryWrapper(it->first, it->second));
target = ::google::protobuf::internal::WireFormatLite::
WriteMessageNoVirtualToArray(
13, *entry, target);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<string, string> map_string_string = 14;
{
::google::protobuf::scoped_ptr<TestArenaMap_MapStringStringEntry> entry;
for (::google::protobuf::Map< ::std::string, ::std::string >::const_iterator
it = this->map_string_string().begin();
it != this->map_string_string().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_string_string_.NewEntryWrapper(it->first, it->second));
target = ::google::protobuf::internal::WireFormatLite::
WriteMessageNoVirtualToArray(
14, *entry, target);
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
it->first.data(), it->first.length(),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"protobuf_unittest.TestArenaMap.MapStringStringEntry.key");
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
it->second.data(), it->second.length(),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"protobuf_unittest.TestArenaMap.MapStringStringEntry.value");
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<int32, bytes> map_int32_bytes = 15;
{
::google::protobuf::scoped_ptr<TestArenaMap_MapInt32BytesEntry> entry;
for (::google::protobuf::Map< ::google::protobuf::int32, ::std::string >::const_iterator
it = this->map_int32_bytes().begin();
it != this->map_int32_bytes().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_int32_bytes_.NewEntryWrapper(it->first, it->second));
target = ::google::protobuf::internal::WireFormatLite::
WriteMessageNoVirtualToArray(
15, *entry, target);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<int32, .protobuf_unittest.MapEnum> map_int32_enum = 16;
{
::google::protobuf::scoped_ptr<TestArenaMap_MapInt32EnumEntry> entry;
for (::google::protobuf::Map< ::google::protobuf::int32, ::protobuf_unittest::MapEnum >::const_iterator
it = this->map_int32_enum().begin();
it != this->map_int32_enum().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_int32_enum_.NewEnumEntryWrapper(it->first, it->second));
target = ::google::protobuf::internal::WireFormatLite::
WriteMessageNoVirtualToArray(
16, *entry, target);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<int32, .protobuf_unittest.ForeignMessage> map_int32_foreign_message = 17;
{
::google::protobuf::scoped_ptr<TestArenaMap_MapInt32ForeignMessageEntry> entry;
for (::google::protobuf::Map< ::google::protobuf::int32, ::protobuf_unittest::ForeignMessage >::const_iterator
it = this->map_int32_foreign_message().begin();
it != this->map_int32_foreign_message().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_int32_foreign_message_.NewEntryWrapper(it->first, it->second));
target = ::google::protobuf::internal::WireFormatLite::
WriteMessageNoVirtualToArray(
17, *entry, target);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<int32, .protobuf_unittest_no_arena.ForeignMessage> map_int32_foreign_message_no_arena = 18;
{
::google::protobuf::scoped_ptr<TestArenaMap_MapInt32ForeignMessageNoArenaEntry> entry;
for (::google::protobuf::Map< ::google::protobuf::int32, ::protobuf_unittest_no_arena::ForeignMessage >::const_iterator
it = this->map_int32_foreign_message_no_arena().begin();
it != this->map_int32_foreign_message_no_arena().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_int32_foreign_message_no_arena_.NewEntryWrapper(it->first, it->second));
target = ::google::protobuf::internal::WireFormatLite::
WriteMessageNoVirtualToArray(
18, *entry, target);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// @@protoc_insertion_point(serialize_to_array_end:protobuf_unittest.TestArenaMap)
return target;
}
int TestArenaMap::ByteSize() const {
// @@protoc_insertion_point(message_byte_size_start:protobuf_unittest.TestArenaMap)
int total_size = 0;
// map<int32, int32> map_int32_int32 = 1;
total_size += 1 * this->map_int32_int32_size();
{
::google::protobuf::scoped_ptr<TestArenaMap_MapInt32Int32Entry> entry;
for (::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::int32 >::const_iterator
it = this->map_int32_int32().begin();
it != this->map_int32_int32().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_int32_int32_.NewEntryWrapper(it->first, it->second));
total_size += ::google::protobuf::internal::WireFormatLite::
MessageSizeNoVirtual(*entry);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<int64, int64> map_int64_int64 = 2;
total_size += 1 * this->map_int64_int64_size();
{
::google::protobuf::scoped_ptr<TestArenaMap_MapInt64Int64Entry> entry;
for (::google::protobuf::Map< ::google::protobuf::int64, ::google::protobuf::int64 >::const_iterator
it = this->map_int64_int64().begin();
it != this->map_int64_int64().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_int64_int64_.NewEntryWrapper(it->first, it->second));
total_size += ::google::protobuf::internal::WireFormatLite::
MessageSizeNoVirtual(*entry);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<uint32, uint32> map_uint32_uint32 = 3;
total_size += 1 * this->map_uint32_uint32_size();
{
::google::protobuf::scoped_ptr<TestArenaMap_MapUint32Uint32Entry> entry;
for (::google::protobuf::Map< ::google::protobuf::uint32, ::google::protobuf::uint32 >::const_iterator
it = this->map_uint32_uint32().begin();
it != this->map_uint32_uint32().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_uint32_uint32_.NewEntryWrapper(it->first, it->second));
total_size += ::google::protobuf::internal::WireFormatLite::
MessageSizeNoVirtual(*entry);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<uint64, uint64> map_uint64_uint64 = 4;
total_size += 1 * this->map_uint64_uint64_size();
{
::google::protobuf::scoped_ptr<TestArenaMap_MapUint64Uint64Entry> entry;
for (::google::protobuf::Map< ::google::protobuf::uint64, ::google::protobuf::uint64 >::const_iterator
it = this->map_uint64_uint64().begin();
it != this->map_uint64_uint64().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_uint64_uint64_.NewEntryWrapper(it->first, it->second));
total_size += ::google::protobuf::internal::WireFormatLite::
MessageSizeNoVirtual(*entry);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<sint32, sint32> map_sint32_sint32 = 5;
total_size += 1 * this->map_sint32_sint32_size();
{
::google::protobuf::scoped_ptr<TestArenaMap_MapSint32Sint32Entry> entry;
for (::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::int32 >::const_iterator
it = this->map_sint32_sint32().begin();
it != this->map_sint32_sint32().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_sint32_sint32_.NewEntryWrapper(it->first, it->second));
total_size += ::google::protobuf::internal::WireFormatLite::
MessageSizeNoVirtual(*entry);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<sint64, sint64> map_sint64_sint64 = 6;
total_size += 1 * this->map_sint64_sint64_size();
{
::google::protobuf::scoped_ptr<TestArenaMap_MapSint64Sint64Entry> entry;
for (::google::protobuf::Map< ::google::protobuf::int64, ::google::protobuf::int64 >::const_iterator
it = this->map_sint64_sint64().begin();
it != this->map_sint64_sint64().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_sint64_sint64_.NewEntryWrapper(it->first, it->second));
total_size += ::google::protobuf::internal::WireFormatLite::
MessageSizeNoVirtual(*entry);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<fixed32, fixed32> map_fixed32_fixed32 = 7;
total_size += 1 * this->map_fixed32_fixed32_size();
{
::google::protobuf::scoped_ptr<TestArenaMap_MapFixed32Fixed32Entry> entry;
for (::google::protobuf::Map< ::google::protobuf::uint32, ::google::protobuf::uint32 >::const_iterator
it = this->map_fixed32_fixed32().begin();
it != this->map_fixed32_fixed32().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_fixed32_fixed32_.NewEntryWrapper(it->first, it->second));
total_size += ::google::protobuf::internal::WireFormatLite::
MessageSizeNoVirtual(*entry);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<fixed64, fixed64> map_fixed64_fixed64 = 8;
total_size += 1 * this->map_fixed64_fixed64_size();
{
::google::protobuf::scoped_ptr<TestArenaMap_MapFixed64Fixed64Entry> entry;
for (::google::protobuf::Map< ::google::protobuf::uint64, ::google::protobuf::uint64 >::const_iterator
it = this->map_fixed64_fixed64().begin();
it != this->map_fixed64_fixed64().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_fixed64_fixed64_.NewEntryWrapper(it->first, it->second));
total_size += ::google::protobuf::internal::WireFormatLite::
MessageSizeNoVirtual(*entry);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<sfixed32, sfixed32> map_sfixed32_sfixed32 = 9;
total_size += 1 * this->map_sfixed32_sfixed32_size();
{
::google::protobuf::scoped_ptr<TestArenaMap_MapSfixed32Sfixed32Entry> entry;
for (::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::int32 >::const_iterator
it = this->map_sfixed32_sfixed32().begin();
it != this->map_sfixed32_sfixed32().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_sfixed32_sfixed32_.NewEntryWrapper(it->first, it->second));
total_size += ::google::protobuf::internal::WireFormatLite::
MessageSizeNoVirtual(*entry);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<sfixed64, sfixed64> map_sfixed64_sfixed64 = 10;
total_size += 1 * this->map_sfixed64_sfixed64_size();
{
::google::protobuf::scoped_ptr<TestArenaMap_MapSfixed64Sfixed64Entry> entry;
for (::google::protobuf::Map< ::google::protobuf::int64, ::google::protobuf::int64 >::const_iterator
it = this->map_sfixed64_sfixed64().begin();
it != this->map_sfixed64_sfixed64().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_sfixed64_sfixed64_.NewEntryWrapper(it->first, it->second));
total_size += ::google::protobuf::internal::WireFormatLite::
MessageSizeNoVirtual(*entry);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<int32, float> map_int32_float = 11;
total_size += 1 * this->map_int32_float_size();
{
::google::protobuf::scoped_ptr<TestArenaMap_MapInt32FloatEntry> entry;
for (::google::protobuf::Map< ::google::protobuf::int32, float >::const_iterator
it = this->map_int32_float().begin();
it != this->map_int32_float().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_int32_float_.NewEntryWrapper(it->first, it->second));
total_size += ::google::protobuf::internal::WireFormatLite::
MessageSizeNoVirtual(*entry);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<int32, double> map_int32_double = 12;
total_size += 1 * this->map_int32_double_size();
{
::google::protobuf::scoped_ptr<TestArenaMap_MapInt32DoubleEntry> entry;
for (::google::protobuf::Map< ::google::protobuf::int32, double >::const_iterator
it = this->map_int32_double().begin();
it != this->map_int32_double().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_int32_double_.NewEntryWrapper(it->first, it->second));
total_size += ::google::protobuf::internal::WireFormatLite::
MessageSizeNoVirtual(*entry);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<bool, bool> map_bool_bool = 13;
total_size += 1 * this->map_bool_bool_size();
{
::google::protobuf::scoped_ptr<TestArenaMap_MapBoolBoolEntry> entry;
for (::google::protobuf::Map< bool, bool >::const_iterator
it = this->map_bool_bool().begin();
it != this->map_bool_bool().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_bool_bool_.NewEntryWrapper(it->first, it->second));
total_size += ::google::protobuf::internal::WireFormatLite::
MessageSizeNoVirtual(*entry);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<string, string> map_string_string = 14;
total_size += 1 * this->map_string_string_size();
{
::google::protobuf::scoped_ptr<TestArenaMap_MapStringStringEntry> entry;
for (::google::protobuf::Map< ::std::string, ::std::string >::const_iterator
it = this->map_string_string().begin();
it != this->map_string_string().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_string_string_.NewEntryWrapper(it->first, it->second));
total_size += ::google::protobuf::internal::WireFormatLite::
MessageSizeNoVirtual(*entry);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<int32, bytes> map_int32_bytes = 15;
total_size += 1 * this->map_int32_bytes_size();
{
::google::protobuf::scoped_ptr<TestArenaMap_MapInt32BytesEntry> entry;
for (::google::protobuf::Map< ::google::protobuf::int32, ::std::string >::const_iterator
it = this->map_int32_bytes().begin();
it != this->map_int32_bytes().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_int32_bytes_.NewEntryWrapper(it->first, it->second));
total_size += ::google::protobuf::internal::WireFormatLite::
MessageSizeNoVirtual(*entry);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<int32, .protobuf_unittest.MapEnum> map_int32_enum = 16;
total_size += 2 * this->map_int32_enum_size();
{
::google::protobuf::scoped_ptr<TestArenaMap_MapInt32EnumEntry> entry;
for (::google::protobuf::Map< ::google::protobuf::int32, ::protobuf_unittest::MapEnum >::const_iterator
it = this->map_int32_enum().begin();
it != this->map_int32_enum().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_int32_enum_.NewEnumEntryWrapper(it->first, it->second));
total_size += ::google::protobuf::internal::WireFormatLite::
MessageSizeNoVirtual(*entry);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<int32, .protobuf_unittest.ForeignMessage> map_int32_foreign_message = 17;
total_size += 2 * this->map_int32_foreign_message_size();
{
::google::protobuf::scoped_ptr<TestArenaMap_MapInt32ForeignMessageEntry> entry;
for (::google::protobuf::Map< ::google::protobuf::int32, ::protobuf_unittest::ForeignMessage >::const_iterator
it = this->map_int32_foreign_message().begin();
it != this->map_int32_foreign_message().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_int32_foreign_message_.NewEntryWrapper(it->first, it->second));
total_size += ::google::protobuf::internal::WireFormatLite::
MessageSizeNoVirtual(*entry);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<int32, .protobuf_unittest_no_arena.ForeignMessage> map_int32_foreign_message_no_arena = 18;
total_size += 2 * this->map_int32_foreign_message_no_arena_size();
{
::google::protobuf::scoped_ptr<TestArenaMap_MapInt32ForeignMessageNoArenaEntry> entry;
for (::google::protobuf::Map< ::google::protobuf::int32, ::protobuf_unittest_no_arena::ForeignMessage >::const_iterator
it = this->map_int32_foreign_message_no_arena().begin();
it != this->map_int32_foreign_message_no_arena().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(map_int32_foreign_message_no_arena_.NewEntryWrapper(it->first, it->second));
total_size += ::google::protobuf::internal::WireFormatLite::
MessageSizeNoVirtual(*entry);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = total_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void TestArenaMap::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:protobuf_unittest.TestArenaMap)
if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
const TestArenaMap* source =
::google::protobuf::internal::DynamicCastToGenerated<const TestArenaMap>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:protobuf_unittest.TestArenaMap)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:protobuf_unittest.TestArenaMap)
MergeFrom(*source);
}
}
void TestArenaMap::MergeFrom(const TestArenaMap& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:protobuf_unittest.TestArenaMap)
if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
map_int32_int32_.MergeFrom(from.map_int32_int32_);
map_int64_int64_.MergeFrom(from.map_int64_int64_);
map_uint32_uint32_.MergeFrom(from.map_uint32_uint32_);
map_uint64_uint64_.MergeFrom(from.map_uint64_uint64_);
map_sint32_sint32_.MergeFrom(from.map_sint32_sint32_);
map_sint64_sint64_.MergeFrom(from.map_sint64_sint64_);
map_fixed32_fixed32_.MergeFrom(from.map_fixed32_fixed32_);
map_fixed64_fixed64_.MergeFrom(from.map_fixed64_fixed64_);
map_sfixed32_sfixed32_.MergeFrom(from.map_sfixed32_sfixed32_);
map_sfixed64_sfixed64_.MergeFrom(from.map_sfixed64_sfixed64_);
map_int32_float_.MergeFrom(from.map_int32_float_);
map_int32_double_.MergeFrom(from.map_int32_double_);
map_bool_bool_.MergeFrom(from.map_bool_bool_);
map_string_string_.MergeFrom(from.map_string_string_);
map_int32_bytes_.MergeFrom(from.map_int32_bytes_);
map_int32_enum_.MergeFrom(from.map_int32_enum_);
map_int32_foreign_message_.MergeFrom(from.map_int32_foreign_message_);
map_int32_foreign_message_no_arena_.MergeFrom(from.map_int32_foreign_message_no_arena_);
}
void TestArenaMap::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:protobuf_unittest.TestArenaMap)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void TestArenaMap::CopyFrom(const TestArenaMap& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:protobuf_unittest.TestArenaMap)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool TestArenaMap::IsInitialized() const {
return true;
}
void TestArenaMap::Swap(TestArenaMap* other) {
if (other == this) return;
if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
InternalSwap(other);
} else {
TestArenaMap temp;
temp.MergeFrom(*this);
CopyFrom(*other);
other->CopyFrom(temp);
}
}
void TestArenaMap::UnsafeArenaSwap(TestArenaMap* other) {
if (other == this) return;
GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
InternalSwap(other);
}
void TestArenaMap::InternalSwap(TestArenaMap* other) {
map_int32_int32_.Swap(&other->map_int32_int32_);
map_int64_int64_.Swap(&other->map_int64_int64_);
map_uint32_uint32_.Swap(&other->map_uint32_uint32_);
map_uint64_uint64_.Swap(&other->map_uint64_uint64_);
map_sint32_sint32_.Swap(&other->map_sint32_sint32_);
map_sint64_sint64_.Swap(&other->map_sint64_sint64_);
map_fixed32_fixed32_.Swap(&other->map_fixed32_fixed32_);
map_fixed64_fixed64_.Swap(&other->map_fixed64_fixed64_);
map_sfixed32_sfixed32_.Swap(&other->map_sfixed32_sfixed32_);
map_sfixed64_sfixed64_.Swap(&other->map_sfixed64_sfixed64_);
map_int32_float_.Swap(&other->map_int32_float_);
map_int32_double_.Swap(&other->map_int32_double_);
map_bool_bool_.Swap(&other->map_bool_bool_);
map_string_string_.Swap(&other->map_string_string_);
map_int32_bytes_.Swap(&other->map_int32_bytes_);
map_int32_enum_.Swap(&other->map_int32_enum_);
map_int32_foreign_message_.Swap(&other->map_int32_foreign_message_);
map_int32_foreign_message_no_arena_.Swap(&other->map_int32_foreign_message_no_arena_);
_internal_metadata_.Swap(&other->_internal_metadata_);
std::swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata TestArenaMap::GetMetadata() const {
protobuf_AssignDescriptorsOnce();
::google::protobuf::Metadata metadata;
metadata.descriptor = TestArenaMap_descriptor_;
metadata.reflection = TestArenaMap_reflection_;
return metadata;
}
#if PROTOBUF_INLINE_NOT_IN_HEADERS
// TestArenaMap
// map<int32, int32> map_int32_int32 = 1;
int TestArenaMap::map_int32_int32_size() const {
return map_int32_int32_.size();
}
void TestArenaMap::clear_map_int32_int32() {
map_int32_int32_.Clear();
}
const ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::int32 >&
TestArenaMap::map_int32_int32() const {
// @@protoc_insertion_point(field_map:protobuf_unittest.TestArenaMap.map_int32_int32)
return map_int32_int32_.GetMap();
}
::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::int32 >*
TestArenaMap::mutable_map_int32_int32() {
// @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestArenaMap.map_int32_int32)
return map_int32_int32_.MutableMap();
}
// map<int64, int64> map_int64_int64 = 2;
int TestArenaMap::map_int64_int64_size() const {
return map_int64_int64_.size();
}
void TestArenaMap::clear_map_int64_int64() {
map_int64_int64_.Clear();
}
const ::google::protobuf::Map< ::google::protobuf::int64, ::google::protobuf::int64 >&
TestArenaMap::map_int64_int64() const {
// @@protoc_insertion_point(field_map:protobuf_unittest.TestArenaMap.map_int64_int64)
return map_int64_int64_.GetMap();
}
::google::protobuf::Map< ::google::protobuf::int64, ::google::protobuf::int64 >*
TestArenaMap::mutable_map_int64_int64() {
// @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestArenaMap.map_int64_int64)
return map_int64_int64_.MutableMap();
}
// map<uint32, uint32> map_uint32_uint32 = 3;
int TestArenaMap::map_uint32_uint32_size() const {
return map_uint32_uint32_.size();
}
void TestArenaMap::clear_map_uint32_uint32() {
map_uint32_uint32_.Clear();
}
const ::google::protobuf::Map< ::google::protobuf::uint32, ::google::protobuf::uint32 >&
TestArenaMap::map_uint32_uint32() const {
// @@protoc_insertion_point(field_map:protobuf_unittest.TestArenaMap.map_uint32_uint32)
return map_uint32_uint32_.GetMap();
}
::google::protobuf::Map< ::google::protobuf::uint32, ::google::protobuf::uint32 >*
TestArenaMap::mutable_map_uint32_uint32() {
// @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestArenaMap.map_uint32_uint32)
return map_uint32_uint32_.MutableMap();
}
// map<uint64, uint64> map_uint64_uint64 = 4;
int TestArenaMap::map_uint64_uint64_size() const {
return map_uint64_uint64_.size();
}
void TestArenaMap::clear_map_uint64_uint64() {
map_uint64_uint64_.Clear();
}
const ::google::protobuf::Map< ::google::protobuf::uint64, ::google::protobuf::uint64 >&
TestArenaMap::map_uint64_uint64() const {
// @@protoc_insertion_point(field_map:protobuf_unittest.TestArenaMap.map_uint64_uint64)
return map_uint64_uint64_.GetMap();
}
::google::protobuf::Map< ::google::protobuf::uint64, ::google::protobuf::uint64 >*
TestArenaMap::mutable_map_uint64_uint64() {
// @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestArenaMap.map_uint64_uint64)
return map_uint64_uint64_.MutableMap();
}
// map<sint32, sint32> map_sint32_sint32 = 5;
int TestArenaMap::map_sint32_sint32_size() const {
return map_sint32_sint32_.size();
}
void TestArenaMap::clear_map_sint32_sint32() {
map_sint32_sint32_.Clear();
}
const ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::int32 >&
TestArenaMap::map_sint32_sint32() const {
// @@protoc_insertion_point(field_map:protobuf_unittest.TestArenaMap.map_sint32_sint32)
return map_sint32_sint32_.GetMap();
}
::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::int32 >*
TestArenaMap::mutable_map_sint32_sint32() {
// @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestArenaMap.map_sint32_sint32)
return map_sint32_sint32_.MutableMap();
}
// map<sint64, sint64> map_sint64_sint64 = 6;
int TestArenaMap::map_sint64_sint64_size() const {
return map_sint64_sint64_.size();
}
void TestArenaMap::clear_map_sint64_sint64() {
map_sint64_sint64_.Clear();
}
const ::google::protobuf::Map< ::google::protobuf::int64, ::google::protobuf::int64 >&
TestArenaMap::map_sint64_sint64() const {
// @@protoc_insertion_point(field_map:protobuf_unittest.TestArenaMap.map_sint64_sint64)
return map_sint64_sint64_.GetMap();
}
::google::protobuf::Map< ::google::protobuf::int64, ::google::protobuf::int64 >*
TestArenaMap::mutable_map_sint64_sint64() {
// @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestArenaMap.map_sint64_sint64)
return map_sint64_sint64_.MutableMap();
}
// map<fixed32, fixed32> map_fixed32_fixed32 = 7;
int TestArenaMap::map_fixed32_fixed32_size() const {
return map_fixed32_fixed32_.size();
}
void TestArenaMap::clear_map_fixed32_fixed32() {
map_fixed32_fixed32_.Clear();
}
const ::google::protobuf::Map< ::google::protobuf::uint32, ::google::protobuf::uint32 >&
TestArenaMap::map_fixed32_fixed32() const {
// @@protoc_insertion_point(field_map:protobuf_unittest.TestArenaMap.map_fixed32_fixed32)
return map_fixed32_fixed32_.GetMap();
}
::google::protobuf::Map< ::google::protobuf::uint32, ::google::protobuf::uint32 >*
TestArenaMap::mutable_map_fixed32_fixed32() {
// @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestArenaMap.map_fixed32_fixed32)
return map_fixed32_fixed32_.MutableMap();
}
// map<fixed64, fixed64> map_fixed64_fixed64 = 8;
int TestArenaMap::map_fixed64_fixed64_size() const {
return map_fixed64_fixed64_.size();
}
void TestArenaMap::clear_map_fixed64_fixed64() {
map_fixed64_fixed64_.Clear();
}
const ::google::protobuf::Map< ::google::protobuf::uint64, ::google::protobuf::uint64 >&
TestArenaMap::map_fixed64_fixed64() const {
// @@protoc_insertion_point(field_map:protobuf_unittest.TestArenaMap.map_fixed64_fixed64)
return map_fixed64_fixed64_.GetMap();
}
::google::protobuf::Map< ::google::protobuf::uint64, ::google::protobuf::uint64 >*
TestArenaMap::mutable_map_fixed64_fixed64() {
// @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestArenaMap.map_fixed64_fixed64)
return map_fixed64_fixed64_.MutableMap();
}
// map<sfixed32, sfixed32> map_sfixed32_sfixed32 = 9;
int TestArenaMap::map_sfixed32_sfixed32_size() const {
return map_sfixed32_sfixed32_.size();
}
void TestArenaMap::clear_map_sfixed32_sfixed32() {
map_sfixed32_sfixed32_.Clear();
}
const ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::int32 >&
TestArenaMap::map_sfixed32_sfixed32() const {
// @@protoc_insertion_point(field_map:protobuf_unittest.TestArenaMap.map_sfixed32_sfixed32)
return map_sfixed32_sfixed32_.GetMap();
}
::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::int32 >*
TestArenaMap::mutable_map_sfixed32_sfixed32() {
// @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestArenaMap.map_sfixed32_sfixed32)
return map_sfixed32_sfixed32_.MutableMap();
}
// map<sfixed64, sfixed64> map_sfixed64_sfixed64 = 10;
int TestArenaMap::map_sfixed64_sfixed64_size() const {
return map_sfixed64_sfixed64_.size();
}
void TestArenaMap::clear_map_sfixed64_sfixed64() {
map_sfixed64_sfixed64_.Clear();
}
const ::google::protobuf::Map< ::google::protobuf::int64, ::google::protobuf::int64 >&
TestArenaMap::map_sfixed64_sfixed64() const {
// @@protoc_insertion_point(field_map:protobuf_unittest.TestArenaMap.map_sfixed64_sfixed64)
return map_sfixed64_sfixed64_.GetMap();
}
::google::protobuf::Map< ::google::protobuf::int64, ::google::protobuf::int64 >*
TestArenaMap::mutable_map_sfixed64_sfixed64() {
// @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestArenaMap.map_sfixed64_sfixed64)
return map_sfixed64_sfixed64_.MutableMap();
}
// map<int32, float> map_int32_float = 11;
int TestArenaMap::map_int32_float_size() const {
return map_int32_float_.size();
}
void TestArenaMap::clear_map_int32_float() {
map_int32_float_.Clear();
}
const ::google::protobuf::Map< ::google::protobuf::int32, float >&
TestArenaMap::map_int32_float() const {
// @@protoc_insertion_point(field_map:protobuf_unittest.TestArenaMap.map_int32_float)
return map_int32_float_.GetMap();
}
::google::protobuf::Map< ::google::protobuf::int32, float >*
TestArenaMap::mutable_map_int32_float() {
// @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestArenaMap.map_int32_float)
return map_int32_float_.MutableMap();
}
// map<int32, double> map_int32_double = 12;
int TestArenaMap::map_int32_double_size() const {
return map_int32_double_.size();
}
void TestArenaMap::clear_map_int32_double() {
map_int32_double_.Clear();
}
const ::google::protobuf::Map< ::google::protobuf::int32, double >&
TestArenaMap::map_int32_double() const {
// @@protoc_insertion_point(field_map:protobuf_unittest.TestArenaMap.map_int32_double)
return map_int32_double_.GetMap();
}
::google::protobuf::Map< ::google::protobuf::int32, double >*
TestArenaMap::mutable_map_int32_double() {
// @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestArenaMap.map_int32_double)
return map_int32_double_.MutableMap();
}
// map<bool, bool> map_bool_bool = 13;
int TestArenaMap::map_bool_bool_size() const {
return map_bool_bool_.size();
}
void TestArenaMap::clear_map_bool_bool() {
map_bool_bool_.Clear();
}
const ::google::protobuf::Map< bool, bool >&
TestArenaMap::map_bool_bool() const {
// @@protoc_insertion_point(field_map:protobuf_unittest.TestArenaMap.map_bool_bool)
return map_bool_bool_.GetMap();
}
::google::protobuf::Map< bool, bool >*
TestArenaMap::mutable_map_bool_bool() {
// @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestArenaMap.map_bool_bool)
return map_bool_bool_.MutableMap();
}
// map<string, string> map_string_string = 14;
int TestArenaMap::map_string_string_size() const {
return map_string_string_.size();
}
void TestArenaMap::clear_map_string_string() {
map_string_string_.Clear();
}
const ::google::protobuf::Map< ::std::string, ::std::string >&
TestArenaMap::map_string_string() const {
// @@protoc_insertion_point(field_map:protobuf_unittest.TestArenaMap.map_string_string)
return map_string_string_.GetMap();
}
::google::protobuf::Map< ::std::string, ::std::string >*
TestArenaMap::mutable_map_string_string() {
// @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestArenaMap.map_string_string)
return map_string_string_.MutableMap();
}
// map<int32, bytes> map_int32_bytes = 15;
int TestArenaMap::map_int32_bytes_size() const {
return map_int32_bytes_.size();
}
void TestArenaMap::clear_map_int32_bytes() {
map_int32_bytes_.Clear();
}
const ::google::protobuf::Map< ::google::protobuf::int32, ::std::string >&
TestArenaMap::map_int32_bytes() const {
// @@protoc_insertion_point(field_map:protobuf_unittest.TestArenaMap.map_int32_bytes)
return map_int32_bytes_.GetMap();
}
::google::protobuf::Map< ::google::protobuf::int32, ::std::string >*
TestArenaMap::mutable_map_int32_bytes() {
// @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestArenaMap.map_int32_bytes)
return map_int32_bytes_.MutableMap();
}
// map<int32, .protobuf_unittest.MapEnum> map_int32_enum = 16;
int TestArenaMap::map_int32_enum_size() const {
return map_int32_enum_.size();
}
void TestArenaMap::clear_map_int32_enum() {
map_int32_enum_.Clear();
}
const ::google::protobuf::Map< ::google::protobuf::int32, ::protobuf_unittest::MapEnum >&
TestArenaMap::map_int32_enum() const {
// @@protoc_insertion_point(field_map:protobuf_unittest.TestArenaMap.map_int32_enum)
return map_int32_enum_.GetMap();
}
::google::protobuf::Map< ::google::protobuf::int32, ::protobuf_unittest::MapEnum >*
TestArenaMap::mutable_map_int32_enum() {
// @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestArenaMap.map_int32_enum)
return map_int32_enum_.MutableMap();
}
// map<int32, .protobuf_unittest.ForeignMessage> map_int32_foreign_message = 17;
int TestArenaMap::map_int32_foreign_message_size() const {
return map_int32_foreign_message_.size();
}
void TestArenaMap::clear_map_int32_foreign_message() {
map_int32_foreign_message_.Clear();
}
const ::google::protobuf::Map< ::google::protobuf::int32, ::protobuf_unittest::ForeignMessage >&
TestArenaMap::map_int32_foreign_message() const {
// @@protoc_insertion_point(field_map:protobuf_unittest.TestArenaMap.map_int32_foreign_message)
return map_int32_foreign_message_.GetMap();
}
::google::protobuf::Map< ::google::protobuf::int32, ::protobuf_unittest::ForeignMessage >*
TestArenaMap::mutable_map_int32_foreign_message() {
// @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestArenaMap.map_int32_foreign_message)
return map_int32_foreign_message_.MutableMap();
}
// map<int32, .protobuf_unittest_no_arena.ForeignMessage> map_int32_foreign_message_no_arena = 18;
int TestArenaMap::map_int32_foreign_message_no_arena_size() const {
return map_int32_foreign_message_no_arena_.size();
}
void TestArenaMap::clear_map_int32_foreign_message_no_arena() {
map_int32_foreign_message_no_arena_.Clear();
}
const ::google::protobuf::Map< ::google::protobuf::int32, ::protobuf_unittest_no_arena::ForeignMessage >&
TestArenaMap::map_int32_foreign_message_no_arena() const {
// @@protoc_insertion_point(field_map:protobuf_unittest.TestArenaMap.map_int32_foreign_message_no_arena)
return map_int32_foreign_message_no_arena_.GetMap();
}
::google::protobuf::Map< ::google::protobuf::int32, ::protobuf_unittest_no_arena::ForeignMessage >*
TestArenaMap::mutable_map_int32_foreign_message_no_arena() {
// @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestArenaMap.map_int32_foreign_message_no_arena)
return map_int32_foreign_message_no_arena_.MutableMap();
}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
const ::google::protobuf::EnumDescriptor* MessageContainingEnumCalledType_Type_descriptor() {
protobuf_AssignDescriptorsOnce();
return MessageContainingEnumCalledType_Type_descriptor_;
}
bool MessageContainingEnumCalledType_Type_IsValid(int value) {
switch(value) {
case 0:
return true;
default:
return false;
}
}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const MessageContainingEnumCalledType_Type MessageContainingEnumCalledType::TYPE_FOO;
const MessageContainingEnumCalledType_Type MessageContainingEnumCalledType::Type_MIN;
const MessageContainingEnumCalledType_Type MessageContainingEnumCalledType::Type_MAX;
const int MessageContainingEnumCalledType::Type_ARRAYSIZE;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int MessageContainingEnumCalledType::kTypeFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
MessageContainingEnumCalledType::MessageContainingEnumCalledType()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
SharedCtor();
// @@protoc_insertion_point(constructor:protobuf_unittest.MessageContainingEnumCalledType)
}
MessageContainingEnumCalledType::MessageContainingEnumCalledType(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena),
type_(arena) {
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:protobuf_unittest.MessageContainingEnumCalledType)
}
void MessageContainingEnumCalledType::InitAsDefaultInstance() {
_is_default_instance_ = true;
}
MessageContainingEnumCalledType::MessageContainingEnumCalledType(const MessageContainingEnumCalledType& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
MergeFrom(from);
// @@protoc_insertion_point(copy_constructor:protobuf_unittest.MessageContainingEnumCalledType)
}
void MessageContainingEnumCalledType::SharedCtor() {
_is_default_instance_ = false;
_cached_size_ = 0;
type_.SetAssignDescriptorCallback(
protobuf_AssignDescriptorsOnce);
type_.SetEntryDescriptor(
&::protobuf_unittest::MessageContainingEnumCalledType_TypeEntry_descriptor_);
}
MessageContainingEnumCalledType::~MessageContainingEnumCalledType() {
// @@protoc_insertion_point(destructor:protobuf_unittest.MessageContainingEnumCalledType)
SharedDtor();
}
void MessageContainingEnumCalledType::SharedDtor() {
if (GetArenaNoVirtual() != NULL) {
return;
}
if (this != default_instance_) {
}
}
void MessageContainingEnumCalledType::ArenaDtor(void* object) {
MessageContainingEnumCalledType* _this = reinterpret_cast< MessageContainingEnumCalledType* >(object);
(void)_this;
}
void MessageContainingEnumCalledType::RegisterArenaDtor(::google::protobuf::Arena* arena) {
}
void MessageContainingEnumCalledType::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* MessageContainingEnumCalledType::descriptor() {
protobuf_AssignDescriptorsOnce();
return MessageContainingEnumCalledType_descriptor_;
}
const MessageContainingEnumCalledType& MessageContainingEnumCalledType::default_instance() {
if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2fmap_5funittest_2eproto();
return *default_instance_;
}
MessageContainingEnumCalledType* MessageContainingEnumCalledType::default_instance_ = NULL;
MessageContainingEnumCalledType* MessageContainingEnumCalledType::New(::google::protobuf::Arena* arena) const {
return ::google::protobuf::Arena::CreateMessage<MessageContainingEnumCalledType>(arena);
}
void MessageContainingEnumCalledType::Clear() {
// @@protoc_insertion_point(message_clear_start:protobuf_unittest.MessageContainingEnumCalledType)
type_.Clear();
}
bool MessageContainingEnumCalledType::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:protobuf_unittest.MessageContainingEnumCalledType)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// map<string, .protobuf_unittest.MessageContainingEnumCalledType> type = 1;
case 1: {
if (tag == 10) {
DO_(input->IncrementRecursionDepth());
parse_loop_type:
::google::protobuf::scoped_ptr<MessageContainingEnumCalledType_TypeEntry> entry(type_.NewEntry());
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, entry.get()));
(*mutable_type())[entry->key()].Swap(entry->mutable_value());
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
entry->key().data(), entry->key().length(),
::google::protobuf::internal::WireFormatLite::PARSE,
"protobuf_unittest.MessageContainingEnumCalledType.TypeEntry.key"));
if (entry->GetArena() != NULL) entry.release();
} else {
goto handle_unusual;
}
if (input->ExpectTag(10)) goto parse_loop_type;
input->UnsafeDecrementRecursionDepth();
if (input->ExpectAtEnd()) goto success;
break;
}
default: {
handle_unusual:
if (tag == 0 ||
::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
goto success;
}
DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:protobuf_unittest.MessageContainingEnumCalledType)
return true;
failure:
// @@protoc_insertion_point(parse_failure:protobuf_unittest.MessageContainingEnumCalledType)
return false;
#undef DO_
}
void MessageContainingEnumCalledType::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:protobuf_unittest.MessageContainingEnumCalledType)
// map<string, .protobuf_unittest.MessageContainingEnumCalledType> type = 1;
{
::google::protobuf::scoped_ptr<MessageContainingEnumCalledType_TypeEntry> entry;
for (::google::protobuf::Map< ::std::string, ::protobuf_unittest::MessageContainingEnumCalledType >::const_iterator
it = this->type().begin();
it != this->type().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(type_.NewEntryWrapper(it->first, it->second));
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
1, *entry, output);
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
it->first.data(), it->first.length(),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"protobuf_unittest.MessageContainingEnumCalledType.TypeEntry.key");
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// @@protoc_insertion_point(serialize_end:protobuf_unittest.MessageContainingEnumCalledType)
}
::google::protobuf::uint8* MessageContainingEnumCalledType::SerializeWithCachedSizesToArray(
::google::protobuf::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:protobuf_unittest.MessageContainingEnumCalledType)
// map<string, .protobuf_unittest.MessageContainingEnumCalledType> type = 1;
{
::google::protobuf::scoped_ptr<MessageContainingEnumCalledType_TypeEntry> entry;
for (::google::protobuf::Map< ::std::string, ::protobuf_unittest::MessageContainingEnumCalledType >::const_iterator
it = this->type().begin();
it != this->type().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(type_.NewEntryWrapper(it->first, it->second));
target = ::google::protobuf::internal::WireFormatLite::
WriteMessageNoVirtualToArray(
1, *entry, target);
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
it->first.data(), it->first.length(),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"protobuf_unittest.MessageContainingEnumCalledType.TypeEntry.key");
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// @@protoc_insertion_point(serialize_to_array_end:protobuf_unittest.MessageContainingEnumCalledType)
return target;
}
int MessageContainingEnumCalledType::ByteSize() const {
// @@protoc_insertion_point(message_byte_size_start:protobuf_unittest.MessageContainingEnumCalledType)
int total_size = 0;
// map<string, .protobuf_unittest.MessageContainingEnumCalledType> type = 1;
total_size += 1 * this->type_size();
{
::google::protobuf::scoped_ptr<MessageContainingEnumCalledType_TypeEntry> entry;
for (::google::protobuf::Map< ::std::string, ::protobuf_unittest::MessageContainingEnumCalledType >::const_iterator
it = this->type().begin();
it != this->type().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(type_.NewEntryWrapper(it->first, it->second));
total_size += ::google::protobuf::internal::WireFormatLite::
MessageSizeNoVirtual(*entry);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = total_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void MessageContainingEnumCalledType::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:protobuf_unittest.MessageContainingEnumCalledType)
if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
const MessageContainingEnumCalledType* source =
::google::protobuf::internal::DynamicCastToGenerated<const MessageContainingEnumCalledType>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:protobuf_unittest.MessageContainingEnumCalledType)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:protobuf_unittest.MessageContainingEnumCalledType)
MergeFrom(*source);
}
}
void MessageContainingEnumCalledType::MergeFrom(const MessageContainingEnumCalledType& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:protobuf_unittest.MessageContainingEnumCalledType)
if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
type_.MergeFrom(from.type_);
}
void MessageContainingEnumCalledType::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:protobuf_unittest.MessageContainingEnumCalledType)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void MessageContainingEnumCalledType::CopyFrom(const MessageContainingEnumCalledType& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:protobuf_unittest.MessageContainingEnumCalledType)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool MessageContainingEnumCalledType::IsInitialized() const {
return true;
}
void MessageContainingEnumCalledType::Swap(MessageContainingEnumCalledType* other) {
if (other == this) return;
if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
InternalSwap(other);
} else {
MessageContainingEnumCalledType temp;
temp.MergeFrom(*this);
CopyFrom(*other);
other->CopyFrom(temp);
}
}
void MessageContainingEnumCalledType::UnsafeArenaSwap(MessageContainingEnumCalledType* other) {
if (other == this) return;
GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
InternalSwap(other);
}
void MessageContainingEnumCalledType::InternalSwap(MessageContainingEnumCalledType* other) {
type_.Swap(&other->type_);
_internal_metadata_.Swap(&other->_internal_metadata_);
std::swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata MessageContainingEnumCalledType::GetMetadata() const {
protobuf_AssignDescriptorsOnce();
::google::protobuf::Metadata metadata;
metadata.descriptor = MessageContainingEnumCalledType_descriptor_;
metadata.reflection = MessageContainingEnumCalledType_reflection_;
return metadata;
}
#if PROTOBUF_INLINE_NOT_IN_HEADERS
// MessageContainingEnumCalledType
// map<string, .protobuf_unittest.MessageContainingEnumCalledType> type = 1;
int MessageContainingEnumCalledType::type_size() const {
return type_.size();
}
void MessageContainingEnumCalledType::clear_type() {
type_.Clear();
}
const ::google::protobuf::Map< ::std::string, ::protobuf_unittest::MessageContainingEnumCalledType >&
MessageContainingEnumCalledType::type() const {
// @@protoc_insertion_point(field_map:protobuf_unittest.MessageContainingEnumCalledType.type)
return type_.GetMap();
}
::google::protobuf::Map< ::std::string, ::protobuf_unittest::MessageContainingEnumCalledType >*
MessageContainingEnumCalledType::mutable_type() {
// @@protoc_insertion_point(field_mutable_map:protobuf_unittest.MessageContainingEnumCalledType.type)
return type_.MutableMap();
}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int MessageContainingMapCalledEntry::kEntryFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
MessageContainingMapCalledEntry::MessageContainingMapCalledEntry()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
SharedCtor();
// @@protoc_insertion_point(constructor:protobuf_unittest.MessageContainingMapCalledEntry)
}
MessageContainingMapCalledEntry::MessageContainingMapCalledEntry(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena),
entry_(arena) {
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:protobuf_unittest.MessageContainingMapCalledEntry)
}
void MessageContainingMapCalledEntry::InitAsDefaultInstance() {
_is_default_instance_ = true;
}
MessageContainingMapCalledEntry::MessageContainingMapCalledEntry(const MessageContainingMapCalledEntry& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
MergeFrom(from);
// @@protoc_insertion_point(copy_constructor:protobuf_unittest.MessageContainingMapCalledEntry)
}
void MessageContainingMapCalledEntry::SharedCtor() {
_is_default_instance_ = false;
_cached_size_ = 0;
entry_.SetAssignDescriptorCallback(
protobuf_AssignDescriptorsOnce);
entry_.SetEntryDescriptor(
&::protobuf_unittest::MessageContainingMapCalledEntry_EntryEntry_descriptor_);
}
MessageContainingMapCalledEntry::~MessageContainingMapCalledEntry() {
// @@protoc_insertion_point(destructor:protobuf_unittest.MessageContainingMapCalledEntry)
SharedDtor();
}
void MessageContainingMapCalledEntry::SharedDtor() {
if (GetArenaNoVirtual() != NULL) {
return;
}
if (this != default_instance_) {
}
}
void MessageContainingMapCalledEntry::ArenaDtor(void* object) {
MessageContainingMapCalledEntry* _this = reinterpret_cast< MessageContainingMapCalledEntry* >(object);
(void)_this;
}
void MessageContainingMapCalledEntry::RegisterArenaDtor(::google::protobuf::Arena* arena) {
}
void MessageContainingMapCalledEntry::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* MessageContainingMapCalledEntry::descriptor() {
protobuf_AssignDescriptorsOnce();
return MessageContainingMapCalledEntry_descriptor_;
}
const MessageContainingMapCalledEntry& MessageContainingMapCalledEntry::default_instance() {
if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2fmap_5funittest_2eproto();
return *default_instance_;
}
MessageContainingMapCalledEntry* MessageContainingMapCalledEntry::default_instance_ = NULL;
MessageContainingMapCalledEntry* MessageContainingMapCalledEntry::New(::google::protobuf::Arena* arena) const {
return ::google::protobuf::Arena::CreateMessage<MessageContainingMapCalledEntry>(arena);
}
void MessageContainingMapCalledEntry::Clear() {
// @@protoc_insertion_point(message_clear_start:protobuf_unittest.MessageContainingMapCalledEntry)
entry_.Clear();
}
bool MessageContainingMapCalledEntry::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:protobuf_unittest.MessageContainingMapCalledEntry)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// map<int32, int32> entry = 1;
case 1: {
if (tag == 10) {
DO_(input->IncrementRecursionDepth());
parse_loop_entry:
::google::protobuf::scoped_ptr<MessageContainingMapCalledEntry_EntryEntry> entry(entry_.NewEntry());
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, entry.get()));
(*mutable_entry())[entry->key()] = *entry->mutable_value();
if (entry->GetArena() != NULL) entry.release();
} else {
goto handle_unusual;
}
if (input->ExpectTag(10)) goto parse_loop_entry;
input->UnsafeDecrementRecursionDepth();
if (input->ExpectAtEnd()) goto success;
break;
}
default: {
handle_unusual:
if (tag == 0 ||
::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
goto success;
}
DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:protobuf_unittest.MessageContainingMapCalledEntry)
return true;
failure:
// @@protoc_insertion_point(parse_failure:protobuf_unittest.MessageContainingMapCalledEntry)
return false;
#undef DO_
}
void MessageContainingMapCalledEntry::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:protobuf_unittest.MessageContainingMapCalledEntry)
// map<int32, int32> entry = 1;
{
::google::protobuf::scoped_ptr<MessageContainingMapCalledEntry_EntryEntry> entry;
for (::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::int32 >::const_iterator
it = this->entry().begin();
it != this->entry().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(entry_.NewEntryWrapper(it->first, it->second));
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
1, *entry, output);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// @@protoc_insertion_point(serialize_end:protobuf_unittest.MessageContainingMapCalledEntry)
}
::google::protobuf::uint8* MessageContainingMapCalledEntry::SerializeWithCachedSizesToArray(
::google::protobuf::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:protobuf_unittest.MessageContainingMapCalledEntry)
// map<int32, int32> entry = 1;
{
::google::protobuf::scoped_ptr<MessageContainingMapCalledEntry_EntryEntry> entry;
for (::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::int32 >::const_iterator
it = this->entry().begin();
it != this->entry().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(entry_.NewEntryWrapper(it->first, it->second));
target = ::google::protobuf::internal::WireFormatLite::
WriteMessageNoVirtualToArray(
1, *entry, target);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// @@protoc_insertion_point(serialize_to_array_end:protobuf_unittest.MessageContainingMapCalledEntry)
return target;
}
int MessageContainingMapCalledEntry::ByteSize() const {
// @@protoc_insertion_point(message_byte_size_start:protobuf_unittest.MessageContainingMapCalledEntry)
int total_size = 0;
// map<int32, int32> entry = 1;
total_size += 1 * this->entry_size();
{
::google::protobuf::scoped_ptr<MessageContainingMapCalledEntry_EntryEntry> entry;
for (::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::int32 >::const_iterator
it = this->entry().begin();
it != this->entry().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(entry_.NewEntryWrapper(it->first, it->second));
total_size += ::google::protobuf::internal::WireFormatLite::
MessageSizeNoVirtual(*entry);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = total_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void MessageContainingMapCalledEntry::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:protobuf_unittest.MessageContainingMapCalledEntry)
if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
const MessageContainingMapCalledEntry* source =
::google::protobuf::internal::DynamicCastToGenerated<const MessageContainingMapCalledEntry>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:protobuf_unittest.MessageContainingMapCalledEntry)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:protobuf_unittest.MessageContainingMapCalledEntry)
MergeFrom(*source);
}
}
void MessageContainingMapCalledEntry::MergeFrom(const MessageContainingMapCalledEntry& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:protobuf_unittest.MessageContainingMapCalledEntry)
if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
entry_.MergeFrom(from.entry_);
}
void MessageContainingMapCalledEntry::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:protobuf_unittest.MessageContainingMapCalledEntry)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void MessageContainingMapCalledEntry::CopyFrom(const MessageContainingMapCalledEntry& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:protobuf_unittest.MessageContainingMapCalledEntry)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool MessageContainingMapCalledEntry::IsInitialized() const {
return true;
}
void MessageContainingMapCalledEntry::Swap(MessageContainingMapCalledEntry* other) {
if (other == this) return;
if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
InternalSwap(other);
} else {
MessageContainingMapCalledEntry temp;
temp.MergeFrom(*this);
CopyFrom(*other);
other->CopyFrom(temp);
}
}
void MessageContainingMapCalledEntry::UnsafeArenaSwap(MessageContainingMapCalledEntry* other) {
if (other == this) return;
GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
InternalSwap(other);
}
void MessageContainingMapCalledEntry::InternalSwap(MessageContainingMapCalledEntry* other) {
entry_.Swap(&other->entry_);
_internal_metadata_.Swap(&other->_internal_metadata_);
std::swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata MessageContainingMapCalledEntry::GetMetadata() const {
protobuf_AssignDescriptorsOnce();
::google::protobuf::Metadata metadata;
metadata.descriptor = MessageContainingMapCalledEntry_descriptor_;
metadata.reflection = MessageContainingMapCalledEntry_reflection_;
return metadata;
}
#if PROTOBUF_INLINE_NOT_IN_HEADERS
// MessageContainingMapCalledEntry
// map<int32, int32> entry = 1;
int MessageContainingMapCalledEntry::entry_size() const {
return entry_.size();
}
void MessageContainingMapCalledEntry::clear_entry() {
entry_.Clear();
}
const ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::int32 >&
MessageContainingMapCalledEntry::entry() const {
// @@protoc_insertion_point(field_map:protobuf_unittest.MessageContainingMapCalledEntry.entry)
return entry_.GetMap();
}
::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::int32 >*
MessageContainingMapCalledEntry::mutable_entry() {
// @@protoc_insertion_point(field_mutable_map:protobuf_unittest.MessageContainingMapCalledEntry.entry)
return entry_.MutableMap();
}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int TestRecursiveMapMessage::kAFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
TestRecursiveMapMessage::TestRecursiveMapMessage()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
SharedCtor();
// @@protoc_insertion_point(constructor:protobuf_unittest.TestRecursiveMapMessage)
}
TestRecursiveMapMessage::TestRecursiveMapMessage(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena),
a_(arena) {
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:protobuf_unittest.TestRecursiveMapMessage)
}
void TestRecursiveMapMessage::InitAsDefaultInstance() {
_is_default_instance_ = true;
}
TestRecursiveMapMessage::TestRecursiveMapMessage(const TestRecursiveMapMessage& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
MergeFrom(from);
// @@protoc_insertion_point(copy_constructor:protobuf_unittest.TestRecursiveMapMessage)
}
void TestRecursiveMapMessage::SharedCtor() {
_is_default_instance_ = false;
_cached_size_ = 0;
a_.SetAssignDescriptorCallback(
protobuf_AssignDescriptorsOnce);
a_.SetEntryDescriptor(
&::protobuf_unittest::TestRecursiveMapMessage_AEntry_descriptor_);
}
TestRecursiveMapMessage::~TestRecursiveMapMessage() {
// @@protoc_insertion_point(destructor:protobuf_unittest.TestRecursiveMapMessage)
SharedDtor();
}
void TestRecursiveMapMessage::SharedDtor() {
if (GetArenaNoVirtual() != NULL) {
return;
}
if (this != default_instance_) {
}
}
void TestRecursiveMapMessage::ArenaDtor(void* object) {
TestRecursiveMapMessage* _this = reinterpret_cast< TestRecursiveMapMessage* >(object);
(void)_this;
}
void TestRecursiveMapMessage::RegisterArenaDtor(::google::protobuf::Arena* arena) {
}
void TestRecursiveMapMessage::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* TestRecursiveMapMessage::descriptor() {
protobuf_AssignDescriptorsOnce();
return TestRecursiveMapMessage_descriptor_;
}
const TestRecursiveMapMessage& TestRecursiveMapMessage::default_instance() {
if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2fmap_5funittest_2eproto();
return *default_instance_;
}
TestRecursiveMapMessage* TestRecursiveMapMessage::default_instance_ = NULL;
TestRecursiveMapMessage* TestRecursiveMapMessage::New(::google::protobuf::Arena* arena) const {
return ::google::protobuf::Arena::CreateMessage<TestRecursiveMapMessage>(arena);
}
void TestRecursiveMapMessage::Clear() {
// @@protoc_insertion_point(message_clear_start:protobuf_unittest.TestRecursiveMapMessage)
a_.Clear();
}
bool TestRecursiveMapMessage::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:protobuf_unittest.TestRecursiveMapMessage)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// map<string, .protobuf_unittest.TestRecursiveMapMessage> a = 1;
case 1: {
if (tag == 10) {
DO_(input->IncrementRecursionDepth());
parse_loop_a:
::google::protobuf::scoped_ptr<TestRecursiveMapMessage_AEntry> entry(a_.NewEntry());
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, entry.get()));
(*mutable_a())[entry->key()].Swap(entry->mutable_value());
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
entry->key().data(), entry->key().length(),
::google::protobuf::internal::WireFormatLite::PARSE,
"protobuf_unittest.TestRecursiveMapMessage.AEntry.key"));
if (entry->GetArena() != NULL) entry.release();
} else {
goto handle_unusual;
}
if (input->ExpectTag(10)) goto parse_loop_a;
input->UnsafeDecrementRecursionDepth();
if (input->ExpectAtEnd()) goto success;
break;
}
default: {
handle_unusual:
if (tag == 0 ||
::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
goto success;
}
DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:protobuf_unittest.TestRecursiveMapMessage)
return true;
failure:
// @@protoc_insertion_point(parse_failure:protobuf_unittest.TestRecursiveMapMessage)
return false;
#undef DO_
}
void TestRecursiveMapMessage::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:protobuf_unittest.TestRecursiveMapMessage)
// map<string, .protobuf_unittest.TestRecursiveMapMessage> a = 1;
{
::google::protobuf::scoped_ptr<TestRecursiveMapMessage_AEntry> entry;
for (::google::protobuf::Map< ::std::string, ::protobuf_unittest::TestRecursiveMapMessage >::const_iterator
it = this->a().begin();
it != this->a().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(a_.NewEntryWrapper(it->first, it->second));
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
1, *entry, output);
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
it->first.data(), it->first.length(),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"protobuf_unittest.TestRecursiveMapMessage.AEntry.key");
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// @@protoc_insertion_point(serialize_end:protobuf_unittest.TestRecursiveMapMessage)
}
::google::protobuf::uint8* TestRecursiveMapMessage::SerializeWithCachedSizesToArray(
::google::protobuf::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:protobuf_unittest.TestRecursiveMapMessage)
// map<string, .protobuf_unittest.TestRecursiveMapMessage> a = 1;
{
::google::protobuf::scoped_ptr<TestRecursiveMapMessage_AEntry> entry;
for (::google::protobuf::Map< ::std::string, ::protobuf_unittest::TestRecursiveMapMessage >::const_iterator
it = this->a().begin();
it != this->a().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(a_.NewEntryWrapper(it->first, it->second));
target = ::google::protobuf::internal::WireFormatLite::
WriteMessageNoVirtualToArray(
1, *entry, target);
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
it->first.data(), it->first.length(),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"protobuf_unittest.TestRecursiveMapMessage.AEntry.key");
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// @@protoc_insertion_point(serialize_to_array_end:protobuf_unittest.TestRecursiveMapMessage)
return target;
}
int TestRecursiveMapMessage::ByteSize() const {
// @@protoc_insertion_point(message_byte_size_start:protobuf_unittest.TestRecursiveMapMessage)
int total_size = 0;
// map<string, .protobuf_unittest.TestRecursiveMapMessage> a = 1;
total_size += 1 * this->a_size();
{
::google::protobuf::scoped_ptr<TestRecursiveMapMessage_AEntry> entry;
for (::google::protobuf::Map< ::std::string, ::protobuf_unittest::TestRecursiveMapMessage >::const_iterator
it = this->a().begin();
it != this->a().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(a_.NewEntryWrapper(it->first, it->second));
total_size += ::google::protobuf::internal::WireFormatLite::
MessageSizeNoVirtual(*entry);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = total_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void TestRecursiveMapMessage::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:protobuf_unittest.TestRecursiveMapMessage)
if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
const TestRecursiveMapMessage* source =
::google::protobuf::internal::DynamicCastToGenerated<const TestRecursiveMapMessage>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:protobuf_unittest.TestRecursiveMapMessage)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:protobuf_unittest.TestRecursiveMapMessage)
MergeFrom(*source);
}
}
void TestRecursiveMapMessage::MergeFrom(const TestRecursiveMapMessage& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:protobuf_unittest.TestRecursiveMapMessage)
if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
a_.MergeFrom(from.a_);
}
void TestRecursiveMapMessage::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:protobuf_unittest.TestRecursiveMapMessage)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void TestRecursiveMapMessage::CopyFrom(const TestRecursiveMapMessage& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:protobuf_unittest.TestRecursiveMapMessage)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool TestRecursiveMapMessage::IsInitialized() const {
return true;
}
void TestRecursiveMapMessage::Swap(TestRecursiveMapMessage* other) {
if (other == this) return;
if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
InternalSwap(other);
} else {
TestRecursiveMapMessage temp;
temp.MergeFrom(*this);
CopyFrom(*other);
other->CopyFrom(temp);
}
}
void TestRecursiveMapMessage::UnsafeArenaSwap(TestRecursiveMapMessage* other) {
if (other == this) return;
GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
InternalSwap(other);
}
void TestRecursiveMapMessage::InternalSwap(TestRecursiveMapMessage* other) {
a_.Swap(&other->a_);
_internal_metadata_.Swap(&other->_internal_metadata_);
std::swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata TestRecursiveMapMessage::GetMetadata() const {
protobuf_AssignDescriptorsOnce();
::google::protobuf::Metadata metadata;
metadata.descriptor = TestRecursiveMapMessage_descriptor_;
metadata.reflection = TestRecursiveMapMessage_reflection_;
return metadata;
}
#if PROTOBUF_INLINE_NOT_IN_HEADERS
// TestRecursiveMapMessage
// map<string, .protobuf_unittest.TestRecursiveMapMessage> a = 1;
int TestRecursiveMapMessage::a_size() const {
return a_.size();
}
void TestRecursiveMapMessage::clear_a() {
a_.Clear();
}
const ::google::protobuf::Map< ::std::string, ::protobuf_unittest::TestRecursiveMapMessage >&
TestRecursiveMapMessage::a() const {
// @@protoc_insertion_point(field_map:protobuf_unittest.TestRecursiveMapMessage.a)
return a_.GetMap();
}
::google::protobuf::Map< ::std::string, ::protobuf_unittest::TestRecursiveMapMessage >*
TestRecursiveMapMessage::mutable_a() {
// @@protoc_insertion_point(field_mutable_map:protobuf_unittest.TestRecursiveMapMessage.a)
return a_.MutableMap();
}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// @@protoc_insertion_point(namespace_scope)
} // namespace protobuf_unittest
// @@protoc_insertion_point(global_scope)
|
// Copyright (c) 2016-2017 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/json/
#ifndef TAOCPP_JSON_INCLUDE_INTERNAL_STRING_STATE_HPP
#define TAOCPP_JSON_INCLUDE_INTERNAL_STRING_STATE_HPP
#include <string>
#include <utility>
namespace tao
{
namespace json
{
namespace internal
{
struct string_state
{
string_state() = default;
string_state( const string_state& ) = delete;
void operator=( const string_state& ) = delete;
template< typename Consumer >
void success( Consumer& consumer )
{
consumer.string( std::move( unescaped ) );
}
std::string unescaped;
};
} // namespace internal
} // namespace json
} // namespace tao
#endif
|
/*
* Copyright 2017 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkTypes.h"
#include "Test.h"
#if SK_SUPPORT_GPU
#include "GrContext.h"
#include "GrColor.h"
#include "GrGeometryProcessor.h"
#include "GrGpuCommandBuffer.h"
#include "GrOpFlushState.h"
#include "GrRenderTargetContext.h"
#include "GrRenderTargetContextPriv.h"
#include "GrResourceProvider.h"
#include "SkMakeUnique.h"
#include "glsl/GrGLSLVertexGeoBuilder.h"
#include "glsl/GrGLSLFragmentShaderBuilder.h"
#include "glsl/GrGLSLGeometryProcessor.h"
#include "glsl/GrGLSLVarying.h"
/**
* This is a GPU-backend specific test for dynamic pipeline state. It draws boxes using dynamic
* scissor rectangles then reads back the result to verify a successful test.
*/
using ScissorState = GrPipeline::ScissorState;
static constexpr int kScreenSize = 6;
static constexpr int kNumMeshes = 4;
static constexpr int kScreenSplitX = kScreenSize/2;
static constexpr int kScreenSplitY = kScreenSize/2;
static const GrPipeline::DynamicState kDynamicStates[kNumMeshes] = {
{SkIRect::MakeLTRB(0, 0, kScreenSplitX, kScreenSplitY)},
{SkIRect::MakeLTRB(0, kScreenSplitY, kScreenSplitX, kScreenSize)},
{SkIRect::MakeLTRB(kScreenSplitX, 0, kScreenSize, kScreenSplitY)},
{SkIRect::MakeLTRB(kScreenSplitX, kScreenSplitY, kScreenSize, kScreenSize)},
};
static const GrColor kMeshColors[kNumMeshes] {
GrColorPackRGBA(255, 0, 0, 255),
GrColorPackRGBA(0, 255, 0, 255),
GrColorPackRGBA(0, 0, 255, 255),
GrColorPackRGBA(0, 0, 0, 255)
};
struct Vertex {
float fX;
float fY;
GrColor fColor;
};
class GrPipelineDynamicStateTestProcessor : public GrGeometryProcessor {
public:
GrPipelineDynamicStateTestProcessor()
: INHERITED(kGrPipelineDynamicStateTestProcessor_ClassID)
, fVertex(this->addVertexAttrib("vertex", kHalf2_GrVertexAttribType))
, fColor(this->addVertexAttrib("color", kUByte4_norm_GrVertexAttribType)) {}
const char* name() const override { return "GrPipelineDynamicStateTest Processor"; }
void getGLSLProcessorKey(const GrShaderCaps&, GrProcessorKeyBuilder*) const final {}
GrGLSLPrimitiveProcessor* createGLSLInstance(const GrShaderCaps&) const final;
protected:
const Attribute& fVertex;
const Attribute& fColor;
friend class GLSLPipelineDynamicStateTestProcessor;
typedef GrGeometryProcessor INHERITED;
};
class GLSLPipelineDynamicStateTestProcessor : public GrGLSLGeometryProcessor {
void setData(const GrGLSLProgramDataManager& pdman, const GrPrimitiveProcessor&,
FPCoordTransformIter&& transformIter) final {}
void onEmitCode(EmitArgs& args, GrGPArgs* gpArgs) final {
const GrPipelineDynamicStateTestProcessor& mp =
args.fGP.cast<GrPipelineDynamicStateTestProcessor>();
GrGLSLVaryingHandler* varyingHandler = args.fVaryingHandler;
varyingHandler->emitAttributes(mp);
varyingHandler->addPassThroughAttribute(&mp.fColor, args.fOutputColor);
GrGLSLVertexBuilder* v = args.fVertBuilder;
v->codeAppendf("float2 vertex = %s;", mp.fVertex.fName);
gpArgs->fPositionVar.set(kFloat2_GrSLType, "vertex");
GrGLSLFPFragmentBuilder* f = args.fFragBuilder;
f->codeAppendf("%s = half4(1);", args.fOutputCoverage);
}
};
GrGLSLPrimitiveProcessor*
GrPipelineDynamicStateTestProcessor::createGLSLInstance(const GrShaderCaps&) const {
return new GLSLPipelineDynamicStateTestProcessor;
}
class GrPipelineDynamicStateTestOp : public GrDrawOp {
public:
DEFINE_OP_CLASS_ID
GrPipelineDynamicStateTestOp(ScissorState scissorState, sk_sp<const GrBuffer> vbuff)
: INHERITED(ClassID())
, fScissorState(scissorState)
, fVertexBuffer(std::move(vbuff)) {
this->setBounds(SkRect::MakeIWH(kScreenSize, kScreenSize),
HasAABloat::kNo, IsZeroArea::kNo);
}
private:
const char* name() const override { return "GrPipelineDynamicStateTestOp"; }
FixedFunctionFlags fixedFunctionFlags() const override { return FixedFunctionFlags::kNone; }
RequiresDstTexture finalize(const GrCaps&, const GrAppliedClip*,
GrPixelConfigIsClamped) override {
return RequiresDstTexture::kNo;
}
bool onCombineIfPossible(GrOp* other, const GrCaps& caps) override { return false; }
void onPrepare(GrOpFlushState*) override {}
void onExecute(GrOpFlushState* state) override {
GrRenderTargetProxy* proxy = state->drawOpArgs().fProxy;
GrPipeline pipeline(proxy, fScissorState, SkBlendMode::kSrc);
SkSTArray<kNumMeshes, GrMesh> meshes;
for (int i = 0; i < kNumMeshes; ++i) {
GrMesh& mesh = meshes.emplace_back(GrPrimitiveType::kTriangleStrip);
mesh.setNonIndexedNonInstanced(4);
mesh.setVertexData(fVertexBuffer.get(), 4 * i);
}
state->rtCommandBuffer()->draw(pipeline, GrPipelineDynamicStateTestProcessor(),
meshes.begin(), kDynamicStates, 4,
SkRect::MakeIWH(kScreenSize, kScreenSize));
}
ScissorState fScissorState;
const sk_sp<const GrBuffer> fVertexBuffer;
typedef GrDrawOp INHERITED;
};
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(GrPipelineDynamicStateTest, reporter, ctxInfo) {
GrContext* const context = ctxInfo.grContext();
GrResourceProvider* rp = context->contextPriv().resourceProvider();
sk_sp<GrRenderTargetContext> rtc(
context->makeDeferredRenderTargetContext(SkBackingFit::kExact, kScreenSize, kScreenSize,
kRGBA_8888_GrPixelConfig, nullptr));
if (!rtc) {
ERRORF(reporter, "could not create render target context.");
return;
}
constexpr float d = (float) kScreenSize;
Vertex vdata[kNumMeshes * 4] = {
{0, 0, kMeshColors[0]},
{0, d, kMeshColors[0]},
{d, 0, kMeshColors[0]},
{d, d, kMeshColors[0]},
{0, 0, kMeshColors[1]},
{0, d, kMeshColors[1]},
{d, 0, kMeshColors[1]},
{d, d, kMeshColors[1]},
{0, 0, kMeshColors[2]},
{0, d, kMeshColors[2]},
{d, 0, kMeshColors[2]},
{d, d, kMeshColors[2]},
{0, 0, kMeshColors[3]},
{0, d, kMeshColors[3]},
{d, 0, kMeshColors[3]},
{d, d, kMeshColors[3]}
};
sk_sp<const GrBuffer> vbuff(rp->createBuffer(sizeof(vdata), kVertex_GrBufferType,
kDynamic_GrAccessPattern,
GrResourceProvider::kNoPendingIO_Flag |
GrResourceProvider::kRequireGpuMemory_Flag,
vdata));
if (!vbuff) {
ERRORF(reporter, "vbuff is null.");
return;
}
uint32_t resultPx[kScreenSize * kScreenSize];
for (ScissorState scissorState : {ScissorState::kEnabled, ScissorState::kDisabled}) {
rtc->clear(nullptr, 0xbaaaaaad, GrRenderTargetContext::CanClearFullscreen::kYes);
rtc->priv().testingOnly_addDrawOp(
skstd::make_unique<GrPipelineDynamicStateTestOp>(scissorState, vbuff));
rtc->readPixels(SkImageInfo::Make(kScreenSize, kScreenSize,
kRGBA_8888_SkColorType, kPremul_SkAlphaType),
resultPx, 4 * kScreenSize, 0, 0, 0);
for (int y = 0; y < kScreenSize; ++y) {
for (int x = 0; x < kScreenSize; ++x) {
int expectedColorIdx;
if (ScissorState::kEnabled == scissorState) {
expectedColorIdx = (x < kScreenSplitX ? 0 : 2) + (y < kScreenSplitY ? 0 : 1);
} else {
expectedColorIdx = kNumMeshes - 1;
}
uint32_t expected = kMeshColors[expectedColorIdx];
uint32_t actual = resultPx[y * kScreenSize + x];
if (expected != actual) {
ERRORF(reporter, "[scissor=%s] pixel (%i,%i): got 0x%x expected 0x%x",
ScissorState::kEnabled == scissorState ? "enabled" : "disabled", x, y,
actual, expected);
return;
}
}
}
}
}
#endif
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/login/screens/error_screen.h"
#include "chrome/browser/chromeos/login/screens/error_screen_actor.h"
#include "chrome/browser/chromeos/login/wizard_controller.h"
namespace chromeos {
ErrorScreen::ErrorScreen(ScreenObserver* screen_observer,
ErrorScreenActor* actor)
: WizardScreen(screen_observer),
actor_(actor),
parent_screen_(OobeDisplay::SCREEN_UNKNOWN) {
DCHECK(actor_);
}
ErrorScreen::~ErrorScreen() {
}
void ErrorScreen::PrepareToShow() {
}
void ErrorScreen::Show() {
DCHECK(actor_);
actor_->Show(parent_screen(), NULL);
}
void ErrorScreen::Hide() {
DCHECK(actor_);
actor_->Hide();
}
std::string ErrorScreen::GetName() const {
return WizardController::kErrorScreenName;
}
void ErrorScreen::FixCaptivePortal() {
DCHECK(actor_);
actor_->FixCaptivePortal();
}
void ErrorScreen::ShowCaptivePortal() {
DCHECK(actor_);
actor_->ShowCaptivePortal();
}
void ErrorScreen::HideCaptivePortal() {
DCHECK(actor_);
actor_->HideCaptivePortal();
}
void ErrorScreen::SetUIState(UIState ui_state) {
DCHECK(actor_);
actor_->SetUIState(ui_state);
}
void ErrorScreen::SetErrorState(ErrorState error_state,
const std::string& network) {
DCHECK(actor_);
actor_->SetErrorState(error_state, network);
}
} // namespace chromeos
|
/* $Id: rtmempage-exec-mmap-posix.cpp $ */
/** @file
* IPRT - RTMemPage*, POSIX with mmap only.
*/
/*
* Copyright (C) 2006-2017 Oracle Corporation
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* you can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*
* The contents of this file may alternatively be used under the terms
* of the Common Development and Distribution License Version 1.0
* (CDDL) only, as it comes in the "COPYING.CDDL" file of the
* VirtualBox OSE distribution, in which case the provisions of the
* CDDL are applicable instead of those of the GPL.
*
* You may elect to license modified versions of this file under the
* terms and conditions of either the GPL or the CDDL or both.
*/
/*********************************************************************************************************************************
* Header Files *
*********************************************************************************************************************************/
#include "internal/iprt.h"
#include <iprt/mem.h>
#include <iprt/asm.h>
#include <iprt/assert.h>
#include <iprt/err.h>
#include <iprt/param.h>
#include <iprt/string.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/mman.h>
#if !defined(MAP_ANONYMOUS) && defined(MAP_ANON)
# define MAP_ANONYMOUS MAP_ANON
#endif
/**
* Allocates memory from the specified heap.
*
* @returns Address of the allocated memory.
* @param cb The number of bytes to allocate.
* @param pszTag The tag.
* @param fZero Whether to zero the memory or not.
* @param fProtExec PROT_EXEC or 0.
*/
static void *rtMemPagePosixAlloc(size_t cb, const char *pszTag, bool fZero, int fProtExec)
{
/*
* Validate & adjust the input.
*/
Assert(cb > 0);
NOREF(pszTag);
cb = RT_ALIGN_Z(cb, PAGE_SIZE);
/*
* Do the allocation.
*/
void *pv = mmap(NULL, cb,
PROT_READ | PROT_WRITE | fProtExec,
MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (pv != MAP_FAILED)
{
AssertPtr(pv);
if (fZero)
RT_BZERO(pv, cb);
}
else
pv = NULL;
return pv;
}
/**
* Free memory allocated by rtMemPagePosixAlloc.
*
* @param pv The address of the memory to free.
* @param cb The size.
*/
static void rtMemPagePosixFree(void *pv, size_t cb)
{
/*
* Validate & adjust the input.
*/
if (!pv)
return;
AssertPtr(pv);
Assert(cb > 0);
Assert(!((uintptr_t)pv & PAGE_OFFSET_MASK));
cb = RT_ALIGN_Z(cb, PAGE_SIZE);
/*
* Free the memory.
*/
int rc = munmap(pv, cb);
AssertMsg(rc == 0, ("rc=%d pv=%p cb=%#zx\n", rc, pv, cb)); NOREF(rc);
}
RTDECL(void *) RTMemPageAllocTag(size_t cb, const char *pszTag) RT_NO_THROW_DEF
{
return rtMemPagePosixAlloc(cb, pszTag, false /*fZero*/, 0);
}
RTDECL(void *) RTMemPageAllocZTag(size_t cb, const char *pszTag) RT_NO_THROW_DEF
{
return rtMemPagePosixAlloc(cb, pszTag, true /*fZero*/, 0);
}
RTDECL(void) RTMemPageFree(void *pv, size_t cb) RT_NO_THROW_DEF
{
return rtMemPagePosixFree(pv, cb);
}
RTDECL(void *) RTMemExecAllocTag(size_t cb, const char *pszTag) RT_NO_THROW_DEF
{
return rtMemPagePosixAlloc(cb, pszTag, false /*fZero*/, PROT_EXEC);
}
RTDECL(void) RTMemExecFree(void *pv, size_t cb) RT_NO_THROW_DEF
{
return rtMemPagePosixFree(pv, cb);
}
|
// MIT Licensed (see LICENSE.md).
#pragma once
#include "Reals.hpp"
namespace Math
{
template <typename ScalarType, uint Dimension>
struct ZeroSharedTemplate GenericVector
{
// should technically add a trait type for the scalar type to do things
// like get zero and whatnot, but that's not necessary yet
typedef ScalarType scalar;
typedef GenericVector<ScalarType, Dimension> SelfType;
typedef SelfType& SelfRef;
typedef const SelfType& SelfParam;
enum CompileTime
{
Dim = Dimension
};
GenericVector();
explicit GenericVector(scalar* data);
scalar& operator[](uint index);
scalar operator[](uint index) const;
// Unary Operators
SelfType operator-(void) const;
// Binary Assignment Operators (reals)
void operator*=(scalar rhs);
void operator/=(scalar rhs);
// Binary Operators (Reals)
SelfType operator*(scalar rhs) const;
SelfType operator/(scalar rhs) const;
// Binary Assignment Operators (vectors)
void operator+=(SelfParam rhs);
void operator-=(SelfParam rhs);
// Binary Operators (vectors)
SelfType operator+(SelfParam rhs) const;
SelfType operator-(SelfParam rhs) const;
// Vector component wise multiply and divide
SelfType operator*(SelfParam rhs) const;
SelfType operator/(SelfParam rhs) const;
/// Component-wise assignment multiplication
void operator*=(SelfParam rhs);
void operator/=(SelfParam rhs);
void ZeroOut();
/// Set all of the values of the vector to the passed in value.
void Splat(scalar value);
/// Compute the dot product of this vector with the given vector.
scalar Dot(SelfParam rhs) const;
/// Get the squared length of this vector.
scalar LengthSq(void) const;
scalar array[Dimension];
};
} // namespace Math
#include "GenericVector.inl"
|
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "base/basictypes.h"
#include "nsAboutProtocolHandler.h"
#include "nsIURI.h"
#include "nsIIOService.h"
#include "nsCRT.h"
#include "nsIComponentManager.h"
#include "nsIServiceManager.h"
#include "nsIAboutModule.h"
#include "nsString.h"
#include "nsReadableUtils.h"
#include "nsNetCID.h"
#include "nsAboutProtocolUtils.h"
#include "nsError.h"
#include "nsNetUtil.h"
#include "nsIObjectInputStream.h"
#include "nsIObjectOutputStream.h"
#include "nsAutoPtr.h"
#include "nsIWritablePropertyBag2.h"
static NS_DEFINE_CID(kSimpleURICID, NS_SIMPLEURI_CID);
static NS_DEFINE_CID(kNestedAboutURICID, NS_NESTEDABOUTURI_CID);
////////////////////////////////////////////////////////////////////////////////
NS_IMPL_ISUPPORTS1(nsAboutProtocolHandler, nsIProtocolHandler)
////////////////////////////////////////////////////////////////////////////////
// nsIProtocolHandler methods:
NS_IMETHODIMP
nsAboutProtocolHandler::GetScheme(nsACString &result)
{
result.AssignLiteral("about");
return NS_OK;
}
NS_IMETHODIMP
nsAboutProtocolHandler::GetDefaultPort(int32_t *result)
{
*result = -1; // no port for about: URLs
return NS_OK;
}
NS_IMETHODIMP
nsAboutProtocolHandler::GetProtocolFlags(uint32_t *result)
{
*result = URI_NORELATIVE | URI_NOAUTH | URI_DANGEROUS_TO_LOAD;
return NS_OK;
}
NS_IMETHODIMP
nsAboutProtocolHandler::NewURI(const nsACString &aSpec,
const char *aCharset, // ignore charset info
nsIURI *aBaseURI,
nsIURI **result)
{
*result = nullptr;
nsresult rv;
// Use a simple URI to parse out some stuff first
nsCOMPtr<nsIURI> url = do_CreateInstance(kSimpleURICID, &rv);
if (NS_FAILED(rv)) return rv;
rv = url->SetSpec(aSpec);
if (NS_FAILED(rv)) {
return rv;
}
// Unfortunately, people create random about: URIs that don't correspond to
// about: modules... Since those URIs will never open a channel, might as
// well consider them unsafe for better perf, and just in case.
bool isSafe = false;
nsCOMPtr<nsIAboutModule> aboutMod;
rv = NS_GetAboutModule(url, getter_AddRefs(aboutMod));
if (NS_SUCCEEDED(rv)) {
// The standard return case
uint32_t flags;
rv = aboutMod->GetURIFlags(url, &flags);
NS_ENSURE_SUCCESS(rv, rv);
isSafe =
((flags & nsIAboutModule::URI_SAFE_FOR_UNTRUSTED_CONTENT) != 0);
}
if (isSafe) {
// We need to indicate that this baby is safe. Use an inner URI that
// no one but the security manager will see. Make sure to preserve our
// path, in case someone decides to hardcode checks for particular
// about: URIs somewhere.
nsAutoCString spec;
rv = url->GetPath(spec);
NS_ENSURE_SUCCESS(rv, rv);
spec.Insert("moz-safe-about:", 0);
nsCOMPtr<nsIURI> inner;
rv = NS_NewURI(getter_AddRefs(inner), spec);
NS_ENSURE_SUCCESS(rv, rv);
nsSimpleNestedURI* outer = new nsNestedAboutURI(inner, aBaseURI);
NS_ENSURE_TRUE(outer, NS_ERROR_OUT_OF_MEMORY);
// Take a ref to it in the COMPtr we plan to return
url = outer;
rv = outer->SetSpec(aSpec);
NS_ENSURE_SUCCESS(rv, rv);
}
// We don't want to allow mutation, since it would allow safe and
// unsafe URIs to change into each other...
NS_TryToSetImmutable(url);
url.swap(*result);
return NS_OK;
}
NS_IMETHODIMP
nsAboutProtocolHandler::NewChannel(nsIURI* uri, nsIChannel* *result)
{
NS_ENSURE_ARG_POINTER(uri);
// about:what you ask?
nsCOMPtr<nsIAboutModule> aboutMod;
nsresult rv = NS_GetAboutModule(uri, getter_AddRefs(aboutMod));
if (NS_SUCCEEDED(rv)) {
// The standard return case:
rv = aboutMod->NewChannel(uri, result);
if (NS_SUCCEEDED(rv)) {
nsRefPtr<nsNestedAboutURI> aboutURI;
nsresult rv2 = uri->QueryInterface(kNestedAboutURICID,
getter_AddRefs(aboutURI));
if (NS_SUCCEEDED(rv2) && aboutURI->GetBaseURI()) {
nsCOMPtr<nsIWritablePropertyBag2> writableBag =
do_QueryInterface(*result);
if (writableBag) {
writableBag->
SetPropertyAsInterface(NS_LITERAL_STRING("baseURI"),
aboutURI->GetBaseURI());
}
}
}
return rv;
}
// mumble...
if (rv == NS_ERROR_FACTORY_NOT_REGISTERED) {
// This looks like an about: we don't know about. Convert
// this to an invalid URI error.
rv = NS_ERROR_MALFORMED_URI;
}
return rv;
}
NS_IMETHODIMP
nsAboutProtocolHandler::AllowPort(int32_t port, const char *scheme, bool *_retval)
{
// don't override anything.
*_retval = false;
return NS_OK;
}
////////////////////////////////////////////////////////////////////////////////
// Safe about protocol handler impl
NS_IMPL_ISUPPORTS1(nsSafeAboutProtocolHandler, nsIProtocolHandler)
// nsIProtocolHandler methods:
NS_IMETHODIMP
nsSafeAboutProtocolHandler::GetScheme(nsACString &result)
{
result.AssignLiteral("moz-safe-about");
return NS_OK;
}
NS_IMETHODIMP
nsSafeAboutProtocolHandler::GetDefaultPort(int32_t *result)
{
*result = -1; // no port for moz-safe-about: URLs
return NS_OK;
}
NS_IMETHODIMP
nsSafeAboutProtocolHandler::GetProtocolFlags(uint32_t *result)
{
*result = URI_NORELATIVE | URI_NOAUTH | URI_LOADABLE_BY_ANYONE;
return NS_OK;
}
NS_IMETHODIMP
nsSafeAboutProtocolHandler::NewURI(const nsACString &aSpec,
const char *aCharset, // ignore charset info
nsIURI *aBaseURI,
nsIURI **result)
{
nsresult rv;
nsCOMPtr<nsIURI> url = do_CreateInstance(kSimpleURICID, &rv);
if (NS_FAILED(rv)) return rv;
rv = url->SetSpec(aSpec);
if (NS_FAILED(rv)) {
return rv;
}
NS_TryToSetImmutable(url);
*result = nullptr;
url.swap(*result);
return rv;
}
NS_IMETHODIMP
nsSafeAboutProtocolHandler::NewChannel(nsIURI* uri, nsIChannel* *result)
{
*result = nullptr;
return NS_ERROR_NOT_AVAILABLE;
}
NS_IMETHODIMP
nsSafeAboutProtocolHandler::AllowPort(int32_t port, const char *scheme, bool *_retval)
{
// don't override anything.
*_retval = false;
return NS_OK;
}
////////////////////////////////////////////////////////////
// nsNestedAboutURI implementation
NS_INTERFACE_MAP_BEGIN(nsNestedAboutURI)
if (aIID.Equals(kNestedAboutURICID))
foundInterface = static_cast<nsIURI*>(this);
else
NS_INTERFACE_MAP_END_INHERITING(nsSimpleNestedURI)
// nsISerializable
NS_IMETHODIMP
nsNestedAboutURI::Read(nsIObjectInputStream* aStream)
{
nsresult rv = nsSimpleNestedURI::Read(aStream);
if (NS_FAILED(rv)) return rv;
bool haveBase;
rv = aStream->ReadBoolean(&haveBase);
if (NS_FAILED(rv)) return rv;
if (haveBase) {
nsCOMPtr<nsISupports> supports;
rv = aStream->ReadObject(true, getter_AddRefs(supports));
if (NS_FAILED(rv)) return rv;
mBaseURI = do_QueryInterface(supports, &rv);
if (NS_FAILED(rv)) return rv;
}
return NS_OK;
}
NS_IMETHODIMP
nsNestedAboutURI::Write(nsIObjectOutputStream* aStream)
{
nsresult rv = nsSimpleNestedURI::Write(aStream);
if (NS_FAILED(rv)) return rv;
rv = aStream->WriteBoolean(mBaseURI != nullptr);
if (NS_FAILED(rv)) return rv;
if (mBaseURI) {
// A previous iteration of this code wrote out mBaseURI as nsISupports
// and then read it in as nsIURI, which is non-kosher when mBaseURI
// implements more than just a single line of interfaces and the
// canonical nsISupports* isn't the one a static_cast<> of mBaseURI
// would produce. For backwards compatibility with existing
// serializations we continue to write mBaseURI as nsISupports but
// switch to reading it as nsISupports, with a post-read QI to get to
// nsIURI.
rv = aStream->WriteCompoundObject(mBaseURI, NS_GET_IID(nsISupports),
true);
if (NS_FAILED(rv)) return rv;
}
return NS_OK;
}
// nsSimpleURI
/* virtual */ nsSimpleURI*
nsNestedAboutURI::StartClone(nsSimpleURI::RefHandlingEnum aRefHandlingMode)
{
// Sadly, we can't make use of nsSimpleNestedURI::StartClone here.
// However, this function is expected to exactly match that function,
// aside from the "new ns***URI()" call.
NS_ENSURE_TRUE(mInnerURI, nullptr);
nsCOMPtr<nsIURI> innerClone;
nsresult rv = aRefHandlingMode == eHonorRef ?
mInnerURI->Clone(getter_AddRefs(innerClone)) :
mInnerURI->CloneIgnoringRef(getter_AddRefs(innerClone));
if (NS_FAILED(rv)) {
return nullptr;
}
nsNestedAboutURI* url = new nsNestedAboutURI(innerClone, mBaseURI);
url->SetMutable(false);
return url;
}
// nsIClassInfo
NS_IMETHODIMP
nsNestedAboutURI::GetClassIDNoAlloc(nsCID *aClassIDNoAlloc)
{
*aClassIDNoAlloc = kNestedAboutURICID;
return NS_OK;
}
|
/*
* Copyright © 2018 Google, Inc.
*
* This is part of HarfBuzz, a text shaping library.
*
* Permission is hereby granted, without written agreement and without
* license or royalty fees, to use, copy, modify, and distribute this
* software and its documentation for any purpose, provided that the
* above copyright notice and the following two paragraphs appear in
* all copies of this software.
*
* IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR
* DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
* ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
* IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*
* THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
* ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO
* PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
*
* Google Author(s): Behdad Esfahbod
*/
#ifndef HB_MAP_HH
#define HB_MAP_HH
#include "hb.hh"
template <typename T>
inline uint32_t Hash (const T &v)
{
/* Knuth's multiplicative method: */
return (uint32_t) v * 2654435761u;
}
/*
* hb_map_t
*/
struct hb_map_t
{
HB_NO_COPY_ASSIGN (hb_map_t);
hb_map_t () { init (); }
~hb_map_t () { fini (); }
struct item_t
{
hb_codepoint_t key;
hb_codepoint_t value;
bool is_unused () const { return key == INVALID; }
bool is_tombstone () const { return key != INVALID && value == INVALID; }
};
hb_object_header_t header;
bool successful; /* Allocations successful */
unsigned int population; /* Not including tombstones. */
unsigned int occupancy; /* Including tombstones. */
unsigned int mask;
unsigned int prime;
item_t *items;
void init_shallow ()
{
successful = true;
population = occupancy = 0;
mask = 0;
prime = 0;
items = nullptr;
}
void init ()
{
hb_object_init (this);
init_shallow ();
}
void fini_shallow ()
{
free (items);
items = nullptr;
}
void fini ()
{
population = occupancy = 0;
hb_object_fini (this);
fini_shallow ();
}
bool in_error () const { return !successful; }
bool resize ()
{
if (unlikely (!successful)) return false;
unsigned int power = hb_bit_storage (population * 2 + 8);
unsigned int new_size = 1u << power;
item_t *new_items = (item_t *) malloc ((size_t) new_size * sizeof (item_t));
if (unlikely (!new_items))
{
successful = false;
return false;
}
memset (new_items, 0xFF, (size_t) new_size * sizeof (item_t));
unsigned int old_size = mask + 1;
item_t *old_items = items;
/* Switch to new, empty, array. */
population = occupancy = 0;
mask = new_size - 1;
prime = prime_for (power);
items = new_items;
/* Insert back old items. */
if (old_items)
for (unsigned int i = 0; i < old_size; i++)
if (old_items[i].key != INVALID && old_items[i].value != INVALID)
set (old_items[i].key, old_items[i].value);
free (old_items);
return true;
}
void set (hb_codepoint_t key, hb_codepoint_t value)
{
if (unlikely (!successful)) return;
if (unlikely (key == INVALID)) return;
if ((occupancy + occupancy / 2) >= mask && !resize ()) return;
unsigned int i = bucket_for (key);
if (value == INVALID && items[i].key != key)
return; /* Trying to delete non-existent key. */
if (!items[i].is_unused ())
{
occupancy--;
if (items[i].is_tombstone ())
population--;
}
items[i].key = key;
items[i].value = value;
occupancy++;
if (!items[i].is_tombstone ())
population++;
}
hb_codepoint_t get (hb_codepoint_t key) const
{
if (unlikely (!items)) return INVALID;
unsigned int i = bucket_for (key);
return items[i].key == key ? items[i].value : INVALID;
}
void del (hb_codepoint_t key) { set (key, INVALID); }
bool has (hb_codepoint_t key) const
{ return get (key) != INVALID; }
hb_codepoint_t operator [] (unsigned int key) const
{ return get (key); }
static constexpr hb_codepoint_t INVALID = HB_MAP_VALUE_INVALID;
void clear ()
{
if (items) memset (items, 0xFF, ((size_t) mask + 1) * sizeof (item_t));
population = occupancy = 0;
}
bool is_empty () const { return population == 0; }
unsigned int get_population () const { return population; }
protected:
unsigned int bucket_for (hb_codepoint_t key) const
{
unsigned int i = Hash (key) % prime;
unsigned int step = 0;
unsigned int tombstone = INVALID;
while (!items[i].is_unused ())
{
if (items[i].key == key)
return i;
if (tombstone == INVALID && items[i].is_tombstone ())
tombstone = i;
i = (i + ++step) & mask;
}
return tombstone == INVALID ? i : tombstone;
}
static unsigned int prime_for (unsigned int shift)
{
/* Following comment and table copied from glib. */
/* Each table size has an associated prime modulo (the first prime
* lower than the table size) used to find the initial bucket. Probing
* then works modulo 2^n. The prime modulo is necessary to get a
* good distribution with poor hash functions.
*/
/* Not declaring static to make all kinds of compilers happy... */
/*static*/ const unsigned int prime_mod [32] =
{
1, /* For 1 << 0 */
2,
3,
7,
13,
31,
61,
127,
251,
509,
1021,
2039,
4093,
8191,
16381,
32749,
65521, /* For 1 << 16 */
131071,
262139,
524287,
1048573,
2097143,
4194301,
8388593,
16777213,
33554393,
67108859,
134217689,
268435399,
536870909,
1073741789,
2147483647 /* For 1 << 31 */
};
if (unlikely (shift >= ARRAY_LENGTH (prime_mod)))
return prime_mod[ARRAY_LENGTH (prime_mod) - 1];
return prime_mod[shift];
}
};
#endif /* HB_MAP_HH */
|
#pragma once
#include <memory>
#include <string>
#include <iostream>
class ISymbolType {
public:
virtual ~ISymbolType() = default;
virtual bool Equals(const ISymbolType &other) const {
return this == &other;
}
protected:
ISymbolType() = default;
};
class ISymbol {
public:
virtual ~ISymbol() = default;
std::string identifier;
ISymbolType* type = nullptr;
virtual void Print() const
{
std::cout << identifier;
}
protected:
ISymbol() = default;
};
|
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
#include "extern/beatsaber-hook/shared/utils/byref.hpp"
// Including type: NUnit.Framework.Internal.TestSuite
#include "NUnit/Framework/Internal/TestSuite.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "extern/beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: NUnit::Framework::Interfaces
namespace NUnit::Framework::Interfaces {
// Forward declaring type: ITypeInfo
class ITypeInfo;
}
// Completed forward declares
// Type namespace: NUnit.Framework.Internal
namespace NUnit::Framework::Internal {
// Forward declaring type: ParameterizedFixtureSuite
class ParameterizedFixtureSuite;
}
#include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(NUnit::Framework::Internal::ParameterizedFixtureSuite);
DEFINE_IL2CPP_ARG_TYPE(NUnit::Framework::Internal::ParameterizedFixtureSuite*, "NUnit.Framework.Internal", "ParameterizedFixtureSuite");
// Type namespace: NUnit.Framework.Internal
namespace NUnit::Framework::Internal {
// Size: 0x8A
#pragma pack(push, 1)
// Autogenerated type: NUnit.Framework.Internal.ParameterizedFixtureSuite
// [TokenAttribute] Offset: FFFFFFFF
class ParameterizedFixtureSuite : public NUnit::Framework::Internal::TestSuite {
public:
#ifdef USE_CODEGEN_FIELDS
public:
#else
protected:
#endif
// private System.Boolean _genericFixture
// Size: 0x1
// Offset: 0x89
bool genericFixture;
// Field size check
static_assert(sizeof(bool) == 0x1);
public:
// Creating conversion operator: operator bool
constexpr operator bool() const noexcept {
return genericFixture;
}
// Get instance field reference: private System.Boolean _genericFixture
bool& dyn__genericFixture();
// public override System.String get_TestType()
// Offset: 0x2484BA8
// Implemented from: NUnit.Framework.Internal.Test
// Base method: System.String Test::get_TestType()
::Il2CppString* get_TestType();
// public System.Void .ctor(NUnit.Framework.Interfaces.ITypeInfo typeInfo)
// Offset: 0x2484944
// Implemented from: NUnit.Framework.Internal.TestSuite
// Base method: System.Void TestSuite::.ctor(NUnit.Framework.Interfaces.ITypeInfo typeInfo)
// Base method: System.Void Test::.ctor(NUnit.Framework.Interfaces.ITypeInfo typeInfo)
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static ParameterizedFixtureSuite* New_ctor(NUnit::Framework::Interfaces::ITypeInfo* typeInfo) {
static auto ___internal__logger = ::Logger::get().WithContext("NUnit::Framework::Internal::ParameterizedFixtureSuite::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<ParameterizedFixtureSuite*, creationType>(typeInfo)));
}
}; // NUnit.Framework.Internal.ParameterizedFixtureSuite
#pragma pack(pop)
static check_size<sizeof(ParameterizedFixtureSuite), 137 + sizeof(bool)> __NUnit_Framework_Internal_ParameterizedFixtureSuiteSizeCheck;
static_assert(sizeof(ParameterizedFixtureSuite) == 0x8A);
}
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: NUnit::Framework::Internal::ParameterizedFixtureSuite::get_TestType
// Il2CppName: get_TestType
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Il2CppString* (NUnit::Framework::Internal::ParameterizedFixtureSuite::*)()>(&NUnit::Framework::Internal::ParameterizedFixtureSuite::get_TestType)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(NUnit::Framework::Internal::ParameterizedFixtureSuite*), "get_TestType", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: NUnit::Framework::Internal::ParameterizedFixtureSuite::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
|
#include "RequesterSimple.hpp"
#include "Subscriber.hpp"
#include "timer.hpp"
#include "json.hpp"
#include <signal.h>
#include <chrono>
#include <ros/ros.h>
#include <tf/transform_broadcaster.h>
#include <nav_msgs/Odometry.h>
#include <ros_layer_walker/wheels_current.h>
#include <geometry_msgs/Pose2D.h>
#include <fstream>
using namespace std;
using json = nlohmann::json;
//************************************************************************************************************************************
//************************************************************************************************************************************
enum WALKER_NODE{DESELECT = 0, FRONT_LEFT = 1, FRONT_RIGHT = 2, REAR_RIGHT = 3, REAR_LEFT = 4};
/*! \details Structure representing the front data of the walker. */
struct OdomInfo{
double x; /*!< linear position x. */
double y; /*!< linear position y.*/
double theta; /*!< angular position theta.*/
double v; /*!< linear velocity.*/
double omega; /*!< angular velocity.*/
};
/*! \details Structure representing the front data of the walker. */
struct FrontNode{
double speed; /*!< \a velocity of the front wheel. */
double angle; /*!< \a angle of the wheel.*/
int current; /*!< \a absorbed current in mA.*/
bool isAlive; /*!< boolean identifying the status of the node.*/
bool isDisabled; /*!< boolean identifying if the node is disabled.*/
};
//************************************************************************************************************************************
//************************************************************************************************************************************
static volatile int terminating = 0;
OdomInfo odomI;
FrontNode frontLeft; /*!< Front left node */
FrontNode frontRight; /*!< Front right node */
ZMQCommon::RequesterSimple req("tcp://192.168.3.2:5601");
ZMQCommon::Subscriber subLOC;
ZMQCommon::Subscriber subHW;
void intHandler(int dummy) {
terminating = 1;
}
double timeNow() {
using chrono::duration_cast;
using chrono::milliseconds;
using chrono::system_clock;
return (long long int)duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count()/1000.;
}
bool sendRequest(ZMQCommon::RequesterSimple & req, json const & jobj) {
string in_msg = jobj.dump();
string out_msg;
ZMQCommon::RequesterSimple::status_t status;
req.request(in_msg, out_msg, status);
// cout << out_msg << endl;
return status==ZMQCommon::RequesterSimple::status_t::STATUS_OK; // TODO: check ACK
}
bool powerEnable(ZMQCommon::RequesterSimple & req, bool enable) {
json jobj;
jobj["cmd"] = string("set_power_enable");
jobj["enable"] = enable;
return sendRequest(req, jobj);
}
bool setDeviceMode(ZMQCommon::RequesterSimple & req, int deviceMode) {
json jobj;
jobj["cmd"] = string("set_device_mode");
jobj["device_mode"] = deviceMode;
return sendRequest(req, jobj);
}
bool powerOn(ZMQCommon::RequesterSimple & req) {
if (!powerEnable(req, true)) return false;
if (!setDeviceMode(req, 5)) return false;
return true;
}
bool walkerStop(ZMQCommon::RequesterSimple & req) {
json jobj;
jobj["cmd"] = string("walker_stop");
return sendRequest(req, jobj);
}
bool powerOff(ZMQCommon::RequesterSimple & req) {
return walkerStop(req) && powerEnable(req, false);
}
bool currentSteering(ZMQCommon::RequesterSimple & req, double left, double right, double acceleration) {
json j_req;
j_req["cmd"] = std::string("set_single_node_current");
j_req["dest"] = WALKER_NODE::REAR_LEFT;
j_req["value"] = acceleration;
sendRequest(req, j_req);
j_req["cmd"] = std::string("set_single_node_current");
j_req["dest"] = WALKER_NODE::REAR_RIGHT;
j_req["value"] = -acceleration;
sendRequest(req, j_req);
json jobj;
jobj["cmd"] = string("set_front_current");
jobj["right"] = right;
jobj["left"] = left;
return sendRequest(req, jobj);
}
void loc_callback(const char *topic, const char *buf, size_t size, void *data){
json j;
try{
j = json::parse(string(buf, size));
//j = j.at("state");
odomI.x = round((double)j.at("state").at("x")*100)/100.0;
odomI.y = round((double)j.at("state").at("y")*100)/100.0;
//int z = j.at("z");
odomI.theta = j.at("state").at("theta");
odomI.omega = j.at("state").at("omega");
odomI.v = j.at("state").at("v");
/*double covxx = j.at("covariance")[0];
double covxy = j.at("covariance")[1];
double covyy = j.at("covariance")[2];
double tmp[4] = {covxx,covxy,covxy,covyy};
QGenericMatrix<2, 2, double> cov(tmp);
cout << j.dump() << endl << endl;*/
}catch(exception &e){
cerr << "error parsing: " << e.what() << endl;
}
}
void odometry(ros::Publisher odom_pub, tf::TransformBroadcaster odom_broadcaster, ros::Time current_time)
{
double x = odomI.x;
double y = odomI.y;
double th = odomI.theta;
double vx = odomI.v*cos(th);
double vy = odomI.v*sin(th);
double vth = odomI.omega;
//since all odometry is 6DOF we'll need a quaternion created from yaw
geometry_msgs::Quaternion odom_quat = tf::createQuaternionMsgFromYaw(th);
//first, we'll publish the transform over tf
geometry_msgs::TransformStamped odom_trans;
odom_trans.header.stamp = current_time;
odom_trans.header.frame_id = "odom";
odom_trans.child_frame_id = "base_link";
odom_trans.transform.translation.x = x;
odom_trans.transform.translation.y = y;
odom_trans.transform.translation.z = 0.0;
odom_trans.transform.rotation = odom_quat;
//send the transform
odom_broadcaster.sendTransform(odom_trans);
//next, we'll publish the odometry message over ROS
nav_msgs::Odometry odom;
odom.header.stamp = current_time;
odom.header.frame_id = "odom";
odom.child_frame_id = "base_link";
//set the position
odom.pose.pose.position.x = x;
odom.pose.pose.position.y = y;
odom.pose.pose.position.z = 0.0;
odom.pose.pose.orientation = odom_quat;
//set the velocity
odom.twist.twist.linear.x = vx;
odom.twist.twist.linear.y = vy;
odom.twist.twist.angular.z = vth;
//publish the message
odom_pub.publish(odom);
}
void hwInfo(ros::Publisher hw_pub)
{
//we'll publish the wheels angles message over ROS
geometry_msgs::Pose2D infos;
infos.x = frontLeft.angle;
infos.y = frontRight.angle;
//publish the message
hw_pub.publish(infos);
}
void hw_callback(const char *topic, const char *buf, size_t size, void *data){
json j;
json j_out;
try{
j = json::parse(string(buf, size));
j_out = j.at("1");
frontLeft.isDisabled = false;
j_out = j_out.at("state");
frontLeft.angle = j_out.at("pos");
frontLeft.speed = j_out.at("vel");
frontLeft.current = j_out.at("cur");
j_out = j.at("1").at("status");
frontLeft.isAlive = j_out.at("alive");
frontLeft.isDisabled = true;
j_out = j.at("2");
frontRight.isDisabled = false;
j_out = j_out.at("state");
frontRight.angle = j_out.at("pos");
frontRight.speed = j_out.at("vel");
frontRight.current = j_out.at("cur");
j_out = j.at("2").at("status");
frontRight.isAlive = j_out.at("alive");
frontRight.isDisabled = true;
}catch(exception &e){
cerr << "error parsing: " << e.what() << endl;
}
}
void command_torque(const geometry_msgs::Pose2D &curr)
{
currentSteering(req,curr.x,curr.y,curr.theta);
}
int main (int argc, char *argv[])
{
ZMQCommon::RequesterSimple arucolist("tcp://192.168.3.1:5567");
ZMQCommon::RequesterSimple::status_t status;
string response;
ifstream ifs("/Users/placido/catkin_ws/src/ros_layer_walker/listaQR.json");
json jobj_aruco = json::parse(ifs);
cout << sendRequest(arucolist,jobj_aruco) << endl;
arucolist.close();
// Subscribe to the location ZMQ publisher of the robot
subLOC.register_callback([&](const char *topic, const char *buf, size_t size, void *data){loc_callback(topic,buf,size,data);});
subLOC.start("tcp://192.168.3.1:5563","LOC");
// Subscribe to the hardware information ZMQ publisher of the robot
subHW.register_callback([&](const char *topic, const char *buf, size_t size, void *data){hw_callback(topic,buf,size,data);});
subHW.start("tcp://192.168.3.2:6000","PUB_HW");
while (!terminating && !powerOn(req)) {
cerr << "[WARN] Cannot start robot..." << endl;
this_thread::sleep_for(chrono::milliseconds(100));
}
if (terminating) return 0;
ros::init(argc, argv, "ros_layer_walker");
ros::NodeHandle n;
ros::Publisher odom_pub = n.advertise<nav_msgs::Odometry>("odom", 50);
tf::TransformBroadcaster odom_broadcaster;
ros::Publisher hw_pub = n.advertise<geometry_msgs::Pose2D>("wheels_angle", 50);
ros::Subscriber ros_sub = n.subscribe("cmd_current", 50, command_torque);
ros::Time current_time;
ros::Rate r(20.0);
while(n.ok() && !terminating){
ros::spinOnce();
current_time = ros::Time::now();
odometry(odom_pub,odom_broadcaster,current_time);
hwInfo(hw_pub);
r.sleep();
}
subLOC.stop();
walkerStop(req);
powerOff(req);
req.close();
return 0;
}
|
/*
* Copyright (C) 2015-2018 Nils Asmussen <nils@os.inf.tu-dresden.de>
* Copyright (C) 2019-2022 Nils Asmussen, Barkhausen Institut
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. 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.
*
* 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.
*
* The views and conclusions contained in the software and documentation are
* those of the authors and should not be interpreted as representing official
* policies, either expressed or implied, of the FreeBSD Project.
*/
#ifndef __SIM_TCU_MEMORY_HH__
#define __SIM_TCU_MEMORY_HH__
#include "sim/system.hh"
#include "mem/tcu/noc_addr.hh"
class TileMemory
{
private:
SimObject *obj;
PortProxy &physp;
public:
const tileid_t memTile;
const Addr memOffset;
const Addr memSize;
TileMemory(SimObject *obj,
tileid_t memTile,
Addr memOffset,
Addr memSize,
PortProxy &phys);
bool hasMem(tileid_t tile) const
{
return (tileDesc(tile) & 0x7) != 1;
}
virtual uint32_t tileDesc(tileid_t tile) const = 0;
NocAddr getPhys(Addr offset) const
{
return NocAddr(memTile, memOffset + offset);
}
};
#endif
|
#include "mzpch.h"
#include "OpenGLBuffer.h"
#include <glad/glad.h>
namespace Mazel
{
#pragma region [VertexBuffer]
OpenGLVertexBuffer::OpenGLVertexBuffer(float* vertices, uint32_t size)
{
glCreateBuffers(1, &m_RendererID);
glBindBuffer(GL_ARRAY_BUFFER, m_RendererID);
glBufferData(GL_ARRAY_BUFFER, size, vertices, GL_STATIC_DRAW);
}
OpenGLVertexBuffer::~OpenGLVertexBuffer()
{
glDeleteBuffers(1, &m_RendererID);
}
void OpenGLVertexBuffer::Bind() const
{
glBindBuffer(GL_ARRAY_BUFFER, m_RendererID);
}
void OpenGLVertexBuffer::Unbind() const
{
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
#pragma endregion [VertexBuffer]
#pragma region [IndexBuffer]
OpenGLIndexBuffer::OpenGLIndexBuffer(uint32_t* indices, uint32_t count)
: m_Count(count)
{
glCreateBuffers(1, &m_RendererID);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_RendererID);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, count * sizeof(uint32_t), indices, GL_STATIC_DRAW);
}
OpenGLIndexBuffer::~OpenGLIndexBuffer()
{
glDeleteBuffers(1, &m_RendererID);
}
void OpenGLIndexBuffer::Bind() const
{
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_RendererID);
}
void OpenGLIndexBuffer::Unbind() const
{
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}
#pragma endregion [IndexBuffer]
}
|
//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2018, Image Engine Design Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of Image Engine Design nor the names of any
// other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#include "IECoreScene/SceneAlgo.h"
#include "IECoreScene/CurvesPrimitive.h"
#include "IECoreScene/MeshPrimitive.h"
#include "IECoreScene/PointsPrimitive.h"
#include "IECoreScene/SceneInterface.h"
#include "tbb/task.h"
#include <atomic>
using namespace IECore;
using namespace IECoreScene;
namespace
{
template<typename LocationFn>
class Task : public tbb::task
{
public :
Task(
const SceneInterface *src, SceneInterface *dst, LocationFn &locationFn, double time, unsigned int flags
) : m_src( src ), m_dst( dst ), m_locationFn( locationFn ), m_time( time ), m_flags( flags )
{
}
~Task() override
{
}
task *execute() override
{
m_locationFn( m_src, m_dst, m_time, m_flags );
SceneInterface::NameList childNames;
m_src->childNames( childNames );
set_ref_count( 1 + childNames.size() );
std::vector<SceneInterfacePtr> childSceneInterfaces;
childSceneInterfaces.reserve( childNames.size() );
std::vector<ConstSceneInterfacePtr> srcChildSceneInterfaces;
srcChildSceneInterfaces.reserve( childNames.size() );
for( const auto &childName : childNames )
{
SceneInterfacePtr dstChild = m_dst ? m_dst->child( childName, SceneInterface::CreateIfMissing ) : nullptr;
if( dstChild )
{
childSceneInterfaces.push_back( dstChild );
}
ConstSceneInterfacePtr srcChild = m_src->child( childName );
srcChildSceneInterfaces.push_back( srcChild );
Task *t = new( allocate_child() ) Task( srcChild.get(), dstChild.get(), m_locationFn, m_time, m_flags );
spawn( *t );
}
wait_for_all();
return nullptr;
}
private :
const SceneInterface *m_src;
SceneInterface *m_dst;
LocationFn &m_locationFn;
double m_time;
unsigned int m_flags;
};
template<typename T>
struct CopyInfo
{
CopyInfo() : polygonCount( 0 ), curveCount( 0 ), pointCount( 0 ), attributeCount( 0 ), tagCount( 0 ), setCount( 0 )
{
}
T polygonCount;
T curveCount;
T pointCount;
T attributeCount;
T tagCount;
T setCount;
};
CopyInfo<size_t> handleLocation( const SceneInterface *src, SceneInterface *dst, double time, unsigned int flags )
{
SceneInterface::Path path;
src->path( path );
bool isRoot = path.empty();
CopyInfo<size_t> copyInfo;
if( flags & SceneAlgo::Bounds )
{
auto bound = src->readBound( time );
if( dst )
{
dst->writeBound( bound, time );
}
}
if( flags & SceneAlgo::Transforms )
{
IECore::ConstDataPtr transform = src->readTransform( time );
if( dst && !isRoot )
{
dst->writeTransform( transform.get(), time );
}
}
if( flags & SceneAlgo::Attributes )
{
SceneInterface::NameList attributeNames;
src->attributeNames( attributeNames );
copyInfo.attributeCount += attributeNames.size();
for( const auto &attributeName : attributeNames )
{
IECore::ConstObjectPtr attr = src->readAttribute( attributeName, time );
if( dst )
{
dst->writeAttribute( attributeName, attr.get(), time );
}
}
}
if( flags & SceneAlgo::Tags )
{
SceneInterface::NameList tags;
src->readTags( tags );
copyInfo.tagCount += tags.size();
if( dst )
{
dst->writeTags( tags );
}
}
if( flags & SceneAlgo::Sets && isRoot )
{
SceneInterface::NameList setNames = src->setNames();
copyInfo.setCount += setNames.size();
for( const auto &setName : setNames )
{
PathMatcher set = src->readSet( setName );
if( dst )
{
dst->writeSet( setName, set );
}
}
}
if( flags & SceneAlgo::Objects && src->hasObject() )
{
IECore::ConstObjectPtr obj = src->readObject( time );
if( IECoreScene::MeshPrimitive::ConstPtr mesh = IECore::runTimeCast<const IECoreScene::MeshPrimitive>( obj ) )
{
copyInfo.polygonCount += mesh->numFaces();
}
else if( IECoreScene::CurvesPrimitive::ConstPtr curves = IECore::runTimeCast<const IECoreScene::CurvesPrimitive>( obj ) )
{
copyInfo.curveCount += curves->numCurves();
}
else if( IECoreScene::PointsPrimitive::ConstPtr points = IECore::runTimeCast<const IECoreScene::PointsPrimitive>( obj ) )
{
copyInfo.pointCount += points->getNumPoints();
}
if( dst )
{
dst->writeObject( obj.get(), time );
}
}
return copyInfo;
}
template<typename LocationFn>
void copy( const SceneInterface *src, SceneInterface *dst, double time, unsigned int flags, LocationFn &locationFn )
{
locationFn( src, dst, time, flags );
SceneInterface::NameList childNames;
src->childNames( childNames );
for( const auto &childName : childNames )
{
SceneInterfacePtr dstChild = dst->child( childName, SceneInterface::CreateIfMissing );
::copy( src->child( childName ).get(), dstChild.get(), time, flags, locationFn );
}
}
} // namespace
namespace IECoreScene
{
namespace SceneAlgo
{
SceneStats parallelReadAll( const SceneInterface *src, int startFrame, int endFrame, float frameRate, unsigned int flags )
{
std::atomic<size_t> locationCount( 0 );
::CopyInfo<std::atomic<size_t> > copyInfos;
auto locationFn = [&locationCount, ©Infos]( const SceneInterface *src, SceneInterface *dst, double time, unsigned int flags )
{
locationCount++;
::CopyInfo<size_t> copyInfo = ::handleLocation( src, nullptr, time, flags );
copyInfos.polygonCount += copyInfo.polygonCount;
copyInfos.tagCount += copyInfo.tagCount;
copyInfos.attributeCount += copyInfo.attributeCount;
copyInfos.curveCount += copyInfo.curveCount;
copyInfos.pointCount += copyInfo.pointCount;
};
for( int f = startFrame; f <= endFrame; ++f )
{
double time = f / frameRate;
tbb::task_group_context taskGroupContext( tbb::task_group_context::isolated );
Task<decltype( locationFn )> *task = new( tbb::task::allocate_root( taskGroupContext ) ) Task<decltype( locationFn )>( src, nullptr, locationFn, time, flags );
tbb::task::spawn_root_and_wait( *task );
}
SceneStats stats;
stats["locations"] = locationCount;
stats["polygons"] = copyInfos.polygonCount;
stats["curves"] = copyInfos.curveCount;
stats["points"] = copyInfos.pointCount;
stats["tags"] = copyInfos.tagCount;
stats["sets"] = copyInfos.setCount;
stats["attributes"] = copyInfos.attributeCount;
return stats;
}
void copy( const SceneInterface *src, SceneInterface *dst, int startFrame, int endFrame, float frameRate, unsigned int flags )
{
for( int f = startFrame; f <= endFrame; ++f )
{
double time = f / frameRate;
// disable copying tags for all frame apart from the first.
if( f != startFrame )
{
flags &= ~Tags;
}
::copy( src, dst, time, flags, ::handleLocation );
}
}
} // SceneAlgo
} // IECoreScene
|
/*
* Copyright (c) 2004-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include "fboss/agent/hw/test/HwPortUtils.h"
#include "fboss/agent/hw/bcm/BcmError.h"
#include "fboss/agent/hw/bcm/BcmSwitch.h"
extern "C" {
#include <bcm/port.h>
}
namespace {
bcm_port_t getBcmPort(facebook::fboss::PortID port) {
return static_cast<bcm_port_t>(port);
}
int getUnit(const facebook::fboss::HwSwitch* hw) {
CHECK(hw);
return static_cast<const facebook::fboss::BcmSwitch*>(hw)->getUnit();
}
void updatePortProfileIDAndName(
facebook::fboss::cfg::SwitchConfig* config,
int portIndex,
facebook::fboss::PortID portID,
const facebook::fboss::Platform* platform) {
auto platformPort = platform->getPlatformPort(portID);
if (auto entry = platformPort->getPlatformPortEntry()) {
config->ports_ref()[portIndex].name_ref() =
*entry->mapping_ref()->name_ref();
*config->ports[portIndex].profileID_ref() =
platformPort->getProfileIDBySpeed(
*config->ports[portIndex].speed_ref());
} else {
throw facebook::fboss::FbossError(
"Port:", portID, " doesn't have PlatformPortEntry");
}
}
} // namespace
namespace facebook::fboss::utility {
bool portEnabled(const HwSwitch* hw, PortID port) {
int enable = -1;
auto rv = bcm_port_enable_get(getUnit(hw), getBcmPort(port), &enable);
bcmCheckError(rv, "failed to get port enable status");
CHECK(enable == 0 || enable == 1);
return (enable == 1);
}
cfg::PortSpeed curPortSpeed(const HwSwitch* hw, PortID port) {
int curSpeed;
auto ret = bcm_port_speed_get(getUnit(hw), getBcmPort(port), &curSpeed);
bcmCheckError(ret, "Failed to get current speed for port");
return cfg::PortSpeed(curSpeed);
}
void assertPort(
const HwSwitch* hw,
PortID port,
bool enabled,
cfg::PortSpeed speed) {
CHECK_EQ(enabled, portEnabled(hw, port));
if (enabled) {
// Only verify speed on enabled ports
CHECK_EQ(
static_cast<int>(speed),
static_cast<int>(utility::curPortSpeed(hw, port)));
}
}
void assertPortStatus(const HwSwitch* hw, PortID port) {
CHECK(portEnabled(hw, port));
}
void assertPortsLoopbackMode(
const HwSwitch* hw,
const std::map<PortID, int>& port2LoopbackMode) {
for (auto portAndLoopBackMode : port2LoopbackMode) {
assertPortLoopbackMode(
hw, portAndLoopBackMode.first, portAndLoopBackMode.second);
}
}
void assertPortSampleDestination(
const HwSwitch* hw,
PortID port,
int expectedSampleDestination) {
int sampleDestination;
auto rv = bcm_port_control_get(
getUnit(hw),
getBcmPort(port),
bcmPortControlSampleIngressDest,
&sampleDestination);
bcmCheckError(rv, "Failed to get sample destination for port:", port);
CHECK_EQ(expectedSampleDestination, sampleDestination);
}
void assertPortsSampleDestination(
const HwSwitch* hw,
const std::map<PortID, int>& port2SampleDestination) {
for (auto portAndSampleDestination : port2SampleDestination) {
assertPortSampleDestination(
hw, portAndSampleDestination.first, portAndSampleDestination.second);
}
}
void assertPortLoopbackMode(
const HwSwitch* hw,
PortID port,
int expectedLoopbackMode) {
int loopbackMode;
auto rv = bcm_port_loopback_get(getUnit(hw), getBcmPort(port), &loopbackMode);
bcmCheckError(rv, "Failed to get loopback mode for port:", port);
CHECK_EQ(expectedLoopbackMode, loopbackMode);
}
void enableOneLane(
cfg::SwitchConfig* config,
cfg::PortSpeed enabledLaneSpeed,
cfg::PortSpeed disabledLaneSpeed,
std::vector<PortID> allPortsinGroup,
const Platform* platform) {
auto portItr = allPortsinGroup.begin();
bool firstLane = true;
int portIndex = 0;
for (; portItr != allPortsinGroup.end(); portItr++, portIndex++) {
*config->ports[portIndex].state_ref() =
firstLane ? cfg::PortState::ENABLED : cfg::PortState::DISABLED;
*config->ports[portIndex].speed_ref() =
firstLane ? enabledLaneSpeed : disabledLaneSpeed;
updatePortProfileIDAndName(config, portIndex, *portItr, platform);
firstLane = false;
}
}
void enableAllLanes(
cfg::SwitchConfig* config,
cfg::PortSpeed enabledLaneSpeed,
std::vector<PortID> allPortsinGroup,
const Platform* platform) {
auto portItr = allPortsinGroup.begin();
int portIndex = 0;
for (; portItr != allPortsinGroup.end(); portItr++, portIndex++) {
*config->ports[portIndex].speed_ref() = enabledLaneSpeed;
*config->ports[portIndex].state_ref() = cfg::PortState::ENABLED;
updatePortProfileIDAndName(config, portIndex, *portItr, platform);
}
}
void enableTwoLanes(
cfg::SwitchConfig* config,
cfg::PortSpeed enabledLaneSpeed,
cfg::PortSpeed disabledLaneSpeed,
std::vector<PortID> allPortsinGroup,
const Platform* platform) {
auto portItr = allPortsinGroup.begin();
bool oddLane;
int portIndex = 0;
for (; portItr != allPortsinGroup.end(); portItr++, portIndex++) {
oddLane = (*portItr - allPortsinGroup.front()) % 2 == 0 ? true : false;
*config->ports[portIndex].state_ref() =
oddLane ? cfg::PortState::ENABLED : cfg::PortState::DISABLED;
*config->ports[portIndex].speed_ref() =
oddLane ? enabledLaneSpeed : disabledLaneSpeed;
updatePortProfileIDAndName(config, portIndex, *portItr, platform);
}
}
void assertQUADMode(
HwSwitch* hw,
cfg::PortSpeed enabledLaneSpeed,
std::vector<PortID> allPortsinGroup) {
auto portItr = allPortsinGroup.begin();
for (; portItr != allPortsinGroup.end(); portItr++) {
utility::assertPort(hw, *portItr, true, enabledLaneSpeed);
}
}
void assertDUALMode(
HwSwitch* hw,
cfg::PortSpeed enabledLaneSpeed,
cfg::PortSpeed disabledLaneSpeed,
std::vector<PortID> allPortsinGroup) {
bool odd_lane;
auto portItr = allPortsinGroup.begin();
for (; portItr != allPortsinGroup.end(); portItr++) {
odd_lane = (*portItr - allPortsinGroup.front()) % 2 == 0 ? true : false;
bool enabled = odd_lane ? true : false;
auto speed = odd_lane ? enabledLaneSpeed : disabledLaneSpeed;
utility::assertPort(hw, *portItr, enabled, speed);
}
}
void assertSINGLEMode(
HwSwitch* hw,
cfg::PortSpeed enabledLaneSpeed,
cfg::PortSpeed disabledLaneSpeed,
std::vector<PortID> allPortsinGroup) {
auto portItr = allPortsinGroup.begin();
for (; portItr != allPortsinGroup.end(); portItr++) {
bool enabled = *portItr == allPortsinGroup.front() ? true : false;
auto speed = enabled ? enabledLaneSpeed : disabledLaneSpeed;
utility::assertPort(hw, *portItr, enabled, speed);
}
}
} // namespace facebook::fboss::utility
|
/*=========================================================================
*
* Copyright David Doria 2011 daviddoria@gmail.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#include <QtGui>
#include <QFileDialog>
#include <QString>
#include "SyntheticLidarScannerWidget.h"
#include "Helpers.h"
#include <vtkActor.h>
#include <vtkAxesActor.h>
#include <vtkBoxRepresentation.h>
#include <vtkBoxWidget2.h>
#include <vtkDoubleArray.h>
#include <vtkFloatArray.h>
#include <vtkImageData.h>
#include <vtkMath.h>
#include <vtkPlanes.h>
#include <vtkPolyDataMapper.h>
#include <vtkPolyData.h>
#include <vtkPointData.h>
#include <vtkProperty.h>
#include <vtkRenderWindow.h>
#include <vtkRenderer.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkRendererCollection.h>
#include <vtkSmartPointer.h>
#include <vtkSphereSource.h>
#include <vtkVertexGlyphFilter.h>
#include <vtkXMLPolyDataWriter.h>
#include <vtkXMLPolyDataReader.h>
#include <vtkXMLImageDataWriter.h>
#include "vtkLidarScanner.h"
#include "ScannerInteractorStyle.h"
#include <sstream>
void SyntheticLidarScannerWidget::ConnectSlots()
{
// The text boxes for the angles should update the display
connect( this->txtMinThetaAngle, SIGNAL( returnPressed() ), this, SLOT(slot_Preview()) );
connect( this->txtMinThetaAngle, SIGNAL( editingFinished()), this, SLOT(slot_Preview()) );
connect( this->txtMaxThetaAngle, SIGNAL( returnPressed() ), this, SLOT(slot_Preview()) );
connect( this->txtMaxThetaAngle, SIGNAL( editingFinished()), this, SLOT(slot_Preview()) );
connect( this->txtMinPhiAngle, SIGNAL( returnPressed() ), this, SLOT(slot_Preview()) );
connect( this->txtMinPhiAngle, SIGNAL( editingFinished()), this, SLOT(slot_Preview()) );
connect( this->txtMaxPhiAngle, SIGNAL( returnPressed() ), this, SLOT(slot_Preview()) );
connect( this->txtMaxPhiAngle, SIGNAL( editingFinished()), this, SLOT(slot_Preview()) );
}
void SyntheticLidarScannerWidget::SharedConstructor()
{
// This must be called first.
this->setupUi(this);
// Set the progress bar to maruee mode
this->progressBar->setMinimum(0);
this->progressBar->setMaximum(0);
this->progressBar->hide();
this->lblScanning->hide();
// This must come before the widget setup
this->Renderer = vtkSmartPointer<vtkRenderer>::New();
this->qvtkWidget->GetRenderWindow()->AddRenderer(this->Renderer);
this->Renderer->SetBackground(.5,.5,1);
this->ScannerStyle = vtkSmartPointer<ScannerInteractorStyle>::New();
this->ScannerStyle->SetCurrentRenderer(this->Renderer);
this->ScannerStyle->SetInteractor(this->qvtkWidget->GetInteractor());
this->ScannerStyle->Initialize();
this->qvtkWidget->GetInteractor()->SetInteractorStyle(this->ScannerStyle);
// GUI initializations
this->txtMinThetaAngle->setText(QString("-10"));
this->txtMaxThetaAngle->setText(QString("10"));
this->txtMinPhiAngle->setText(QString("-10"));
this->txtMaxPhiAngle->setText(QString("10"));
this->txtNumberOfThetaPoints->setText(QString("10"));
this->txtNumberOfPhiPoints->setText(QString("10"));
this->ConnectSlots();
this->Refresh();
}
SyntheticLidarScannerWidget::SyntheticLidarScannerWidget() : QMainWindow()
{
SharedConstructor();
}
SyntheticLidarScannerWidget::SyntheticLidarScannerWidget(const std::string& fileName)
{
SharedConstructor();
OpenFile(fileName);
}
void SyntheticLidarScannerWidget::ResetAndRefresh()
{
// Refresh
this->qvtkWidget->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->ResetCamera();
this->qvtkWidget->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->Render();
this->qvtkWidget->GetRenderWindow()->Render();
}
void SyntheticLidarScannerWidget::Refresh()
{
// Refresh
this->qvtkWidget->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->Render();
this->qvtkWidget->GetRenderWindow()->Render();
}
void SyntheticLidarScannerWidget::SetScannerParameters()
{
this->ScannerStyle->LidarScanner->SetMinPhiAngleDegrees(this->txtMinPhiAngle->text().toDouble());
this->ScannerStyle->LidarScanner->SetMaxPhiAngleDegrees(this->txtMaxPhiAngle->text().toDouble());
this->ScannerStyle->LidarScanner->SetMinThetaAngleDegrees(this->txtMinThetaAngle->text().toDouble());
this->ScannerStyle->LidarScanner->SetMaxThetaAngleDegrees(this->txtMaxThetaAngle->text().toDouble());
this->ScannerStyle->LidarScanner->SetNumberOfThetaPoints(this->txtNumberOfThetaPoints->text().toUInt());
this->ScannerStyle->LidarScanner->SetNumberOfPhiPoints(this->txtNumberOfPhiPoints->text().toUInt());
}
void SyntheticLidarScannerWidget::on_btnScan_clicked()
{
// Start the progress bar
this->progressBar->show();
this->lblScanning->show();
// Get the parameters from the UI and set them in the LidarScanner object
SetScannerParameters();
// Perform the scan
this->ScannerStyle->LidarScanner->SetInputData(this->ScannerStyle->Scene);
this->ScannerStyle->LidarScanner->Update();
this->ScannerStyle->LidarScanner->GetValidOutputPoints(this->ScannerStyle->Scan);
Helpers::WritePolyData(this->ScannerStyle->Scan, "scan.vtp"); // This works
// Setup the visualization
this->ScannerStyle->ScanMapper->SetInputData(this->ScannerStyle->Scan);
this->ScannerStyle->ScanActor->SetMapper(this->ScannerStyle->ScanMapper);
this->ScannerStyle->ScanActor->GetProperty()->SetPointSize(4);
this->ScannerStyle->ScanActor->GetProperty()->SetColor(1,0,0);
this->Renderer->AddActor(this->ScannerStyle->ScanActor);
this->Refresh();
// Stop the progress bar
this->progressBar->hide();
this->lblScanning->hide();
}
void SyntheticLidarScannerWidget::on_actionSaveMesh_activated()
{
// Set a filename to save
QString fileName = QFileDialog::getSaveFileName(this,
"Save Scan", "scan.vtp", "VTP Files (*.vtp)");
if(fileName.isEmpty())
{
return;
}
std::cout << "Saving to " << fileName.toStdString() << "..." << std::endl;
if(this->ScannerStyle->Scan)
{
vtkSmartPointer<vtkPolyData> polydata = vtkSmartPointer<vtkPolyData>::New();
this->ScannerStyle->LidarScanner->GetOutputMesh(polydata);
vtkSmartPointer<vtkXMLPolyDataWriter> writer =
vtkSmartPointer<vtkXMLPolyDataWriter>::New();
writer->SetInputData(polydata);
writer->SetFileName(fileName.toStdString().c_str());
writer->Write();
}
else
{
std::cerr << "You must scan before you can save!" << std::endl;
}
}
void SyntheticLidarScannerWidget::on_actionSavePoints_activated()
{
// Set a filename to save
QString fileName = QFileDialog::getSaveFileName(this,
tr("Save Scan"), "/home/doriad", tr("Image Files (*.vtp)"));
if(fileName.isEmpty())
{
return;
}
std::cout << "Saving to " << fileName.toStdString() << "..." << std::endl;
if(this->ScannerStyle->Scan)
{
vtkSmartPointer<vtkXMLPolyDataWriter> writer =
vtkSmartPointer<vtkXMLPolyDataWriter>::New();
writer->SetInputData(this->ScannerStyle->Scan);
writer->SetFileName(fileName.toStdString().c_str());
writer->Write();
}
else
{
std::cerr << "You must scan before you can save!" << std::endl;
}
}
void SyntheticLidarScannerWidget::on_actionSavePTX_activated()
{
// Set a filename to save
QString fileName = QFileDialog::getSaveFileName(this,
tr("Save Scan"), "/home/doriad", tr("Image Files (*.ptx)"));
std::cout << "Saving to " << fileName.toStdString() << "..." << std::endl;
if(this->ScannerStyle->Scan)
{
this->ScannerStyle->LidarScanner->WritePTX(fileName.toStdString());
}
else
{
std::cerr << "You must scan before you can save!" << std::endl;
}
}
void SyntheticLidarScannerWidget::on_actionSaveFullOutput_activated()
{
// Set a filename to save
QString fileName = QFileDialog::getSaveFileName(this,
tr("Save Scan"), "/home/doriad", tr("Image Files (*.vti)"));
std::cout << "Saving to " << fileName.toStdString() << "..." << std::endl;
vtkImageData* fullOutput = this->ScannerStyle->LidarScanner->GetOutput();
if(fullOutput)
{
vtkSmartPointer<vtkXMLImageDataWriter> writer =
vtkSmartPointer<vtkXMLImageDataWriter>::New();
writer->SetInputData(fullOutput);
writer->SetFileName(fileName.toStdString().c_str());
writer->Write();
}
else
{
std::cerr << "You must scan before you can save!" << std::endl;
}
}
void SyntheticLidarScannerWidget::slot_Preview()
{
SetScannerParameters();
this->ScannerStyle->CreateRepresentation();
this->ScannerStyle->LidarScannerMapper->SetInputData(this->ScannerStyle->LidarScannerRepresentation);
this->ScannerStyle->LidarScannerActor->SetMapper(this->ScannerStyle->LidarScannerMapper);
this->ScannerStyle->LidarScannerActor->GetProperty()->SetOpacity(.5);
this->ScannerStyle->LidarScannerActor->GetProperty()->SetColor(224./255., 176./255., 1);
this->Renderer->AddActor(this->ScannerStyle->LidarScannerActor);
this->Refresh();
}
void SyntheticLidarScannerWidget::OpenFile(const std::string& fileName)
{
// Open the file
vtkSmartPointer<vtkXMLPolyDataReader> reader =
vtkSmartPointer<vtkXMLPolyDataReader>::New();
reader->SetFileName(fileName.c_str());
reader->Update();
// Store the data as the scene
this->ScannerStyle->Scene->ShallowCopy(reader->GetOutput());
this->ScannerStyle->SceneMapper->SetInputData(this->ScannerStyle->Scene);
this->ScannerStyle->SceneActor->SetMapper(this->ScannerStyle->SceneMapper);
this->Renderer->AddActor(this->ScannerStyle->SceneActor);
this->ResetAndRefresh();
}
void SyntheticLidarScannerWidget::on_actionOpen_activated()
{
// Get a filename to open
QString fileName = QFileDialog::getOpenFileName(this,
//tr("Open File"), "/home/doriad", tr("Image Files (*.vtp)"));
tr("Open File"), "/media/portable/src/github/SyntheticLidarScanner", tr("Image Files (*.vtp)"));
std::cout << "Got filename: " << fileName.toStdString() << std::endl;
if(fileName.toStdString().empty())
{
return;
}
OpenFile(fileName.toStdString());
}
void SyntheticLidarScannerWidget::on_btnHideBox_clicked()
{
std::cout << "Hiding box..." << std::endl;
this->ScannerStyle->BoxWidget->EnabledOff();
}
void SyntheticLidarScannerWidget::on_btnShowBox_clicked()
{
std::cout << "Hiding box..." << std::endl;
this->ScannerStyle->BoxWidget->EnabledOn();
}
|
#include "gimbal_protocol_v2.h"
#include "gimbal_impl.h"
#include "global_include.h"
#include <functional>
#include <cmath>
namespace mavsdk {
GimbalProtocolV2::GimbalProtocolV2(
SystemImpl& system_impl,
const mavlink_gimbal_manager_information_t& information,
uint8_t gimbal_manager_sysid,
uint8_t gimbal_manager_compid) :
GimbalProtocolBase(system_impl),
_gimbal_device_id(information.gimbal_device_id),
_gimbal_manager_sysid(gimbal_manager_sysid),
_gimbal_manager_compid(gimbal_manager_compid)
{}
void GimbalProtocolV2::process_gimbal_manager_status(const mavlink_message_t& message)
{
Gimbal::ControlMode new_control_mode;
mavlink_gimbal_manager_status_t gimbal_manager_status;
mavlink_msg_gimbal_manager_status_decode(&message, &gimbal_manager_status);
const int primary_control_sysid = gimbal_manager_status.primary_control_sysid;
const int primary_control_compid = gimbal_manager_status.primary_control_compid;
const int secondary_control_sysid = gimbal_manager_status.secondary_control_sysid;
const int secondary_control_compid = gimbal_manager_status.secondary_control_compid;
if (primary_control_sysid == static_cast<int>(_system_impl.get_own_system_id()) &&
primary_control_compid == static_cast<int>(_system_impl.get_own_component_id())) {
new_control_mode = Gimbal::ControlMode::Primary;
} else if (
secondary_control_sysid == static_cast<int>(_system_impl.get_own_system_id()) &&
secondary_control_compid == static_cast<int>(_system_impl.get_own_component_id())) {
new_control_mode = Gimbal::ControlMode::Secondary;
} else {
new_control_mode = Gimbal::ControlMode::None;
}
_current_control_status.control_mode = new_control_mode;
_current_control_status.sysid_primary_control = primary_control_sysid;
_current_control_status.compid_primary_control = primary_control_compid;
_current_control_status.sysid_secondary_control = secondary_control_sysid;
_current_control_status.compid_secondary_control = secondary_control_compid;
if (_control_callback) {
auto temp_status = _current_control_status;
auto temp_callback = _control_callback;
_system_impl.call_user_callback(
[temp_callback, temp_status]() { temp_callback(temp_status); });
}
}
Gimbal::Result GimbalProtocolV2::set_pitch_and_yaw(float pitch_deg, float yaw_deg)
{
const float roll_rad = 0.0f;
const float pitch_rad = to_rad_from_deg(pitch_deg);
const float yaw_rad = to_rad_from_deg(yaw_deg);
float quaternion[4];
mavlink_euler_to_quaternion(roll_rad, pitch_rad, yaw_rad, quaternion);
const uint32_t flags =
GIMBAL_MANAGER_FLAGS_ROLL_LOCK | GIMBAL_MANAGER_FLAGS_PITCH_LOCK |
((_gimbal_mode == Gimbal::GimbalMode::YawLock) ? GIMBAL_MANAGER_FLAGS_YAW_LOCK : 0);
mavlink_message_t message;
mavlink_msg_gimbal_manager_set_attitude_pack(
_system_impl.get_own_system_id(),
_system_impl.get_own_component_id(),
&message,
_gimbal_manager_sysid,
_gimbal_manager_compid,
flags,
_gimbal_device_id,
quaternion,
NAN,
NAN,
NAN);
return _system_impl.send_message(message) ? Gimbal::Result::Success : Gimbal::Result::Error;
}
void GimbalProtocolV2::set_pitch_and_yaw_async(
float pitch_deg, float yaw_deg, Gimbal::ResultCallback callback)
{
// Sending the message should be quick and we can just do that straighaway.
Gimbal::Result result = set_pitch_and_yaw(pitch_deg, yaw_deg);
if (callback) {
_system_impl.call_user_callback([callback, result]() { callback(result); });
}
}
Gimbal::Result
GimbalProtocolV2::set_pitch_rate_and_yaw_rate(float pitch_rate_deg_s, float yaw_rate_deg_s)
{
const uint32_t flags =
GIMBAL_MANAGER_FLAGS_ROLL_LOCK | GIMBAL_MANAGER_FLAGS_PITCH_LOCK |
((_gimbal_mode == Gimbal::GimbalMode::YawLock) ? GIMBAL_MANAGER_FLAGS_YAW_LOCK : 0);
const float quaternion[4] = {NAN, NAN, NAN, NAN};
mavlink_message_t message;
mavlink_msg_gimbal_manager_set_attitude_pack(
_system_impl.get_own_system_id(),
_system_impl.get_own_component_id(),
&message,
_gimbal_manager_sysid,
_gimbal_manager_compid,
flags,
_gimbal_device_id,
quaternion,
0.0f,
to_rad_from_deg(pitch_rate_deg_s),
to_rad_from_deg(yaw_rate_deg_s));
return _system_impl.send_message(message) ? Gimbal::Result::Success : Gimbal::Result::Error;
}
void GimbalProtocolV2::set_pitch_rate_and_yaw_rate_async(
float pitch_rate_deg_s, float yaw_rate_deg_s, Gimbal::ResultCallback callback)
{
// Sending the message should be quick and we can just do that straighaway.
Gimbal::Result result = set_pitch_rate_and_yaw_rate(pitch_rate_deg_s, yaw_rate_deg_s);
if (callback) {
auto temp_callback = callback;
_system_impl.call_user_callback([temp_callback, result]() { temp_callback(result); });
}
}
Gimbal::Result GimbalProtocolV2::set_mode(const Gimbal::GimbalMode gimbal_mode)
{
_gimbal_mode = gimbal_mode;
return Gimbal::Result::Success;
}
void GimbalProtocolV2::set_mode_async(
const Gimbal::GimbalMode gimbal_mode, Gimbal::ResultCallback callback)
{
_gimbal_mode = gimbal_mode;
if (callback) {
_system_impl.call_user_callback([callback]() { callback(Gimbal::Result::Success); });
}
}
Gimbal::Result
GimbalProtocolV2::set_roi_location(double latitude_deg, double longitude_deg, float altitude_m)
{
MavlinkCommandSender::CommandInt command{};
command.command = MAV_CMD_DO_SET_ROI_LOCATION;
command.params.x = static_cast<int32_t>(std::round(latitude_deg * 1e7));
command.params.y = static_cast<int32_t>(std::round(longitude_deg * 1e7));
command.params.z = altitude_m;
command.target_system_id = _gimbal_manager_sysid;
command.target_component_id = _gimbal_manager_compid;
return GimbalImpl::gimbal_result_from_command_result(_system_impl.send_command(command));
}
void GimbalProtocolV2::set_roi_location_async(
double latitude_deg, double longitude_deg, float altitude_m, Gimbal::ResultCallback callback)
{
MavlinkCommandSender::CommandInt command{};
command.command = MAV_CMD_DO_SET_ROI_LOCATION;
command.params.x = static_cast<int32_t>(std::round(latitude_deg * 1e7));
command.params.y = static_cast<int32_t>(std::round(longitude_deg * 1e7));
command.params.z = altitude_m;
command.target_system_id = _gimbal_manager_sysid;
command.target_component_id = _gimbal_manager_compid;
_system_impl.send_command_async(
command, [this, callback](MavlinkCommandSender::Result result, float) {
GimbalImpl::receive_command_result(result, callback);
});
}
Gimbal::Result GimbalProtocolV2::take_control(Gimbal::ControlMode control_mode)
{
auto prom = std::promise<Gimbal::Result>();
auto fut = prom.get_future();
take_control_async(control_mode, [&prom](Gimbal::Result result) { prom.set_value(result); });
return fut.get();
}
void GimbalProtocolV2::take_control_async(
Gimbal::ControlMode control_mode, Gimbal::ResultCallback callback)
{
if (control_mode == Gimbal::ControlMode::None) {
release_control_async(callback);
return;
} else if (control_mode == Gimbal::ControlMode::Secondary) {
_system_impl.call_user_callback([callback]() { callback(Gimbal::Result::Unsupported); });
LogErr() << "Gimbal secondary control is not implemented yet!";
return;
}
float own_sysid = _system_impl.get_own_system_id();
float own_compid = _system_impl.get_own_component_id();
MavlinkCommandSender::CommandLong command{};
command.command = MAV_CMD_DO_GIMBAL_MANAGER_CONFIGURE;
command.params.param1 =
control_mode == Gimbal::ControlMode::Primary ? own_sysid : -3.0f; // sysid primary control
command.params.param2 =
control_mode == Gimbal::ControlMode::Primary ? own_compid : -3.0f; // compid primary control
command.params.param3 =
control_mode == Gimbal::ControlMode::Primary ? own_sysid : -3.0f; // sysid secondary control
command.params.param4 = control_mode == Gimbal::ControlMode::Primary ?
own_compid :
-3.0f; // compid secondary control
command.params.param7 = _gimbal_device_id;
command.target_system_id = _gimbal_manager_sysid;
command.target_component_id = _gimbal_manager_compid;
_system_impl.send_command_async(
command, [this, callback](MavlinkCommandSender::Result result, float) {
GimbalImpl::receive_command_result(result, callback);
});
}
Gimbal::Result GimbalProtocolV2::release_control()
{
auto prom = std::promise<Gimbal::Result>();
auto fut = prom.get_future();
release_control_async([&prom](Gimbal::Result result) { prom.set_value(result); });
return fut.get();
}
void GimbalProtocolV2::release_control_async(Gimbal::ResultCallback callback)
{
MavlinkCommandSender::CommandLong command{};
command.command = MAV_CMD_DO_GIMBAL_MANAGER_CONFIGURE;
command.params.param1 = -3.0f; // sysid primary control
command.params.param2 = -3.0f; // compid primary control
command.params.param3 = -3.0f; // sysid secondary control
command.params.param4 = -3.0f; // compid secondary control
command.params.param7 = _gimbal_device_id;
command.target_system_id = _gimbal_manager_sysid;
command.target_component_id = _gimbal_manager_compid;
_system_impl.send_command_async(
command, [this, callback](MavlinkCommandSender::Result result, float) {
GimbalImpl::receive_command_result(result, callback);
});
}
Gimbal::ControlStatus GimbalProtocolV2::control()
{
auto prom = std::promise<Gimbal::ControlStatus>();
auto fut = prom.get_future();
control_async(
[&prom](Gimbal::ControlStatus control_status) { prom.set_value(control_status); });
return fut.get();
}
void GimbalProtocolV2::control_async(Gimbal::ControlCallback callback)
{
if (!_is_mavlink_manager_status_registered) {
_is_mavlink_manager_status_registered = true;
_system_impl.register_mavlink_message_handler(
MAVLINK_MSG_ID_GIMBAL_MANAGER_STATUS,
std::bind(
&GimbalProtocolV2::process_gimbal_manager_status, this, std::placeholders::_1),
this);
}
_control_callback = callback;
_system_impl.call_user_callback([this, callback]() { callback(_current_control_status); });
}
} // namespace mavsdk
|
#include <iostream>
#include <vector>
#include <stdlib.h>
#include <stdint.h>
#include <assert.h>
#include <pthread.h>
#include "BufferManager/BufferManager.hpp"
using namespace std;
BufferManager* bm;
unsigned pagesOnDisk;
unsigned pagesInRAM;
unsigned threadCount;
unsigned* threadSeed;
volatile bool stop=false;
unsigned randomPage(unsigned threadNum) {
// pseudo-gaussian, causes skewed access pattern
unsigned page=0;
for (unsigned i=0; i<20; i++)
page+=rand_r(&threadSeed[threadNum])%pagesOnDisk;
return page/20;
}
static void* scan(void *arg) {
// scan all pages and check if the counters are not decreasing
vector<unsigned> counters(pagesOnDisk, 0);
while (!stop) {
unsigned start = random()%(pagesOnDisk-10);
for (unsigned page=start; page<start+10; page++) {
BufferFrame& bf = bm->fixPage(page, false);
unsigned newcount = reinterpret_cast<unsigned*>(bf.getData())[0];
assert(counters[page]<=newcount);
counters[page]=newcount;
bm->unfixPage(bf, false);
}
}
return NULL;
}
static void* readWrite(void *arg) {
// read or write random pages
uintptr_t threadNum = reinterpret_cast<uintptr_t>(arg);
uintptr_t count = 0;
for (unsigned i=0; i<100000/threadCount; i++) {
bool isWrite = rand_r(&threadSeed[threadNum])%128<10;
BufferFrame& bf = bm->fixPage(randomPage(threadNum), isWrite);
if (isWrite) {
count++;
reinterpret_cast<unsigned*>(bf.getData())[0]++;
}
bm->unfixPage(bf, isWrite);
}
return reinterpret_cast<void*>(count);
}
int main(int argc, char** argv) {
if (argc==4) {
pagesOnDisk = atoi(argv[1]);
pagesInRAM = atoi(argv[2]);
threadCount = atoi(argv[3]);
} else {
cerr << "usage: " << argv[0] << " <pagesOnDisk> <pagesInRAM> <threads>" << endl;
exit(1);
}
threadSeed = new unsigned[threadCount];
for (unsigned i=0; i<threadCount; i++)
threadSeed[i] = i*97134;
bm = new BufferManager(pagesInRAM);
vector<pthread_t> threads(threadCount);
pthread_attr_t pattr;
pthread_attr_init(&pattr);
// set all counters to 0
for (unsigned i=0; i<pagesOnDisk; i++) {
BufferFrame& bf = bm->fixPage(i, true);
reinterpret_cast<unsigned*>(bf.getData())[0]=0;
bm->unfixPage(bf, true);
}
// start scan thread
pthread_t scanThread;
pthread_create(&scanThread, &pattr, scan, NULL);
// start read/write threads
for (unsigned i=0; i<threadCount; i++)
pthread_create(&threads[i], &pattr, readWrite, reinterpret_cast<void*>(i));
// wait for read/write threads
unsigned totalCount = 0;
for (unsigned i=0; i<threadCount; i++) {
void *ret;
pthread_join(threads[i], &ret);
totalCount+=reinterpret_cast<uintptr_t>(ret);
}
// wait for scan thread
stop=true;
pthread_join(scanThread, NULL);
// restart buffer manager
delete bm;
bm = new BufferManager(pagesInRAM);
// check counter
unsigned totalCountOnDisk = 0;
for (unsigned i=0; i<pagesOnDisk; i++) {
BufferFrame& bf = bm->fixPage(i,false);
totalCountOnDisk+=reinterpret_cast<unsigned*>(bf.getData())[0];
bm->unfixPage(bf, false);
}
if (totalCount==totalCountOnDisk) {
cout << "test successful" << endl;
delete bm;
return 0;
} else {
cerr << "error: expected " << totalCount << " but got " << totalCountOnDisk << endl;
delete bm;
return 1;
}
}
|
/************************************************************************/
/* namespace std */
/************************************************************************/
#include <ctime>
#include <vector>
#include <string>
#include <fstream>
#include <iostream>
#include <sstream>
#include <queue>
#include <set>
#include <map>
using std::map;
using std::vector;
using std::string;
using std::ofstream;
using std::string;
using std::exception;
using std::to_string;
using std::cout;
using std::endl;
|
/******************************************************************************
* Copyright 2019 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/planning/tasks/deciders/path_assessment_decider.h"
#include <algorithm>
#include <cmath>
#include <limits>
#include "modules/common/configs/vehicle_config_helper.h"
#include "modules/common/proto/pnc_point.pb.h"
#include "modules/map/hdmap/hdmap_util.h"
#include "modules/planning/common/planning_context.h"
#include "modules/planning/tasks/deciders/path_bounds_decider.h"
#include "modules/planning/tasks/deciders/path_decider_obstacle_utils.h"
namespace apollo {
namespace planning {
using apollo::common::ErrorCode;
using apollo::common::Status;
using apollo::common::VehicleConfigHelper;
using apollo::common::math::Box2d;
using apollo::common::math::NormalizeAngle;
using apollo::common::math::Polygon2d;
using apollo::common::math::Vec2d;
using apollo::hdmap::HDMapUtil;
namespace {
// PointDecision contains (s, PathPointType, distance to closest obstacle).
using PathPointDecision = std::tuple<double, PathData::PathPointType, double>;
constexpr double kMinObstacleArea = 1e-4;
} // namespace
PathAssessmentDecider::PathAssessmentDecider(const TaskConfig& config)
: Decider(config) {}
Status PathAssessmentDecider::Process(
Frame* const frame, ReferenceLineInfo* const reference_line_info) {
// Sanity checks.
CHECK_NOTNULL(frame);
CHECK_NOTNULL(reference_line_info);
const auto& candidate_path_data = reference_line_info->GetCandidatePathData();
if (candidate_path_data.empty()) {
ADEBUG << "Candidate path data is empty.";
} else {
ADEBUG << "There are " << candidate_path_data.size() << " candidate paths";
}
// 1. Remove invalid path.
std::vector<PathData> valid_path_data;
for (const auto& curr_path_data : candidate_path_data) {
// RecordDebugInfo(curr_path_data, curr_path_data.path_label(),
// reference_line_info);
if (curr_path_data.path_label().find("fallback") != std::string::npos) {
if (IsValidFallbackPath(*reference_line_info, curr_path_data)) {
valid_path_data.push_back(curr_path_data);
}
} else {
if (IsValidRegularPath(*reference_line_info, curr_path_data)) {
valid_path_data.push_back(curr_path_data);
}
}
}
// 2. Analyze and add important info for speed decider to use.
for (auto& curr_path_data : valid_path_data) {
if (curr_path_data.path_label().find("fallback") != std::string::npos) {
continue;
}
SetPathInfo(*reference_line_info, &curr_path_data);
// Trim all the lane-borrowing paths so that it ends with an in-lane
// position.
TrimTailingOutLanePoints(&curr_path_data);
// TODO(jiacheng): remove empty path_data.
// RecordDebugInfo(curr_path_data, curr_path_data.path_label(),
// reference_line_info);
ADEBUG << "For " << curr_path_data.path_label() << ", "
<< "path length = " << curr_path_data.frenet_frame_path().size();
}
// If there is no valid path_data, exit.
if (valid_path_data.empty()) {
const std::string msg = "Neither regular nor fallback path is valid.";
AERROR << msg;
return Status(ErrorCode::PLANNING_ERROR, msg);
}
ADEBUG << "There are " << valid_path_data.size() << " valid path data.";
// 3. Pick the optimal path.
std::sort(valid_path_data.begin(), valid_path_data.end(),
[](const PathData& lhs, const PathData& rhs) {
ADEBUG << "Comparing " << lhs.path_label() << " and "
<< rhs.path_label();
// Empty path_data is never the larger one.
if (lhs.Empty()) {
ADEBUG << "LHS is empty.";
return false;
}
if (rhs.Empty()) {
ADEBUG << "RHS is empty.";
return true;
}
// Regular path goes before fallback path.
bool lhs_is_regular =
lhs.path_label().find("regular") != std::string::npos;
bool rhs_is_regular =
rhs.path_label().find("regular") != std::string::npos;
if (lhs_is_regular != rhs_is_regular) {
return lhs_is_regular;
}
// For two lane-borrow directions, based on ADC's position,
// select the more convenient one.
if ((lhs.path_label().find("left") != std::string::npos &&
rhs.path_label().find("right") != std::string::npos) ||
(lhs.path_label().find("right") != std::string::npos &&
rhs.path_label().find("left") != std::string::npos)) {
double adc_l = lhs.frenet_frame_path().front().l();
if (adc_l < -1.0 || adc_l > 1.0) {
if (adc_l < -1.0) {
return lhs.path_label().find("right") != std::string::npos;
} else {
return lhs.path_label().find("left") != std::string::npos;
}
}
}
// Select longer path.
// If roughly same length, then select self-lane path.
bool lhs_on_selflane =
lhs.path_label().find("self") != std::string::npos;
bool rhs_on_selflane =
rhs.path_label().find("self") != std::string::npos;
constexpr double kSelfPathLengthComparisonTolerance = 15.0;
constexpr double kNeighborPathLengthComparisonTolerance = 25.0;
double lhs_path_length = lhs.frenet_frame_path().back().s();
double rhs_path_length = rhs.frenet_frame_path().back().s();
if (lhs_on_selflane || rhs_on_selflane) {
if (std::fabs(lhs_path_length - rhs_path_length) >
kSelfPathLengthComparisonTolerance) {
return lhs_path_length > rhs_path_length;
} else {
return lhs_on_selflane;
}
} else {
if (std::fabs(lhs_path_length - rhs_path_length) >
kNeighborPathLengthComparisonTolerance) {
return lhs_path_length > rhs_path_length;
}
}
// If roughly same length, and must borrow neighbor lane,
// then prefer to borrow forward lane rather than reverse lane.
int lhs_on_reverse =
ContainsOutOnReverseLane(lhs.path_point_decision_guide());
int rhs_on_reverse =
ContainsOutOnReverseLane(rhs.path_point_decision_guide());
// TODO(jiacheng): make this a flag.
if (std::abs(lhs_on_reverse - rhs_on_reverse) > 6) {
return lhs_on_reverse < rhs_on_reverse;
}
// If same length, both neighbor lane are forward,
// then select the one that returns back to in-lane earlier.
constexpr double kBackToSelfLaneComparisonTolerance = 20.0;
int lhs_back_idx =
GetBackToInLaneIndex(lhs.path_point_decision_guide());
int rhs_back_idx =
GetBackToInLaneIndex(rhs.path_point_decision_guide());
double lhs_back_s = lhs.frenet_frame_path()[lhs_back_idx].s();
double rhs_back_s = rhs.frenet_frame_path()[rhs_back_idx].s();
if (std::fabs(lhs_back_s - rhs_back_s) >
kBackToSelfLaneComparisonTolerance) {
return lhs_back_idx < rhs_back_idx;
}
// If same length, both forward, back to inlane at same time,
// select the left one to side-pass.
bool lhs_on_leftlane =
lhs.path_label().find("left") != std::string::npos;
bool rhs_on_leftlane =
rhs.path_label().find("left") != std::string::npos;
if (lhs_on_leftlane != rhs_on_leftlane) {
ADEBUG << "Select left lane over right lane.";
return lhs_on_leftlane;
}
// Otherwise, they are the same path, lhs is not < rhs.
return false;
});
ADEBUG << "There are " << valid_path_data.size() << " path(s).";
ADEBUG << "Using " << valid_path_data.front().path_label() << " path.";
if (valid_path_data.front().path_label().find("fallback") !=
std::string::npos) {
FLAGS_static_decision_nudge_l_buffer = 0.8;
} else {
FLAGS_static_decision_nudge_l_buffer = 0.3;
}
*(reference_line_info->mutable_path_data()) = valid_path_data.front();
reference_line_info->SetBlockingObstacleId(
valid_path_data.front().blocking_obstacle_id());
std::vector<PathData> new_candidate_path_data;
for (const auto& curr_path_data : valid_path_data) {
if (!curr_path_data.Empty()) {
new_candidate_path_data.push_back(curr_path_data);
}
}
reference_line_info->SetCandidatePathData(new_candidate_path_data);
if (!(reference_line_info->GetBlockingObstacleId()).empty()) {
if (PlanningContext::Instance()->front_static_obstacle_cycle_counter() <
0) {
PlanningContext::Instance()->ResetFrontStaticObstacleCycleCounter();
}
PlanningContext::Instance()->set_front_static_obstacle_id(
reference_line_info->GetBlockingObstacleId());
PlanningContext::Instance()->IncrementFrontStaticObstacleCycleCounter();
} else {
PlanningContext::Instance()->ResetFrontStaticObstacleCycleCounter();
}
if (reference_line_info->path_data().path_label().find("self") !=
std::string::npos &&
std::get<1>(reference_line_info->path_data()
.path_point_decision_guide()
.front()) == PathData::PathPointType::IN_LANE) {
if (PlanningContext::Instance()->able_to_use_self_lane_counter() < 0) {
PlanningContext::Instance()->ResetAbleToUseSelfLaneCounter();
}
PlanningContext::Instance()->IncrementAbleToUseSelfLaneCounter();
} else {
PlanningContext::Instance()->ResetAbleToUseSelfLaneCounter();
}
// Plot the path in simulator for debug purpose.
RecordDebugInfo(reference_line_info->path_data(), "Planning PathData",
reference_line_info);
return Status::OK();
}
bool PathAssessmentDecider::IsValidRegularPath(
const ReferenceLineInfo& reference_line_info, const PathData& path_data) {
// Basic sanity checks.
if (path_data.Empty()) {
ADEBUG << path_data.path_label() << ": path data is empty.";
return false;
}
// Check if the path is greatly off the reference line.
if (IsGreatlyOffReferenceLine(path_data)) {
ADEBUG << path_data.path_label() << ": ADC is greatly off reference line.";
return false;
}
// Check if the path is greatly off the road.
if (IsGreatlyOffRoad(reference_line_info, path_data)) {
ADEBUG << path_data.path_label() << ": ADC is greatly off road.";
return false;
}
// Check if there is any collision.
if (IsCollidingWithStaticObstacles(reference_line_info, path_data)) {
ADEBUG << path_data.path_label() << ": ADC has collision.";
return false;
}
return true;
}
bool PathAssessmentDecider::IsValidFallbackPath(
const ReferenceLineInfo& reference_line_info, const PathData& path_data) {
// Basic sanity checks.
if (path_data.Empty()) {
ADEBUG << "Fallback Path: path data is empty.";
return false;
}
// Check if the path is greatly off the reference line.
if (IsGreatlyOffReferenceLine(path_data)) {
ADEBUG << "Fallback Path: ADC is greatly off reference line.";
return false;
}
// Check if the path is greatly off the road.
if (IsGreatlyOffRoad(reference_line_info, path_data)) {
ADEBUG << "Fallback Path: ADC is greatly off road.";
return false;
}
return true;
}
void PathAssessmentDecider::SetPathInfo(
const ReferenceLineInfo& reference_line_info, PathData* const path_data) {
// Go through every path_point, and label its:
// - in-lane/out-of-lane info
// - distance to the closest obstacle.
std::vector<PathPointDecision> path_decision;
InitPathPointDecision(*path_data, &path_decision);
SetPathPointType(reference_line_info, *path_data, &path_decision);
SetObstacleDistance(reference_line_info, *path_data, &path_decision);
path_data->SetPathPointDecisionGuide(path_decision);
}
void PathAssessmentDecider::TrimTailingOutLanePoints(
PathData* const path_data) {
// Don't trim self-lane path or fallback path.
if (path_data->path_label().find("fallback") != std::string::npos ||
path_data->path_label().find("self") != std::string::npos) {
return;
}
// Trim.
ADEBUG << "Trimming " << path_data->path_label();
auto frenet_path = path_data->frenet_frame_path();
auto path_point_decision = path_data->path_point_decision_guide();
CHECK_EQ(frenet_path.size(), path_point_decision.size());
while (!path_point_decision.empty() &&
std::get<1>(path_point_decision.back()) !=
PathData::PathPointType::IN_LANE) {
if (std::get<1>(path_point_decision.back()) ==
PathData::PathPointType::OUT_ON_FORWARD_LANE) {
ADEBUG << "Trimming out forward lane point";
} else if (std::get<1>(path_point_decision.back()) ==
PathData::PathPointType::OUT_ON_REVERSE_LANE) {
ADEBUG << "Trimming out reverse lane point";
} else {
ADEBUG << "Trimming unknown lane point";
}
frenet_path.pop_back();
path_point_decision.pop_back();
}
path_data->SetFrenetPath(frenet_path);
path_data->SetPathPointDecisionGuide(path_point_decision);
}
bool PathAssessmentDecider::IsGreatlyOffReferenceLine(
const PathData& path_data) {
constexpr double kOffReferenceLineThreshold = 20.0;
const auto& frenet_path = path_data.frenet_frame_path();
for (const auto& frenet_path_point : frenet_path) {
if (std::fabs(frenet_path_point.l()) > kOffReferenceLineThreshold) {
ADEBUG << "Greatly off reference line at s = " << frenet_path_point.s()
<< ", with l = " << frenet_path_point.l();
return true;
}
}
return false;
}
bool PathAssessmentDecider::IsGreatlyOffRoad(
const ReferenceLineInfo& reference_line_info, const PathData& path_data) {
constexpr double kOffRoadThreshold = 10.0;
const auto& frenet_path = path_data.frenet_frame_path();
for (const auto& frenet_path_point : frenet_path) {
double road_left_width = 0.0;
double road_right_width = 0.0;
if (reference_line_info.reference_line().GetRoadWidth(
frenet_path_point.s(), &road_left_width, &road_right_width)) {
if (frenet_path_point.l() > road_left_width + kOffRoadThreshold ||
frenet_path_point.l() < -road_right_width - kOffRoadThreshold) {
ADEBUG << "Greatly off-road at s = " << frenet_path_point.s()
<< ", with l = " << frenet_path_point.l();
return true;
}
}
}
return false;
}
bool PathAssessmentDecider::IsCollidingWithStaticObstacles(
const ReferenceLineInfo& reference_line_info, const PathData& path_data) {
// Get all obstacles and convert them into frenet-frame polygons.
std::vector<Polygon2d> obstacle_polygons;
const auto& indexed_obstacles =
reference_line_info.path_decision().obstacles();
for (const auto* obstacle : indexed_obstacles.Items()) {
// Filter out unrelated obstacles.
if (!IsWithinPathDeciderScopeObstacle(*obstacle)) {
continue;
}
// Ignore too small obstacles.
const auto& obstacle_sl = obstacle->PerceptionSLBoundary();
if ((obstacle_sl.end_s() - obstacle_sl.start_s()) *
(obstacle_sl.end_l() - obstacle_sl.start_l()) <
kMinObstacleArea) {
continue;
}
// Convert into polygon and save it.
obstacle_polygons.push_back(
Polygon2d({Vec2d(obstacle_sl.start_s(), obstacle_sl.start_l()),
Vec2d(obstacle_sl.start_s(), obstacle_sl.end_l()),
Vec2d(obstacle_sl.end_s(), obstacle_sl.end_l()),
Vec2d(obstacle_sl.end_s(), obstacle_sl.start_l())}));
}
// Go through all the four corner points at every path pt, check collision.
for (size_t i = 0; i < path_data.discretized_path().size(); ++i) {
if (path_data.frenet_frame_path().back().s() -
path_data.frenet_frame_path()[i].s() <
kNumExtraTailBoundPoint * kPathBoundsDeciderResolution) {
break;
}
const auto& path_point = path_data.discretized_path()[i];
// Get the four corner points ABCD of ADC at every path point.
const auto& vehicle_box =
common::VehicleConfigHelper::Instance()->GetBoundingBox(path_point);
std::vector<Vec2d> ABCDpoints = vehicle_box.GetAllCorners();
for (const auto& corner_point : ABCDpoints) {
// For each corner point, project it onto reference_line
common::SLPoint curr_point_sl;
if (!reference_line_info.reference_line().XYToSL(corner_point,
&curr_point_sl)) {
AERROR << "Failed to get the projection from point onto "
"reference_line";
return true;
}
auto curr_point = Vec2d(curr_point_sl.s(), curr_point_sl.l());
// Check if it's in any polygon of other static obstacles.
for (const auto& obstacle_polygon : obstacle_polygons) {
if (obstacle_polygon.IsPointIn(curr_point)) {
ADEBUG << "ADC is colliding with obstacle at path s = "
<< path_point.s();
return true;
}
}
}
}
return false;
}
void PathAssessmentDecider::InitPathPointDecision(
const PathData& path_data,
std::vector<PathPointDecision>* const path_point_decision) {
// Sanity checks.
CHECK_NOTNULL(path_point_decision);
path_point_decision->clear();
// Go through every path point in path data, and initialize a
// corresponding path point decision.
for (const auto& frenet_path_point : path_data.frenet_frame_path()) {
path_point_decision->emplace_back(frenet_path_point.s(),
PathData::PathPointType::UNKNOWN,
std::numeric_limits<double>::max());
}
}
void PathAssessmentDecider::SetPathPointType(
const ReferenceLineInfo& reference_line_info, const PathData& path_data,
std::vector<PathPointDecision>* const path_point_decision) {
// Sanity checks.
CHECK_NOTNULL(path_point_decision);
// Go through every path_point, and add in-lane/out-of-lane info.
const auto& discrete_path = path_data.discretized_path();
const auto& vehicle_config =
common::VehicleConfigHelper::Instance()->GetConfig();
const double ego_length = vehicle_config.vehicle_param().length();
const double ego_width = vehicle_config.vehicle_param().width();
const double ego_back_to_center =
vehicle_config.vehicle_param().back_edge_to_center();
const double ego_center_shift_distance =
ego_length / 2.0 - ego_back_to_center;
bool is_prev_point_out_lane = false;
for (size_t i = 0; i < discrete_path.size(); ++i) {
const auto& rear_center_path_point = discrete_path[i];
const double ego_theta = rear_center_path_point.theta();
Box2d ego_box({rear_center_path_point.x(), rear_center_path_point.y()},
ego_theta, ego_length, ego_width);
Vec2d shift_vec{ego_center_shift_distance * std::cos(ego_theta),
ego_center_shift_distance * std::sin(ego_theta)};
ego_box.Shift(shift_vec);
SLBoundary ego_sl_boundary;
reference_line_info.reference_line().GetSLBoundary(ego_box,
&ego_sl_boundary);
double lane_left_width = 0.0;
double lane_right_width = 0.0;
double middle_s =
(ego_sl_boundary.start_s() + ego_sl_boundary.end_s()) / 2.0;
if (reference_line_info.reference_line().GetLaneWidth(
middle_s, &lane_left_width, &lane_right_width)) {
// Rough sl boundary estimate using single point lane width
double back_to_inlane_extra_buffer = 0.5;
double in_and_out_lane_hysteresis_buffer =
is_prev_point_out_lane ? back_to_inlane_extra_buffer : 0.0;
if (ego_sl_boundary.end_l() >
lane_left_width + in_and_out_lane_hysteresis_buffer ||
ego_sl_boundary.start_l() <
-lane_right_width - in_and_out_lane_hysteresis_buffer) {
if (path_data.path_label().find("reverse") != std::string::npos) {
std::get<1>((*path_point_decision)[i]) =
PathData::PathPointType::OUT_ON_REVERSE_LANE;
} else if (path_data.path_label().find("forward") !=
std::string::npos) {
std::get<1>((*path_point_decision)[i]) =
PathData::PathPointType::OUT_ON_FORWARD_LANE;
} else {
std::get<1>((*path_point_decision)[i]) =
PathData::PathPointType::UNKNOWN;
}
if (!is_prev_point_out_lane) {
if (ego_sl_boundary.end_l() >
lane_left_width + back_to_inlane_extra_buffer ||
ego_sl_boundary.start_l() <
-lane_right_width - back_to_inlane_extra_buffer) {
is_prev_point_out_lane = true;
}
}
} else {
// The path point is within the reference_line's lane.
std::get<1>((*path_point_decision)[i]) =
PathData::PathPointType::IN_LANE;
if (is_prev_point_out_lane) {
if (ego_sl_boundary.end_l() > lane_left_width ||
ego_sl_boundary.start_l() < -lane_right_width) {
is_prev_point_out_lane = false;
}
}
}
} else {
AERROR << "reference line not ready when setting path point guide";
return;
}
}
}
void PathAssessmentDecider::SetObstacleDistance(
const ReferenceLineInfo& reference_line_info, const PathData& path_data,
std::vector<PathPointDecision>* const path_point_decision) {
// Sanity checks
CHECK_NOTNULL(path_point_decision);
// Get all obstacles and convert them into frenet-frame polygons.
std::vector<Polygon2d> obstacle_polygons;
const auto& indexed_obstacles =
reference_line_info.path_decision().obstacles();
for (const auto* obstacle : indexed_obstacles.Items()) {
// Filter out unrelated obstacles.
if (!IsWithinPathDeciderScopeObstacle(*obstacle)) {
continue;
}
// Convert into polygon and save it.
const auto& obstacle_box = obstacle->PerceptionBoundingBox();
if (obstacle_box.area() < kMinObstacleArea) {
continue;
}
obstacle_polygons.emplace_back(obstacle_box);
}
// Go through every path point, update closest obstacle info.
const auto& discrete_path = path_data.discretized_path();
for (size_t i = 0; i < discrete_path.size(); ++i) {
const auto& path_point = discrete_path[i];
// Get the bounding box of the vehicle at that point.
const auto& vehicle_box =
common::VehicleConfigHelper::Instance()->GetBoundingBox(path_point);
// Go through all the obstacle polygons, and update the min distance.
double min_distance_to_obstacles = std::numeric_limits<double>::max();
for (const auto& obstacle_polygon : obstacle_polygons) {
double distance_to_vehicle = obstacle_polygon.DistanceTo(vehicle_box);
min_distance_to_obstacles =
std::min(min_distance_to_obstacles, distance_to_vehicle);
}
std::get<2>((*path_point_decision)[i]) = min_distance_to_obstacles;
}
}
void PathAssessmentDecider::RecordDebugInfo(
const PathData& path_data, const std::string& debug_name,
ReferenceLineInfo* const reference_line_info) {
const auto& path_points = path_data.discretized_path();
auto* ptr_optimized_path =
reference_line_info->mutable_debug()->mutable_planning_data()->add_path();
ptr_optimized_path->set_name(debug_name);
ptr_optimized_path->mutable_path_point()->CopyFrom(
{path_points.begin(), path_points.end()});
}
int ContainsOutOnReverseLane(
const std::vector<PathPointDecision>& path_point_decision) {
int ret = 0;
for (const auto& curr_decision : path_point_decision) {
if (std::get<1>(curr_decision) ==
PathData::PathPointType::OUT_ON_REVERSE_LANE) {
++ret;
}
}
return ret;
}
int GetBackToInLaneIndex(
const std::vector<PathPointDecision>& path_point_decision) {
// CHECK(!path_point_decision.empty());
// CHECK(std::get<1>(path_point_decision.back()) ==
// PathData::PathPointType::IN_LANE);
for (int i = static_cast<int>(path_point_decision.size()) - 1; i >= 0; --i) {
if (std::get<1>(path_point_decision[i]) !=
PathData::PathPointType::IN_LANE) {
return i;
}
}
return 0;
}
} // namespace planning
} // namespace apollo
|
/*
==============================================================================
This is an automatically generated GUI class created by the Introjucer!
Be careful when adding custom code to these files, as only the code within
the "//[xyz]" and "//[/xyz]" sections will be retained when the file is loaded
and re-saved.
Created with Introjucer version: 4.1.0
------------------------------------------------------------------------------
The Introjucer is part of the JUCE library - "Jules' Utility Class Extensions"
Copyright (c) 2015 - ROLI Ltd.
==============================================================================
*/
//[Headers] You can add your own extra header files here...
namespace hise { using namespace juce;
//[/Headers]
#include "WavetableBody.h"
//[MiscUserDefs] You can add your own user definitions and misc code here...
//[/MiscUserDefs]
//==============================================================================
WavetableBody::WavetableBody (ProcessorEditor *p)
: ProcessorEditorBody(p)
{
//[Constructor_pre] You can add your own custom stuff here..
//[/Constructor_pre]
addAndMakeVisible (waveTableDisplay = new WavetableDisplayComponent (dynamic_cast<WavetableSynth*>(getProcessor())));
waveTableDisplay->setName ("new component");
addAndMakeVisible (fadeTimeLabel = new Label ("new label",
TRANS("Fade Time")));
fadeTimeLabel->setFont (Font ("Khmer UI", 13.00f, Font::plain));
fadeTimeLabel->setJustificationType (Justification::centredLeft);
fadeTimeLabel->setEditable (false, false, false);
fadeTimeLabel->setColour (Label::textColourId, Colours::white);
fadeTimeLabel->setColour (TextEditor::textColourId, Colours::black);
fadeTimeLabel->setColour (TextEditor::backgroundColourId, Colour (0x00000000));
addAndMakeVisible (voiceAmountLabel = new Label ("new label",
TRANS("Voice Amount")));
voiceAmountLabel->setFont (Font ("Khmer UI", 13.00f, Font::plain));
voiceAmountLabel->setJustificationType (Justification::centredLeft);
voiceAmountLabel->setEditable (false, false, false);
voiceAmountLabel->setColour (Label::textColourId, Colours::white);
voiceAmountLabel->setColour (TextEditor::textColourId, Colours::black);
voiceAmountLabel->setColour (TextEditor::backgroundColourId, Colour (0x00000000));
addAndMakeVisible (voiceAmountEditor = new Label ("new label",
TRANS("64")));
voiceAmountEditor->setFont (Font ("Khmer UI", 14.00f, Font::plain));
voiceAmountEditor->setJustificationType (Justification::centredLeft);
voiceAmountEditor->setEditable (true, true, false);
voiceAmountEditor->setColour (Label::backgroundColourId, Colour (0x38ffffff));
voiceAmountEditor->setColour (Label::outlineColourId, Colour (0x38ffffff));
voiceAmountEditor->setColour (TextEditor::textColourId, Colours::black);
voiceAmountEditor->setColour (TextEditor::backgroundColourId, Colour (0x00000000));
voiceAmountEditor->setColour (TextEditor::highlightColourId, Colour (0x407a0000));
voiceAmountEditor->addListener (this);
addAndMakeVisible (fadeTimeEditor = new Label ("new label",
TRANS("15 ms")));
fadeTimeEditor->setFont (Font ("Khmer UI", 14.00f, Font::plain));
fadeTimeEditor->setJustificationType (Justification::centredLeft);
fadeTimeEditor->setEditable (true, true, false);
fadeTimeEditor->setColour (Label::backgroundColourId, Colour (0x38ffffff));
fadeTimeEditor->setColour (Label::outlineColourId, Colour (0x38ffffff));
fadeTimeEditor->setColour (TextEditor::textColourId, Colours::black);
fadeTimeEditor->setColour (TextEditor::backgroundColourId, Colour (0x00000000));
fadeTimeEditor->setColour (TextEditor::highlightColourId, Colour (0x407a0000));
fadeTimeEditor->addListener (this);
addAndMakeVisible (component = new TableEditor (dynamic_cast<WavetableSynth*>(getProcessor())->getGainTable()));
component->setName ("new component");
addAndMakeVisible (hiqButton = new HiToggleButton ("HQ"));
hiqButton->setTooltip (TRANS("Enables HQ rendering mode (more CPU intensive)"));
hiqButton->addListener (this);
hiqButton->setColour (ToggleButton::textColourId, Colours::white);
//[UserPreSize]
fadeTimeLabel->setFont (GLOBAL_FONT());
voiceAmountLabel->setFont (GLOBAL_FONT());
voiceAmountEditor->setFont (GLOBAL_FONT());
fadeTimeEditor->setFont (GLOBAL_FONT());
hiqButton->setup(getProcessor(), WavetableSynth::HqMode, "HQ");
//[/UserPreSize]
setSize (800, 130);
//[Constructor] You can add your own custom stuff here..
h = getHeight();
//[/Constructor]
}
WavetableBody::~WavetableBody()
{
//[Destructor_pre]. You can add your own custom destruction code here..
//[/Destructor_pre]
waveTableDisplay = nullptr;
fadeTimeLabel = nullptr;
voiceAmountLabel = nullptr;
voiceAmountEditor = nullptr;
fadeTimeEditor = nullptr;
component = nullptr;
hiqButton = nullptr;
//[Destructor]. You can add your own custom destruction code here..
//[/Destructor]
}
//==============================================================================
void WavetableBody::paint (Graphics& g)
{
//[UserPrePaint] Add your own custom painting code here..
//[/UserPrePaint]
g.setColour (Colour (0x23ffffff));
g.drawRect (16, 0, getWidth() - 32, getHeight() - 16, 1);
g.setColour (Colour (0x52ffffff));
g.setFont (Font ("Arial", 24.00f, Font::bold));
g.drawText (TRANS("WAVETABLE"),
getWidth() - 24 - 200, 4, 200, 30,
Justification::centredRight, true);
//[UserPaint] Add your own custom painting code here..
//[/UserPaint]
}
void WavetableBody::resized()
{
//[UserPreResize] Add your own custom resize code here..
//[/UserPreResize]
waveTableDisplay->setBounds (32, 10, 160, 94);
fadeTimeLabel->setBounds (getWidth() - 33 - 79, 31, 79, 24);
voiceAmountLabel->setBounds (getWidth() - 109 - 79, 32, 79, 24);
voiceAmountEditor->setBounds (getWidth() - 115 - 68, 50, 68, 16);
fadeTimeEditor->setBounds (getWidth() - 56 - 51, 50, 51, 16);
component->setBounds (203, 10, getWidth() - 412, 91);
hiqButton->setBounds (getWidth() - 54 - 128, 72, 128, 32);
//[UserResized] Add your own custom resize handling here..
//[/UserResized]
}
void WavetableBody::labelTextChanged (Label* labelThatHasChanged)
{
//[UserlabelTextChanged_Pre]
//[/UserlabelTextChanged_Pre]
if (labelThatHasChanged == voiceAmountEditor)
{
//[UserLabelCode_voiceAmountEditor] -- add your label text handling code here..
//[/UserLabelCode_voiceAmountEditor]
}
else if (labelThatHasChanged == fadeTimeEditor)
{
//[UserLabelCode_fadeTimeEditor] -- add your label text handling code here..
//[/UserLabelCode_fadeTimeEditor]
}
//[UserlabelTextChanged_Post]
//[/UserlabelTextChanged_Post]
}
void WavetableBody::buttonClicked (Button* buttonThatWasClicked)
{
//[UserbuttonClicked_Pre]
//[/UserbuttonClicked_Pre]
if (buttonThatWasClicked == hiqButton)
{
//[UserButtonCode_hiqButton] -- add your button handler code here..
//[/UserButtonCode_hiqButton]
}
//[UserbuttonClicked_Post]
//[/UserbuttonClicked_Post]
}
//[MiscUserCode] You can add your own definitions of your custom methods or any other code here...
void WavetableDisplayComponent::timerCallback()
{
ModulatorSynthVoice *voice = dynamic_cast<ModulatorSynthVoice*>(synth->getVoice(0));
if (voice == nullptr) return;
ModulatorSynthSound *sound = dynamic_cast<ModulatorSynthSound*>(voice->getCurrentlyPlayingSound().get());
if (dynamic_cast<WavetableSound*>(sound) != nullptr)
{
WavetableSound *wavetableSound = dynamic_cast<WavetableSound*>(sound);
WavetableSynthVoice *wavetableVoice = dynamic_cast<WavetableSynthVoice*>(voice);
const int tableIndex = wavetableVoice->getCurrentTableIndex();
tableValues = wavetableSound->getWaveTableData(tableIndex);
tableLength = wavetableSound->getTableSize();
normalizeValue = 1.0f / wavetableSound->getMaxLevel();
repaint();
}
else if (!isDisplayForWavetableSynth())
{
tableValues = dynamic_cast<SineSynth*>(synth)->getSaturatedTableValues();
tableLength = 128;
normalizeValue = 1.0f;
repaint();
}
else
{
tableValues = nullptr;
repaint();
}
}
//[/MiscUserCode]
//==============================================================================
#if 0
/* -- Introjucer information section --
This is where the Introjucer stores the metadata that describe this GUI layout, so
make changes in here at your peril!
BEGIN_JUCER_METADATA
<JUCER_COMPONENT documentType="Component" className="WavetableBody" componentName=""
parentClasses="public ProcessorEditorBody" constructorParams="ProcessorEditor *p"
variableInitialisers="ProcessorEditorBody(p)" snapPixels="8"
snapActive="0" snapShown="1" overlayOpacity="0.330" fixedSize="1"
initialWidth="800" initialHeight="130">
<BACKGROUND backgroundColour="ffffff">
<RECT pos="16 0 32M 16M" fill="solid: 43a52a" hasStroke="1" stroke="1, mitered, butt"
strokeColour="solid: 23ffffff"/>
<TEXT pos="24Rr 4 200 30" fill="solid: 52ffffff" hasStroke="0" text="WAVETABLE"
fontname="Arial" fontsize="24" bold="1" italic="0" justification="34"/>
</BACKGROUND>
<GENERICCOMPONENT name="new component" id="5bdd135efdbc6b85" memberName="waveTableDisplay"
virtualName="" explicitFocusOrder="0" pos="32 10 160 94" class="WavetableDisplayComponent"
params="dynamic_cast<WavetableSynth*>(getProcessor())"/>
<LABEL name="new label" id="f18e00eab8404cdf" memberName="fadeTimeLabel"
virtualName="" explicitFocusOrder="0" pos="33Rr 31 79 24" textCol="ffffffff"
edTextCol="ff000000" edBkgCol="0" labelText="Fade Time" editableSingleClick="0"
editableDoubleClick="0" focusDiscardsChanges="0" fontname="Khmer UI"
fontsize="13" bold="0" italic="0" justification="33"/>
<LABEL name="new label" id="5836a90d75d1dd4a" memberName="voiceAmountLabel"
virtualName="" explicitFocusOrder="0" pos="109Rr 32 79 24" textCol="ffffffff"
edTextCol="ff000000" edBkgCol="0" labelText="Voice Amount" editableSingleClick="0"
editableDoubleClick="0" focusDiscardsChanges="0" fontname="Khmer UI"
fontsize="13" bold="0" italic="0" justification="33"/>
<LABEL name="new label" id="fa0dc77af8626dc7" memberName="voiceAmountEditor"
virtualName="" explicitFocusOrder="0" pos="115Rr 50 68 16" bkgCol="38ffffff"
outlineCol="38ffffff" edTextCol="ff000000" edBkgCol="0" hiliteCol="407a0000"
labelText="64" editableSingleClick="1" editableDoubleClick="1"
focusDiscardsChanges="0" fontname="Khmer UI" fontsize="14" bold="0"
italic="0" justification="33"/>
<LABEL name="new label" id="9747f9d28c74d65d" memberName="fadeTimeEditor"
virtualName="" explicitFocusOrder="0" pos="56Rr 50 51 16" bkgCol="38ffffff"
outlineCol="38ffffff" edTextCol="ff000000" edBkgCol="0" hiliteCol="407a0000"
labelText="15 ms" editableSingleClick="1" editableDoubleClick="1"
focusDiscardsChanges="0" fontname="Khmer UI" fontsize="14" bold="0"
italic="0" justification="33"/>
<GENERICCOMPONENT name="new component" id="86c524f43e825eb1" memberName="component"
virtualName="" explicitFocusOrder="0" pos="203 10 412M 91" class="TableEditor"
params="dynamic_cast<WavetableSynth*>(getProcessor())->getGainTable()"/>
<TOGGLEBUTTON name="HQ" id="dfdc6e861a38fb62" memberName="hiqButton" virtualName="HiToggleButton"
explicitFocusOrder="0" pos="54Rr 72 128 32" tooltip="Enables HQ rendering mode (more CPU intensive)"
txtcol="ffffffff" buttonText="HQ" connectedEdges="0" needsCallback="1"
radioGroupId="0" state="0"/>
</JUCER_COMPONENT>
END_JUCER_METADATA
*/
#endif
//[EndFile] You can add extra defines here...
} // namespace hise
//[/EndFile]
|
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
// Including type: System.IO.Compression.ZipArchiveEntry
#include "System/IO/Compression/ZipArchiveEntry.hpp"
// Including type: System.IO.Stream
#include "System/IO/Stream.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
#include "beatsaber-hook/shared/utils/typedefs-array.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System::IO::Compression
namespace System::IO::Compression {
// Forward declaring type: CheckSumAndSizeWriteStream
class CheckSumAndSizeWriteStream;
}
// Forward declaring namespace: System::IO
namespace System::IO {
// Forward declaring type: SeekOrigin
struct SeekOrigin;
}
// Completed forward declares
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::System::IO::Compression::ZipArchiveEntry::DirectToArchiveWriterStream);
DEFINE_IL2CPP_ARG_TYPE(::System::IO::Compression::ZipArchiveEntry::DirectToArchiveWriterStream*, "System.IO.Compression", "ZipArchiveEntry/DirectToArchiveWriterStream");
// Type namespace: System.IO.Compression
namespace System::IO::Compression {
// Size: 0x4A
#pragma pack(push, 1)
// Autogenerated type: System.IO.Compression.ZipArchiveEntry/System.IO.Compression.DirectToArchiveWriterStream
// [TokenAttribute] Offset: FFFFFFFF
class ZipArchiveEntry::DirectToArchiveWriterStream : public ::System::IO::Stream {
public:
public:
// private System.Int64 _position
// Size: 0x8
// Offset: 0x28
int64_t position;
// Field size check
static_assert(sizeof(int64_t) == 0x8);
// private System.IO.Compression.CheckSumAndSizeWriteStream _crcSizeStream
// Size: 0x8
// Offset: 0x30
::System::IO::Compression::CheckSumAndSizeWriteStream* crcSizeStream;
// Field size check
static_assert(sizeof(::System::IO::Compression::CheckSumAndSizeWriteStream*) == 0x8);
// private System.Boolean _everWritten
// Size: 0x1
// Offset: 0x38
bool everWritten;
// Field size check
static_assert(sizeof(bool) == 0x1);
// private System.Boolean _isDisposed
// Size: 0x1
// Offset: 0x39
bool isDisposed;
// Field size check
static_assert(sizeof(bool) == 0x1);
// Padding between fields: isDisposed and: entry
char __padding3[0x6] = {};
// private System.IO.Compression.ZipArchiveEntry _entry
// Size: 0x8
// Offset: 0x40
::System::IO::Compression::ZipArchiveEntry* entry;
// Field size check
static_assert(sizeof(::System::IO::Compression::ZipArchiveEntry*) == 0x8);
// private System.Boolean _usedZip64inLH
// Size: 0x1
// Offset: 0x48
bool usedZip64inLH;
// Field size check
static_assert(sizeof(bool) == 0x1);
// private System.Boolean _canWrite
// Size: 0x1
// Offset: 0x49
bool canWrite;
// Field size check
static_assert(sizeof(bool) == 0x1);
public:
// Get instance field reference: private System.Int64 _position
[[deprecated("Use field access instead!")]] int64_t& dyn__position();
// Get instance field reference: private System.IO.Compression.CheckSumAndSizeWriteStream _crcSizeStream
[[deprecated("Use field access instead!")]] ::System::IO::Compression::CheckSumAndSizeWriteStream*& dyn__crcSizeStream();
// Get instance field reference: private System.Boolean _everWritten
[[deprecated("Use field access instead!")]] bool& dyn__everWritten();
// Get instance field reference: private System.Boolean _isDisposed
[[deprecated("Use field access instead!")]] bool& dyn__isDisposed();
// Get instance field reference: private System.IO.Compression.ZipArchiveEntry _entry
[[deprecated("Use field access instead!")]] ::System::IO::Compression::ZipArchiveEntry*& dyn__entry();
// Get instance field reference: private System.Boolean _usedZip64inLH
[[deprecated("Use field access instead!")]] bool& dyn__usedZip64inLH();
// Get instance field reference: private System.Boolean _canWrite
[[deprecated("Use field access instead!")]] bool& dyn__canWrite();
// public System.Void .ctor(System.IO.Compression.CheckSumAndSizeWriteStream crcSizeStream, System.IO.Compression.ZipArchiveEntry entry)
// Offset: 0x16A0420
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static ZipArchiveEntry::DirectToArchiveWriterStream* New_ctor(::System::IO::Compression::CheckSumAndSizeWriteStream* crcSizeStream, ::System::IO::Compression::ZipArchiveEntry* entry) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::IO::Compression::ZipArchiveEntry::DirectToArchiveWriterStream::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<ZipArchiveEntry::DirectToArchiveWriterStream*, creationType>(crcSizeStream, entry)));
}
// private System.Void ThrowIfDisposed()
// Offset: 0x16A1EE8
void ThrowIfDisposed();
// public override System.Int64 get_Length()
// Offset: 0x16A1E90
// Implemented from: System.IO.Stream
// Base method: System.Int64 Stream::get_Length()
int64_t get_Length();
// public override System.Int64 get_Position()
// Offset: 0x16A1F70
// Implemented from: System.IO.Stream
// Base method: System.Int64 Stream::get_Position()
int64_t get_Position();
// public override System.Void set_Position(System.Int64 value)
// Offset: 0x16A1F94
// Implemented from: System.IO.Stream
// Base method: System.Void Stream::set_Position(System.Int64 value)
void set_Position(int64_t value);
// public override System.Boolean get_CanRead()
// Offset: 0x16A1FEC
// Implemented from: System.IO.Stream
// Base method: System.Boolean Stream::get_CanRead()
bool get_CanRead();
// public override System.Boolean get_CanSeek()
// Offset: 0x16A1FF4
// Implemented from: System.IO.Stream
// Base method: System.Boolean Stream::get_CanSeek()
bool get_CanSeek();
// public override System.Boolean get_CanWrite()
// Offset: 0x16A1FFC
// Implemented from: System.IO.Stream
// Base method: System.Boolean Stream::get_CanWrite()
bool get_CanWrite();
// public override System.Int32 Read(System.Byte[] buffer, System.Int32 offset, System.Int32 count)
// Offset: 0x16A2004
// Implemented from: System.IO.Stream
// Base method: System.Int32 Stream::Read(System.Byte[] buffer, System.Int32 offset, System.Int32 count)
int Read(::ArrayW<uint8_t> buffer, int offset, int count);
// public override System.Int64 Seek(System.Int64 offset, System.IO.SeekOrigin origin)
// Offset: 0x16A205C
// Implemented from: System.IO.Stream
// Base method: System.Int64 Stream::Seek(System.Int64 offset, System.IO.SeekOrigin origin)
int64_t Seek(int64_t offset, ::System::IO::SeekOrigin origin);
// public override System.Void SetLength(System.Int64 value)
// Offset: 0x16A20B4
// Implemented from: System.IO.Stream
// Base method: System.Void Stream::SetLength(System.Int64 value)
void SetLength(int64_t value);
// public override System.Void Write(System.Byte[] buffer, System.Int32 offset, System.Int32 count)
// Offset: 0x16A210C
// Implemented from: System.IO.Stream
// Base method: System.Void Stream::Write(System.Byte[] buffer, System.Int32 offset, System.Int32 count)
void Write(::ArrayW<uint8_t> buffer, int offset, int count);
// public override System.Void Flush()
// Offset: 0x16A22A0
// Implemented from: System.IO.Stream
// Base method: System.Void Stream::Flush()
void Flush();
// protected override System.Void Dispose(System.Boolean disposing)
// Offset: 0x16A22D8
// Implemented from: System.IO.Stream
// Base method: System.Void Stream::Dispose(System.Boolean disposing)
void Dispose(bool disposing);
}; // System.IO.Compression.ZipArchiveEntry/System.IO.Compression.DirectToArchiveWriterStream
#pragma pack(pop)
static check_size<sizeof(ZipArchiveEntry::DirectToArchiveWriterStream), 73 + sizeof(bool)> __System_IO_Compression_ZipArchiveEntry_DirectToArchiveWriterStreamSizeCheck;
static_assert(sizeof(ZipArchiveEntry::DirectToArchiveWriterStream) == 0x4A);
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: System::IO::Compression::ZipArchiveEntry::DirectToArchiveWriterStream::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
// Writing MetadataGetter for method: System::IO::Compression::ZipArchiveEntry::DirectToArchiveWriterStream::ThrowIfDisposed
// Il2CppName: ThrowIfDisposed
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::IO::Compression::ZipArchiveEntry::DirectToArchiveWriterStream::*)()>(&System::IO::Compression::ZipArchiveEntry::DirectToArchiveWriterStream::ThrowIfDisposed)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::IO::Compression::ZipArchiveEntry::DirectToArchiveWriterStream*), "ThrowIfDisposed", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::IO::Compression::ZipArchiveEntry::DirectToArchiveWriterStream::get_Length
// Il2CppName: get_Length
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int64_t (System::IO::Compression::ZipArchiveEntry::DirectToArchiveWriterStream::*)()>(&System::IO::Compression::ZipArchiveEntry::DirectToArchiveWriterStream::get_Length)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::IO::Compression::ZipArchiveEntry::DirectToArchiveWriterStream*), "get_Length", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::IO::Compression::ZipArchiveEntry::DirectToArchiveWriterStream::get_Position
// Il2CppName: get_Position
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int64_t (System::IO::Compression::ZipArchiveEntry::DirectToArchiveWriterStream::*)()>(&System::IO::Compression::ZipArchiveEntry::DirectToArchiveWriterStream::get_Position)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::IO::Compression::ZipArchiveEntry::DirectToArchiveWriterStream*), "get_Position", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::IO::Compression::ZipArchiveEntry::DirectToArchiveWriterStream::set_Position
// Il2CppName: set_Position
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::IO::Compression::ZipArchiveEntry::DirectToArchiveWriterStream::*)(int64_t)>(&System::IO::Compression::ZipArchiveEntry::DirectToArchiveWriterStream::set_Position)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "Int64")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::IO::Compression::ZipArchiveEntry::DirectToArchiveWriterStream*), "set_Position", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: System::IO::Compression::ZipArchiveEntry::DirectToArchiveWriterStream::get_CanRead
// Il2CppName: get_CanRead
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (System::IO::Compression::ZipArchiveEntry::DirectToArchiveWriterStream::*)()>(&System::IO::Compression::ZipArchiveEntry::DirectToArchiveWriterStream::get_CanRead)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::IO::Compression::ZipArchiveEntry::DirectToArchiveWriterStream*), "get_CanRead", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::IO::Compression::ZipArchiveEntry::DirectToArchiveWriterStream::get_CanSeek
// Il2CppName: get_CanSeek
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (System::IO::Compression::ZipArchiveEntry::DirectToArchiveWriterStream::*)()>(&System::IO::Compression::ZipArchiveEntry::DirectToArchiveWriterStream::get_CanSeek)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::IO::Compression::ZipArchiveEntry::DirectToArchiveWriterStream*), "get_CanSeek", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::IO::Compression::ZipArchiveEntry::DirectToArchiveWriterStream::get_CanWrite
// Il2CppName: get_CanWrite
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (System::IO::Compression::ZipArchiveEntry::DirectToArchiveWriterStream::*)()>(&System::IO::Compression::ZipArchiveEntry::DirectToArchiveWriterStream::get_CanWrite)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::IO::Compression::ZipArchiveEntry::DirectToArchiveWriterStream*), "get_CanWrite", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::IO::Compression::ZipArchiveEntry::DirectToArchiveWriterStream::Read
// Il2CppName: Read
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (System::IO::Compression::ZipArchiveEntry::DirectToArchiveWriterStream::*)(::ArrayW<uint8_t>, int, int)>(&System::IO::Compression::ZipArchiveEntry::DirectToArchiveWriterStream::Read)> {
static const MethodInfo* get() {
static auto* buffer = &il2cpp_functions::array_class_get(::il2cpp_utils::GetClassFromName("System", "Byte"), 1)->byval_arg;
static auto* offset = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
static auto* count = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::IO::Compression::ZipArchiveEntry::DirectToArchiveWriterStream*), "Read", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{buffer, offset, count});
}
};
// Writing MetadataGetter for method: System::IO::Compression::ZipArchiveEntry::DirectToArchiveWriterStream::Seek
// Il2CppName: Seek
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int64_t (System::IO::Compression::ZipArchiveEntry::DirectToArchiveWriterStream::*)(int64_t, ::System::IO::SeekOrigin)>(&System::IO::Compression::ZipArchiveEntry::DirectToArchiveWriterStream::Seek)> {
static const MethodInfo* get() {
static auto* offset = &::il2cpp_utils::GetClassFromName("System", "Int64")->byval_arg;
static auto* origin = &::il2cpp_utils::GetClassFromName("System.IO", "SeekOrigin")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::IO::Compression::ZipArchiveEntry::DirectToArchiveWriterStream*), "Seek", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{offset, origin});
}
};
// Writing MetadataGetter for method: System::IO::Compression::ZipArchiveEntry::DirectToArchiveWriterStream::SetLength
// Il2CppName: SetLength
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::IO::Compression::ZipArchiveEntry::DirectToArchiveWriterStream::*)(int64_t)>(&System::IO::Compression::ZipArchiveEntry::DirectToArchiveWriterStream::SetLength)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "Int64")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::IO::Compression::ZipArchiveEntry::DirectToArchiveWriterStream*), "SetLength", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: System::IO::Compression::ZipArchiveEntry::DirectToArchiveWriterStream::Write
// Il2CppName: Write
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::IO::Compression::ZipArchiveEntry::DirectToArchiveWriterStream::*)(::ArrayW<uint8_t>, int, int)>(&System::IO::Compression::ZipArchiveEntry::DirectToArchiveWriterStream::Write)> {
static const MethodInfo* get() {
static auto* buffer = &il2cpp_functions::array_class_get(::il2cpp_utils::GetClassFromName("System", "Byte"), 1)->byval_arg;
static auto* offset = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
static auto* count = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::IO::Compression::ZipArchiveEntry::DirectToArchiveWriterStream*), "Write", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{buffer, offset, count});
}
};
// Writing MetadataGetter for method: System::IO::Compression::ZipArchiveEntry::DirectToArchiveWriterStream::Flush
// Il2CppName: Flush
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::IO::Compression::ZipArchiveEntry::DirectToArchiveWriterStream::*)()>(&System::IO::Compression::ZipArchiveEntry::DirectToArchiveWriterStream::Flush)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::IO::Compression::ZipArchiveEntry::DirectToArchiveWriterStream*), "Flush", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::IO::Compression::ZipArchiveEntry::DirectToArchiveWriterStream::Dispose
// Il2CppName: Dispose
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::IO::Compression::ZipArchiveEntry::DirectToArchiveWriterStream::*)(bool)>(&System::IO::Compression::ZipArchiveEntry::DirectToArchiveWriterStream::Dispose)> {
static const MethodInfo* get() {
static auto* disposing = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::IO::Compression::ZipArchiveEntry::DirectToArchiveWriterStream*), "Dispose", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{disposing});
}
};
|
#include "VulkanDescriptorSetLayoutBuilder.h"
#include "VulkanMesh.h"
#include "VulkanShader.h"
using namespace NCL;
using namespace Rendering;
VulkanDescriptorSetLayoutBuilder& VulkanDescriptorSetLayoutBuilder::WithSamplers(unsigned int count, vk::ShaderStageFlags inShaders) {
vk::DescriptorSetLayoutBinding binding = vk::DescriptorSetLayoutBinding()
.setBinding((uint32_t)addedBindings.size())
.setDescriptorCount(count)
.setDescriptorType(vk::DescriptorType::eCombinedImageSampler)
.setStageFlags(inShaders);
addedBindings.emplace_back(binding);
return *this;
}
VulkanDescriptorSetLayoutBuilder& VulkanDescriptorSetLayoutBuilder::WithUniformBuffers(unsigned int count, vk::ShaderStageFlags inShaders) {
vk::DescriptorSetLayoutBinding binding = vk::DescriptorSetLayoutBinding()
.setBinding((uint32_t)addedBindings.size())
.setDescriptorCount(count)
.setDescriptorType(vk::DescriptorType::eUniformBuffer)
.setStageFlags(inShaders);
addedBindings.emplace_back(binding);
return *this;
}
VulkanDescriptorSetLayoutBuilder& VulkanDescriptorSetLayoutBuilder::WithDebugName(const string& name) {
debugName = name;
return *this;
}
vk::DescriptorSetLayout VulkanDescriptorSetLayoutBuilder::Build(VulkanRenderer& renderer) {
vk::DescriptorSetLayout outLayout = renderer.device.createDescriptorSetLayout(
vk::DescriptorSetLayoutCreateInfo({}, (uint32_t)addedBindings.size(), addedBindings.data())
);
renderer.SetDebugName(vk::ObjectType::eDescriptorSetLayout, (uint64_t)(VkDescriptorSetLayout)outLayout, debugName);
return outLayout;
}
|
// (C) Copyright David Abrahams 2002.
// (C) Copyright Jeremy Siek 2002.
// (C) Copyright Thomas Witt 2002.
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_ENABLE_IF_23022003THW_HPP
#define BOOST_ENABLE_IF_23022003THW_HPP
#include <boost/detail/workaround.hpp>
#include <boost/mpl/identity.hpp>
#include <boost/iterator/detail/config_def.hpp>
//
// Boost iterators uses its own enable_if cause we need
// special semantics for deficient compilers.
// 23/02/03 thw
//
namespace boost
{
namespace iterators
{
//
// Base machinery for all kinds of enable if
//
template<bool>
struct enabled
{
template<typename T>
struct base
{
typedef T type;
};
};
//
// For compilers that don't support "Substitution Failure Is Not An Error"
// enable_if falls back to always enabled. See comments
// on operator implementation for consequences.
//
template<>
struct enabled<false>
{
template<typename T>
struct base
{
#ifdef BOOST_NO_SFINAE
typedef T type;
// This way to do it would give a nice error message containing
// invalid overload, but has the big disadvantage that
// there is no reference to user code in the error message.
//
// struct invalid_overload;
// typedef invalid_overload type;
//
#endif
};
};
template <class Cond,
class Return>
struct enable_if
# if !defined(BOOST_NO_SFINAE) && !defined(BOOST_NO_IS_CONVERTIBLE)
: enabled<(Cond::value)>::template base<Return>
# else
: mpl::identity<Return>
# endif
{
# if BOOST_WORKAROUND(BOOST_MSVC, <= 1200)
typedef Return type;
# endif
};
} // namespace iterators
} // namespace boost
#include <boost/iterator/detail/config_undef.hpp>
#endif // BOOST_ENABLE_IF_23022003THW_HPP
|
#include <iostream>
#include <clickhouse-cpp/client.h>
#include <clickhouse-cpp/error_codes.h>
#include <clickhouse-cpp/types/type_parser.h>
#include <clickhouse-cpp/columns/factory.h>
#include "click2db.h"
#define CONNECT_TIMEOUT 60
Click2DB::Click2DB() : m_run(false), m_pQueue(std::make_unique<Queue>(10000))
{
}
Click2DB::~Click2DB()
{
if (m_run.load(std::memory_order_acquire))
{
m_run.store(false, std::memory_order_release);
if (m_t.joinable())
m_t.join();
}
}
bool Click2DB::init(INode *pnode)
{
m_pnode = pnode;
if (!pnode->getStrParam("host", m_host))
{
m_pnode->logger()->error("Error at get host");
return false;
}
if (!pnode->getStrParam("user", m_user))
{
m_pnode->logger()->error("Error at get user");
return false;
}
if (!pnode->getStrParam("pass", m_password))
{
m_pnode->logger()->error("Error at get password");
return false;
}
if (!pnode->getStrParam("table", m_tableName))
{
m_pnode->logger()->error("Error at get table");
return false;
}
if (!pnode->getStrParam("tosend", m_toSend))
{
m_pnode->logger()->error("Error at path for sending files");
return false;
}
pnode->getStrParam("failed", m_sendFailed);
pnode->getStrParam("badfiles", m_loadFailed);
pnode->getStrParam("metrics", m_metrics);
if (!m_metrics.empty())
{
m_pnode->metrics()->connect(g_ErrorDB,"ErrorDB",m_metrics);
m_pnode->metrics()->connect(g_ErrorFS,"ErrorFS",m_metrics);
m_pnode->metrics()->connect(g_ErrorTypes,"ErrorTypes",m_metrics);
m_pnode->metrics()->connect(g_InsertedRows,"InsertedRows",m_metrics);
}
if (!std::filesystem::exists(m_toSend))
{
std::filesystem::create_directories(m_toSend);
}
if (!m_sendFailed.empty() && !std::filesystem::exists(m_sendFailed))
{
std::filesystem::create_directories(m_sendFailed);
}
if (!m_loadFailed.empty() && !std::filesystem::exists(m_loadFailed))
{
std::filesystem::create_directories(m_loadFailed);
}
// перебираем папку tosend на предмет существующих файлов
std::filesystem::directory_iterator end_itr;
for (std::filesystem::directory_iterator itr(m_toSend); itr != end_itr; itr++)
{
if (!is_directory(itr->status()))
{
std::string fileName = m_toSend + "/" + itr->path().filename().string();
m_pQueue->enqueue(std::make_pair(0, fileName));
}
}
m_pnode->logger()->info("Clickhouse: {}:{}", m_host, m_tableName);
return true;
}
bool Click2DB::start()
{
m_run.store(true, std::memory_order_release);
m_t = std::thread(&Click2DB::lifeProc, this);
return true;
}
bool Click2DB::tryConnect()
{
try
{
if (!m_pClickDB)
{
m_pClickDB = std::make_unique<clickhouse::Client>(clickhouse::ClientOptions()
.SetHost(m_host)
//.SetPingBeforeQuery(true)
.TcpKeepAlive(true)
.SetTcpKeepAliveIdle(30)
.SetUser(m_user)
.SetPassword(m_password)
.SetCompressionMethod(clickhouse::CompressionMethod::LZ4));
m_pnode->logger()->info("Connect to {} succeeded", m_host);
}
}
catch (const std::exception &e)
{
m_pnode->logger()->warn("Connection with {} {}", m_host, e.what());
m_tblType.clear();
m_pClickDB.reset();
return false;
}
return true;
}
void Click2DB::lifeProc()
{
bool updateTblDesc = true;
int emptyCounter = 0; // подсчет холостых тактов для активации проверки соединения
while (m_run.load(std::memory_order_acquire))
{
if (!m_pClickDB && !tryConnect())
{
emptyCounter = 0; // сбрасываем счетчик холостых тактов
for(int i=0;i<CONNECT_TIMEOUT && m_run.load(std::memory_order_acquire);i++)
std::this_thread::sleep_for(std::chrono::seconds(1));
continue;
}
if (emptyCounter / 2 > CONNECT_TIMEOUT)
{
// время ожидания очереди 500 мс, поэтому количество
// попыток прочитать из очереди деленное на 2 равно CONNECT_TIMEOUT
// и если в течении этого времени не было обмена с базой
// выполняем проверку соединения
emptyCounter = 0; // сбрасываем счетчик холостых тактов
try
{
m_pnode->logger()->debug("Ping to {}", m_host);
m_pClickDB->Ping();
}
catch (const std::exception &pExecpt)
{
m_pnode->logger()->debug("Ping to {} failed: {}", m_host, pExecpt.what());
// при проверке соединения произошла ошибка связанная с подключением
m_pClickDB.reset();
m_tblType.clear();
}
}
if (updateTblDesc || m_tblType.empty())
{
emptyCounter = 0; // сбрасываем счетчик холостых тактов
try
{
descibeTable();
}
catch (const std::exception &pExecpt)
{
m_pnode->logger()->error("Describe table {}:{} failed: {}", m_host, m_tableName, pExecpt.what());
++g_ErrorDB;
// при попытке получить описание произошла ошибка связанная с подключением
m_pClickDB.reset();
m_tblType.clear();
}
updateTblDesc = m_tblType.empty();
}
if (m_tblType.empty())
{
updateTblDesc = true;
std::this_thread::sleep_for(std::chrono::seconds(CONNECT_TIMEOUT));
continue;
}
std::pair<int, std::filesystem::path> file;
if (m_pQueue->wait_dequeue_timed(file, std::chrono::milliseconds(500)))
{
emptyCounter = 0; // сбрасываем счетчик холостых тактов
ClickTable table;
try
{
table.load(file.second.string());
}
catch (const std::exception &pExecpt)
{
++g_ErrorFS;
m_pnode->logger()->error("Error at load {}: {}, move file to bad dir", file.second.string(), pExecpt.what());
if (!m_pnode->moveFile(m_loadFailed, file.second))
++g_ErrorFS;
continue;
}
try
{
sendTable(table);
m_pnode->logger()->debug("Send {} rows from '{}' to {}::{} succeeded", table.rowCount(), file.second.string(), m_host, m_tableName);
if (!m_pnode->moveFile("", file.second))
++g_ErrorFS;
}
catch (const std::exception &pExecpt)
{
++g_ErrorDB;
file.first++;
if (file.first < 3)
{
m_pnode->logger()->warn("Send to {}:{} failed, try more'{}': {}", m_host, m_tableName, file.second.string(), pExecpt.what());
m_pQueue->enqueue(file);
// что то пошло не так, обновим информацию о таблице
updateTblDesc = true;
}
else
{
m_pnode->logger()->error("Send to {}:{} failed, try count over '{}': {}", m_host, m_tableName, file.second.string(), pExecpt.what());
if (!m_pnode->moveFile(m_sendFailed, file.second))
++g_ErrorFS;
}
}
}
else
{
emptyCounter++;
}
}
m_pnode->logger()->debug("Click2DB::thread exit");
}
static void column2ClickColumn(const Value &inColumn, clickhouse::ColumnRef column)
{
switch (column->Type()->GetCode())
{
case clickhouse::Type::Int8:
{
auto columnType = column->As<clickhouse::ColumnInt8>();
for (auto &el : *inColumn._vector)
columnType->Append(el.getInt8());
break;
}
case clickhouse::Type::Int16:
{
auto columnType = column->As<clickhouse::ColumnInt16>();
for (auto &el : *inColumn._vector)
columnType->Append(el.getInt16());
break;
}
case clickhouse::Type::Int32:
{
auto columnType = column->As<clickhouse::ColumnInt32>();
for (auto &el : *inColumn._vector)
columnType->Append(el.getInt32());
break;
}
case clickhouse::Type::Int64:
{
auto columnType = column->As<clickhouse::ColumnInt64>();
for (auto &el : *inColumn._vector)
columnType->Append(el.getInt64());
break;
}
case clickhouse::Type::Int128:
{
auto columnType = column->As<clickhouse::ColumnInt128>();
for (auto &el : *inColumn._vector)
columnType->Append(el.getInt64());
break;
}
case clickhouse::Type::UInt8:
{
auto columnType = column->As<clickhouse::ColumnUInt8>();
for (auto &el : *inColumn._vector)
columnType->Append(el.getUInt8());
break;
}
case clickhouse::Type::UInt16:
{
auto columnType = column->As<clickhouse::ColumnUInt16>();
for (auto &el : *inColumn._vector)
columnType->Append(el.getUInt16());
break;
}
case clickhouse::Type::UInt32:
{
auto columnType = column->As<clickhouse::ColumnUInt32>();
for (auto &el : *inColumn._vector)
columnType->Append(el.getUInt32());
break;
}
case clickhouse::Type::IPv4:
{
auto columnType = column->As<clickhouse::ColumnUInt32>();
for (auto &el : *inColumn._vector)
{
columnType->Append(ntohl(inet_addr(el.getString().c_str())));
}
break;
}
case clickhouse::Type::UInt64:
{
auto columnType = column->As<clickhouse::ColumnUInt64>();
for (auto &el : *inColumn._vector)
columnType->Append(el.getUInt64());
break;
}
case clickhouse::Type::Float32:
{
auto columnType = column->As<clickhouse::ColumnFloat32>();
for (auto &el : *inColumn._vector)
columnType->Append(el.getFloat());
break;
}
case clickhouse::Type::Float64:
{
auto columnType = column->As<clickhouse::ColumnFloat64>();
for (auto &el : *inColumn._vector)
columnType->Append(el.getDouble());
break;
}
case clickhouse::Type::String:
{
auto columnType = column->As<clickhouse::ColumnString>();
for (auto &el : *inColumn._vector)
columnType->Append(el.getString());
break;
}
case clickhouse::Type::FixedString:
{
auto columnType = column->As<clickhouse::ColumnFixedString>();
for (auto &el : *inColumn._vector)
columnType->Append(el.getString());
break;
}
case clickhouse::Type::DateTime:
{
auto columnType = column->As<clickhouse::ColumnDateTime>();
for (auto &el : *inColumn._vector)
columnType->Append(el.getDateTime());
break;
}
case clickhouse::Type::Date:
{
auto columnType = column->As<clickhouse::ColumnDate>();
for (auto &el : *inColumn._vector)
columnType->Append(el.getDate());
break;
}
case clickhouse::Type::Array:
{
auto columnName = column->Type()->As<clickhouse::ArrayType>()->GetItemType()->GetName();
auto columnType = column->As<clickhouse::ColumnArray>();
for (auto &el : *inColumn._vector)
{
auto col = clickhouse::CreateColumnByType(columnName);
column2ClickColumn(el, col);
columnType->AppendAsColumn(col);
}
break;
}
case clickhouse::Type::Nullable:
{
auto nullableColumn = column->As<clickhouse::ColumnNullable>();
auto nestedColunmn = nullableColumn->Nested();
column2ClickColumn(inColumn, nestedColunmn);
for (auto &el : *inColumn._vector)
{
nullableColumn->Append(el.isNull());
}
break;
break;
}
case clickhouse::Type::Enum8:
{
auto columnType = column->As<clickhouse::ColumnEnum8>();
for (auto &el : *inColumn._vector)
{
if (el.type() == CT_UINT)
columnType->Append(el.getUInt64());
else if (el.type() == CT_INT)
columnType->Append(el.getInt64());
else if (el.type() == CT_STR)
columnType->Append(el.getString());
else
{
throw std::runtime_error("convert to Enum8 failed");
}
}
break;
}
case clickhouse::Type::Enum16:
{
auto columnType = column->As<clickhouse::ColumnEnum16>();
for (auto &el : *inColumn._vector)
{
if (el.type() == CT_UINT)
columnType->Append(el.getUInt64());
else if (el.type() == CT_INT)
columnType->Append(el.getInt64());
else if (el.type() == CT_STR)
columnType->Append(el.getString());
else
{
throw std::runtime_error("convert to Enum16 failed");
}
}
break;
}
case clickhouse::Type::Decimal32:
case clickhouse::Type::Decimal64:
case clickhouse::Type::Decimal128:
{
auto columnType = column->As<clickhouse::ColumnDecimal>();
for (auto &el : *inColumn._vector)
{
if (el.type() == CT_UINT)
columnType->Append(el.getUInt64());
else
columnType->Append(el.getInt64());
}
break;
}
case clickhouse::Type::IPv6:
{
auto columnType = column->As<clickhouse::ColumnFixedString>();
for (auto &el : *inColumn._vector)
columnType->Append(el.getString());
break;
}
// case clickhouse::Type::Tuple:
// {
// auto columnType = column->As<clickhouse::ColumnTuple>();
// break;
// }
case clickhouse::Type::UUID:
{
auto columnType = column->As<clickhouse::ColumnUUID>();
for (auto &el : *inColumn._vector)
columnType->Append(el.getUInt128());
break;
}
default:
throw std::runtime_error("unsupported clickhouse type");
}
}
void Click2DB::sendTable(const ClickTable &table)
{
// блок заполнения таблицы
auto fillTable = [this](const ClickTable &table, clickhouse::Block &block) {
bool hasUnknownTypes = false;
for (auto &col : table.m_tbl)
{
auto typeItr = m_tblType.find(col.first);
if (typeItr == m_tblType.end())
{
m_pnode->logger()->warn("No column '{}' in {}:{}", col.first, m_host, m_tableName);
++g_ErrorTypes;
hasUnknownTypes = true;
continue;
}
clickhouse::ColumnRef column = clickhouse::CreateColumnByType(typeItr->second);
if (column)
{
try
{
column2ClickColumn(col.second._data, column);
}
catch (std::exception &ex)
{
m_pnode->logger()->warn("Error at convert {} to CH type {}: {}", col.first, typeItr->second, ex.what());
++g_ErrorTypes;
continue;
}
block.AppendColumn(col.first, column);
}
else
{
m_pnode->logger()->error("create column '{}' aka '{}' in {}:{} failed", col.first, typeItr->second, m_host, m_tableName);
++g_ErrorTypes;
}
}
return hasUnknownTypes;
};
clickhouse::Block block;
if (fillTable(table, block))
{
// в таблице есть неизвестные элементы, пробуем обновить описание таблицы
if (descibeTable())
{
// описание поменялось, перезаполняем таблицу
block = clickhouse::Block();
fillTable(table, block);
}
}
if (block.GetColumnCount() == 0)
{
throw std::runtime_error("no column om table");
}
if (block.GetRowCount() == 0)
{
throw std::runtime_error("no rows om table");
}
auto beginTime = std::chrono::steady_clock::now();
m_pClickDB->Insert(m_tableName, block);
auto endTime = std::chrono::steady_clock::now();
auto queryTime = std::chrono::duration_cast<std::chrono::milliseconds>(endTime - beginTime).count();
// сбрасываем метрику
g_InsertedRows+=table.rowCount();
//m_pnode->metrics()->push(m_metrics, "InsertedTime", queryTime);
return;
}
bool Click2DB::descibeTable()
{
if (!m_pClickDB)
{
throw std::runtime_error("Describe failed: no connection");
}
auto beginTime = std::chrono::steady_clock::now();
std::map<std::string, std::string> tblType;
clickhouse::Query query(std::string("INSERT INTO " + m_tableName + " VALUES"));
m_pClickDB->Execute(query.OnDataCancelable([&tblType](const clickhouse::Block &desc) {
for (clickhouse::Block::Iterator bi(desc); bi.IsValid(); bi.Next())
{
auto name = bi.Name();
auto typeName = bi.Type()->GetName();
tblType[name] = typeName;
}
return false;
}));
m_tblType.swap(tblType);
bool isChanged = m_tblType != tblType;
auto endTime = std::chrono::steady_clock::now();
auto queryTime = std::chrono::duration_cast<std::chrono::milliseconds>(endTime - beginTime).count();
if (tblType.empty() && !m_tblType.empty())
{
m_pnode->logger()->debug("Describe table '{}:{}' succeeded by {} msec", m_host, m_tableName, queryTime);
}
else if (isChanged)
{
m_pnode->logger()->debug("Table description '{}:{}' is updated by {} msec", m_host, m_tableName, queryTime);
}
else
{
m_pnode->logger()->debug("Describe table '{}:{}': no changes by {} msec", m_host, m_tableName, queryTime);
}
return isChanged;
}
bool Click2DB::doProc(const std::filesystem::path &inFile)
{
std::filesystem::path toFile = std::filesystem::path(m_toSend) / inFile.filename();
std::error_code err;
std::filesystem::copy_file(inFile, toFile, err);
if (err)
{
m_pnode->logger()->warn("Copy file failed ({}): {} -> {}", err.message(), inFile.string(), toFile.string());
return false;
}
m_pQueue->enqueue(std::make_pair(0, toFile));
return true;
}
|
/* 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 "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/iterator_range.h"
#include "llvm/Support/Casting.h"
#include "mlir/IR/Operation.h" // TF:local_config_mlir
#include "mlir/IR/Value.h" // TF:local_config_mlir
#include "mlir/Pass/Pass.h" // TF:local_config_mlir
#include "mlir/Pass/PassRegistry.h" // TF:local_config_mlir
#include "tensorflow/compiler/mlir/tensorflow/ir/tf_executor.h"
#include "tensorflow/compiler/mlir/tensorflow/transforms/passes.h"
namespace mlir {
namespace tf_executor {
// Prunes unreachable operations of a tf_executor.graph operation.
void PruneGraph(GraphOp graph) {
// A graph has a single block which forms a DAG: operations that aren't
// reachable from the `fetch` operands can be eliminated.
llvm::SmallPtrSet<Operation*, 8> reachable_ops;
llvm::SmallVector<Operation*, 8> ops_to_visit;
// Visit an op's operands if it is output of an Operation in same graph.
auto visit_op = [&](Operation* op) {
for (Value operand : op->getOperands()) {
Operation* def = operand->getDefiningOp();
if (def && def->getParentOp() == graph &&
reachable_ops.insert(def).second) {
// Op has not been visited, add to queue to visit later.
ops_to_visit.push_back(def);
}
}
};
// Visit `fetch` operands.
visit_op(graph.GetFetch());
while (!ops_to_visit.empty()) {
Operation* op = ops_to_visit.pop_back_val();
if (auto island_op = llvm::dyn_cast<IslandOp>(op)) {
// Visit island and island inner ops operands.
op->walk([&](Operation* inner_op) { visit_op(inner_op); });
continue;
} else {
// Op is not an island, only visit its operands.
visit_op(op);
}
// If op is a `tf_executor.NextIteration.Source`, visit its associated
// `tf_executor.NextIteration.Sink` op.
if (auto source_op = llvm::dyn_cast<NextIterationSourceOp>(op)) {
Operation* sink_op = source_op.GetSink().getOperation();
if (reachable_ops.insert(sink_op).second) {
ops_to_visit.push_back(sink_op);
}
}
}
// Erase unreachable ops in reverse order.
for (Operation& op : llvm::make_early_inc_range(
llvm::drop_begin(llvm::reverse(graph.GetBody()), 1))) {
if (reachable_ops.find(&op) == reachable_ops.end()) {
op.erase();
}
}
}
namespace {
// This transformation pass prunes a TF graph eliminating dead-nodes.
struct GraphPruning : public FunctionPass<GraphPruning> {
void runOnFunction() override {
getFunction().walk([](tf_executor::GraphOp graph) { PruneGraph(graph); });
}
};
} // namespace
std::unique_ptr<OpPassBase<FuncOp>> CreateTFExecutorGraphPruningPass() {
return std::make_unique<GraphPruning>();
}
static PassRegistration<GraphPruning> pass(
"tf-executor-graph-pruning",
"Prune unreachable nodes in a TensorFlow Graph.");
} // namespace tf_executor
} // namespace mlir
|
// Copyright (c) 2014-2018, The Monero Project
// Copyright (c) 2018, The sevabit Project
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// 2. 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.
//
// 3. Neither the name of the copyright holder 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 HOLDER 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.
//
// Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers
#include <memory>
#include <stdexcept>
#include <boost/algorithm/string/split.hpp>
#include "misc_log_ex.h"
#include "daemon/daemon.h"
#include "rpc/daemon_handler.h"
#include "rpc/zmq_server.h"
#include "common/password.h"
#include "common/util.h"
#include "daemon/core.h"
#include "daemon/p2p.h"
#include "daemon/protocol.h"
#include "daemon/rpc.h"
#include "daemon/command_server.h"
#include "daemon/command_server.h"
#include "daemon/command_line_args.h"
#include "version.h"
using namespace epee;
#include <functional>
#undef sevabit_DEFAULT_LOG_CATEGORY
#define sevabit_DEFAULT_LOG_CATEGORY "daemon"
namespace daemonize {
struct t_internals {
private:
t_protocol protocol;
public:
t_core core;
t_p2p p2p;
std::vector<std::unique_ptr<t_rpc>> rpcs;
t_internals(
boost::program_options::variables_map const & vm
)
: core{vm}
, protocol{vm, core, command_line::get_arg(vm, cryptonote::arg_offline)}
, p2p{vm, protocol}
{
// Handle circular dependencies
protocol.set_p2p_endpoint(p2p.get());
core.set_protocol(protocol.get());
const auto testnet = command_line::get_arg(vm, cryptonote::arg_testnet_on);
const auto stagenet = command_line::get_arg(vm, cryptonote::arg_stagenet_on);
const auto restricted = command_line::get_arg(vm, cryptonote::core_rpc_server::arg_restricted_rpc);
const auto main_rpc_port = command_line::get_arg(vm, cryptonote::core_rpc_server::arg_rpc_bind_port);
rpcs.emplace_back(new t_rpc{vm, core, p2p, restricted, testnet ? cryptonote::TESTNET : stagenet ? cryptonote::STAGENET : cryptonote::MAINNET, main_rpc_port, "core"});
auto restricted_rpc_port_arg = cryptonote::core_rpc_server::arg_rpc_restricted_bind_port;
if(!command_line::is_arg_defaulted(vm, restricted_rpc_port_arg))
{
auto restricted_rpc_port = command_line::get_arg(vm, restricted_rpc_port_arg);
rpcs.emplace_back(new t_rpc{vm, core, p2p, true, testnet ? cryptonote::TESTNET : stagenet ? cryptonote::STAGENET : cryptonote::MAINNET, restricted_rpc_port, "restricted"});
}
}
};
void t_daemon::init_options(boost::program_options::options_description & option_spec)
{
t_core::init_options(option_spec);
t_p2p::init_options(option_spec);
t_rpc::init_options(option_spec);
}
t_daemon::t_daemon(
boost::program_options::variables_map const & vm
)
: mp_internals{new t_internals{vm}}
{
zmq_rpc_bind_port = command_line::get_arg(vm, daemon_args::arg_zmq_rpc_bind_port);
zmq_rpc_bind_address = command_line::get_arg(vm, daemon_args::arg_zmq_rpc_bind_ip);
}
t_daemon::~t_daemon() = default;
// MSVC is brain-dead and can't default this...
t_daemon::t_daemon(t_daemon && other)
{
if (this != &other)
{
mp_internals = std::move(other.mp_internals);
other.mp_internals.reset(nullptr);
}
}
// or this
t_daemon & t_daemon::operator=(t_daemon && other)
{
if (this != &other)
{
mp_internals = std::move(other.mp_internals);
other.mp_internals.reset(nullptr);
}
return *this;
}
bool t_daemon::run(bool interactive)
{
if (nullptr == mp_internals)
{
throw std::runtime_error{"Can't run stopped daemon"};
}
tools::signal_handler::install(std::bind(&daemonize::t_daemon::stop_p2p, this));
try
{
if (!mp_internals->core.run())
return false;
for(auto& rpc: mp_internals->rpcs)
rpc->run();
std::unique_ptr<daemonize::t_command_server> rpc_commands;
if (interactive && mp_internals->rpcs.size())
{
// The first three variables are not used when the fourth is false
rpc_commands.reset(new daemonize::t_command_server(0, 0, boost::none, false, mp_internals->rpcs.front()->get_server()));
rpc_commands->start_handling(std::bind(&daemonize::t_daemon::stop_p2p, this));
}
cryptonote::rpc::DaemonHandler rpc_daemon_handler(mp_internals->core.get(), mp_internals->p2p.get());
cryptonote::rpc::ZmqServer zmq_server(rpc_daemon_handler);
if (!zmq_server.addTCPSocket(zmq_rpc_bind_address, zmq_rpc_bind_port))
{
LOG_ERROR(std::string("Failed to add TCP Socket (") + zmq_rpc_bind_address
+ ":" + zmq_rpc_bind_port + ") to ZMQ RPC Server");
if (rpc_commands)
rpc_commands->stop_handling();
for(auto& rpc : mp_internals->rpcs)
rpc->stop();
return false;
}
MINFO("Starting ZMQ server...");
zmq_server.run();
MINFO(std::string("ZMQ server started at ") + zmq_rpc_bind_address
+ ":" + zmq_rpc_bind_port + ".");
mp_internals->p2p.run(); // blocks until p2p goes down
if (rpc_commands)
rpc_commands->stop_handling();
zmq_server.stop();
for(auto& rpc : mp_internals->rpcs)
rpc->stop();
mp_internals->core.get().get_miner().stop();
MGINFO("Node stopped.");
return true;
}
catch (std::exception const & ex)
{
MFATAL("Uncaught exception! " << ex.what());
return false;
}
catch (...)
{
MFATAL("Uncaught exception!");
return false;
}
}
void t_daemon::stop()
{
if (nullptr == mp_internals)
{
throw std::runtime_error{"Can't stop stopped daemon"};
}
mp_internals->core.get().get_miner().stop();
mp_internals->p2p.stop();
for(auto& rpc : mp_internals->rpcs)
rpc->stop();
mp_internals.reset(nullptr); // Ensure resources are cleaned up before we return
}
void t_daemon::stop_p2p()
{
if (nullptr == mp_internals)
{
throw std::runtime_error{"Can't send stop signal to a stopped daemon"};
}
mp_internals->p2p.get().send_stop_signal();
}
} // namespace daemonize
|
// Copyright (C) 2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include "low_precision/rt_info/precisions_attribute.hpp"
#include <memory>
#include <string>
#include <unordered_map>
#include <iterator>
#include <vector>
#include <ngraph/opsets/opset1.hpp>
#include "low_precision/network_helper.hpp"
using namespace ngraph;
using namespace ov;
// order defines default precision
std::vector<ngraph::element::Type> PrecisionsAttribute::defaultPrecisions = {ngraph::element::u8, ngraph::element::i8};
PrecisionsAttribute::PrecisionsAttribute(const std::vector<ngraph::element::Type>& precisions) {
sharedValue->precisions = precisions;
}
template class ngraph::VariantImpl<std::shared_ptr<PrecisionsAttribute>>;
constexpr VariantTypeInfo VariantWrapper<std::shared_ptr<PrecisionsAttribute>>::type_info;
std::shared_ptr<VariantWrapper<std::shared_ptr<PrecisionsAttribute>>> VariantWrapper<std::shared_ptr<PrecisionsAttribute>>::create(
const std::shared_ptr<ngraph::Node>& node,
const AttributeParameters& params) {
auto attribute = ngraph::pass::low_precision::make_shared_attribute<PrecisionsAttribute>();
auto wrapper = std::make_shared<ngraph::VariantWrapper<std::shared_ptr<PrecisionsAttribute>>>(attribute);
auto& rt = ov::is_type<opset1::FakeQuantize>(node) ? node->output(0).get_rt_info() : node->get_rt_info();
rt[ngraph::VariantWrapper<std::shared_ptr<PrecisionsAttribute>>::type_info.name] = wrapper;
return wrapper;
}
void VariantWrapper<std::shared_ptr<PrecisionsAttribute>>::merge(
std::vector<std::shared_ptr<VariantWrapper<std::shared_ptr<PrecisionsAttribute>>>>& attributes) {
auto& my = this->get()->sharedValue->precisions;
for (auto attribute : attributes) {
const auto& attributeValues = attribute->get()->sharedValue->precisions;
auto it = my.begin();
while (it != my.end()) {
if (std::find(attributeValues.begin(), attributeValues.end(), *it) == attributeValues.end()) {
it = my.erase(it);
} else {
it++;
}
}
if (my.size() == 0ul) {
break;
}
}
}
ov::Any VariantWrapper<std::shared_ptr<PrecisionsAttribute>>::init(const std::shared_ptr<ngraph::Node>& node) {
return {};
}
std::string VariantWrapper<std::shared_ptr<PrecisionsAttribute>>::to_string() {
std::stringstream ss;
ss << m_value->get_string();
bool firstPrecision = true;
ss << "precisions: {";
for (const auto& value : m_value->sharedValue->precisions) {
if (!firstPrecision) {
ss << ", ";
}
ss << value;
firstPrecision = false;
}
ss << "}";
return ss.str();
}
|
/**
* Copyright (C) 2011
* University of Rochester Department of Computer Science
* and
* Lehigh University Department of Computer Science and Engineering
*
* License: Modified BSD
* Please see the file LICENSE.RSTM for licensing information
*/
#include "algs.hpp"
#include "../cm.hpp"
namespace stm
{
/*** BACKING FOR GLOBAL METADATA */
/**
* This is the Orec Timestamp, the NOrec/TML seqlock, the CGL lock, and the
* RingSW ring index
*/
pad_word_t timestamp = {0};
/**
* Sometimes we use the Timestamp not as a counter, but as a bool. If we
* want to switch back to using it as a counter, we need to know what the
* old value was. This holds the old value.
*
* This is only used within STM implementations, to log and recover the
* value
*/
pad_word_t timestamp_max = {0};
/*** the set of orecs (locks) */
orec_t orecs[NUM_STRIPES] = {{{{0}}}};
/*** the set of nanorecs */
orec_t nanorecs[RING_ELEMENTS] = {{{{0}}}};
/*** the ring */
pad_word_t last_complete = {0};
pad_word_t last_init = {0};
filter_t ring_wf[RING_ELEMENTS] TM_ALIGN(16);
/*** priority stuff */
pad_word_t prioTxCount = {0};
rrec_t rrecs[RREC_COUNT] = {{{0}}};
/*** the table of bytelocks */
bytelock_t bytelocks[NUM_STRIPES] = {{0}};
/*** the table of bitlocks */
bitlock_t bitlocks[NUM_STRIPES] = {{0}};
/*** the array of epochs */
pad_word_t epochs[MAX_THREADS] = {{0}};
/*** Swiss greedy CM */
pad_word_t greedy_ts = {0};
/*** for MCS */
mcs_qnode_t* mcslock = NULL;
/*** for Ticket */
ticket_lock_t ticketlock = {0};
/*** for some CMs */
pad_word_t fcm_timestamp = {0};
/*** Store descriptions of the STM algorithms */
alg_t stms[ALG_MAX];
/*** for ProfileApp* */
dynprof_t* app_profiles = NULL;
/*** These are the adaptivity-related fields */
uint32_t profile_txns = 1; // number of txns per profile
dynprof_t* profiles = NULL; // where to store profiles
/*** Use the stms array to map a string name to an algorithm ID */
int stm_name_map(const char* phasename)
{
for (int i = 0; i < ALG_MAX; ++i)
if (0 == strcmp(phasename, stms[i].name))
return i;
return -1;
}
} // namespace stm
|
// Copyright (c) 2012-2014 The Bitcoin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "clientversion.h"
#include "tinyformat.h"
#include <string>
/**
* Name of client reported in the 'version' message. Report the same name
* for both Neptond and Nepton-qt, to make it harder for attackers to
* target servers or GUI users specifically.
*/
const std::string CLIENT_NAME("Nepton Core");
/**
* Client version number
*/
#define CLIENT_VERSION_SUFFIX ""
/**
* The following part of the code determines the CLIENT_BUILD variable.
* Several mechanisms are used for this:
* * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
* generated by the build environment, possibly containing the output
* of git-describe in a macro called BUILD_DESC
* * secondly, if this is an exported version of the code, GIT_ARCHIVE will
* be defined (automatically using the export-subst git attribute), and
* GIT_COMMIT will contain the commit id.
* * then, three options exist for determining CLIENT_BUILD:
* * if BUILD_DESC is defined, use that literally (output of git-describe)
* * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
* * otherwise, use v[maj].[min].[rev].[build]-unk
* finally CLIENT_VERSION_SUFFIX is added
*/
//! First, include build.h if requested
#ifdef HAVE_BUILD_INFO
#include "build.h"
#endif
//! git will put "#define GIT_ARCHIVE 1" on the next line inside archives.
#ifdef GIT_ARCHIVE
#define GIT_COMMIT_ID "cbcb549"
#define GIT_COMMIT_DATE "Tue, 9 Feb 2016 16:54:57 -0500"
#endif
#define BUILD_DESC_WITH_SUFFIX(maj, min, rev, build, suffix) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-" DO_STRINGIZE(suffix)
#define BUILD_DESC_FROM_COMMIT(maj, min, rev, build, commit) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit
#define BUILD_DESC_FROM_UNKNOWN(maj, min, rev, build) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk"
#ifndef BUILD_DESC
#ifdef BUILD_SUFFIX
#define BUILD_DESC BUILD_DESC_WITH_SUFFIX(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, BUILD_SUFFIX)
#elif defined(GIT_COMMIT_ID)
#define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID)
#else
#define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD)
#endif
#endif
#ifndef BUILD_DATE
#ifdef GIT_COMMIT_DATE
#define BUILD_DATE GIT_COMMIT_DATE
#else
#define BUILD_DATE __DATE__ ", " __TIME__
#endif
#endif
const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
const std::string CLIENT_DATE(BUILD_DATE);
static std::string FormatVersion(int nVersion)
{
if (nVersion % 100 == 0)
return strprintf("%d.%d.%d", nVersion / 1000000, (nVersion / 10000) % 100, (nVersion / 100) % 100);
else
return strprintf("%d.%d.%d.%d", nVersion / 1000000, (nVersion / 10000) % 100, (nVersion / 100) % 100, nVersion % 100);
}
std::string FormatFullVersion()
{
return CLIENT_BUILD;
}
/**
* Format the subversion field according to BIP 14 spec (https://github.com/bitcoin/bips/blob/master/bip-0014.mediawiki)
*/
std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments)
{
std::ostringstream ss;
ss << "/";
ss << name << ":" << FormatVersion(nClientVersion);
if (!comments.empty()) {
std::vector<std::string>::const_iterator it(comments.begin());
ss << "(" << *it;
for (++it; it != comments.end(); ++it)
ss << "; " << *it;
ss << ")";
}
ss << "/";
return ss.str();
}
|
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Support/FormatVariadic.h"
#include "mlir/IR/Attributes.h" // from @llvm-project
#include "mlir/IR/Builders.h" // from @llvm-project
#include "mlir/IR/BuiltinOps.h" // from @llvm-project
#include "mlir/Pass/Pass.h" // from @llvm-project
#include "mlir/Pass/PassManager.h" // from @llvm-project
#include "mlir/Pass/PassRegistry.h" // from @llvm-project
#include "mlir/Transforms/Passes.h" // from @llvm-project
#include "tensorflow/compiler/mlir/tensorflow/ir/tf_ops.h"
#include "tensorflow/compiler/mlir/tensorflow/ir/tf_structs.h"
#include "tensorflow/compiler/mlir/tensorflow/transforms/passes.h"
#include "tensorflow/compiler/mlir/tensorflow/utils/device_util.h"
#define DEBUG_TYPE "tf-layout-optimization"
namespace mlir {
namespace TF {
namespace {
#include "tensorflow/compiler/mlir/tensorflow/ir/tf_ops_helpers.inc"
// Helper method that returns an op from 'transpose_ops' that match criteria
// for an 'operand' and 'permutation'
TransposeOp ReuseExistingTranspose(const OpOperand* operand,
const SmallVector<int64_t, 4>& permutation,
Operation* op, ConstOp permutation_op,
SmallVector<TransposeOp, 2>* transpose_ops) {
for (auto it = transpose_ops->begin(); it != transpose_ops->end(); ++it) {
auto tranpose_op = *it;
for (auto tranpose_operand : tranpose_op.getOperands()) {
auto ranked_tranpose_type =
tranpose_operand.getType().dyn_cast_or_null<RankedTensorType>();
if (!ranked_tranpose_type) continue;
if (ranked_tranpose_type.getRank() == permutation.size() &&
operand->get().getType() ==
ShuffleRankedTensorType(ranked_tranpose_type, permutation)) {
TransposeOp transpose = tranpose_op;
transpose.getOperation()->moveBefore(op);
transpose.setOperand(0, operand->get());
transpose.setOperand(1, permutation_op);
transpose_ops->erase(it);
return transpose;
}
}
}
return nullptr;
}
// LayoutAssignmentPass assigns optimal data layout (data format) for all
// layout sensitive operations.
class LayoutAssignmentPass
: public PassWrapper<LayoutAssignmentPass, FunctionPass> {
public:
LayoutAssignmentPass() = default;
explicit LayoutAssignmentPass(const std::string& force_data_format) {
force_data_format_ = force_data_format;
}
LayoutAssignmentPass(const LayoutAssignmentPass& pass) {}
void runOnFunction() final;
private:
// Force a specified data format for all layout sensitive operations.
Option<std::string> force_data_format_{
*this, "force-data-format",
llvm::cl::desc("Force data format for all layout sensitive ops")};
};
// MoveTransposesPass moves all Transpose ops to the beginning or to the end of
// the basic block where they are defined. This will allow canonicalzer to
// delete redundant transposes.
class MoveTransposesPass
: public PassWrapper<MoveTransposesPass, FunctionPass> {
public:
enum class Direction { kBegin, kEnd };
MoveTransposesPass() = default;
explicit MoveTransposesPass(Direction direction, bool fold_transpose_in_ops) {
direction_ = direction;
fold_transpose_in_ops_ = fold_transpose_in_ops;
}
MoveTransposesPass(const MoveTransposesPass& pass) {}
void runOnFunction() final;
private:
Option<bool> fold_transpose_in_ops_{
*this, "fold-transpose-in-ops",
llvm::cl::desc(
"Whether to fold transposes in ops which can support folding."),
llvm::cl::init(true)};
Option<Direction> direction_{
*this, "direction",
llvm::cl::desc("Move transposes to the beginning or the end of the block "
"where they are defined."),
llvm::cl::values(
clEnumValN(Direction::kBegin, "begin", "beginning of the block"),
clEnumValN(Direction::kEnd, "end", "end of the block"))};
};
using Permutation = SmallVector<int64_t, 4>;
void LayoutAssignmentPass::runOnFunction() {
FuncOp func = getFunction();
// Get runtime devices information from the closest parent module.
RuntimeDevices devices;
if (failed(::tensorflow::GetDevicesFromOp(func->getParentOfType<ModuleOp>(),
&devices)))
return signalPassFailure();
// If there is no runtime device information and data format is not explicitly
// forced, there is nothing to do.
if (devices.NumDevices() == 0 && force_data_format_.empty()) return;
func.walk([&](LayoutSensitiveInterface layout_sensitive_interface) {
// Get desired op data format.
StringRef target_data_format = force_data_format_;
if (target_data_format.empty()) {
target_data_format = layout_sensitive_interface.GetOptimalLayout(devices);
}
// Skip ops that already use target data format.
auto data_format = layout_sensitive_interface.data_format();
if (data_format == target_data_format) return;
// Transpose arguments into the target data format.
Permutation args_permutation =
GetDataFormatPermutation(data_format, target_data_format);
// Transpose results back to the original data format.
Permutation res_permutation =
GetDataFormatPermutation(target_data_format, data_format);
if (args_permutation.empty() || res_permutation.empty()) return;
mlir::Operation* op = layout_sensitive_interface.getOperation();
Location loc = op->getLoc();
OpBuilder builder = OpBuilder::atBlockEnd(op->getBlock());
auto perm_attr = [&](Permutation permutation) -> DenseIntElementsAttr {
auto perm_ty = RankedTensorType::get({4}, builder.getIntegerType(64));
return DenseIntElementsAttr::get(perm_ty, permutation);
};
// Change operation data format.
if (failed(layout_sensitive_interface.UpdateDataFormat(target_data_format)))
return;
// Permute arguments into the target data format.
builder.setInsertionPoint(op);
auto arg_perm = builder.create<ConstOp>(loc, perm_attr(args_permutation));
for (int64_t arg : layout_sensitive_interface.GetLayoutDependentArgs()) {
op->setOperand(
arg, builder.create<TransposeOp>(loc, op->getOperand(arg), arg_perm));
}
// Permute results back to the original data format.
builder.setInsertionPointAfter(op);
auto res_perm = builder.create<ConstOp>(loc, perm_attr(res_permutation));
for (int64_t res : layout_sensitive_interface.GetLayoutDependentResults()) {
OpResult result = op->getResult(res);
auto transposed_res = builder.create<TransposeOp>(loc, result, res_perm);
result.replaceAllUsesWith(transposed_res);
transposed_res.setOperand(0, result);
}
});
}
// Move Transpose operations that permute `op` results before the `op`.
void MoveTransposeBefore(Operation* op, SmallVector<Operation*, 8>* work_list) {
// TODO(ezhulenev): Move transpose across layout sensitive operations.
if (!op->hasTrait<OpTrait::TF::LayoutAgnostic>()) return;
// Transpose operations that use operation results.
SmallVector<TransposeOp, 2> transpose_ops;
// Constant operation that defines permutation indices for result transposes.
ConstOp permutation_op;
// All operation results must be used by transpose operations with the same
// permutation indices.
for (OpResult result : op->getResults()) {
for (Operation* user : result.getUsers()) {
// Result user must be a transpose operation.
TransposeOp transpose = dyn_cast<TransposeOp>(user);
if (!transpose) return;
// With permutation defined by constant operation.
ConstOp perm =
dyn_cast_or_null<ConstOp>(transpose.getOperand(1).getDefiningOp());
if (!perm) return;
// With the same permutation indices.
auto dense_elem_attr = perm.value().dyn_cast<DenseElementsAttr>();
if (!dense_elem_attr) return;
if (!permutation_op) permutation_op = perm;
// Check that permutation matches for all result transposes.
if (perm.value() != permutation_op.value()) return;
// Add a transpose operation for later reuse.
transpose_ops.push_back(transpose);
}
}
// Nothing to do here.
if (!permutation_op || transpose_ops.empty()) return;
SmallVector<int64_t, 4> permutation;
auto perm_attr = permutation_op.value().cast<DenseElementsAttr>();
for (const auto& value : perm_attr.getIntValues())
permutation.push_back(value.getSExtValue());
// We want to make sure the shape of the operand equals the transposed shape.
// mismatch can happen if 'op' supports broadcasting and the operands have
// different ranks.
if (op->hasTrait<OpTrait::ResultsBroadcastableShape>()) {
auto transpose_op = *transpose_ops.begin();
auto result_type =
transpose_op.getResult().getType().dyn_cast_or_null<ShapedType>();
auto is_valid_move =
llvm::all_of(op->getOperands(), [result_type](Value operand) -> bool {
auto operand_type = operand.getType().dyn_cast_or_null<ShapedType>();
return result_type && operand_type && result_type.hasRank() &&
operand_type.hasRank() &&
result_type.getRank() == operand_type.getRank();
});
if (!is_valid_move) return;
}
// At this point we checked that we can safely move Transpose node before
// `op`, and bypass all result transposes.
Location loc = op->getLoc();
// Move constant op defining result permutation to the beginning of the block.
permutation_op.getOperation()->moveBefore(&op->getBlock()->front());
// Bypass Transpose nodes for all results.
for (OpResult result : op->getResults()) {
result.setType(cast<TransposeOp>(*result.getUsers().begin()).y().getType());
for (Operation* transpose : result.getUsers()) {
transpose->getResult(0).replaceAllUsesWith(result);
}
}
// Maybe add a Transpose node for all operands (or reuse existing transposes).
OpBuilder builder(op);
builder.setInsertionPoint(op);
for (OpOperand& operand : op->getOpOperands()) {
// Try to push transpose further up.
if (Operation* operand_op = operand.get().getDefiningOp())
work_list->push_back(operand_op);
// Try to reuse result transposes.
TransposeOp transpose = ReuseExistingTranspose(
&operand, permutation, op, permutation_op, &transpose_ops);
// If no transpose available for using, create new one.
if (!transpose)
transpose =
builder.create<TransposeOp>(loc, operand.get(), permutation_op);
operand.set(transpose);
}
// Remove unused transpose operations.
while (!transpose_ops.empty()) {
TransposeOp transpose = transpose_ops.pop_back_val();
transpose.erase();
}
}
// Move Transpose operations that permute `op` operands after the `op`.
void MoveTransposeAfter(Operation* op, SmallVector<Operation*, 8>* work_list,
bool fold_transpose_in_ops) {
// Indices of operands and results that depend on data layout.
SmallVector<unsigned, 4> layout_dependent_operands;
SmallVector<unsigned, 4> layout_dependent_results;
auto fold_operands = dyn_cast<FoldOperandsTransposeInterface>(op);
bool layout_agnostic = op->hasTrait<OpTrait::TF::LayoutAgnostic>();
if (fold_operands && fold_transpose_in_ops) {
layout_dependent_operands = fold_operands.GetLayoutDependentArgs();
layout_dependent_results = fold_operands.GetLayoutDependentResults();
} else if (layout_agnostic) {
// For layout agnostic operation (e.g. element wise operations) all operands
// and results must have the same data layout.
for (unsigned i = 0; i < op->getNumOperands(); ++i)
layout_dependent_operands.push_back(i);
for (unsigned i = 0; i < op->getNumResults(); ++i)
layout_dependent_results.push_back(i);
}
// Transpose operations that are operands of the `op`.
SmallVector<TransposeOp, 2> transpose_ops;
// Constant operation that defines permutation indices for operand transposes.
ConstOp permutation_op;
// Layout dependent operands must be transpose operations with the same
// permutation indices.
for (unsigned idx : layout_dependent_operands) {
OpOperand& operand = op->getOpOperand(idx);
// Operand must be defined by a transpose op.
TransposeOp transpose =
dyn_cast_or_null<TransposeOp>(operand.get().getDefiningOp());
if (!transpose) return;
// With permutation defined by constant operation.
ConstOp perm =
dyn_cast_or_null<ConstOp>(transpose.getOperand(1).getDefiningOp());
if (!perm) return;
// With the same permutation indices.
auto dense_elem_attr = perm.value().dyn_cast<DenseElementsAttr>();
if (!dense_elem_attr) return;
if (!permutation_op) permutation_op = perm;
// Check that permutation matches for all result transposes.
if (perm.value() != permutation_op.value()) return;
// Add a transpose operation for later reuse only if it's used once.
if (transpose.getResult().hasOneUse()) transpose_ops.push_back(transpose);
}
// Nothing to do here.
if (!permutation_op) return;
// All results after transpose must preserve the original result type.
SmallVector<Type, 4> original_type(op->getNumResults());
for (unsigned idx : layout_dependent_results)
original_type[idx] = op->getResult(idx).getType();
// Check if we can fold transpose into the operation.
if (fold_operands && fold_transpose_in_ops) {
SmallVector<int64_t, 8> permutation;
auto attr = permutation_op.value().cast<DenseElementsAttr>();
for (const auto& value : attr.getIntValues())
permutation.push_back(value.getSExtValue());
if (failed(fold_operands.FoldOperandsPermutation(permutation))) return;
}
// At this point we checked that we can safely move Transpose node after
// `op`, bypass all operands transposes, and transpose op results.
Location loc = op->getLoc();
// Move constant op defining result permutation to the beginning of the block.
permutation_op.getOperation()->moveBefore(&op->getBlock()->front());
// Bypass Transpose nodes for layout dependent operands.
for (unsigned idx : layout_dependent_operands) {
OpOperand& operand = op->getOpOperand(idx);
TransposeOp transpose =
dyn_cast<TransposeOp>(operand.get().getDefiningOp());
operand.set(transpose.getOperand(0));
}
// Maybe add Transpose nodes for layout dependent results
// (or reuse existing transposes).
OpBuilder builder(op);
builder.setInsertionPoint(op);
for (unsigned idx : layout_dependent_results) {
OpResult result = op->getResult(idx);
// Forward operand type only for layout agnostic operations, operations with
// custom folding will update the result type in `FoldOperandsPermutation`.
if (layout_agnostic) result.setType(op->getOperand(0).getType());
// Try to push transpose further down.
for (Operation* user : result.getUsers()) work_list->push_back(user);
// Try to reuse operand transposes.
TransposeOp transpose;
if (!transpose_ops.empty()) {
transpose = transpose_ops.pop_back_val();
transpose.getOperation()->moveBefore(op->getNextNode());
transpose.setOperand(0, result);
transpose.setOperand(1, permutation_op);
transpose.getResult().setType(original_type[idx]);
} else {
transpose = builder.create<TransposeOp>(loc, result, permutation_op);
}
// Forward all users to the transpose operation.
result.replaceAllUsesWith(transpose);
transpose.setOperand(0, result);
}
// Remove unused transpose operations.
while (!transpose_ops.empty()) {
TransposeOp transpose = transpose_ops.pop_back_val();
transpose.erase();
}
}
void MoveTransposesPass::runOnFunction() {
FuncOp func = getFunction();
SmallVector<Operation*, 8> work_list;
func.walk([&](TransposeOp transpose) {
if (direction_ == Direction::kBegin) {
// Try to push transpose before the operand operation.
for (auto operand : transpose.getOperands()) {
if (auto op = operand.getDefiningOp()) work_list.push_back(op);
}
} else {
// Try to push transpose after the user operation.
for (Operation* user : transpose.y().getUsers()) {
work_list.push_back(user);
}
}
});
while (!work_list.empty()) {
Operation* op = work_list.pop_back_val();
if (direction_ == Direction::kBegin) {
MoveTransposeBefore(op, &work_list);
} else if (direction_ == Direction::kEnd) {
MoveTransposeAfter(op, &work_list, fold_transpose_in_ops_);
}
}
func.walk([&](TransposeOp transpose) {
OpBuilder builder(transpose);
SmallVector<Value, 1> fold_result;
if (succeeded(builder.tryFold(transpose.getOperation(), fold_result))) {
assert(fold_result.size() == 1);
transpose.replaceAllUsesWith(fold_result[0]);
}
});
}
} // namespace
void CreateLayoutOptimizationPipeline(
OpPassManager& pm, // NOLINT - MLIR contract is pass by mutable reference.
const LayoutOptimizationPipelineOptions& options) {
using Direction = MoveTransposesPass::Direction;
// Assign optimal layout for layout sensitive ops.
pm.addPass(std::make_unique<LayoutAssignmentPass>(options.force_data_format));
// Move transposes to the beginning of the block and try to fold them.
pm.addPass(std::make_unique<MoveTransposesPass>(
Direction::kBegin, !options.skip_fold_transpose_in_ops));
// Move transposes to the end of the block and try to fold them.
pm.addPass(std::make_unique<MoveTransposesPass>(
Direction::kEnd, !options.skip_fold_transpose_in_ops));
}
static PassRegistration<LayoutAssignmentPass> layout_assignment(
"tf-layout-assignment", "Layout assignment pass");
static PassRegistration<MoveTransposesPass> move_transposes(
"tf-move-transposes", "Move transposes pass");
static mlir::PassPipelineRegistration<LayoutOptimizationPipelineOptions>
pipeline("tf-layout-optimization",
"Assigns optimal data layout to all layout sensitive operations "
"and cancel redundant transpose operations.",
CreateLayoutOptimizationPipeline);
} // namespace TF
} // namespace mlir
|
/**
* \file PnlWzskScfGeom.cpp
* job handler for job PnlWzskScfGeom (implementation)
* \copyright (C) 2016-2020 MPSI Technologies GmbH
* \author Emily Johnson (auto-generation)
* \date created: 5 Dec 2020
*/
// IP header --- ABOVE
#ifdef WZSKCMBD
#include <Wzskcmbd.h>
#else
#include <Wzskd.h>
#endif
#include "PnlWzskScfGeom.h"
#include "PnlWzskScfGeom_blks.cpp"
using namespace std;
using namespace Sbecore;
using namespace Xmlio;
// IP ns.cust --- INSERT
/******************************************************************************
class PnlWzskScfGeom
******************************************************************************/
PnlWzskScfGeom::PnlWzskScfGeom(
XchgWzsk* xchg
, DbsWzsk* dbswzsk
, const ubigint jrefSup
, const uint ixWzskVLocale
) :
JobWzsk(xchg, VecWzskVJob::PNLWZSKSCFGEOM, jrefSup, ixWzskVLocale)
{
jref = xchg->addJob(dbswzsk, this, jrefSup);
// IP constructor.cust1 --- INSERT
// IP constructor.cust2 --- INSERT
set<uint> moditems;
refresh(dbswzsk, moditems);
// IP constructor.cust3 --- INSERT
};
PnlWzskScfGeom::~PnlWzskScfGeom() {
// IP destructor.spec --- INSERT
// IP destructor.cust --- INSERT
xchg->removeJobByJref(jref);
};
// IP cust --- INSERT
DpchEngWzsk* PnlWzskScfGeom::getNewDpchEng(
set<uint> items
) {
DpchEngWzsk* dpcheng = NULL;
if (items.empty()) {
dpcheng = new DpchEngWzskConfirm(true, jref, "");
} else {
insert(items, DpchEngData::JREF);
dpcheng = new DpchEngData(jref, &statshr, items);
};
return dpcheng;
};
void PnlWzskScfGeom::refresh(
DbsWzsk* dbswzsk
, set<uint>& moditems
, const bool unmute
) {
if (muteRefresh && !unmute) return;
muteRefresh = true;
// IP refresh --- INSERT
muteRefresh = false;
};
void PnlWzskScfGeom::handleRequest(
DbsWzsk* dbswzsk
, ReqWzsk* req
) {
if (req->ixVBasetype == ReqWzsk::VecVBasetype::CMD) {
reqCmd = req;
if (req->cmd == "cmdset") {
} else {
cout << "\tinvalid command!" << endl;
};
if (!req->retain) reqCmd = NULL;
} else if (req->ixVBasetype == ReqWzsk::VecVBasetype::DPCHAPP) {
if (req->dpchapp->ixWzskVDpch == VecWzskVDpch::DPCHAPPWZSKINIT) {
handleDpchAppWzskInit(dbswzsk, (DpchAppWzskInit*) (req->dpchapp), &(req->dpcheng));
} else if (req->dpchapp->ixWzskVDpch == VecWzskVDpch::DPCHAPPWZSKSCFGEOMDO) {
DpchAppDo* dpchappdo = (DpchAppDo*) (req->dpchapp);
if (dpchappdo->ixVDo != 0) {
if (dpchappdo->ixVDo == VecVDo::BUTREGULARIZECLICK) {
handleDpchAppDoButRegularizeClick(dbswzsk, &(req->dpcheng));
} else if (dpchappdo->ixVDo == VecVDo::BUTMINIMIZECLICK) {
handleDpchAppDoButMinimizeClick(dbswzsk, &(req->dpcheng));
};
};
};
};
};
void PnlWzskScfGeom::handleDpchAppWzskInit(
DbsWzsk* dbswzsk
, DpchAppWzskInit* dpchappwzskinit
, DpchEngWzsk** dpcheng
) {
*dpcheng = getNewDpchEng({DpchEngData::ALL});
};
void PnlWzskScfGeom::handleDpchAppDoButRegularizeClick(
DbsWzsk* dbswzsk
, DpchEngWzsk** dpcheng
) {
// IP handleDpchAppDoButRegularizeClick --- BEGIN
statshr.ixWzskVExpstate = VecWzskVExpstate::REGD;
*dpcheng = getNewDpchEng({DpchEngData::STATSHR});
// IP handleDpchAppDoButRegularizeClick --- END
};
void PnlWzskScfGeom::handleDpchAppDoButMinimizeClick(
DbsWzsk* dbswzsk
, DpchEngWzsk** dpcheng
) {
// IP handleDpchAppDoButMinimizeClick --- BEGIN
statshr.ixWzskVExpstate = VecWzskVExpstate::MIND;
*dpcheng = getNewDpchEng({DpchEngData::STATSHR});
// IP handleDpchAppDoButMinimizeClick --- END
};
|
// stdafx.cpp : source file that includes just the standard includes
// Assignment2Animals.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
|
/*
IterativeYang.cxx
Author: Benjamin A. Thomas
Copyright 2013-2015 Institute of Nuclear Medicine, University College London.
Copyright 2014-2015 Clinical Imaging Research Centre, A*STAR-NUS.
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.
This program implements the Iterative Yang (IY) partial volume correction
(PVC) technique. Please cite the following paper:
Erlandsson, K. and Buvat, I. and Pretorius, P.H. and Thomas, B.A.
and Hutton, B.F., (2012). "A review of partial volume correction
techniques for emission tomography and their applications in neurology,
cardiology and oncology", Physics in Medicine and Biology,
vol. 57, no. 21, R119-59.
*/
#include "EnvironmentInfo.h"
#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include <metaCommand.h>
#include "petpvcFuzzyCorrectionFilter.h"
#include "petpvcIterativeYangPVCImageFilter.h"
typedef itk::Vector<float, 3> VectorType;
typedef itk::Image<float, 4> MaskImageType;
typedef itk::Image<float, 3> PETImageType;
typedef itk::ImageFileReader<MaskImageType> MaskReaderType;
typedef itk::ImageFileReader<PETImageType> PETReaderType;
typedef itk::ImageFileWriter<PETImageType> PETWriterType;
//Produces the text for the acknowledgments dialog in Slicer.
std::string getAcknowledgments(void);
int main(int argc, char *argv[])
{
itk::ImageToImageFilterCommon::SetGlobalDefaultCoordinateTolerance( 1e-2 );
itk::ImageToImageFilterCommon::SetGlobalDefaultDirectionTolerance( 1e-2 );
const char * const AUTHOR = "Benjamin A. Thomas";
const char * const APP_TITLE = "Iterative Yang (IY) PVC";
std::stringstream version_number;
version_number << VERSION_MAJOR << "." << VERSION_MINOR << "." << VERSION_PATCH;
const std::string VERSION_NO = version_number.str();
typedef petpvc::IterativeYangPVCImageFilter<PETImageType, MaskImageType> FilterType;
typedef petpvc::FuzzyCorrectionFilter< MaskImageType> FuzzyFilterType;
//Setting up command line argument list.
MetaCommand command;
command.SetVersion(VERSION_NO.c_str());
command.SetAuthor(AUTHOR);
command.SetName(APP_TITLE);
command.SetDescription(
"Performs iterative Yang (IY) partial volume correction");
std::string sAcks = getAcknowledgments();
command.SetAcknowledgments(sAcks.c_str());
command.SetCategory("PETPVC");
command.AddField("petfile", "PET filename", MetaCommand::IMAGE, MetaCommand::DATA_IN);
command.AddField("maskfile", "mask filename", MetaCommand::IMAGE, MetaCommand::DATA_IN);
command.AddField("outputfile", "output filename", MetaCommand::IMAGE, MetaCommand::DATA_OUT);
command.SetOption("FWHMx", "x", true,
"The full-width at half maximum in mm along x-axis");
command.AddOptionField("FWHMx", "X", MetaCommand::FLOAT, true, "");
command.SetOption("FWHMy", "y", true,
"The full-width at half maximum in mm along y-axis");
command.AddOptionField("FWHMy", "Y", MetaCommand::FLOAT, true, "");
command.SetOption("FWHMz", "z", true,
"The full-width at half maximum in mm along z-axis");
command.AddOptionField("FWHMz", "Z", MetaCommand::FLOAT, true, "");
command.SetOption("Iterations", "i", false, "Number of iterations");
command.SetOptionLongTag("Iterations", "iter");
command.AddOptionField("Iterations", "Val", MetaCommand::INT, false, "10");
command.SetOption("debug", "d", false,"Prints debug information");
command.SetOptionLongTag("debug", "debug");
//Parse command line.
if (!command.Parse(argc, argv)) {
return EXIT_FAILURE;
}
//Get image filenames
std::string sPETFileName = command.GetValueAsString("petfile");
std::string sMaskFileName = command.GetValueAsString("maskfile");
std::string sOutputFileName = command.GetValueAsString("outputfile");
//Get values for PSF.
float fFWHM_x = command.GetValueAsFloat("FWHMx", "X");
float fFWHM_y = command.GetValueAsFloat("FWHMy", "Y");
float fFWHM_z = command.GetValueAsFloat("FWHMz", "Z");
//Get number of iterations
int nNumOfIters = command.GetValueAsInt("Iterations", "Val");
//Make vector of FWHM in x,y and z.
VectorType vFWHM;
vFWHM[0] = fFWHM_x;
vFWHM[1] = fFWHM_y;
vFWHM[2] = fFWHM_z;
//Toggle debug mode
bool bDebug = command.GetValueAsBool("debug");
//Create reader for mask image.
MaskReaderType::Pointer maskReader = MaskReaderType::New();
maskReader->SetFileName(sMaskFileName);
//Try to read mask.
try {
maskReader->Update();
} catch (itk::ExceptionObject & err) {
std::cerr << "[Error]\tCannot read mask input file: " << sMaskFileName
<< std::endl;
return EXIT_FAILURE;
}
//Create reader for PET image.
PETReaderType::Pointer petReader = PETReaderType::New();
petReader->SetFileName(sPETFileName);
//Try to read PET.
try {
petReader->Update();
} catch (itk::ExceptionObject & err) {
std::cerr << "[Error]\tCannot read PET input file: " << sPETFileName
<< std::endl;
return EXIT_FAILURE;
}
//Calculate the variance for a given FWHM.
VectorType vVariance;
vVariance = vFWHM / (2.0 * sqrt(2.0 * log(2.0)));
//std::cout << vVariance << std::endl;
VectorType vVoxelSize = petReader->GetOutput()->GetSpacing();
//std::cout << vVoxelSize << std::endl;
vVariance[0] = pow(vVariance[0], 2);
vVariance[1] = pow(vVariance[1], 2);
vVariance[2] = pow(vVariance[2], 2);
FilterType::Pointer iyFilter = FilterType::New();
iyFilter->SetInput( petReader->GetOutput() );
iyFilter->SetMaskInput( maskReader->GetOutput() );
iyFilter->SetPSF(vVariance);
iyFilter->SetIterations( nNumOfIters );
iyFilter->SetVerbose ( bDebug );
//Perform IY.
try {
iyFilter->Update();
} catch (itk::ExceptionObject & err) {
std::cerr << "[Error]\tfailure applying Iterative Yang on: " << sPETFileName
<< "\n" << err
<< std::endl;
return EXIT_FAILURE;
}
PETWriterType::Pointer petWriter = PETWriterType::New();
petWriter->SetFileName(sOutputFileName);
petWriter->SetInput( iyFilter->GetOutput() );
try {
petWriter->Update();
} catch (itk::ExceptionObject & err) {
std::cerr << "\n[Error]\tCannot write output file: " << sOutputFileName
<< std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
std::string getAcknowledgments(void)
{
//Produces acknowledgments string for 3DSlicer.
std::string sAck = "This program implements the Iterative Yang (IY) partial volume correction (PVC) technique. Please cite the following paper:\n"
"\tErlandsson, K. and Buvat, I. and Pretorius, P.H. and Thomas, B.A. and Hutton, B.F., (2012).\n\t\"A review of partial volume correction techniques "
"for emission tomography and their applications in neurology, cardiology and oncology\", \n\tPhysics in Medicine and Biology, vol. 57, no. 21, R119-59.";
return sAck;
}
|
#include "qsidebutton.h"
#include "common/qstealth.h"
#define SC_QSS_SIDE_BTN_DEFAULT "background-color: transparent; border: none; outline: none;"
#define SC_QSS_SIDE_BTN_CLICKED "background-color: #00c6ff; border: none; outline: none;"
#define SC_QSS_SIDE_BTN_HOVER "background-color: #24ccfd; border: none; outline: none;"
QSideButton::QSideButton(QWidget *parent, int id) :
QPushButton(parent)
{
this->id = id;
this->deactivated = false;
// lblText = new QLabel(this);
lblIcon = new QLabel(this);
// lblText->setGeometry(80, 0, 170, 50);
lblIcon->setGeometry(0, 0, 250, 50);
// lblIcon->move(this->rect().center() - lblIcon->rect().center());
// lblText->setText(SC_getTitle(id));
connect(this, SIGNAL(clicked()), this, SLOT(slotClicked()));
setState(SC_BUTTON_STATE_DEFAULT);
}
void QSideButton::setState(SC_BUTTON_STATE state)
{
this->state = state;
// set icon
QString path = (state == SC_BUTTON_STATE_DEFAULT) ? SC_SIDEBAR_PATH_DEFAULT : SC_SIDEBAR_PATH_ACTIVE;
path += SC_getIconName(id);
path += ".png";
lblIcon->setStyleSheet("background-image: url(" + path + "); background-position: center; background-repeat: no-repeat; border: none; outline: none;");
// set text and color
// QString color = (state == SC_BUTTON_STATE_DEFAULT) ? SC_MAIN_COLOR_WHITE : SC_MAIN_COLOR_BLUE;
// lblText->setStyleSheet("background-image: url(); font-size: 14px; color: " + color + ";");
// for button back
if (this->deactivated) {
setStyleSheet(SC_QSS_SIDE_BTN_DEFAULT);
} else {
setStyleSheet(
state == SC_BUTTON_STATE_CLICKED ? SC_QSS_SIDE_BTN_CLICKED :
state == SC_BUTTON_STATE_DEFAULT ? SC_QSS_SIDE_BTN_DEFAULT : SC_QSS_SIDE_BTN_HOVER);
}
}
void QSideButton::setDeactivated(bool deactivate) {
this->deactivated = deactivate;
}
void QSideButton::enterEvent(QEvent *)
{
if ((state == SC_BUTTON_STATE_CLICKED) || this->deactivated) {
return;
}
setState(SC_BUTTON_STATE_HOVER);
}
void QSideButton::leaveEvent(QEvent *)
{
if ((state == SC_BUTTON_STATE_CLICKED) || this->deactivated) {
return;
}
setState(SC_BUTTON_STATE_DEFAULT);
}
void QSideButton::slotClicked()
{
if (!this->deactivated) {
emit clicked(id);
}
}
//void QSideButton::mouseReleaseEvent(QMouseEvent * e)
//{
// if (!rect().contains(e->pos())) return;
// emit clicked(id);
//}
|
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: edge-based-graph.proto
#include "edge-based-graph.pb.h"
#include <algorithm>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/extension_set.h>
#include <google/protobuf/wire_format_lite_inl.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/reflection_ops.h>
#include <google/protobuf/wire_format.h>
// @@protoc_insertion_point(includes)
#include <google/protobuf/port_def.inc>
extern PROTOBUF_INTERNAL_EXPORT_edge_2dbased_2dgraph_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_EdgeBasedNode_edge_2dbased_2dgraph_2eproto;
extern PROTOBUF_INTERNAL_EXPORT_edge_2dbased_2dgraph_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_NodeBasedAnnotation_edge_2dbased_2dgraph_2eproto;
namespace pbebg {
class EdgeBasedNodeDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<EdgeBasedNode> _instance;
} _EdgeBasedNode_default_instance_;
class NodeBasedAnnotationDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<NodeBasedAnnotation> _instance;
} _NodeBasedAnnotation_default_instance_;
class EdgeBasedNodeContainerDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<EdgeBasedNodeContainer> _instance;
} _EdgeBasedNodeContainer_default_instance_;
class TurnInstructionsDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<TurnInstructions> _instance;
} _TurnInstructions_default_instance_;
class TurnPenaltiesDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<TurnPenalties> _instance;
} _TurnPenalties_default_instance_;
} // namespace pbebg
static void InitDefaultsEdgeBasedNode_edge_2dbased_2dgraph_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::pbebg::_EdgeBasedNode_default_instance_;
new (ptr) ::pbebg::EdgeBasedNode();
::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
}
::pbebg::EdgeBasedNode::InitAsDefaultInstance();
}
::google::protobuf::internal::SCCInfo<0> scc_info_EdgeBasedNode_edge_2dbased_2dgraph_2eproto =
{{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsEdgeBasedNode_edge_2dbased_2dgraph_2eproto}, {}};
static void InitDefaultsNodeBasedAnnotation_edge_2dbased_2dgraph_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::pbebg::_NodeBasedAnnotation_default_instance_;
new (ptr) ::pbebg::NodeBasedAnnotation();
::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
}
::pbebg::NodeBasedAnnotation::InitAsDefaultInstance();
}
::google::protobuf::internal::SCCInfo<0> scc_info_NodeBasedAnnotation_edge_2dbased_2dgraph_2eproto =
{{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsNodeBasedAnnotation_edge_2dbased_2dgraph_2eproto}, {}};
static void InitDefaultsEdgeBasedNodeContainer_edge_2dbased_2dgraph_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::pbebg::_EdgeBasedNodeContainer_default_instance_;
new (ptr) ::pbebg::EdgeBasedNodeContainer();
::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
}
::pbebg::EdgeBasedNodeContainer::InitAsDefaultInstance();
}
::google::protobuf::internal::SCCInfo<2> scc_info_EdgeBasedNodeContainer_edge_2dbased_2dgraph_2eproto =
{{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 2, InitDefaultsEdgeBasedNodeContainer_edge_2dbased_2dgraph_2eproto}, {
&scc_info_EdgeBasedNode_edge_2dbased_2dgraph_2eproto.base,
&scc_info_NodeBasedAnnotation_edge_2dbased_2dgraph_2eproto.base,}};
static void InitDefaultsTurnInstructions_edge_2dbased_2dgraph_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::pbebg::_TurnInstructions_default_instance_;
new (ptr) ::pbebg::TurnInstructions();
::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
}
::pbebg::TurnInstructions::InitAsDefaultInstance();
}
::google::protobuf::internal::SCCInfo<0> scc_info_TurnInstructions_edge_2dbased_2dgraph_2eproto =
{{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsTurnInstructions_edge_2dbased_2dgraph_2eproto}, {}};
static void InitDefaultsTurnPenalties_edge_2dbased_2dgraph_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::pbebg::_TurnPenalties_default_instance_;
new (ptr) ::pbebg::TurnPenalties();
::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
}
::pbebg::TurnPenalties::InitAsDefaultInstance();
}
::google::protobuf::internal::SCCInfo<0> scc_info_TurnPenalties_edge_2dbased_2dgraph_2eproto =
{{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsTurnPenalties_edge_2dbased_2dgraph_2eproto}, {}};
void InitDefaults_edge_2dbased_2dgraph_2eproto() {
::google::protobuf::internal::InitSCC(&scc_info_EdgeBasedNode_edge_2dbased_2dgraph_2eproto.base);
::google::protobuf::internal::InitSCC(&scc_info_NodeBasedAnnotation_edge_2dbased_2dgraph_2eproto.base);
::google::protobuf::internal::InitSCC(&scc_info_EdgeBasedNodeContainer_edge_2dbased_2dgraph_2eproto.base);
::google::protobuf::internal::InitSCC(&scc_info_TurnInstructions_edge_2dbased_2dgraph_2eproto.base);
::google::protobuf::internal::InitSCC(&scc_info_TurnPenalties_edge_2dbased_2dgraph_2eproto.base);
}
::google::protobuf::Metadata file_level_metadata_edge_2dbased_2dgraph_2eproto[5];
constexpr ::google::protobuf::EnumDescriptor const** file_level_enum_descriptors_edge_2dbased_2dgraph_2eproto = nullptr;
constexpr ::google::protobuf::ServiceDescriptor const** file_level_service_descriptors_edge_2dbased_2dgraph_2eproto = nullptr;
const ::google::protobuf::uint32 TableStruct_edge_2dbased_2dgraph_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = {
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::pbebg::EdgeBasedNode, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
PROTOBUF_FIELD_OFFSET(::pbebg::EdgeBasedNode, geometry_id_),
PROTOBUF_FIELD_OFFSET(::pbebg::EdgeBasedNode, component_id_),
PROTOBUF_FIELD_OFFSET(::pbebg::EdgeBasedNode, annotation_id_),
PROTOBUF_FIELD_OFFSET(::pbebg::EdgeBasedNode, is_tiny_),
PROTOBUF_FIELD_OFFSET(::pbebg::EdgeBasedNode, segregated_),
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::pbebg::NodeBasedAnnotation, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
PROTOBUF_FIELD_OFFSET(::pbebg::NodeBasedAnnotation, name_id_),
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::pbebg::EdgeBasedNodeContainer, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
PROTOBUF_FIELD_OFFSET(::pbebg::EdgeBasedNodeContainer, nodes_),
PROTOBUF_FIELD_OFFSET(::pbebg::EdgeBasedNodeContainer, annotation_data_),
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::pbebg::TurnInstructions, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
PROTOBUF_FIELD_OFFSET(::pbebg::TurnInstructions, turn_instruction_),
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::pbebg::TurnPenalties, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
PROTOBUF_FIELD_OFFSET(::pbebg::TurnPenalties, turn_penalties_),
};
static const ::google::protobuf::internal::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = {
{ 0, -1, sizeof(::pbebg::EdgeBasedNode)},
{ 10, -1, sizeof(::pbebg::NodeBasedAnnotation)},
{ 16, -1, sizeof(::pbebg::EdgeBasedNodeContainer)},
{ 23, -1, sizeof(::pbebg::TurnInstructions)},
{ 29, -1, sizeof(::pbebg::TurnPenalties)},
};
static ::google::protobuf::Message const * const file_default_instances[] = {
reinterpret_cast<const ::google::protobuf::Message*>(&::pbebg::_EdgeBasedNode_default_instance_),
reinterpret_cast<const ::google::protobuf::Message*>(&::pbebg::_NodeBasedAnnotation_default_instance_),
reinterpret_cast<const ::google::protobuf::Message*>(&::pbebg::_EdgeBasedNodeContainer_default_instance_),
reinterpret_cast<const ::google::protobuf::Message*>(&::pbebg::_TurnInstructions_default_instance_),
reinterpret_cast<const ::google::protobuf::Message*>(&::pbebg::_TurnPenalties_default_instance_),
};
::google::protobuf::internal::AssignDescriptorsTable assign_descriptors_table_edge_2dbased_2dgraph_2eproto = {
{}, AddDescriptors_edge_2dbased_2dgraph_2eproto, "edge-based-graph.proto", schemas,
file_default_instances, TableStruct_edge_2dbased_2dgraph_2eproto::offsets,
file_level_metadata_edge_2dbased_2dgraph_2eproto, 5, file_level_enum_descriptors_edge_2dbased_2dgraph_2eproto, file_level_service_descriptors_edge_2dbased_2dgraph_2eproto,
};
const char descriptor_table_protodef_edge_2dbased_2dgraph_2eproto[] =
"\n\026edge-based-graph.proto\022\005pbebg\"v\n\rEdgeB"
"asedNode\022\023\n\013geometry_id\030\001 \001(\r\022\024\n\014compone"
"nt_id\030\002 \001(\r\022\025\n\rannotation_id\030\003 \001(\r\022\017\n\007is"
"_tiny\030\004 \001(\010\022\022\n\nsegregated\030\005 \001(\010\"&\n\023NodeB"
"asedAnnotation\022\017\n\007name_id\030\001 \001(\r\"r\n\026EdgeB"
"asedNodeContainer\022#\n\005nodes\030\001 \003(\0132\024.pbebg"
".EdgeBasedNode\0223\n\017annotation_data\030\002 \003(\0132"
"\032.pbebg.NodeBasedAnnotation\",\n\020TurnInstr"
"uctions\022\030\n\020turn_instruction\030\001 \003(\r\"\'\n\rTur"
"nPenalties\022\026\n\016turn_penalties\030\001 \003(\rb\006prot"
"o3"
;
::google::protobuf::internal::DescriptorTable descriptor_table_edge_2dbased_2dgraph_2eproto = {
false, InitDefaults_edge_2dbased_2dgraph_2eproto,
descriptor_table_protodef_edge_2dbased_2dgraph_2eproto,
"edge-based-graph.proto", &assign_descriptors_table_edge_2dbased_2dgraph_2eproto, 402,
};
void AddDescriptors_edge_2dbased_2dgraph_2eproto() {
static constexpr ::google::protobuf::internal::InitFunc deps[1] =
{
};
::google::protobuf::internal::AddDescriptors(&descriptor_table_edge_2dbased_2dgraph_2eproto, deps, 0);
}
// Force running AddDescriptors() at dynamic initialization time.
static bool dynamic_init_dummy_edge_2dbased_2dgraph_2eproto = []() { AddDescriptors_edge_2dbased_2dgraph_2eproto(); return true; }();
namespace pbebg {
// ===================================================================
void EdgeBasedNode::InitAsDefaultInstance() {
}
class EdgeBasedNode::HasBitSetters {
public:
};
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int EdgeBasedNode::kGeometryIdFieldNumber;
const int EdgeBasedNode::kComponentIdFieldNumber;
const int EdgeBasedNode::kAnnotationIdFieldNumber;
const int EdgeBasedNode::kIsTinyFieldNumber;
const int EdgeBasedNode::kSegregatedFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
EdgeBasedNode::EdgeBasedNode()
: ::google::protobuf::Message(), _internal_metadata_(nullptr) {
SharedCtor();
// @@protoc_insertion_point(constructor:pbebg.EdgeBasedNode)
}
EdgeBasedNode::EdgeBasedNode(const EdgeBasedNode& from)
: ::google::protobuf::Message(),
_internal_metadata_(nullptr) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
::memcpy(&geometry_id_, &from.geometry_id_,
static_cast<size_t>(reinterpret_cast<char*>(&segregated_) -
reinterpret_cast<char*>(&geometry_id_)) + sizeof(segregated_));
// @@protoc_insertion_point(copy_constructor:pbebg.EdgeBasedNode)
}
void EdgeBasedNode::SharedCtor() {
::memset(&geometry_id_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&segregated_) -
reinterpret_cast<char*>(&geometry_id_)) + sizeof(segregated_));
}
EdgeBasedNode::~EdgeBasedNode() {
// @@protoc_insertion_point(destructor:pbebg.EdgeBasedNode)
SharedDtor();
}
void EdgeBasedNode::SharedDtor() {
}
void EdgeBasedNode::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const EdgeBasedNode& EdgeBasedNode::default_instance() {
::google::protobuf::internal::InitSCC(&::scc_info_EdgeBasedNode_edge_2dbased_2dgraph_2eproto.base);
return *internal_default_instance();
}
void EdgeBasedNode::Clear() {
// @@protoc_insertion_point(message_clear_start:pbebg.EdgeBasedNode)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
::memset(&geometry_id_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&segregated_) -
reinterpret_cast<char*>(&geometry_id_)) + sizeof(segregated_));
_internal_metadata_.Clear();
}
#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
const char* EdgeBasedNode::_InternalParse(const char* begin, const char* end, void* object,
::google::protobuf::internal::ParseContext* ctx) {
auto msg = static_cast<EdgeBasedNode*>(object);
::google::protobuf::int32 size; (void)size;
int depth; (void)depth;
::google::protobuf::uint32 tag;
::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
auto ptr = begin;
while (ptr < end) {
ptr = ::google::protobuf::io::Parse32(ptr, &tag);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
switch (tag >> 3) {
// uint32 geometry_id = 1;
case 1: {
if (static_cast<::google::protobuf::uint8>(tag) != 8) goto handle_unusual;
msg->set_geometry_id(::google::protobuf::internal::ReadVarint(&ptr));
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
break;
}
// uint32 component_id = 2;
case 2: {
if (static_cast<::google::protobuf::uint8>(tag) != 16) goto handle_unusual;
msg->set_component_id(::google::protobuf::internal::ReadVarint(&ptr));
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
break;
}
// uint32 annotation_id = 3;
case 3: {
if (static_cast<::google::protobuf::uint8>(tag) != 24) goto handle_unusual;
msg->set_annotation_id(::google::protobuf::internal::ReadVarint(&ptr));
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
break;
}
// bool is_tiny = 4;
case 4: {
if (static_cast<::google::protobuf::uint8>(tag) != 32) goto handle_unusual;
msg->set_is_tiny(::google::protobuf::internal::ReadVarint(&ptr));
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
break;
}
// bool segregated = 5;
case 5: {
if (static_cast<::google::protobuf::uint8>(tag) != 40) goto handle_unusual;
msg->set_segregated(::google::protobuf::internal::ReadVarint(&ptr));
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
break;
}
default: {
handle_unusual:
if ((tag & 7) == 4 || tag == 0) {
ctx->EndGroup(tag);
return ptr;
}
auto res = UnknownFieldParse(tag, {_InternalParse, msg},
ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
ptr = res.first;
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr != nullptr);
if (res.second) return ptr;
}
} // switch
} // while
return ptr;
}
#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool EdgeBasedNode::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:pbebg.EdgeBasedNode)
for (;;) {
::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// uint32 geometry_id = 1;
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) == (8 & 0xFF)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>(
input, &geometry_id_)));
} else {
goto handle_unusual;
}
break;
}
// uint32 component_id = 2;
case 2: {
if (static_cast< ::google::protobuf::uint8>(tag) == (16 & 0xFF)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>(
input, &component_id_)));
} else {
goto handle_unusual;
}
break;
}
// uint32 annotation_id = 3;
case 3: {
if (static_cast< ::google::protobuf::uint8>(tag) == (24 & 0xFF)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>(
input, &annotation_id_)));
} else {
goto handle_unusual;
}
break;
}
// bool is_tiny = 4;
case 4: {
if (static_cast< ::google::protobuf::uint8>(tag) == (32 & 0xFF)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
input, &is_tiny_)));
} else {
goto handle_unusual;
}
break;
}
// bool segregated = 5;
case 5: {
if (static_cast< ::google::protobuf::uint8>(tag) == (40 & 0xFF)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
input, &segregated_)));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:pbebg.EdgeBasedNode)
return true;
failure:
// @@protoc_insertion_point(parse_failure:pbebg.EdgeBasedNode)
return false;
#undef DO_
}
#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void EdgeBasedNode::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:pbebg.EdgeBasedNode)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// uint32 geometry_id = 1;
if (this->geometry_id() != 0) {
::google::protobuf::internal::WireFormatLite::WriteUInt32(1, this->geometry_id(), output);
}
// uint32 component_id = 2;
if (this->component_id() != 0) {
::google::protobuf::internal::WireFormatLite::WriteUInt32(2, this->component_id(), output);
}
// uint32 annotation_id = 3;
if (this->annotation_id() != 0) {
::google::protobuf::internal::WireFormatLite::WriteUInt32(3, this->annotation_id(), output);
}
// bool is_tiny = 4;
if (this->is_tiny() != 0) {
::google::protobuf::internal::WireFormatLite::WriteBool(4, this->is_tiny(), output);
}
// bool segregated = 5;
if (this->segregated() != 0) {
::google::protobuf::internal::WireFormatLite::WriteBool(5, this->segregated(), output);
}
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:pbebg.EdgeBasedNode)
}
::google::protobuf::uint8* EdgeBasedNode::InternalSerializeWithCachedSizesToArray(
::google::protobuf::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:pbebg.EdgeBasedNode)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// uint32 geometry_id = 1;
if (this->geometry_id() != 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteUInt32ToArray(1, this->geometry_id(), target);
}
// uint32 component_id = 2;
if (this->component_id() != 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteUInt32ToArray(2, this->component_id(), target);
}
// uint32 annotation_id = 3;
if (this->annotation_id() != 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteUInt32ToArray(3, this->annotation_id(), target);
}
// bool is_tiny = 4;
if (this->is_tiny() != 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(4, this->is_tiny(), target);
}
// bool segregated = 5;
if (this->segregated() != 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(5, this->segregated(), target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:pbebg.EdgeBasedNode)
return target;
}
size_t EdgeBasedNode::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:pbebg.EdgeBasedNode)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
// uint32 geometry_id = 1;
if (this->geometry_id() != 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::UInt32Size(
this->geometry_id());
}
// uint32 component_id = 2;
if (this->component_id() != 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::UInt32Size(
this->component_id());
}
// uint32 annotation_id = 3;
if (this->annotation_id() != 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::UInt32Size(
this->annotation_id());
}
// bool is_tiny = 4;
if (this->is_tiny() != 0) {
total_size += 1 + 1;
}
// bool segregated = 5;
if (this->segregated() != 0) {
total_size += 1 + 1;
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void EdgeBasedNode::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:pbebg.EdgeBasedNode)
GOOGLE_DCHECK_NE(&from, this);
const EdgeBasedNode* source =
::google::protobuf::DynamicCastToGenerated<EdgeBasedNode>(
&from);
if (source == nullptr) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:pbebg.EdgeBasedNode)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:pbebg.EdgeBasedNode)
MergeFrom(*source);
}
}
void EdgeBasedNode::MergeFrom(const EdgeBasedNode& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:pbebg.EdgeBasedNode)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
if (from.geometry_id() != 0) {
set_geometry_id(from.geometry_id());
}
if (from.component_id() != 0) {
set_component_id(from.component_id());
}
if (from.annotation_id() != 0) {
set_annotation_id(from.annotation_id());
}
if (from.is_tiny() != 0) {
set_is_tiny(from.is_tiny());
}
if (from.segregated() != 0) {
set_segregated(from.segregated());
}
}
void EdgeBasedNode::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:pbebg.EdgeBasedNode)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void EdgeBasedNode::CopyFrom(const EdgeBasedNode& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:pbebg.EdgeBasedNode)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool EdgeBasedNode::IsInitialized() const {
return true;
}
void EdgeBasedNode::Swap(EdgeBasedNode* other) {
if (other == this) return;
InternalSwap(other);
}
void EdgeBasedNode::InternalSwap(EdgeBasedNode* other) {
using std::swap;
_internal_metadata_.Swap(&other->_internal_metadata_);
swap(geometry_id_, other->geometry_id_);
swap(component_id_, other->component_id_);
swap(annotation_id_, other->annotation_id_);
swap(is_tiny_, other->is_tiny_);
swap(segregated_, other->segregated_);
}
::google::protobuf::Metadata EdgeBasedNode::GetMetadata() const {
::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_edge_2dbased_2dgraph_2eproto);
return ::file_level_metadata_edge_2dbased_2dgraph_2eproto[kIndexInFileMessages];
}
// ===================================================================
void NodeBasedAnnotation::InitAsDefaultInstance() {
}
class NodeBasedAnnotation::HasBitSetters {
public:
};
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int NodeBasedAnnotation::kNameIdFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
NodeBasedAnnotation::NodeBasedAnnotation()
: ::google::protobuf::Message(), _internal_metadata_(nullptr) {
SharedCtor();
// @@protoc_insertion_point(constructor:pbebg.NodeBasedAnnotation)
}
NodeBasedAnnotation::NodeBasedAnnotation(const NodeBasedAnnotation& from)
: ::google::protobuf::Message(),
_internal_metadata_(nullptr) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
name_id_ = from.name_id_;
// @@protoc_insertion_point(copy_constructor:pbebg.NodeBasedAnnotation)
}
void NodeBasedAnnotation::SharedCtor() {
name_id_ = 0u;
}
NodeBasedAnnotation::~NodeBasedAnnotation() {
// @@protoc_insertion_point(destructor:pbebg.NodeBasedAnnotation)
SharedDtor();
}
void NodeBasedAnnotation::SharedDtor() {
}
void NodeBasedAnnotation::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const NodeBasedAnnotation& NodeBasedAnnotation::default_instance() {
::google::protobuf::internal::InitSCC(&::scc_info_NodeBasedAnnotation_edge_2dbased_2dgraph_2eproto.base);
return *internal_default_instance();
}
void NodeBasedAnnotation::Clear() {
// @@protoc_insertion_point(message_clear_start:pbebg.NodeBasedAnnotation)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
name_id_ = 0u;
_internal_metadata_.Clear();
}
#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
const char* NodeBasedAnnotation::_InternalParse(const char* begin, const char* end, void* object,
::google::protobuf::internal::ParseContext* ctx) {
auto msg = static_cast<NodeBasedAnnotation*>(object);
::google::protobuf::int32 size; (void)size;
int depth; (void)depth;
::google::protobuf::uint32 tag;
::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
auto ptr = begin;
while (ptr < end) {
ptr = ::google::protobuf::io::Parse32(ptr, &tag);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
switch (tag >> 3) {
// uint32 name_id = 1;
case 1: {
if (static_cast<::google::protobuf::uint8>(tag) != 8) goto handle_unusual;
msg->set_name_id(::google::protobuf::internal::ReadVarint(&ptr));
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
break;
}
default: {
handle_unusual:
if ((tag & 7) == 4 || tag == 0) {
ctx->EndGroup(tag);
return ptr;
}
auto res = UnknownFieldParse(tag, {_InternalParse, msg},
ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
ptr = res.first;
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr != nullptr);
if (res.second) return ptr;
}
} // switch
} // while
return ptr;
}
#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool NodeBasedAnnotation::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:pbebg.NodeBasedAnnotation)
for (;;) {
::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// uint32 name_id = 1;
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) == (8 & 0xFF)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>(
input, &name_id_)));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:pbebg.NodeBasedAnnotation)
return true;
failure:
// @@protoc_insertion_point(parse_failure:pbebg.NodeBasedAnnotation)
return false;
#undef DO_
}
#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void NodeBasedAnnotation::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:pbebg.NodeBasedAnnotation)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// uint32 name_id = 1;
if (this->name_id() != 0) {
::google::protobuf::internal::WireFormatLite::WriteUInt32(1, this->name_id(), output);
}
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:pbebg.NodeBasedAnnotation)
}
::google::protobuf::uint8* NodeBasedAnnotation::InternalSerializeWithCachedSizesToArray(
::google::protobuf::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:pbebg.NodeBasedAnnotation)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// uint32 name_id = 1;
if (this->name_id() != 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteUInt32ToArray(1, this->name_id(), target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:pbebg.NodeBasedAnnotation)
return target;
}
size_t NodeBasedAnnotation::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:pbebg.NodeBasedAnnotation)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
// uint32 name_id = 1;
if (this->name_id() != 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::UInt32Size(
this->name_id());
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void NodeBasedAnnotation::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:pbebg.NodeBasedAnnotation)
GOOGLE_DCHECK_NE(&from, this);
const NodeBasedAnnotation* source =
::google::protobuf::DynamicCastToGenerated<NodeBasedAnnotation>(
&from);
if (source == nullptr) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:pbebg.NodeBasedAnnotation)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:pbebg.NodeBasedAnnotation)
MergeFrom(*source);
}
}
void NodeBasedAnnotation::MergeFrom(const NodeBasedAnnotation& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:pbebg.NodeBasedAnnotation)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
if (from.name_id() != 0) {
set_name_id(from.name_id());
}
}
void NodeBasedAnnotation::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:pbebg.NodeBasedAnnotation)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void NodeBasedAnnotation::CopyFrom(const NodeBasedAnnotation& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:pbebg.NodeBasedAnnotation)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool NodeBasedAnnotation::IsInitialized() const {
return true;
}
void NodeBasedAnnotation::Swap(NodeBasedAnnotation* other) {
if (other == this) return;
InternalSwap(other);
}
void NodeBasedAnnotation::InternalSwap(NodeBasedAnnotation* other) {
using std::swap;
_internal_metadata_.Swap(&other->_internal_metadata_);
swap(name_id_, other->name_id_);
}
::google::protobuf::Metadata NodeBasedAnnotation::GetMetadata() const {
::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_edge_2dbased_2dgraph_2eproto);
return ::file_level_metadata_edge_2dbased_2dgraph_2eproto[kIndexInFileMessages];
}
// ===================================================================
void EdgeBasedNodeContainer::InitAsDefaultInstance() {
}
class EdgeBasedNodeContainer::HasBitSetters {
public:
};
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int EdgeBasedNodeContainer::kNodesFieldNumber;
const int EdgeBasedNodeContainer::kAnnotationDataFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
EdgeBasedNodeContainer::EdgeBasedNodeContainer()
: ::google::protobuf::Message(), _internal_metadata_(nullptr) {
SharedCtor();
// @@protoc_insertion_point(constructor:pbebg.EdgeBasedNodeContainer)
}
EdgeBasedNodeContainer::EdgeBasedNodeContainer(const EdgeBasedNodeContainer& from)
: ::google::protobuf::Message(),
_internal_metadata_(nullptr),
nodes_(from.nodes_),
annotation_data_(from.annotation_data_) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
// @@protoc_insertion_point(copy_constructor:pbebg.EdgeBasedNodeContainer)
}
void EdgeBasedNodeContainer::SharedCtor() {
::google::protobuf::internal::InitSCC(
&scc_info_EdgeBasedNodeContainer_edge_2dbased_2dgraph_2eproto.base);
}
EdgeBasedNodeContainer::~EdgeBasedNodeContainer() {
// @@protoc_insertion_point(destructor:pbebg.EdgeBasedNodeContainer)
SharedDtor();
}
void EdgeBasedNodeContainer::SharedDtor() {
}
void EdgeBasedNodeContainer::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const EdgeBasedNodeContainer& EdgeBasedNodeContainer::default_instance() {
::google::protobuf::internal::InitSCC(&::scc_info_EdgeBasedNodeContainer_edge_2dbased_2dgraph_2eproto.base);
return *internal_default_instance();
}
void EdgeBasedNodeContainer::Clear() {
// @@protoc_insertion_point(message_clear_start:pbebg.EdgeBasedNodeContainer)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
nodes_.Clear();
annotation_data_.Clear();
_internal_metadata_.Clear();
}
#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
const char* EdgeBasedNodeContainer::_InternalParse(const char* begin, const char* end, void* object,
::google::protobuf::internal::ParseContext* ctx) {
auto msg = static_cast<EdgeBasedNodeContainer*>(object);
::google::protobuf::int32 size; (void)size;
int depth; (void)depth;
::google::protobuf::uint32 tag;
::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
auto ptr = begin;
while (ptr < end) {
ptr = ::google::protobuf::io::Parse32(ptr, &tag);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
switch (tag >> 3) {
// repeated .pbebg.EdgeBasedNode nodes = 1;
case 1: {
if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual;
do {
ptr = ::google::protobuf::io::ReadSize(ptr, &size);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
parser_till_end = ::pbebg::EdgeBasedNode::_InternalParse;
object = msg->add_nodes();
if (size > end - ptr) goto len_delim_till_end;
ptr += size;
GOOGLE_PROTOBUF_PARSER_ASSERT(ctx->ParseExactRange(
{parser_till_end, object}, ptr - size, ptr));
if (ptr >= end) break;
} while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 10 && (ptr += 1));
break;
}
// repeated .pbebg.NodeBasedAnnotation annotation_data = 2;
case 2: {
if (static_cast<::google::protobuf::uint8>(tag) != 18) goto handle_unusual;
do {
ptr = ::google::protobuf::io::ReadSize(ptr, &size);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
parser_till_end = ::pbebg::NodeBasedAnnotation::_InternalParse;
object = msg->add_annotation_data();
if (size > end - ptr) goto len_delim_till_end;
ptr += size;
GOOGLE_PROTOBUF_PARSER_ASSERT(ctx->ParseExactRange(
{parser_till_end, object}, ptr - size, ptr));
if (ptr >= end) break;
} while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 18 && (ptr += 1));
break;
}
default: {
handle_unusual:
if ((tag & 7) == 4 || tag == 0) {
ctx->EndGroup(tag);
return ptr;
}
auto res = UnknownFieldParse(tag, {_InternalParse, msg},
ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
ptr = res.first;
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr != nullptr);
if (res.second) return ptr;
}
} // switch
} // while
return ptr;
len_delim_till_end:
return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
{parser_till_end, object}, size);
}
#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool EdgeBasedNodeContainer::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:pbebg.EdgeBasedNodeContainer)
for (;;) {
::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// repeated .pbebg.EdgeBasedNode nodes = 1;
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, add_nodes()));
} else {
goto handle_unusual;
}
break;
}
// repeated .pbebg.NodeBasedAnnotation annotation_data = 2;
case 2: {
if (static_cast< ::google::protobuf::uint8>(tag) == (18 & 0xFF)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, add_annotation_data()));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:pbebg.EdgeBasedNodeContainer)
return true;
failure:
// @@protoc_insertion_point(parse_failure:pbebg.EdgeBasedNodeContainer)
return false;
#undef DO_
}
#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void EdgeBasedNodeContainer::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:pbebg.EdgeBasedNodeContainer)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// repeated .pbebg.EdgeBasedNode nodes = 1;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->nodes_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
1,
this->nodes(static_cast<int>(i)),
output);
}
// repeated .pbebg.NodeBasedAnnotation annotation_data = 2;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->annotation_data_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
2,
this->annotation_data(static_cast<int>(i)),
output);
}
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:pbebg.EdgeBasedNodeContainer)
}
::google::protobuf::uint8* EdgeBasedNodeContainer::InternalSerializeWithCachedSizesToArray(
::google::protobuf::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:pbebg.EdgeBasedNodeContainer)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// repeated .pbebg.EdgeBasedNode nodes = 1;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->nodes_size()); i < n; i++) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
1, this->nodes(static_cast<int>(i)), target);
}
// repeated .pbebg.NodeBasedAnnotation annotation_data = 2;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->annotation_data_size()); i < n; i++) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
2, this->annotation_data(static_cast<int>(i)), target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:pbebg.EdgeBasedNodeContainer)
return target;
}
size_t EdgeBasedNodeContainer::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:pbebg.EdgeBasedNodeContainer)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
// repeated .pbebg.EdgeBasedNode nodes = 1;
{
unsigned int count = static_cast<unsigned int>(this->nodes_size());
total_size += 1UL * count;
for (unsigned int i = 0; i < count; i++) {
total_size +=
::google::protobuf::internal::WireFormatLite::MessageSize(
this->nodes(static_cast<int>(i)));
}
}
// repeated .pbebg.NodeBasedAnnotation annotation_data = 2;
{
unsigned int count = static_cast<unsigned int>(this->annotation_data_size());
total_size += 1UL * count;
for (unsigned int i = 0; i < count; i++) {
total_size +=
::google::protobuf::internal::WireFormatLite::MessageSize(
this->annotation_data(static_cast<int>(i)));
}
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void EdgeBasedNodeContainer::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:pbebg.EdgeBasedNodeContainer)
GOOGLE_DCHECK_NE(&from, this);
const EdgeBasedNodeContainer* source =
::google::protobuf::DynamicCastToGenerated<EdgeBasedNodeContainer>(
&from);
if (source == nullptr) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:pbebg.EdgeBasedNodeContainer)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:pbebg.EdgeBasedNodeContainer)
MergeFrom(*source);
}
}
void EdgeBasedNodeContainer::MergeFrom(const EdgeBasedNodeContainer& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:pbebg.EdgeBasedNodeContainer)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
nodes_.MergeFrom(from.nodes_);
annotation_data_.MergeFrom(from.annotation_data_);
}
void EdgeBasedNodeContainer::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:pbebg.EdgeBasedNodeContainer)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void EdgeBasedNodeContainer::CopyFrom(const EdgeBasedNodeContainer& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:pbebg.EdgeBasedNodeContainer)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool EdgeBasedNodeContainer::IsInitialized() const {
return true;
}
void EdgeBasedNodeContainer::Swap(EdgeBasedNodeContainer* other) {
if (other == this) return;
InternalSwap(other);
}
void EdgeBasedNodeContainer::InternalSwap(EdgeBasedNodeContainer* other) {
using std::swap;
_internal_metadata_.Swap(&other->_internal_metadata_);
CastToBase(&nodes_)->InternalSwap(CastToBase(&other->nodes_));
CastToBase(&annotation_data_)->InternalSwap(CastToBase(&other->annotation_data_));
}
::google::protobuf::Metadata EdgeBasedNodeContainer::GetMetadata() const {
::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_edge_2dbased_2dgraph_2eproto);
return ::file_level_metadata_edge_2dbased_2dgraph_2eproto[kIndexInFileMessages];
}
// ===================================================================
void TurnInstructions::InitAsDefaultInstance() {
}
class TurnInstructions::HasBitSetters {
public:
};
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int TurnInstructions::kTurnInstructionFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
TurnInstructions::TurnInstructions()
: ::google::protobuf::Message(), _internal_metadata_(nullptr) {
SharedCtor();
// @@protoc_insertion_point(constructor:pbebg.TurnInstructions)
}
TurnInstructions::TurnInstructions(const TurnInstructions& from)
: ::google::protobuf::Message(),
_internal_metadata_(nullptr),
turn_instruction_(from.turn_instruction_) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
// @@protoc_insertion_point(copy_constructor:pbebg.TurnInstructions)
}
void TurnInstructions::SharedCtor() {
}
TurnInstructions::~TurnInstructions() {
// @@protoc_insertion_point(destructor:pbebg.TurnInstructions)
SharedDtor();
}
void TurnInstructions::SharedDtor() {
}
void TurnInstructions::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const TurnInstructions& TurnInstructions::default_instance() {
::google::protobuf::internal::InitSCC(&::scc_info_TurnInstructions_edge_2dbased_2dgraph_2eproto.base);
return *internal_default_instance();
}
void TurnInstructions::Clear() {
// @@protoc_insertion_point(message_clear_start:pbebg.TurnInstructions)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
turn_instruction_.Clear();
_internal_metadata_.Clear();
}
#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
const char* TurnInstructions::_InternalParse(const char* begin, const char* end, void* object,
::google::protobuf::internal::ParseContext* ctx) {
auto msg = static_cast<TurnInstructions*>(object);
::google::protobuf::int32 size; (void)size;
int depth; (void)depth;
::google::protobuf::uint32 tag;
::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
auto ptr = begin;
while (ptr < end) {
ptr = ::google::protobuf::io::Parse32(ptr, &tag);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
switch (tag >> 3) {
// repeated uint32 turn_instruction = 1;
case 1: {
if (static_cast<::google::protobuf::uint8>(tag) == 10) {
ptr = ::google::protobuf::io::ReadSize(ptr, &size);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
parser_till_end = ::google::protobuf::internal::PackedUInt32Parser;
object = msg->mutable_turn_instruction();
if (size > end - ptr) goto len_delim_till_end;
auto newend = ptr + size;
if (size) ptr = parser_till_end(ptr, newend, object, ctx);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend);
break;
} else if (static_cast<::google::protobuf::uint8>(tag) != 8) goto handle_unusual;
do {
msg->add_turn_instruction(::google::protobuf::internal::ReadVarint(&ptr));
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
if (ptr >= end) break;
} while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 8 && (ptr += 1));
break;
}
default: {
handle_unusual:
if ((tag & 7) == 4 || tag == 0) {
ctx->EndGroup(tag);
return ptr;
}
auto res = UnknownFieldParse(tag, {_InternalParse, msg},
ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
ptr = res.first;
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr != nullptr);
if (res.second) return ptr;
}
} // switch
} // while
return ptr;
len_delim_till_end:
return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
{parser_till_end, object}, size);
}
#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool TurnInstructions::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:pbebg.TurnInstructions)
for (;;) {
::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// repeated uint32 turn_instruction = 1;
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPackedPrimitive<
::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>(
input, this->mutable_turn_instruction())));
} else if (static_cast< ::google::protobuf::uint8>(tag) == (8 & 0xFF)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadRepeatedPrimitiveNoInline<
::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>(
1, 10u, input, this->mutable_turn_instruction())));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:pbebg.TurnInstructions)
return true;
failure:
// @@protoc_insertion_point(parse_failure:pbebg.TurnInstructions)
return false;
#undef DO_
}
#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void TurnInstructions::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:pbebg.TurnInstructions)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// repeated uint32 turn_instruction = 1;
if (this->turn_instruction_size() > 0) {
::google::protobuf::internal::WireFormatLite::WriteTag(1, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, output);
output->WriteVarint32(_turn_instruction_cached_byte_size_.load(
std::memory_order_relaxed));
}
for (int i = 0, n = this->turn_instruction_size(); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteUInt32NoTag(
this->turn_instruction(i), output);
}
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:pbebg.TurnInstructions)
}
::google::protobuf::uint8* TurnInstructions::InternalSerializeWithCachedSizesToArray(
::google::protobuf::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:pbebg.TurnInstructions)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// repeated uint32 turn_instruction = 1;
if (this->turn_instruction_size() > 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteTagToArray(
1,
::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED,
target);
target = ::google::protobuf::io::CodedOutputStream::WriteVarint32ToArray(
_turn_instruction_cached_byte_size_.load(std::memory_order_relaxed),
target);
target = ::google::protobuf::internal::WireFormatLite::
WriteUInt32NoTagToArray(this->turn_instruction_, target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:pbebg.TurnInstructions)
return target;
}
size_t TurnInstructions::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:pbebg.TurnInstructions)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
// repeated uint32 turn_instruction = 1;
{
size_t data_size = ::google::protobuf::internal::WireFormatLite::
UInt32Size(this->turn_instruction_);
if (data_size > 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
static_cast<::google::protobuf::int32>(data_size));
}
int cached_size = ::google::protobuf::internal::ToCachedSize(data_size);
_turn_instruction_cached_byte_size_.store(cached_size,
std::memory_order_relaxed);
total_size += data_size;
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void TurnInstructions::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:pbebg.TurnInstructions)
GOOGLE_DCHECK_NE(&from, this);
const TurnInstructions* source =
::google::protobuf::DynamicCastToGenerated<TurnInstructions>(
&from);
if (source == nullptr) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:pbebg.TurnInstructions)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:pbebg.TurnInstructions)
MergeFrom(*source);
}
}
void TurnInstructions::MergeFrom(const TurnInstructions& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:pbebg.TurnInstructions)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
turn_instruction_.MergeFrom(from.turn_instruction_);
}
void TurnInstructions::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:pbebg.TurnInstructions)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void TurnInstructions::CopyFrom(const TurnInstructions& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:pbebg.TurnInstructions)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool TurnInstructions::IsInitialized() const {
return true;
}
void TurnInstructions::Swap(TurnInstructions* other) {
if (other == this) return;
InternalSwap(other);
}
void TurnInstructions::InternalSwap(TurnInstructions* other) {
using std::swap;
_internal_metadata_.Swap(&other->_internal_metadata_);
turn_instruction_.InternalSwap(&other->turn_instruction_);
}
::google::protobuf::Metadata TurnInstructions::GetMetadata() const {
::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_edge_2dbased_2dgraph_2eproto);
return ::file_level_metadata_edge_2dbased_2dgraph_2eproto[kIndexInFileMessages];
}
// ===================================================================
void TurnPenalties::InitAsDefaultInstance() {
}
class TurnPenalties::HasBitSetters {
public:
};
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int TurnPenalties::kTurnPenaltiesFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
TurnPenalties::TurnPenalties()
: ::google::protobuf::Message(), _internal_metadata_(nullptr) {
SharedCtor();
// @@protoc_insertion_point(constructor:pbebg.TurnPenalties)
}
TurnPenalties::TurnPenalties(const TurnPenalties& from)
: ::google::protobuf::Message(),
_internal_metadata_(nullptr),
turn_penalties_(from.turn_penalties_) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
// @@protoc_insertion_point(copy_constructor:pbebg.TurnPenalties)
}
void TurnPenalties::SharedCtor() {
}
TurnPenalties::~TurnPenalties() {
// @@protoc_insertion_point(destructor:pbebg.TurnPenalties)
SharedDtor();
}
void TurnPenalties::SharedDtor() {
}
void TurnPenalties::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const TurnPenalties& TurnPenalties::default_instance() {
::google::protobuf::internal::InitSCC(&::scc_info_TurnPenalties_edge_2dbased_2dgraph_2eproto.base);
return *internal_default_instance();
}
void TurnPenalties::Clear() {
// @@protoc_insertion_point(message_clear_start:pbebg.TurnPenalties)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
turn_penalties_.Clear();
_internal_metadata_.Clear();
}
#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
const char* TurnPenalties::_InternalParse(const char* begin, const char* end, void* object,
::google::protobuf::internal::ParseContext* ctx) {
auto msg = static_cast<TurnPenalties*>(object);
::google::protobuf::int32 size; (void)size;
int depth; (void)depth;
::google::protobuf::uint32 tag;
::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end;
auto ptr = begin;
while (ptr < end) {
ptr = ::google::protobuf::io::Parse32(ptr, &tag);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
switch (tag >> 3) {
// repeated uint32 turn_penalties = 1;
case 1: {
if (static_cast<::google::protobuf::uint8>(tag) == 10) {
ptr = ::google::protobuf::io::ReadSize(ptr, &size);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
parser_till_end = ::google::protobuf::internal::PackedUInt32Parser;
object = msg->mutable_turn_penalties();
if (size > end - ptr) goto len_delim_till_end;
auto newend = ptr + size;
if (size) ptr = parser_till_end(ptr, newend, object, ctx);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend);
break;
} else if (static_cast<::google::protobuf::uint8>(tag) != 8) goto handle_unusual;
do {
msg->add_turn_penalties(::google::protobuf::internal::ReadVarint(&ptr));
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
if (ptr >= end) break;
} while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 8 && (ptr += 1));
break;
}
default: {
handle_unusual:
if ((tag & 7) == 4 || tag == 0) {
ctx->EndGroup(tag);
return ptr;
}
auto res = UnknownFieldParse(tag, {_InternalParse, msg},
ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx);
ptr = res.first;
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr != nullptr);
if (res.second) return ptr;
}
} // switch
} // while
return ptr;
len_delim_till_end:
return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg},
{parser_till_end, object}, size);
}
#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool TurnPenalties::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:pbebg.TurnPenalties)
for (;;) {
::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// repeated uint32 turn_penalties = 1;
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPackedPrimitive<
::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>(
input, this->mutable_turn_penalties())));
} else if (static_cast< ::google::protobuf::uint8>(tag) == (8 & 0xFF)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadRepeatedPrimitiveNoInline<
::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>(
1, 10u, input, this->mutable_turn_penalties())));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:pbebg.TurnPenalties)
return true;
failure:
// @@protoc_insertion_point(parse_failure:pbebg.TurnPenalties)
return false;
#undef DO_
}
#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void TurnPenalties::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:pbebg.TurnPenalties)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// repeated uint32 turn_penalties = 1;
if (this->turn_penalties_size() > 0) {
::google::protobuf::internal::WireFormatLite::WriteTag(1, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, output);
output->WriteVarint32(_turn_penalties_cached_byte_size_.load(
std::memory_order_relaxed));
}
for (int i = 0, n = this->turn_penalties_size(); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteUInt32NoTag(
this->turn_penalties(i), output);
}
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:pbebg.TurnPenalties)
}
::google::protobuf::uint8* TurnPenalties::InternalSerializeWithCachedSizesToArray(
::google::protobuf::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:pbebg.TurnPenalties)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// repeated uint32 turn_penalties = 1;
if (this->turn_penalties_size() > 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteTagToArray(
1,
::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED,
target);
target = ::google::protobuf::io::CodedOutputStream::WriteVarint32ToArray(
_turn_penalties_cached_byte_size_.load(std::memory_order_relaxed),
target);
target = ::google::protobuf::internal::WireFormatLite::
WriteUInt32NoTagToArray(this->turn_penalties_, target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:pbebg.TurnPenalties)
return target;
}
size_t TurnPenalties::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:pbebg.TurnPenalties)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
// repeated uint32 turn_penalties = 1;
{
size_t data_size = ::google::protobuf::internal::WireFormatLite::
UInt32Size(this->turn_penalties_);
if (data_size > 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
static_cast<::google::protobuf::int32>(data_size));
}
int cached_size = ::google::protobuf::internal::ToCachedSize(data_size);
_turn_penalties_cached_byte_size_.store(cached_size,
std::memory_order_relaxed);
total_size += data_size;
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void TurnPenalties::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:pbebg.TurnPenalties)
GOOGLE_DCHECK_NE(&from, this);
const TurnPenalties* source =
::google::protobuf::DynamicCastToGenerated<TurnPenalties>(
&from);
if (source == nullptr) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:pbebg.TurnPenalties)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:pbebg.TurnPenalties)
MergeFrom(*source);
}
}
void TurnPenalties::MergeFrom(const TurnPenalties& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:pbebg.TurnPenalties)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
turn_penalties_.MergeFrom(from.turn_penalties_);
}
void TurnPenalties::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:pbebg.TurnPenalties)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void TurnPenalties::CopyFrom(const TurnPenalties& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:pbebg.TurnPenalties)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool TurnPenalties::IsInitialized() const {
return true;
}
void TurnPenalties::Swap(TurnPenalties* other) {
if (other == this) return;
InternalSwap(other);
}
void TurnPenalties::InternalSwap(TurnPenalties* other) {
using std::swap;
_internal_metadata_.Swap(&other->_internal_metadata_);
turn_penalties_.InternalSwap(&other->turn_penalties_);
}
::google::protobuf::Metadata TurnPenalties::GetMetadata() const {
::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_edge_2dbased_2dgraph_2eproto);
return ::file_level_metadata_edge_2dbased_2dgraph_2eproto[kIndexInFileMessages];
}
// @@protoc_insertion_point(namespace_scope)
} // namespace pbebg
namespace google {
namespace protobuf {
template<> PROTOBUF_NOINLINE ::pbebg::EdgeBasedNode* Arena::CreateMaybeMessage< ::pbebg::EdgeBasedNode >(Arena* arena) {
return Arena::CreateInternal< ::pbebg::EdgeBasedNode >(arena);
}
template<> PROTOBUF_NOINLINE ::pbebg::NodeBasedAnnotation* Arena::CreateMaybeMessage< ::pbebg::NodeBasedAnnotation >(Arena* arena) {
return Arena::CreateInternal< ::pbebg::NodeBasedAnnotation >(arena);
}
template<> PROTOBUF_NOINLINE ::pbebg::EdgeBasedNodeContainer* Arena::CreateMaybeMessage< ::pbebg::EdgeBasedNodeContainer >(Arena* arena) {
return Arena::CreateInternal< ::pbebg::EdgeBasedNodeContainer >(arena);
}
template<> PROTOBUF_NOINLINE ::pbebg::TurnInstructions* Arena::CreateMaybeMessage< ::pbebg::TurnInstructions >(Arena* arena) {
return Arena::CreateInternal< ::pbebg::TurnInstructions >(arena);
}
template<> PROTOBUF_NOINLINE ::pbebg::TurnPenalties* Arena::CreateMaybeMessage< ::pbebg::TurnPenalties >(Arena* arena) {
return Arena::CreateInternal< ::pbebg::TurnPenalties >(arena);
}
} // namespace protobuf
} // namespace google
// @@protoc_insertion_point(global_scope)
#include <google/protobuf/port_undef.inc>
|
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $Header: $
// $NoKeywords: $
//===========================================================================//
#include "shaderlib/cshader.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
DEFINE_FALLBACK_SHADER( UnlitTwoTexture, UnlitTwoTexture_DX6 )
BEGIN_SHADER( UnlitTwoTexture_DX6,
"Help for UnlitTwoTexture_DX6" )
BEGIN_SHADER_PARAMS
SHADER_PARAM( TEXTURE2, SHADER_PARAM_TYPE_TEXTURE, "shadertest/BaseTexture", "second texture" )
SHADER_PARAM( FRAME2, SHADER_PARAM_TYPE_INTEGER, "0", "frame number for $texture2" )
SHADER_PARAM( TEXTURE2TRANSFORM, SHADER_PARAM_TYPE_MATRIX, "center .5 .5 scale 1 1 rotate 0 translate 0 0", "$texture2 texcoord transform" )
END_SHADER_PARAMS
SHADER_INIT
{
if (params[BASETEXTURE]->IsDefined())
LoadTexture( BASETEXTURE );
if (params[TEXTURE2]->IsDefined())
LoadTexture( TEXTURE2 );
}
SHADER_DRAW
{
SHADOW_STATE
{
pShaderShadow->EnableTexture( SHADER_SAMPLER0, true );
pShaderShadow->EnableTexture( SHADER_SAMPLER1, true );
SetModulationShadowState();
// Either we've got a constant modulation
bool isTranslucent = IsAlphaModulating();
// Or we've got a texture alpha on either texture
isTranslucent = isTranslucent || TextureIsTranslucent( BASETEXTURE, true ) ||
TextureIsTranslucent( TEXTURE2, true );
if ( isTranslucent )
{
if ( IS_FLAG_SET(MATERIAL_VAR_ADDITIVE) )
{
EnableAlphaBlending( SHADER_BLEND_SRC_ALPHA, SHADER_BLEND_ONE );
}
else
{
EnableAlphaBlending( SHADER_BLEND_SRC_ALPHA, SHADER_BLEND_ONE_MINUS_SRC_ALPHA );
}
}
else
{
if ( IS_FLAG_SET(MATERIAL_VAR_ADDITIVE) )
{
EnableAlphaBlending( SHADER_BLEND_ONE, SHADER_BLEND_ONE );
}
else
{
DisableAlphaBlending( );
}
}
pShaderShadow->DrawFlags( SHADER_DRAW_POSITION | SHADER_DRAW_TEXCOORD0 |
SHADER_DRAW_TEXCOORD1 );
DefaultFog();
}
DYNAMIC_STATE
{
BindTexture( SHADER_SAMPLER0, BASETEXTURE, FRAME );
SetFixedFunctionTextureTransform( MATERIAL_TEXTURE0, BASETEXTURETRANSFORM );
BindTexture( SHADER_SAMPLER1, TEXTURE2, FRAME2 );
SetFixedFunctionTextureTransform( MATERIAL_TEXTURE1, TEXTURE2TRANSFORM );
SetModulationDynamicState();
}
Draw();
}
END_SHADER
|
#ifndef MESH_HPP
#define MESH_HPP
#include <vector>
#include <GL/glew.h>
#include "tools/ResourceLoader.hpp"
class Mesh {
private:
GLuint vao;
std::vector<GLuint> vbos;
int size;
void LoadIntoAttributeList(int location, int size, std::vector<float> data);
void LoadIntoIndexBuffer(std::vector<int> data);
void Unbind();
public:
Mesh(std::vector<float> positions,
std::vector<float> textureCoordinates,
std::vector<float> colors,
std::vector<float> normals,
std::vector<int> indices);
Mesh(ResourceLoader::MeshData* data);
~Mesh();
void Render();
};
#endif
|
//////////////////////
/// File generated by glLoadGen, version 2.0.5
/// glLoadGen's website: https://bitbucket.org/alfonse/glloadgen/wiki/Home
/// File generated from command line: core_4_5 -spec=gl -version=4.5 -profile=core -style=pointer_cpp -indent=space -stdext=electroslag.txt -geninfo
#ifndef POINTER_CPP_GENERATED_HEADEROPENGL_HPP
#define POINTER_CPP_GENERATED_HEADEROPENGL_HPP
#if defined(__glew_h__) || defined(__GLEW_H__)
#error Attempt to include auto-generated header after including glew.h
#endif
#if defined(__gl_h_) || defined(__GL_H__)
#error Attempt to include auto-generated header after including gl.h
#endif
#if defined(__glext_h_) || defined(__GLEXT_H_)
#error Attempt to include auto-generated header after including glext.h
#endif
#if defined(__gltypes_h_)
#error Attempt to include auto-generated header after gltypes.h
#endif
#if defined(__gl_ATI_h_)
#error Attempt to include auto-generated header after including glATI.h
#endif
#define __glew_h__
#define __GLEW_H__
#define __gl_h_
#define __GL_H__
#define __glext_h_
#define __GLEXT_H_
#define __gltypes_h_
#define __gl_ATI_h_
#ifndef APIENTRY
#if defined(__MINGW32__)
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN 1
#endif
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#elif (_MSC_VER >= 800) || defined(_STDCALL_SUPPORTED) || defined(__BORLANDC__)
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN 1
#endif
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#else
#define APIENTRY
#endif
#endif /*APIENTRY*/
#ifndef CODEGEN_FUNCPTR
#define CODEGEN_REMOVE_FUNCPTR
#if defined(_WIN32)
#define CODEGEN_FUNCPTR APIENTRY
#else
#define CODEGEN_FUNCPTR
#endif
#endif /*CODEGEN_FUNCPTR*/
#ifndef GLAPI
#define GLAPI extern
#endif
#ifndef GL_LOAD_GEN_BASIC_OPENGL_TYPEDEFS
#define GL_LOAD_GEN_BASIC_OPENGL_TYPEDEFS
#endif /*GL_LOAD_GEN_BASIC_OPENGL_TYPEDEFS*/
#include <stddef.h>
#ifndef GLEXT_64_TYPES_DEFINED
/* This code block is duplicated in glxext.h, so must be protected */
#define GLEXT_64_TYPES_DEFINED
/* Define int32_t, int64_t, and uint64_t types for UST/MSC */
/* (as used in the GL_EXT_timer_query extension). */
#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
#include <inttypes.h>
#elif defined(__sun__) || defined(__digital__)
#include <inttypes.h>
#if defined(__STDC__)
#if defined(__arch64__) || defined(_LP64)
typedef long int int64_t;
typedef unsigned long int uint64_t;
#else
typedef long long int int64_t;
typedef unsigned long long int uint64_t;
#endif /* __arch64__ */
#endif /* __STDC__ */
#elif defined( __VMS ) || defined(__sgi)
#include <inttypes.h>
#elif defined(__SCO__) || defined(__USLC__)
#include <stdint.h>
#elif defined(__UNIXOS2__) || defined(__SOL64__)
typedef long int int32_t;
typedef long long int int64_t;
typedef unsigned long long int uint64_t;
#elif defined(_WIN32) && defined(__GNUC__)
#include <stdint.h>
#elif defined(_WIN32)
typedef __int32 int32_t;
typedef __int64 int64_t;
typedef unsigned __int64 uint64_t;
#else
/* Fallback if nothing above works */
#include <inttypes.h>
#endif
#endif
typedef unsigned int GLenum;
typedef unsigned char GLboolean;
typedef unsigned int GLbitfield;
typedef void GLvoid;
typedef signed char GLbyte;
typedef short GLshort;
typedef int GLint;
typedef unsigned char GLubyte;
typedef unsigned short GLushort;
typedef unsigned int GLuint;
typedef int GLsizei;
typedef float GLfloat;
typedef float GLclampf;
typedef double GLdouble;
typedef double GLclampd;
typedef char GLchar;
typedef char GLcharARB;
#ifdef __APPLE__
typedef void *GLhandleARB;
#else
typedef unsigned int GLhandleARB;
#endif
typedef unsigned short GLhalfARB;
typedef unsigned short GLhalf;
typedef GLint GLfixed;
typedef ptrdiff_t GLintptr;
typedef ptrdiff_t GLsizeiptr;
typedef int64_t GLint64;
typedef uint64_t GLuint64;
typedef ptrdiff_t GLintptrARB;
typedef ptrdiff_t GLsizeiptrARB;
typedef int64_t GLint64EXT;
typedef uint64_t GLuint64EXT;
typedef struct __GLsync *GLsync;
struct _cl_context;
struct _cl_event;
typedef void (APIENTRY *GLDEBUGPROC)(GLenum source,GLenum type,GLuint id,GLenum severity,GLsizei length,const GLchar *message,const void *userParam);
typedef void (APIENTRY *GLDEBUGPROCARB)(GLenum source,GLenum type,GLuint id,GLenum severity,GLsizei length,const GLchar *message,const void *userParam);
typedef void (APIENTRY *GLDEBUGPROCAMD)(GLuint id,GLenum category,GLenum severity,GLsizei length,const GLchar *message,void *userParam);
typedef unsigned short GLhalfNV;
typedef GLintptr GLvdpauSurfaceNV;
namespace gl
{
namespace exts
{
class LoadTest
{
private:
//Safe bool idiom. Joy!
typedef void (LoadTest::*bool_type)() const;
void big_long_name_that_really_doesnt_matter() const {}
public:
operator bool_type() const
{
return m_isLoaded ? &LoadTest::big_long_name_that_really_doesnt_matter : 0;
}
int GetNumMissing() const {return m_numMissing;}
LoadTest() : m_isLoaded(false), m_numMissing(0) {}
LoadTest(bool isLoaded, int numMissing) : m_isLoaded(isLoaded), m_numMissing(numMissing) {}
private:
bool m_isLoaded;
int m_numMissing;
};
extern LoadTest var_EXT_texture_compression_s3tc;
extern LoadTest var_EXT_texture_sRGB;
extern LoadTest var_EXT_texture_filter_anisotropic;
extern LoadTest var_ARB_bindless_texture;
} //namespace exts
enum
{
COMPRESSED_RGBA_S3TC_DXT1_EXT = 0x83F1,
COMPRESSED_RGBA_S3TC_DXT3_EXT = 0x83F2,
COMPRESSED_RGBA_S3TC_DXT5_EXT = 0x83F3,
COMPRESSED_RGB_S3TC_DXT1_EXT = 0x83F0,
COMPRESSED_SLUMINANCE_ALPHA_EXT = 0x8C4B,
COMPRESSED_SLUMINANCE_EXT = 0x8C4A,
COMPRESSED_SRGB_ALPHA_EXT = 0x8C49,
COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT = 0x8C4D,
COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT = 0x8C4E,
COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT = 0x8C4F,
COMPRESSED_SRGB_EXT = 0x8C48,
COMPRESSED_SRGB_S3TC_DXT1_EXT = 0x8C4C,
SLUMINANCE8_ALPHA8_EXT = 0x8C45,
SLUMINANCE8_EXT = 0x8C47,
SLUMINANCE_ALPHA_EXT = 0x8C44,
SLUMINANCE_EXT = 0x8C46,
SRGB8_ALPHA8_EXT = 0x8C43,
SRGB8_EXT = 0x8C41,
SRGB_ALPHA_EXT = 0x8C42,
SRGB_EXT = 0x8C40,
MAX_TEXTURE_MAX_ANISOTROPY_EXT = 0x84FF,
TEXTURE_MAX_ANISOTROPY_EXT = 0x84FE,
UNSIGNED_INT64_ARB = 0x140F,
ALPHA = 0x1906,
ALWAYS = 0x0207,
AND = 0x1501,
AND_INVERTED = 0x1504,
AND_REVERSE = 0x1502,
BACK = 0x0405,
BACK_LEFT = 0x0402,
BACK_RIGHT = 0x0403,
BLEND = 0x0BE2,
BLEND_DST = 0x0BE0,
BLEND_SRC = 0x0BE1,
BLUE = 0x1905,
BYTE = 0x1400,
CCW = 0x0901,
CLEAR = 0x1500,
COLOR = 0x1800,
COLOR_BUFFER_BIT = 0x00004000,
COLOR_CLEAR_VALUE = 0x0C22,
COLOR_LOGIC_OP = 0x0BF2,
COLOR_WRITEMASK = 0x0C23,
COPY = 0x1503,
COPY_INVERTED = 0x150C,
CULL_FACE = 0x0B44,
CULL_FACE_MODE = 0x0B45,
CW = 0x0900,
DECR = 0x1E03,
DEPTH = 0x1801,
DEPTH_BUFFER_BIT = 0x00000100,
DEPTH_CLEAR_VALUE = 0x0B73,
DEPTH_COMPONENT = 0x1902,
DEPTH_FUNC = 0x0B74,
DEPTH_RANGE = 0x0B70,
DEPTH_TEST = 0x0B71,
DEPTH_WRITEMASK = 0x0B72,
DITHER = 0x0BD0,
DONT_CARE = 0x1100,
DOUBLE = 0x140A,
DOUBLEBUFFER = 0x0C32,
DRAW_BUFFER = 0x0C01,
DST_ALPHA = 0x0304,
DST_COLOR = 0x0306,
EQUAL = 0x0202,
EQUIV = 0x1509,
EXTENSIONS = 0x1F03,
FALSE_ = 0,
FASTEST = 0x1101,
FILL = 0x1B02,
FLOAT = 0x1406,
FRONT = 0x0404,
FRONT_AND_BACK = 0x0408,
FRONT_FACE = 0x0B46,
FRONT_LEFT = 0x0400,
FRONT_RIGHT = 0x0401,
GEQUAL = 0x0206,
GREATER = 0x0204,
GREEN = 0x1904,
INCR = 0x1E02,
INT = 0x1404,
INVALID_ENUM = 0x0500,
INVALID_OPERATION = 0x0502,
INVALID_VALUE = 0x0501,
INVERT = 0x150A,
KEEP = 0x1E00,
LEFT = 0x0406,
LEQUAL = 0x0203,
LESS = 0x0201,
LINE = 0x1B01,
LINEAR = 0x2601,
LINEAR_MIPMAP_LINEAR = 0x2703,
LINEAR_MIPMAP_NEAREST = 0x2701,
LINES = 0x0001,
LINE_LOOP = 0x0002,
LINE_SMOOTH = 0x0B20,
LINE_SMOOTH_HINT = 0x0C52,
LINE_STRIP = 0x0003,
LINE_WIDTH = 0x0B21,
LINE_WIDTH_GRANULARITY = 0x0B23,
LINE_WIDTH_RANGE = 0x0B22,
LOGIC_OP_MODE = 0x0BF0,
MAX_TEXTURE_SIZE = 0x0D33,
MAX_VIEWPORT_DIMS = 0x0D3A,
NAND = 0x150E,
NEAREST = 0x2600,
NEAREST_MIPMAP_LINEAR = 0x2702,
NEAREST_MIPMAP_NEAREST = 0x2700,
NEVER = 0x0200,
NICEST = 0x1102,
NONE = 0,
NOOP = 0x1505,
NOR = 0x1508,
NOTEQUAL = 0x0205,
NO_ERROR_ = 0,
ONE = 1,
ONE_MINUS_DST_ALPHA = 0x0305,
ONE_MINUS_DST_COLOR = 0x0307,
ONE_MINUS_SRC_ALPHA = 0x0303,
ONE_MINUS_SRC_COLOR = 0x0301,
OR = 0x1507,
OR_INVERTED = 0x150D,
OR_REVERSE = 0x150B,
OUT_OF_MEMORY = 0x0505,
PACK_ALIGNMENT = 0x0D05,
PACK_LSB_FIRST = 0x0D01,
PACK_ROW_LENGTH = 0x0D02,
PACK_SKIP_PIXELS = 0x0D04,
PACK_SKIP_ROWS = 0x0D03,
PACK_SWAP_BYTES = 0x0D00,
POINT = 0x1B00,
POINTS = 0x0000,
POINT_SIZE = 0x0B11,
POINT_SIZE_GRANULARITY = 0x0B13,
POINT_SIZE_RANGE = 0x0B12,
POLYGON_MODE = 0x0B40,
POLYGON_OFFSET_FACTOR = 0x8038,
POLYGON_OFFSET_FILL = 0x8037,
POLYGON_OFFSET_LINE = 0x2A02,
POLYGON_OFFSET_POINT = 0x2A01,
POLYGON_OFFSET_UNITS = 0x2A00,
POLYGON_SMOOTH = 0x0B41,
POLYGON_SMOOTH_HINT = 0x0C53,
PROXY_TEXTURE_1D = 0x8063,
PROXY_TEXTURE_2D = 0x8064,
QUADS = 0x0007,
R3_G3_B2 = 0x2A10,
READ_BUFFER = 0x0C02,
RED = 0x1903,
RENDERER = 0x1F01,
REPEAT = 0x2901,
REPLACE = 0x1E01,
RGB = 0x1907,
RGB10 = 0x8052,
RGB10_A2 = 0x8059,
RGB12 = 0x8053,
RGB16 = 0x8054,
RGB4 = 0x804F,
RGB5 = 0x8050,
RGB5_A1 = 0x8057,
RGB8 = 0x8051,
RGBA = 0x1908,
RGBA12 = 0x805A,
RGBA16 = 0x805B,
RGBA2 = 0x8055,
RGBA4 = 0x8056,
RGBA8 = 0x8058,
RIGHT = 0x0407,
SCISSOR_BOX = 0x0C10,
SCISSOR_TEST = 0x0C11,
SET = 0x150F,
SHORT = 0x1402,
SRC_ALPHA = 0x0302,
SRC_ALPHA_SATURATE = 0x0308,
SRC_COLOR = 0x0300,
STACK_OVERFLOW = 0x0503,
STACK_UNDERFLOW = 0x0504,
STENCIL = 0x1802,
STENCIL_BUFFER_BIT = 0x00000400,
STENCIL_CLEAR_VALUE = 0x0B91,
STENCIL_FAIL = 0x0B94,
STENCIL_FUNC = 0x0B92,
STENCIL_INDEX = 0x1901,
STENCIL_PASS_DEPTH_FAIL = 0x0B95,
STENCIL_PASS_DEPTH_PASS = 0x0B96,
STENCIL_REF = 0x0B97,
STENCIL_TEST = 0x0B90,
STENCIL_VALUE_MASK = 0x0B93,
STENCIL_WRITEMASK = 0x0B98,
STEREO = 0x0C33,
SUBPIXEL_BITS = 0x0D50,
TEXTURE = 0x1702,
TEXTURE_1D = 0x0DE0,
TEXTURE_2D = 0x0DE1,
TEXTURE_ALPHA_SIZE = 0x805F,
TEXTURE_BINDING_1D = 0x8068,
TEXTURE_BINDING_2D = 0x8069,
TEXTURE_BLUE_SIZE = 0x805E,
TEXTURE_BORDER_COLOR = 0x1004,
TEXTURE_GREEN_SIZE = 0x805D,
TEXTURE_HEIGHT = 0x1001,
TEXTURE_INTERNAL_FORMAT = 0x1003,
TEXTURE_MAG_FILTER = 0x2800,
TEXTURE_MIN_FILTER = 0x2801,
TEXTURE_RED_SIZE = 0x805C,
TEXTURE_WIDTH = 0x1000,
TEXTURE_WRAP_S = 0x2802,
TEXTURE_WRAP_T = 0x2803,
TRIANGLES = 0x0004,
TRIANGLE_FAN = 0x0006,
TRIANGLE_STRIP = 0x0005,
TRUE_ = 1,
UNPACK_ALIGNMENT = 0x0CF5,
UNPACK_LSB_FIRST = 0x0CF1,
UNPACK_ROW_LENGTH = 0x0CF2,
UNPACK_SKIP_PIXELS = 0x0CF4,
UNPACK_SKIP_ROWS = 0x0CF3,
UNPACK_SWAP_BYTES = 0x0CF0,
UNSIGNED_BYTE = 0x1401,
UNSIGNED_INT = 0x1405,
UNSIGNED_SHORT = 0x1403,
VENDOR = 0x1F00,
VERSION = 0x1F02,
VERTEX_ARRAY = 0x8074,
VIEWPORT = 0x0BA2,
XOR = 0x1506,
ZERO = 0,
ALIASED_LINE_WIDTH_RANGE = 0x846E,
BGR = 0x80E0,
BGRA = 0x80E1,
CLAMP_TO_EDGE = 0x812F,
MAX_3D_TEXTURE_SIZE = 0x8073,
MAX_ELEMENTS_INDICES = 0x80E9,
MAX_ELEMENTS_VERTICES = 0x80E8,
PACK_IMAGE_HEIGHT = 0x806C,
PACK_SKIP_IMAGES = 0x806B,
PROXY_TEXTURE_3D = 0x8070,
SMOOTH_LINE_WIDTH_GRANULARITY = 0x0B23,
SMOOTH_LINE_WIDTH_RANGE = 0x0B22,
SMOOTH_POINT_SIZE_GRANULARITY = 0x0B13,
SMOOTH_POINT_SIZE_RANGE = 0x0B12,
TEXTURE_3D = 0x806F,
TEXTURE_BASE_LEVEL = 0x813C,
TEXTURE_BINDING_3D = 0x806A,
TEXTURE_DEPTH = 0x8071,
TEXTURE_MAX_LEVEL = 0x813D,
TEXTURE_MAX_LOD = 0x813B,
TEXTURE_MIN_LOD = 0x813A,
TEXTURE_WRAP_R = 0x8072,
UNPACK_IMAGE_HEIGHT = 0x806E,
UNPACK_SKIP_IMAGES = 0x806D,
UNSIGNED_BYTE_2_3_3_REV = 0x8362,
UNSIGNED_BYTE_3_3_2 = 0x8032,
UNSIGNED_INT_10_10_10_2 = 0x8036,
UNSIGNED_INT_2_10_10_10_REV = 0x8368,
UNSIGNED_INT_8_8_8_8 = 0x8035,
UNSIGNED_INT_8_8_8_8_REV = 0x8367,
UNSIGNED_SHORT_1_5_5_5_REV = 0x8366,
UNSIGNED_SHORT_4_4_4_4 = 0x8033,
UNSIGNED_SHORT_4_4_4_4_REV = 0x8365,
UNSIGNED_SHORT_5_5_5_1 = 0x8034,
UNSIGNED_SHORT_5_6_5 = 0x8363,
UNSIGNED_SHORT_5_6_5_REV = 0x8364,
ACTIVE_TEXTURE = 0x84E0,
CLAMP_TO_BORDER = 0x812D,
COMPRESSED_RGB = 0x84ED,
COMPRESSED_RGBA = 0x84EE,
COMPRESSED_TEXTURE_FORMATS = 0x86A3,
MAX_CUBE_MAP_TEXTURE_SIZE = 0x851C,
MULTISAMPLE = 0x809D,
NUM_COMPRESSED_TEXTURE_FORMATS = 0x86A2,
PROXY_TEXTURE_CUBE_MAP = 0x851B,
SAMPLES = 0x80A9,
SAMPLE_ALPHA_TO_COVERAGE = 0x809E,
SAMPLE_ALPHA_TO_ONE = 0x809F,
SAMPLE_BUFFERS = 0x80A8,
SAMPLE_COVERAGE = 0x80A0,
SAMPLE_COVERAGE_INVERT = 0x80AB,
SAMPLE_COVERAGE_VALUE = 0x80AA,
TEXTURE0 = 0x84C0,
TEXTURE1 = 0x84C1,
TEXTURE10 = 0x84CA,
TEXTURE11 = 0x84CB,
TEXTURE12 = 0x84CC,
TEXTURE13 = 0x84CD,
TEXTURE14 = 0x84CE,
TEXTURE15 = 0x84CF,
TEXTURE16 = 0x84D0,
TEXTURE17 = 0x84D1,
TEXTURE18 = 0x84D2,
TEXTURE19 = 0x84D3,
TEXTURE2 = 0x84C2,
TEXTURE20 = 0x84D4,
TEXTURE21 = 0x84D5,
TEXTURE22 = 0x84D6,
TEXTURE23 = 0x84D7,
TEXTURE24 = 0x84D8,
TEXTURE25 = 0x84D9,
TEXTURE26 = 0x84DA,
TEXTURE27 = 0x84DB,
TEXTURE28 = 0x84DC,
TEXTURE29 = 0x84DD,
TEXTURE3 = 0x84C3,
TEXTURE30 = 0x84DE,
TEXTURE31 = 0x84DF,
TEXTURE4 = 0x84C4,
TEXTURE5 = 0x84C5,
TEXTURE6 = 0x84C6,
TEXTURE7 = 0x84C7,
TEXTURE8 = 0x84C8,
TEXTURE9 = 0x84C9,
TEXTURE_BINDING_CUBE_MAP = 0x8514,
TEXTURE_COMPRESSED = 0x86A1,
TEXTURE_COMPRESSED_IMAGE_SIZE = 0x86A0,
TEXTURE_COMPRESSION_HINT = 0x84EF,
TEXTURE_CUBE_MAP = 0x8513,
TEXTURE_CUBE_MAP_NEGATIVE_X = 0x8516,
TEXTURE_CUBE_MAP_NEGATIVE_Y = 0x8518,
TEXTURE_CUBE_MAP_NEGATIVE_Z = 0x851A,
TEXTURE_CUBE_MAP_POSITIVE_X = 0x8515,
TEXTURE_CUBE_MAP_POSITIVE_Y = 0x8517,
TEXTURE_CUBE_MAP_POSITIVE_Z = 0x8519,
BLEND_COLOR = 0x8005,
BLEND_DST_ALPHA = 0x80CA,
BLEND_DST_RGB = 0x80C8,
BLEND_SRC_ALPHA = 0x80CB,
BLEND_SRC_RGB = 0x80C9,
CONSTANT_ALPHA = 0x8003,
CONSTANT_COLOR = 0x8001,
DECR_WRAP = 0x8508,
DEPTH_COMPONENT16 = 0x81A5,
DEPTH_COMPONENT24 = 0x81A6,
DEPTH_COMPONENT32 = 0x81A7,
FUNC_ADD = 0x8006,
FUNC_REVERSE_SUBTRACT = 0x800B,
FUNC_SUBTRACT = 0x800A,
INCR_WRAP = 0x8507,
MAX = 0x8008,
MAX_TEXTURE_LOD_BIAS = 0x84FD,
MIN = 0x8007,
MIRRORED_REPEAT = 0x8370,
ONE_MINUS_CONSTANT_ALPHA = 0x8004,
ONE_MINUS_CONSTANT_COLOR = 0x8002,
POINT_FADE_THRESHOLD_SIZE = 0x8128,
TEXTURE_COMPARE_FUNC = 0x884D,
TEXTURE_COMPARE_MODE = 0x884C,
TEXTURE_DEPTH_SIZE = 0x884A,
TEXTURE_LOD_BIAS = 0x8501,
ARRAY_BUFFER = 0x8892,
ARRAY_BUFFER_BINDING = 0x8894,
BUFFER_ACCESS = 0x88BB,
BUFFER_MAPPED = 0x88BC,
BUFFER_MAP_POINTER = 0x88BD,
BUFFER_SIZE = 0x8764,
BUFFER_USAGE = 0x8765,
CURRENT_QUERY = 0x8865,
DYNAMIC_COPY = 0x88EA,
DYNAMIC_DRAW = 0x88E8,
DYNAMIC_READ = 0x88E9,
ELEMENT_ARRAY_BUFFER = 0x8893,
ELEMENT_ARRAY_BUFFER_BINDING = 0x8895,
QUERY_COUNTER_BITS = 0x8864,
QUERY_RESULT = 0x8866,
QUERY_RESULT_AVAILABLE = 0x8867,
READ_ONLY = 0x88B8,
READ_WRITE = 0x88BA,
SAMPLES_PASSED = 0x8914,
SRC1_ALPHA = 0x8589,
STATIC_COPY = 0x88E6,
STATIC_DRAW = 0x88E4,
STATIC_READ = 0x88E5,
STREAM_COPY = 0x88E2,
STREAM_DRAW = 0x88E0,
STREAM_READ = 0x88E1,
VERTEX_ATTRIB_ARRAY_BUFFER_BINDING = 0x889F,
WRITE_ONLY = 0x88B9,
ACTIVE_ATTRIBUTES = 0x8B89,
ACTIVE_ATTRIBUTE_MAX_LENGTH = 0x8B8A,
ACTIVE_UNIFORMS = 0x8B86,
ACTIVE_UNIFORM_MAX_LENGTH = 0x8B87,
ATTACHED_SHADERS = 0x8B85,
BLEND_EQUATION_ALPHA = 0x883D,
BLEND_EQUATION_RGB = 0x8009,
BOOL = 0x8B56,
BOOL_VEC2 = 0x8B57,
BOOL_VEC3 = 0x8B58,
BOOL_VEC4 = 0x8B59,
COMPILE_STATUS = 0x8B81,
CURRENT_PROGRAM = 0x8B8D,
CURRENT_VERTEX_ATTRIB = 0x8626,
DELETE_STATUS = 0x8B80,
DRAW_BUFFER0 = 0x8825,
DRAW_BUFFER1 = 0x8826,
DRAW_BUFFER10 = 0x882F,
DRAW_BUFFER11 = 0x8830,
DRAW_BUFFER12 = 0x8831,
DRAW_BUFFER13 = 0x8832,
DRAW_BUFFER14 = 0x8833,
DRAW_BUFFER15 = 0x8834,
DRAW_BUFFER2 = 0x8827,
DRAW_BUFFER3 = 0x8828,
DRAW_BUFFER4 = 0x8829,
DRAW_BUFFER5 = 0x882A,
DRAW_BUFFER6 = 0x882B,
DRAW_BUFFER7 = 0x882C,
DRAW_BUFFER8 = 0x882D,
DRAW_BUFFER9 = 0x882E,
FLOAT_MAT2 = 0x8B5A,
FLOAT_MAT3 = 0x8B5B,
FLOAT_MAT4 = 0x8B5C,
FLOAT_VEC2 = 0x8B50,
FLOAT_VEC3 = 0x8B51,
FLOAT_VEC4 = 0x8B52,
FRAGMENT_SHADER = 0x8B30,
FRAGMENT_SHADER_DERIVATIVE_HINT = 0x8B8B,
INFO_LOG_LENGTH = 0x8B84,
INT_VEC2 = 0x8B53,
INT_VEC3 = 0x8B54,
INT_VEC4 = 0x8B55,
LINK_STATUS = 0x8B82,
LOWER_LEFT = 0x8CA1,
MAX_COMBINED_TEXTURE_IMAGE_UNITS = 0x8B4D,
MAX_DRAW_BUFFERS = 0x8824,
MAX_FRAGMENT_UNIFORM_COMPONENTS = 0x8B49,
MAX_TEXTURE_IMAGE_UNITS = 0x8872,
MAX_VARYING_FLOATS = 0x8B4B,
MAX_VERTEX_ATTRIBS = 0x8869,
MAX_VERTEX_TEXTURE_IMAGE_UNITS = 0x8B4C,
MAX_VERTEX_UNIFORM_COMPONENTS = 0x8B4A,
POINT_SPRITE_COORD_ORIGIN = 0x8CA0,
SAMPLER_1D = 0x8B5D,
SAMPLER_1D_SHADOW = 0x8B61,
SAMPLER_2D = 0x8B5E,
SAMPLER_2D_SHADOW = 0x8B62,
SAMPLER_3D = 0x8B5F,
SAMPLER_CUBE = 0x8B60,
SHADER_SOURCE_LENGTH = 0x8B88,
SHADER_TYPE = 0x8B4F,
SHADING_LANGUAGE_VERSION = 0x8B8C,
STENCIL_BACK_FAIL = 0x8801,
STENCIL_BACK_FUNC = 0x8800,
STENCIL_BACK_PASS_DEPTH_FAIL = 0x8802,
STENCIL_BACK_PASS_DEPTH_PASS = 0x8803,
STENCIL_BACK_REF = 0x8CA3,
STENCIL_BACK_VALUE_MASK = 0x8CA4,
STENCIL_BACK_WRITEMASK = 0x8CA5,
UPPER_LEFT = 0x8CA2,
VALIDATE_STATUS = 0x8B83,
VERTEX_ATTRIB_ARRAY_ENABLED = 0x8622,
VERTEX_ATTRIB_ARRAY_NORMALIZED = 0x886A,
VERTEX_ATTRIB_ARRAY_POINTER = 0x8645,
VERTEX_ATTRIB_ARRAY_SIZE = 0x8623,
VERTEX_ATTRIB_ARRAY_STRIDE = 0x8624,
VERTEX_ATTRIB_ARRAY_TYPE = 0x8625,
VERTEX_PROGRAM_POINT_SIZE = 0x8642,
VERTEX_SHADER = 0x8B31,
COMPRESSED_SRGB = 0x8C48,
COMPRESSED_SRGB_ALPHA = 0x8C49,
FLOAT_MAT2x3 = 0x8B65,
FLOAT_MAT2x4 = 0x8B66,
FLOAT_MAT3x2 = 0x8B67,
FLOAT_MAT3x4 = 0x8B68,
FLOAT_MAT4x2 = 0x8B69,
FLOAT_MAT4x3 = 0x8B6A,
PIXEL_PACK_BUFFER = 0x88EB,
PIXEL_PACK_BUFFER_BINDING = 0x88ED,
PIXEL_UNPACK_BUFFER = 0x88EC,
PIXEL_UNPACK_BUFFER_BINDING = 0x88EF,
SRGB = 0x8C40,
SRGB8 = 0x8C41,
SRGB8_ALPHA8 = 0x8C43,
SRGB_ALPHA = 0x8C42,
BGRA_INTEGER = 0x8D9B,
BGR_INTEGER = 0x8D9A,
BLUE_INTEGER = 0x8D96,
BUFFER_ACCESS_FLAGS = 0x911F,
BUFFER_MAP_LENGTH = 0x9120,
BUFFER_MAP_OFFSET = 0x9121,
CLAMP_READ_COLOR = 0x891C,
CLIP_DISTANCE0 = 0x3000,
CLIP_DISTANCE1 = 0x3001,
CLIP_DISTANCE2 = 0x3002,
CLIP_DISTANCE3 = 0x3003,
CLIP_DISTANCE4 = 0x3004,
CLIP_DISTANCE5 = 0x3005,
CLIP_DISTANCE6 = 0x3006,
CLIP_DISTANCE7 = 0x3007,
COLOR_ATTACHMENT0 = 0x8CE0,
COLOR_ATTACHMENT1 = 0x8CE1,
COLOR_ATTACHMENT10 = 0x8CEA,
COLOR_ATTACHMENT11 = 0x8CEB,
COLOR_ATTACHMENT12 = 0x8CEC,
COLOR_ATTACHMENT13 = 0x8CED,
COLOR_ATTACHMENT14 = 0x8CEE,
COLOR_ATTACHMENT15 = 0x8CEF,
COLOR_ATTACHMENT16 = 0x8CF0,
COLOR_ATTACHMENT17 = 0x8CF1,
COLOR_ATTACHMENT18 = 0x8CF2,
COLOR_ATTACHMENT19 = 0x8CF3,
COLOR_ATTACHMENT2 = 0x8CE2,
COLOR_ATTACHMENT20 = 0x8CF4,
COLOR_ATTACHMENT21 = 0x8CF5,
COLOR_ATTACHMENT22 = 0x8CF6,
COLOR_ATTACHMENT23 = 0x8CF7,
COLOR_ATTACHMENT24 = 0x8CF8,
COLOR_ATTACHMENT25 = 0x8CF9,
COLOR_ATTACHMENT26 = 0x8CFA,
COLOR_ATTACHMENT27 = 0x8CFB,
COLOR_ATTACHMENT28 = 0x8CFC,
COLOR_ATTACHMENT29 = 0x8CFD,
COLOR_ATTACHMENT3 = 0x8CE3,
COLOR_ATTACHMENT30 = 0x8CFE,
COLOR_ATTACHMENT31 = 0x8CFF,
COLOR_ATTACHMENT4 = 0x8CE4,
COLOR_ATTACHMENT5 = 0x8CE5,
COLOR_ATTACHMENT6 = 0x8CE6,
COLOR_ATTACHMENT7 = 0x8CE7,
COLOR_ATTACHMENT8 = 0x8CE8,
COLOR_ATTACHMENT9 = 0x8CE9,
COMPARE_REF_TO_TEXTURE = 0x884E,
COMPRESSED_RED = 0x8225,
COMPRESSED_RED_RGTC1 = 0x8DBB,
COMPRESSED_RG = 0x8226,
COMPRESSED_RG_RGTC2 = 0x8DBD,
COMPRESSED_SIGNED_RED_RGTC1 = 0x8DBC,
COMPRESSED_SIGNED_RG_RGTC2 = 0x8DBE,
CONTEXT_FLAGS = 0x821E,
CONTEXT_FLAG_FORWARD_COMPATIBLE_BIT = 0x00000001,
DEPTH24_STENCIL8 = 0x88F0,
DEPTH32F_STENCIL8 = 0x8CAD,
DEPTH_ATTACHMENT = 0x8D00,
DEPTH_COMPONENT32F = 0x8CAC,
DEPTH_STENCIL = 0x84F9,
DEPTH_STENCIL_ATTACHMENT = 0x821A,
DRAW_FRAMEBUFFER = 0x8CA9,
DRAW_FRAMEBUFFER_BINDING = 0x8CA6,
FIXED_ONLY = 0x891D,
FLOAT_32_UNSIGNED_INT_24_8_REV = 0x8DAD,
FRAMEBUFFER = 0x8D40,
FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE = 0x8215,
FRAMEBUFFER_ATTACHMENT_BLUE_SIZE = 0x8214,
FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING = 0x8210,
FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE = 0x8211,
FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE = 0x8216,
FRAMEBUFFER_ATTACHMENT_GREEN_SIZE = 0x8213,
FRAMEBUFFER_ATTACHMENT_OBJECT_NAME = 0x8CD1,
FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE = 0x8CD0,
FRAMEBUFFER_ATTACHMENT_RED_SIZE = 0x8212,
FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE = 0x8217,
FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE = 0x8CD3,
FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER = 0x8CD4,
FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL = 0x8CD2,
FRAMEBUFFER_BINDING = 0x8CA6,
FRAMEBUFFER_COMPLETE = 0x8CD5,
FRAMEBUFFER_DEFAULT = 0x8218,
FRAMEBUFFER_INCOMPLETE_ATTACHMENT = 0x8CD6,
FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER = 0x8CDB,
FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT = 0x8CD7,
FRAMEBUFFER_INCOMPLETE_MULTISAMPLE = 0x8D56,
FRAMEBUFFER_INCOMPLETE_READ_BUFFER = 0x8CDC,
FRAMEBUFFER_SRGB = 0x8DB9,
FRAMEBUFFER_UNDEFINED = 0x8219,
FRAMEBUFFER_UNSUPPORTED = 0x8CDD,
GREEN_INTEGER = 0x8D95,
HALF_FLOAT = 0x140B,
INTERLEAVED_ATTRIBS = 0x8C8C,
INT_SAMPLER_1D = 0x8DC9,
INT_SAMPLER_1D_ARRAY = 0x8DCE,
INT_SAMPLER_2D = 0x8DCA,
INT_SAMPLER_2D_ARRAY = 0x8DCF,
INT_SAMPLER_3D = 0x8DCB,
INT_SAMPLER_CUBE = 0x8DCC,
INVALID_FRAMEBUFFER_OPERATION = 0x0506,
MAJOR_VERSION = 0x821B,
MAP_FLUSH_EXPLICIT_BIT = 0x0010,
MAP_INVALIDATE_BUFFER_BIT = 0x0008,
MAP_INVALIDATE_RANGE_BIT = 0x0004,
MAP_READ_BIT = 0x0001,
MAP_UNSYNCHRONIZED_BIT = 0x0020,
MAP_WRITE_BIT = 0x0002,
MAX_ARRAY_TEXTURE_LAYERS = 0x88FF,
MAX_CLIP_DISTANCES = 0x0D32,
MAX_COLOR_ATTACHMENTS = 0x8CDF,
MAX_PROGRAM_TEXEL_OFFSET = 0x8905,
MAX_RENDERBUFFER_SIZE = 0x84E8,
MAX_SAMPLES = 0x8D57,
MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS = 0x8C8A,
MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS = 0x8C8B,
MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS = 0x8C80,
MAX_VARYING_COMPONENTS = 0x8B4B,
MINOR_VERSION = 0x821C,
MIN_PROGRAM_TEXEL_OFFSET = 0x8904,
NUM_EXTENSIONS = 0x821D,
PRIMITIVES_GENERATED = 0x8C87,
PROXY_TEXTURE_1D_ARRAY = 0x8C19,
PROXY_TEXTURE_2D_ARRAY = 0x8C1B,
QUERY_BY_REGION_NO_WAIT = 0x8E16,
QUERY_BY_REGION_WAIT = 0x8E15,
QUERY_NO_WAIT = 0x8E14,
QUERY_WAIT = 0x8E13,
R11F_G11F_B10F = 0x8C3A,
R16 = 0x822A,
R16F = 0x822D,
R16I = 0x8233,
R16UI = 0x8234,
R32F = 0x822E,
R32I = 0x8235,
R32UI = 0x8236,
R8 = 0x8229,
R8I = 0x8231,
R8UI = 0x8232,
RASTERIZER_DISCARD = 0x8C89,
READ_FRAMEBUFFER = 0x8CA8,
READ_FRAMEBUFFER_BINDING = 0x8CAA,
RED_INTEGER = 0x8D94,
RENDERBUFFER = 0x8D41,
RENDERBUFFER_ALPHA_SIZE = 0x8D53,
RENDERBUFFER_BINDING = 0x8CA7,
RENDERBUFFER_BLUE_SIZE = 0x8D52,
RENDERBUFFER_DEPTH_SIZE = 0x8D54,
RENDERBUFFER_GREEN_SIZE = 0x8D51,
RENDERBUFFER_HEIGHT = 0x8D43,
RENDERBUFFER_INTERNAL_FORMAT = 0x8D44,
RENDERBUFFER_RED_SIZE = 0x8D50,
RENDERBUFFER_SAMPLES = 0x8CAB,
RENDERBUFFER_STENCIL_SIZE = 0x8D55,
RENDERBUFFER_WIDTH = 0x8D42,
RG = 0x8227,
RG16 = 0x822C,
RG16F = 0x822F,
RG16I = 0x8239,
RG16UI = 0x823A,
RG32F = 0x8230,
RG32I = 0x823B,
RG32UI = 0x823C,
RG8 = 0x822B,
RG8I = 0x8237,
RG8UI = 0x8238,
RGB16F = 0x881B,
RGB16I = 0x8D89,
RGB16UI = 0x8D77,
RGB32F = 0x8815,
RGB32I = 0x8D83,
RGB32UI = 0x8D71,
RGB8I = 0x8D8F,
RGB8UI = 0x8D7D,
RGB9_E5 = 0x8C3D,
RGBA16F = 0x881A,
RGBA16I = 0x8D88,
RGBA16UI = 0x8D76,
RGBA32F = 0x8814,
RGBA32I = 0x8D82,
RGBA32UI = 0x8D70,
RGBA8I = 0x8D8E,
RGBA8UI = 0x8D7C,
RGBA_INTEGER = 0x8D99,
RGB_INTEGER = 0x8D98,
RG_INTEGER = 0x8228,
SAMPLER_1D_ARRAY = 0x8DC0,
SAMPLER_1D_ARRAY_SHADOW = 0x8DC3,
SAMPLER_2D_ARRAY = 0x8DC1,
SAMPLER_2D_ARRAY_SHADOW = 0x8DC4,
SAMPLER_CUBE_SHADOW = 0x8DC5,
SEPARATE_ATTRIBS = 0x8C8D,
STENCIL_ATTACHMENT = 0x8D20,
STENCIL_INDEX1 = 0x8D46,
STENCIL_INDEX16 = 0x8D49,
STENCIL_INDEX4 = 0x8D47,
STENCIL_INDEX8 = 0x8D48,
TEXTURE_1D_ARRAY = 0x8C18,
TEXTURE_2D_ARRAY = 0x8C1A,
TEXTURE_ALPHA_TYPE = 0x8C13,
TEXTURE_BINDING_1D_ARRAY = 0x8C1C,
TEXTURE_BINDING_2D_ARRAY = 0x8C1D,
TEXTURE_BLUE_TYPE = 0x8C12,
TEXTURE_DEPTH_TYPE = 0x8C16,
TEXTURE_GREEN_TYPE = 0x8C11,
TEXTURE_RED_TYPE = 0x8C10,
TEXTURE_SHARED_SIZE = 0x8C3F,
TEXTURE_STENCIL_SIZE = 0x88F1,
TRANSFORM_FEEDBACK_BUFFER = 0x8C8E,
TRANSFORM_FEEDBACK_BUFFER_BINDING = 0x8C8F,
TRANSFORM_FEEDBACK_BUFFER_MODE = 0x8C7F,
TRANSFORM_FEEDBACK_BUFFER_SIZE = 0x8C85,
TRANSFORM_FEEDBACK_BUFFER_START = 0x8C84,
TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN = 0x8C88,
TRANSFORM_FEEDBACK_VARYINGS = 0x8C83,
TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH = 0x8C76,
UNSIGNED_INT_10F_11F_11F_REV = 0x8C3B,
UNSIGNED_INT_24_8 = 0x84FA,
UNSIGNED_INT_5_9_9_9_REV = 0x8C3E,
UNSIGNED_INT_SAMPLER_1D = 0x8DD1,
UNSIGNED_INT_SAMPLER_1D_ARRAY = 0x8DD6,
UNSIGNED_INT_SAMPLER_2D = 0x8DD2,
UNSIGNED_INT_SAMPLER_2D_ARRAY = 0x8DD7,
UNSIGNED_INT_SAMPLER_3D = 0x8DD3,
UNSIGNED_INT_SAMPLER_CUBE = 0x8DD4,
UNSIGNED_INT_VEC2 = 0x8DC6,
UNSIGNED_INT_VEC3 = 0x8DC7,
UNSIGNED_INT_VEC4 = 0x8DC8,
UNSIGNED_NORMALIZED = 0x8C17,
VERTEX_ARRAY_BINDING = 0x85B5,
VERTEX_ATTRIB_ARRAY_INTEGER = 0x88FD,
ACTIVE_UNIFORM_BLOCKS = 0x8A36,
ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH = 0x8A35,
COPY_READ_BUFFER = 0x8F36,
COPY_WRITE_BUFFER = 0x8F37,
INT_SAMPLER_2D_RECT = 0x8DCD,
INT_SAMPLER_BUFFER = 0x8DD0,
INVALID_INDEX = 0xFFFFFFFF,
MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS = 0x8A33,
MAX_COMBINED_GEOMETRY_UNIFORM_COMPONENTS = 0x8A32,
MAX_COMBINED_UNIFORM_BLOCKS = 0x8A2E,
MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS = 0x8A31,
MAX_FRAGMENT_UNIFORM_BLOCKS = 0x8A2D,
MAX_GEOMETRY_UNIFORM_BLOCKS = 0x8A2C,
MAX_RECTANGLE_TEXTURE_SIZE = 0x84F8,
MAX_TEXTURE_BUFFER_SIZE = 0x8C2B,
MAX_UNIFORM_BLOCK_SIZE = 0x8A30,
MAX_UNIFORM_BUFFER_BINDINGS = 0x8A2F,
MAX_VERTEX_UNIFORM_BLOCKS = 0x8A2B,
PRIMITIVE_RESTART = 0x8F9D,
PRIMITIVE_RESTART_INDEX = 0x8F9E,
PROXY_TEXTURE_RECTANGLE = 0x84F7,
R16_SNORM = 0x8F98,
R8_SNORM = 0x8F94,
RG16_SNORM = 0x8F99,
RG8_SNORM = 0x8F95,
RGB16_SNORM = 0x8F9A,
RGB8_SNORM = 0x8F96,
RGBA16_SNORM = 0x8F9B,
RGBA8_SNORM = 0x8F97,
SAMPLER_2D_RECT = 0x8B63,
SAMPLER_2D_RECT_SHADOW = 0x8B64,
SAMPLER_BUFFER = 0x8DC2,
SIGNED_NORMALIZED = 0x8F9C,
TEXTURE_BINDING_BUFFER = 0x8C2C,
TEXTURE_BINDING_RECTANGLE = 0x84F6,
TEXTURE_BUFFER = 0x8C2A,
TEXTURE_BUFFER_DATA_STORE_BINDING = 0x8C2D,
TEXTURE_RECTANGLE = 0x84F5,
UNIFORM_ARRAY_STRIDE = 0x8A3C,
UNIFORM_BLOCK_ACTIVE_UNIFORMS = 0x8A42,
UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES = 0x8A43,
UNIFORM_BLOCK_BINDING = 0x8A3F,
UNIFORM_BLOCK_DATA_SIZE = 0x8A40,
UNIFORM_BLOCK_INDEX = 0x8A3A,
UNIFORM_BLOCK_NAME_LENGTH = 0x8A41,
UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER = 0x8A46,
UNIFORM_BLOCK_REFERENCED_BY_GEOMETRY_SHADER = 0x8A45,
UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER = 0x8A44,
UNIFORM_BUFFER = 0x8A11,
UNIFORM_BUFFER_BINDING = 0x8A28,
UNIFORM_BUFFER_OFFSET_ALIGNMENT = 0x8A34,
UNIFORM_BUFFER_SIZE = 0x8A2A,
UNIFORM_BUFFER_START = 0x8A29,
UNIFORM_IS_ROW_MAJOR = 0x8A3E,
UNIFORM_MATRIX_STRIDE = 0x8A3D,
UNIFORM_NAME_LENGTH = 0x8A39,
UNIFORM_OFFSET = 0x8A3B,
UNIFORM_SIZE = 0x8A38,
UNIFORM_TYPE = 0x8A37,
UNSIGNED_INT_SAMPLER_2D_RECT = 0x8DD5,
UNSIGNED_INT_SAMPLER_BUFFER = 0x8DD8,
ALREADY_SIGNALED = 0x911A,
CONDITION_SATISFIED = 0x911C,
CONTEXT_COMPATIBILITY_PROFILE_BIT = 0x00000002,
CONTEXT_CORE_PROFILE_BIT = 0x00000001,
CONTEXT_PROFILE_MASK = 0x9126,
DEPTH_CLAMP = 0x864F,
FIRST_VERTEX_CONVENTION = 0x8E4D,
FRAMEBUFFER_ATTACHMENT_LAYERED = 0x8DA7,
FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS = 0x8DA8,
GEOMETRY_INPUT_TYPE = 0x8917,
GEOMETRY_OUTPUT_TYPE = 0x8918,
GEOMETRY_SHADER = 0x8DD9,
GEOMETRY_VERTICES_OUT = 0x8916,
INT_SAMPLER_2D_MULTISAMPLE = 0x9109,
INT_SAMPLER_2D_MULTISAMPLE_ARRAY = 0x910C,
LAST_VERTEX_CONVENTION = 0x8E4E,
LINES_ADJACENCY = 0x000A,
LINE_STRIP_ADJACENCY = 0x000B,
MAX_COLOR_TEXTURE_SAMPLES = 0x910E,
MAX_DEPTH_TEXTURE_SAMPLES = 0x910F,
MAX_FRAGMENT_INPUT_COMPONENTS = 0x9125,
MAX_GEOMETRY_INPUT_COMPONENTS = 0x9123,
MAX_GEOMETRY_OUTPUT_COMPONENTS = 0x9124,
MAX_GEOMETRY_OUTPUT_VERTICES = 0x8DE0,
MAX_GEOMETRY_TEXTURE_IMAGE_UNITS = 0x8C29,
MAX_GEOMETRY_TOTAL_OUTPUT_COMPONENTS = 0x8DE1,
MAX_GEOMETRY_UNIFORM_COMPONENTS = 0x8DDF,
MAX_INTEGER_SAMPLES = 0x9110,
MAX_SAMPLE_MASK_WORDS = 0x8E59,
MAX_SERVER_WAIT_TIMEOUT = 0x9111,
MAX_VERTEX_OUTPUT_COMPONENTS = 0x9122,
OBJECT_TYPE = 0x9112,
PROGRAM_POINT_SIZE = 0x8642,
PROVOKING_VERTEX = 0x8E4F,
PROXY_TEXTURE_2D_MULTISAMPLE = 0x9101,
PROXY_TEXTURE_2D_MULTISAMPLE_ARRAY = 0x9103,
QUADS_FOLLOW_PROVOKING_VERTEX_CONVENTION = 0x8E4C,
SAMPLER_2D_MULTISAMPLE = 0x9108,
SAMPLER_2D_MULTISAMPLE_ARRAY = 0x910B,
SAMPLE_MASK = 0x8E51,
SAMPLE_MASK_VALUE = 0x8E52,
SAMPLE_POSITION = 0x8E50,
SIGNALED = 0x9119,
SYNC_CONDITION = 0x9113,
SYNC_FENCE = 0x9116,
SYNC_FLAGS = 0x9115,
SYNC_FLUSH_COMMANDS_BIT = 0x00000001,
SYNC_GPU_COMMANDS_COMPLETE = 0x9117,
SYNC_STATUS = 0x9114,
TEXTURE_2D_MULTISAMPLE = 0x9100,
TEXTURE_2D_MULTISAMPLE_ARRAY = 0x9102,
TEXTURE_BINDING_2D_MULTISAMPLE = 0x9104,
TEXTURE_BINDING_2D_MULTISAMPLE_ARRAY = 0x9105,
TEXTURE_CUBE_MAP_SEAMLESS = 0x884F,
TEXTURE_FIXED_SAMPLE_LOCATIONS = 0x9107,
TEXTURE_SAMPLES = 0x9106,
TIMEOUT_EXPIRED = 0x911B,
TIMEOUT_IGNORED = 0xFFFFFFFFFFFFFFFF,
TRIANGLES_ADJACENCY = 0x000C,
TRIANGLE_STRIP_ADJACENCY = 0x000D,
UNSIGNALED = 0x9118,
UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE = 0x910A,
UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY = 0x910D,
WAIT_FAILED_ = 0x911D,
ANY_SAMPLES_PASSED = 0x8C2F,
INT_2_10_10_10_REV = 0x8D9F,
MAX_DUAL_SOURCE_DRAW_BUFFERS = 0x88FC,
ONE_MINUS_SRC1_ALPHA = 0x88FB,
ONE_MINUS_SRC1_COLOR = 0x88FA,
RGB10_A2UI = 0x906F,
SAMPLER_BINDING = 0x8919,
SRC1_COLOR = 0x88F9,
TEXTURE_SWIZZLE_A = 0x8E45,
TEXTURE_SWIZZLE_B = 0x8E44,
TEXTURE_SWIZZLE_G = 0x8E43,
TEXTURE_SWIZZLE_R = 0x8E42,
TEXTURE_SWIZZLE_RGBA = 0x8E46,
TIMESTAMP = 0x8E28,
TIME_ELAPSED = 0x88BF,
VERTEX_ATTRIB_ARRAY_DIVISOR = 0x88FE,
ACTIVE_SUBROUTINES = 0x8DE5,
ACTIVE_SUBROUTINE_MAX_LENGTH = 0x8E48,
ACTIVE_SUBROUTINE_UNIFORMS = 0x8DE6,
ACTIVE_SUBROUTINE_UNIFORM_LOCATIONS = 0x8E47,
ACTIVE_SUBROUTINE_UNIFORM_MAX_LENGTH = 0x8E49,
COMPATIBLE_SUBROUTINES = 0x8E4B,
DOUBLE_MAT2 = 0x8F46,
DOUBLE_MAT2x3 = 0x8F49,
DOUBLE_MAT2x4 = 0x8F4A,
DOUBLE_MAT3 = 0x8F47,
DOUBLE_MAT3x2 = 0x8F4B,
DOUBLE_MAT3x4 = 0x8F4C,
DOUBLE_MAT4 = 0x8F48,
DOUBLE_MAT4x2 = 0x8F4D,
DOUBLE_MAT4x3 = 0x8F4E,
DOUBLE_VEC2 = 0x8FFC,
DOUBLE_VEC3 = 0x8FFD,
DOUBLE_VEC4 = 0x8FFE,
DRAW_INDIRECT_BUFFER = 0x8F3F,
DRAW_INDIRECT_BUFFER_BINDING = 0x8F43,
FRACTIONAL_EVEN = 0x8E7C,
FRACTIONAL_ODD = 0x8E7B,
FRAGMENT_INTERPOLATION_OFFSET_BITS = 0x8E5D,
GEOMETRY_SHADER_INVOCATIONS = 0x887F,
INT_SAMPLER_CUBE_MAP_ARRAY = 0x900E,
ISOLINES = 0x8E7A,
MAX_COMBINED_TESS_CONTROL_UNIFORM_COMPONENTS = 0x8E1E,
MAX_COMBINED_TESS_EVALUATION_UNIFORM_COMPONENTS = 0x8E1F,
MAX_FRAGMENT_INTERPOLATION_OFFSET = 0x8E5C,
MAX_GEOMETRY_SHADER_INVOCATIONS = 0x8E5A,
MAX_PATCH_VERTICES = 0x8E7D,
MAX_PROGRAM_TEXTURE_GATHER_OFFSET = 0x8E5F,
MAX_SUBROUTINES = 0x8DE7,
MAX_SUBROUTINE_UNIFORM_LOCATIONS = 0x8DE8,
MAX_TESS_CONTROL_INPUT_COMPONENTS = 0x886C,
MAX_TESS_CONTROL_OUTPUT_COMPONENTS = 0x8E83,
MAX_TESS_CONTROL_TEXTURE_IMAGE_UNITS = 0x8E81,
MAX_TESS_CONTROL_TOTAL_OUTPUT_COMPONENTS = 0x8E85,
MAX_TESS_CONTROL_UNIFORM_BLOCKS = 0x8E89,
MAX_TESS_CONTROL_UNIFORM_COMPONENTS = 0x8E7F,
MAX_TESS_EVALUATION_INPUT_COMPONENTS = 0x886D,
MAX_TESS_EVALUATION_OUTPUT_COMPONENTS = 0x8E86,
MAX_TESS_EVALUATION_TEXTURE_IMAGE_UNITS = 0x8E82,
MAX_TESS_EVALUATION_UNIFORM_BLOCKS = 0x8E8A,
MAX_TESS_EVALUATION_UNIFORM_COMPONENTS = 0x8E80,
MAX_TESS_GEN_LEVEL = 0x8E7E,
MAX_TESS_PATCH_COMPONENTS = 0x8E84,
MAX_TRANSFORM_FEEDBACK_BUFFERS = 0x8E70,
MAX_VERTEX_STREAMS = 0x8E71,
MIN_FRAGMENT_INTERPOLATION_OFFSET = 0x8E5B,
MIN_PROGRAM_TEXTURE_GATHER_OFFSET = 0x8E5E,
MIN_SAMPLE_SHADING_VALUE = 0x8C37,
NUM_COMPATIBLE_SUBROUTINES = 0x8E4A,
PATCHES = 0x000E,
PATCH_DEFAULT_INNER_LEVEL = 0x8E73,
PATCH_DEFAULT_OUTER_LEVEL = 0x8E74,
PATCH_VERTICES = 0x8E72,
PROXY_TEXTURE_CUBE_MAP_ARRAY = 0x900B,
SAMPLER_CUBE_MAP_ARRAY = 0x900C,
SAMPLER_CUBE_MAP_ARRAY_SHADOW = 0x900D,
SAMPLE_SHADING = 0x8C36,
TESS_CONTROL_OUTPUT_VERTICES = 0x8E75,
TESS_CONTROL_SHADER = 0x8E88,
TESS_EVALUATION_SHADER = 0x8E87,
TESS_GEN_MODE = 0x8E76,
TESS_GEN_POINT_MODE = 0x8E79,
TESS_GEN_SPACING = 0x8E77,
TESS_GEN_VERTEX_ORDER = 0x8E78,
TEXTURE_BINDING_CUBE_MAP_ARRAY = 0x900A,
TEXTURE_CUBE_MAP_ARRAY = 0x9009,
TRANSFORM_FEEDBACK = 0x8E22,
TRANSFORM_FEEDBACK_BINDING = 0x8E25,
TRANSFORM_FEEDBACK_BUFFER_ACTIVE = 0x8E24,
TRANSFORM_FEEDBACK_BUFFER_PAUSED = 0x8E23,
UNIFORM_BLOCK_REFERENCED_BY_TESS_CONTROL_SHADER = 0x84F0,
UNIFORM_BLOCK_REFERENCED_BY_TESS_EVALUATION_SHADER = 0x84F1,
UNSIGNED_INT_SAMPLER_CUBE_MAP_ARRAY = 0x900F,
ACTIVE_PROGRAM = 0x8259,
ALL_SHADER_BITS = 0xFFFFFFFF,
FIXED = 0x140C,
FRAGMENT_SHADER_BIT = 0x00000002,
GEOMETRY_SHADER_BIT = 0x00000004,
HIGH_FLOAT = 0x8DF2,
HIGH_INT = 0x8DF5,
IMPLEMENTATION_COLOR_READ_FORMAT = 0x8B9B,
IMPLEMENTATION_COLOR_READ_TYPE = 0x8B9A,
LAYER_PROVOKING_VERTEX = 0x825E,
LOW_FLOAT = 0x8DF0,
LOW_INT = 0x8DF3,
MAX_FRAGMENT_UNIFORM_VECTORS = 0x8DFD,
MAX_VARYING_VECTORS = 0x8DFC,
MAX_VERTEX_UNIFORM_VECTORS = 0x8DFB,
MAX_VIEWPORTS = 0x825B,
MEDIUM_FLOAT = 0x8DF1,
MEDIUM_INT = 0x8DF4,
NUM_PROGRAM_BINARY_FORMATS = 0x87FE,
NUM_SHADER_BINARY_FORMATS = 0x8DF9,
PROGRAM_BINARY_FORMATS = 0x87FF,
PROGRAM_BINARY_LENGTH = 0x8741,
PROGRAM_BINARY_RETRIEVABLE_HINT = 0x8257,
PROGRAM_PIPELINE_BINDING = 0x825A,
PROGRAM_SEPARABLE = 0x8258,
RGB565 = 0x8D62,
SHADER_BINARY_FORMATS = 0x8DF8,
SHADER_COMPILER = 0x8DFA,
TESS_CONTROL_SHADER_BIT = 0x00000008,
TESS_EVALUATION_SHADER_BIT = 0x00000010,
UNDEFINED_VERTEX = 0x8260,
VERTEX_SHADER_BIT = 0x00000001,
VIEWPORT_BOUNDS_RANGE = 0x825D,
VIEWPORT_INDEX_PROVOKING_VERTEX = 0x825F,
VIEWPORT_SUBPIXEL_BITS = 0x825C,
ACTIVE_ATOMIC_COUNTER_BUFFERS = 0x92D9,
ALL_BARRIER_BITS = 0xFFFFFFFF,
ATOMIC_COUNTER_BARRIER_BIT = 0x00001000,
ATOMIC_COUNTER_BUFFER = 0x92C0,
ATOMIC_COUNTER_BUFFER_ACTIVE_ATOMIC_COUNTERS = 0x92C5,
ATOMIC_COUNTER_BUFFER_ACTIVE_ATOMIC_COUNTER_INDICES = 0x92C6,
ATOMIC_COUNTER_BUFFER_BINDING = 0x92C1,
ATOMIC_COUNTER_BUFFER_DATA_SIZE = 0x92C4,
ATOMIC_COUNTER_BUFFER_REFERENCED_BY_FRAGMENT_SHADER = 0x92CB,
ATOMIC_COUNTER_BUFFER_REFERENCED_BY_GEOMETRY_SHADER = 0x92CA,
ATOMIC_COUNTER_BUFFER_REFERENCED_BY_TESS_CONTROL_SHADER = 0x92C8,
ATOMIC_COUNTER_BUFFER_REFERENCED_BY_TESS_EVALUATION_SHADER = 0x92C9,
ATOMIC_COUNTER_BUFFER_REFERENCED_BY_VERTEX_SHADER = 0x92C7,
ATOMIC_COUNTER_BUFFER_SIZE = 0x92C3,
ATOMIC_COUNTER_BUFFER_START = 0x92C2,
BUFFER_UPDATE_BARRIER_BIT = 0x00000200,
COMMAND_BARRIER_BIT = 0x00000040,
COMPRESSED_RGBA_BPTC_UNORM = 0x8E8C,
COMPRESSED_RGB_BPTC_SIGNED_FLOAT = 0x8E8E,
COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT = 0x8E8F,
COMPRESSED_SRGB_ALPHA_BPTC_UNORM = 0x8E8D,
COPY_READ_BUFFER_BINDING = 0x8F36,
COPY_WRITE_BUFFER_BINDING = 0x8F37,
ELEMENT_ARRAY_BARRIER_BIT = 0x00000002,
FRAMEBUFFER_BARRIER_BIT = 0x00000400,
IMAGE_1D = 0x904C,
IMAGE_1D_ARRAY = 0x9052,
IMAGE_2D = 0x904D,
IMAGE_2D_ARRAY = 0x9053,
IMAGE_2D_MULTISAMPLE = 0x9055,
IMAGE_2D_MULTISAMPLE_ARRAY = 0x9056,
IMAGE_2D_RECT = 0x904F,
IMAGE_3D = 0x904E,
IMAGE_BINDING_ACCESS = 0x8F3E,
IMAGE_BINDING_FORMAT = 0x906E,
IMAGE_BINDING_LAYER = 0x8F3D,
IMAGE_BINDING_LAYERED = 0x8F3C,
IMAGE_BINDING_LEVEL = 0x8F3B,
IMAGE_BINDING_NAME = 0x8F3A,
IMAGE_BUFFER = 0x9051,
IMAGE_CUBE = 0x9050,
IMAGE_CUBE_MAP_ARRAY = 0x9054,
IMAGE_FORMAT_COMPATIBILITY_BY_CLASS = 0x90C9,
IMAGE_FORMAT_COMPATIBILITY_BY_SIZE = 0x90C8,
IMAGE_FORMAT_COMPATIBILITY_TYPE = 0x90C7,
INT_IMAGE_1D = 0x9057,
INT_IMAGE_1D_ARRAY = 0x905D,
INT_IMAGE_2D = 0x9058,
INT_IMAGE_2D_ARRAY = 0x905E,
INT_IMAGE_2D_MULTISAMPLE = 0x9060,
INT_IMAGE_2D_MULTISAMPLE_ARRAY = 0x9061,
INT_IMAGE_2D_RECT = 0x905A,
INT_IMAGE_3D = 0x9059,
INT_IMAGE_BUFFER = 0x905C,
INT_IMAGE_CUBE = 0x905B,
INT_IMAGE_CUBE_MAP_ARRAY = 0x905F,
MAX_ATOMIC_COUNTER_BUFFER_BINDINGS = 0x92DC,
MAX_ATOMIC_COUNTER_BUFFER_SIZE = 0x92D8,
MAX_COMBINED_ATOMIC_COUNTERS = 0x92D7,
MAX_COMBINED_ATOMIC_COUNTER_BUFFERS = 0x92D1,
MAX_COMBINED_IMAGE_UNIFORMS = 0x90CF,
MAX_COMBINED_IMAGE_UNITS_AND_FRAGMENT_OUTPUTS = 0x8F39,
MAX_FRAGMENT_ATOMIC_COUNTERS = 0x92D6,
MAX_FRAGMENT_ATOMIC_COUNTER_BUFFERS = 0x92D0,
MAX_FRAGMENT_IMAGE_UNIFORMS = 0x90CE,
MAX_GEOMETRY_ATOMIC_COUNTERS = 0x92D5,
MAX_GEOMETRY_ATOMIC_COUNTER_BUFFERS = 0x92CF,
MAX_GEOMETRY_IMAGE_UNIFORMS = 0x90CD,
MAX_IMAGE_SAMPLES = 0x906D,
MAX_IMAGE_UNITS = 0x8F38,
MAX_TESS_CONTROL_ATOMIC_COUNTERS = 0x92D3,
MAX_TESS_CONTROL_ATOMIC_COUNTER_BUFFERS = 0x92CD,
MAX_TESS_CONTROL_IMAGE_UNIFORMS = 0x90CB,
MAX_TESS_EVALUATION_ATOMIC_COUNTERS = 0x92D4,
MAX_TESS_EVALUATION_ATOMIC_COUNTER_BUFFERS = 0x92CE,
MAX_TESS_EVALUATION_IMAGE_UNIFORMS = 0x90CC,
MAX_VERTEX_ATOMIC_COUNTERS = 0x92D2,
MAX_VERTEX_ATOMIC_COUNTER_BUFFERS = 0x92CC,
MAX_VERTEX_IMAGE_UNIFORMS = 0x90CA,
MIN_MAP_BUFFER_ALIGNMENT = 0x90BC,
NUM_SAMPLE_COUNTS = 0x9380,
PACK_COMPRESSED_BLOCK_DEPTH = 0x912D,
PACK_COMPRESSED_BLOCK_HEIGHT = 0x912C,
PACK_COMPRESSED_BLOCK_SIZE = 0x912E,
PACK_COMPRESSED_BLOCK_WIDTH = 0x912B,
PIXEL_BUFFER_BARRIER_BIT = 0x00000080,
SHADER_IMAGE_ACCESS_BARRIER_BIT = 0x00000020,
TEXTURE_FETCH_BARRIER_BIT = 0x00000008,
TEXTURE_IMMUTABLE_FORMAT = 0x912F,
TEXTURE_UPDATE_BARRIER_BIT = 0x00000100,
TRANSFORM_FEEDBACK_ACTIVE = 0x8E24,
TRANSFORM_FEEDBACK_BARRIER_BIT = 0x00000800,
TRANSFORM_FEEDBACK_PAUSED = 0x8E23,
UNIFORM_ATOMIC_COUNTER_BUFFER_INDEX = 0x92DA,
UNIFORM_BARRIER_BIT = 0x00000004,
UNPACK_COMPRESSED_BLOCK_DEPTH = 0x9129,
UNPACK_COMPRESSED_BLOCK_HEIGHT = 0x9128,
UNPACK_COMPRESSED_BLOCK_SIZE = 0x912A,
UNPACK_COMPRESSED_BLOCK_WIDTH = 0x9127,
UNSIGNED_INT_ATOMIC_COUNTER = 0x92DB,
UNSIGNED_INT_IMAGE_1D = 0x9062,
UNSIGNED_INT_IMAGE_1D_ARRAY = 0x9068,
UNSIGNED_INT_IMAGE_2D = 0x9063,
UNSIGNED_INT_IMAGE_2D_ARRAY = 0x9069,
UNSIGNED_INT_IMAGE_2D_MULTISAMPLE = 0x906B,
UNSIGNED_INT_IMAGE_2D_MULTISAMPLE_ARRAY = 0x906C,
UNSIGNED_INT_IMAGE_2D_RECT = 0x9065,
UNSIGNED_INT_IMAGE_3D = 0x9064,
UNSIGNED_INT_IMAGE_BUFFER = 0x9067,
UNSIGNED_INT_IMAGE_CUBE = 0x9066,
UNSIGNED_INT_IMAGE_CUBE_MAP_ARRAY = 0x906A,
VERTEX_ATTRIB_ARRAY_BARRIER_BIT = 0x00000001,
ACTIVE_RESOURCES = 0x92F5,
ACTIVE_VARIABLES = 0x9305,
ANY_SAMPLES_PASSED_CONSERVATIVE = 0x8D6A,
ARRAY_SIZE = 0x92FB,
ARRAY_STRIDE = 0x92FE,
ATOMIC_COUNTER_BUFFER_INDEX = 0x9301,
ATOMIC_COUNTER_BUFFER_REFERENCED_BY_COMPUTE_SHADER = 0x90ED,
AUTO_GENERATE_MIPMAP = 0x8295,
BLOCK_INDEX = 0x92FD,
BUFFER = 0x82E0,
BUFFER_BINDING = 0x9302,
BUFFER_DATA_SIZE = 0x9303,
BUFFER_VARIABLE = 0x92E5,
CAVEAT_SUPPORT = 0x82B8,
CLEAR_BUFFER = 0x82B4,
COLOR_COMPONENTS = 0x8283,
COLOR_ENCODING = 0x8296,
COLOR_RENDERABLE = 0x8286,
COMPRESSED_R11_EAC = 0x9270,
COMPRESSED_RG11_EAC = 0x9272,
COMPRESSED_RGB8_ETC2 = 0x9274,
COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2 = 0x9276,
COMPRESSED_RGBA8_ETC2_EAC = 0x9278,
COMPRESSED_SIGNED_R11_EAC = 0x9271,
COMPRESSED_SIGNED_RG11_EAC = 0x9273,
COMPRESSED_SRGB8_ALPHA8_ETC2_EAC = 0x9279,
COMPRESSED_SRGB8_ETC2 = 0x9275,
COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2 = 0x9277,
COMPUTE_SHADER = 0x91B9,
COMPUTE_SHADER_BIT = 0x00000020,
COMPUTE_SUBROUTINE = 0x92ED,
COMPUTE_SUBROUTINE_UNIFORM = 0x92F3,
COMPUTE_TEXTURE = 0x82A0,
COMPUTE_WORK_GROUP_SIZE = 0x8267,
CONTEXT_FLAG_DEBUG_BIT = 0x00000002,
DEBUG_CALLBACK_FUNCTION = 0x8244,
DEBUG_CALLBACK_USER_PARAM = 0x8245,
DEBUG_GROUP_STACK_DEPTH = 0x826D,
DEBUG_LOGGED_MESSAGES = 0x9145,
DEBUG_NEXT_LOGGED_MESSAGE_LENGTH = 0x8243,
DEBUG_OUTPUT = 0x92E0,
DEBUG_OUTPUT_SYNCHRONOUS = 0x8242,
DEBUG_SEVERITY_HIGH = 0x9146,
DEBUG_SEVERITY_LOW = 0x9148,
DEBUG_SEVERITY_MEDIUM = 0x9147,
DEBUG_SEVERITY_NOTIFICATION = 0x826B,
DEBUG_SOURCE_API = 0x8246,
DEBUG_SOURCE_APPLICATION = 0x824A,
DEBUG_SOURCE_OTHER = 0x824B,
DEBUG_SOURCE_SHADER_COMPILER = 0x8248,
DEBUG_SOURCE_THIRD_PARTY = 0x8249,
DEBUG_SOURCE_WINDOW_SYSTEM = 0x8247,
DEBUG_TYPE_DEPRECATED_BEHAVIOR = 0x824D,
DEBUG_TYPE_ERROR = 0x824C,
DEBUG_TYPE_MARKER = 0x8268,
DEBUG_TYPE_OTHER = 0x8251,
DEBUG_TYPE_PERFORMANCE = 0x8250,
DEBUG_TYPE_POP_GROUP = 0x826A,
DEBUG_TYPE_PORTABILITY = 0x824F,
DEBUG_TYPE_PUSH_GROUP = 0x8269,
DEBUG_TYPE_UNDEFINED_BEHAVIOR = 0x824E,
DEPTH_COMPONENTS = 0x8284,
DEPTH_RENDERABLE = 0x8287,
DEPTH_STENCIL_TEXTURE_MODE = 0x90EA,
DISPATCH_INDIRECT_BUFFER = 0x90EE,
DISPATCH_INDIRECT_BUFFER_BINDING = 0x90EF,
FILTER = 0x829A,
FRAGMENT_SUBROUTINE = 0x92EC,
FRAGMENT_SUBROUTINE_UNIFORM = 0x92F2,
FRAGMENT_TEXTURE = 0x829F,
FRAMEBUFFER_BLEND = 0x828B,
FRAMEBUFFER_DEFAULT_FIXED_SAMPLE_LOCATIONS = 0x9314,
FRAMEBUFFER_DEFAULT_HEIGHT = 0x9311,
FRAMEBUFFER_DEFAULT_LAYERS = 0x9312,
FRAMEBUFFER_DEFAULT_SAMPLES = 0x9313,
FRAMEBUFFER_DEFAULT_WIDTH = 0x9310,
FRAMEBUFFER_RENDERABLE = 0x8289,
FRAMEBUFFER_RENDERABLE_LAYERED = 0x828A,
FULL_SUPPORT = 0x82B7,
GEOMETRY_SUBROUTINE = 0x92EB,
GEOMETRY_SUBROUTINE_UNIFORM = 0x92F1,
GEOMETRY_TEXTURE = 0x829E,
GET_TEXTURE_IMAGE_FORMAT = 0x8291,
GET_TEXTURE_IMAGE_TYPE = 0x8292,
IMAGE_CLASS_10_10_10_2 = 0x82C3,
IMAGE_CLASS_11_11_10 = 0x82C2,
IMAGE_CLASS_1_X_16 = 0x82BE,
IMAGE_CLASS_1_X_32 = 0x82BB,
IMAGE_CLASS_1_X_8 = 0x82C1,
IMAGE_CLASS_2_X_16 = 0x82BD,
IMAGE_CLASS_2_X_32 = 0x82BA,
IMAGE_CLASS_2_X_8 = 0x82C0,
IMAGE_CLASS_4_X_16 = 0x82BC,
IMAGE_CLASS_4_X_32 = 0x82B9,
IMAGE_CLASS_4_X_8 = 0x82BF,
IMAGE_COMPATIBILITY_CLASS = 0x82A8,
IMAGE_PIXEL_FORMAT = 0x82A9,
IMAGE_PIXEL_TYPE = 0x82AA,
IMAGE_TEXEL_SIZE = 0x82A7,
INTERNALFORMAT_ALPHA_SIZE = 0x8274,
INTERNALFORMAT_ALPHA_TYPE = 0x827B,
INTERNALFORMAT_BLUE_SIZE = 0x8273,
INTERNALFORMAT_BLUE_TYPE = 0x827A,
INTERNALFORMAT_DEPTH_SIZE = 0x8275,
INTERNALFORMAT_DEPTH_TYPE = 0x827C,
INTERNALFORMAT_GREEN_SIZE = 0x8272,
INTERNALFORMAT_GREEN_TYPE = 0x8279,
INTERNALFORMAT_PREFERRED = 0x8270,
INTERNALFORMAT_RED_SIZE = 0x8271,
INTERNALFORMAT_RED_TYPE = 0x8278,
INTERNALFORMAT_SHARED_SIZE = 0x8277,
INTERNALFORMAT_STENCIL_SIZE = 0x8276,
INTERNALFORMAT_STENCIL_TYPE = 0x827D,
INTERNALFORMAT_SUPPORTED = 0x826F,
IS_PER_PATCH = 0x92E7,
IS_ROW_MAJOR = 0x9300,
LOCATION = 0x930E,
LOCATION_INDEX = 0x930F,
MANUAL_GENERATE_MIPMAP = 0x8294,
MATRIX_STRIDE = 0x92FF,
MAX_COMBINED_COMPUTE_UNIFORM_COMPONENTS = 0x8266,
MAX_COMBINED_DIMENSIONS = 0x8282,
MAX_COMBINED_SHADER_OUTPUT_RESOURCES = 0x8F39,
MAX_COMBINED_SHADER_STORAGE_BLOCKS = 0x90DC,
MAX_COMPUTE_ATOMIC_COUNTERS = 0x8265,
MAX_COMPUTE_ATOMIC_COUNTER_BUFFERS = 0x8264,
MAX_COMPUTE_IMAGE_UNIFORMS = 0x91BD,
MAX_COMPUTE_SHADER_STORAGE_BLOCKS = 0x90DB,
MAX_COMPUTE_SHARED_MEMORY_SIZE = 0x8262,
MAX_COMPUTE_TEXTURE_IMAGE_UNITS = 0x91BC,
MAX_COMPUTE_UNIFORM_BLOCKS = 0x91BB,
MAX_COMPUTE_UNIFORM_COMPONENTS = 0x8263,
MAX_COMPUTE_WORK_GROUP_COUNT = 0x91BE,
MAX_COMPUTE_WORK_GROUP_INVOCATIONS = 0x90EB,
MAX_COMPUTE_WORK_GROUP_SIZE = 0x91BF,
MAX_DEBUG_GROUP_STACK_DEPTH = 0x826C,
MAX_DEBUG_LOGGED_MESSAGES = 0x9144,
MAX_DEBUG_MESSAGE_LENGTH = 0x9143,
MAX_DEPTH = 0x8280,
MAX_ELEMENT_INDEX = 0x8D6B,
MAX_FRAGMENT_SHADER_STORAGE_BLOCKS = 0x90DA,
MAX_FRAMEBUFFER_HEIGHT = 0x9316,
MAX_FRAMEBUFFER_LAYERS = 0x9317,
MAX_FRAMEBUFFER_SAMPLES = 0x9318,
MAX_FRAMEBUFFER_WIDTH = 0x9315,
MAX_GEOMETRY_SHADER_STORAGE_BLOCKS = 0x90D7,
MAX_HEIGHT = 0x827F,
MAX_LABEL_LENGTH = 0x82E8,
MAX_LAYERS = 0x8281,
MAX_NAME_LENGTH = 0x92F6,
MAX_NUM_ACTIVE_VARIABLES = 0x92F7,
MAX_NUM_COMPATIBLE_SUBROUTINES = 0x92F8,
MAX_SHADER_STORAGE_BLOCK_SIZE = 0x90DE,
MAX_SHADER_STORAGE_BUFFER_BINDINGS = 0x90DD,
MAX_TESS_CONTROL_SHADER_STORAGE_BLOCKS = 0x90D8,
MAX_TESS_EVALUATION_SHADER_STORAGE_BLOCKS = 0x90D9,
MAX_UNIFORM_LOCATIONS = 0x826E,
MAX_VERTEX_ATTRIB_BINDINGS = 0x82DA,
MAX_VERTEX_ATTRIB_RELATIVE_OFFSET = 0x82D9,
MAX_VERTEX_SHADER_STORAGE_BLOCKS = 0x90D6,
MAX_WIDTH = 0x827E,
MIPMAP = 0x8293,
NAME_LENGTH = 0x92F9,
NUM_ACTIVE_VARIABLES = 0x9304,
NUM_SHADING_LANGUAGE_VERSIONS = 0x82E9,
OFFSET = 0x92FC,
PRIMITIVE_RESTART_FIXED_INDEX = 0x8D69,
PROGRAM = 0x82E2,
PROGRAM_INPUT = 0x92E3,
PROGRAM_OUTPUT = 0x92E4,
PROGRAM_PIPELINE = 0x82E4,
QUERY = 0x82E3,
READ_PIXELS = 0x828C,
READ_PIXELS_FORMAT = 0x828D,
READ_PIXELS_TYPE = 0x828E,
REFERENCED_BY_COMPUTE_SHADER = 0x930B,
REFERENCED_BY_FRAGMENT_SHADER = 0x930A,
REFERENCED_BY_GEOMETRY_SHADER = 0x9309,
REFERENCED_BY_TESS_CONTROL_SHADER = 0x9307,
REFERENCED_BY_TESS_EVALUATION_SHADER = 0x9308,
REFERENCED_BY_VERTEX_SHADER = 0x9306,
SAMPLER = 0x82E6,
SHADER = 0x82E1,
SHADER_IMAGE_ATOMIC = 0x82A6,
SHADER_IMAGE_LOAD = 0x82A4,
SHADER_IMAGE_STORE = 0x82A5,
SHADER_STORAGE_BARRIER_BIT = 0x00002000,
SHADER_STORAGE_BLOCK = 0x92E6,
SHADER_STORAGE_BUFFER = 0x90D2,
SHADER_STORAGE_BUFFER_BINDING = 0x90D3,
SHADER_STORAGE_BUFFER_OFFSET_ALIGNMENT = 0x90DF,
SHADER_STORAGE_BUFFER_SIZE = 0x90D5,
SHADER_STORAGE_BUFFER_START = 0x90D4,
SIMULTANEOUS_TEXTURE_AND_DEPTH_TEST = 0x82AC,
SIMULTANEOUS_TEXTURE_AND_DEPTH_WRITE = 0x82AE,
SIMULTANEOUS_TEXTURE_AND_STENCIL_TEST = 0x82AD,
SIMULTANEOUS_TEXTURE_AND_STENCIL_WRITE = 0x82AF,
SRGB_READ = 0x8297,
SRGB_WRITE = 0x8298,
STENCIL_COMPONENTS = 0x8285,
STENCIL_RENDERABLE = 0x8288,
TESS_CONTROL_SUBROUTINE = 0x92E9,
TESS_CONTROL_SUBROUTINE_UNIFORM = 0x92EF,
TESS_CONTROL_TEXTURE = 0x829C,
TESS_EVALUATION_SUBROUTINE = 0x92EA,
TESS_EVALUATION_SUBROUTINE_UNIFORM = 0x92F0,
TESS_EVALUATION_TEXTURE = 0x829D,
TEXTURE_BUFFER_OFFSET = 0x919D,
TEXTURE_BUFFER_OFFSET_ALIGNMENT = 0x919F,
TEXTURE_BUFFER_SIZE = 0x919E,
TEXTURE_COMPRESSED_BLOCK_HEIGHT = 0x82B2,
TEXTURE_COMPRESSED_BLOCK_SIZE = 0x82B3,
TEXTURE_COMPRESSED_BLOCK_WIDTH = 0x82B1,
TEXTURE_GATHER = 0x82A2,
TEXTURE_GATHER_SHADOW = 0x82A3,
TEXTURE_IMAGE_FORMAT = 0x828F,
TEXTURE_IMAGE_TYPE = 0x8290,
TEXTURE_IMMUTABLE_LEVELS = 0x82DF,
TEXTURE_SHADOW = 0x82A1,
TEXTURE_VIEW = 0x82B5,
TEXTURE_VIEW_MIN_LAYER = 0x82DD,
TEXTURE_VIEW_MIN_LEVEL = 0x82DB,
TEXTURE_VIEW_NUM_LAYERS = 0x82DE,
TEXTURE_VIEW_NUM_LEVELS = 0x82DC,
TOP_LEVEL_ARRAY_SIZE = 0x930C,
TOP_LEVEL_ARRAY_STRIDE = 0x930D,
TRANSFORM_FEEDBACK_VARYING = 0x92F4,
TYPE = 0x92FA,
UNIFORM = 0x92E1,
UNIFORM_BLOCK = 0x92E2,
UNIFORM_BLOCK_REFERENCED_BY_COMPUTE_SHADER = 0x90EC,
VERTEX_ATTRIB_ARRAY_LONG = 0x874E,
VERTEX_ATTRIB_BINDING = 0x82D4,
VERTEX_ATTRIB_RELATIVE_OFFSET = 0x82D5,
VERTEX_BINDING_BUFFER = 0x8F4F,
VERTEX_BINDING_DIVISOR = 0x82D6,
VERTEX_BINDING_OFFSET = 0x82D7,
VERTEX_BINDING_STRIDE = 0x82D8,
VERTEX_SUBROUTINE = 0x92E8,
VERTEX_SUBROUTINE_UNIFORM = 0x92EE,
VERTEX_TEXTURE = 0x829B,
VIEW_CLASS_128_BITS = 0x82C4,
VIEW_CLASS_16_BITS = 0x82CA,
VIEW_CLASS_24_BITS = 0x82C9,
VIEW_CLASS_32_BITS = 0x82C8,
VIEW_CLASS_48_BITS = 0x82C7,
VIEW_CLASS_64_BITS = 0x82C6,
VIEW_CLASS_8_BITS = 0x82CB,
VIEW_CLASS_96_BITS = 0x82C5,
VIEW_CLASS_BPTC_FLOAT = 0x82D3,
VIEW_CLASS_BPTC_UNORM = 0x82D2,
VIEW_CLASS_RGTC1_RED = 0x82D0,
VIEW_CLASS_RGTC2_RG = 0x82D1,
VIEW_CLASS_S3TC_DXT1_RGB = 0x82CC,
VIEW_CLASS_S3TC_DXT1_RGBA = 0x82CD,
VIEW_CLASS_S3TC_DXT3_RGBA = 0x82CE,
VIEW_CLASS_S3TC_DXT5_RGBA = 0x82CF,
VIEW_COMPATIBILITY_CLASS = 0x82B6,
BUFFER_IMMUTABLE_STORAGE = 0x821F,
BUFFER_STORAGE_FLAGS = 0x8220,
CLEAR_TEXTURE = 0x9365,
CLIENT_MAPPED_BUFFER_BARRIER_BIT = 0x00004000,
CLIENT_STORAGE_BIT = 0x0200,
DYNAMIC_STORAGE_BIT = 0x0100,
LOCATION_COMPONENT = 0x934A,
MAP_COHERENT_BIT = 0x0080,
MAP_PERSISTENT_BIT = 0x0040,
MAX_VERTEX_ATTRIB_STRIDE = 0x82E5,
MIRROR_CLAMP_TO_EDGE = 0x8743,
PRIMITIVE_RESTART_FOR_PATCHES_SUPPORTED = 0x8221,
QUERY_BUFFER = 0x9192,
QUERY_BUFFER_BARRIER_BIT = 0x00008000,
QUERY_BUFFER_BINDING = 0x9193,
QUERY_RESULT_NO_WAIT = 0x9194,
TEXTURE_BUFFER_BINDING = 0x8C2A,
TRANSFORM_FEEDBACK_BUFFER_INDEX = 0x934B,
TRANSFORM_FEEDBACK_BUFFER_STRIDE = 0x934C,
CLIP_DEPTH_MODE = 0x935D,
CLIP_ORIGIN = 0x935C,
CONTEXT_FLAG_ROBUST_ACCESS_BIT = 0x00000004,
CONTEXT_LOST = 0x0507,
CONTEXT_RELEASE_BEHAVIOR = 0x82FB,
CONTEXT_RELEASE_BEHAVIOR_FLUSH = 0x82FC,
GUILTY_CONTEXT_RESET = 0x8253,
INNOCENT_CONTEXT_RESET = 0x8254,
LOSE_CONTEXT_ON_RESET = 0x8252,
MAX_COMBINED_CLIP_AND_CULL_DISTANCES = 0x82FA,
MAX_CULL_DISTANCES = 0x82F9,
NEGATIVE_ONE_TO_ONE = 0x935E,
NO_RESET_NOTIFICATION = 0x8261,
QUERY_BY_REGION_NO_WAIT_INVERTED = 0x8E1A,
QUERY_BY_REGION_WAIT_INVERTED = 0x8E19,
QUERY_NO_WAIT_INVERTED = 0x8E18,
QUERY_TARGET = 0x82EA,
QUERY_WAIT_INVERTED = 0x8E17,
RESET_NOTIFICATION_STRATEGY = 0x8256,
TEXTURE_TARGET = 0x1006,
UNKNOWN_CONTEXT_RESET = 0x8255,
ZERO_TO_ONE = 0x935F,
};
extern GLuint64 (CODEGEN_FUNCPTR *GetImageHandleARB)(GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum format);
extern GLuint64 (CODEGEN_FUNCPTR *GetTextureHandleARB)(GLuint texture);
extern GLuint64 (CODEGEN_FUNCPTR *GetTextureSamplerHandleARB)(GLuint texture, GLuint sampler);
extern void (CODEGEN_FUNCPTR *GetVertexAttribLui64vARB)(GLuint index, GLenum pname, GLuint64EXT * params);
extern GLboolean (CODEGEN_FUNCPTR *IsImageHandleResidentARB)(GLuint64 handle);
extern GLboolean (CODEGEN_FUNCPTR *IsTextureHandleResidentARB)(GLuint64 handle);
extern void (CODEGEN_FUNCPTR *MakeImageHandleNonResidentARB)(GLuint64 handle);
extern void (CODEGEN_FUNCPTR *MakeImageHandleResidentARB)(GLuint64 handle, GLenum access);
extern void (CODEGEN_FUNCPTR *MakeTextureHandleNonResidentARB)(GLuint64 handle);
extern void (CODEGEN_FUNCPTR *MakeTextureHandleResidentARB)(GLuint64 handle);
extern void (CODEGEN_FUNCPTR *ProgramUniformHandleui64ARB)(GLuint program, GLint location, GLuint64 value);
extern void (CODEGEN_FUNCPTR *ProgramUniformHandleui64vARB)(GLuint program, GLint location, GLsizei count, const GLuint64 * values);
extern void (CODEGEN_FUNCPTR *UniformHandleui64ARB)(GLint location, GLuint64 value);
extern void (CODEGEN_FUNCPTR *UniformHandleui64vARB)(GLint location, GLsizei count, const GLuint64 * value);
extern void (CODEGEN_FUNCPTR *VertexAttribL1ui64ARB)(GLuint index, GLuint64EXT x);
extern void (CODEGEN_FUNCPTR *VertexAttribL1ui64vARB)(GLuint index, const GLuint64EXT * v);
extern void (CODEGEN_FUNCPTR *BlendFunc)(GLenum sfactor, GLenum dfactor);
extern void (CODEGEN_FUNCPTR *Clear)(GLbitfield mask);
extern void (CODEGEN_FUNCPTR *ClearColor)(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha);
extern void (CODEGEN_FUNCPTR *ClearDepth)(GLdouble depth);
extern void (CODEGEN_FUNCPTR *ClearStencil)(GLint s);
extern void (CODEGEN_FUNCPTR *ColorMask)(GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha);
extern void (CODEGEN_FUNCPTR *CullFace)(GLenum mode);
extern void (CODEGEN_FUNCPTR *DepthFunc)(GLenum func);
extern void (CODEGEN_FUNCPTR *DepthMask)(GLboolean flag);
extern void (CODEGEN_FUNCPTR *DepthRange)(GLdouble ren_near, GLdouble ren_far);
extern void (CODEGEN_FUNCPTR *Disable)(GLenum cap);
extern void (CODEGEN_FUNCPTR *DrawBuffer)(GLenum buf);
extern void (CODEGEN_FUNCPTR *Enable)(GLenum cap);
extern void (CODEGEN_FUNCPTR *Finish)(void);
extern void (CODEGEN_FUNCPTR *Flush)(void);
extern void (CODEGEN_FUNCPTR *FrontFace)(GLenum mode);
extern void (CODEGEN_FUNCPTR *GetBooleanv)(GLenum pname, GLboolean * data);
extern void (CODEGEN_FUNCPTR *GetDoublev)(GLenum pname, GLdouble * data);
extern GLenum (CODEGEN_FUNCPTR *GetError)(void);
extern void (CODEGEN_FUNCPTR *GetFloatv)(GLenum pname, GLfloat * data);
extern void (CODEGEN_FUNCPTR *GetIntegerv)(GLenum pname, GLint * data);
extern const GLubyte * (CODEGEN_FUNCPTR *GetString)(GLenum name);
extern void (CODEGEN_FUNCPTR *GetTexImage)(GLenum target, GLint level, GLenum format, GLenum type, void * pixels);
extern void (CODEGEN_FUNCPTR *GetTexLevelParameterfv)(GLenum target, GLint level, GLenum pname, GLfloat * params);
extern void (CODEGEN_FUNCPTR *GetTexLevelParameteriv)(GLenum target, GLint level, GLenum pname, GLint * params);
extern void (CODEGEN_FUNCPTR *GetTexParameterfv)(GLenum target, GLenum pname, GLfloat * params);
extern void (CODEGEN_FUNCPTR *GetTexParameteriv)(GLenum target, GLenum pname, GLint * params);
extern void (CODEGEN_FUNCPTR *Hint)(GLenum target, GLenum mode);
extern GLboolean (CODEGEN_FUNCPTR *IsEnabled)(GLenum cap);
extern void (CODEGEN_FUNCPTR *LineWidth)(GLfloat width);
extern void (CODEGEN_FUNCPTR *LogicOp)(GLenum opcode);
extern void (CODEGEN_FUNCPTR *PixelStoref)(GLenum pname, GLfloat param);
extern void (CODEGEN_FUNCPTR *PixelStorei)(GLenum pname, GLint param);
extern void (CODEGEN_FUNCPTR *PointSize)(GLfloat size);
extern void (CODEGEN_FUNCPTR *PolygonMode)(GLenum face, GLenum mode);
extern void (CODEGEN_FUNCPTR *ReadBuffer)(GLenum src);
extern void (CODEGEN_FUNCPTR *ReadPixels)(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, void * pixels);
extern void (CODEGEN_FUNCPTR *Scissor)(GLint x, GLint y, GLsizei width, GLsizei height);
extern void (CODEGEN_FUNCPTR *StencilFunc)(GLenum func, GLint ref, GLuint mask);
extern void (CODEGEN_FUNCPTR *StencilMask)(GLuint mask);
extern void (CODEGEN_FUNCPTR *StencilOp)(GLenum fail, GLenum zfail, GLenum zpass);
extern void (CODEGEN_FUNCPTR *TexImage1D)(GLenum target, GLint level, GLint internalformat, GLsizei width, GLint border, GLenum format, GLenum type, const void * pixels);
extern void (CODEGEN_FUNCPTR *TexImage2D)(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void * pixels);
extern void (CODEGEN_FUNCPTR *TexParameterf)(GLenum target, GLenum pname, GLfloat param);
extern void (CODEGEN_FUNCPTR *TexParameterfv)(GLenum target, GLenum pname, const GLfloat * params);
extern void (CODEGEN_FUNCPTR *TexParameteri)(GLenum target, GLenum pname, GLint param);
extern void (CODEGEN_FUNCPTR *TexParameteriv)(GLenum target, GLenum pname, const GLint * params);
extern void (CODEGEN_FUNCPTR *Viewport)(GLint x, GLint y, GLsizei width, GLsizei height);
extern void (CODEGEN_FUNCPTR *BindTexture)(GLenum target, GLuint texture);
extern void (CODEGEN_FUNCPTR *CopyTexImage1D)(GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLint border);
extern void (CODEGEN_FUNCPTR *CopyTexImage2D)(GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border);
extern void (CODEGEN_FUNCPTR *CopyTexSubImage1D)(GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width);
extern void (CODEGEN_FUNCPTR *CopyTexSubImage2D)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height);
extern void (CODEGEN_FUNCPTR *DeleteTextures)(GLsizei n, const GLuint * textures);
extern void (CODEGEN_FUNCPTR *DrawArrays)(GLenum mode, GLint first, GLsizei count);
extern void (CODEGEN_FUNCPTR *DrawElements)(GLenum mode, GLsizei count, GLenum type, const void * indices);
extern void (CODEGEN_FUNCPTR *GenTextures)(GLsizei n, GLuint * textures);
extern void (CODEGEN_FUNCPTR *GetPointerv)(GLenum pname, void ** params);
extern GLboolean (CODEGEN_FUNCPTR *IsTexture)(GLuint texture);
extern void (CODEGEN_FUNCPTR *PolygonOffset)(GLfloat factor, GLfloat units);
extern void (CODEGEN_FUNCPTR *TexSubImage1D)(GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const void * pixels);
extern void (CODEGEN_FUNCPTR *TexSubImage2D)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void * pixels);
extern void (CODEGEN_FUNCPTR *CopyTexSubImage3D)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height);
extern void (CODEGEN_FUNCPTR *DrawRangeElements)(GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void * indices);
extern void (CODEGEN_FUNCPTR *TexImage3D)(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void * pixels);
extern void (CODEGEN_FUNCPTR *TexSubImage3D)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void * pixels);
extern void (CODEGEN_FUNCPTR *ActiveTexture)(GLenum texture);
extern void (CODEGEN_FUNCPTR *CompressedTexImage1D)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const void * data);
extern void (CODEGEN_FUNCPTR *CompressedTexImage2D)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void * data);
extern void (CODEGEN_FUNCPTR *CompressedTexImage3D)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void * data);
extern void (CODEGEN_FUNCPTR *CompressedTexSubImage1D)(GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const void * data);
extern void (CODEGEN_FUNCPTR *CompressedTexSubImage2D)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void * data);
extern void (CODEGEN_FUNCPTR *CompressedTexSubImage3D)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void * data);
extern void (CODEGEN_FUNCPTR *GetCompressedTexImage)(GLenum target, GLint level, void * img);
extern void (CODEGEN_FUNCPTR *SampleCoverage)(GLfloat value, GLboolean invert);
extern void (CODEGEN_FUNCPTR *BlendColor)(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha);
extern void (CODEGEN_FUNCPTR *BlendEquation)(GLenum mode);
extern void (CODEGEN_FUNCPTR *BlendFuncSeparate)(GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha);
extern void (CODEGEN_FUNCPTR *MultiDrawArrays)(GLenum mode, const GLint * first, const GLsizei * count, GLsizei drawcount);
extern void (CODEGEN_FUNCPTR *MultiDrawElements)(GLenum mode, const GLsizei * count, GLenum type, const void *const* indices, GLsizei drawcount);
extern void (CODEGEN_FUNCPTR *PointParameterf)(GLenum pname, GLfloat param);
extern void (CODEGEN_FUNCPTR *PointParameterfv)(GLenum pname, const GLfloat * params);
extern void (CODEGEN_FUNCPTR *PointParameteri)(GLenum pname, GLint param);
extern void (CODEGEN_FUNCPTR *PointParameteriv)(GLenum pname, const GLint * params);
extern void (CODEGEN_FUNCPTR *BeginQuery)(GLenum target, GLuint id);
extern void (CODEGEN_FUNCPTR *BindBuffer)(GLenum target, GLuint buffer);
extern void (CODEGEN_FUNCPTR *BufferData)(GLenum target, GLsizeiptr size, const void * data, GLenum usage);
extern void (CODEGEN_FUNCPTR *BufferSubData)(GLenum target, GLintptr offset, GLsizeiptr size, const void * data);
extern void (CODEGEN_FUNCPTR *DeleteBuffers)(GLsizei n, const GLuint * buffers);
extern void (CODEGEN_FUNCPTR *DeleteQueries)(GLsizei n, const GLuint * ids);
extern void (CODEGEN_FUNCPTR *EndQuery)(GLenum target);
extern void (CODEGEN_FUNCPTR *GenBuffers)(GLsizei n, GLuint * buffers);
extern void (CODEGEN_FUNCPTR *GenQueries)(GLsizei n, GLuint * ids);
extern void (CODEGEN_FUNCPTR *GetBufferParameteriv)(GLenum target, GLenum pname, GLint * params);
extern void (CODEGEN_FUNCPTR *GetBufferPointerv)(GLenum target, GLenum pname, void ** params);
extern void (CODEGEN_FUNCPTR *GetBufferSubData)(GLenum target, GLintptr offset, GLsizeiptr size, void * data);
extern void (CODEGEN_FUNCPTR *GetQueryObjectiv)(GLuint id, GLenum pname, GLint * params);
extern void (CODEGEN_FUNCPTR *GetQueryObjectuiv)(GLuint id, GLenum pname, GLuint * params);
extern void (CODEGEN_FUNCPTR *GetQueryiv)(GLenum target, GLenum pname, GLint * params);
extern GLboolean (CODEGEN_FUNCPTR *IsBuffer)(GLuint buffer);
extern GLboolean (CODEGEN_FUNCPTR *IsQuery)(GLuint id);
extern void * (CODEGEN_FUNCPTR *MapBuffer)(GLenum target, GLenum access);
extern GLboolean (CODEGEN_FUNCPTR *UnmapBuffer)(GLenum target);
extern void (CODEGEN_FUNCPTR *AttachShader)(GLuint program, GLuint shader);
extern void (CODEGEN_FUNCPTR *BindAttribLocation)(GLuint program, GLuint index, const GLchar * name);
extern void (CODEGEN_FUNCPTR *BlendEquationSeparate)(GLenum modeRGB, GLenum modeAlpha);
extern void (CODEGEN_FUNCPTR *CompileShader)(GLuint shader);
extern GLuint (CODEGEN_FUNCPTR *CreateProgram)(void);
extern GLuint (CODEGEN_FUNCPTR *CreateShader)(GLenum type);
extern void (CODEGEN_FUNCPTR *DeleteProgram)(GLuint program);
extern void (CODEGEN_FUNCPTR *DeleteShader)(GLuint shader);
extern void (CODEGEN_FUNCPTR *DetachShader)(GLuint program, GLuint shader);
extern void (CODEGEN_FUNCPTR *DisableVertexAttribArray)(GLuint index);
extern void (CODEGEN_FUNCPTR *DrawBuffers)(GLsizei n, const GLenum * bufs);
extern void (CODEGEN_FUNCPTR *EnableVertexAttribArray)(GLuint index);
extern void (CODEGEN_FUNCPTR *GetActiveAttrib)(GLuint program, GLuint index, GLsizei bufSize, GLsizei * length, GLint * size, GLenum * type, GLchar * name);
extern void (CODEGEN_FUNCPTR *GetActiveUniform)(GLuint program, GLuint index, GLsizei bufSize, GLsizei * length, GLint * size, GLenum * type, GLchar * name);
extern void (CODEGEN_FUNCPTR *GetAttachedShaders)(GLuint program, GLsizei maxCount, GLsizei * count, GLuint * shaders);
extern GLint (CODEGEN_FUNCPTR *GetAttribLocation)(GLuint program, const GLchar * name);
extern void (CODEGEN_FUNCPTR *GetProgramInfoLog)(GLuint program, GLsizei bufSize, GLsizei * length, GLchar * infoLog);
extern void (CODEGEN_FUNCPTR *GetProgramiv)(GLuint program, GLenum pname, GLint * params);
extern void (CODEGEN_FUNCPTR *GetShaderInfoLog)(GLuint shader, GLsizei bufSize, GLsizei * length, GLchar * infoLog);
extern void (CODEGEN_FUNCPTR *GetShaderSource)(GLuint shader, GLsizei bufSize, GLsizei * length, GLchar * source);
extern void (CODEGEN_FUNCPTR *GetShaderiv)(GLuint shader, GLenum pname, GLint * params);
extern GLint (CODEGEN_FUNCPTR *GetUniformLocation)(GLuint program, const GLchar * name);
extern void (CODEGEN_FUNCPTR *GetUniformfv)(GLuint program, GLint location, GLfloat * params);
extern void (CODEGEN_FUNCPTR *GetUniformiv)(GLuint program, GLint location, GLint * params);
extern void (CODEGEN_FUNCPTR *GetVertexAttribPointerv)(GLuint index, GLenum pname, void ** pointer);
extern void (CODEGEN_FUNCPTR *GetVertexAttribdv)(GLuint index, GLenum pname, GLdouble * params);
extern void (CODEGEN_FUNCPTR *GetVertexAttribfv)(GLuint index, GLenum pname, GLfloat * params);
extern void (CODEGEN_FUNCPTR *GetVertexAttribiv)(GLuint index, GLenum pname, GLint * params);
extern GLboolean (CODEGEN_FUNCPTR *IsProgram)(GLuint program);
extern GLboolean (CODEGEN_FUNCPTR *IsShader)(GLuint shader);
extern void (CODEGEN_FUNCPTR *LinkProgram)(GLuint program);
extern void (CODEGEN_FUNCPTR *ShaderSource)(GLuint shader, GLsizei count, const GLchar *const* string, const GLint * length);
extern void (CODEGEN_FUNCPTR *StencilFuncSeparate)(GLenum face, GLenum func, GLint ref, GLuint mask);
extern void (CODEGEN_FUNCPTR *StencilMaskSeparate)(GLenum face, GLuint mask);
extern void (CODEGEN_FUNCPTR *StencilOpSeparate)(GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass);
extern void (CODEGEN_FUNCPTR *Uniform1f)(GLint location, GLfloat v0);
extern void (CODEGEN_FUNCPTR *Uniform1fv)(GLint location, GLsizei count, const GLfloat * value);
extern void (CODEGEN_FUNCPTR *Uniform1i)(GLint location, GLint v0);
extern void (CODEGEN_FUNCPTR *Uniform1iv)(GLint location, GLsizei count, const GLint * value);
extern void (CODEGEN_FUNCPTR *Uniform2f)(GLint location, GLfloat v0, GLfloat v1);
extern void (CODEGEN_FUNCPTR *Uniform2fv)(GLint location, GLsizei count, const GLfloat * value);
extern void (CODEGEN_FUNCPTR *Uniform2i)(GLint location, GLint v0, GLint v1);
extern void (CODEGEN_FUNCPTR *Uniform2iv)(GLint location, GLsizei count, const GLint * value);
extern void (CODEGEN_FUNCPTR *Uniform3f)(GLint location, GLfloat v0, GLfloat v1, GLfloat v2);
extern void (CODEGEN_FUNCPTR *Uniform3fv)(GLint location, GLsizei count, const GLfloat * value);
extern void (CODEGEN_FUNCPTR *Uniform3i)(GLint location, GLint v0, GLint v1, GLint v2);
extern void (CODEGEN_FUNCPTR *Uniform3iv)(GLint location, GLsizei count, const GLint * value);
extern void (CODEGEN_FUNCPTR *Uniform4f)(GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3);
extern void (CODEGEN_FUNCPTR *Uniform4fv)(GLint location, GLsizei count, const GLfloat * value);
extern void (CODEGEN_FUNCPTR *Uniform4i)(GLint location, GLint v0, GLint v1, GLint v2, GLint v3);
extern void (CODEGEN_FUNCPTR *Uniform4iv)(GLint location, GLsizei count, const GLint * value);
extern void (CODEGEN_FUNCPTR *UniformMatrix2fv)(GLint location, GLsizei count, GLboolean transpose, const GLfloat * value);
extern void (CODEGEN_FUNCPTR *UniformMatrix3fv)(GLint location, GLsizei count, GLboolean transpose, const GLfloat * value);
extern void (CODEGEN_FUNCPTR *UniformMatrix4fv)(GLint location, GLsizei count, GLboolean transpose, const GLfloat * value);
extern void (CODEGEN_FUNCPTR *UseProgram)(GLuint program);
extern void (CODEGEN_FUNCPTR *ValidateProgram)(GLuint program);
extern void (CODEGEN_FUNCPTR *VertexAttrib1d)(GLuint index, GLdouble x);
extern void (CODEGEN_FUNCPTR *VertexAttrib1dv)(GLuint index, const GLdouble * v);
extern void (CODEGEN_FUNCPTR *VertexAttrib1f)(GLuint index, GLfloat x);
extern void (CODEGEN_FUNCPTR *VertexAttrib1fv)(GLuint index, const GLfloat * v);
extern void (CODEGEN_FUNCPTR *VertexAttrib1s)(GLuint index, GLshort x);
extern void (CODEGEN_FUNCPTR *VertexAttrib1sv)(GLuint index, const GLshort * v);
extern void (CODEGEN_FUNCPTR *VertexAttrib2d)(GLuint index, GLdouble x, GLdouble y);
extern void (CODEGEN_FUNCPTR *VertexAttrib2dv)(GLuint index, const GLdouble * v);
extern void (CODEGEN_FUNCPTR *VertexAttrib2f)(GLuint index, GLfloat x, GLfloat y);
extern void (CODEGEN_FUNCPTR *VertexAttrib2fv)(GLuint index, const GLfloat * v);
extern void (CODEGEN_FUNCPTR *VertexAttrib2s)(GLuint index, GLshort x, GLshort y);
extern void (CODEGEN_FUNCPTR *VertexAttrib2sv)(GLuint index, const GLshort * v);
extern void (CODEGEN_FUNCPTR *VertexAttrib3d)(GLuint index, GLdouble x, GLdouble y, GLdouble z);
extern void (CODEGEN_FUNCPTR *VertexAttrib3dv)(GLuint index, const GLdouble * v);
extern void (CODEGEN_FUNCPTR *VertexAttrib3f)(GLuint index, GLfloat x, GLfloat y, GLfloat z);
extern void (CODEGEN_FUNCPTR *VertexAttrib3fv)(GLuint index, const GLfloat * v);
extern void (CODEGEN_FUNCPTR *VertexAttrib3s)(GLuint index, GLshort x, GLshort y, GLshort z);
extern void (CODEGEN_FUNCPTR *VertexAttrib3sv)(GLuint index, const GLshort * v);
extern void (CODEGEN_FUNCPTR *VertexAttrib4Nbv)(GLuint index, const GLbyte * v);
extern void (CODEGEN_FUNCPTR *VertexAttrib4Niv)(GLuint index, const GLint * v);
extern void (CODEGEN_FUNCPTR *VertexAttrib4Nsv)(GLuint index, const GLshort * v);
extern void (CODEGEN_FUNCPTR *VertexAttrib4Nub)(GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w);
extern void (CODEGEN_FUNCPTR *VertexAttrib4Nubv)(GLuint index, const GLubyte * v);
extern void (CODEGEN_FUNCPTR *VertexAttrib4Nuiv)(GLuint index, const GLuint * v);
extern void (CODEGEN_FUNCPTR *VertexAttrib4Nusv)(GLuint index, const GLushort * v);
extern void (CODEGEN_FUNCPTR *VertexAttrib4bv)(GLuint index, const GLbyte * v);
extern void (CODEGEN_FUNCPTR *VertexAttrib4d)(GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w);
extern void (CODEGEN_FUNCPTR *VertexAttrib4dv)(GLuint index, const GLdouble * v);
extern void (CODEGEN_FUNCPTR *VertexAttrib4f)(GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
extern void (CODEGEN_FUNCPTR *VertexAttrib4fv)(GLuint index, const GLfloat * v);
extern void (CODEGEN_FUNCPTR *VertexAttrib4iv)(GLuint index, const GLint * v);
extern void (CODEGEN_FUNCPTR *VertexAttrib4s)(GLuint index, GLshort x, GLshort y, GLshort z, GLshort w);
extern void (CODEGEN_FUNCPTR *VertexAttrib4sv)(GLuint index, const GLshort * v);
extern void (CODEGEN_FUNCPTR *VertexAttrib4ubv)(GLuint index, const GLubyte * v);
extern void (CODEGEN_FUNCPTR *VertexAttrib4uiv)(GLuint index, const GLuint * v);
extern void (CODEGEN_FUNCPTR *VertexAttrib4usv)(GLuint index, const GLushort * v);
extern void (CODEGEN_FUNCPTR *VertexAttribPointer)(GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void * pointer);
extern void (CODEGEN_FUNCPTR *UniformMatrix2x3fv)(GLint location, GLsizei count, GLboolean transpose, const GLfloat * value);
extern void (CODEGEN_FUNCPTR *UniformMatrix2x4fv)(GLint location, GLsizei count, GLboolean transpose, const GLfloat * value);
extern void (CODEGEN_FUNCPTR *UniformMatrix3x2fv)(GLint location, GLsizei count, GLboolean transpose, const GLfloat * value);
extern void (CODEGEN_FUNCPTR *UniformMatrix3x4fv)(GLint location, GLsizei count, GLboolean transpose, const GLfloat * value);
extern void (CODEGEN_FUNCPTR *UniformMatrix4x2fv)(GLint location, GLsizei count, GLboolean transpose, const GLfloat * value);
extern void (CODEGEN_FUNCPTR *UniformMatrix4x3fv)(GLint location, GLsizei count, GLboolean transpose, const GLfloat * value);
extern void (CODEGEN_FUNCPTR *BeginConditionalRender)(GLuint id, GLenum mode);
extern void (CODEGEN_FUNCPTR *BeginTransformFeedback)(GLenum primitiveMode);
extern void (CODEGEN_FUNCPTR *BindBufferBase)(GLenum target, GLuint index, GLuint buffer);
extern void (CODEGEN_FUNCPTR *BindBufferRange)(GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size);
extern void (CODEGEN_FUNCPTR *BindFragDataLocation)(GLuint program, GLuint color, const GLchar * name);
extern void (CODEGEN_FUNCPTR *BindFramebuffer)(GLenum target, GLuint framebuffer);
extern void (CODEGEN_FUNCPTR *BindRenderbuffer)(GLenum target, GLuint renderbuffer);
extern void (CODEGEN_FUNCPTR *BindVertexArray)(GLuint ren_array);
extern void (CODEGEN_FUNCPTR *BlitFramebuffer)(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter);
extern GLenum (CODEGEN_FUNCPTR *CheckFramebufferStatus)(GLenum target);
extern void (CODEGEN_FUNCPTR *ClampColor)(GLenum target, GLenum clamp);
extern void (CODEGEN_FUNCPTR *ClearBufferfi)(GLenum buffer, GLint drawbuffer, GLfloat depth, GLint stencil);
extern void (CODEGEN_FUNCPTR *ClearBufferfv)(GLenum buffer, GLint drawbuffer, const GLfloat * value);
extern void (CODEGEN_FUNCPTR *ClearBufferiv)(GLenum buffer, GLint drawbuffer, const GLint * value);
extern void (CODEGEN_FUNCPTR *ClearBufferuiv)(GLenum buffer, GLint drawbuffer, const GLuint * value);
extern void (CODEGEN_FUNCPTR *ColorMaski)(GLuint index, GLboolean r, GLboolean g, GLboolean b, GLboolean a);
extern void (CODEGEN_FUNCPTR *DeleteFramebuffers)(GLsizei n, const GLuint * framebuffers);
extern void (CODEGEN_FUNCPTR *DeleteRenderbuffers)(GLsizei n, const GLuint * renderbuffers);
extern void (CODEGEN_FUNCPTR *DeleteVertexArrays)(GLsizei n, const GLuint * arrays);
extern void (CODEGEN_FUNCPTR *Disablei)(GLenum target, GLuint index);
extern void (CODEGEN_FUNCPTR *Enablei)(GLenum target, GLuint index);
extern void (CODEGEN_FUNCPTR *EndConditionalRender)(void);
extern void (CODEGEN_FUNCPTR *EndTransformFeedback)(void);
extern void (CODEGEN_FUNCPTR *FlushMappedBufferRange)(GLenum target, GLintptr offset, GLsizeiptr length);
extern void (CODEGEN_FUNCPTR *FramebufferRenderbuffer)(GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer);
extern void (CODEGEN_FUNCPTR *FramebufferTexture1D)(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level);
extern void (CODEGEN_FUNCPTR *FramebufferTexture2D)(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level);
extern void (CODEGEN_FUNCPTR *FramebufferTexture3D)(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint zoffset);
extern void (CODEGEN_FUNCPTR *FramebufferTextureLayer)(GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer);
extern void (CODEGEN_FUNCPTR *GenFramebuffers)(GLsizei n, GLuint * framebuffers);
extern void (CODEGEN_FUNCPTR *GenRenderbuffers)(GLsizei n, GLuint * renderbuffers);
extern void (CODEGEN_FUNCPTR *GenVertexArrays)(GLsizei n, GLuint * arrays);
extern void (CODEGEN_FUNCPTR *GenerateMipmap)(GLenum target);
extern void (CODEGEN_FUNCPTR *GetBooleani_v)(GLenum target, GLuint index, GLboolean * data);
extern GLint (CODEGEN_FUNCPTR *GetFragDataLocation)(GLuint program, const GLchar * name);
extern void (CODEGEN_FUNCPTR *GetFramebufferAttachmentParameteriv)(GLenum target, GLenum attachment, GLenum pname, GLint * params);
extern void (CODEGEN_FUNCPTR *GetIntegeri_v)(GLenum target, GLuint index, GLint * data);
extern void (CODEGEN_FUNCPTR *GetRenderbufferParameteriv)(GLenum target, GLenum pname, GLint * params);
extern const GLubyte * (CODEGEN_FUNCPTR *GetStringi)(GLenum name, GLuint index);
extern void (CODEGEN_FUNCPTR *GetTexParameterIiv)(GLenum target, GLenum pname, GLint * params);
extern void (CODEGEN_FUNCPTR *GetTexParameterIuiv)(GLenum target, GLenum pname, GLuint * params);
extern void (CODEGEN_FUNCPTR *GetTransformFeedbackVarying)(GLuint program, GLuint index, GLsizei bufSize, GLsizei * length, GLsizei * size, GLenum * type, GLchar * name);
extern void (CODEGEN_FUNCPTR *GetUniformuiv)(GLuint program, GLint location, GLuint * params);
extern void (CODEGEN_FUNCPTR *GetVertexAttribIiv)(GLuint index, GLenum pname, GLint * params);
extern void (CODEGEN_FUNCPTR *GetVertexAttribIuiv)(GLuint index, GLenum pname, GLuint * params);
extern GLboolean (CODEGEN_FUNCPTR *IsEnabledi)(GLenum target, GLuint index);
extern GLboolean (CODEGEN_FUNCPTR *IsFramebuffer)(GLuint framebuffer);
extern GLboolean (CODEGEN_FUNCPTR *IsRenderbuffer)(GLuint renderbuffer);
extern GLboolean (CODEGEN_FUNCPTR *IsVertexArray)(GLuint ren_array);
extern void * (CODEGEN_FUNCPTR *MapBufferRange)(GLenum target, GLintptr offset, GLsizeiptr length, GLbitfield access);
extern void (CODEGEN_FUNCPTR *RenderbufferStorage)(GLenum target, GLenum internalformat, GLsizei width, GLsizei height);
extern void (CODEGEN_FUNCPTR *RenderbufferStorageMultisample)(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height);
extern void (CODEGEN_FUNCPTR *TexParameterIiv)(GLenum target, GLenum pname, const GLint * params);
extern void (CODEGEN_FUNCPTR *TexParameterIuiv)(GLenum target, GLenum pname, const GLuint * params);
extern void (CODEGEN_FUNCPTR *TransformFeedbackVaryings)(GLuint program, GLsizei count, const GLchar *const* varyings, GLenum bufferMode);
extern void (CODEGEN_FUNCPTR *Uniform1ui)(GLint location, GLuint v0);
extern void (CODEGEN_FUNCPTR *Uniform1uiv)(GLint location, GLsizei count, const GLuint * value);
extern void (CODEGEN_FUNCPTR *Uniform2ui)(GLint location, GLuint v0, GLuint v1);
extern void (CODEGEN_FUNCPTR *Uniform2uiv)(GLint location, GLsizei count, const GLuint * value);
extern void (CODEGEN_FUNCPTR *Uniform3ui)(GLint location, GLuint v0, GLuint v1, GLuint v2);
extern void (CODEGEN_FUNCPTR *Uniform3uiv)(GLint location, GLsizei count, const GLuint * value);
extern void (CODEGEN_FUNCPTR *Uniform4ui)(GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3);
extern void (CODEGEN_FUNCPTR *Uniform4uiv)(GLint location, GLsizei count, const GLuint * value);
extern void (CODEGEN_FUNCPTR *VertexAttribI1i)(GLuint index, GLint x);
extern void (CODEGEN_FUNCPTR *VertexAttribI1iv)(GLuint index, const GLint * v);
extern void (CODEGEN_FUNCPTR *VertexAttribI1ui)(GLuint index, GLuint x);
extern void (CODEGEN_FUNCPTR *VertexAttribI1uiv)(GLuint index, const GLuint * v);
extern void (CODEGEN_FUNCPTR *VertexAttribI2i)(GLuint index, GLint x, GLint y);
extern void (CODEGEN_FUNCPTR *VertexAttribI2iv)(GLuint index, const GLint * v);
extern void (CODEGEN_FUNCPTR *VertexAttribI2ui)(GLuint index, GLuint x, GLuint y);
extern void (CODEGEN_FUNCPTR *VertexAttribI2uiv)(GLuint index, const GLuint * v);
extern void (CODEGEN_FUNCPTR *VertexAttribI3i)(GLuint index, GLint x, GLint y, GLint z);
extern void (CODEGEN_FUNCPTR *VertexAttribI3iv)(GLuint index, const GLint * v);
extern void (CODEGEN_FUNCPTR *VertexAttribI3ui)(GLuint index, GLuint x, GLuint y, GLuint z);
extern void (CODEGEN_FUNCPTR *VertexAttribI3uiv)(GLuint index, const GLuint * v);
extern void (CODEGEN_FUNCPTR *VertexAttribI4bv)(GLuint index, const GLbyte * v);
extern void (CODEGEN_FUNCPTR *VertexAttribI4i)(GLuint index, GLint x, GLint y, GLint z, GLint w);
extern void (CODEGEN_FUNCPTR *VertexAttribI4iv)(GLuint index, const GLint * v);
extern void (CODEGEN_FUNCPTR *VertexAttribI4sv)(GLuint index, const GLshort * v);
extern void (CODEGEN_FUNCPTR *VertexAttribI4ubv)(GLuint index, const GLubyte * v);
extern void (CODEGEN_FUNCPTR *VertexAttribI4ui)(GLuint index, GLuint x, GLuint y, GLuint z, GLuint w);
extern void (CODEGEN_FUNCPTR *VertexAttribI4uiv)(GLuint index, const GLuint * v);
extern void (CODEGEN_FUNCPTR *VertexAttribI4usv)(GLuint index, const GLushort * v);
extern void (CODEGEN_FUNCPTR *VertexAttribIPointer)(GLuint index, GLint size, GLenum type, GLsizei stride, const void * pointer);
extern void (CODEGEN_FUNCPTR *CopyBufferSubData)(GLenum readTarget, GLenum writeTarget, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size);
extern void (CODEGEN_FUNCPTR *DrawArraysInstanced)(GLenum mode, GLint first, GLsizei count, GLsizei instancecount);
extern void (CODEGEN_FUNCPTR *DrawElementsInstanced)(GLenum mode, GLsizei count, GLenum type, const void * indices, GLsizei instancecount);
extern void (CODEGEN_FUNCPTR *GetActiveUniformBlockName)(GLuint program, GLuint uniformBlockIndex, GLsizei bufSize, GLsizei * length, GLchar * uniformBlockName);
extern void (CODEGEN_FUNCPTR *GetActiveUniformBlockiv)(GLuint program, GLuint uniformBlockIndex, GLenum pname, GLint * params);
extern void (CODEGEN_FUNCPTR *GetActiveUniformName)(GLuint program, GLuint uniformIndex, GLsizei bufSize, GLsizei * length, GLchar * uniformName);
extern void (CODEGEN_FUNCPTR *GetActiveUniformsiv)(GLuint program, GLsizei uniformCount, const GLuint * uniformIndices, GLenum pname, GLint * params);
extern GLuint (CODEGEN_FUNCPTR *GetUniformBlockIndex)(GLuint program, const GLchar * uniformBlockName);
extern void (CODEGEN_FUNCPTR *GetUniformIndices)(GLuint program, GLsizei uniformCount, const GLchar *const* uniformNames, GLuint * uniformIndices);
extern void (CODEGEN_FUNCPTR *PrimitiveRestartIndex)(GLuint index);
extern void (CODEGEN_FUNCPTR *TexBuffer)(GLenum target, GLenum internalformat, GLuint buffer);
extern void (CODEGEN_FUNCPTR *UniformBlockBinding)(GLuint program, GLuint uniformBlockIndex, GLuint uniformBlockBinding);
extern GLenum (CODEGEN_FUNCPTR *ClientWaitSync)(GLsync sync, GLbitfield flags, GLuint64 timeout);
extern void (CODEGEN_FUNCPTR *DeleteSync)(GLsync sync);
extern void (CODEGEN_FUNCPTR *DrawElementsBaseVertex)(GLenum mode, GLsizei count, GLenum type, const void * indices, GLint basevertex);
extern void (CODEGEN_FUNCPTR *DrawElementsInstancedBaseVertex)(GLenum mode, GLsizei count, GLenum type, const void * indices, GLsizei instancecount, GLint basevertex);
extern void (CODEGEN_FUNCPTR *DrawRangeElementsBaseVertex)(GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void * indices, GLint basevertex);
extern GLsync (CODEGEN_FUNCPTR *FenceSync)(GLenum condition, GLbitfield flags);
extern void (CODEGEN_FUNCPTR *FramebufferTexture)(GLenum target, GLenum attachment, GLuint texture, GLint level);
extern void (CODEGEN_FUNCPTR *GetBufferParameteri64v)(GLenum target, GLenum pname, GLint64 * params);
extern void (CODEGEN_FUNCPTR *GetInteger64i_v)(GLenum target, GLuint index, GLint64 * data);
extern void (CODEGEN_FUNCPTR *GetInteger64v)(GLenum pname, GLint64 * data);
extern void (CODEGEN_FUNCPTR *GetMultisamplefv)(GLenum pname, GLuint index, GLfloat * val);
extern void (CODEGEN_FUNCPTR *GetSynciv)(GLsync sync, GLenum pname, GLsizei bufSize, GLsizei * length, GLint * values);
extern GLboolean (CODEGEN_FUNCPTR *IsSync)(GLsync sync);
extern void (CODEGEN_FUNCPTR *MultiDrawElementsBaseVertex)(GLenum mode, const GLsizei * count, GLenum type, const void *const* indices, GLsizei drawcount, const GLint * basevertex);
extern void (CODEGEN_FUNCPTR *ProvokingVertex)(GLenum mode);
extern void (CODEGEN_FUNCPTR *SampleMaski)(GLuint maskNumber, GLbitfield mask);
extern void (CODEGEN_FUNCPTR *TexImage2DMultisample)(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations);
extern void (CODEGEN_FUNCPTR *TexImage3DMultisample)(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations);
extern void (CODEGEN_FUNCPTR *WaitSync)(GLsync sync, GLbitfield flags, GLuint64 timeout);
extern void (CODEGEN_FUNCPTR *BindFragDataLocationIndexed)(GLuint program, GLuint colorNumber, GLuint index, const GLchar * name);
extern void (CODEGEN_FUNCPTR *BindSampler)(GLuint unit, GLuint sampler);
extern void (CODEGEN_FUNCPTR *DeleteSamplers)(GLsizei count, const GLuint * samplers);
extern void (CODEGEN_FUNCPTR *GenSamplers)(GLsizei count, GLuint * samplers);
extern GLint (CODEGEN_FUNCPTR *GetFragDataIndex)(GLuint program, const GLchar * name);
extern void (CODEGEN_FUNCPTR *GetQueryObjecti64v)(GLuint id, GLenum pname, GLint64 * params);
extern void (CODEGEN_FUNCPTR *GetQueryObjectui64v)(GLuint id, GLenum pname, GLuint64 * params);
extern void (CODEGEN_FUNCPTR *GetSamplerParameterIiv)(GLuint sampler, GLenum pname, GLint * params);
extern void (CODEGEN_FUNCPTR *GetSamplerParameterIuiv)(GLuint sampler, GLenum pname, GLuint * params);
extern void (CODEGEN_FUNCPTR *GetSamplerParameterfv)(GLuint sampler, GLenum pname, GLfloat * params);
extern void (CODEGEN_FUNCPTR *GetSamplerParameteriv)(GLuint sampler, GLenum pname, GLint * params);
extern GLboolean (CODEGEN_FUNCPTR *IsSampler)(GLuint sampler);
extern void (CODEGEN_FUNCPTR *QueryCounter)(GLuint id, GLenum target);
extern void (CODEGEN_FUNCPTR *SamplerParameterIiv)(GLuint sampler, GLenum pname, const GLint * param);
extern void (CODEGEN_FUNCPTR *SamplerParameterIuiv)(GLuint sampler, GLenum pname, const GLuint * param);
extern void (CODEGEN_FUNCPTR *SamplerParameterf)(GLuint sampler, GLenum pname, GLfloat param);
extern void (CODEGEN_FUNCPTR *SamplerParameterfv)(GLuint sampler, GLenum pname, const GLfloat * param);
extern void (CODEGEN_FUNCPTR *SamplerParameteri)(GLuint sampler, GLenum pname, GLint param);
extern void (CODEGEN_FUNCPTR *SamplerParameteriv)(GLuint sampler, GLenum pname, const GLint * param);
extern void (CODEGEN_FUNCPTR *VertexAttribDivisor)(GLuint index, GLuint divisor);
extern void (CODEGEN_FUNCPTR *VertexAttribP1ui)(GLuint index, GLenum type, GLboolean normalized, GLuint value);
extern void (CODEGEN_FUNCPTR *VertexAttribP1uiv)(GLuint index, GLenum type, GLboolean normalized, const GLuint * value);
extern void (CODEGEN_FUNCPTR *VertexAttribP2ui)(GLuint index, GLenum type, GLboolean normalized, GLuint value);
extern void (CODEGEN_FUNCPTR *VertexAttribP2uiv)(GLuint index, GLenum type, GLboolean normalized, const GLuint * value);
extern void (CODEGEN_FUNCPTR *VertexAttribP3ui)(GLuint index, GLenum type, GLboolean normalized, GLuint value);
extern void (CODEGEN_FUNCPTR *VertexAttribP3uiv)(GLuint index, GLenum type, GLboolean normalized, const GLuint * value);
extern void (CODEGEN_FUNCPTR *VertexAttribP4ui)(GLuint index, GLenum type, GLboolean normalized, GLuint value);
extern void (CODEGEN_FUNCPTR *VertexAttribP4uiv)(GLuint index, GLenum type, GLboolean normalized, const GLuint * value);
extern void (CODEGEN_FUNCPTR *BeginQueryIndexed)(GLenum target, GLuint index, GLuint id);
extern void (CODEGEN_FUNCPTR *BindTransformFeedback)(GLenum target, GLuint id);
extern void (CODEGEN_FUNCPTR *BlendEquationSeparatei)(GLuint buf, GLenum modeRGB, GLenum modeAlpha);
extern void (CODEGEN_FUNCPTR *BlendEquationi)(GLuint buf, GLenum mode);
extern void (CODEGEN_FUNCPTR *BlendFuncSeparatei)(GLuint buf, GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha);
extern void (CODEGEN_FUNCPTR *BlendFunci)(GLuint buf, GLenum src, GLenum dst);
extern void (CODEGEN_FUNCPTR *DeleteTransformFeedbacks)(GLsizei n, const GLuint * ids);
extern void (CODEGEN_FUNCPTR *DrawArraysIndirect)(GLenum mode, const void * indirect);
extern void (CODEGEN_FUNCPTR *DrawElementsIndirect)(GLenum mode, GLenum type, const void * indirect);
extern void (CODEGEN_FUNCPTR *DrawTransformFeedback)(GLenum mode, GLuint id);
extern void (CODEGEN_FUNCPTR *DrawTransformFeedbackStream)(GLenum mode, GLuint id, GLuint stream);
extern void (CODEGEN_FUNCPTR *EndQueryIndexed)(GLenum target, GLuint index);
extern void (CODEGEN_FUNCPTR *GenTransformFeedbacks)(GLsizei n, GLuint * ids);
extern void (CODEGEN_FUNCPTR *GetActiveSubroutineName)(GLuint program, GLenum shadertype, GLuint index, GLsizei bufsize, GLsizei * length, GLchar * name);
extern void (CODEGEN_FUNCPTR *GetActiveSubroutineUniformName)(GLuint program, GLenum shadertype, GLuint index, GLsizei bufsize, GLsizei * length, GLchar * name);
extern void (CODEGEN_FUNCPTR *GetActiveSubroutineUniformiv)(GLuint program, GLenum shadertype, GLuint index, GLenum pname, GLint * values);
extern void (CODEGEN_FUNCPTR *GetProgramStageiv)(GLuint program, GLenum shadertype, GLenum pname, GLint * values);
extern void (CODEGEN_FUNCPTR *GetQueryIndexediv)(GLenum target, GLuint index, GLenum pname, GLint * params);
extern GLuint (CODEGEN_FUNCPTR *GetSubroutineIndex)(GLuint program, GLenum shadertype, const GLchar * name);
extern GLint (CODEGEN_FUNCPTR *GetSubroutineUniformLocation)(GLuint program, GLenum shadertype, const GLchar * name);
extern void (CODEGEN_FUNCPTR *GetUniformSubroutineuiv)(GLenum shadertype, GLint location, GLuint * params);
extern void (CODEGEN_FUNCPTR *GetUniformdv)(GLuint program, GLint location, GLdouble * params);
extern GLboolean (CODEGEN_FUNCPTR *IsTransformFeedback)(GLuint id);
extern void (CODEGEN_FUNCPTR *MinSampleShading)(GLfloat value);
extern void (CODEGEN_FUNCPTR *PatchParameterfv)(GLenum pname, const GLfloat * values);
extern void (CODEGEN_FUNCPTR *PatchParameteri)(GLenum pname, GLint value);
extern void (CODEGEN_FUNCPTR *PauseTransformFeedback)(void);
extern void (CODEGEN_FUNCPTR *ResumeTransformFeedback)(void);
extern void (CODEGEN_FUNCPTR *Uniform1d)(GLint location, GLdouble x);
extern void (CODEGEN_FUNCPTR *Uniform1dv)(GLint location, GLsizei count, const GLdouble * value);
extern void (CODEGEN_FUNCPTR *Uniform2d)(GLint location, GLdouble x, GLdouble y);
extern void (CODEGEN_FUNCPTR *Uniform2dv)(GLint location, GLsizei count, const GLdouble * value);
extern void (CODEGEN_FUNCPTR *Uniform3d)(GLint location, GLdouble x, GLdouble y, GLdouble z);
extern void (CODEGEN_FUNCPTR *Uniform3dv)(GLint location, GLsizei count, const GLdouble * value);
extern void (CODEGEN_FUNCPTR *Uniform4d)(GLint location, GLdouble x, GLdouble y, GLdouble z, GLdouble w);
extern void (CODEGEN_FUNCPTR *Uniform4dv)(GLint location, GLsizei count, const GLdouble * value);
extern void (CODEGEN_FUNCPTR *UniformMatrix2dv)(GLint location, GLsizei count, GLboolean transpose, const GLdouble * value);
extern void (CODEGEN_FUNCPTR *UniformMatrix2x3dv)(GLint location, GLsizei count, GLboolean transpose, const GLdouble * value);
extern void (CODEGEN_FUNCPTR *UniformMatrix2x4dv)(GLint location, GLsizei count, GLboolean transpose, const GLdouble * value);
extern void (CODEGEN_FUNCPTR *UniformMatrix3dv)(GLint location, GLsizei count, GLboolean transpose, const GLdouble * value);
extern void (CODEGEN_FUNCPTR *UniformMatrix3x2dv)(GLint location, GLsizei count, GLboolean transpose, const GLdouble * value);
extern void (CODEGEN_FUNCPTR *UniformMatrix3x4dv)(GLint location, GLsizei count, GLboolean transpose, const GLdouble * value);
extern void (CODEGEN_FUNCPTR *UniformMatrix4dv)(GLint location, GLsizei count, GLboolean transpose, const GLdouble * value);
extern void (CODEGEN_FUNCPTR *UniformMatrix4x2dv)(GLint location, GLsizei count, GLboolean transpose, const GLdouble * value);
extern void (CODEGEN_FUNCPTR *UniformMatrix4x3dv)(GLint location, GLsizei count, GLboolean transpose, const GLdouble * value);
extern void (CODEGEN_FUNCPTR *UniformSubroutinesuiv)(GLenum shadertype, GLsizei count, const GLuint * indices);
extern void (CODEGEN_FUNCPTR *ActiveShaderProgram)(GLuint pipeline, GLuint program);
extern void (CODEGEN_FUNCPTR *BindProgramPipeline)(GLuint pipeline);
extern void (CODEGEN_FUNCPTR *ClearDepthf)(GLfloat d);
extern GLuint (CODEGEN_FUNCPTR *CreateShaderProgramv)(GLenum type, GLsizei count, const GLchar *const* strings);
extern void (CODEGEN_FUNCPTR *DeleteProgramPipelines)(GLsizei n, const GLuint * pipelines);
extern void (CODEGEN_FUNCPTR *DepthRangeArrayv)(GLuint first, GLsizei count, const GLdouble * v);
extern void (CODEGEN_FUNCPTR *DepthRangeIndexed)(GLuint index, GLdouble n, GLdouble f);
extern void (CODEGEN_FUNCPTR *DepthRangef)(GLfloat n, GLfloat f);
extern void (CODEGEN_FUNCPTR *GenProgramPipelines)(GLsizei n, GLuint * pipelines);
extern void (CODEGEN_FUNCPTR *GetDoublei_v)(GLenum target, GLuint index, GLdouble * data);
extern void (CODEGEN_FUNCPTR *GetFloati_v)(GLenum target, GLuint index, GLfloat * data);
extern void (CODEGEN_FUNCPTR *GetProgramBinary)(GLuint program, GLsizei bufSize, GLsizei * length, GLenum * binaryFormat, void * binary);
extern void (CODEGEN_FUNCPTR *GetProgramPipelineInfoLog)(GLuint pipeline, GLsizei bufSize, GLsizei * length, GLchar * infoLog);
extern void (CODEGEN_FUNCPTR *GetProgramPipelineiv)(GLuint pipeline, GLenum pname, GLint * params);
extern void (CODEGEN_FUNCPTR *GetShaderPrecisionFormat)(GLenum shadertype, GLenum precisiontype, GLint * range, GLint * precision);
extern void (CODEGEN_FUNCPTR *GetVertexAttribLdv)(GLuint index, GLenum pname, GLdouble * params);
extern GLboolean (CODEGEN_FUNCPTR *IsProgramPipeline)(GLuint pipeline);
extern void (CODEGEN_FUNCPTR *ProgramBinary)(GLuint program, GLenum binaryFormat, const void * binary, GLsizei length);
extern void (CODEGEN_FUNCPTR *ProgramParameteri)(GLuint program, GLenum pname, GLint value);
extern void (CODEGEN_FUNCPTR *ProgramUniform1d)(GLuint program, GLint location, GLdouble v0);
extern void (CODEGEN_FUNCPTR *ProgramUniform1dv)(GLuint program, GLint location, GLsizei count, const GLdouble * value);
extern void (CODEGEN_FUNCPTR *ProgramUniform1f)(GLuint program, GLint location, GLfloat v0);
extern void (CODEGEN_FUNCPTR *ProgramUniform1fv)(GLuint program, GLint location, GLsizei count, const GLfloat * value);
extern void (CODEGEN_FUNCPTR *ProgramUniform1i)(GLuint program, GLint location, GLint v0);
extern void (CODEGEN_FUNCPTR *ProgramUniform1iv)(GLuint program, GLint location, GLsizei count, const GLint * value);
extern void (CODEGEN_FUNCPTR *ProgramUniform1ui)(GLuint program, GLint location, GLuint v0);
extern void (CODEGEN_FUNCPTR *ProgramUniform1uiv)(GLuint program, GLint location, GLsizei count, const GLuint * value);
extern void (CODEGEN_FUNCPTR *ProgramUniform2d)(GLuint program, GLint location, GLdouble v0, GLdouble v1);
extern void (CODEGEN_FUNCPTR *ProgramUniform2dv)(GLuint program, GLint location, GLsizei count, const GLdouble * value);
extern void (CODEGEN_FUNCPTR *ProgramUniform2f)(GLuint program, GLint location, GLfloat v0, GLfloat v1);
extern void (CODEGEN_FUNCPTR *ProgramUniform2fv)(GLuint program, GLint location, GLsizei count, const GLfloat * value);
extern void (CODEGEN_FUNCPTR *ProgramUniform2i)(GLuint program, GLint location, GLint v0, GLint v1);
extern void (CODEGEN_FUNCPTR *ProgramUniform2iv)(GLuint program, GLint location, GLsizei count, const GLint * value);
extern void (CODEGEN_FUNCPTR *ProgramUniform2ui)(GLuint program, GLint location, GLuint v0, GLuint v1);
extern void (CODEGEN_FUNCPTR *ProgramUniform2uiv)(GLuint program, GLint location, GLsizei count, const GLuint * value);
extern void (CODEGEN_FUNCPTR *ProgramUniform3d)(GLuint program, GLint location, GLdouble v0, GLdouble v1, GLdouble v2);
extern void (CODEGEN_FUNCPTR *ProgramUniform3dv)(GLuint program, GLint location, GLsizei count, const GLdouble * value);
extern void (CODEGEN_FUNCPTR *ProgramUniform3f)(GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2);
extern void (CODEGEN_FUNCPTR *ProgramUniform3fv)(GLuint program, GLint location, GLsizei count, const GLfloat * value);
extern void (CODEGEN_FUNCPTR *ProgramUniform3i)(GLuint program, GLint location, GLint v0, GLint v1, GLint v2);
extern void (CODEGEN_FUNCPTR *ProgramUniform3iv)(GLuint program, GLint location, GLsizei count, const GLint * value);
extern void (CODEGEN_FUNCPTR *ProgramUniform3ui)(GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2);
extern void (CODEGEN_FUNCPTR *ProgramUniform3uiv)(GLuint program, GLint location, GLsizei count, const GLuint * value);
extern void (CODEGEN_FUNCPTR *ProgramUniform4d)(GLuint program, GLint location, GLdouble v0, GLdouble v1, GLdouble v2, GLdouble v3);
extern void (CODEGEN_FUNCPTR *ProgramUniform4dv)(GLuint program, GLint location, GLsizei count, const GLdouble * value);
extern void (CODEGEN_FUNCPTR *ProgramUniform4f)(GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3);
extern void (CODEGEN_FUNCPTR *ProgramUniform4fv)(GLuint program, GLint location, GLsizei count, const GLfloat * value);
extern void (CODEGEN_FUNCPTR *ProgramUniform4i)(GLuint program, GLint location, GLint v0, GLint v1, GLint v2, GLint v3);
extern void (CODEGEN_FUNCPTR *ProgramUniform4iv)(GLuint program, GLint location, GLsizei count, const GLint * value);
extern void (CODEGEN_FUNCPTR *ProgramUniform4ui)(GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3);
extern void (CODEGEN_FUNCPTR *ProgramUniform4uiv)(GLuint program, GLint location, GLsizei count, const GLuint * value);
extern void (CODEGEN_FUNCPTR *ProgramUniformMatrix2dv)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble * value);
extern void (CODEGEN_FUNCPTR *ProgramUniformMatrix2fv)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat * value);
extern void (CODEGEN_FUNCPTR *ProgramUniformMatrix2x3dv)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble * value);
extern void (CODEGEN_FUNCPTR *ProgramUniformMatrix2x3fv)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat * value);
extern void (CODEGEN_FUNCPTR *ProgramUniformMatrix2x4dv)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble * value);
extern void (CODEGEN_FUNCPTR *ProgramUniformMatrix2x4fv)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat * value);
extern void (CODEGEN_FUNCPTR *ProgramUniformMatrix3dv)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble * value);
extern void (CODEGEN_FUNCPTR *ProgramUniformMatrix3fv)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat * value);
extern void (CODEGEN_FUNCPTR *ProgramUniformMatrix3x2dv)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble * value);
extern void (CODEGEN_FUNCPTR *ProgramUniformMatrix3x2fv)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat * value);
extern void (CODEGEN_FUNCPTR *ProgramUniformMatrix3x4dv)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble * value);
extern void (CODEGEN_FUNCPTR *ProgramUniformMatrix3x4fv)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat * value);
extern void (CODEGEN_FUNCPTR *ProgramUniformMatrix4dv)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble * value);
extern void (CODEGEN_FUNCPTR *ProgramUniformMatrix4fv)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat * value);
extern void (CODEGEN_FUNCPTR *ProgramUniformMatrix4x2dv)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble * value);
extern void (CODEGEN_FUNCPTR *ProgramUniformMatrix4x2fv)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat * value);
extern void (CODEGEN_FUNCPTR *ProgramUniformMatrix4x3dv)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble * value);
extern void (CODEGEN_FUNCPTR *ProgramUniformMatrix4x3fv)(GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat * value);
extern void (CODEGEN_FUNCPTR *ReleaseShaderCompiler)(void);
extern void (CODEGEN_FUNCPTR *ScissorArrayv)(GLuint first, GLsizei count, const GLint * v);
extern void (CODEGEN_FUNCPTR *ScissorIndexed)(GLuint index, GLint left, GLint bottom, GLsizei width, GLsizei height);
extern void (CODEGEN_FUNCPTR *ScissorIndexedv)(GLuint index, const GLint * v);
extern void (CODEGEN_FUNCPTR *ShaderBinary)(GLsizei count, const GLuint * shaders, GLenum binaryformat, const void * binary, GLsizei length);
extern void (CODEGEN_FUNCPTR *UseProgramStages)(GLuint pipeline, GLbitfield stages, GLuint program);
extern void (CODEGEN_FUNCPTR *ValidateProgramPipeline)(GLuint pipeline);
extern void (CODEGEN_FUNCPTR *VertexAttribL1d)(GLuint index, GLdouble x);
extern void (CODEGEN_FUNCPTR *VertexAttribL1dv)(GLuint index, const GLdouble * v);
extern void (CODEGEN_FUNCPTR *VertexAttribL2d)(GLuint index, GLdouble x, GLdouble y);
extern void (CODEGEN_FUNCPTR *VertexAttribL2dv)(GLuint index, const GLdouble * v);
extern void (CODEGEN_FUNCPTR *VertexAttribL3d)(GLuint index, GLdouble x, GLdouble y, GLdouble z);
extern void (CODEGEN_FUNCPTR *VertexAttribL3dv)(GLuint index, const GLdouble * v);
extern void (CODEGEN_FUNCPTR *VertexAttribL4d)(GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w);
extern void (CODEGEN_FUNCPTR *VertexAttribL4dv)(GLuint index, const GLdouble * v);
extern void (CODEGEN_FUNCPTR *VertexAttribLPointer)(GLuint index, GLint size, GLenum type, GLsizei stride, const void * pointer);
extern void (CODEGEN_FUNCPTR *ViewportArrayv)(GLuint first, GLsizei count, const GLfloat * v);
extern void (CODEGEN_FUNCPTR *ViewportIndexedf)(GLuint index, GLfloat x, GLfloat y, GLfloat w, GLfloat h);
extern void (CODEGEN_FUNCPTR *ViewportIndexedfv)(GLuint index, const GLfloat * v);
extern void (CODEGEN_FUNCPTR *BindImageTexture)(GLuint unit, GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum access, GLenum format);
extern void (CODEGEN_FUNCPTR *DrawArraysInstancedBaseInstance)(GLenum mode, GLint first, GLsizei count, GLsizei instancecount, GLuint baseinstance);
extern void (CODEGEN_FUNCPTR *DrawElementsInstancedBaseInstance)(GLenum mode, GLsizei count, GLenum type, const void * indices, GLsizei instancecount, GLuint baseinstance);
extern void (CODEGEN_FUNCPTR *DrawElementsInstancedBaseVertexBaseInstance)(GLenum mode, GLsizei count, GLenum type, const void * indices, GLsizei instancecount, GLint basevertex, GLuint baseinstance);
extern void (CODEGEN_FUNCPTR *DrawTransformFeedbackInstanced)(GLenum mode, GLuint id, GLsizei instancecount);
extern void (CODEGEN_FUNCPTR *DrawTransformFeedbackStreamInstanced)(GLenum mode, GLuint id, GLuint stream, GLsizei instancecount);
extern void (CODEGEN_FUNCPTR *GetActiveAtomicCounterBufferiv)(GLuint program, GLuint bufferIndex, GLenum pname, GLint * params);
extern void (CODEGEN_FUNCPTR *GetInternalformativ)(GLenum target, GLenum internalformat, GLenum pname, GLsizei bufSize, GLint * params);
extern void (CODEGEN_FUNCPTR *MemoryBarrier)(GLbitfield barriers);
extern void (CODEGEN_FUNCPTR *TexStorage1D)(GLenum target, GLsizei levels, GLenum internalformat, GLsizei width);
extern void (CODEGEN_FUNCPTR *TexStorage2D)(GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height);
extern void (CODEGEN_FUNCPTR *TexStorage3D)(GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth);
extern void (CODEGEN_FUNCPTR *BindVertexBuffer)(GLuint bindingindex, GLuint buffer, GLintptr offset, GLsizei stride);
extern void (CODEGEN_FUNCPTR *ClearBufferData)(GLenum target, GLenum internalformat, GLenum format, GLenum type, const void * data);
extern void (CODEGEN_FUNCPTR *ClearBufferSubData)(GLenum target, GLenum internalformat, GLintptr offset, GLsizeiptr size, GLenum format, GLenum type, const void * data);
extern void (CODEGEN_FUNCPTR *CopyImageSubData)(GLuint srcName, GLenum srcTarget, GLint srcLevel, GLint srcX, GLint srcY, GLint srcZ, GLuint dstName, GLenum dstTarget, GLint dstLevel, GLint dstX, GLint dstY, GLint dstZ, GLsizei srcWidth, GLsizei srcHeight, GLsizei srcDepth);
extern void (CODEGEN_FUNCPTR *DebugMessageCallback)(GLDEBUGPROC callback, const void * userParam);
extern void (CODEGEN_FUNCPTR *DebugMessageControl)(GLenum source, GLenum type, GLenum severity, GLsizei count, const GLuint * ids, GLboolean enabled);
extern void (CODEGEN_FUNCPTR *DebugMessageInsert)(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar * buf);
extern void (CODEGEN_FUNCPTR *DispatchCompute)(GLuint num_groups_x, GLuint num_groups_y, GLuint num_groups_z);
extern void (CODEGEN_FUNCPTR *DispatchComputeIndirect)(GLintptr indirect);
extern void (CODEGEN_FUNCPTR *FramebufferParameteri)(GLenum target, GLenum pname, GLint param);
extern GLuint (CODEGEN_FUNCPTR *GetDebugMessageLog)(GLuint count, GLsizei bufSize, GLenum * sources, GLenum * types, GLuint * ids, GLenum * severities, GLsizei * lengths, GLchar * messageLog);
extern void (CODEGEN_FUNCPTR *GetFramebufferParameteriv)(GLenum target, GLenum pname, GLint * params);
extern void (CODEGEN_FUNCPTR *GetInternalformati64v)(GLenum target, GLenum internalformat, GLenum pname, GLsizei bufSize, GLint64 * params);
extern void (CODEGEN_FUNCPTR *GetObjectLabel)(GLenum identifier, GLuint name, GLsizei bufSize, GLsizei * length, GLchar * label);
extern void (CODEGEN_FUNCPTR *GetObjectPtrLabel)(const void * ptr, GLsizei bufSize, GLsizei * length, GLchar * label);
extern void (CODEGEN_FUNCPTR *GetProgramInterfaceiv)(GLuint program, GLenum programInterface, GLenum pname, GLint * params);
extern GLuint (CODEGEN_FUNCPTR *GetProgramResourceIndex)(GLuint program, GLenum programInterface, const GLchar * name);
extern GLint (CODEGEN_FUNCPTR *GetProgramResourceLocation)(GLuint program, GLenum programInterface, const GLchar * name);
extern GLint (CODEGEN_FUNCPTR *GetProgramResourceLocationIndex)(GLuint program, GLenum programInterface, const GLchar * name);
extern void (CODEGEN_FUNCPTR *GetProgramResourceName)(GLuint program, GLenum programInterface, GLuint index, GLsizei bufSize, GLsizei * length, GLchar * name);
extern void (CODEGEN_FUNCPTR *GetProgramResourceiv)(GLuint program, GLenum programInterface, GLuint index, GLsizei propCount, const GLenum * props, GLsizei bufSize, GLsizei * length, GLint * params);
extern void (CODEGEN_FUNCPTR *InvalidateBufferData)(GLuint buffer);
extern void (CODEGEN_FUNCPTR *InvalidateBufferSubData)(GLuint buffer, GLintptr offset, GLsizeiptr length);
extern void (CODEGEN_FUNCPTR *InvalidateFramebuffer)(GLenum target, GLsizei numAttachments, const GLenum * attachments);
extern void (CODEGEN_FUNCPTR *InvalidateSubFramebuffer)(GLenum target, GLsizei numAttachments, const GLenum * attachments, GLint x, GLint y, GLsizei width, GLsizei height);
extern void (CODEGEN_FUNCPTR *InvalidateTexImage)(GLuint texture, GLint level);
extern void (CODEGEN_FUNCPTR *InvalidateTexSubImage)(GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth);
extern void (CODEGEN_FUNCPTR *MultiDrawArraysIndirect)(GLenum mode, const void * indirect, GLsizei drawcount, GLsizei stride);
extern void (CODEGEN_FUNCPTR *MultiDrawElementsIndirect)(GLenum mode, GLenum type, const void * indirect, GLsizei drawcount, GLsizei stride);
extern void (CODEGEN_FUNCPTR *ObjectLabel)(GLenum identifier, GLuint name, GLsizei length, const GLchar * label);
extern void (CODEGEN_FUNCPTR *ObjectPtrLabel)(const void * ptr, GLsizei length, const GLchar * label);
extern void (CODEGEN_FUNCPTR *PopDebugGroup)(void);
extern void (CODEGEN_FUNCPTR *PushDebugGroup)(GLenum source, GLuint id, GLsizei length, const GLchar * message);
extern void (CODEGEN_FUNCPTR *ShaderStorageBlockBinding)(GLuint program, GLuint storageBlockIndex, GLuint storageBlockBinding);
extern void (CODEGEN_FUNCPTR *TexBufferRange)(GLenum target, GLenum internalformat, GLuint buffer, GLintptr offset, GLsizeiptr size);
extern void (CODEGEN_FUNCPTR *TexStorage2DMultisample)(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations);
extern void (CODEGEN_FUNCPTR *TexStorage3DMultisample)(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations);
extern void (CODEGEN_FUNCPTR *TextureView)(GLuint texture, GLenum target, GLuint origtexture, GLenum internalformat, GLuint minlevel, GLuint numlevels, GLuint minlayer, GLuint numlayers);
extern void (CODEGEN_FUNCPTR *VertexAttribBinding)(GLuint attribindex, GLuint bindingindex);
extern void (CODEGEN_FUNCPTR *VertexAttribFormat)(GLuint attribindex, GLint size, GLenum type, GLboolean normalized, GLuint relativeoffset);
extern void (CODEGEN_FUNCPTR *VertexAttribIFormat)(GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset);
extern void (CODEGEN_FUNCPTR *VertexAttribLFormat)(GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset);
extern void (CODEGEN_FUNCPTR *VertexBindingDivisor)(GLuint bindingindex, GLuint divisor);
extern void (CODEGEN_FUNCPTR *BindBuffersBase)(GLenum target, GLuint first, GLsizei count, const GLuint * buffers);
extern void (CODEGEN_FUNCPTR *BindBuffersRange)(GLenum target, GLuint first, GLsizei count, const GLuint * buffers, const GLintptr * offsets, const GLsizeiptr * sizes);
extern void (CODEGEN_FUNCPTR *BindImageTextures)(GLuint first, GLsizei count, const GLuint * textures);
extern void (CODEGEN_FUNCPTR *BindSamplers)(GLuint first, GLsizei count, const GLuint * samplers);
extern void (CODEGEN_FUNCPTR *BindTextures)(GLuint first, GLsizei count, const GLuint * textures);
extern void (CODEGEN_FUNCPTR *BindVertexBuffers)(GLuint first, GLsizei count, const GLuint * buffers, const GLintptr * offsets, const GLsizei * strides);
extern void (CODEGEN_FUNCPTR *BufferStorage)(GLenum target, GLsizeiptr size, const void * data, GLbitfield flags);
extern void (CODEGEN_FUNCPTR *ClearTexImage)(GLuint texture, GLint level, GLenum format, GLenum type, const void * data);
extern void (CODEGEN_FUNCPTR *ClearTexSubImage)(GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void * data);
extern void (CODEGEN_FUNCPTR *BindTextureUnit)(GLuint unit, GLuint texture);
extern void (CODEGEN_FUNCPTR *BlitNamedFramebuffer)(GLuint readFramebuffer, GLuint drawFramebuffer, GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter);
extern GLenum (CODEGEN_FUNCPTR *CheckNamedFramebufferStatus)(GLuint framebuffer, GLenum target);
extern void (CODEGEN_FUNCPTR *ClearNamedBufferData)(GLuint buffer, GLenum internalformat, GLenum format, GLenum type, const void * data);
extern void (CODEGEN_FUNCPTR *ClearNamedBufferSubData)(GLuint buffer, GLenum internalformat, GLintptr offset, GLsizeiptr size, GLenum format, GLenum type, const void * data);
extern void (CODEGEN_FUNCPTR *ClearNamedFramebufferfi)(GLuint framebuffer, GLenum buffer, GLint drawbuffer, const GLfloat depth, GLint stencil);
extern void (CODEGEN_FUNCPTR *ClearNamedFramebufferfv)(GLuint framebuffer, GLenum buffer, GLint drawbuffer, const GLfloat * value);
extern void (CODEGEN_FUNCPTR *ClearNamedFramebufferiv)(GLuint framebuffer, GLenum buffer, GLint drawbuffer, const GLint * value);
extern void (CODEGEN_FUNCPTR *ClearNamedFramebufferuiv)(GLuint framebuffer, GLenum buffer, GLint drawbuffer, const GLuint * value);
extern void (CODEGEN_FUNCPTR *ClipControl)(GLenum origin, GLenum depth);
extern void (CODEGEN_FUNCPTR *CompressedTextureSubImage1D)(GLuint texture, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const void * data);
extern void (CODEGEN_FUNCPTR *CompressedTextureSubImage2D)(GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void * data);
extern void (CODEGEN_FUNCPTR *CompressedTextureSubImage3D)(GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void * data);
extern void (CODEGEN_FUNCPTR *CopyNamedBufferSubData)(GLuint readBuffer, GLuint writeBuffer, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size);
extern void (CODEGEN_FUNCPTR *CopyTextureSubImage1D)(GLuint texture, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width);
extern void (CODEGEN_FUNCPTR *CopyTextureSubImage2D)(GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height);
extern void (CODEGEN_FUNCPTR *CopyTextureSubImage3D)(GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height);
extern void (CODEGEN_FUNCPTR *CreateBuffers)(GLsizei n, GLuint * buffers);
extern void (CODEGEN_FUNCPTR *CreateFramebuffers)(GLsizei n, GLuint * framebuffers);
extern void (CODEGEN_FUNCPTR *CreateProgramPipelines)(GLsizei n, GLuint * pipelines);
extern void (CODEGEN_FUNCPTR *CreateQueries)(GLenum target, GLsizei n, GLuint * ids);
extern void (CODEGEN_FUNCPTR *CreateRenderbuffers)(GLsizei n, GLuint * renderbuffers);
extern void (CODEGEN_FUNCPTR *CreateSamplers)(GLsizei n, GLuint * samplers);
extern void (CODEGEN_FUNCPTR *CreateTextures)(GLenum target, GLsizei n, GLuint * textures);
extern void (CODEGEN_FUNCPTR *CreateTransformFeedbacks)(GLsizei n, GLuint * ids);
extern void (CODEGEN_FUNCPTR *CreateVertexArrays)(GLsizei n, GLuint * arrays);
extern void (CODEGEN_FUNCPTR *DisableVertexArrayAttrib)(GLuint vaobj, GLuint index);
extern void (CODEGEN_FUNCPTR *EnableVertexArrayAttrib)(GLuint vaobj, GLuint index);
extern void (CODEGEN_FUNCPTR *FlushMappedNamedBufferRange)(GLuint buffer, GLintptr offset, GLsizeiptr length);
extern void (CODEGEN_FUNCPTR *GenerateTextureMipmap)(GLuint texture);
extern void (CODEGEN_FUNCPTR *GetCompressedTextureImage)(GLuint texture, GLint level, GLsizei bufSize, void * pixels);
extern void (CODEGEN_FUNCPTR *GetCompressedTextureSubImage)(GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLsizei bufSize, void * pixels);
extern GLenum (CODEGEN_FUNCPTR *GetGraphicsResetStatus)(void);
extern void (CODEGEN_FUNCPTR *GetNamedBufferParameteri64v)(GLuint buffer, GLenum pname, GLint64 * params);
extern void (CODEGEN_FUNCPTR *GetNamedBufferParameteriv)(GLuint buffer, GLenum pname, GLint * params);
extern void (CODEGEN_FUNCPTR *GetNamedBufferPointerv)(GLuint buffer, GLenum pname, void ** params);
extern void (CODEGEN_FUNCPTR *GetNamedBufferSubData)(GLuint buffer, GLintptr offset, GLsizeiptr size, void * data);
extern void (CODEGEN_FUNCPTR *GetNamedFramebufferAttachmentParameteriv)(GLuint framebuffer, GLenum attachment, GLenum pname, GLint * params);
extern void (CODEGEN_FUNCPTR *GetNamedFramebufferParameteriv)(GLuint framebuffer, GLenum pname, GLint * param);
extern void (CODEGEN_FUNCPTR *GetNamedRenderbufferParameteriv)(GLuint renderbuffer, GLenum pname, GLint * params);
extern void (CODEGEN_FUNCPTR *GetQueryBufferObjecti64v)(GLuint id, GLuint buffer, GLenum pname, GLintptr offset);
extern void (CODEGEN_FUNCPTR *GetQueryBufferObjectiv)(GLuint id, GLuint buffer, GLenum pname, GLintptr offset);
extern void (CODEGEN_FUNCPTR *GetQueryBufferObjectui64v)(GLuint id, GLuint buffer, GLenum pname, GLintptr offset);
extern void (CODEGEN_FUNCPTR *GetQueryBufferObjectuiv)(GLuint id, GLuint buffer, GLenum pname, GLintptr offset);
extern void (CODEGEN_FUNCPTR *GetTextureImage)(GLuint texture, GLint level, GLenum format, GLenum type, GLsizei bufSize, void * pixels);
extern void (CODEGEN_FUNCPTR *GetTextureLevelParameterfv)(GLuint texture, GLint level, GLenum pname, GLfloat * params);
extern void (CODEGEN_FUNCPTR *GetTextureLevelParameteriv)(GLuint texture, GLint level, GLenum pname, GLint * params);
extern void (CODEGEN_FUNCPTR *GetTextureParameterIiv)(GLuint texture, GLenum pname, GLint * params);
extern void (CODEGEN_FUNCPTR *GetTextureParameterIuiv)(GLuint texture, GLenum pname, GLuint * params);
extern void (CODEGEN_FUNCPTR *GetTextureParameterfv)(GLuint texture, GLenum pname, GLfloat * params);
extern void (CODEGEN_FUNCPTR *GetTextureParameteriv)(GLuint texture, GLenum pname, GLint * params);
extern void (CODEGEN_FUNCPTR *GetTextureSubImage)(GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, GLsizei bufSize, void * pixels);
extern void (CODEGEN_FUNCPTR *GetTransformFeedbacki64_v)(GLuint xfb, GLenum pname, GLuint index, GLint64 * param);
extern void (CODEGEN_FUNCPTR *GetTransformFeedbacki_v)(GLuint xfb, GLenum pname, GLuint index, GLint * param);
extern void (CODEGEN_FUNCPTR *GetTransformFeedbackiv)(GLuint xfb, GLenum pname, GLint * param);
extern void (CODEGEN_FUNCPTR *GetVertexArrayIndexed64iv)(GLuint vaobj, GLuint index, GLenum pname, GLint64 * param);
extern void (CODEGEN_FUNCPTR *GetVertexArrayIndexediv)(GLuint vaobj, GLuint index, GLenum pname, GLint * param);
extern void (CODEGEN_FUNCPTR *GetVertexArrayiv)(GLuint vaobj, GLenum pname, GLint * param);
extern void (CODEGEN_FUNCPTR *GetnCompressedTexImage)(GLenum target, GLint lod, GLsizei bufSize, void * pixels);
extern void (CODEGEN_FUNCPTR *GetnTexImage)(GLenum target, GLint level, GLenum format, GLenum type, GLsizei bufSize, void * pixels);
extern void (CODEGEN_FUNCPTR *GetnUniformdv)(GLuint program, GLint location, GLsizei bufSize, GLdouble * params);
extern void (CODEGEN_FUNCPTR *GetnUniformfv)(GLuint program, GLint location, GLsizei bufSize, GLfloat * params);
extern void (CODEGEN_FUNCPTR *GetnUniformiv)(GLuint program, GLint location, GLsizei bufSize, GLint * params);
extern void (CODEGEN_FUNCPTR *GetnUniformuiv)(GLuint program, GLint location, GLsizei bufSize, GLuint * params);
extern void (CODEGEN_FUNCPTR *InvalidateNamedFramebufferData)(GLuint framebuffer, GLsizei numAttachments, const GLenum * attachments);
extern void (CODEGEN_FUNCPTR *InvalidateNamedFramebufferSubData)(GLuint framebuffer, GLsizei numAttachments, const GLenum * attachments, GLint x, GLint y, GLsizei width, GLsizei height);
extern void * (CODEGEN_FUNCPTR *MapNamedBuffer)(GLuint buffer, GLenum access);
extern void * (CODEGEN_FUNCPTR *MapNamedBufferRange)(GLuint buffer, GLintptr offset, GLsizeiptr length, GLbitfield access);
extern void (CODEGEN_FUNCPTR *MemoryBarrierByRegion)(GLbitfield barriers);
extern void (CODEGEN_FUNCPTR *NamedBufferData)(GLuint buffer, GLsizeiptr size, const void * data, GLenum usage);
extern void (CODEGEN_FUNCPTR *NamedBufferStorage)(GLuint buffer, GLsizeiptr size, const void * data, GLbitfield flags);
extern void (CODEGEN_FUNCPTR *NamedBufferSubData)(GLuint buffer, GLintptr offset, GLsizeiptr size, const void * data);
extern void (CODEGEN_FUNCPTR *NamedFramebufferDrawBuffer)(GLuint framebuffer, GLenum buf);
extern void (CODEGEN_FUNCPTR *NamedFramebufferDrawBuffers)(GLuint framebuffer, GLsizei n, const GLenum * bufs);
extern void (CODEGEN_FUNCPTR *NamedFramebufferParameteri)(GLuint framebuffer, GLenum pname, GLint param);
extern void (CODEGEN_FUNCPTR *NamedFramebufferReadBuffer)(GLuint framebuffer, GLenum src);
extern void (CODEGEN_FUNCPTR *NamedFramebufferRenderbuffer)(GLuint framebuffer, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer);
extern void (CODEGEN_FUNCPTR *NamedFramebufferTexture)(GLuint framebuffer, GLenum attachment, GLuint texture, GLint level);
extern void (CODEGEN_FUNCPTR *NamedFramebufferTextureLayer)(GLuint framebuffer, GLenum attachment, GLuint texture, GLint level, GLint layer);
extern void (CODEGEN_FUNCPTR *NamedRenderbufferStorage)(GLuint renderbuffer, GLenum internalformat, GLsizei width, GLsizei height);
extern void (CODEGEN_FUNCPTR *NamedRenderbufferStorageMultisample)(GLuint renderbuffer, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height);
extern void (CODEGEN_FUNCPTR *ReadnPixels)(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLsizei bufSize, void * data);
extern void (CODEGEN_FUNCPTR *TextureBarrier)(void);
extern void (CODEGEN_FUNCPTR *TextureBuffer)(GLuint texture, GLenum internalformat, GLuint buffer);
extern void (CODEGEN_FUNCPTR *TextureBufferRange)(GLuint texture, GLenum internalformat, GLuint buffer, GLintptr offset, GLsizeiptr size);
extern void (CODEGEN_FUNCPTR *TextureParameterIiv)(GLuint texture, GLenum pname, const GLint * params);
extern void (CODEGEN_FUNCPTR *TextureParameterIuiv)(GLuint texture, GLenum pname, const GLuint * params);
extern void (CODEGEN_FUNCPTR *TextureParameterf)(GLuint texture, GLenum pname, GLfloat param);
extern void (CODEGEN_FUNCPTR *TextureParameterfv)(GLuint texture, GLenum pname, const GLfloat * param);
extern void (CODEGEN_FUNCPTR *TextureParameteri)(GLuint texture, GLenum pname, GLint param);
extern void (CODEGEN_FUNCPTR *TextureParameteriv)(GLuint texture, GLenum pname, const GLint * param);
extern void (CODEGEN_FUNCPTR *TextureStorage1D)(GLuint texture, GLsizei levels, GLenum internalformat, GLsizei width);
extern void (CODEGEN_FUNCPTR *TextureStorage2D)(GLuint texture, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height);
extern void (CODEGEN_FUNCPTR *TextureStorage2DMultisample)(GLuint texture, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations);
extern void (CODEGEN_FUNCPTR *TextureStorage3D)(GLuint texture, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth);
extern void (CODEGEN_FUNCPTR *TextureStorage3DMultisample)(GLuint texture, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations);
extern void (CODEGEN_FUNCPTR *TextureSubImage1D)(GLuint texture, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const void * pixels);
extern void (CODEGEN_FUNCPTR *TextureSubImage2D)(GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void * pixels);
extern void (CODEGEN_FUNCPTR *TextureSubImage3D)(GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void * pixels);
extern void (CODEGEN_FUNCPTR *TransformFeedbackBufferBase)(GLuint xfb, GLuint index, GLuint buffer);
extern void (CODEGEN_FUNCPTR *TransformFeedbackBufferRange)(GLuint xfb, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size);
extern GLboolean (CODEGEN_FUNCPTR *UnmapNamedBuffer)(GLuint buffer);
extern void (CODEGEN_FUNCPTR *VertexArrayAttribBinding)(GLuint vaobj, GLuint attribindex, GLuint bindingindex);
extern void (CODEGEN_FUNCPTR *VertexArrayAttribFormat)(GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLboolean normalized, GLuint relativeoffset);
extern void (CODEGEN_FUNCPTR *VertexArrayAttribIFormat)(GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset);
extern void (CODEGEN_FUNCPTR *VertexArrayAttribLFormat)(GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset);
extern void (CODEGEN_FUNCPTR *VertexArrayBindingDivisor)(GLuint vaobj, GLuint bindingindex, GLuint divisor);
extern void (CODEGEN_FUNCPTR *VertexArrayElementBuffer)(GLuint vaobj, GLuint buffer);
extern void (CODEGEN_FUNCPTR *VertexArrayVertexBuffer)(GLuint vaobj, GLuint bindingindex, GLuint buffer, GLintptr offset, GLsizei stride);
extern void (CODEGEN_FUNCPTR *VertexArrayVertexBuffers)(GLuint vaobj, GLuint first, GLsizei count, const GLuint * buffers, const GLintptr * offsets, const GLsizei * strides);
namespace sys
{
exts::LoadTest LoadFunctions();
int GetMinorVersion();
int GetMajorVersion();
bool IsVersionGEQ(int majorVersion, int minorVersion);
} //namespace sys
} //namespace gl
#endif //POINTER_CPP_GENERATED_HEADEROPENGL_HPP
|
//write include statements
#include "expressions.h"
#include<iostream>
//write namespace using statement for cout
using std::cout;
using std::cin;
/*
Call multiply_numbers with 10 and 10 parameter values and display function result
*/
int main()
{
//initialize variables
double meal_amount;
double tip_rate;
double tip_amount;
double tax_amount;
double total;
//Ask for meal amount
cout<<"How much was your meal? ";
cin>>meal_amount;
//Calculate tax
tax_amount = get_sales_tax_amount(meal_amount);
//Ask for tip percentage
cout<<"What percentage would you like to tip? ";
cin>>tip_rate;
//Get tip amount
tip_amount = get_tip_amount(meal_amount, tip_rate);
//Get total
total = meal_amount + tip_amount + tax_amount;
//Print results
cout<<"Meal Amount: "<<meal_amount<<"\n";
cout<<"Sales Tax: "<<tax_amount<<"\n";
cout<<"Tip Amount: "<<tip_amount<<"\n";
cout<<"Total: "<<total<<"\n";
return 0;
}
|
//===------------------------- unwind_01.cpp ------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
// UNSUPPORTED: no-exceptions
#include <assert.h>
#if defined(__GNUC__)
#pragma GCC diagnostic ignored "-Wunreachable-code"
#endif
struct A
{
static int count;
int id_;
A() : id_(++count) {}
~A() {assert(id_ == count--);}
private:
A(const A&);
A& operator=(const A&);
};
int A::count = 0;
struct B
{
static int count;
int id_;
B() : id_(++count) {}
~B() {assert(id_ == count--);}
private:
B(const B&);
B& operator=(const B&);
};
int B::count = 0;
struct C
{
static int count;
int id_;
C() : id_(++count) {}
~C() {assert(id_ == count--);}
private:
C(const C&);
C& operator=(const C&);
};
int C::count = 0;
void f2()
{
C c;
A a;
throw 55;
B b;
}
void f1()
{
A a;
B b;
f2();
C c;
}
int main()
{
try
{
f1();
assert(false);
}
catch (int* i)
{
assert(false);
}
catch (long i)
{
assert(false);
}
catch (int i)
{
assert(i == 55);
}
catch (...)
{
assert(false);
}
assert(A::count == 0);
assert(B::count == 0);
assert(C::count == 0);
}
|
// This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.
#ifndef OPENCV_DNN_SRC_CUDA4DNN_CSL_STREAM_HPP
#define OPENCV_DNN_SRC_CUDA4DNN_CSL_STREAM_HPP
#include "error.hpp"
#include <opencv2/core.hpp>
#include <opencv2/core/utils/logger.hpp>
#include <cuda_runtime_api.h>
#include <memory>
#include <sstream>
#include <utility>
namespace cv { namespace dnn { namespace cuda4dnn { namespace csl {
/** \file stream.hpp
*
* Default streams are not supported as they limit flexiblity. All operations are always
* carried out in non-default streams in the CUDA backend. The stream classes sacrifice
* the ability to support default streams in exchange for better error detection. That is,
* a default constructed stream represents no stream and any attempt to use it will throw an
* exception.
*/
/** @brief non-copyable smart CUDA stream
*
* UniqueStream is a smart non-sharable wrapper for CUDA stream handle which ensures that
* the handle is destroyed after use. Unless explicitly specified by a constructor argument,
* the stream object does not represent any stream by default.
*/
class UniqueStream {
public:
UniqueStream() noexcept : stream{ 0 } { }
UniqueStream(UniqueStream&) = delete;
UniqueStream(UniqueStream&& other) noexcept {
stream = other.stream;
other.stream = 0;
}
/** creates a non-default stream if `create` is true; otherwise, no stream is created */
UniqueStream(bool create) : stream{ 0 } {
if (create) {
/* we create non-blocking streams to avoid inrerruptions from users using the default stream */
CUDA4DNN_CHECK_CUDA(cudaStreamCreateWithFlags(&stream, cudaStreamNonBlocking));
}
}
~UniqueStream() {
try {
/* cudaStreamDestroy does not throw if a valid stream is passed unless a previous
* asynchronous operation errored.
*/
if (stream != 0)
CUDA4DNN_CHECK_CUDA(cudaStreamDestroy(stream));
} catch (const CUDAException& ex) {
std::ostringstream os;
os << "Asynchronous exception caught during CUDA stream destruction.\n";
os << ex.what();
os << "Exception will be ignored.\n";
CV_LOG_WARNING(0, os.str().c_str());
}
}
UniqueStream& operator=(const UniqueStream&) = delete;
UniqueStream& operator=(UniqueStream&& other) noexcept {
CV_Assert(other);
if (&other != this) {
UniqueStream(std::move(*this)); /* destroy current stream */
stream = other.stream;
other.stream = 0;
}
return *this;
}
/** returns the raw CUDA stream handle */
cudaStream_t get() const noexcept {
CV_Assert(stream);
return stream;
}
/** blocks the calling thread until all pending operations in the stream finish */
void synchronize() const {
CV_Assert(stream);
CUDA4DNN_CHECK_CUDA(cudaStreamSynchronize(stream));
}
/** returns true if there are pending operations in the stream */
bool busy() const {
CV_Assert(stream);
auto status = cudaStreamQuery(stream);
if (status == cudaErrorNotReady)
return true;
CUDA4DNN_CHECK_CUDA(status);
return false;
}
/** returns true if the stream is valid */
explicit operator bool() const noexcept { return static_cast<bool>(stream); }
private:
cudaStream_t stream;
};
/** @brief sharable smart CUDA stream
*
* Stream is a smart sharable wrapper for CUDA stream handle which ensures that
* the handle is destroyed after use. Unless explicitly specified in the constructor,
* the stream object represents no stream.
*/
class Stream {
public:
Stream() { }
Stream(const Stream&) = default;
Stream(Stream&&) = default;
/** if \p create is `true`, a new stream will be created; otherwise, no stream is created */
Stream(bool create) {
if (create)
stream = std::make_shared<UniqueStream>(create);
}
Stream& operator=(const Stream&) = default;
Stream& operator=(Stream&&) = default;
/** blocks the caller thread until all operations in the stream are complete */
void synchronize() const {
CV_Assert(stream);
stream->synchronize();
}
/** returns true if there are operations pending in the stream */
bool busy() const {
CV_Assert(stream);
return stream->busy();
}
/** returns true if the object points has a valid stream */
explicit operator bool() const noexcept {
if (!stream)
return false;
return stream->operator bool();
}
cudaStream_t get() const noexcept {
CV_Assert(stream);
return stream->get();
}
private:
std::shared_ptr<UniqueStream> stream;
};
}}}} /* namespace cv::dnn::cuda4dnn::csl */
#endif /* OPENCV_DNN_SRC_CUDA4DNN_CSL_STREAM_HPP */
|
/************************************************************************************
OpenGL with Qt - Tutorial
-------------------------
Autor : Andreas Nicolai <andreas.nicolai@gmx.net>
Repository : https://github.com/ghorwin/OpenGLWithQt-Tutorial
License : BSD License,
see https://github.com/ghorwin/OpenGLWithQt-Tutorial/blob/master/LICENSE
************************************************************************************/
#include "SceneView.h"
#include <QExposeEvent>
#include <QOpenGLShaderProgram>
#include <QDateTime>
#include "DebugApplication.h"
#define SHADER(x) m_shaderPrograms[x].shaderProgram()
const QVector3D UP_VECTOR = QVector3D(0.0f, 1.0f, 0.0f);
const unsigned int SHADOW_WIDTH = 4000, SHADOW_HEIGHT = 4000;
QVector3D LIGHT_POS(50.0f, 100.0f, 75.0f);
SceneView::SceneView() :
m_inputEventReceived(false),
m_frameBufferObject(nullptr)
{
// tell keyboard handler to monitor certain keys
m_keyboardMouseHandler.addRecognizedKey(Qt::Key_W);
m_keyboardMouseHandler.addRecognizedKey(Qt::Key_A);
m_keyboardMouseHandler.addRecognizedKey(Qt::Key_S);
m_keyboardMouseHandler.addRecognizedKey(Qt::Key_D);
m_keyboardMouseHandler.addRecognizedKey(Qt::Key_Q);
m_keyboardMouseHandler.addRecognizedKey(Qt::Key_E);
m_keyboardMouseHandler.addRecognizedKey(Qt::Key_Shift);
// *** create scene (no OpenGL calls are being issued below, just the data structures are created.
// Shaderprogram #0 : regular geometry (painting triangles via element index)
ShaderProgram blocks(":/shaders/sceneWithShadowMap.vert",":/shaders/sceneWithShadowMap.frag");
blocks.m_uniformNames.append("worldToView"); // #0
blocks.m_uniformNames.append("lightSpaceMatrix"); // #1
blocks.m_uniformNames.append("lightPos"); // #2
blocks.m_uniformNames.append("viewPos"); // #3
blocks.m_uniformNames.append("shadowMap"); // #4
m_shaderPrograms.append( blocks );
// Shaderprogram #1 : grid (painting grid lines)
ShaderProgram grid(":/shaders/grid.vert",":/shaders/grid.frag");
grid.m_uniformNames.append("worldToView"); // mat4
grid.m_uniformNames.append("gridColor"); // vec3
grid.m_uniformNames.append("backColor"); // vec3
m_shaderPrograms.append( grid );
// Shaderprogram #2 : only for shadow
ShaderProgram shadow(":/shaders/depthMap.vert",":/shaders/depthMap.frag");
shadow.m_uniformNames.append("worldToView");
m_shaderPrograms.append( shadow );
// Shaderprogram #3 : screenfill (for debugging, only)
ShaderProgram screenFill(":/shaders/screenfill.vert",":/shaders/screenfill.frag");
m_shaderPrograms.append( screenFill );
// *** initialize camera placement and model placement in the world
// move camera a little back and up
m_camera.translate(-50,100,150);
// look slightly down
m_camera.rotate(-30, m_camera.right());
// look slightly right
m_camera.rotate(-25, UP_VECTOR);
}
SceneView::~SceneView() {
if (m_context) {
m_context->makeCurrent(this);
for (ShaderProgram & p : m_shaderPrograms)
p.destroy();
m_boxObject.destroy();
m_gridObject.destroy();
m_texture2ScreenObject.destroy();
m_gpuTimers.destroy();
delete m_frameBufferObject;
}
}
void SceneView::initializeGL() {
FUNCID(SceneView::initializeGL);
try {
// initialize shader programs
for (ShaderProgram & p : m_shaderPrograms)
p.create();
// tell OpenGL to show only faces whose normal vector points towards us
glEnable(GL_CULL_FACE);
// enable depth testing
glEnable(GL_DEPTH_TEST);
// set the background color = clear color
glClearColor(0.1f, 0.15f, 0.3f, 1.0f);
// initialize drawable objects
m_boxObject.create(SHADER(0));
m_gridObject.create(SHADER(1));
m_texture2ScreenObject.create(SHADER(3));
// Timer
m_gpuTimers.setSampleCount(7);
m_gpuTimers.create();
// generate framebuffer for depth map
glGenFramebuffers(1, &depthMapFBO);
// generate depth map texture
glGenTextures(1, &depthMap);
glBindTexture(GL_TEXTURE_2D, depthMap);
// create the texture
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, SHADOW_WIDTH, SHADOW_HEIGHT, 0, GL_DEPTH_COMPONENT, GL_FLOAT, nullptr);
// and set texture parameters
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
// attach depth texture to framebuffer
glBindFramebuffer(GL_FRAMEBUFFER, depthMapFBO);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, depthMap, 0);
// explicitely tell OpenGL that we do not want to render to color buffer
glDrawBuffer(GL_NONE);
glReadBuffer(GL_NONE);
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE)
qDebug() << "Framebuffer complete";
glBindFramebuffer(GL_FRAMEBUFFER, 0); // unbind framebuffer
QMatrix4x4 lightProjection;
float near_plane = 1.0f;
float far_plane = 500.5f;
lightProjection.ortho(-100.f, 100.f, -100.f, 100.f, near_plane, far_plane);
QMatrix4x4 lightCam;
lightCam.setToIdentity();
lightCam.lookAt( LIGHT_POS,
QVector3D(0,0,0),
UP_VECTOR);
m_lightSpaceMatrix = lightProjection * lightCam * m_transform.toMatrix();
SHADER(0)->setUniformValue(m_shaderPrograms[0].m_uniformIDs[4], 0); // uniform #4 = "shadowMap" -> bind to TEXTURE0
}
catch (OpenGLException & ex) {
throw OpenGLException(ex, "OpenGL initialization failed.", FUNC_ID);
}
}
void SceneView::resizeGL(int width, int height) {
// the projection matrix need to be updated only for window size changes
m_projection.setToIdentity();
// create projection matrix, i.e. camera lens
m_projection.perspective(
/* vertical angle */ 45.0f,
/* aspect ratio */ width / float(height),
/* near */ 0.1f,
/* far */ 1000.0f
);
// Mind: to not use 0.0 for near plane, otherwise depth buffering and depth testing won't work!
// update cached world2view matrix
updateWorld2ViewMatrix();
}
void SceneView::paintGL() {
m_cpuTimer.start();
if (((DebugApplication *)qApp)->m_aboutToTerminate)
return;
// process input, i.e. check if any keys have been pressed
if (m_inputEventReceived)
processInput();
m_gpuTimers.reset();
m_gpuTimers.recordSample(); // render shadow map
// *** render shadow map ***
glViewport(0, 0, SHADOW_WIDTH, SHADOW_HEIGHT);
glBindFramebuffer(GL_FRAMEBUFFER, depthMapFBO);
glClear(GL_DEPTH_BUFFER_BIT);
SHADER(2)->bind();
SHADER(2)->setUniformValue(m_shaderPrograms[2].m_uniformIDs[0], m_lightSpaceMatrix);
m_gpuTimers.recordSample(); // render main scene
m_boxObject.render();
SHADER(2)->release();
glBindFramebuffer(GL_FRAMEBUFFER, 0);
m_gpuTimers.recordSample(); // render main scene
const qreal retinaScale = devicePixelRatio(); // needed for Macs with retina display
glViewport(0, 0, width() * retinaScale, height() * retinaScale);
qDebug() << "SceneView::paintGL(): Rendering to:" << width()* retinaScale << "x" << height()* retinaScale;
// set the background color = clear color
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// bind depthmap to TEXTURE0 -> maps to "shadowMap" texture in shader
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, depthMap);
//#define RENDER_DEPTHMAP
#ifdef RENDER_DEPTHMAP
glDisable(GL_DEPTH_TEST); // disable depth test so screen-space quad isn't discarded due to depth test.
// // clear all relevant buffers
glClearColor(1.0f, 1.0f, 1.0f, 1.0f); // set clear color to white (not really necessery actually, since we won't be able to see behind the quad anyways)
glClear(GL_COLOR_BUFFER_BIT);
SHADER(3)->bind();
// m_gpuTimers.recordSample(); // render framebuffer
m_texture2ScreenObject.render();
glEnable(GL_DEPTH_TEST); // disable depth test so screen-space quad isn't discarded due to depth test.
#else
// *** render boxes ***
SHADER(0)->bind();
SHADER(0)->setUniformValue(m_shaderPrograms[0].m_uniformIDs[0], m_worldToView);
SHADER(0)->setUniformValue(m_shaderPrograms[0].m_uniformIDs[1], m_lightSpaceMatrix);
SHADER(0)->setUniformValue(m_shaderPrograms[0].m_uniformIDs[2], LIGHT_POS); // lightPos
SHADER(0)->setUniformValue(m_shaderPrograms[0].m_uniformIDs[3], m_camera.translation()); // cameraPos
m_gpuTimers.recordSample(); // render main scene
m_boxObject.render();
SHADER(0)->release();
// *** render grid ***
QVector3D backColor(0.1f, 0.15f, 0.3f);
QVector3D gridColor(0.5f, 0.5f, 0.7f);
m_gpuTimers.recordSample(); // render grid
SHADER(1)->bind();
SHADER(1)->setUniformValue(m_shaderPrograms[1].m_uniformIDs[0], m_worldToView);
SHADER(1)->setUniformValue(m_shaderPrograms[1].m_uniformIDs[1], gridColor);
SHADER(1)->setUniformValue(m_shaderPrograms[1].m_uniformIDs[2], backColor);
m_gpuTimers.recordSample(); // render main scene
m_gridObject.render();
SHADER(1)->release();
#endif // RENDER_DEPTHMAP
#if 0
// do some animation stuff
m_transform.rotate(1.0f, QVector3D(0.0f, 0.1f, 0.0f));
updateWorld2ViewMatrix();
renderLater();
#endif
m_gpuTimers.recordSample(); // done painting
checkInput();
QVector<GLuint64> intervals = m_gpuTimers.waitForIntervals();
for (GLuint64 it : intervals)
qDebug() << " " << it*1e-6 << "ms/frame";
QVector<GLuint64> samples = m_gpuTimers.waitForSamples();
qDebug() << "Total render time: " << (samples.back() - samples.front())*1e-6 << "ms/frame";
qint64 elapsedMs = m_cpuTimer.elapsed();
qDebug() << "Total paintGL time: " << elapsedMs << "ms";
}
void SceneView::keyPressEvent(QKeyEvent *event) {
m_keyboardMouseHandler.keyPressEvent(event);
checkInput();
}
void SceneView::keyReleaseEvent(QKeyEvent *event) {
m_keyboardMouseHandler.keyReleaseEvent(event);
checkInput();
}
void SceneView::mousePressEvent(QMouseEvent *event) {
m_keyboardMouseHandler.mousePressEvent(event);
checkInput();
}
void SceneView::mouseReleaseEvent(QMouseEvent *event) {
m_keyboardMouseHandler.mouseReleaseEvent(event);
checkInput();
}
void SceneView::mouseMoveEvent(QMouseEvent * /*event*/) {
checkInput();
}
void SceneView::wheelEvent(QWheelEvent *event) {
m_keyboardMouseHandler.wheelEvent(event);
checkInput();
}
void SceneView::checkInput() {
// this function is called whenever _any_ key/mouse event was issued
// we test, if the current state of the key handler requires a scene update
// (camera movement) and if so, we just set a flag to do that upon next repaint
// and we schedule a repaint
// trigger key held?
if (m_keyboardMouseHandler.buttonDown(Qt::RightButton)) {
// any of the interesting keys held?
if (m_keyboardMouseHandler.keyDown(Qt::Key_W) ||
m_keyboardMouseHandler.keyDown(Qt::Key_A) ||
m_keyboardMouseHandler.keyDown(Qt::Key_S) ||
m_keyboardMouseHandler.keyDown(Qt::Key_D) ||
m_keyboardMouseHandler.keyDown(Qt::Key_Q) ||
m_keyboardMouseHandler.keyDown(Qt::Key_E))
{
m_inputEventReceived = true;
// qDebug() << "SceneView::checkInput() inputEventReceived";
renderLater();
return;
}
// has the mouse been moved?
if (m_keyboardMouseHandler.mouseDownPos() != QCursor::pos()) {
m_inputEventReceived = true;
// qDebug() << "SceneView::checkInput() inputEventReceived: " << QCursor::pos() << m_keyboardMouseHandler.mouseDownPos();
renderLater();
return;
}
}
// scroll-wheel turned?
if (m_keyboardMouseHandler.wheelDelta() != 0) {
m_inputEventReceived = true;
renderLater();
return;
}
}
void SceneView::processInput() {
// function must only be called if an input event has been received
Q_ASSERT(m_inputEventReceived);
m_inputEventReceived = false;
// qDebug() << "SceneView::processInput()";
// check for trigger key
if (m_keyboardMouseHandler.buttonDown(Qt::RightButton)) {
// Handle translations
QVector3D translation;
if (m_keyboardMouseHandler.keyDown(Qt::Key_W)) translation += m_camera.forward();
if (m_keyboardMouseHandler.keyDown(Qt::Key_S)) translation -= m_camera.forward();
if (m_keyboardMouseHandler.keyDown(Qt::Key_A)) translation -= m_camera.right();
if (m_keyboardMouseHandler.keyDown(Qt::Key_D)) translation += m_camera.right();
if (m_keyboardMouseHandler.keyDown(Qt::Key_Q)) translation -= m_camera.up();
if (m_keyboardMouseHandler.keyDown(Qt::Key_E)) translation += m_camera.up();
float transSpeed = 0.8f;
if (m_keyboardMouseHandler.keyDown(Qt::Key_Shift))
transSpeed = 0.1f;
m_camera.translate(transSpeed * translation);
// Handle rotations
// get and reset mouse delta (pass current mouse cursor position)
QPoint mouseDelta = m_keyboardMouseHandler.resetMouseDelta(QCursor::pos()); // resets the internal position
static const float rotatationSpeed = 0.4f;
const QVector3D LocalUp(0.0f, 1.0f, 0.0f); // same as in Camera::up()
m_camera.rotate(-rotatationSpeed * mouseDelta.x(), LocalUp);
m_camera.rotate(-rotatationSpeed * mouseDelta.y(), m_camera.right());
// finally, reset "WasPressed" key states
m_keyboardMouseHandler.clearWasPressedKeyStates();
}
int wheelDelta = m_keyboardMouseHandler.resetWheelDelta();
if (wheelDelta != 0) {
float transSpeed = 8.f;
if (m_keyboardMouseHandler.keyDown(Qt::Key_Shift))
transSpeed = 0.8f;
m_camera.translate(wheelDelta * transSpeed * m_camera.forward());
}
updateWorld2ViewMatrix();
// not need to request update here, since we are called from paint anyway
}
void SceneView::updateWorld2ViewMatrix() {
// transformation steps:
// model space -> transform -> world space
// world space -> camera/eye -> camera view
// camera view -> projection -> normalized device coordinates (NDC)
m_worldToView = m_projection * m_camera.toMatrix() * m_transform.toMatrix();
}
|
/*
* This Code Was Created By Brett Porter For NeHe Productions 2000
* Visit NeHe Productions At http://nehe.gamedev.net
*
* Visit Brett Porter's Web Page at
* http://www.geocities.com/brettporter/programming
*/
#include <windows.h> // Header File For Windows
#include <stdio.h> // Header File For Standard Input/Output
#include <gl\gl.h> // Header File For The OpenGL32 Library
#include <gl\glu.h> // Header File For The GLu32 Library
#include <gl\glaux.h> // Header File For The Glaux Library
#include "MilkshapeModel.h" // Header File For Milkshape File
#pragma comment( lib, "opengl32.lib" ) // Search For OpenGL32.lib While Linking ( NEW )
#pragma comment( lib, "glu32.lib" ) // Search For GLu32.lib While Linking ( NEW )
#pragma comment( lib, "glaux.lib" ) // Search For GLaux.lib While Linking ( NEW )
HDC hDC=NULL; // Private GDI Device Context
HGLRC hRC=NULL; // Permanent Rendering Context
HWND hWnd=NULL; // Holds Our Window Handle
HINSTANCE hInstance; // Holds The Instance Of The Application
Model *pModel = NULL; // Holds The Model Data
bool keys[256]; // Array Used For The Keyboard Routine
bool active=TRUE; // Window Active Flag Set To TRUE By Default
bool fullscreen=TRUE; // Fullscreen Flag Set To Fullscreen Mode By Default
GLfloat yrot=0.0f; // Y Rotation
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); // Declaration For WndProc
AUX_RGBImageRec *LoadBMP(const char *Filename) // Loads A Bitmap Image
{
FILE *File=NULL; // File Handle
if (!Filename) // Make Sure A Filename Was Given
{
return NULL; // If Not Return NULL
}
File=fopen(Filename,"r"); // Check To See If The File Exists
if (File) // Does The File Exist?
{
fclose(File); // Close The Handle
return auxDIBImageLoad(Filename); // Load The Bitmap And Return A Pointer
}
return NULL; // If Load Failed Return NULL
}
GLuint LoadGLTexture( const char *filename ) // Load Bitmaps And Convert To Textures
{
AUX_RGBImageRec *pImage; // Create Storage Space For The Texture
GLuint texture = 0; // Texture ID
pImage = LoadBMP( filename ); // Loads The Bitmap Specified By filename
// Load The Bitmap, Check For Errors, If Bitmap's Not Found Quit
if ( pImage != NULL && pImage->data != NULL ) // If Texture Image Exists
{
glGenTextures(1, &texture); // Create The Texture
// Typical Texture Generation Using Data From The Bitmap
glBindTexture(GL_TEXTURE_2D, texture);
glTexImage2D(GL_TEXTURE_2D, 0, 3, pImage->sizeX, pImage->sizeY, 0, GL_RGB, GL_UNSIGNED_BYTE, pImage->data);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
free(pImage->data); // Free The Texture Image Memory
free(pImage); // Free The Image Structure
}
return texture; // Return The Status
}
GLvoid ReSizeGLScene(GLsizei width, GLsizei height) // Resize And Initialize The GL Window
{
if (height==0) // Prevent A Divide By Zero By
{
height=1; // Making Height Equal One
}
glViewport(0,0,width,height); // Reset The Current Viewport
glMatrixMode(GL_PROJECTION); // Select The Projection Matrix
glLoadIdentity(); // Reset The Projection Matrix
// Calculate The Aspect Ratio Of The Window
gluPerspective(45.0f,(GLfloat)width/(GLfloat)height,1.0f,1000.0f); // View Depth of 1000
glMatrixMode(GL_MODELVIEW); // Select The Modelview Matrix
glLoadIdentity(); // Reset The Modelview Matrix
}
int InitGL(GLvoid) // All Setup For OpenGL Goes Here
{
pModel->reloadTextures(); // Loads Model Textures
glEnable(GL_TEXTURE_2D); // Enable Texture Mapping ( NEW )
glShadeModel(GL_SMOOTH); // Enable Smooth Shading
glClearColor(0.0f, 0.0f, 0.0f, 0.5f); // Black Background
glClearDepth(1.0f); // Depth Buffer Setup
glEnable(GL_DEPTH_TEST); // Enables Depth Testing
glDepthFunc(GL_LEQUAL); // The Type Of Depth Testing To Do
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); // Really Nice Perspective Calculations
return TRUE; // Initialization Went OK
}
int DrawGLScene(GLvoid) // Here's Where We Do All The Drawing
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear The Screen And The Depth Buffer
glLoadIdentity(); // Reset The Modelview Matrix
gluLookAt( 75, 75, 75, 0, 0, 0, 0, 1, 0 ); // (3) Eye Postion (3) Center Point (3) Y-Axis Up Vector
glRotatef(yrot,0.0f,1.0f,0.0f); // Rotate On The Y-Axis By yrot
pModel->draw(); // Draw The Model
yrot+=1.0f; // Increase yrot By One
return TRUE; // Keep Going
}
GLvoid KillGLWindow(GLvoid) // Properly Kill The Window
{
if (fullscreen) // Are We In Fullscreen Mode?
{
ChangeDisplaySettings(NULL,0); // If So Switch Back To The Desktop
ShowCursor(TRUE); // Show Mouse Pointer
}
if (hRC) // Do We Have A Rendering Context?
{
if (!wglMakeCurrent(NULL,NULL)) // Are We Able To Release The DC And RC Contexts?
{
MessageBox(NULL,"Release Of DC And RC Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
}
if (!wglDeleteContext(hRC)) // Are We Able To Delete The RC?
{
MessageBox(NULL,"Release Rendering Context Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
}
hRC=NULL; // Set RC To NULL
}
if (hDC && !ReleaseDC(hWnd,hDC)) // Are We Able To Release The DC
{
MessageBox(NULL,"Release Device Context Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
hDC=NULL; // Set DC To NULL
}
if (hWnd && !DestroyWindow(hWnd)) // Are We Able To Destroy The Window?
{
MessageBox(NULL,"Could Not Release hWnd.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
hWnd=NULL; // Set hWnd To NULL
}
if (!UnregisterClass("OpenGL",hInstance)) // Are We Able To Unregister Class
{
MessageBox(NULL,"Could Not Unregister Class.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
hInstance=NULL; // Set hInstance To NULL
}
}
/* This Code Creates Our OpenGL Window. Parameters Are: *
* title - Title To Appear At The Top Of The Window *
* width - Width Of The GL Window Or Fullscreen Mode *
* height - Height Of The GL Window Or Fullscreen Mode *
* bits - Number Of Bits To Use For Color (8/16/24/32) *
* fullscreenflag - Use Fullscreen Mode (TRUE) Or Windowed Mode (FALSE) */
BOOL CreateGLWindow(char* title, int width, int height, int bits, bool fullscreenflag)
{
GLuint PixelFormat; // Holds The Results After Searching For A Match
WNDCLASS wc; // Windows Class Structure
DWORD dwExStyle; // Window Extended Style
DWORD dwStyle; // Window Style
RECT WindowRect; // Grabs Rectangle Upper Left / Lower Right Values
WindowRect.left=(long)0; // Set Left Value To 0
WindowRect.right=(long)width; // Set Right Value To Requested Width
WindowRect.top=(long)0; // Set Top Value To 0
WindowRect.bottom=(long)height; // Set Bottom Value To Requested Height
fullscreen=fullscreenflag; // Set The Global Fullscreen Flag
hInstance = GetModuleHandle(NULL); // Grab An Instance For Our Window
wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; // Redraw On Size, And Own DC For Window.
wc.lpfnWndProc = (WNDPROC) WndProc; // WndProc Handles Messages
wc.cbClsExtra = 0; // No Extra Window Data
wc.cbWndExtra = 0; // No Extra Window Data
wc.hInstance = hInstance; // Set The Instance
wc.hIcon = LoadIcon(NULL, IDI_WINLOGO); // Load The Default Icon
wc.hCursor = LoadCursor(NULL, IDC_ARROW); // Load The Arrow Pointer
wc.hbrBackground = NULL; // No Background Required For GL
wc.lpszMenuName = NULL; // We Don't Want A Menu
wc.lpszClassName = "OpenGL"; // Set The Class Name
if (!RegisterClass(&wc)) // Attempt To Register The Window Class
{
MessageBox(NULL,"Failed To Register The Window Class.","ERROR",MB_OK|MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}
if (fullscreen) // Attempt Fullscreen Mode?
{
DEVMODE dmScreenSettings; // Device Mode
memset(&dmScreenSettings,0,sizeof(dmScreenSettings)); // Makes Sure Memory's Cleared
dmScreenSettings.dmSize=sizeof(dmScreenSettings); // Size Of The Devmode Structure
dmScreenSettings.dmPelsWidth = width; // Selected Screen Width
dmScreenSettings.dmPelsHeight = height; // Selected Screen Height
dmScreenSettings.dmBitsPerPel = bits; // Selected Bits Per Pixel
dmScreenSettings.dmFields=DM_BITSPERPEL|DM_PELSWIDTH|DM_PELSHEIGHT;
// Try To Set Selected Mode And Get Results. NOTE: CDS_FULLSCREEN Gets Rid Of Start Bar.
if (ChangeDisplaySettings(&dmScreenSettings,CDS_FULLSCREEN)!=DISP_CHANGE_SUCCESSFUL)
{
// If The Mode Fails, Offer Two Options. Quit Or Use Windowed Mode.
if (MessageBox(NULL,"The Requested Fullscreen Mode Is Not Supported By\nYour Video Card. Use Windowed Mode Instead?","NeHe GL",MB_YESNO|MB_ICONEXCLAMATION)==IDYES)
{
fullscreen=FALSE; // Windowed Mode Selected. Fullscreen = FALSE
}
else
{
// Pop Up A Message Box Letting User Know The Program Is Closing.
MessageBox(NULL,"Program Will Now Close.","ERROR",MB_OK|MB_ICONSTOP);
return FALSE; // Return FALSE
}
}
}
if (fullscreen) // Are We Still In Fullscreen Mode?
{
dwExStyle=WS_EX_APPWINDOW; // Window Extended Style
dwStyle=WS_POPUP; // Windows Style
ShowCursor(FALSE); // Hide Mouse Pointer
}
else
{
dwExStyle=WS_EX_APPWINDOW | WS_EX_WINDOWEDGE; // Window Extended Style
dwStyle=WS_OVERLAPPEDWINDOW; // Windows Style
}
AdjustWindowRectEx(&WindowRect, dwStyle, FALSE, dwExStyle); // Adjust Window To True Requested Size
// Create The Window
if (!(hWnd=CreateWindowEx( dwExStyle, // Extended Style For The Window
"OpenGL", // Class Name
title, // Window Title
dwStyle | // Defined Window Style
WS_CLIPSIBLINGS | // Required Window Style
WS_CLIPCHILDREN, // Required Window Style
0, 0, // Window Position
WindowRect.right-WindowRect.left, // Calculate Window Width
WindowRect.bottom-WindowRect.top, // Calculate Window Height
NULL, // No Parent Window
NULL, // No Menu
hInstance, // Instance
NULL))) // Dont Pass Anything To WM_CREATE
{
KillGLWindow(); // Reset The Display
MessageBox(NULL,"Window Creation Error.","ERROR",MB_OK|MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}
static PIXELFORMATDESCRIPTOR pfd= // pfd Tells Windows How We Want Things To Be
{
sizeof(PIXELFORMATDESCRIPTOR), // Size Of This Pixel Format Descriptor
1, // Version Number
PFD_DRAW_TO_WINDOW | // Format Must Support Window
PFD_SUPPORT_OPENGL | // Format Must Support OpenGL
PFD_DOUBLEBUFFER, // Must Support Double Buffering
PFD_TYPE_RGBA, // Request An RGBA Format
bits, // Select Our Color Depth
0, 0, 0, 0, 0, 0, // Color Bits Ignored
0, // No Alpha Buffer
0, // Shift Bit Ignored
0, // No Accumulation Buffer
0, 0, 0, 0, // Accumulation Bits Ignored
16, // 16Bit Z-Buffer (Depth Buffer)
0, // No Stencil Buffer
0, // No Auxiliary Buffer
PFD_MAIN_PLANE, // Main Drawing Layer
0, // Reserved
0, 0, 0 // Layer Masks Ignored
};
if (!(hDC=GetDC(hWnd))) // Did We Get A Device Context?
{
KillGLWindow(); // Reset The Display
MessageBox(NULL,"Can't Create A GL Device Context.","ERROR",MB_OK|MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}
if (!(PixelFormat=ChoosePixelFormat(hDC,&pfd))) // Did Windows Find A Matching Pixel Format?
{
KillGLWindow(); // Reset The Display
MessageBox(NULL,"Can't Find A Suitable PixelFormat.","ERROR",MB_OK|MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}
if(!SetPixelFormat(hDC,PixelFormat,&pfd)) // Are We Able To Set The Pixel Format?
{
KillGLWindow(); // Reset The Display
MessageBox(NULL,"Can't Set The PixelFormat.","ERROR",MB_OK|MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}
if (!(hRC=wglCreateContext(hDC))) // Are We Able To Get A Rendering Context?
{
KillGLWindow(); // Reset The Display
MessageBox(NULL,"Can't Create A GL Rendering Context.","ERROR",MB_OK|MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}
if(!wglMakeCurrent(hDC,hRC)) // Try To Activate The Rendering Context
{
KillGLWindow(); // Reset The Display
MessageBox(NULL,"Can't Activate The GL Rendering Context.","ERROR",MB_OK|MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}
ShowWindow(hWnd,SW_SHOW); // Show The Window
SetForegroundWindow(hWnd); // Slightly Higher Priority
SetFocus(hWnd); // Sets Keyboard Focus To The Window
ReSizeGLScene(width, height); // Set Up Our Perspective GL Screen
if (!InitGL()) // Initialize Our Newly Created GL Window
{
KillGLWindow(); // Reset The Display
MessageBox(NULL,"Initialization Failed.","ERROR",MB_OK|MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}
return TRUE; // Success
}
LRESULT CALLBACK WndProc( HWND hWnd, // Handle For This Window
UINT uMsg, // Message For This Window
WPARAM wParam, // Additional Message Information
LPARAM lParam) // Additional Message Information
{
switch (uMsg) // Check For Windows Messages
{
case WM_ACTIVATE: // Watch For Window Activate Message
{
if (!HIWORD(wParam)) // Check Minimization State
{
active=TRUE; // Program Is Active
}
else
{
active=FALSE; // Program Is No Longer Active
}
return 0; // Return To The Message Loop
}
case WM_SYSCOMMAND: // Intercept System Commands
{
switch (wParam) // Check System Calls
{
case SC_SCREENSAVE: // Screensaver Trying To Start?
case SC_MONITORPOWER: // Monitor Trying To Enter Powersave?
return 0; // Prevent From Happening
}
break; // Exit
}
case WM_CLOSE: // Did We Receive A Close Message?
{
PostQuitMessage(0); // Send A Quit Message
return 0; // Jump Back
}
case WM_KEYDOWN: // Is A Key Being Held Down?
{
keys[wParam] = TRUE; // If So, Mark It As TRUE
return 0; // Jump Back
}
case WM_KEYUP: // Has A Key Been Released?
{
keys[wParam] = FALSE; // If So, Mark It As FALSE
return 0; // Jump Back
}
case WM_SIZE: // Resize The OpenGL Window
{
ReSizeGLScene(LOWORD(lParam),HIWORD(lParam)); // LoWord=Width, HiWord=Height
return 0; // Jump Back
}
}
// Pass All Unhandled Messages To DefWindowProc
return DefWindowProc(hWnd,uMsg,wParam,lParam);
}
int WINAPI WinMain( HINSTANCE hInstance, // Instance
HINSTANCE hPrevInstance, // Previous Instance
LPSTR lpCmdLine, // Command Line Parameters
int nCmdShow) // Window Show State
{
MSG msg; // Windows Message Structure
BOOL done=FALSE; // Bool Variable To Exit Loop
pModel = new MilkshapeModel(); // Memory To Hold The Model
if ( pModel->loadModelData( "data/model.ms3d" ) == false ) // Loads The Model And Checks For Errors
{
MessageBox( NULL, "Couldn't load the model data\\model.ms3d", "Error", MB_OK | MB_ICONERROR );
return 0; // If Model Didn't Load Quit
}
// Ask The User Which Screen Mode They Prefer
if (MessageBox(NULL,"Would You Like To Run In Fullscreen Mode?", "Start FullScreen?",MB_YESNO|MB_ICONQUESTION)==IDNO)
{
fullscreen=FALSE; // Windowed Mode
}
// Create Our OpenGL Window
if (!CreateGLWindow("Brett Porter & NeHe's Model Rendering Tutorial",640,480,16,fullscreen))
{
return 0; // Quit If Window Was Not Created
}
while(!done) // Loop That Runs While done=FALSE
{
if (PeekMessage(&msg,NULL,0,0,PM_REMOVE)) // Is There A Message Waiting?
{
if (msg.message==WM_QUIT) // Have We Received A Quit Message?
{
done=TRUE; // If So done=TRUE
}
else // If Not, Deal With Window Messages
{
TranslateMessage(&msg); // Translate The Message
DispatchMessage(&msg); // Dispatch The Message
}
}
else // If There Are No Messages
{
// Draw The Scene. Watch For ESC Key And Quit Messages From DrawGLScene()
if ((active && !DrawGLScene()) || keys[VK_ESCAPE]) // Active? Was There A Quit Received?
{
done=TRUE; // ESC or DrawGLScene Signalled A Quit
}
else // Not Time To Quit, Update Screen
{
SwapBuffers(hDC); // Swap Buffers (Double Buffering)
}
if (keys[VK_F1]) // Is F1 Being Pressed?
{
keys[VK_F1]=FALSE; // If So Make Key FALSE
KillGLWindow(); // Kill Our Current Window
fullscreen=!fullscreen; // Toggle Fullscreen / Windowed Mode
// Recreate Our OpenGL Window
if (!CreateGLWindow("Brett Porter & NeHe's Model Rendering Tutorial",640,480,16,fullscreen))
{
return 0; // Quit If Window Was Not Created
}
}
}
}
// Shutdown
KillGLWindow(); // Kill The Window
return (msg.wParam); // Exit The Program
}
|
#include <thread>
#include <chrono>
#include <numeric>
#include <algorithm>
#include <functional>
#include <vector>
#include <iostream>
#include <iomanip>
#include <cassert>
namespace workspace {
template <
typename Time = std::chrono::microseconds,
typename Clock = std::chrono::high_resolution_clock>
struct perf_timer
{
template <typename F, typename... Args>
static Time duration(F&& f, Args... args)
{
auto const start = Clock::now();
std::invoke(std::forward<F>(f), std::forward<Args>(args)...);
auto const end = Clock::now();
return std::chrono::duration_cast<Time>(end - start);
}
};
unsigned get_num_of_threads() {
return std::thread::hardware_concurrency();
}
template <typename Iter, typename F>
void parallel_map(Iter begin, Iter end, F f) {
auto const size = std::distance(begin, end);
if (size <= 10000) {
std::transform(begin, end, begin, std::forward<F>(f));
return;
}
auto const num_of_threads = get_num_of_threads();
auto const part = size / num_of_threads;
auto last = begin;
std::vector<std::thread> threads{};
for (unsigned i{0}; i < num_of_threads; ++i, begin = last) {
if (num_of_threads - 1 == i)
last = end;
else
std::advance(last, part);
threads.emplace_back([=, &f]{ std::transform(begin, last, begin, std::forward<F>(f)); });
}
for (auto & t : threads)
t.join();
}
template <typename Iter, typename R, typename F>
auto parallel_reduce(Iter begin, Iter end, R init, F op) {
auto const size = std::distance(begin, end);
if (size <= 10000)
return std::accumulate(begin, end, init, std::forward<F>(op));
auto const num_of_threads = get_num_of_threads();
auto const part = size / num_of_threads;
std::vector<std::thread> threads{};
std::vector<R> values(num_of_threads);
auto last = begin;
for (unsigned i{0}; i < num_of_threads; ++i, begin = last) {
if ((num_of_threads - 1) == i)
last = end;
else
std::advance(last, part);
threads.emplace_back([=, &op](R& result) {
result = std::accumulate(begin, last, R{}, std::forward<F>(op)); },
std::ref(values[i]));
}
for (auto & t : threads)
t.join();
return std::accumulate(std::begin(values), std::end(values), init, std::forward<F>(op));
}
void run() {
std::vector<int> sizes {
10000, 100000, 500000,
1000000, 2000000, 5000000,
10000000, 25000000, 50000000
};
std::cout
<< std::right << std::setw(12) << std::setfill(' ') << "size"
<< std::right << std::setw(12) << "s map"
<< std::right << std::setw(12) << "p map"
<< std::right << std::setw(12) << "s fold"
<< std::right << std::setw(12) << "p fold"
<< std::endl;
for (auto const size : sizes) {
std::vector<int> v(size);
std::iota(std::begin(v), std::end(v), 1);
auto v1 = v;
auto s1 = 0LL;
auto const tsm = perf_timer<>::duration([&] {
std::transform(std::begin(v1), std::end(v1), std::begin(v1),
[](int const i) { return i + i; });
});
auto tsf = perf_timer<>::duration([&] {
s1 = std::accumulate(std::begin(v1), std::end(v1), 0LL, std::plus<>());
});
auto v2 = v;
auto s2 = 0LL;
auto tpm = perf_timer<>::duration([&] {
parallel_map(std::begin(v2), std::end(v2), [](int const i) { return i + i; });
});
auto tpf = perf_timer<>::duration([&] {
s2 = parallel_reduce(std::begin(v2), std::end(v2), 0LL, std::plus<>());
});
assert(v1 == v2);
assert(s1 == s2);
std::cout
<< std::right << std::setw(12) << std::setfill(' ') << size
<< std::right << std::setw(12) << std::chrono::duration<double, std::micro>(tsm).count()
<< std::right << std::setw(12) << std::chrono::duration<double, std::micro>(tpm).count()
<< std::right << std::setw(12) << std::chrono::duration<double, std::micro>(tsf).count()
<< std::right << std::setw(12) << std::chrono::duration<double, std::micro>(tpf).count()
<< std::endl;
}
}
} // workspace
int main() {
workspace::run();
return 0;
}
|
#include "openmc/particle_restart.h"
#include "openmc/array.h"
#include "openmc/constants.h"
#include "openmc/hdf5_interface.h"
#include "openmc/mgxs_interface.h"
#include "openmc/nuclide.h"
#include "openmc/output.h"
#include "openmc/particle.h"
#include "openmc/photon.h"
#include "openmc/random_lcg.h"
#include "openmc/settings.h"
#include "openmc/simulation.h"
#include "openmc/tallies/derivative.h"
#include "openmc/tallies/tally.h"
#include "openmc/track_output.h"
#include <algorithm> // for copy
#include <stdexcept>
#include <string>
namespace openmc {
void read_particle_restart(Particle& p, RunMode& previous_run_mode)
{
// Write meessage
write_message(
5, "Loading particle restart file {}", settings::path_particle_restart);
// Open file
hid_t file_id = file_open(settings::path_particle_restart, 'r');
// Read data from file
read_dataset(file_id, "current_batch", simulation::current_batch);
read_dataset(file_id, "generations_per_batch", settings::gen_per_batch);
read_dataset(file_id, "current_generation", simulation::current_gen);
read_dataset(file_id, "n_particles", settings::n_particles);
std::string mode;
read_dataset(file_id, "run_mode", mode);
if (mode == "eigenvalue") {
previous_run_mode = RunMode::EIGENVALUE;
} else if (mode == "fixed source") {
previous_run_mode = RunMode::FIXED_SOURCE;
}
read_dataset(file_id, "id", p.id());
int type;
read_dataset(file_id, "type", type);
p.type() = static_cast<ParticleType>(type);
read_dataset(file_id, "weight", p.wgt());
read_dataset(file_id, "energy", p.E());
read_dataset(file_id, "xyz", p.r());
read_dataset(file_id, "uvw", p.u());
// Set energy group and average energy in multi-group mode
if (!settings::run_CE) {
p.g() = p.E();
p.E() = data::mg.energy_bin_avg_[p.g()];
}
// Set particle last attributes
p.wgt_last() = p.wgt();
p.r_last_current() = p.r();
p.r_last() = p.r();
p.u_last() = p.u();
p.E_last() = p.E();
p.g_last() = p.g();
// Close hdf5 file
file_close(file_id);
}
void run_particle_restart()
{
// Set verbosity high
settings::verbosity = 10;
// Initialize nuclear data (energy limits, log grid, etc.)
initialize_data();
// Initialize the particle to be tracked
Particle p;
// Read in the restart information
RunMode previous_run_mode;
read_particle_restart(p, previous_run_mode);
// write track if that was requested on command line
if (settings::write_all_tracks)
p.write_track() = true;
// Set all tallies to 0 for now (just tracking errors)
model::tallies.clear();
// Compute random number seed
int64_t particle_seed;
switch (previous_run_mode) {
case RunMode::EIGENVALUE:
case RunMode::FIXED_SOURCE:
particle_seed = (simulation::total_gen + overall_generation() - 1) *
settings::n_particles +
p.id();
break;
default:
throw std::runtime_error {
"Unexpected run mode: " +
std::to_string(static_cast<int>(previous_run_mode))};
}
init_particle_seeds(particle_seed, p.seeds());
// Force calculation of cross-sections by setting last energy to zero
if (settings::run_CE) {
p.invalidate_neutron_xs();
}
// Prepare to write out particle track.
if (p.write_track())
add_particle_track(p);
// Transport neutron
transport_history_based_single_particle(p);
// Write output if particle made it
print_particle(p);
}
} // namespace openmc
|
//
// This class stores the name and related
// hardware mapings for a ROC
//
#include "CalibFormats/SiPixelObjects/interface/PixelROCName.h"
#include <string>
#include <iostream>
#include <sstream>
#include <cctype>
#include <cassert>
#include <cstdlib>
using namespace std;
using namespace pos;
PixelROCName::PixelROCName():
id_(0)
{}
PixelROCName::PixelROCName(std::string rocname)
{
parsename(rocname);
}
void PixelROCName::setIdFPix(char np, char LR,int disk,
int blade, int panel, int plaquet, int roc){
std::string mthn = "[PixelROCName::setIdFPix()]\t\t\t\t " ;
id_=0;
//std::cout << __LINE__ << "]\t" << mthn << "subdet: " << subdet << std::endl;
//std::cout << __LINE__ << "]\t" << mthn << "np : " << np << std::endl;
//std::cout << __LINE__ << "]\t" << mthn << "LR : " << LR << std::endl;
//std::cout << __LINE__ << "]\t" << mthn << "disk : " << disk << std::endl;
assert(roc>=0&&roc<10);
if (np=='p') id_=(id_|0x40000000);
//std::cout<< __LINE__ << "]\t" << mthn <<"2 id_="<<std::hex<<id_<<std::dec<<std::endl;
if (LR=='I') id_=(id_|0x20000000);
//std::cout<< __LINE__ << "]\t" << mthn <<"3 id_="<<std::hex<<id_<<std::dec<<std::endl;
id_=(id_|(disk<<12));
//std::cout<< __LINE__ << "]\t" << mthn <<"4 id_="<<std::hex<<id_<<std::dec<<std::endl;
id_=(id_|(blade<<7));
//std::cout<< __LINE__ << "]\t" << mthn <<"5 id_="<<std::hex<<id_<<std::dec<<std::endl;
id_=(id_|((panel-1)<<6));
//std::cout<< __LINE__ << "]\t" << mthn <<"6 id_="<<std::hex<<id_<<std::dec<<std::endl;
id_=(id_|((plaquet-1)<<4));
//std::cout<< __LINE__ << "]\t" << mthn <<"7 id_="<<std::hex<<id_<<std::dec<<std::endl;
id_=(id_|roc);
//std::cout<< __LINE__ << "]\t" << mthn <<"final id_="<<std::hex<<id_<<std::dec<<std::endl;
}
void PixelROCName::setIdBPix(char np, char LR,int sec,
int layer, int ladder, char HF,
int module, int roc){
id_=0;
//std::cout<< __LINE__ << "]\t" << mthn <<"BPix ladder:"<<ladder<<std::endl;
//std::cout<< __LINE__ << "]\t" << mthn <<"np : " << np << std::endl;
//std::cout<< __LINE__ << "]\t" << mthn <<"LR : " << LR << std::endl;
//std::cout<< __LINE__ << "]\t" << mthn <<"disk: " << disk << std::endl;
assert(roc>=0&&roc<16);
id_=0x80000000;
if (np=='p') id_=(id_|0x40000000);
//std::cout<< __LINE__ << "]\t" << mthn <<"2 id_="<<std::hex<<id_<<std::dec<<std::endl;
if (LR=='I') id_=(id_|0x20000000);
//std::cout<< __LINE__ << "]\t" << mthn <<"3 id_="<<std::hex<<id_<<std::dec<<std::endl;
id_=(id_|((sec-1)<<14));
//std::cout<< __LINE__ << "]\t" << mthn <<"4 id_="<<std::hex<<id_<<std::dec<<std::endl;
if (HF=='F') id_=(id_|0x00000800);
id_=(id_|(layer<<12));
//std::cout<< __LINE__ << "]\t" << mthn <<"5 id_="<<std::hex<<id_<<std::dec<<std::endl;
id_=(id_|(ladder<<6));
//std::cout<< __LINE__ << "]\t" << mthn <<"6 id_="<<std::hex<<id_<<std::dec<<std::endl;
id_=(id_|((module-1)<<4));
//std::cout<< __LINE__ << "]\t" << mthn <<"7 id_="<<std::hex<<id_<<std::dec<<std::endl;
id_=(id_|roc);
//std::cout<< __LINE__ << "]\t" << mthn <<"final id_="<<std::hex<<id_<<std::dec<<std::endl;
}
void PixelROCName::check(bool check, const string& name){
static std::string mthn = "[PixelROCName::check()]\t\t\t\t " ;
if (check) return;
cout << __LINE__ << "]\t" << mthn << "ERROR tried to parse string:'"<<name;
cout << "' as a ROC name. Will terminate."<<endl;
::abort();
}
void PixelROCName::parsename(std::string name){
//
// The name should be on the format
//
// FPix_BpR_D1_BLD1_PNL1_PLQ1_ROC1
//
// std::cout << "[PixelROCName::parsename()]\t\tROC name:"<<name<<std::endl;
check(name[0]=='F'||name[0]=='B',name);
if (name[0]=='F'){
check(name[0]=='F',name);
check(name[1]=='P',name);
check(name[2]=='i',name);
check(name[3]=='x',name);
check(name[4]=='_',name);
check(name[5]=='B',name);
check((name[6]=='m')||(name[6]=='p'),name);
char np=name[6];
check((name[7]=='I')||(name[7]=='O'),name);
char LR=name[7];
check(name[8]=='_',name);
check(name[9]=='D',name);
char digit[2]={0,0};
digit[0]=name[10];
int disk=atoi(digit);
check(name[11]=='_',name);
check(name[12]=='B',name);
check(name[13]=='L',name);
check(name[14]=='D',name);
check(std::isdigit(name[15]),name);
digit[0]=name[15];
int bld=atoi(digit);
unsigned int offset=0;
if (std::isdigit(name[16])){
digit[0]=name[16];
bld=10*bld+atoi(digit);
offset++;
}
check(name[16+offset]=='_',name);
check(name[17+offset]=='P',name);
check(name[18+offset]=='N',name);
check(name[19+offset]=='L',name);
check(std::isdigit(name[20+offset]),name);
digit[0]=name[20+offset];
int pnl=atoi(digit);
check(name[21+offset]=='_',name);
check(name[22+offset]=='P',name);
check(name[23+offset]=='L',name);
check(name[24+offset]=='Q',name);
check(std::isdigit(name[25+offset]),name);
digit[0]=name[25+offset];
int plq=atoi(digit);
check(name[26+offset]=='_',name);
check(name[27+offset]=='R',name);
check(name[28+offset]=='O',name);
check(name[29+offset]=='C',name);
check(std::isdigit(name[30+offset]),name);
digit[0]=name[30+offset];
int roc=atoi(digit);
if (name.size()==32+offset){
digit[0]=name[31+offset];
roc=roc*10+atoi(digit);
}
setIdFPix(np,LR,disk,bld,pnl,plq,roc);
}
else{
check(name[0]=='B',name);
check(name[1]=='P',name);
check(name[2]=='i',name);
check(name[3]=='x',name);
check(name[4]=='_',name);
check(name[5]=='B',name);
check((name[6]=='m')||(name[6]=='p'),name);
char np=name[6];
check((name[7]=='I')||(name[7]=='O'),name);
char LR=name[7];
check(name[8]=='_',name);
check(name[9]=='S',name);
check(name[10]=='E',name);
check(name[11]=='C',name);
char digit[2]={0,0};
digit[0]=name[12];
int sec=atoi(digit);
check(name[13]=='_',name);
check(name[14]=='L',name);
check(name[15]=='Y',name);
check(name[16]=='R',name);
check(std::isdigit(name[17]),name);
digit[0]=name[17];
int layer=atoi(digit);
check(name[18]=='_',name);
check(name[19]=='L',name);
check(name[20]=='D',name);
check(name[21]=='R',name);
check(std::isdigit(name[22]),name);
digit[0]=name[22];
int ladder=atoi(digit);
unsigned int offset=0;
if (std::isdigit(name[23])){
offset++;
digit[0]=name[22+offset];
ladder=10*ladder+atoi(digit);
}
check(name[23+offset]=='H'||name[23+offset]=='F',name);
char HF=name[23+offset];
check(name[24+offset]=='_',name);
check(name[25+offset]=='M',name);
check(name[26+offset]=='O',name);
check(name[27+offset]=='D',name);
check(std::isdigit(name[28+offset]),name);
digit[0]=name[28+offset];
int module=atoi(digit);
check(name[29+offset]=='_',name);
check(name[30+offset]=='R',name);
check(name[31+offset]=='O',name);
check(name[32+offset]=='C',name);
check(std::isdigit(name[33+offset]),name);
digit[0]=name[33+offset];
int roc=atoi(digit);
if (name.size()==35+offset){
digit[0]=name[34+offset];
roc=roc*10+atoi(digit);
}
setIdBPix(np,LR,sec,layer,ladder,HF,module,roc);
}
}
PixelROCName::PixelROCName(std::ifstream& s){
std::string tmp;
s >> tmp;
parsename(tmp);
}
std::string PixelROCName::rocname() const{
std::string s;
std::ostringstream s1;
if (detsub()=='F') {
s1<<"FPix";
s1<<"_B";
s1<<mp();
s1<<IO();
s1<<"_D";
s1<<disk();
s1<<"_BLD";
s1<<blade();
s1<<"_PNL";
s1<<panel();
s1<<"_PLQ";
s1<<plaquet();
s1<<"_ROC";
s1<<roc();
assert(roc()>=0&&roc()<=10);
}
else{
s1<<"BPix";
s1<<"_B";
s1<<mp();
s1<<IO();
s1<<"_SEC";
s1<<sec();
s1<<"_LYR";
s1<<layer();
s1<<"_LDR";
s1<<ladder();
s1<<HF();
s1<<"_MOD";
s1<<module();
s1<<"_ROC";
s1<<roc();
assert(roc()>=0&&roc()<=15);
}
s=s1.str();
return s;
}
std::ostream& pos::operator<<(std::ostream& s, const PixelROCName& pixelroc){
// FPix_BpR_D1_BLD1_PNL1_PLQ1_ROC1
s<<pixelroc.rocname();
return s;
}
const PixelROCName& PixelROCName::operator=(const PixelROCName& aROC){
id_=aROC.id_;
return *this;
}
|
#include "FSMContextBase.h"
FSMContextBase::FSMContextBase(UWorld* world) :
mWorld{ world },
mIsTimerOver {true}
{
}
void FSMContextBase::StartTimer(float duration)
{
FTimerDelegate timerDelegate;
timerDelegate.BindLambda([this] {
OnTimeOver();
});
mIsTimerOver = false;
mWorld->GetTimerManager().SetTimer(mTimerHandle, timerDelegate, duration, true);
}
void FSMContextBase::StartTimer(float duration, std::function<void()> callback)
{
FTimerDelegate timerDelegate;
timerDelegate.BindLambda([this, &callback] {
callback();
OnTimeOver();
});
mIsTimerOver = false;
mWorld->GetTimerManager().SetTimer(mTimerHandle, timerDelegate, duration, true);
}
void FSMContextBase::StopTimer()
{
mIsTimerOver = true;
mWorld->GetTimerManager().ClearTimer(mTimerHandle);
}
void FSMContextBase::OnTimeOver()
{
mIsTimerOver = true;
StopTimer();
}
|
/*
* Copyright (c) 2013-2019 Huawei Technologies Co., Ltd. All rights reserved.
* Copyright (c) 2020-2021 Huawei Device Co., Ltd. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. 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.
*
* 3. Neither the name of the copyright holder 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 HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "it_test_signal.h"
#include "signal.h"
static void SigPrint(int sig)
{
printf("%s\n", __FUNCTION__, __LINE__);
return;
}
static void SigPrint1(int sig)
{
printf("%s\n", __FUNCTION__, __LINE__);
return;
}
static int g_sigCount = 0;
static void SigPrint2(int sig)
{
g_sigCount = 1;
printf("%s, count = %d\n", __FUNCTION__, g_sigCount);
return;
}
static void *ThreadSetFunc2(void *arg)
{
void (*retSig)(int);
retSig = signal(SIGALRM, SigPrint2);
ICUNIT_GOTO_NOT_EQUAL(retSig, SIG_ERR, retSig, EXIT);
pthread_exit((void *)NULL);
return NULL;
EXIT:
pthread_exit((void *)-1);
return (void *)-1;
}
static void *ThreadSetDfl(void *arg)
{
void (*retSig)(int);
retSig = signal(SIGALRM, SIG_DFL);
ICUNIT_GOTO_NOT_EQUAL(retSig, SIG_ERR, retSig, EXIT);
pthread_exit((void *)NULL);
return NULL;
EXIT:
pthread_exit((void *)-1);
return (void *)-1;
}
static void *ThreadKill(void *arg)
{
int retValue;
retValue = raise(SIGALRM);
ICUNIT_GOTO_EQUAL(retValue, 0, retValue, EXIT);
pthread_exit((void *)NULL);
return NULL;
EXIT:
pthread_exit((void *)-1);
return (void *)-1;
}
static int TestSigMultiPthread()
{
int fpid;
int status;
int *status1 = nullptr;
int ret;
int count;
pthread_t thread, thread1, thread2;
fpid = fork();
ICUNIT_ASSERT_WITHIN_EQUAL(fpid, 0, UINT_MAX, fpid);
if (fpid == 0) {
ret = pthread_create(&thread1, NULL, ThreadSetDfl, 0);
if (ret != 0) {
exit(ret);
}
ret = pthread_create(&thread2, NULL, ThreadSetFunc2, 0);
if (ret != 0) {
exit(ret);
}
ret = pthread_create(&thread, NULL, ThreadKill, 0);
if (ret != 0) {
exit(ret);
}
pthread_join(thread, (void **)&status1);
if ((int)(intptr_t)status1 != 0) {
exit(-1);
}
pthread_join(thread1, (void **)&status1);
if ((int)(intptr_t)status1 != 0) {
exit(-1);
}
pthread_join(thread2, (void **)&status1);
if ((int)(intptr_t)status1 != 0) {
exit(-1);
}
if (g_sigCount != 1) {
exit(g_sigCount);
}
exit(0);
}
ret = waitpid(fpid, &status, 0);
ICUNIT_ASSERT_EQUAL(ret, fpid, ret);
ICUNIT_ASSERT_EQUAL(WEXITSTATUS(status), 0, WEXITSTATUS(status));
return 0;
}
void ItPosixSignal013(void)
{
TEST_ADD_CASE(__FUNCTION__, TestSigMultiPthread, TEST_POSIX, TEST_SIGNAL, TEST_LEVEL0, TEST_FUNCTION);
}
|
#pragma once
#include <string>
#include <vector>
#include <memory>
#include "Plugin.hpp"
#include "PluginLoader_API.h"
class PluginLoader_API PluginLoader {
public:
PluginLoader(void *API_Handle);
void Load(const std::string& ListFile);
bool isEmpty() const;
public:
// Iterators and access methods
std::shared_ptr<Plugin> Get(size_t index);
std::shared_ptr<Plugin> operator[](size_t index);
size_t size() const;
std::vector<std::shared_ptr<Plugin>>::iterator begin();
std::vector<std::shared_ptr<Plugin>>::iterator end();
const std::vector<std::shared_ptr<Plugin>>::const_iterator cbegin();
const std::vector<std::shared_ptr<Plugin>>::const_iterator cend();
private:
std::vector<std::shared_ptr<Plugin>> m_Plugins;
std::vector<std::string> m_ListFiles;
void *m_API_Handle;
std::string m_ListFile;
size_t m_PluginCount;
};
|
/****************************************************************************
*
* (c) 2009-2019 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
*
* QGroundControl is licensed according to the terms in the file
* COPYING.md in the root of the source code directory.
*
* @brief Custom QGCCorePlugin Implementation
* @author Gus Grubba <gus@auterion.com>
*/
#include <QtQml>
#include <QQmlEngine>
#include <QDateTime>
#include "QGCSettings.h"
#include "MAVLinkLogManager.h"
#include "CustomPlugin.h"
#include "CustomQuickInterface.h"
#include "CustomVideoManager.h"
#include "MultiVehicleManager.h"
#include "QGCApplication.h"
#include "SettingsManager.h"
#include "AppMessages.h"
#include "QmlComponentInfo.h"
#include "QGCPalette.h"
QGC_LOGGING_CATEGORY(CustomLog, "CustomLog")
CustomVideoReceiver::CustomVideoReceiver(QObject* parent)
: VideoReceiver(parent)
{
#if defined(QGC_GST_STREAMING)
//-- Shorter RTSP test interval
_restart_time_ms = 1000;
#endif
}
CustomVideoReceiver::~CustomVideoReceiver()
{
}
//-----------------------------------------------------------------------------
static QObject*
customQuickInterfaceSingletonFactory(QQmlEngine*, QJSEngine*)
{
qCDebug(CustomLog) << "Creating CustomQuickInterface instance";
CustomQuickInterface* pIFace = new CustomQuickInterface();
CustomPlugin* pPlug = dynamic_cast<CustomPlugin*>(qgcApp()->toolbox()->corePlugin());
if(pPlug) {
pIFace->init();
} else {
qCritical() << "Error obtaining instance of CustomPlugin";
}
return pIFace;
}
//-----------------------------------------------------------------------------
CustomOptions::CustomOptions(CustomPlugin*, QObject* parent)
: QGCOptions(parent)
{
}
//-----------------------------------------------------------------------------
bool
CustomOptions::showFirmwareUpgrade() const
{
return qgcApp()->toolbox()->corePlugin()->showAdvancedUI();
}
QColor
CustomOptions::toolbarBackgroundLight() const
{
return CustomPlugin::_windowShadeEnabledLightColor;
}
QColor
CustomOptions::toolbarBackgroundDark() const
{
return CustomPlugin::_windowShadeEnabledDarkColor;
}
//-----------------------------------------------------------------------------
CustomPlugin::CustomPlugin(QGCApplication *app, QGCToolbox* toolbox)
: QGCCorePlugin(app, toolbox)
{
_pOptions = new CustomOptions(this, this);
_showAdvancedUI = false;
}
//-----------------------------------------------------------------------------
CustomPlugin::~CustomPlugin()
{
}
//-----------------------------------------------------------------------------
void
CustomPlugin::setToolbox(QGCToolbox* toolbox)
{
QGCCorePlugin::setToolbox(toolbox);
qmlRegisterSingletonType<CustomQuickInterface>("CustomQuickInterface", 1, 0, "CustomQuickInterface", customQuickInterfaceSingletonFactory);
//-- Disable automatic logging
toolbox->mavlinkLogManager()->setEnableAutoStart(false);
toolbox->mavlinkLogManager()->setEnableAutoUpload(false);
connect(qgcApp()->toolbox()->corePlugin(), &QGCCorePlugin::showAdvancedUIChanged, this, &CustomPlugin::_advancedChanged);
}
//-----------------------------------------------------------------------------
void
CustomPlugin::_advancedChanged(bool changed)
{
//-- We are now in "Advanced Mode" (or not)
emit _pOptions->showFirmwareUpgradeChanged(changed);
}
//-----------------------------------------------------------------------------
void
CustomPlugin::addSettingsEntry(const QString& title,
const char* qmlFile,
const char* iconFile/*= nullptr*/)
{
Q_CHECK_PTR(qmlFile);
// 'this' instance will take ownership on the QmlComponentInfo instance
_customSettingsList.append(QVariant::fromValue(
new QmlComponentInfo(title,
QUrl::fromUserInput(qmlFile),
iconFile == nullptr ? QUrl() : QUrl::fromUserInput(iconFile),
this)));
}
//-----------------------------------------------------------------------------
QVariantList&
CustomPlugin::settingsPages()
{
if(_customSettingsList.isEmpty()) {
addSettingsEntry(tr("General"), "qrc:/qml/GeneralSettings.qml", "qrc:/res/gear-white.svg");
addSettingsEntry(tr("Comm Links"), "qrc:/qml/LinkSettings.qml", "qrc:/res/waves.svg");
addSettingsEntry(tr("Offline Maps"),"qrc:/qml/OfflineMap.qml", "qrc:/res/waves.svg");
#if defined(QGC_GST_MICROHARD_ENABLED)
addSettingsEntry(tr("Microhard"), "qrc:/qml/MicrohardSettings.qml");
#endif
#if defined(QGC_GST_TAISYNC_ENABLED)
addSettingsEntry(tr("Taisync"), "qrc:/qml/TaisyncSettings.qml");
#endif
#if defined(QGC_AIRMAP_ENABLED)
addSettingsEntry(tr("AirMap"), "qrc:/qml/AirmapSettings.qml");
#endif
addSettingsEntry(tr("MAVLink"), "qrc:/qml/MavlinkSettings.qml", " qrc:/res/waves.svg");
addSettingsEntry(tr("Console"), "qrc:/qml/QGroundControl/Controls/AppMessages.qml");
#if defined(QGC_ENABLE_QZXING)
addSettingsEntry(tr("Barcode Test"),"qrc:/custom/BarcodeReader.qml");
#endif
#if defined(QT_DEBUG)
//-- These are always present on Debug builds
addSettingsEntry(tr("Mock Link"), "qrc:/qml/MockLink.qml");
addSettingsEntry(tr("Debug"), "qrc:/qml/DebugWindow.qml");
addSettingsEntry(tr("Palette Test"),"qrc:/qml/QmlTest.qml");
#endif
}
return _customSettingsList;
}
//-----------------------------------------------------------------------------
QGCOptions*
CustomPlugin::options()
{
return _pOptions;
}
//-----------------------------------------------------------------------------
QString
CustomPlugin::brandImageIndoor(void) const
{
return QStringLiteral("/custom/img/void.png");
}
//-----------------------------------------------------------------------------
QString
CustomPlugin::brandImageOutdoor(void) const
{
return QStringLiteral("/custom/img/void.png");
}
//-----------------------------------------------------------------------------
bool
CustomPlugin::overrideSettingsGroupVisibility(QString name)
{
if (name == BrandImageSettings::name) {
return false;
}
return true;
}
//-----------------------------------------------------------------------------
VideoManager*
CustomPlugin::createVideoManager(QGCApplication *app, QGCToolbox *toolbox)
{
return new CustomVideoManager(app, toolbox);
}
//-----------------------------------------------------------------------------
VideoReceiver*
CustomPlugin::createVideoReceiver(QObject* parent)
{
return new CustomVideoReceiver(parent);
}
//-----------------------------------------------------------------------------
QQmlApplicationEngine*
CustomPlugin::createRootWindow(QObject *parent)
{
QQmlApplicationEngine* pEngine = new QQmlApplicationEngine(parent);
pEngine->addImportPath("qrc:/qml");
pEngine->addImportPath("qrc:/Custom/Widgets");
pEngine->addImportPath("qrc:/Custom/Camera");
pEngine->rootContext()->setContextProperty("joystickManager", qgcApp()->toolbox()->joystickManager());
pEngine->rootContext()->setContextProperty("debugMessageModel", AppMessages::getModel());
pEngine->load(QUrl(QStringLiteral("qrc:/qml/MainRootWindow.qml")));
return pEngine;
}
//-----------------------------------------------------------------------------
bool
CustomPlugin::adjustSettingMetaData(const QString& settingsGroup, FactMetaData& metaData)
{
if (settingsGroup == AppSettings::settingsGroup) {
if (metaData.name() == AppSettings::appFontPointSizeName) {
#if defined(Q_OS_LINUX)
int defaultFontPointSize = 11;
metaData.setRawDefaultValue(defaultFontPointSize);
#endif
} else if (metaData.name() == AppSettings::indoorPaletteName) {
QVariant indoorPalette = 1;
metaData.setRawDefaultValue(indoorPalette);
return true;
}
}
return true;
}
const QColor CustomPlugin::_windowShadeEnabledLightColor("#FFFFFF");
const QColor CustomPlugin::_windowShadeEnabledDarkColor("#212529");
//-----------------------------------------------------------------------------
void
CustomPlugin::paletteOverride(QString colorName, QGCPalette::PaletteColorInfo_t& colorInfo)
{
if (colorName == QStringLiteral("window")) {
colorInfo[QGCPalette::Dark][QGCPalette::ColorGroupEnabled] = QColor("#212529");
colorInfo[QGCPalette::Dark][QGCPalette::ColorGroupDisabled] = QColor("#212529");
colorInfo[QGCPalette::Light][QGCPalette::ColorGroupEnabled] = QColor("#ffffff");
colorInfo[QGCPalette::Light][QGCPalette::ColorGroupDisabled] = QColor("#f8f9fa");
}
else if (colorName == QStringLiteral("windowShade")) {
colorInfo[QGCPalette::Dark][QGCPalette::ColorGroupEnabled] = QColor("#343a40");
colorInfo[QGCPalette::Dark][QGCPalette::ColorGroupDisabled] = QColor("#343a40");
colorInfo[QGCPalette::Light][QGCPalette::ColorGroupEnabled] = QColor("#f1f3f5");
colorInfo[QGCPalette::Light][QGCPalette::ColorGroupDisabled] = QColor("#d9d9d9");
}
else if (colorName == QStringLiteral("windowShadeDark")) {
colorInfo[QGCPalette::Dark][QGCPalette::ColorGroupEnabled] = QColor("#1a1c1f");
colorInfo[QGCPalette::Dark][QGCPalette::ColorGroupDisabled] = QColor("#1a1c1f");
colorInfo[QGCPalette::Light][QGCPalette::ColorGroupEnabled] = QColor("#e9ecef");
colorInfo[QGCPalette::Light][QGCPalette::ColorGroupDisabled] = QColor("#bdbdbd");
}
else if (colorName == QStringLiteral("text")) {
colorInfo[QGCPalette::Dark][QGCPalette::ColorGroupEnabled] = QColor("#ffffff");
colorInfo[QGCPalette::Dark][QGCPalette::ColorGroupDisabled] = QColor("#777c89");
colorInfo[QGCPalette::Light][QGCPalette::ColorGroupEnabled] = QColor("#212529");
colorInfo[QGCPalette::Light][QGCPalette::ColorGroupDisabled] = QColor("#9d9d9d");
}
else if (colorName == QStringLiteral("warningText")) {
colorInfo[QGCPalette::Dark][QGCPalette::ColorGroupEnabled] = QColor("#e03131");
colorInfo[QGCPalette::Dark][QGCPalette::ColorGroupDisabled] = QColor("#e03131");
colorInfo[QGCPalette::Light][QGCPalette::ColorGroupEnabled] = QColor("#cc0808");
colorInfo[QGCPalette::Light][QGCPalette::ColorGroupDisabled] = QColor("#cc0808");
}
else if (colorName == QStringLiteral("button")) {
colorInfo[QGCPalette::Dark][QGCPalette::ColorGroupEnabled] = QColor("#495057");
colorInfo[QGCPalette::Dark][QGCPalette::ColorGroupDisabled] = QColor("#495057");
colorInfo[QGCPalette::Light][QGCPalette::ColorGroupEnabled] = QColor("#ffffff");
colorInfo[QGCPalette::Light][QGCPalette::ColorGroupDisabled] = QColor("#ffffff");
}
else if (colorName == QStringLiteral("buttonText")) {
colorInfo[QGCPalette::Dark][QGCPalette::ColorGroupEnabled] = QColor("#ffffff");
colorInfo[QGCPalette::Dark][QGCPalette::ColorGroupDisabled] = QColor("#777c89");
colorInfo[QGCPalette::Light][QGCPalette::ColorGroupEnabled] = QColor("#212529");
colorInfo[QGCPalette::Light][QGCPalette::ColorGroupDisabled] = QColor("#9d9d9d");
}
else if (colorName == QStringLiteral("buttonHighlight")) {
colorInfo[QGCPalette::Dark][QGCPalette::ColorGroupEnabled] = QColor("#07916d");
colorInfo[QGCPalette::Dark][QGCPalette::ColorGroupDisabled] = QColor("#495057");
colorInfo[QGCPalette::Light][QGCPalette::ColorGroupEnabled] = QColor("#aeebd0");
colorInfo[QGCPalette::Light][QGCPalette::ColorGroupDisabled] = QColor("#e4e4e4");
}
else if (colorName == QStringLiteral("buttonHighlightText")) {
colorInfo[QGCPalette::Dark][QGCPalette::ColorGroupEnabled] = QColor("#ffffff");
colorInfo[QGCPalette::Dark][QGCPalette::ColorGroupDisabled] = QColor("#777c89");
colorInfo[QGCPalette::Light][QGCPalette::ColorGroupEnabled] = QColor("#212529");
colorInfo[QGCPalette::Light][QGCPalette::ColorGroupDisabled] = QColor("#2c2c2c");
}
else if (colorName == QStringLiteral("primaryButton")) {
colorInfo[QGCPalette::Dark][QGCPalette::ColorGroupEnabled] = QColor("#12b886");
colorInfo[QGCPalette::Dark][QGCPalette::ColorGroupDisabled] = QColor("#495057");
colorInfo[QGCPalette::Light][QGCPalette::ColorGroupEnabled] = QColor("#aeebd0");
colorInfo[QGCPalette::Light][QGCPalette::ColorGroupDisabled] = QColor("#585858");
}
else if (colorName == QStringLiteral("primaryButtonText")) {
colorInfo[QGCPalette::Dark][QGCPalette::ColorGroupEnabled] = QColor("#ffffff");
colorInfo[QGCPalette::Dark][QGCPalette::ColorGroupDisabled] = QColor("#ffffff");
colorInfo[QGCPalette::Light][QGCPalette::ColorGroupEnabled] = QColor("#212529");
colorInfo[QGCPalette::Light][QGCPalette::ColorGroupDisabled] = QColor("#cad0d0");
}
else if (colorName == QStringLiteral("textField")) {
colorInfo[QGCPalette::Dark][QGCPalette::ColorGroupEnabled] = QColor("#212529");
colorInfo[QGCPalette::Dark][QGCPalette::ColorGroupDisabled] = QColor("#495057");
colorInfo[QGCPalette::Light][QGCPalette::ColorGroupEnabled] = QColor("#f1f3f5");
colorInfo[QGCPalette::Light][QGCPalette::ColorGroupDisabled] = QColor("#ffffff");
}
else if (colorName == QStringLiteral("textFieldText")) {
colorInfo[QGCPalette::Dark][QGCPalette::ColorGroupEnabled] = QColor("#ffffff");
colorInfo[QGCPalette::Dark][QGCPalette::ColorGroupDisabled] = QColor("#777c89");
colorInfo[QGCPalette::Light][QGCPalette::ColorGroupEnabled] = QColor("#212529");
colorInfo[QGCPalette::Light][QGCPalette::ColorGroupDisabled] = QColor("#808080");
}
else if (colorName == QStringLiteral("mapButton")) {
colorInfo[QGCPalette::Dark][QGCPalette::ColorGroupEnabled] = QColor("#000000");
colorInfo[QGCPalette::Dark][QGCPalette::ColorGroupDisabled] = QColor("#585858");
colorInfo[QGCPalette::Light][QGCPalette::ColorGroupEnabled] = QColor("#212529");
colorInfo[QGCPalette::Light][QGCPalette::ColorGroupDisabled] = QColor("#585858");
}
else if (colorName == QStringLiteral("mapButtonHighlight")) {
colorInfo[QGCPalette::Dark][QGCPalette::ColorGroupEnabled] = QColor("#07916d");
colorInfo[QGCPalette::Dark][QGCPalette::ColorGroupDisabled] = QColor("#585858");
colorInfo[QGCPalette::Light][QGCPalette::ColorGroupEnabled] = QColor("#be781c");
colorInfo[QGCPalette::Light][QGCPalette::ColorGroupDisabled] = QColor("#585858");
}
else if (colorName == QStringLiteral("mapIndicator")) {
colorInfo[QGCPalette::Dark][QGCPalette::ColorGroupEnabled] = QColor("#9dda4f");
colorInfo[QGCPalette::Dark][QGCPalette::ColorGroupDisabled] = QColor("#585858");
colorInfo[QGCPalette::Light][QGCPalette::ColorGroupEnabled] = QColor("#be781c");
colorInfo[QGCPalette::Light][QGCPalette::ColorGroupDisabled] = QColor("#585858");
}
else if (colorName == QStringLiteral("mapIndicatorChild")) {
colorInfo[QGCPalette::Dark][QGCPalette::ColorGroupEnabled] = QColor("#527942");
colorInfo[QGCPalette::Dark][QGCPalette::ColorGroupDisabled] = QColor("#585858");
colorInfo[QGCPalette::Light][QGCPalette::ColorGroupEnabled] = QColor("#766043");
colorInfo[QGCPalette::Light][QGCPalette::ColorGroupDisabled] = QColor("#585858");
}
else if (colorName == QStringLiteral("colorGreen")) {
colorInfo[QGCPalette::Dark][QGCPalette::ColorGroupEnabled] = QColor("#27bf89");
colorInfo[QGCPalette::Dark][QGCPalette::ColorGroupDisabled] = QColor("#0ca678");
colorInfo[QGCPalette::Light][QGCPalette::ColorGroupEnabled] = QColor("#009431");
colorInfo[QGCPalette::Light][QGCPalette::ColorGroupDisabled] = QColor("#009431");
}
else if (colorName == QStringLiteral("colorOrange")) {
colorInfo[QGCPalette::Dark][QGCPalette::ColorGroupEnabled] = QColor("#f7b24a");
colorInfo[QGCPalette::Dark][QGCPalette::ColorGroupDisabled] = QColor("#f6921e");
colorInfo[QGCPalette::Light][QGCPalette::ColorGroupEnabled] = QColor("#b95604");
colorInfo[QGCPalette::Light][QGCPalette::ColorGroupDisabled] = QColor("#b95604");
}
else if (colorName == QStringLiteral("colorRed")) {
colorInfo[QGCPalette::Dark][QGCPalette::ColorGroupEnabled] = QColor("#e1544c");
colorInfo[QGCPalette::Dark][QGCPalette::ColorGroupDisabled] = QColor("#e03131");
colorInfo[QGCPalette::Light][QGCPalette::ColorGroupEnabled] = QColor("#ed3939");
colorInfo[QGCPalette::Light][QGCPalette::ColorGroupDisabled] = QColor("#ed3939");
}
else if (colorName == QStringLiteral("colorGrey")) {
colorInfo[QGCPalette::Dark][QGCPalette::ColorGroupEnabled] = QColor("#8b90a0");
colorInfo[QGCPalette::Dark][QGCPalette::ColorGroupDisabled] = QColor("#8b90a0");
colorInfo[QGCPalette::Light][QGCPalette::ColorGroupEnabled] = QColor("#808080");
colorInfo[QGCPalette::Light][QGCPalette::ColorGroupDisabled] = QColor("#808080");
}
else if (colorName == QStringLiteral("colorBlue")) {
colorInfo[QGCPalette::Dark][QGCPalette::ColorGroupEnabled] = QColor("#228be6");
colorInfo[QGCPalette::Dark][QGCPalette::ColorGroupDisabled] = QColor("#228be6");
colorInfo[QGCPalette::Light][QGCPalette::ColorGroupEnabled] = QColor("#1a72ff");
colorInfo[QGCPalette::Light][QGCPalette::ColorGroupDisabled] = QColor("#1a72ff");
}
else if (colorName == QStringLiteral("alertBackground")) {
colorInfo[QGCPalette::Dark][QGCPalette::ColorGroupEnabled] = QColor("#d4b106");
colorInfo[QGCPalette::Dark][QGCPalette::ColorGroupDisabled] = QColor("#d4b106");
colorInfo[QGCPalette::Light][QGCPalette::ColorGroupEnabled] = QColor("#fffb8f");
colorInfo[QGCPalette::Light][QGCPalette::ColorGroupDisabled] = QColor("#b45d48");
}
else if (colorName == QStringLiteral("alertBorder")) {
colorInfo[QGCPalette::Dark][QGCPalette::ColorGroupEnabled] = QColor("#876800");
colorInfo[QGCPalette::Dark][QGCPalette::ColorGroupDisabled] = QColor("#876800");
colorInfo[QGCPalette::Light][QGCPalette::ColorGroupEnabled] = QColor("#808080");
colorInfo[QGCPalette::Light][QGCPalette::ColorGroupDisabled] = QColor("#808080");
}
else if (colorName == QStringLiteral("alertText")) {
colorInfo[QGCPalette::Dark][QGCPalette::ColorGroupEnabled] = QColor("#000000");
colorInfo[QGCPalette::Dark][QGCPalette::ColorGroupDisabled] = QColor("#fff9ed");
colorInfo[QGCPalette::Light][QGCPalette::ColorGroupEnabled] = QColor("#212529");
colorInfo[QGCPalette::Light][QGCPalette::ColorGroupDisabled] = QColor("#fff9ed");
}
else if (colorName == QStringLiteral("missionItemEditor")) {
colorInfo[QGCPalette::Dark][QGCPalette::ColorGroupEnabled] = QColor("#212529");
colorInfo[QGCPalette::Dark][QGCPalette::ColorGroupDisabled] = QColor("#0b1420");
colorInfo[QGCPalette::Light][QGCPalette::ColorGroupEnabled] = QColor("#ffffff");
colorInfo[QGCPalette::Light][QGCPalette::ColorGroupDisabled] = QColor("#585858");
}
else if (colorName == QStringLiteral("hoverColor")) {
colorInfo[QGCPalette::Dark][QGCPalette::ColorGroupEnabled] = QColor("#07916d");
colorInfo[QGCPalette::Dark][QGCPalette::ColorGroupDisabled] = QColor("#33c494");
colorInfo[QGCPalette::Light][QGCPalette::ColorGroupEnabled] = QColor("#aeebd0");
colorInfo[QGCPalette::Light][QGCPalette::ColorGroupDisabled] = QColor("#464f5a");
}
else if (colorName == QStringLiteral("mapWidgetBorderLight")) {
colorInfo[QGCPalette::Dark][QGCPalette::ColorGroupEnabled] = QColor("#ffffff");
colorInfo[QGCPalette::Dark][QGCPalette::ColorGroupDisabled] = QColor("#ffffff");
colorInfo[QGCPalette::Light][QGCPalette::ColorGroupEnabled] = QColor("#f1f3f5");
colorInfo[QGCPalette::Light][QGCPalette::ColorGroupDisabled] = QColor("#ffffff");
}
else if (colorName == QStringLiteral("mapWidgetBorderDark")) {
colorInfo[QGCPalette::Dark][QGCPalette::ColorGroupEnabled] = QColor("#000000");
colorInfo[QGCPalette::Dark][QGCPalette::ColorGroupDisabled] = QColor("#000000");
colorInfo[QGCPalette::Light][QGCPalette::ColorGroupEnabled] = QColor("#212529");
colorInfo[QGCPalette::Light][QGCPalette::ColorGroupDisabled] = QColor("#000000");
}
else if (colorName == QStringLiteral("brandingPurple")) {
colorInfo[QGCPalette::Dark][QGCPalette::ColorGroupEnabled] = QColor("#4a2c6d");
colorInfo[QGCPalette::Dark][QGCPalette::ColorGroupDisabled] = QColor("#4a2c6d");
colorInfo[QGCPalette::Light][QGCPalette::ColorGroupEnabled] = QColor("#4a2c6d");
colorInfo[QGCPalette::Light][QGCPalette::ColorGroupDisabled] = QColor("#4a2c6d");
}
else if (colorName == QStringLiteral("brandingBlue")) {
colorInfo[QGCPalette::Dark][QGCPalette::ColorGroupEnabled] = QColor("#6045c5");
colorInfo[QGCPalette::Dark][QGCPalette::ColorGroupDisabled] = QColor("#48d6ff");
colorInfo[QGCPalette::Light][QGCPalette::ColorGroupEnabled] = QColor("#6045c5");
colorInfo[QGCPalette::Light][QGCPalette::ColorGroupDisabled] = QColor("#48d6ff");
}
}
|
/*
* ModSecurity, http://www.modsecurity.org/
* Copyright (c) 2015 - 2021 Trustwave Holdings, Inc. (http://www.trustwave.com/)
*
* 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
*
* If any of the files related to licensing are missing or if you have any
* other questions related to licensing please contact Trustwave Holdings, Inc.
* directly using the email address security@modsecurity.org.
*
*/
#include "src/operators/rx_global.h"
#include <string>
#include <list>
#include <memory>
#include "src/operators/operator.h"
#include "modsecurity/rule.h"
#include "modsecurity/rule_message.h"
namespace modsecurity {
namespace operators {
bool RxGlobal::init(const std::string &arg, std::string *error) {
if (m_string->m_containsMacro == false) {
m_re = new Regex(m_param);
}
return true;
}
bool RxGlobal::evaluate(Transaction *transaction, RuleWithActions *rule,
const std::string& input, std::shared_ptr<RuleMessage> ruleMessage) {
Regex *re;
if (m_param.empty() && !m_string->m_containsMacro) {
return true;
}
if (m_string->m_containsMacro) {
std::string eparam(m_string->evaluate(transaction));
re = new Regex(eparam);
} else {
re = m_re;
}
std::vector<Utils::SMatchCapture> captures;
re->searchGlobal(input, captures);
if (rule && rule->hasCaptureAction() && transaction) {
for (const Utils::SMatchCapture& capture : captures) {
const std::string capture_substring(input.substr(capture.m_offset,capture.m_length));
transaction->m_collections.m_tx_collection->storeOrUpdateFirst(
std::to_string(capture.m_group), capture_substring);
ms_dbg_a(transaction, 7, "Added regex subexpression TX." +
std::to_string(capture.m_group) + ": " + capture_substring);
transaction->m_matched.push_back(capture_substring);
}
}
for (const auto & capture : captures) {
logOffset(ruleMessage, capture.m_offset, capture.m_length);
}
if (m_string->m_containsMacro) {
delete re;
}
if (captures.size() > 0) {
return true;
}
return false;
}
} // namespace operators
} // namespace modsecurity
|
#include "bank_a.h"
#include <iostream>
BankA::BankA(const string &dep_name,
const string &a_num,
double bal)
{
this->dep_name = dep_name;
this->a_num = a_num;
this->bal = bal;
}
void BankA::show()
{
using namespace std;
cout << this->dep_name << " (" << this->a_num << ") Balance: " << this->bal << endl;
}
void BankA::deposit(double bal)
{
this->bal += bal;
}
void BankA::withdraw(double bal)
{
this->bal -= bal;
}
|
/****************************************************************************************
* @author: kzvd4729 created: Nov/19/2017 20:01
* solution_verdict: Accepted language: GNU C++14
* run_time: 15 ms memory_used: 1900 KB
* problem: https://codeforces.com/contest/894/problem/A
****************************************************************************************/
#include<bits/stdc++.h>
#define long long long
using namespace std;
string s;
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin>>s;
long l=s.size();
long ans=0;
for(long i=0;i<l;i++)
{
for(long j=i+1;j<l;j++)
{
for(long k=j+1;k<l;k++)
{
if(s[i]=='Q'&&s[k]=='Q'&&s[j]=='A')ans++;
}
}
}
cout<<ans<<endl;
return 0;
}
|
// Copyright (C) 2018-2022 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#pragma once
#include "openvino/op/ops.hpp"
namespace ov {
namespace opset5 {
#define _OPENVINO_OP_REG(a, b) using b::a;
#include "openvino/opsets/opset5_tbl.hpp"
#undef _OPENVINO_OP_REG
} // namespace opset5
} // namespace ov
|
//---------------------------------------------------------------------------
// Greenplum Database
// Copyright (C) 2017 Pivotal, Inc.
//
// Implementation of DXL Part list null test expression
#include "naucrates/dxl/operators/CDXLScalarPartListNullTest.h"
#include "naucrates/dxl/operators/CDXLNode.h"
#include "naucrates/dxl/xml/CXMLSerializer.h"
#include "gpopt/mdcache/CMDAccessor.h"
using namespace gpopt;
using namespace gpmd;
using namespace gpos;
using namespace gpdxl;
// Ctor
CDXLScalarPartListNullTest::CDXLScalarPartListNullTest
(
IMemoryPool *mp,
ULONG partitioning_level,
BOOL is_null
)
:
CDXLScalar(mp),
m_partitioning_level(partitioning_level),
m_is_null(is_null)
{
}
// Operator type
Edxlopid
CDXLScalarPartListNullTest::GetDXLOperator() const
{
return EdxlopScalarPartListNullTest;
}
// Operator name
const CWStringConst *
CDXLScalarPartListNullTest::GetOpNameStr() const
{
return CDXLTokens::GetDXLTokenStr(EdxltokenScalarPartListNullTest);
}
// Serialize operator in DXL format
void
CDXLScalarPartListNullTest::SerializeToDXL
(
CXMLSerializer *xml_serializer,
const CDXLNode * // dxlnode
)
const
{
const CWStringConst *element_name = GetOpNameStr();
xml_serializer->OpenElement(CDXLTokens::GetDXLTokenStr(EdxltokenNamespacePrefix), element_name);
xml_serializer->AddAttribute(CDXLTokens::GetDXLTokenStr(EdxltokenPartLevel), m_partitioning_level);
xml_serializer->AddAttribute(CDXLTokens::GetDXLTokenStr(EdxltokenScalarIsNull), m_is_null);
xml_serializer->CloseElement(CDXLTokens::GetDXLTokenStr(EdxltokenNamespacePrefix), element_name);
}
// partitioning level
ULONG
CDXLScalarPartListNullTest::GetPartitioningLevel() const
{
return m_partitioning_level;
}
// Null Test type (true for 'is null', false for 'is not null')
BOOL
CDXLScalarPartListNullTest::IsNull() const
{
return m_is_null;
}
// does the operator return a boolean result
BOOL
CDXLScalarPartListNullTest::HasBoolResult
(
CMDAccessor * //md_accessor
)
const
{
return true;
}
#ifdef GPOS_DEBUG
// Checks whether operator node is well-structured
void
CDXLScalarPartListNullTest::AssertValid
(
const CDXLNode *dxlnode,
BOOL // validate_children
)
const
{
GPOS_ASSERT(0 == dxlnode->Arity());
}
#endif // GPOS_DEBUG
// conversion function
CDXLScalarPartListNullTest *
CDXLScalarPartListNullTest::Cast
(
CDXLOperator *dxl_op
)
{
GPOS_ASSERT(NULL != dxl_op);
GPOS_ASSERT(EdxlopScalarPartListNullTest == dxl_op->GetDXLOperator());
return dynamic_cast<CDXLScalarPartListNullTest*>(dxl_op);
}
// EOF
|
/*************************************************************************
* *
* Open Dynamics Engine, Copyright (C) 2001,2002 Russell L. Smith. *
* All rights reserved. Email: russ@q12.org Web: www.q12.org *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of EITHER: *
* (1) The GNU Lesser General Public License as published by the Free *
* Software Foundation; either version 2.1 of the License, or (at *
* your option) any later version. The text of the GNU Lesser *
* General Public License is included with this library in the *
* file LICENSE.TXT. *
* (2) The BSD-style license that is included with this library in *
* the file LICENSE-BSD.TXT. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files *
* LICENSE.TXT and LICENSE-BSD.TXT for more details. *
* *
*************************************************************************/
//234567890123456789012345678901234567890123456789012345678901234567890123456789
// 1 2 3 4 5 6 7
////////////////////////////////////////////////////////////////////////////////
// This file create unit test for some of the functions found in:
// ode/src/joinst/hinge.cpp
//
//
////////////////////////////////////////////////////////////////////////////////
#include <UnitTest++.h>
#include <ode/ode.h>
#include "../../ode/src/config.h"
#include "../../ode/src/joints/hinge.h"
SUITE (TestdxJointHinge)
{
// The 2 bodies are positionned at (0, 0, 0), with no rotation
// The joint is an Hinge Joint
// Axis is along the X axis
// Anchor at (0, 0, 0)
// ^Y
// |
// |
// |
// |
// |
// Z <---- . (X going out of the page)
struct dxJointHinge_Fixture_B1_and_B2_At_Zero_Axis_Along_X {
dxJointHinge_Fixture_B1_and_B2_At_Zero_Axis_Along_X()
{
wId = dWorldCreate();
bId1 = dBodyCreate (wId);
dBodySetPosition (bId1, 0, 0, 0);
bId2 = dBodyCreate (wId);
dBodySetPosition (bId2, 0, 0, 0);
jId = dJointCreateHinge (wId, 0);
joint = (dxJointHinge*) jId;
dJointAttach (jId, bId1, bId2);
dJointSetHingeAnchor (jId, 0, 0, 0);
axis[0] = 1;
axis[1] = 0;
axis[2] = 0;
}
~dxJointHinge_Fixture_B1_and_B2_At_Zero_Axis_Along_X()
{
dWorldDestroy (wId);
}
dWorldID wId;
dBodyID bId1;
dBodyID bId2;
dJointID jId;
dxJointHinge* joint;
dVector3 axis;
};
// Rotate 2nd body 90deg around X then back to original position
//
// ^ ^ ^
// | | => | <---
// | | |
// B1 B2 B1 B2
//
// Start with a Delta of 90deg
// ^ ^ ^
// | <--- => | |
// | | |
// B1 B2 B1 B2
TEST_FIXTURE (dxJointHinge_Fixture_B1_and_B2_At_Zero_Axis_Along_X,
test_dJointSetHingeAxisOffset_B2_90deg) {
dMatrix3 R;
CHECK_CLOSE (dJointGetHingeAngle (jId), 0.0, 1e-4);
dRFromAxisAndAngle (R, 1, 0, 0, M_PI/2.0);
dBodySetRotation (bId2, R);
CHECK_CLOSE (-M_PI/2.0, dJointGetHingeAngle (jId), 1e-4);
dJointSetHingeAxisOffset (jId, axis[0], axis[1], axis[2], -M_PI/2.0);
CHECK_CLOSE (-M_PI/2.0, dJointGetHingeAngle (jId), 1e-4);
dRFromAxisAndAngle (R, 1, 0, 0, 0);
dBodySetRotation (bId2, R);
CHECK_CLOSE (0.0, dJointGetHingeAngle (jId), 1e-4);
}
// Rotate 2nd body -90deg around X then back to original position
//
// ^ ^ ^
// | | => | --->
// | | |
// B1 B2 B1 B2
//
// Start with a Delta of 90deg
// ^ ^ ^
// | ---> => | |
// | | |
// B1 B2 B1 B2
TEST_FIXTURE (dxJointHinge_Fixture_B1_and_B2_At_Zero_Axis_Along_X,
test_dJointSetHingeAxisOffset_B2_Minus90deg) {
dMatrix3 R;
dJointSetHingeAxis (jId, axis[0], axis[1], axis[2]);
CHECK_CLOSE (dJointGetHingeAngle (jId), 0.0, 1e-4);
dRFromAxisAndAngle (R, 1, 0, 0, -M_PI/2.0);
dBodySetRotation (bId2, R);
CHECK_CLOSE (M_PI/2.0, dJointGetHingeAngle (jId), 1e-4);
dJointSetHingeAxisOffset (jId, axis[0], axis[1], axis[2], M_PI/2.0);
CHECK_CLOSE (M_PI/2.0, dJointGetHingeAngle (jId), 1e-4);
dRFromAxisAndAngle (R, 1, 0, 0, 0);
dBodySetRotation (bId2, R);
CHECK_CLOSE (0.0, dJointGetHingeAngle (jId), 1e-4);
}
// Rotate 1st body 0.23rad around X then back to original position
//
// ^ ^ ^ ^
// | | => \ |
// | | \ |
// B1 B2 B1 B2
//
// Start with a Delta of 0.23rad
// ^ ^ ^ ^
// \ | => | |
// \ | | |
// B1 B2 B1 B2
TEST_FIXTURE (dxJointHinge_Fixture_B1_and_B2_At_Zero_Axis_Along_X,
test_dJointSetHingeAxisOffset_B1_0_23rad) {
dMatrix3 R;
dJointSetHingeAxis (jId, axis[0], axis[1], axis[2]);
CHECK_CLOSE (dJointGetHingeAngle (jId), 0.0, 1e-4);
dRFromAxisAndAngle (R, 1, 0, 0, REAL(0.23) );
dBodySetRotation (bId1, R);
CHECK_CLOSE (REAL(0.23), dJointGetHingeAngle (jId), 1e-4);
dJointSetHingeAxisOffset (jId, axis[0], axis[1], axis[2], REAL(0.23));
CHECK_CLOSE (REAL(0.23), dJointGetHingeAngle (jId), 1e-4);
dRFromAxisAndAngle (R, 1, 0, 0, 0);
dBodySetRotation (bId1, R);
CHECK_CLOSE (0.0, dJointGetHingeAngle (jId), 1e-4);
}
// Rotate 1st body -0.23rad around Z then back to original position
//
// ^ ^ ^ ^
// | | => / |
// | | / |
// B1 B2 B1 B2
//
// Start with a Delta of 0.23rad
// ^ ^ ^ ^
// / | => | |
// / | | |
// B1 B2 B1 B2
TEST_FIXTURE (dxJointHinge_Fixture_B1_and_B2_At_Zero_Axis_Along_X,
test_dJointSetHingeAxisOffset_B1_Minus0_23rad) {
dMatrix3 R;
dJointSetHingeAxis (jId, axis[0], axis[1], axis[2]);
CHECK_CLOSE (dJointGetHingeAngle (jId), 0.0, 1e-4);
dRFromAxisAndAngle (R, 1, 0, 0, -REAL(0.23));
dBodySetRotation (bId1, R);
CHECK_CLOSE (-REAL(0.23), dJointGetHingeAngle (jId), 1e-4);
dJointSetHingeAxisOffset (jId, axis[0], axis[1], axis[2], -REAL(0.23));
CHECK_CLOSE (-REAL(0.23), dJointGetHingeAngle (jId), 1e-4);
dRFromAxisAndAngle (R, 1, 0, 0, 0);
dBodySetRotation (bId1, R);
CHECK_CLOSE (0.0, dJointGetHingeAngle (jId), 1e-4);
}
// The 2 bodies are positionned at (0, 0, 0), with no rotation
// The joint is an Hinge Joint.
// Axis in the inverse direction of the X axis
// Anchor at (0, 0, 0)
// ^Y
// |
// |
// |
// |
// |
// Z <---- x (X going out of the page)
struct dxJointHinge_Fixture_B1_and_B2_At_Zero_Axis_Inverse_of_X {
dxJointHinge_Fixture_B1_and_B2_At_Zero_Axis_Inverse_of_X()
{
wId = dWorldCreate();
bId1 = dBodyCreate (wId);
dBodySetPosition (bId1, 0, -1, 0);
bId2 = dBodyCreate (wId);
dBodySetPosition (bId2, 0, 1, 0);
jId = dJointCreateHinge (wId, 0);
joint = (dxJointHinge*) jId;
dJointAttach (jId, bId1, bId2);
dJointSetHingeAnchor (jId, 0, 0, 0);
axis[0] = -1;
axis[1] = 0;
axis[2] = 0;
}
~dxJointHinge_Fixture_B1_and_B2_At_Zero_Axis_Inverse_of_X()
{
dWorldDestroy (wId);
}
dWorldID wId;
dBodyID bId1;
dBodyID bId2;
dJointID jId;
dxJointHinge* joint;
dVector3 axis;
};
// Rotate 2nd body 90deg around X then back to original position
//
// ^ ^ ^
// | | => | <---
// | | |
// B1 B2 B1 B2
//
// Start with a Delta of 90deg
// ^ ^ ^
// | <--- => | |
// | | |
// B1 B2 B1 B2
TEST_FIXTURE (dxJointHinge_Fixture_B1_and_B2_At_Zero_Axis_Inverse_of_X,
test_dJointSetHingeAxisOffset_B2_90Deg) {
dMatrix3 R;
dJointSetHingeAxis (jId, axis[0], axis[1], axis[2]);
CHECK_CLOSE (dJointGetHingeAngle (jId), 0.0, 1e-4);
dRFromAxisAndAngle (R, 1, 0, 0, M_PI/2.0);
dBodySetRotation (bId2, R);
CHECK_CLOSE (M_PI/2.0, dJointGetHingeAngle (jId), 1e-4);
dJointSetHingeAxisOffset (jId, axis[0], axis[1], axis[2], M_PI/2.0);
CHECK_CLOSE (M_PI/2.0, dJointGetHingeAngle (jId), 1e-4);
dRFromAxisAndAngle (R, 1, 0, 0, 0);
dBodySetRotation (bId2, R);
CHECK_CLOSE (0.0, dJointGetHingeAngle (jId), 1e-4);
}
// Rotate 2nd body -90deg around X then back to original position
//
// ^ ^ ^
// | | => | --->
// | | |
// B1 B2 B1 B2
//
// Start with a Delta of 90deg
// ^ ^ ^
// | ---> => | |
// | | |
// B1 B2 B1 B2
TEST_FIXTURE (dxJointHinge_Fixture_B1_and_B2_At_Zero_Axis_Inverse_of_X,
test_dJointSetHingeAxisOffset_B2_Minus90Deg) {
dMatrix3 R;
dJointSetHingeAxis (jId, axis[0], axis[1], axis[2]);
CHECK_CLOSE (dJointGetHingeAngle (jId), 0.0, 1e-4);
dRFromAxisAndAngle (R, 1, 0, 0, -M_PI/2.0);
dBodySetRotation (bId2, R);
CHECK_CLOSE (-M_PI/2.0, dJointGetHingeAngle (jId), 1e-4);
dJointSetHingeAxisOffset (jId, axis[0], axis[1], axis[2], -M_PI/2.0);
CHECK_CLOSE (-M_PI/2.0, dJointGetHingeAngle (jId), 1e-4);
dRFromAxisAndAngle (R, 1, 0, 0, 0);
dBodySetRotation (bId2, R);
CHECK_CLOSE (0.0, dJointGetHingeAngle (jId), 1e-4);
}
// Rotate 1st body 0.23rad around X then back to original position
//
// ^ ^ ^ ^
// | | => \ |
// | | \ |
// B1 B2 B1 B2
//
// Start with a Delta of 0.23rad
// ^ ^ ^ ^
// \ | => | |
// \ | | |
// B1 B2 B1 B2
TEST_FIXTURE (dxJointHinge_Fixture_B1_and_B2_At_Zero_Axis_Inverse_of_X,
test_dJointSetHingeAxisOffset_B1_0_23rad) {
dMatrix3 R;
dJointSetHingeAxis (jId, axis[0], axis[1], axis[2]);
CHECK_CLOSE (dJointGetHingeAngle (jId), 0.0, 1e-4);
dRFromAxisAndAngle (R, 1, 0, 0, REAL(0.23));
dBodySetRotation (bId1, R);
CHECK_CLOSE (-REAL(0.23), dJointGetHingeAngle (jId), 1e-4);
dJointSetHingeAxisOffset (jId, axis[0], axis[1], axis[2], -REAL(0.23));
CHECK_CLOSE (-REAL(0.23), dJointGetHingeAngle (jId), 1e-4);
dRFromAxisAndAngle (R, 1, 0, 0, 0);
dBodySetRotation (bId1, R);
CHECK_CLOSE (0.0, dJointGetHingeAngle (jId), 1e-4);
}
// Rotate 2nd body -0.23rad around Z then back to original position
//
// ^ ^ ^ ^
// | | => / |
// | | / |
// B1 B2 B1 B2
//
// Start with a Delta of 0.23rad
// ^ ^ ^ ^
// / | => | |
// / | | |
// B1 B2 B1 B2
TEST_FIXTURE (dxJointHinge_Fixture_B1_and_B2_At_Zero_Axis_Inverse_of_X,
test_dJointSetHingeAxisOffset_B1_Minus0_23rad) {
dMatrix3 R;
dJointSetHingeAxis (jId, axis[0], axis[1], axis[2]);
CHECK_CLOSE (dJointGetHingeAngle (jId), 0.0, 1e-4);
dRFromAxisAndAngle (R, 1, 0, 0, -REAL(0.23));
dBodySetRotation (bId1, R);
CHECK_CLOSE (REAL(0.23), dJointGetHingeAngle (jId), 1e-4);
dJointSetHingeAxisOffset (jId, axis[0], axis[1], axis[2], REAL(0.23));
CHECK_CLOSE (REAL(0.23), dJointGetHingeAngle (jId), 1e-4);
dRFromAxisAndAngle (R, 1, 0, 0, 0);
dBodySetRotation (bId1, R);
CHECK_CLOSE (0.0, dJointGetHingeAngle (jId), 1e-4);
}
// Only one body body1 at (0,0,0)
// The joint is an Hinge Joint.
// Axis is along the X axis
// Anchor at (0, 0, 0)
//
// ^Y
// |
// |
// |
// |
// |
// Z <-- X
struct dxJointHinge_Fixture_B1_At_Zero_Axis_Along_X {
dxJointHinge_Fixture_B1_At_Zero_Axis_Along_X()
{
wId = dWorldCreate();
bId1 = dBodyCreate (wId);
dBodySetPosition (bId1, 0, 0, 0);
jId = dJointCreateHinge (wId, 0);
joint = (dxJointHinge*) jId;
dJointAttach (jId, bId1, NULL);
dJointSetHingeAnchor (jId, 0, 0, 0);
axis[0] = 1;
axis[1] = 0;
axis[2] = 0;
}
~dxJointHinge_Fixture_B1_At_Zero_Axis_Along_X()
{
dWorldDestroy (wId);
}
dWorldID wId;
dBodyID bId1;
dJointID jId;
dxJointHinge* joint;
dVector3 axis;
};
// Rotate B1 by 90deg around X then back to original position
//
// ^
// | => <---
// |
// B1 B1
//
// Start with a Delta of 90deg
// ^
// <--- => |
// |
// B1 B1
TEST_FIXTURE (dxJointHinge_Fixture_B1_At_Zero_Axis_Along_X,
test_dJointSetHingeAxisOffset_1Body_B1_90Deg) {
dMatrix3 R;
dJointSetHingeAxis (jId, axis[0], axis[1], axis[2]);
CHECK_CLOSE (dJointGetHingeAngle (jId), 0.0, 1e-4);
dRFromAxisAndAngle (R, 1, 0, 0, M_PI/2.0);
dBodySetRotation (bId1, R);
CHECK_CLOSE (M_PI/2.0, dJointGetHingeAngle (jId), 1e-4);
dJointSetHingeAxisOffset (jId, axis[0], axis[1], axis[2], M_PI/2.0);
CHECK_CLOSE (M_PI/2.0, dJointGetHingeAngle (jId), 1e-4);
dRFromAxisAndAngle (R, 1, 0, 0, 0);
dBodySetRotation (bId1, R);
CHECK_CLOSE (0, dJointGetHingeAngle (jId), 1e-4);
}
// Rotate B1 by -0.23rad around X then back to original position
//
// ^ ^
// | => /
// | /
// B1 B1
//
// Start with a Delta of -0.23rad
// ^ ^
// / => |
// / |
// B1 B1
TEST_FIXTURE (dxJointHinge_Fixture_B1_At_Zero_Axis_Along_X,
test_dJointSetHingeAxisOffset_1Body_B1_Minus0_23rad) {
dMatrix3 R;
dJointSetHingeAxis (jId, axis[0], axis[1], axis[2]);
CHECK_CLOSE (dJointGetHingeAngle (jId), 0.0, 1e-4);
dRFromAxisAndAngle (R, 1, 0, 0, -REAL(0.23));
dBodySetRotation (bId1, R);
CHECK_CLOSE (-REAL(0.23), dJointGetHingeAngle (jId), 1e-4);
dJointSetHingeAxisOffset (jId, axis[0], axis[1], axis[2], -REAL(0.23));
CHECK_CLOSE (-REAL(0.23), dJointGetHingeAngle (jId), 1e-4);
dRFromAxisAndAngle (R, 1, 0, 0, 0);
dBodySetRotation (bId1, R);
CHECK_CLOSE (0, dJointGetHingeAngle (jId), 1e-4);
}
// Only one body body1 at (0,0,0)
// The joint is an Hinge Joint.
// Axis the inverse of the X axis
// Anchor at (0, 0, 0)
//
// ^Y
// |
// |
// |
// |
// |
// Z <-- X
struct dxJointHinge_Fixture_B1_At_Zero_Axis_Inverse_of_X {
dxJointHinge_Fixture_B1_At_Zero_Axis_Inverse_of_X()
{
wId = dWorldCreate();
bId1 = dBodyCreate (wId);
dBodySetPosition (bId1, 0, 0, 0);
jId = dJointCreateHinge (wId, 0);
joint = (dxJointHinge*) jId;
dJointAttach (jId, bId1, NULL);
dJointSetHingeAnchor (jId, 0, 0, 0);
axis[0] = -1;
axis[1] = 0;
axis[2] = 0;
}
~dxJointHinge_Fixture_B1_At_Zero_Axis_Inverse_of_X()
{
dWorldDestroy (wId);
}
dWorldID wId;
dBodyID bId1;
dJointID jId;
dxJointHinge* joint;
dVector3 axis;
};
// Rotate B1 by 90deg around X then back to original position
//
// ^
// | => <---
// |
// B1 B1
//
// Start with a Delta of 90deg
// ^
// <--- => |
// |
// B1 B1
TEST_FIXTURE (dxJointHinge_Fixture_B1_At_Zero_Axis_Inverse_of_X,
test_dJointSetHingeAxisOffset_1Body_B1_90Deg) {
dMatrix3 R;
dJointSetHingeAxis (jId, axis[0], axis[1], axis[2]);
CHECK_CLOSE (dJointGetHingeAngle (jId), 0.0, 1e-4);
dRFromAxisAndAngle (R, 1, 0, 0, M_PI/2.0);
dBodySetRotation (bId1, R);
CHECK_CLOSE (-M_PI/2.0, dJointGetHingeAngle (jId), 1e-4);
dJointSetHingeAxisOffset (jId, axis[0], axis[1], axis[2], -M_PI/2.0);
CHECK_CLOSE (-M_PI/2.0, dJointGetHingeAngle (jId), 1e-4);
dRFromAxisAndAngle (R, 1, 0, 0, 0);
dBodySetRotation (bId1, R);
CHECK_CLOSE (0, dJointGetHingeAngle (jId), 1e-4);
}
// Rotate B1 by -0.23rad around X then back to original position
//
// ^ ^
// | => /
// | /
// B1 B1
//
// Start with a Delta of -0.23rad
// ^ ^
// / => |
// / |
// B1 B1
TEST_FIXTURE (dxJointHinge_Fixture_B1_At_Zero_Axis_Inverse_of_X,
test_dJointSetHingeAxisOffset_1Body_B1_Minus0_23rad) {
dMatrix3 R;
dJointSetHingeAxis (jId, axis[0], axis[1], axis[2]);
CHECK_CLOSE (dJointGetHingeAngle (jId), 0.0, 1e-4);
dRFromAxisAndAngle (R, 1, 0, 0, -REAL(0.23));
dBodySetRotation (bId1, R);
CHECK_CLOSE (REAL(0.23), dJointGetHingeAngle (jId), 1e-4);
dJointSetHingeAxisOffset (jId, axis[0], axis[1], axis[2], REAL(0.23));
CHECK_CLOSE (REAL(0.23), dJointGetHingeAngle (jId), 1e-4);
dRFromAxisAndAngle (R, 1, 0, 0, 0);
dBodySetRotation (bId1, R);
CHECK_CLOSE (0, dJointGetHingeAngle (jId), 1e-4);
}
// Only one body body2 at (0,0,0)
// The joint is an Hinge Joint.
// Axis is along the X axis
// Anchor at (0, 0, 0)
//
// ^Y
// |
// |
// |
// |
// |
// Z <-- X
struct dxJointHinge_Fixture_B2_At_Zero_Axis_Along_X {
dxJointHinge_Fixture_B2_At_Zero_Axis_Along_X()
{
wId = dWorldCreate();
bId2 = dBodyCreate (wId);
dBodySetPosition (bId2, 0, 0, 0);
jId = dJointCreateHinge (wId, 0);
joint = (dxJointHinge*) jId;
dJointAttach (jId, NULL, bId2);
dJointSetHingeAnchor (jId, 0, 0, 0);
axis[0] = 1;
axis[1] = 0;
axis[2] = 0;
}
~dxJointHinge_Fixture_B2_At_Zero_Axis_Along_X()
{
dWorldDestroy (wId);
}
dWorldID wId;
dBodyID bId2;
dJointID jId;
dxJointHinge* joint;
dVector3 axis;
};
// Rotate B2 by 90deg around X then back to original position
//
// ^
// | => <---
// |
// B2 B2
//
// Start with a Delta of 90deg
// ^
// <--- => |
// |
// B2 B2
TEST_FIXTURE (dxJointHinge_Fixture_B2_At_Zero_Axis_Along_X,
test_dJointSetHingeAxisOffset_1Body_B2_90Deg) {
dMatrix3 R;
dJointSetHingeAxis (jId, axis[0], axis[1], axis[2]);
CHECK_CLOSE (dJointGetHingeAngle (jId), 0.0, 1e-4);
dRFromAxisAndAngle (R, 1, 0, 0, M_PI/2.0);
dBodySetRotation (bId2, R);
CHECK_CLOSE (-M_PI/2.0, dJointGetHingeAngle (jId), 1e-4);
dJointSetHingeAxisOffset (jId, axis[0], axis[1], axis[2], -M_PI/2.0);
CHECK_CLOSE (-M_PI/2.0, dJointGetHingeAngle (jId), 1e-4);
dRFromAxisAndAngle (R, 1, 0, 0, 0);
dBodySetRotation (bId2, R);
CHECK_CLOSE (0, dJointGetHingeAngle (jId), 1e-4);
}
// Rotate B2 by -0.23rad around X then back to original position
//
// ^ ^
// | => /
// | /
// B2 B2
//
// Start with a Delta of -0.23rad
// ^ ^
// / => |
// / |
// B2 B2
TEST_FIXTURE (dxJointHinge_Fixture_B2_At_Zero_Axis_Along_X,
test_dJointSetHingeAxisOffset_1Body_B2_Minus0_23rad) {
dMatrix3 R;
dJointSetHingeAxis (jId, axis[0], axis[1], axis[2]);
CHECK_CLOSE (dJointGetHingeAngle (jId), 0.0, 1e-4);
dRFromAxisAndAngle (R, 1, 0, 0, -REAL(0.23));
dBodySetRotation (bId2, R);
CHECK_CLOSE (REAL(0.23), dJointGetHingeAngle (jId), 1e-4);
dJointSetHingeAxisOffset (jId, axis[0], axis[1], axis[2], REAL(0.23));
CHECK_CLOSE (REAL(0.23), dJointGetHingeAngle (jId), 1e-4);
dRFromAxisAndAngle (R, 1, 0, 0, 0);
dBodySetRotation (bId2, R);
CHECK_CLOSE (0, dJointGetHingeAngle (jId), 1e-4);
}
// Create 2 bodies attached by a Hinge joint
// Axis is along the X axis (Default value
// Anchor at (0, 0, 0) (Default value)
//
// ^Y
// |
// * Body2
// |
// |
// Body1 |
// * Z-------->
struct dxJointHinge_Test_Initialization {
dxJointHinge_Test_Initialization()
{
wId = dWorldCreate();
// Remove gravity to have the only force be the force of the joint
dWorldSetGravity(wId, 0,0,0);
for (int j=0; j<2; ++j) {
bId[j][0] = dBodyCreate (wId);
dBodySetPosition (bId[j][0], -1, -2, -3);
bId[j][1] = dBodyCreate (wId);
dBodySetPosition (bId[j][1], 11, 22, 33);
dMatrix3 R;
dVector3 axis; // Random axis
axis[0] = REAL(0.53);
axis[1] = -REAL(0.71);
axis[2] = REAL(0.43);
dNormalize3(axis);
dRFromAxisAndAngle (R, axis[0], axis[1], axis[2],
REAL(0.47123)); // 27deg
dBodySetRotation (bId[j][0], R);
axis[0] = REAL(1.2);
axis[1] = REAL(0.87);
axis[2] = -REAL(0.33);
dNormalize3(axis);
dRFromAxisAndAngle (R, axis[0], axis[1], axis[2],
REAL(0.47123)); // 27deg
dBodySetRotation (bId[j][1], R);
jId[j] = dJointCreateHinge (wId, 0);
dJointAttach (jId[j], bId[j][0], bId[j][1]);
// dJointSetHingeParam(jId[j], dParamLoStop, 1);
// dJointSetHingeParam(jId[j], dParamHiStop, 2);
// dJointSetHingeParam(jId[j], dParamFMax, 200);
}
}
~dxJointHinge_Test_Initialization()
{
dWorldDestroy (wId);
}
dWorldID wId;
dBodyID bId[2][2];
dJointID jId[2];
};
// Test if setting a Hinge with its default values
// will behave the same as a default Hinge joint
TEST_FIXTURE (dxJointHinge_Test_Initialization,
test_Hinge_Initialization) {
using namespace std;
dVector3 axis;
dJointGetHingeAxis(jId[1], axis);
dJointSetHingeAxis(jId[1], axis[0], axis[1], axis[2]);
dVector3 anchor;
dJointGetHingeAnchor(jId[1], anchor);
dJointSetHingeAnchor(jId[1], anchor[0], anchor[1], anchor[2]);
for (int b=0; b<2; ++b) {
// Compare body b of the first joint with its equivalent on the
// second joint
const dReal *qA = dBodyGetQuaternion(bId[0][b]);
const dReal *qB = dBodyGetQuaternion(bId[1][b]);
CHECK_CLOSE (qA[0], qB[0], 1e-6);
CHECK_CLOSE (qA[1], qB[1], 1e-6);
CHECK_CLOSE (qA[2], qB[2], 1e-6);
CHECK_CLOSE (qA[3], qB[3], 1e-6);
}
dWorldStep (wId,0.5);
dWorldStep (wId,0.5);
dWorldStep (wId,0.5);
dWorldStep (wId,0.5);
for (int b=0; b<2; ++b) {
// Compare body b of the first joint with its equivalent on the
// second joint
const dReal *qA = dBodyGetQuaternion(bId[0][b]);
const dReal *qB = dBodyGetQuaternion(bId[1][b]);
CHECK_CLOSE (qA[0], qB[0], 1e-6);
CHECK_CLOSE (qA[1], qB[1], 1e-6);
CHECK_CLOSE (qA[2], qB[2], 1e-6);
CHECK_CLOSE (qA[3], qB[3], 1e-6);
const dReal *posA = dBodyGetPosition(bId[0][b]);
const dReal *posB = dBodyGetPosition(bId[1][b]);
CHECK_CLOSE (posA[0], posB[0], 1e-6);
CHECK_CLOSE (posA[1], posB[1], 1e-6);
CHECK_CLOSE (posA[2], posB[2], 1e-6);
CHECK_CLOSE (posA[3], posB[3], 1e-6);
}
}
TEST_FIXTURE(dxJointHinge_Fixture_B1_and_B2_At_Zero_Axis_Along_X,
test_Hinge_dParamVel)
{
const dReal targetvel = 100;
const dReal tolerance = targetvel *
#ifdef dSINGLE
1e-2
#else
1e-6
#endif
;
dJointSetHingeParam(jId, dParamFMax, dInfinity);
dJointSetHingeParam(jId, dParamVel, targetvel);
dWorldStep(wId, 0.001);
const dReal *v1 = dBodyGetAngularVel(bId1);
const dReal *v2 = dBodyGetAngularVel(bId2);
dVector3 rvel = { v1[0]-v2[0], v1[1]-v2[1], v1[2]-v2[2] };
CHECK_CLOSE(rvel[0], targetvel, tolerance);
CHECK_CLOSE(rvel[1], 0, tolerance);
CHECK_CLOSE(rvel[2], 0, tolerance);
}
} // End of SUITE TestdxJointHinge
|
#include <fstream>
using namespace TagLib;
ByteVector getPictureData(const char *filename) {
std::ifstream is;
is.open(filename, std::ios::binary);
is.seekg(0, std::ios::end);
int length = is.tellg();
is.seekg(0, std::ios::beg);
char *buffer = new char[length];
is.read(buffer, length);
is.close();
ByteVector result(buffer, length);
delete[] buffer;
return result;
}
|
#include <pybind11/pybind11.h>
namespace py = pybind11;
#include "../../cplusplus/src/player/Player.h"
#include "../../cplusplus/src/Game.h"
void init_Player(py::module &m) {
py::class_<Player>(m, "Player")
.def(py::init<Game&, int>())
.def_readonly("sGatheredGold", &Player::sGatheredGold)
.def_readonly("sGatheredLumber", &Player::sGatheredGold)
.def_readonly("sGatheredOil", &Player::sGatheredGold)
.def_readonly("sDamageDone", &Player::sGatheredGold)
.def_readonly("sDamageTaken", &Player::sGatheredGold)
.def_readonly("sUnitsCreated", &Player::sGatheredGold)
.def("oil", &Player::getOil)
.def("gold", &Player::getGold)
.def("lumber", &Player::getLumber)
.def("foodConsumption", &Player::getFoodConsumption)
.def("food", &Player::getFood)
.def("get_name", &Player::getName)
.def("set_name", &Player::setName)
.def("is_defeated", &Player::isDefeated)
.def("getScore",&Player::getScore)
.def("get_id", &Player::getId)
.def("do_action", &Player::do_action)
.def("do_my_action", &Player::do_my_action)
.def("get_queue_size", &Player::getQueueSize)
.def("do_manual_action", &Player::do_manual_action);
}
|
// This file is a part of Julia. License is MIT: https://julialang.org/license
// utility procedures used in code generation
static Instruction *tbaa_decorate(MDNode *md, Instruction *inst)
{
inst->setMetadata(llvm::LLVMContext::MD_tbaa, md);
if (isa<LoadInst>(inst) && md == tbaa_const)
inst->setMetadata(LLVMContext::MD_invariant_load, MDNode::get(md->getContext(), None));
return inst;
}
static Value *track_pjlvalue(jl_codectx_t &ctx, Value *V)
{
assert(V->getType() == T_pjlvalue);
return ctx.builder.CreateAddrSpaceCast(V, T_prjlvalue);
}
// Take an arbitrary untracked value and make it gc-tracked
static Value *maybe_decay_untracked(jl_codectx_t &ctx, Value *V)
{
if (V->getType() == T_pjlvalue)
return ctx.builder.CreateAddrSpaceCast(V, T_prjlvalue);
assert(V->getType() == T_prjlvalue);
return V;
}
// Take any value and mark that it may be derived from a rooted value
static Value *decay_derived(jl_codectx_t &ctx, Value *V)
{
Type *T = V->getType();
if (cast<PointerType>(T)->getAddressSpace() == AddressSpace::Derived)
return V;
// Once llvm deletes pointer element types, we won't need it here any more either.
Type *NewT = PointerType::get(cast<PointerType>(T)->getElementType(), AddressSpace::Derived);
return ctx.builder.CreateAddrSpaceCast(V, NewT);
}
// Take any value and make it safe to pass to GEP
static Value *maybe_decay_tracked(jl_codectx_t &ctx, Value *V)
{
Type *T = V->getType();
if (cast<PointerType>(T)->getAddressSpace() != AddressSpace::Tracked)
return V;
Type *NewT = PointerType::get(cast<PointerType>(T)->getElementType(), AddressSpace::Derived);
return ctx.builder.CreateAddrSpaceCast(V, NewT);
}
static Value *mark_callee_rooted(jl_codectx_t &ctx, Value *V)
{
assert(V->getType() == T_pjlvalue || V->getType() == T_prjlvalue);
return ctx.builder.CreateAddrSpaceCast(V,
PointerType::get(T_jlvalue, AddressSpace::CalleeRooted));
}
AtomicOrdering get_llvm_atomic_order(enum jl_memory_order order)
{
switch (order) {
case jl_memory_order_notatomic: return AtomicOrdering::NotAtomic;
case jl_memory_order_unordered: return AtomicOrdering::Unordered;
case jl_memory_order_monotonic: return AtomicOrdering::Monotonic;
case jl_memory_order_acquire: return AtomicOrdering::Acquire;
case jl_memory_order_release: return AtomicOrdering::Release;
case jl_memory_order_acq_rel: return AtomicOrdering::AcquireRelease;
case jl_memory_order_seq_cst: return AtomicOrdering::SequentiallyConsistent;
default:
assert("invalid atomic ordering");
abort();
}
}
// --- language feature checks ---
#define JL_FEAT_TEST(ctx, feature) ((ctx).params->feature)
// --- string constants ---
static Value *stringConstPtr(
jl_codegen_params_t &emission_context,
IRBuilder<> &irbuilder,
const std::string &txt)
{
Module *M = jl_builderModule(irbuilder);
StringRef ctxt(txt.c_str(), txt.size() + 1);
Constant *Data = ConstantDataArray::get(jl_LLVMContext, arrayRefFromStringRef(ctxt));
GlobalVariable *gv = get_pointer_to_constant(emission_context, Data, "_j_str", *M);
Value *zero = ConstantInt::get(Type::getInt32Ty(jl_LLVMContext), 0);
Value *Args[] = { zero, zero };
return irbuilder.CreateInBoundsGEP(gv->getValueType(), gv, Args);
}
// --- MDNode ---
Metadata *to_md_tree(jl_value_t *val) {
if (val == jl_nothing)
return nullptr;
Metadata *MD = nullptr;
if (jl_is_symbol(val)) {
MD = MDString::get(jl_LLVMContext, jl_symbol_name((jl_sym_t*)val));
} else if (jl_is_bool(val)) {
MD = ConstantAsMetadata::get(ConstantInt::get(T_int1, jl_unbox_bool(val)));
} else if (jl_is_long(val)) {
MD = ConstantAsMetadata::get(ConstantInt::get(T_int64, jl_unbox_long(val)));
} else if (jl_is_tuple(val)) {
SmallVector<Metadata *, 8> MDs;
for (int f = 0, nf = jl_nfields(val); f < nf; ++f) {
MD = to_md_tree(jl_fieldref(val, f));
if (MD)
MDs.push_back(MD);
}
MD = MDNode::get(jl_LLVMContext, MDs);
} else {
jl_error("LLVM metadata needs to Symbol/Bool/Int or Tuple thereof");
}
return MD;
}
// --- Debug info ---
static DIType *_julia_type_to_di(jl_codegen_params_t *ctx, jl_value_t *jt, DIBuilder *dbuilder, bool isboxed)
{
jl_datatype_t *jdt = (jl_datatype_t*)jt;
if (isboxed || !jl_is_datatype(jt) || !jdt->isconcretetype)
return jl_pvalue_dillvmt;
assert(jdt->layout);
DIType* _ditype = NULL;
DIType* &ditype = (ctx ? ctx->ditypes[jdt] : _ditype);
if (ditype)
return ditype;
const char *tname = jl_symbol_name(jdt->name->name);
if (jl_is_primitivetype(jt)) {
uint64_t SizeInBits = jl_datatype_nbits(jdt);
ditype = dbuilder->createBasicType(tname, SizeInBits, llvm::dwarf::DW_ATE_unsigned);
}
else if (jl_is_structtype(jt) && !jl_is_layout_opaque(jdt->layout)) {
size_t ntypes = jl_datatype_nfields(jdt);
std::vector<llvm::Metadata*> Elements(ntypes);
for (unsigned i = 0; i < ntypes; i++) {
jl_value_t *el = jl_svecref(jdt->types, i);
DIType *di;
if (jl_field_isptr(jdt, i))
di = jl_pvalue_dillvmt;
// TODO: elseif jl_islayout_inline
else
di = _julia_type_to_di(ctx, el, dbuilder, false);
Elements[i] = di;
}
DINodeArray ElemArray = dbuilder->getOrCreateArray(Elements);
std::string unique_name;
raw_string_ostream(unique_name) << (uintptr_t)jdt;
ditype = dbuilder->createStructType(
NULL, // Scope
tname, // Name
NULL, // File
0, // LineNumber
jl_datatype_nbits(jdt), // SizeInBits
8 * jl_datatype_align(jdt), // AlignInBits
DINode::FlagZero, // Flags
NULL, // DerivedFrom
ElemArray, // Elements
dwarf::DW_LANG_Julia, // RuntimeLanguage
nullptr, // VTableHolder
unique_name // UniqueIdentifier
);
}
else {
// return a typealias for types with hidden content
ditype = dbuilder->createTypedef(jl_pvalue_dillvmt, tname, NULL, 0, NULL);
}
return ditype;
}
static DIType *julia_type_to_di(jl_codectx_t &ctx, jl_value_t *jt, DIBuilder *dbuilder, bool isboxed)
{
return _julia_type_to_di(&ctx.emission_context, jt, dbuilder, isboxed);
}
static Value *emit_pointer_from_objref(jl_codectx_t &ctx, Value *V)
{
unsigned AS = cast<PointerType>(V->getType())->getAddressSpace();
if (AS != AddressSpace::Tracked && AS != AddressSpace::Derived)
return V;
V = decay_derived(ctx, V);
Type *T = PointerType::get(T_jlvalue, AddressSpace::Derived);
if (V->getType() != T)
V = ctx.builder.CreateBitCast(V, T);
Function *F = prepare_call(pointer_from_objref_func);
CallInst *Call = ctx.builder.CreateCall(F, V);
Call->setAttributes(F->getAttributes());
return Call;
}
static Value *get_gc_root_for(const jl_cgval_t &x)
{
if (x.Vboxed)
return x.Vboxed;
if (x.ispointer() && !x.constant) {
assert(x.V);
if (PointerType *T = dyn_cast<PointerType>(x.V->getType())) {
if (T->getAddressSpace() == AddressSpace::Tracked ||
T->getAddressSpace() == AddressSpace::Derived) {
return x.V;
}
}
}
return nullptr;
}
// --- emitting pointers directly into code ---
static inline Constant *literal_static_pointer_val(const void *p, Type *T = T_pjlvalue);
static Value *julia_pgv(jl_codectx_t &ctx, const char *cname, void *addr)
{
// emit a GlobalVariable for a jl_value_t named "cname"
// store the name given so we can reuse it (facilitating merging later)
// so first see if there already is a GlobalVariable for this address
GlobalVariable* &gv = ctx.global_targets[addr];
Module *M = jl_Module;
StringRef localname;
std::string gvname;
if (!gv) {
raw_string_ostream(gvname) << cname << ctx.global_targets.size();
localname = StringRef(gvname);
}
else {
localname = gv->getName();
if (gv->getParent() != M)
gv = cast_or_null<GlobalVariable>(M->getNamedValue(localname));
}
if (gv == nullptr)
gv = new GlobalVariable(*M, T_pjlvalue,
false, GlobalVariable::PrivateLinkage,
NULL, localname);
// LLVM passes sometimes strip metadata when moving load around
// since the load at the new location satisfy the same condition as the origional one.
// Mark the global as constant to LLVM code using our own metadata
// which is much less likely to be striped.
gv->setMetadata("julia.constgv", MDNode::get(gv->getContext(), None));
assert(localname == gv->getName());
assert(!gv->hasInitializer());
return gv;
}
static Value *julia_pgv(jl_codectx_t &ctx, const char *prefix, jl_sym_t *name, jl_module_t *mod, void *addr)
{
// emit a GlobalVariable for a jl_value_t, using the prefix, name, and module to
// to create a readable name of the form prefixModA.ModB.name
size_t len = strlen(jl_symbol_name(name)) + strlen(prefix) + 1;
jl_module_t *parent = mod, *prev = NULL;
while (parent != NULL && parent != prev) {
len += strlen(jl_symbol_name(parent->name))+1;
prev = parent;
parent = parent->parent;
}
char *fullname = (char*)alloca(len);
strcpy(fullname, prefix);
len -= strlen(jl_symbol_name(name)) + 1;
strcpy(fullname + len, jl_symbol_name(name));
parent = mod;
prev = NULL;
while (parent != NULL && parent != prev) {
size_t part = strlen(jl_symbol_name(parent->name)) + 1;
strcpy(fullname + len - part, jl_symbol_name(parent->name));
fullname[len - 1] = '.';
len -= part;
prev = parent;
parent = parent->parent;
}
return julia_pgv(ctx, fullname, addr);
}
static JuliaVariable *julia_const_gv(jl_value_t *val);
static Value *literal_pointer_val_slot(jl_codectx_t &ctx, jl_value_t *p)
{
// emit a pointer to a jl_value_t* which will allow it to be valid across reloading code
// also, try to give it a nice name for gdb, for easy identification
if (!imaging_mode) {
// TODO: this is an optimization, but is it useful or premature
// (it'll block any attempt to cache these, but can be simply deleted)
Module *M = jl_Module;
GlobalVariable *gv = new GlobalVariable(
*M, T_pjlvalue, true, GlobalVariable::PrivateLinkage,
literal_static_pointer_val(p));
gv->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
return gv;
}
if (JuliaVariable *gv = julia_const_gv(p)) {
// if this is a known special object, use the existing GlobalValue
return prepare_global_in(jl_Module, gv);
}
if (jl_is_datatype(p)) {
jl_datatype_t *addr = (jl_datatype_t*)p;
// DataTypes are prefixed with a +
return julia_pgv(ctx, "+", addr->name->name, addr->name->module, p);
}
if (jl_is_method(p)) {
jl_method_t *m = (jl_method_t*)p;
// functions are prefixed with a -
return julia_pgv(ctx, "-", m->name, m->module, p);
}
if (jl_is_method_instance(p)) {
jl_method_instance_t *linfo = (jl_method_instance_t*)p;
// Type-inferred functions are also prefixed with a -
if (jl_is_method(linfo->def.method))
return julia_pgv(ctx, "-", linfo->def.method->name, linfo->def.method->module, p);
}
if (jl_is_symbol(p)) {
jl_sym_t *addr = (jl_sym_t*)p;
// Symbols are prefixed with jl_sym#
return julia_pgv(ctx, "jl_sym#", addr, NULL, p);
}
// something else gets just a generic name
return julia_pgv(ctx, "jl_global#", p);
}
static size_t dereferenceable_size(jl_value_t *jt)
{
if (jl_is_array_type(jt)) {
// Array has at least this much data
return sizeof(jl_array_t);
}
else if (jl_is_datatype(jt) && jl_struct_try_layout((jl_datatype_t*)jt)) {
return jl_datatype_size(jt);
}
return 0;
}
// Return the min required / expected alignment of jltype (on the stack or heap)
static unsigned julia_alignment(jl_value_t *jt)
{
if (jl_is_array_type(jt)) {
// Array always has this alignment
return JL_SMALL_BYTE_ALIGNMENT;
}
if (jt == (jl_value_t*)jl_datatype_type) {
// types are never allocated in julia code/on the stack
// and this is the guarantee we have for the GC bits
return 16;
}
assert(jl_is_datatype(jt) && jl_struct_try_layout((jl_datatype_t*)jt));
unsigned alignment = jl_datatype_align(jt);
if (alignment > JL_HEAP_ALIGNMENT)
return JL_HEAP_ALIGNMENT;
return alignment;
}
static inline void maybe_mark_argument_dereferenceable(Argument *A, jl_value_t *jt)
{
AttrBuilder B;
B.addAttribute(Attribute::NonNull);
// The `dereferencable` below does not imply `nonnull` for non addrspace(0) pointers.
size_t size = dereferenceable_size(jt);
if (size) {
B.addDereferenceableAttr(size);
B.addAlignmentAttr(julia_alignment(jt));
}
A->addAttrs(B);
}
static inline Instruction *maybe_mark_load_dereferenceable(Instruction *LI, bool can_be_null,
size_t size, size_t align)
{
if (isa<PointerType>(LI->getType())) {
if (!can_be_null)
// The `dereferencable` below does not imply `nonnull` for non addrspace(0) pointers.
LI->setMetadata(LLVMContext::MD_nonnull, MDNode::get(jl_LLVMContext, None));
if (size) {
Metadata *OP = ConstantAsMetadata::get(ConstantInt::get(T_int64, size));
LI->setMetadata(can_be_null ? LLVMContext::MD_dereferenceable_or_null : LLVMContext::MD_dereferenceable,
MDNode::get(jl_LLVMContext, { OP }));
if (align >= 1) {
Metadata *OP = ConstantAsMetadata::get(ConstantInt::get(T_int64, align));
LI->setMetadata(LLVMContext::MD_align, MDNode::get(jl_LLVMContext, { OP }));
}
}
}
return LI;
}
static inline Instruction *maybe_mark_load_dereferenceable(Instruction *LI, bool can_be_null, jl_value_t *jt)
{
size_t size = dereferenceable_size(jt);
unsigned alignment = 1;
if (size > 0)
alignment = julia_alignment(jt);
return maybe_mark_load_dereferenceable(LI, can_be_null, size, alignment);
}
// Returns T_pjlvalue
static Value *literal_pointer_val(jl_codectx_t &ctx, jl_value_t *p)
{
if (p == NULL)
return V_null;
if (!imaging_mode)
return literal_static_pointer_val(p);
Value *pgv = literal_pointer_val_slot(ctx, p);
return tbaa_decorate(tbaa_const, maybe_mark_load_dereferenceable(
ctx.builder.CreateAlignedLoad(T_pjlvalue, pgv, Align(sizeof(void*))),
false, jl_typeof(p)));
}
// Returns T_pjlvalue
static Value *literal_pointer_val(jl_codectx_t &ctx, jl_binding_t *p)
{
// emit a pointer to any jl_value_t which will be valid across reloading code
if (p == NULL)
return V_null;
if (!imaging_mode)
return literal_static_pointer_val(p);
// bindings are prefixed with jl_bnd#
Value *pgv = julia_pgv(ctx, "jl_bnd#", p->name, p->owner, p);
return tbaa_decorate(tbaa_const, maybe_mark_load_dereferenceable(
ctx.builder.CreateAlignedLoad(T_pjlvalue, pgv, Align(sizeof(void*))),
false, sizeof(jl_binding_t), alignof(jl_binding_t)));
}
// bitcast a value, but preserve its address space when dealing with pointer types
static Value *emit_bitcast(jl_codectx_t &ctx, Value *v, Type *jl_value)
{
if (isa<PointerType>(jl_value) &&
v->getType()->getPointerAddressSpace() != jl_value->getPointerAddressSpace()) {
// Cast to the proper address space
Type *jl_value_addr =
PointerType::get(cast<PointerType>(jl_value)->getElementType(),
v->getType()->getPointerAddressSpace());
return ctx.builder.CreateBitCast(v, jl_value_addr);
}
else {
return ctx.builder.CreateBitCast(v, jl_value);
}
}
static Value *maybe_bitcast(jl_codectx_t &ctx, Value *V, Type *to) {
if (to != V->getType())
return emit_bitcast(ctx, V, to);
return V;
}
static Value *julia_binding_gv(jl_codectx_t &ctx, Value *bv)
{
Value *offset = ConstantInt::get(T_size, offsetof(jl_binding_t, value) / sizeof(size_t));
return ctx.builder.CreateInBoundsGEP(T_prjlvalue, bv, offset);
}
static Value *julia_binding_gv(jl_codectx_t &ctx, jl_binding_t *b)
{
// emit a literal_pointer_val to the value field of a jl_binding_t
// binding->value are prefixed with *
Value *bv;
if (imaging_mode)
bv = emit_bitcast(ctx,
tbaa_decorate(tbaa_const,
ctx.builder.CreateAlignedLoad(T_pjlvalue, julia_pgv(ctx, "*", b->name, b->owner, b), Align(sizeof(void*)))),
T_pprjlvalue);
else
bv = ConstantExpr::getBitCast(literal_static_pointer_val(b), T_pprjlvalue);
return julia_binding_gv(ctx, bv);
}
// --- mapping between julia and llvm types ---
static bool type_is_permalloc(jl_value_t *typ)
{
// Singleton should almost always be handled by the later optimization passes.
// Also do it here since it is cheap and save some effort in LLVM passes.
if (jl_is_datatype(typ) && jl_is_datatype_singleton((jl_datatype_t*)typ))
return true;
return typ == (jl_value_t*)jl_symbol_type ||
typ == (jl_value_t*)jl_int8_type ||
typ == (jl_value_t*)jl_uint8_type;
}
static unsigned convert_struct_offset(Type *lty, unsigned byte_offset)
{
const DataLayout &DL = jl_data_layout;
const StructLayout *SL = DL.getStructLayout(cast<StructType>(lty));
unsigned idx = SL->getElementContainingOffset(byte_offset);
assert(SL->getElementOffset(idx) == byte_offset);
return idx;
}
static unsigned convert_struct_offset(jl_codectx_t &ctx, Type *lty, unsigned byte_offset)
{
return convert_struct_offset(lty, byte_offset);
}
static Value *emit_struct_gep(jl_codectx_t &ctx, Type *lty, Value *base, unsigned byte_offset)
{
unsigned idx = convert_struct_offset(ctx, lty, byte_offset);
return ctx.builder.CreateConstInBoundsGEP2_32(lty, base, 0, idx);
}
static Type *_julia_struct_to_llvm(jl_codegen_params_t *ctx, jl_value_t *jt, bool *isboxed, bool llvmcall=false);
static Type *_julia_type_to_llvm(jl_codegen_params_t *ctx, jl_value_t *jt, bool *isboxed)
{
// this function converts a Julia Type into the equivalent LLVM type
if (isboxed) *isboxed = false;
if (jt == (jl_value_t*)jl_bottom_type)
return T_void;
if (jl_is_concrete_immutable(jt)) {
if (jl_datatype_nbits(jt) == 0)
return T_void;
Type *t = _julia_struct_to_llvm(ctx, jt, isboxed);
assert(t != NULL);
return t;
}
if (isboxed) *isboxed = true;
return T_prjlvalue;
}
static Type *julia_type_to_llvm(jl_codectx_t &ctx, jl_value_t *jt, bool *isboxed)
{
return _julia_type_to_llvm(&ctx.emission_context, jt, isboxed);
}
extern "C" JL_DLLEXPORT
Type *jl_type_to_llvm(jl_value_t *jt, bool *isboxed)
{
return _julia_type_to_llvm(NULL, jt, isboxed);
}
// converts a julia bitstype into the equivalent LLVM bitstype
static Type *bitstype_to_llvm(jl_value_t *bt, bool llvmcall = false)
{
assert(jl_is_primitivetype(bt));
if (bt == (jl_value_t*)jl_bool_type)
return T_int8;
if (bt == (jl_value_t*)jl_int32_type)
return T_int32;
if (bt == (jl_value_t*)jl_int64_type)
return T_int64;
if (bt == (jl_value_t*)jl_float16_type)
return T_float16;
if (bt == (jl_value_t*)jl_float32_type)
return T_float32;
if (bt == (jl_value_t*)jl_float64_type)
return T_float64;
if (jl_is_llvmpointer_type(bt)) {
jl_value_t *as_param = jl_tparam1(bt);
int as;
if (jl_is_int32(as_param))
as = jl_unbox_int32(as_param);
else if (jl_is_int64(as_param))
as = jl_unbox_int64(as_param);
else
jl_error("invalid pointer address space");
return PointerType::get(T_int8, as);
}
int nb = jl_datatype_size(bt);
return Type::getIntNTy(jl_LLVMContext, nb * 8);
}
static bool jl_type_hasptr(jl_value_t* typ)
{ // assumes that jl_stored_inline(typ) is true (and therefore that layout is defined)
return jl_is_datatype(typ) && ((jl_datatype_t*)typ)->layout->npointers > 0;
}
static unsigned jl_field_align(jl_datatype_t *dt, size_t i)
{
unsigned al = jl_field_offset(dt, i);
al |= 16;
al &= -al;
return std::min({al, (unsigned)jl_datatype_align(dt), (unsigned)JL_HEAP_ALIGNMENT});
}
static Type *_julia_struct_to_llvm(jl_codegen_params_t *ctx, jl_value_t *jt, bool *isboxed, bool llvmcall)
{
// this function converts a Julia Type into the equivalent LLVM struct
// use this where C-compatible (unboxed) structs are desired
// use julia_type_to_llvm directly when you want to preserve Julia's type semantics
if (isboxed) *isboxed = false;
if (jt == (jl_value_t*)jl_bottom_type)
return T_void;
if (jl_is_primitivetype(jt))
return bitstype_to_llvm(jt, llvmcall);
jl_datatype_t *jst = (jl_datatype_t*)jt;
if (jl_is_structtype(jt) && !(jst->layout && jl_is_layout_opaque(jst->layout))) {
bool isTuple = jl_is_tuple_type(jt);
jl_svec_t *ftypes = jl_get_fieldtypes(jst);
size_t i, ntypes = jl_svec_len(ftypes);
if (!jl_struct_try_layout(jst))
return NULL; // caller should have checked jl_type_mappable_to_c already, but we'll be nice
if (ntypes == 0 || jl_datatype_nbits(jst) == 0)
return T_void;
Type *_struct_decl = NULL;
// TODO: we should probably make a temporary root for `jst` somewhere
// don't use pre-filled struct_decl for llvmcall (f16, etc. may be different)
Type *&struct_decl = (ctx && !llvmcall ? ctx->llvmtypes[jst] : _struct_decl);
if (struct_decl)
return struct_decl;
std::vector<Type*> latypes(0);
bool isarray = true;
bool isvector = true;
jl_value_t *jlasttype = NULL;
Type *lasttype = NULL;
bool allghost = true;
for (i = 0; i < ntypes; i++) {
jl_value_t *ty = jl_svecref(ftypes, i);
if (jlasttype != NULL && ty != jlasttype)
isvector = false;
jlasttype = ty;
if (jl_field_isatomic(jst, i)) {
// TODO: eventually support this?
// though it's a bit unclear how the implicit load should be interpreted
return NULL;
}
Type *lty;
if (jl_field_isptr(jst, i)) {
lty = T_prjlvalue;
isvector = false;
}
else if (ty == (jl_value_t*)jl_bool_type) {
lty = T_int8;
}
else if (jl_is_uniontype(ty)) {
// pick an Integer type size such that alignment will generally be correct,
// and always end with an Int8 (selector byte).
// We may need to insert padding first to get to the right offset
size_t fsz = 0, al = 0;
bool isptr = !jl_islayout_inline(ty, &fsz, &al);
assert(!isptr && fsz == jl_field_size(jst, i) - 1); (void)isptr;
if (fsz > 0) {
if (al > MAX_ALIGN) {
Type *AlignmentType;
AlignmentType = ArrayType::get(FixedVectorType::get(T_int8, al), 0);
latypes.push_back(AlignmentType);
al = MAX_ALIGN;
}
Type *AlignmentType = IntegerType::get(jl_LLVMContext, 8 * al);
unsigned NumATy = fsz / al;
unsigned remainder = fsz % al;
assert(al == 1 || NumATy > 0);
while (NumATy--)
latypes.push_back(AlignmentType);
while (remainder--)
latypes.push_back(T_int8);
}
latypes.push_back(T_int8);
isarray = false;
allghost = false;
continue;
}
else {
bool isptr;
lty = _julia_struct_to_llvm(ctx, ty, &isptr, llvmcall);
assert(lty && !isptr);
}
if (lasttype != NULL && lasttype != lty)
isarray = false;
lasttype = lty;
if (!type_is_ghost(lty)) {
allghost = false;
latypes.push_back(lty);
}
}
if (allghost) {
assert(jst->layout == NULL); // otherwise should have been caught above
struct_decl = T_void;
}
else if (jl_is_vecelement_type(jt) && !jl_is_uniontype(jl_svecref(ftypes, 0))) {
// VecElement type is unwrapped in LLVM (when possible)
struct_decl = latypes[0];
}
else if (isarray && !type_is_ghost(lasttype)) {
if (isTuple && isvector && jl_special_vector_alignment(ntypes, jlasttype) != 0)
struct_decl = FixedVectorType::get(lasttype, ntypes);
else if (isTuple || !llvmcall)
struct_decl = ArrayType::get(lasttype, ntypes);
else
struct_decl = StructType::get(jl_LLVMContext, latypes);
}
else {
#if 0 // stress-test code that tries to assume julia-index == llvm-index
// (also requires change to emit_new_struct to not assume 0 == 0)
if (!isTuple && latypes.size() > 1) {
Type *NoopType = ArrayType::get(T_int1, 0);
latypes.insert(latypes.begin(), NoopType);
}
#endif
struct_decl = StructType::get(jl_LLVMContext, latypes);
}
return struct_decl;
}
// TODO: enable this (with tests) to change ccall calling convention for Union:
// if (jl_is_uniontype(ty)) {
// // pick an Integer type size such that alignment will be correct
// // and always end with an Int8 (selector byte)
// lty = ArrayType::get(IntegerType::get(jl_LLVMContext, 8 * al), fsz / al);
// std::vector<Type*> Elements(2);
// Elements[0] = lty;
// Elements[1] = T_int8;
// unsigned remainder = fsz % al;
// while (remainder--)
// Elements.push_back(T_int8);
// lty = StructType::get(jl_LLVMContext, makeArrayRef(Elements));
// }
if (isboxed) *isboxed = true;
return T_prjlvalue;
}
static Type *julia_struct_to_llvm(jl_codectx_t &ctx, jl_value_t *jt, bool *isboxed)
{
return _julia_struct_to_llvm(&ctx.emission_context, jt, isboxed);
}
static bool is_datatype_all_pointers(jl_datatype_t *dt)
{
size_t i, l = jl_datatype_nfields(dt);
for (i = 0; i < l; i++) {
if (!jl_field_isptr(dt, i)) {
return false;
}
}
return true;
}
static bool is_tupletype_homogeneous(jl_svec_t *t, bool allow_va = false)
{
size_t i, l = jl_svec_len(t);
if (l > 0) {
jl_value_t *t0 = jl_svecref(t, 0);
if (!jl_is_concrete_type(t0)) {
if (allow_va && jl_is_vararg(t0) &&
jl_is_concrete_type(jl_unwrap_vararg(t0)))
return true;
return false;
}
for (i = 1; i < l; i++) {
if (allow_va && i == l - 1 && jl_is_vararg(jl_svecref(t, i))) {
if (t0 != jl_unwrap_vararg(jl_svecref(t, i)))
return false;
continue;
}
if (t0 != jl_svecref(t, i))
return false;
}
}
return true;
}
static bool for_each_uniontype_small(
std::function<void(unsigned, jl_datatype_t*)> f,
jl_value_t *ty,
unsigned &counter)
{
if (counter > 127)
return false;
if (jl_is_uniontype(ty)) {
bool allunbox = for_each_uniontype_small(f, ((jl_uniontype_t*)ty)->a, counter);
allunbox &= for_each_uniontype_small(f, ((jl_uniontype_t*)ty)->b, counter);
return allunbox;
}
else if (jl_is_pointerfree(ty)) {
f(++counter, (jl_datatype_t*)ty);
return true;
}
return false;
}
static bool is_uniontype_allunboxed(jl_value_t *typ)
{
unsigned counter = 0;
return for_each_uniontype_small([&](unsigned, jl_datatype_t*) {}, typ, counter);
}
static Value *emit_typeof_boxed(jl_codectx_t &ctx, const jl_cgval_t &p);
static unsigned get_box_tindex(jl_datatype_t *jt, jl_value_t *ut)
{
unsigned new_idx = 0;
unsigned new_counter = 0;
for_each_uniontype_small(
// find the corresponding index in the new union-type
[&](unsigned new_idx_, jl_datatype_t *new_jt) {
if (jt == new_jt)
new_idx = new_idx_;
},
ut,
new_counter);
return new_idx;
}
// --- generating various field accessors ---
static Value *emit_nthptr_addr(jl_codectx_t &ctx, Value *v, ssize_t n, bool gctracked = true)
{
return ctx.builder.CreateInBoundsGEP(
T_prjlvalue,
emit_bitcast(ctx, maybe_decay_tracked(ctx, v), T_pprjlvalue),
ConstantInt::get(T_size, n));
}
static Value *emit_nthptr_addr(jl_codectx_t &ctx, Value *v, Value *idx)
{
return ctx.builder.CreateInBoundsGEP(
T_prjlvalue,
emit_bitcast(ctx, maybe_decay_tracked(ctx, v), T_pprjlvalue),
idx);
}
static LoadInst *emit_nthptr_recast(jl_codectx_t &ctx, Value *v, Value *idx, MDNode *tbaa, Type *ptype)
{
// p = (jl_value_t**)v; *(ptype)&p[n]
Value *vptr = emit_nthptr_addr(ctx, v, idx);
return cast<LoadInst>(tbaa_decorate(tbaa, ctx.builder.CreateLoad(emit_bitcast(ctx, vptr, ptype))));
}
static LoadInst *emit_nthptr_recast(jl_codectx_t &ctx, Value *v, ssize_t n, MDNode *tbaa, Type *ptype)
{
// p = (jl_value_t**)v; *(ptype)&p[n]
Value *vptr = emit_nthptr_addr(ctx, v, n);
return cast<LoadInst>(tbaa_decorate(tbaa, ctx.builder.CreateLoad(emit_bitcast(ctx, vptr, ptype))));
}
static Value *boxed(jl_codectx_t &ctx, const jl_cgval_t &v);
// Returns T_prjlvalue
static Value *emit_typeof(jl_codectx_t &ctx, Value *tt)
{
assert(tt != NULL && !isa<AllocaInst>(tt) && "expected a conditionally boxed value");
return ctx.builder.CreateCall(prepare_call(jl_typeof_func), {tt});
}
static jl_cgval_t emit_typeof(jl_codectx_t &ctx, const jl_cgval_t &p)
{
// given p, compute its type
if (p.constant)
return mark_julia_const(jl_typeof(p.constant));
if (p.isboxed && !jl_is_concrete_type(p.typ)) {
if (jl_is_type_type(p.typ)) {
jl_value_t *tp = jl_tparam0(p.typ);
if (!jl_is_type(tp) || jl_is_concrete_type(tp)) {
// convert 1::Type{1} ==> typeof(1) ==> Int
return mark_julia_const(jl_typeof(tp));
}
}
return mark_julia_type(ctx, emit_typeof(ctx, p.V), true, jl_datatype_type);
}
if (p.TIndex) {
Value *tindex = ctx.builder.CreateAnd(p.TIndex, ConstantInt::get(T_int8, 0x7f));
bool allunboxed = is_uniontype_allunboxed(p.typ);
Value *datatype_or_p = imaging_mode ? Constant::getNullValue(T_ppjlvalue) : V_rnull;
unsigned counter = 0;
for_each_uniontype_small(
[&](unsigned idx, jl_datatype_t *jt) {
Value *cmp = ctx.builder.CreateICmpEQ(tindex, ConstantInt::get(T_int8, idx));
Value *ptr;
if (imaging_mode) {
ptr = literal_pointer_val_slot(ctx, (jl_value_t*)jt);
}
else {
ptr = track_pjlvalue(ctx, literal_pointer_val(ctx, (jl_value_t*)jt));
}
datatype_or_p = ctx.builder.CreateSelect(cmp, ptr, datatype_or_p);
},
p.typ,
counter);
auto emit_unboxty = [&] () -> Value* {
if (imaging_mode)
return track_pjlvalue(
ctx, tbaa_decorate(tbaa_const, ctx.builder.CreateAlignedLoad(T_pjlvalue, datatype_or_p, Align(sizeof(void*)))));
return datatype_or_p;
};
Value *res;
if (!allunboxed) {
Value *isnull = ctx.builder.CreateIsNull(datatype_or_p);
BasicBlock *boxBB = BasicBlock::Create(jl_LLVMContext, "boxed", ctx.f);
BasicBlock *unboxBB = BasicBlock::Create(jl_LLVMContext, "unboxed", ctx.f);
BasicBlock *mergeBB = BasicBlock::Create(jl_LLVMContext, "merge", ctx.f);
ctx.builder.CreateCondBr(isnull, boxBB, unboxBB);
ctx.builder.SetInsertPoint(boxBB);
auto boxTy = emit_typeof(ctx, p.Vboxed);
ctx.builder.CreateBr(mergeBB);
boxBB = ctx.builder.GetInsertBlock(); // could have changed
ctx.builder.SetInsertPoint(unboxBB);
auto unboxTy = emit_unboxty();
ctx.builder.CreateBr(mergeBB);
unboxBB = ctx.builder.GetInsertBlock(); // could have changed
ctx.builder.SetInsertPoint(mergeBB);
auto phi = ctx.builder.CreatePHI(T_prjlvalue, 2);
phi->addIncoming(boxTy, boxBB);
phi->addIncoming(unboxTy, unboxBB);
res = phi;
}
else {
res = emit_unboxty();
}
return mark_julia_type(ctx, res, true, jl_datatype_type);
}
return mark_julia_const(p.typ);
}
// Returns T_prjlvalue
static Value *emit_typeof_boxed(jl_codectx_t &ctx, const jl_cgval_t &p)
{
return boxed(ctx, emit_typeof(ctx, p));
}
static Value *emit_datatype_types(jl_codectx_t &ctx, Value *dt)
{
Value *Ptr = emit_bitcast(ctx, decay_derived(ctx, dt), T_ppjlvalue);
Value *Idx = ConstantInt::get(T_size, offsetof(jl_datatype_t, types) / sizeof(void*));
return tbaa_decorate(tbaa_const, ctx.builder.CreateAlignedLoad(
T_pjlvalue, ctx.builder.CreateInBoundsGEP(T_pjlvalue, Ptr, Idx), Align(sizeof(void*))));
}
static Value *emit_datatype_nfields(jl_codectx_t &ctx, Value *dt)
{
Value *type_svec = emit_bitcast(ctx, emit_datatype_types(ctx, dt), T_psize);
return tbaa_decorate(tbaa_const, ctx.builder.CreateAlignedLoad(T_size, type_svec, Align(sizeof(void*))));
}
static Value *emit_datatype_size(jl_codectx_t &ctx, Value *dt)
{
Value *Ptr = emit_bitcast(ctx, decay_derived(ctx, dt), T_pint32);
Value *Idx = ConstantInt::get(T_size, offsetof(jl_datatype_t, size) / sizeof(int));
return tbaa_decorate(tbaa_const, ctx.builder.CreateAlignedLoad(T_int32, ctx.builder.CreateInBoundsGEP(T_int32, Ptr, Idx), Align(sizeof(int32_t))));
}
/* this is valid code, it's simply unused
static Value *emit_sizeof(jl_codectx_t &ctx, const jl_cgval_t &p)
{
if (p.TIndex) {
Value *tindex = ctx.builder.CreateAnd(p.TIndex, ConstantInt::get(T_int8, 0x7f));
Value *size = ConstantInt::get(T_int32, -1);
unsigned counter = 0;
bool allunboxed = for_each_uniontype_small(
[&](unsigned idx, jl_datatype_t *jt) {
Value *cmp = ctx.builder.CreateICmpEQ(tindex, ConstantInt::get(T_int8, idx));
size = ctx.builder.CreateSelect(cmp, ConstantInt::get(T_int32, jl_datatype_size(jt)), size);
},
p.typ,
counter);
if (!allunboxed && p.ispointer() && p.V && !isa<AllocaInst>(p.V)) {
BasicBlock *currBB = ctx.builder.GetInsertBlock();
BasicBlock *dynloadBB = BasicBlock::Create(jl_LLVMContext, "dyn_sizeof", ctx.f);
BasicBlock *postBB = BasicBlock::Create(jl_LLVMContext, "post_sizeof", ctx.f);
Value *isboxed = ctx.builder.CreateICmpNE(
ctx.builder.CreateAnd(p.TIndex, ConstantInt::get(T_int8, 0x80)),
ConstantInt::get(T_int8, 0));
ctx.builder.CreateCondBr(isboxed, dynloadBB, postBB);
ctx.builder.SetInsertPoint(dynloadBB);
Value *datatype = emit_typeof(p.V);
Value *dyn_size = emit_datatype_size(ctx, datatype);
ctx.builder.CreateBr(postBB);
dynloadBB = ctx.builder.GetInsertBlock(); // could have changed
ctx.builder.SetInsertPoint(postBB);
PHINode *sizeof_merge = ctx.builder.CreatePHI(T_int32, 2);
sizeof_merge->addIncoming(dyn_size, dynloadBB);
sizeof_merge->addIncoming(size, currBB);
size = sizeof_merge;
}
#ifndef NDEBUG
// try to catch codegen errors early, before it uses this to memcpy over the entire stack
CreateConditionalAbort(ctx.builder, ctx.builder.CreateICmpEQ(size, ConstantInt::get(T_int32, -1)));
#endif
return size;
}
else if (jl_is_concrete_type(p.typ)) {
return ConstantInt::get(T_int32, jl_datatype_size(p.typ));
}
else {
Value *datatype = emit_typeof_boxed(ctx, p);
Value *dyn_size = emit_datatype_size(ctx, datatype);
return dyn_size;
}
}
*/
static Value *emit_datatype_mutabl(jl_codectx_t &ctx, Value *dt)
{
Value *Ptr = emit_bitcast(ctx, decay_derived(ctx, dt), T_ppint8);
Value *Idx = ConstantInt::get(T_size, offsetof(jl_datatype_t, name));
Value *Nam = tbaa_decorate(tbaa_const,
ctx.builder.CreateAlignedLoad(T_pint8, ctx.builder.CreateInBoundsGEP(T_pint8, Ptr, Idx), Align(sizeof(int8_t*))));
Value *Idx2 = ConstantInt::get(T_size, offsetof(jl_typename_t, n_uninitialized) + sizeof(((jl_typename_t*)nullptr)->n_uninitialized));
Value *mutabl = tbaa_decorate(tbaa_const,
ctx.builder.CreateAlignedLoad(T_int8, ctx.builder.CreateInBoundsGEP(T_int8, Nam, Idx2), Align(1)));
mutabl = ctx.builder.CreateLShr(mutabl, 1);
return ctx.builder.CreateTrunc(mutabl, T_int1);
}
static Value *emit_datatype_isprimitivetype(jl_codectx_t &ctx, Value *dt)
{
Value *immut = ctx.builder.CreateNot(emit_datatype_mutabl(ctx, dt));
Value *nofields = ctx.builder.CreateICmpEQ(emit_datatype_nfields(ctx, dt), V_size0);
Value *sized = ctx.builder.CreateICmpSGT(emit_datatype_size(ctx, dt), ConstantInt::get(T_int32, 0));
return ctx.builder.CreateAnd(immut, ctx.builder.CreateAnd(nofields, sized));
}
static Value *emit_datatype_name(jl_codectx_t &ctx, Value *dt)
{
Value *vptr = emit_nthptr_addr(ctx, dt, (ssize_t)(offsetof(jl_datatype_t, name) / sizeof(char*)));
return tbaa_decorate(tbaa_const, ctx.builder.CreateAlignedLoad(T_prjlvalue, vptr, Align(sizeof(void*))));
}
// --- generating various error checks ---
// Do not use conditional throw for cases that type inference can know
// the error is always thrown. This may cause non dominated use
// of SSA value error in the verifier.
static void just_emit_error(jl_codectx_t &ctx, Function *F, const std::string &txt)
{
ctx.builder.CreateCall(F, stringConstPtr(ctx.emission_context, ctx.builder, txt));
}
static void emit_error(jl_codectx_t &ctx, Function *F, const std::string &txt)
{
just_emit_error(ctx, F, txt);
ctx.builder.CreateUnreachable();
BasicBlock *cont = BasicBlock::Create(jl_LLVMContext, "after_error", ctx.f);
ctx.builder.SetInsertPoint(cont);
}
static void emit_error(jl_codectx_t &ctx, const std::string &txt)
{
emit_error(ctx, prepare_call(jlerror_func), txt);
}
// DO NOT PASS IN A CONST CONDITION!
static void error_unless(jl_codectx_t &ctx, Value *cond, const std::string &msg)
{
BasicBlock *failBB = BasicBlock::Create(jl_LLVMContext, "fail", ctx.f);
BasicBlock *passBB = BasicBlock::Create(jl_LLVMContext, "pass");
ctx.builder.CreateCondBr(cond, passBB, failBB);
ctx.builder.SetInsertPoint(failBB);
just_emit_error(ctx, prepare_call(jlerror_func), msg);
ctx.builder.CreateUnreachable();
ctx.f->getBasicBlockList().push_back(passBB);
ctx.builder.SetInsertPoint(passBB);
}
static void raise_exception(jl_codectx_t &ctx, Value *exc,
BasicBlock *contBB=nullptr)
{
ctx.builder.CreateCall(prepare_call(jlthrow_func), { mark_callee_rooted(ctx, exc) });
ctx.builder.CreateUnreachable();
if (!contBB) {
contBB = BasicBlock::Create(jl_LLVMContext, "after_throw", ctx.f);
}
else {
ctx.f->getBasicBlockList().push_back(contBB);
}
ctx.builder.SetInsertPoint(contBB);
}
// DO NOT PASS IN A CONST CONDITION!
static void raise_exception_unless(jl_codectx_t &ctx, Value *cond, Value *exc)
{
BasicBlock *failBB = BasicBlock::Create(jl_LLVMContext,"fail",ctx.f);
BasicBlock *passBB = BasicBlock::Create(jl_LLVMContext,"pass");
ctx.builder.CreateCondBr(cond, passBB, failBB);
ctx.builder.SetInsertPoint(failBB);
raise_exception(ctx, exc, passBB);
}
static Value *null_pointer_cmp(jl_codectx_t &ctx, Value *v)
{
return ctx.builder.CreateICmpNE(v, Constant::getNullValue(v->getType()));
}
// If `nullcheck` is not NULL and a pointer NULL check is necessary
// store the pointer to be checked in `*nullcheck` instead of checking it
static void null_pointer_check(jl_codectx_t &ctx, Value *v, Value **nullcheck = nullptr)
{
if (nullcheck) {
*nullcheck = v;
return;
}
raise_exception_unless(ctx, null_pointer_cmp(ctx, v),
literal_pointer_val(ctx, jl_undefref_exception));
}
template<typename Func>
static Value *emit_guarded_test(jl_codectx_t &ctx, Value *ifnot, Value *defval, Func &&func)
{
if (auto Cond = dyn_cast<ConstantInt>(ifnot)) {
if (Cond->isZero())
return defval;
return func();
}
BasicBlock *currBB = ctx.builder.GetInsertBlock();
BasicBlock *passBB = BasicBlock::Create(jl_LLVMContext, "guard_pass", ctx.f);
BasicBlock *exitBB = BasicBlock::Create(jl_LLVMContext, "guard_exit", ctx.f);
ctx.builder.CreateCondBr(ifnot, passBB, exitBB);
ctx.builder.SetInsertPoint(passBB);
auto res = func();
passBB = ctx.builder.GetInsertBlock();
ctx.builder.CreateBr(exitBB);
ctx.builder.SetInsertPoint(exitBB);
if (defval == nullptr)
return nullptr;
PHINode *phi = ctx.builder.CreatePHI(defval->getType(), 2);
phi->addIncoming(defval, currBB);
phi->addIncoming(res, passBB);
return phi;
}
template<typename Func>
static Value *emit_guarded_test(jl_codectx_t &ctx, Value *ifnot, bool defval, Func &&func)
{
return emit_guarded_test(ctx, ifnot, ConstantInt::get(T_int1, defval), func);
}
template<typename Func>
static Value *emit_nullcheck_guard(jl_codectx_t &ctx, Value *nullcheck, Func &&func)
{
if (!nullcheck)
return func();
return emit_guarded_test(ctx, null_pointer_cmp(ctx, nullcheck), false, func);
}
template<typename Func>
static Value *emit_nullcheck_guard2(jl_codectx_t &ctx, Value *nullcheck1,
Value *nullcheck2, Func &&func)
{
if (!nullcheck1)
return emit_nullcheck_guard(ctx, nullcheck2, func);
if (!nullcheck2)
return emit_nullcheck_guard(ctx, nullcheck1, func);
nullcheck1 = null_pointer_cmp(ctx, nullcheck1);
nullcheck2 = null_pointer_cmp(ctx, nullcheck2);
// If both are NULL, return true.
return emit_guarded_test(ctx, ctx.builder.CreateOr(nullcheck1, nullcheck2), true, [&] {
return emit_guarded_test(ctx, ctx.builder.CreateAnd(nullcheck1, nullcheck2),
false, func);
});
}
static void emit_type_error(jl_codectx_t &ctx, const jl_cgval_t &x, Value *type, const std::string &msg)
{
Value *msg_val = stringConstPtr(ctx.emission_context, ctx.builder, msg);
ctx.builder.CreateCall(prepare_call(jltypeerror_func),
{ msg_val, maybe_decay_untracked(ctx, type), mark_callee_rooted(ctx, boxed(ctx, x))});
}
// Should agree with `emit_isa` below
static bool _can_optimize_isa(jl_value_t *type, int &counter)
{
if (counter > 127)
return false;
if (jl_is_uniontype(type)) {
counter++;
return (_can_optimize_isa(((jl_uniontype_t*)type)->a, counter) &&
_can_optimize_isa(((jl_uniontype_t*)type)->b, counter));
}
if (jl_is_type_type(type) && jl_pointer_egal(type))
return true;
if (jl_has_intersect_type_not_kind(type))
return false;
if (jl_is_concrete_type(type))
return true;
jl_datatype_t *dt = (jl_datatype_t*)jl_unwrap_unionall(type);
if (jl_is_datatype(dt) && !dt->name->abstract && jl_subtype(dt->name->wrapper, type))
return true;
return false;
}
static bool can_optimize_isa_union(jl_uniontype_t *type)
{
int counter = 1;
return (_can_optimize_isa(type->a, counter) && _can_optimize_isa(type->b, counter));
}
// a simple case of emit_isa that is obvious not to include a safe-point
static Value *emit_exactly_isa(jl_codectx_t &ctx, const jl_cgval_t &arg, jl_value_t *dt)
{
assert(jl_is_concrete_type(dt));
return ctx.builder.CreateICmpEQ(
emit_typeof_boxed(ctx, arg),
track_pjlvalue(ctx, literal_pointer_val(ctx, dt)));
}
static std::pair<Value*, bool> emit_isa(jl_codectx_t &ctx, const jl_cgval_t &x,
jl_value_t *type, const std::string *msg);
static void emit_isa_union(jl_codectx_t &ctx, const jl_cgval_t &x, jl_value_t *type,
SmallVectorImpl<std::pair<std::pair<BasicBlock*,BasicBlock*>,Value*>> &bbs)
{
if (jl_is_uniontype(type)) {
emit_isa_union(ctx, x, ((jl_uniontype_t*)type)->a, bbs);
emit_isa_union(ctx, x, ((jl_uniontype_t*)type)->b, bbs);
return;
}
BasicBlock *enter = ctx.builder.GetInsertBlock();
Value *v = emit_isa(ctx, x, type, nullptr).first;
BasicBlock *exit = ctx.builder.GetInsertBlock();
bbs.emplace_back(std::make_pair(enter, exit), v);
BasicBlock *isaBB = BasicBlock::Create(jl_LLVMContext, "isa", ctx.f);
ctx.builder.SetInsertPoint(isaBB);
}
// Should agree with `_can_optimize_isa` above
static std::pair<Value*, bool> emit_isa(jl_codectx_t &ctx, const jl_cgval_t &x, jl_value_t *type, const std::string *msg)
{
// TODO: The subtype check below suffers from incorrectness issues due to broken
// subtyping for kind types (see https://github.com/JuliaLang/julia/issues/27078). For
// actual `isa` calls, this optimization should already have been performed upstream
// anyway, but having this optimization in codegen might still be beneficial for
// `typeassert`s if we can make it correct.
Optional<bool> known_isa;
jl_value_t *intersected_type = type;
if (x.constant)
known_isa = jl_isa(x.constant, type);
else if (jl_is_not_broken_subtype(x.typ, type) && jl_subtype(x.typ, type)) {
known_isa = true;
} else {
intersected_type = jl_type_intersection(x.typ, type);
if (intersected_type == (jl_value_t*)jl_bottom_type)
known_isa = false;
}
if (known_isa) {
if (!*known_isa && msg) {
emit_type_error(ctx, x, literal_pointer_val(ctx, type), *msg);
ctx.builder.CreateUnreachable();
BasicBlock *failBB = BasicBlock::Create(jl_LLVMContext, "fail", ctx.f);
ctx.builder.SetInsertPoint(failBB);
}
return std::make_pair(ConstantInt::get(T_int1, *known_isa), true);
}
if (jl_is_type_type(intersected_type) && jl_pointer_egal(intersected_type)) {
// Use the check in `jl_pointer_egal` to see if the type enclosed
// has unique pointer value.
auto ptr = track_pjlvalue(ctx, literal_pointer_val(ctx, jl_tparam0(intersected_type)));
return {ctx.builder.CreateICmpEQ(boxed(ctx, x), ptr), false};
}
// intersection with Type needs to be handled specially
if (jl_has_intersect_type_not_kind(type) || jl_has_intersect_type_not_kind(intersected_type)) {
Value *vx = boxed(ctx, x);
Value *vtyp = track_pjlvalue(ctx, literal_pointer_val(ctx, type));
if (msg && *msg == "typeassert") {
ctx.builder.CreateCall(prepare_call(jltypeassert_func), { vx, vtyp });
return std::make_pair(ConstantInt::get(T_int1, 1), true);
}
return std::make_pair(ctx.builder.CreateICmpNE(
ctx.builder.CreateCall(prepare_call(jlisa_func), { vx, vtyp }),
ConstantInt::get(T_int32, 0)), false);
}
// tests for isa concretetype can be handled with pointer comparisons
if (jl_is_concrete_type(intersected_type)) {
if (x.TIndex) {
unsigned tindex = get_box_tindex((jl_datatype_t*)intersected_type, x.typ);
if (tindex > 0) {
// optimize more when we know that this is a split union-type where tindex = 0 is invalid
Value *xtindex = ctx.builder.CreateAnd(x.TIndex, ConstantInt::get(T_int8, 0x7f));
return std::make_pair(ctx.builder.CreateICmpEQ(xtindex, ConstantInt::get(T_int8, tindex)), false);
}
else if (x.Vboxed) {
// test for (x.TIndex == 0x80 && typeof(x.V) == type)
Value *isboxed = ctx.builder.CreateICmpEQ(x.TIndex, ConstantInt::get(T_int8, 0x80));
BasicBlock *currBB = ctx.builder.GetInsertBlock();
BasicBlock *isaBB = BasicBlock::Create(jl_LLVMContext, "isa", ctx.f);
BasicBlock *postBB = BasicBlock::Create(jl_LLVMContext, "post_isa", ctx.f);
ctx.builder.CreateCondBr(isboxed, isaBB, postBB);
ctx.builder.SetInsertPoint(isaBB);
Value *istype_boxed = ctx.builder.CreateICmpEQ(emit_typeof(ctx, x.Vboxed),
track_pjlvalue(ctx, literal_pointer_val(ctx, intersected_type)));
ctx.builder.CreateBr(postBB);
isaBB = ctx.builder.GetInsertBlock(); // could have changed
ctx.builder.SetInsertPoint(postBB);
PHINode *istype = ctx.builder.CreatePHI(T_int1, 2);
istype->addIncoming(ConstantInt::get(T_int1, 0), currBB);
istype->addIncoming(istype_boxed, isaBB);
return std::make_pair(istype, false);
} else {
// handle the case where we know that `x` is unboxed (but of unknown type), but that concrete type `type` cannot be unboxed
return std::make_pair(ConstantInt::get(T_int1, 0), false);
}
}
return std::make_pair(emit_exactly_isa(ctx, x, intersected_type), false);
}
jl_datatype_t *dt = (jl_datatype_t*)jl_unwrap_unionall(intersected_type);
if (jl_is_datatype(dt) && !dt->name->abstract && jl_subtype(dt->name->wrapper, type)) {
// intersection is a supertype of all instances of its constructor,
// so the isa test reduces to a comparison of the typename by pointer
return std::make_pair(
ctx.builder.CreateICmpEQ(
mark_callee_rooted(ctx, emit_datatype_name(ctx, emit_typeof_boxed(ctx, x))),
mark_callee_rooted(ctx, literal_pointer_val(ctx, (jl_value_t*)dt->name))),
false);
}
if (jl_is_uniontype(intersected_type) &&
can_optimize_isa_union((jl_uniontype_t*)intersected_type)) {
SmallVector<std::pair<std::pair<BasicBlock*,BasicBlock*>,Value*>,4> bbs;
emit_isa_union(ctx, x, intersected_type, bbs);
int nbbs = bbs.size();
BasicBlock *currBB = ctx.builder.GetInsertBlock();
PHINode *res = ctx.builder.CreatePHI(T_int1, nbbs);
for (int i = 0; i < nbbs; i++) {
auto bb = bbs[i].first.second;
ctx.builder.SetInsertPoint(bb);
if (i + 1 < nbbs) {
ctx.builder.CreateCondBr(bbs[i].second, currBB, bbs[i + 1].first.first);
res->addIncoming(ConstantInt::get(T_int1, 1), bb);
}
else {
ctx.builder.CreateBr(currBB);
res->addIncoming(bbs[i].second, bb);
}
}
ctx.builder.SetInsertPoint(currBB);
return {res, false};
}
// everything else can be handled via subtype tests
return std::make_pair(ctx.builder.CreateICmpNE(
ctx.builder.CreateCall(prepare_call(jlsubtype_func),
{ emit_typeof_boxed(ctx, x),
track_pjlvalue(ctx, literal_pointer_val(ctx, type)) }),
ConstantInt::get(T_int32, 0)), false);
}
static void emit_typecheck(jl_codectx_t &ctx, const jl_cgval_t &x, jl_value_t *type, const std::string &msg)
{
Value *istype;
bool handled_msg;
std::tie(istype, handled_msg) = emit_isa(ctx, x, type, &msg);
if (!handled_msg) {
BasicBlock *failBB = BasicBlock::Create(jl_LLVMContext, "fail", ctx.f);
BasicBlock *passBB = BasicBlock::Create(jl_LLVMContext, "pass");
ctx.builder.CreateCondBr(istype, passBB, failBB);
ctx.builder.SetInsertPoint(failBB);
emit_type_error(ctx, x, literal_pointer_val(ctx, type), msg);
ctx.builder.CreateUnreachable();
ctx.f->getBasicBlockList().push_back(passBB);
ctx.builder.SetInsertPoint(passBB);
}
}
static Value *emit_isconcrete(jl_codectx_t &ctx, Value *typ)
{
Value *isconcrete;
isconcrete = ctx.builder.CreateConstInBoundsGEP1_32(T_int8, emit_bitcast(ctx, decay_derived(ctx, typ), T_pint8), offsetof(jl_datatype_t, hash) + sizeof(((jl_datatype_t*)nullptr)->hash));
isconcrete = tbaa_decorate(tbaa_const, ctx.builder.CreateAlignedLoad(T_int8, isconcrete, Align(1)));
isconcrete = ctx.builder.CreateLShr(isconcrete, 1);
isconcrete = ctx.builder.CreateTrunc(isconcrete, T_int1);
return isconcrete;
}
static void emit_concretecheck(jl_codectx_t &ctx, Value *typ, const std::string &msg)
{
assert(typ->getType() == T_prjlvalue);
emit_typecheck(ctx, mark_julia_type(ctx, typ, true, jl_any_type), (jl_value_t*)jl_datatype_type, msg);
error_unless(ctx, emit_isconcrete(ctx, typ), msg);
}
#define CHECK_BOUNDS 1
static bool bounds_check_enabled(jl_codectx_t &ctx, jl_value_t *inbounds) {
#if CHECK_BOUNDS==1
if (jl_options.check_bounds == JL_OPTIONS_CHECK_BOUNDS_ON)
return 1;
if (jl_options.check_bounds == JL_OPTIONS_CHECK_BOUNDS_OFF)
return 0;
if (inbounds == jl_false)
return 0;
return 1;
#else
return 0;
#endif
}
static Value *emit_bounds_check(jl_codectx_t &ctx, const jl_cgval_t &ainfo, jl_value_t *ty, Value *i, Value *len, jl_value_t *boundscheck)
{
Value *im1 = ctx.builder.CreateSub(i, ConstantInt::get(T_size, 1));
#if CHECK_BOUNDS==1
if (bounds_check_enabled(ctx, boundscheck)) {
Value *ok = ctx.builder.CreateICmpULT(im1, len);
BasicBlock *failBB = BasicBlock::Create(jl_LLVMContext, "fail", ctx.f);
BasicBlock *passBB = BasicBlock::Create(jl_LLVMContext, "pass");
ctx.builder.CreateCondBr(ok, passBB, failBB);
ctx.builder.SetInsertPoint(failBB);
if (!ty) { // jl_value_t** tuple (e.g. the vararg)
ctx.builder.CreateCall(prepare_call(jlvboundserror_func), { ainfo.V, len, i });
}
else if (ainfo.isboxed) { // jl_datatype_t or boxed jl_value_t
ctx.builder.CreateCall(prepare_call(jlboundserror_func), { mark_callee_rooted(ctx, boxed(ctx, ainfo)), i });
}
else { // unboxed jl_value_t*
Value *a = ainfo.V;
if (ainfo.isghost) {
a = Constant::getNullValue(T_pint8);
}
else if (!ainfo.ispointer()) {
// CreateAlloca is OK here since we are on an error branch
Value *tempSpace = ctx.builder.CreateAlloca(a->getType());
ctx.builder.CreateStore(a, tempSpace);
a = tempSpace;
}
ctx.builder.CreateCall(prepare_call(jluboundserror_func), {
emit_bitcast(ctx, decay_derived(ctx, a), T_pint8),
literal_pointer_val(ctx, ty),
i });
}
ctx.builder.CreateUnreachable();
ctx.f->getBasicBlockList().push_back(passBB);
ctx.builder.SetInsertPoint(passBB);
}
#endif
return im1;
}
static Value *emit_unbox(jl_codectx_t &ctx, Type *to, const jl_cgval_t &x, jl_value_t *jt, Value* dest = NULL, MDNode *tbaa_dest = nullptr, bool isVolatile = false);
static void emit_write_barrier(jl_codectx_t&, Value*, ArrayRef<Value*>);
static void emit_write_barrier(jl_codectx_t&, Value*, Value*);
static void emit_write_multibarrier(jl_codectx_t&, Value*, Value*, jl_value_t*);
std::vector<unsigned> first_ptr(Type *T)
{
if (isa<StructType>(T) || isa<ArrayType>(T) || isa<VectorType>(T)) {
if (!isa<StructType>(T)) {
uint64_t num_elements;
if (auto *AT = dyn_cast<ArrayType>(T))
num_elements = AT->getNumElements();
else {
VectorType *VT = cast<VectorType>(T);
#if JL_LLVM_VERSION >= 120000
ElementCount EC = VT->getElementCount();
num_elements = EC.getKnownMinValue();
#else
num_elements = VT->getNumElements();
#endif
}
if (num_elements == 0)
return {};
}
unsigned i = 0;
for (Type *ElTy : T->subtypes()) {
if (isa<PointerType>(ElTy) && ElTy->getPointerAddressSpace() == AddressSpace::Tracked) {
return std::vector<unsigned>{i};
}
auto path = first_ptr(ElTy);
if (!path.empty()) {
path.push_back(i);
return path;
}
i++;
}
}
return {};
}
Value *extract_first_ptr(jl_codectx_t &ctx, Value *V)
{
auto path = first_ptr(V->getType());
if (path.empty())
return NULL;
std::reverse(std::begin(path), std::end(path));
return ctx.builder.CreateExtractValue(V, path);
}
static void emit_lockstate_value(jl_codectx_t &ctx, Value *strct, bool newstate)
{
Value *v = mark_callee_rooted(ctx, strct);
ctx.builder.CreateCall(prepare_call(newstate ? jllockvalue_func : jlunlockvalue_func), v);
}
static void emit_lockstate_value(jl_codectx_t &ctx, const jl_cgval_t &strct, bool newstate)
{
assert(strct.isboxed);
emit_lockstate_value(ctx, boxed(ctx, strct), newstate);
}
// If `nullcheck` is not NULL and a pointer NULL check is necessary
// store the pointer to be checked in `*nullcheck` instead of checking it
static jl_cgval_t typed_load(jl_codectx_t &ctx, Value *ptr, Value *idx_0based, jl_value_t *jltype,
MDNode *tbaa, MDNode *aliasscope, bool isboxed, AtomicOrdering Order,
bool maybe_null_if_boxed = true, unsigned alignment = 0,
Value **nullcheck = nullptr)
{
Type *elty = isboxed ? T_prjlvalue : julia_type_to_llvm(ctx, jltype);
if (type_is_ghost(elty))
return ghostValue(jltype);
AllocaInst *intcast = NULL;
if (!isboxed && Order != AtomicOrdering::NotAtomic && !elty->isIntOrPtrTy() && !elty->isFloatingPointTy()) {
const DataLayout &DL = jl_data_layout;
unsigned nb = DL.getTypeSizeInBits(elty);
intcast = ctx.builder.CreateAlloca(elty);
elty = Type::getIntNTy(jl_LLVMContext, nb);
}
Type *ptrty = PointerType::get(elty, ptr->getType()->getPointerAddressSpace());
Value *data;
if (ptr->getType() != ptrty)
data = emit_bitcast(ctx, ptr, ptrty);
else
data = ptr;
if (idx_0based)
data = ctx.builder.CreateInBoundsGEP(elty, data, idx_0based);
Instruction *load;
// TODO: can only lazy load if we can create a gc root for ptr for the lifetime of elt
//if (elty->isAggregateType() && tbaa == tbaa_immut && !alignment) { // can lazy load on demand, no copy needed
// elt = data;
//}
//else {
if (isboxed)
alignment = sizeof(void*);
else if (!alignment)
alignment = julia_alignment(jltype);
load = ctx.builder.CreateAlignedLoad(data, Align(alignment), false);
cast<LoadInst>(load)->setOrdering(Order);
if (aliasscope)
load->setMetadata("alias.scope", aliasscope);
if (isboxed)
load = maybe_mark_load_dereferenceable(load, true, jltype);
if (tbaa)
load = tbaa_decorate(tbaa, load);
if (intcast) {
ctx.builder.CreateStore(load, ctx.builder.CreateBitCast(intcast, load->getType()->getPointerTo()));
load = ctx.builder.CreateLoad(intcast);
}
if (maybe_null_if_boxed) {
Value *first_ptr = isboxed ? load : extract_first_ptr(ctx, load);
if (first_ptr)
null_pointer_check(ctx, first_ptr, nullcheck);
}
//}
if (jltype == (jl_value_t*)jl_bool_type) { // "freeze" undef memory to a valid value
// NOTE: if we zero-initialize arrays, this optimization should become valid
//load->setMetadata(LLVMContext::MD_range, MDNode::get(jl_LLVMContext, {
// ConstantAsMetadata::get(ConstantInt::get(T_int8, 0)),
// ConstantAsMetadata::get(ConstantInt::get(T_int8, 2)) }));
load = ctx.builder.Insert(CastInst::Create(Instruction::Trunc, load, T_int1));
}
return mark_julia_type(ctx, load, isboxed, jltype);
}
static jl_cgval_t typed_store(jl_codectx_t &ctx,
Value *ptr, Value *idx_0based, const jl_cgval_t &rhs, const jl_cgval_t &cmp,
jl_value_t *jltype, MDNode *tbaa, MDNode *aliasscope,
Value *parent, // for the write barrier, NULL if no barrier needed
bool isboxed, AtomicOrdering Order, AtomicOrdering FailOrder, unsigned alignment,
bool needlock, bool issetfield, bool isreplacefield, bool maybe_null_if_boxed)
{
assert(!needlock || parent != nullptr);
jl_cgval_t oldval = rhs;
Type *elty = isboxed ? T_prjlvalue : julia_type_to_llvm(ctx, jltype);
if (type_is_ghost(elty))
return oldval;
Value *intcast = nullptr;
if (!isboxed && Order != AtomicOrdering::NotAtomic && !elty->isIntOrPtrTy() && !elty->isFloatingPointTy()) {
const DataLayout &DL = jl_data_layout;
unsigned nb = DL.getTypeSizeInBits(elty);
if (!issetfield)
intcast = ctx.builder.CreateAlloca(elty);
elty = Type::getIntNTy(jl_LLVMContext, nb);
}
Value *r;
if (!isboxed)
r = emit_unbox(ctx, elty, rhs, jltype);
else
r = boxed(ctx, rhs);
Type *ptrty = PointerType::get(elty, ptr->getType()->getPointerAddressSpace());
if (ptr->getType() != ptrty)
ptr = ctx.builder.CreateBitCast(ptr, ptrty);
if (idx_0based)
ptr = ctx.builder.CreateInBoundsGEP(r->getType(), ptr, idx_0based);
if (isboxed)
alignment = sizeof(void*);
else if (!alignment)
alignment = julia_alignment(jltype);
Instruction *instr = nullptr;
Value *Compare = nullptr;
Value *Success = nullptr;
BasicBlock *DoneBB = issetfield || (!isreplacefield && !isboxed) ? nullptr : BasicBlock::Create(jl_LLVMContext, "done_xchg", ctx.f);
if (needlock)
emit_lockstate_value(ctx, parent, true);
if (issetfield || Order == AtomicOrdering::NotAtomic) {
if (!issetfield) {
instr = ctx.builder.CreateAlignedLoad(elty, ptr, Align(alignment));
if (aliasscope)
instr->setMetadata("noalias", aliasscope);
if (tbaa)
tbaa_decorate(tbaa, instr);
}
if (isreplacefield) {
oldval = mark_julia_type(ctx, instr, isboxed, jltype);
Value *first_ptr = nullptr;
if (maybe_null_if_boxed)
first_ptr = isboxed ? instr : extract_first_ptr(ctx, instr);
Success = emit_nullcheck_guard(ctx, first_ptr, [&] {
return emit_f_is(ctx, oldval, cmp);
});
BasicBlock *BB = BasicBlock::Create(jl_LLVMContext, "xchg", ctx.f);
ctx.builder.CreateCondBr(Success, BB, DoneBB);
ctx.builder.SetInsertPoint(BB);
}
StoreInst *store = ctx.builder.CreateAlignedStore(r, ptr, Align(alignment));
store->setOrdering(Order);
if (aliasscope)
store->setMetadata("noalias", aliasscope);
if (tbaa)
tbaa_decorate(tbaa, store);
if (DoneBB)
ctx.builder.CreateBr(DoneBB);
}
else if (isboxed || isreplacefield) {
// we have to handle isboxed here as a workaround for really bad LLVM design issue: plain Xchg only works with integers
bool needloop;
PHINode *Succ = nullptr, *Current = nullptr;
if (isreplacefield) {
if (!isboxed) {
needloop = ((jl_datatype_t*)jltype)->layout->haspadding;
Value *SameType = emit_isa(ctx, cmp, jltype, nullptr).first;
if (SameType != ConstantInt::getTrue(jl_LLVMContext)) {
BasicBlock *SkipBB = BasicBlock::Create(jl_LLVMContext, "skip_xchg", ctx.f);
BasicBlock *BB = BasicBlock::Create(jl_LLVMContext, "xchg", ctx.f);
ctx.builder.CreateCondBr(SameType, BB, SkipBB);
ctx.builder.SetInsertPoint(SkipBB);
LoadInst *load = ctx.builder.CreateAlignedLoad(elty, ptr, Align(alignment));
load->setOrdering(FailOrder);
if (aliasscope)
load->setMetadata("noalias", aliasscope);
if (tbaa)
tbaa_decorate(tbaa, load);
instr = load;
ctx.builder.CreateBr(DoneBB);
ctx.builder.SetInsertPoint(DoneBB);
Succ = ctx.builder.CreatePHI(T_int1, 2);
Succ->addIncoming(ConstantInt::get(T_int1, 0), SkipBB);
Current = ctx.builder.CreatePHI(instr->getType(), 2);
Current->addIncoming(instr, SkipBB);
ctx.builder.SetInsertPoint(BB);
}
Compare = emit_unbox(ctx, elty, cmp, jltype);
}
else if (cmp.isboxed) {
Compare = boxed(ctx, cmp);
needloop = !jl_is_mutable_datatype(jltype);
}
else {
Compare = V_rnull;
needloop = true;
}
}
else {
LoadInst *Current = ctx.builder.CreateAlignedLoad(elty, ptr, Align(alignment));
Current->setOrdering(AtomicOrdering::Monotonic);
if (aliasscope)
Current->setMetadata("noalias", aliasscope);
if (tbaa)
tbaa_decorate(tbaa, Current);
Compare = Current;
needloop = true;
}
BasicBlock *BB;
if (needloop) {
BasicBlock *From = ctx.builder.GetInsertBlock();
BB = BasicBlock::Create(jl_LLVMContext, "xchg", ctx.f);
ctx.builder.CreateBr(BB);
ctx.builder.SetInsertPoint(BB);
PHINode *Cmp = ctx.builder.CreatePHI(r->getType(), 2);
Cmp->addIncoming(Compare, From);
Compare = Cmp;
}
if (Order == AtomicOrdering::Unordered)
Order = AtomicOrdering::Monotonic;
if (!isreplacefield)
FailOrder = AtomicOrdering::Monotonic;
else if (FailOrder == AtomicOrdering::Unordered)
FailOrder = AtomicOrdering::Monotonic;
#if JL_LLVM_VERSION >= 130000
auto *store = ctx.builder.CreateAtomicCmpXchg(ptr, Compare, r, Align(alignment), Order, FailOrder);
#else
auto *store = ctx.builder.CreateAtomicCmpXchg(ptr, Compare, r, Order, FailOrder);
store->setAlignment(Align(alignment));
#endif
if (aliasscope)
store->setMetadata("noalias", aliasscope);
if (tbaa)
tbaa_decorate(tbaa, store);
instr = ctx.builder.Insert(ExtractValueInst::Create(store, 0));
Success = ctx.builder.CreateExtractValue(store, 1);
Value *Done = Success;
if (needloop) {
if (isreplacefield) {
if (intcast) {
ctx.builder.CreateStore(instr, ctx.builder.CreateBitCast(intcast, instr->getType()->getPointerTo()));
oldval = mark_julia_slot(intcast, jltype, NULL, tbaa_stack);
}
else {
oldval = mark_julia_type(ctx, instr, isboxed, jltype);
}
Done = emit_guarded_test(ctx, ctx.builder.CreateNot(Success), false, [&] {
Value *first_ptr = nullptr;
if (maybe_null_if_boxed)
first_ptr = isboxed ? instr : extract_first_ptr(ctx, instr);
return emit_nullcheck_guard(ctx, first_ptr, [&] {
return emit_f_is(ctx, oldval, cmp);
});
});
Done = ctx.builder.CreateNot(Done);
}
cast<PHINode>(Compare)->addIncoming(instr, ctx.builder.GetInsertBlock());
}
if (Succ != nullptr) {
Current->addIncoming(instr, ctx.builder.GetInsertBlock());
instr = Current;
Succ->addIncoming(Success, ctx.builder.GetInsertBlock());
Success = Succ;
}
if (needloop)
ctx.builder.CreateCondBr(Done, DoneBB, BB);
else
ctx.builder.CreateBr(DoneBB);
}
else {
#if JL_LLVM_VERSION >= 130000
instr = ctx.builder.CreateAtomicRMW(AtomicRMWInst::Xchg, ptr, r, Align(alignment), Order);
#else
auto *store = ctx.builder.CreateAtomicRMW(AtomicRMWInst::Xchg, ptr, r, Order);
store->setAlignment(Align(alignment));
instr = store;
#endif
if (aliasscope)
instr->setMetadata("noalias", aliasscope);
if (tbaa)
tbaa_decorate(tbaa, instr);
assert(DoneBB == nullptr);
}
if (DoneBB)
ctx.builder.SetInsertPoint(DoneBB);
if (needlock)
emit_lockstate_value(ctx, parent, false);
if (parent != NULL) {
BasicBlock *DoneBB;
if (isreplacefield) {
// TOOD: avoid this branch if we aren't making a write barrier
BasicBlock *BB = BasicBlock::Create(jl_LLVMContext, "xchg_wb", ctx.f);
DoneBB = BasicBlock::Create(jl_LLVMContext, "done_xchg_wb", ctx.f);
ctx.builder.CreateCondBr(Success, BB, DoneBB);
ctx.builder.SetInsertPoint(BB);
}
if (!isboxed)
emit_write_multibarrier(ctx, parent, r, rhs.typ);
else if (!type_is_permalloc(rhs.typ))
emit_write_barrier(ctx, parent, r);
if (isreplacefield) {
ctx.builder.CreateBr(DoneBB);
ctx.builder.SetInsertPoint(DoneBB);
}
}
if (!issetfield) {
if (intcast) {
ctx.builder.CreateStore(instr, ctx.builder.CreateBitCast(intcast, instr->getType()->getPointerTo()));
instr = ctx.builder.CreateLoad(intcast);
}
if (maybe_null_if_boxed) {
Value *first_ptr = isboxed ? instr : extract_first_ptr(ctx, instr);
if (first_ptr)
null_pointer_check(ctx, first_ptr, nullptr);
}
oldval = mark_julia_type(ctx, instr, isboxed, jltype);
if (isreplacefield) {
// TODO: do better here
jl_cgval_t argv[2] = {oldval, mark_julia_type(ctx, Success, false, jl_bool_type)};
instr = emit_jlcall(ctx, jltuple_func, V_rnull, argv, 2, JLCALL_F_CC);
oldval = mark_julia_type(ctx, instr, true, jl_any_type);
}
}
return oldval;
}
// --- convert boolean value to julia ---
// Returns T_pjlvalue
static Value *julia_bool(jl_codectx_t &ctx, Value *cond)
{
return ctx.builder.CreateSelect(cond, literal_pointer_val(ctx, jl_true),
literal_pointer_val(ctx, jl_false));
}
// --- accessing the representations of built-in data types ---
static Constant *julia_const_to_llvm(jl_codectx_t &ctx, jl_value_t *e);
static Value *data_pointer(jl_codectx_t &ctx, const jl_cgval_t &x)
{
assert(x.ispointer());
Value *data = x.V;
if (x.constant) {
Constant *val = julia_const_to_llvm(ctx, x.constant);
if (val)
data = get_pointer_to_constant(ctx.emission_context, val, "_j_const", *jl_Module);
else
data = literal_pointer_val(ctx, x.constant);
}
return data;
}
static void emit_memcpy_llvm(jl_codectx_t &ctx, Value *dst, MDNode *tbaa_dst, Value *src, MDNode *tbaa_src,
uint64_t sz, unsigned align, bool is_volatile)
{
if (sz == 0)
return;
assert(align && "align must be specified");
// If the types are small and simple, use load and store directly.
// Going through memcpy can cause LLVM (e.g. SROA) to create bitcasts between float and int
// that interferes with other optimizations.
if (sz <= 64) {
// The size limit is arbitrary but since we mainly care about floating points and
// machine size vectors this should be enough.
const DataLayout &DL = jl_data_layout;
auto srcty = cast<PointerType>(src->getType());
auto srcel = srcty->getElementType();
auto dstty = cast<PointerType>(dst->getType());
auto dstel = dstty->getElementType();
if (srcel->isArrayTy() && srcel->getArrayNumElements() == 1) {
src = ctx.builder.CreateConstInBoundsGEP2_32(srcel, src, 0, 0);
srcel = srcel->getArrayElementType();
srcty = srcel->getPointerTo();
}
if (dstel->isArrayTy() && dstel->getArrayNumElements() == 1) {
dst = ctx.builder.CreateConstInBoundsGEP2_32(dstel, dst, 0, 0);
dstel = dstel->getArrayElementType();
dstty = dstel->getPointerTo();
}
bool direct = false;
if (srcel->isSized() && srcel->isSingleValueType() && DL.getTypeStoreSize(srcel) == sz) {
direct = true;
dst = emit_bitcast(ctx, dst, srcty);
}
else if (dstel->isSized() && dstel->isSingleValueType() &&
DL.getTypeStoreSize(dstel) == sz) {
direct = true;
src = emit_bitcast(ctx, src, dstty);
}
if (direct) {
auto val = tbaa_decorate(tbaa_src, ctx.builder.CreateAlignedLoad(src, Align(align), is_volatile));
tbaa_decorate(tbaa_dst, ctx.builder.CreateAlignedStore(val, dst, Align(align), is_volatile));
return;
}
}
// the memcpy intrinsic does not allow to specify different alias tags
// for the load part (x.tbaa) and the store part (tbaa_stack).
// since the tbaa lattice has to be a tree we have unfortunately
// x.tbaa ∪ tbaa_stack = tbaa_root if x.tbaa != tbaa_stack
ctx.builder.CreateMemCpy(dst, MaybeAlign(align), src, MaybeAlign(0), sz, is_volatile, MDNode::getMostGenericTBAA(tbaa_dst, tbaa_src));
}
static void emit_memcpy_llvm(jl_codectx_t &ctx, Value *dst, MDNode *tbaa_dst, Value *src, MDNode *tbaa_src,
Value *sz, unsigned align, bool is_volatile)
{
if (auto const_sz = dyn_cast<ConstantInt>(sz)) {
emit_memcpy_llvm(ctx, dst, tbaa_dst, src, tbaa_src, const_sz->getZExtValue(), align, is_volatile);
return;
}
ctx.builder.CreateMemCpy(dst, MaybeAlign(align), src, MaybeAlign(0), sz, is_volatile, MDNode::getMostGenericTBAA(tbaa_dst, tbaa_src));
}
template<typename T1>
static void emit_memcpy(jl_codectx_t &ctx, Value *dst, MDNode *tbaa_dst, Value *src, MDNode *tbaa_src,
T1 &&sz, unsigned align, bool is_volatile=false)
{
emit_memcpy_llvm(ctx, dst, tbaa_dst, src, tbaa_src, sz, align, is_volatile);
}
template<typename T1>
static void emit_memcpy(jl_codectx_t &ctx, Value *dst, MDNode *tbaa_dst, const jl_cgval_t &src,
T1 &&sz, unsigned align, bool is_volatile=false)
{
emit_memcpy_llvm(ctx, dst, tbaa_dst, data_pointer(ctx, src), src.tbaa, sz, align, is_volatile);
}
static void emit_atomic_error(jl_codectx_t &ctx, const std::string &msg)
{
emit_error(ctx, prepare_call(jlatomicerror_func), msg);
}
static jl_cgval_t emit_getfield_knownidx(jl_codectx_t &ctx, const jl_cgval_t &strct,
unsigned idx, jl_datatype_t *jt,
enum jl_memory_order order, Value **nullcheck=nullptr);
static bool emit_getfield_unknownidx(jl_codectx_t &ctx,
jl_cgval_t *ret, jl_cgval_t strct,
Value *idx, jl_datatype_t *stt, jl_value_t *inbounds,
enum jl_memory_order order)
{
size_t nfields = jl_datatype_nfields(stt);
bool maybe_null = (unsigned)stt->name->n_uninitialized != 0;
auto idx0 = [&]() {
return emit_bounds_check(ctx, strct, (jl_value_t*)stt, idx, ConstantInt::get(T_size, nfields), inbounds);
};
if (nfields == 0) {
(void)idx0();
*ret = jl_cgval_t();
return true;
}
if (nfields == 1) {
if (jl_has_free_typevars(jl_field_type(stt, 0))) {
return false;
}
(void)idx0();
*ret = emit_getfield_knownidx(ctx, strct, 0, stt, order);
return true;
}
assert(!jl_is_vecelement_type((jl_value_t*)stt));
if (!strct.ispointer()) { // unboxed
assert(jl_is_concrete_immutable((jl_value_t*)stt));
bool isboxed = is_datatype_all_pointers(stt);
bool issame = is_tupletype_homogeneous(stt->types);
if (issame) {
jl_value_t *jft = jl_svecref(stt->types, 0);
if (strct.isghost) {
(void)idx0();
*ret = ghostValue(jft);
return true;
}
if (isa<VectorType>(strct.V->getType())) {
assert(stt->layout->npointers == 0); // we could, but don't emit this
idx = idx0();
if (sizeof(void*) != sizeof(int))
idx = ctx.builder.CreateTrunc(idx, T_int32); // llvm3.3 requires this, harmless elsewhere
Value *fld = ctx.builder.CreateExtractElement(strct.V, idx);
*ret = mark_julia_type(ctx, fld, isboxed, jft);
return true;
}
else if (isa<ArrayType>(strct.V->getType())) {
if (!isboxed && nfields > 3) {
// For small objects and tracked pointers, emit a set of Select statements,
// otherwise emit as a stack load. This keeps LLVM from becoming unhappy
// about seeing loads of tracked pointers.
strct = value_to_pointer(ctx, strct);
assert(strct.ispointer());
}
// fall-through to next branch, where we'll handle it
}
else {
llvm_unreachable("homogeneous struct should have had a homogeneous type");
}
}
if (isboxed || (issame && isa<ArrayType>(strct.V->getType()))) {
assert((cast<ArrayType>(strct.V->getType())->getElementType() == T_prjlvalue) == isboxed);
Value *idx = idx0();
unsigned i = 0;
Value *fld = ctx.builder.CreateExtractValue(strct.V, makeArrayRef(i));
for (i = 1; i < nfields; i++) {
fld = ctx.builder.CreateSelect(
ctx.builder.CreateICmpEQ(idx, ConstantInt::get(idx->getType(), i)),
ctx.builder.CreateExtractValue(strct.V, makeArrayRef(i)),
fld);
}
jl_value_t *jft = issame ? jl_svecref(stt->types, 0) : (jl_value_t*)jl_any_type;
if (isboxed && maybe_null)
null_pointer_check(ctx, fld);
*ret = mark_julia_type(ctx, fld, isboxed, jft);
return true;
}
}
bool maybeatomic = stt->name->atomicfields != NULL;
if (strct.ispointer() && !maybeatomic) { // boxed or stack
if (order != jl_memory_order_notatomic && order != jl_memory_order_unspecified) {
emit_atomic_error(ctx, "getfield: non-atomic field cannot be accessed atomically");
*ret = jl_cgval_t(); // unreachable
return true;
}
if (is_datatype_all_pointers(stt)) {
size_t minimum_field_size = std::numeric_limits<size_t>::max();
size_t minimum_align = JL_HEAP_ALIGNMENT;
for (size_t i = 0; i < nfields; ++i) {
jl_value_t *ft = jl_field_type(stt, i);
minimum_field_size = std::min(minimum_field_size,
dereferenceable_size(ft));
if (minimum_field_size == 0) {
minimum_align = 1;
break;
}
minimum_align = std::min(minimum_align,
(size_t)julia_alignment(ft));
}
Value *fldptr = ctx.builder.CreateInBoundsGEP(
T_prjlvalue,
maybe_decay_tracked(ctx, emit_bitcast(ctx, data_pointer(ctx, strct), T_pprjlvalue)),
idx0());
LoadInst *fld = ctx.builder.CreateAlignedLoad(T_prjlvalue, fldptr, Align(sizeof(void*)));
fld->setOrdering(AtomicOrdering::Unordered);
tbaa_decorate(strct.tbaa, fld);
maybe_mark_load_dereferenceable(fld, maybe_null, minimum_field_size, minimum_align);
if (maybe_null)
null_pointer_check(ctx, fld);
*ret = mark_julia_type(ctx, fld, true, jl_any_type);
return true;
}
else if (is_tupletype_homogeneous(stt->types)) {
assert(nfields > 0); // nf == 0 trapped by all_pointers case
jl_value_t *jft = jl_svecref(stt->types, 0);
assert(jl_is_concrete_type(jft));
idx = idx0();
Value *ptr = maybe_decay_tracked(ctx, data_pointer(ctx, strct));
if (!stt->name->mutabl && !(maybe_null && (jft == (jl_value_t*)jl_bool_type ||
((jl_datatype_t*)jft)->layout->npointers))) {
// just compute the pointer and let user load it when necessary
Type *fty = julia_type_to_llvm(ctx, jft);
Value *addr = ctx.builder.CreateInBoundsGEP(fty, emit_bitcast(ctx, ptr, PointerType::get(fty, 0)), idx);
*ret = mark_julia_slot(addr, jft, NULL, strct.tbaa);
return true;
}
*ret = typed_load(ctx, ptr, idx, jft, strct.tbaa, nullptr, false, AtomicOrdering::NotAtomic, maybe_null);
return true;
}
else if (strct.isboxed) {
idx = ctx.builder.CreateSub(idx, ConstantInt::get(T_size, 1));
Value *fld = ctx.builder.CreateCall(prepare_call(jlgetnthfieldchecked_func), { boxed(ctx, strct), idx });
*ret = mark_julia_type(ctx, fld, true, jl_any_type);
return true;
}
}
return false;
}
static jl_cgval_t emit_unionload(jl_codectx_t &ctx, Value *addr, Value *ptindex, jl_value_t *jfty, size_t fsz, size_t al, MDNode *tbaa, bool mutabl)
{
Instruction *tindex0 = tbaa_decorate(tbaa_unionselbyte, ctx.builder.CreateAlignedLoad(T_int8, ptindex, Align(1)));
//tindex0->setMetadata(LLVMContext::MD_range, MDNode::get(jl_LLVMContext, {
// ConstantAsMetadata::get(ConstantInt::get(T_int8, 0)),
// ConstantAsMetadata::get(ConstantInt::get(T_int8, union_max)) }));
Value *tindex = ctx.builder.CreateNUWAdd(ConstantInt::get(T_int8, 1), tindex0);
if (mutabl) {
// move value to an immutable stack slot (excluding tindex)
Type *ET = IntegerType::get(jl_LLVMContext, 8 * al);
AllocaInst *lv = emit_static_alloca(ctx, ET);
lv->setOperand(0, ConstantInt::get(T_int32, (fsz + al - 1) / al));
emit_memcpy(ctx, lv, tbaa, addr, tbaa, fsz, al);
addr = lv;
}
return mark_julia_slot(addr, jfty, tindex, tbaa);
}
// If `nullcheck` is not NULL and a pointer NULL check is necessary
// store the pointer to be checked in `*nullcheck` instead of checking it
static jl_cgval_t emit_getfield_knownidx(jl_codectx_t &ctx, const jl_cgval_t &strct,
unsigned idx, jl_datatype_t *jt,
enum jl_memory_order order, Value **nullcheck)
{
jl_value_t *jfty = jl_field_type(jt, idx);
bool isatomic = jl_field_isatomic(jt, idx);
bool needlock = isatomic && !jl_field_isptr(jt, idx) && jl_datatype_size(jfty) > MAX_ATOMIC_SIZE;
if (!isatomic && order != jl_memory_order_notatomic && order != jl_memory_order_unspecified) {
emit_atomic_error(ctx, "getfield: non-atomic field cannot be accessed atomically");
return jl_cgval_t(); // unreachable
}
if (isatomic && order == jl_memory_order_notatomic) {
emit_atomic_error(ctx, "getfield: atomic field cannot be accessed non-atomically");
return jl_cgval_t(); // unreachable
}
if (jfty == jl_bottom_type) {
raise_exception(ctx, literal_pointer_val(ctx, jl_undefref_exception));
return jl_cgval_t(); // unreachable
}
if (type_is_ghost(julia_type_to_llvm(ctx, jfty)))
return ghostValue(jfty);
size_t nfields = jl_datatype_nfields(jt);
bool maybe_null = idx >= nfields - (unsigned)jt->name->n_uninitialized;
size_t byte_offset = jl_field_offset(jt, idx);
auto tbaa = strct.tbaa;
if (tbaa == tbaa_datatype && byte_offset != offsetof(jl_datatype_t, types))
tbaa = tbaa_const;
if (strct.ispointer()) {
Value *staddr = maybe_decay_tracked(ctx, data_pointer(ctx, strct));
bool isboxed;
Type *lt = julia_type_to_llvm(ctx, (jl_value_t*)jt, &isboxed);
Value *addr;
if (isboxed) {
// byte_offset == 0 is an important special case here, e.g.
// for single field wrapper types. Introducing the bitcast
// can pessimize mem2reg
if (byte_offset > 0) {
addr = ctx.builder.CreateInBoundsGEP(
T_int8,
emit_bitcast(ctx, staddr, T_pint8),
ConstantInt::get(T_size, byte_offset));
}
else {
addr = staddr;
}
}
else {
staddr = maybe_bitcast(ctx, staddr, lt->getPointerTo());
if (jl_is_vecelement_type((jl_value_t*)jt))
addr = staddr; // VecElement types are unwrapped in LLVM.
else if (isa<StructType>(lt))
addr = emit_struct_gep(ctx, lt, staddr, byte_offset);
else
addr = ctx.builder.CreateConstInBoundsGEP2_32(lt, staddr, 0, idx);
}
if (jl_field_isptr(jt, idx)) {
LoadInst *Load = ctx.builder.CreateAlignedLoad(T_prjlvalue, maybe_bitcast(ctx, addr, T_pprjlvalue), Align(sizeof(void*)));
Load->setOrdering(order <= jl_memory_order_notatomic ? AtomicOrdering::Unordered : get_llvm_atomic_order(order));
maybe_mark_load_dereferenceable(Load, maybe_null, jl_field_type(jt, idx));
Value *fldv = tbaa_decorate(tbaa, Load);
if (maybe_null)
null_pointer_check(ctx, fldv, nullcheck);
return mark_julia_type(ctx, fldv, true, jfty);
}
else if (jl_is_uniontype(jfty)) {
size_t fsz = 0, al = 0;
bool isptr = !jl_islayout_inline(jfty, &fsz, &al);
assert(!isptr && fsz == jl_field_size(jt, idx) - 1); (void)isptr;
Value *ptindex;
if (isboxed) {
ptindex = ctx.builder.CreateConstInBoundsGEP1_32(
T_int8, emit_bitcast(ctx, staddr, T_pint8), byte_offset + fsz);
}
else {
ptindex = emit_struct_gep(ctx, cast<StructType>(lt), staddr, byte_offset + fsz);
}
return emit_unionload(ctx, addr, ptindex, jfty, fsz, al, tbaa, jt->name->mutabl);
}
assert(jl_is_concrete_type(jfty));
if (!jt->name->mutabl && !(maybe_null && (jfty == (jl_value_t*)jl_bool_type ||
((jl_datatype_t*)jfty)->layout->npointers))) {
// just compute the pointer and let user load it when necessary
return mark_julia_slot(addr, jfty, NULL, tbaa);
}
unsigned align = jl_field_align(jt, idx);
if (needlock)
emit_lockstate_value(ctx, strct, true);
jl_cgval_t ret = typed_load(ctx, addr, NULL, jfty, tbaa, nullptr, false,
needlock || order <= jl_memory_order_notatomic ? AtomicOrdering::NotAtomic : get_llvm_atomic_order(order), // TODO: we should use unordered for anything with CountTrackedPointers(elty).count > 0
maybe_null, align, nullcheck);
if (needlock)
emit_lockstate_value(ctx, strct, false);
return ret;
}
else if (isa<UndefValue>(strct.V)) {
return jl_cgval_t();
}
else {
Value *obj = strct.V; // aka emit_unbox
Type *T = obj->getType();
Value *fldv;
if (jl_is_vecelement_type((jl_value_t*)jt)) {
// VecElement types are unwrapped in LLVM.
fldv = obj;
}
else if (isa<VectorType>(T)) {
fldv = ctx.builder.CreateExtractElement(obj, ConstantInt::get(T_int32, idx));
}
else if (!jl_field_isptr(jt, idx) && jl_is_uniontype(jfty)) {
int fsz = jl_field_size(jt, idx) - 1;
unsigned ptindex = convert_struct_offset(ctx, T, byte_offset + fsz);
AllocaInst *lv = NULL;
if (fsz > 0) {
unsigned st_idx = convert_struct_offset(ctx, T, byte_offset);
IntegerType *ET = cast<IntegerType>(T->getStructElementType(st_idx));
unsigned align = (ET->getBitWidth() + 7) / 8;
lv = emit_static_alloca(ctx, ET);
lv->setOperand(0, ConstantInt::get(T_int32, (fsz + align - 1) / align));
// emit all of the align-sized words
unsigned i = 0;
for (; i < fsz / align; i++) {
unsigned fld = st_idx + i;
Value *fldv = ctx.builder.CreateExtractValue(obj, makeArrayRef(fld));
Value *fldp = ctx.builder.CreateConstInBoundsGEP1_32(ET, lv, i);
ctx.builder.CreateAlignedStore(fldv, fldp, Align(align));
}
// emit remaining bytes up to tindex
if (i < ptindex - st_idx) {
Value *staddr = ctx.builder.CreateConstInBoundsGEP1_32(ET, lv, i);
staddr = ctx.builder.CreateBitCast(staddr, T_pint8);
for (; i < ptindex - st_idx; i++) {
Value *fldv = ctx.builder.CreateExtractValue(obj, makeArrayRef(st_idx + i));
Value *fldp = ctx.builder.CreateConstInBoundsGEP1_32(T_int8, staddr, i);
ctx.builder.CreateAlignedStore(fldv, fldp, Align(1));
}
}
}
Value *tindex0 = ctx.builder.CreateExtractValue(obj, makeArrayRef(ptindex));
Value *tindex = ctx.builder.CreateNUWAdd(ConstantInt::get(T_int8, 1), tindex0);
return mark_julia_slot(lv, jfty, tindex, tbaa_stack);
}
else {
unsigned st_idx;
if (isa<ArrayType>(T))
st_idx = idx;
else if (isa<StructType>(T))
st_idx = convert_struct_offset(ctx, T, byte_offset);
else
llvm_unreachable("encountered incompatible type for a struct");
fldv = ctx.builder.CreateExtractValue(obj, makeArrayRef(st_idx));
}
if (maybe_null) {
Value *first_ptr = jl_field_isptr(jt, idx) ? fldv : extract_first_ptr(ctx, fldv);
if (first_ptr)
null_pointer_check(ctx, first_ptr, nullcheck);
}
return mark_julia_type(ctx, fldv, jl_field_isptr(jt, idx), jfty);
}
}
// emit length of vararg tuple
static Value *emit_n_varargs(jl_codectx_t &ctx)
{
Value *valen = NULL;
if (ctx.nvargs != -1) {
valen = ConstantInt::get(T_int32, ctx.nvargs);
} else {
assert(ctx.argCount);
int nreq = ctx.nReqArgs;
valen = ctx.builder.CreateSub((Value*)ctx.argCount,
ConstantInt::get(T_int32, nreq));
}
#ifdef _P64
return ctx.builder.CreateSExt(valen, T_int64);
#else
return valen;
#endif
}
static bool arraytype_constdim(jl_value_t *ty, size_t *dim)
{
if (jl_is_array_type(ty) && jl_is_long(jl_tparam1(ty))) {
*dim = jl_unbox_long(jl_tparam1(ty));
return true;
}
return false;
}
static bool arraytype_constshape(jl_value_t *ty)
{
size_t dim;
if (!arraytype_constdim(ty, &dim))
return false;
return dim != 1;
}
static bool arraytype_constelsize(jl_datatype_t *ty, size_t *elsz)
{
assert(jl_is_array_type(ty));
jl_value_t *ety = jl_tparam0(ty);
if (jl_has_free_typevars(ety))
return false;
// `jl_islayout_inline` requires `*elsz` and `al` to be initialized.
size_t al = 0;
*elsz = 0;
int union_max = jl_islayout_inline(ety, elsz, &al);
bool isboxed = (union_max == 0);
if (isboxed) {
*elsz = sizeof(void*);
}
else if (jl_is_primitivetype(ety)) {
// Primitive types should use the array element size, but
// this can be different from the type's size
*elsz = LLT_ALIGN(*elsz, al);
}
return true;
}
static intptr_t arraytype_maxsize(jl_value_t *ty)
{
if (!jl_is_array_type(ty))
return INTPTR_MAX;
size_t elsz;
if (arraytype_constelsize((jl_datatype_t*)ty, &elsz) || elsz == 0)
return INTPTR_MAX;
return INTPTR_MAX / elsz;
}
static Value *emit_arraysize(jl_codectx_t &ctx, const jl_cgval_t &tinfo, Value *dim)
{
size_t ndim;
MDNode *tbaa = tbaa_arraysize;
if (arraytype_constdim(tinfo.typ, &ndim)) {
if (ndim == 0)
return ConstantInt::get(T_size, 1);
if (ndim > 1) {
if (tinfo.constant && isa<ConstantInt>(dim)) {
auto n = cast<ConstantInt>(dim)->getZExtValue() - 1;
return ConstantInt::get(T_size, jl_array_dim(tinfo.constant, n));
}
tbaa = tbaa_const;
}
}
Value *t = boxed(ctx, tinfo);
int o = offsetof(jl_array_t, nrows) / sizeof(void*) - 1;
auto load = emit_nthptr_recast(ctx,
t,
ctx.builder.CreateAdd(dim, ConstantInt::get(dim->getType(), o)),
tbaa, T_psize);
MDBuilder MDB(jl_LLVMContext);
auto rng = MDB.createRange(V_size0, ConstantInt::get(T_size, arraytype_maxsize(tinfo.typ)));
load->setMetadata(LLVMContext::MD_range, rng);
return load;
}
static Value *emit_arraysize(jl_codectx_t &ctx, const jl_cgval_t &tinfo, int dim)
{
return emit_arraysize(ctx, tinfo, ConstantInt::get(T_int32, dim));
}
static Value *emit_vectormaxsize(jl_codectx_t &ctx, const jl_cgval_t &ary)
{
return emit_arraysize(ctx, ary, 2); // maxsize aliases ncols in memory layout for vector
}
static Value *emit_arraylen_prim(jl_codectx_t &ctx, const jl_cgval_t &tinfo)
{
size_t ndim;
jl_value_t *ty = tinfo.typ;
MDNode *tbaa = tbaa_arraylen;
if (arraytype_constdim(ty, &ndim)) {
if (ndim == 0)
return ConstantInt::get(T_size, 1);
if (ndim != 1) {
if (tinfo.constant)
return ConstantInt::get(T_size, jl_array_len(tinfo.constant));
tbaa = tbaa_const;
}
}
Value *t = boxed(ctx, tinfo);
#ifdef STORE_ARRAY_LEN
Value *addr = ctx.builder.CreateStructGEP(jl_array_llvmt,
emit_bitcast(ctx, decay_derived(ctx, t), jl_parray_llvmt),
1); //index (not offset) of length field in jl_parray_llvmt
LoadInst *len = ctx.builder.CreateAlignedLoad(addr, Align(sizeof(size_t)));
len->setOrdering(AtomicOrdering::NotAtomic);
MDBuilder MDB(jl_LLVMContext);
auto rng = MDB.createRange(V_size0, ConstantInt::get(T_size, arraytype_maxsize(tinfo.typ)));
len->setMetadata(LLVMContext::MD_range, rng);
return tbaa_decorate(tbaa, len);
#else
(void)tbaa;
jl_value_t *p1 = jl_tparam1(ty); // FIXME: check that ty is an array type
if (jl_is_long(p1)) {
size_t nd = jl_unbox_long(p1);
Value *l = ConstantInt::get(T_size, 1);
for(size_t i=0; i < nd; i++) {
l = ctx.builder.CreateMul(l, emit_arraysize(ctx, t, (int)(i + 1)));
}
return l;
}
else {
std::vector<Type *> fargt(0);
fargt.push_back(T_pjlvalue);
FunctionType *ft = FunctionType::get(T_size, fargt, false);
Value *alen = jl_Module->getOrInsertFunction("jl_array_len_", ft); // TODO: move to codegen init block
return ctx.builder.CreateCall(prepare_call(alen), t);
}
#endif
}
static Value *emit_arraylen(jl_codectx_t &ctx, const jl_cgval_t &tinfo)
{
return emit_arraylen_prim(ctx, tinfo);
}
static Value *emit_arrayptr_internal(jl_codectx_t &ctx, const jl_cgval_t &tinfo, Value *t, unsigned AS, bool isboxed)
{
Value *addr =
ctx.builder.CreateStructGEP(jl_array_llvmt,
emit_bitcast(ctx, t, jl_parray_llvmt),
0); // index (not offset) of data field in jl_parray_llvmt
// Normally allocated array of 0 dimention always have a inline pointer.
// However, we can't rely on that here since arrays can also be constructed from C pointers.
MDNode *tbaa = arraytype_constshape(tinfo.typ) ? tbaa_const : tbaa_arrayptr;
PointerType *PT = cast<PointerType>(addr->getType());
PointerType *PPT = cast<PointerType>(PT->getElementType());
if (isboxed) {
addr = ctx.builder.CreateBitCast(addr,
PointerType::get(PointerType::get(T_prjlvalue, AS),
PT->getAddressSpace()));
} else if (AS != PPT->getAddressSpace()) {
addr = ctx.builder.CreateBitCast(addr,
PointerType::get(
PointerType::get(PPT->getElementType(), AS),
PT->getAddressSpace()));
}
LoadInst *LI = ctx.builder.CreateAlignedLoad(addr, Align(sizeof(char*)));
LI->setOrdering(AtomicOrdering::NotAtomic);
LI->setMetadata(LLVMContext::MD_nonnull, MDNode::get(jl_LLVMContext, None));
tbaa_decorate(tbaa, LI);
return LI;
}
static Value *emit_arrayptr(jl_codectx_t &ctx, const jl_cgval_t &tinfo, bool isboxed = false)
{
Value *t = boxed(ctx, tinfo);
return emit_arrayptr_internal(ctx, tinfo, decay_derived(ctx, t), AddressSpace::Loaded, isboxed);
}
static Value *emit_unsafe_arrayptr(jl_codectx_t &ctx, const jl_cgval_t &tinfo, bool isboxed = false)
{
Value *t = boxed(ctx, tinfo);
t = emit_pointer_from_objref(ctx, decay_derived(ctx, t));
return emit_arrayptr_internal(ctx, tinfo, t, 0, isboxed);
}
static Value *emit_arrayptr(jl_codectx_t &ctx, const jl_cgval_t &tinfo, jl_value_t *ex, bool isboxed = false)
{
return emit_arrayptr(ctx, tinfo, isboxed);
}
static Value *emit_arraysize(jl_codectx_t &ctx, const jl_cgval_t &tinfo, jl_value_t *ex, int dim)
{
return emit_arraysize(ctx, tinfo, dim);
}
static Value *emit_arrayflags(jl_codectx_t &ctx, const jl_cgval_t &tinfo)
{
Value *t = boxed(ctx, tinfo);
#ifdef STORE_ARRAY_LEN
int arrayflag_field = 2;
#else
int arrayflag_field = 1;
#endif
Value *addr = ctx.builder.CreateStructGEP(
jl_array_llvmt,
emit_bitcast(ctx, decay_derived(ctx, t), jl_parray_llvmt),
arrayflag_field);
return tbaa_decorate(tbaa_arrayflags, ctx.builder.CreateAlignedLoad(T_int16, addr, Align(sizeof(int16_t))));
}
static Value *emit_arrayndims(jl_codectx_t &ctx, const jl_cgval_t &ary)
{
Value *flags = emit_arrayflags(ctx, ary);
cast<LoadInst>(flags)->setMetadata(LLVMContext::MD_invariant_load, MDNode::get(jl_LLVMContext, None));
flags = ctx.builder.CreateLShr(flags, 2);
flags = ctx.builder.CreateAnd(flags, 0x1FF); // (1<<9) - 1
return flags;
}
static Value *emit_arrayelsize(jl_codectx_t &ctx, const jl_cgval_t &tinfo)
{
Value *t = boxed(ctx, tinfo);
#ifdef STORE_ARRAY_LEN
int elsize_field = 3;
#else
int elsize_field = 2;
#endif
Value *addr = ctx.builder.CreateStructGEP(jl_array_llvmt,
emit_bitcast(ctx, decay_derived(ctx, t), jl_parray_llvmt),
elsize_field);
return tbaa_decorate(tbaa_const, ctx.builder.CreateAlignedLoad(T_int16, addr, Align(sizeof(int16_t))));
}
static Value *emit_arrayoffset(jl_codectx_t &ctx, const jl_cgval_t &tinfo, int nd)
{
if (nd != -1 && nd != 1) // only Vector can have an offset
return ConstantInt::get(T_int32, 0);
Value *t = boxed(ctx, tinfo);
#ifdef STORE_ARRAY_LEN
int offset_field = 4;
#else
int offset_field = 3;
#endif
Value *addr = ctx.builder.CreateStructGEP(
jl_array_llvmt,
emit_bitcast(ctx, decay_derived(ctx, t), jl_parray_llvmt),
offset_field);
return tbaa_decorate(tbaa_arrayoffset, ctx.builder.CreateAlignedLoad(T_int32, addr, Align(sizeof(int32_t))));
}
// Returns the size of the array represented by `tinfo` for the given dimension `dim` if
// `dim` is a valid dimension, otherwise returns constant one.
static Value *emit_arraysize_for_unsafe_dim(jl_codectx_t &ctx,
const jl_cgval_t &tinfo, jl_value_t *ex, size_t dim, size_t nd)
{
return dim > nd ? ConstantInt::get(T_size, 1) : emit_arraysize(ctx, tinfo, ex, dim);
}
// `nd == -1` means the dimension is unknown.
static Value *emit_array_nd_index(
jl_codectx_t &ctx, const jl_cgval_t &ainfo, jl_value_t *ex, ssize_t nd,
const jl_cgval_t *argv, size_t nidxs, jl_value_t *inbounds)
{
Value *a = boxed(ctx, ainfo);
Value *i = V_size0;
Value *stride = ConstantInt::get(T_size, 1);
#if CHECK_BOUNDS==1
bool bc = bounds_check_enabled(ctx, inbounds);
BasicBlock *failBB = NULL, *endBB = NULL;
if (bc) {
failBB = BasicBlock::Create(jl_LLVMContext, "oob");
endBB = BasicBlock::Create(jl_LLVMContext, "idxend");
}
#endif
Value **idxs = (Value**)alloca(sizeof(Value*) * nidxs);
for (size_t k = 0; k < nidxs; k++) {
idxs[k] = emit_unbox(ctx, T_size, argv[k], (jl_value_t*)jl_long_type); // type asserted by caller
}
Value *ii = NULL;
for (size_t k = 0; k < nidxs; k++) {
ii = ctx.builder.CreateSub(idxs[k], ConstantInt::get(T_size, 1));
i = ctx.builder.CreateAdd(i, ctx.builder.CreateMul(ii, stride));
if (k < nidxs - 1) {
assert(nd >= 0);
Value *d = emit_arraysize_for_unsafe_dim(ctx, ainfo, ex, k + 1, nd);
#if CHECK_BOUNDS==1
if (bc) {
BasicBlock *okBB = BasicBlock::Create(jl_LLVMContext, "ib");
// if !(i < d) goto error
ctx.builder.CreateCondBr(ctx.builder.CreateICmpULT(ii, d), okBB, failBB);
ctx.f->getBasicBlockList().push_back(okBB);
ctx.builder.SetInsertPoint(okBB);
}
#endif
stride = ctx.builder.CreateMul(stride, d);
}
}
#if CHECK_BOUNDS==1
if (bc) {
// We have already emitted a bounds check for each index except for
// the last one which we therefore have to do here.
if (nidxs == 1) {
// Linear indexing: Check against the entire linear span of the array
Value *alen = emit_arraylen(ctx, ainfo);
ctx.builder.CreateCondBr(ctx.builder.CreateICmpULT(i, alen), endBB, failBB);
} else if (nidxs >= (size_t)nd){
// No dimensions were omitted; just check the last remaining index
assert(nd >= 0);
Value *last_index = ii;
Value *last_dimension = emit_arraysize_for_unsafe_dim(ctx, ainfo, ex, nidxs, nd);
ctx.builder.CreateCondBr(ctx.builder.CreateICmpULT(last_index, last_dimension), endBB, failBB);
} else {
// There were fewer indices than dimensions; check the last remaining index
BasicBlock *checktrailingdimsBB = BasicBlock::Create(jl_LLVMContext, "dimsib");
assert(nd >= 0);
Value *last_index = ii;
Value *last_dimension = emit_arraysize_for_unsafe_dim(ctx, ainfo, ex, nidxs, nd);
ctx.builder.CreateCondBr(ctx.builder.CreateICmpULT(last_index, last_dimension), checktrailingdimsBB, failBB);
ctx.f->getBasicBlockList().push_back(checktrailingdimsBB);
ctx.builder.SetInsertPoint(checktrailingdimsBB);
// And then also make sure that all dimensions that weren't explicitly
// indexed into have size 1
for (size_t k = nidxs+1; k < (size_t)nd; k++) {
BasicBlock *dimsokBB = BasicBlock::Create(jl_LLVMContext, "dimsok");
Value *dim = emit_arraysize_for_unsafe_dim(ctx, ainfo, ex, k, nd);
ctx.builder.CreateCondBr(ctx.builder.CreateICmpEQ(dim, ConstantInt::get(T_size, 1)), dimsokBB, failBB);
ctx.f->getBasicBlockList().push_back(dimsokBB);
ctx.builder.SetInsertPoint(dimsokBB);
}
Value *dim = emit_arraysize_for_unsafe_dim(ctx, ainfo, ex, nd, nd);
ctx.builder.CreateCondBr(ctx.builder.CreateICmpEQ(dim, ConstantInt::get(T_size, 1)), endBB, failBB);
}
ctx.f->getBasicBlockList().push_back(failBB);
ctx.builder.SetInsertPoint(failBB);
// CreateAlloca is OK here since we are on an error branch
Value *tmp = ctx.builder.CreateAlloca(T_size, ConstantInt::get(T_size, nidxs));
for (size_t k = 0; k < nidxs; k++) {
ctx.builder.CreateAlignedStore(idxs[k], ctx.builder.CreateInBoundsGEP(T_size, tmp, ConstantInt::get(T_size, k)), Align(sizeof(size_t)));
}
ctx.builder.CreateCall(prepare_call(jlboundserrorv_func),
{ mark_callee_rooted(ctx, a), tmp, ConstantInt::get(T_size, nidxs) });
ctx.builder.CreateUnreachable();
ctx.f->getBasicBlockList().push_back(endBB);
ctx.builder.SetInsertPoint(endBB);
}
#endif
return i;
}
// --- boxing ---
static Value *emit_allocobj(jl_codectx_t &ctx, size_t static_size, Value *jt);
static void init_bits_value(jl_codectx_t &ctx, Value *newv, Value *v, MDNode *tbaa,
unsigned alignment = sizeof(void*)) // min alignment in julia's gc is pointer-aligned
{
// newv should already be tagged
tbaa_decorate(tbaa, ctx.builder.CreateAlignedStore(v, emit_bitcast(ctx, newv,
PointerType::get(v->getType(), 0)), Align(alignment)));
}
static void init_bits_cgval(jl_codectx_t &ctx, Value *newv, const jl_cgval_t& v, MDNode *tbaa)
{
// newv should already be tagged
if (v.ispointer()) {
emit_memcpy(ctx, newv, tbaa, v, jl_datatype_size(v.typ), sizeof(void*));
}
else {
init_bits_value(ctx, newv, v.V, tbaa);
}
}
static jl_value_t *static_constant_instance(Constant *constant, jl_value_t *jt)
{
assert(constant != NULL && jl_is_concrete_type(jt));
jl_datatype_t *jst = (jl_datatype_t*)jt;
if (isa<UndefValue>(constant))
return NULL;
if (ConstantInt *cint = dyn_cast<ConstantInt>(constant)) {
if (jst == jl_bool_type)
return cint->isZero() ? jl_false : jl_true;
return jl_new_bits(jt,
const_cast<uint64_t *>(cint->getValue().getRawData()));
}
if (ConstantFP *cfp = dyn_cast<ConstantFP>(constant)) {
return jl_new_bits(jt,
const_cast<uint64_t *>(cfp->getValueAPF().bitcastToAPInt().getRawData()));
}
if (isa<ConstantPointerNull>(constant)) {
uint64_t val = 0;
return jl_new_bits(jt, &val);
}
// issue #8464
if (ConstantExpr *ce = dyn_cast<ConstantExpr>(constant)) {
unsigned OpCode = ce->getOpcode();
if (OpCode == Instruction::BitCast || OpCode == Instruction::PtrToInt || OpCode == Instruction::IntToPtr) {
return static_constant_instance(ce->getOperand(0), jt);
}
return NULL;
}
if (isa<GlobalValue>(constant))
return NULL;
size_t nargs;
if (const auto *CC = dyn_cast<ConstantAggregate>(constant))
nargs = CC->getNumOperands();
else if (const auto *CAZ = dyn_cast<ConstantAggregateZero>(constant))
nargs = CAZ->getNumElements();
else if (const auto *CDS = dyn_cast<ConstantDataSequential>(constant))
nargs = CDS->getNumElements();
else
return NULL;
assert(nargs > 0 && jst->instance == NULL);
if (nargs != jl_datatype_nfields(jst))
return NULL;
jl_value_t **flds;
JL_GC_PUSHARGS(flds, nargs);
for (size_t i = 0; i < nargs; i++) {
jl_value_t *ft = jl_field_type(jst, i);
if (jl_field_isptr(jst, i) || jl_is_uniontype(ft)) {
JL_GC_POP();
return NULL; // TODO: handle this?
}
unsigned llvm_idx = i;
if (i > 0 && isa<StructType>(constant->getType()))
llvm_idx = convert_struct_offset(constant->getType(), jl_field_offset(jst, i));
Constant *fld = constant->getAggregateElement(llvm_idx);
flds[i] = static_constant_instance(fld, ft);
if (flds[i] == NULL) {
JL_GC_POP();
return NULL; // must have been unreachable
}
}
jl_value_t *obj = jl_new_structv(jst, flds, nargs);
JL_GC_POP();
return obj;
}
static Value *call_with_attrs(jl_codectx_t &ctx, JuliaFunction *intr, Value *v)
{
Function *F = prepare_call(intr);
CallInst *Call = ctx.builder.CreateCall(F, v);
Call->setAttributes(F->getAttributes());
return Call;
}
static void jl_add_method_root(jl_codectx_t &ctx, jl_value_t *val);
static Value *as_value(jl_codectx_t &ctx, Type *to, const jl_cgval_t &v)
{
assert(!v.isboxed);
return emit_unbox(ctx, to, v, v.typ);
}
static Value *load_i8box(jl_codectx_t &ctx, Value *v, jl_datatype_t *ty)
{
auto jvar = ty == jl_int8_type ? jlboxed_int8_cache : jlboxed_uint8_cache;
Constant *gv = prepare_global_in(jl_Module, jvar);
Value *idx[] = {ConstantInt::get(T_int32, 0), ctx.builder.CreateZExt(v, T_int32)};
auto slot = ctx.builder.CreateInBoundsGEP(gv, idx);
return tbaa_decorate(tbaa_const, maybe_mark_load_dereferenceable(
ctx.builder.CreateAlignedLoad(T_pjlvalue, slot, Align(sizeof(void*))), false,
(jl_value_t*)ty));
}
// some types have special boxing functions with small-value caches
// Returns T_prjlvalue
static Value *_boxed_special(jl_codectx_t &ctx, const jl_cgval_t &vinfo, Type *t)
{
jl_value_t *jt = vinfo.typ;
if (jt == (jl_value_t*)jl_bool_type)
return track_pjlvalue(ctx, julia_bool(ctx, ctx.builder.CreateTrunc(as_value(ctx, t, vinfo), T_int1)));
if (t == T_int1)
return track_pjlvalue(ctx, julia_bool(ctx, as_value(ctx, t, vinfo)));
if (ctx.linfo && jl_is_method(ctx.linfo->def.method) && !vinfo.ispointer()) { // don't bother codegen pre-boxing for toplevel
if (Constant *c = dyn_cast<Constant>(vinfo.V)) {
jl_value_t *s = static_constant_instance(c, jt);
if (s) {
jl_add_method_root(ctx, s);
return track_pjlvalue(ctx, literal_pointer_val(ctx, s));
}
}
}
jl_datatype_t *jb = (jl_datatype_t*)jt;
assert(jl_is_datatype(jb));
Value *box = NULL;
if (jb == jl_int8_type)
box = track_pjlvalue(ctx, load_i8box(ctx, as_value(ctx, t, vinfo), jb));
else if (jb == jl_int16_type)
box = call_with_attrs(ctx, box_int16_func, as_value(ctx, t, vinfo));
else if (jb == jl_int32_type)
box = call_with_attrs(ctx, box_int32_func, as_value(ctx, t, vinfo));
else if (jb == jl_int64_type)
box = call_with_attrs(ctx, box_int64_func, as_value(ctx, t, vinfo));
else if (jb == jl_float32_type)
box = ctx.builder.CreateCall(prepare_call(box_float32_func), as_value(ctx, t, vinfo));
//if (jb == jl_float64_type)
// box = ctx.builder.CreateCall(box_float64_func, as_value(ctx, t, vinfo);
// for Float64, fall through to generic case below, to inline alloc & init of Float64 box. cheap, I know.
else if (jb == jl_uint8_type)
box = track_pjlvalue(ctx, load_i8box(ctx, as_value(ctx, t, vinfo), jb));
else if (jb == jl_uint16_type)
box = call_with_attrs(ctx, box_uint16_func, as_value(ctx, t, vinfo));
else if (jb == jl_uint32_type)
box = call_with_attrs(ctx, box_uint32_func, as_value(ctx, t, vinfo));
else if (jb == jl_uint64_type)
box = call_with_attrs(ctx, box_uint64_func, as_value(ctx, t, vinfo));
else if (jb == jl_char_type)
box = call_with_attrs(ctx, box_char_func, as_value(ctx, t, vinfo));
else if (jb == jl_ssavalue_type) {
unsigned zero = 0;
Value *v = as_value(ctx, t, vinfo);
assert(v->getType() == ctx.emission_context.llvmtypes[jl_ssavalue_type]);
v = ctx.builder.CreateExtractValue(v, makeArrayRef(&zero, 1));
box = call_with_attrs(ctx, box_ssavalue_func, v);
}
else if (!jb->name->abstract && jl_datatype_nbits(jb) == 0) {
// singleton
assert(jb->instance != NULL);
return track_pjlvalue(ctx, literal_pointer_val(ctx, jb->instance));
}
return box;
}
static Value *compute_box_tindex(jl_codectx_t &ctx, Value *datatype, jl_value_t *supertype, jl_value_t *ut)
{
Value *tindex = ConstantInt::get(T_int8, 0);
unsigned counter = 0;
for_each_uniontype_small(
[&](unsigned idx, jl_datatype_t *jt) {
if (jl_subtype((jl_value_t*)jt, supertype)) {
Value *cmp = ctx.builder.CreateICmpEQ(track_pjlvalue(ctx, literal_pointer_val(ctx, (jl_value_t*)jt)), datatype);
tindex = ctx.builder.CreateSelect(cmp, ConstantInt::get(T_int8, idx), tindex);
}
},
ut,
counter);
return tindex;
}
// Returns typeof(v), or null if v is a null pointer at run time.
// This is used when the value might have come from an undefined variable,
// yet we try to read its type to compute a union index when moving the value.
static Value *emit_typeof_or_null(jl_codectx_t &ctx, Value *v)
{
BasicBlock *nonnull = BasicBlock::Create(jl_LLVMContext, "nonnull", ctx.f);
BasicBlock *postBB = BasicBlock::Create(jl_LLVMContext, "postnull", ctx.f);
Value *isnull = ctx.builder.CreateICmpEQ(v, Constant::getNullValue(v->getType()));
ctx.builder.CreateCondBr(isnull, postBB, nonnull);
BasicBlock *entry = ctx.builder.GetInsertBlock();
ctx.builder.SetInsertPoint(nonnull);
Value *typof = emit_typeof(ctx, v);
ctx.builder.CreateBr(postBB);
nonnull = ctx.builder.GetInsertBlock(); // could have changed
ctx.builder.SetInsertPoint(postBB);
PHINode *ti = ctx.builder.CreatePHI(typof->getType(), 2);
ti->addIncoming(Constant::getNullValue(typof->getType()), entry);
ti->addIncoming(typof, nonnull);
return ti;
}
// get the runtime tindex value, assuming val is already converted to type typ if it has a TIndex
static Value *compute_tindex_unboxed(jl_codectx_t &ctx, const jl_cgval_t &val, jl_value_t *typ)
{
if (val.typ == jl_bottom_type)
return UndefValue::get(T_int8);
if (val.constant)
return ConstantInt::get(T_int8, get_box_tindex((jl_datatype_t*)jl_typeof(val.constant), typ));
if (val.TIndex)
return ctx.builder.CreateAnd(val.TIndex, ConstantInt::get(T_int8, 0x7f));
Value *typof;
if (val.isboxed && !jl_is_concrete_type(val.typ) && !jl_is_type_type(val.typ))
typof = emit_typeof_or_null(ctx, val.V);
else
typof = emit_typeof_boxed(ctx, val);
return compute_box_tindex(ctx, typof, val.typ, typ);
}
static void union_alloca_type(jl_uniontype_t *ut,
bool &allunbox, size_t &nbytes, size_t &align, size_t &min_align)
{
nbytes = 0;
align = 0;
min_align = MAX_ALIGN;
// compute the size of the union alloca that could hold this type
unsigned counter = 0;
allunbox = for_each_uniontype_small(
[&](unsigned idx, jl_datatype_t *jt) {
if (!jl_is_datatype_singleton(jt)) {
size_t nb1 = jl_datatype_size(jt);
size_t align1 = jl_datatype_align(jt);
if (nb1 > nbytes)
nbytes = nb1;
if (align1 > align)
align = align1;
if (align1 < min_align)
min_align = align1;
}
},
(jl_value_t*)ut,
counter);
}
static AllocaInst *try_emit_union_alloca(jl_codectx_t &ctx, jl_uniontype_t *ut, bool &allunbox, size_t &min_align, size_t &nbytes)
{
size_t align;
union_alloca_type(ut, allunbox, nbytes, align, min_align);
if (nbytes > 0) {
// at least some of the values can live on the stack
// try to pick an Integer type size such that SROA will emit reasonable code
Type *AT = ArrayType::get(IntegerType::get(jl_LLVMContext, 8 * min_align), (nbytes + min_align - 1) / min_align);
AllocaInst *lv = emit_static_alloca(ctx, AT);
if (align > 1)
lv->setAlignment(Align(align));
return lv;
}
return NULL;
}
/*
* Box unboxed values in a union. Optionally, skip certain unboxed values,
* returning `V_null` in one of the skipped cases. If `skip` is not empty,
* skip[0] (corresponding to unknown boxed) must always be set. In that
* case, the calling code must separately deal with the case where
* `vinfo` is already an unknown boxed union (union tag 0x80).
*/
// Returns T_prjlvalue
static Value *box_union(jl_codectx_t &ctx, const jl_cgval_t &vinfo, const SmallBitVector &skip)
{
// given vinfo::Union{T, S}, emit IR of the form:
// ...
// switch <tindex>, label <box_union_isboxed> [ 1, label <box_union_1>
// 2, label <box_union_2> ]
// box_union_1:
// box1 = create_box(T)
// br post_box_union
// box_union_2:
// box2 = create_box(S)
// br post_box_union
// box_union_isboxed:
// br post_box_union
// post_box_union:
// box = phi [ box1, box_union_1 ], [ box2, box_union_2 ], [ vinfo, box_union_isboxed ]
// ...
Value *tindex = vinfo.TIndex;
BasicBlock *defaultBB = BasicBlock::Create(jl_LLVMContext, "box_union_isboxed", ctx.f);
SwitchInst *switchInst = ctx.builder.CreateSwitch(tindex, defaultBB);
BasicBlock *postBB = BasicBlock::Create(jl_LLVMContext, "post_box_union", ctx.f);
ctx.builder.SetInsertPoint(postBB);
PHINode *box_merge = ctx.builder.CreatePHI(T_prjlvalue, 2);
unsigned counter = 0;
for_each_uniontype_small(
[&](unsigned idx, jl_datatype_t *jt) {
if (idx < skip.size() && skip[idx])
return;
Type *t = julia_type_to_llvm(ctx, (jl_value_t*)jt);
BasicBlock *tempBB = BasicBlock::Create(jl_LLVMContext, "box_union", ctx.f);
ctx.builder.SetInsertPoint(tempBB);
switchInst->addCase(ConstantInt::get(T_int8, idx), tempBB);
Value *box;
if (type_is_ghost(t)) {
box = track_pjlvalue(ctx, literal_pointer_val(ctx, jt->instance));
}
else {
jl_cgval_t vinfo_r = jl_cgval_t(vinfo, (jl_value_t*)jt, NULL);
box = _boxed_special(ctx, vinfo_r, t);
if (!box) {
box = emit_allocobj(ctx, jl_datatype_size(jt), literal_pointer_val(ctx, (jl_value_t*)jt));
init_bits_cgval(ctx, box, vinfo_r, jl_is_mutable(jt) ? tbaa_mutab : tbaa_immut);
}
}
tempBB = ctx.builder.GetInsertBlock(); // could have changed
box_merge->addIncoming(box, tempBB);
ctx.builder.CreateBr(postBB);
},
vinfo.typ,
counter);
ctx.builder.SetInsertPoint(defaultBB);
if (skip.size() > 0) {
assert(skip[0]);
box_merge->addIncoming(V_rnull, defaultBB);
ctx.builder.CreateBr(postBB);
}
else if (!vinfo.Vboxed) {
Function *trap_func = Intrinsic::getDeclaration(
ctx.f->getParent(),
Intrinsic::trap);
ctx.builder.CreateCall(trap_func);
ctx.builder.CreateUnreachable();
}
else {
box_merge->addIncoming(vinfo.Vboxed, defaultBB);
ctx.builder.CreateBr(postBB);
}
ctx.builder.SetInsertPoint(postBB);
return box_merge;
}
// this is used to wrap values for generic contexts, where a
// dynamically-typed value is required (e.g. argument to unknown function).
// if it's already a pointer it's left alone.
// Returns T_prjlvalue
static Value *boxed(jl_codectx_t &ctx, const jl_cgval_t &vinfo)
{
jl_value_t *jt = vinfo.typ;
if (jt == jl_bottom_type || jt == NULL)
// We have an undef value on a (hopefully) dead branch
return UndefValue::get(T_prjlvalue);
if (vinfo.constant)
return track_pjlvalue(ctx, literal_pointer_val(ctx, vinfo.constant));
// This can happen in early bootstrap for `gc_preserve_begin` return value.
if (jt == (jl_value_t*)jl_nothing_type)
return track_pjlvalue(ctx, literal_pointer_val(ctx, jl_nothing));
if (vinfo.isboxed) {
assert(vinfo.V == vinfo.Vboxed);
assert(vinfo.V->getType() == T_prjlvalue);
return vinfo.V;
}
Value *box;
if (vinfo.TIndex) {
SmallBitVector skip_none;
box = box_union(ctx, vinfo, skip_none);
}
else {
assert(vinfo.V && "Missing data for unboxed value.");
assert(jl_is_concrete_immutable(jt) && "This type shouldn't have been unboxed.");
Type *t = julia_type_to_llvm(ctx, jt);
assert(!type_is_ghost(t)); // ghost values should have been handled by vinfo.constant above!
box = _boxed_special(ctx, vinfo, t);
if (!box) {
box = emit_allocobj(ctx, jl_datatype_size(jt), literal_pointer_val(ctx, (jl_value_t*)jt));
init_bits_cgval(ctx, box, vinfo, jl_is_mutable(jt) ? tbaa_mutab : tbaa_immut);
}
}
return box;
}
// copy src to dest, if src is justbits. if skip is true, the value of dest is undefined
static void emit_unionmove(jl_codectx_t &ctx, Value *dest, MDNode *tbaa_dst, const jl_cgval_t &src, Value *skip, bool isVolatile=false)
{
if (AllocaInst *ai = dyn_cast<AllocaInst>(dest))
// TODO: make this a lifetime_end & dereferencable annotation?
ctx.builder.CreateAlignedStore(UndefValue::get(ai->getAllocatedType()), ai, ai->getAlign());
if (jl_is_concrete_type(src.typ) || src.constant) {
jl_value_t *typ = src.constant ? jl_typeof(src.constant) : src.typ;
Type *store_ty = julia_type_to_llvm(ctx, typ);
assert(skip || jl_is_pointerfree(typ));
if (jl_is_pointerfree(typ)) {
if (!src.ispointer() || src.constant) {
emit_unbox(ctx, store_ty, src, typ, dest, tbaa_dst, isVolatile);
}
else {
Value *src_ptr = data_pointer(ctx, src);
unsigned nb = jl_datatype_size(typ);
unsigned alignment = julia_alignment(typ);
Value *nbytes = ConstantInt::get(T_size, nb);
if (skip) {
// TODO: this Select is very bad for performance, but is necessary to work around LLVM bugs with the undef option that we want to use:
// select copy dest -> dest to simulate an undef value / conditional copy
// src_ptr = ctx.builder.CreateSelect(skip, dest, src_ptr);
nbytes = ctx.builder.CreateSelect(skip, V_size0, nbytes);
}
emit_memcpy(ctx, dest, tbaa_dst, src_ptr, src.tbaa, nbytes, alignment, isVolatile);
}
}
}
else if (src.TIndex) {
Value *tindex = ctx.builder.CreateAnd(src.TIndex, ConstantInt::get(T_int8, 0x7f));
if (skip)
tindex = ctx.builder.CreateSelect(skip, ConstantInt::get(T_int8, 0), tindex);
Value *src_ptr = data_pointer(ctx, src);
src_ptr = src_ptr ? maybe_bitcast(ctx, src_ptr, T_pint8) : src_ptr;
dest = maybe_bitcast(ctx, dest, T_pint8);
BasicBlock *defaultBB = BasicBlock::Create(jl_LLVMContext, "union_move_skip", ctx.f);
SwitchInst *switchInst = ctx.builder.CreateSwitch(tindex, defaultBB);
BasicBlock *postBB = BasicBlock::Create(jl_LLVMContext, "post_union_move", ctx.f);
unsigned counter = 0;
bool allunboxed = for_each_uniontype_small(
[&](unsigned idx, jl_datatype_t *jt) {
unsigned nb = jl_datatype_size(jt);
unsigned alignment = julia_alignment((jl_value_t*)jt);
BasicBlock *tempBB = BasicBlock::Create(jl_LLVMContext, "union_move", ctx.f);
ctx.builder.SetInsertPoint(tempBB);
switchInst->addCase(ConstantInt::get(T_int8, idx), tempBB);
if (nb > 0) {
if (!src_ptr) {
Function *trap_func =
Intrinsic::getDeclaration(ctx.f->getParent(), Intrinsic::trap);
ctx.builder.CreateCall(trap_func);
ctx.builder.CreateUnreachable();
return;
} else {
emit_memcpy(ctx, dest, tbaa_dst, src_ptr,
src.tbaa, nb, alignment, isVolatile);
}
}
ctx.builder.CreateBr(postBB);
},
src.typ,
counter);
ctx.builder.SetInsertPoint(defaultBB);
if (!skip && allunboxed && (src.V == NULL || isa<AllocaInst>(src.V))) {
Function *trap_func = Intrinsic::getDeclaration(
ctx.f->getParent(),
Intrinsic::trap);
ctx.builder.CreateCall(trap_func);
ctx.builder.CreateUnreachable();
}
else {
ctx.builder.CreateBr(postBB);
}
ctx.builder.SetInsertPoint(postBB);
}
else {
assert(src.isboxed && "expected boxed value for sizeof/alignment computation");
Value *datatype = emit_typeof_boxed(ctx, src);
Value *copy_bytes = emit_datatype_size(ctx, datatype);
if (skip) {
copy_bytes = ctx.builder.CreateSelect(skip, ConstantInt::get(copy_bytes->getType(), 0), copy_bytes);
}
emit_memcpy(ctx, dest, tbaa_dst, src, copy_bytes, /*TODO: min-align*/1, isVolatile);
}
}
static void emit_cpointercheck(jl_codectx_t &ctx, const jl_cgval_t &x, const std::string &msg)
{
Value *t = emit_typeof_boxed(ctx, x);
emit_typecheck(ctx, mark_julia_type(ctx, t, true, jl_any_type), (jl_value_t*)jl_datatype_type, msg);
Value *istype =
ctx.builder.CreateICmpEQ(mark_callee_rooted(ctx, emit_datatype_name(ctx, t)),
mark_callee_rooted(ctx, literal_pointer_val(ctx, (jl_value_t*)jl_pointer_typename)));
BasicBlock *failBB = BasicBlock::Create(jl_LLVMContext,"fail",ctx.f);
BasicBlock *passBB = BasicBlock::Create(jl_LLVMContext,"pass");
ctx.builder.CreateCondBr(istype, passBB, failBB);
ctx.builder.SetInsertPoint(failBB);
emit_type_error(ctx, x, literal_pointer_val(ctx, (jl_value_t*)jl_pointer_type), msg);
ctx.builder.CreateUnreachable();
ctx.f->getBasicBlockList().push_back(passBB);
ctx.builder.SetInsertPoint(passBB);
}
// allocation for known size object
static Value *emit_allocobj(jl_codectx_t &ctx, size_t static_size, Value *jt)
{
Value *ptls_ptr = emit_bitcast(ctx, get_current_ptls(ctx), T_pint8);
Function *F = prepare_call(jl_alloc_obj_func);
auto call = ctx.builder.CreateCall(F, {ptls_ptr, ConstantInt::get(T_size, static_size), maybe_decay_untracked(ctx, jt)});
call->setAttributes(F->getAttributes());
return call;
}
// allocation for unknown object from an untracked pointer
static Value *emit_new_bits(jl_codectx_t &ctx, Value *jt, Value *pval)
{
pval = ctx.builder.CreateBitCast(pval, T_pint8);
Function *F = prepare_call(jl_newbits_func);
auto call = ctx.builder.CreateCall(F, { jt, pval });
call->setAttributes(F->getAttributes());
return call;
}
// if ptr is NULL this emits a write barrier _back_
static void emit_write_barrier(jl_codectx_t &ctx, Value *parent, Value *ptr)
{
emit_write_barrier(ctx, parent, makeArrayRef(ptr));
}
static void emit_write_barrier(jl_codectx_t &ctx, Value *parent, ArrayRef<Value*> ptrs)
{
SmallVector<Value*, 8> decay_ptrs;
decay_ptrs.push_back(maybe_decay_untracked(ctx, emit_bitcast(ctx, parent, T_prjlvalue)));
for (auto ptr : ptrs) {
decay_ptrs.push_back(maybe_decay_untracked(ctx, emit_bitcast(ctx, ptr, T_prjlvalue)));
}
ctx.builder.CreateCall(prepare_call(jl_write_barrier_func), decay_ptrs);
}
static void find_perm_offsets(jl_datatype_t *typ, SmallVector<unsigned,4> &res, unsigned offset)
{
// This is a inlined field at `offset`.
if (!typ->layout || typ->layout->npointers == 0)
return;
size_t nf = jl_svec_len(typ->types);
for (size_t i = 0; i < nf; i++) {
jl_value_t *_fld = jl_svecref(typ->types, i);
if (!jl_is_datatype(_fld))
continue;
jl_datatype_t *fld = (jl_datatype_t*)_fld;
if (jl_field_isptr(typ, i)) {
// pointer field, check if field is perm-alloc
if (type_is_permalloc((jl_value_t*)fld))
res.push_back(offset + jl_field_offset(typ, i));
continue;
}
// inline field
find_perm_offsets(fld, res, offset + jl_field_offset(typ, i));
}
}
static void emit_write_multibarrier(jl_codectx_t &ctx, Value *parent, Value *agg,
jl_value_t *jltype)
{
SmallVector<unsigned,4> perm_offsets;
if (jltype && jl_is_datatype(jltype) && ((jl_datatype_t*)jltype)->layout)
find_perm_offsets((jl_datatype_t*)jltype, perm_offsets, 0);
auto ptrs = ExtractTrackedValues(agg, agg->getType(), false, ctx.builder, perm_offsets);
emit_write_barrier(ctx, parent, ptrs);
}
static jl_cgval_t emit_setfield(jl_codectx_t &ctx,
jl_datatype_t *sty, const jl_cgval_t &strct, size_t idx0,
const jl_cgval_t &rhs, const jl_cgval_t &cmp,
bool checked, bool wb, AtomicOrdering Order, AtomicOrdering FailOrder,
bool needlock, bool issetfield, bool isreplacefield)
{
if (!sty->name->mutabl && checked) {
std::string msg = "setfield!: immutable struct of type "
+ std::string(jl_symbol_name(sty->name->name))
+ " cannot be changed";
emit_error(ctx, msg);
return jl_cgval_t();
}
assert(strct.ispointer());
size_t byte_offset = jl_field_offset(sty, idx0);
Value *addr = data_pointer(ctx, strct);
if (byte_offset > 0) {
addr = ctx.builder.CreateInBoundsGEP(
T_int8,
emit_bitcast(ctx, maybe_decay_tracked(ctx, addr), T_pint8),
ConstantInt::get(T_size, byte_offset)); // TODO: use emit_struct_gep
}
jl_value_t *jfty = jl_svecref(sty->types, idx0);
if (!jl_field_isptr(sty, idx0) && jl_is_uniontype(jfty)) {
size_t fsz = 0, al = 0;
bool isptr = !jl_islayout_inline(jfty, &fsz, &al);
assert(!isptr && fsz == jl_field_size(sty, idx0) - 1); (void)isptr;
// compute tindex from rhs
jl_cgval_t rhs_union = convert_julia_type(ctx, rhs, jfty);
if (rhs_union.typ == jl_bottom_type)
return jl_cgval_t();
Value *tindex = compute_tindex_unboxed(ctx, rhs_union, jfty);
tindex = ctx.builder.CreateNUWSub(tindex, ConstantInt::get(T_int8, 1));
Value *ptindex = ctx.builder.CreateInBoundsGEP(T_int8, emit_bitcast(ctx, maybe_decay_tracked(ctx, addr), T_pint8), ConstantInt::get(T_size, fsz));
if (needlock)
emit_lockstate_value(ctx, strct, true);
jl_cgval_t oldval = rhs;
if (!issetfield)
oldval = emit_unionload(ctx, addr, ptindex, jfty, fsz, al, strct.tbaa, true);
Value *Success;
BasicBlock *DoneBB;
if (isreplacefield) {
BasicBlock *BB = BasicBlock::Create(jl_LLVMContext, "xchg", ctx.f);
DoneBB = BasicBlock::Create(jl_LLVMContext, "done_xchg", ctx.f);
Success = emit_f_is(ctx, oldval, cmp);
ctx.builder.CreateCondBr(Success, BB, DoneBB);
ctx.builder.SetInsertPoint(BB);
}
tbaa_decorate(tbaa_unionselbyte, ctx.builder.CreateAlignedStore(tindex, ptindex, Align(1)));
// copy data
if (!rhs.isghost) {
emit_unionmove(ctx, addr, strct.tbaa, rhs, nullptr);
}
if (isreplacefield) {
ctx.builder.CreateBr(DoneBB);
ctx.builder.SetInsertPoint(DoneBB);
}
if (needlock)
emit_lockstate_value(ctx, strct, false);
return oldval;
}
else {
unsigned align = jl_field_align(sty, idx0);
bool isboxed = jl_field_isptr(sty, idx0);
size_t nfields = jl_datatype_nfields(sty);
bool maybe_null = idx0 >= nfields - (unsigned)sty->name->n_uninitialized;
return typed_store(ctx, addr, NULL, rhs, cmp, jfty, strct.tbaa, nullptr,
wb ? maybe_bitcast(ctx, data_pointer(ctx, strct), T_pjlvalue) : nullptr,
isboxed, Order, FailOrder, align,
needlock, issetfield, isreplacefield, maybe_null);
}
}
static jl_cgval_t emit_new_struct(jl_codectx_t &ctx, jl_value_t *ty, size_t nargs, const jl_cgval_t *argv)
{
assert(jl_is_datatype(ty));
assert(jl_is_concrete_type(ty));
jl_datatype_t *sty = (jl_datatype_t*)ty;
size_t nf = jl_datatype_nfields(sty);
if (nf > 0 || sty->name->mutabl) {
if (deserves_stack(ty)) {
Type *lt = julia_type_to_llvm(ctx, ty);
unsigned na = nargs < nf ? nargs : nf;
// whether we should perform the initialization with the struct as a IR value
// or instead initialize the stack buffer with stores
auto tracked = CountTrackedPointers(lt);
bool init_as_value = false;
if (lt->isVectorTy() || jl_is_vecelement_type(ty)) { // maybe also check the size ?
init_as_value = true;
}
else if (tracked.count) {
init_as_value = true;
}
Value *strct;
if (type_is_ghost(lt)) {
strct = NULL;
}
else if (init_as_value) {
if (tracked.count)
strct = Constant::getNullValue(lt);
else
strct = UndefValue::get(lt);
}
else {
strct = emit_static_alloca(ctx, lt);
if (tracked.count)
undef_derived_strct(ctx.builder, strct, sty, tbaa_stack);
}
for (unsigned i = 0; i < na; i++) {
jl_value_t *jtype = jl_svecref(sty->types, i);
jl_cgval_t fval_info = argv[i];
emit_typecheck(ctx, fval_info, jtype, "new");
fval_info = update_julia_type(ctx, fval_info, jtype);
if (type_is_ghost(lt))
continue;
Type *fty = julia_type_to_llvm(ctx, jtype);
if (type_is_ghost(fty))
continue;
Value *dest = NULL;
unsigned offs = jl_field_offset(sty, i);
unsigned llvm_idx = (i > 0 && isa<StructType>(lt)) ? convert_struct_offset(ctx, lt, offs) : i;
if (!init_as_value) {
// avoid unboxing the argument explicitly
// and use memcpy instead
dest = ctx.builder.CreateConstInBoundsGEP2_32(lt, strct, 0, llvm_idx);
}
Value *fval = NULL;
if (jl_field_isptr(sty, i)) {
fval = boxed(ctx, fval_info);
if (!init_as_value)
cast<StoreInst>(tbaa_decorate(tbaa_stack,
ctx.builder.CreateAlignedStore(fval, dest, Align(jl_field_align(sty, i)))))
->setOrdering(AtomicOrdering::Unordered);
}
else if (jl_is_uniontype(jtype)) {
// compute tindex from rhs
jl_cgval_t rhs_union = convert_julia_type(ctx, fval_info, jtype);
if (rhs_union.typ == jl_bottom_type)
return jl_cgval_t();
Value *tindex = compute_tindex_unboxed(ctx, rhs_union, jtype);
tindex = ctx.builder.CreateNUWSub(tindex, ConstantInt::get(T_int8, 1));
size_t fsz = 0, al = 0;
bool isptr = !jl_islayout_inline(jtype, &fsz, &al);
assert(!isptr && fsz == jl_field_size(sty, i) - 1); (void)isptr;
if (init_as_value) {
// If you wanted to implement init_as_value,
// would need to emit the union-move into temporary memory,
// then load it and combine with the tindex.
// But more efficient to just store it directly.
unsigned ptindex = convert_struct_offset(ctx, lt, offs + fsz);
if (fsz > 0 && !fval_info.isghost) {
Type *ET = IntegerType::get(jl_LLVMContext, 8 * al);
assert(lt->getStructElementType(llvm_idx) == ET);
AllocaInst *lv = emit_static_alloca(ctx, ET);
lv->setOperand(0, ConstantInt::get(T_int32, (fsz + al - 1) / al));
emit_unionmove(ctx, lv, tbaa_stack, fval_info, nullptr);
// emit all of the align-sized words
unsigned i = 0;
for (; i < fsz / al; i++) {
Value *fldp = ctx.builder.CreateConstInBoundsGEP1_32(ET, lv, i);
Value *fldv = tbaa_decorate(tbaa_stack, ctx.builder.CreateAlignedLoad(ET, fldp, Align(al)));
strct = ctx.builder.CreateInsertValue(strct, fldv, makeArrayRef(llvm_idx + i));
}
// emit remaining bytes up to tindex
if (i < ptindex - llvm_idx) {
Value *staddr = ctx.builder.CreateConstInBoundsGEP1_32(ET, lv, i);
staddr = ctx.builder.CreateBitCast(staddr, T_pint8);
for (; i < ptindex - llvm_idx; i++) {
Value *fldp = ctx.builder.CreateConstInBoundsGEP1_32(T_int8, staddr, i);
Value *fldv = tbaa_decorate(tbaa_stack, ctx.builder.CreateAlignedLoad(T_int8, fldp, Align(1)));
strct = ctx.builder.CreateInsertValue(strct, fldv, makeArrayRef(llvm_idx + i));
}
}
}
llvm_idx = ptindex;
fval = tindex;
if (jl_is_vecelement_type(ty))
fval = ctx.builder.CreateInsertValue(strct, fval, makeArrayRef(llvm_idx));
}
else {
Value *ptindex = emit_struct_gep(ctx, lt, strct, offs + fsz);
tbaa_decorate(tbaa_unionselbyte, ctx.builder.CreateAlignedStore(tindex, ptindex, Align(1)));
if (!rhs_union.isghost)
emit_unionmove(ctx, dest, tbaa_stack, fval_info, nullptr);
}
}
else {
fval = emit_unbox(ctx, fty, fval_info, jtype, dest, tbaa_stack);
}
if (init_as_value) {
assert(fval);
if (jl_is_vecelement_type(ty))
strct = fval; // VecElement type comes unwrapped in LLVM.
else if (lt->isVectorTy())
strct = ctx.builder.CreateInsertElement(strct, fval, ConstantInt::get(T_int32, llvm_idx));
else if (lt->isAggregateType())
strct = ctx.builder.CreateInsertValue(strct, fval, makeArrayRef(llvm_idx));
else
assert(false);
}
}
for (size_t i = nargs; i < nf; i++) {
if (!jl_field_isptr(sty, i) && jl_is_uniontype(jl_field_type(sty, i))) {
unsigned offs = jl_field_offset(sty, i);
int fsz = jl_field_size(sty, i) - 1;
unsigned llvm_idx = convert_struct_offset(ctx, cast<StructType>(lt), offs + fsz);
if (init_as_value)
strct = ctx.builder.CreateInsertValue(strct, ConstantInt::get(T_int8, 0), makeArrayRef(llvm_idx));
else
tbaa_decorate(tbaa_unionselbyte, ctx.builder.CreateAlignedStore(
ConstantInt::get(T_int8, 0),
ctx.builder.CreateConstInBoundsGEP2_32(lt, strct, 0, llvm_idx),
Align(1)));
}
}
if (type_is_ghost(lt))
return mark_julia_const(sty->instance);
else if (init_as_value)
return mark_julia_type(ctx, strct, false, ty);
else
return mark_julia_slot(strct, ty, NULL, tbaa_stack);
}
Value *strct = emit_allocobj(ctx, jl_datatype_size(sty),
literal_pointer_val(ctx, (jl_value_t*)ty));
jl_cgval_t strctinfo = mark_julia_type(ctx, strct, true, ty);
strct = decay_derived(ctx, strct);
undef_derived_strct(ctx.builder, strct, sty, strctinfo.tbaa);
for (size_t i = nargs; i < nf; i++) {
if (!jl_field_isptr(sty, i) && jl_is_uniontype(jl_field_type(sty, i))) {
tbaa_decorate(tbaa_unionselbyte, ctx.builder.CreateAlignedStore(
ConstantInt::get(T_int8, 0),
ctx.builder.CreateInBoundsGEP(T_int8, emit_bitcast(ctx, strct, T_pint8),
ConstantInt::get(T_size, jl_field_offset(sty, i) + jl_field_size(sty, i) - 1)),
Align(1)));
}
}
// TODO: verify that nargs <= nf (currently handled by front-end)
for (size_t i = 0; i < nargs; i++) {
const jl_cgval_t &rhs = argv[i];
bool need_wb; // set to true if the store might cause the allocation of a box newer than the struct
if (jl_field_isptr(sty, i))
need_wb = !rhs.isboxed;
else
need_wb = false;
emit_typecheck(ctx, rhs, jl_svecref(sty->types, i), "new");
emit_setfield(ctx, sty, strctinfo, i, rhs, jl_cgval_t(), false, need_wb, AtomicOrdering::NotAtomic, AtomicOrdering::NotAtomic, false, true, false);
}
return strctinfo;
}
else {
// 0 fields, ghost or bitstype
if (jl_datatype_nbits(sty) == 0)
return ghostValue(sty);
bool isboxed;
Type *lt = julia_type_to_llvm(ctx, ty, &isboxed);
assert(!isboxed);
return mark_julia_type(ctx, UndefValue::get(lt), false, ty);
}
}
static void emit_signal_fence(jl_codectx_t &ctx)
{
#if defined(_CPU_ARM_) || defined(_CPU_AARCH64_)
// LLVM generates very inefficient code (and might include function call)
// for signal fence. Fallback to the poor man signal fence with
// inline asm instead.
// https://llvm.org/bugs/show_bug.cgi?id=27545
ctx.builder.CreateCall(InlineAsm::get(FunctionType::get(T_void, false), "",
"~{memory}", true));
#else
ctx.builder.CreateFence(AtomicOrdering::SequentiallyConsistent, SyncScope::SingleThread);
#endif
}
static Value *emit_defer_signal(jl_codectx_t &ctx)
{
Value *ptls = emit_bitcast(ctx, get_current_ptls(ctx),
PointerType::get(T_sigatomic, 0));
Constant *offset = ConstantInt::getSigned(T_int32,
offsetof(jl_tls_states_t, defer_signal) / sizeof(sig_atomic_t));
return ctx.builder.CreateInBoundsGEP(T_sigatomic, ptls, ArrayRef<Value*>(offset), "jl_defer_signal");
}
#ifndef NDEBUG
static int compare_cgparams(const jl_cgparams_t *a, const jl_cgparams_t *b)
{
return
(a->track_allocations == b->track_allocations) &&
(a->code_coverage == b->code_coverage) &&
(a->prefer_specsig == b->prefer_specsig) &&
(a->gnu_pubnames == b->gnu_pubnames) &&
(a->debug_info_kind == b->debug_info_kind) &&
(a->lookup == b->lookup) &&
(a->generic_context == b->generic_context);
}
#endif
|
/******************************************************************************
* Copyright © 2014-2018 The SuperNET Developers. *
* *
* See the AUTHORS, DEVELOPER-AGREEMENT and LICENSE files at *
* the top-level directory of this distribution for the individual copyright *
* holder information and the developer policies on copyright and licensing. *
* *
* Unless otherwise agreed in a custom licensing agreement, no part of the *
* SuperNET software, including this file may be copied, modified, propagated *
* or distributed except according to the terms contained in the LICENSE file *
* *
* Removal or modification of this copyright notice is prohibited. *
* *
******************************************************************************/
#include "CCGateways.h"
/*
prevent duplicate bindtxid via mempool scan
wait for notarization for oraclefeed and validation of gatewaysdeposit
debug multisig and do partial signing
validation
string oracles
*/
/*
Uses MofN CC's normal msig handling to create automated deposits -> token issuing. And partial signing by the selected pubkeys for releasing the funds. A user would be able to select which pubkeys to use to construct the automated deposit/redeem multisigs.
the potential pubkeys to be used would be based on active oracle data providers with recent activity.
bind asset <-> SAFE gateway deposit address
SAFE deposit -> globally spendable marker utxo
spend marker utxo and spend linked/locked asset to user's CC address
redeem -> asset to global CC address with withdraw address -> gateway spendable marker utxo
spend market utxo and withdraw from gateway deposit address
rpc calls:
GatewayList
GatewayInfo bindtxid
GatewayBind coin tokenid M N pubkey(s)
external: deposit to depositaddr with claimpubkey
GatewayDeposit coin tokenid external.deposittxid -> markertxid
GatewayClaim coin tokenid external.deposittxid markertxid -> spend marker and deposit asset
GatewayWithdraw coin tokenid withdrawaddr
external: do withdraw to withdrawaddr and spend marker, support for partial signatures and autocomplete
deposit addr can be 1 to MofN pubkeys
1:1 gateway with native coin
In order to create a new gateway it is necessary to follow some strict steps.
1. create a token with the max possible supply that will be issued
2. transfer 100% of them to the gateways CC's global pubkey's asset CC address. (yes it is a bit confusing)
3. create an oracle with the identical name, ie. SAFE and format must start with Ihh (height, blockhash, merkleroot)
4. register a publisher and fund it with a subscribe. there will be a special client app that will automatically publish the merkleroots.
5. Now a gatewaysbind can bind an external coin to an asset, along with the oracle for the merkleroots. the txid from the bind is used in most of the other gateways CC calls
usage:
./c tokencreate SAFE 1000000 SAFE_equivalent_token_for_gatewaysCC
a7398a8748354dd0a3f8d07d70e65294928ecc3674674bb2d9483011ccaa9a7a
transfer to gateways pubkey: 03ea9c062b9652d8eff34879b504eda0717895d27597aaeb60347d65eed96ccb40 RDMqGyREkP1Gwub1Nr5Ye8a325LGZsWBCb
./c tokentransfer a7398a8748354dd0a3f8d07d70e65294928ecc3674674bb2d9483011ccaa9a7a 03ea9c062b9652d8eff34879b504eda0717895d27597aaeb60347d65eed96ccb40 100000000000000
2206fc39c0f384ca79819eb491ddbf889642cbfe4d0796bb6a8010ed53064a56
./c oraclescreate SAFE blockheaders Ihh
1f1aefcca2bdea8196cfd77337fb21de22d200ddea977c2f9e8742c55829d808
./c oraclesregister 1f1aefcca2bdea8196cfd77337fb21de22d200ddea977c2f9e8742c55829d808 1000000
83b59eac238cbe54616ee13b2fdde85a48ec869295eb04051671a1727c9eb402
./c oraclessubscribe 1f1aefcca2bdea8196cfd77337fb21de22d200ddea977c2f9e8742c55829d808 02ebc786cb83de8dc3922ab83c21f3f8a2f3216940c3bf9da43ce39e2a3a882c92 1000
f9499d8bb04ffb511fcec4838d72e642ec832558824a2ce5aed87f1f686f8102
gatewaysbind tokenid oracletxid coin tokensupply M N pubkey(s)
./c gatewaysbind a7398a8748354dd0a3f8d07d70e65294928ecc3674674bb2d9483011ccaa9a7a 1f1aefcca2bdea8196cfd77337fb21de22d200ddea977c2f9e8742c55829d808 SAFE 100000000000000 1 1 02ebc786cb83de8dc3922ab83c21f3f8a2f3216940c3bf9da43ce39e2a3a882c92
e6c99f79d4afb216aa8063658b4222edb773dd24bb0f8e91bd4ef341f3e47e5e
./c gatewaysinfo e6c99f79d4afb216aa8063658b4222edb773dd24bb0f8e91bd4ef341f3e47e5e
{
"result": "success",
"name": "Gateways",
"pubkey": "02ebc786cb83de8dc3922ab83c21f3f8a2f3216940c3bf9da43ce39e2a3a882c92",
"coin": "SAFE",
"oracletxid": "1f1aefcca2bdea8196cfd77337fb21de22d200ddea977c2f9e8742c55829d808",
"taddr": 0,
"prefix": 60,
"prefix2": 85,
"deposit": "",
"tokenid": "a7398a8748354dd0a3f8d07d70e65294928ecc3674674bb2d9483011ccaa9a7a",
"totalsupply": "1000000.00000000",
"remaining": "1000000.00000000",
"issued": "0.00000000"
}
To make a gateway deposit, send the funds to the "deposit" address, along with any amount to the same pubkey address you want to get the assetized SAFE to appear in.
0223d114dededb04f253816d6ad0ce78dd08c617c94ce3c53bf50dc74a5157bef8 pubkey for RFpxgqff7FDHFuHa3jSX5NzqqWCcELz8ha
./safecoin-cli z_sendmany "<funding addr>" '[{"address":"RFpxgqff7FDHFuHa3jSX5NzqqWCcELz8ha","amount":0.0001},{"address":"RHV2As4rox97BuE3LK96vMeNY8VsGRTmBj","amount":7.6999}]'
bc41a00e429db741c3199f17546a48012fd3b7eea45dfc6bc2f5228278133009 height.1003776 merkle.90aedc2f19200afc9aca2e351438d011ebae8264a58469bf225883045f61917f
./safecoin-cli gettxoutproof '["bc41a00e429db741c3199f17546a48012fd3b7eea45dfc6bc2f5228278133009"]'
04000000232524ea04b54489eb222f8b3f566ed35504e3050488a63f0ab7b1c2030000007f91615f04835822bf6984a56482aeeb11d03814352eca9afc0a20192fdcae900000000000000000000000000000000000000000000000000000000000000000268e965ba608071d0800038e16762900000000000000000000000000000000000000000042008dd6fd4005016b4292b05df6dfd316c458c53e28fb2befb96e4870a40c6c04e733d75d8a7a18cce34fe326005efdc403bfa4644e30eeafdaeff34419edc591299e6cc5933cb2eeecbab5c4dfe97cd413b75215999a3dd02b540373581e81d8512bff1640590a6b4da4aaa9b8adc0102c38ca0022daed997b53ed192ba326e212fba5e505ce29e3ad149cef7f48d0e00948a1acd81731d84008760759211eb4abbc7b037939a7964182edb59cf9065357e864188ee5fc7316e8796963036bb99eeb9f06c95d64f78749ecec7181c12eb5d83a3b9b1c1e8a0aae9a20ce04a250b28216620bfc99bb81a6de4db80b93a5aea916de97c1a272e26644abdd683f19c5e3174a2e4513ed767d8f11a4c3074295f697839c5d9139676a813451cc7da38f68cbae5d990a79075f98903233ca04fe1b4b099e433585e5adcc45d41d54a9c648179297359c75950a5e574f13f70b728bbbf552770256315cd0a00139d6ab6934cb5ed70a4fc01a92611b096dd0028f17f4cc687b75f37dca530aa47a18321c50528dbd9272eabb3e13a87021a05918a6d2627e2caba6d7cf1a9f0b831ea3337b9a6af92746d83140078d60c72b6beacf91c9e68a34cee209e08670be1d17ff8d80b7a2285b1325461a2e33f2ee675593f1900e066a5d212615cd8da18749b0e684eee73edcc9031709be715b889c6d015cf4bd4ad5ab7e21bd3492c208930a54d353ef36a437f507ead38855633c1b88d060d9e4221ca8ce2f698e8a6ae0d41e9ace3cbd401f1e0f07650e9c126d4ef20278c8be6e85c7637513643f8d02d7ad64c09da11c16429d60e5160c345844b8158ece62794e8ad280d4e4664150e74978609ece431e51a9f9e1ce8aa49c16f36c7fd12b71acc42d893e18476b8b1e144a8175519612efc93e0aecc61f3b21212c958b0e2331d76aaa62faf11a58fe2bd91ab9ab01b906406c9bbc02df2a106e67182aae0a20b538bf19f09c57f9de5e198ba254580fb1b11e22ad526550093420cb7c68628d4c3ad329c8acc6e219093d277810ed016b6099b7e3781de412a22dacedaa2acf29e8062debcd85c7b9529a20b2782a2470763ac27cf89611a527d43ac89b8063ffb93b6ed993425194f8ee821a8493a563072c896f9584f95db28e3f2fc5fb4a6f3c39d615cd563641717cd50afb73ed3989cbf504b2043882993ce9575f56402534173b1396fbc13df80920b46788ae340ad5a91f25177cc74aa69024d76f56166199d2e4d50a053555256c4e3137ea1cee1130e916a88b6ee5cf2c85652fb8824d5dacfa485e3ef6190591ac0c2fcacc4fc7deb65aca4b0b89b76e35a46b0627e2e967cc63a5d606a984c8e63eabb98fde3e69114340ae524c974cb936e57690e98a7a74533f6f7d1d0496976496b54d14a8163efb32b70dfbb79d80a3022c4f53571c08bf044270565716b435084376714b224ab23e9817c05af8223723afc0577af5c8fc28f71036ca82528aaa4ca9bcd18a50e25d2a528f183d3a2074d968d170876d8dce434c5937261b55173ab87e03d5632ca0834fdc5387c15ab3a17d75c0f274004f289ff1bf7d14e97fdf4172eb49adfb418cc2f4794806ae7c0111c97df4d65d38679ec93fea3ef738ed565e8906a8fe1861cafe3938c772fedcfab40159938e06ef414fd299f2355c6d3369bc1bd3c4db64ce205f0a1b70a40030f505b736e28230de82e97776b5ee7b10708bb3020d28cec7a8e124549ec80c547ac4e7b52bf397c72bcfce30820554ab8fb4d1f73b209bc32a0e7e878843cdbf5f01222728ccea7e6ab7cb5e3fee3234f5b85d1985f91492f6ceaa6454a658dab5074f163ce26ed753137fa61c940679de13bd7b212cd3cf2b334f5201cecbc7473342bd7a239e09169bccd56d03000000037a9068df0625e548e71263c8361b4e904c998378f6b9e32729c3f19b10ad752e093013788222f5c26bfc5da4eeb7d32f01486a54179f19c341b79d420ea041bc8878d22fad4692b2d609c3cf190903874d3682a714c7483518c9392e07c25035010b
./safecoin-cli getrawtransaction bc41a00e429db741c3199f17546a48012fd3b7eea45dfc6bc2f5228278133009
010000000149964cdcd17fe9b1cae4d0f3b5f5db301d9b4f54099fdf4d34498df281757094010000006a4730440220594f3a630dd73c123f44621aa8bb9968ab86734833453dd479af6d79ae6f584202207bb5e35f13b337ccc8a88d9a006c8c5ddb016c0a6f4f2dc44357a8128623d85d01210223154bf53cd3a75e64d86697070d6437c8f0010a09c1df35b659e31ce3d79b5dffffffff0310270000000000001976a91447d2e323a14b0c3be08698aa46a9b91489b189d688ac701de52d000000001976a91459fdba29ea85c65ad90f6d38f7a6646476b26b1688acb0a86a00000000001976a914f9a9daf5519dae38b8b61d945f075da895df441d88ace18d965b
gatewaysdeposit bindtxid height coin cointxid claimvout deposithex proof destpub amount
./safecoin-cli -ac_name=AT5 gatewaysdeposit e6c99f79d4afb216aa8063658b4222edb773dd24bb0f8e91bd4ef341f3e47e5e 1003776 SAFE bc41a00e429db741c3199f17546a48012fd3b7eea45dfc6bc2f5228278133009 0 010000000149964cdcd17fe9b1cae4d0f3b5f5db301d9b4f54099fdf4d34498df281757094010000006a4730440220594f3a630dd73c123f44621aa8bb9968ab86734833453dd479af6d79ae6f584202207bb5e35f13b337ccc8a88d9a006c8c5ddb016c0a6f4f2dc44357a8128623d85d01210223154bf53cd3a75e64d86697070d6437c8f0010a09c1df35b659e31ce3d79b5dffffffff0310270000000000001976a91447d2e323a14b0c3be08698aa46a9b91489b189d688ac701de52d000000001976a91459fdba29ea85c65ad90f6d38f7a6646476b26b1688acb0a86a00000000001976a914f9a9daf5519dae38b8b61d945f075da895df441d88ace18d965b 04000000232524ea04b54489eb222f8b3f566ed35504e3050488a63f0ab7b1c2030000007f91615f04835822bf6984a56482aeeb11d03814352eca9afc0a20192fdcae900000000000000000000000000000000000000000000000000000000000000000268e965ba608071d0800038e16762900000000000000000000000000000000000000000042008dd6fd4005016b4292b05df6dfd316c458c53e28fb2befb96e4870a40c6c04e733d75d8a7a18cce34fe326005efdc403bfa4644e30eeafdaeff34419edc591299e6cc5933cb2eeecbab5c4dfe97cd413b75215999a3dd02b540373581e81d8512bff1640590a6b4da4aaa9b8adc0102c38ca0022daed997b53ed192ba326e212fba5e505ce29e3ad149cef7f48d0e00948a1acd81731d84008760759211eb4abbc7b037939a7964182edb59cf9065357e864188ee5fc7316e8796963036bb99eeb9f06c95d64f78749ecec7181c12eb5d83a3b9b1c1e8a0aae9a20ce04a250b28216620bfc99bb81a6de4db80b93a5aea916de97c1a272e26644abdd683f19c5e3174a2e4513ed767d8f11a4c3074295f697839c5d9139676a813451cc7da38f68cbae5d990a79075f98903233ca04fe1b4b099e433585e5adcc45d41d54a9c648179297359c75950a5e574f13f70b728bbbf552770256315cd0a00139d6ab6934cb5ed70a4fc01a92611b096dd0028f17f4cc687b75f37dca530aa47a18321c50528dbd9272eabb3e13a87021a05918a6d2627e2caba6d7cf1a9f0b831ea3337b9a6af92746d83140078d60c72b6beacf91c9e68a34cee209e08670be1d17ff8d80b7a2285b1325461a2e33f2ee675593f1900e066a5d212615cd8da18749b0e684eee73edcc9031709be715b889c6d015cf4bd4ad5ab7e21bd3492c208930a54d353ef36a437f507ead38855633c1b88d060d9e4221ca8ce2f698e8a6ae0d41e9ace3cbd401f1e0f07650e9c126d4ef20278c8be6e85c7637513643f8d02d7ad64c09da11c16429d60e5160c345844b8158ece62794e8ad280d4e4664150e74978609ece431e51a9f9e1ce8aa49c16f36c7fd12b71acc42d893e18476b8b1e144a8175519612efc93e0aecc61f3b21212c958b0e2331d76aaa62faf11a58fe2bd91ab9ab01b906406c9bbc02df2a106e67182aae0a20b538bf19f09c57f9de5e198ba254580fb1b11e22ad526550093420cb7c68628d4c3ad329c8acc6e219093d277810ed016b6099b7e3781de412a22dacedaa2acf29e8062debcd85c7b9529a20b2782a2470763ac27cf89611a527d43ac89b8063ffb93b6ed993425194f8ee821a8493a563072c896f9584f95db28e3f2fc5fb4a6f3c39d615cd563641717cd50afb73ed3989cbf504b2043882993ce9575f56402534173b1396fbc13df80920b46788ae340ad5a91f25177cc74aa69024d76f56166199d2e4d50a053555256c4e3137ea1cee1130e916a88b6ee5cf2c85652fb8824d5dacfa485e3ef6190591ac0c2fcacc4fc7deb65aca4b0b89b76e35a46b0627e2e967cc63a5d606a984c8e63eabb98fde3e69114340ae524c974cb936e57690e98a7a74533f6f7d1d0496976496b54d14a8163efb32b70dfbb79d80a3022c4f53571c08bf044270565716b435084376714b224ab23e9817c05af8223723afc0577af5c8fc28f71036ca82528aaa4ca9bcd18a50e25d2a528f183d3a2074d968d170876d8dce434c5937261b55173ab87e03d5632ca0834fdc5387c15ab3a17d75c0f274004f289ff1bf7d14e97fdf4172eb49adfb418cc2f4794806ae7c0111c97df4d65d38679ec93fea3ef738ed565e8906a8fe1861cafe3938c772fedcfab40159938e06ef414fd299f2355c6d3369bc1bd3c4db64ce205f0a1b70a40030f505b736e28230de82e97776b5ee7b10708bb3020d28cec7a8e124549ec80c547ac4e7b52bf397c72bcfce30820554ab8fb4d1f73b209bc32a0e7e878843cdbf5f01222728ccea7e6ab7cb5e3fee3234f5b85d1985f91492f6ceaa6454a658dab5074f163ce26ed753137fa61c940679de13bd7b212cd3cf2b334f5201cecbc7473342bd7a239e09169bccd56d03000000037a9068df0625e548e71263c8361b4e904c998378f6b9e32729c3f19b10ad752e093013788222f5c26bfc5da4eeb7d32f01486a54179f19c341b79d420ea041bc8878d22fad4692b2d609c3cf190903874d3682a714c7483518c9392e07c25035010b 0223d114dededb04f253816d6ad0ce78dd08c617c94ce3c53bf50dc74a5157bef8 7.6999
-> 9d80ea79a65aaa0d464f8b762356fa01047e16e9793505a22ca04559f81a6eb6
to get the merkleroots onchain, from the multisig signers nodes run the oraclefeed program with acname oracletxid pubkey Ihh
./oraclefeed AT5 1f1aefcca2bdea8196cfd77337fb21de22d200ddea977c2f9e8742c55829d808 02ebc786cb83de8dc3922ab83c21f3f8a2f3216940c3bf9da43ce39e2a3a882c92 Ihh
gatewaysclaim bindtxid coin deposittxid destpub amount
./c gatewaysclaim e6c99f79d4afb216aa8063658b4222edb773dd24bb0f8e91bd4ef341f3e47e5e SAFE 9d80ea79a65aaa0d464f8b762356fa01047e16e9793505a22ca04559f81a6eb6 0223d114dededb04f253816d6ad0ce78dd08c617c94ce3c53bf50dc74a5157bef8 7.6999
now the asset is in the pubkey's asset address!
it can be used, traded freely and any node who has the asset can do a gatewayswithdraw
gatewayswithdraw bindtxid coin withdrawpub amount
./c gatewayswithdraw e6c99f79d4afb216aa8063658b4222edb773dd24bb0f8e91bd4ef341f3e47e5e SAFE 03b7621b44118017a16043f19b30cc8a4cfe068ac4e42417bae16ba460c80f3828 1
ef3cc452da006eb2edda6b6ed3d3347664be51260f3e91f59ec44ec9701367f0
Now there is a withdraw pending, so it needs to be processed by the signing nodes on the SAFE side
gatewayspending bindtxid coin
gatewayspending will display all pending withdraws and if it is done on one of the msigpubkeys, then it will queue it for processing
./c gatewayspending e6c99f79d4afb216aa8063658b4222edb773dd24bb0f8e91bd4ef341f3e47e5e SAFE
Implementation Issues:
When thinking about validation, it is clear that we cant use EVAL_ASSETS for the locked coins as there wont be any enforcement of the gateways locking. This means we need a way to transfer assets into gateways outputs and back. It seems a tokenconvert rpc will be needed and hopefully that will be enough to make it all work properly.
Care must be taken so that tokens are not lost and can be converted back.
This changes the usage to require tokenconvert before doing the bind and also tokenconvert before doing a withdraw. EVAL_GATEWAYS has evalcode of 241
The gatewaysclaim automatically converts the deposit amount of tokens back to EVAL_ASSETS.
*/
void GatewaysAddQueue(std::string coin,uint256 txid,CScript scriptPubKey,int64_t nValue)
{
char destaddr[64],str[65];
Getscriptaddress(destaddr,scriptPubKey);
fprintf(stderr,"GatewaysAddQueue: %s %s %s %.8f\n",coin.c_str(),uint256_str(str,txid),destaddr,(double)nValue/COIN);
}
// start of consensus code
CScript EncodeGatewaysBindOpRet(uint8_t funcid,std::string coin,uint256 tokenid,int64_t totalsupply,uint256 oracletxid,uint8_t M,uint8_t N,std::vector<CPubKey> pubkeys,uint8_t taddr,uint8_t prefix,uint8_t prefix2)
{
CScript opret; uint8_t evalcode = EVAL_GATEWAYS;
opret << OP_RETURN << E_MARSHAL(ss << evalcode << funcid << coin << prefix << prefix2 << taddr << tokenid << totalsupply << M << N << pubkeys << oracletxid);
return(opret);
}
uint8_t DecodeGatewaysBindOpRet(char *depositaddr,const CScript &scriptPubKey,std::string &coin,uint256 &tokenid,int64_t &totalsupply,uint256 &oracletxid,uint8_t &M,uint8_t &N,std::vector<CPubKey> &pubkeys,uint8_t &taddr,uint8_t &prefix,uint8_t &prefix2)
{
std::vector<uint8_t> vopret; uint8_t *script,e,f;
GetOpReturnData(scriptPubKey, vopret);
script = (uint8_t *)vopret.data();
depositaddr[0] = 0;
if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> coin; ss >> prefix; ss >> prefix2; ss >> taddr; ss >> tokenid; ss >> totalsupply; ss >> M; ss >> N; ss >> pubkeys; ss >> oracletxid) != 0 )
{
if ( prefix == 60 )
{
if ( N > 1 )
{
strcpy(depositaddr,CBitcoinAddress(CScriptID(GetScriptForMultisig(M,pubkeys))).ToString().c_str());
//Getscriptaddress(depositaddr,GetScriptForMultisig(M,pubkeys));
fprintf(stderr,"f.%c M.%d of N.%d size.%d -> %s\n",f,M,N,(int32_t)pubkeys.size(),depositaddr);
} else Getscriptaddress(depositaddr,CScript() << ParseHex(HexStr(pubkeys[0])) << OP_CHECKSIG);
}
else
{
fprintf(stderr,"need to generate non-SAFE addresses prefix.%d\n",prefix);
}
return(f);
} else fprintf(stderr,"error decoding bind opret\n");
return(0);
}
CScript EncodeGatewaysDepositOpRet(uint8_t funcid,std::string coin,uint256 bindtxid,std::vector<CPubKey> publishers,std::vector<uint256>txids,int32_t height,uint256 cointxid,int32_t claimvout,std::string deposithex,std::vector<uint8_t>proof,CPubKey destpub,int64_t amount)
{
CScript opret; uint8_t evalcode = EVAL_GATEWAYS;
opret << OP_RETURN << E_MARSHAL(ss << evalcode << funcid << coin << bindtxid << publishers << txids << height << cointxid << claimvout << deposithex << proof << destpub << amount);
return(opret);
}
uint8_t DecodeGatewaysDepositOpRet(const CScript &scriptPubKey,std::string &coin,uint256 &bindtxid,std::vector<CPubKey>&publishers,std::vector<uint256>&txids,int32_t &height,uint256 &cointxid, int32_t &claimvout,std::string &deposithex,std::vector<uint8_t> &proof,CPubKey &destpub,int64_t &amount)
{
std::vector<uint8_t> vopret; uint8_t *script,e,f;
GetOpReturnData(scriptPubKey, vopret);
script = (uint8_t *)vopret.data();
if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> coin; ss >> bindtxid; ss >> publishers; ss >> txids; ss >> height; ss >> cointxid; ss >> claimvout; ss >> deposithex; ss >> proof; ss >> destpub; ss >> amount) != 0 )
{
return(f);
}
return(0);
}
CScript EncodeGatewaysClaimOpRet(uint8_t funcid,uint256 assetid,std::string refcoin,uint256 bindtxid,uint256 deposittxid,CPubKey destpub,int64_t amount)
{
CScript opret; uint8_t evalcode = EVAL_ASSETS;
opret << OP_RETURN << E_MARSHAL(ss << evalcode << funcid << assetid << refcoin << bindtxid << deposittxid << destpub << amount);
return(opret);
}
uint8_t DecodeGatewaysClaimOpRet(const CScript &scriptPubKey,uint256 &assetid,std::string &refcoin,uint256 &bindtxid,uint256 &deposittxid,CPubKey &destpub,int64_t &amount)
{
std::vector<uint8_t> vopret; uint8_t *script,e,f;
GetOpReturnData(scriptPubKey, vopret);
script = (uint8_t *)vopret.data();
if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> assetid; ss >> refcoin; ss >> bindtxid; ss >> deposittxid; ss >> destpub; ss >> amount) != 0 )
{
return(f);
}
return(0);
}
CScript EncodeGatewaysWithdrawOpRet(uint8_t funcid,uint256 assetid, std::string refcoin, CPubKey withdrawpub, int64_t amount)
{
CScript opret; uint8_t evalcode = EVAL_GATEWAYS;
opret << OP_RETURN << E_MARSHAL(ss << evalcode << funcid << assetid << refcoin << withdrawpub << amount);
return(opret);
}
uint8_t DecodeGatewaysWithdrawOpRet(const CScript &scriptPubKey, uint256 &assetid, std::string &refcoin, CPubKey &withdrawpub, int64_t &amount)
{
std::vector<uint8_t> vopret; uint8_t *script,e,f;
GetOpReturnData(scriptPubKey, vopret);
script = (uint8_t *)vopret.data();
if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> assetid; ss >> refcoin; ss >> withdrawpub; ss >> amount) != 0 )
{
return(f);
}
return(0);
}
CScript EncodeGatewaysPartialOpRet(uint8_t funcid,int32_t K, CPubKey signerpk, std::string refcoin,std::string hex)
{
CScript opret; uint8_t evalcode = EVAL_GATEWAYS;
opret << OP_RETURN << E_MARSHAL(ss << evalcode << funcid << K << signerpk << refcoin << hex);
return(opret);
}
uint8_t DecodeGatewaysPartialOpRet(const CScript &scriptPubKey,int32_t &K, CPubKey &signerpk, std::string &refcoin,std::string &hex)
{
std::vector<uint8_t> vopret; uint8_t *script,e,f;
GetOpReturnData(scriptPubKey, vopret);
script = (uint8_t *)vopret.data();
if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> K; ss >> signerpk; ss >> refcoin; ss >> hex) != 0 )
{
return(f);
}
return(0);
}
CScript EncodeGatewaysCompleteSigningOpRet(uint8_t funcid,std::string refcoin,uint256 withdrawtxid,std::string hex)
{
CScript opret; uint8_t evalcode = EVAL_GATEWAYS;
opret << OP_RETURN << E_MARSHAL(ss << evalcode << funcid << refcoin << withdrawtxid << hex);
return(opret);
}
uint8_t DecodeGatewaysCompleteSigningOpRet(const CScript &scriptPubKey, std::string &refcoin, uint256 &withdrawtxid,std::string &hex)
{
std::vector<uint8_t> vopret; uint8_t *script,e,f;
GetOpReturnData(scriptPubKey, vopret);
script = (uint8_t *)vopret.data();
if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> refcoin; ss >> withdrawtxid; ss >> hex) != 0 )
{
return(f);
}
return(0);
}
CScript EncodeGatewaysMarkDoneOpRet(uint8_t funcid,std::string refcoin,uint256 withdrawtxid)
{
CScript opret; uint8_t evalcode = EVAL_GATEWAYS;
opret << OP_RETURN << E_MARSHAL(ss << evalcode << funcid << refcoin << withdrawtxid);
return(opret);
}
uint8_t DecodeGatewaysMarkDoneOpRet(const CScript &scriptPubKey, std::string &refcoin, uint256 &withdrawtxid)
{
std::vector<uint8_t> vopret; uint8_t *script,e,f;
GetOpReturnData(scriptPubKey, vopret);
script = (uint8_t *)vopret.data();
if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> refcoin; ss >> withdrawtxid;) != 0 )
{
return(f);
}
return(0);
}
uint8_t DecodeGatewaysOpRet(const CScript &scriptPubKey)
{
std::vector<uint8_t> vopret; uint8_t *script,e,f;
GetOpReturnData(scriptPubKey, vopret);
script = (uint8_t *)vopret.data();
if ( vopret.size() > 2 && (script[0] == EVAL_GATEWAYS || script[0] == EVAL_ASSETS) && E_UNMARSHAL(vopret,ss >> e; ss >> f) != 0 )
{
if (f == 'B' && f == 'D' && f == 't' && f == 'W' && f == 'P' && f == 'M')
return(f);
}
return(0);
}
int64_t IsGatewaysvout(struct CCcontract_info *cp,const CTransaction& tx,int32_t v)
{
char destaddr[64];
if ( tx.vout[v].scriptPubKey.IsPayToCryptoCondition() != 0 )
{
if ( Getscriptaddress(destaddr,tx.vout[v].scriptPubKey) > 0 && strcmp(destaddr,cp->unspendableCCaddr) == 0 )
return(tx.vout[v].nValue);
}
return(0);
}
bool GatewaysExactAmounts(struct CCcontract_info *cp,Eval* eval,const CTransaction &tx,int32_t minage,uint64_t txfee)
{
static uint256 zerohash;
CTransaction vinTx; uint256 hashBlock,activehash; int32_t i,numvins,numvouts; int64_t inputs=0,outputs=0,assetoshis;
numvins = tx.vin.size();
numvouts = tx.vout.size();
for (i=0; i<numvins; i++)
{
//fprintf(stderr,"vini.%d\n",i);
if ( (*cp->ismyvin)(tx.vin[i].scriptSig) != 0 )
{
//fprintf(stderr,"vini.%d check mempool\n",i);
if ( eval->GetTxUnconfirmed(tx.vin[i].prevout.hash,vinTx,hashBlock) == 0 )
return eval->Invalid("cant find vinTx");
else
{
//fprintf(stderr,"vini.%d check hash and vout\n",i);
if ( hashBlock == zerohash )
return eval->Invalid("cant Gateways from mempool");
if ( (assetoshis= IsGatewaysvout(cp,vinTx,tx.vin[i].prevout.n)) != 0 )
inputs += assetoshis;
}
}
}
for (i=0; i<numvouts; i++)
{
//fprintf(stderr,"i.%d of numvouts.%d\n",i,numvouts);
if ( (assetoshis= IsGatewaysvout(cp,tx,i)) != 0 )
outputs += assetoshis;
}
if ( inputs != outputs+txfee )
{
fprintf(stderr,"inputs %llu vs outputs %llu\n",(long long)inputs,(long long)outputs);
return eval->Invalid("mismatched inputs != outputs + txfee");
}
else return(true);
}
static int32_t myIs_coinaddr_inmempoolvout(char *coinaddr)
{
int32_t i,n; char destaddr[64];
BOOST_FOREACH(const CTxMemPoolEntry &e,mempool.mapTx)
{
const CTransaction &tx = e.GetTx();
if ( (n= tx.vout.size()) > 0 )
{
const uint256 &txid = tx.GetHash();
for (i=0; i<n; i++)
{
Getscriptaddress(destaddr,tx.vout[i].scriptPubKey);
if ( strcmp(destaddr,coinaddr) == 0 )
{
fprintf(stderr,"found (%s) vout in mempool\n",coinaddr);
return(1);
}
}
}
}
return(0);
}
uint256 GatewaysReverseScan(uint256 &txid,int32_t height,uint256 reforacletxid,uint256 batontxid)
{
CTransaction tx; uint256 hash,mhash,bhash,hashBlock,oracletxid; int32_t len,len2,numvouts; int64_t val,merkleht; CPubKey pk; std::vector<uint8_t>data;
txid = zeroid;
char str[65];
//fprintf(stderr,"start reverse scan %s\n",uint256_str(str,batontxid));
while ( myGetTransaction(batontxid,tx,hashBlock) != 0 && (numvouts= tx.vout.size()) > 0 )
{
//fprintf(stderr,"check %s\n",uint256_str(str,batontxid));
if ( DecodeOraclesData(tx.vout[numvouts-1].scriptPubKey,oracletxid,bhash,pk,data) == 'D' && oracletxid == reforacletxid )
{
//fprintf(stderr,"decoded %s\n",uint256_str(str,batontxid));
if ( oracle_format(&hash,&merkleht,0,'I',(uint8_t *)data.data(),0,(int32_t)data.size()) == sizeof(int32_t) && merkleht == height )
{
len = oracle_format(&hash,&val,0,'h',(uint8_t *)data.data(),sizeof(int32_t),(int32_t)data.size());
len2 = oracle_format(&mhash,&val,0,'h',(uint8_t *)data.data(),(int32_t)(sizeof(int32_t)+sizeof(uint256)),(int32_t)data.size());
char str2[65]; fprintf(stderr,"found merkleht.%d len.%d len2.%d %s %s\n",(int32_t)merkleht,len,len2,uint256_str(str,hash),uint256_str(str2,mhash));
if ( len == sizeof(hash)+sizeof(int32_t) && len2 == 2*sizeof(mhash)+sizeof(int32_t) && mhash != zeroid )
{
txid = batontxid;
//fprintf(stderr,"set txid\n");
return(mhash);
}
else
{
//fprintf(stderr,"missing hash\n");
return(zeroid);
}
} //else fprintf(stderr,"height.%d vs search ht.%d\n",(int32_t)merkleht,(int32_t)height);
batontxid = bhash;
//fprintf(stderr,"new hash %s\n",uint256_str(str,batontxid));
} else break;
}
fprintf(stderr,"end of loop\n");
return(zeroid);
}
int32_t GatewaysCointxidExists(struct CCcontract_info *cp,uint256 cointxid) // dont forget to check mempool!
{
char txidaddr[64]; std::string coin; int32_t numvouts; uint256 hashBlock;
std::vector<std::pair<CAddressIndexKey, CAmount> > addressIndex;
CCtxidaddr(txidaddr,cointxid);
SetCCtxids(addressIndex,txidaddr);
for (std::vector<std::pair<CAddressIndexKey, CAmount> >::const_iterator it=addressIndex.begin(); it!=addressIndex.end(); it++)
{
return(-1);
}
return(myIs_coinaddr_inmempoolvout(txidaddr));
}
/* Get the block merkle root for a proof
* IN: proofData
* OUT: merkle root
* OUT: transaction IDS
*/
uint256 BitcoinGetProofMerkleRoot(const std::vector<uint8_t> &proofData, std::vector<uint256> &txids)
{
CMerkleBlock merkleBlock;
if (!E_UNMARSHAL(proofData, ss >> merkleBlock))
return uint256();
return merkleBlock.txn.ExtractMatches(txids);
}
int64_t GatewaysVerify(char *refdepositaddr,uint256 oracletxid,int32_t claimvout,std::string refcoin,uint256 cointxid,const std::string deposithex,std::vector<uint8_t>proof,uint256 merkleroot,CPubKey destpub)
{
std::vector<uint256> txids; uint256 proofroot,hashBlock,txid = zeroid; CTransaction tx; std::string name,description,format; char destaddr[64],destpubaddr[64],claimaddr[64],str[65],str2[65]; int32_t i,numvouts; int64_t nValue = 0;
if ( myGetTransaction(oracletxid,tx,hashBlock) == 0 || (numvouts= tx.vout.size()) <= 0 )
{
fprintf(stderr,"GatewaysVerify cant find oracletxid %s\n",uint256_str(str,oracletxid));
return(0);
}
if ( DecodeOraclesCreateOpRet(tx.vout[numvouts-1].scriptPubKey,name,description,format) != 'C' || name != refcoin )
{
fprintf(stderr,"GatewaysVerify mismatched oracle name %s != %s\n",name.c_str(),refcoin.c_str());
return(0);
}
proofroot = BitcoinGetProofMerkleRoot(proof,txids);
if ( proofroot != merkleroot )
{
fprintf(stderr,"GatewaysVerify mismatched merkleroot %s != %s\n",uint256_str(str,proofroot),uint256_str(str2,merkleroot));
return(0);
}
if ( DecodeHexTx(tx,deposithex) != 0 )
{
Getscriptaddress(claimaddr,tx.vout[claimvout].scriptPubKey);
Getscriptaddress(destpubaddr,CScript() << ParseHex(HexStr(destpub)) << OP_CHECKSIG);
if ( strcmp(claimaddr,destpubaddr) == 0 )
{
for (i=0; i<numvouts; i++)
{
Getscriptaddress(destaddr,tx.vout[i].scriptPubKey);
if ( strcmp(refdepositaddr,destaddr) == 0 )
{
txid = tx.GetHash();
nValue = tx.vout[i].nValue;
break;
}
}
} else fprintf(stderr,"claimaddr.(%s) != destpubaddr.(%s)\n",claimaddr,destpubaddr);
}
if ( txid == cointxid )
{
fprintf(stderr,"verified proof for cointxid in merkleroot\n");
return(nValue);
} else fprintf(stderr,"(%s) != (%s) or txid %s mismatch.%d or script mismatch\n",refdepositaddr,destaddr,uint256_str(str,txid),txid != cointxid);
return(0);
}
int64_t GatewaysDepositval(CTransaction tx,CPubKey mypk)
{
int32_t numvouts,claimvout,height; int64_t amount; std::string coin,deposithex; std::vector<CPubKey> publishers; std::vector<uint256>txids; uint256 bindtxid,cointxid; std::vector<uint8_t> proof; CPubKey claimpubkey;
if ( (numvouts= tx.vout.size()) > 0 )
{
if ( DecodeGatewaysDepositOpRet(tx.vout[numvouts-1].scriptPubKey,coin,bindtxid,publishers,txids,height,cointxid,claimvout,deposithex,proof,claimpubkey,amount) == 'D' && claimpubkey == mypk )
{
// coin, bindtxid, publishers
fprintf(stderr,"need to validate deposittxid more\n");
return(amount);
}
}
return(0);
}
bool GatewaysValidate(struct CCcontract_info *cp,Eval *eval,const CTransaction &tx, uint32_t nIn)
{
int32_t numvins,numvouts,preventCCvins,preventCCvouts,i,numblocks,height,claimvout; bool retval; uint8_t funcid,hash[32],M,N,taddr,prefix,prefix2;
char str[65],destaddr[64],depositaddr[65],validationError[512];
std::vector<uint256> txids; std::vector<CPubKey> pubkeys,publishers,tmppublishers; std::vector<uint8_t> proof; int64_t totalsupply,amount,tmpamount;
uint256 hashblock,txid,bindtxid,deposittxid,assetid,oracletxid,tokenid,cointxid,tmptxid,tmpxtxid2,merkleroot,mhash; CTransaction bindtx,deposittx,oracletx;
std::string refcoin,tmprefcoin,deposithex; CPubKey destpub,tmpdestpub;
fprintf(stderr,"return true without gateways validation\n");
return(true);
numvins = tx.vin.size();
numvouts = tx.vout.size();
preventCCvins = preventCCvouts = -1;
if ( numvouts < 1 )
return eval->Invalid("no vouts");
else
{
// for (i=0; i<numvins; i++)
// {
// if ( IsCCInput(tx.vin[0].scriptSig) == 0 )
// {
// return eval->Invalid("illegal normal vini");
// }
// }
//fprintf(stderr,"check amounts\n");
// if ( GatewaysExactAmounts(cp,eval,tx,1,10000) == false )
// {
// fprintf(stderr,"Gatewaysget invalid amount\n");
// return false;
// }
// else
// {
txid = tx.GetHash();
memcpy(hash,&txid,sizeof(hash));
if ( (funcid = DecodeGatewaysOpRet(tx.vout[numvouts-1].scriptPubKey)) != 0)
{
switch ( funcid )
{
case 'B':
//vin.0: normal input
//vout.0: CC vout txfee marker
//vout.n-1: opreturn - 'B' coin tokenid totalsupply oracletxid M N pubkeys taddr prefix prefix2
return eval->Invalid("unexpected GatewaysValidate for gatewaysbind!");
break;
case 'D':
//vin.0: normal input
//vout.0: CC vout txfee marker to destination pubkey
//vout.1: normal output txfee marker to txidaddr
//vout.n-1: opreturn - 'D' coin bindtxid publishers txids height cointxid deposithex proof destpub amount
return eval->Invalid("unexpected GatewaysValidate for gatewaysdeposit!");
break;
case 't':
//vin.0: normal input
//vin.1: CC input of converted token to gateways eval code
//vin.2: CC input of marker from gatewaysdeposit tx
//vout.0: CC vout of total tokens from deposit amount to asset eval code
//(vout.1): CC vout if there is change of unused tokens back to owner of tokens (deposit amount less than available tokens)
//vout.n-1: opreturn - 't' assetid zeroid 0 mypubkey (NOTE: opreturn is with asset eval code)
if ((numvouts=tx.vout.size()) > 0 && DecodeGatewaysClaimOpRet(tx.vout[numvouts-1].scriptPubKey,assetid,refcoin,bindtxid,deposittxid,destpub,amount)==0)
return eval->Invalid("invalid gatewaysclaim OP_RETURN data!");
else if ( IsCCInput(tx.vin[0].scriptSig) != 0 )
return eval->Invalid("vin.0 is normal for gatewaysClaim!");
else if ( IsCCInput(tx.vin[1].scriptSig) == 0 )
return eval->Invalid("vin.1 is CC for gatewaysClaim!");
else if ( IsCCInput(tx.vin[2].scriptSig) == 0 )
return eval->Invalid("vin.2 is CC for gatewaysClaim!");
else if ( tx.vout[0].scriptPubKey.IsPayToCryptoCondition() == 0 )
return eval->Invalid("vout.0 is CC for gatewaysClaim!");
else if ( numvouts > 2 && tx.vout[1].scriptPubKey.IsPayToCryptoCondition() == 0 )
return eval->Invalid("vout.1 is CC for gatewaysClaim!");
else if (myGetTransaction(bindtxid,bindtx,hashblock) == 0)
return eval->Invalid("invalid gatewaysbind txid!");
else if ((numvouts=bindtx.vout.size()) > 0 && DecodeGatewaysBindOpRet(depositaddr,bindtx.vout[numvouts-1].scriptPubKey,tmprefcoin,tokenid,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2) != 'B')
return eval->Invalid("invalid gatewaysbind OP_RETURN data!");
else if (tmprefcoin!=refcoin)
return eval->Invalid("refcoin different in bind tx");
else if (tokenid!=assetid)
return eval->Invalid("assetid does not match tokenid from gatewaysbind");
else if (safecoin_txnotarizedconfirmed(bindtxid) == false)
return eval->Invalid("gatewaysbind tx is not yet confirmed(notarised)!");
else if (myGetTransaction(deposittxid,deposittx,hashblock) == 0)
return eval->Invalid("invalid gatewaysdeposittxid!");
else if ((numvouts=deposittx.vout.size()) > 0 && DecodeGatewaysDepositOpRet(deposittx.vout[numvouts-1].scriptPubKey,tmprefcoin,tmptxid,tmppublishers,txids,height,cointxid,claimvout,deposithex,proof,tmpdestpub,tmpamount) != 'D')
return eval->Invalid("invalid gatewaysdeposit OP_RETURN data!");
else if (tmprefcoin!=refcoin)
return eval->Invalid("refcoin different in deposit tx");
else if (bindtxid!=tmptxid)
return eval->Invalid("bindtxid does not match to bindtxid from gatewaysdeposit");
else if (tmpamount>totalsupply)
return eval->Invalid("deposit amount greater then bind total supply");
else if (safecoin_txnotarizedconfirmed(deposittxid) == false)
return eval->Invalid("gatewaysdeposit tx is not yet confirmed(notarised)!");
else if (amount>tmpamount)
return eval->Invalid("claimed amount greater then deposit amount");
else if (destpub!=tmpdestpub)
return eval->Invalid("destination pubkey different than in deposit tx");
else
{
int32_t m;
merkleroot = zeroid;
for (i=m=0; i<N; i++)
{
fprintf(stderr,"pubkeys[%d] %s\n",i,pubkey33_str(str,(uint8_t *)&pubkeys[i]));
if ( (mhash= GatewaysReverseScan(txid,height,oracletxid,OraclesBatontxid(oracletxid,pubkeys[i]))) != zeroid )
{
if ( merkleroot == zeroid )
merkleroot = mhash, m = 1;
else if ( mhash == merkleroot )
m++;
publishers.push_back(pubkeys[i]);
txids.push_back(txid);
}
}
if ( merkleroot == zeroid || m < N/2 )
{
sprintf(validationError,"couldnt find merkleroot for ht.%d %s oracle.%s m.%d vs n.%d\n",height,tmprefcoin.c_str(),uint256_str(str,oracletxid),m,N);
return eval->Invalid(validationError);
}
if ( GatewaysCointxidExists(cp,cointxid) != 0 )
{
sprintf(validationError,"cointxid.%s already exists\n",uint256_str(str,cointxid));
return eval->Invalid(validationError);
}
if (GatewaysVerify(depositaddr,oracletxid,claimvout,tmprefcoin,cointxid,deposithex,proof,merkleroot,destpub)!=amount)
return eval->Invalid("deposittxid didnt validate\n");
}
break;
case 'W':
//vin.0: normal input
//vin.1: CC input of converted token back to gateways eval code
//vout.0: CC vout of tokens back to gateways CC address
//vout.1: normal vout txfee marker to withdraw destination pubkey
//vout.2: CC vout txfee marker to gateways CC address
//vout.n-2: CC vout if there is change of unused tokens back to owner of tokens (withdraw amount less than owner available tokens)
//vout.n-1: opreturn - 'W' assetid refcoin withdrawpub amount
break;
case 'P':
//vin.0: normal input
//(vin.1): CC input form previous marker of gatewayspartialsign tx (if exists)
//vout.0: CC vout 5k sat marker to senders pubKey
//vout.n-1: opreturn - 'P' number_of_signs mypk refcoin hex
break;
case 'C':
//vin.0: CC input from gatewayswithdraw tx marker to gateways CC address
//vout.0: CC vout txfee marker to gateways CC address
//vout.n-1: opreturn - 'C' refcoin cointxid external_tx_hex
break;
case 'M':
//vin.0: CC input from gatewayscompletesigning tx marker to gateways CC address
//vout.0: opreturn - 'M' refcoin cointxid
break;
}
}
retval = PreventCC(eval,tx,preventCCvins,numvins,preventCCvouts,numvouts);
if ( retval != 0 )
fprintf(stderr,"Gatewaysget validated\n");
else fprintf(stderr,"Gatewaysget invalid\n");
return(retval);
// }
}
}
// end of consensus code
// helper functions for rpc calls in rpcwallet.cpp
int64_t AddGatewaysInputs(struct CCcontract_info *cp,CMutableTransaction &mtx,CPubKey pk,uint256 refassetid,int64_t total,int32_t maxinputs)
{
char coinaddr[64],destaddr[64]; int64_t threshold,nValue,price,totalinputs = 0; uint256 assetid,txid,hashBlock; std::vector<uint8_t> origpubkey; std::vector<uint8_t> vopret; CTransaction vintx; int32_t j,vout,n = 0; uint8_t evalcode,funcid;
std::vector<std::pair<CAddressUnspentKey, CAddressUnspentValue> > unspentOutputs;
GetCCaddress(cp,coinaddr,pk);
SetCCunspents(unspentOutputs,coinaddr);
threshold = total/(maxinputs+1);
//fprintf(stderr,"check %s for gateway inputs\n",coinaddr);
for (std::vector<std::pair<CAddressUnspentKey, CAddressUnspentValue> >::const_iterator it=unspentOutputs.begin(); it!=unspentOutputs.end(); it++)
{
txid = it->first.txhash;
vout = (int32_t)it->first.index;
if ( it->second.satoshis < threshold )
continue;
for (j=0; j<mtx.vin.size(); j++)
if ( txid == mtx.vin[j].prevout.hash && vout == mtx.vin[j].prevout.n )
break;
if ( j != mtx.vin.size() )
continue;
if ( GetTransaction(txid,vintx,hashBlock,false) != 0 )
{
Getscriptaddress(destaddr,vintx.vout[vout].scriptPubKey);
//fprintf(stderr,"check %s vout.%d %.8f %.8f\n",destaddr,vout,(double)vintx.vout[vout].nValue/COIN,(double)it->second.satoshis/COIN);
if ( strcmp(destaddr,coinaddr) != 0 && strcmp(destaddr,cp->unspendableCCaddr) != 0 && strcmp(destaddr,cp->unspendableaddr2) != 0 )
continue;
GetOpReturnData(vintx.vout[vintx.vout.size()-1].scriptPubKey, vopret);
if ( E_UNMARSHAL(vopret,ss >> evalcode; ss >> funcid; ss >> assetid) != 0 )
{
assetid = revuint256(assetid);
char str[65],str2[65]; fprintf(stderr,"vout.%d %d:%d (%c) check for refassetid.%s vs %s %.8f\n",vout,evalcode,cp->evalcode,funcid,uint256_str(str,refassetid),uint256_str(str2,assetid),(double)vintx.vout[vout].nValue/COIN);
if ( assetid == refassetid && funcid == 't' && (nValue= vintx.vout[vout].nValue) > 0 && myIsutxo_spentinmempool(txid,vout) == 0 )
{
//fprintf(stderr,"total %llu maxinputs.%d %.8f\n",(long long)total,maxinputs,(double)it->second.satoshis/COIN);
if ( total != 0 && maxinputs != 0 )
mtx.vin.push_back(CTxIn(txid,vout,CScript()));
//nValue = it->second.satoshis;
totalinputs += nValue;
n++;
if ( (total > 0 && totalinputs >= total) || (maxinputs > 0 && n >= maxinputs) )
break;
}
}
}
}
return(totalinputs);
}
int32_t GatewaysBindExists(struct CCcontract_info *cp,CPubKey gatewayspk,uint256 reftokenid) // dont forget to check mempool!
{
char markeraddr[64],depositaddr[64]; std::string coin; int32_t numvouts; int64_t totalsupply; uint256 tokenid,oracletxid,hashBlock; uint8_t M,N,taddr,prefix,prefix2; std::vector<CPubKey> pubkeys; CTransaction tx;
std::vector<std::pair<CAddressIndexKey, CAmount> > addressIndex;
_GetCCaddress(markeraddr,EVAL_GATEWAYS,gatewayspk);
fprintf(stderr,"bind markeraddr.(%s) need to scan mempool also\n",markeraddr);
SetCCtxids(addressIndex,markeraddr);
for (std::vector<std::pair<CAddressIndexKey, CAmount> >::const_iterator it=addressIndex.begin(); it!=addressIndex.end(); it++)
{
if ( GetTransaction(it->first.txhash,tx,hashBlock,false) != 0 && (numvouts= tx.vout.size()) > 0 )
{
if ( DecodeGatewaysBindOpRet(depositaddr,tx.vout[numvouts-1].scriptPubKey,coin,tokenid,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2) == 'B' )
{
if ( tokenid == reftokenid )
{
fprintf(stderr,"trying to bind an existing tokenid\n");
return(1);
}
}
}
}
return(0);
}
std::string GatewaysBind(uint64_t txfee,std::string coin,uint256 tokenid,int64_t totalsupply,uint256 oracletxid,uint8_t M,uint8_t N,std::vector<CPubKey> pubkeys)
{
CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), safecoin_nextheight());
CTransaction oracletx; uint8_t taddr,prefix,prefix2; CPubKey mypk,gatewayspk; CScript opret; uint256 hashBlock; struct CCcontract_info *cp,C; std::string name,description,format; int32_t i,numvouts; int64_t fullsupply; char destaddr[64],coinaddr[64],str[65],*fstr;
cp = CCinit(&C,EVAL_GATEWAYS);
if ( strcmp((char *)"SAFE",coin.c_str()) == 0 )
{
taddr = 0;
prefix = 60;
prefix2 = 85;
}
else
{
fprintf(stderr,"set taddr, prefix, prefix2 for %s\n",coin.c_str());
taddr = 0;
prefix = 60;
prefix2 = 85;
}
if ( N == 0 || N > 15 || M > N )
{
fprintf(stderr,"illegal M.%d or N.%d\n",M,N);
return("");
}
if ( pubkeys.size() != N )
{
fprintf(stderr,"M.%d N.%d but pubkeys[%d]\n",M,N,(int32_t)pubkeys.size());
return("");
}
for (i=0; i<N; i++)
{
Getscriptaddress(coinaddr,CScript() << ParseHex(HexStr(pubkeys[i])) << OP_CHECKSIG);
if ( CCaddress_balance(coinaddr) == 0 )
{
fprintf(stderr,"M.%d N.%d but pubkeys[%d] has no balance\n",M,N,i);
return("");
}
}
if ( txfee == 0 )
txfee = 10000;
mypk = pubkey2pk(Mypubkey());
gatewayspk = GetUnspendable(cp,0);
if ( _GetCCaddress(destaddr,EVAL_GATEWAYS,gatewayspk) == 0 )
{
fprintf(stderr,"Gateway bind.%s (%s) cant create globaladdr\n",coin.c_str(),uint256_str(str,tokenid));
return("");
}
if ( (fullsupply= CCfullsupply(tokenid)) != totalsupply )
{
fprintf(stderr,"Gateway bind.%s (%s) globaladdr.%s totalsupply %.8f != fullsupply %.8f\n",coin.c_str(),uint256_str(str,tokenid),cp->unspendableCCaddr,(double)totalsupply/COIN,(double)fullsupply/COIN);
return("");
}
if ( CCtoken_balance(destaddr,tokenid) != totalsupply )
{
fprintf(stderr,"Gateway bind.%s (%s) destaddr.%s globaladdr.%s token balance %.8f != %.8f\n",coin.c_str(),uint256_str(str,tokenid),destaddr,cp->unspendableCCaddr,(double)CCtoken_balance(destaddr,tokenid)/COIN,(double)totalsupply/COIN);
return("");
}
if ( GetTransaction(oracletxid,oracletx,hashBlock,false) == 0 || (numvouts= oracletx.vout.size()) <= 0 )
{
fprintf(stderr,"cant find oracletxid %s\n",uint256_str(str,oracletxid));
return("");
}
if ( DecodeOraclesCreateOpRet(oracletx.vout[numvouts-1].scriptPubKey,name,description,format) != 'C' )
{
fprintf(stderr,"mismatched oracle name %s != %s\n",name.c_str(),coin.c_str());
return("");
}
if ( (fstr= (char *)format.c_str()) == 0 || strncmp(fstr,"Ihh",3) != 0 )
{
fprintf(stderr,"illegal format (%s) != (%s)\n",fstr,(char *)"Ihh");
return("");
}
if ( GatewaysBindExists(cp,gatewayspk,tokenid) != 0 ) // dont forget to check mempool!
{
fprintf(stderr,"Gateway bind.%s (%s) already exists\n",coin.c_str(),uint256_str(str,tokenid));
return("");
}
if ( AddNormalinputs(mtx,mypk,2*txfee,3) > 0 )
{
mtx.vout.push_back(MakeCC1vout(cp->evalcode,txfee,gatewayspk));
return(FinalizeCCTx(0,cp,mtx,mypk,txfee,EncodeGatewaysBindOpRet('B',coin,tokenid,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2)));
}
CCerror = strprintf("cant find enough inputs");
fprintf(stderr,"%s\n", CCerror.c_str() );
return("");
}
std::string GatewaysDeposit(uint64_t txfee,uint256 bindtxid,int32_t height,std::string refcoin,uint256 cointxid,int32_t claimvout,std::string deposithex,std::vector<uint8_t>proof,CPubKey destpub,int64_t amount)
{
CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), safecoin_nextheight());
CTransaction bindtx; CPubKey mypk,gatewayspk; uint256 oracletxid,merkleroot,mhash,hashBlock,tokenid,txid;
int64_t totalsupply; int32_t i,m,n,numvouts; uint8_t M,N,taddr,prefix,prefix2; std::string coin; struct CCcontract_info *cp,C;
std::vector<CPubKey> pubkeys,publishers; std::vector<uint256>txids; char str[67],depositaddr[64],txidaddr[64];
cp = CCinit(&C,EVAL_GATEWAYS);
if ( txfee == 0 )
txfee = 10000;
mypk = pubkey2pk(Mypubkey());
gatewayspk = GetUnspendable(cp,0);
//fprintf(stderr,"GatewaysDeposit ht.%d %s %.8f numpks.%d\n",height,refcoin.c_str(),(double)amount/COIN,(int32_t)pubkeys.size());
if ( GetTransaction(bindtxid,bindtx,hashBlock,false) == 0 || (numvouts= bindtx.vout.size()) <= 0 )
{
fprintf(stderr,"cant find bindtxid %s\n",uint256_str(str,bindtxid));
return("");
}
if ( DecodeGatewaysBindOpRet(depositaddr,bindtx.vout[numvouts-1].scriptPubKey,coin,tokenid,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2) != 'B' || refcoin != coin )
{
fprintf(stderr,"invalid coin - bindtxid %s coin.%s\n",uint256_str(str,bindtxid),coin.c_str());
return("");
}
n = (int32_t)pubkeys.size();
merkleroot = zeroid;
for (i=m=0; i<n; i++)
{
fprintf(stderr,"pubkeys[%d] %s\n",i,pubkey33_str(str,(uint8_t *)&pubkeys[i]));
if ( (mhash= GatewaysReverseScan(txid,height,oracletxid,OraclesBatontxid(oracletxid,pubkeys[i]))) != zeroid )
{
if ( merkleroot == zeroid )
merkleroot = mhash, m = 1;
else if ( mhash == merkleroot )
m++;
publishers.push_back(pubkeys[i]);
txids.push_back(txid);
}
}
fprintf(stderr,"cointxid.%s m.%d of n.%d\n",uint256_str(str,cointxid),m,n);
if ( merkleroot == zeroid || m < n/2 )
{
//uint256 tmp;
//decode_hex((uint8_t *)&tmp,32,(char *)"90aedc2f19200afc9aca2e351438d011ebae8264a58469bf225883045f61917f");
//merkleroot = revuint256(tmp);
fprintf(stderr,"couldnt find merkleroot for ht.%d %s oracle.%s m.%d vs n.%d\n",height,coin.c_str(),uint256_str(str,oracletxid),m,n);
return("");
}
if ( GatewaysCointxidExists(cp,cointxid) != 0 )
{
fprintf(stderr,"cointxid.%s already exists\n",uint256_str(str,cointxid));
return("");
}
if ( GatewaysVerify(depositaddr,oracletxid,claimvout,coin,cointxid,deposithex,proof,merkleroot,destpub) != amount )
{
fprintf(stderr,"deposittxid didnt validate\n");
return("");
}
if ( AddNormalinputs(mtx,mypk,3*txfee,4) > 0 )
{
mtx.vout.push_back(MakeCC1vout(cp->evalcode,txfee,destpub));
mtx.vout.push_back(CTxOut(txfee,CScript() << ParseHex(HexStr(CCtxidaddr(txidaddr,cointxid))) << OP_CHECKSIG));
return(FinalizeCCTx(0,cp,mtx,mypk,txfee,EncodeGatewaysDepositOpRet('D',coin,bindtxid,publishers,txids,height,cointxid,claimvout,deposithex,proof,destpub,amount)));
}
fprintf(stderr,"cant find enough inputs\n");
return("");
}
std::string GatewaysClaim(uint64_t txfee,uint256 bindtxid,std::string refcoin,uint256 deposittxid,CPubKey destpub,int64_t amount)
{
CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), safecoin_nextheight());
CTransaction tx; CPubKey mypk,gatewayspk,tmpdestpub; struct CCcontract_info *cp,C; uint8_t M,N,taddr,prefix,prefix2;
std::string coin, deposithex; std::vector<CPubKey> msigpubkeys,publishers; int64_t totalsupply,depositamount,tmpamount,inputs,CCchange=0;
int32_t numvouts,claimvout,height; std::vector<uint8_t> proof;
uint256 hashBlock,assetid,oracletxid,tmptxid,cointxid; char str[65],depositaddr[64],coinaddr[64],destaddr[64]; std::vector<uint256> txids;
cp = CCinit(&C,EVAL_GATEWAYS);
if ( txfee == 0 )
txfee = 10000;
mypk = pubkey2pk(Mypubkey());
gatewayspk = GetUnspendable(cp,0);
if ( GetTransaction(bindtxid,tx,hashBlock,false) == 0 || (numvouts= tx.vout.size()) <= 0 )
{
fprintf(stderr,"cant find bindtxid %s\n",uint256_str(str,bindtxid));
return("");
}
if ( DecodeGatewaysBindOpRet(depositaddr,tx.vout[numvouts-1].scriptPubKey,coin,assetid,totalsupply,oracletxid,M,N,msigpubkeys,taddr,prefix,prefix2) != 'B' || coin != refcoin )
{
fprintf(stderr,"invalid coin - bindtxid %s coin.%s\n",uint256_str(str,bindtxid),coin.c_str());
return("");
}
if ( GetTransaction(deposittxid,tx,hashBlock,false) == 0 || (numvouts= tx.vout.size()) <= 0 )
{
fprintf(stderr,"cant find deposittxid %s\n",uint256_str(str,bindtxid));
return("");
}
if (DecodeGatewaysDepositOpRet(tx.vout[numvouts-1].scriptPubKey,coin,tmptxid,publishers,txids,height,cointxid,claimvout,deposithex,proof,tmpdestpub,tmpamount) != 'D' || coin != refcoin)
{
fprintf(stderr,"invalid coin - deposittxid %s coin.%s\n",uint256_str(str,bindtxid),coin.c_str());
return("");
}
if (tmpdestpub!=destpub)
{
fprintf(stderr,"different destination pubkey from desdeposittxid\n");
return("");
}
if ( (depositamount= GatewaysDepositval(tx,mypk)) != amount )
{
fprintf(stderr,"invalid Gateways deposittxid %s %.8f != %.8f\n",uint256_str(str,deposittxid),(double)depositamount/COIN,(double)amount/COIN);
return("");
}
//fprintf(stderr,"depositaddr.(%s) vs %s\n",depositaddr,cp->unspendableaddr2);
if ( AddNormalinputs(mtx,mypk,txfee,3) > 0 )
{
if ( (inputs= AddGatewaysInputs(cp,mtx,gatewayspk,assetid,amount,60)) > 0 )
{
if ( inputs > amount )
CCchange = (inputs - amount);
_GetCCaddress(destaddr,EVAL_GATEWAYS,mypk);
//printf("expecting deposittxid/v0 to be to %s\n",destaddr);
mtx.vin.push_back(CTxIn(deposittxid,0,CScript())); // triggers EVAL_GATEWAYS validation
mtx.vout.push_back(MakeCC1vout(EVAL_ASSETS,amount,mypk)); // transfer back to normal token
if ( CCchange != 0 )
mtx.vout.push_back(MakeCC1vout(EVAL_GATEWAYS,CCchange,gatewayspk));
return(FinalizeCCTx(0,cp,mtx,mypk,txfee,EncodeGatewaysClaimOpRet('t',assetid,refcoin,bindtxid,deposittxid,destpub,amount)));
}
}
CCerror = strprintf("cant find enough inputs or mismatched total");
fprintf(stderr,"%s\n", CCerror.c_str() );
return("");
}
std::string GatewaysWithdraw(uint64_t txfee,uint256 bindtxid,std::string refcoin,CPubKey withdrawpub,int64_t amount)
{
CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), safecoin_nextheight());
CTransaction tx; CPubKey mypk,gatewayspk; struct CCcontract_info *cp,C;
uint256 assetid,hashBlock,oracletxid; int32_t numvouts; int64_t totalsupply,inputs,CCchange=0; uint8_t M,N,taddr,prefix,prefix2; std::string coin;
std::vector<CPubKey> msigpubkeys; char depositaddr[64],str[65],coinaddr[64];
cp = CCinit(&C,EVAL_GATEWAYS);
if ( txfee == 0 )
txfee = 10000;
mypk = pubkey2pk(Mypubkey());
gatewayspk = GetUnspendable(cp,0);
if ( GetTransaction(bindtxid,tx,hashBlock,false) == 0 || (numvouts= tx.vout.size()) <= 0 )
{
fprintf(stderr,"cant find bindtxid %s\n",uint256_str(str,bindtxid));
return("");
}
if ( DecodeGatewaysBindOpRet(depositaddr,tx.vout[numvouts-1].scriptPubKey,coin,assetid,totalsupply,oracletxid,M,N,msigpubkeys,taddr,prefix,prefix2) != 'B' || coin != refcoin )
{
fprintf(stderr,"invalid bindtxid %s coin.%s\n",uint256_str(str,bindtxid),coin.c_str());
return("");
}
if ( AddNormalinputs(mtx,mypk,3*txfee,4) > 0 )
{
if ( (inputs= AddGatewaysInputs(cp,mtx,mypk,assetid,amount,60)) > 0 )
{
if ( inputs > amount )
CCchange = (inputs - amount);
mtx.vout.push_back(MakeCC1vout(EVAL_GATEWAYS,amount,gatewayspk));
mtx.vout.push_back(CTxOut(txfee,CScript() << ParseHex(HexStr(withdrawpub)) << OP_CHECKSIG));
mtx.vout.push_back(MakeCC1vout(EVAL_GATEWAYS,txfee,gatewayspk));
if ( CCchange != 0 )
mtx.vout.push_back(MakeCC1vout(EVAL_GATEWAYS,CCchange,mypk));
return(FinalizeCCTx(0,cp,mtx,mypk,txfee,EncodeGatewaysWithdrawOpRet('W',assetid,refcoin,withdrawpub,amount)));
}
}
CCerror = strprintf("cant find enough inputs or mismatched total");
fprintf(stderr,"%s\n", CCerror.c_str() );
return("");
}
std::string GatewaysPartialSign(uint64_t txfee,uint256 txid,std::string refcoin, std::string hex)
{
CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), safecoin_nextheight());
CPubKey mypk,txidaddrpk,signerpk; struct CCcontract_info *cp,C; CTransaction tx;
std::vector<std::pair<CAddressUnspentKey, CAddressUnspentValue> > unspentOutputs; char txidaddr[65];
int32_t maxK,K=0; uint256 tmptxid,parttxid,hashBlock;
cp = CCinit(&C,EVAL_GATEWAYS);
if ( txfee == 0 )
txfee = 5000;
mypk = pubkey2pk(Mypubkey());
txidaddrpk=CCtxidaddr(txidaddr,txid);
SetCCunspents(unspentOutputs,txidaddr);
maxK=0;
if (unspentOutputs.size()==0)
{
if (AddNormalinputs(mtx,mypk,2*txfee,3)==0) fprintf(stderr,"error adding funds for partialsign\n");
}
else
{
for (std::vector<std::pair<CAddressUnspentKey, CAddressUnspentValue> >::const_iterator it=unspentOutputs.begin(); it!=unspentOutputs.end(); it++)
{
tmptxid = it->first.txhash;
if (GetTransaction(tmptxid,tx,hashBlock,false) != 0 && tx.vout.size() > 0 && DecodeGatewaysPartialOpRet(tx.vout[tx.vout.size()-1].scriptPubKey,K,signerpk,refcoin,hex) == 'P' && K>maxK )
{
maxK=K;
parttxid=tmptxid;
}
}
if (maxK>0)
{
if (AddNormalinputs(mtx,mypk,txfee,3)==0) fprintf(stderr,"error adding funds for partialsign\n");
mtx.vin.push_back(CTxIn(parttxid,0,CScript()));
}
else fprintf(stderr,"Error finding previous partial tx\n");
}
mtx.vout.push_back(MakeCC1vout(EVAL_GATEWAYS,5000,txidaddrpk));
return(FinalizeCCTx(0,cp,mtx,mypk,txfee,EncodeGatewaysPartialOpRet('P',maxK+1,mypk,refcoin,hex)));
}
std::string GatewaysCompleteSigning(uint64_t txfee,uint256 withdrawtxid,std::string refcoin,std::string hex)
{
CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), safecoin_nextheight());
CPubKey mypk,gatewayspk; struct CCcontract_info *cp,C; char txidaddr[65];
cp = CCinit(&C,EVAL_GATEWAYS);
mypk = pubkey2pk(Mypubkey());
gatewayspk = GetUnspendable(cp,0);
if ( txfee == 0 )
txfee = 10000;
mtx.vin.push_back(CTxIn(withdrawtxid,2,CScript()));
mtx.vout.push_back(MakeCC1vout(EVAL_GATEWAYS,txfee,gatewayspk));
return(FinalizeCCTx(0,cp,mtx,mypk,txfee,EncodeGatewaysCompleteSigningOpRet('C',refcoin,withdrawtxid,hex)));
}
std::string GatewaysMarkDone(uint64_t txfee,uint256 completetxid,std::string refcoin)
{
CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), safecoin_nextheight());
CPubKey mypk,gatewayspk; struct CCcontract_info *cp,C; char txidaddr[65];
cp = CCinit(&C,EVAL_GATEWAYS);
mypk = pubkey2pk(Mypubkey());
if ( txfee == 0 )
txfee = 10000;
mtx.vin.push_back(CTxIn(completetxid,0,CScript()));
return(FinalizeCCTx(0,cp,mtx,mypk,txfee,EncodeGatewaysMarkDoneOpRet('M',refcoin,completetxid)));
}
UniValue GatewaysPendingWithdraws(uint256 bindtxid,std::string refcoin)
{
UniValue result(UniValue::VOBJ),pending(UniValue::VARR); CTransaction tx; std::string tmprefcoin; CPubKey mypk,gatewayspk,withdrawpub; std::vector<CPubKey> msigpubkeys;
uint256 hashBlock,assetid,txid,oracletxid; uint8_t M,N,taddr,prefix,prefix2;
char depositaddr[64],coinaddr[64],destaddr[64],str[65],withaddr[64],numstr[32],txidaddr[64],cctxidaddr[64],signeraddr[64];
int32_t i,n,numvouts,vout,queueflag; int64_t totalsupply,amount,nValue; struct CCcontract_info *cp,C;
std::vector<std::pair<CAddressUnspentKey, CAddressUnspentValue> > unspentOutputs;
cp = CCinit(&C,EVAL_GATEWAYS);
mypk = pubkey2pk(Mypubkey());
gatewayspk = GetUnspendable(cp,0);
_GetCCaddress(coinaddr,EVAL_GATEWAYS,gatewayspk);
if ( GetTransaction(bindtxid,tx,hashBlock,false) == 0 || (numvouts= tx.vout.size()) <= 0 )
{
fprintf(stderr,"cant find bindtxid %s\n",uint256_str(str,bindtxid));
return(result);
}
if ( DecodeGatewaysBindOpRet(depositaddr,tx.vout[numvouts-1].scriptPubKey,tmprefcoin,assetid,totalsupply,oracletxid,M,N,msigpubkeys,taddr,prefix,prefix2) != 'B' || tmprefcoin != refcoin )
{
fprintf(stderr,"invalid bindtxid %s coin.%s\n",uint256_str(str,bindtxid),tmprefcoin.c_str());
return(result);
}
n = msigpubkeys.size();
queueflag = 0;
for (i=0; i<n; i++)
if ( msigpubkeys[i] == mypk )
{
queueflag = 1;
break;
}
SetCCunspents(unspentOutputs,coinaddr);
for (std::vector<std::pair<CAddressUnspentKey, CAddressUnspentValue> >::const_iterator it=unspentOutputs.begin(); it!=unspentOutputs.end(); it++)
{
txid = it->first.txhash;
vout = (int32_t)it->first.index;
nValue = (int64_t)it->second.satoshis;
fprintf(stderr,"%s %d %ld\n",txid.ToString().c_str(),vout,(long)nValue);
if ( vout == 2 && nValue == 10000 && GetTransaction(txid,tx,hashBlock,false) != 0 && (numvouts= tx.vout.size())>0 &&
DecodeGatewaysWithdrawOpRet(tx.vout[numvouts-1].scriptPubKey,assetid,tmprefcoin,withdrawpub,amount) == 'W' && myIsutxo_spentinmempool(txid,vout) == 0)
{
Getscriptaddress(destaddr,tx.vout[0].scriptPubKey);
Getscriptaddress(withaddr,tx.vout[1].scriptPubKey);
if ( strcmp(destaddr,coinaddr) == 0 )
{
UniValue obj(UniValue::VOBJ);
obj.push_back(Pair("txid",uint256_str(str,txid)));
_GetCCaddress(cctxidaddr,EVAL_GATEWAYS,CCtxidaddr(txidaddr,txid));
obj.push_back(Pair("txidaddr",cctxidaddr));
obj.push_back(Pair("withdrawaddr",withaddr));
sprintf(numstr,"%.8f",(double)tx.vout[0].nValue/COIN);
obj.push_back(Pair("amount",numstr));
obj.push_back(Pair("confirmed_or_notarized",safecoin_txnotarizedconfirmed(txid)));
if ( queueflag != 0 )
{
obj.push_back(Pair("depositaddr",depositaddr));
Getscriptaddress(signeraddr,CScript() << ParseHex(HexStr(mypk)) << OP_CHECKSIG);
obj.push_back(Pair("signeraddr",signeraddr));
}
pending.push_back(obj);
}
}
}
result.push_back(Pair("coin",refcoin));
result.push_back(Pair("pending",pending));
result.push_back(Pair("queueflag",queueflag));
return(result);
}
UniValue GatewaysProcessedWithdraws(uint256 bindtxid,std::string refcoin)
{
UniValue result(UniValue::VOBJ),processed(UniValue::VARR); CTransaction tx; std::string tmprefcoin,hex; CPubKey mypk,gatewayspk,withdrawpub; std::vector<CPubKey> msigpubkeys;
uint256 withdrawtxid,hashBlock,txid,assetid,oracletxid; uint8_t M,N,taddr,prefix,prefix2;
char depositaddr[64],coinaddr[64],str[65],numstr[32],txidaddr[64],cctxidaddr[64],withaddr[64];
int32_t i,n,numvouts,vout,queueflag; int64_t totalsupply,nValue,amount; struct CCcontract_info *cp,C;
std::vector<std::pair<CAddressUnspentKey, CAddressUnspentValue> > unspentOutputs;
cp = CCinit(&C,EVAL_GATEWAYS);
mypk = pubkey2pk(Mypubkey());
gatewayspk = GetUnspendable(cp,0);
_GetCCaddress(coinaddr,EVAL_GATEWAYS,gatewayspk);
if ( GetTransaction(bindtxid,tx,hashBlock,false) == 0 || (numvouts= tx.vout.size()) <= 0 )
{
fprintf(stderr,"cant find bindtxid %s\n",uint256_str(str,bindtxid));
return(result);
}
if ( DecodeGatewaysBindOpRet(depositaddr,tx.vout[numvouts-1].scriptPubKey,tmprefcoin,assetid,totalsupply,oracletxid,M,N,msigpubkeys,taddr,prefix,prefix2) != 'B' || tmprefcoin != refcoin )
{
fprintf(stderr,"invalid bindtxid %s coin.%s\n",uint256_str(str,bindtxid),tmprefcoin.c_str());
return(result);
}
n = msigpubkeys.size();
queueflag = 0;
for (i=0; i<n; i++)
if ( msigpubkeys[i] == mypk )
{
queueflag = 1;
break;
}
SetCCunspents(unspentOutputs,coinaddr);
for (std::vector<std::pair<CAddressUnspentKey, CAddressUnspentValue> >::const_iterator it=unspentOutputs.begin(); it!=unspentOutputs.end(); it++)
{
txid = it->first.txhash;
vout = (int32_t)it->first.index;
nValue = (int64_t)it->second.satoshis;
//fprintf(stderr,"%s %d %ld\n",txid.ToString().c_str(),vout,(long)nValue);
if ( vout == 0 && nValue == 10000 && GetTransaction(txid,tx,hashBlock,false) != 0 && (numvouts= tx.vout.size())>0 &&
DecodeGatewaysCompleteSigningOpRet(tx.vout[numvouts-1].scriptPubKey,tmprefcoin,withdrawtxid,hex) == 'C' && myIsutxo_spentinmempool(txid,vout) == 0)
{
if (GetTransaction(withdrawtxid,tx,hashBlock,false) != 0 && (numvouts= tx.vout.size())>0 && DecodeGatewaysWithdrawOpRet(tx.vout[numvouts-1].scriptPubKey,assetid,tmprefcoin,withdrawpub,amount) == 'W')
{
UniValue obj(UniValue::VOBJ);
obj.push_back(Pair("txid",uint256_str(str,txid)));
obj.push_back(Pair("withdrawtxid",uint256_str(str,withdrawtxid)));
_GetCCaddress(cctxidaddr,EVAL_GATEWAYS,CCtxidaddr(txidaddr,withdrawtxid));
obj.push_back(Pair("withdrawtxidaddr",cctxidaddr));
Getscriptaddress(withaddr,tx.vout[1].scriptPubKey);
obj.push_back(Pair("withdrawaddr",withaddr));
obj.push_back(Pair("confirmed_or_notarized",safecoin_txnotarizedconfirmed(txid)));
obj.push_back(Pair("hex",hex));
processed.push_back(obj);
}
}
}
result.push_back(Pair("coin",refcoin));
result.push_back(Pair("processed",processed));
result.push_back(Pair("queueflag",queueflag));
return(result);
}
UniValue GatewaysMultisig(char *cctxidaddr)
{
std::string parthex,hex,refcoin; uint256 txid,hashBlock; CTransaction tx; int32_t i,maxK,K,numvouts; CPubKey signerpk;
std::vector<std::pair<CAddressUnspentKey, CAddressUnspentValue> > unspentOutputs; UniValue result(UniValue::VOBJ);
SetCCunspents(unspentOutputs,cctxidaddr);
maxK=0;
for (std::vector<std::pair<CAddressUnspentKey, CAddressUnspentValue> >::const_iterator it=unspentOutputs.begin(); it!=unspentOutputs.end(); it++)
{
txid = it->first.txhash;
if (GetTransaction(txid,tx,hashBlock,false) != 0 && (numvouts=tx.vout.size()) > 0 && DecodeGatewaysPartialOpRet(tx.vout[tx.vout.size()-1].scriptPubKey,K,signerpk,refcoin,hex) == 'P' && K>maxK )
{
maxK=K;
parthex=hex;
}
}
BOOST_FOREACH(const CTxMemPoolEntry &e, mempool.mapTx)
{
const CTransaction &txmempool = e.GetTx();
const uint256 &hash = txmempool.GetHash();
if ((numvouts=txmempool.vout.size()) > 0 && DecodeGatewaysPartialOpRet(txmempool.vout[numvouts-1].scriptPubKey,K,signerpk,refcoin,hex) == 'P' && K>maxK)
{
maxK=K;
parthex=hex;
}
}
result.push_back(Pair("hex",parthex));
result.push_back(Pair("number_of_signs",maxK));
return (result);
}
UniValue GatewaysList()
{
UniValue result(UniValue::VARR); std::vector<std::pair<CAddressIndexKey, CAmount> > addressIndex; struct CCcontract_info *cp,C; uint256 txid,hashBlock,oracletxid,tokenid; CTransaction vintx; std::string coin; int64_t totalsupply; char str[65],depositaddr[64]; uint8_t M,N,taddr,prefix,prefix2; std::vector<CPubKey> pubkeys;
cp = CCinit(&C,EVAL_GATEWAYS);
SetCCtxids(addressIndex,cp->unspendableCCaddr);
for (std::vector<std::pair<CAddressIndexKey, CAmount> >::const_iterator it=addressIndex.begin(); it!=addressIndex.end(); it++)
{
txid = it->first.txhash;
if ( GetTransaction(txid,vintx,hashBlock,false) != 0 )
{
if ( vintx.vout.size() > 0 && DecodeGatewaysBindOpRet(depositaddr,vintx.vout[vintx.vout.size()-1].scriptPubKey,coin,tokenid,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2) != 0 )
{
result.push_back(uint256_str(str,txid));
}
}
}
return(result);
}
UniValue GatewaysInfo(uint256 bindtxid)
{
CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), safecoin_nextheight());
UniValue result(UniValue::VOBJ),a(UniValue::VARR); std::string coin; char str[67],numstr[65],depositaddr[64],gatewaysassets[64]; uint8_t M,N; std::vector<CPubKey> pubkeys; uint8_t taddr,prefix,prefix2; uint256 tokenid,oracletxid,hashBlock; CTransaction tx; CPubKey Gatewayspk; struct CCcontract_info *cp,C; int32_t i; int64_t totalsupply,remaining;
result.push_back(Pair("result","success"));
result.push_back(Pair("name","Gateways"));
cp = CCinit(&C,EVAL_GATEWAYS);
Gatewayspk = GetUnspendable(cp,0);
_GetCCaddress(gatewaysassets,EVAL_GATEWAYS,Gatewayspk);
if ( GetTransaction(bindtxid,tx,hashBlock,false) != 0 )
{
depositaddr[0] = 0;
if ( tx.vout.size() > 0 && DecodeGatewaysBindOpRet(depositaddr,tx.vout[tx.vout.size()-1].scriptPubKey,coin,tokenid,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2) != 0 && M <= N && N > 0 )
{
if ( N > 1 )
{
result.push_back(Pair("M",M));
result.push_back(Pair("N",N));
for (i=0; i<N; i++)
a.push_back(pubkey33_str(str,(uint8_t *)&pubkeys[i]));
result.push_back(Pair("pubkeys",a));
} else result.push_back(Pair("pubkey",pubkey33_str(str,(uint8_t *)&pubkeys[0])));
result.push_back(Pair("coin",coin));
result.push_back(Pair("oracletxid",uint256_str(str,oracletxid)));
result.push_back(Pair("taddr",taddr));
result.push_back(Pair("prefix",prefix));
result.push_back(Pair("prefix2",prefix2));
result.push_back(Pair("deposit",depositaddr));
result.push_back(Pair("tokenid",uint256_str(str,tokenid)));
sprintf(numstr,"%.8f",(double)totalsupply/COIN);
result.push_back(Pair("totalsupply",numstr));
remaining = CCtoken_balance(gatewaysassets,tokenid);
sprintf(numstr,"%.8f",(double)remaining/COIN);
result.push_back(Pair("remaining",numstr));
sprintf(numstr,"%.8f",(double)(totalsupply - remaining)/COIN);
result.push_back(Pair("issued",numstr));
}
}
return(result);
}
|
# /* **************************************************************************
# * *
# * (C) Copyright Edward Diener 2011. *
# * (C) Copyright Paul Mensonides 2011. *
# * Distributed under the Boost Software License, Version 1.0. (See *
# * accompanying file LICENSE_1_0.txt or copy at *
# * http://www.boost.org/LICENSE_1_0.txt) *
# * *
# ************************************************************************** */
#
# /* See http://www.boost.org for most recent version. */
#
# ifndef BOOST_PREPROCESSOR_VARIADIC_ELEM_HPP
# define BOOST_PREPROCESSOR_VARIADIC_ELEM_HPP
#
# include <eosiolib/preprocessor/cat.hpp>
# include <eosiolib/preprocessor/config/config.hpp>
#
# /* BOOST_PP_VARIADIC_ELEM */
#
# if BOOST_PP_VARIADICS
# if BOOST_PP_VARIADICS_MSVC
# define BOOST_PP_VARIADIC_ELEM(n, ...) BOOST_PP_VARIADIC_ELEM_I(n,__VA_ARGS__)
# define BOOST_PP_VARIADIC_ELEM_I(n, ...) BOOST_PP_CAT(BOOST_PP_CAT(BOOST_PP_VARIADIC_ELEM_, n)(__VA_ARGS__,),)
# else
# define BOOST_PP_VARIADIC_ELEM(n, ...) BOOST_PP_CAT(BOOST_PP_VARIADIC_ELEM_, n)(__VA_ARGS__,)
# endif
# define BOOST_PP_VARIADIC_ELEM_0(e0, ...) e0
# define BOOST_PP_VARIADIC_ELEM_1(e0, e1, ...) e1
# define BOOST_PP_VARIADIC_ELEM_2(e0, e1, e2, ...) e2
# define BOOST_PP_VARIADIC_ELEM_3(e0, e1, e2, e3, ...) e3
# define BOOST_PP_VARIADIC_ELEM_4(e0, e1, e2, e3, e4, ...) e4
# define BOOST_PP_VARIADIC_ELEM_5(e0, e1, e2, e3, e4, e5, ...) e5
# define BOOST_PP_VARIADIC_ELEM_6(e0, e1, e2, e3, e4, e5, e6, ...) e6
# define BOOST_PP_VARIADIC_ELEM_7(e0, e1, e2, e3, e4, e5, e6, e7, ...) e7
# define BOOST_PP_VARIADIC_ELEM_8(e0, e1, e2, e3, e4, e5, e6, e7, e8, ...) e8
# define BOOST_PP_VARIADIC_ELEM_9(e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, ...) e9
# define BOOST_PP_VARIADIC_ELEM_10(e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, ...) e10
# define BOOST_PP_VARIADIC_ELEM_11(e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, ...) e11
# define BOOST_PP_VARIADIC_ELEM_12(e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, ...) e12
# define BOOST_PP_VARIADIC_ELEM_13(e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, ...) e13
# define BOOST_PP_VARIADIC_ELEM_14(e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, ...) e14
# define BOOST_PP_VARIADIC_ELEM_15(e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, ...) e15
# define BOOST_PP_VARIADIC_ELEM_16(e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, ...) e16
# define BOOST_PP_VARIADIC_ELEM_17(e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, e17, ...) e17
# define BOOST_PP_VARIADIC_ELEM_18(e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, e17, e18, ...) e18
# define BOOST_PP_VARIADIC_ELEM_19(e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, e17, e18, e19, ...) e19
# define BOOST_PP_VARIADIC_ELEM_20(e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, e17, e18, e19, e20, ...) e20
# define BOOST_PP_VARIADIC_ELEM_21(e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, e17, e18, e19, e20, e21, ...) e21
# define BOOST_PP_VARIADIC_ELEM_22(e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, e17, e18, e19, e20, e21, e22, ...) e22
# define BOOST_PP_VARIADIC_ELEM_23(e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, e17, e18, e19, e20, e21, e22, e23, ...) e23
# define BOOST_PP_VARIADIC_ELEM_24(e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, e17, e18, e19, e20, e21, e22, e23, e24, ...) e24
# define BOOST_PP_VARIADIC_ELEM_25(e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, e17, e18, e19, e20, e21, e22, e23, e24, e25, ...) e25
# define BOOST_PP_VARIADIC_ELEM_26(e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, e17, e18, e19, e20, e21, e22, e23, e24, e25, e26, ...) e26
# define BOOST_PP_VARIADIC_ELEM_27(e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, e17, e18, e19, e20, e21, e22, e23, e24, e25, e26, e27, ...) e27
# define BOOST_PP_VARIADIC_ELEM_28(e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, e17, e18, e19, e20, e21, e22, e23, e24, e25, e26, e27, e28, ...) e28
# define BOOST_PP_VARIADIC_ELEM_29(e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, e17, e18, e19, e20, e21, e22, e23, e24, e25, e26, e27, e28, e29, ...) e29
# define BOOST_PP_VARIADIC_ELEM_30(e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, e17, e18, e19, e20, e21, e22, e23, e24, e25, e26, e27, e28, e29, e30, ...) e30
# define BOOST_PP_VARIADIC_ELEM_31(e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, e17, e18, e19, e20, e21, e22, e23, e24, e25, e26, e27, e28, e29, e30, e31, ...) e31
# define BOOST_PP_VARIADIC_ELEM_32(e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, e17, e18, e19, e20, e21, e22, e23, e24, e25, e26, e27, e28, e29, e30, e31, e32, ...) e32
# define BOOST_PP_VARIADIC_ELEM_33(e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, e17, e18, e19, e20, e21, e22, e23, e24, e25, e26, e27, e28, e29, e30, e31, e32, e33, ...) e33
# define BOOST_PP_VARIADIC_ELEM_34(e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, e17, e18, e19, e20, e21, e22, e23, e24, e25, e26, e27, e28, e29, e30, e31, e32, e33, e34, ...) e34
# define BOOST_PP_VARIADIC_ELEM_35(e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, e17, e18, e19, e20, e21, e22, e23, e24, e25, e26, e27, e28, e29, e30, e31, e32, e33, e34, e35, ...) e35
# define BOOST_PP_VARIADIC_ELEM_36(e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, e17, e18, e19, e20, e21, e22, e23, e24, e25, e26, e27, e28, e29, e30, e31, e32, e33, e34, e35, e36, ...) e36
# define BOOST_PP_VARIADIC_ELEM_37(e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, e17, e18, e19, e20, e21, e22, e23, e24, e25, e26, e27, e28, e29, e30, e31, e32, e33, e34, e35, e36, e37, ...) e37
# define BOOST_PP_VARIADIC_ELEM_38(e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, e17, e18, e19, e20, e21, e22, e23, e24, e25, e26, e27, e28, e29, e30, e31, e32, e33, e34, e35, e36, e37, e38, ...) e38
# define BOOST_PP_VARIADIC_ELEM_39(e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, e17, e18, e19, e20, e21, e22, e23, e24, e25, e26, e27, e28, e29, e30, e31, e32, e33, e34, e35, e36, e37, e38, e39, ...) e39
# define BOOST_PP_VARIADIC_ELEM_40(e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, e17, e18, e19, e20, e21, e22, e23, e24, e25, e26, e27, e28, e29, e30, e31, e32, e33, e34, e35, e36, e37, e38, e39, e40, ...) e40
# define BOOST_PP_VARIADIC_ELEM_41(e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, e17, e18, e19, e20, e21, e22, e23, e24, e25, e26, e27, e28, e29, e30, e31, e32, e33, e34, e35, e36, e37, e38, e39, e40, e41, ...) e41
# define BOOST_PP_VARIADIC_ELEM_42(e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, e17, e18, e19, e20, e21, e22, e23, e24, e25, e26, e27, e28, e29, e30, e31, e32, e33, e34, e35, e36, e37, e38, e39, e40, e41, e42, ...) e42
# define BOOST_PP_VARIADIC_ELEM_43(e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, e17, e18, e19, e20, e21, e22, e23, e24, e25, e26, e27, e28, e29, e30, e31, e32, e33, e34, e35, e36, e37, e38, e39, e40, e41, e42, e43, ...) e43
# define BOOST_PP_VARIADIC_ELEM_44(e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, e17, e18, e19, e20, e21, e22, e23, e24, e25, e26, e27, e28, e29, e30, e31, e32, e33, e34, e35, e36, e37, e38, e39, e40, e41, e42, e43, e44, ...) e44
# define BOOST_PP_VARIADIC_ELEM_45(e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, e17, e18, e19, e20, e21, e22, e23, e24, e25, e26, e27, e28, e29, e30, e31, e32, e33, e34, e35, e36, e37, e38, e39, e40, e41, e42, e43, e44, e45, ...) e45
# define BOOST_PP_VARIADIC_ELEM_46(e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, e17, e18, e19, e20, e21, e22, e23, e24, e25, e26, e27, e28, e29, e30, e31, e32, e33, e34, e35, e36, e37, e38, e39, e40, e41, e42, e43, e44, e45, e46, ...) e46
# define BOOST_PP_VARIADIC_ELEM_47(e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, e17, e18, e19, e20, e21, e22, e23, e24, e25, e26, e27, e28, e29, e30, e31, e32, e33, e34, e35, e36, e37, e38, e39, e40, e41, e42, e43, e44, e45, e46, e47, ...) e47
# define BOOST_PP_VARIADIC_ELEM_48(e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, e17, e18, e19, e20, e21, e22, e23, e24, e25, e26, e27, e28, e29, e30, e31, e32, e33, e34, e35, e36, e37, e38, e39, e40, e41, e42, e43, e44, e45, e46, e47, e48, ...) e48
# define BOOST_PP_VARIADIC_ELEM_49(e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, e17, e18, e19, e20, e21, e22, e23, e24, e25, e26, e27, e28, e29, e30, e31, e32, e33, e34, e35, e36, e37, e38, e39, e40, e41, e42, e43, e44, e45, e46, e47, e48, e49, ...) e49
# define BOOST_PP_VARIADIC_ELEM_50(e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, e17, e18, e19, e20, e21, e22, e23, e24, e25, e26, e27, e28, e29, e30, e31, e32, e33, e34, e35, e36, e37, e38, e39, e40, e41, e42, e43, e44, e45, e46, e47, e48, e49, e50, ...) e50
# define BOOST_PP_VARIADIC_ELEM_51(e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, e17, e18, e19, e20, e21, e22, e23, e24, e25, e26, e27, e28, e29, e30, e31, e32, e33, e34, e35, e36, e37, e38, e39, e40, e41, e42, e43, e44, e45, e46, e47, e48, e49, e50, e51, ...) e51
# define BOOST_PP_VARIADIC_ELEM_52(e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, e17, e18, e19, e20, e21, e22, e23, e24, e25, e26, e27, e28, e29, e30, e31, e32, e33, e34, e35, e36, e37, e38, e39, e40, e41, e42, e43, e44, e45, e46, e47, e48, e49, e50, e51, e52, ...) e52
# define BOOST_PP_VARIADIC_ELEM_53(e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, e17, e18, e19, e20, e21, e22, e23, e24, e25, e26, e27, e28, e29, e30, e31, e32, e33, e34, e35, e36, e37, e38, e39, e40, e41, e42, e43, e44, e45, e46, e47, e48, e49, e50, e51, e52, e53, ...) e53
# define BOOST_PP_VARIADIC_ELEM_54(e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, e17, e18, e19, e20, e21, e22, e23, e24, e25, e26, e27, e28, e29, e30, e31, e32, e33, e34, e35, e36, e37, e38, e39, e40, e41, e42, e43, e44, e45, e46, e47, e48, e49, e50, e51, e52, e53, e54, ...) e54
# define BOOST_PP_VARIADIC_ELEM_55(e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, e17, e18, e19, e20, e21, e22, e23, e24, e25, e26, e27, e28, e29, e30, e31, e32, e33, e34, e35, e36, e37, e38, e39, e40, e41, e42, e43, e44, e45, e46, e47, e48, e49, e50, e51, e52, e53, e54, e55, ...) e55
# define BOOST_PP_VARIADIC_ELEM_56(e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, e17, e18, e19, e20, e21, e22, e23, e24, e25, e26, e27, e28, e29, e30, e31, e32, e33, e34, e35, e36, e37, e38, e39, e40, e41, e42, e43, e44, e45, e46, e47, e48, e49, e50, e51, e52, e53, e54, e55, e56, ...) e56
# define BOOST_PP_VARIADIC_ELEM_57(e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, e17, e18, e19, e20, e21, e22, e23, e24, e25, e26, e27, e28, e29, e30, e31, e32, e33, e34, e35, e36, e37, e38, e39, e40, e41, e42, e43, e44, e45, e46, e47, e48, e49, e50, e51, e52, e53, e54, e55, e56, e57, ...) e57
# define BOOST_PP_VARIADIC_ELEM_58(e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, e17, e18, e19, e20, e21, e22, e23, e24, e25, e26, e27, e28, e29, e30, e31, e32, e33, e34, e35, e36, e37, e38, e39, e40, e41, e42, e43, e44, e45, e46, e47, e48, e49, e50, e51, e52, e53, e54, e55, e56, e57, e58, ...) e58
# define BOOST_PP_VARIADIC_ELEM_59(e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, e17, e18, e19, e20, e21, e22, e23, e24, e25, e26, e27, e28, e29, e30, e31, e32, e33, e34, e35, e36, e37, e38, e39, e40, e41, e42, e43, e44, e45, e46, e47, e48, e49, e50, e51, e52, e53, e54, e55, e56, e57, e58, e59, ...) e59
# define BOOST_PP_VARIADIC_ELEM_60(e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, e17, e18, e19, e20, e21, e22, e23, e24, e25, e26, e27, e28, e29, e30, e31, e32, e33, e34, e35, e36, e37, e38, e39, e40, e41, e42, e43, e44, e45, e46, e47, e48, e49, e50, e51, e52, e53, e54, e55, e56, e57, e58, e59, e60, ...) e60
# define BOOST_PP_VARIADIC_ELEM_61(e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, e17, e18, e19, e20, e21, e22, e23, e24, e25, e26, e27, e28, e29, e30, e31, e32, e33, e34, e35, e36, e37, e38, e39, e40, e41, e42, e43, e44, e45, e46, e47, e48, e49, e50, e51, e52, e53, e54, e55, e56, e57, e58, e59, e60, e61, ...) e61
# define BOOST_PP_VARIADIC_ELEM_62(e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, e17, e18, e19, e20, e21, e22, e23, e24, e25, e26, e27, e28, e29, e30, e31, e32, e33, e34, e35, e36, e37, e38, e39, e40, e41, e42, e43, e44, e45, e46, e47, e48, e49, e50, e51, e52, e53, e54, e55, e56, e57, e58, e59, e60, e61, e62, ...) e62
# define BOOST_PP_VARIADIC_ELEM_63(e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, e17, e18, e19, e20, e21, e22, e23, e24, e25, e26, e27, e28, e29, e30, e31, e32, e33, e34, e35, e36, e37, e38, e39, e40, e41, e42, e43, e44, e45, e46, e47, e48, e49, e50, e51, e52, e53, e54, e55, e56, e57, e58, e59, e60, e61, e62, e63, ...) e63
# endif
#
# endif
|
#include <QApplication>
#include "guiutil.h"
#include "bitcoinaddressvalidator.h"
#include "walletmodel.h"
#include "bitcoinunits.h"
#include "util.h"
#include "init.h"
#include <QDateTime>
#include <QDoubleValidator>
#include <QFont>
#include <QLineEdit>
#if QT_VERSION >= 0x050000
#include <QUrlQuery>
#else
#include <QUrl>
#endif
#include <QTextDocument> // for Qt::mightBeRichText
#include <QAbstractItemView>
#include <QClipboard>
#include <QFileDialog>
#include <QDesktopServices>
#include <QThread>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#ifdef WIN32
#ifdef _WIN32_WINNT
#undef _WIN32_WINNT
#endif
#define _WIN32_WINNT 0x0501
#ifdef _WIN32_IE
#undef _WIN32_IE
#endif
#define _WIN32_IE 0x0501
#define WIN32_LEAN_AND_MEAN 1
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include "shlwapi.h"
#include "shlobj.h"
#include "shellapi.h"
#endif
namespace GUIUtil {
QString dateTimeStr(const QDateTime &date)
{
return date.date().toString(Qt::SystemLocaleShortDate) + QString(" ") + date.toString("hh:mm");
}
QString dateTimeStr(qint64 nTime)
{
return dateTimeStr(QDateTime::fromTime_t((qint32)nTime));
}
QFont bitcoinAddressFont()
{
QFont font("Monospace");
font.setStyleHint(QFont::TypeWriter);
return font;
}
void setupAddressWidget(QLineEdit *widget, QWidget *parent)
{
widget->setMaxLength(BitcoinAddressValidator::MaxAddressLength);
widget->setValidator(new BitcoinAddressValidator(parent));
widget->setFont(bitcoinAddressFont());
}
void setupAmountWidget(QLineEdit *widget, QWidget *parent)
{
QDoubleValidator *amountValidator = new QDoubleValidator(parent);
amountValidator->setDecimals(8);
amountValidator->setBottom(0.0);
widget->setValidator(amountValidator);
widget->setAlignment(Qt::AlignRight|Qt::AlignVCenter);
}
bool parseBitcoinURI(const QUrl &uri, SendCoinsRecipient *out)
{
// return if URI is not valid or is no bitcoin URI
if(!uri.isValid() || uri.scheme() != QString("potcoin"))
return false;
SendCoinsRecipient rv;
rv.address = uri.path();
rv.amount = 0;
#if QT_VERSION < 0x050000
QList<QPair<QString, QString> > items = uri.queryItems();
#else
QUrlQuery uriQuery(uri);
QList<QPair<QString, QString> > items = uriQuery.queryItems();
#endif
for (QList<QPair<QString, QString> >::iterator i = items.begin(); i != items.end(); i++)
{
bool fShouldReturnFalse = false;
if (i->first.startsWith("req-"))
{
i->first.remove(0, 4);
fShouldReturnFalse = true;
}
if (i->first == "label")
{
rv.label = i->second;
fShouldReturnFalse = false;
}
else if (i->first == "amount")
{
if(!i->second.isEmpty())
{
if(!BitcoinUnits::parse(BitcoinUnits::BTC, i->second, &rv.amount))
{
return false;
}
}
fShouldReturnFalse = false;
}
if (fShouldReturnFalse)
return false;
}
if(out)
{
*out = rv;
}
return true;
}
bool parseBitcoinURI(QString uri, SendCoinsRecipient *out)
{
// Convert bitcoin:// to bitcoin:
//
// Cannot handle this later, because bitcoin:// will cause Qt to see the part after // as host,
// which will lower-case it (and thus invalidate the address).
if(uri.startsWith("potcoin://"))
{
uri.replace(0, 11, "potcoin:");
}
QUrl uriInstance(uri);
return parseBitcoinURI(uriInstance, out);
}
QString HtmlEscape(const QString& str, bool fMultiLine)
{
#if QT_VERSION < 0x050000
QString escaped = Qt::escape(str);
#else
QString escaped = str.toHtmlEscaped();
#endif
if(fMultiLine)
{
escaped = escaped.replace("\n", "<br>\n");
}
return escaped;
}
QString HtmlEscape(const std::string& str, bool fMultiLine)
{
return HtmlEscape(QString::fromStdString(str), fMultiLine);
}
void copyEntryData(QAbstractItemView *view, int column, int role)
{
if(!view || !view->selectionModel())
return;
QModelIndexList selection = view->selectionModel()->selectedRows(column);
if(!selection.isEmpty())
{
// Copy first item (global clipboard)
QApplication::clipboard()->setText(selection.at(0).data(role).toString(), QClipboard::Clipboard);
// Copy first item (global mouse selection for e.g. X11 - NOP on Windows)
QApplication::clipboard()->setText(selection.at(0).data(role).toString(), QClipboard::Selection);
}
}
void setClipboard(const QString& str)
{
QApplication::clipboard()->setText(str, QClipboard::Clipboard);
QApplication::clipboard()->setText(str, QClipboard::Selection);
}
QString getSaveFileName(QWidget *parent, const QString &caption,
const QString &dir,
const QString &filter,
QString *selectedSuffixOut)
{
QString selectedFilter;
QString myDir;
if(dir.isEmpty()) // Default to user documents location
{
#if QT_VERSION < 0x050000
myDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation);
#else
myDir = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
#endif
}
else
{
myDir = dir;
}
QString result = QFileDialog::getSaveFileName(parent, caption, myDir, filter, &selectedFilter);
/* Extract first suffix from filter pattern "Description (*.foo)" or "Description (*.foo *.bar ...) */
QRegExp filter_re(".* \\(\\*\\.(.*)[ \\)]");
QString selectedSuffix;
if(filter_re.exactMatch(selectedFilter))
{
selectedSuffix = filter_re.cap(1);
}
/* Add suffix if needed */
QFileInfo info(result);
if(!result.isEmpty())
{
if(info.suffix().isEmpty() && !selectedSuffix.isEmpty())
{
/* No suffix specified, add selected suffix */
if(!result.endsWith("."))
result.append(".");
result.append(selectedSuffix);
}
}
/* Return selected suffix if asked to */
if(selectedSuffixOut)
{
*selectedSuffixOut = selectedSuffix;
}
return result;
}
Qt::ConnectionType blockingGUIThreadConnection()
{
if(QThread::currentThread() != qApp->thread())
{
return Qt::BlockingQueuedConnection;
}
else
{
return Qt::DirectConnection;
}
}
bool checkPoint(const QPoint &p, const QWidget *w)
{
QWidget *atW = QApplication::widgetAt(w->mapToGlobal(p));
if (!atW) return false;
return atW->topLevelWidget() == w;
}
bool isObscured(QWidget *w)
{
return !(checkPoint(QPoint(0, 0), w)
&& checkPoint(QPoint(w->width() - 1, 0), w)
&& checkPoint(QPoint(0, w->height() - 1), w)
&& checkPoint(QPoint(w->width() - 1, w->height() - 1), w)
&& checkPoint(QPoint(w->width() / 2, w->height() / 2), w));
}
void openDebugLogfile()
{
boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
/* Open debug.log with the associated application */
if (boost::filesystem::exists(pathDebug))
QDesktopServices::openUrl(QUrl::fromLocalFile(QString::fromStdString(pathDebug.string())));
}
ToolTipToRichTextFilter::ToolTipToRichTextFilter(int size_threshold, QObject *parent) :
QObject(parent), size_threshold(size_threshold)
{
}
bool ToolTipToRichTextFilter::eventFilter(QObject *obj, QEvent *evt)
{
if(evt->type() == QEvent::ToolTipChange)
{
QWidget *widget = static_cast<QWidget*>(obj);
QString tooltip = widget->toolTip();
if(tooltip.size() > size_threshold && !tooltip.startsWith("<qt/>") && !Qt::mightBeRichText(tooltip))
{
// Prefix <qt/> to make sure Qt detects this as rich text
// Escape the current message as HTML and replace \n by <br>
tooltip = "<qt/>" + HtmlEscape(tooltip, true);
widget->setToolTip(tooltip);
return true;
}
}
return QObject::eventFilter(obj, evt);
}
#ifdef WIN32
boost::filesystem::path static StartupShortcutPath()
{
return GetSpecialFolderPath(CSIDL_STARTUP) / "Potcoin.lnk";
}
bool GetStartOnSystemStartup()
{
// check for Bitcoin.lnk
return boost::filesystem::exists(StartupShortcutPath());
}
bool SetStartOnSystemStartup(bool fAutoStart)
{
// If the shortcut exists already, remove it for updating
boost::filesystem::remove(StartupShortcutPath());
if (fAutoStart)
{
CoInitialize(NULL);
// Get a pointer to the IShellLink interface.
IShellLink* psl = NULL;
HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL,
CLSCTX_INPROC_SERVER, IID_IShellLink,
reinterpret_cast<void**>(&psl));
if (SUCCEEDED(hres))
{
// Get the current executable path
TCHAR pszExePath[MAX_PATH];
GetModuleFileName(NULL, pszExePath, sizeof(pszExePath));
TCHAR pszArgs[5] = TEXT("-min");
// Set the path to the shortcut target
psl->SetPath(pszExePath);
PathRemoveFileSpec(pszExePath);
psl->SetWorkingDirectory(pszExePath);
psl->SetShowCmd(SW_SHOWMINNOACTIVE);
psl->SetArguments(pszArgs);
// Query IShellLink for the IPersistFile interface for
// saving the shortcut in persistent storage.
IPersistFile* ppf = NULL;
hres = psl->QueryInterface(IID_IPersistFile,
reinterpret_cast<void**>(&ppf));
if (SUCCEEDED(hres))
{
WCHAR pwsz[MAX_PATH];
// Ensure that the string is ANSI.
MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().string().c_str(), -1, pwsz, MAX_PATH);
// Save the link by calling IPersistFile::Save.
hres = ppf->Save(pwsz, TRUE);
ppf->Release();
psl->Release();
CoUninitialize();
return true;
}
psl->Release();
}
CoUninitialize();
return false;
}
return true;
}
#elif defined(LINUX)
// Follow the Desktop Application Autostart Spec:
// http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html
boost::filesystem::path static GetAutostartDir()
{
namespace fs = boost::filesystem;
char* pszConfigHome = getenv("XDG_CONFIG_HOME");
if (pszConfigHome) return fs::path(pszConfigHome) / "autostart";
char* pszHome = getenv("HOME");
if (pszHome) return fs::path(pszHome) / ".config" / "autostart";
return fs::path();
}
boost::filesystem::path static GetAutostartFilePath()
{
return GetAutostartDir() / "potcoin.desktop";
}
bool GetStartOnSystemStartup()
{
boost::filesystem::ifstream optionFile(GetAutostartFilePath());
if (!optionFile.good())
return false;
// Scan through file for "Hidden=true":
std::string line;
while (!optionFile.eof())
{
getline(optionFile, line);
if (line.find("Hidden") != std::string::npos &&
line.find("true") != std::string::npos)
return false;
}
optionFile.close();
return true;
}
bool SetStartOnSystemStartup(bool fAutoStart)
{
if (!fAutoStart)
boost::filesystem::remove(GetAutostartFilePath());
else
{
char pszExePath[MAX_PATH+1];
memset(pszExePath, 0, sizeof(pszExePath));
if (readlink("/proc/self/exe", pszExePath, sizeof(pszExePath)-1) == -1)
return false;
boost::filesystem::create_directories(GetAutostartDir());
boost::filesystem::ofstream optionFile(GetAutostartFilePath(), std::ios_base::out|std::ios_base::trunc);
if (!optionFile.good())
return false;
// Write a bitcoin.desktop file to the autostart directory:
optionFile << "[Desktop Entry]\n";
optionFile << "Type=Application\n";
optionFile << "Name=Potcoin\n";
optionFile << "Exec=" << pszExePath << " -min\n";
optionFile << "Terminal=false\n";
optionFile << "Hidden=false\n";
optionFile.close();
}
return true;
}
#elif defined(Q_OS_MAC)
// based on: https://github.com/Mozketo/LaunchAtLoginController/blob/master/LaunchAtLoginController.m
#include <CoreFoundation/CoreFoundation.h>
#include <CoreServices/CoreServices.h>
LSSharedFileListItemRef findStartupItemInList(LSSharedFileListRef list, CFURLRef findUrl);
LSSharedFileListItemRef findStartupItemInList(LSSharedFileListRef list, CFURLRef findUrl)
{
// loop through the list of startup items and try to find the bitcoin app
CFArrayRef listSnapshot = LSSharedFileListCopySnapshot(list, NULL);
for(int i = 0; i < CFArrayGetCount(listSnapshot); i++) {
LSSharedFileListItemRef item = (LSSharedFileListItemRef)CFArrayGetValueAtIndex(listSnapshot, i);
UInt32 resolutionFlags = kLSSharedFileListNoUserInteraction | kLSSharedFileListDoNotMountVolumes;
CFURLRef currentItemURL = NULL;
LSSharedFileListItemResolve(item, resolutionFlags, ¤tItemURL, NULL);
if(currentItemURL && CFEqual(currentItemURL, findUrl)) {
// found
CFRelease(currentItemURL);
return item;
}
if(currentItemURL) {
CFRelease(currentItemURL);
}
}
return NULL;
}
bool GetStartOnSystemStartup()
{
CFURLRef bitcoinAppUrl = CFBundleCopyBundleURL(CFBundleGetMainBundle());
LSSharedFileListRef loginItems = LSSharedFileListCreate(NULL, kLSSharedFileListSessionLoginItems, NULL);
LSSharedFileListItemRef foundItem = findStartupItemInList(loginItems, bitcoinAppUrl);
return !!foundItem; // return boolified object
}
bool SetStartOnSystemStartup(bool fAutoStart)
{
CFURLRef bitcoinAppUrl = CFBundleCopyBundleURL(CFBundleGetMainBundle());
LSSharedFileListRef loginItems = LSSharedFileListCreate(NULL, kLSSharedFileListSessionLoginItems, NULL);
LSSharedFileListItemRef foundItem = findStartupItemInList(loginItems, bitcoinAppUrl);
if(fAutoStart && !foundItem) {
// add bitcoin app to startup item list
LSSharedFileListInsertItemURL(loginItems, kLSSharedFileListItemBeforeFirst, NULL, NULL, bitcoinAppUrl, NULL, NULL);
}
else if(!fAutoStart && foundItem) {
// remove item
LSSharedFileListItemRemove(loginItems, foundItem);
}
return true;
}
#else
bool GetStartOnSystemStartup() { return false; }
bool SetStartOnSystemStartup(bool fAutoStart) { return false; }
#endif
HelpMessageBox::HelpMessageBox(QWidget *parent) :
QMessageBox(parent)
{
header = tr("Potcoin-Qt") + " " + tr("version") + " " +
QString::fromStdString(FormatFullVersion()) + "\n\n" +
tr("Usage:") + "\n" +
" potcoin-qt [" + tr("command-line options") + "] " + "\n";
coreOptions = QString::fromStdString(HelpMessage());
uiOptions = tr("UI options") + ":\n" +
" -lang=<lang> " + tr("Set language, for example \"de_DE\" (default: system locale)") + "\n" +
" -min " + tr("Start minimized") + "\n" +
" -splash " + tr("Show splash screen on startup (default: 1)") + "\n";
setWindowTitle(tr("Potcoin-Qt"));
setTextFormat(Qt::PlainText);
// setMinimumWidth is ignored for QMessageBox so put in non-breaking spaces to make it wider.
setText(header + QString(QChar(0x2003)).repeated(50));
setDetailedText(coreOptions + "\n" + uiOptions);
}
void HelpMessageBox::printToConsole()
{
// On other operating systems, the expected action is to print the message to the console.
QString strUsage = header + "\n" + coreOptions + "\n" + uiOptions;
fprintf(stdout, "%s", strUsage.toStdString().c_str());
}
void HelpMessageBox::showOrPrint()
{
#if defined(WIN32)
// On Windows, show a message box, as there is no stderr/stdout in windowed applications
exec();
#else
// On other operating systems, print help text to console
printToConsole();
#endif
}
} // namespace GUIUtil
|
#include "Precompile.hpp"
#include "ValueDragBoxUI.hpp"
#include <cinttypes>
#include <imgui.h>
#include <unordered_map>
namespace krakoa::ui
{
const char* GetPrintfToken(size_t hashcode)
{
static const std::unordered_map<size_t, const char*> tokenMap = {
{typeid(long double).hash_code(), "%.6f"},
{typeid(double).hash_code(), "%.6f"},
{typeid(float).hash_code(), "%.3f"},
{typeid(std::int8_t).hash_code(), "%" PRId8},
{typeid(std::int16_t).hash_code(), "%" PRId16},
{typeid(std::int32_t).hash_code(), "%" PRId32},
{typeid(long).hash_code(), "%" PRId32},
{typeid(std::int64_t).hash_code(), "%" PRIu64},
{typeid(std::uint8_t).hash_code(), "%" PRIu8},
{typeid(std::uint16_t).hash_code(), "%" PRIu16},
{typeid(std::uint32_t).hash_code(), "%" PRIu32},
{typeid(unsigned long).hash_code(), "%" PRIu32},
{typeid(std::uint64_t).hash_code(), "%" PRIu64},
};
return tokenMap.at(hashcode);
}
template <>
bool DrawDragValue(const std::string_view& label, std::int8_t& value, float increment, std::int8_t v_min
, std::int8_t v_max, const char* format, const UICallBack& instruction)
{
if (ImGui::DragScalar(label.data(), ImGuiDataType_S8, &value, increment, &v_min, &v_max, format))
{
if (instruction)
instruction();
return true;
}
return false;
}
template <>
bool DrawDragValue(const std::string_view& label, std::int16_t& value, float increment, std::int16_t v_min
, std::int16_t v_max, const char* format, const UICallBack& instruction)
{
if (ImGui::DragScalar(label.data(), ImGuiDataType_S16, &value, increment, &v_min, &v_max, format))
{
if (instruction)
instruction();
return true;
}
return false;
}
template <>
bool DrawDragValue(const std::string_view& label, std::int32_t& value, float increment, std::int32_t v_min
, std::int32_t v_max, const char* format, const UICallBack& instruction)
{
if (ImGui::DragScalar(label.data(), ImGuiDataType_S32, &value, increment, &v_min, &v_max, format))
{
if (instruction)
instruction();
return true;
}
return false;
}
template<>
bool DrawDragValue(const std::string_view& label, std::int64_t& value, float increment, std::int64_t v_min, std::int64_t v_max
, const char* format, const UICallBack& instruction)
{
if (ImGui::DragScalar(label.data(), ImGuiDataType_S64, &value, increment, &v_min, &v_max, format))
{
if (instruction)
instruction();
return true;
}
return false;
}
template<>
bool DrawDragValue(const std::string_view& label, std::uint8_t& value, float increment, std::uint8_t v_min, std::uint8_t v_max
, const char* format, const UICallBack& instruction)
{
if (ImGui::DragScalar(label.data(), ImGuiDataType_U8, &value, increment, &v_min, &v_max, format))
{
if (instruction)
instruction();
return true;
}
return false;
}
template<>
bool DrawDragValue(const std::string_view& label, std::uint16_t& value, float increment, std::uint16_t v_min, std::uint16_t v_max
, const char* format, const UICallBack& instruction)
{
if (ImGui::DragScalar(label.data(), ImGuiDataType_U16, &value, increment, &v_min, &v_max, format))
{
if (instruction)
instruction();
return true;
}
return false;
}
template<>
bool DrawDragValue(const std::string_view& label, std::uint32_t& value, float increment, std::uint32_t v_min, std::uint32_t v_max
, const char* format, const UICallBack& instruction)
{
if (ImGui::DragScalar(label.data(), ImGuiDataType_U32, &value, increment, &v_min, &v_max, format))
{
if (instruction)
instruction();
return true;
}
return false;
}
template<>
bool DrawDragValue(const std::string_view& label, std::uint64_t& value, float increment, std::uint64_t v_min, std::uint64_t v_max
, const char* format, const UICallBack& instruction)
{
if (ImGui::DragScalar(label.data(), ImGuiDataType_U64, &value, increment, &v_min, &v_max, format))
{
if (instruction)
instruction();
return true;
}
return false;
}
template<>
bool DrawDragValue(const std::string_view& label, float& value, float increment, float v_min, float v_max
, const char* format, const UICallBack& instruction)
{
if (ImGui::DragScalar(label.data(), ImGuiDataType_Float, &value, increment, &v_min, &v_max, format))
{
if (instruction)
instruction();
return true;
}
return false;
}
template<>
bool DrawDragValue(const std::string_view& label, double& value, float increment, double v_min, double v_max
, const char* format, const UICallBack& instruction)
{
if (ImGui::DragScalar(label.data(), ImGuiDataType_Double, &value, increment, &v_min, &v_max, format))
{
if (instruction)
instruction();
return true;
}
return false;
}
}
|
//
// ********************************************************************
// * License and Disclaimer *
// * *
// * The Geant4 software is copyright of the Copyright Holders of *
// * the Geant4 Collaboration. It is provided under the terms and *
// * conditions of the Geant4 Software License, included in the file *
// * LICENSE and available at http://cern.ch/geant4/license . These *
// * include a list of copyright holders. *
// * *
// * Neither the authors of this software system, nor their employing *
// * institutes,nor the agencies providing financial support for this *
// * work make any representation or warranty, express or implied, *
// * regarding this software system or assume any liability for its *
// * use. Please see the license in the file LICENSE and URL above *
// * for the full disclaimer and the limitation of liability. *
// * *
// * This code implementation is the result of the scientific and *
// * technical work of the GEANT4 collaboration. *
// * By using, copying, modifying or distributing the software (or *
// * any work based on the software) you agree to acknowledge its *
// * use in resulting scientific publications, and indicate your *
// * acceptance of all terms of the Geant4 Software license. *
// ********************************************************************
//
/// \file analysis/shared/include/DetectorConstruction.hh
/// \brief Definition of the DetectorConstruction class
//
//
// $Id: DetectorConstruction.hh 77256 2013-11-22 10:10:23Z gcosmo $
//
//
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
#ifndef DETECTORCONSTRUCTION_HH
#define DETECTORCONSTRUCTION_HH
#include <unordered_map>
#include "G4VUserDetectorConstruction.hh"
#include "globals.hh"
#include "G4ThreeVector.hh"
class G4Box;
class G4LogicalVolume;
class G4VPhysicalVolume;
class G4Material;
class DetectorMessenger;
//class DetectionSystemGammaTracking;
class DetectionSystemGriffin;
class DetectionSystem8pi;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
class DetectionSystemDescant;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
class ApparatusDescantStructure;
class ApparatusLayeredTarget;
class DetectionSystemDescant;
class DetectionSystemSceptar;
class DetectionSystemSpice;
class DetectionSystemTrific;
class DetectionSystemPaces;
class DetectionSystemSodiumIodide;
class DetectionSystemLanthanumBromide;
class DetectionSystemBox;
class DetectionSystemAncillaryBGO;
//class MagneticField;
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
struct DetectorProperties {
G4int systemID;
G4int detectorNumber;
G4int crystalNumber;
void Clear()
{
systemID = 0;
detectorNumber = 0;
crystalNumber = 0;
}
};
bool operator==(const DetectorProperties& lhs, const DetectorProperties& rhs);
class DetectorConstruction : public G4VUserDetectorConstruction
{
public:
DetectorConstruction();
~DetectorConstruction();
G4int GriffinDetectorsMap(G4int i) { if(i < 0 || i > 15) return -1; return fGriffinDetectorsMap[i]; }
void PassEfficiencyPosition( G4ThreeVector num ) {fDetEffPosition = num;}
void SetWorldMaterial( G4String );
void SetWorldDimensions( G4ThreeVector );
void SetWorldVis( G4bool );
void SetWorldStepLimit( G4double );
//Generic Target
void SetGenericTargetMaterial( G4String );
void SetGenericTargetDimensions( G4ThreeVector );
void SetGenericTargetPosition( G4ThreeVector );
void SetGenericTarget( );
G4double LayeredTargetLayerStart(int);
void LayeredTargetAdd(G4String, G4double);
void SetTabMagneticField(G4String, G4double, G4double);
// Grid Functions
void SetGridMat( G4String input ) {fGridMat = input;};
void SetGridSize( G4double input ) {fGridSize = input;};
void SetGridDimensions( G4ThreeVector input ) {fGridDimensions = input;};
void SetGridColour( G4ThreeVector input ) {fGridColour = input;};
void SetGridPosOffset( G4ThreeVector input ) {fGridOffset = input;};
void AddGrid();
void AddApparatusSpiceTargetChamber(G4String);
void AddApparatus8piVacuumChamber();
void AddApparatus8piVacuumChamberAuxMatShell(G4double thickness);
void AddApparatusGriffinStructure(G4int selector);
G4double GetWorldSizeX() {return fWorldSizeX;};
G4double GetWorldSizeY() {return fWorldSizeY;};
G4double GetWorldSizeZ() {return fWorldSizeZ;};
const G4VPhysicalVolume* GetphysiWorld() {return fPhysiWorld;};
G4VPhysicalVolume* Construct();
void UpdateGeometry();
void AddDetectionSystemSodiumIodide(G4int ndet);
void AddDetectionSystemLanthanumBromide(G4ThreeVector input);
void AddDetectionSystemAncillaryBGO(G4ThreeVector input);
void AddDetectionSystem8pi(G4int ndet);
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void AddDetectionSystemDescant(G4int ndet);
void AddDetectionSystemDescantAuxPorts(G4ThreeVector input);
void SetDetectionSystemDescantRotation(G4ThreeVector input);
void SetDetectionSystemDescantColor(G4String input);
void AddDetectionSystemDescantCart(G4ThreeVector input);
void AddDetectionSystemDescantSpher(G4ThreeVector input, G4double unit);
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void AddApparatusDescantStructure();
void AddDetectionSystemTestcan(G4ThreeVector input);
void AddDetectionSystem8piDetector(G4int ndet);
void AddDetectionSystemGriffinForward(G4int ndet);
void AddDetectionSystemGriffinForwardDetector(G4int ndet);
void AddDetectionSystemGriffinBack(G4int ndet);
void AddDetectionSystemGriffinBackDetector(G4int ndet);
//void AddDetectionSystemGriffinPositionConfig(G4ThreeVector input);
void AddDetectionSystemGriffinHevimet(G4int input);
void AddDetectionSystemGriffinCustom(G4int ndet);
void AddDetectionSystemGriffinCustomDetector(G4int ndet = 0);
void AddDetectionSystemGriffinShieldSelect(G4int ShieldSelect );
void AddDetectionSystemGriffinSetRadialDistance(G4double detectorDist);
void AddDetectionSystemGriffinSetExtensionSuppLocation(G4int detectorPos);
void AddDetectionSystemGriffinSetPosition(G4ThreeVector params);
void AddDetectionSystemGriffinSetDeadLayer(G4ThreeVector params);
void AddDetectionSystemSceptar(G4int ndet);
void AddDetectionSystemPaces(G4int ndet);
void AddDetectionSystemSpice();
void AddDetectionSystemTrific(G4double);
G4double GetLanthanumBromideCrystalRadius();
G4double GetLanthanumBromideCrystalLength();
G4double GetLanthanumBromideR();
G4double GetLanthanumBromideTheta(G4int i);
G4double GetLanthanumBromidePhi(G4int i);
G4double GetLanthanumBromideYaw(G4int i);
G4double GetLanthanumBromidePitch(G4int i);
G4double GetLanthanumBromideRoll(G4int i);
G4double GetLanthanumBromideCrystalRadialPosition();
G4bool GridCell() { return fGridCell; }
G4bool Griffin() { return fGriffin; }
G4bool LaBr() { return fLaBr; }
G4bool AncBgo() { return fAncBgo; }
G4bool NaI() { return fNaI; }
G4bool Sceptar() { return fSceptar; }
G4bool EightPi() { return fEightPi; }
G4bool Spice() { return fSpice; }
G4bool Paces() { return fPaces; }
G4bool Descant() { return fDescant; }
G4bool Testcan() { return fTestcan; }
void RecordGun( G4bool input ){fRecordGun = input;};
G4bool RecordingGun(){return fRecordGun;};
void UseTIGRESSPositions( G4bool input ) {fUseTigressPositions = input;};
bool HasProperties(G4VPhysicalVolume* vol) { return fPropertiesMap.find(vol) != fPropertiesMap.end(); }
DetectorProperties GetProperties(G4VPhysicalVolume* vol) { return fPropertiesMap.at(vol); }
void SetProperties();
void SetPropertiesRecursive(G4LogicalVolume* vol);
void Print();
void PrintRecursive(G4LogicalVolume* vol);
G4double fTrifWindowThickness;
G4bool fTrifAluminised;
G4bool fTrifFlatWindow;
private:
bool CheckVolumeName(G4String volumeName);
DetectorProperties ParseVolumeName(G4String volumeName);
G4int fGriffinDetectorsMapIndex;
G4int fGriffinDetectorsMap[16];
G4double fWorldSizeX;
G4double fWorldSizeY;
G4double fWorldSizeZ;
G4bool fWorldVis;
G4bool fBuiltDetectors;
G4double fGriffinFwdBackPosition;
G4int fDetectorShieldSelect ;
G4double fDetectorRadialDistance ;
G4int fExtensionSuppressorLocation ;
G4int fCustomDetectorNumber ;
G4int fCustomDetectorPosition ;
G4int fCustomDetectorVal ;
G4int fHevimetSelector ;
G4bool fUseTigressPositions;
G4bool fRecordGun;
// Box
G4String fBoxMat;
G4double fBoxThickness;
G4ThreeVector fBoxInnerDimensions;
G4ThreeVector fBoxColour;
G4Box* fSolidWorld; //pointer to the solid World
G4LogicalVolume* fLogicWorld; //pointer to the logical World
G4VPhysicalVolume* fPhysiWorld; //pointer to the physical World
// Grid
G4String fGridMat;
G4double fGridSize;
G4ThreeVector fGridDimensions;
G4ThreeVector fGridColour;
G4ThreeVector fGridOffset;
void DefineSuppressedParameters();
void DefineMaterials();
G4double fCoords[20][5];
G4bool fSetGenericTargetMaterial;
G4bool fSetGenericTargetDimensions;
G4bool fSetGenericTargetPosition;
G4String fGenericTargetMaterial;
G4ThreeVector fGenericTargetDimensions;
G4ThreeVector fGenericTargetPosition;
G4bool fSetFieldBoxMaterial;
G4bool fSetFieldBoxDimensions;
G4bool fSetFieldBoxPosition;
G4bool fSetFieldBoxMagneticField;
G4String fFieldBoxMaterial;
G4ThreeVector fFieldBoxDimensions;
G4ThreeVector fFieldBoxPosition;
G4ThreeVector fFieldBoxMagneticField;
G4String fMatWorldName;
ApparatusLayeredTarget* fApparatusLayeredTarget;
DetectorMessenger* fDetectorMessenger;
G4double fGriffinDeadLayer[16][4];
G4ThreeVector fDescantRotation;
G4String fDescantColor;
G4ThreeVector fDetEffPosition;
//booleans which control which histograms are created (these are set by the detector construction)
G4bool fGridCell;
G4bool fGriffin;
G4bool fLaBr;
G4bool fAncBgo;
G4bool fNaI;
G4bool fSceptar;
G4bool fEightPi;
G4bool fDescant;
G4bool fTestcan;
G4bool fSpice;
G4bool fPaces;
//unordered maps which hold properties of the physical volumes created
std::unordered_map<G4VPhysicalVolume*, DetectorProperties> fPropertiesMap;
};
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
#endif
|
/* Copyright (c) 2016, Google Inc.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
* OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
#include <openssl_grpc/base.h>
#include <stdio.h>
#include <string.h>
#include <gtest/gtest.h>
#include <openssl_grpc/bn.h>
#include <openssl_grpc/cpu.h>
#include <openssl_grpc/ec.h>
#include <openssl_grpc/mem.h>
#include <openssl_grpc/nid.h>
#include "internal.h"
#include "../bn/internal.h"
#include "../../internal.h"
#include "../../test/abi_test.h"
#include "../../test/file_test.h"
#include "../../test/test_util.h"
#include "p256-x86_64.h"
// Disable tests if BORINGSSL_SHARED_LIBRARY is defined. These tests need access
// to internal functions.
#if !defined(OPENSSL_NO_ASM) && defined(OPENSSL_X86_64) && \
!defined(OPENSSL_SMALL) && !defined(BORINGSSL_SHARED_LIBRARY)
TEST(P256_X86_64Test, SelectW5) {
// Fill a table with some garbage input.
alignas(64) P256_POINT table[16];
for (size_t i = 0; i < 16; i++) {
OPENSSL_memset(table[i].X, 3 * i, sizeof(table[i].X));
OPENSSL_memset(table[i].Y, 3 * i + 1, sizeof(table[i].Y));
OPENSSL_memset(table[i].Z, 3 * i + 2, sizeof(table[i].Z));
}
for (int i = 0; i <= 16; i++) {
P256_POINT val;
ecp_nistz256_select_w5(&val, table, i);
P256_POINT expected;
if (i == 0) {
OPENSSL_memset(&expected, 0, sizeof(expected));
} else {
expected = table[i-1];
}
EXPECT_EQ(Bytes(reinterpret_cast<const char *>(&expected), sizeof(expected)),
Bytes(reinterpret_cast<const char *>(&val), sizeof(val)));
}
// This is a constant-time function, so it is only necessary to instrument one
// index for ABI checking.
P256_POINT val;
CHECK_ABI(ecp_nistz256_select_w5, &val, table, 7);
}
TEST(P256_X86_64Test, SelectW7) {
// Fill a table with some garbage input.
alignas(64) P256_POINT_AFFINE table[64];
for (size_t i = 0; i < 64; i++) {
OPENSSL_memset(table[i].X, 2 * i, sizeof(table[i].X));
OPENSSL_memset(table[i].Y, 2 * i + 1, sizeof(table[i].Y));
}
for (int i = 0; i <= 64; i++) {
P256_POINT_AFFINE val;
ecp_nistz256_select_w7(&val, table, i);
P256_POINT_AFFINE expected;
if (i == 0) {
OPENSSL_memset(&expected, 0, sizeof(expected));
} else {
expected = table[i-1];
}
EXPECT_EQ(Bytes(reinterpret_cast<const char *>(&expected), sizeof(expected)),
Bytes(reinterpret_cast<const char *>(&val), sizeof(val)));
}
// This is a constant-time function, so it is only necessary to instrument one
// index for ABI checking.
P256_POINT_AFFINE val;
CHECK_ABI(ecp_nistz256_select_w7, &val, table, 42);
}
TEST(P256_X86_64Test, BEEU) {
if ((OPENSSL_ia32cap_P[1] & (1 << 28)) == 0) {
// No AVX support; cannot run the BEEU code.
return;
}
bssl::UniquePtr<EC_GROUP> group(
EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1));
ASSERT_TRUE(group);
BN_ULONG order_words[P256_LIMBS];
ASSERT_TRUE(
bn_copy_words(order_words, P256_LIMBS, EC_GROUP_get0_order(group.get())));
BN_ULONG in[P256_LIMBS], out[P256_LIMBS];
EC_SCALAR in_scalar, out_scalar, result;
OPENSSL_memset(in, 0, sizeof(in));
// Trying to find the inverse of zero should fail.
ASSERT_FALSE(beeu_mod_inverse_vartime(out, in, order_words));
// This is not a constant-time function, so instrument both zero and a few
// inputs below.
ASSERT_FALSE(CHECK_ABI(beeu_mod_inverse_vartime, out, in, order_words));
// kOneMont is 1, in Montgomery form.
static const BN_ULONG kOneMont[P256_LIMBS] = {
TOBN(0xc46353d, 0x039cdaaf),
TOBN(0x43190552, 0x58e8617b),
0,
0xffffffff,
};
for (BN_ULONG i = 1; i < 2000; i++) {
SCOPED_TRACE(i);
in[0] = i;
if (i >= 1000) {
in[1] = i << 8;
in[2] = i << 32;
in[3] = i << 48;
} else {
in[1] = in[2] = in[3] = 0;
}
EXPECT_TRUE(bn_less_than_words(in, order_words, P256_LIMBS));
ASSERT_TRUE(beeu_mod_inverse_vartime(out, in, order_words));
EXPECT_TRUE(bn_less_than_words(out, order_words, P256_LIMBS));
// Calculate out*in and confirm that it equals one, modulo the order.
OPENSSL_memcpy(in_scalar.bytes, in, sizeof(in));
OPENSSL_memcpy(out_scalar.bytes, out, sizeof(out));
ec_scalar_to_montgomery(group.get(), &in_scalar, &in_scalar);
ec_scalar_to_montgomery(group.get(), &out_scalar, &out_scalar);
ec_scalar_mul_montgomery(group.get(), &result, &in_scalar, &out_scalar);
EXPECT_EQ(0, OPENSSL_memcmp(kOneMont, &result, sizeof(kOneMont)));
// Invert the result and expect to get back to the original value.
ASSERT_TRUE(beeu_mod_inverse_vartime(out, out, order_words));
EXPECT_EQ(0, OPENSSL_memcmp(in, out, sizeof(in)));
if (i < 5) {
EXPECT_TRUE(CHECK_ABI(beeu_mod_inverse_vartime, out, in, order_words));
}
}
}
static bool GetFieldElement(FileTest *t, BN_ULONG out[P256_LIMBS],
const char *name) {
std::vector<uint8_t> bytes;
if (!t->GetBytes(&bytes, name)) {
return false;
}
if (bytes.size() != BN_BYTES * P256_LIMBS) {
ADD_FAILURE() << "Invalid length: " << name;
return false;
}
// |byte| contains bytes in big-endian while |out| should contain |BN_ULONG|s
// in little-endian.
OPENSSL_memset(out, 0, P256_LIMBS * sizeof(BN_ULONG));
for (size_t i = 0; i < bytes.size(); i++) {
out[P256_LIMBS - 1 - (i / BN_BYTES)] <<= 8;
out[P256_LIMBS - 1 - (i / BN_BYTES)] |= bytes[i];
}
return true;
}
static std::string FieldElementToString(const BN_ULONG a[P256_LIMBS]) {
std::string ret;
for (size_t i = P256_LIMBS-1; i < P256_LIMBS; i--) {
char buf[2 * BN_BYTES + 1];
BIO_snprintf(buf, sizeof(buf), BN_HEX_FMT2, a[i]);
ret += buf;
}
return ret;
}
static testing::AssertionResult ExpectFieldElementsEqual(
const char *expected_expr, const char *actual_expr,
const BN_ULONG expected[P256_LIMBS], const BN_ULONG actual[P256_LIMBS]) {
if (OPENSSL_memcmp(expected, actual, sizeof(BN_ULONG) * P256_LIMBS) == 0) {
return testing::AssertionSuccess();
}
return testing::AssertionFailure()
<< "Expected: " << FieldElementToString(expected) << " ("
<< expected_expr << ")\n"
<< "Actual: " << FieldElementToString(actual) << " (" << actual_expr
<< ")";
}
#define EXPECT_FIELD_ELEMENTS_EQUAL(a, b) \
EXPECT_PRED_FORMAT2(ExpectFieldElementsEqual, a, b)
static bool PointToAffine(P256_POINT_AFFINE *out, const P256_POINT *in) {
static const uint8_t kP[] = {
0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
};
bssl::UniquePtr<BIGNUM> x(BN_new()), y(BN_new()), z(BN_new());
bssl::UniquePtr<BIGNUM> p(BN_bin2bn(kP, sizeof(kP), nullptr));
if (!x || !y || !z || !p ||
!bn_set_words(x.get(), in->X, P256_LIMBS) ||
!bn_set_words(y.get(), in->Y, P256_LIMBS) ||
!bn_set_words(z.get(), in->Z, P256_LIMBS)) {
return false;
}
// Coordinates must be fully-reduced.
if (BN_cmp(x.get(), p.get()) >= 0 ||
BN_cmp(y.get(), p.get()) >= 0 ||
BN_cmp(z.get(), p.get()) >= 0) {
return false;
}
if (BN_is_zero(z.get())) {
// The point at infinity is represented as (0, 0).
OPENSSL_memset(out, 0, sizeof(P256_POINT_AFFINE));
return true;
}
bssl::UniquePtr<BN_CTX> ctx(BN_CTX_new());
bssl::UniquePtr<BN_MONT_CTX> mont(
BN_MONT_CTX_new_for_modulus(p.get(), ctx.get()));
if (!ctx || !mont ||
// Invert Z.
!BN_from_montgomery(z.get(), z.get(), mont.get(), ctx.get()) ||
!BN_mod_inverse(z.get(), z.get(), p.get(), ctx.get()) ||
!BN_to_montgomery(z.get(), z.get(), mont.get(), ctx.get()) ||
// Convert (X, Y, Z) to (X/Z^2, Y/Z^3).
!BN_mod_mul_montgomery(x.get(), x.get(), z.get(), mont.get(),
ctx.get()) ||
!BN_mod_mul_montgomery(x.get(), x.get(), z.get(), mont.get(),
ctx.get()) ||
!BN_mod_mul_montgomery(y.get(), y.get(), z.get(), mont.get(),
ctx.get()) ||
!BN_mod_mul_montgomery(y.get(), y.get(), z.get(), mont.get(),
ctx.get()) ||
!BN_mod_mul_montgomery(y.get(), y.get(), z.get(), mont.get(),
ctx.get()) ||
!bn_copy_words(out->X, P256_LIMBS, x.get()) ||
!bn_copy_words(out->Y, P256_LIMBS, y.get())) {
return false;
}
return true;
}
static testing::AssertionResult ExpectPointsEqual(
const char *expected_expr, const char *actual_expr,
const P256_POINT_AFFINE *expected, const P256_POINT *actual) {
// There are multiple representations of the same |P256_POINT|, so convert to
// |P256_POINT_AFFINE| and compare.
P256_POINT_AFFINE affine;
if (!PointToAffine(&affine, actual)) {
return testing::AssertionFailure()
<< "Could not convert " << actual_expr << " to affine: ("
<< FieldElementToString(actual->X) << ", "
<< FieldElementToString(actual->Y) << ", "
<< FieldElementToString(actual->Z) << ")";
}
if (OPENSSL_memcmp(expected, &affine, sizeof(P256_POINT_AFFINE)) != 0) {
return testing::AssertionFailure()
<< "Expected: (" << FieldElementToString(expected->X) << ", "
<< FieldElementToString(expected->Y) << ") (" << expected_expr
<< "; affine)\n"
<< "Actual: (" << FieldElementToString(affine.X) << ", "
<< FieldElementToString(affine.Y) << ") (" << actual_expr << ")";
}
return testing::AssertionSuccess();
}
#define EXPECT_POINTS_EQUAL(a, b) EXPECT_PRED_FORMAT2(ExpectPointsEqual, a, b)
static void TestNegate(FileTest *t) {
BN_ULONG a[P256_LIMBS], b[P256_LIMBS];
ASSERT_TRUE(GetFieldElement(t, a, "A"));
ASSERT_TRUE(GetFieldElement(t, b, "B"));
// Test that -A = B.
BN_ULONG ret[P256_LIMBS];
ecp_nistz256_neg(ret, a);
EXPECT_FIELD_ELEMENTS_EQUAL(b, ret);
OPENSSL_memcpy(ret, a, sizeof(ret));
ecp_nistz256_neg(ret, ret /* a */);
EXPECT_FIELD_ELEMENTS_EQUAL(b, ret);
// Test that -B = A.
ecp_nistz256_neg(ret, b);
EXPECT_FIELD_ELEMENTS_EQUAL(a, ret);
OPENSSL_memcpy(ret, b, sizeof(ret));
ecp_nistz256_neg(ret, ret /* b */);
EXPECT_FIELD_ELEMENTS_EQUAL(a, ret);
}
static void TestMulMont(FileTest *t) {
BN_ULONG a[P256_LIMBS], b[P256_LIMBS], result[P256_LIMBS];
ASSERT_TRUE(GetFieldElement(t, a, "A"));
ASSERT_TRUE(GetFieldElement(t, b, "B"));
ASSERT_TRUE(GetFieldElement(t, result, "Result"));
BN_ULONG ret[P256_LIMBS];
ecp_nistz256_mul_mont(ret, a, b);
EXPECT_FIELD_ELEMENTS_EQUAL(result, ret);
ecp_nistz256_mul_mont(ret, b, a);
EXPECT_FIELD_ELEMENTS_EQUAL(result, ret);
OPENSSL_memcpy(ret, a, sizeof(ret));
ecp_nistz256_mul_mont(ret, ret /* a */, b);
EXPECT_FIELD_ELEMENTS_EQUAL(result, ret);
OPENSSL_memcpy(ret, a, sizeof(ret));
ecp_nistz256_mul_mont(ret, b, ret);
EXPECT_FIELD_ELEMENTS_EQUAL(result, ret);
OPENSSL_memcpy(ret, b, sizeof(ret));
ecp_nistz256_mul_mont(ret, a, ret /* b */);
EXPECT_FIELD_ELEMENTS_EQUAL(result, ret);
OPENSSL_memcpy(ret, b, sizeof(ret));
ecp_nistz256_mul_mont(ret, ret /* b */, a);
EXPECT_FIELD_ELEMENTS_EQUAL(result, ret);
if (OPENSSL_memcmp(a, b, sizeof(a)) == 0) {
ecp_nistz256_sqr_mont(ret, a);
EXPECT_FIELD_ELEMENTS_EQUAL(result, ret);
OPENSSL_memcpy(ret, a, sizeof(ret));
ecp_nistz256_sqr_mont(ret, ret /* a */);
EXPECT_FIELD_ELEMENTS_EQUAL(result, ret);
}
}
static void TestFromMont(FileTest *t) {
BN_ULONG a[P256_LIMBS], result[P256_LIMBS];
ASSERT_TRUE(GetFieldElement(t, a, "A"));
ASSERT_TRUE(GetFieldElement(t, result, "Result"));
BN_ULONG ret[P256_LIMBS];
ecp_nistz256_from_mont(ret, a);
EXPECT_FIELD_ELEMENTS_EQUAL(result, ret);
OPENSSL_memcpy(ret, a, sizeof(ret));
ecp_nistz256_from_mont(ret, ret /* a */);
EXPECT_FIELD_ELEMENTS_EQUAL(result, ret);
}
static void TestPointAdd(FileTest *t) {
P256_POINT a, b;
P256_POINT_AFFINE result;
ASSERT_TRUE(GetFieldElement(t, a.X, "A.X"));
ASSERT_TRUE(GetFieldElement(t, a.Y, "A.Y"));
ASSERT_TRUE(GetFieldElement(t, a.Z, "A.Z"));
ASSERT_TRUE(GetFieldElement(t, b.X, "B.X"));
ASSERT_TRUE(GetFieldElement(t, b.Y, "B.Y"));
ASSERT_TRUE(GetFieldElement(t, b.Z, "B.Z"));
ASSERT_TRUE(GetFieldElement(t, result.X, "Result.X"));
ASSERT_TRUE(GetFieldElement(t, result.Y, "Result.Y"));
P256_POINT ret;
ecp_nistz256_point_add(&ret, &a, &b);
EXPECT_POINTS_EQUAL(&result, &ret);
ecp_nistz256_point_add(&ret, &b, &a);
EXPECT_POINTS_EQUAL(&result, &ret);
OPENSSL_memcpy(&ret, &a, sizeof(ret));
ecp_nistz256_point_add(&ret, &ret /* a */, &b);
EXPECT_POINTS_EQUAL(&result, &ret);
OPENSSL_memcpy(&ret, &a, sizeof(ret));
ecp_nistz256_point_add(&ret, &b, &ret /* a */);
EXPECT_POINTS_EQUAL(&result, &ret);
OPENSSL_memcpy(&ret, &b, sizeof(ret));
ecp_nistz256_point_add(&ret, &a, &ret /* b */);
EXPECT_POINTS_EQUAL(&result, &ret);
OPENSSL_memcpy(&ret, &b, sizeof(ret));
ecp_nistz256_point_add(&ret, &ret /* b */, &a);
EXPECT_POINTS_EQUAL(&result, &ret);
P256_POINT_AFFINE a_affine, b_affine, infinity;
OPENSSL_memset(&infinity, 0, sizeof(infinity));
ASSERT_TRUE(PointToAffine(&a_affine, &a));
ASSERT_TRUE(PointToAffine(&b_affine, &b));
// ecp_nistz256_point_add_affine does not work when a == b unless doubling the
// point at infinity.
if (OPENSSL_memcmp(&a_affine, &b_affine, sizeof(a_affine)) != 0 ||
OPENSSL_memcmp(&a_affine, &infinity, sizeof(a_affine)) == 0) {
ecp_nistz256_point_add_affine(&ret, &a, &b_affine);
EXPECT_POINTS_EQUAL(&result, &ret);
OPENSSL_memcpy(&ret, &a, sizeof(ret));
ecp_nistz256_point_add_affine(&ret, &ret /* a */, &b_affine);
EXPECT_POINTS_EQUAL(&result, &ret);
ecp_nistz256_point_add_affine(&ret, &b, &a_affine);
EXPECT_POINTS_EQUAL(&result, &ret);
OPENSSL_memcpy(&ret, &b, sizeof(ret));
ecp_nistz256_point_add_affine(&ret, &ret /* b */, &a_affine);
EXPECT_POINTS_EQUAL(&result, &ret);
}
if (OPENSSL_memcmp(&a, &b, sizeof(a)) == 0) {
ecp_nistz256_point_double(&ret, &a);
EXPECT_POINTS_EQUAL(&result, &ret);
ret = a;
ecp_nistz256_point_double(&ret, &ret /* a */);
EXPECT_POINTS_EQUAL(&result, &ret);
}
}
static void TestOrdMulMont(FileTest *t) {
// This test works on scalars rather than field elements, but the
// representation is the same.
BN_ULONG a[P256_LIMBS], b[P256_LIMBS], result[P256_LIMBS];
ASSERT_TRUE(GetFieldElement(t, a, "A"));
ASSERT_TRUE(GetFieldElement(t, b, "B"));
ASSERT_TRUE(GetFieldElement(t, result, "Result"));
BN_ULONG ret[P256_LIMBS];
ecp_nistz256_ord_mul_mont(ret, a, b);
EXPECT_FIELD_ELEMENTS_EQUAL(result, ret);
ecp_nistz256_ord_mul_mont(ret, b, a);
EXPECT_FIELD_ELEMENTS_EQUAL(result, ret);
OPENSSL_memcpy(ret, a, sizeof(ret));
ecp_nistz256_ord_mul_mont(ret, ret /* a */, b);
EXPECT_FIELD_ELEMENTS_EQUAL(result, ret);
OPENSSL_memcpy(ret, a, sizeof(ret));
ecp_nistz256_ord_mul_mont(ret, b, ret);
EXPECT_FIELD_ELEMENTS_EQUAL(result, ret);
OPENSSL_memcpy(ret, b, sizeof(ret));
ecp_nistz256_ord_mul_mont(ret, a, ret /* b */);
EXPECT_FIELD_ELEMENTS_EQUAL(result, ret);
OPENSSL_memcpy(ret, b, sizeof(ret));
ecp_nistz256_ord_mul_mont(ret, ret /* b */, a);
EXPECT_FIELD_ELEMENTS_EQUAL(result, ret);
if (OPENSSL_memcmp(a, b, sizeof(a)) == 0) {
ecp_nistz256_ord_sqr_mont(ret, a, 1);
EXPECT_FIELD_ELEMENTS_EQUAL(result, ret);
OPENSSL_memcpy(ret, a, sizeof(ret));
ecp_nistz256_ord_sqr_mont(ret, ret /* a */, 1);
EXPECT_FIELD_ELEMENTS_EQUAL(result, ret);
}
}
TEST(P256_X86_64Test, TestVectors) {
return FileTestGTest("crypto/fipsmodule/ec/p256-x86_64_tests.txt",
[](FileTest *t) {
if (t->GetParameter() == "Negate") {
TestNegate(t);
} else if (t->GetParameter() == "MulMont") {
TestMulMont(t);
} else if (t->GetParameter() == "FromMont") {
TestFromMont(t);
} else if (t->GetParameter() == "PointAdd") {
TestPointAdd(t);
} else if (t->GetParameter() == "OrdMulMont") {
TestOrdMulMont(t);
} else {
FAIL() << "Unknown test type:" << t->GetParameter();
}
});
}
// Instrument the functions covered in TestVectors for ABI checking.
TEST(P256_X86_64Test, ABI) {
BN_ULONG a[P256_LIMBS], b[P256_LIMBS], c[P256_LIMBS];
OPENSSL_memset(a, 0x01, sizeof(a));
// These functions are all constant-time, so it is only necessary to
// instrument one call each for ABI checking.
CHECK_ABI(ecp_nistz256_neg, b, a);
CHECK_ABI(ecp_nistz256_mul_mont, c, a, b);
CHECK_ABI(ecp_nistz256_sqr_mont, c, a);
CHECK_ABI(ecp_nistz256_from_mont, c, a);
CHECK_ABI(ecp_nistz256_ord_mul_mont, c, a, b);
// Check a few different loop counts.
CHECK_ABI(ecp_nistz256_ord_sqr_mont, b, a, 1);
CHECK_ABI(ecp_nistz256_ord_sqr_mont, b, a, 3);
// Point addition has some special cases around infinity and doubling. Test a
// few different scenarios.
static const P256_POINT kA = {
{TOBN(0x60559ac7, 0xc8d0d89d), TOBN(0x6cda3400, 0x545f7e2c),
TOBN(0x9b5159e0, 0x323e6048), TOBN(0xcb8dea33, 0x27057fe6)},
{TOBN(0x81a2d3bc, 0xc93a2d53), TOBN(0x81f40762, 0xa4f33ccf),
TOBN(0xc3c3300a, 0xa8ad50ea), TOBN(0x553de89b, 0x31719830)},
{TOBN(0x3fd9470f, 0xb277d181), TOBN(0xc191b8d5, 0x6376f206),
TOBN(0xb2572c1f, 0x45eda26f), TOBN(0x4589e40d, 0xf2efc546)},
};
static const P256_POINT kB = {
{TOBN(0x3cf0b0aa, 0x92054341), TOBN(0xb949bb80, 0xdab57807),
TOBN(0x99de6814, 0xefd21b3e), TOBN(0x32ad5649, 0x7c6c6e83)},
{TOBN(0x06afaa02, 0x688399e0), TOBN(0x75f2d096, 0x2a3ce65c),
TOBN(0xf6a31eb7, 0xca0244b3), TOBN(0x57b33b7a, 0xcfeee75e)},
{TOBN(0x7617d2e0, 0xb4f1d35f), TOBN(0xa922cb10, 0x7f592b65),
TOBN(0x12fd6c7a, 0x51a2f474), TOBN(0x337d5e1e, 0xc2fc711b)},
};
// This file represents Jacobian infinity as (*, *, 0).
static const P256_POINT kInfinity = {
{TOBN(0, 0), TOBN(0, 0), TOBN(0, 0), TOBN(0, 0)},
{TOBN(0, 0), TOBN(0, 0), TOBN(0, 0), TOBN(0, 0)},
{TOBN(0, 0), TOBN(0, 0), TOBN(0, 0), TOBN(0, 0)},
};
P256_POINT p;
CHECK_ABI(ecp_nistz256_point_add, &p, &kA, &kB);
CHECK_ABI(ecp_nistz256_point_add, &p, &kA, &kA);
OPENSSL_memcpy(&p, &kA, sizeof(P256_POINT));
ecp_nistz256_neg(p.Y, p.Y);
CHECK_ABI(ecp_nistz256_point_add, &p, &kA, &p); // A + -A
CHECK_ABI(ecp_nistz256_point_add, &p, &kA, &kInfinity);
CHECK_ABI(ecp_nistz256_point_add, &p, &kInfinity, &kA);
CHECK_ABI(ecp_nistz256_point_add, &p, &kInfinity, &kInfinity);
CHECK_ABI(ecp_nistz256_point_double, &p, &kA);
CHECK_ABI(ecp_nistz256_point_double, &p, &kInfinity);
static const P256_POINT_AFFINE kC = {
{TOBN(0x7e3ad339, 0xfb3fa5f0), TOBN(0x559d669d, 0xe3a047b2),
TOBN(0x8883b298, 0x7042e595), TOBN(0xfabada65, 0x7e477f08)},
{TOBN(0xd9cfceb8, 0xda1c3e85), TOBN(0x80863761, 0x0ce6d6bc),
TOBN(0xa8409d84, 0x66034f02), TOBN(0x05519925, 0x31a68d55)},
};
// This file represents affine infinity as (0, 0).
static const P256_POINT_AFFINE kInfinityAffine = {
{TOBN(0, 0), TOBN(0, 0), TOBN(0, 0), TOBN(0, 0)},
{TOBN(0, 0), TOBN(0, 0), TOBN(0, 0), TOBN(0, 0)},
};
CHECK_ABI(ecp_nistz256_point_add_affine, &p, &kA, &kC);
CHECK_ABI(ecp_nistz256_point_add_affine, &p, &kA, &kInfinityAffine);
CHECK_ABI(ecp_nistz256_point_add_affine, &p, &kInfinity, &kInfinityAffine);
CHECK_ABI(ecp_nistz256_point_add_affine, &p, &kInfinity, &kC);
}
#endif
|
/*
* PDFedit - free program for PDF document manipulation.
* Copyright (C) 2006-2009 PDFedit team: Michal Hocko,
* Jozef Misutka,
* Martin Petricek
* Former team members: Miroslav Jahoda
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 2 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program (in doc/LICENSE.GPL); if not, write to the
* Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
* Project is hosted on http://sourceforge.net/projects/pdfedit
*/
/** @file
QObject wrapper around CPdf (PDF document)<br>
Export some functions to scripting.<br>
See doc/user/scripting.xml or kernel documentation for more informations about these functions
@author Martin Petricek
*/
#include <qstring.h>
#include "qspdf.h"
#include "pdfutil.h"
#include <stdio.h>
#include "qspage.h"
#include "qsdict.h"
#include <kernel/cobject.h>
#include <kernel/cpdf.h>
#include "util.h"
namespace gui {
/**
Construct wrapper with given PDF document
@param _pdf Pdf document
@param _base Scripting base
@param _destructive If true, document will be closed (without saving) when this object is deleted
*/
QSPdf::QSPdf(boost::shared_ptr<CPdf>_pdf,BaseCore *_base,bool _destructive/*=false*/) : QSCObject ("Pdf",_base) {
destructive=_destructive;
obj=_pdf;
}
/** destructor */
QSPdf::~QSPdf() {
//Unload the pdf if this is 'destructive' PDF
unloadPdf();
}
/**
Close the document, if it was opened with 'destructive' flag set (via loadPdf).
Otherwise it does nothing.
The document must not be used in any way after it is closed
*/
void QSPdf::unloadPdf() {
if (obj && destructive) {
obj.reset();
}
}
/**
Sets PDF password to use for decryption. Needed for opening password-protected documents
@param pass password to set
@return true if the password was successfully set, false in case of error (bad password ...)
*/
bool QSPdf::setPassword(const QString &pass) {
return util::setPdfPassword(obj,pass);
}
/**
Return true if document is protected and opening the document reqires credentials
(usually a password), false otherwise.
*/
bool QSPdf::needsCredentials() {
return obj->needsCredentials();
}
/**
Check validity of specified reference
@param valueNum Object number
@param valueGen Generation number
@return True if valid and is contained in this document
*/
bool QSPdf::referenceValid(int valueNum,int valueGen) {
if (nullPtr(obj,"referenceValid")) return false;
IndiRef ref;
ref.num=valueNum;
ref.gen=valueGen;
//Check reference validity
return util::isRefValid(obj,ref);
}
/**
Save copy under different name. Does not check if the file exists, overwrite anything without warning
@param name Name of file
@return true if saved successfully, false if any error occured
*/
bool QSPdf::saveAs(QString name) {
if (nullPtr(obj,"saveAs")) return false;
if (name.isNull()) return false;//No empty names!
QString errorStr;
bool resultOk=util::saveCopy(obj,name,&errorStr);
if (!resultOk) base->errorException("Pdf","saveAs",tr("Unable to save:\n%1").arg(errorStr));
return resultOk;
}
/**
Save document to disk under original name
@param newRevision If true, create new revision while saving
@return true if saved succesfully, false if failed to save because of any reason
*/
bool QSPdf::save(bool newRevision/*=false*/) {
try {
//Exception can occur while saving, for example if document is read-only
obj->save(newRevision);
return true;
} catch (ReadOnlyDocumentException &e) {
base->errorException("Pdf","save",tr("Document is in read-only mode"));
return false;
} catch (...) {
base->errorException("Pdf","save",tr("Unknown error occured while saving document"));
return false;
}
}
/**
\see CPdf::getDictionary
@return document catalog
*/
QSDict* QSPdf::getDictionary() {
if (nullPtr(obj,"getDictionary")) return NULL;
return new QSDict(obj->getDictionary(),base);
}
/**
\see CPdf::isLinearized()
@return True if document is linearized
*/
bool QSPdf::isLinearized() {
if (nullPtr(obj,"isLinearized")) return false;
return obj->isLinearized();
}
/**
Check for PDF validity - return true, if this object is valid PDF wrapper,
false if the pdf was closed or not yet opened
@return True if document is valid
*/
bool QSPdf::isValid() {
if (obj==NULL) return false;
return true;
}
/**
Insert page in document at specified position
\see CPdf::insertPage
@param page page to insert
@param position Position in which to insert
*/
QSPage* QSPdf::insertPage(QSPage* page, int position) {
if (nullPtr(obj,"insertPage")) return NULL;
try {
return new QSPage(obj->insertPage(page->get(),position),base);
} catch (ReadOnlyDocumentException &e) {
base->errorException("Pdf","insertPage",QObject::tr("Document is read-only"));
return NULL;
}
}
/**
QSA bugfix version
\copydoc insertPage(QSPage*,int)
*/
QSPage* QSPdf::insertPage(QObject* page, int position) {
QSPage *qpage=qobject_cast<QSPage*>(page,"insertPage",1,"Page");
if (!qpage) return NULL;//Something invalid passed
try {
return insertPage(qpage,position);
} catch (ReadOnlyDocumentException &e) {
base->errorException("Pdf","insertPage",QObject::tr("Document is read-only"));
return NULL;
}
}
/**
Remove page at given position
(numbering starts from 1)
\see CPdf::removePage()
@param position Page number to remove
*/
void QSPdf::removePage(int position) {
if (nullPtr(obj,"removePage")) return;
try {
obj->removePage(position);
} catch (ReadOnlyDocumentException &e) {
base->errorException("Pdf","removePage",QObject::tr("Document is read-only"));
} catch (PageNotFoundException &e) {
base->errorException("Pdf","removePage",tr("Page not found"));
}
}
/**
Return position of given page
\see CPdf::getPagePosition
@param page page to examine
@return page position or -1 in case of error (page not in document, invalid page, etc...)
*/
int QSPdf::getPagePosition(QSPage *page) {
if (nullPtr(obj,"getPagePosition")) return -1;
if (nullPtr(page,"getPagePosition")) return -1;
try {
return obj->getPagePosition(page->get());
} catch (...) {
//Probably "page not found"
return -1;
}
}
/**
\copydoc getPagePosition(QSPage *)
QSA bugfix version
*/
int QSPdf::getPagePosition(QObject *page) {
QSPage *qpage=qobject_cast<QSPage*>(page,"getPagePosition",1,"Page");
if (!qpage) return -1;//Something invalid passed
return getPagePosition(qpage);
}
/**
Return number of pages in document
\see CPdf::getPageCount
@return count of pages
*/
int QSPdf::getPageCount() {
if (nullPtr(obj,"getPageCount")) return -1;
return obj->getPageCount();
}
/**
Return page at given position
(numbering starts from 1)
\see CPdf::getPage()
@param position Page number
@return page at positoin
*/
QSPage* QSPdf::getPage(int position) {
if (nullPtr(obj,"getPage")) return NULL;
try {
return new QSPage(obj->getPage(position),base);
} catch (PageNotFoundException &e) {
base->errorException("Pdf","getPage",tr("Page not found"));
return NULL;
}
}
/**
Get first page
\see CPdf::getFirstPage
@return first page in document
*/
QSPage* QSPdf::getFirstPage() {
if (nullPtr(obj,"getFirstPage")) return NULL;
try {
return new QSPage(obj->getFirstPage(),base);
} catch (PageNotFoundException &e) {
base->errorException("Pdf","getFirstPage",tr("Page not found"));
return NULL;
}
}
/**
Return page next to the one specified
\see CPdf::getNextPage
@param page Page to examine
@return next page
*/
QSPage* QSPdf::getNextPage(QSPage* page) {
if (nullPtr(obj,"getNextPage")) return NULL;
try {
return new QSPage(obj->getNextPage(page->get()),base);
} catch (PageNotFoundException &e) {
base->errorException("Pdf","getNextPage",tr("Page not found"));
return NULL;
}
}
/**
Return page previous to the one specified
\see CPdf::getPrevPage
@param page Page to examine
@return previous page
*/
QSPage* QSPdf::getPrevPage(QSPage* page) {
if (nullPtr(obj,"getPrevPage")) return NULL;
try {
return new QSPage(obj->getPrevPage(page->get()),base);
} catch (PageNotFoundException &e) {
base->errorException("Pdf","getPrevPage",tr("Page not found"));
return NULL;
}
}
/**
Return true if next page in relation to given page exists
\see CPdf::hasNextPage
@param page Page to examine
@return presence of next page
*/
bool QSPdf::hasNextPage(QSPage* page) {
if (nullPtr(obj,"hasNextPage")) return false;
return obj->hasNextPage(page->get());
}
/**
Return true if previous page in relation to given page exists
\see CPdf::hasPrevPage
@param page Page to examine
@return presence of previous page
*/
bool QSPdf::hasPrevPage(QSPage* page) {
if (nullPtr(obj,"hasPrevPage")) return false;
return obj->hasPrevPage(page->get());
}
/**
\copydoc getNextPage(QSPage*)
qsa bugfix version
*/
QSPage* QSPdf::getNextPage(QObject* page) {
QSPage *qpage=qobject_cast<QSPage*>(page,"getNextPage",1,"Page");
if (!qpage) return NULL;
return getNextPage(qpage);
}
/**
\copydoc getPrevPage(QSPage*)
qsa bugfix version
*/
QSPage* QSPdf::getPrevPage(QObject* page) {
QSPage *qpage=qobject_cast<QSPage*>(page,"getNextPage",1,"Page");
if (!qpage) return NULL;
return getPrevPage(qpage);
}
/**
\copydoc hasNextPage(QSPage*)
qsa bugfix version
*/
bool QSPdf::hasNextPage(QObject* page) {
QSPage *qpage=qobject_cast<QSPage*>(page,"hasNextPage",1,"Page");
if (!qpage) return false;
return hasNextPage(qpage);
}
/**
\copydoc hasPrevPage(QSPage*)
qsa bugfix version
*/
bool QSPdf::hasPrevPage(QObject* page) {
QSPage *qpage=qobject_cast<QSPage*>(page,"hasPrevPage",1,"Page");
if (!qpage) return false;
return hasPrevPage(qpage);
}
/**
Get count of revisions
\see CPdf::getRevisionsCount
@return count of revisions
*/
int QSPdf::getRevisionsCount() {
if (nullPtr(obj,"getRevisionsCount")) return 0;
return obj->getRevisionsCount();
}
/**
Get actual revision number
\see CPdf::getActualRevision
@return actual revison
*/
int QSPdf::getActualRevision() {
if (nullPtr(obj,"getActualRevision")) return 0;
return obj->getActualRevision();
}
/**
Get last page in document
\see CPdf::getLastPage
@return last page
*/
QSPage* QSPdf::getLastPage() {
if (nullPtr(obj,"getLastPage")) return 0;
try {
return new QSPage(obj->getLastPage(),base);
} catch (PageNotFoundException &e) {
base->errorException("Pdf","getLastPage",tr("Page not found"));
return NULL;
}
}
/**
Get CPdf held inside this class. Not exposed to scripting
@return CPdf object
*/
boost::shared_ptr<CPdf> QSPdf::get() const {
return obj;
}
/**
Set CPdf held inside this class. Not exposed to scripting
@param pdf CPdf object
*/
void QSPdf::set(boost::shared_ptr<CPdf> pdf) {
obj=pdf;
}
/**
Checks whether document is encrypted.
@return true if encrypted, false otherwise.
*/
bool QSPdf::isEncrypted() {
if (nullPtr(obj,"isEncrypted")) return 0;
return pdfobjects::utils::isEncrypted(obj);
}
/**
Checks whether document is opened in read-only mode
@return true if read-only, false if read-write.
*/
bool QSPdf::isReadOnly() {
if (nullPtr(obj,"isReadOnly")) return 0;
return obj->getMode()==CPdf::ReadOnly;
}
} // namespace gui
|
/*
* Copyright Andrey Semashev 2007 - 2013.
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt)
*/
/*!
* \file timestamp.cpp
* \author Andrey Semashev
* \date 31.07.2011
*
* \brief This header is the Boost.Log library implementation, see the library documentation
* at http://www.boost.org/doc/libs/release/libs/log/doc/html/index.html.
*/
#include <boost/log/detail/timestamp.hpp>
#if defined(BOOST_WINDOWS) && !defined(__CYGWIN__)
#include <boost/detail/interlocked.hpp>
#include "windows_version.hpp"
#include <windows.h>
#else
#include <unistd.h> // for config macros
#if defined(macintosh) || defined(__APPLE__) || defined(__APPLE_CC__)
#include <mach/mach_time.h>
#include <mach/kern_return.h>
#include <boost/log/utility/once_block.hpp>
#endif
#include <time.h>
#include <errno.h>
#include <boost/throw_exception.hpp>
#include <boost/system/error_code.hpp>
#include <boost/system/system_error.hpp>
#endif
#include <boost/log/detail/header.hpp>
namespace boost {
BOOST_LOG_OPEN_NAMESPACE
namespace aux {
#if defined(BOOST_WINDOWS) && !defined(__CYGWIN__)
#if _WIN32_WINNT >= 0x0600
// Directly use API from Vista and later
BOOST_LOG_API get_tick_count_t get_tick_count = &GetTickCount64;
#else // _WIN32_WINNT >= 0x0600
BOOST_LOG_ANONYMOUS_NAMESPACE {
#if defined(_MSC_VER) && !defined(_M_CEE_PURE)
# if defined(_M_IX86)
# if defined(_M_IX86_FP) && _M_IX86_FP >= 2
//! Atomically loads and stores the 64-bit value through SSE2 instructions
BOOST_FORCEINLINE void move64(const uint64_t* from, uint64_t* to)
{
__asm
{
mov eax, from
mov edx, to
movq xmm4, qword ptr [eax]
movq qword ptr [edx], xmm4
};
}
# else // defined(_M_IX86_FP) && _M_IX86_FP >= 2
//! Atomically loads and stores the 64-bit value through FPU instructions
BOOST_FORCEINLINE void move64(const uint64_t* from, uint64_t* to)
{
__asm
{
mov eax, from
mov edx, to
fild qword ptr [eax]
fistp qword ptr [edx]
};
}
# endif // defined(_M_IX86_FP) && _M_IX86_FP >= 2
# elif defined(_M_AMD64) || defined(_M_IA64)
//! Atomically loads and stores the 64-bit value
BOOST_FORCEINLINE void move64(const uint64_t* from, uint64_t* to)
{
*to = *from;
}
# else
# define BOOST_LOG_GENERIC_MOVE64 1
# endif
#elif defined(__GNUC__)
# if defined(__i386__)
# if defined(__SSE2__)
//! Atomically loads and stores the 64-bit value through SSE2 instructions
BOOST_FORCEINLINE void move64(const uint64_t* from, uint64_t* to)
{
__asm__ __volatile__
(
"movq %1, %%xmm4\n\t"
"movq %%xmm4, %0\n\t"
: "=m" (*to)
: "m" (*from)
: "memory", "xmm4"
);
}
# else // defined(__SSE2__)
//! Atomically loads and stores the 64-bit value through FPU instructions
BOOST_FORCEINLINE void move64(const uint64_t* from, uint64_t* to)
{
__asm__ __volatile__
(
"fildq %1\n\t"
"fistpq %0"
: "=m" (*to)
: "m" (*from)
: "memory"
);
}
# endif // defined(__SSE2__)
# elif defined(__x86_64__)
//! Atomically loads and stores the 64-bit value
BOOST_FORCEINLINE void move64(const uint64_t* from, uint64_t* to)
{
*to = *from;
}
# else
# define BOOST_LOG_GENERIC_MOVE64 1
# endif
#else
# define BOOST_LOG_GENERIC_MOVE64 1
#endif
#if defined(BOOST_LOG_GENERIC_MOVE64)
BOOST_ALIGNMENT(16) long g_spin_lock = 0;
//! Atomically loads and stores the 64-bit value
BOOST_FORCEINLINE void move64(const uint64_t* from, uint64_t* to)
{
while (BOOST_INTERLOCKED_COMPARE_EXCHANGE(&g_spin_lock, 1, 0) != 0);
*to = *from;
BOOST_INTERLOCKED_EXCHANGE(&g_spin_lock, 0);
}
#endif // defined(BOOST_LOG_GENERIC_MOVE64)
BOOST_ALIGNMENT(16) uint64_t g_ticks = 0;
union ticks_caster
{
uint64_t as_uint64;
struct
{
uint32_t ticks;
uint32_t counter;
}
as_components;
};
//! Artifical implementation of GetTickCount64
uint64_t __stdcall get_tick_count64()
{
ticks_caster state;
move64(&g_ticks, &state.as_uint64);
uint32_t new_ticks = GetTickCount();
state.as_components.counter += new_ticks < state.as_components.ticks;
state.as_components.ticks = new_ticks;
move64(&state.as_uint64, &g_ticks);
return state.as_uint64;
}
uint64_t __stdcall get_tick_count_init()
{
HMODULE hKernel32 = GetModuleHandleA("kernel32.dll");
if (hKernel32)
{
get_tick_count_t p = (get_tick_count_t)GetProcAddress(hKernel32, "GetTickCount64");
if (p)
{
// Use native API
get_tick_count = p;
return p();
}
}
// No native API available
get_tick_count = &get_tick_count64;
return get_tick_count64();
}
} // namespace
BOOST_LOG_API get_tick_count_t get_tick_count = &get_tick_count_init;
#endif // _WIN32_WINNT >= 0x0600
#elif defined(_POSIX_TIMERS) && _POSIX_TIMERS > 0
BOOST_LOG_API int64_t duration::milliseconds() const
{
// Timestamps are always in nanoseconds
return m_ticks / 1000000LL;
}
BOOST_LOG_ANONYMOUS_NAMESPACE {
/*!
* \c get_timestamp implementation based on POSIX realtime clock.
* Note that this implementation is only used as a last resort since
* this timer can be manually set and may jump due to DST change.
*/
timestamp get_timestamp_realtime_clock()
{
timespec ts;
if (clock_gettime(CLOCK_REALTIME, &ts) != 0)
{
const int err = errno;
BOOST_THROW_EXCEPTION(boost::system::system_error(
err, boost::system::system_category(), "Failed to acquire current time"));
}
return timestamp(static_cast< uint64_t >(ts.tv_sec) * 1000000000ULL + ts.tv_nsec);
}
# if defined(_POSIX_MONOTONIC_CLOCK)
//! \c get_timestamp implementation based on POSIX monotonic clock
timestamp get_timestamp_monotonic_clock()
{
timespec ts;
if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0)
{
const int err = errno;
if (err == EINVAL)
{
// The current platform does not support monotonic timer.
// Fall back to realtime clock, which is not exactly what we need
// but is better than nothing.
get_timestamp = &get_timestamp_realtime_clock;
return get_timestamp_realtime_clock();
}
BOOST_THROW_EXCEPTION(boost::system::system_error(
err, boost::system::system_category(), "Failed to acquire current time"));
}
return timestamp(static_cast< uint64_t >(ts.tv_sec) * 1000000000ULL + ts.tv_nsec);
}
# define BOOST_LOG_DEFAULT_GET_TIMESTAMP get_timestamp_monotonic_clock
# else // if defined(_POSIX_MONOTONIC_CLOCK)
# define BOOST_LOG_DEFAULT_GET_TIMESTAMP get_timestamp_realtime_clock
# endif // if defined(_POSIX_MONOTONIC_CLOCK)
} // namespace
// Use POSIX API
BOOST_LOG_API get_timestamp_t get_timestamp = &BOOST_LOG_DEFAULT_GET_TIMESTAMP;
# undef BOOST_LOG_DEFAULT_GET_TIMESTAMP
#elif defined(macintosh) || defined(__APPLE__) || defined(__APPLE_CC__)
BOOST_LOG_API int64_t duration::milliseconds() const
{
static mach_timebase_info_data_t timebase_info = {};
BOOST_LOG_ONCE_BLOCK()
{
kern_return_t err = mach_timebase_info(&timebase_info);
if (err != KERN_SUCCESS)
{
BOOST_THROW_EXCEPTION(boost::system::system_error(
err, boost::system::system_category(), "Failed to initialize timebase info"));
}
}
// Often the timebase rational equals 1, we can optimize for this case
if (timebase_info.numer == timebase_info.denom)
{
// Timestamps are in nanoseconds
return m_ticks / 1000000LL;
}
else
{
return (m_ticks * timebase_info.numer) / (1000000LL * timebase_info.denom);
}
}
BOOST_LOG_ANONYMOUS_NAMESPACE {
//! \c get_timestamp implementation based on MacOS X absolute time
timestamp get_timestamp_mach()
{
return timestamp(mach_absolute_time());
}
} // namespace
// Use MacOS X API
BOOST_LOG_API get_timestamp_t get_timestamp = &get_timestamp_mach;
#else
# error Boost.Log: Timestamp generation is not supported for your platform
#endif
} // namespace aux
BOOST_LOG_CLOSE_NAMESPACE // namespace log
} // namespace boost
#include <boost/log/detail/footer.hpp>
|
/*
* yosys -- Yosys Open SYnthesis Suite
*
* Copyright (C) 2012 Clifford Wolf <clifford@clifford.at>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
#include "kernel/yosys.h"
#include "kernel/sigtools.h"
USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN
Const make_value(string &value)
{
if (GetSize(value) >= 2 && value.front() == '"' && value.back() == '"')
return Const(value.substr(1, GetSize(value)-2));
SigSpec sig;
SigSpec::parse(sig, nullptr, value);
return sig.as_const();
}
bool match_name(string &name, IdString &id, bool ignore_case=false)
{
string str1 = RTLIL::escape_id(name);
string str2 = id.str();
if (ignore_case)
return !strcasecmp(str1.c_str(), str2.c_str());
return str1 == str2;
}
bool match_value(string &value, Const &val, bool ignore_case=false)
{
if (ignore_case && ((val.flags & RTLIL::CONST_FLAG_STRING) != 0) && GetSize(value) && value.front() == '"' && value.back() == '"') {
string str1 = value.substr(1, GetSize(value)-2);
string str2 = val.decode_string();
return !strcasecmp(str1.c_str(), str2.c_str());
}
return make_value(value) == val;
}
struct AttrmapAction {
virtual ~AttrmapAction() { }
virtual bool apply(IdString &id, Const &val) = 0;
};
struct AttrmapTocase : AttrmapAction {
string name;
virtual bool apply(IdString &id, Const&) {
if (match_name(name, id, true))
id = RTLIL::escape_id(name);
return true;
}
};
struct AttrmapRename : AttrmapAction {
string old_name, new_name;
virtual bool apply(IdString &id, Const&) {
if (match_name(old_name, id))
id = RTLIL::escape_id(new_name);
return true;
}
};
struct AttrmapMap : AttrmapAction {
bool imap;
string old_name, new_name;
string old_value, new_value;
virtual bool apply(IdString &id, Const &val) {
if (match_name(old_name, id) && match_value(old_value, val, true)) {
id = RTLIL::escape_id(new_name);
val = make_value(new_value);
}
return true;
}
};
struct AttrmapRemove : AttrmapAction {
string name, value;
virtual bool apply(IdString &id, Const &val) {
return !(match_name(name, id) && match_value(value, val));
}
};
void attrmap_apply(string objname, vector<std::unique_ptr<AttrmapAction>> &actions, dict<RTLIL::IdString, RTLIL::Const> &attributes)
{
dict<RTLIL::IdString, RTLIL::Const> new_attributes;
for (auto attr : attributes)
{
auto new_attr = attr;
for (auto &action : actions)
if (!action->apply(new_attr.first, new_attr.second))
goto delete_this_attr;
if (new_attr != attr)
log("Changed attribute on %s: %s=%s -> %s=%s\n", objname.c_str(),
log_id(attr.first), log_const(attr.second), log_id(new_attr.first), log_const(new_attr.second));
new_attributes[new_attr.first] = new_attr.second;
if (0)
delete_this_attr:
log("Removed attribute on %s: %s=%s\n", objname.c_str(), log_id(attr.first), log_const(attr.second));
}
attributes.swap(new_attributes);
}
struct AttrmapPass : public Pass {
AttrmapPass() : Pass("attrmap", "renaming attributes") { }
virtual void help()
{
// |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
log("\n");
log(" attrmap [options] [selection]\n");
log("\n");
log("This command renames attributes and/or mapps key/value pairs to\n");
log("other key/value pairs.\n");
log("\n");
log(" -tocase <name>\n");
log(" Match attribute names case-insensitively and set it to the specified\n");
log(" name.\n");
log("\n");
log(" -rename <old_name> <new_name>\n");
log(" Rename attributes as specified\n");
log("\n");
log(" -map <old_name>=<old_value> <new_name>=<new_value>\n");
log(" Map key/value pairs as indicated.\n");
log("\n");
log(" -imap <old_name>=<old_value> <new_name>=<new_value>\n");
log(" Like -map, but use case-insensitive match for <old_value> when\n");
log(" it is a string value.\n");
log("\n");
log(" -remove <name>=<value>\n");
log(" Remove attributes matching this pattern.\n");
log("\n");
log(" -modattr\n");
log(" Operate on module attributes instead of attributes on wires and cells.\n");
log("\n");
log("For example, mapping Xilinx-style \"keep\" attributes to Yosys-style:\n");
log("\n");
log(" attrmap -tocase keep -imap keep=\"true\" keep=1 \\\n");
log(" -imap keep=\"false\" keep=0 -remove keep=0\n");
log("\n");
}
virtual void execute(std::vector<std::string> args, RTLIL::Design *design)
{
log_header(design, "Executing ATTRMAP pass (move or copy attributes).\n");
bool modattr_mode = false;
vector<std::unique_ptr<AttrmapAction>> actions;
size_t argidx;
for (argidx = 1; argidx < args.size(); argidx++)
{
std::string arg = args[argidx];
if (arg == "-tocase" && argidx+1 < args.size()) {
auto action = new AttrmapTocase;
action->name = args[++argidx];
actions.push_back(std::unique_ptr<AttrmapAction>(action));
continue;
}
if (arg == "-rename" && argidx+2 < args.size()) {
auto action = new AttrmapRename;
action->old_name = args[++argidx];
action->new_name = args[++argidx];
actions.push_back(std::unique_ptr<AttrmapAction>(action));
continue;
}
if ((arg == "-map" || arg == "-imap") && argidx+2 < args.size()) {
string arg1 = args[++argidx];
string arg2 = args[++argidx];
string val1, val2;
size_t p = arg1.find("=");
if (p != string::npos) {
val1 = arg1.substr(p+1);
arg1 = arg1.substr(0, p);
}
p = arg2.find("=");
if (p != string::npos) {
val2 = arg2.substr(p+1);
arg2 = arg2.substr(0, p);
}
auto action = new AttrmapMap;
action->imap = (arg == "-map");
action->old_name = arg1;
action->new_name = arg2;
action->old_value = val1;
action->new_value = val2;
actions.push_back(std::unique_ptr<AttrmapAction>(action));
continue;
}
if (arg == "-remove" && argidx+1 < args.size()) {
string arg1 = args[++argidx], val1;
size_t p = arg1.find("=");
if (p != string::npos) {
val1 = arg1.substr(p+1);
arg1 = arg1.substr(0, p);
}
auto action = new AttrmapRemove;
action->name = arg1;
action->value = val1;
actions.push_back(std::unique_ptr<AttrmapAction>(action));
continue;
}
if (arg == "-modattr") {
modattr_mode = true;
continue;
}
break;
}
extra_args(args, argidx, design);
if (modattr_mode)
{
for (auto module : design->selected_whole_modules())
attrmap_apply(stringf("%s", log_id(module)), actions, module->attributes);
}
else
{
for (auto module : design->selected_modules())
{
for (auto wire : module->selected_wires())
attrmap_apply(stringf("%s.%s", log_id(module), log_id(wire)), actions, wire->attributes);
for (auto cell : module->selected_cells())
attrmap_apply(stringf("%s.%s", log_id(module), log_id(cell)), actions, cell->attributes);
}
}
}
} AttrmapPass;
PRIVATE_NAMESPACE_END
|
/*
* Copyright (c) 2015 Kaprica Security, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
#include <cstdio.h>
#include <cstring.h>
#include "audiotrack.h"
#include "comp32.h"
#include "compfour.h"
#include "compeight.h"
#include "fxgain.h"
#include "fxpan.h"
#include "fxreverb.h"
#include "interface.h"
static const char menuMainPrompt[] = \
"1) New track...\n" \
"2) Import track\n" \
"3) Export...\n" \
"4) List tracks\n" \
"5) Change gain [track] [hundredths]\n" \
"6) Change pan [track] [hundredths]\n" \
"7) Combine/split [track] [?track]\n" \
"8) Effects...\n" \
"9) Quit\n";
static const char menuEffectsPrompt[] = \
"1) Apply gain [track] [hundredths]\n" \
"2) Apply pan [track] [hundredths]\n" \
"3) Echo [track] [delay in samples]\n" \
"4) Add silence [track] [number of samples]\n" \
"5) Cancel\n";
static const char menuExportPrompt[] = \
"1) Uncompressed 32-bit signed\n" \
"2) Compressed 4-bit\n" \
"3) Compressed 8-bit\n" \
"4) Cancel\n";
static const char menuNewPrompt[] = \
"1) Silence [number of samples]\n" \
"2) Sine Wave [number of samples] [HZ]\n" \
"3) Square Wave [number of samples] [HZ]\n" \
"4) White Noise [number of samples]\n" \
"5) Cancel\n";
Interface::Interface()
{
}
Interface::~Interface()
{
}
void Interface::run()
{
menuMain();
}
bool Interface::menuMain()
{
AudioTrack *track, *other;
int value;
char line[100], *word, *buf;
while (true)
{
fwrite(menuMainPrompt, strlen(menuMainPrompt), stdout);
if (freaduntil(line, sizeof(line), '\n', stdin) < 0)
return false;
if (line[0] == '9')
break;
buf = line;
word = strsep(&buf, " ");
switch(line[0])
{
case '1':
if (!menuNew())
return false;
break;
case '2':
if (!importAudio())
return false;
break;
case '3':
if (!menuExport())
return false;
break;
case '4':
listTracks();
break;
case '5':
word = strsep(&buf, " ");
if (word == NULL)
{
fprintf(stdout, "Missing track\n");
continue;
}
value = strtol(word, NULL, 10);
track = mixer.getTrack(value);
if (track == NULL)
{
fprintf(stdout, "Invalid track\n");
continue;
}
word = strsep(&buf, " ");
if (word == NULL)
{
fprintf(stdout, "Missing gain\n");
continue;
}
value = strtol(word, NULL, 10);
if (value < -1000 || value > 1000)
{
fprintf(stdout, "Invalid gain (-10.00...10.00)\n");
continue;
}
track->setGain(Gain::fromRational(value, 100));
break;
case '6':
word = strsep(&buf, " ");
if (word == NULL)
{
fprintf(stdout, "Missing track\n");
continue;
}
value = strtol(word, NULL, 10);
track = mixer.getTrack(value);
if (track == NULL)
{
fprintf(stdout, "Invalid track\n");
continue;
}
word = strsep(&buf, " ");
if (word == NULL)
{
fprintf(stdout, "Missing pan\n");
continue;
}
value = strtol(word, NULL, 10);
if (value < -100 || value > 100)
{
fprintf(stdout, "Invalid pan (-1.00...1.00)\n");
continue;
}
if (value == 100)
track->setPan(INT32_MAX);
else
track->setPan((double)value / 100 * INT32_MAX);
break;
case '7':
word = strsep(&buf, " ");
if (word == NULL)
{
fprintf(stdout, "Missing track 1\n");
continue;
}
value = strtol(word, NULL, 10);
track = mixer.getTrack(value);
if (track == NULL)
{
fprintf(stdout, "Invalid track 1\n");
continue;
}
word = strsep(&buf, " ");
if (word != NULL)
{
value = strtol(word, NULL, 10);
other = mixer.getTrack(value);
if (other == NULL)
{
fprintf(stdout, "Invalid track 2\n");
continue;
}
}
else
{
other = NULL;
}
if (other == NULL)
{
if (!track->getStereo())
{
fprintf(stdout, "Cannot split a mono track\n");
continue;
}
mixer.splitTrack(track->id);
}
else
{
if (track->getStereo() || other->getStereo())
{
fprintf(stdout, "Cannot combine a stereo track\n");
continue;
}
mixer.combineTracks(track->id, other->id);
}
break;
case '8':
menuEffects();
break;
default:
fprintf(stdout, "Invalid choice\n");
break;
}
}
fprintf(stdout, "Thank you for trying out Grit! Please leave us a nice review on the app store.\n");
return true;
}
bool Interface::menuExport()
{
char line[100];
while (true)
{
fwrite(menuExportPrompt, strlen(menuExportPrompt), stdout);
if (freaduntil(line, sizeof(line), '\n', stdin) < 0)
return false;
if (line[0] == '4')
break;
switch(line[0])
{
case '1':
exportAudio(Compression32());
break;
case '2':
exportAudio(CompressionFour());
break;
case '3':
exportAudio(CompressionEight());
break;
default:
fprintf(stdout, "Invalid choice\n");
continue;
}
break;
}
return true;
}
bool Interface::menuNew()
{
char line[100], *buf, *word;
unsigned int samples, hz;
AudioTrack *track;
while (true)
{
fwrite(menuNewPrompt, strlen(menuNewPrompt), stdout);
if (freaduntil(line, sizeof(line), '\n', stdin) < 0)
return false;
if (line[0] == '5')
break;
buf = line;
word = strsep(&buf, " "); // ignore command
word = strsep(&buf, " ");
if (word == NULL)
{
fprintf(stdout, "Missing samples\n");
continue;
}
samples = strtoul(word, NULL, 10);
if (samples > INT32_MAX)
{
fprintf(stdout, "Invalid samples\n");
continue;
}
switch(line[0])
{
case '1':
track = new AudioTrack(AudioStream::fromSilence(samples));
mixer.addTrack(track);
break;
case '2':
case '3':
word = strsep(&buf, " ");
if (word == NULL)
{
fprintf(stdout, "Missing frequency\n");
continue;
}
hz = strtoul(word, NULL, 10);
if (hz >= 50000)
{
fprintf(stdout, "Invalid frequency\n");
continue;
}
if (line[0] == '2')
track = new AudioTrack(AudioStream::fromSineWave(samples, hz));
else
track = new AudioTrack(AudioStream::fromSquareWave(samples, hz));
mixer.addTrack(track);
break;
case '4':
track = new AudioTrack(mixer.generateWhiteNoise(samples));
mixer.addTrack(track);
break;
default:
fprintf(stdout, "Invalid choice\n");
continue;
}
break;
}
return true;
}
void Interface::listTracks()
{
for (auto LinkedList<AudioTrack *>::Iterator it = mixer.getTracks(); !it.empty(); it.next())
{
AudioTrack *track = it.value();
fprintf(stdout, "%d) %s samples=%d\n", track->id, track->getStereo() ? "stereo" : "mono", track->getLength());
}
}
void Interface::exportAudio(const Compression &comp)
{
AudioTrack *track = mixer.exportMix();
unsigned int size = sizeof(AudioHeader) + comp.getMaxBufferSize(*track);
uint8_t *data = new uint8_t[size];
AudioHeader *hdr = (AudioHeader *)data;
hdr->magic = 0x2e617564;
hdr->offset = sizeof(AudioHeader);
hdr->samples = track->getLength();
hdr->encoding = comp.getId();
hdr->sample_rate = SAMPLE_RATE;
hdr->channels = track->getStereo() ? 2 : 1;
comp.compress(*track, &data[sizeof(AudioHeader)]);
fwrite(&size, sizeof(size), stdout);
fwrite(data, size, stdout);
delete data;
delete track;
}
bool Interface::importAudio()
{
unsigned int size;
if (fread(&size, sizeof(size), stdin) != sizeof(size))
return false;
if (size >= INT32_MAX || size <= sizeof(AudioHeader))
return false;
uint8_t *data = new uint8_t[size];
if (fread(data, size, stdin) != size)
return false;
AudioHeader *hdr = (AudioHeader *)data;
if (hdr->magic == 0x2e617564 && hdr->offset == sizeof(AudioHeader) && hdr->samples < INT32_MAX && hdr->sample_rate == SAMPLE_RATE)
{
Compression *comp = Compression::fromId(hdr->encoding);
if (comp != NULL)
{
AudioTrack *track;
if (hdr->channels == 1)
track = new AudioTrack(AudioStream::fromSilence(hdr->samples));
else
track = new AudioTrack(AudioStream::fromSilence(hdr->samples), AudioStream::fromSilence(hdr->samples));
#ifdef PATCHED_1
if (size - hdr->offset >= comp->getMaxBufferSize(*track))
#endif
comp->decompress(*track, &data[sizeof(AudioHeader)]);
mixer.addTrack(track);
delete comp;
}
}
delete data;
return true;
}
bool Interface::menuEffects()
{
char line[100], *buf, *word;
int value;
AudioTrack *track;
while (true)
{
fwrite(menuEffectsPrompt, strlen(menuEffectsPrompt), stdout);
if (freaduntil(line, sizeof(line), '\n', stdin) < 0)
return false;
if (line[0] == '5')
break;
buf = line;
word = strsep(&buf, " "); // ignore command
word = strsep(&buf, " ");
if (word == NULL)
{
fprintf(stdout, "Missing track\n");
continue;
}
value = strtol(word, NULL, 10);
track = mixer.getTrack(value);
if (track == NULL)
{
fprintf(stdout, "Invalid track\n");
continue;
}
switch(line[0])
{
case '1':
word = strsep(&buf, " ");
if (word == NULL)
{
fprintf(stdout, "Missing gain\n");
continue;
}
value = strtol(word, NULL, 10);
if (value < -1000 || value > 1000)
{
fprintf(stdout, "Invalid gain (-10.00...10.00)\n");
continue;
}
FxGain(Gain::fromRational(value, 100)).apply(*track);
break;
case '2':
word = strsep(&buf, " ");
if (word == NULL)
{
fprintf(stdout, "Missing pan\n");
continue;
}
value = strtol(word, NULL, 10);
if (value < -100 || value > 100)
{
fprintf(stdout, "Invalid pan (-1.00...1.00)\n");
continue;
}
if (value == 100)
FxPan(INT32_MAX).apply(*track);
else
FxPan((double)value / 100 * INT32_MAX).apply(*track);
break;
case '3':
word = strsep(&buf, " ");
if (word == NULL)
{
fprintf(stdout, "Missing delay\n");
continue;
}
value = strtol(word, NULL, 10);
if (value <= 0)
{
fprintf(stdout, "Invalid delay (>0)\n");
continue;
}
FxReverb(value).apply(*track);
break;
case '4':
word = strsep(&buf, " ");
if (word == NULL)
{
fprintf(stdout, "Missing samples\n");
continue;
}
value = strtol(word, NULL, 10);
if (value <= 0)
{
fprintf(stdout, "Invalid samples (>0)\n");
continue;
}
track->setLength(track->getLength() + value);
break;
default:
fprintf(stdout, "Invalid choice\n");
continue;
}
break;
}
return true;
}
|
// clang-format off
#include "net.h"
#include "masternodeconfig.h"
#include "util.h"
#include "ui_interface.h"
#include <base58.h>
// clang-format on
CMasternodeConfig masternodeConfig;
void CMasternodeConfig::add(std::string alias, std::string ip, std::string privKey, std::string txHash, std::string outputIndex)
{
CMasternodeEntry cme(alias, ip, privKey, txHash, outputIndex);
entries.push_back(cme);
}
bool CMasternodeConfig::read(std::string& strErr)
{
int linenumber = 1;
boost::filesystem::path pathMasternodeConfigFile = GetMasternodeConfigFile();
boost::filesystem::ifstream streamConfig(pathMasternodeConfigFile);
if (!streamConfig.good()) {
FILE* configFile = fopen(pathMasternodeConfigFile.string().c_str(), "a");
if (configFile != NULL) {
std::string strHeader = "# Masternode config file\n"
"# Format: alias IP:port masternodeprivkey collateral_output_txid collateral_output_index\n"
"# Example: mn1 127.0.0.2:27413 93HaYBVUCYjEMeeH1Y4sBGLALQZE1Yc1K64xiqgX37tGBDQL8Xg 2bcd3c84c84f87eaa86e4e56834c92927a07f9e18718810b92e0d0324456a67c 0\n";
fwrite(strHeader.c_str(), std::strlen(strHeader.c_str()), 1, configFile);
fclose(configFile);
}
return true; // Nothing to read, so just return
}
for (std::string line; std::getline(streamConfig, line); linenumber++) {
if (line.empty()) continue;
std::istringstream iss(line);
std::string comment, alias, ip, privKey, txHash, outputIndex;
if (iss >> comment) {
if (comment.at(0) == '#') continue;
iss.str(line);
iss.clear();
}
if (!(iss >> alias >> ip >> privKey >> txHash >> outputIndex)) {
iss.str(line);
iss.clear();
if (!(iss >> alias >> ip >> privKey >> txHash >> outputIndex)) {
strErr = _("Could not parse masternode.conf") + "\n" +
strprintf(_("Line: %d"), linenumber) + "\n\"" + line + "\"";
streamConfig.close();
return false;
}
}
if (Params().NetworkID() == CBaseChainParams::MAIN) {
if (CService(ip).GetPort() != 27413) {
strErr = _("Invalid port detected in masternode.conf") + "\n" +
strprintf(_("Line: %d"), linenumber) + "\n\"" + line + "\"" + "\n" +
_("(must be 27413 for mainnet)");
streamConfig.close();
return false;
}
} else if (CService(ip).GetPort() == 27413) {
strErr = _("Invalid port detected in masternode.conf") + "\n" +
strprintf(_("Line: %d"), linenumber) + "\n\"" + line + "\"" + "\n" +
_("(27413 could be used only on mainnet)");
streamConfig.close();
return false;
}
add(alias, ip, privKey, txHash, outputIndex);
}
streamConfig.close();
return true;
}
bool CMasternodeConfig::CMasternodeEntry::castOutputIndex(int &n)
{
try {
n = std::stoi(outputIndex);
} catch (const std::exception e) {
LogPrintf("%s: %s on getOutputIndex\n", __func__, e.what());
return false;
}
return true;
}
|
#include "RelativeInformation.h"
RelativeInformation::RelativeInformation() {}
RelativeInformation::~RelativeInformation() {}
void RelativeInformation::RegisterDynamicsInfo(const int sat_id, const Dynamics* dynamics) { dynamics_database_.emplace(sat_id, dynamics); }
void RelativeInformation::RemoveDynamicsInfo(const int sat_id) { dynamics_database_.erase(sat_id); }
const libra::Quaternion RelativeInformation::CalcRelativeAttitudeQuaternion(const int target_sat_id, const int reference_sat_id) const {
// Observer SC Body frame(obs_sat) -> ECI frame(i)
Quaternion q_reference_i2b = dynamics_database_.at(reference_sat_id)->GetAttitude().GetQuaternion_i2b();
Quaternion q_reference_b2i = q_reference_i2b.conjugate();
// ECI frame(i) -> Target SC body frame(main_sat)
Quaternion q_target_i2b = dynamics_database_.at(target_sat_id)->GetAttitude().GetQuaternion_i2b();
return q_target_i2b * q_reference_b2i;
}
const libra::Vector<3> RelativeInformation::GetRelativePosition_i(const int target_sat_id, const int reference_sat_id) const {
libra::Vector<3> target_sat_pos_i = dynamics_database_.at(target_sat_id)->GetOrbit().GetSatPosition_i();
libra::Vector<3> reference_sat_pos_i = dynamics_database_.at(reference_sat_id)->GetOrbit().GetSatPosition_i();
return target_sat_pos_i - reference_sat_pos_i;
}
const libra::Vector<3> RelativeInformation::GetRelativeVelocity_i(const int target_sat_id, const int reference_sat_id) const {
libra::Vector<3> target_sat_vel_i = dynamics_database_.at(target_sat_id)->GetOrbit().GetSatVelocity_i();
libra::Vector<3> reference_sat_vel_i = dynamics_database_.at(reference_sat_id)->GetOrbit().GetSatVelocity_i();
return target_sat_vel_i - reference_sat_vel_i;
}
std::string RelativeInformation::GetLogHeader() const {
std::string str_tmp = "";
for (size_t target_sat_id = 0; target_sat_id < dynamics_database_.size(); target_sat_id++) {
for (size_t reference_sat_id = 0; reference_sat_id < target_sat_id; reference_sat_id++) {
str_tmp += WriteVector("sat" + std::to_string(target_sat_id) + " pos from sat" + std::to_string(reference_sat_id), "i", "m", 3);
}
}
for (size_t target_sat_id = 0; target_sat_id < dynamics_database_.size(); target_sat_id++) {
for (size_t reference_sat_id = 0; reference_sat_id < target_sat_id; reference_sat_id++) {
str_tmp += WriteVector("sat" + std::to_string(target_sat_id) + " velocity from sat" + std::to_string(reference_sat_id), "i", "m", 3);
}
}
return str_tmp;
}
std::string RelativeInformation::GetLogValue() const {
std::string str_tmp = "";
for (size_t target_sat_id = 0; target_sat_id < dynamics_database_.size(); target_sat_id++) {
for (size_t reference_sat_id = 0; reference_sat_id < target_sat_id; reference_sat_id++) {
str_tmp += WriteVector(GetRelativePosition_i(target_sat_id, reference_sat_id));
}
}
for (size_t target_sat_id = 0; target_sat_id < dynamics_database_.size(); target_sat_id++) {
for (size_t reference_sat_id = 0; reference_sat_id < target_sat_id; reference_sat_id++) {
str_tmp += WriteVector(GetRelativeVelocity_i(target_sat_id, reference_sat_id));
}
}
return str_tmp;
}
void RelativeInformation::LogSetup(Logger& logger) { logger.AddLoggable(this); }
|
// Copyright (c) 2021 Johannes Delport
// This code is licensed under MIT license (see LICENSE for details)
#include "JoSIM/Simulation.hpp"
#include "JoSIM/AnalysisType.hpp"
#include "JoSIM/Components.hpp"
#include "JoSIM/Matrix.hpp"
#include "JoSIM/Constants.hpp"
#include "JoSIM/Model.hpp"
#include "JoSIM/ProgressBar.hpp"
#include <cmath>
#include <iostream>
using namespace JoSIM;
Simulation::Simulation(Input &iObj, Matrix &mObj) {
while (needsTR_) {
// Do generic simulation setup for given step size
setup(iObj, mObj);
// Do solver setup
if (SLU) {
// SLU setup
lu.create_matrix(mObj.rp.size() - 1, mObj.nz, mObj.ci, mObj.rp);
lu.factorize();
} else {
// KLU setup
simOK_ = klu_l_defaults(&Common_);
assert(simOK_);
Symbolic_ = klu_l_analyze(
mObj.rp.size() - 1, &mObj.rp.front(), &mObj.ci.front(), &Common_);
Numeric_ = klu_l_factor(
&mObj.rp.front(), &mObj.ci.front(), &mObj.nz.front(),
Symbolic_, &Common_);
}
// Run transient simulation
trans_sim(mObj);
// If step size is too large, reduce and try again
if (needsTR_) {
reduce_step(iObj, mObj);
}
// Do solver cleanup
if (SLU) {
// SLU cleanup
lu.free();
} else {
// KLU cleanup
klu_l_free_symbolic(&Symbolic_, &Common_);
klu_l_free_numeric(&Numeric_, &Common_);
}
}
}
void Simulation::setup(Input& iObj, Matrix& mObj) {
// Simulation setup
SLU = iObj.SLU;
simSize_ = iObj.transSim.simsize();
atyp_ = iObj.argAnal;
minOut_ = iObj.argMin;
needsLU_ = false;
needsTR_ = false;
stepSize_ = iObj.transSim.tstep();
prstep_ = iObj.transSim.prstep();
prstart_ = iObj.transSim.prstart();
startup_ = iObj.transSim.startup();
x_.clear();
x_.resize(mObj.branchIndex, 0.0);
if (!mObj.relevantTraces.empty()) {
results.xVector.resize(mObj.branchIndex);
for (const auto& i : mObj.relevantIndices) {
results.xVector.at(i).emplace();
}
} else {
results.xVector.resize(mObj.branchIndex, std::vector<double>(0));
}
}
void Simulation::trans_sim(Matrix &mObj) {
// Ensure time axis is cleared
results.timeAxis.clear();
ProgressBar bar;
if(!minOut_) {
bar.create_thread();
bar.set_bar_width(30);
bar.fill_bar_progress_with("O");
bar.fill_bar_remainder_with(" ");
bar.set_status_text("Simulating");
bar.set_total((float)simSize_);
}
// Initialize the b matrix
b_.resize(mObj.rp.size(), 0.0);
if (startup_) {
// Stabilize the simulation before starting at t=0
int startup = 2 * pow(10, (abs(log10(stepSize_)) - 12) * 2 + 1);
for (int i = -startup; i < 0; ++i) {
double step = i * stepSize_;
// Setup the b matrix
setup_b(mObj, i, i * stepSize_);
if (needsTR_) return;
// Assign x_prev the new b
x_ = b_;
// Solve Ax=b, storing the results in x_
if (SLU) {
lu.solve(x_);
} else {
simOK_ = klu_l_tsolve(
Symbolic_, Numeric_, mObj.rp.size() - 1, 1, &x_.front(), &Common_);
// If anything is a amiss, complain about it
if (!simOK_) Errors::simulation_errors(
SimulationErrors::MATRIX_SINGULAR);
}
}
}
// Start the simulation loop
for(int i = 0; i < simSize_; ++i) {
double step = i * stepSize_;
// If not minimal printing report progress
if(!minOut_) {
bar.update(static_cast<float>(i));
}
// Setup the b matrix
setup_b(mObj, i, i * stepSize_);
if (needsTR_) return;
// Assign x_prev the new b
x_ = b_;
// Solve Ax=b, storing the results in x_
if (SLU) {
lu.solve(x_);
} else {
simOK_ = klu_l_tsolve(
Symbolic_, Numeric_, mObj.rp.size() - 1, 1, &x_.front(), &Common_);
// If anything is a amiss, complain about it
if (!simOK_) Errors::simulation_errors(
SimulationErrors::MATRIX_SINGULAR);
}
// Store results (only requested, to prevent massive memory usage)
for(int j = 0; j < results.xVector.size(); ++j) {
if(results.xVector.at(j)) {
results.xVector.at(j).value().emplace_back(x_.at(j));
}
}
// Store the time step
results.timeAxis.emplace_back(step);
}
if(!minOut_) {
bar.complete();
std::cout << "\n";
}
}
void Simulation::reduce_step(Input& iObj, Matrix& mObj) {
iObj.transSim.tstep(iObj.transSim.tstep() / 2);
bool tempMinOut = iObj.argMin;
if (!iObj.argMin) iObj.argMin = true;
Matrix newmObj;
mObj = newmObj;
// Create the matrix in csr format
for (auto& i : mObj.sourcegen) {
i.clearMisc();
}
mObj.create_matrix(iObj);
find_relevant_traces(iObj, mObj);
//// Dump expanded Netlist since it is no longer needed
//iObj.netlist.expNetlist.clear();
//iObj.netlist.expNetlist.shrink_to_fit();
if (!tempMinOut) iObj.argMin = tempMinOut;
results.xVector.clear();
results.timeAxis.clear();
}
void Simulation::setup_b(
Matrix &mObj, int i, double step, double factor) {
// Clear b matrix and reset
b_.clear();
b_.resize(mObj.rp.size(), 0.0);
// Handle jj
handle_jj(mObj, i, step, factor);
if(needsTR_) return;
// Re-factorize the LU if any jj transitions
if (needsLU_) {
mObj.create_nz();
if (SLU) {
lu.factorize(true);
} else {
klu_l_free_numeric(&Numeric_, &Common_);
Numeric_ = klu_l_factor(
&mObj.rp.front(), &mObj.ci.front(), &mObj.nz.front(),
Symbolic_, &Common_);
}
needsLU_ = false;
}
// Handle current sources
handle_cs(mObj, step, i);
// Handle resistors
handle_resistors(mObj, step);
// Handle inductors
handle_inductors(mObj, factor);
// Handle capacitors
handle_capacitors(mObj);
// Handle voltage sources
handle_vs(mObj, i, step, factor);
// Handle phase sources
handle_ps(mObj, i, step, factor);
// Handle ccvs
handle_ccvs(mObj);
// Handle vccs
handle_vccs(mObj);
// Handle transmission lines
handle_tx(mObj, i, step);
}
void Simulation::handle_cs(Matrix &mObj, double &step, const int &i) {
for (const auto &j : mObj.components.currentsources) {
if(j.indexInfo.nodeConfig_ == NodeConfig::POSGND) {
b_.at(j.indexInfo.posIndex_.value()) -=
(mObj.sourcegen.at(j.sourceIndex_).value(step));
} else if(j.indexInfo.nodeConfig_ == NodeConfig::GNDNEG) {
b_.at(j.indexInfo.negIndex_.value()) +=
(mObj.sourcegen.at(j.sourceIndex_).value(step));
} else {
b_.at(j.indexInfo.posIndex_.value()) -=
(mObj.sourcegen.at(j.sourceIndex_).value(step));
b_.at(j.indexInfo.negIndex_.value()) +=
(mObj.sourcegen.at(j.sourceIndex_).value(step));
}
}
}
void Simulation::handle_resistors(Matrix &mObj, double &step) {
for (const auto &j : mObj.components.resistorIndices) {
auto &temp = std::get<Resistor>(mObj.components.devices.at(j));
NodeConfig &nc = temp.indexInfo.nodeConfig_;
if(nc == NodeConfig::POSGND) {
if (temp.thermalNoise) {
b_.at(temp.indexInfo.posIndex_.value()) -=
temp.thermalNoise.value().value(step);
}
temp.pn1_ = (x_.at(temp.indexInfo.posIndex_.value()));
} else if(nc == NodeConfig::GNDNEG) {
if (temp.thermalNoise) {
b_.at(temp.indexInfo.negIndex_.value()) +=
temp.thermalNoise.value().value(step);
}
temp.pn1_ = (-x_.at(temp.indexInfo.negIndex_.value()));
} else {
if (temp.thermalNoise) {
b_.at(temp.indexInfo.posIndex_.value()) -=
temp.thermalNoise.value().value(step);
b_.at(temp.indexInfo.negIndex_.value()) +=
temp.thermalNoise.value().value(step);
}
temp.pn1_ = (x_.at(temp.indexInfo.posIndex_.value())
- x_.at(temp.indexInfo.negIndex_.value()));
}
if (atyp_ == AnalysisType::Phase) {
// 4/3 φp1 - 1/3 φp2
b_.at(temp.indexInfo.currentIndex_.value()) =
(4.0 / 3.0) * temp.pn1_ - (1.0 / 3.0) * temp.pn2_;
temp.pn4_ = temp.pn3_;
temp.pn3_ = temp.pn2_;
temp.pn2_ = temp.pn1_;
}
}
}
void Simulation::handle_inductors(Matrix &mObj, double factor) {
for (const auto &j : mObj.components.inductorIndices) {
auto &temp = std::get<Inductor>(mObj.components.devices.at(j));
if(atyp_ == AnalysisType::Voltage) {
// -2L/h Ip + L/2h Ip2
b_.at(temp.indexInfo.currentIndex_.value()) =
-(2.0 * temp.netlistInfo.value_/(stepSize_ * factor)) *
x_.at(temp.indexInfo.currentIndex_.value()) +
((temp.netlistInfo.value_/(2.0 * (stepSize_ * factor))) *
temp.In2_);
// -2M/h Im + M/2h Im2
for(const auto &m : temp.get_mutualInductance()) {
Inductor &mi =
std::get<Inductor>(mObj.components.devices.at(m.first));
b_.at(temp.indexInfo.currentIndex_.value()) +=
(-((2 * m.second) / (stepSize_ * factor)) *
x_.at(mi.indexInfo.currentIndex_.value()) +
(m.second / (2.0 * (stepSize_ * factor))) * mi.In2_);
}
temp.In4_ = temp.In3_;
temp.In3_ = temp.In2_;
temp.In2_ = x_.at(temp.indexInfo.currentIndex_.value());
}
}
}
void Simulation::handle_capacitors(Matrix &mObj) {
for (const auto &j : mObj.components.capacitorIndices) {
auto &temp = std::get<Capacitor>(mObj.components.devices.at(j));
if(temp.indexInfo.posIndex_ && !temp.indexInfo.negIndex_) {
temp.pn1_ = (x_.at(temp.indexInfo.posIndex_.value()));
} else if(!temp.indexInfo.posIndex_ && temp.indexInfo.negIndex_) {
temp.pn1_ = (-x_.at(temp.indexInfo.negIndex_.value()));
} else {
temp.pn1_ = (x_.at(temp.indexInfo.posIndex_.value())
- x_.at(temp.indexInfo.negIndex_.value()));
}
if(atyp_ == AnalysisType::Voltage) {
// 4/3 Vp1 - 1/3 Vp2
b_.at(temp.indexInfo.currentIndex_.value()) =
(4.0/3.0) * temp.pn1_ - (1.0/3.0) * temp.pn2_;
} else if (atyp_ == AnalysisType::Phase) {
// (8/3)φn-1 - (22/9)φn-2 + (8/9)φn-3 - (1/9)φn-4
b_.at(temp.indexInfo.currentIndex_.value()) =
(8.0/3.0) * temp.pn1_ - (22.0/9.0) * temp.pn2_ +
(8.0/9.0) * temp.pn3_ - (1.0/9.0) * temp.pn4_;
temp.pn7_ = temp.pn6_;
temp.pn6_ = temp.pn5_;
temp.pn5_ = temp.pn4_;
temp.pn4_ = temp.pn3_;
temp.pn3_ = temp.pn2_;
}
temp.pn2_ = temp.pn1_;
}
}
void Simulation::handle_jj(
Matrix &mObj, int &i, double &step, double factor) {
for (const auto &j : mObj.components.junctionIndices) {
auto &temp = std::get<JJ>(mObj.components.devices.at(j));
const auto &model = temp.model_;
if(temp.indexInfo.posIndex_ && !temp.indexInfo.negIndex_) {
if (temp.thermalNoise) {
b_.at(temp.indexInfo.posIndex_.value()) -=
temp.thermalNoise.value().value(step);
}
temp.pn1_ = (x_.at(temp.indexInfo.posIndex_.value()));
} else if(!temp.indexInfo.posIndex_ && temp.indexInfo.negIndex_) {
if (temp.thermalNoise) {
b_.at(temp.indexInfo.negIndex_.value()) +=
temp.thermalNoise.value().value(step);
}
temp.pn1_ = (-x_.at(temp.indexInfo.negIndex_.value()));
} else {
if (temp.thermalNoise) {
b_.at(temp.indexInfo.posIndex_.value()) -=
temp.thermalNoise.value().value(step);
b_.at(temp.indexInfo.negIndex_.value()) +=
temp.thermalNoise.value().value(step);
}
temp.pn1_ = (x_.at(temp.indexInfo.posIndex_.value())
- x_.at(temp.indexInfo.negIndex_.value()));
}
if(i > 0) {
if(atyp_ == AnalysisType::Voltage) {
temp.vn1_ = temp.pn1_;
temp.pn1_ = x_.at(temp.variableIndex_);
} else if (atyp_ == AnalysisType::Phase) {
temp.vn1_ = x_.at(temp.variableIndex_);
temp.pn1_ = temp.pn1_;
}
}
// Guess voltage (V0)
double v0 =
(5.0/2.0) * temp.vn1_ - 2.0 * temp.vn2_ + (1.0 / 2.0) * temp.vn3_;
// Phase guess (P0)
temp.phi0_ = (4.0/3.0) * temp.pn1_ - (1.0/3.0) * temp.pn2_ +
((1.0 / Constants::SIGMA) *
((2.0 * (stepSize_)) / 3.0)) * v0;
// Ensure timestep is not too large
if ((double)i/(double)simSize_ > 0.01) {
if (abs(temp.phi0_ - temp.pn1_) > (0.20 * 2 * Constants::PI)) {
needsTR_ = true;
return;
/*Errors::simulation_errors(
SimulationErrors::PHASEGUESS_TOO_LARGE, temp.netlistInfo.label_);*/
}
}
// (hbar / 2 * e) ( -(2 / h) φp1 + (1 / 2h) φp2 )
if(atyp_ == AnalysisType::Voltage) {
b_.at(temp.variableIndex_) =
(Constants::SIGMA) * (-(2.0 / (stepSize_)) *
temp.pn1_ + (1.0 / (2.0 * (stepSize_))) * temp.pn2_);
// (4 / 3) φp1 - (1/3) φp2
} else if (atyp_ == AnalysisType::Phase) {
b_.at(temp.variableIndex_) =
(4.0 / 3.0) * temp.pn1_ - (1.0 / 3.0) * temp.pn2_;
}
temp.pn4_ = temp.pn3_;
temp.pn3_ = temp.pn2_;
temp.pn2_ = temp.pn1_;
temp.vn6_ = temp.vn5_;
temp.vn5_ = temp.vn4_;
temp.vn4_ = temp.vn3_;
temp.vn3_ = temp.vn2_;
// Update junction transition
if(model.rtype() == 1) {
auto testLU = temp.update_value(v0);
if(testLU && !needsLU_) {
needsLU_ = true;
}
}
// sin (φ0 - φ)
double sin_phi = sin(temp.phi0_ - temp.model_.phiOff());
if (!temp.model_.tDep()) {
// -(hR / h + 2RC) * (Ic sin (φ0) - 2C / h Vp1 + C/2h Vp2 + It)
b_.at(temp.indexInfo.currentIndex_.value()) =
(temp.matrixInfo.nonZeros_.back()) * (temp.model_.ic() * sin_phi -
(((2 * model.c()) / (stepSize_)) * temp.vn1_) +
((model.c() / (2.0 * (stepSize_))) * temp.vn2_) +
temp.it_);
} else {
double sin2_half_phi = sin((temp.phi0_ - temp.model_.phiOff()) / 2);
sin2_half_phi = sin2_half_phi * sin2_half_phi;
double sqrt_part = sqrt(1 - model.d() * sin2_half_phi);
b_.at(temp.indexInfo.currentIndex_.value()) =
// -(hR / h + 2RC) *(
(temp.matrixInfo.nonZeros_.back()) * ((
// (π * Δ / 2 * e * Rn)
((Constants::PI * temp.del_)
/ (2 * Constants::EV * temp.model_.rn()))
// * (sin(φ0 - φ) / √(1 - D * sin²((φ0 - φ) / 2))
* (sin_phi / sqrt_part)
// * tanh(Δ / (2 * kB * T) * √(1 - D * sin²((φ0 - φ) / 2)))
* tanh(temp.del_ / (2 * Constants::BOLTZMANN * model.t())
* sqrt_part))
// - 2C / h Vp1
- (((2 * model.c()) / stepSize_) * temp.vn1_)
// + C/2h Vp2
+ ((model.c() / (2.0 * stepSize_)) * temp.vn2_)
// + It)
+ temp.it_);
}
temp.vn2_ = temp.vn1_;
}
}
void Simulation::handle_vs(
Matrix &mObj, const int &i, double &step, double factor) {
for (const auto &j : mObj.components.vsIndices) {
auto &temp = std::get<VoltageSource>(mObj.components.devices.at(j));
JoSIM::NodeConfig &nc = temp.indexInfo.nodeConfig_;
if(atyp_ == AnalysisType::Voltage) {
// Vn
b_.at(temp.indexInfo.currentIndex_.value()) =
(mObj.sourcegen.at(temp.sourceIndex_).value(step));
} else if (atyp_ == AnalysisType::Phase) {
if(nc == NodeConfig::POSGND) {
temp.pn1_ = (x_.at(temp.indexInfo.posIndex_.value()));
} else if(nc == NodeConfig::GNDNEG) {
temp.pn1_ = (-x_.at(temp.indexInfo.negIndex_.value()));
} else {
temp.pn1_ = (x_.at(temp.indexInfo.posIndex_.value())
- x_.at(temp.indexInfo.negIndex_.value()));
}
// (2e/hbar)(2h/3)Vn + (4/3)φn-1 - (1/3)φn-2
b_.at(temp.indexInfo.currentIndex_.value()) =
((2 * stepSize_ * factor) / (3 * Constants::SIGMA)) *
(mObj.sourcegen.at(temp.sourceIndex_).value(step)) +
(4.0 / 3.0) * temp.pn1_ - (1.0 / 3.0) * temp.pn2_;
temp.pn4_ = temp.pn3_;
temp.pn3_ = temp.pn2_;
temp.pn2_ = temp.pn1_;
}
}
}
void Simulation::handle_ps(
Matrix &mObj, const int &i, double &step, double factor) {
for (const auto &j : mObj.components.psIndices) {
auto &temp = std::get<PhaseSource>(mObj.components.devices.at(j));
if (atyp_ == AnalysisType::Phase) {
// φn
b_.at(temp.indexInfo.currentIndex_.value()) =
(mObj.sourcegen.at(temp.sourceIndex_).value(step));
} else if(atyp_ == AnalysisType::Voltage) {
if(i == 0) {
b_.at(temp.indexInfo.currentIndex_.value()) =
(Constants::SIGMA / (stepSize_ * factor)) * ((3.0/2.0) *
(mObj.sourcegen.at(temp.sourceIndex_).value(step)));
} else if (i == 1) {
b_.at(temp.indexInfo.currentIndex_.value()) =
(Constants::SIGMA / (stepSize_ * factor)) * ((3.0/2.0) *
(mObj.sourcegen.at(temp.sourceIndex_).value(step)) - 2.0 *
(mObj.sourcegen.at(
temp.sourceIndex_).value(step - (stepSize_*factor))));
} else {
b_.at(temp.indexInfo.currentIndex_.value()) =
(Constants::SIGMA / (stepSize_ * factor)) * ((3.0/2.0) *
(mObj.sourcegen.at(temp.sourceIndex_).value(step)) - 2.0 *
(mObj.sourcegen.at(
temp.sourceIndex_).value(step - (stepSize_*factor))) + 0.5 *
(mObj.sourcegen.at(
temp.sourceIndex_).value(step - (2 * stepSize_*factor))));
}
}
}
}
void Simulation::handle_ccvs(Matrix &mObj) {
for (const auto &j : mObj.components.ccvsIndices) {
auto &temp = std::get<CCVS>(mObj.components.devices.at(j));
if (atyp_ == AnalysisType::Phase) {
if(temp.indexInfo.posIndex_ && !temp.indexInfo.negIndex_) {
temp.pn1_ = (x_.at(temp.indexInfo.posIndex_.value()));
} else if(!temp.indexInfo.posIndex_ && temp.indexInfo.negIndex_) {
temp.pn1_ = (-x_.at(temp.indexInfo.negIndex_.value()));
} else {
temp.pn1_ = (x_.at(temp.indexInfo.posIndex_.value())
- x_.at(temp.indexInfo.negIndex_.value()));
}
b_.at(temp.indexInfo.currentIndex_.value()) =
(4.0 / 3.0) * temp.pn1_ - (1.0 / 3.0) * temp.pn2_;
temp.pn4_ = temp.pn3_;
temp.pn3_ = temp.pn2_;
temp.pn2_ = temp.pn1_;
}
}
}
void Simulation::handle_vccs(Matrix &mObj) {
for (const auto &j : mObj.components.vccsIndices) {
auto &temp = std::get<VCCS>(mObj.components.devices.at(j));
if (atyp_ == AnalysisType::Phase) {
if(temp.posIndex2_ && !temp.negIndex2_) {
temp.pn1_ = (x_.at(temp.posIndex2_.value()));
} else if(!temp.posIndex2_ && temp.negIndex2_) {
temp.pn1_ = (-x_.at(temp.negIndex2_.value()));
} else {
temp.pn1_ = (x_.at(temp.posIndex2_.value())
- x_.at(temp.negIndex2_.value()));
}
b_.at(temp.indexInfo.currentIndex_.value()) =
(4.0 / 3.0) * temp.pn1_ - (1.0 / 3.0) * temp.pn2_;
temp.pn4_ = temp.pn3_;
temp.pn3_ = temp.pn2_;
temp.pn2_ = temp.pn1_;
}
}
}
void Simulation::handle_tx(
Matrix &mObj, const int &i, double &step, double factor) {
for (const auto &j : mObj.components.txIndices) {
auto &temp = std::get<TransmissionLine>(mObj.components.devices.at(j));
// Z0
double &Z = temp.netlistInfo.value_;
// Td == k
int &k = temp.timestepDelay_;
// Shorthands
JoSIM::NodeConfig &nc = temp.indexInfo.nodeConfig_,
&nc2 = temp.nodeConfig2_;
int_o &posInd = temp.indexInfo.posIndex_,
&negInd = temp.indexInfo.negIndex_,
&posInd2 = temp.posIndex2_,
&negInd2 = temp.negIndex2_;
int &curInd = temp.indexInfo.currentIndex_.value(),
&curInd2 = temp.currentIndex2_;
if(atyp_ == AnalysisType::Voltage) {
if(i >= k) {
// φ1n-k
if(nc == NodeConfig::POSGND) {
temp.nk_1_ = results.xVector.at(posInd.value()).value().at(i - k);
} else if(nc == NodeConfig::GNDNEG) {
temp.nk_1_ = -results.xVector.at(negInd.value()).value().at(i - k);
} else {
temp.nk_1_ = results.xVector.at(posInd.value()).value().at(i - k) -
results.xVector.at(negInd.value()).value().at(i - k);
}
// φ2n-k
if(nc2 == NodeConfig::POSGND) {
temp.nk_2_ = results.xVector.at(posInd2.value()).value().at(i - k);
} else if(nc2 == NodeConfig::GNDNEG) {
temp.nk_2_ = -results.xVector.at(negInd2.value()).value().at(i - k);
} else {
temp.nk_2_ = results.xVector.at(posInd2.value()).value().at(i - k) -
results.xVector.at(negInd2.value()).value().at(i - k);
}
// I1n-k
double &I1nk = results.xVector.at(curInd).value().at(i - k);
// I2n-k
double &I2nk = results.xVector.at(curInd2).value().at(i - k);
// I1 = ZI2n-k + V2n-k
b_.at(curInd) = Z * I2nk + temp.nk_2_;
// I2 = ZI1n-k + V1n-k
b_.at(curInd2) = Z * I1nk + temp.nk_1_;
}
} else if (atyp_ == AnalysisType::Phase) {
if (i > 0) {
temp.n2_1_ = temp.n1_1_;
temp.n2_2_ = temp.n1_2_;
// φ1n-1
if(nc == NodeConfig::POSGND) {
temp.n1_1_ = (x_.at(posInd.value()));
} else if(nc == NodeConfig::GNDNEG) {
temp.n1_1_ = (-x_.at(negInd.value()));
} else {
temp.n1_1_ = (x_.at(posInd.value()) - x_.at(negInd.value()));
}
// φ2n-1
if(nc2 == NodeConfig::POSGND) {
temp.n1_2_ = (x_.at(posInd2.value()));
} else if(nc2 == NodeConfig::GNDNEG) {
temp.n1_2_ = (-x_.at(negInd2.value()));
} else {
temp.n1_2_ = (x_.at(posInd2.value()) - x_.at(negInd2.value()));
}
}
if (i >= k) {
// φ1n-k
if(nc == NodeConfig::POSGND) {
temp.nk_1_ = results.xVector.at(posInd.value()).value().at(i - k);
} else if(nc == NodeConfig::GNDNEG) {
temp.nk_1_ = -results.xVector.at(negInd.value()).value().at(i - k);
} else {
temp.nk_1_ = results.xVector.at(posInd.value()).value().at(i - k) -
results.xVector.at(negInd.value()).value().at(i - k);
}
// φ2n-k
if(nc2 == NodeConfig::POSGND) {
temp.nk_2_ = results.xVector.at(posInd2.value()).value().at(i - k);
} else if(nc2 == NodeConfig::GNDNEG) {
temp.nk_2_ = -results.xVector.at(negInd2.value()).value().at(i - k);
} else {
temp.nk_2_ = results.xVector.at(posInd2.value()).value().at(i - k) -
results.xVector.at(negInd2.value()).value().at(i - k);
}
// I1n-k
double &I1nk = results.xVector.at(curInd).value().at(i - k);
// I2n-k
double &I2nk = results.xVector.at(curInd2).value().at(i - k);
if (i == k) {
// I1 = Z(2e/hbar)(2h/3)I2n-k + (4/3)φ1n-1 - (1/3)φ1n-2 + φ2n-k
b_.at(curInd) = (Z / Constants::SIGMA) *
((2.0 * stepSize_ * factor) / 3.0) * I2nk +
(4.0 / 3.0) * temp.n1_1_ - (1.0 / 3.0) * temp.n2_1_ + temp.nk_2_;
// I2 = Z(2e/hbar)(2h/3)I1n-k + (4/3)φ2n-1 - (1/3)φ2n-2 + φ1n-k
b_.at(curInd2) = (Z / Constants::SIGMA) *
((2.0 * stepSize_ * factor) / 3.0) * I1nk
+ (4.0 / 3.0) * temp.n1_2_ - (1.0 / 3.0) * temp.n2_2_ + temp.nk_1_;
} else if (i == k + 1) {
// φ1n-k-1
if(nc == NodeConfig::POSGND) {
temp.nk1_1_ = results.xVector.at(
posInd.value()).value().at(i - k - 1);
} else if(nc == NodeConfig::GNDNEG) {
temp.nk1_1_ = -results.xVector.at(
negInd.value()).value().at(i - k - 1);
} else {
temp.nk1_1_ = results.xVector.at(
posInd.value()).value().at(i - k - 1) -
results.xVector.at(negInd.value()).value().at(i - k - 1);
}
// φ2n-k-1
if(nc2 == NodeConfig::POSGND) {
temp.nk1_2_ = results.xVector.at(
posInd2.value()).value().at(i - k - 1);
} else if(nc2 == NodeConfig::GNDNEG) {
temp.nk1_2_ = -results.xVector.at(
negInd2.value()).value().at(i - k - 1);
} else {
temp.nk1_2_ = results.xVector.at(
posInd2.value()).value().at(i - k - 1) -
results.xVector.at(negInd2.value()).value().at(i - k - 1);
}
// I1 = Z(2e/hbar)(2h/3)I2n-k + (4/3)φ1n-1 - (1/3)φ1n-2 +
// φ2n-k - (4/3)φ2n-k-1
b_.at(curInd) = (Z / Constants::SIGMA) *
((2.0 * stepSize_ * factor) / 3.0) * I2nk +
(4.0 / 3.0) * temp.n1_1_ - (1.0 / 3.0) * temp.n2_1_ +
temp.nk_2_ - (4.0 / 3.0) * temp.nk1_2_;
// I2 = Z(2e/hbar)(2h/3)I1n-k + (4/3)φ2n-1 - (1/3)φ2n-2 +
// φ1n-k - (4/3)φ1n-k-1
b_.at(curInd2) = (Z / Constants::SIGMA) *
((2.0 * stepSize_ * factor) / 3.0) * I1nk +
(4.0 / 3.0) * temp.n1_2_ - (1.0 / 3.0) * temp.n2_2_ +
temp.nk_1_ - (4.0 / 3.0) * temp.nk1_1_;
} else if (i > k + 1) {
// φ1n-k-1
if(nc == NodeConfig::POSGND) {
temp.nk1_1_ = results.xVector.at(
posInd.value()).value().at(i - k - 1);
} else if(nc == NodeConfig::GNDNEG) {
temp.nk1_1_ = -results.xVector.at(
negInd.value()).value().at(i - k - 1);
} else {
temp.nk1_1_ = results.xVector.at(
posInd.value()).value().at(i - k - 1) -
results.xVector.at(negInd.value()).value().at(i - k - 1);
}
// φ2n-k-1
if(nc2 == NodeConfig::POSGND) {
temp.nk1_2_ = results.xVector.at(
posInd2.value()).value().at(i - k - 1);
} else if(nc2 == NodeConfig::GNDNEG) {
temp.nk1_2_ = -results.xVector.at(
negInd2.value()).value().at(i - k - 1);
} else {
temp.nk1_2_ = results.xVector.at(
posInd2.value()).value().at(i - k - 1) -
results.xVector.at(negInd2.value()).value().at(i - k - 1);
}
// φ1n-k-2
if(nc == NodeConfig::POSGND) {
temp.nk2_1_ = results.xVector.at(
posInd.value()).value().at(i - k - 2);
} else if(nc == NodeConfig::GNDNEG) {
temp.nk2_1_ = -results.xVector.at(
negInd.value()).value().at(i - k - 2);
} else {
temp.nk2_1_ = results.xVector.at(
posInd.value()).value().at(i - k - 2) -
results.xVector.at(negInd.value()).value().at(i - k - 2);
}
// φ2n-k-2
if(nc2 == NodeConfig::POSGND) {
temp.nk2_2_ = results.xVector.at(
posInd2.value()).value().at(i - k - 2);
} else if(nc2 == NodeConfig::GNDNEG) {
temp.nk2_2_ = -results.xVector.at(
negInd2.value()).value().at(i - k - 2);
} else {
temp.nk2_2_ = results.xVector.at(
posInd2.value()).value().at(i - k - 2) -
results.xVector.at(negInd2.value()).value().at(i - k - 2);
}
// I1 = Z(2e/hbar)(2h/3)I2n-k + (4/3)φ1n-1 - (1/3)φ1n-2 +
// φ2n-k - (4/3)φ2n-k-1 + (1/3)φ2n-k-2
b_.at(curInd) = (Z / Constants::SIGMA) *
((2.0 * stepSize_ * factor) / 3.0) * I2nk +
(4.0 / 3.0) * temp.n1_1_ - (1.0 / 3.0) * temp.n2_1_ + temp.nk_2_ -
(4.0 / 3.0) * temp.nk1_2_ + (1.0 / 3.0) * temp.nk2_2_;
// I2 = Z(2e/hbar)(2h/3)I1n-k + (4/3)φ2n-1 - (1/3)φ2n-2 +
// φ1n-k - (4/3)φ1n-k-1 + (1/3)φ1n-k-2
b_.at(curInd2) = (Z / Constants::SIGMA) *
((2.0 * stepSize_ * factor) / 3.0) * I1nk +
(4.0 / 3.0) * temp.n1_2_ - (1.0 / 3.0) * temp.n2_2_ + temp.nk_1_ -
(4.0 / 3.0) * temp.nk1_1_ + (1.0 / 3.0) * temp.nk2_1_;
}
} else {
// I1 = (4/3)φ1n-1 - (1/3)φ1n-2
b_.at(curInd) = (4.0 / 3.0) * temp.n1_1_ - (1.0 / 3.0) * temp.n2_1_;
// I2 = (4/3)φ2n-1 - (1/3)φ2n-2
b_.at(curInd2) = (4.0 / 3.0) * temp.n1_2_ - (1.0 / 3.0) * temp.n2_2_;
}
}
}
}
|
// Copyright (c) 2011-2017 The Cryptonote developers
// Copyright (c) 2014-2017 XDN developers
// Copyright (c) 2016-2017 BXC developers
// Copyright (c) 2017 UltraNote developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "PaymentServiceJsonRpcServer.h"
#include <functional>
#include "PaymentServiceJsonRpcMessages.h"
#include "WalletService.h"
#include "Serialization/JsonInputValueSerializer.h"
#include "Serialization/JsonOutputStreamSerializer.h"
namespace PaymentService {
PaymentServiceJsonRpcServer::PaymentServiceJsonRpcServer(System::Dispatcher& sys, System::Event& stopEvent, WalletService& service, Logging::ILogger& loggerGroup)
: JsonRpcServer(sys, stopEvent, loggerGroup)
, service(service)
, logger(loggerGroup, "PaymentServiceJsonRpcServer")
{
handlers.emplace("reset", jsonHandler<Reset::Request, Reset::Response>(std::bind(&PaymentServiceJsonRpcServer::handleReset, this, std::placeholders::_1, std::placeholders::_2)));
handlers.emplace("createAddress", jsonHandler<CreateAddress::Request, CreateAddress::Response>(std::bind(&PaymentServiceJsonRpcServer::handleCreateAddress, this, std::placeholders::_1, std::placeholders::_2)));
handlers.emplace("deleteAddress", jsonHandler<DeleteAddress::Request, DeleteAddress::Response>(std::bind(&PaymentServiceJsonRpcServer::handleDeleteAddress, this, std::placeholders::_1, std::placeholders::_2)));
handlers.emplace("getSpendKeys", jsonHandler<GetSpendKeys::Request, GetSpendKeys::Response>(std::bind(&PaymentServiceJsonRpcServer::handleGetSpendKeys, this, std::placeholders::_1, std::placeholders::_2)));
handlers.emplace("getBalance", jsonHandler<GetBalance::Request, GetBalance::Response>(std::bind(&PaymentServiceJsonRpcServer::handleGetBalance, this, std::placeholders::_1, std::placeholders::_2)));
handlers.emplace("getBlockHashes", jsonHandler<GetBlockHashes::Request, GetBlockHashes::Response>(std::bind(&PaymentServiceJsonRpcServer::handleGetBlockHashes, this, std::placeholders::_1, std::placeholders::_2)));
handlers.emplace("getTransactionHashes", jsonHandler<GetTransactionHashes::Request, GetTransactionHashes::Response>(std::bind(&PaymentServiceJsonRpcServer::handleGetTransactionHashes, this, std::placeholders::_1, std::placeholders::_2)));
handlers.emplace("getTransactions", jsonHandler<GetTransactions::Request, GetTransactions::Response>(std::bind(&PaymentServiceJsonRpcServer::handleGetTransactions, this, std::placeholders::_1, std::placeholders::_2)));
handlers.emplace("getUnconfirmedTransactionHashes", jsonHandler<GetUnconfirmedTransactionHashes::Request, GetUnconfirmedTransactionHashes::Response>(std::bind(&PaymentServiceJsonRpcServer::handleGetUnconfirmedTransactionHashes, this, std::placeholders::_1, std::placeholders::_2)));
handlers.emplace("getTransaction", jsonHandler<GetTransaction::Request, GetTransaction::Response>(std::bind(&PaymentServiceJsonRpcServer::handleGetTransaction, this, std::placeholders::_1, std::placeholders::_2)));
handlers.emplace("sendTransaction", jsonHandler<SendTransaction::Request, SendTransaction::Response>(std::bind(&PaymentServiceJsonRpcServer::handleSendTransaction, this, std::placeholders::_1, std::placeholders::_2)));
handlers.emplace("createDelayedTransaction", jsonHandler<CreateDelayedTransaction::Request, CreateDelayedTransaction::Response>(std::bind(&PaymentServiceJsonRpcServer::handleCreateDelayedTransaction, this, std::placeholders::_1, std::placeholders::_2)));
handlers.emplace("getDelayedTransactionHashes", jsonHandler<GetDelayedTransactionHashes::Request, GetDelayedTransactionHashes::Response>(std::bind(&PaymentServiceJsonRpcServer::handleGetDelayedTransactionHashes, this, std::placeholders::_1, std::placeholders::_2)));
handlers.emplace("deleteDelayedTransaction", jsonHandler<DeleteDelayedTransaction::Request, DeleteDelayedTransaction::Response>(std::bind(&PaymentServiceJsonRpcServer::handleDeleteDelayedTransaction, this, std::placeholders::_1, std::placeholders::_2)));
handlers.emplace("sendDelayedTransaction", jsonHandler<SendDelayedTransaction::Request, SendDelayedTransaction::Response>(std::bind(&PaymentServiceJsonRpcServer::handleSendDelayedTransaction, this, std::placeholders::_1, std::placeholders::_2)));
handlers.emplace("getViewKey", jsonHandler<GetViewKey::Request, GetViewKey::Response>(std::bind(&PaymentServiceJsonRpcServer::handleGetViewKey, this, std::placeholders::_1, std::placeholders::_2)));
handlers.emplace("getStatus", jsonHandler<GetStatus::Request, GetStatus::Response>(std::bind(&PaymentServiceJsonRpcServer::handleGetStatus, this, std::placeholders::_1, std::placeholders::_2)));
handlers.emplace("getAddresses", jsonHandler<GetAddresses::Request, GetAddresses::Response>(std::bind(&PaymentServiceJsonRpcServer::handleGetAddresses, this, std::placeholders::_1, std::placeholders::_2)));
}
void PaymentServiceJsonRpcServer::processJsonRpcRequest(const Common::JsonValue& req, Common::JsonValue& resp) {
try {
prepareJsonResponse(req, resp);
if (!req.contains("method")) {
logger(Logging::WARNING) << "Field \"method\" is not found in json request: " << req;
makeGenericErrorReponse(resp, "Invalid Request", -3600);
return;
}
if (!req("method").isString()) {
logger(Logging::WARNING) << "Field \"method\" is not a string type: " << req;
makeGenericErrorReponse(resp, "Invalid Request", -3600);
return;
}
std::string method = req("method").getString();
auto it = handlers.find(method);
if (it == handlers.end()) {
logger(Logging::WARNING) << "Requested method not found: " << method;
makeMethodNotFoundResponse(resp);
return;
}
logger(Logging::DEBUGGING) << method << " request came";
Common::JsonValue params(Common::JsonValue::OBJECT);
if (req.contains("params")) {
params = req("params");
}
it->second(params, resp);
} catch (std::exception& e) {
logger(Logging::WARNING) << "Error occurred while processing JsonRpc request: " << e.what();
makeGenericErrorReponse(resp, e.what());
}
}
std::error_code PaymentServiceJsonRpcServer::handleReset(const Reset::Request& request, Reset::Response& response) {
if (request.viewSecretKey.empty()) {
return service.resetWallet();
} else {
return service.replaceWithNewWallet(request.viewSecretKey);
}
}
std::error_code PaymentServiceJsonRpcServer::handleCreateAddress(const CreateAddress::Request& request, CreateAddress::Response& response) {
if (request.spendSecretKey.empty() && request.spendPublicKey.empty()) {
return service.createAddress(response.address);
} else if (!request.spendSecretKey.empty()) {
return service.createAddress(request.spendSecretKey, response.address);
} else {
return service.createTrackingAddress(request.spendPublicKey, response.address);
}
}
std::error_code PaymentServiceJsonRpcServer::handleDeleteAddress(const DeleteAddress::Request& request, DeleteAddress::Response& response) {
return service.deleteAddress(request.address);
}
std::error_code PaymentServiceJsonRpcServer::handleGetSpendKeys(const GetSpendKeys::Request& request, GetSpendKeys::Response& response) {
return service.getSpendkeys(request.address, response.spendPublicKey, response.spendSecretKey, response.guiKey);
}
std::error_code PaymentServiceJsonRpcServer::handleGetBalance(const GetBalance::Request& request, GetBalance::Response& response) {
if (!request.address.empty()) {
return service.getBalance(request.address, response.availableBalance, response.lockedAmount);
} else {
return service.getBalance(response.availableBalance, response.lockedAmount);
}
}
std::error_code PaymentServiceJsonRpcServer::handleGetBlockHashes(const GetBlockHashes::Request& request, GetBlockHashes::Response& response) {
return service.getBlockHashes(request.firstBlockIndex, request.blockCount, response.blockHashes);
}
std::error_code PaymentServiceJsonRpcServer::handleGetTransactionHashes(const GetTransactionHashes::Request& request, GetTransactionHashes::Response& response) {
if (!request.blockHash.empty()) {
return service.getTransactionHashes(request.addresses, request.blockHash, request.blockCount, request.paymentId, response.items);
} else {
return service.getTransactionHashes(request.addresses, request.firstBlockIndex, request.blockCount, request.paymentId, response.items);
}
}
std::error_code PaymentServiceJsonRpcServer::handleGetTransactions(const GetTransactions::Request& request, GetTransactions::Response& response) {
if (!request.blockHash.empty()) {
return service.getTransactions(request.addresses, request.blockHash, request.blockCount, request.paymentId, response.items);
} else {
return service.getTransactions(request.addresses, request.firstBlockIndex, request.blockCount, request.paymentId, response.items);
}
}
std::error_code PaymentServiceJsonRpcServer::handleGetUnconfirmedTransactionHashes(const GetUnconfirmedTransactionHashes::Request& request, GetUnconfirmedTransactionHashes::Response& response) {
return service.getUnconfirmedTransactionHashes(request.addresses, response.transactionHashes);
}
std::error_code PaymentServiceJsonRpcServer::handleGetTransaction(const GetTransaction::Request& request, GetTransaction::Response& response) {
return service.getTransaction(request.transactionHash, response.transaction);
}
std::error_code PaymentServiceJsonRpcServer::handleSendTransaction(const SendTransaction::Request& request, SendTransaction::Response& response) {
return service.sendTransaction(request, response.transactionHash);
}
std::error_code PaymentServiceJsonRpcServer::handleCreateDelayedTransaction(const CreateDelayedTransaction::Request& request, CreateDelayedTransaction::Response& response) {
return service.createDelayedTransaction(request, response.transactionHash);
}
std::error_code PaymentServiceJsonRpcServer::handleGetDelayedTransactionHashes(const GetDelayedTransactionHashes::Request& request, GetDelayedTransactionHashes::Response& response) {
return service.getDelayedTransactionHashes(response.transactionHashes);
}
std::error_code PaymentServiceJsonRpcServer::handleDeleteDelayedTransaction(const DeleteDelayedTransaction::Request& request, DeleteDelayedTransaction::Response& response) {
return service.deleteDelayedTransaction(request.transactionHash);
}
std::error_code PaymentServiceJsonRpcServer::handleSendDelayedTransaction(const SendDelayedTransaction::Request& request, SendDelayedTransaction::Response& response) {
return service.sendDelayedTransaction(request.transactionHash);
}
std::error_code PaymentServiceJsonRpcServer::handleGetViewKey(const GetViewKey::Request& request, GetViewKey::Response& response) {
return service.getViewKey(response.viewSecretKey, response.viewPublicKey);
}
std::error_code PaymentServiceJsonRpcServer::handleGetStatus(const GetStatus::Request& request, GetStatus::Response& response) {
return service.getStatus(response.blockCount, response.knownBlockCount, response.lastBlockHash, response.peerCount);
}
std::error_code PaymentServiceJsonRpcServer::handleGetAddresses(const GetAddresses::Request& request, GetAddresses::Response& response) {
return service.getAddresses(response.addresses);
}
}
|
/* Copyright 2008-2009 Uppsala University
*
* 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 "Policy.h"
Policy::Policy(PolicyType_t _powerPolicy, PolicyType_t _storagePolicy) :
#ifdef DEBUG_LEAKS
LeakMonitor(LEAK_TYPE_POLICY),
#endif
powerPolicy(_powerPolicy),
storagePolicy(_storagePolicy)
{
}
bool operator==(const Policy& p1, const Policy& p2)
{
return (p1.powerPolicy == p2.powerPolicy) &&
(p1.storagePolicy == p2.storagePolicy);
}
|
#include<bits/stdc++.h>
using namespace std;
// eg. (a+) b(+) will also bet true here -- as its only balance check
class Stack{
private:
int size;
int top;
int *s;
public:
Stack(){
top=-1;
}
Stack(int size){
this->size=size;
s=new int[size];
top=-1;
}
~Stack(){
delete s;
}
void push(int x){
if(top>=size-1){
cout<<"Stack Full!"<<endl;
return;
}
top=top+1;
s[top]=x;
cout<<"Pushed : "<<x<<" at index : "<<top<<endl;
}
int pop(){
if(top<0){
cout<<"Stack empty already!"<<endl;
return 0;
}
int bakup=s[top];
top=top-1;
cout<<"Popped : "<<bakup<<" from index : "<<top+1<<endl;
return bakup;
}
void peek(int index){
if(index<=0||index>top){
cout<<"Invalid index!"<<endl;
return;
}
int bakup=top;
while(bakup!=index){
bakup--;
}
cout<<"Element at index : "<<index<<" is : "<<s[bakup]<<endl;
}
int getTopIndex(){
return top;
}
int getTopElement(){
return s[top];
}
bool isEmpty(){
if(top==-1){
return 1;
}else{
return 0;
}
}
bool isFull(){
if(top==size-1){
return 1;
}else{
return 0;
}
}
};
int main(){
char a[]="{[(hello)]}"; // parenthesis are correct!
// char a[]="{[(hello}]}"; // parenthesis are incorrect!
int size=sizeof(a)/sizeof(a[0]);
// for(int i=0;i<size;i++){
// printf("%c",a[i]);
// }
int got;
Stack s(size);
for(int i=0;i<size;i++){
if(a[i]=='('||a[i]=='['||a[i]=='{'){
s.push(a[i]);
}else if(a[i]==')'||a[i]==']'||a[i]=='}'){
got=s.pop();
if(got=='('&&a[i]==')'){
continue;
}else if(got=='['&&a[i]==']'){
continue;
}else if(got=='{'&&a[i]=='}'){
continue;
}else{
cout<<"Wrong Pattern!"<<endl;
break;
}
}
}
if(s.isEmpty()){
cout<<"Parenthesis are correct!";
}else{
cout<<"Parenthesis are not correct!";
}
}
|
#include "../.././Core/Container/Misc/BinTable.hh"
|
/****************************************************************************
**
** Copyright (C) 2008-2010 C.B. Barber. All rights reserved.
**
****************************************************************************/
#//! QhullError -- All exceptions thrown by Qhull are QhullErrors
#include "QhullError.h"
#include <memory>
#include <string>
#include <sstream>
#include <iostream>
using std::cout;
using std::ostringstream;
using std::string;
typedef std::auto_ptr<std::stringstream> StringStreamPointer; //! auto_ptr transfers ownership on copy
#ifdef _MSC_VER // Microsoft Visual C++ -- warning level 4
#endif
namespace orgQhull {
#//GetSet
}//namespace orgQhull
|
/*
www.sourceforge.net/projects/tinyxml
Original code (2.0 and earlier )copyright (c) 2000-2002 Lee Thomason (www.grinninglizard.com)
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.
*/
#include "stdafx.h"
#include <ctype.h>
#include <stddef.h>
#include "tinyxml.h"
//#define DEBUG_PARSER
#if defined( DEBUG_PARSER )
# if defined( DEBUG ) && defined( _MSC_VER )
# include <windows.h>
# define TIXML_LOG OutputDebugString
# else
# define TIXML_LOG printf
# endif
#endif
// Note tha "PutString" hardcodes the same list. This
// is less flexible than it appears. Changing the entries
// or order will break putstring.
TiXmlBase::Entity TiXmlBase::entity[ NUM_ENTITY ] =
{
{ "&", 5, '&' },
{ "<", 4, '<' },
{ ">", 4, '>' },
{ """, 6, '\"' },
{ "'", 6, '\'' }
};
// Bunch of unicode info at:
// http://www.unicode.org/faq/utf_bom.html
// Including the basic of this table, which determines the #bytes in the
// sequence from the lead byte. 1 placed for invalid sequences --
// although the result will be junk, pass it through as much as possible.
// Beware of the non-characters in UTF-8:
// ef bb bf (Microsoft "lead bytes")
// ef bf be
// ef bf bf
const unsigned char TIXML_UTF_LEAD_0 = 0xefU;
const unsigned char TIXML_UTF_LEAD_1 = 0xbbU;
const unsigned char TIXML_UTF_LEAD_2 = 0xbfU;
const int TiXmlBase::utf8ByteTable[256] =
{
// 0 1 2 3 4 5 6 7 8 9 a b c d e f
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x00
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x10
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x20
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x30
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x40
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x50
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x60
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x70 End of ASCII range
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x80 0x80 to 0xc1 invalid
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x90
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0xa0
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0xb0
1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // 0xc0 0xc2 to 0xdf 2 byte
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // 0xd0
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, // 0xe0 0xe0 to 0xef 3 byte
4, 4, 4, 4, 4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // 0xf0 0xf0 to 0xf4 4 byte, 0xf5 and higher invalid
};
void TiXmlBase::ConvertUTF32ToUTF8( unsigned long input, char* output, int* length )
{
const unsigned long BYTE_MASK = 0xBF;
const unsigned long BYTE_MARK = 0x80;
const unsigned long FIRST_BYTE_MARK[7] = { 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC };
if (input < 0x80)
*length = 1;
else if ( input < 0x800 )
*length = 2;
else if ( input < 0x10000 )
*length = 3;
else if ( input < 0x200000 )
*length = 4;
else
{ *length = 0; return; } // This code won't covert this correctly anyway.
output += *length;
// Scary scary fall throughs.
switch (*length)
{
case 4:
--output;
*output = (char)((input | BYTE_MARK) & BYTE_MASK);
input >>= 6;
case 3:
--output;
*output = (char)((input | BYTE_MARK) & BYTE_MASK);
input >>= 6;
case 2:
--output;
*output = (char)((input | BYTE_MARK) & BYTE_MASK);
input >>= 6;
case 1:
--output;
*output = (char)(input | FIRST_BYTE_MARK[*length]);
}
}
/*static*/ int TiXmlBase::IsAlpha( unsigned char anyByte, TiXmlEncoding /*encoding*/ )
{
// This will only work for low-ascii, everything else is assumed to be a valid
// letter. I'm not sure this is the best approach, but it is quite tricky trying
// to figure out alhabetical vs. not across encoding. So take a very
// conservative approach.
// if ( encoding == TIXML_ENCODING_UTF8 )
// {
if ( anyByte < 127 )
return isalpha( anyByte );
else
return 1; // What else to do? The unicode set is huge...get the english ones right.
// }
// else
// {
// return isalpha( anyByte );
// }
}
/*static*/ int TiXmlBase::IsAlphaNum( unsigned char anyByte, TiXmlEncoding /*encoding*/ )
{
// This will only work for low-ascii, everything else is assumed to be a valid
// letter. I'm not sure this is the best approach, but it is quite tricky trying
// to figure out alhabetical vs. not across encoding. So take a very
// conservative approach.
// if ( encoding == TIXML_ENCODING_UTF8 )
// {
if ( anyByte < 127 )
return isalnum( anyByte );
else
return 1; // What else to do? The unicode set is huge...get the english ones right.
// }
// else
// {
// return isalnum( anyByte );
// }
}
class TiXmlParsingData
{
friend class TiXmlDocument;
public:
void Stamp( const char* now, TiXmlEncoding encoding );
const TiXmlCursor& Cursor() { return cursor; }
private:
// Only used by the document!
TiXmlParsingData( const char* start, int _tabsize, int row, int col )
{
assert( start );
stamp = start;
tabsize = _tabsize;
cursor.row = row;
cursor.col = col;
}
TiXmlCursor cursor;
const char* stamp;
int tabsize;
};
void TiXmlParsingData::Stamp( const char* now, TiXmlEncoding encoding )
{
assert( now );
// Do nothing if the tabsize is 0.
if ( tabsize < 1 )
{
return;
}
// Get the current row, column.
int row = cursor.row;
int col = cursor.col;
const char* p = stamp;
assert( p );
while ( p < now )
{
// Treat p as unsigned, so we have a happy compiler.
const unsigned char* pU = (const unsigned char*)p;
// Code contributed by Fletcher Dunn: (modified by lee)
switch (*pU) {
case 0:
// We *should* never get here, but in case we do, don't
// advance past the terminating null character, ever
return;
case '\r':
// bump down to the next line
++row;
col = 0;
// Eat the character
++p;
// Check for \r\n sequence, and treat this as a single character
if (*p == '\n') {
++p;
}
break;
case '\n':
// bump down to the next line
++row;
col = 0;
// Eat the character
++p;
// Check for \n\r sequence, and treat this as a single
// character. (Yes, this bizarre thing does occur still
// on some arcane platforms...)
if (*p == '\r') {
++p;
}
break;
case '\t':
// Eat the character
++p;
// Skip to next tab stop
col = (col / tabsize + 1) * tabsize;
break;
case TIXML_UTF_LEAD_0:
if ( encoding == TIXML_ENCODING_UTF8 )
{
if ( *(p+1) && *(p+2) )
{
// In these cases, don't advance the column. These are
// 0-width spaces.
if ( *(pU+1)==TIXML_UTF_LEAD_1 && *(pU+2)==TIXML_UTF_LEAD_2 )
p += 3;
else if ( *(pU+1)==0xbfU && *(pU+2)==0xbeU )
p += 3;
else if ( *(pU+1)==0xbfU && *(pU+2)==0xbfU )
p += 3;
else
{ p +=3; ++col; } // A normal character.
}
}
else
{
++p;
++col;
}
break;
default:
if ( encoding == TIXML_ENCODING_UTF8 )
{
// Eat the 1 to 4 byte utf8 character.
int step = TiXmlBase::utf8ByteTable[*((const unsigned char*)p)];
if ( step == 0 )
step = 1; // Error case from bad encoding, but handle gracefully.
p += step;
// Just advance one column, of course.
++col;
}
else
{
++p;
++col;
}
break;
}
}
cursor.row = row;
cursor.col = col;
assert( cursor.row >= -1 );
assert( cursor.col >= -1 );
stamp = p;
assert( stamp );
}
const char* TiXmlBase::SkipWhiteSpace( const char* p, TiXmlEncoding encoding )
{
if ( !p || !*p )
{
return 0;
}
if ( encoding == TIXML_ENCODING_UTF8 )
{
while ( *p )
{
const unsigned char* pU = (const unsigned char*)p;
// Skip the stupid Microsoft UTF-8 Byte order marks
if ( *(pU+0)==TIXML_UTF_LEAD_0
&& *(pU+1)==TIXML_UTF_LEAD_1
&& *(pU+2)==TIXML_UTF_LEAD_2 )
{
p += 3;
continue;
}
else if(*(pU+0)==TIXML_UTF_LEAD_0
&& *(pU+1)==0xbfU
&& *(pU+2)==0xbeU )
{
p += 3;
continue;
}
else if(*(pU+0)==TIXML_UTF_LEAD_0
&& *(pU+1)==0xbfU
&& *(pU+2)==0xbfU )
{
p += 3;
continue;
}
if ( IsWhiteSpace( *p ) || *p == '\n' || *p =='\r' ) // Still using old rules for white space.
++p;
else
break;
}
}
else
{
while ( *p && IsWhiteSpace( *p ) || *p == '\n' || *p =='\r' )
++p;
}
return p;
}
#ifdef TIXML_USE_STL
/*static*/ bool TiXmlBase::StreamWhiteSpace( std::istream * in, TIXML_STRING * tag )
{
for( ;; )
{
if ( !in->good() ) return false;
int c = in->peek();
// At this scope, we can't get to a document. So fail silently.
if ( !IsWhiteSpace( c ) || c <= 0 )
return true;
*tag += (char) in->get();
}
}
/*static*/ bool TiXmlBase::StreamTo( std::istream * in, int character, TIXML_STRING * tag )
{
//assert( character > 0 && character < 128 ); // else it won't work in utf-8
while ( in->good() )
{
int c = in->peek();
if ( c == character )
return true;
if ( c <= 0 ) // Silent failure: can't get document at this scope
return false;
in->get();
*tag += (char) c;
}
return false;
}
#endif
// One of TinyXML's more performance demanding functions. Try to keep the memory overhead down. The
// "assign" optimization removes over 10% of the execution time.
//
const char* TiXmlBase::ReadName( const char* p, TIXML_STRING * name, TiXmlEncoding encoding )
{
// Oddly, not supported on some comilers,
//name->clear();
// So use this:
*name = "";
assert( p );
// Names start with letters or underscores.
// Of course, in unicode, tinyxml has no idea what a letter *is*. The
// algorithm is generous.
//
// After that, they can be letters, underscores, numbers,
// hyphens, or colons. (Colons are valid ony for namespaces,
// but tinyxml can't tell namespaces from names.)
if ( p && *p
&& ( IsAlpha( (unsigned char) *p, encoding ) || *p == '_' ) )
{
const char* start = p;
while( p && *p
&& ( IsAlphaNum( (unsigned char ) *p, encoding )
|| *p == '_'
|| *p == '-'
|| *p == '.'
|| *p == ':' ) )
{
//(*name) += *p; // expensive
++p;
}
if ( p-start > 0 ) {
name->assign( start, p-start );
}
return p;
}
return 0;
}
const char* TiXmlBase::GetEntity( const char* p, char* value, int* length, TiXmlEncoding encoding )
{
// Presume an entity, and pull it out.
TIXML_STRING ent;
int i;
*length = 0;
if ( *(p+1) && *(p+1) == '#' && *(p+2) )
{
unsigned long ucs = 0;
ptrdiff_t delta = 0;
unsigned mult = 1;
if ( *(p+2) == 'x' )
{
// Hexadecimal.
if ( !*(p+3) ) return 0;
const char* q = p+3;
q = strchr( q, ';' );
if ( !q || !*q ) return 0;
delta = q-p;
--q;
while ( *q != 'x' )
{
if ( *q >= '0' && *q <= '9' )
ucs += mult * (*q - '0');
else if ( *q >= 'a' && *q <= 'f' )
ucs += mult * (*q - 'a' + 10);
else if ( *q >= 'A' && *q <= 'F' )
ucs += mult * (*q - 'A' + 10 );
else
return 0;
mult *= 16;
--q;
}
}
else
{
// Decimal.
if ( !*(p+2) ) return 0;
const char* q = p+2;
q = strchr( q, ';' );
if ( !q || !*q ) return 0;
delta = q-p;
--q;
while ( *q != '#' )
{
if ( *q >= '0' && *q <= '9' )
ucs += mult * (*q - '0');
else
return 0;
mult *= 10;
--q;
}
}
if ( encoding == TIXML_ENCODING_UTF8 )
{
// convert the UCS to UTF-8
ConvertUTF32ToUTF8( ucs, value, length );
}
else
{
*value = (char)ucs;
*length = 1;
}
return p + delta + 1;
}
// Now try to match it.
for( i=0; i<NUM_ENTITY; ++i )
{
if ( strncmp( entity[i].str, p, entity[i].strLength ) == 0 )
{
assert( strlen( entity[i].str ) == entity[i].strLength );
*value = entity[i].chr;
*length = 1;
return ( p + entity[i].strLength );
}
}
// So it wasn't an entity, its unrecognized, or something like that.
*value = *p; // Don't put back the last one, since we return it!
//*length = 1; // Leave unrecognized entities - this doesn't really work.
// Just writes strange XML.
return p+1;
}
bool TiXmlBase::StringEqual( const char* p,
const char* tag,
bool ignoreCase,
TiXmlEncoding encoding )
{
assert( p );
assert( tag );
if ( !p || !*p )
{
assert( 0 );
return false;
}
const char* q = p;
if ( ignoreCase )
{
while ( *q && *tag && ToLower( *q, encoding ) == ToLower( *tag, encoding ) )
{
++q;
++tag;
}
if ( *tag == 0 )
return true;
}
else
{
while ( *q && *tag && *q == *tag )
{
++q;
++tag;
}
if ( *tag == 0 ) // Have we found the end of the tag, and everything equal?
return true;
}
return false;
}
const char* TiXmlBase::ReadText( const char* p,
TIXML_STRING * text,
bool trimWhiteSpace,
const char* endTag,
bool caseInsensitive,
TiXmlEncoding encoding )
{
*text = "";
if ( !trimWhiteSpace // certain tags always keep whitespace
|| !condenseWhiteSpace ) // if true, whitespace is always kept
{
// Keep all the white space.
while ( p && *p
&& !StringEqual( p, endTag, caseInsensitive, encoding )
)
{
int len;
char cArr[4] = { 0, 0, 0, 0 };
p = GetChar( p, cArr, &len, encoding );
text->append( cArr, len );
}
}
else
{
bool whitespace = false;
// Remove leading white space:
p = SkipWhiteSpace( p, encoding );
while ( p && *p
&& !StringEqual( p, endTag, caseInsensitive, encoding ) )
{
if ( *p == '\r' || *p == '\n' )
{
whitespace = true;
++p;
}
else if ( IsWhiteSpace( *p ) )
{
whitespace = true;
++p;
}
else
{
// If we've found whitespace, add it before the
// new character. Any whitespace just becomes a space.
if ( whitespace )
{
(*text) += ' ';
whitespace = false;
}
int len;
char cArr[4] = { 0, 0, 0, 0 };
p = GetChar( p, cArr, &len, encoding );
if ( len == 1 )
(*text) += cArr[0]; // more efficient
else
text->append( cArr, len );
}
}
}
if ( p )
p += strlen( endTag );
return p;
}
#ifdef TIXML_USE_STL
void TiXmlDocument::StreamIn( std::istream * in, TIXML_STRING * tag )
{
// The basic issue with a document is that we don't know what we're
// streaming. Read something presumed to be a tag (and hope), then
// identify it, and call the appropriate stream method on the tag.
//
// This "pre-streaming" will never read the closing ">" so the
// sub-tag can orient itself.
if ( !StreamTo( in, '<', tag ) )
{
SetError( TIXML_ERROR_PARSING_EMPTY, 0, 0, TIXML_ENCODING_UNKNOWN );
return;
}
while ( in->good() )
{
int tagIndex = (int) tag->length();
while ( in->good() && in->peek() != '>' )
{
int c = in->get();
if ( c <= 0 )
{
SetError( TIXML_ERROR_EMBEDDED_NULL, 0, 0, TIXML_ENCODING_UNKNOWN );
break;
}
(*tag) += (char) c;
}
if ( in->good() )
{
// We now have something we presume to be a node of
// some sort. Identify it, and call the node to
// continue streaming.
TiXmlNode* node = Identify( tag->c_str() + tagIndex, TIXML_DEFAULT_ENCODING );
if ( node )
{
node->StreamIn( in, tag );
bool isElement = node->ToElement() != 0;
delete node;
node = 0;
// If this is the root element, we're done. Parsing will be
// done by the >> operator.
if ( isElement )
{
return;
}
}
else
{
SetError( TIXML_ERROR, 0, 0, TIXML_ENCODING_UNKNOWN );
return;
}
}
}
// We should have returned sooner.
SetError( TIXML_ERROR, 0, 0, TIXML_ENCODING_UNKNOWN );
}
#endif
const char* TiXmlDocument::Parse( const char* p, TiXmlParsingData* prevData, TiXmlEncoding encoding )
{
ClearError();
// Parse away, at the document level. Since a document
// contains nothing but other tags, most of what happens
// here is skipping white space.
if ( !p || !*p )
{
SetError( TIXML_ERROR_DOCUMENT_EMPTY, 0, 0, TIXML_ENCODING_UNKNOWN );
return 0;
}
// Note that, for a document, this needs to come
// before the while space skip, so that parsing
// starts from the pointer we are given.
location.Clear();
if ( prevData )
{
location.row = prevData->cursor.row;
location.col = prevData->cursor.col;
}
else
{
location.row = 0;
location.col = 0;
}
TiXmlParsingData data( p, TabSize(), location.row, location.col );
location = data.Cursor();
if ( encoding == TIXML_ENCODING_UNKNOWN )
{
// Check for the Microsoft UTF-8 lead bytes.
const unsigned char* pU = (const unsigned char*)p;
if ( *(pU+0) && *(pU+0) == TIXML_UTF_LEAD_0
&& *(pU+1) && *(pU+1) == TIXML_UTF_LEAD_1
&& *(pU+2) && *(pU+2) == TIXML_UTF_LEAD_2 )
{
encoding = TIXML_ENCODING_UTF8;
useMicrosoftBOM = true;
}
}
p = SkipWhiteSpace( p, encoding );
if ( !p )
{
SetError( TIXML_ERROR_DOCUMENT_EMPTY, 0, 0, TIXML_ENCODING_UNKNOWN );
return 0;
}
while ( p && *p )
{
TiXmlNode* node = Identify( p, encoding );
if ( node )
{
p = node->Parse( p, &data, encoding );
LinkEndChild( node );
}
else
{
break;
}
// Did we get encoding info?
if ( encoding == TIXML_ENCODING_UNKNOWN
&& node->ToDeclaration() )
{
TiXmlDeclaration* dec = node->ToDeclaration();
const char* enc = dec->Encoding();
assert( enc );
if ( *enc == 0 )
encoding = TIXML_ENCODING_UTF8;
else if ( StringEqual( enc, "UTF-8", true, TIXML_ENCODING_UNKNOWN ) )
encoding = TIXML_ENCODING_UTF8;
else if ( StringEqual( enc, "UTF8", true, TIXML_ENCODING_UNKNOWN ) )
encoding = TIXML_ENCODING_UTF8; // incorrect, but be nice
else
encoding = TIXML_ENCODING_LEGACY;
}
p = SkipWhiteSpace( p, encoding );
}
// Was this empty?
if ( !firstChild ) {
SetError( TIXML_ERROR_DOCUMENT_EMPTY, 0, 0, encoding );
return 0;
}
// All is well.
return p;
}
void TiXmlDocument::SetError( int err, const char* pError, TiXmlParsingData* data, TiXmlEncoding encoding )
{
// The first error in a chain is more accurate - don't set again!
if ( error )
return;
assert( err > 0 && err < TIXML_ERROR_STRING_COUNT );
error = true;
errorId = err;
errorDesc = errorString[ errorId ];
errorLocation.Clear();
if ( pError && data )
{
data->Stamp( pError, encoding );
errorLocation = data->Cursor();
}
}
TiXmlNode* TiXmlNode::Identify( const char* p, TiXmlEncoding encoding )
{
TiXmlNode* returnNode = 0;
p = SkipWhiteSpace( p, encoding );
if( !p || !*p || *p != '<' )
{
return 0;
}
TiXmlDocument* doc = GetDocument();
p = SkipWhiteSpace( p, encoding );
if ( !p || !*p )
{
return 0;
}
// What is this thing?
// - Elements start with a letter or underscore, but xml is reserved.
// - Comments: <!--
// - Decleration: <?xml
// - Everthing else is unknown to tinyxml.
//
const char* xmlHeader = { "<?xml" };
const char* commentHeader = { "<!--" };
const char* dtdHeader = { "<!" };
const char* cdataHeader = { "<![CDATA[" };
if ( StringEqual( p, xmlHeader, true, encoding ) )
{
#ifdef DEBUG_PARSER
TIXML_LOG( "XML parsing Declaration\n" );
#endif
returnNode = new TiXmlDeclaration();
}
else if ( StringEqual( p, commentHeader, false, encoding ) )
{
#ifdef DEBUG_PARSER
TIXML_LOG( "XML parsing Comment\n" );
#endif
returnNode = new TiXmlComment();
}
else if ( StringEqual( p, cdataHeader, false, encoding ) )
{
#ifdef DEBUG_PARSER
TIXML_LOG( "XML parsing CDATA\n" );
#endif
TiXmlText* text = new TiXmlText( "" );
text->SetCDATA( true );
returnNode = text;
}
else if ( StringEqual( p, dtdHeader, false, encoding ) )
{
#ifdef DEBUG_PARSER
TIXML_LOG( "XML parsing Unknown(1)\n" );
#endif
returnNode = new TiXmlUnknown();
}
else if ( IsAlpha( *(p+1), encoding )
|| *(p+1) == '_' )
{
#ifdef DEBUG_PARSER
TIXML_LOG( "XML parsing Element\n" );
#endif
returnNode = new TiXmlElement( "" );
}
else
{
#ifdef DEBUG_PARSER
TIXML_LOG( "XML parsing Unknown(2)\n" );
#endif
returnNode = new TiXmlUnknown();
}
if ( returnNode )
{
// Set the parent, so it can report errors
returnNode->parent = this;
}
else
{
if ( doc )
doc->SetError( TIXML_ERROR_OUT_OF_MEMORY, 0, 0, TIXML_ENCODING_UNKNOWN );
}
return returnNode;
}
#ifdef TIXML_USE_STL
void TiXmlElement::StreamIn (std::istream * in, TIXML_STRING * tag)
{
// We're called with some amount of pre-parsing. That is, some of "this"
// element is in "tag". Go ahead and stream to the closing ">"
while( in->good() )
{
int c = in->get();
if ( c <= 0 )
{
TiXmlDocument* document = GetDocument();
if ( document )
document->SetError( TIXML_ERROR_EMBEDDED_NULL, 0, 0, TIXML_ENCODING_UNKNOWN );
return;
}
(*tag) += (char) c ;
if ( c == '>' )
break;
}
if ( tag->length() < 3 ) return;
// Okay...if we are a "/>" tag, then we're done. We've read a complete tag.
// If not, identify and stream.
if ( tag->at( tag->length() - 1 ) == '>'
&& tag->at( tag->length() - 2 ) == '/' )
{
// All good!
return;
}
else if ( tag->at( tag->length() - 1 ) == '>' )
{
// There is more. Could be:
// text
// cdata text (which looks like another node)
// closing tag
// another node.
for ( ;; )
{
StreamWhiteSpace( in, tag );
// Do we have text?
if ( in->good() && in->peek() != '<' )
{
// Yep, text.
TiXmlText text( "" );
text.StreamIn( in, tag );
// What follows text is a closing tag or another node.
// Go around again and figure it out.
continue;
}
// We now have either a closing tag...or another node.
// We should be at a "<", regardless.
if ( !in->good() ) return;
assert( in->peek() == '<' );
int tagIndex = (int) tag->length();
bool closingTag = false;
bool firstCharFound = false;
for( ;; )
{
if ( !in->good() )
return;
int c = in->peek();
if ( c <= 0 )
{
TiXmlDocument* document = GetDocument();
if ( document )
document->SetError( TIXML_ERROR_EMBEDDED_NULL, 0, 0, TIXML_ENCODING_UNKNOWN );
return;
}
if ( c == '>' )
break;
*tag += (char) c;
in->get();
// Early out if we find the CDATA id.
if ( c == '[' && tag->size() >= 9 )
{
size_t len = tag->size();
const char* start = tag->c_str() + len - 9;
if ( strcmp( start, "<![CDATA[" ) == 0 ) {
assert( !closingTag );
break;
}
}
if ( !firstCharFound && c != '<' && !IsWhiteSpace( c ) )
{
firstCharFound = true;
if ( c == '/' )
closingTag = true;
}
}
// If it was a closing tag, then read in the closing '>' to clean up the input stream.
// If it was not, the streaming will be done by the tag.
if ( closingTag )
{
if ( !in->good() )
return;
int c = in->get();
if ( c <= 0 )
{
TiXmlDocument* document = GetDocument();
if ( document )
document->SetError( TIXML_ERROR_EMBEDDED_NULL, 0, 0, TIXML_ENCODING_UNKNOWN );
return;
}
assert( c == '>' );
*tag += (char) c;
// We are done, once we've found our closing tag.
return;
}
else
{
// If not a closing tag, id it, and stream.
const char* tagloc = tag->c_str() + tagIndex;
TiXmlNode* node = Identify( tagloc, TIXML_DEFAULT_ENCODING );
if ( !node )
return;
node->StreamIn( in, tag );
delete node;
node = 0;
// No return: go around from the beginning: text, closing tag, or node.
}
}
}
}
#endif
const char* TiXmlElement::Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding )
{
p = SkipWhiteSpace( p, encoding );
TiXmlDocument* document = GetDocument();
if ( !p || !*p )
{
if ( document ) document->SetError( TIXML_ERROR_PARSING_ELEMENT, 0, 0, encoding );
return 0;
}
if ( data )
{
data->Stamp( p, encoding );
location = data->Cursor();
}
if ( *p != '<' )
{
if ( document ) document->SetError( TIXML_ERROR_PARSING_ELEMENT, p, data, encoding );
return 0;
}
p = SkipWhiteSpace( p+1, encoding );
// Read the name.
const char* pErr = p;
p = ReadName( p, &value, encoding );
if ( !p || !*p )
{
if ( document ) document->SetError( TIXML_ERROR_FAILED_TO_READ_ELEMENT_NAME, pErr, data, encoding );
return 0;
}
TIXML_STRING endTag ("</");
endTag += value;
endTag += ">";
// Check for and read attributes. Also look for an empty
// tag or an end tag.
while ( p && *p )
{
pErr = p;
p = SkipWhiteSpace( p, encoding );
if ( !p || !*p )
{
if ( document ) document->SetError( TIXML_ERROR_READING_ATTRIBUTES, pErr, data, encoding );
return 0;
}
if ( *p == '/' )
{
++p;
// Empty tag.
if ( *p != '>' )
{
if ( document ) document->SetError( TIXML_ERROR_PARSING_EMPTY, p, data, encoding );
return 0;
}
return (p+1);
}
else if ( *p == '>' )
{
// Done with attributes (if there were any.)
// Read the value -- which can include other
// elements -- read the end tag, and return.
++p;
p = ReadValue( p, data, encoding ); // Note this is an Element method, and will set the error if one happens.
if ( !p || !*p ) {
// We were looking for the end tag, but found nothing.
// Fix for [ 1663758 ] Failure to report error on bad XML
if ( document ) document->SetError( TIXML_ERROR_READING_END_TAG, p, data, encoding );
return 0;
}
// We should find the end tag now
if ( StringEqual( p, endTag.c_str(), false, encoding ) )
{
p += endTag.length();
return p;
}
else
{
if ( document ) document->SetError( TIXML_ERROR_READING_END_TAG, p, data, encoding );
return 0;
}
}
else
{
// Try to read an attribute:
TiXmlAttribute* attrib = new TiXmlAttribute();
if ( !attrib )
{
if ( document ) document->SetError( TIXML_ERROR_OUT_OF_MEMORY, pErr, data, encoding );
return 0;
}
attrib->SetDocument( document );
pErr = p;
p = attrib->Parse( p, data, encoding );
if ( !p || !*p )
{
if ( document ) document->SetError( TIXML_ERROR_PARSING_ELEMENT, pErr, data, encoding );
delete attrib;
return 0;
}
// Handle the strange case of double attributes:
#ifdef TIXML_USE_STL
TiXmlAttribute* node = attributeSet.Find( attrib->NameTStr() );
#else
TiXmlAttribute* node = attributeSet.Find( attrib->Name() );
#endif
if ( node )
{
node->SetValue( attrib->Value() );
delete attrib;
return 0;
}
attributeSet.Add( attrib );
}
}
return p;
}
const char* TiXmlElement::ReadValue( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding )
{
TiXmlDocument* document = GetDocument();
// Read in text and elements in any order.
const char* pWithWhiteSpace = p;
p = SkipWhiteSpace( p, encoding );
while ( p && *p )
{
if ( *p != '<' )
{
// Take what we have, make a text element.
TiXmlText* textNode = new TiXmlText( "" );
if ( !textNode )
{
if ( document ) document->SetError( TIXML_ERROR_OUT_OF_MEMORY, 0, 0, encoding );
return 0;
}
if ( TiXmlBase::IsWhiteSpaceCondensed() )
{
p = textNode->Parse( p, data, encoding );
}
else
{
// Special case: we want to keep the white space
// so that leading spaces aren't removed.
p = textNode->Parse( pWithWhiteSpace, data, encoding );
}
if ( !textNode->Blank() )
LinkEndChild( textNode );
else
delete textNode;
}
else
{
// We hit a '<'
// Have we hit a new element or an end tag? This could also be
// a TiXmlText in the "CDATA" style.
if ( StringEqual( p, "</", false, encoding ) )
{
return p;
}
else
{
TiXmlNode* node = Identify( p, encoding );
if ( node )
{
p = node->Parse( p, data, encoding );
LinkEndChild( node );
}
else
{
return 0;
}
}
}
pWithWhiteSpace = p;
p = SkipWhiteSpace( p, encoding );
}
if ( !p )
{
if ( document ) document->SetError( TIXML_ERROR_READING_ELEMENT_VALUE, 0, 0, encoding );
}
return p;
}
#ifdef TIXML_USE_STL
void TiXmlUnknown::StreamIn( std::istream * in, TIXML_STRING * tag )
{
while ( in->good() )
{
int c = in->get();
if ( c <= 0 )
{
TiXmlDocument* document = GetDocument();
if ( document )
document->SetError( TIXML_ERROR_EMBEDDED_NULL, 0, 0, TIXML_ENCODING_UNKNOWN );
return;
}
(*tag) += (char) c;
if ( c == '>' )
{
// All is well.
return;
}
}
}
#endif
const char* TiXmlUnknown::Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding )
{
TiXmlDocument* document = GetDocument();
p = SkipWhiteSpace( p, encoding );
if ( data )
{
data->Stamp( p, encoding );
location = data->Cursor();
}
if ( !p || !*p || *p != '<' )
{
if ( document ) document->SetError( TIXML_ERROR_PARSING_UNKNOWN, p, data, encoding );
return 0;
}
++p;
value = "";
while ( p && *p && *p != '>' )
{
value += *p;
++p;
}
if ( !p )
{
if ( document ) document->SetError( TIXML_ERROR_PARSING_UNKNOWN, 0, 0, encoding );
}
if ( *p == '>' )
return p+1;
return p;
}
#ifdef TIXML_USE_STL
void TiXmlComment::StreamIn( std::istream * in, TIXML_STRING * tag )
{
while ( in->good() )
{
int c = in->get();
if ( c <= 0 )
{
TiXmlDocument* document = GetDocument();
if ( document )
document->SetError( TIXML_ERROR_EMBEDDED_NULL, 0, 0, TIXML_ENCODING_UNKNOWN );
return;
}
(*tag) += (char) c;
if ( c == '>'
&& tag->at( tag->length() - 2 ) == '-'
&& tag->at( tag->length() - 3 ) == '-' )
{
// All is well.
return;
}
}
}
#endif
const char* TiXmlComment::Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding )
{
TiXmlDocument* document = GetDocument();
value = "";
p = SkipWhiteSpace( p, encoding );
if ( data )
{
data->Stamp( p, encoding );
location = data->Cursor();
}
const char* startTag = "<!--";
const char* endTag = "-->";
if ( !StringEqual( p, startTag, false, encoding ) )
{
document->SetError( TIXML_ERROR_PARSING_COMMENT, p, data, encoding );
return 0;
}
p += strlen( startTag );
// [ 1475201 ] TinyXML parses entities in comments
// Oops - ReadText doesn't work, because we don't want to parse the entities.
// p = ReadText( p, &value, false, endTag, false, encoding );
//
// from the XML spec:
/*
[Definition: Comments may appear anywhere in a document outside other markup; in addition,
they may appear within the document type declaration at places allowed by the grammar.
They are not part of the document's character data; an XML processor MAY, but need not,
make it possible for an application to retrieve the text of comments. For compatibility,
the string "--" (double-hyphen) MUST NOT occur within comments.] Parameter entity
references MUST NOT be recognized within comments.
An example of a comment:
<!-- declarations for <head> & <body> -->
*/
value = "";
// Keep all the white space.
while ( p && *p && !StringEqual( p, endTag, false, encoding ) )
{
value.append( p, 1 );
++p;
}
if ( p )
p += strlen( endTag );
return p;
}
const char* TiXmlAttribute::Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding )
{
p = SkipWhiteSpace( p, encoding );
if ( !p || !*p ) return 0;
// int tabsize = 4;
// if ( document )
// tabsize = document->TabSize();
if ( data )
{
data->Stamp( p, encoding );
location = data->Cursor();
}
// Read the name, the '=' and the value.
const char* pErr = p;
p = ReadName( p, &name, encoding );
if ( !p || !*p )
{
if ( document ) document->SetError( TIXML_ERROR_READING_ATTRIBUTES, pErr, data, encoding );
return 0;
}
p = SkipWhiteSpace( p, encoding );
if ( !p || !*p || *p != '=' )
{
if ( document ) document->SetError( TIXML_ERROR_READING_ATTRIBUTES, p, data, encoding );
return 0;
}
++p; // skip '='
p = SkipWhiteSpace( p, encoding );
if ( !p || !*p )
{
if ( document ) document->SetError( TIXML_ERROR_READING_ATTRIBUTES, p, data, encoding );
return 0;
}
const char* end;
const char SINGLE_QUOTE = '\'';
const char DOUBLE_QUOTE = '\"';
if ( *p == SINGLE_QUOTE )
{
++p;
end = "\'"; // single quote in string
p = ReadText( p, &value, false, end, false, encoding );
}
else if ( *p == DOUBLE_QUOTE )
{
++p;
end = "\""; // double quote in string
p = ReadText( p, &value, false, end, false, encoding );
}
else
{
// All attribute values should be in single or double quotes.
// But this is such a common error that the parser will try
// its best, even without them.
value = "";
while ( p && *p // existence
&& !IsWhiteSpace( *p ) && *p != '\n' && *p != '\r' // whitespace
&& *p != '/' && *p != '>' ) // tag end
{
if ( *p == SINGLE_QUOTE || *p == DOUBLE_QUOTE ) {
// [ 1451649 ] Attribute values with trailing quotes not handled correctly
// We did not have an opening quote but seem to have a
// closing one. Give up and throw an error.
if ( document ) document->SetError( TIXML_ERROR_READING_ATTRIBUTES, p, data, encoding );
return 0;
}
value += *p;
++p;
}
}
return p;
}
#ifdef TIXML_USE_STL
void TiXmlText::StreamIn( std::istream * in, TIXML_STRING * tag )
{
while ( in->good() )
{
int c = in->peek();
if ( !cdata && (c == '<' ) )
{
return;
}
if ( c <= 0 )
{
TiXmlDocument* document = GetDocument();
if ( document )
document->SetError( TIXML_ERROR_EMBEDDED_NULL, 0, 0, TIXML_ENCODING_UNKNOWN );
return;
}
(*tag) += (char) c;
in->get(); // "commits" the peek made above
if ( cdata && c == '>' && tag->size() >= 3 ) {
size_t len = tag->size();
if ( (*tag)[len-2] == ']' && (*tag)[len-3] == ']' ) {
// terminator of cdata.
return;
}
}
}
}
#endif
const char* TiXmlText::Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding )
{
value = "";
TiXmlDocument* document = GetDocument();
if ( data )
{
data->Stamp( p, encoding );
location = data->Cursor();
}
const char* const startTag = "<![CDATA[";
const char* const endTag = "]]>";
if ( cdata || StringEqual( p, startTag, false, encoding ) )
{
cdata = true;
if ( !StringEqual( p, startTag, false, encoding ) )
{
document->SetError( TIXML_ERROR_PARSING_CDATA, p, data, encoding );
return 0;
}
p += strlen( startTag );
// Keep all the white space, ignore the encoding, etc.
while ( p && *p
&& !StringEqual( p, endTag, false, encoding )
)
{
value += *p;
++p;
}
TIXML_STRING dummy;
p = ReadText( p, &dummy, false, endTag, false, encoding );
return p;
}
else
{
bool ignoreWhite = true;
const char* end = "<";
p = ReadText( p, &value, ignoreWhite, end, false, encoding );
if ( p )
return p-1; // don't truncate the '<'
return 0;
}
}
#ifdef TIXML_USE_STL
void TiXmlDeclaration::StreamIn( std::istream * in, TIXML_STRING * tag )
{
while ( in->good() )
{
int c = in->get();
if ( c <= 0 )
{
TiXmlDocument* document = GetDocument();
if ( document )
document->SetError( TIXML_ERROR_EMBEDDED_NULL, 0, 0, TIXML_ENCODING_UNKNOWN );
return;
}
(*tag) += (char) c;
if ( c == '>' )
{
// All is well.
return;
}
}
}
#endif
const char* TiXmlDeclaration::Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding _encoding )
{
p = SkipWhiteSpace( p, _encoding );
// Find the beginning, find the end, and look for
// the stuff in-between.
TiXmlDocument* document = GetDocument();
if ( !p || !*p || !StringEqual( p, "<?xml", true, _encoding ) )
{
if ( document ) document->SetError( TIXML_ERROR_PARSING_DECLARATION, 0, 0, _encoding );
return 0;
}
if ( data )
{
data->Stamp( p, _encoding );
location = data->Cursor();
}
p += 5;
version = "";
encoding = "";
standalone = "";
while ( p && *p )
{
if ( *p == '>' )
{
++p;
return p;
}
p = SkipWhiteSpace( p, _encoding );
if ( StringEqual( p, "version", true, _encoding ) )
{
TiXmlAttribute attrib;
p = attrib.Parse( p, data, _encoding );
version = attrib.Value();
}
else if ( StringEqual( p, "encoding", true, _encoding ) )
{
TiXmlAttribute attrib;
p = attrib.Parse( p, data, _encoding );
encoding = attrib.Value();
}
else if ( StringEqual( p, "standalone", true, _encoding ) )
{
TiXmlAttribute attrib;
p = attrib.Parse( p, data, _encoding );
standalone = attrib.Value();
}
else
{
// Read over whatever it is.
while( p && *p && *p != '>' && !IsWhiteSpace( *p ) )
++p;
}
}
return 0;
}
bool TiXmlText::Blank() const
{
for ( unsigned i=0; i<value.length(); i++ )
if ( !IsWhiteSpace( value[i] ) )
return false;
return true;
}
|
/*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/live/model/DescribeRoomKickoutUserListResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Live;
using namespace AlibabaCloud::Live::Model;
DescribeRoomKickoutUserListResult::DescribeRoomKickoutUserListResult() :
ServiceResult()
{}
DescribeRoomKickoutUserListResult::DescribeRoomKickoutUserListResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
DescribeRoomKickoutUserListResult::~DescribeRoomKickoutUserListResult()
{}
void DescribeRoomKickoutUserListResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
auto allUserListNode = value["UserList"]["User"];
for (auto valueUserListUser : allUserListNode)
{
User userListObject;
if(!valueUserListUser["AppUid"].isNull())
userListObject.appUid = valueUserListUser["AppUid"].asString();
if(!valueUserListUser["OpStartTime"].isNull())
userListObject.opStartTime = valueUserListUser["OpStartTime"].asString();
if(!valueUserListUser["OpEndTime"].isNull())
userListObject.opEndTime = valueUserListUser["OpEndTime"].asString();
userList_.push_back(userListObject);
}
if(!value["TotalNum"].isNull())
totalNum_ = std::stoi(value["TotalNum"].asString());
if(!value["TotalPage"].isNull())
totalPage_ = std::stoi(value["TotalPage"].asString());
}
int DescribeRoomKickoutUserListResult::getTotalNum()const
{
return totalNum_;
}
int DescribeRoomKickoutUserListResult::getTotalPage()const
{
return totalPage_;
}
std::vector<DescribeRoomKickoutUserListResult::User> DescribeRoomKickoutUserListResult::getUserList()const
{
return userList_;
}
|
/*
* Neuron.cpp
*
* Author: Nicolae Natea
*/
#include <stdint.h>
#include <assert.h>
#include <random>
#include "Neuron.hpp"
namespace BackPropagation
{
namespace
{
std::random_device g_rand_dev;
std::mt19937 mt(g_rand_dev());
std::uniform_real_distribution<double> distrib(-0.5, 0.5);
}
Neuron::Neuron(size_t nbrOfInputs, functions::Activation_function_cPtr &func) :
m_error(0.0f), m_output(0.0f), m_func(func)
{
// Check if different than the input layer.
if (nbrOfInputs)
{
m_weights.resize(nbrOfInputs);
m_momentums.resize(nbrOfInputs);
for (int i = 0; i < nbrOfInputs; i++)
{
// Initialize internal weights with a small random value
m_weights[i] = distrib(mt);
m_momentums[i] = 0.0f;
}
}
}
Neuron::~Neuron()
{
}
double Neuron::compute(const std::vector<double> &inputs)
{
size_t offset = 0;
double sum = 0.0f;
// Avoid range checks below.
assert(inputs.size() == m_weights.size());
// Naive loop seems slightly faster, but, this looks nicer
sum = std::inner_product(inputs.begin(), inputs.end(), m_weights.begin(), (double)0.0);
// Run activation function
m_output = m_func->compute(sum);
return m_output;
}
void Neuron::adjust(
double error,
const std::vector<double> &inputs,
std::vector<double> &adjustedError)
{
// Update error
m_error = m_func->derivative(m_output) * error;
// Adjust weights
{
size_t offset = 0;
// Avoid range checks below. m_momentums.size() == m_weights.size()
assert(inputs.size() == m_weights.size());
for (auto &output : inputs)
{
// Update momentum
double momentum = m_momentums[offset];
m_momentums[offset] = output * m_error;
// Update weights
m_weights[offset] += m_momentums[offset] + momentum;
// Compute input errors
adjustedError[offset] += m_weights[offset] * m_error;
++offset;
}
}
}
std::ostream& operator<<(std::ostream &output, const Neuron &neuron)
{
for (auto weight : neuron.m_weights)
{
output << weight << " ";
}
return output;
}
}
|
/**
* @file data_loader.cpp
* @author Weiqi Shen (weiqishen1994@ufl.edu)
* @brief
* @version 0.1
* @date 2019-01-29
*
* @copyright Copyright (c) 2019
*
*/
#include "data_loader.h"
#include <sys/stat.h>
data_loader::data_loader(string in_filename)
{
struct stat st = {0};
if (stat(in_filename.c_str(), &st) == -1)
Fatal_Error("data file not exist");
file_nameS = in_filename;
open_flag = false; //set open flag to false
cout << "Loading snapshot file info..." << flush;
open_file();
read_attr();
read_coord();
close_file();
cout << "done." << endl;
cout << endl;
cout << "Sampling interval: " << dt << " s" << endl;
cout << "Total number of probes: " << n_probe_data << endl;
cout << "Total number of snapshots: " << n_snap_data << endl;
cout << "Fields from data: " << fields_data << endl;
}
data_loader::~data_loader()
{
close_file();
}
void data_loader::open_file()
{
if (open_flag == true) //opened
return;
file_id = H5Fopen(file_nameS.c_str(), H5F_ACC_RDONLY, H5P_DEFAULT);
if (file_id >= 0) //success
open_flag = true;
else //failed
Fatal_Error("Failed to open file");
}
void data_loader::close_file()
{
if (open_flag) //opened
{
if (H5Fclose(file_id) >= 0) //success
open_flag = false;
else //failed
Fatal_Error("Failed to close file");
}
}
void data_loader::read_attr()
{
hid_t data_id, dt_id, fields_id, space_id;
hid_t str_ftype, str_type;
hsize_t dim[3];
char **temp_field;//char* array to hold field
//open attributions
dt_id = H5Aopen(file_id, "dt", H5P_DEFAULT);
fields_id = H5Aopen(file_id, "fields", H5P_DEFAULT);
//create memory space for fields
space_id = H5Aget_space(fields_id);
H5Sget_simple_extent_dims(space_id, dim, NULL);
H5Sclose(space_id);
fields_data.setup(dim[0]); //setup fields array
temp_field = new char *[dim[0]];
str_ftype = H5Aget_type(fields_id);
str_type = H5Tget_native_type(str_ftype, H5T_DIR_ASCEND);
//read attributes
H5Aread(dt_id, H5T_NATIVE_DOUBLE, &dt);
H5Aread(fields_id, str_type, temp_field);
H5Tclose(str_ftype);
H5Tclose(str_type);
H5Aclose(dt_id);
H5Aclose(fields_id);
//copy back to fields
for (size_t i = 0; i < size_t(dim[0]); i++)
{
fields_data(i).assign(temp_field[i]);
delete[] temp_field[i];
}
delete[] temp_field;
//set id of fields to read
if (run_input.norm_pod == SPECIFIC_TOTAL_ENTHALPY)
{
if (fields_data(0) == "rho")
field_data_id.push_back(0);
else
Fatal_Error("The first field in data file must be density!");
for (size_t i = 0; i < fields_data.get_len(); i++)
{
if (fields_data(i) == "pressure")
{
pressure_id = i;
break;
}
if (i == fields_data.get_len() - 1)
Fatal_Error("Cant find pressure field in the data!");
}
}
for (size_t i = field_data_id.size(); i < run_input.fields_pod.get_len(); i++) //loop over the pod fields
{
for (size_t j = 0; j < fields_data.get_len(); j++) //loop over the data fields
{
if (run_input.fields_pod(i) == fields_data(j) || (run_input.norm_pod==COMPRESSIBLE_ENERGY&&run_input.fields_pod(i) == "T"&&fields_data(j)=="pressure")) //found in the data file
{
field_data_id.push_back(j);
break;
}
if (j == fields_data.get_len() - 1)
Fatal_Error("Can't find the POD field in the data file!");
}
}
if (!is_sorted(field_data_id.begin(), field_data_id.end()))
Fatal_Error("Field for POD should in the same order of field in data file!");
//open dataset and read dimensions
data_id = H5Dopen2(file_id, "data", H5P_DEFAULT);
if (data_id < 0)
Fatal_Error("Failed to open dataset");
space_id = H5Dget_space(data_id);
H5Sget_simple_extent_dims(space_id, dim, NULL);
n_probe_data = dim[1];
n_snap_data = dim[2];
H5Sclose(space_id);
H5Dclose(data_id);
}
void data_loader::partial_load_data(size_t p_start, size_t n_p, size_t s_start, size_t n_s, double *out_data)
{
hid_t dataset_id, memspace_id, dataspace_id;
hsize_t dim[3]; //dimension for date of each snapshot
hsize_t count[3];
hsize_t offset[3];
ndarray<double> temp_pressure;
if (run_input.norm_pod == SPECIFIC_TOTAL_ENTHALPY)
temp_pressure.setup(n_p);
//set subset dataset to read
dim[0] = run_input.fields_pod.get_len();//dimension for each read field*point*1
dim[1] = n_p;
dim[2] = 1;
offset[1] = p_start; //offset of each slice field_i*p_0*t_i
count[0] = 1;//count of each slice 1*point*1
count[1] = n_p;
count[2] = 1;
//open dataset
dataset_id = H5Dopen2(file_id, "data", H5P_DEFAULT);
//set subset to read
memspace_id = H5Screate_simple(3, dim, NULL);
dataspace_id = H5Dget_space(dataset_id);
for (size_t i = 0; i < n_s; i++)//for each snapshot
{
H5Sselect_none(dataspace_id);
offset[2] = s_start + i;
for (auto id : field_data_id)
{
offset[0] = id;
if (H5Sselect_hyperslab(dataspace_id, H5S_SELECT_OR, offset,
NULL, count, NULL) < 0)
Fatal_Error("Failed to get hyperslab");
}
//read from dataset
if (H5Dread(dataset_id, H5T_NATIVE_DOUBLE, memspace_id, dataspace_id, H5P_DEFAULT,
out_data + dim[0]*dim[1] * i) < 0)
Fatal_Error("Failed to read subset of data");
//calculate speed of sound if norm=2
if (run_input.norm_pod == SPECIFIC_TOTAL_ENTHALPY)
{
hid_t memspace_id2;
offset[0] = pressure_id;
if (H5Sselect_hyperslab(dataspace_id, H5S_SELECT_SET, offset,
NULL, count, NULL) < 0)
Fatal_Error("Failed to get hyperslab");
//read from dataset
memspace_id2 = H5Screate_simple(3, count, NULL);
if (H5Dread(dataset_id, H5T_NATIVE_DOUBLE, memspace_id2, dataspace_id, H5P_DEFAULT,
temp_pressure.get_ptr()) < 0)
Fatal_Error("Failed to read subset of data");
for (size_t j = 0; j < n_p; j++)
out_data[j + dim[0] * dim[1] * i] = sqrt(run_input.gamma * temp_pressure(j) / out_data[j + dim[0] * dim[1] * i]);
H5Sclose(memspace_id2);
}
else if (run_input.norm_pod == COMPRESSIBLE_ENERGY)
{
//calculate temperature from pressure and temperature
for (size_t j = 0; j < n_p; j++)
out_data[j + (dim[0] - 1) * n_p+ dim[0] * dim[1] * i] /= out_data[j + dim[0] * dim[1] * i] * run_input.R_gas; //T=P/Rrho
}
}
//close objects
H5Sclose(memspace_id);
H5Sclose(dataspace_id);
H5Dclose(dataset_id);
}
void data_loader::read_coord()
{
int n_dim; //to varify coordinate array dimension
ndarray<hsize_t> dim; //coordinate array dimension
hid_t dataset_id, dataspace_id;
dataset_id = H5Dopen2(file_id, "coord", H5P_DEFAULT);
if (dataset_id < 0)
Fatal_Error("Failed to open \'coord\'");
dataspace_id = H5Dget_space(dataset_id);
n_dim = H5Sget_simple_extent_ndims(dataspace_id);
if (n_dim == 2)
dim.setup(2);
else
Fatal_Error("Invalid coordinate array!");
H5Sget_simple_extent_dims(dataspace_id, dim.get_ptr(), NULL);
coord.setup({(size_t)dim(1), (size_t)dim(0)}); //dim*n_points
if (H5Dread(dataset_id, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, coord.get_ptr()) < 0)
Fatal_Error("Failed to read subset of data");
H5Sclose(dataspace_id);
H5Dclose(dataset_id);
}
|
/*
********************************************************************************
* Copyright (C) 1999-2015 International Business Machines Corporation and
* others. All Rights Reserved.
********************************************************************************
* Date Name Description
* 10/20/99 alan Creation.
* 03/22/2000 Madhu Added additional tests
********************************************************************************
*/
#include <stdio.h>
#include <string.h>
#include "unicode/utypes.h"
#include "usettest.h"
#include "unicode/ucnv.h"
#include "unicode/uniset.h"
#include "unicode/uchar.h"
#include "unicode/usetiter.h"
#include "unicode/ustring.h"
#include "unicode/parsepos.h"
#include "unicode/symtable.h"
#include "unicode/uversion.h"
#include "hash.h"
#define TEST_ASSERT_SUCCESS(status) {if (U_FAILURE(status)) { \
dataerrln("fail in file \"%s\", line %d: \"%s\"", __FILE__, __LINE__, \
u_errorName(status));}}
#define TEST_ASSERT(expr) {if (!(expr)) { \
dataerrln("fail in file \"%s\", line %d", __FILE__, __LINE__); }}
UnicodeString operator+(const UnicodeString& left, const UnicodeSet& set) {
UnicodeString pat;
set.toPattern(pat);
return left + UnicodeSetTest::escape(pat);
}
#define CASE(id,test) case id: \
name = #test; \
if (exec) { \
logln(#test "---"); \
logln(); \
test(); \
} \
break
UnicodeSetTest::UnicodeSetTest() : utf8Cnv(NULL) {
}
UConverter *UnicodeSetTest::openUTF8Converter() {
if(utf8Cnv==NULL) {
UErrorCode errorCode=U_ZERO_ERROR;
utf8Cnv=ucnv_open("UTF-8", &errorCode);
}
return utf8Cnv;
}
UnicodeSetTest::~UnicodeSetTest() {
ucnv_close(utf8Cnv);
}
void
UnicodeSetTest::runIndexedTest(int32_t index, UBool exec,
const char* &name, char* /*par*/) {
// if (exec) logln((UnicodeString)"TestSuite UnicodeSetTest");
switch (index) {
CASE(0,TestPatterns);
CASE(1,TestAddRemove);
CASE(2,TestCategories);
CASE(3,TestCloneEqualHash);
CASE(4,TestMinimalRep);
CASE(5,TestAPI);
CASE(6,TestScriptSet);
CASE(7,TestPropertySet);
CASE(8,TestClone);
CASE(9,TestExhaustive);
CASE(10,TestToPattern);
CASE(11,TestIndexOf);
CASE(12,TestStrings);
CASE(13,Testj2268);
CASE(14,TestCloseOver);
CASE(15,TestEscapePattern);
CASE(16,TestInvalidCodePoint);
CASE(17,TestSymbolTable);
CASE(18,TestSurrogate);
CASE(19,TestPosixClasses);
CASE(20,TestIteration);
CASE(21,TestFreezable);
CASE(22,TestSpan);
CASE(23,TestStringSpan);
CASE(24,TestUCAUnsafeBackwards);
default: name = ""; break;
}
}
static const char NOT[] = "%%%%";
/**
* UVector was improperly copying contents
* This code will crash this is still true
*/
void UnicodeSetTest::Testj2268() {
UnicodeSet t;
t.add(UnicodeString("abc"));
UnicodeSet test(t);
UnicodeString ustrPat;
test.toPattern(ustrPat, TRUE);
}
/**
* Test toPattern().
*/
void UnicodeSetTest::TestToPattern() {
UErrorCode ec = U_ZERO_ERROR;
// Test that toPattern() round trips with syntax characters and
// whitespace.
{
static const char* OTHER_TOPATTERN_TESTS[] = {
"[[:latin:]&[:greek:]]",
"[[:latin:]-[:greek:]]",
"[:nonspacing mark:]",
NULL
};
for (int32_t j=0; OTHER_TOPATTERN_TESTS[j]!=NULL; ++j) {
ec = U_ZERO_ERROR;
UnicodeSet s(OTHER_TOPATTERN_TESTS[j], ec);
if (U_FAILURE(ec)) {
dataerrln((UnicodeString)"FAIL: bad pattern " + OTHER_TOPATTERN_TESTS[j] + " - " + UnicodeString(u_errorName(ec)));
continue;
}
checkPat(OTHER_TOPATTERN_TESTS[j], s);
}
for (UChar32 i = 0; i <= 0x10FFFF; ++i) {
if ((i <= 0xFF && !u_isalpha(i)) || u_isspace(i)) {
// check various combinations to make sure they all work.
if (i != 0 && !toPatternAux(i, i)){
continue;
}
if (!toPatternAux(0, i)){
continue;
}
if (!toPatternAux(i, 0xFFFF)){
continue;
}
}
}
}
// Test pattern behavior of multicharacter strings.
{
ec = U_ZERO_ERROR;
UnicodeSet* s = new UnicodeSet("[a-z {aa} {ab}]", ec);
// This loop isn't a loop. It's here to make the compiler happy.
// If you're curious, try removing it and changing the 'break'
// statements (except for the last) to goto's.
for (;;) {
if (U_FAILURE(ec)) break;
const char* exp1[] = {"aa", "ab", NOT, "ac", NULL};
expectToPattern(*s, "[a-z{aa}{ab}]", exp1);
s->add("ac");
const char* exp2[] = {"aa", "ab", "ac", NOT, "xy", NULL};
expectToPattern(*s, "[a-z{aa}{ab}{ac}]", exp2);
s->applyPattern(UNICODE_STRING_SIMPLE("[a-z {\\{l} {r\\}}]"), ec);
if (U_FAILURE(ec)) break;
const char* exp3[] = {"{l", "r}", NOT, "xy", NULL};
expectToPattern(*s, UNICODE_STRING_SIMPLE("[a-z{r\\}}{\\{l}]"), exp3);
s->add("[]");
const char* exp4[] = {"{l", "r}", "[]", NOT, "xy", NULL};
expectToPattern(*s, UNICODE_STRING_SIMPLE("[a-z{\\[\\]}{r\\}}{\\{l}]"), exp4);
s->applyPattern(UNICODE_STRING_SIMPLE("[a-z {\\u4E01\\u4E02}{\\n\\r}]"), ec);
if (U_FAILURE(ec)) break;
const char* exp5[] = {"\\u4E01\\u4E02", "\n\r", NULL};
expectToPattern(*s, UNICODE_STRING_SIMPLE("[a-z{\\u000A\\u000D}{\\u4E01\\u4E02}]"), exp5);
// j2189
s->clear();
s->add(UnicodeString("abc", ""));
s->add(UnicodeString("abc", ""));
const char* exp6[] = {"abc", NOT, "ab", NULL};
expectToPattern(*s, "[{abc}]", exp6);
break;
}
if (U_FAILURE(ec)) errln("FAIL: pattern parse error");
delete s;
}
// JB#3400: For 2 character ranges prefer [ab] to [a-b]
UnicodeSet s;
s.add((UChar)97, (UChar)98); // 'a', 'b'
expectToPattern(s, "[ab]", NULL);
}
UBool UnicodeSetTest::toPatternAux(UChar32 start, UChar32 end) {
// use Integer.toString because Utility.hex doesn't handle ints
UnicodeString pat = "";
// TODO do these in hex
//String source = "0x" + Integer.toString(start,16).toUpperCase();
//if (start != end) source += "..0x" + Integer.toString(end,16).toUpperCase();
UnicodeString source;
source = source + (uint32_t)start;
if (start != end)
source = source + ".." + (uint32_t)end;
UnicodeSet testSet;
testSet.add(start, end);
return checkPat(source, testSet);
}
UBool UnicodeSetTest::checkPat(const UnicodeString& source,
const UnicodeSet& testSet) {
// What we want to make sure of is that a pattern generated
// by toPattern(), with or without escaped unprintables, can
// be passed back into the UnicodeSet constructor.
UnicodeString pat0;
testSet.toPattern(pat0, TRUE);
if (!checkPat(source + " (escaped)", testSet, pat0)) return FALSE;
//String pat1 = unescapeLeniently(pat0);
//if (!checkPat(source + " (in code)", testSet, pat1)) return false;
UnicodeString pat2;
testSet.toPattern(pat2, FALSE);
if (!checkPat(source, testSet, pat2)) return FALSE;
//String pat3 = unescapeLeniently(pat2);
// if (!checkPat(source + " (in code)", testSet, pat3)) return false;
//logln(source + " => " + pat0 + ", " + pat1 + ", " + pat2 + ", " + pat3);
logln((UnicodeString)source + " => " + pat0 + ", " + pat2);
return TRUE;
}
UBool UnicodeSetTest::checkPat(const UnicodeString& source,
const UnicodeSet& testSet,
const UnicodeString& pat) {
UErrorCode ec = U_ZERO_ERROR;
UnicodeSet testSet2(pat, ec);
if (testSet2 != testSet) {
errln((UnicodeString)"Fail toPattern: " + source + " => " + pat);
return FALSE;
}
return TRUE;
}
void
UnicodeSetTest::TestPatterns(void) {
UnicodeSet set;
expectPattern(set, UnicodeString("[[a-m]&[d-z]&[k-y]]", ""), "km");
expectPattern(set, UnicodeString("[[a-z]-[m-y]-[d-r]]", ""), "aczz");
expectPattern(set, UnicodeString("[a\\-z]", ""), "--aazz");
expectPattern(set, UnicodeString("[-az]", ""), "--aazz");
expectPattern(set, UnicodeString("[az-]", ""), "--aazz");
expectPattern(set, UnicodeString("[[[a-z]-[aeiou]i]]", ""), "bdfnptvz");
// Throw in a test of complement
set.complement();
UnicodeString exp;
exp.append((UChar)0x0000).append("aeeoouu").append((UChar)(0x007a+1)).append((UChar)0xFFFF);
expectPairs(set, exp);
}
void
UnicodeSetTest::TestCategories(void) {
UErrorCode status = U_ZERO_ERROR;
const char* pat = " [:Lu:] "; // Whitespace ok outside [:..:]
UnicodeSet set(pat, status);
if (U_FAILURE(status)) {
dataerrln((UnicodeString)"Fail: Can't construct set with " + pat + " - " + UnicodeString(u_errorName(status)));
return;
} else {
expectContainment(set, pat, "ABC", "abc");
}
UChar32 i;
int32_t failures = 0;
// Make sure generation of L doesn't pollute cached Lu set
// First generate L, then Lu
set.applyPattern("[:L:]", status);
if (U_FAILURE(status)) { errln("FAIL"); return; }
for (i=0; i<0x200; ++i) {
UBool l = u_isalpha((UChar)i);
if (l != set.contains(i)) {
errln((UnicodeString)"FAIL: L contains " + (unsigned short)i + " = " +
set.contains(i));
if (++failures == 10) break;
}
}
set.applyPattern("[:Lu:]", status);
if (U_FAILURE(status)) { errln("FAIL"); return; }
for (i=0; i<0x200; ++i) {
UBool lu = (u_charType((UChar)i) == U_UPPERCASE_LETTER);
if (lu != set.contains(i)) {
errln((UnicodeString)"FAIL: Lu contains " + (unsigned short)i + " = " +
set.contains(i));
if (++failures == 20) break;
}
}
}
void
UnicodeSetTest::TestCloneEqualHash(void) {
UErrorCode status = U_ZERO_ERROR;
// set1 and set2 used to be built with the obsolete constructor taking
// UCharCategory values; replaced with pattern constructors
// markus 20030502
UnicodeSet *set1=new UnicodeSet(UNICODE_STRING_SIMPLE("\\p{Lowercase Letter}"), status); // :Ll: Letter, lowercase
UnicodeSet *set1a=new UnicodeSet(UNICODE_STRING_SIMPLE("[:Ll:]"), status); // Letter, lowercase
if (U_FAILURE(status)){
dataerrln((UnicodeString)"FAIL: Can't construst set with category->Ll" + " - " + UnicodeString(u_errorName(status)));
return;
}
UnicodeSet *set2=new UnicodeSet(UNICODE_STRING_SIMPLE("\\p{Decimal Number}"), status); //Number, Decimal digit
UnicodeSet *set2a=new UnicodeSet(UNICODE_STRING_SIMPLE("[:Nd:]"), status); //Number, Decimal digit
if (U_FAILURE(status)){
errln((UnicodeString)"FAIL: Can't construct set with category->Nd");
return;
}
if (*set1 != *set1a) {
errln("FAIL: category constructor for Ll broken");
}
if (*set2 != *set2a) {
errln("FAIL: category constructor for Nd broken");
}
delete set1a;
delete set2a;
logln("Testing copy construction");
UnicodeSet *set1copy=new UnicodeSet(*set1);
if(*set1 != *set1copy || *set1 == *set2 ||
getPairs(*set1) != getPairs(*set1copy) ||
set1->hashCode() != set1copy->hashCode()){
errln("FAIL : Error in copy construction");
return;
}
logln("Testing =operator");
UnicodeSet set1equal=*set1;
UnicodeSet set2equal=*set2;
if(set1equal != *set1 || set1equal != *set1copy || set2equal != *set2 ||
set2equal == *set1 || set2equal == *set1copy || set2equal == set1equal){
errln("FAIL: Error in =operator");
}
logln("Testing clone()");
UnicodeSet *set1clone=(UnicodeSet*)set1->clone();
UnicodeSet *set2clone=(UnicodeSet*)set2->clone();
if(*set1clone != *set1 || *set1clone != *set1copy || *set1clone != set1equal ||
*set2clone != *set2 || *set2clone == *set1copy || *set2clone != set2equal ||
*set2clone == *set1 || *set2clone == set1equal || *set2clone == *set1clone){
errln("FAIL: Error in clone");
}
logln("Testing hashcode");
if(set1->hashCode() != set1equal.hashCode() || set1->hashCode() != set1clone->hashCode() ||
set2->hashCode() != set2equal.hashCode() || set2->hashCode() != set2clone->hashCode() ||
set1copy->hashCode() != set1equal.hashCode() || set1copy->hashCode() != set1clone->hashCode() ||
set1->hashCode() == set2->hashCode() || set1copy->hashCode() == set2->hashCode() ||
set2->hashCode() == set1clone->hashCode() || set2->hashCode() == set1equal.hashCode() ){
errln("FAIL: Error in hashCode()");
}
delete set1;
delete set1copy;
delete set2;
delete set1clone;
delete set2clone;
}
void
UnicodeSetTest::TestAddRemove(void) {
UnicodeSet set; // Construct empty set
doAssert(set.isEmpty() == TRUE, "set should be empty");
doAssert(set.size() == 0, "size should be 0");
set.complement();
doAssert(set.size() == 0x110000, "size should be 0x110000");
set.clear();
set.add(0x0061, 0x007a);
expectPairs(set, "az");
doAssert(set.isEmpty() == FALSE, "set should not be empty");
doAssert(set.size() != 0, "size should not be equal to 0");
doAssert(set.size() == 26, "size should be equal to 26");
set.remove(0x006d, 0x0070);
expectPairs(set, "alqz");
doAssert(set.size() == 22, "size should be equal to 22");
set.remove(0x0065, 0x0067);
expectPairs(set, "adhlqz");
doAssert(set.size() == 19, "size should be equal to 19");
set.remove(0x0064, 0x0069);
expectPairs(set, "acjlqz");
doAssert(set.size() == 16, "size should be equal to 16");
set.remove(0x0063, 0x0072);
expectPairs(set, "absz");
doAssert(set.size() == 10, "size should be equal to 10");
set.add(0x0066, 0x0071);
expectPairs(set, "abfqsz");
doAssert(set.size() == 22, "size should be equal to 22");
set.remove(0x0061, 0x0067);
expectPairs(set, "hqsz");
set.remove(0x0061, 0x007a);
expectPairs(set, "");
doAssert(set.isEmpty() == TRUE, "set should be empty");
doAssert(set.size() == 0, "size should be 0");
set.add(0x0061);
doAssert(set.isEmpty() == FALSE, "set should not be empty");
doAssert(set.size() == 1, "size should not be equal to 1");
set.add(0x0062);
set.add(0x0063);
expectPairs(set, "ac");
doAssert(set.size() == 3, "size should not be equal to 3");
set.add(0x0070);
set.add(0x0071);
expectPairs(set, "acpq");
doAssert(set.size() == 5, "size should not be equal to 5");
set.clear();
expectPairs(set, "");
doAssert(set.isEmpty() == TRUE, "set should be empty");
doAssert(set.size() == 0, "size should be 0");
// Try removing an entire set from another set
expectPattern(set, "[c-x]", "cx");
UnicodeSet set2;
expectPattern(set2, "[f-ky-za-bc[vw]]", "acfkvwyz");
set.removeAll(set2);
expectPairs(set, "deluxx");
// Try adding an entire set to another set
expectPattern(set, "[jackiemclean]", "aacceein");
expectPattern(set2, "[hitoshinamekatajamesanderson]", "aadehkmort");
set.addAll(set2);
expectPairs(set, "aacehort");
doAssert(set.containsAll(set2) == TRUE, "set should contain all the elements in set2");
// Try retaining an set of elements contained in another set (intersection)
UnicodeSet set3;
expectPattern(set3, "[a-c]", "ac");
doAssert(set.containsAll(set3) == FALSE, "set doesn't contain all the elements in set3");
set3.remove(0x0062);
expectPairs(set3, "aacc");
doAssert(set.containsAll(set3) == TRUE, "set should contain all the elements in set3");
set.retainAll(set3);
expectPairs(set, "aacc");
doAssert(set.size() == set3.size(), "set.size() should be set3.size()");
doAssert(set.containsAll(set3) == TRUE, "set should contain all the elements in set3");
set.clear();
doAssert(set.size() != set3.size(), "set.size() != set3.size()");
// Test commutativity
expectPattern(set, "[hitoshinamekatajamesanderson]", "aadehkmort");
expectPattern(set2, "[jackiemclean]", "aacceein");
set.addAll(set2);
expectPairs(set, "aacehort");
doAssert(set.containsAll(set2) == TRUE, "set should contain all the elements in set2");
}
/**
* Make sure minimal representation is maintained.
*/
void UnicodeSetTest::TestMinimalRep() {
UErrorCode status = U_ZERO_ERROR;
// This is pretty thoroughly tested by checkCanonicalRep()
// run against the exhaustive operation results. Use the code
// here for debugging specific spot problems.
// 1 overlap against 2
UnicodeSet set("[h-km-q]", status);
if (U_FAILURE(status)) { errln("FAIL"); return; }
UnicodeSet set2("[i-o]", status);
if (U_FAILURE(status)) { errln("FAIL"); return; }
set.addAll(set2);
expectPairs(set, "hq");
// right
set.applyPattern("[a-m]", status);
if (U_FAILURE(status)) { errln("FAIL"); return; }
set2.applyPattern("[e-o]", status);
if (U_FAILURE(status)) { errln("FAIL"); return; }
set.addAll(set2);
expectPairs(set, "ao");
// left
set.applyPattern("[e-o]", status);
if (U_FAILURE(status)) { errln("FAIL"); return; }
set2.applyPattern("[a-m]", status);
if (U_FAILURE(status)) { errln("FAIL"); return; }
set.addAll(set2);
expectPairs(set, "ao");
// 1 overlap against 3
set.applyPattern("[a-eg-mo-w]", status);
if (U_FAILURE(status)) { errln("FAIL"); return; }
set2.applyPattern("[d-q]", status);
if (U_FAILURE(status)) { errln("FAIL"); return; }
set.addAll(set2);
expectPairs(set, "aw");
}
void UnicodeSetTest::TestAPI() {
UErrorCode status = U_ZERO_ERROR;
// default ct
UnicodeSet set;
if (!set.isEmpty() || set.getRangeCount() != 0) {
errln((UnicodeString)"FAIL, set should be empty but isn't: " +
set);
}
// clear(), isEmpty()
set.add(0x0061);
if (set.isEmpty()) {
errln((UnicodeString)"FAIL, set shouldn't be empty but is: " +
set);
}
set.clear();
if (!set.isEmpty()) {
errln((UnicodeString)"FAIL, set should be empty but isn't: " +
set);
}
// size()
set.clear();
if (set.size() != 0) {
errln((UnicodeString)"FAIL, size should be 0, but is " + set.size() +
": " + set);
}
set.add(0x0061);
if (set.size() != 1) {
errln((UnicodeString)"FAIL, size should be 1, but is " + set.size() +
": " + set);
}
set.add(0x0031, 0x0039);
if (set.size() != 10) {
errln((UnicodeString)"FAIL, size should be 10, but is " + set.size() +
": " + set);
}
// contains(first, last)
set.clear();
set.applyPattern("[A-Y 1-8 b-d l-y]", status);
if (U_FAILURE(status)) { errln("FAIL"); return; }
for (int32_t i = 0; i<set.getRangeCount(); ++i) {
UChar32 a = set.getRangeStart(i);
UChar32 b = set.getRangeEnd(i);
if (!set.contains(a, b)) {
errln((UnicodeString)"FAIL, should contain " + (unsigned short)a + '-' + (unsigned short)b +
" but doesn't: " + set);
}
if (set.contains((UChar32)(a-1), b)) {
errln((UnicodeString)"FAIL, shouldn't contain " +
(unsigned short)(a-1) + '-' + (unsigned short)b +
" but does: " + set);
}
if (set.contains(a, (UChar32)(b+1))) {
errln((UnicodeString)"FAIL, shouldn't contain " +
(unsigned short)a + '-' + (unsigned short)(b+1) +
" but does: " + set);
}
}
// Ported InversionList test.
UnicodeSet a((UChar32)3,(UChar32)10);
UnicodeSet b((UChar32)7,(UChar32)15);
UnicodeSet c;
logln((UnicodeString)"a [3-10]: " + a);
logln((UnicodeString)"b [7-15]: " + b);
c = a;
c.addAll(b);
UnicodeSet exp((UChar32)3,(UChar32)15);
if (c == exp) {
logln((UnicodeString)"c.set(a).add(b): " + c);
} else {
errln((UnicodeString)"FAIL: c.set(a).add(b) = " + c + ", expect " + exp);
}
c.complement();
exp.set((UChar32)0, (UChar32)2);
exp.add((UChar32)16, UnicodeSet::MAX_VALUE);
if (c == exp) {
logln((UnicodeString)"c.complement(): " + c);
} else {
errln((UnicodeString)"FAIL: c.complement() = " + c + ", expect " + exp);
}
c.complement();
exp.set((UChar32)3, (UChar32)15);
if (c == exp) {
logln((UnicodeString)"c.complement(): " + c);
} else {
errln((UnicodeString)"FAIL: c.complement() = " + c + ", expect " + exp);
}
c = a;
c.complementAll(b);
exp.set((UChar32)3,(UChar32)6);
exp.add((UChar32)11,(UChar32) 15);
if (c == exp) {
logln((UnicodeString)"c.set(a).exclusiveOr(b): " + c);
} else {
errln((UnicodeString)"FAIL: c.set(a).exclusiveOr(b) = " + c + ", expect " + exp);
}
exp = c;
bitsToSet(setToBits(c), c);
if (c == exp) {
logln((UnicodeString)"bitsToSet(setToBits(c)): " + c);
} else {
errln((UnicodeString)"FAIL: bitsToSet(setToBits(c)) = " + c + ", expect " + exp);
}
// Additional tests for coverage JB#2118
//UnicodeSet::complement(class UnicodeString const &)
//UnicodeSet::complementAll(class UnicodeString const &)
//UnicodeSet::containsNone(class UnicodeSet const &)
//UnicodeSet::containsNone(long,long)
//UnicodeSet::containsSome(class UnicodeSet const &)
//UnicodeSet::containsSome(long,long)
//UnicodeSet::removeAll(class UnicodeString const &)
//UnicodeSet::retain(long)
//UnicodeSet::retainAll(class UnicodeString const &)
//UnicodeSet::serialize(unsigned short *,long,enum UErrorCode &)
//UnicodeSetIterator::getString(void)
set.clear();
set.complement("ab");
exp.applyPattern("[{ab}]", status);
if (U_FAILURE(status)) { errln("FAIL"); return; }
if (set != exp) { errln("FAIL: complement(\"ab\")"); return; }
UnicodeSetIterator iset(set);
if (!iset.next() || !iset.isString()) {
errln("FAIL: UnicodeSetIterator::next/isString");
} else if (iset.getString() != "ab") {
errln("FAIL: UnicodeSetIterator::getString");
}
set.add((UChar32)0x61, (UChar32)0x7A);
set.complementAll("alan");
exp.applyPattern("[{ab}b-kmo-z]", status);
if (U_FAILURE(status)) { errln("FAIL"); return; }
if (set != exp) { errln("FAIL: complementAll(\"alan\")"); return; }
exp.applyPattern("[a-z]", status);
if (U_FAILURE(status)) { errln("FAIL"); return; }
if (set.containsNone(exp)) { errln("FAIL: containsNone(UnicodeSet)"); }
if (!set.containsSome(exp)) { errln("FAIL: containsSome(UnicodeSet)"); }
exp.applyPattern("[aln]", status);
if (U_FAILURE(status)) { errln("FAIL"); return; }
if (!set.containsNone(exp)) { errln("FAIL: containsNone(UnicodeSet)"); }
if (set.containsSome(exp)) { errln("FAIL: containsSome(UnicodeSet)"); }
if (set.containsNone((UChar32)0x61, (UChar32)0x7A)) {
errln("FAIL: containsNone(UChar32, UChar32)");
}
if (!set.containsSome((UChar32)0x61, (UChar32)0x7A)) {
errln("FAIL: containsSome(UChar32, UChar32)");
}
if (!set.containsNone((UChar32)0x41, (UChar32)0x5A)) {
errln("FAIL: containsNone(UChar32, UChar32)");
}
if (set.containsSome((UChar32)0x41, (UChar32)0x5A)) {
errln("FAIL: containsSome(UChar32, UChar32)");
}
set.removeAll("liu");
exp.applyPattern("[{ab}b-hj-kmo-tv-z]", status);
if (U_FAILURE(status)) { errln("FAIL"); return; }
if (set != exp) { errln("FAIL: removeAll(\"liu\")"); return; }
set.retainAll("star");
exp.applyPattern("[rst]", status);
if (U_FAILURE(status)) { errln("FAIL"); return; }
if (set != exp) { errln("FAIL: retainAll(\"star\")"); return; }
set.retain((UChar32)0x73);
exp.applyPattern("[s]", status);
if (U_FAILURE(status)) { errln("FAIL"); return; }
if (set != exp) { errln("FAIL: retain('s')"); return; }
uint16_t buf[32];
int32_t slen = set.serialize(buf, sizeof(buf)/sizeof(buf[0]), status);
if (U_FAILURE(status)) { errln("FAIL: serialize"); return; }
if (slen != 3 || buf[0] != 2 || buf[1] != 0x73 || buf[2] != 0x74) {
errln("FAIL: serialize");
return;
}
// Conversions to and from USet
UnicodeSet *uniset = &set;
USet *uset = uniset->toUSet();
TEST_ASSERT((void *)uset == (void *)uniset);
UnicodeSet *setx = UnicodeSet::fromUSet(uset);
TEST_ASSERT((void *)setx == (void *)uset);
const UnicodeSet *constSet = uniset;
const USet *constUSet = constSet->toUSet();
TEST_ASSERT((void *)constUSet == (void *)constSet);
const UnicodeSet *constSetx = UnicodeSet::fromUSet(constUSet);
TEST_ASSERT((void *)constSetx == (void *)constUSet);
// span(UnicodeString) and spanBack(UnicodeString) convenience methods
UnicodeString longString=UNICODE_STRING_SIMPLE("aaaaaaaaaabbbbbbbbbbcccccccccc");
UnicodeSet ac(0x61, 0x63);
ac.remove(0x62).freeze();
if( ac.span(longString, -5, USET_SPAN_CONTAINED)!=10 ||
ac.span(longString, 0, USET_SPAN_CONTAINED)!=10 ||
ac.span(longString, 5, USET_SPAN_CONTAINED)!=10 ||
ac.span(longString, 10, USET_SPAN_CONTAINED)!=10 ||
ac.span(longString, 15, USET_SPAN_CONTAINED)!=15 ||
ac.span(longString, 20, USET_SPAN_CONTAINED)!=30 ||
ac.span(longString, 25, USET_SPAN_CONTAINED)!=30 ||
ac.span(longString, 30, USET_SPAN_CONTAINED)!=30 ||
ac.span(longString, 35, USET_SPAN_CONTAINED)!=30 ||
ac.span(longString, INT32_MAX, USET_SPAN_CONTAINED)!=30
) {
errln("UnicodeSet.span(UnicodeString, ...) returns incorrect end indexes");
}
if( ac.spanBack(longString, -5, USET_SPAN_CONTAINED)!=0 ||
ac.spanBack(longString, 0, USET_SPAN_CONTAINED)!=0 ||
ac.spanBack(longString, 5, USET_SPAN_CONTAINED)!=0 ||
ac.spanBack(longString, 10, USET_SPAN_CONTAINED)!=0 ||
ac.spanBack(longString, 15, USET_SPAN_CONTAINED)!=15 ||
ac.spanBack(longString, 20, USET_SPAN_CONTAINED)!=20 ||
ac.spanBack(longString, 25, USET_SPAN_CONTAINED)!=20 ||
ac.spanBack(longString, 30, USET_SPAN_CONTAINED)!=20 ||
ac.spanBack(longString, 35, USET_SPAN_CONTAINED)!=20 ||
ac.spanBack(longString, INT32_MAX, USET_SPAN_CONTAINED)!=20
) {
errln("UnicodeSet.spanBack(UnicodeString, ...) returns incorrect start indexes");
}
}
void UnicodeSetTest::TestIteration() {
UErrorCode ec = U_ZERO_ERROR;
int i = 0;
int outerLoop;
// 6 code points, 3 ranges, 2 strings, 8 total elements
// Iteration will access them in sorted order - a, b, c, y, z, U0001abcd, "str1", "str2"
UnicodeSet set(UNICODE_STRING_SIMPLE("[zabyc\\U0001abcd{str1}{str2}]"), ec);
TEST_ASSERT_SUCCESS(ec);
UnicodeSetIterator it(set);
for (outerLoop=0; outerLoop<3; outerLoop++) {
// Run the test multiple times, to check that iterator.reset() is working.
for (i=0; i<10; i++) {
UBool nextv = it.next();
UBool isString = it.isString();
int32_t codePoint = it.getCodepoint();
//int32_t codePointEnd = it.getCodepointEnd();
UnicodeString s = it.getString();
switch (i) {
case 0:
TEST_ASSERT(nextv == TRUE);
TEST_ASSERT(isString == FALSE);
TEST_ASSERT(codePoint==0x61);
TEST_ASSERT(s == "a");
break;
case 1:
TEST_ASSERT(nextv == TRUE);
TEST_ASSERT(isString == FALSE);
TEST_ASSERT(codePoint==0x62);
TEST_ASSERT(s == "b");
break;
case 2:
TEST_ASSERT(nextv == TRUE);
TEST_ASSERT(isString == FALSE);
TEST_ASSERT(codePoint==0x63);
TEST_ASSERT(s == "c");
break;
case 3:
TEST_ASSERT(nextv == TRUE);
TEST_ASSERT(isString == FALSE);
TEST_ASSERT(codePoint==0x79);
TEST_ASSERT(s == "y");
break;
case 4:
TEST_ASSERT(nextv == TRUE);
TEST_ASSERT(isString == FALSE);
TEST_ASSERT(codePoint==0x7a);
TEST_ASSERT(s == "z");
break;
case 5:
TEST_ASSERT(nextv == TRUE);
TEST_ASSERT(isString == FALSE);
TEST_ASSERT(codePoint==0x1abcd);
TEST_ASSERT(s == UnicodeString((UChar32)0x1abcd));
break;
case 6:
TEST_ASSERT(nextv == TRUE);
TEST_ASSERT(isString == TRUE);
TEST_ASSERT(s == "str1");
break;
case 7:
TEST_ASSERT(nextv == TRUE);
TEST_ASSERT(isString == TRUE);
TEST_ASSERT(s == "str2");
break;
case 8:
TEST_ASSERT(nextv == FALSE);
break;
case 9:
TEST_ASSERT(nextv == FALSE);
break;
}
}
it.reset(); // prepare to run the iteration again.
}
}
void UnicodeSetTest::TestStrings() {
UErrorCode ec = U_ZERO_ERROR;
UnicodeSet* testList[] = {
UnicodeSet::createFromAll("abc"),
new UnicodeSet("[a-c]", ec),
&(UnicodeSet::createFrom("ch")->add('a','z').add("ll")),
new UnicodeSet("[{ll}{ch}a-z]", ec),
UnicodeSet::createFrom("ab}c"),
new UnicodeSet("[{ab\\}c}]", ec),
&((new UnicodeSet('a','z'))->add('A', 'Z').retain('M','m').complement('X')),
new UnicodeSet("[[a-zA-Z]&[M-m]-[X]]", ec),
NULL
};
if (U_FAILURE(ec)) {
errln("FAIL: couldn't construct test sets");
}
for (int32_t i = 0; testList[i] != NULL; i+=2) {
if (U_SUCCESS(ec)) {
UnicodeString pat0, pat1;
testList[i]->toPattern(pat0, TRUE);
testList[i+1]->toPattern(pat1, TRUE);
if (*testList[i] == *testList[i+1]) {
logln((UnicodeString)"Ok: " + pat0 + " == " + pat1);
} else {
logln((UnicodeString)"FAIL: " + pat0 + " != " + pat1);
}
}
delete testList[i];
delete testList[i+1];
}
}
/**
* Test the [:Latin:] syntax.
*/
void UnicodeSetTest::TestScriptSet() {
expectContainment(UNICODE_STRING_SIMPLE("[:Latin:]"), "aA", CharsToUnicodeString("\\u0391\\u03B1"));
expectContainment(UNICODE_STRING_SIMPLE("[:Greek:]"), CharsToUnicodeString("\\u0391\\u03B1"), "aA");
/* Jitterbug 1423 */
expectContainment(UNICODE_STRING_SIMPLE("[[:Common:][:Inherited:]]"), CharsToUnicodeString("\\U00003099\\U0001D169\\u0000"), "aA");
}
/**
* Test the [:Latin:] syntax.
*/
void UnicodeSetTest::TestPropertySet() {
static const char* const DATA[] = {
// Pattern, Chars IN, Chars NOT in
"[:Latin:]",
"aA",
"\\u0391\\u03B1",
"[\\p{Greek}]",
"\\u0391\\u03B1",
"aA",
"\\P{ GENERAL Category = upper case letter }",
"abc",
"ABC",
#if !UCONFIG_NO_NORMALIZATION
// Combining class: @since ICU 2.2
// Check both symbolic and numeric
"\\p{ccc=Nukta}",
"\\u0ABC",
"abc",
"\\p{Canonical Combining Class = 11}",
"\\u05B1",
"\\u05B2",
"[:c c c = iota subscript :]",
"\\u0345",
"xyz",
#endif
// Bidi class: @since ICU 2.2
"\\p{bidiclass=lefttoright}",
"abc",
"\\u0671\\u0672",
// Binary properties: @since ICU 2.2
"\\p{ideographic}",
"\\u4E0A",
"x",
"[:math=false:]",
"q)*(",
// weiv: )(and * were removed from math in Unicode 4.0.1
//"(*+)",
"+<>^",
// JB#1767 \N{}, \p{ASCII}
"[:Ascii:]",
"abc\\u0000\\u007F",
"\\u0080\\u4E00",
"[\\N{ latin small letter a }[:name= latin small letter z:]]",
"az",
"qrs",
// JB#2015
"[:any:]",
"a\\U0010FFFF",
"",
"[:nv=0.5:]",
"\\u00BD\\u0F2A",
"\\u00BC",
// JB#2653: Age
"[:Age=1.1:]",
"\\u03D6", // 1.1
"\\u03D8\\u03D9", // 3.2
"[:Age=3.1:]",
"\\u1800\\u3400\\U0002f800",
"\\u0220\\u034f\\u30ff\\u33ff\\ufe73\\U00010000\\U00050000",
// JB#2350: Case_Sensitive
"[:Case Sensitive:]",
"A\\u1FFC\\U00010410",
";\\u00B4\\U00010500",
// JB#2832: C99-compatibility props
"[:blank:]",
" \\u0009",
"1-9A-Z",
"[:graph:]",
"19AZ",
" \\u0003\\u0007\\u0009\\u000A\\u000D",
"[:punct:]",
"!@#%&*()[]{}-_\\/;:,.?'\"",
"09azAZ",
"[:xdigit:]",
"09afAF",
"gG!",
// Regex compatibility test
"[-b]", // leading '-' is literal
"-b",
"ac",
"[^-b]", // leading '-' is literal
"ac",
"-b",
"[b-]", // trailing '-' is literal
"-b",
"ac",
"[^b-]", // trailing '-' is literal
"ac",
"-b",
"[a-b-]", // trailing '-' is literal
"ab-",
"c=",
"[[a-q]&[p-z]-]", // trailing '-' is literal
"pq-",
"or=",
"[\\s|\\)|:|$|\\>]", // from regex tests
"s|):$>",
"abc",
"[\\uDC00cd]", // JB#2906: isolated trail at start
"cd\\uDC00",
"ab\\uD800\\U00010000",
"[ab\\uD800]", // JB#2906: isolated trail at start
"ab\\uD800",
"cd\\uDC00\\U00010000",
"[ab\\uD800cd]", // JB#2906: isolated lead in middle
"abcd\\uD800",
"ef\\uDC00\\U00010000",
"[ab\\uDC00cd]", // JB#2906: isolated trail in middle
"abcd\\uDC00",
"ef\\uD800\\U00010000",
#if !UCONFIG_NO_NORMALIZATION
"[:^lccc=0:]", // Lead canonical class
"\\u0300\\u0301",
"abcd\\u00c0\\u00c5",
"[:^tccc=0:]", // Trail canonical class
"\\u0300\\u0301\\u00c0\\u00c5",
"abcd",
"[[:^lccc=0:][:^tccc=0:]]", // Lead and trail canonical class
"\\u0300\\u0301\\u00c0\\u00c5",
"abcd",
"[[:^lccc=0:]-[:^tccc=0:]]", // Stuff that starts with an accent but ends with a base (none right now)
"",
"abcd\\u0300\\u0301\\u00c0\\u00c5",
"[[:ccc=0:]-[:lccc=0:]-[:tccc=0:]]", // Weirdos. Complete canonical class is zero, but both lead and trail are not
"\\u0F73\\u0F75\\u0F81",
"abcd\\u0300\\u0301\\u00c0\\u00c5",
#endif /* !UCONFIG_NO_NORMALIZATION */
"[:Assigned:]",
"A\\uE000\\uF8FF\\uFDC7\\U00010000\\U0010FFFD",
"\\u0888\\uFDD3\\uFFFE\\U00050005",
// Script_Extensions, new in Unicode 6.0
"[:scx=Arab:]",
"\\u061E\\u061F\\u0620\\u0621\\u063F\\u0640\\u0650\\u065E\\uFDF1\\uFDF2\\uFDF3",
"\\u061D\\uFDEF\\uFDFE",
// U+FDF2 has Script=Arabic and also Arab in its Script_Extensions,
// so scx-sc is missing U+FDF2.
"[[:Script_Extensions=Arabic:]-[:Arab:]]",
"\\u0640\\u064B\\u0650\\u0655",
"\\uFDF2"
};
static const int32_t DATA_LEN = sizeof(DATA)/sizeof(DATA[0]);
for (int32_t i=0; i<DATA_LEN; i+=3) {
expectContainment(UnicodeString(DATA[i], -1, US_INV), CharsToUnicodeString(DATA[i+1]),
CharsToUnicodeString(DATA[i+2]));
}
}
/**
* Test that Posix style character classes [:digit:], etc.
* have the Unicode definitions from TR 18.
*/
void UnicodeSetTest::TestPosixClasses() {
{
UErrorCode status = U_ZERO_ERROR;
UnicodeSet s1("[:alpha:]", status);
UnicodeSet s2(UNICODE_STRING_SIMPLE("\\p{Alphabetic}"), status);
TEST_ASSERT_SUCCESS(status);
TEST_ASSERT(s1==s2);
}
{
UErrorCode status = U_ZERO_ERROR;
UnicodeSet s1("[:lower:]", status);
UnicodeSet s2(UNICODE_STRING_SIMPLE("\\p{lowercase}"), status);
TEST_ASSERT_SUCCESS(status);
TEST_ASSERT(s1==s2);
}
{
UErrorCode status = U_ZERO_ERROR;
UnicodeSet s1("[:upper:]", status);
UnicodeSet s2(UNICODE_STRING_SIMPLE("\\p{Uppercase}"), status);
TEST_ASSERT_SUCCESS(status);
TEST_ASSERT(s1==s2);
}
{
UErrorCode status = U_ZERO_ERROR;
UnicodeSet s1("[:punct:]", status);
UnicodeSet s2(UNICODE_STRING_SIMPLE("\\p{gc=Punctuation}"), status);
TEST_ASSERT_SUCCESS(status);
TEST_ASSERT(s1==s2);
}
{
UErrorCode status = U_ZERO_ERROR;
UnicodeSet s1("[:digit:]", status);
UnicodeSet s2(UNICODE_STRING_SIMPLE("\\p{gc=DecimalNumber}"), status);
TEST_ASSERT_SUCCESS(status);
TEST_ASSERT(s1==s2);
}
{
UErrorCode status = U_ZERO_ERROR;
UnicodeSet s1("[:xdigit:]", status);
UnicodeSet s2(UNICODE_STRING_SIMPLE("[\\p{DecimalNumber}\\p{HexDigit}]"), status);
TEST_ASSERT_SUCCESS(status);
TEST_ASSERT(s1==s2);
}
{
UErrorCode status = U_ZERO_ERROR;
UnicodeSet s1("[:alnum:]", status);
UnicodeSet s2(UNICODE_STRING_SIMPLE("[\\p{Alphabetic}\\p{DecimalNumber}]"), status);
TEST_ASSERT_SUCCESS(status);
TEST_ASSERT(s1==s2);
}
{
UErrorCode status = U_ZERO_ERROR;
UnicodeSet s1("[:space:]", status);
UnicodeSet s2(UNICODE_STRING_SIMPLE("\\p{Whitespace}"), status);
TEST_ASSERT_SUCCESS(status);
TEST_ASSERT(s1==s2);
}
{
UErrorCode status = U_ZERO_ERROR;
UnicodeSet s1("[:blank:]", status);
TEST_ASSERT_SUCCESS(status);
UnicodeSet s2(UNICODE_STRING_SIMPLE("[\\p{Whitespace}-[\\u000a\\u000B\\u000c\\u000d\\u0085\\p{LineSeparator}\\p{ParagraphSeparator}]]"),
status);
TEST_ASSERT_SUCCESS(status);
TEST_ASSERT(s1==s2);
}
{
UErrorCode status = U_ZERO_ERROR;
UnicodeSet s1("[:cntrl:]", status);
TEST_ASSERT_SUCCESS(status);
UnicodeSet s2(UNICODE_STRING_SIMPLE("\\p{Control}"), status);
TEST_ASSERT_SUCCESS(status);
TEST_ASSERT(s1==s2);
}
{
UErrorCode status = U_ZERO_ERROR;
UnicodeSet s1("[:graph:]", status);
TEST_ASSERT_SUCCESS(status);
UnicodeSet s2(UNICODE_STRING_SIMPLE("[^\\p{Whitespace}\\p{Control}\\p{Surrogate}\\p{Unassigned}]"), status);
TEST_ASSERT_SUCCESS(status);
TEST_ASSERT(s1==s2);
}
{
UErrorCode status = U_ZERO_ERROR;
UnicodeSet s1("[:print:]", status);
TEST_ASSERT_SUCCESS(status);
UnicodeSet s2(UNICODE_STRING_SIMPLE("[[:graph:][:blank:]-[\\p{Control}]]") ,status);
TEST_ASSERT_SUCCESS(status);
TEST_ASSERT(s1==s2);
}
}
/**
* Test cloning of UnicodeSet. For C++, we test the copy constructor.
*/
void UnicodeSetTest::TestClone() {
UErrorCode ec = U_ZERO_ERROR;
UnicodeSet s("[abcxyz]", ec);
UnicodeSet t(s);
expectContainment(t, "abc", "def");
}
/**
* Test the indexOf() and charAt() methods.
*/
void UnicodeSetTest::TestIndexOf() {
UErrorCode ec = U_ZERO_ERROR;
UnicodeSet set("[a-cx-y3578]", ec);
if (U_FAILURE(ec)) {
errln("FAIL: UnicodeSet constructor");
return;
}
for (int32_t i=0; i<set.size(); ++i) {
UChar32 c = set.charAt(i);
if (set.indexOf(c) != i) {
errln("FAIL: charAt(%d) = %X => indexOf() => %d",
i, c, set.indexOf(c));
}
}
UChar32 c = set.charAt(set.size());
if (c != -1) {
errln("FAIL: charAt(<out of range>) = %X", c);
}
int32_t j = set.indexOf((UChar32)0x71/*'q'*/);
if (j != -1) {
errln((UnicodeString)"FAIL: indexOf('q') = " + j);
}
}
/**
* Test closure API.
*/
void UnicodeSetTest::TestCloseOver() {
UErrorCode ec = U_ZERO_ERROR;
char CASE[] = {(char)USET_CASE_INSENSITIVE};
char CASE_MAPPINGS[] = {(char)USET_ADD_CASE_MAPPINGS};
const char* DATA[] = {
// selector, input, output
CASE,
"[aq\\u00DF{Bc}{bC}{Fi}]",
"[aAqQ\\u00DF\\u1E9E\\uFB01{ss}{bc}{fi}]", // U+1E9E LATIN CAPITAL LETTER SHARP S is new in Unicode 5.1
CASE,
"[\\u01F1]", // 'DZ'
"[\\u01F1\\u01F2\\u01F3]",
CASE,
"[\\u1FB4]",
"[\\u1FB4{\\u03AC\\u03B9}]",
CASE,
"[{F\\uFB01}]",
"[\\uFB03{ffi}]",
CASE, // make sure binary search finds limits
"[a\\uFF3A]",
"[aA\\uFF3A\\uFF5A]",
CASE,
"[a-z]","[A-Za-z\\u017F\\u212A]",
CASE,
"[abc]","[A-Ca-c]",
CASE,
"[ABC]","[A-Ca-c]",
CASE, "[i]", "[iI]",
CASE, "[\\u0130]", "[\\u0130{i\\u0307}]", // dotted I
CASE, "[{i\\u0307}]", "[\\u0130{i\\u0307}]", // i with dot
CASE, "[\\u0131]", "[\\u0131]", // dotless i
CASE, "[\\u0390]", "[\\u0390\\u1FD3{\\u03B9\\u0308\\u0301}]",
CASE, "[\\u03c2]", "[\\u03a3\\u03c2\\u03c3]", // sigmas
CASE, "[\\u03f2]", "[\\u03f2\\u03f9]", // lunate sigmas
CASE, "[\\u03f7]", "[\\u03f7\\u03f8]",
CASE, "[\\u1fe3]", "[\\u03b0\\u1fe3{\\u03c5\\u0308\\u0301}]",
CASE, "[\\ufb05]", "[\\ufb05\\ufb06{st}]",
CASE, "[{st}]", "[\\ufb05\\ufb06{st}]",
CASE, "[\\U0001044F]", "[\\U00010427\\U0001044F]",
CASE, "[{a\\u02BE}]", "[\\u1E9A{a\\u02BE}]", // first in sorted table
CASE, "[{\\u1f7c\\u03b9}]", "[\\u1ff2{\\u1f7c\\u03b9}]", // last in sorted table
#if !UCONFIG_NO_FILE_IO
CASE_MAPPINGS,
"[aq\\u00DF{Bc}{bC}{Fi}]",
"[aAqQ\\u00DF{ss}{Ss}{SS}{Bc}{BC}{bC}{bc}{FI}{Fi}{fi}]",
#endif
CASE_MAPPINGS,
"[\\u01F1]", // 'DZ'
"[\\u01F1\\u01F2\\u01F3]",
CASE_MAPPINGS,
"[a-z]",
"[A-Za-z]",
NULL
};
UnicodeSet s;
UnicodeSet t;
UnicodeString buf;
for (int32_t i=0; DATA[i]!=NULL; i+=3) {
int32_t selector = DATA[i][0];
UnicodeString pat(DATA[i+1], -1, US_INV);
UnicodeString exp(DATA[i+2], -1, US_INV);
s.applyPattern(pat, ec);
s.closeOver(selector);
t.applyPattern(exp, ec);
if (U_FAILURE(ec)) {
errln("FAIL: applyPattern failed");
continue;
}
if (s == t) {
logln((UnicodeString)"Ok: " + pat + ".closeOver(" + selector + ") => " + exp);
} else {
dataerrln((UnicodeString)"FAIL: " + pat + ".closeOver(" + selector + ") => " +
s.toPattern(buf, TRUE) + ", expected " + exp);
}
}
#if 0
/*
* Unused test code.
* This was used to compare the old implementation (using USET_CASE)
* with the new one (using 0x100 temporarily)
* while transitioning from hardcoded case closure tables in uniset.cpp
* (moved to uniset_props.cpp) to building the data by gencase into ucase.icu.
* and using ucase.c functions for closure.
* See Jitterbug 3432 RFE: Move uniset.cpp data to a data file
*
* Note: The old and new implementation never fully matched because
* the old implementation turned out to not map U+0130 and U+0131 correctly
* (dotted I and dotless i) and because the old implementation's data tables
* were outdated compared to Unicode 4.0.1 at the time of the change to the
* new implementation. (So sigmas and some other characters were not handled
* according to the newer Unicode version.)
*/
UnicodeSet sens("[:case_sensitive:]", ec), sens2, s2;
UnicodeSetIterator si(sens);
UnicodeString str, buf2;
const UnicodeString *pStr;
UChar32 c;
while(si.next()) {
if(!si.isString()) {
c=si.getCodepoint();
s.clear();
s.add(c);
str.setTo(c);
str.foldCase();
sens2.add(str);
t=s;
s.closeOver(USET_CASE);
t.closeOver(0x100);
if(s!=t) {
errln("FAIL: closeOver(U+%04x) differs: ", c);
errln((UnicodeString)"old "+s.toPattern(buf, TRUE)+" new: "+t.toPattern(buf2, TRUE));
}
}
}
// remove all code points
// should contain all full case folding mapping strings
sens2.remove(0, 0x10ffff);
si.reset(sens2);
while(si.next()) {
if(si.isString()) {
pStr=&si.getString();
s.clear();
s.add(*pStr);
t=s2=s;
s.closeOver(USET_CASE);
t.closeOver(0x100);
if(s!=t) {
errln((UnicodeString)"FAIL: closeOver("+s2.toPattern(buf, TRUE)+") differs: ");
errln((UnicodeString)"old "+s.toPattern(buf, TRUE)+" new: "+t.toPattern(buf2, TRUE));
}
}
}
#endif
// Test the pattern API
s.applyPattern("[abc]", USET_CASE_INSENSITIVE, NULL, ec);
if (U_FAILURE(ec)) {
errln("FAIL: applyPattern failed");
} else {
expectContainment(s, "abcABC", "defDEF");
}
UnicodeSet v("[^abc]", USET_CASE_INSENSITIVE, NULL, ec);
if (U_FAILURE(ec)) {
errln("FAIL: constructor failed");
} else {
expectContainment(v, "defDEF", "abcABC");
}
UnicodeSet cm("[abck]", USET_ADD_CASE_MAPPINGS, NULL, ec);
if (U_FAILURE(ec)) {
errln("FAIL: construct w/case mappings failed");
} else {
expectContainment(cm, "abckABCK", CharsToUnicodeString("defDEF\\u212A"));
}
}
void UnicodeSetTest::TestEscapePattern() {
const char pattern[] =
"[\\uFEFF \\u200A-\\u200E \\U0001D173-\\U0001D17A \\U000F0000-\\U000FFFFD ]";
const char exp[] =
"[\\u200A-\\u200E\\uFEFF\\U0001D173-\\U0001D17A\\U000F0000-\\U000FFFFD]";
// We test this with two passes; in the second pass we
// pre-unescape the pattern. Since U+200E is Pattern_White_Space,
// this fails -- which is what we expect.
for (int32_t pass=1; pass<=2; ++pass) {
UErrorCode ec = U_ZERO_ERROR;
UnicodeString pat(pattern, -1, US_INV);
if (pass==2) {
pat = pat.unescape();
}
// Pattern is only good for pass 1
UBool isPatternValid = (pass==1);
UnicodeSet set(pat, ec);
if (U_SUCCESS(ec) != isPatternValid){
errln((UnicodeString)"FAIL: applyPattern(" +
escape(pat) + ") => " +
u_errorName(ec));
continue;
}
if (U_FAILURE(ec)) {
continue;
}
if (set.contains((UChar)0x0644)){
errln((UnicodeString)"FAIL: " + escape(pat) + " contains(U+0664)");
}
UnicodeString newpat;
set.toPattern(newpat, TRUE);
if (newpat == UnicodeString(exp, -1, US_INV)) {
logln(escape(pat) + " => " + newpat);
} else {
errln((UnicodeString)"FAIL: " + escape(pat) + " => " + newpat);
}
for (int32_t i=0; i<set.getRangeCount(); ++i) {
UnicodeString str("Range ");
str.append((UChar)(0x30 + i))
.append(": ")
.append((UChar32)set.getRangeStart(i))
.append(" - ")
.append((UChar32)set.getRangeEnd(i));
str = str + " (" + set.getRangeStart(i) + " - " +
set.getRangeEnd(i) + ")";
if (set.getRangeStart(i) < 0) {
errln((UnicodeString)"FAIL: " + escape(str));
} else {
logln(escape(str));
}
}
}
}
void UnicodeSetTest::expectRange(const UnicodeString& label,
const UnicodeSet& set,
UChar32 start, UChar32 end) {
UnicodeSet exp(start, end);
UnicodeString pat;
if (set == exp) {
logln(label + " => " + set.toPattern(pat, TRUE));
} else {
UnicodeString xpat;
errln((UnicodeString)"FAIL: " + label + " => " +
set.toPattern(pat, TRUE) +
", expected " + exp.toPattern(xpat, TRUE));
}
}
void UnicodeSetTest::TestInvalidCodePoint() {
const UChar32 DATA[] = {
// Test range Expected range
0, 0x10FFFF, 0, 0x10FFFF,
(UChar32)-1, 8, 0, 8,
8, 0x110000, 8, 0x10FFFF
};
const int32_t DATA_LENGTH = sizeof(DATA)/sizeof(DATA[0]);
UnicodeString pat;
int32_t i;
for (i=0; i<DATA_LENGTH; i+=4) {
UChar32 start = DATA[i];
UChar32 end = DATA[i+1];
UChar32 xstart = DATA[i+2];
UChar32 xend = DATA[i+3];
// Try various API using the test code points
UnicodeSet set(start, end);
expectRange((UnicodeString)"ct(" + start + "," + end + ")",
set, xstart, xend);
set.clear();
set.set(start, end);
expectRange((UnicodeString)"set(" + start + "," + end + ")",
set, xstart, xend);
UBool b = set.contains(start);
b = set.contains(start, end);
b = set.containsNone(start, end);
b = set.containsSome(start, end);
(void)b; // Suppress set but not used warning.
/*int32_t index = set.indexOf(start);*/
set.clear();
set.add(start);
set.add(start, end);
expectRange((UnicodeString)"add(" + start + "," + end + ")",
set, xstart, xend);
set.set(0, 0x10FFFF);
set.retain(start, end);
expectRange((UnicodeString)"retain(" + start + "," + end + ")",
set, xstart, xend);
set.retain(start);
set.set(0, 0x10FFFF);
set.remove(start);
set.remove(start, end);
set.complement();
expectRange((UnicodeString)"!remove(" + start + "," + end + ")",
set, xstart, xend);
set.set(0, 0x10FFFF);
set.complement(start, end);
set.complement();
expectRange((UnicodeString)"!complement(" + start + "," + end + ")",
set, xstart, xend);
set.complement(start);
}
const UChar32 DATA2[] = {
0,
0x10FFFF,
(UChar32)-1,
0x110000
};
const int32_t DATA2_LENGTH = sizeof(DATA2)/sizeof(DATA2[0]);
for (i=0; i<DATA2_LENGTH; ++i) {
UChar32 c = DATA2[i], end = 0x10FFFF;
UBool valid = (c >= 0 && c <= 0x10FFFF);
UnicodeSet set(0, 0x10FFFF);
// For single-codepoint contains, invalid codepoints are NOT contained
UBool b = set.contains(c);
if (b == valid) {
logln((UnicodeString)"[\\u0000-\\U0010FFFF].contains(" + c +
") = " + b);
} else {
errln((UnicodeString)"FAIL: [\\u0000-\\U0010FFFF].contains(" + c +
") = " + b);
}
// For codepoint range contains, containsNone, and containsSome,
// invalid or empty (start > end) ranges have UNDEFINED behavior.
b = set.contains(c, end);
logln((UnicodeString)"* [\\u0000-\\U0010FFFF].contains(" + c +
"," + end + ") = " + b);
b = set.containsNone(c, end);
logln((UnicodeString)"* [\\u0000-\\U0010FFFF].containsNone(" + c +
"," + end + ") = " + b);
b = set.containsSome(c, end);
logln((UnicodeString)"* [\\u0000-\\U0010FFFF].containsSome(" + c +
"," + end + ") = " + b);
int32_t index = set.indexOf(c);
if ((index >= 0) == valid) {
logln((UnicodeString)"[\\u0000-\\U0010FFFF].indexOf(" + c +
") = " + index);
} else {
errln((UnicodeString)"FAIL: [\\u0000-\\U0010FFFF].indexOf(" + c +
") = " + index);
}
}
}
// Used by TestSymbolTable
class TokenSymbolTable : public SymbolTable {
public:
Hashtable contents;
TokenSymbolTable(UErrorCode& ec) : contents(FALSE, ec) {
contents.setValueDeleter(uprv_deleteUObject);
}
~TokenSymbolTable() {}
/**
* (Non-SymbolTable API) Add the given variable and value to
* the table. Variable should NOT contain leading '$'.
*/
void add(const UnicodeString& var, const UnicodeString& value,
UErrorCode& ec) {
if (U_SUCCESS(ec)) {
contents.put(var, new UnicodeString(value), ec);
}
}
/**
* SymbolTable API
*/
virtual const UnicodeString* lookup(const UnicodeString& s) const {
return (const UnicodeString*) contents.get(s);
}
/**
* SymbolTable API
*/
virtual const UnicodeFunctor* lookupMatcher(UChar32 /*ch*/) const {
return NULL;
}
/**
* SymbolTable API
*/
virtual UnicodeString parseReference(const UnicodeString& text,
ParsePosition& pos, int32_t limit) const {
int32_t start = pos.getIndex();
int32_t i = start;
UnicodeString result;
while (i < limit) {
UChar c = text.charAt(i);
if ((i==start && !u_isIDStart(c)) || !u_isIDPart(c)) {
break;
}
++i;
}
if (i == start) { // No valid name chars
return result; // Indicate failure with empty string
}
pos.setIndex(i);
text.extractBetween(start, i, result);
return result;
}
};
void UnicodeSetTest::TestSymbolTable() {
// Multiple test cases can be set up here. Each test case
// is terminated by null:
// var, value, var, value,..., input pat., exp. output pat., null
const char* DATA[] = {
"us", "a-z", "[0-1$us]", "[0-1a-z]", NULL,
"us", "[a-z]", "[0-1$us]", "[0-1[a-z]]", NULL,
"us", "\\[a\\-z\\]", "[0-1$us]", "[-01\\[\\]az]", NULL,
NULL
};
for (int32_t i=0; DATA[i]!=NULL; ++i) {
UErrorCode ec = U_ZERO_ERROR;
TokenSymbolTable sym(ec);
if (U_FAILURE(ec)) {
errln("FAIL: couldn't construct TokenSymbolTable");
continue;
}
// Set up variables
while (DATA[i+2] != NULL) {
sym.add(UnicodeString(DATA[i], -1, US_INV), UnicodeString(DATA[i+1], -1, US_INV), ec);
if (U_FAILURE(ec)) {
errln("FAIL: couldn't add to TokenSymbolTable");
continue;
}
i += 2;
}
// Input pattern and expected output pattern
UnicodeString inpat = UnicodeString(DATA[i], -1, US_INV), exppat = UnicodeString(DATA[i+1], -1, US_INV);
i += 2;
ParsePosition pos(0);
UnicodeSet us(inpat, pos, USET_IGNORE_SPACE, &sym, ec);
if (U_FAILURE(ec)) {
errln("FAIL: couldn't construct UnicodeSet");
continue;
}
// results
if (pos.getIndex() != inpat.length()) {
errln((UnicodeString)"Failed to read to end of string \""
+ inpat + "\": read to "
+ pos.getIndex() + ", length is "
+ inpat.length());
}
UnicodeSet us2(exppat, ec);
if (U_FAILURE(ec)) {
errln("FAIL: couldn't construct expected UnicodeSet");
continue;
}
UnicodeString a, b;
if (us != us2) {
errln((UnicodeString)"Failed, got " + us.toPattern(a, TRUE) +
", expected " + us2.toPattern(b, TRUE));
} else {
logln((UnicodeString)"Ok, got " + us.toPattern(a, TRUE));
}
}
}
void UnicodeSetTest::TestSurrogate() {
const char* DATA[] = {
// These should all behave identically
"[abc\\uD800\\uDC00]",
// "[abc\uD800\uDC00]", // Can't do this on C -- only Java
"[abc\\U00010000]",
0
};
for (int i=0; DATA[i] != 0; ++i) {
UErrorCode ec = U_ZERO_ERROR;
logln((UnicodeString)"Test pattern " + i + " :" + UnicodeString(DATA[i], -1, US_INV));
UnicodeString str = UnicodeString(DATA[i], -1, US_INV);
UnicodeSet set(str, ec);
if (U_FAILURE(ec)) {
errln("FAIL: UnicodeSet constructor");
continue;
}
expectContainment(set,
CharsToUnicodeString("abc\\U00010000"),
CharsToUnicodeString("\\uD800;\\uDC00")); // split apart surrogate-pair
if (set.size() != 4) {
errln((UnicodeString)"FAIL: " + UnicodeString(DATA[i], -1, US_INV) + ".size() == " +
set.size() + ", expected 4");
}
{
UErrorCode subErr = U_ZERO_ERROR;
checkRoundTrip(set);
checkSerializeRoundTrip(set, subErr);
}
}
}
void UnicodeSetTest::TestExhaustive() {
// exhaustive tests. Simulate UnicodeSets with integers.
// That gives us very solid tests (except for large memory tests).
int32_t limit = 128;
UnicodeSet x, y, z, aa;
for (int32_t i = 0; i < limit; ++i) {
bitsToSet(i, x);
logln((UnicodeString)"Testing " + i + ", " + x);
_testComplement(i, x, y);
UnicodeSet &toTest = bitsToSet(i, aa);
// AS LONG AS WE ARE HERE, check roundtrip
checkRoundTrip(toTest);
UErrorCode ec = U_ZERO_ERROR;
checkSerializeRoundTrip(toTest, ec);
for (int32_t j = 0; j < limit; ++j) {
_testAdd(i,j, x,y,z);
_testXor(i,j, x,y,z);
_testRetain(i,j, x,y,z);
_testRemove(i,j, x,y,z);
}
}
}
void UnicodeSetTest::_testComplement(int32_t a, UnicodeSet& x, UnicodeSet& z) {
bitsToSet(a, x);
z = x;
z.complement();
int32_t c = setToBits(z);
if (c != (~a)) {
errln((UnicodeString)"FAILED: add: ~" + x + " != " + z);
errln((UnicodeString)"FAILED: add: ~" + a + " != " + c);
}
checkCanonicalRep(z, (UnicodeString)"complement " + a);
}
void UnicodeSetTest::_testAdd(int32_t a, int32_t b, UnicodeSet& x, UnicodeSet& y, UnicodeSet& z) {
bitsToSet(a, x);
bitsToSet(b, y);
z = x;
z.addAll(y);
int32_t c = setToBits(z);
if (c != (a | b)) {
errln((UnicodeString)"FAILED: add: " + x + " | " + y + " != " + z);
errln((UnicodeString)"FAILED: add: " + a + " | " + b + " != " + c);
}
checkCanonicalRep(z, (UnicodeString)"add " + a + "," + b);
}
void UnicodeSetTest::_testRetain(int32_t a, int32_t b, UnicodeSet& x, UnicodeSet& y, UnicodeSet& z) {
bitsToSet(a, x);
bitsToSet(b, y);
z = x;
z.retainAll(y);
int32_t c = setToBits(z);
if (c != (a & b)) {
errln((UnicodeString)"FAILED: retain: " + x + " & " + y + " != " + z);
errln((UnicodeString)"FAILED: retain: " + a + " & " + b + " != " + c);
}
checkCanonicalRep(z, (UnicodeString)"retain " + a + "," + b);
}
void UnicodeSetTest::_testRemove(int32_t a, int32_t b, UnicodeSet& x, UnicodeSet& y, UnicodeSet& z) {
bitsToSet(a, x);
bitsToSet(b, y);
z = x;
z.removeAll(y);
int32_t c = setToBits(z);
if (c != (a &~ b)) {
errln((UnicodeString)"FAILED: remove: " + x + " &~ " + y + " != " + z);
errln((UnicodeString)"FAILED: remove: " + a + " &~ " + b + " != " + c);
}
checkCanonicalRep(z, (UnicodeString)"remove " + a + "," + b);
}
void UnicodeSetTest::_testXor(int32_t a, int32_t b, UnicodeSet& x, UnicodeSet& y, UnicodeSet& z) {
bitsToSet(a, x);
bitsToSet(b, y);
z = x;
z.complementAll(y);
int32_t c = setToBits(z);
if (c != (a ^ b)) {
errln((UnicodeString)"FAILED: complement: " + x + " ^ " + y + " != " + z);
errln((UnicodeString)"FAILED: complement: " + a + " ^ " + b + " != " + c);
}
checkCanonicalRep(z, (UnicodeString)"complement " + a + "," + b);
}
/**
* Check that ranges are monotonically increasing and non-
* overlapping.
*/
void UnicodeSetTest::checkCanonicalRep(const UnicodeSet& set, const UnicodeString& msg) {
int32_t n = set.getRangeCount();
if (n < 0) {
errln((UnicodeString)"FAIL result of " + msg +
": range count should be >= 0 but is " +
n /*+ " for " + set.toPattern())*/);
return;
}
UChar32 last = 0;
for (int32_t i=0; i<n; ++i) {
UChar32 start = set.getRangeStart(i);
UChar32 end = set.getRangeEnd(i);
if (start > end) {
errln((UnicodeString)"FAIL result of " + msg +
": range " + (i+1) +
" start > end: " + (int)start + ", " + (int)end +
" for " + set);
}
if (i > 0 && start <= last) {
errln((UnicodeString)"FAIL result of " + msg +
": range " + (i+1) +
" overlaps previous range: " + (int)start + ", " + (int)end +
" for " + set);
}
last = end;
}
}
/**
* Convert a bitmask to a UnicodeSet.
*/
UnicodeSet& UnicodeSetTest::bitsToSet(int32_t a, UnicodeSet& result) {
result.clear();
for (UChar32 i = 0; i < 32; ++i) {
if ((a & (1<<i)) != 0) {
result.add(i);
}
}
return result;
}
/**
* Convert a UnicodeSet to a bitmask. Only the characters
* U+0000 to U+0020 are represented in the bitmask.
*/
int32_t UnicodeSetTest::setToBits(const UnicodeSet& x) {
int32_t result = 0;
for (int32_t i = 0; i < 32; ++i) {
if (x.contains((UChar32)i)) {
result |= (1<<i);
}
}
return result;
}
/**
* Return the representation of an inversion list based UnicodeSet
* as a pairs list. Ranges are listed in ascending Unicode order.
* For example, the set [a-zA-M3] is represented as "33AMaz".
*/
UnicodeString UnicodeSetTest::getPairs(const UnicodeSet& set) {
UnicodeString pairs;
for (int32_t i=0; i<set.getRangeCount(); ++i) {
UChar32 start = set.getRangeStart(i);
UChar32 end = set.getRangeEnd(i);
if (end > 0xFFFF) {
end = 0xFFFF;
i = set.getRangeCount(); // Should be unnecessary
}
pairs.append((UChar)start).append((UChar)end);
}
return pairs;
}
/**
* Basic consistency check for a few items.
* That the iterator works, and that we can create a pattern and
* get the same thing back
*/
void UnicodeSetTest::checkRoundTrip(const UnicodeSet& s) {
{
UnicodeSet t(s);
checkEqual(s, t, "copy ct");
}
{
UnicodeSet t(0xabcd, 0xdef0); // dummy contents should be overwritten
t = s;
checkEqual(s, t, "operator=");
}
{
UnicodeSet t;
copyWithIterator(t, s, FALSE);
checkEqual(s, t, "iterator roundtrip");
}
{
UnicodeSet t;
copyWithIterator(t, s, TRUE); // try range
checkEqual(s, t, "iterator roundtrip");
}
{
UnicodeSet t;
UnicodeString pat;
UErrorCode ec = U_ZERO_ERROR;
s.toPattern(pat, FALSE);
t.applyPattern(pat, ec);
if (U_FAILURE(ec)) {
errln("FAIL: toPattern(escapeUnprintable=FALSE), applyPattern - %s", u_errorName(ec));
return;
} else {
checkEqual(s, t, "toPattern(false)");
}
}
{
UnicodeSet t;
UnicodeString pat;
UErrorCode ec = U_ZERO_ERROR;
s.toPattern(pat, TRUE);
t.applyPattern(pat, ec);
if (U_FAILURE(ec)) {
errln("FAIL: toPattern(escapeUnprintable=TRUE), applyPattern - %s", u_errorName(ec));
return;
} else {
checkEqual(s, t, "toPattern(true)");
}
}
}
void UnicodeSetTest::checkSerializeRoundTrip(const UnicodeSet& t, UErrorCode &status) {
if(U_FAILURE(status)) return;
int32_t len = t.serialize(serializeBuffer.getAlias(), serializeBuffer.getCapacity(), status);
if(status == U_BUFFER_OVERFLOW_ERROR) {
status = U_ZERO_ERROR;
serializeBuffer.resize(len);
len = t.serialize(serializeBuffer.getAlias(), serializeBuffer.getCapacity(), status);
// let 2nd error stand
}
if(U_FAILURE(status)) {
errln("checkSerializeRoundTrip: error %s serializing buffer\n", u_errorName(status));
return;
}
UnicodeSet deserialized(serializeBuffer.getAlias(), len, UnicodeSet::kSerialized, status);
if(U_FAILURE(status)) {
errln("checkSerializeRoundTrip: error %s deserializing buffer: buf %p len %d, original %d\n", u_errorName(status), serializeBuffer.getAlias(), len, t.getRangeCount());
return;
}
checkEqual(t, deserialized, "Set was unequal when deserialized");
}
void UnicodeSetTest::copyWithIterator(UnicodeSet& t, const UnicodeSet& s, UBool withRange) {
t.clear();
UnicodeSetIterator it(s);
if (withRange) {
while (it.nextRange()) {
if (it.isString()) {
t.add(it.getString());
} else {
t.add(it.getCodepoint(), it.getCodepointEnd());
}
}
} else {
while (it.next()) {
if (it.isString()) {
t.add(it.getString());
} else {
t.add(it.getCodepoint());
}
}
}
}
UBool UnicodeSetTest::checkEqual(const UnicodeSet& s, const UnicodeSet& t, const char* message) {
assertEquals(UnicodeString("RangeCount: ","") + message, s.getRangeCount(), t.getRangeCount());
assertEquals(UnicodeString("size: ","") + message, s.size(), t.size());
UnicodeString source; s.toPattern(source, TRUE);
UnicodeString result; t.toPattern(result, TRUE);
if (s != t) {
errln((UnicodeString)"FAIL: " + message
+ "; source = " + source
+ "; result = " + result
);
return FALSE;
} else {
logln((UnicodeString)"Ok: " + message
+ "; source = " + source
+ "; result = " + result
);
}
return TRUE;
}
void
UnicodeSetTest::expectContainment(const UnicodeString& pat,
const UnicodeString& charsIn,
const UnicodeString& charsOut) {
UErrorCode ec = U_ZERO_ERROR;
UnicodeSet set(pat, ec);
if (U_FAILURE(ec)) {
dataerrln((UnicodeString)"FAIL: pattern \"" +
pat + "\" => " + u_errorName(ec));
return;
}
expectContainment(set, pat, charsIn, charsOut);
}
void
UnicodeSetTest::expectContainment(const UnicodeSet& set,
const UnicodeString& charsIn,
const UnicodeString& charsOut) {
UnicodeString pat;
set.toPattern(pat);
expectContainment(set, pat, charsIn, charsOut);
}
void
UnicodeSetTest::expectContainment(const UnicodeSet& set,
const UnicodeString& setName,
const UnicodeString& charsIn,
const UnicodeString& charsOut) {
UnicodeString bad;
UChar32 c;
int32_t i;
for (i=0; i<charsIn.length(); i+=U16_LENGTH(c)) {
c = charsIn.char32At(i);
if (!set.contains(c)) {
bad.append(c);
}
}
if (bad.length() > 0) {
errln((UnicodeString)"Fail: set " + setName + " does not contain " + prettify(bad) +
", expected containment of " + prettify(charsIn));
} else {
logln((UnicodeString)"Ok: set " + setName + " contains " + prettify(charsIn));
}
bad.truncate(0);
for (i=0; i<charsOut.length(); i+=U16_LENGTH(c)) {
c = charsOut.char32At(i);
if (set.contains(c)) {
bad.append(c);
}
}
if (bad.length() > 0) {
errln((UnicodeString)"Fail: set " + setName + " contains " + prettify(bad) +
", expected non-containment of " + prettify(charsOut));
} else {
logln((UnicodeString)"Ok: set " + setName + " does not contain " + prettify(charsOut));
}
}
void
UnicodeSetTest::expectPattern(UnicodeSet& set,
const UnicodeString& pattern,
const UnicodeString& expectedPairs){
UErrorCode status = U_ZERO_ERROR;
set.applyPattern(pattern, status);
if (U_FAILURE(status)) {
errln(UnicodeString("FAIL: applyPattern(\"") + pattern +
"\") failed");
return;
} else {
if (getPairs(set) != expectedPairs ) {
errln(UnicodeString("FAIL: applyPattern(\"") + pattern +
"\") => pairs \"" +
escape(getPairs(set)) + "\", expected \"" +
escape(expectedPairs) + "\"");
} else {
logln(UnicodeString("Ok: applyPattern(\"") + pattern +
"\") => pairs \"" +
escape(getPairs(set)) + "\"");
}
}
// the result of calling set.toPattern(), which is the string representation of
// this set(set), is passed to a UnicodeSet constructor, and tested that it
// will produce another set that is equal to this one.
UnicodeString temppattern;
set.toPattern(temppattern);
UnicodeSet *tempset=new UnicodeSet(temppattern, status);
if (U_FAILURE(status)) {
errln(UnicodeString("FAIL: applyPattern(\""+ pattern + "\").toPattern() => " + temppattern + " => invalid pattern"));
return;
}
if(*tempset != set || getPairs(*tempset) != getPairs(set)){
errln(UnicodeString("FAIL: applyPattern(\""+ pattern + "\").toPattern() => " + temppattern + " => pairs \""+ escape(getPairs(*tempset)) + "\", expected pairs \"" +
escape(getPairs(set)) + "\""));
} else{
logln(UnicodeString("Ok: applyPattern(\""+ pattern + "\").toPattern() => " + temppattern + " => pairs \"" + escape(getPairs(*tempset)) + "\""));
}
delete tempset;
}
void
UnicodeSetTest::expectPairs(const UnicodeSet& set, const UnicodeString& expectedPairs) {
if (getPairs(set) != expectedPairs) {
errln(UnicodeString("FAIL: Expected pair list \"") +
escape(expectedPairs) + "\", got \"" +
escape(getPairs(set)) + "\"");
}
}
void UnicodeSetTest::expectToPattern(const UnicodeSet& set,
const UnicodeString& expPat,
const char** expStrings) {
UnicodeString pat;
set.toPattern(pat, TRUE);
if (pat == expPat) {
logln((UnicodeString)"Ok: toPattern() => \"" + pat + "\"");
} else {
errln((UnicodeString)"FAIL: toPattern() => \"" + pat + "\", expected \"" + expPat + "\"");
return;
}
if (expStrings == NULL) {
return;
}
UBool in = TRUE;
for (int32_t i=0; expStrings[i] != NULL; ++i) {
if (expStrings[i] == NOT) { // sic; pointer comparison
in = FALSE;
continue;
}
UnicodeString s = CharsToUnicodeString(expStrings[i]);
UBool contained = set.contains(s);
if (contained == in) {
logln((UnicodeString)"Ok: " + expPat +
(contained ? " contains {" : " does not contain {") +
escape(expStrings[i]) + "}");
} else {
errln((UnicodeString)"FAIL: " + expPat +
(contained ? " contains {" : " does not contain {") +
escape(expStrings[i]) + "}");
}
}
}
static UChar toHexString(int32_t i) { return (UChar)(i + (i < 10 ? 0x30 : (0x41 - 10))); }
void
UnicodeSetTest::doAssert(UBool condition, const char *message)
{
if (!condition) {
errln(UnicodeString("ERROR : ") + message);
}
}
UnicodeString
UnicodeSetTest::escape(const UnicodeString& s) {
UnicodeString buf;
for (int32_t i=0; i<s.length(); )
{
UChar32 c = s.char32At(i);
if (0x0020 <= c && c <= 0x007F) {
buf += c;
} else {
if (c <= 0xFFFF) {
buf += (UChar)0x5c; buf += (UChar)0x75;
} else {
buf += (UChar)0x5c; buf += (UChar)0x55;
buf += toHexString((c & 0xF0000000) >> 28);
buf += toHexString((c & 0x0F000000) >> 24);
buf += toHexString((c & 0x00F00000) >> 20);
buf += toHexString((c & 0x000F0000) >> 16);
}
buf += toHexString((c & 0xF000) >> 12);
buf += toHexString((c & 0x0F00) >> 8);
buf += toHexString((c & 0x00F0) >> 4);
buf += toHexString(c & 0x000F);
}
i += U16_LENGTH(c);
}
return buf;
}
void UnicodeSetTest::TestFreezable() {
UErrorCode errorCode=U_ZERO_ERROR;
UnicodeString idPattern=UNICODE_STRING("[:ID_Continue:]", 15);
UnicodeSet idSet(idPattern, errorCode);
if(U_FAILURE(errorCode)) {
dataerrln("FAIL: unable to create UnicodeSet([:ID_Continue:]) - %s", u_errorName(errorCode));
return;
}
UnicodeString wsPattern=UNICODE_STRING("[:White_Space:]", 15);
UnicodeSet wsSet(wsPattern, errorCode);
if(U_FAILURE(errorCode)) {
dataerrln("FAIL: unable to create UnicodeSet([:White_Space:]) - %s", u_errorName(errorCode));
return;
}
idSet.add(idPattern);
UnicodeSet frozen(idSet);
frozen.freeze();
if(idSet.isFrozen() || !frozen.isFrozen()) {
errln("FAIL: isFrozen() is wrong");
}
if(frozen!=idSet || !(frozen==idSet)) {
errln("FAIL: a copy-constructed frozen set differs from its original");
}
frozen=wsSet;
if(frozen!=idSet || !(frozen==idSet)) {
errln("FAIL: a frozen set was modified by operator=");
}
UnicodeSet frozen2(frozen);
if(frozen2!=frozen || frozen2!=idSet) {
errln("FAIL: a copied frozen set differs from its frozen original");
}
if(!frozen2.isFrozen()) {
errln("FAIL: copy-constructing a frozen set results in a thawed one");
}
UnicodeSet frozen3(5, 55); // Set to some values to really test assignment below, not copy construction.
if(frozen3.contains(0, 4) || !frozen3.contains(5, 55) || frozen3.contains(56, 0x10ffff)) {
errln("FAIL: UnicodeSet(5, 55) failed");
}
frozen3=frozen;
if(!frozen3.isFrozen()) {
errln("FAIL: copying a frozen set results in a thawed one");
}
UnicodeSet *cloned=(UnicodeSet *)frozen.clone();
if(!cloned->isFrozen() || *cloned!=frozen || cloned->containsSome(0xd802, 0xd805)) {
errln("FAIL: clone() failed");
}
cloned->add(0xd802, 0xd805);
if(cloned->containsSome(0xd802, 0xd805)) {
errln("FAIL: unable to modify clone");
}
delete cloned;
UnicodeSet *thawed=(UnicodeSet *)frozen.cloneAsThawed();
if(thawed->isFrozen() || *thawed!=frozen || thawed->containsSome(0xd802, 0xd805)) {
errln("FAIL: cloneAsThawed() failed");
}
thawed->add(0xd802, 0xd805);
if(!thawed->contains(0xd802, 0xd805)) {
errln("FAIL: unable to modify thawed clone");
}
delete thawed;
frozen.set(5, 55);
if(frozen!=idSet || !(frozen==idSet)) {
errln("FAIL: UnicodeSet::set() modified a frozen set");
}
frozen.clear();
if(frozen!=idSet || !(frozen==idSet)) {
errln("FAIL: UnicodeSet::clear() modified a frozen set");
}
frozen.closeOver(USET_CASE_INSENSITIVE);
if(frozen!=idSet || !(frozen==idSet)) {
errln("FAIL: UnicodeSet::closeOver() modified a frozen set");
}
frozen.compact();
if(frozen!=idSet || !(frozen==idSet)) {
errln("FAIL: UnicodeSet::compact() modified a frozen set");
}
ParsePosition pos;
frozen.
applyPattern(wsPattern, errorCode).
applyPattern(wsPattern, USET_IGNORE_SPACE, NULL, errorCode).
applyPattern(wsPattern, pos, USET_IGNORE_SPACE, NULL, errorCode).
applyIntPropertyValue(UCHAR_CANONICAL_COMBINING_CLASS, 230, errorCode).
applyPropertyAlias(UNICODE_STRING_SIMPLE("Assigned"), UnicodeString(), errorCode);
if(frozen!=idSet || !(frozen==idSet)) {
errln("FAIL: UnicodeSet::applyXYZ() modified a frozen set");
}
frozen.
add(0xd800).
add(0xd802, 0xd805).
add(wsPattern).
addAll(idPattern).
addAll(wsSet);
if(frozen!=idSet || !(frozen==idSet)) {
errln("FAIL: UnicodeSet::addXYZ() modified a frozen set");
}
frozen.
retain(0x62).
retain(0x64, 0x69).
retainAll(wsPattern).
retainAll(wsSet);
if(frozen!=idSet || !(frozen==idSet)) {
errln("FAIL: UnicodeSet::retainXYZ() modified a frozen set");
}
frozen.
remove(0x62).
remove(0x64, 0x69).
remove(idPattern).
removeAll(idPattern).
removeAll(idSet);
if(frozen!=idSet || !(frozen==idSet)) {
errln("FAIL: UnicodeSet::removeXYZ() modified a frozen set");
}
frozen.
complement().
complement(0x62).
complement(0x64, 0x69).
complement(idPattern).
complementAll(idPattern).
complementAll(idSet);
if(frozen!=idSet || !(frozen==idSet)) {
errln("FAIL: UnicodeSet::complementXYZ() modified a frozen set");
}
}
// Test span() etc. -------------------------------------------------------- ***
// Append the UTF-8 version of the string to t and return the appended UTF-8 length.
static int32_t
appendUTF8(const UChar *s, int32_t length, char *t, int32_t capacity) {
UErrorCode errorCode=U_ZERO_ERROR;
int32_t length8=0;
u_strToUTF8(t, capacity, &length8, s, length, &errorCode);
if(U_SUCCESS(errorCode)) {
return length8;
} else {
// The string contains an unpaired surrogate.
// Ignore this string.
return 0;
}
}
class UnicodeSetWithStringsIterator;
// Make the strings in a UnicodeSet easily accessible.
class UnicodeSetWithStrings {
public:
UnicodeSetWithStrings(const UnicodeSet &normalSet) :
set(normalSet), stringsLength(0), hasSurrogates(FALSE) {
int32_t size=set.size();
if(size>0 && set.charAt(size-1)<0) {
// If a set's last element is not a code point, then it must contain strings.
// Iterate over the set, skip all code point ranges, and cache the strings.
// Convert them to UTF-8 for spanUTF8().
UnicodeSetIterator iter(set);
const UnicodeString *s;
char *s8=utf8;
int32_t length8, utf8Count=0;
while(iter.nextRange() && stringsLength<UPRV_LENGTHOF(strings)) {
if(iter.isString()) {
// Store the pointer to the set's string element
// which we happen to know is a stable pointer.
strings[stringsLength]=s=&iter.getString();
utf8Count+=
utf8Lengths[stringsLength]=length8=
appendUTF8(s->getBuffer(), s->length(),
s8, (int32_t)(sizeof(utf8)-utf8Count));
if(length8==0) {
hasSurrogates=TRUE; // Contains unpaired surrogates.
}
s8+=length8;
++stringsLength;
}
}
}
}
const UnicodeSet &getSet() const {
return set;
}
UBool hasStrings() const {
return (UBool)(stringsLength>0);
}
UBool hasStringsWithSurrogates() const {
return hasSurrogates;
}
private:
friend class UnicodeSetWithStringsIterator;
const UnicodeSet &set;
const UnicodeString *strings[20];
int32_t stringsLength;
UBool hasSurrogates;
char utf8[1024];
int32_t utf8Lengths[20];
};
class UnicodeSetWithStringsIterator {
public:
UnicodeSetWithStringsIterator(const UnicodeSetWithStrings &set) :
fSet(set), nextStringIndex(0), nextUTF8Start(0) {
}
void reset() {
nextStringIndex=nextUTF8Start=0;
}
const UnicodeString *nextString() {
if(nextStringIndex<fSet.stringsLength) {
return fSet.strings[nextStringIndex++];
} else {
return NULL;
}
}
// Do not mix with calls to nextString().
const char *nextUTF8(int32_t &length) {
if(nextStringIndex<fSet.stringsLength) {
const char *s8=fSet.utf8+nextUTF8Start;
nextUTF8Start+=length=fSet.utf8Lengths[nextStringIndex++];
return s8;
} else {
length=0;
return NULL;
}
}
private:
const UnicodeSetWithStrings &fSet;
int32_t nextStringIndex;
int32_t nextUTF8Start;
};
// Compare 16-bit Unicode strings (which may be malformed UTF-16)
// at code point boundaries.
// That is, each edge of a match must not be in the middle of a surrogate pair.
static inline UBool
matches16CPB(const UChar *s, int32_t start, int32_t limit, const UnicodeString &t) {
s+=start;
limit-=start;
int32_t length=t.length();
return 0==t.compare(s, length) &&
!(0<start && U16_IS_LEAD(s[-1]) && U16_IS_TRAIL(s[0])) &&
!(length<limit && U16_IS_LEAD(s[length-1]) && U16_IS_TRAIL(s[length]));
}
// Implement span() with contains() for comparison.
static int32_t containsSpanUTF16(const UnicodeSetWithStrings &set, const UChar *s, int32_t length,
USetSpanCondition spanCondition) {
const UnicodeSet &realSet(set.getSet());
if(!set.hasStrings()) {
if(spanCondition!=USET_SPAN_NOT_CONTAINED) {
spanCondition=USET_SPAN_CONTAINED; // Pin to 0/1 values.
}
UChar32 c;
int32_t start=0, prev;
while((prev=start)<length) {
U16_NEXT(s, start, length, c);
if(realSet.contains(c)!=spanCondition) {
break;
}
}
return prev;
} else if(spanCondition==USET_SPAN_NOT_CONTAINED) {
UnicodeSetWithStringsIterator iter(set);
UChar32 c;
int32_t start, next;
for(start=next=0; start<length;) {
U16_NEXT(s, next, length, c);
if(realSet.contains(c)) {
break;
}
const UnicodeString *str;
iter.reset();
while((str=iter.nextString())!=NULL) {
if(str->length()<=(length-start) && matches16CPB(s, start, length, *str)) {
// spanNeedsStrings=TRUE;
return start;
}
}
start=next;
}
return start;
} else /* USET_SPAN_CONTAINED or USET_SPAN_SIMPLE */ {
UnicodeSetWithStringsIterator iter(set);
UChar32 c;
int32_t start, next, maxSpanLimit=0;
for(start=next=0; start<length;) {
U16_NEXT(s, next, length, c);
if(!realSet.contains(c)) {
next=start; // Do not span this single, not-contained code point.
}
const UnicodeString *str;
iter.reset();
while((str=iter.nextString())!=NULL) {
if(str->length()<=(length-start) && matches16CPB(s, start, length, *str)) {
// spanNeedsStrings=TRUE;
int32_t matchLimit=start+str->length();
if(matchLimit==length) {
return length;
}
if(spanCondition==USET_SPAN_CONTAINED) {
// Iterate for the shortest match at each position.
// Recurse for each but the shortest match.
if(next==start) {
next=matchLimit; // First match from start.
} else {
if(matchLimit<next) {
// Remember shortest match from start for iteration.
int32_t temp=next;
next=matchLimit;
matchLimit=temp;
}
// Recurse for non-shortest match from start.
int32_t spanLength=containsSpanUTF16(set, s+matchLimit, length-matchLimit,
USET_SPAN_CONTAINED);
if((matchLimit+spanLength)>maxSpanLimit) {
maxSpanLimit=matchLimit+spanLength;
if(maxSpanLimit==length) {
return length;
}
}
}
} else /* spanCondition==USET_SPAN_SIMPLE */ {
if(matchLimit>next) {
// Remember longest match from start.
next=matchLimit;
}
}
}
}
if(next==start) {
break; // No match from start.
}
start=next;
}
if(start>maxSpanLimit) {
return start;
} else {
return maxSpanLimit;
}
}
}
static int32_t containsSpanBackUTF16(const UnicodeSetWithStrings &set, const UChar *s, int32_t length,
USetSpanCondition spanCondition) {
if(length==0) {
return 0;
}
const UnicodeSet &realSet(set.getSet());
if(!set.hasStrings()) {
if(spanCondition!=USET_SPAN_NOT_CONTAINED) {
spanCondition=USET_SPAN_CONTAINED; // Pin to 0/1 values.
}
UChar32 c;
int32_t prev=length;
do {
U16_PREV(s, 0, length, c);
if(realSet.contains(c)!=spanCondition) {
break;
}
} while((prev=length)>0);
return prev;
} else if(spanCondition==USET_SPAN_NOT_CONTAINED) {
UnicodeSetWithStringsIterator iter(set);
UChar32 c;
int32_t prev=length, length0=length;
do {
U16_PREV(s, 0, length, c);
if(realSet.contains(c)) {
break;
}
const UnicodeString *str;
iter.reset();
while((str=iter.nextString())!=NULL) {
if(str->length()<=prev && matches16CPB(s, prev-str->length(), length0, *str)) {
// spanNeedsStrings=TRUE;
return prev;
}
}
} while((prev=length)>0);
return prev;
} else /* USET_SPAN_CONTAINED or USET_SPAN_SIMPLE */ {
UnicodeSetWithStringsIterator iter(set);
UChar32 c;
int32_t prev=length, minSpanStart=length, length0=length;
do {
U16_PREV(s, 0, length, c);
if(!realSet.contains(c)) {
length=prev; // Do not span this single, not-contained code point.
}
const UnicodeString *str;
iter.reset();
while((str=iter.nextString())!=NULL) {
if(str->length()<=prev && matches16CPB(s, prev-str->length(), length0, *str)) {
// spanNeedsStrings=TRUE;
int32_t matchStart=prev-str->length();
if(matchStart==0) {
return 0;
}
if(spanCondition==USET_SPAN_CONTAINED) {
// Iterate for the shortest match at each position.
// Recurse for each but the shortest match.
if(length==prev) {
length=matchStart; // First match from prev.
} else {
if(matchStart>length) {
// Remember shortest match from prev for iteration.
int32_t temp=length;
length=matchStart;
matchStart=temp;
}
// Recurse for non-shortest match from prev.
int32_t spanStart=containsSpanBackUTF16(set, s, matchStart,
USET_SPAN_CONTAINED);
if(spanStart<minSpanStart) {
minSpanStart=spanStart;
if(minSpanStart==0) {
return 0;
}
}
}
} else /* spanCondition==USET_SPAN_SIMPLE */ {
if(matchStart<length) {
// Remember longest match from prev.
length=matchStart;
}
}
}
}
if(length==prev) {
break; // No match from prev.
}
} while((prev=length)>0);
if(prev<minSpanStart) {
return prev;
} else {
return minSpanStart;
}
}
}
static int32_t containsSpanUTF8(const UnicodeSetWithStrings &set, const char *s, int32_t length,
USetSpanCondition spanCondition) {
const UnicodeSet &realSet(set.getSet());
if(!set.hasStrings()) {
if(spanCondition!=USET_SPAN_NOT_CONTAINED) {
spanCondition=USET_SPAN_CONTAINED; // Pin to 0/1 values.
}
UChar32 c;
int32_t start=0, prev;
while((prev=start)<length) {
U8_NEXT_OR_FFFD(s, start, length, c);
if(realSet.contains(c)!=spanCondition) {
break;
}
}
return prev;
} else if(spanCondition==USET_SPAN_NOT_CONTAINED) {
UnicodeSetWithStringsIterator iter(set);
UChar32 c;
int32_t start, next;
for(start=next=0; start<length;) {
U8_NEXT_OR_FFFD(s, next, length, c);
if(realSet.contains(c)) {
break;
}
const char *s8;
int32_t length8;
iter.reset();
while((s8=iter.nextUTF8(length8))!=NULL) {
if(length8!=0 && length8<=(length-start) && 0==memcmp(s+start, s8, length8)) {
// spanNeedsStrings=TRUE;
return start;
}
}
start=next;
}
return start;
} else /* USET_SPAN_CONTAINED or USET_SPAN_SIMPLE */ {
UnicodeSetWithStringsIterator iter(set);
UChar32 c;
int32_t start, next, maxSpanLimit=0;
for(start=next=0; start<length;) {
U8_NEXT_OR_FFFD(s, next, length, c);
if(!realSet.contains(c)) {
next=start; // Do not span this single, not-contained code point.
}
const char *s8;
int32_t length8;
iter.reset();
while((s8=iter.nextUTF8(length8))!=NULL) {
if(length8!=0 && length8<=(length-start) && 0==memcmp(s+start, s8, length8)) {
// spanNeedsStrings=TRUE;
int32_t matchLimit=start+length8;
if(matchLimit==length) {
return length;
}
if(spanCondition==USET_SPAN_CONTAINED) {
// Iterate for the shortest match at each position.
// Recurse for each but the shortest match.
if(next==start) {
next=matchLimit; // First match from start.
} else {
if(matchLimit<next) {
// Remember shortest match from start for iteration.
int32_t temp=next;
next=matchLimit;
matchLimit=temp;
}
// Recurse for non-shortest match from start.
int32_t spanLength=containsSpanUTF8(set, s+matchLimit, length-matchLimit,
USET_SPAN_CONTAINED);
if((matchLimit+spanLength)>maxSpanLimit) {
maxSpanLimit=matchLimit+spanLength;
if(maxSpanLimit==length) {
return length;
}
}
}
} else /* spanCondition==USET_SPAN_SIMPLE */ {
if(matchLimit>next) {
// Remember longest match from start.
next=matchLimit;
}
}
}
}
if(next==start) {
break; // No match from start.
}
start=next;
}
if(start>maxSpanLimit) {
return start;
} else {
return maxSpanLimit;
}
}
}
static int32_t containsSpanBackUTF8(const UnicodeSetWithStrings &set, const char *s, int32_t length,
USetSpanCondition spanCondition) {
if(length==0) {
return 0;
}
const UnicodeSet &realSet(set.getSet());
if(!set.hasStrings()) {
if(spanCondition!=USET_SPAN_NOT_CONTAINED) {
spanCondition=USET_SPAN_CONTAINED; // Pin to 0/1 values.
}
UChar32 c;
int32_t prev=length;
do {
U8_PREV_OR_FFFD(s, 0, length, c);
if(realSet.contains(c)!=spanCondition) {
break;
}
} while((prev=length)>0);
return prev;
} else if(spanCondition==USET_SPAN_NOT_CONTAINED) {
UnicodeSetWithStringsIterator iter(set);
UChar32 c;
int32_t prev=length;
do {
U8_PREV_OR_FFFD(s, 0, length, c);
if(realSet.contains(c)) {
break;
}
const char *s8;
int32_t length8;
iter.reset();
while((s8=iter.nextUTF8(length8))!=NULL) {
if(length8!=0 && length8<=prev && 0==memcmp(s+prev-length8, s8, length8)) {
// spanNeedsStrings=TRUE;
return prev;
}
}
} while((prev=length)>0);
return prev;
} else /* USET_SPAN_CONTAINED or USET_SPAN_SIMPLE */ {
UnicodeSetWithStringsIterator iter(set);
UChar32 c;
int32_t prev=length, minSpanStart=length;
do {
U8_PREV_OR_FFFD(s, 0, length, c);
if(!realSet.contains(c)) {
length=prev; // Do not span this single, not-contained code point.
}
const char *s8;
int32_t length8;
iter.reset();
while((s8=iter.nextUTF8(length8))!=NULL) {
if(length8!=0 && length8<=prev && 0==memcmp(s+prev-length8, s8, length8)) {
// spanNeedsStrings=TRUE;
int32_t matchStart=prev-length8;
if(matchStart==0) {
return 0;
}
if(spanCondition==USET_SPAN_CONTAINED) {
// Iterate for the shortest match at each position.
// Recurse for each but the shortest match.
if(length==prev) {
length=matchStart; // First match from prev.
} else {
if(matchStart>length) {
// Remember shortest match from prev for iteration.
int32_t temp=length;
length=matchStart;
matchStart=temp;
}
// Recurse for non-shortest match from prev.
int32_t spanStart=containsSpanBackUTF8(set, s, matchStart,
USET_SPAN_CONTAINED);
if(spanStart<minSpanStart) {
minSpanStart=spanStart;
if(minSpanStart==0) {
return 0;
}
}
}
} else /* spanCondition==USET_SPAN_SIMPLE */ {
if(matchStart<length) {
// Remember longest match from prev.
length=matchStart;
}
}
}
}
if(length==prev) {
break; // No match from prev.
}
} while((prev=length)>0);
if(prev<minSpanStart) {
return prev;
} else {
return minSpanStart;
}
}
}
// spans to be performed and compared
enum {
SPAN_UTF16 =1,
SPAN_UTF8 =2,
SPAN_UTFS =3,
SPAN_SET =4,
SPAN_COMPLEMENT =8,
SPAN_POLARITY =0xc,
SPAN_FWD =0x10,
SPAN_BACK =0x20,
SPAN_DIRS =0x30,
SPAN_CONTAINED =0x100,
SPAN_SIMPLE =0x200,
SPAN_CONDITION =0x300,
SPAN_ALL =0x33f
};
static inline USetSpanCondition invertSpanCondition(USetSpanCondition spanCondition, USetSpanCondition contained) {
return spanCondition == USET_SPAN_NOT_CONTAINED ? contained : USET_SPAN_NOT_CONTAINED;
}
static inline int32_t slen(const void *s, UBool isUTF16) {
return isUTF16 ? u_strlen((const UChar *)s) : strlen((const char *)s);
}
/*
* Count spans on a string with the method according to type and set the span limits.
* The set may be the complement of the original.
* When using spanBack() and comparing with span(), use a span condition for the first spanBack()
* according to the expected number of spans.
* Sets typeName to an empty string if there is no such type.
* Returns -1 if the span option is filtered out.
*/
static int32_t getSpans(const UnicodeSetWithStrings &set, UBool isComplement,
const void *s, int32_t length, UBool isUTF16,
uint32_t whichSpans,
int type, const char *&typeName,
int32_t limits[], int32_t limitsCapacity,
int32_t expectCount) {
const UnicodeSet &realSet(set.getSet());
int32_t start, count;
USetSpanCondition spanCondition, firstSpanCondition, contained;
UBool isForward;
if(type<0 || 7<type) {
typeName="";
return 0;
}
static const char *const typeNames16[]={
"contains", "contains(LM)",
"span", "span(LM)",
"containsBack", "containsBack(LM)",
"spanBack", "spanBack(LM)"
};
static const char *const typeNames8[]={
"containsUTF8", "containsUTF8(LM)",
"spanUTF8", "spanUTF8(LM)",
"containsBackUTF8", "containsBackUTF8(LM)", // not implemented
"spanBackUTF8", "spanBackUTF8(LM)"
};
typeName= isUTF16 ? typeNames16[type] : typeNames8[type];
// filter span options
if(type<=3) {
// span forward
if((whichSpans&SPAN_FWD)==0) {
return -1;
}
isForward=TRUE;
} else {
// span backward
if((whichSpans&SPAN_BACK)==0) {
return -1;
}
isForward=FALSE;
}
if((type&1)==0) {
// use USET_SPAN_CONTAINED
if((whichSpans&SPAN_CONTAINED)==0) {
return -1;
}
contained=USET_SPAN_CONTAINED;
} else {
// use USET_SPAN_SIMPLE
if((whichSpans&SPAN_SIMPLE)==0) {
return -1;
}
contained=USET_SPAN_SIMPLE;
}
// Default first span condition for going forward with an uncomplemented set.
spanCondition=USET_SPAN_NOT_CONTAINED;
if(isComplement) {
spanCondition=invertSpanCondition(spanCondition, contained);
}
// First span condition for span(), used to terminate the spanBack() iteration.
firstSpanCondition=spanCondition;
// spanBack(): Its initial span condition is span()'s last span condition,
// which is the opposite of span()'s first span condition
// if we expect an even number of spans.
// (The loop inverts spanCondition (expectCount-1) times
// before the expectCount'th span() call.)
// If we do not compare forward and backward directions, then we do not have an
// expectCount and just start with firstSpanCondition.
if(!isForward && (whichSpans&SPAN_FWD)!=0 && (expectCount&1)==0) {
spanCondition=invertSpanCondition(spanCondition, contained);
}
count=0;
switch(type) {
case 0:
case 1:
start=0;
if(length<0) {
length=slen(s, isUTF16);
}
for(;;) {
start+= isUTF16 ? containsSpanUTF16(set, (const UChar *)s+start, length-start, spanCondition) :
containsSpanUTF8(set, (const char *)s+start, length-start, spanCondition);
if(count<limitsCapacity) {
limits[count]=start;
}
++count;
if(start>=length) {
break;
}
spanCondition=invertSpanCondition(spanCondition, contained);
}
break;
case 2:
case 3:
start=0;
for(;;) {
start+= isUTF16 ? realSet.span((const UChar *)s+start, length>=0 ? length-start : length, spanCondition) :
realSet.spanUTF8((const char *)s+start, length>=0 ? length-start : length, spanCondition);
if(count<limitsCapacity) {
limits[count]=start;
}
++count;
if(length>=0 ? start>=length :
isUTF16 ? ((const UChar *)s)[start]==0 :
((const char *)s)[start]==0
) {
break;
}
spanCondition=invertSpanCondition(spanCondition, contained);
}
break;
case 4:
case 5:
if(length<0) {
length=slen(s, isUTF16);
}
for(;;) {
++count;
if(count<=limitsCapacity) {
limits[limitsCapacity-count]=length;
}
length= isUTF16 ? containsSpanBackUTF16(set, (const UChar *)s, length, spanCondition) :
containsSpanBackUTF8(set, (const char *)s, length, spanCondition);
if(length==0 && spanCondition==firstSpanCondition) {
break;
}
spanCondition=invertSpanCondition(spanCondition, contained);
}
if(count<limitsCapacity) {
memmove(limits, limits+(limitsCapacity-count), count*4);
}
break;
case 6:
case 7:
for(;;) {
++count;
if(count<=limitsCapacity) {
limits[limitsCapacity-count]= length >=0 ? length : slen(s, isUTF16);
}
// Note: Length<0 is tested only for the first spanBack().
// If we wanted to keep length<0 for all spanBack()s, we would have to
// temporarily modify the string by placing a NUL where the previous spanBack() stopped.
length= isUTF16 ? realSet.spanBack((const UChar *)s, length, spanCondition) :
realSet.spanBackUTF8((const char *)s, length, spanCondition);
if(length==0 && spanCondition==firstSpanCondition) {
break;
}
spanCondition=invertSpanCondition(spanCondition, contained);
}
if(count<limitsCapacity) {
memmove(limits, limits+(limitsCapacity-count), count*4);
}
break;
default:
typeName="";
return -1;
}
return count;
}
// sets to be tested; odd index=isComplement
enum {
SLOW,
SLOW_NOT,
FAST,
FAST_NOT,
SET_COUNT
};
static const char *const setNames[SET_COUNT]={
"slow",
"slow.not",
"fast",
"fast.not"
};
/*
* Verify that we get the same results whether we look at text with contains(),
* span() or spanBack(), using unfrozen or frozen versions of the set,
* and using the set or its complement (switching the spanConditions accordingly).
* The latter verifies that
* set.span(spanCondition) == set.complement().span(!spanCondition).
*
* The expectLimits[] are either provided by the caller (with expectCount>=0)
* or returned to the caller (with an input expectCount<0).
*/
void UnicodeSetTest::testSpan(const UnicodeSetWithStrings *sets[4],
const void *s, int32_t length, UBool isUTF16,
uint32_t whichSpans,
int32_t expectLimits[], int32_t &expectCount,
const char *testName, int32_t index) {
int32_t limits[500];
int32_t limitsCount;
int i, j;
const char *typeName;
int type;
for(i=0; i<SET_COUNT; ++i) {
if((i&1)==0) {
// Even-numbered sets are original, uncomplemented sets.
if((whichSpans&SPAN_SET)==0) {
continue;
}
} else {
// Odd-numbered sets are complemented.
if((whichSpans&SPAN_COMPLEMENT)==0) {
continue;
}
}
for(type=0;; ++type) {
limitsCount=getSpans(*sets[i], (UBool)(i&1),
s, length, isUTF16,
whichSpans,
type, typeName,
limits, UPRV_LENGTHOF(limits), expectCount);
if(typeName[0]==0) {
break; // All types tried.
}
if(limitsCount<0) {
continue; // Span option filtered out.
}
if(expectCount<0) {
expectCount=limitsCount;
if(limitsCount>UPRV_LENGTHOF(limits)) {
errln("FAIL: %s[0x%lx].%s.%s span count=%ld > %ld capacity - too many spans",
testName, (long)index, setNames[i], typeName, (long)limitsCount, (long)UPRV_LENGTHOF(limits));
return;
}
memcpy(expectLimits, limits, limitsCount*4);
} else if(limitsCount!=expectCount) {
errln("FAIL: %s[0x%lx].%s.%s span count=%ld != %ld",
testName, (long)index, setNames[i], typeName, (long)limitsCount, (long)expectCount);
} else {
for(j=0; j<limitsCount; ++j) {
if(limits[j]!=expectLimits[j]) {
errln("FAIL: %s[0x%lx].%s.%s span count=%ld limits[%d]=%ld != %ld",
testName, (long)index, setNames[i], typeName, (long)limitsCount,
j, (long)limits[j], (long)expectLimits[j]);
break;
}
}
}
}
}
// Compare span() with containsAll()/containsNone(),
// but only if we have expectLimits[] from the uncomplemented set.
if(isUTF16 && (whichSpans&SPAN_SET)!=0) {
const UChar *s16=(const UChar *)s;
UnicodeString string;
int32_t prev=0, limit, length;
for(i=0; i<expectCount; ++i) {
limit=expectLimits[i];
length=limit-prev;
if(length>0) {
string.setTo(FALSE, s16+prev, length); // read-only alias
if(i&1) {
if(!sets[SLOW]->getSet().containsAll(string)) {
errln("FAIL: %s[0x%lx].%s.containsAll(%ld..%ld)==FALSE contradicts span()",
testName, (long)index, setNames[SLOW], (long)prev, (long)limit);
return;
}
if(!sets[FAST]->getSet().containsAll(string)) {
errln("FAIL: %s[0x%lx].%s.containsAll(%ld..%ld)==FALSE contradicts span()",
testName, (long)index, setNames[FAST], (long)prev, (long)limit);
return;
}
} else {
if(!sets[SLOW]->getSet().containsNone(string)) {
errln("FAIL: %s[0x%lx].%s.containsNone(%ld..%ld)==FALSE contradicts span()",
testName, (long)index, setNames[SLOW], (long)prev, (long)limit);
return;
}
if(!sets[FAST]->getSet().containsNone(string)) {
errln("FAIL: %s[0x%lx].%s.containsNone(%ld..%ld)==FALSE contradicts span()",
testName, (long)index, setNames[FAST], (long)prev, (long)limit);
return;
}
}
}
prev=limit;
}
}
}
// Specifically test either UTF-16 or UTF-8.
void UnicodeSetTest::testSpan(const UnicodeSetWithStrings *sets[4],
const void *s, int32_t length, UBool isUTF16,
uint32_t whichSpans,
const char *testName, int32_t index) {
int32_t expectLimits[500];
int32_t expectCount=-1;
testSpan(sets, s, length, isUTF16, whichSpans, expectLimits, expectCount, testName, index);
}
UBool stringContainsUnpairedSurrogate(const UChar *s, int32_t length) {
UChar c, c2;
if(length>=0) {
while(length>0) {
c=*s++;
--length;
if(0xd800<=c && c<0xe000) {
if(c>=0xdc00 || length==0 || !U16_IS_TRAIL(c2=*s++)) {
return TRUE;
}
--length;
}
}
} else {
while((c=*s++)!=0) {
if(0xd800<=c && c<0xe000) {
if(c>=0xdc00 || !U16_IS_TRAIL(c2=*s++)) {
return TRUE;
}
}
}
}
return FALSE;
}
// Test both UTF-16 and UTF-8 versions of span() etc. on the same sets and text,
// unless either UTF is turned off in whichSpans.
// Testing UTF-16 and UTF-8 together requires that surrogate code points
// have the same contains(c) value as U+FFFD.
void UnicodeSetTest::testSpanBothUTFs(const UnicodeSetWithStrings *sets[4],
const UChar *s16, int32_t length16,
uint32_t whichSpans,
const char *testName, int32_t index) {
int32_t expectLimits[500];
int32_t expectCount;
expectCount=-1; // Get expectLimits[] from testSpan().
if((whichSpans&SPAN_UTF16)!=0) {
testSpan(sets, s16, length16, TRUE, whichSpans, expectLimits, expectCount, testName, index);
}
if((whichSpans&SPAN_UTF8)==0) {
return;
}
// Convert s16[] and expectLimits[] to UTF-8.
uint8_t s8[3000];
int32_t offsets[3000];
const UChar *s16Limit=s16+length16;
char *t=(char *)s8;
char *tLimit=t+sizeof(s8);
int32_t *o=offsets;
UErrorCode errorCode=U_ZERO_ERROR;
// Convert with substitution: Turn unpaired surrogates into U+FFFD.
ucnv_fromUnicode(openUTF8Converter(), &t, tLimit, &s16, s16Limit, o, TRUE, &errorCode);
if(U_FAILURE(errorCode)) {
errln("FAIL: %s[0x%lx] ucnv_fromUnicode(to UTF-8) fails with %s",
testName, (long)index, u_errorName(errorCode));
ucnv_resetFromUnicode(utf8Cnv);
return;
}
int32_t length8=(int32_t)(t-(char *)s8);
// Convert expectLimits[].
int32_t i, j, expect;
for(i=j=0; i<expectCount; ++i) {
expect=expectLimits[i];
if(expect==length16) {
expectLimits[i]=length8;
} else {
while(offsets[j]<expect) {
++j;
}
expectLimits[i]=j;
}
}
testSpan(sets, s8, length8, FALSE, whichSpans, expectLimits, expectCount, testName, index);
}
static UChar32 nextCodePoint(UChar32 c) {
// Skip some large and boring ranges.
switch(c) {
case 0x3441:
return 0x4d7f;
case 0x5100:
return 0x9f00;
case 0xb040:
return 0xd780;
case 0xe041:
return 0xf8fe;
case 0x10100:
return 0x20000;
case 0x20041:
return 0xe0000;
case 0xe0101:
return 0x10fffd;
default:
return c+1;
}
}
// Verify that all implementations represent the same set.
void UnicodeSetTest::testSpanContents(const UnicodeSetWithStrings *sets[4], uint32_t whichSpans, const char *testName) {
// contains(U+FFFD) is inconsistent with contains(some surrogates),
// or the set contains strings with unpaired surrogates which don't translate to valid UTF-8:
// Skip the UTF-8 part of the test - if the string contains surrogates -
// because it is likely to produce a different result.
UBool inconsistentSurrogates=
(!(sets[0]->getSet().contains(0xfffd) ?
sets[0]->getSet().contains(0xd800, 0xdfff) :
sets[0]->getSet().containsNone(0xd800, 0xdfff)) ||
sets[0]->hasStringsWithSurrogates());
UChar s[1000];
int32_t length=0;
uint32_t localWhichSpans;
UChar32 c, first;
for(first=c=0;; c=nextCodePoint(c)) {
if(c>0x10ffff || length>(UPRV_LENGTHOF(s)-U16_MAX_LENGTH)) {
localWhichSpans=whichSpans;
if(stringContainsUnpairedSurrogate(s, length) && inconsistentSurrogates) {
localWhichSpans&=~SPAN_UTF8;
}
testSpanBothUTFs(sets, s, length, localWhichSpans, testName, first);
if(c>0x10ffff) {
break;
}
length=0;
first=c;
}
U16_APPEND_UNSAFE(s, length, c);
}
}
// Test with a particular, interesting string.
// Specify length and try NUL-termination.
void UnicodeSetTest::testSpanUTF16String(const UnicodeSetWithStrings *sets[4], uint32_t whichSpans, const char *testName) {
static const UChar s[]={
0x61, 0x62, 0x20, // Latin, space
0x3b1, 0x3b2, 0x3b3, // Greek
0xd900, // lead surrogate
0x3000, 0x30ab, 0x30ad, // wide space, Katakana
0xdc05, // trail surrogate
0xa0, 0xac00, 0xd7a3, // nbsp, Hangul
0xd900, 0xdc05, // unassigned supplementary
0xd840, 0xdfff, 0xd860, 0xdffe, // Han supplementary
0xd7a4, 0xdc05, 0xd900, 0x2028, // unassigned, surrogates in wrong order, LS
0 // NUL
};
if((whichSpans&SPAN_UTF16)==0) {
return;
}
testSpan(sets, s, -1, TRUE, (whichSpans&~SPAN_UTF8), testName, 0);
testSpan(sets, s, UPRV_LENGTHOF(s)-1, TRUE, (whichSpans&~SPAN_UTF8), testName, 1);
}
void UnicodeSetTest::testSpanUTF8String(const UnicodeSetWithStrings *sets[4], uint32_t whichSpans, const char *testName) {
static const char s[]={
"abc" // Latin
/* trail byte in lead position */
"\x80"
" " // space
/* truncated multi-byte sequences */
"\xd0"
"\xe0"
"\xe1"
"\xed"
"\xee"
"\xf0"
"\xf1"
"\xf4"
"\xf8"
"\xfc"
"\xCE\xB1\xCE\xB2\xCE\xB3" // Greek
/* trail byte in lead position */
"\x80"
"\xe0\x80"
"\xe0\xa0"
"\xe1\x80"
"\xed\x80"
"\xed\xa0"
"\xee\x80"
"\xf0\x80"
"\xf0\x90"
"\xf1\x80"
"\xf4\x80"
"\xf4\x90"
"\xf8\x80"
"\xfc\x80"
"\xE3\x80\x80\xE3\x82\xAB\xE3\x82\xAD" // wide space, Katakana
/* trail byte in lead position */
"\x80"
"\xf0\x80\x80"
"\xf0\x90\x80"
"\xf1\x80\x80"
"\xf4\x80\x80"
"\xf4\x90\x80"
"\xf8\x80\x80"
"\xfc\x80\x80"
"\xC2\xA0\xEA\xB0\x80\xED\x9E\xA3" // nbsp, Hangul
/* trail byte in lead position */
"\x80"
"\xf8\x80\x80\x80"
"\xfc\x80\x80\x80"
"\xF1\x90\x80\x85" // unassigned supplementary
/* trail byte in lead position */
"\x80"
"\xfc\x80\x80\x80\x80"
"\xF0\xA0\x8F\xBF\xF0\xA8\x8F\xBE" // Han supplementary
/* trail byte in lead position */
"\x80"
/* complete sequences but non-shortest forms or out of range etc. */
"\xc0\x80"
"\xe0\x80\x80"
"\xed\xa0\x80"
"\xf0\x80\x80\x80"
"\xf4\x90\x80\x80"
"\xf8\x80\x80\x80\x80"
"\xfc\x80\x80\x80\x80\x80"
"\xfe"
"\xff"
/* trail byte in lead position */
"\x80"
"\xED\x9E\xA4\xE2\x80\xA8" // unassigned, LS, NUL-terminated
};
if((whichSpans&SPAN_UTF8)==0) {
return;
}
testSpan(sets, s, -1, FALSE, (whichSpans&~SPAN_UTF16), testName, 0);
testSpan(sets, s, UPRV_LENGTHOF(s)-1, FALSE, (whichSpans&~SPAN_UTF16), testName, 1);
}
// Take a set of span options and multiply them so that
// each portion only has one of the options a, b and c.
// If b==0, then the set of options is just modified with mask and a.
// If b!=0 and c==0, then the set of options is just modified with mask, a and b.
static int32_t
addAlternative(uint32_t whichSpans[], int32_t whichSpansCount,
uint32_t mask, uint32_t a, uint32_t b, uint32_t c) {
uint32_t s;
int32_t i;
for(i=0; i<whichSpansCount; ++i) {
s=whichSpans[i]&mask;
whichSpans[i]=s|a;
if(b!=0) {
whichSpans[whichSpansCount+i]=s|b;
if(c!=0) {
whichSpans[2*whichSpansCount+i]=s|c;
}
}
}
return b==0 ? whichSpansCount : c==0 ? 2*whichSpansCount : 3*whichSpansCount;
}
#define _63_a "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
#define _64_a "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
#define _63_b "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"
#define _64_b "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"
void UnicodeSetTest::TestSpan() {
// "[...]" is a UnicodeSet pattern.
// "*" performs tests on all Unicode code points and on a selection of
// malformed UTF-8/16 strings.
// "-options" limits the scope of testing for the current set.
// By default, the test verifies that equivalent boundaries are found
// for UTF-16 and UTF-8, going forward and backward,
// alternating USET_SPAN_NOT_CONTAINED with
// either USET_SPAN_CONTAINED or USET_SPAN_SIMPLE.
// Single-character options:
// 8 -- UTF-16 and UTF-8 boundaries may differ.
// Cause: contains(U+FFFD) is inconsistent with contains(some surrogates),
// or the set contains strings with unpaired surrogates
// which do not translate to valid UTF-8.
// c -- set.span() and set.complement().span() boundaries may differ.
// Cause: Set strings are not complemented.
// b -- span() and spanBack() boundaries may differ.
// Cause: Strings in the set overlap, and spanBack(USET_SPAN_CONTAINED)
// and spanBack(USET_SPAN_SIMPLE) are defined to
// match with non-overlapping substrings.
// For example, with a set containing "ab" and "ba",
// span() of "aba" yields boundaries { 0, 2, 3 }
// because the initial "ab" matches from 0 to 2,
// while spanBack() yields boundaries { 0, 1, 3 }
// because the final "ba" matches from 1 to 3.
// l -- USET_SPAN_CONTAINED and USET_SPAN_SIMPLE boundaries may differ.
// Cause: Strings in the set overlap, and a longer match may
// require a sequence including non-longest substrings.
// For example, with a set containing "ab", "abc" and "cd",
// span(contained) of "abcd" spans the entire string
// but span(longest match) only spans the first 3 characters.
// Each "-options" first resets all options and then applies the specified options.
// A "-" without options resets the options.
// The options are also reset for each new set.
// Other strings will be spanned.
static const char *const testdata[]={
"[:ID_Continue:]",
"*",
"[:White_Space:]",
"*",
"[]",
"*",
"[\\u0000-\\U0010FFFF]",
"*",
"[\\u0000\\u0080\\u0800\\U00010000]",
"*",
"[\\u007F\\u07FF\\uFFFF\\U0010FFFF]",
"*",
"[[[:ID_Continue:]-[\\u30ab\\u30ad]]{\\u3000\\u30ab}{\\u3000\\u30ab\\u30ad}]",
"-c",
"*",
"[[[:ID_Continue:]-[\\u30ab\\u30ad]]{\\u30ab\\u30ad}{\\u3000\\u30ab\\u30ad}]",
"-c",
"*",
// Overlapping strings cause overlapping attempts to match.
"[x{xy}{xya}{axy}{ax}]",
"-cl",
// More repetitions of "xya" would take too long with the recursive
// reference implementation.
// containsAll()=FALSE
// test_string 0x14
"xx"
"xyaxyaxyaxya" // set.complement().span(longest match) will stop here.
"xx" // set.complement().span(contained) will stop between the two 'x'es.
"xyaxyaxyaxya"
"xx"
"xyaxyaxyaxya" // span() ends here.
"aaa",
// containsAll()=TRUE
// test_string 0x15
"xx"
"xyaxyaxyaxya"
"xx"
"xyaxyaxyaxya"
"xx"
"xyaxyaxyaxy",
"-bc",
// test_string 0x17
"byayaxya", // span() -> { 4, 7, 8 } spanBack() -> { 5, 8 }
"-c",
"byayaxy", // span() -> { 4, 7 } complement.span() -> { 7 }
"byayax", // span() -> { 4, 6 } complement.span() -> { 6 }
"-",
"byaya", // span() -> { 5 }
"byay", // span() -> { 4 }
"bya", // span() -> { 3 }
// span(longest match) will not span the whole string.
"[a{ab}{bc}]",
"-cl",
// test_string 0x21
"abc",
"[a{ab}{abc}{cd}]",
"-cl",
"acdabcdabccd",
// spanBack(longest match) will not span the whole string.
"[c{ab}{bc}]",
"-cl",
"abc",
"[d{cd}{bcd}{ab}]",
"-cl",
"abbcdabcdabd",
// Test with non-ASCII set strings - test proper handling of surrogate pairs
// and UTF-8 trail bytes.
// Copies of above test sets and strings, but transliterated to have
// different code points with similar trail units.
// Previous: a b c d
// Unicode: 042B 30AB 200AB 204AB
// UTF-16: 042B 30AB D840 DCAB D841 DCAB
// UTF-8: D0 AB E3 82 AB F0 A0 82 AB F0 A0 92 AB
"[\\u042B{\\u042B\\u30AB}{\\u042B\\u30AB\\U000200AB}{\\U000200AB\\U000204AB}]",
"-cl",
"\\u042B\\U000200AB\\U000204AB\\u042B\\u30AB\\U000200AB\\U000204AB\\u042B\\u30AB\\U000200AB\\U000200AB\\U000204AB",
"[\\U000204AB{\\U000200AB\\U000204AB}{\\u30AB\\U000200AB\\U000204AB}{\\u042B\\u30AB}]",
"-cl",
"\\u042B\\u30AB\\u30AB\\U000200AB\\U000204AB\\u042B\\u30AB\\U000200AB\\U000204AB\\u042B\\u30AB\\U000204AB",
// Stress bookkeeping and recursion.
// The following strings are barely doable with the recursive
// reference implementation.
// The not-contained character at the end prevents an early exit from the span().
"[b{bb}]",
"-c",
// test_string 0x33
"bbbbbbbbbbbbbbbbbbbbbbbb-",
// On complement sets, span() and spanBack() get different results
// because b is not in the complement set and there is an odd number of b's
// in the test string.
"-bc",
"bbbbbbbbbbbbbbbbbbbbbbbbb-",
// Test with set strings with an initial or final code point span
// longer than 254.
"[a{" _64_a _64_a _64_a _64_a "b}"
"{a" _64_b _64_b _64_b _64_b "}]",
"-c",
_64_a _64_a _64_a _63_a "b",
_64_a _64_a _64_a _64_a "b",
_64_a _64_a _64_a _64_a "aaaabbbb",
"a" _64_b _64_b _64_b _63_b,
"a" _64_b _64_b _64_b _64_b,
"aaaabbbb" _64_b _64_b _64_b _64_b,
// Test with strings containing unpaired surrogates.
// They are not representable in UTF-8, and a leading trail surrogate
// and a trailing lead surrogate must not match in the middle of a proper surrogate pair.
// U+20001 == \\uD840\\uDC01
// U+20400 == \\uD841\\uDC00
"[a\\U00020001\\U00020400{ab}{b\\uD840}{\\uDC00a}]",
"-8cl",
"aaab\\U00020001ba\\U00020400aba\\uD840ab\\uD840\\U00020000b\\U00020000a\\U00020000\\uDC00a\\uDC00babbb"
};
uint32_t whichSpans[96]={ SPAN_ALL };
int32_t whichSpansCount=1;
UnicodeSet *sets[SET_COUNT]={ NULL };
const UnicodeSetWithStrings *sets_with_str[SET_COUNT]={ NULL };
char testName[1024];
char *testNameLimit=testName;
int32_t i, j;
for(i=0; i<UPRV_LENGTHOF(testdata); ++i) {
const char *s=testdata[i];
if(s[0]=='[') {
// Create new test sets from this pattern.
for(j=0; j<SET_COUNT; ++j) {
delete sets_with_str[j];
delete sets[j];
}
UErrorCode errorCode=U_ZERO_ERROR;
sets[SLOW]=new UnicodeSet(UnicodeString(s, -1, US_INV).unescape(), errorCode);
if(U_FAILURE(errorCode)) {
dataerrln("FAIL: Unable to create UnicodeSet(%s) - %s", s, u_errorName(errorCode));
break;
}
sets[SLOW_NOT]=new UnicodeSet(*sets[SLOW]);
sets[SLOW_NOT]->complement();
// Intermediate set: Test cloning of a frozen set.
UnicodeSet *fast=new UnicodeSet(*sets[SLOW]);
fast->freeze();
sets[FAST]=(UnicodeSet *)fast->clone();
delete fast;
UnicodeSet *fastNot=new UnicodeSet(*sets[SLOW_NOT]);
fastNot->freeze();
sets[FAST_NOT]=(UnicodeSet *)fastNot->clone();
delete fastNot;
for(j=0; j<SET_COUNT; ++j) {
sets_with_str[j]=new UnicodeSetWithStrings(*sets[j]);
}
strcpy(testName, s);
testNameLimit=strchr(testName, 0);
*testNameLimit++=':';
*testNameLimit=0;
whichSpans[0]=SPAN_ALL;
whichSpansCount=1;
} else if(s[0]=='-') {
whichSpans[0]=SPAN_ALL;
whichSpansCount=1;
while(*++s!=0) {
switch(*s) {
case 'c':
whichSpansCount=addAlternative(whichSpans, whichSpansCount,
~SPAN_POLARITY,
SPAN_SET,
SPAN_COMPLEMENT,
0);
break;
case 'b':
whichSpansCount=addAlternative(whichSpans, whichSpansCount,
~SPAN_DIRS,
SPAN_FWD,
SPAN_BACK,
0);
break;
case 'l':
// test USET_SPAN_CONTAINED FWD & BACK, and separately
// USET_SPAN_SIMPLE only FWD, and separately
// USET_SPAN_SIMPLE only BACK
whichSpansCount=addAlternative(whichSpans, whichSpansCount,
~(SPAN_DIRS|SPAN_CONDITION),
SPAN_DIRS|SPAN_CONTAINED,
SPAN_FWD|SPAN_SIMPLE,
SPAN_BACK|SPAN_SIMPLE);
break;
case '8':
whichSpansCount=addAlternative(whichSpans, whichSpansCount,
~SPAN_UTFS,
SPAN_UTF16,
SPAN_UTF8,
0);
break;
default:
errln("FAIL: unrecognized span set option in \"%s\"", testdata[i]);
break;
}
}
} else if(0==strcmp(s, "*")) {
strcpy(testNameLimit, "bad_string");
for(j=0; j<whichSpansCount; ++j) {
if(whichSpansCount>1) {
sprintf(testNameLimit+10 /* strlen("bad_string") */,
"%%0x%3x",
whichSpans[j]);
}
testSpanUTF16String(sets_with_str, whichSpans[j], testName);
testSpanUTF8String(sets_with_str, whichSpans[j], testName);
}
strcpy(testNameLimit, "contents");
for(j=0; j<whichSpansCount; ++j) {
if(whichSpansCount>1) {
sprintf(testNameLimit+8 /* strlen("contents") */,
"%%0x%3x",
whichSpans[j]);
}
testSpanContents(sets_with_str, whichSpans[j], testName);
}
} else {
UnicodeString string=UnicodeString(s, -1, US_INV).unescape();
strcpy(testNameLimit, "test_string");
for(j=0; j<whichSpansCount; ++j) {
if(whichSpansCount>1) {
sprintf(testNameLimit+11 /* strlen("test_string") */,
"%%0x%3x",
whichSpans[j]);
}
testSpanBothUTFs(sets_with_str, string.getBuffer(), string.length(), whichSpans[j], testName, i);
}
}
}
for(j=0; j<SET_COUNT; ++j) {
delete sets_with_str[j];
delete sets[j];
}
}
// Test select patterns and strings, and test USET_SPAN_SIMPLE.
void UnicodeSetTest::TestStringSpan() {
static const char *pattern="[x{xy}{xya}{axy}{ax}]";
static const char *const string=
"xx"
"xyaxyaxyaxyaxyaxyaxyaxyaxyaxyaxyaxyaxyaxyaxyaxyaxyaxyaxyaxyaxya"
"xx"
"xyaxyaxyaxyaxyaxyaxyaxyaxyaxyaxyaxyaxyaxyaxyaxyaxyaxyaxyaxyaxya"
"xx"
"xyaxyaxyaxyaxyaxyaxyaxyaxyaxyaxyaxyaxyaxyaxyaxyaxyaxyaxyaxyaxy"
"aaaa";
UErrorCode errorCode=U_ZERO_ERROR;
UnicodeString pattern16=UnicodeString(pattern, -1, US_INV);
UnicodeSet set(pattern16, errorCode);
if(U_FAILURE(errorCode)) {
errln("FAIL: Unable to create UnicodeSet(%s) - %s", pattern, u_errorName(errorCode));
return;
}
UnicodeString string16=UnicodeString(string, -1, US_INV).unescape();
if(set.containsAll(string16)) {
errln("FAIL: UnicodeSet(%s).containsAll(%s) should be FALSE", pattern, string);
}
// Remove trailing "aaaa".
string16.truncate(string16.length()-4);
if(!set.containsAll(string16)) {
errln("FAIL: UnicodeSet(%s).containsAll(%s[:-4]) should be TRUE", pattern, string);
}
string16=UNICODE_STRING_SIMPLE("byayaxya");
const UChar *s16=string16.getBuffer();
int32_t length16=string16.length();
(void)length16; // Suppress set but not used warning.
if( set.span(s16, 8, USET_SPAN_NOT_CONTAINED)!=4 ||
set.span(s16, 7, USET_SPAN_NOT_CONTAINED)!=4 ||
set.span(s16, 6, USET_SPAN_NOT_CONTAINED)!=4 ||
set.span(s16, 5, USET_SPAN_NOT_CONTAINED)!=5 ||
set.span(s16, 4, USET_SPAN_NOT_CONTAINED)!=4 ||
set.span(s16, 3, USET_SPAN_NOT_CONTAINED)!=3
) {
errln("FAIL: UnicodeSet(%s).span(while not) returns the wrong value", pattern);
}
pattern="[a{ab}{abc}{cd}]";
pattern16=UnicodeString(pattern, -1, US_INV);
set.applyPattern(pattern16, errorCode);
if(U_FAILURE(errorCode)) {
errln("FAIL: Unable to create UnicodeSet(%s) - %s", pattern, u_errorName(errorCode));
return;
}
string16=UNICODE_STRING_SIMPLE("acdabcdabccd");
s16=string16.getBuffer();
length16=string16.length();
if( set.span(s16, 12, USET_SPAN_CONTAINED)!=12 ||
set.span(s16, 12, USET_SPAN_SIMPLE)!=6 ||
set.span(s16+7, 5, USET_SPAN_SIMPLE)!=5
) {
errln("FAIL: UnicodeSet(%s).span(while longest match) returns the wrong value", pattern);
}
pattern="[d{cd}{bcd}{ab}]";
pattern16=UnicodeString(pattern, -1, US_INV);
set.applyPattern(pattern16, errorCode).freeze();
if(U_FAILURE(errorCode)) {
errln("FAIL: Unable to create UnicodeSet(%s) - %s", pattern, u_errorName(errorCode));
return;
}
string16=UNICODE_STRING_SIMPLE("abbcdabcdabd");
s16=string16.getBuffer();
length16=string16.length();
if( set.spanBack(s16, 12, USET_SPAN_CONTAINED)!=0 ||
set.spanBack(s16, 12, USET_SPAN_SIMPLE)!=6 ||
set.spanBack(s16, 5, USET_SPAN_SIMPLE)!=0
) {
errln("FAIL: UnicodeSet(%s).spanBack(while longest match) returns the wrong value", pattern);
}
}
/**
* Including collationroot.h fails here with
1>c:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\include\driverspecs.h(142): error C2008: '$' : unexpected in macro definition
* .. so, we skip this test on Windows.
*
* the cause is that intltest builds with /Za which disables language extensions - which means
* windows header files can't be used.
*/
#if !UCONFIG_NO_COLLATION && !U_PLATFORM_HAS_WIN32_API
#include "collationroot.h"
#include "collationtailoring.h"
#endif
void UnicodeSetTest::TestUCAUnsafeBackwards() {
#if U_PLATFORM_HAS_WIN32_API
infoln("Skipping TestUCAUnsafeBackwards() - can't include collationroot.h on Windows without language extensions!");
#elif !UCONFIG_NO_COLLATION
UErrorCode errorCode = U_ZERO_ERROR;
// Get the unsafeBackwardsSet
const CollationCacheEntry *rootEntry = CollationRoot::getRootCacheEntry(errorCode);
if(U_FAILURE(errorCode)) {
dataerrln("FAIL: %s getting root cache entry", u_errorName(errorCode));
return;
}
//const UVersionInfo &version = rootEntry->tailoring->version;
const UnicodeSet *unsafeBackwardSet = rootEntry->tailoring->unsafeBackwardSet;
checkSerializeRoundTrip(*unsafeBackwardSet, errorCode);
if(!logKnownIssue("11891","UnicodeSet fails to round trip on CollationRoot...unsafeBackwards set")) {
// simple test case
// TODO(ticket #11891): Simplify this test function to this simple case. Rename it appropriately.
// TODO(ticket #11891): Port test to Java. Is this a bug there, too?
UnicodeSet surrogates;
surrogates.add(0xd83a); // a lead surrogate
surrogates.add(0xdc00, 0xdfff); // a range of trail surrogates
UnicodeString pat;
surrogates.toPattern(pat, FALSE); // bad: [ 0xd83a, 0xdc00, 0x2d, 0xdfff ]
// TODO: Probably fix either UnicodeSet::_generatePattern() or _appendToPat()
// so that at least one type of surrogate code points are escaped,
// or (minimally) so that adjacent lead+trail surrogate code points are escaped.
errorCode = U_ZERO_ERROR;
UnicodeSet s2;
s2.applyPattern(pat, errorCode); // looks like invalid range [ 0x1e800, 0x2d, 0xdfff ]
if(U_FAILURE(errorCode)) {
errln("FAIL: surrogates to/from pattern - %s", u_errorName(errorCode));
} else {
checkEqual(surrogates, s2, "surrogates to/from pattern");
}
// This occurs in the UCA unsafe-backwards set.
checkRoundTrip(*unsafeBackwardSet);
}
#endif
}
|
#include "pybulletphysics.h"
static PyObject*
StaticPlaneShape_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
PyObject *py_vector3 = NULL;
float planeConstant = 0;
if (!PyArg_ParseTuple(args, "Of", &py_vector3, &planeConstant)) {
return NULL;
}
bulletphysics_CollisionShapeObject *self = (bulletphysics_CollisionShapeObject *)type->tp_alloc(type, 0);
if (self != NULL) {
bulletphysics_Vector3Object *vector3 = (bulletphysics_Vector3Object *) py_vector3;
self->shape = new btStaticPlaneShape(*(vector3->vector), planeConstant );
}
return (PyObject *)self;
}
static PyTypeObject bulletphysics_StaticPlaneShapeType = {
PyObject_HEAD_INIT(NULL)
0, /*ob_size*/
"bulletphysics.StaticPlaneShape", /*tp_name*/
sizeof(bulletphysics_CollisionShapeObject), /*tp_basicsize*/
0, /*tp_itemsize*/
0, /*tp_dealloc*/
0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_compare*/
0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash */
0, /*tp_call*/
0, /*tp_str*/
0, /*tp_getattro*/
0, /*tp_setattro*/
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /*tp_flags*/
"StaticPlaneShape object", /* tp_doc */
};
extern PyTypeObject bulletphysics_CollisionShapeType;
void pybulletphysics_add_StaticPlaneShape(PyObject *module) {
bulletphysics_StaticPlaneShapeType.tp_base = &bulletphysics_CollisionShapeType;
bulletphysics_StaticPlaneShapeType.tp_new = StaticPlaneShape_new;
if (PyType_Ready(&bulletphysics_StaticPlaneShapeType) < 0)
return;
Py_INCREF(&bulletphysics_StaticPlaneShapeType);
PyModule_AddObject(module, "StaticPlaneShape", (PyObject *)&bulletphysics_StaticPlaneShapeType);
}
|
/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2013-2018 Inviwo Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*********************************************************************************/
#include <modules/qtwidgets/properties/transferfunctionpropertydialog.h>
#include <modules/qtwidgets/properties/transferfunctionpropertywidgetqt.h>
#include <modules/qtwidgets/properties/collapsiblegroupboxwidgetqt.h>
#include <modules/qtwidgets/properties/transferfunctioneditorcontrolpoint.h>
#include <modules/qtwidgets/inviwofiledialog.h>
#include <modules/qtwidgets/colorwheel.h>
#include <modules/qtwidgets/rangesliderqt.h>
#include <inviwo/core/util/filesystem.h>
#include <inviwo/core/util/fileextension.h>
#include <inviwo/core/io/datareaderexception.h>
#include <inviwo/core/io/datawriter.h>
#include <warn/push>
#include <warn/ignore/all>
#include <QImage>
#include <QGraphicsItem>
#include <QPushButton>
#include <QSizePolicy>
#include <QComboBox>
#include <QGradientStops>
#include <QPixmap>
#include <warn/pop>
namespace inviwo {
TransferFunctionPropertyDialog::TransferFunctionPropertyDialog(TransferFunctionProperty* tfProperty)
: PropertyEditorWidgetQt(tfProperty, "Transfer Function Editor", "TransferFunctionEditorWidget")
, TransferFunctionObserver()
, sliderRange_(static_cast<int>(tfProperty->get().getTextureSize()))
, tfProperty_(tfProperty)
, tfEditor_(nullptr)
, tfEditorView_(nullptr)
, tfPixmap_(nullptr)
, gradient_(0, 0, 100, 20) {
tfProperty_->get().addObserver(this);
tfEditor_ = util::make_unique<TransferFunctionEditor>(tfProperty_, this);
connect(tfEditor_.get(), &TransferFunctionEditor::colorChanged, this,
[this](const QColor& color) {
colorWheel_->blockSignals(true);
colorWheel_->setColor(color);
colorWheel_->blockSignals(false);
});
tfEditorView_ = new TransferFunctionEditorView(tfProperty_);
// put origin to bottom left corner
ivec2 minEditorDims = vec2(255, 100);
tfEditorView_->setFocusPolicy(Qt::StrongFocus);
tfEditorView_->scale(1.0, -1.0);
tfEditorView_->setAlignment(Qt::AlignLeft | Qt::AlignBottom);
tfEditorView_->setMinimumSize(minEditorDims.x, minEditorDims.y);
tfEditorView_->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
tfEditorView_->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
tfEditorView_->setScene(tfEditor_.get());
zoomVSlider_ = new RangeSliderQt(Qt::Vertical, this, true);
zoomVSlider_->setRange(0, sliderRange_);
zoomVSlider_->setMinSeparation(5);
// flip slider values to compensate for vertical slider layout
zoomVSlider_->setValue(
sliderRange_ - static_cast<int>(tfProperty_->getZoomV().y * sliderRange_),
sliderRange_ - static_cast<int>(tfProperty_->getZoomV().x * sliderRange_));
connect(zoomVSlider_, &RangeSliderQt::valuesChanged, this,
&TransferFunctionPropertyDialog::changeVerticalZoom);
zoomVSlider_->setTooltipFormat([range = sliderRange_](int /*handle*/, int val) {
return toString(1.0f - static_cast<float>(val) / range);
});
zoomHSlider_ = new RangeSliderQt(Qt::Horizontal, this, true);
zoomHSlider_->setRange(0, sliderRange_);
zoomHSlider_->setMinSeparation(5);
zoomHSlider_->setValue(static_cast<int>(tfProperty_->getZoomH().x * sliderRange_),
static_cast<int>(tfProperty_->getZoomH().y * sliderRange_));
connect(zoomHSlider_, &RangeSliderQt::valuesChanged, this,
&TransferFunctionPropertyDialog::changeHorizontalZoom);
zoomHSlider_->setTooltipFormat([range = sliderRange_](int /*handle*/, int val) {
return toString(static_cast<float>(val) / range);
});
maskSlider_ = new RangeSliderQt(Qt::Horizontal, this, true);
maskSlider_->setRange(0, sliderRange_);
maskSlider_->setValue(static_cast<int>(tfProperty_->getMask().x * sliderRange_),
static_cast<int>(tfProperty_->getMask().y * sliderRange_));
connect(maskSlider_, &RangeSliderQt::valuesChanged, this,
&TransferFunctionPropertyDialog::changeMask);
maskSlider_->setTooltipFormat([range = sliderRange_](int /*handle*/, int val) {
return toString(static_cast<float>(val) / range);
});
colorWheel_ = util::make_unique<ColorWheel>();
connect(colorWheel_.get(), &ColorWheel::colorChange, tfEditor_.get(),
&TransferFunctionEditor::setPointColor);
btnClearTF_ = new QPushButton("Reset");
connect(btnClearTF_, &QPushButton::clicked, [this]() { tfEditor_->resetTransferFunction(); });
btnClearTF_->setStyleSheet(QString("min-width: 30px; padding-left: 7px; padding-right: 7px;"));
btnImportTF_ = new QPushButton("Import");
connect(btnImportTF_, &QPushButton::clicked, [this]() { importTransferFunction(); });
btnImportTF_->setStyleSheet(QString("min-width: 30px; padding-left: 7px; padding-right: 7px;"));
btnExportTF_ = new QPushButton("Export");
connect(btnExportTF_, &QPushButton::clicked, [this]() { exportTransferFunction(); });
btnExportTF_->setStyleSheet(QString("min-width: 30px; padding-left: 7px; padding-right: 7px;"));
tfPreview_ = new QLabel();
tfPreview_->setMinimumSize(1, 20);
QSizePolicy sliderPol = tfPreview_->sizePolicy();
sliderPol.setHorizontalStretch(3);
tfPreview_->setSizePolicy(sliderPol);
chkShowHistogram_ = new QComboBox();
chkShowHistogram_->addItem("Histogram: Off");
chkShowHistogram_->addItem("Histogram: 100%");
chkShowHistogram_->addItem("Histogram: 99%");
chkShowHistogram_->addItem("Histogram: 95%");
chkShowHistogram_->addItem("Histogram: 90%");
chkShowHistogram_->addItem("Histogram: Log");
chkShowHistogram_->setCurrentIndex(static_cast<int>(tfProperty_->getHistogramMode()));
connect(chkShowHistogram_,
static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this,
&TransferFunctionPropertyDialog::showHistogram);
pointMoveMode_ = new QComboBox();
pointMoveMode_->addItem("Point Movement: Free");
pointMoveMode_->addItem("Point Movement: Restrict");
pointMoveMode_->addItem("Point Movement: Push");
pointMoveMode_->setCurrentIndex(0);
connect(pointMoveMode_, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged),
this, &TransferFunctionPropertyDialog::changeMoveMode);
QFrame* leftPanel = new QFrame(this);
QGridLayout* leftLayout = new QGridLayout();
leftLayout->setContentsMargins(0, 0, 0, 0);
leftLayout->setSpacing(7);
leftLayout->addWidget(zoomVSlider_, 0, 0);
leftLayout->addWidget(tfEditorView_, 0, 1);
leftLayout->addWidget(zoomHSlider_, 1, 1);
leftLayout->addWidget(tfPreview_, 2, 1);
leftLayout->addWidget(maskSlider_, 3, 1);
leftPanel->setLayout(leftLayout);
QFrame* rightPanel = new QFrame(this);
QVBoxLayout* rightLayout = new QVBoxLayout();
rightLayout->setContentsMargins(0, 0, 0, 0);
rightLayout->setSpacing(7);
rightLayout->setAlignment(Qt::AlignTop);
rightLayout->addWidget(colorWheel_.get());
rightLayout->addWidget(chkShowHistogram_);
rightLayout->addWidget(pointMoveMode_);
rightLayout->addStretch(3);
QHBoxLayout* rowLayout = new QHBoxLayout();
rowLayout->addWidget(btnClearTF_);
rowLayout->addWidget(btnImportTF_);
rowLayout->addWidget(btnExportTF_);
rightLayout->addLayout(rowLayout);
rightPanel->setLayout(rightLayout);
QWidget* mainPanel = new QWidget(this);
QHBoxLayout* mainLayout = new QHBoxLayout();
mainLayout->setContentsMargins(7, 7, 7, 7);
mainLayout->setSpacing(7);
mainLayout->addWidget(leftPanel);
mainLayout->addWidget(rightPanel);
mainPanel->setLayout(mainLayout);
setWidget(mainPanel);
updateFromProperty();
if (!tfProperty_->getVolumeInport()) {
chkShowHistogram_->setVisible(false);
}
loadState();
}
TransferFunctionPropertyDialog::~TransferFunctionPropertyDialog() {
tfEditor_->disconnect();
hide();
}
void TransferFunctionPropertyDialog::updateFromProperty() {
if (!tfProperty_->getOwner()) return;
auto processorName = tfProperty_->getOwner()->getProcessor()->getDisplayName();
auto windowTitle =
"Transfer Function Editor - " + tfProperty_->getDisplayName() + " (" + processorName + ")";
setWindowTitle(utilqt::toQString(windowTitle));
TransferFunction& transFunc = tfProperty_->get();
QVector<QGradientStop> gradientStops;
for (size_t i = 0; i < transFunc.getNumPoints(); i++) {
const auto curPoint = transFunc.getPoint(i);
vec4 curColor = curPoint->getRGBA();
// increase alpha to allow better visibility by 1 - (a - 1)^4
const float factor = (1.0f - curColor.a) * (1.0f - curColor.a);
curColor.a = 1.0f - factor * factor;
gradientStops.append(QGradientStop(
curPoint->getPos(), QColor::fromRgbF(curColor.r, curColor.g, curColor.b, curColor.a)));
}
gradient_.setStops(gradientStops);
updateTFPreview();
}
void TransferFunctionPropertyDialog::updateTFPreview() {
int gradientWidth = tfPreview_->width();
gradient_.setFinalStop(gradientWidth, 0);
if (!tfPixmap_ || gradientWidth != tfPixmap_->width()) {
tfPixmap_ = util::make_unique<QPixmap>(gradientWidth, 20);
}
QPainter tfPainter(tfPixmap_.get());
QPixmap checkerBoard(10, 10);
QPainter checkerBoardPainter(&checkerBoard);
checkerBoardPainter.fillRect(0, 0, 5, 5, Qt::lightGray);
checkerBoardPainter.fillRect(5, 0, 5, 5, Qt::darkGray);
checkerBoardPainter.fillRect(0, 5, 5, 5, Qt::darkGray);
checkerBoardPainter.fillRect(5, 5, 5, 5, Qt::lightGray);
checkerBoardPainter.end();
tfPainter.fillRect(0, 0, gradientWidth, 20, QBrush(checkerBoard));
tfPainter.fillRect(0, 0, gradientWidth, 20, gradient_);
// draw masking indicators
if (tfProperty_->getMask().x > 0.0f) {
tfPainter.fillRect(0, 0, static_cast<int>(tfProperty_->getMask().x * gradientWidth), 20,
QColor(25, 25, 25, 100));
tfPainter.drawLine(static_cast<int>(tfProperty_->getMask().x * gradientWidth), 0,
static_cast<int>(tfProperty_->getMask().x * gradientWidth), 20);
}
if (tfProperty_->getMask().y < 1.0f) {
tfPainter.fillRect(static_cast<int>(tfProperty_->getMask().y * gradientWidth), 0,
static_cast<int>((1.0f - tfProperty_->getMask().y) * gradientWidth) + 1,
20, QColor(25, 25, 25, 150));
tfPainter.drawLine(static_cast<int>(tfProperty_->getMask().y * gradientWidth), 0,
static_cast<int>(tfProperty_->getMask().y * gradientWidth), 20);
}
tfPreview_->setPixmap(*tfPixmap_);
}
void TransferFunctionPropertyDialog::changeVerticalZoom(int zoomMin, int zoomMax) {
// normalize zoom values, as sliders in TransferFunctionPropertyDialog
// have the range [0...100]
// and flip/rescale values to compensate slider layout
const auto zoomMaxF = static_cast<float>(sliderRange_ - zoomMin) / sliderRange_;
const auto zoomMinF = static_cast<float>(sliderRange_ - zoomMax) / sliderRange_;
tfProperty_->setZoomV(zoomMinF, zoomMaxF);
}
void TransferFunctionPropertyDialog::changeHorizontalZoom(int zoomMin, int zoomMax) {
const auto zoomMinF = static_cast<float>(zoomMin) / sliderRange_;
const auto zoomMaxF = static_cast<float>(zoomMax) / sliderRange_;
tfProperty_->setZoomH(zoomMinF, zoomMaxF);
}
// Connected to valuesChanged on the maskSlider
void TransferFunctionPropertyDialog::changeMask(int maskMin, int maskMax) {
const auto maskMinF = static_cast<float>(maskMin) / sliderRange_;
const auto maskMaxF = static_cast<float>(maskMax) / sliderRange_;
tfProperty_->setMask(maskMinF, maskMaxF);
updateTFPreview();
}
void TransferFunctionPropertyDialog::importTransferFunction() {
InviwoFileDialog importFileDialog(this, "Import transfer function", "transferfunction");
importFileDialog.setAcceptMode(AcceptMode::Open);
importFileDialog.setFileMode(FileMode::ExistingFile);
importFileDialog.addExtension("itf", "Inviwo Transfer Function");
importFileDialog.addExtension("png", "Transfer Function Image");
importFileDialog.addExtension("", "All files"); // this will add "All files (*)"
if (importFileDialog.exec()) {
QString file = importFileDialog.selectedFiles().at(0);
try {
NetworkLock lock(tfProperty_);
tfProperty_->get().load(file.toLocal8Bit().constData(),
importFileDialog.getSelectedFileExtension());
} catch (DataReaderException& e) {
util::log(e.getContext(), e.getMessage(), LogLevel::Error, LogAudience::User);
}
}
}
void TransferFunctionPropertyDialog::exportTransferFunction() {
InviwoFileDialog exportFileDialog(this, "Export transfer function", "transferfunction");
exportFileDialog.setAcceptMode(AcceptMode::Save);
exportFileDialog.setFileMode(FileMode::AnyFile);
exportFileDialog.addExtension("itf", "Inviwo Transfer Function");
exportFileDialog.addExtension("png", "Transfer Function Image");
exportFileDialog.addExtension("", "All files"); // this will add "All files (*)"
if (exportFileDialog.exec()) {
const std::string file = exportFileDialog.selectedFiles().at(0).toLocal8Bit().constData();
const auto fileExt = exportFileDialog.getSelectedFileExtension();
try {
tfProperty_->get().save(file, fileExt);
util::log(IvwContext, "Data exported to disk: " + file, LogLevel::Info,
LogAudience::User);
} catch (DataWriterException& e) {
util::log(e.getContext(), e.getMessage(), LogLevel::Error, LogAudience::User);
}
}
}
void TransferFunctionPropertyDialog::showHistogram(int type) {
tfProperty_->setHistogramMode(static_cast<HistogramMode>(type));
}
void TransferFunctionPropertyDialog::resizeEvent(QResizeEvent* event) {
PropertyEditorWidgetQt::resizeEvent(event);
updateTFPreview();
}
void TransferFunctionPropertyDialog::showEvent(QShowEvent* event) {
updateTFPreview();
tfEditorView_->update();
PropertyEditorWidgetQt::showEvent(event);
}
void TransferFunctionPropertyDialog::onControlPointAdded(TransferFunctionDataPoint* p) {
tfEditor_->onControlPointAdded(p);
updateFromProperty();
}
void TransferFunctionPropertyDialog::onControlPointRemoved(TransferFunctionDataPoint* p) {
tfEditor_->onControlPointRemoved(p);
updateFromProperty();
}
void TransferFunctionPropertyDialog::onControlPointChanged(const TransferFunctionDataPoint* p) {
tfEditor_->onControlPointChanged(p);
updateFromProperty();
}
TransferFunctionEditorView* TransferFunctionPropertyDialog::getEditorView() const {
return tfEditorView_;
}
void TransferFunctionPropertyDialog::setReadOnly(bool readonly) {
colorWheel_->setDisabled(readonly);
tfEditorView_->setDisabled(readonly);
btnClearTF_->setDisabled(readonly);
btnImportTF_->setDisabled(readonly);
pointMoveMode_->setDisabled(readonly);
maskSlider_->setDisabled(readonly);
}
void TransferFunctionPropertyDialog::changeMoveMode(int i) { tfEditor_->setMoveMode(i); }
} // namespace inviwo
|
#include "utils.hpp"
#include "mapnik_geometry.hpp"
// mapnik
#include <mapnik/wkt/wkt_factory.hpp>
// boost
#include MAPNIK_MAKE_SHARED_INCLUDE
Persistent<FunctionTemplate> Geometry::constructor;
void Geometry::Initialize(Handle<Object> target) {
NanScope();
Local<FunctionTemplate> lcons = NanNew<FunctionTemplate>(Geometry::New);
lcons->InstanceTemplate()->SetInternalFieldCount(1);
lcons->SetClassName(NanNew("Geometry"));
NODE_SET_PROTOTYPE_METHOD(lcons, "extent", extent);
NODE_SET_PROTOTYPE_METHOD(lcons, "type", type);
NODE_MAPNIK_DEFINE_CONSTANT(lcons->GetFunction(),
"Point",MAPNIK_POINT)
NODE_MAPNIK_DEFINE_CONSTANT(lcons->GetFunction(),
"LineString",MAPNIK_LINESTRING)
NODE_MAPNIK_DEFINE_CONSTANT(lcons->GetFunction(),
"Polygon",MAPNIK_POLYGON)
target->Set(NanNew("Geometry"), lcons->GetFunction());
NanAssignPersistent(constructor, lcons);
}
Geometry::Geometry() :
ObjectWrap(),
this_() {}
Geometry::~Geometry()
{
}
NAN_METHOD(Geometry::New)
{
NanScope();
//if (!args.IsConstructCall()) {
// NanThrowError("Cannot call constructor as function, you need to use 'new' keyword");
// NanReturnUndefined();
//}
if (args[0]->IsExternal())
{
Local<External> ext = args[0].As<External>();
void* ptr = ext->Value();
Geometry* g = static_cast<Geometry*>(ptr);
g->Wrap(args.This());
NanReturnValue(args.This());
}
else
{
NanThrowError("a mapnik.Geometry cannot be created directly - rather you should create mapnik.Path objects which can contain one or more geometries");
NanReturnUndefined();
}
NanReturnValue(args.This());
}
NAN_METHOD(Geometry::extent)
{
NanScope();
Geometry* g = node::ObjectWrap::Unwrap<Geometry>(args.Holder());
Local<Array> a = NanNew<Array>(4);
mapnik::box2d<double> const& e = g->this_->envelope();
a->Set(0, NanNew<Number>(e.minx()));
a->Set(1, NanNew<Number>(e.miny()));
a->Set(2, NanNew<Number>(e.maxx()));
a->Set(3, NanNew<Number>(e.maxy()));
NanReturnValue(a);
}
NAN_METHOD(Geometry::type)
{
NanScope();
Geometry* g = node::ObjectWrap::Unwrap<Geometry>(args.Holder());
MAPNIK_GEOM_TYPE type = g->this_->type();
// TODO - can we return the actual symbol?
//NanReturnValue(constructor->GetFunction()->Get(NanNew("Point")));
NanReturnValue(NanNew(static_cast<int>(type)));
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.