hexsha stringlengths 40 40 | size int64 22 2.4M | ext stringclasses 5
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 260 | max_stars_repo_name stringlengths 5 109 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 260 | max_issues_repo_name stringlengths 5 109 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 260 | max_forks_repo_name stringlengths 5 109 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 22 2.4M | avg_line_length float64 5 169k | max_line_length int64 5 786k | alphanum_fraction float64 0.06 0.95 | matches listlengths 1 11 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
08d6945a853d8a626a4de745e1a441afaae66d3d | 2,766 | h | C | Modules/Numerics/FEM/include/itkFEMLoadBC.h | lassoan/ITK | 4634cb0490934f055065230e3db64df8f546b72a | [
"Apache-2.0"
] | 2 | 2019-09-15T10:17:06.000Z | 2019-09-15T10:19:06.000Z | Modules/Numerics/FEM/include/itkFEMLoadBC.h | lassoan/ITK | 4634cb0490934f055065230e3db64df8f546b72a | [
"Apache-2.0"
] | null | null | null | Modules/Numerics/FEM/include/itkFEMLoadBC.h | lassoan/ITK | 4634cb0490934f055065230e3db64df8f546b72a | [
"Apache-2.0"
] | 1 | 2021-09-23T08:33:37.000Z | 2021-09-23T08:33:37.000Z | /*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.
*
*=========================================================================*/
#ifndef itkFEMLoadBC_h
#define itkFEMLoadBC_h
#include "itkFEMLoadBase.h"
#include "ITKFEMExport.h"
namespace itk
{
namespace fem
{
/**
* \class LoadBC
* \brief Generic essential (Dirichlet) boundary conditions.
*
* Objects of this class specify, which DOFs in a system are fixed.
* \ingroup ITKFEM
*/
class ITKFEM_EXPORT LoadBC : public Load
{
public:
/** Standard class type aliases. */
using Self = LoadBC;
using Superclass = Load;
using Pointer = SmartPointer<Self>;
using ConstPointer = SmartPointer<const Self>;
/** Method for creation through the object factory. */
itkSimpleNewMacro(Self);
/** Run-time type information (and related methods). */
itkTypeMacro(LoadBC, Load);
/** CreateAnother method will clone the existing instance of this type,
* including its internal member variables. */
::itk::LightObject::Pointer
CreateAnother() const override;
/** Default constructor */
LoadBC()
: m_DegreeOfFreedom(0)
, m_Value()
{}
/** Set the number of degrees of freedom*/
void
SetDegreeOfFreedom(int dof);
/** Get the number of degrees of freedom*/
int
GetDegreeOfFreedom() const;
/** Set the boundary condition using vector representation*/
void
SetValue(const vnl_vector<Element::Float> val);
/** Get the boundary condition as vector representation*/
vnl_vector<Element::Float>
GetValue() const;
protected:
void
PrintSelf(std::ostream & os, Indent indent) const override;
/**
* Local DOF number within the Element object.
*/
unsigned int m_DegreeOfFreedom;
/**
* Value which the DOF is being fixed.
*
* \note This is a vector so that implementation of BC on isotropic elements
* is easy. Which value is applied to the master force vector is
* defined by optional dim parameter (defaults to 0) in AssembleF
* function in solver.
*/
vnl_vector<Element::Float> m_Value;
};
} // end namespace fem
} // end namespace itk
#endif // itkFEMLoadBC_h
| 27.66 | 78 | 0.667028 | [
"object",
"vector"
] |
08e565e352a7d7e00011217170b94ed32e5f9600 | 1,770 | h | C | MonoNative/mscorlib/System/Runtime/Remoting/mscorlib_System_Runtime_Remoting_TypeEntry.h | brunolauze/MonoNative | 959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66 | [
"BSD-2-Clause"
] | 7 | 2015-03-10T03:36:16.000Z | 2021-11-05T01:16:58.000Z | MonoNative/mscorlib/System/Runtime/Remoting/mscorlib_System_Runtime_Remoting_TypeEntry.h | brunolauze/MonoNative | 959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66 | [
"BSD-2-Clause"
] | 1 | 2020-06-23T10:02:33.000Z | 2020-06-24T02:05:47.000Z | MonoNative/mscorlib/System/Runtime/Remoting/mscorlib_System_Runtime_Remoting_TypeEntry.h | brunolauze/MonoNative | 959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66 | [
"BSD-2-Clause"
] | null | null | null | #ifndef __MONO_NATIVE_MSCORLIB_SYSTEM_RUNTIME_REMOTING_TYPEENTRY_H
#define __MONO_NATIVE_MSCORLIB_SYSTEM_RUNTIME_REMOTING_TYPEENTRY_H
#include <mscorlib/System/mscorlib_System_Object.h>
namespace mscorlib
{
namespace System
{
class String;
class Type;
}
}
namespace mscorlib
{
namespace System
{
namespace Runtime
{
namespace Remoting
{
class TypeEntry
: public mscorlib::System::Object
{
public:
TypeEntry(mscorlib::NativeTypeInfo *nativeTypeInfo)
: mscorlib::System::Object(nativeTypeInfo)
{
};
TypeEntry(MonoObject *nativeObject)
: mscorlib::System::Object(nativeObject)
{
};
~TypeEntry()
{
};
TypeEntry & operator=(TypeEntry &value) { __native_object__ = value.GetNativeObject(); return value; };
bool operator==(TypeEntry &value) { return mscorlib::System::Object::Equals(value); };
operator MonoObject*() { return __native_object__; };
MonoObject* operator=(MonoObject* value) { return __native_object__ = value; };
virtual MonoObject* GetNativeObject() override { return __native_object__; };
//Public Properties
__declspec(property(get=get_AssemblyName, put=set_AssemblyName)) mscorlib::System::String AssemblyName;
__declspec(property(get=get_TypeName, put=set_TypeName)) mscorlib::System::String TypeName;
//Get Set Properties Methods
// Get/Set:AssemblyName
mscorlib::System::String get_AssemblyName() const;
void set_AssemblyName(mscorlib::System::String value);
// Get/Set:TypeName
mscorlib::System::String get_TypeName() const;
void set_TypeName(mscorlib::System::String value);
protected:
private:
};
}
}
}
}
#endif
| 22.405063 | 109 | 0.685311 | [
"object"
] |
08ea16263acbcff82ff51c1cd984c800cae399d4 | 6,234 | h | C | production_apps/BEM4I/Examples/Lame/testLameSteklovPoincare.h | readex-eu/readex-apps | 38493b11806c306f4e8f1b7b2d97764b45fac8e2 | [
"BSD-3-Clause"
] | 2 | 2020-11-25T13:10:11.000Z | 2021-03-15T20:26:35.000Z | production_apps/BEM4I/Examples/Lame/testLameSteklovPoincare.h | readex-eu/readex-apps | 38493b11806c306f4e8f1b7b2d97764b45fac8e2 | [
"BSD-3-Clause"
] | null | null | null | production_apps/BEM4I/Examples/Lame/testLameSteklovPoincare.h | readex-eu/readex-apps | 38493b11806c306f4e8f1b7b2d97764b45fac8e2 | [
"BSD-3-Clause"
] | 1 | 2018-09-30T19:04:38.000Z | 2018-09-30T19:04:38.000Z | #include "../../Settings.h"
#include <iostream>
#include "../auxiliary.h"
#include "../../ProgressMonitor.h"
#include "../../FullMatrix.h"
#include "../../SurfaceMesh3D.h"
#include "../../BESpace.h"
#include "../../Vector.h"
#include "../../IdentityOperator.h"
#include "../../BEBilinearFormLame1Layer.h"
#include "../../BEBilinearFormLaplace2Layer.h"
#include "../../BEBilinearFormLame2Layer.h"
#include "../../BEBilinearFormLameHypersingular.h"
using namespace std;
using namespace bem4i;
void testLameSteklovPoincare(
string const & filename,
int refine4,
int refine9,
bool mapToUnitBall,
int orderNear,
int orderFar
);
namespace bem4i {
template<class LO, class SC>
void getLameSteklovPoincare(
SC * Sarray,
LO nNodes,
const SC * nodes,
LO nElems,
const LO * elems,
SC nu,
SC E,
LO orderNear,
LO orderFar,
bool verbose = false
);
}
int main(
int argc,
char** argv
) {
intro( );
string filename = "input/cube_12.txt";
testLameSteklovPoincare( filename, 1, 0, true, 3, 4 );
return 0;
}
void testLameSteklovPoincare(
const string & filename,
int refine4,
int refine9,
bool mapToUnitBall,
int orderNear,
int orderFar
) {
typedef double SC;
typedef int LO;
std::cout.precision( 8 );
std::cout.setf( std::ios::scientific );
SurfaceMesh3D< LO, SC > mesh;
mesh.load( filename.c_str( ) );
mesh.refine( refine4, 2 );
mesh.refine( refine9, 3 );
if ( mapToUnitBall ) mesh.mapToUnitBall( );
//mesh.printParaviewVtk("mesh_alex.vtu");
LO nNodes = mesh.getNNodes( );
LO nElems = mesh.getNElements( );
LO rows = 3 * nNodes;
SC * Sarray = new SC[ rows * rows ];
SC nu = 0.33;
SC E = 1.1e5;
bem4i::getLameSteklovPoincare<LO, SC>( Sarray, nNodes,
mesh.getNodes( )->data( ), nElems, mesh.getElements( )->data( ), nu, E,
orderNear, orderFar, true );
///*
std::ofstream file( "output/sp_lame.txt" );
file.precision( 8 );
file.setf( std::ios::scientific );
FullMatrix< LO, SC > S( rows, rows, Sarray );
S.print( file );
//*/
//Vector<LO, SC> rhs(456);
//rhs.load("input/rhs_alex.txt");
//S.LUSolve(rhs);
//rhs.print();
delete [] Sarray;
}
namespace bem4i {
//__attribute__( ( visibility( "default" ) ) )
template<class LO, class SC>
void getLameSteklovPoincare(
SC * Sarray,
LO nNodes,
const SC * nodes,
LO nElems,
const LO * elems,
SC nu,
SC E,
LO orderNear,
LO orderFar,
bool verbose
) {
typedef typename GetType<LO, SC>::SCVT SCVT;
if ( orderNear < 2 ) orderNear = 2;
if ( orderNear > 4 ) orderNear = 4;
if ( orderFar < 3 ) orderFar = 3;
if ( orderFar > 5 ) orderFar = 5;
bool symmetricV = false;
#if N_MIC > 0
symmetricV = false;
#endif
std::vector< SCVT > nodesv;
nodesv.assign( nodes, nodes + 3 * nNodes );
std::vector< LO > elemsv;
elemsv.assign( elems, elems + 3 * nElems );
SurfaceMesh3D< LO, SC > mesh( nodesv, elemsv );
if ( verbose ) mesh.printInfo( );
quadratureType quadType = SauterSchwab;
int quadNear[ 4 ] = { orderNear, orderNear, orderNear, orderNear };
int quadFar[] = { orderFar, orderFar };
if ( verbose ) std::cout << "Sauter-Schwab near-field order " << orderNear <<
", Gauss far-field order " << orderFar << std::endl;
BESpace< LO, SC > bespace00( &mesh, p0, p0 );
BESpace< LO, SC > bespace10( &mesh, p1, p0 );
BESpace< LO, SC > bespace11( &mesh, p1, p1 );
SparseMatrix<LO, SC> T12, T13, T23, T;
mesh.assembleT( T12, T13, T23, T );
std::vector< SparseMatrix< LO, SC > * > Tv;
Tv.push_back( &T12 );
Tv.push_back( &T13 );
Tv.push_back( &T23 );
Tv.push_back( &T );
FullMatrix< LO, SC > * Vlap = new FullMatrix< LO, SC >( 0, 0 );
FullMatrix< LO, SC > * V = new FullMatrix< LO, SC >( 0, 0 );
BEBilinearFormLame1Layer< LO, SC > formV( &bespace00, quadNear,
quadType, quadFar, symmetricV );
formV.setE( E );
formV.setNu( nu );
#if N_MIC < 1
if ( verbose ) ProgressMonitor::init( "V, Vlap" );
formV.assemble( *V, *Vlap );
if ( verbose ) ProgressMonitor::step( );
#endif
FullMatrix< LO, SC > * Klap = new FullMatrix< LO, SC >( 0, 0 );
BEBilinearFormLaplace2Layer< LO, SC > formKlap( &bespace10, quadNear,
quadType, quadFar );
#if N_MIC < 1
if ( verbose ) ProgressMonitor::init( "Klap" );
formKlap.assemble( *Klap );
#else
if ( verbose ) ProgressMonitor::init( "V, VLap, Klap" );
formV.assembleAllMIC( *V, *Vlap, *Klap, bespace10 );
#endif
if ( verbose ) ProgressMonitor::step( );
FullMatrix< LO, SC > * K = new FullMatrix< LO, SC >( 0, 0 );
BEBilinearFormLame2Layer< LO, SC > formK( &bespace10, quadNear,
quadType, quadFar );
formK.setE( E );
formK.setNu( nu );
if ( verbose ) ProgressMonitor::init( "K" );
formK.assemble( *K, *Vlap, *V, *Klap, Tv );
if ( verbose ) ProgressMonitor::step( );
delete Klap;
FullMatrix< LO, SC > * D = new FullMatrix< LO, SC >( 0, 0 );
BEBilinearFormLameHypersingular< LO, SC > formD( &bespace11, quadNear,
quadType, quadFar );
formD.setE( E );
formD.setNu( nu );
if ( verbose ) ProgressMonitor::init( "D" );
formD.assemble( *D, *Vlap, *V, Tv );
if ( verbose ) ProgressMonitor::step( );
delete Vlap;
IdentityOperator< LO, SC > id( &bespace10 );
SparseMatrix< LO, SC > M;
id.assemble( M );
Eigen::SparseMatrix<SC, Eigen::ColMajor, LO> * Me = M.getEigenSparseMatrix( );
for ( LO j = 0; j < Me->outerSize( ); ++j ) {
typename Eigen::SparseMatrix<SC, Eigen::ColMajor, LO>::InnerIterator
it( *Me, j );
for (; it; ++it ) {
K->add( it.row( ), it.col( ), 0.5 * it.value( ) );
K->add( it.row( ) + nElems, it.col( ) + nNodes, 0.5 * it.value( ) );
K->add( it.row( ) + 2 * nElems, it.col( ) + 2 * nNodes,
0.5 * it.value( ) );
}
}
FullMatrix< LO, SC > * VinvK = new FullMatrix< LO, SC >( *K );
if ( verbose ) ProgressMonitor::init( "Applying inverse of V" );
V->CholeskiSolve( *VinvK );
if ( verbose ) ProgressMonitor::step( );
delete V;
FullMatrix< LO, SC > S( 3 * nNodes, 3 * nNodes, Sarray );
S.setAll( 0.0 );
S.multiply( *K, *VinvK, true, false, 1.0, 0.0 );
delete VinvK;
delete K;
S.add( *D, 1.0 );
delete D;
}
} | 25.54918 | 80 | 0.610042 | [
"mesh",
"vector"
] |
08ec9dfc661f3aca6c806c70ef6aa83f9e9728a8 | 8,087 | c | C | test/Sema/zvector2.c | LambdaMan/clang | 6edb1bc43453c555f37f713992cd99c674806ead | [
"Apache-2.0"
] | 793 | 2015-12-03T16:45:26.000Z | 2022-02-12T20:14:20.000Z | test/Sema/zvector2.c | LambdaMan/clang | 6edb1bc43453c555f37f713992cd99c674806ead | [
"Apache-2.0"
] | 497 | 2017-04-04T14:22:22.000Z | 2020-03-10T14:12:27.000Z | test/Sema/zvector2.c | LambdaMan/clang | 6edb1bc43453c555f37f713992cd99c674806ead | [
"Apache-2.0"
] | 241 | 2015-12-03T16:51:28.000Z | 2021-10-14T00:21:08.000Z | // RUN: %clang_cc1 -triple s390x-linux-gnu -fzvector -target-cpu z14 \
// RUN: -fno-lax-vector-conversions -W -Wall -Wconversion \
// RUN: -Werror -fsyntax-only -verify %s
vector signed char sc, sc2;
vector unsigned char uc, uc2;
vector bool char bc, bc2;
vector signed short ss, ss2;
vector unsigned short us, us2;
vector bool short bs, bs2;
vector signed int si, si2;
vector unsigned int ui, ui2;
vector bool int bi, bi2;
vector signed long long sl, sl2;
vector unsigned long long ul, ul2;
vector bool long long bl, bl2;
vector double fd, fd2;
vector float ff, ff2;
// Verify that __vector is also recognized
__vector float ff3;
// Verify operation of vec_step
int res_ff[vec_step(ff) == 4 ? 1 : -1];
void foo(void)
{
// -------------------------------------------------------------------------
// Test assignment.
// -------------------------------------------------------------------------
ff = ff2;
sc = ff2; // expected-error {{incompatible type}}
ff = sc2; // expected-error {{incompatible type}}
uc = ff2; // expected-error {{incompatible type}}
ff = uc2; // expected-error {{incompatible type}}
bc = ff2; // expected-error {{incompatible type}}
ff = bc2; // expected-error {{incompatible type}}
fd = ff2; // expected-error {{incompatible type}}
ff = fd2; // expected-error {{incompatible type}}
// -------------------------------------------------------------------------
// Test casts to same element width.
// -------------------------------------------------------------------------
ui = (vector unsigned int)ff2;
ff = (vector float)si2;
// -------------------------------------------------------------------------
// Test casts to different element width.
// -------------------------------------------------------------------------
uc = (vector unsigned char)ff2;
us = (vector unsigned short)ff2;
ul = (vector unsigned long long)ff2;
ff = (vector float)sc2;
ff = (vector float)ss2;
ff = (vector float)sl2;
// -------------------------------------------------------------------------
// Test unary operators.
// -------------------------------------------------------------------------
++ff2;
ff++;
--ff2;
ff--;
ff = +ff2;
ff = -ff2;
ff = ~ff2; // expected-error {{invalid argument}}
// -------------------------------------------------------------------------
// Test binary arithmetic operators.
// -------------------------------------------------------------------------
ff = ff + ff2;
ff = ff + ui2; // expected-error {{cannot convert}}
ff = si + ff2; // expected-error {{cannot convert}}
ff = fd + ff2; // expected-error {{cannot convert}}
ff += ff2;
ff += fd2; // expected-error {{cannot convert}}
sc += ff2; // expected-error {{cannot convert}}
ff = ff - ff2;
ff = ff - ui2; // expected-error {{cannot convert}}
ff = si - ff2; // expected-error {{cannot convert}}
ff = fd - ff2; // expected-error {{cannot convert}}
ff -= ff2;
ff -= fd2; // expected-error {{cannot convert}}
sc -= ff2; // expected-error {{cannot convert}}
ff = ff * ff2;
ff = ff * ui2; // expected-error {{cannot convert}}
ff = si * ff2; // expected-error {{cannot convert}}
ff = fd * ff2; // expected-error {{cannot convert}}
ff *= ff2;
ff *= fd2; // expected-error {{cannot convert}}
sc *= ff2; // expected-error {{cannot convert}}
ff = ff / ff2;
ff = ff / ui2; // expected-error {{cannot convert}}
ff = si / ff2; // expected-error {{cannot convert}}
ff = fd / ff2; // expected-error {{cannot convert}}
ff /= ff2;
ff /= fd2; // expected-error {{cannot convert}}
sc /= ff2; // expected-error {{cannot convert}}
ff = ff % ff2; // expected-error {{invalid operands}}
ff = ff % ui2; // expected-error {{invalid operands}}
ff = si % ff2; // expected-error {{invalid operands}}
ff = fd % ff2; // expected-error {{invalid operands}}
ff %= ff2; // expected-error {{invalid operands}}
ff %= fd2; // expected-error {{invalid operands}}
sc %= ff2; // expected-error {{invalid operands}}
// -------------------------------------------------------------------------
// Test bitwise binary operators.
// -------------------------------------------------------------------------
ff = ff & ff2; // expected-error {{invalid operands}}
ff = bi & ff2; // expected-error {{invalid operands}}
ff = fd & ff2; // expected-error {{invalid operands}}
ff = ff & bi2; // expected-error {{invalid operands}}
ff = ff & si2; // expected-error {{invalid operands}}
ff = ff & ui2; // expected-error {{invalid operands}}
sc &= ff2; // expected-error {{invalid operands}}
ff &= bc2; // expected-error {{invalid operands}}
ff &= fd2; // expected-error {{invalid operands}}
ff = ff | ff2; // expected-error {{invalid operands}}
ff = bi | ff2; // expected-error {{invalid operands}}
ff = fd | ff2; // expected-error {{invalid operands}}
ff = ff | bi2; // expected-error {{invalid operands}}
ff = ff | si2; // expected-error {{invalid operands}}
ff = ff | ui2; // expected-error {{invalid operands}}
sc |= ff2; // expected-error {{invalid operands}}
ff |= bc2; // expected-error {{invalid operands}}
ff |= fd2; // expected-error {{invalid operands}}
ff = ff ^ ff2; // expected-error {{invalid operands}}
ff = bi ^ ff2; // expected-error {{invalid operands}}
ff = fd ^ ff2; // expected-error {{invalid operands}}
ff = ff ^ bi2; // expected-error {{invalid operands}}
ff = ff ^ si2; // expected-error {{invalid operands}}
ff = ff ^ ui2; // expected-error {{invalid operands}}
sc ^= ff2; // expected-error {{invalid operands}}
ff ^= bc2; // expected-error {{invalid operands}}
ff ^= fd2; // expected-error {{invalid operands}}
// -------------------------------------------------------------------------
// Test shift operators.
// -------------------------------------------------------------------------
ff = ff << ff2; // expected-error {{integer is required}}
ff = ff << fd2; // expected-error {{integer is required}}
ff = ff << ui2; // expected-error {{integer is required}}
ff = sl << ff2; // expected-error {{integer is required}}
sc <<= ff2; // expected-error {{integer is required}}
ff <<= ff2; // expected-error {{integer is required}}
fd <<= ff2; // expected-error {{integer is required}}
ff = ff >> ff2; // expected-error {{integer is required}}
ff = ff >> fd2; // expected-error {{integer is required}}
ff = ff >> ui2; // expected-error {{integer is required}}
ff = sl >> ff2; // expected-error {{integer is required}}
sc >>= ff2; // expected-error {{integer is required}}
ff >>= ff2; // expected-error {{integer is required}}
fd >>= ff2; // expected-error {{integer is required}}
// -------------------------------------------------------------------------
// Test comparison operators.
// -------------------------------------------------------------------------
(void)(ff == ff2);
(void)(ff == fd2); // expected-error {{cannot convert}}
(void)(ff == ui2); // expected-error {{cannot convert}}
(void)(ui == ff2); // expected-error {{cannot convert}}
(void)(ff != ff2);
(void)(ff != fd2); // expected-error {{cannot convert}}
(void)(ff != ui2); // expected-error {{cannot convert}}
(void)(ui != ff2); // expected-error {{cannot convert}}
(void)(ff <= ff2);
(void)(ff <= fd2); // expected-error {{cannot convert}}
(void)(ff <= ui2); // expected-error {{cannot convert}}
(void)(ui <= ff2); // expected-error {{cannot convert}}
(void)(ff >= ff2);
(void)(ff >= fd2); // expected-error {{cannot convert}}
(void)(ff >= ui2); // expected-error {{cannot convert}}
(void)(ui >= ff2); // expected-error {{cannot convert}}
(void)(ff < ff2);
(void)(ff < fd2); // expected-error {{cannot convert}}
(void)(ff < ui2); // expected-error {{cannot convert}}
(void)(ui < ff2); // expected-error {{cannot convert}}
(void)(ff > ff2);
(void)(ff > fd2); // expected-error {{cannot convert}}
(void)(ff > ui2); // expected-error {{cannot convert}}
(void)(ui > ff2); // expected-error {{cannot convert}}
}
| 36.926941 | 78 | 0.525535 | [
"vector"
] |
08ee1c25ec1d74e5f6ee80a6d09cb5cf9be3dd2f | 4,939 | h | C | AAFusion/AAFusion.h | DongZhaoYu/AARFS | abb67f411e42eff3dd0015f89d9d3c29dee9cdc4 | [
"MIT"
] | null | null | null | AAFusion/AAFusion.h | DongZhaoYu/AARFS | abb67f411e42eff3dd0015f89d9d3c29dee9cdc4 | [
"MIT"
] | null | null | null | AAFusion/AAFusion.h | DongZhaoYu/AARFS | abb67f411e42eff3dd0015f89d9d3c29dee9cdc4 | [
"MIT"
] | 1 | 2019-05-09T04:02:24.000Z | 2019-05-09T04:02:24.000Z | /*
* @file: AAFusion.h
* @brief: the definition of the class for AIS and radar data fusion
* @author: dongzhaoyu
* @date: 2008-5-11
*
* Copyright (C) CTEC Xi'an JiaoTong University
*/
#if _MSC_VER > 1200
#pragma once
#define _AAFUSION_H
#endif
#include "AADataGenerator.h"
#include <iostream>
#include <fstream>
#define _ASSIGN_BY_MARK(var, it, mark) do { if ((mark) == 1) var = (it)##->##m_Angle; \
else if ((mark) == 2) var = (it)##->##m_Speed; \
else var = (it)##->##m_Distance; }while(0)
#define ASSIGN_BY_MARK(var, it, mark) _ASSIGN_BY_MARK(var, it, mark)
#define _SET_BY_MARK(it, var, mark) do { if ((mark) == 1) (it)##->##m_Angle = var; \
else if ((mark) == 2) (it)##->##m_Speed = var; \
else (it)##->##m_Distance = var; }while(0)
#define SET_BY_MARK(it, var, mark) _SET_BY_MARK(it, var, mark)
#define _PUSH_BY_MARK(it, var, mark) do { if ((mark) == 1) (it)##->##m_Angle.push_back(var); \
else if ((mark) == 2) (it)##->##m_Speed.push_back(var); \
else (it)##->##m_Distance.push_back(var); }while(0)
#define PUSH_BY_MARK(it, var, mark) _PUSH_BY_MARK(it, var, mark)
#define E 2.71828f
#define RCYCLE 3
#define AISERROR 800
#define RADARERROR 800
#define ARCYCLE (F64)1.0f / (F64)RCYCLE
#define ABS(x) ((x) >= 0 ? (x) : -(x))
#define MAX(a, b) ((a) > (b) ? (a) : (b))
#define MIN(a, b) ((a) > (b) ? (b) : (a))
#define ROW 0.5f
#define RADARPOINTCOUNT 4
#define AISPOINTCOUNT 20
//a procedure execute by the fusion thread, the para will be a pointer to AAFusion Object
DWORD WINAPI AAFusionData(LPVOID);
//AAFusion will fusion the data received by radar and AIS
class AAFusion : public AAReader
{
public:
typedef DWORD (WINAPI *FusionProc)(LPVOID);
typedef struct _FusionPara
{
S32 m_PointCount;
F64 m_RelationDegree;
}FusionPara; //a struct to store the fusion result
typedef struct _FINNERPARA
{
S32 m_l;
F64 m_a;
F64 m_b;
F64 m_c;
F64 m_d;
F64 m_e;
F64 m_f;
}FINNERPARA; //a struct to store the model para
typedef struct _MODELPARA
{
FINNERPARA m_Angle;
FINNERPARA m_Speed;
FINNERPARA m_Distance;
}MODELPARA; // model para for angle, speed and distance
typedef struct _StandbySetEle
{
S32 m_index; //the index of radar trace
RadarIterator m_start; //the start iterator of Radar trace
}StandbySetEle;
typedef std::list<F64> AAF64List;
typedef struct _SynEle
{
AAF64List m_Angle;
AAF64List m_Speed;
AAF64List m_Distance;
S32 m_rindex;
}SynEle;
typedef std::list<SynEle> AASynArray; //a list to store the synchronized samples for a specified ais sampled trace
typedef std::list<StandbySetEle> AAStandbySet; //a list to store the standby traces sampled by radar for a specified ais sampled trace
typedef CGrowableArray<MODELPARA> AARadarPara; // a array to store the paras for each radar sampled trace
typedef CGrowableArray<CGrowableArray<FusionPara> > AAFusionResult; //a 2D array to store the fusion result
AAFusion();
AAFusion(S32 shipcount);
AAFusion(S32 shipcount, SceneVisitor *ais, SceneVisitor *radar, FusionProc fusionproc = AAFusionData);
~AAFusion();
void FusionData();
void SetFusionResult(S32, S32, FusionPara&); //rindex, aindex
Bool GetFusionResult(S32, AISData&); //input rindex, output the associated ais data, return if the data exit or not
#if defined _DEBUG
void show();
void ShowStandbySet(S32, AAStandbySet&);
void ShowSynArray(S32, AASynArray&);
void ShowResult();
#endif
protected:
inline void InitResult();
inline void CalAB(S32, FINNERPARA&, S32);
void CalAngleAB(S32 index, FINNERPARA ¶) { CalAB(index, para, 1); }
void CalSpeedAB(S32 index, FINNERPARA ¶) { CalAB(index, para, 2); }
void CalDistanceAB(S32 index, FINNERPARA ¶) { CalAB(index, para, 3); }
inline void SynArray(StandbySetEle&, S32, SynEle&, S32);
void SynAngleArray(StandbySetEle &stele, S32 aindex, SynEle &synele) { synele.m_Angle.clear(); SynArray(stele, aindex, synele, 1); }
void SynSpeedArray(StandbySetEle &stele, S32 aindex, SynEle &synele) { synele.m_Speed.clear(); SynArray(stele, aindex, synele, 2); }
void SynDistanceArray(StandbySetEle &stele, S32 aindex, SynEle &synele) { synele.m_Distance.clear(); SynArray(stele, aindex, synele, 3); }
inline S32 CalRelationDegree(S32, AASynArray&); //return the associated radar trace index
private:
volatile Bool m_Work;
HANDLE m_FusionThread;
FusionProc m_FusionProc;
CRITICAL_SECTION m_CS;
S32 m_ShipCount;
AAFusionResult m_Result;
SceneVisitor *m_AISSampler; //deconstructor can not delete m_AISSampler and m_RadarSampler
SceneVisitor *m_RadarSampler;
AARadarPara m_RadarPara; //the model para for each radar sampled trace
CGrowableArray<AISData> m_AISFusionBuffer; //the ais data fused
#if defined _DEBUG
std::fstream m_debugfile;
#endif
}; | 36.585185 | 140 | 0.691436 | [
"object",
"model"
] |
08ef8f7c55778d12e3f91e537984aca363673b6e | 26,666 | h | C | vehicle/adapt-sysroot/lib/gcc/arm-linux-androideabi/4.6.x-google/plugin/include/tree-pass.h | slicht-uri/Sandshark-Beta-Lab- | 6cff36b227b49b776d13187c307e648d2a52bdae | [
"MIT"
] | 45 | 2016-12-27T12:43:30.000Z | 2022-03-01T07:11:31.000Z | vehicle/adapt-sysroot/lib/gcc/arm-linux-androideabi/4.6.x-google/plugin/include/tree-pass.h | slicht-uri/Sandshark-Beta-Lab- | 6cff36b227b49b776d13187c307e648d2a52bdae | [
"MIT"
] | 8 | 2016-12-16T20:42:12.000Z | 2016-12-16T20:50:52.000Z | resources/arm-eabi-4.6/lib/gcc/arm-eabi/4.6.x-google/plugin/include/tree-pass.h | dxwu/BinderFilter | abe266fec20a4ab04bfaf2f25b2cb54ae059fe45 | [
"MIT"
] | 19 | 2017-01-14T17:49:09.000Z | 2022-03-01T07:11:36.000Z | /* Definitions for describing one tree-ssa optimization pass.
Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011
Free Software Foundation, Inc.
Contributed by Richard Henderson <rth@redhat.com>
This file is part of GCC.
GCC is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3, or (at your option)
any later version.
GCC 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 GCC; see the file COPYING3. If not see
<http://www.gnu.org/licenses/>. */
#ifndef GCC_TREE_PASS_H
#define GCC_TREE_PASS_H 1
#include "timevar.h"
/* Different tree dump places. When you add new tree dump places,
extend the DUMP_FILES array in tree-dump.c. */
enum tree_dump_index
{
TDI_none, /* No dump */
TDI_cgraph, /* dump function call graph. */
TDI_tu, /* dump the whole translation unit. */
TDI_class, /* dump class hierarchy. */
TDI_original, /* dump each function before optimizing it */
TDI_generic, /* dump each function after genericizing it */
TDI_nested, /* dump each function after unnesting it */
TDI_vcg, /* create a VCG graph file for each
function's flowgraph. */
TDI_ada, /* dump declarations in Ada syntax. */
TDI_tree_all, /* enable all the GENERIC/GIMPLE dumps. */
TDI_rtl_all, /* enable all the RTL dumps. */
TDI_ipa_all, /* enable all the IPA dumps. */
TDI_end
};
/* Bit masks to control dumping. Not all values are applicable to
all dumps. Add new ones at the end. When you define new
values, extend the DUMP_OPTIONS array in tree-dump.c */
#define TDF_ADDRESS (1 << 0) /* dump node addresses */
#define TDF_SLIM (1 << 1) /* don't go wild following links */
#define TDF_RAW (1 << 2) /* don't unparse the function */
#define TDF_DETAILS (1 << 3) /* show more detailed info about
each pass */
#define TDF_STATS (1 << 4) /* dump various statistics about
each pass */
#define TDF_BLOCKS (1 << 5) /* display basic block boundaries */
#define TDF_VOPS (1 << 6) /* display virtual operands */
#define TDF_LINENO (1 << 7) /* display statement line numbers */
#define TDF_UID (1 << 8) /* display decl UIDs */
#define TDF_TREE (1 << 9) /* is a tree dump */
#define TDF_RTL (1 << 10) /* is a RTL dump */
#define TDF_IPA (1 << 11) /* is an IPA dump */
#define TDF_STMTADDR (1 << 12) /* Address of stmt. */
#define TDF_GRAPH (1 << 13) /* a graph dump is being emitted */
#define TDF_MEMSYMS (1 << 14) /* display memory symbols in expr.
Implies TDF_VOPS. */
#define TDF_DIAGNOSTIC (1 << 15) /* A dump to be put in a diagnostic
message. */
#define TDF_VERBOSE (1 << 16) /* A dump that uses the full tree
dumper to print stmts. */
#define TDF_RHS_ONLY (1 << 17) /* a flag to only print the RHS of
a gimple stmt. */
#define TDF_ASMNAME (1 << 18) /* display asm names of decls */
#define TDF_EH (1 << 19) /* display EH region number
holding this gimple statement. */
#define TDF_NOUID (1 << 20) /* omit UIDs from dumps. */
#define TDF_ALIAS (1 << 21) /* display alias information */
#define TDF_ENUMERATE_LOCALS (1 << 22) /* Enumerate locals by uid. */
#define TDF_CSELIB (1 << 23) /* Dump cselib details. */
/* In tree-dump.c */
extern char *get_dump_file_name (int);
extern int dump_enabled_p (int);
extern int dump_initialized_p (int);
extern FILE *dump_begin (int, int *);
extern void dump_end (int, FILE *);
extern void dump_node (const_tree, int, FILE *);
extern int dump_switch_p (const char *);
extern const char *dump_flag_name (int);
/* Global variables used to communicate with passes. */
extern FILE *dump_file;
extern int dump_flags;
extern const char *dump_file_name;
/* Return the dump_file_info for the given phase. */
extern struct dump_file_info *get_dump_file_info (int);
/* Optimization pass type. */
enum opt_pass_type
{
GIMPLE_PASS,
RTL_PASS,
SIMPLE_IPA_PASS,
IPA_PASS
};
/* Describe one pass; this is the common part shared across different pass
types. */
struct opt_pass
{
/* Optimization pass type. */
enum opt_pass_type type;
/* Terse name of the pass used as a fragment of the dump file
name. If the name starts with a star, no dump happens. */
const char *name;
/* If non-null, this pass and all sub-passes are executed only if
the function returns true. */
bool (*gate) (void);
/* This is the code to run. If null, then there should be sub-passes
otherwise this pass does nothing. The return value contains
TODOs to execute in addition to those in TODO_flags_finish. */
unsigned int (*execute) (void);
/* A list of sub-passes to run, dependent on gate predicate. */
struct opt_pass *sub;
/* Next in the list of passes to run, independent of gate predicate. */
struct opt_pass *next;
/* Static pass number, used as a fragment of the dump file name. */
int static_pass_number;
/* The timevar id associated with this pass. */
/* ??? Ideally would be dynamically assigned. */
timevar_id_t tv_id;
/* Sets of properties input and output from this pass. */
unsigned int properties_required;
unsigned int properties_provided;
unsigned int properties_destroyed;
/* Flags indicating common sets things to do before and after. */
unsigned int todo_flags_start;
unsigned int todo_flags_finish;
};
/* Description of GIMPLE pass. */
struct gimple_opt_pass
{
struct opt_pass pass;
};
/* Description of RTL pass. */
struct rtl_opt_pass
{
struct opt_pass pass;
};
struct varpool_node;
struct cgraph_node;
struct cgraph_node_set_def;
struct varpool_node_set_def;
/* Description of IPA pass with generate summary, write, execute, read and
transform stages. */
struct ipa_opt_pass_d
{
struct opt_pass pass;
/* IPA passes can analyze function body and variable initializers
using this hook and produce summary. */
void (*generate_summary) (void);
/* This hook is used to serialize IPA summaries on disk. */
void (*write_summary) (struct cgraph_node_set_def *,
struct varpool_node_set_def *);
/* This hook is used to deserialize IPA summaries from disk. */
void (*read_summary) (void);
/* This hook is used to serialize IPA optimization summaries on disk. */
void (*write_optimization_summary) (struct cgraph_node_set_def *,
struct varpool_node_set_def *);
/* This hook is used to deserialize IPA summaries from disk. */
void (*read_optimization_summary) (void);
/* Hook to convert gimple stmt uids into true gimple statements. The second
parameter is an array of statements indexed by their uid. */
void (*stmt_fixup) (struct cgraph_node *, gimple *);
/* Results of interprocedural propagation of an IPA pass is applied to
function body via this hook. */
unsigned int function_transform_todo_flags_start;
unsigned int (*function_transform) (struct cgraph_node *);
void (*variable_transform) (struct varpool_node *);
};
/* Description of simple IPA pass. Simple IPA passes have just one execute
hook. */
struct simple_ipa_opt_pass
{
struct opt_pass pass;
};
/* Define a tree dump switch. */
struct dump_file_info
{
const char *suffix; /* suffix to give output file. */
const char *swtch; /* command line switch */
const char *glob; /* command line glob */
int flags; /* user flags */
int state; /* state of play */
int num; /* dump file number */
};
/* Pass properties. */
#define PROP_gimple_any (1 << 0) /* entire gimple grammar */
#define PROP_gimple_lcf (1 << 1) /* lowered control flow */
#define PROP_gimple_leh (1 << 2) /* lowered eh */
#define PROP_cfg (1 << 3)
#define PROP_referenced_vars (1 << 4)
#define PROP_ssa (1 << 5)
#define PROP_no_crit_edges (1 << 6)
#define PROP_rtl (1 << 7)
#define PROP_gimple_lomp (1 << 8) /* lowered OpenMP directives */
#define PROP_cfglayout (1 << 9) /* cfglayout mode on RTL */
#define PROP_gimple_lcx (1 << 10) /* lowered complex */
#define PROP_trees \
(PROP_gimple_any | PROP_gimple_lcf | PROP_gimple_leh | PROP_gimple_lomp)
/* To-do flags. */
#define TODO_dump_func (1 << 0)
#define TODO_ggc_collect (1 << 1)
#define TODO_verify_ssa (1 << 2)
#define TODO_verify_flow (1 << 3)
#define TODO_verify_stmts (1 << 4)
#define TODO_cleanup_cfg (1 << 5)
#define TODO_dump_cgraph (1 << 7)
#define TODO_remove_functions (1 << 8)
#define TODO_rebuild_frequencies (1 << 9)
#define TODO_verify_rtl_sharing (1 << 10)
/* To-do flags for calls to update_ssa. */
/* Update the SSA form inserting PHI nodes for newly exposed symbols
and virtual names marked for updating. When updating real names,
only insert PHI nodes for a real name O_j in blocks reached by all
the new and old definitions for O_j. If the iterated dominance
frontier for O_j is not pruned, we may end up inserting PHI nodes
in blocks that have one or more edges with no incoming definition
for O_j. This would lead to uninitialized warnings for O_j's
symbol. */
#define TODO_update_ssa (1 << 11)
/* Update the SSA form without inserting any new PHI nodes at all.
This is used by passes that have either inserted all the PHI nodes
themselves or passes that need only to patch use-def and def-def
chains for virtuals (e.g., DCE). */
#define TODO_update_ssa_no_phi (1 << 12)
/* Insert PHI nodes everywhere they are needed. No pruning of the
IDF is done. This is used by passes that need the PHI nodes for
O_j even if it means that some arguments will come from the default
definition of O_j's symbol.
WARNING: If you need to use this flag, chances are that your pass
may be doing something wrong. Inserting PHI nodes for an old name
where not all edges carry a new replacement may lead to silent
codegen errors or spurious uninitialized warnings. */
#define TODO_update_ssa_full_phi (1 << 13)
/* Passes that update the SSA form on their own may want to delegate
the updating of virtual names to the generic updater. Since FUD
chains are easier to maintain, this simplifies the work they need
to do. NOTE: If this flag is used, any OLD->NEW mappings for real
names are explicitly destroyed and only the symbols marked for
renaming are processed. */
#define TODO_update_ssa_only_virtuals (1 << 14)
/* Some passes leave unused local variables that can be removed from
cfun->local_decls. This reduces the size of dump files
and the memory footprint for VAR_DECLs. */
#define TODO_remove_unused_locals (1 << 15)
/* Call df_finish at the end of the pass. This is done after all of
the dumpers have been allowed to run so that they have access to
the instance before it is destroyed. */
#define TODO_df_finish (1 << 17)
/* Call df_verify at the end of the pass if checking is enabled. */
#define TODO_df_verify (1 << 18)
/* Internally used for the first instance of a pass. */
#define TODO_mark_first_instance (1 << 19)
/* Rebuild aliasing info. */
#define TODO_rebuild_alias (1 << 20)
/* Rebuild the addressable-vars bitmap and do register promotion. */
#define TODO_update_address_taken (1 << 21)
/* Rebuild the callgraph edges. */
#define TODO_rebuild_cgraph_edges (1 << 22)
/* Internally used in execute_function_todo(). */
#define TODO_update_ssa_any \
(TODO_update_ssa \
| TODO_update_ssa_no_phi \
| TODO_update_ssa_full_phi \
| TODO_update_ssa_only_virtuals)
#define TODO_verify_all \
(TODO_verify_ssa | TODO_verify_flow | TODO_verify_stmts)
/* Register pass info. */
enum pass_positioning_ops
{
PASS_POS_INSERT_AFTER, /* Insert after the reference pass. */
PASS_POS_INSERT_BEFORE, /* Insert before the reference pass. */
PASS_POS_REPLACE /* Replace the reference pass. */
};
struct register_pass_info
{
struct opt_pass *pass; /* New pass to register. */
const char *reference_pass_name; /* Name of the reference pass for hooking
up the new pass. */
int ref_pass_instance_number; /* Insert the pass at the specified
instance number of the reference pass.
Do it for every instance if it is 0. */
enum pass_positioning_ops pos_op; /* how to insert the new pass. */
};
extern void tree_lowering_passes (tree decl);
extern struct gimple_opt_pass pass_mudflap_1;
extern struct gimple_opt_pass pass_mudflap_2;
extern struct gimple_opt_pass pass_lower_cf;
extern struct gimple_opt_pass pass_refactor_eh;
extern struct gimple_opt_pass pass_lower_eh;
extern struct gimple_opt_pass pass_lower_eh_dispatch;
extern struct gimple_opt_pass pass_lower_resx;
extern struct gimple_opt_pass pass_build_cfg;
extern struct gimple_opt_pass pass_direct_call_profile;
extern struct gimple_opt_pass pass_early_tree_profile;
extern struct gimple_opt_pass pass_referenced_vars;
extern struct gimple_opt_pass pass_cleanup_eh;
extern struct gimple_opt_pass pass_sra;
extern struct gimple_opt_pass pass_sra_early;
extern struct gimple_opt_pass pass_early_ipa_sra;
extern struct gimple_opt_pass pass_tail_recursion;
extern struct gimple_opt_pass pass_tail_calls;
extern struct gimple_opt_pass pass_tree_loop;
extern struct gimple_opt_pass pass_tree_loop_init;
extern struct gimple_opt_pass pass_lim;
extern struct gimple_opt_pass pass_tree_unswitch;
extern struct gimple_opt_pass pass_predcom;
extern struct gimple_opt_pass pass_iv_canon;
extern struct gimple_opt_pass pass_scev_cprop;
extern struct gimple_opt_pass pass_empty_loop;
extern struct gimple_opt_pass pass_record_bounds;
extern struct gimple_opt_pass pass_graphite;
extern struct gimple_opt_pass pass_graphite_transforms;
extern struct gimple_opt_pass pass_if_conversion;
extern struct gimple_opt_pass pass_loop_distribution;
extern struct gimple_opt_pass pass_vectorize;
extern struct gimple_opt_pass pass_slp_vectorize;
extern struct gimple_opt_pass pass_complete_unroll;
extern struct gimple_opt_pass pass_complete_unrolli;
extern struct gimple_opt_pass pass_parallelize_loops;
extern struct gimple_opt_pass pass_loop_prefetch;
extern struct gimple_opt_pass pass_iv_optimize;
extern struct gimple_opt_pass pass_tree_loop_done;
extern struct gimple_opt_pass pass_ch;
extern struct gimple_opt_pass pass_ccp;
extern struct gimple_opt_pass pass_phi_only_cprop;
extern struct gimple_opt_pass pass_build_ssa;
extern struct gimple_opt_pass pass_build_alias;
extern struct gimple_opt_pass pass_build_ealias;
extern struct gimple_opt_pass pass_dominator;
extern struct gimple_opt_pass pass_dce;
extern struct gimple_opt_pass pass_dce_loop;
extern struct gimple_opt_pass pass_cd_dce;
extern struct gimple_opt_pass pass_call_cdce;
extern struct gimple_opt_pass pass_merge_phi;
extern struct gimple_opt_pass pass_split_crit_edges;
extern struct gimple_opt_pass pass_pre;
extern struct gimple_opt_pass pass_profile;
extern struct gimple_opt_pass pass_strip_predict_hints;
extern struct gimple_opt_pass pass_lower_complex_O0;
extern struct gimple_opt_pass pass_lower_complex;
extern struct gimple_opt_pass pass_lower_vector;
extern struct gimple_opt_pass pass_lower_vector_ssa;
extern struct gimple_opt_pass pass_lower_omp;
extern struct gimple_opt_pass pass_diagnose_omp_blocks;
extern struct gimple_opt_pass pass_expand_omp;
extern struct gimple_opt_pass pass_expand_omp_ssa;
extern struct gimple_opt_pass pass_object_sizes;
extern struct gimple_opt_pass pass_fold_builtins;
extern struct gimple_opt_pass pass_stdarg;
extern struct gimple_opt_pass pass_early_warn_uninitialized;
extern struct gimple_opt_pass pass_late_warn_uninitialized;
extern struct gimple_opt_pass pass_cse_reciprocals;
extern struct gimple_opt_pass pass_cse_sincos;
extern struct gimple_opt_pass pass_optimize_bswap;
extern struct gimple_opt_pass pass_optimize_widening_mul;
extern struct gimple_opt_pass pass_warn_function_return;
extern struct gimple_opt_pass pass_warn_function_noreturn;
extern struct gimple_opt_pass pass_cselim;
extern struct gimple_opt_pass pass_phiopt;
extern struct gimple_opt_pass pass_forwprop;
extern struct gimple_opt_pass pass_phiprop;
extern struct gimple_opt_pass pass_tree_ifcombine;
extern struct gimple_opt_pass pass_dse;
extern struct gimple_opt_pass pass_nrv;
extern struct gimple_opt_pass pass_rename_ssa_copies;
extern struct gimple_opt_pass pass_rest_of_compilation;
extern struct gimple_opt_pass pass_sink_code;
extern struct gimple_opt_pass pass_fre;
extern struct gimple_opt_pass pass_check_data_deps;
extern struct gimple_opt_pass pass_copy_prop;
extern struct gimple_opt_pass pass_vrp;
extern struct gimple_opt_pass pass_uncprop;
extern struct gimple_opt_pass pass_return_slot;
extern struct gimple_opt_pass pass_reassoc;
extern struct gimple_opt_pass pass_rebuild_cgraph_edges;
extern struct gimple_opt_pass pass_remove_cgraph_callee_edges;
extern struct gimple_opt_pass pass_build_cgraph_edges;
extern struct gimple_opt_pass pass_local_pure_const;
extern struct gimple_opt_pass pass_tracer;
extern struct gimple_opt_pass pass_warn_unused_result;
extern struct gimple_opt_pass pass_split_functions;
extern struct gimple_opt_pass pass_feedback_split_functions;
extern struct gimple_opt_pass pass_threadsafe_analyze;
extern struct gimple_opt_pass pass_tree_convert_builtin_dispatch;
extern struct gimple_opt_pass pass_auto_clone;
/* IPA Passes */
extern struct simple_ipa_opt_pass pass_ipa_lower_emutls;
extern struct simple_ipa_opt_pass pass_ipa_function_and_variable_visibility;
extern struct simple_ipa_opt_pass pass_ipa_tree_profile;
extern struct simple_ipa_opt_pass pass_early_local_passes;
extern struct ipa_opt_pass_d pass_ipa_whole_program_visibility;
extern struct ipa_opt_pass_d pass_ipa_lto_gimple_out;
extern struct simple_ipa_opt_pass pass_ipa_increase_alignment;
extern struct simple_ipa_opt_pass pass_ipa_matrix_reorg;
extern struct ipa_opt_pass_d pass_ipa_inline;
extern struct simple_ipa_opt_pass pass_ipa_free_lang_data;
extern struct ipa_opt_pass_d pass_ipa_cp;
extern struct ipa_opt_pass_d pass_ipa_reference;
extern struct ipa_opt_pass_d pass_ipa_pure_const;
extern struct simple_ipa_opt_pass pass_ipa_type_escape;
extern struct simple_ipa_opt_pass pass_ipa_pta;
extern struct simple_ipa_opt_pass pass_ipa_struct_reorg;
extern struct ipa_opt_pass_d pass_ipa_lto_wpa_fixup;
extern struct ipa_opt_pass_d pass_ipa_lto_finish_out;
extern struct ipa_opt_pass_d pass_ipa_profile;
extern struct ipa_opt_pass_d pass_ipa_cdtor_merge;
extern struct simple_ipa_opt_pass pass_ipa_multiversion_dispatch;
extern struct gimple_opt_pass pass_all_optimizations;
extern struct gimple_opt_pass pass_cleanup_cfg_post_optimizing;
extern struct gimple_opt_pass pass_init_datastructures;
extern struct gimple_opt_pass pass_fixup_cfg;
extern struct rtl_opt_pass pass_expand;
extern struct rtl_opt_pass pass_init_function;
extern struct rtl_opt_pass pass_jump;
extern struct rtl_opt_pass pass_rtl_eh;
extern struct rtl_opt_pass pass_initial_value_sets;
extern struct rtl_opt_pass pass_unshare_all_rtl;
extern struct rtl_opt_pass pass_instantiate_virtual_regs;
extern struct rtl_opt_pass pass_rtl_fwprop;
extern struct rtl_opt_pass pass_rtl_fwprop_addr;
extern struct rtl_opt_pass pass_jump2;
extern struct rtl_opt_pass pass_lower_subreg;
extern struct rtl_opt_pass pass_cse;
extern struct rtl_opt_pass pass_fast_rtl_dce;
extern struct rtl_opt_pass pass_ud_rtl_dce;
extern struct rtl_opt_pass pass_rtl_dce;
extern struct rtl_opt_pass pass_rtl_dse1;
extern struct rtl_opt_pass pass_rtl_dse2;
extern struct rtl_opt_pass pass_rtl_dse3;
extern struct rtl_opt_pass pass_rtl_cprop;
extern struct rtl_opt_pass pass_rtl_pre;
extern struct rtl_opt_pass pass_rtl_hoist;
extern struct rtl_opt_pass pass_rtl_store_motion;
extern struct rtl_opt_pass pass_cse_after_global_opts;
extern struct rtl_opt_pass pass_rtl_ifcvt;
extern struct rtl_opt_pass pass_simplify_got;
extern struct rtl_opt_pass pass_into_cfg_layout_mode;
extern struct rtl_opt_pass pass_outof_cfg_layout_mode;
extern struct rtl_opt_pass pass_loop2;
extern struct rtl_opt_pass pass_rtl_loop_init;
extern struct rtl_opt_pass pass_rtl_move_loop_invariants;
extern struct rtl_opt_pass pass_rtl_unswitch;
extern struct rtl_opt_pass pass_rtl_unroll_and_peel_loops;
extern struct rtl_opt_pass pass_rtl_doloop;
extern struct rtl_opt_pass pass_rtl_loop_done;
extern struct rtl_opt_pass pass_web;
extern struct rtl_opt_pass pass_cse2;
extern struct rtl_opt_pass pass_df_initialize_opt;
extern struct rtl_opt_pass pass_df_initialize_no_opt;
extern struct rtl_opt_pass pass_reginfo_init;
extern struct rtl_opt_pass pass_inc_dec;
extern struct rtl_opt_pass pass_stack_ptr_mod;
extern struct rtl_opt_pass pass_initialize_regs;
extern struct rtl_opt_pass pass_combine;
extern struct rtl_opt_pass pass_if_after_combine;
extern struct rtl_opt_pass pass_implicit_zee;
extern struct rtl_opt_pass pass_partition_blocks;
extern struct rtl_opt_pass pass_match_asm_constraints;
extern struct rtl_opt_pass pass_regmove;
extern struct rtl_opt_pass pass_split_all_insns;
extern struct rtl_opt_pass pass_fast_rtl_byte_dce;
extern struct rtl_opt_pass pass_lower_subreg2;
extern struct rtl_opt_pass pass_mode_switching;
extern struct rtl_opt_pass pass_sms;
extern struct rtl_opt_pass pass_sched;
extern struct rtl_opt_pass pass_ira;
extern struct rtl_opt_pass pass_postreload;
extern struct rtl_opt_pass pass_clean_state;
extern struct rtl_opt_pass pass_branch_prob;
extern struct rtl_opt_pass pass_value_profile_transformations;
extern struct rtl_opt_pass pass_postreload_cse;
extern struct rtl_opt_pass pass_gcse2;
extern struct rtl_opt_pass pass_split_after_reload;
extern struct rtl_opt_pass pass_branch_target_load_optimize1;
extern struct rtl_opt_pass pass_thread_prologue_and_epilogue;
extern struct rtl_opt_pass pass_stack_adjustments;
extern struct rtl_opt_pass pass_peephole2;
extern struct rtl_opt_pass pass_if_after_reload;
extern struct rtl_opt_pass pass_regrename;
extern struct rtl_opt_pass pass_cprop_hardreg;
extern struct rtl_opt_pass pass_reorder_blocks;
extern struct rtl_opt_pass pass_branch_target_load_optimize2;
extern struct rtl_opt_pass pass_leaf_regs;
extern struct rtl_opt_pass pass_split_before_sched2;
extern struct rtl_opt_pass pass_compare_elim_after_reload;
extern struct rtl_opt_pass pass_sched2;
extern struct rtl_opt_pass pass_stack_regs;
extern struct rtl_opt_pass pass_stack_regs_run;
extern struct rtl_opt_pass pass_df_finish;
extern struct rtl_opt_pass pass_compute_alignments;
extern struct rtl_opt_pass pass_duplicate_computed_gotos;
extern struct rtl_opt_pass pass_variable_tracking;
extern struct rtl_opt_pass pass_free_cfg;
extern struct rtl_opt_pass pass_machine_reorg;
extern struct rtl_opt_pass pass_cleanup_barriers;
extern struct rtl_opt_pass pass_delay_slots;
extern struct rtl_opt_pass pass_split_for_shorten_branches;
extern struct rtl_opt_pass pass_split_before_regstack;
extern struct rtl_opt_pass pass_convert_to_eh_region_ranges;
extern struct rtl_opt_pass pass_shorten_branches;
extern struct rtl_opt_pass pass_set_nothrow_function_flags;
extern struct rtl_opt_pass pass_final;
extern struct rtl_opt_pass pass_rtl_seqabstr;
extern struct gimple_opt_pass pass_release_ssa_names;
extern struct gimple_opt_pass pass_early_inline;
extern struct gimple_opt_pass pass_inline_parameters;
extern struct gimple_opt_pass pass_all_early_optimizations;
extern struct gimple_opt_pass pass_update_address_taken;
extern struct gimple_opt_pass pass_convert_switch;
/* The root of the compilation pass tree, once constructed. */
extern struct opt_pass *all_passes, *all_small_ipa_passes, *all_lowering_passes,
*all_regular_ipa_passes, *all_lto_gen_passes;
/* Define a list of pass lists so that both passes.c and plugins can easily
find all the pass lists. */
#define GCC_PASS_LISTS \
DEF_PASS_LIST (all_lowering_passes) \
DEF_PASS_LIST (all_small_ipa_passes) \
DEF_PASS_LIST (all_regular_ipa_passes) \
DEF_PASS_LIST (all_lto_gen_passes) \
DEF_PASS_LIST (all_passes)
#define DEF_PASS_LIST(LIST) PASS_LIST_NO_##LIST,
enum
{
GCC_PASS_LISTS
PASS_LIST_NUM
};
#undef DEF_PASS_LIST
/* This is used by plugins, and should also be used in
passes.c:register_pass. */
extern struct opt_pass **gcc_pass_lists[];
/* Current optimization pass. */
extern struct opt_pass *current_pass;
extern struct opt_pass * get_pass_for_id (int);
extern bool execute_one_pass (struct opt_pass *);
extern void execute_pass_list (struct opt_pass *);
extern void execute_ipa_pass_list (struct opt_pass *);
extern void execute_ipa_summary_passes (struct ipa_opt_pass_d *);
extern void execute_all_ipa_transforms (void);
extern void execute_all_ipa_stmt_fixups (struct cgraph_node *, gimple *);
extern bool pass_init_dump_file (struct opt_pass *);
extern void pass_fini_dump_file (struct opt_pass *);
extern const char *get_current_pass_name (void);
extern void print_current_pass (FILE *);
extern void debug_pass (void);
extern void ipa_write_summaries (void);
extern void ipa_write_optimization_summaries (struct cgraph_node_set_def *,
struct varpool_node_set_def *);
extern void ipa_read_summaries (void);
extern void ipa_read_optimization_summaries (void);
extern void register_one_dump_file (struct opt_pass *);
extern bool function_called_by_processed_nodes_p (void);
extern void register_pass (struct register_pass_info *);
/* Set to true if the pass is called the first time during compilation of the
current function. Note that using this information in the optimization
passes is considered not to be clean, and it should be avoided if possible.
This flag is currently used to prevent loops from being peeled repeatedly
in jump threading; it will be removed once we preserve loop structures
throughout the compilation -- we will be able to mark the affected loops
directly in jump threading, and avoid peeling them next time. */
extern bool first_pass_instance;
/* Declare for plugins. */
extern void do_per_function_toporder (void (*) (void *), void *);
extern void disable_pass (const char *);
extern void enable_pass (const char *);
extern void dump_passes (void);
#endif /* GCC_TREE_PASS_H */
| 40.836141 | 80 | 0.782757 | [
"transform"
] |
08f0fb6a8591352b1cbd98a5cbc4cac68eea1250 | 2,561 | h | C | chromium/chromecast/crash/linux/dump_info.h | wedataintelligence/vivaldi-source | 22a46f2c969f6a0b7ca239a05575d1ea2738768c | [
"BSD-3-Clause"
] | null | null | null | chromium/chromecast/crash/linux/dump_info.h | wedataintelligence/vivaldi-source | 22a46f2c969f6a0b7ca239a05575d1ea2738768c | [
"BSD-3-Clause"
] | null | null | null | chromium/chromecast/crash/linux/dump_info.h | wedataintelligence/vivaldi-source | 22a46f2c969f6a0b7ca239a05575d1ea2738768c | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2015 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.
#ifndef CHROMECAST_CRASH_LINUX_DUMP_INFO_H_
#define CHROMECAST_CRASH_LINUX_DUMP_INFO_H_
#include <string>
#include "base/macros.h"
#include "base/memory/scoped_ptr.h"
#include "chromecast/crash/linux/minidump_params.h"
namespace base {
class Value;
}
namespace chromecast {
// Class that encapsulates the construction and parsing of dump entries
// in the log file.
class DumpInfo {
public:
// Validate the input as a valid JSON representation of DumpInfo, then
// populate the relevant fields.
explicit DumpInfo(const base::Value* entry);
// Attempt to construct a DumpInfo object that has the following info:
//
// -crashed_process_dump: the full path of the dump written
// -crashed_process_logfile: the full path of the logfile written
// -dump_time: the time of the dump written
// -params: a structure containing other useful crash information
DumpInfo(const std::string& crashed_process_dump,
const std::string& crashed_process_logfile,
const time_t& dump_time,
const MinidumpParams& params);
~DumpInfo();
const std::string& crashed_process_dump() const {
return crashed_process_dump_;
}
const std::string& logfile() const { return logfile_; }
const time_t& dump_time() const { return dump_time_; }
// Return a deep copy of the entry's JSON representation.
// The format is:
// {
// "name": <name>,
// "dump_time": <dump_time (kDumpTimeFormat)>,
// "dump": <dump>,
// "uptime": <uptime>,
// "logfile": <logfile>,
// "suffix": <suffix>,
// "prev_app_name": <prev_app_name>,
// "cur_app_name": <current_app_name>,
// "last_app_name": <last_app_name>,
// "release_version": <release_version>,
// "build_number": <build_number>
// "reason": <reason>
// }
scoped_ptr<base::Value> GetAsValue() const;
const MinidumpParams& params() const { return params_; }
bool valid() const { return valid_; }
private:
// Checks if parsed JSON in |value| is valid, if so populates the object's
// fields from |value|.
bool ParseEntry(const base::Value* value);
bool SetDumpTimeFromString(const std::string& timestr);
std::string crashed_process_dump_;
std::string logfile_;
time_t dump_time_;
MinidumpParams params_;
bool valid_;
DISALLOW_COPY_AND_ASSIGN(DumpInfo);
};
} // namespace chromecast
#endif // CHROMECAST_CRASH_LINUX_DUMP_INFO_H_
| 30.129412 | 76 | 0.706365 | [
"object"
] |
08f15f7b1a4783bccf4bcd9cf72f866797283e1e | 4,056 | h | C | libs/base/include/mrpt/poses/CPosePDFGrid.h | feroze/mrpt-shivang | 95bf524c5e10ed2e622bd199f1b0597951b45370 | [
"BSD-3-Clause"
] | 2 | 2017-03-25T18:09:17.000Z | 2017-05-22T08:14:48.000Z | libs/base/include/mrpt/poses/CPosePDFGrid.h | feroze/mrpt-shivang | 95bf524c5e10ed2e622bd199f1b0597951b45370 | [
"BSD-3-Clause"
] | null | null | null | libs/base/include/mrpt/poses/CPosePDFGrid.h | feroze/mrpt-shivang | 95bf524c5e10ed2e622bd199f1b0597951b45370 | [
"BSD-3-Clause"
] | 1 | 2018-07-29T09:40:46.000Z | 2018-07-29T09:40:46.000Z | /* +---------------------------------------------------------------------------+
| Mobile Robot Programming Toolkit (MRPT) |
| http://www.mrpt.org/ |
| |
| Copyright (c) 2005-2017, Individual contributors, see AUTHORS file |
| See: http://www.mrpt.org/Authors - All rights reserved. |
| Released under BSD License. See details in http://www.mrpt.org/License |
+---------------------------------------------------------------------------+ */
#ifndef CPosePDFGrid_H
#define CPosePDFGrid_H
#include <mrpt/poses/CPosePDF.h>
#include <mrpt/poses/CPose2DGridTemplate.h>
#include <mrpt/utils/bits.h> // DEG2RAD()
namespace mrpt
{
namespace poses
{
// This must be added to any CSerializable derived class:
DEFINE_SERIALIZABLE_PRE_CUSTOM_BASE( CPosePDFGrid, CPosePDF )
/** Declares a class that represents a Probability Distribution
* function (PDF) of a 2D pose (x,y,phi).
* This class implements that PDF using a 3D grid.
*
* \sa CPose2D, CPosePDF, CPose2DGridTemplate
* \ingroup poses_pdf_grp
*/
class BASE_IMPEXP CPosePDFGrid : public CPosePDF, public CPose2DGridTemplate<double>
{
// This must be added to any CSerializable derived class:
DEFINE_SERIALIZABLE( CPosePDFGrid )
protected:
public:
/** Constructor: Initializes a, uniform distribution over the whole given range.
*/
CPosePDFGrid(
double xMin = -1.0f,
double xMax = 1.0f,
double yMin = -1.0f,
double yMax = 1.0f,
double resolutionXY = 0.5f,
double resolutionPhi = mrpt::utils::DEG2RAD(180),
double phiMin = -M_PIf,
double phiMax = M_PIf
);
virtual ~CPosePDFGrid(); //!< Destructor
void copyFrom(const CPosePDF &o) MRPT_OVERRIDE; //!< Copy operator, translating if necesary (for example, between particles and gaussian representations)
void normalize(); //!< Normalizes the PDF, such as all cells sum the unity.
void uniformDistribution(); //!< Assigns the same value to all the cells in the grid, so the sum 1.
void getMean(CPose2D &mean_pose) const MRPT_OVERRIDE; //!< Returns an estimate of the pose, (the mean, or mathematical expectation of the PDF). \sa getCovariance
void getCovarianceAndMean(mrpt::math::CMatrixDouble33 &cov,CPose2D &mean_point) const MRPT_OVERRIDE; //!< Returns an estimate of the pose covariance matrix (3x3 cov matrix) and the mean, both at once. \sa getMean
void saveToTextFile(const std::string &dataFile) const MRPT_OVERRIDE; //!< Save the contents of the 3D grid in one file, as a vertical concatenation of rectangular matrix for the different "PHI" discrete levels, and the size in X,Y,and PHI in another file named "<filename>_dims.txt"
/** this = p (+) this. This can be used to convert a PDF from local coordinates to global, providing the point (newReferenceBase) from which
* "to project" the current pdf. Result PDF substituted the currently stored one in the object. */
void changeCoordinatesReference( const CPose3D &newReferenceBase ) MRPT_OVERRIDE;
void bayesianFusion(const CPosePDF &p1,const CPosePDF &p2, const double &minMahalanobisDistToDrop = 0 ) MRPT_OVERRIDE; //!< Bayesian fusion of 2 densities (In the grid representation this becomes a pointwise multiplication)
void inverse(CPosePDF &o) const MRPT_OVERRIDE; //!< Returns a new PDF such as: NEW_PDF = (0,0,0) - THIS_PDF
void drawSingleSample( CPose2D &outPart ) const MRPT_OVERRIDE; //!< Draws a single sample from the distribution (WARNING: weights are assumed to be normalized!)
void drawManySamples( size_t N, std::vector<mrpt::math::CVectorDouble> & outSamples ) const MRPT_OVERRIDE; //!< Draws a number of samples from the distribution, and saves as a list of 1x3 vectors, where each row contains a (x,y,phi) datum.
}; // End of class def.
DEFINE_SERIALIZABLE_POST_CUSTOM_BASE( CPosePDFGrid, CPosePDF )
} // End of namespace
} // End of namespace
#endif
| 54.08 | 285 | 0.671598 | [
"object",
"vector",
"3d"
] |
08f19847f8fefab5b9e63b80a0c6b786cec18e3f | 4,070 | h | C | Examples/include/Aspose.Pdf.Cpp/InteractiveFeatures/Annotations/PDF3DContent.h | kashifiqb/Aspose.PDF-for-C | 13d49bba591c5704685820185741e64a462a5bdc | [
"MIT"
] | null | null | null | Examples/include/Aspose.Pdf.Cpp/InteractiveFeatures/Annotations/PDF3DContent.h | kashifiqb/Aspose.PDF-for-C | 13d49bba591c5704685820185741e64a462a5bdc | [
"MIT"
] | null | null | null | Examples/include/Aspose.Pdf.Cpp/InteractiveFeatures/Annotations/PDF3DContent.h | kashifiqb/Aspose.PDF-for-C | 13d49bba591c5704685820185741e64a462a5bdc | [
"MIT"
] | null | null | null | #pragma once
#include <system/string.h>
#include <system/shared_ptr.h>
#include <system/object.h>
#include <system/io/stream.h>
#include <system/array.h>
#include <cstdint>
#include "aspose_pdf_api_defs.h"
namespace Aspose { namespace Pdf { namespace Annotations { class PDF3DStream; } } }
namespace Aspose { namespace Pdf { namespace Engine { namespace Data { class PdfStream; } } } }
namespace Aspose {
namespace Pdf {
namespace Annotations {
/// <summary>
/// Class PDF3DContent.
/// </summary>
class ASPOSE_PDF_SHARED_API PDF3DContent : public System::Object
{
typedef PDF3DContent ThisType;
typedef System::Object BaseType;
typedef ::System::BaseTypesInfo<BaseType> ThisTypeBaseTypesInfo;
RTTI_INFO_DECL();
FRIEND_FUNCTION_System_MakeObject;
friend class Aspose::Pdf::Annotations::PDF3DStream;
public:
/// <summary>
/// Gets the extension .
/// </summary>
/// <value>The extension.</value>
System::String get_Extension();
/// <summary>
/// Initializes a new instance of the <see cref="PDF3DContent"/> class.
/// </summary>
PDF3DContent();
/// <summary>
/// Initializes a new instance of the <see cref="PDF3DContent"/> class.
/// </summary>
/// <param name="filename">The filename.</param>
/// <exception cref="ArgumentException">Unknown 3D Artwork type</exception>
PDF3DContent(System::String filename);
/// <summary>
/// Loads 3D content with the specified filename.
/// </summary>
/// <param name="filename">The filename.</param>
/// <exception cref="ArgumentException">Unknown 3D content type</exception>
void Load(System::String filename);
/// <summary>
/// Loads 3D content with the specified filename as PRC format.
/// </summary>
/// <param name="filename">The filename.</param>
void LoadAsPRC(System::String filename);
/// <summary>
/// Loads 3D content with the specified filename as U3D format.
/// </summary>
/// <param name="filename">The filename.</param>
void LoadAsU3D(System::String filename);
/// <summary>
/// Loads 3D content from stream as PRC format.
/// </summary>
/// <param name="stream">The 3D content stream.</param>
void LoadAsPRC(System::SharedPtr<System::IO::Stream> stream);
/// <summary>
/// Loads 3D content from stream as U3D format.
/// </summary>
/// <param name="stream">The 3D content stream.</param>
void LoadAsU3D(System::SharedPtr<System::IO::Stream> stream);
/// <summary>
/// Loads 3D content from byte array as PRC format.
/// </summary>
/// <param name="stream">The stream.</param>
void LoadAsPRC(System::ArrayPtr<uint8_t> stream);
/// <summary>
/// Loads 3D content from byte array as U3D format.
/// </summary>
/// <param name="stream">The stream.</param>
void LoadAsU3D(System::ArrayPtr<uint8_t> stream);
/// <summary>
/// Saves 3D content to file.
/// </summary>
/// <param name="filename">The file name.</param>
/// <exception cref="ArgumentException">3DArtwork content format is PRC or U3D.</exception>
void SaveToFile(System::String filename);
/// <summary>
/// Gets 3D content as stream.
/// </summary>
/// <returns>Stream.</returns>
System::SharedPtr<System::IO::Stream> GetAsStream();
/// <summary>
/// Gets 3D content as byte array.
/// </summary>
/// <returns>System.Byte[].</returns>
System::ArrayPtr<uint8_t> GetAsByteArray();
protected:
System::SharedPtr<PDF3DStream> Pdf3DStream;
System::ArrayPtr<uint8_t> Data;
PDF3DContent(System::SharedPtr<Aspose::Pdf::Engine::Data::PdfStream> stream);
System::Object::shared_members_type GetSharedMembers() override;
private:
System::SharedPtr<Aspose::Pdf::Engine::Data::PdfStream> _stream;
System::String _extension;
static System::ArrayPtr<uint8_t> ReadFully(System::SharedPtr<System::IO::Stream> input);
};
} // namespace Annotations
} // namespace Pdf
} // namespace Aspose
| 31.307692 | 95 | 0.653563 | [
"object",
"3d"
] |
8329e6d5c728ed6b5e07a783f2e295e500652bcd | 4,025 | h | C | Foundation/include/Poco/Activity.h | YKYou/poco | 468f80622845b7015ac6ed02e02475ba43e845dc | [
"BSL-1.0"
] | 5,766 | 2015-01-01T01:27:15.000Z | 2022-03-31T09:27:29.000Z | Foundation/include/Poco/Activity.h | YKYou/poco | 468f80622845b7015ac6ed02e02475ba43e845dc | [
"BSL-1.0"
] | 2,345 | 2015-01-01T20:43:10.000Z | 2022-03-31T19:45:02.000Z | Foundation/include/Poco/Activity.h | YKYou/poco | 468f80622845b7015ac6ed02e02475ba43e845dc | [
"BSL-1.0"
] | 1,963 | 2015-01-01T01:29:44.000Z | 2022-03-31T06:41:54.000Z | //
// Activity.h
//
// Library: Foundation
// Package: Threading
// Module: ActiveObjects
//
// Definition of the Activity template class.
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef Foundation_Activity_INCLUDED
#define Foundation_Activity_INCLUDED
#include "Poco/Foundation.h"
#include "Poco/RunnableAdapter.h"
#include "Poco/ThreadPool.h"
#include "Poco/Event.h"
#include "Poco/Mutex.h"
namespace Poco {
template <class C>
class Activity: public Runnable
/// This template class helps to implement active objects.
/// An active object uses threads to decouple method
/// execution from method invocation, or to perform tasks
/// autonomously, without intervention of a caller.
///
/// An activity is a (typically longer running) method
/// that executes within its own task. Activities can
/// be started automatically (upon object construction)
/// or manually at a later time. Activities can also
/// be stopped at any time. However, to make stopping
/// an activity work, the method implementing the
/// activity has to check periodically whether it
/// has been requested to stop, and if so, return.
/// Activities are stopped before the object they belong to is
/// destroyed. Methods implementing activities cannot have arguments
/// or return values.
///
/// Activity objects are used as follows:
///
/// class ActiveObject
/// {
/// public:
/// ActiveObject():
/// _activity(this, &ActiveObject::runActivity)
/// {
/// ...
/// }
///
/// ...
///
/// protected:
/// void runActivity()
/// {
/// while (!_activity.isStopped())
/// {
/// ...
/// }
/// }
///
/// private:
/// Activity<ActiveObject> _activity;
/// };
{
public:
typedef RunnableAdapter<C> RunnableAdapterType;
typedef typename RunnableAdapterType::Callback Callback;
Activity(C* pOwner, Callback method):
_pOwner(pOwner),
_runnable(*pOwner, method),
_stopped(true),
_running(false),
_done(Event::EVENT_MANUALRESET)
/// Creates the activity. Call start() to
/// start it.
{
poco_check_ptr (pOwner);
}
~Activity()
/// Stops and destroys the activity.
{
try
{
stop();
wait();
}
catch (...)
{
poco_unexpected();
}
}
void start()
/// Starts the activity by acquiring a
/// thread for it from the default thread pool.
{
start(ThreadPool::defaultPool());
}
void start(ThreadPool& pool)
{
FastMutex::ScopedLock lock(_mutex);
if (!_running)
{
_done.reset();
_stopped = false;
_running = true;
try
{
pool.start(*this);
}
catch (...)
{
_running = false;
throw;
}
}
}
void stop()
/// Requests to stop the activity.
{
_stopped = true;
}
void wait()
/// Waits for the activity to complete.
{
if (_running)
{
_done.wait();
}
}
void wait(long milliseconds)
/// Waits the given interval for the activity to complete.
/// An TimeoutException is thrown if the activity does not
/// complete within the given interval.
{
if (_running)
{
_done.wait(milliseconds);
}
}
bool isStopped() const
/// Returns true if the activity has been requested to stop.
{
return _stopped;
}
bool isRunning() const
/// Returns true if the activity is running.
{
return _running;
}
protected:
void run()
{
try
{
_runnable.run();
}
catch (...)
{
_running = false;
_done.set();
throw;
}
_running = false;
_done.set();
}
private:
Activity();
Activity(const Activity&);
Activity& operator = (const Activity&);
C* _pOwner;
RunnableAdapterType _runnable;
std::atomic<bool> _stopped;
std::atomic<bool> _running;
Event _done;
FastMutex _mutex;
};
} // namespace Poco
#endif // Foundation_Activity_INCLUDED
| 19.444444 | 74 | 0.622112 | [
"object"
] |
832bf6918d65041ab85c80db740844b873ae414d | 1,670 | h | C | src/module/access/KAuthMark.h | jcleng/nix-kangle-3.5.13.2 | cc7bbaa429ada9a7eb7a023a152b6e2fc5defe3f | [
"MIT"
] | null | null | null | src/module/access/KAuthMark.h | jcleng/nix-kangle-3.5.13.2 | cc7bbaa429ada9a7eb7a023a152b6e2fc5defe3f | [
"MIT"
] | null | null | null | src/module/access/KAuthMark.h | jcleng/nix-kangle-3.5.13.2 | cc7bbaa429ada9a7eb7a023a152b6e2fc5defe3f | [
"MIT"
] | null | null | null | /*
* KAuthMark.h
*
* Created on: 2010-4-28
* Author: keengo
* Copyright (c) 2010, NanChang BangTeng Inc
* All Rights Reserved.
*
* You may use the Software for free for non-commercial use
* under the License Restrictions.
*
* You may modify the source code(if being provieded) or interface
* of the Software under the License Restrictions.
*
* You may use the Software for commercial use after purchasing the
* commercial license.Moreover, according to the license you purchased
* you may get specified term, manner and content of technical
* support from NanChang BangTeng Inc
*
* See COPYING file for detail.
*/
#ifndef KAUTHACL_H_
#define KAUTHACL_H_
#include <map>
#include "KMark.h"
#include "global.h"
#include "KLineFile.h"
#include "KReg.h"
class KAuthMark: public KMark {
public:
KAuthMark();
virtual ~KAuthMark();
bool mark(KHttpRequest *rq, KHttpObject *obj,
const int chainJumpType, int &jumpType);
//bool match(KHttpRequest *rq, KHttpObject *obj);
KMark *newInstance();
const char *getName();
std::string getHtml(KModel *model);
std::string getDisplay();
void editHtml(std::map<std::string, std::string> &attribute) throw (KHtmlSupportException);
void buildXML(std::stringstream &s);
private:
std::string getRequireUsers();
bool loadAuthFile(std::string &path);
bool checkLogin(KHttpRequest *rq);
OpenState lastState;
std::string file;
time_t lastModified;
int cryptType;
int auth_type;
char *realm;
char *header;
KMutex lock;
std::map<std::string,std::string> users;
KReg *reg_user;
bool reg_user_revert;
bool all;
bool failed_deny;
bool file_sign;
time_t lastLoad;
};
#endif /* KAUTHacl_H_ */
| 24.925373 | 92 | 0.730539 | [
"model"
] |
83340e24d0e46f6beb66ea212c47016f41d348ad | 10,047 | h | C | aws-cpp-sdk-route53/include/aws/route53/model/ListVPCAssociationAuthorizationsRequest.h | capeanalytics/aws-sdk-cpp | e88f75add5a9433601b6d46fe738e493da56ac3b | [
"Apache-2.0"
] | null | null | null | aws-cpp-sdk-route53/include/aws/route53/model/ListVPCAssociationAuthorizationsRequest.h | capeanalytics/aws-sdk-cpp | e88f75add5a9433601b6d46fe738e493da56ac3b | [
"Apache-2.0"
] | null | null | null | aws-cpp-sdk-route53/include/aws/route53/model/ListVPCAssociationAuthorizationsRequest.h | capeanalytics/aws-sdk-cpp | e88f75add5a9433601b6d46fe738e493da56ac3b | [
"Apache-2.0"
] | null | null | null | /*
* 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.
*/
#pragma once
#include <aws/route53/Route53_EXPORTS.h>
#include <aws/route53/Route53Request.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>
namespace Aws
{
namespace Http
{
class URI;
} //namespace Http
namespace Route53
{
namespace Model
{
/**
* <p>A complex type that contains information about that can be associated with
* your hosted zone.</p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListVPCAssociationAuthorizationsRequest">AWS
* API Reference</a></p>
*/
class AWS_ROUTE53_API ListVPCAssociationAuthorizationsRequest : public Route53Request
{
public:
ListVPCAssociationAuthorizationsRequest();
Aws::String SerializePayload() const override;
void AddQueryStringParameters(Aws::Http::URI& uri) const override;
/**
* <p>The ID of the hosted zone for which you want a list of VPCs that can be
* associated with the hosted zone.</p>
*/
inline const Aws::String& GetHostedZoneId() const{ return m_hostedZoneId; }
/**
* <p>The ID of the hosted zone for which you want a list of VPCs that can be
* associated with the hosted zone.</p>
*/
inline void SetHostedZoneId(const Aws::String& value) { m_hostedZoneIdHasBeenSet = true; m_hostedZoneId = value; }
/**
* <p>The ID of the hosted zone for which you want a list of VPCs that can be
* associated with the hosted zone.</p>
*/
inline void SetHostedZoneId(Aws::String&& value) { m_hostedZoneIdHasBeenSet = true; m_hostedZoneId = std::move(value); }
/**
* <p>The ID of the hosted zone for which you want a list of VPCs that can be
* associated with the hosted zone.</p>
*/
inline void SetHostedZoneId(const char* value) { m_hostedZoneIdHasBeenSet = true; m_hostedZoneId.assign(value); }
/**
* <p>The ID of the hosted zone for which you want a list of VPCs that can be
* associated with the hosted zone.</p>
*/
inline ListVPCAssociationAuthorizationsRequest& WithHostedZoneId(const Aws::String& value) { SetHostedZoneId(value); return *this;}
/**
* <p>The ID of the hosted zone for which you want a list of VPCs that can be
* associated with the hosted zone.</p>
*/
inline ListVPCAssociationAuthorizationsRequest& WithHostedZoneId(Aws::String&& value) { SetHostedZoneId(std::move(value)); return *this;}
/**
* <p>The ID of the hosted zone for which you want a list of VPCs that can be
* associated with the hosted zone.</p>
*/
inline ListVPCAssociationAuthorizationsRequest& WithHostedZoneId(const char* value) { SetHostedZoneId(value); return *this;}
/**
* <p> <i>Optional</i>: If a response includes a <code>NextToken</code> element,
* there are more VPCs that can be associated with the specified hosted zone. To
* get the next page of results, submit another request, and include the value of
* <code>NextToken</code> from the response in the <code>nexttoken</code> parameter
* in another <code>ListVPCAssociationAuthorizations</code> request.</p>
*/
inline const Aws::String& GetNextToken() const{ return m_nextToken; }
/**
* <p> <i>Optional</i>: If a response includes a <code>NextToken</code> element,
* there are more VPCs that can be associated with the specified hosted zone. To
* get the next page of results, submit another request, and include the value of
* <code>NextToken</code> from the response in the <code>nexttoken</code> parameter
* in another <code>ListVPCAssociationAuthorizations</code> request.</p>
*/
inline void SetNextToken(const Aws::String& value) { m_nextTokenHasBeenSet = true; m_nextToken = value; }
/**
* <p> <i>Optional</i>: If a response includes a <code>NextToken</code> element,
* there are more VPCs that can be associated with the specified hosted zone. To
* get the next page of results, submit another request, and include the value of
* <code>NextToken</code> from the response in the <code>nexttoken</code> parameter
* in another <code>ListVPCAssociationAuthorizations</code> request.</p>
*/
inline void SetNextToken(Aws::String&& value) { m_nextTokenHasBeenSet = true; m_nextToken = std::move(value); }
/**
* <p> <i>Optional</i>: If a response includes a <code>NextToken</code> element,
* there are more VPCs that can be associated with the specified hosted zone. To
* get the next page of results, submit another request, and include the value of
* <code>NextToken</code> from the response in the <code>nexttoken</code> parameter
* in another <code>ListVPCAssociationAuthorizations</code> request.</p>
*/
inline void SetNextToken(const char* value) { m_nextTokenHasBeenSet = true; m_nextToken.assign(value); }
/**
* <p> <i>Optional</i>: If a response includes a <code>NextToken</code> element,
* there are more VPCs that can be associated with the specified hosted zone. To
* get the next page of results, submit another request, and include the value of
* <code>NextToken</code> from the response in the <code>nexttoken</code> parameter
* in another <code>ListVPCAssociationAuthorizations</code> request.</p>
*/
inline ListVPCAssociationAuthorizationsRequest& WithNextToken(const Aws::String& value) { SetNextToken(value); return *this;}
/**
* <p> <i>Optional</i>: If a response includes a <code>NextToken</code> element,
* there are more VPCs that can be associated with the specified hosted zone. To
* get the next page of results, submit another request, and include the value of
* <code>NextToken</code> from the response in the <code>nexttoken</code> parameter
* in another <code>ListVPCAssociationAuthorizations</code> request.</p>
*/
inline ListVPCAssociationAuthorizationsRequest& WithNextToken(Aws::String&& value) { SetNextToken(std::move(value)); return *this;}
/**
* <p> <i>Optional</i>: If a response includes a <code>NextToken</code> element,
* there are more VPCs that can be associated with the specified hosted zone. To
* get the next page of results, submit another request, and include the value of
* <code>NextToken</code> from the response in the <code>nexttoken</code> parameter
* in another <code>ListVPCAssociationAuthorizations</code> request.</p>
*/
inline ListVPCAssociationAuthorizationsRequest& WithNextToken(const char* value) { SetNextToken(value); return *this;}
/**
* <p> <i>Optional</i>: An integer that specifies the maximum number of VPCs that
* you want Amazon Route 53 to return. If you don't specify a value for
* <code>MaxResults</code>, Amazon Route 53 returns up to 50 VPCs per page.</p>
*/
inline const Aws::String& GetMaxResults() const{ return m_maxResults; }
/**
* <p> <i>Optional</i>: An integer that specifies the maximum number of VPCs that
* you want Amazon Route 53 to return. If you don't specify a value for
* <code>MaxResults</code>, Amazon Route 53 returns up to 50 VPCs per page.</p>
*/
inline void SetMaxResults(const Aws::String& value) { m_maxResultsHasBeenSet = true; m_maxResults = value; }
/**
* <p> <i>Optional</i>: An integer that specifies the maximum number of VPCs that
* you want Amazon Route 53 to return. If you don't specify a value for
* <code>MaxResults</code>, Amazon Route 53 returns up to 50 VPCs per page.</p>
*/
inline void SetMaxResults(Aws::String&& value) { m_maxResultsHasBeenSet = true; m_maxResults = std::move(value); }
/**
* <p> <i>Optional</i>: An integer that specifies the maximum number of VPCs that
* you want Amazon Route 53 to return. If you don't specify a value for
* <code>MaxResults</code>, Amazon Route 53 returns up to 50 VPCs per page.</p>
*/
inline void SetMaxResults(const char* value) { m_maxResultsHasBeenSet = true; m_maxResults.assign(value); }
/**
* <p> <i>Optional</i>: An integer that specifies the maximum number of VPCs that
* you want Amazon Route 53 to return. If you don't specify a value for
* <code>MaxResults</code>, Amazon Route 53 returns up to 50 VPCs per page.</p>
*/
inline ListVPCAssociationAuthorizationsRequest& WithMaxResults(const Aws::String& value) { SetMaxResults(value); return *this;}
/**
* <p> <i>Optional</i>: An integer that specifies the maximum number of VPCs that
* you want Amazon Route 53 to return. If you don't specify a value for
* <code>MaxResults</code>, Amazon Route 53 returns up to 50 VPCs per page.</p>
*/
inline ListVPCAssociationAuthorizationsRequest& WithMaxResults(Aws::String&& value) { SetMaxResults(std::move(value)); return *this;}
/**
* <p> <i>Optional</i>: An integer that specifies the maximum number of VPCs that
* you want Amazon Route 53 to return. If you don't specify a value for
* <code>MaxResults</code>, Amazon Route 53 returns up to 50 VPCs per page.</p>
*/
inline ListVPCAssociationAuthorizationsRequest& WithMaxResults(const char* value) { SetMaxResults(value); return *this;}
private:
Aws::String m_hostedZoneId;
bool m_hostedZoneIdHasBeenSet;
Aws::String m_nextToken;
bool m_nextTokenHasBeenSet;
Aws::String m_maxResults;
bool m_maxResultsHasBeenSet;
};
} // namespace Model
} // namespace Route53
} // namespace Aws
| 46.948598 | 141 | 0.69792 | [
"model"
] |
833547a23acc603c5734f24c9dba3ee27ce34ab5 | 14,729 | h | C | llvm/3.4.2/llvm-3.4.2.src/include/llvm/IR/PassManager.h | tangyibin/goblin-core | 1940db6e95908c81687b2b22ddd9afbc8db9cdfe | [
"BSD-3-Clause"
] | 36 | 2015-01-13T19:34:04.000Z | 2022-03-07T22:22:15.000Z | llvm/3.4.2/llvm-3.4.2.src/include/llvm/IR/PassManager.h | tangyibin/goblin-core | 1940db6e95908c81687b2b22ddd9afbc8db9cdfe | [
"BSD-3-Clause"
] | 7 | 2015-10-20T19:05:01.000Z | 2021-11-13T14:55:47.000Z | llvm/3.4.2/llvm-3.4.2.src/include/llvm/IR/PassManager.h | tangyibin/goblin-core | 1940db6e95908c81687b2b22ddd9afbc8db9cdfe | [
"BSD-3-Clause"
] | 18 | 2015-04-23T20:59:52.000Z | 2021-11-18T20:06:39.000Z | //===- PassManager.h - Pass management infrastructure -----------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
/// \file
///
/// This header defines various interfaces for pass management in LLVM. There
/// is no "pass" interface in LLVM per se. Instead, an instance of any class
/// which supports a method to 'run' it over a unit of IR can be used as
/// a pass. A pass manager is generally a tool to collect a sequence of passes
/// which run over a particular IR construct, and run each of them in sequence
/// over each such construct in the containing IR construct. As there is no
/// containing IR construct for a Module, a manager for passes over modules
/// forms the base case which runs its managed passes in sequence over the
/// single module provided.
///
/// The core IR library provides managers for running passes over
/// modules and functions.
///
/// * FunctionPassManager can run over a Module, runs each pass over
/// a Function.
/// * ModulePassManager must be directly run, runs each pass over the Module.
///
/// Note that the implementations of the pass managers use concept-based
/// polymorphism as outlined in the "Value Semantics and Concept-based
/// Polymorphism" talk (or its abbreviated sibling "Inheritance Is The Base
/// Class of Evil") by Sean Parent:
/// * http://github.com/sean-parent/sean-parent.github.com/wiki/Papers-and-Presentations
/// * http://www.youtube.com/watch?v=_BpMYeUFXv8
/// * http://channel9.msdn.com/Events/GoingNative/2013/Inheritance-Is-The-Base-Class-of-Evil
///
//===----------------------------------------------------------------------===//
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/polymorphic_ptr.h"
#include "llvm/Support/type_traits.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Module.h"
#include <list>
#include <vector>
namespace llvm {
class Module;
class Function;
/// \brief Implementation details of the pass manager interfaces.
namespace detail {
/// \brief Template for the abstract base class used to dispatch
/// polymorphically over pass objects.
template <typename T> struct PassConcept {
// Boiler plate necessary for the container of derived classes.
virtual ~PassConcept() {}
virtual PassConcept *clone() = 0;
/// \brief The polymorphic API which runs the pass over a given IR entity.
virtual bool run(T Arg) = 0;
};
/// \brief A template wrapper used to implement the polymorphic API.
///
/// Can be instantiated for any object which provides a \c run method
/// accepting a \c T. It requires the pass to be a copyable
/// object.
template <typename T, typename PassT> struct PassModel : PassConcept<T> {
PassModel(PassT Pass) : Pass(llvm_move(Pass)) {}
virtual PassModel *clone() { return new PassModel(Pass); }
virtual bool run(T Arg) { return Pass.run(Arg); }
PassT Pass;
};
}
class AnalysisManager;
class ModulePassManager {
public:
ModulePassManager(Module *M, AnalysisManager *AM = 0) : M(M), AM(AM) {}
template <typename ModulePassT> void addPass(ModulePassT Pass) {
Passes.push_back(new ModulePassModel<ModulePassT>(llvm_move(Pass)));
}
void run();
private:
// Pull in the concept type and model template specialized for modules.
typedef detail::PassConcept<Module *> ModulePassConcept;
template <typename PassT>
struct ModulePassModel : detail::PassModel<Module *, PassT> {
ModulePassModel(PassT Pass) : detail::PassModel<Module *, PassT>(Pass) {}
};
Module *M;
AnalysisManager *AM;
std::vector<polymorphic_ptr<ModulePassConcept> > Passes;
};
class FunctionPassManager {
public:
FunctionPassManager(AnalysisManager *AM = 0) : AM(AM) {}
template <typename FunctionPassT> void addPass(FunctionPassT Pass) {
Passes.push_back(new FunctionPassModel<FunctionPassT>(llvm_move(Pass)));
}
bool run(Module *M);
private:
// Pull in the concept type and model template specialized for functions.
typedef detail::PassConcept<Function *> FunctionPassConcept;
template <typename PassT>
struct FunctionPassModel : detail::PassModel<Function *, PassT> {
FunctionPassModel(PassT Pass)
: detail::PassModel<Function *, PassT>(Pass) {}
};
AnalysisManager *AM;
std::vector<polymorphic_ptr<FunctionPassConcept> > Passes;
};
/// \brief An analysis manager to coordinate and cache analyses run over
/// a module.
///
/// The analysis manager is typically used by passes in a pass pipeline
/// (consisting potentially of several individual pass managers) over a module
/// of IR. It provides registration of available analyses, declaring
/// requirements on support for specific analyses, running of an specific
/// analysis over a specific unit of IR to compute an analysis result, and
/// caching of the analysis results to reuse them across multiple passes.
///
/// It is the responsibility of callers to use the invalidation API to
/// invalidate analysis results when the IR they correspond to changes. The
/// \c ModulePassManager and \c FunctionPassManager do this automatically.
class AnalysisManager {
public:
AnalysisManager(Module *M) : M(M) {}
/// \brief Get the result of an analysis pass for this module.
///
/// If there is not a valid cached result in the manager already, this will
/// re-run the analysis to produce a valid result.
///
/// The module passed in must be the same module as the analysis manager was
/// constructed around.
template <typename PassT>
const typename PassT::Result &getResult(Module *M) {
assert(ModuleAnalysisPasses.count(PassT::ID()) &&
"This analysis pass was not registered prior to being queried");
const AnalysisResultConcept<Module> &ResultConcept =
getResultImpl(PassT::ID(), M);
typedef AnalysisResultModel<Module, typename PassT::Result> ResultModelT;
return static_cast<const ResultModelT &>(ResultConcept).Result;
}
/// \brief Get the result of an analysis pass for a function.
///
/// If there is not a valid cached result in the manager already, this will
/// re-run the analysis to produce a valid result.
template <typename PassT>
const typename PassT::Result &getResult(Function *F) {
assert(FunctionAnalysisPasses.count(PassT::ID()) &&
"This analysis pass was not registered prior to being queried");
const AnalysisResultConcept<Function> &ResultConcept =
getResultImpl(PassT::ID(), F);
typedef AnalysisResultModel<Function, typename PassT::Result> ResultModelT;
return static_cast<const ResultModelT &>(ResultConcept).Result;
}
/// \brief Register an analysis pass with the manager.
///
/// This provides an initialized and set-up analysis pass to the
/// analysis
/// manager. Whomever is setting up analysis passes must use this to
/// populate
/// the manager with all of the analysis passes available.
template <typename PassT> void registerAnalysisPass(PassT Pass) {
registerAnalysisPassImpl<PassT>(llvm_move(Pass));
}
/// \brief Invalidate a specific analysis pass for an IR module.
///
/// Note that the analysis result can disregard invalidation.
template <typename PassT> void invalidate(Module *M) {
invalidateImpl(PassT::ID(), M);
}
/// \brief Invalidate a specific analysis pass for an IR function.
///
/// Note that the analysis result can disregard invalidation.
template <typename PassT> void invalidate(Function *F) {
invalidateImpl(PassT::ID(), F);
}
/// \brief Invalidate analyses cached for an IR Module.
///
/// Note that specific analysis results can disregard invalidation by
/// overriding their invalidate method.
///
/// The module must be the module this analysis manager was constructed
/// around.
void invalidateAll(Module *M);
/// \brief Invalidate analyses cached for an IR Function.
///
/// Note that specific analysis results can disregard invalidation by
/// overriding the invalidate method.
void invalidateAll(Function *F);
private:
/// \brief Abstract concept of an analysis result.
///
/// This concept is parameterized over the IR unit that this result pertains
/// to.
template <typename IRUnitT> struct AnalysisResultConcept {
virtual ~AnalysisResultConcept() {}
virtual AnalysisResultConcept *clone() = 0;
/// \brief Method to try and mark a result as invalid.
///
/// When the outer \c AnalysisManager detects a change in some underlying
/// unit of the IR, it will call this method on all of the results cached.
///
/// \returns true if the result should indeed be invalidated (the default).
virtual bool invalidate(IRUnitT *IR) = 0;
};
/// \brief Wrapper to model the analysis result concept.
///
/// Can wrap any type which implements a suitable invalidate member and model
/// the AnalysisResultConcept for the AnalysisManager.
template <typename IRUnitT, typename ResultT>
struct AnalysisResultModel : AnalysisResultConcept<IRUnitT> {
AnalysisResultModel(ResultT Result) : Result(llvm_move(Result)) {}
virtual AnalysisResultModel *clone() {
return new AnalysisResultModel(Result);
}
/// \brief The model delegates to the \c ResultT method.
virtual bool invalidate(IRUnitT *IR) { return Result.invalidate(IR); }
ResultT Result;
};
/// \brief Abstract concept of an analysis pass.
///
/// This concept is parameterized over the IR unit that it can run over and
/// produce an analysis result.
template <typename IRUnitT> struct AnalysisPassConcept {
virtual ~AnalysisPassConcept() {}
virtual AnalysisPassConcept *clone() = 0;
/// \brief Method to run this analysis over a unit of IR.
/// \returns The analysis result object to be queried by users, the caller
/// takes ownership.
virtual AnalysisResultConcept<IRUnitT> *run(IRUnitT *IR) = 0;
};
/// \brief Wrapper to model the analysis pass concept.
///
/// Can wrap any type which implements a suitable \c run method. The method
/// must accept the IRUnitT as an argument and produce an object which can be
/// wrapped in a \c AnalysisResultModel.
template <typename PassT>
struct AnalysisPassModel : AnalysisPassConcept<typename PassT::IRUnitT> {
AnalysisPassModel(PassT Pass) : Pass(llvm_move(Pass)) {}
virtual AnalysisPassModel *clone() { return new AnalysisPassModel(Pass); }
// FIXME: Replace PassT::IRUnitT with type traits when we use C++11.
typedef typename PassT::IRUnitT IRUnitT;
// FIXME: Replace PassT::Result with type traits when we use C++11.
typedef AnalysisResultModel<IRUnitT, typename PassT::Result> ResultModelT;
/// \brief The model delegates to the \c PassT::run method.
///
/// The return is wrapped in an \c AnalysisResultModel.
virtual ResultModelT *run(IRUnitT *IR) {
return new ResultModelT(Pass.run(IR));
}
PassT Pass;
};
/// \brief Get a module pass result, running the pass if necessary.
const AnalysisResultConcept<Module> &getResultImpl(void *PassID, Module *M);
/// \brief Get a function pass result, running the pass if necessary.
const AnalysisResultConcept<Function> &getResultImpl(void *PassID,
Function *F);
/// \brief Invalidate a module pass result.
void invalidateImpl(void *PassID, Module *M);
/// \brief Invalidate a function pass result.
void invalidateImpl(void *PassID, Function *F);
/// \brief Module pass specific implementation of registration.
template <typename PassT>
typename enable_if<is_same<typename PassT::IRUnitT, Module> >::type
registerAnalysisPassImpl(PassT Pass) {
assert(!ModuleAnalysisPasses.count(PassT::ID()) &&
"Registered the same analysis pass twice!");
ModuleAnalysisPasses[PassT::ID()] =
new AnalysisPassModel<PassT>(llvm_move(Pass));
}
/// \brief Function pass specific implementation of registration.
template <typename PassT>
typename enable_if<is_same<typename PassT::IRUnitT, Function> >::type
registerAnalysisPassImpl(PassT Pass) {
assert(!FunctionAnalysisPasses.count(PassT::ID()) &&
"Registered the same analysis pass twice!");
FunctionAnalysisPasses[PassT::ID()] =
new AnalysisPassModel<PassT>(llvm_move(Pass));
}
/// \brief Map type from module analysis pass ID to pass concept pointer.
typedef DenseMap<void *, polymorphic_ptr<AnalysisPassConcept<Module> > >
ModuleAnalysisPassMapT;
/// \brief Collection of module analysis passes, indexed by ID.
ModuleAnalysisPassMapT ModuleAnalysisPasses;
/// \brief Map type from module analysis pass ID to pass result concept pointer.
typedef DenseMap<void *, polymorphic_ptr<AnalysisResultConcept<Module> > >
ModuleAnalysisResultMapT;
/// \brief Cache of computed module analysis results for this module.
ModuleAnalysisResultMapT ModuleAnalysisResults;
/// \brief Map type from function analysis pass ID to pass concept pointer.
typedef DenseMap<void *, polymorphic_ptr<AnalysisPassConcept<Function> > >
FunctionAnalysisPassMapT;
/// \brief Collection of function analysis passes, indexed by ID.
FunctionAnalysisPassMapT FunctionAnalysisPasses;
/// \brief List of function analysis pass IDs and associated concept pointers.
///
/// Requires iterators to be valid across appending new entries and arbitrary
/// erases. Provides both the pass ID and concept pointer such that it is
/// half of a bijection and provides storage for the actual result concept.
typedef std::list<
std::pair<void *, polymorphic_ptr<AnalysisResultConcept<Function> > > >
FunctionAnalysisResultListT;
/// \brief Map type from function pointer to our custom list type.
typedef DenseMap<Function *, FunctionAnalysisResultListT> FunctionAnalysisResultListMapT;
/// \brief Map from function to a list of function analysis results.
///
/// Provides linear time removal of all analysis results for a function and
/// the ultimate storage for a particular cached analysis result.
FunctionAnalysisResultListMapT FunctionAnalysisResultLists;
/// \brief Map type from a pair of analysis ID and function pointer to an
/// iterator into a particular result list.
typedef DenseMap<std::pair<void *, Function *>,
FunctionAnalysisResultListT::iterator>
FunctionAnalysisResultMapT;
/// \brief Map from an analysis ID and function to a particular cached
/// analysis result.
FunctionAnalysisResultMapT FunctionAnalysisResults;
/// \brief Module handle for the \c AnalysisManager.
Module *M;
};
}
| 38.356771 | 92 | 0.713966 | [
"object",
"vector",
"model"
] |
833cd57ca0dbfffadbe6b03da0e9fc444ee1750d | 5,049 | h | C | src/include/kv/table.h | hezhihua/horsedb | d0a14d2e6a31aa40402b077e779e89d668b9f66d | [
"Apache-2.0"
] | 8 | 2020-11-20T07:33:08.000Z | 2020-12-25T03:45:09.000Z | src/include/kv/table.h | hezhihua/horsedb | d0a14d2e6a31aa40402b077e779e89d668b9f66d | [
"Apache-2.0"
] | null | null | null | src/include/kv/table.h | hezhihua/horsedb | d0a14d2e6a31aa40402b077e779e89d668b9f66d | [
"Apache-2.0"
] | 2 | 2020-11-20T14:20:50.000Z | 2021-10-11T07:43:09.000Z | #ifndef __TABLE__
#define __TABLE__
#include <string>
#include <vector>
#include <memory>
#include "SQLParser.h"
#include "util/sqlhelper.h"
#include "kv/meta.h"
#include "iguana/json.hpp"
using namespace std;
using namespace hsql;
#define tablePrefix "t"
#define recordPrefixSep "_r"
#define indexPrefixSep "_i"
#define defaultPriveteKeyName "id"
#define defaultPriveteKeyLength 11
namespace horsedb{
enum class DataType {
UNKNOWN,
INT,
LONG,
FLOAT,
DOUBLE,
CHAR,
VARCHAR,
TEXT,
DATETIME
};
// Represents the type of a column, e.g., FLOAT or VARCHAR(10)
struct ColumnType {
ColumnType() = default;
ColumnType(DataType data_type, int64_t length = 0);
DataType data_type;
int64_t length; // Used for, e.g., VARCHAR(10)
};
//REFLECTION(ColumnType, data_type,length);
struct Column
{
Column() = default;
Column(string name,horsedb::ColumnType type,bool nullable):_name(name),_data_type(type.data_type),_length(type.length),_nullable(nullable){}
string _name;
//horsedb::ColumnType _type;
DataType _data_type;
int64_t _length; // Used for, e.g., VARCHAR(10)
bool _nullable;
};
REFLECTION(Column, _name,_data_type,_length,_nullable);
struct Key
{
Key() = default;
Key(string name,bool isUniqueKey,bool isPrivateKey):_name(name),_isUniqueKey(isUniqueKey),_isPrivateKey(isPrivateKey){}
string _name;
bool _isUniqueKey;
bool _isPrivateKey;
vector<string> _vColumnName;
};
REFLECTION(Key, _name,_isUniqueKey,_isPrivateKey,_vColumnName);
struct Row
{
Row() = default;
Row(const vector<string> &vData):_vData(vData){};
vector<string> _vData;
};
REFLECTION(Row, _vData);
class Table
{
public:
// CREATE TABLE User {
// ID int,
// Name varchar(20),
// Role varchar(20),
// Age int,
// PRIMARY KEY (ID),
// Key idxAge (age) //目前只支持单列索引,不支持联合索引
// };
//每行数据按照如下规则进行编码成 Key-Value
//Key: tablePrefix{tableID}_recordPrefixSep{rowID}
//Value: [col1, col2, col3]
// t10_r1 --> ["HorseDB", "SQL Layer", 10]
// t10_r2 --> ["HorseDB", "KV Engine", 20]
// t10_r3 --> ["HorseDB", "Manager", 30]
//Unique Index
//Key: tablePrefix{tableID}_indexPrefixSep{indexID}_indexedColumnsValue
//Value: rowID
//非Unique Index
//Key: tablePrefix{tableID}_indexPrefixSep{indexID}_indexedColumnsValue_rowID
//Value: null
// t10_i1_10_1 --> null
// t10_i1_20_2 --> null
// t10_i1_30_3 --> null
Table(){};
Table(std::shared_ptr<Meta> metaPtr,std::shared_ptr<DBBase> dbPtr,string dbname="");
~ Table(){};
int initTable();
int fillTable(const CreateStatement* createSt);
int createTable(const CreateStatement* createSt,const string &dbname,const map<string,string> &mSession=map<string,string>());
int parseInsert(const InsertStatement* insertSt,vector<string> &vColumnName, vector<string> &vData, string &tbname);
int insertTable(const InsertStatement* insertSt,const string &dbname,const map<string,string> &mSession=map<string,string>());
string insertTbKey(const string &tbname,string &sRowID,const map<string,string> &mSession=map<string,string>());
int selectTable(const SelectStatement* insertSt,vector<string> &vColumnName, vector<map<string,string>> &mData, const string &dbname);
string getPreRowKeyByTb(const string &tbname);
string IndexNotUniqueKey(const string &tbname,const string &columnName,const string &columnValue,const string &sRowID);
string IndexUniqueKey(const string &tbname,const string &columnName,const string &columnValue);
bool isIndexColumn(const string& sColumnName,Table &tb,bool &bUnique,bool &bPrivate);
void str2Row(const vector<string> &vStrRow,const Table &tTable,vector<map<string,string>> &vRowData,const vector<string> &vResultKey,
const map<string,string> &mCondition=map<string,string>());
void indexRowKey2RowKey(const string &tbname,const vector<string> &vIndexRowKey,vector<string> &vRowKey);
int createDatabase(const CreateStatement* createSt,const map<string,string> &mSession=map<string,string>());
int create(const CreateStatement* createSt,const string &dbname,const map<string,string> &mSession=map<string,string>());
int getDBTables(vector<string> &vTable,const string &dbname);
bool getPrivateKeyName(const Table &tb,string& sPrivateColumnName);
bool getMetaTable(const string &tbname,const string &dbname,Table &tTable);
string _dbname;
string _name;
vector<Column> _vColumns;
vector<Key> _vKey;
std::shared_ptr<Meta> _metaPtr;
std::shared_ptr<DBBase> _dbPtr;
};
REFLECTION(Table, _dbname,_name,_vColumns,_vKey);
}
#endif
| 31.754717 | 146 | 0.659933 | [
"vector"
] |
8343758bd8dee0c0c0e87015c61a0c516ac10ef9 | 5,381 | h | C | hphp/util/stack-trace.h | jeffomatic/hhvm | afd1a0c089aff36a31b8990490366606694a2842 | [
"PHP-3.01",
"Zend-2.0"
] | 2 | 2019-09-01T19:40:10.000Z | 2019-10-18T13:30:30.000Z | hphp/util/stack-trace.h | alisha/hhvm | 523dc33b444bd5b59695eff2b64056629b0ed523 | [
"PHP-3.01",
"Zend-2.0"
] | 2 | 2020-10-11T22:54:12.000Z | 2021-07-20T22:12:10.000Z | hphp/util/stack-trace.h | alisha/hhvm | 523dc33b444bd5b59695eff2b64056629b0ed523 | [
"PHP-3.01",
"Zend-2.0"
] | 1 | 2020-12-30T13:22:47.000Z | 2020-12-30T13:22:47.000Z | /*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#ifndef incl_HPHP_STACKTRACE_H_
#define incl_HPHP_STACKTRACE_H_
#include <map>
#include <memory>
#include <string>
#include <vector>
#include <folly/Range.h>
#include "hphp/util/compatibility.h"
#include "hphp/util/portability.h"
#ifndef _MSC_VER
#include <dlfcn.h>
#endif
namespace HPHP {
////////////////////////////////////////////////////////////////////////////////
/*
* An unsymbolized stack frame.
*/
struct StackFrame {
explicit StackFrame(void* addr) : addr{addr} {}
void* addr{nullptr};
int lineno{0};
int offset{0};
};
/*
* A StackFrame that has been symbolized with a filename and function name.
*/
struct StackFrameExtra : StackFrame {
explicit StackFrameExtra(void* addr) : StackFrame(addr) {}
std::string toString() const;
std::string filename;
std::string funcname;
};
////////////////////////////////////////////////////////////////////////////////
/*
* Taking a stacktrace at current execution location. Do not use directly, use
* StackTrace or StackTraceNoHeap instead.
*/
struct StackTraceBase {
static constexpr unsigned kMaxFrame = 175;
static bool Enabled;
static const char* const* FunctionBlacklist;
static unsigned FunctionBlacklistCount;
protected:
StackTraceBase();
};
////////////////////////////////////////////////////////////////////////////////
struct StackTrace : StackTraceBase {
struct PerfMap {
void rebuild();
bool translate(StackFrameExtra*) const;
struct Range {
uintptr_t base;
uintptr_t past;
struct Cmp {
bool operator() (const Range& a, const Range& b) const {
return a.past <= b.base;
}
};
};
bool m_built = false;
std::map<Range,std::string,Range::Cmp> m_map;
};
//////////////////////////////////////////////////////////////////////////////
/*
* Construct the current stacktrace if `trace' and Enabled are true,
* else an empty stacktrace.
*/
explicit StackTrace(bool trace = true);
/*
* Construct the current stacktrace even when Enabled is false.
*/
enum Force {};
explicit StackTrace(Force);
/*
* Construct a stacktrace from a list of instruction pointers.
*/
StackTrace(void* const* ips, size_t count);
/*
* Constructing from hexEncode() results.
*/
explicit StackTrace(folly::StringPiece);
/*
* Translate a frame pointer to file name and line number pair.
*/
static std::shared_ptr<StackFrameExtra> Translate(void* addr,
PerfMap* pm = nullptr);
/*
* Encode the stacktrace addresses in a string.
*
* Skip minLevel frames, and end after the maxLevel'th at the most.
*/
std::string hexEncode(int minLevel = 0, int maxLevel = 999) const;
/*
* Generate a string representation of the stack trace.
*/
const std::string& toString(int skip = 0, int limit = -1) const;
/*
* Get translated frames.
*/
void get(std::vector<std::shared_ptr<StackFrameExtra>>&) const;
//////////////////////////////////////////////////////////////////////////////
private:
std::vector<void*> m_frames;
// Cached backtrace string.
mutable std::string m_trace;
mutable bool m_trace_usable{false};
};
////////////////////////////////////////////////////////////////////////////////
/*
* Computing a stack trace without using the heap. Ideally this should be safe
* to use within a signal handler.
*/
struct StackTraceNoHeap : StackTraceBase {
/*
* Construct the curent stacktrace if `trace' is true, else an empty
* stacktrace.
*/
explicit StackTraceNoHeap(bool trace = true);
/*
* Log process/thread information, plus any extra logging that was queued.
*/
void log(const char* errorType, int fd, const char* buildId,
int debuggerCount) const;
/*
* Log the C++ stack trace
*/
void printStackTrace(int fd) const;
/*
* Add extra information to log together with a crash stacktrace log.
*/
static void AddExtraLogging(const char* name, const std::string& value);
static void ClearAllExtraLogging();
struct ExtraLoggingClearer {
ExtraLoggingClearer() {}
~ExtraLoggingClearer() {
StackTraceNoHeap::ClearAllExtraLogging();
}
};
private:
void* m_frames[kMaxFrame];
unsigned m_frame_count;
};
////////////////////////////////////////////////////////////////////////////////
}
#endif
| 26.905 | 80 | 0.54711 | [
"vector"
] |
8349c9ebfd0c481dd6152882ed5592561626e5df | 15,136 | h | C | src/emu/processor-proxy.h | elopez/rv8 | 834259098a5c182874aac97d82a164d144244e1a | [
"MIT"
] | 463 | 2017-05-11T05:18:51.000Z | 2021-01-29T05:18:41.000Z | src/emu/processor-proxy.h | michaeljclark/riscv-mc | 834259098a5c182874aac97d82a164d144244e1a | [
"MIT"
] | 25 | 2017-05-11T07:57:48.000Z | 2020-07-01T04:04:36.000Z | src/emu/processor-proxy.h | michaeljclark/riscv-mc | 834259098a5c182874aac97d82a164d144244e1a | [
"MIT"
] | 62 | 2017-06-02T01:07:33.000Z | 2020-11-12T18:58:07.000Z | //
// processor-proxy.h
//
#ifndef rv_processor_proxy_h
#define rv_processor_proxy_h
namespace riscv {
/* Processor ABI/AEE proxy emulator that delegates ecall to an abi proxy */
template <typename P>
struct processor_proxy : P
{
int set_child_tid;
int clear_child_tid;
elf_file elf;
addr_t imageoffset;
addr_t imagebase;
std::string stats_dirname;
const char* name() { return "rv-sim"; }
void init() {}
void destroy()
{
/* Unmap memory segments */
for (auto &seg: P::mmu.mem->segments) {
guest_munmap(seg.first, seg.second);
}
}
void exit(int rc)
{
if (P::log & proc_log_exit_log_stats) {
/* reopen console if necessary */
struct pollfd pfd[3] = { { .fd=fileno(stdout) } };
poll(pfd, 1, 0);
if (pfd[0].revents & POLLNVAL) {
int fd = open("/dev/tty", O_WRONLY);
if (fd < 0) ::exit(rc);
if (dup2(fd, fileno(stdout)) < 0) ::exit(rc);
}
/* print integer register file */
printf("\n");
printf("integer register file\n");
printf("~~~~~~~~~~~~~~~~~~~~~\n");
P::print_int_registers();
/* print control and status registers */
printf("\n");
printf("control and status registers\n");
printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n");
P::print_csr_registers();
/* print program counter histogram */
if ((P::log & proc_log_hist_pc) && !(P::log & proc_log_jit_trap)) {
printf("\n");
printf("program counter histogram\n");
printf("~~~~~~~~~~~~~~~~~~~~~~~~~\n");
histogram_pc_print(*this, false);
printf("\n");
}
/* print register histogram */
if ((P::log & proc_log_hist_reg) && !(P::log & proc_log_jit_trap)) {
printf("\n");
printf("register usage histogram\n");
printf("~~~~~~~~~~~~~~~~~~~~~~~~\n");
histogram_reg_print(*this, false);
}
/* print register histogram */
if ((P::log & proc_log_hist_inst) && !(P::log & proc_log_jit_trap)) {
printf("\n");
printf("instruction usage histogram\n");
printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~\n");
histogram_inst_print(*this, false);
printf("\n");
}
}
if ((P::log & proc_log_exit_save_stats) && !(P::log & proc_log_jit_trap)) {
if (P::log & proc_log_hist_pc) {
std::string filename = stats_dirname + "/" + "hist-pc.csv";
histogram_pc_save(*this, filename);
}
if (P::log & proc_log_hist_reg) {
std::string filename = stats_dirname + "/" + "hist-reg.csv";
histogram_reg_save(*this, filename);
}
if (P::log & proc_log_hist_inst) {
std::string filename = stats_dirname + "/" + "hist-inst.csv";
histogram_inst_save(*this, filename);
}
}
}
static inline int elf_p_flags_mmap(int v)
{
int prot = 0;
if (v & PF_X) prot |= PROT_EXEC;
if (v & PF_W) prot |= PROT_WRITE;
if (v & PF_R) prot |= PROT_READ;
return prot;
}
/* resolve a symbol from the ELF symbol table */
const char* symlookup_elf(addr_t addr)
{
static char symbol_tmpname[256];
if (addr < imageoffset) {
snprintf(symbol_tmpname, sizeof(symbol_tmpname),
"0x%016llx", addr);
return symbol_tmpname;
}
addr -= imageoffset;
auto sym = elf.sym_by_addr((Elf64_Addr)addr);
if (sym) {
snprintf(symbol_tmpname, sizeof(symbol_tmpname),
"%s", elf.sym_name(sym));
return symbol_tmpname;
}
sym = elf.sym_by_nearest_addr((Elf64_Addr)addr);
if (sym) {
int64_t offset = int64_t(addr) - sym->st_value;
snprintf(symbol_tmpname, sizeof(symbol_tmpname),
"%s%s0x%" PRIx64, elf.sym_name(sym),
offset < 0 ? "-" : "+", offset < 0 ? -offset : offset);
return symbol_tmpname;
}
return nullptr;
}
/* search for the ELF interpreter if one exists */
char* find_interp_path(const char* elf_filename, const char* interp_name)
{
static char search_path[PATH_MAX + 1];
static char interp_path[PATH_MAX + 1];
struct stat statbuf;
if (!interp_name) return nullptr;
strncpy(search_path, elf_filename, PATH_MAX);
while (strlen(search_path) > 1) {
char *path = dirname(search_path);
strncpy(search_path, path, PATH_MAX);
snprintf(interp_path, PATH_MAX,
interp_name[0] == '/' ? "%s%s" : "%s/%s",
search_path, interp_name);
if (stat(interp_path, &statbuf) == 0) {
return interp_path;
}
}
return nullptr;
}
/* Map ELF executable into address space */
void map_executable(std::string elf_filename, std::vector<std::string> &cmdline, bool symbolicate)
{
/* load ELF (headers only unless symbolicating) */
elf.load(elf_filename, symbolicate ? elf_load_all : elf_load_headers);
/* load dynamic loader if we have a dynamic executable */
const char* interp_name = elf.interp_name();
if (interp_name) {
const char* interp_path = find_interp_path(elf_filename.c_str(), interp_name);
if (interp_path) {
cmdline.insert(cmdline.begin(), interp_path);
elf.load(interp_path, symbolicate ? elf_load_all : elf_load_headers);
elf_filename = interp_path;
} else {
panic("error: can't find interpreter: %s", interp_name);
}
}
/* map dynamic loader into high memory (1GB below memory top) */
imageoffset = (elf.ehdr.e_type == ET_DYN &&
elf.phdrs.size() > 0 &&
elf.phdrs[0].p_vaddr == 0) ? P::mmu_type::memory_top - 0x40000000 : 0;
P::pc = elf.ehdr.e_entry + imageoffset;
/* Find the ELF executable PT_LOAD segments and mmap them into user memory */
for (size_t i = 0; i < elf.phdrs.size(); i++) {
Elf64_Phdr &phdr = elf.phdrs[i];
if (phdr.p_type == PT_LOAD) {
map_load_segment_user(elf_filename.c_str(), phdr, imageoffset);
}
}
}
/* Map a single stack segment into user address space */
void map_proxy_stack(addr_t stack_top, size_t stack_size)
{
void *addr = guest_mmap((void*)(stack_top - stack_size), stack_size,
PROT_READ | PROT_WRITE, MAP_FIXED | MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
if (addr == MAP_FAILED) {
panic("map_proxy_stack: error: mmap: %s", strerror(errno));
}
/* keep track of the mapped segment and set the stack_top */
P::mmu.mem->segments.push_back(std::pair<void*,size_t>((void*)(stack_top - stack_size), stack_size));
P::ireg[rv_ireg_sp] = stack_top;
/* log stack creation */
if (P::log & proc_log_memory) {
debug("mmap-sp :%016" PRIxPTR "-%016" PRIxPTR " +R+W",
(stack_top - stack_size), stack_top);
}
}
void copy_to_proxy_stack(addr_t stack_top, size_t stack_size, void *data, size_t len)
{
P::ireg[rv_ireg_sp] = P::ireg[rv_ireg_sp] - len;
if (size_t(stack_top - P::ireg[rv_ireg_sp]) > stack_size) {
panic("copy_to_proxy_stack: overflow: %d > %d",
stack_top - P::ireg[rv_ireg_sp], stack_size);
}
memcpy((void*)(uintptr_t)P::ireg[rv_ireg_sp].r.xu.val, data, len);
}
void setup_proxy_stack(host_cpu &cpu,
std::vector<std::string> &host_cmdline,
std::vector<std::string> &host_env,
addr_t stack_top, size_t stack_size)
{
/* set up auxiliary vector, environment and command line at top of stack */
/*
STACK TOP
random (16 bytes)
env data
arg data
padding, align 16
auxv table, AT_NULL terminated
envp array, null terminated
argv pointer array, null terminated
argc <- stack pointer
*/
/* setup 16 bytes of random data at the top of the stack */
for (int i = 0; i < 4; i++) {
u32 random = cpu.get_random_seed();
P::ireg[rv_ireg_sp].r.xu.val -= sizeof(u32);
memcpy((void*)(uintptr_t)P::ireg[rv_ireg_sp].r.xu.val, &random, sizeof(random));
}
typename P::ux random_data = P::ireg[rv_ireg_sp];
/* set up aux data */
std::vector<typename P::ux> aux_data = {
AT_BASE, typename P::ux(imagebase),
AT_PHDR, typename P::ux(imagebase + elf.ehdr.e_phoff),
AT_PHNUM, elf.ehdr.e_phnum,
AT_PHENT, elf.ehdr.e_phentsize,
AT_PAGESZ, page_size,
AT_RANDOM, random_data,
AT_UID, getuid(),
AT_EUID, geteuid(),
AT_GID, getgid(),
AT_EGID, getegid(),
AT_NULL, 0
};
/* add environment data to stack */
std::vector<typename P::ux> env_data;
for (auto &env : host_env) {
copy_to_proxy_stack(stack_top, stack_size, (void*)env.c_str(), env.size() + 1);
env_data.push_back(typename P::ux(P::ireg[rv_ireg_sp].r.xu.val));
}
env_data.push_back(0);
/* add command line data to stack */
std::vector<typename P::ux> arg_data;
for (auto &arg : host_cmdline) {
copy_to_proxy_stack(stack_top, stack_size, (void*)arg.c_str(), arg.size() + 1);
arg_data.push_back(typename P::ux(P::ireg[rv_ireg_sp].r.xu.val));
}
arg_data.push_back(0);
/* align stack to 16 bytes */
P::ireg[rv_ireg_sp] = P::ireg[rv_ireg_sp] & ~15;
/* add auxiliary vector to stack */
copy_to_proxy_stack(stack_top, stack_size, (void*)aux_data.data(),
aux_data.size() * sizeof(typename P::ux));
/* add environment array to stack */
copy_to_proxy_stack(stack_top, stack_size, (void*)env_data.data(),
env_data.size() * sizeof(typename P::ux));
/* add command line array to stack */
copy_to_proxy_stack(stack_top, stack_size, (void*)arg_data.data(),
arg_data.size() * sizeof(typename P::ux));
/* add argc, argv, envp to stack */
typename P::ux argc = host_cmdline.size();
copy_to_proxy_stack(stack_top, stack_size, (void*)&argc, sizeof(argc));
}
/* Map ELF load segments into proxy MMU address space */
void map_load_segment_user(const char* filename, Elf64_Phdr &phdr, addr_t voffset)
{
int fd = open(filename, O_RDONLY);
if (fd < 0) {
panic("map_executable: error: open: %s: %s", filename, strerror(errno));
}
/* round the mmap start address and length to the nearest page size */
addr_t map_delta = phdr.p_offset & (page_size-1);
addr_t map_offset = phdr.p_offset - map_delta;
addr_t map_vaddr = phdr.p_vaddr + voffset - map_delta;
addr_t map_len = round_up(phdr.p_memsz + map_delta, page_size);
addr_t map_end = map_vaddr + map_len;
addr_t brk = addr_t(phdr.p_vaddr + voffset + phdr.p_memsz);
if (!imagebase) imagebase = map_vaddr;
/* map the segment */
void *addr = guest_mmap((void*)map_vaddr, map_len,
elf_p_flags_mmap(phdr.p_flags), MAP_FIXED | MAP_PRIVATE, fd, map_offset);
close(fd);
if (addr == MAP_FAILED) {
panic("map_executable: error: mmap: %s: %s", filename, strerror(errno));
}
/* erase trailing bytes past the end of the mapping */
if ((phdr.p_flags & PF_W) && phdr.p_memsz > phdr.p_filesz) {
addr_t start = addr_t(phdr.p_vaddr + voffset + phdr.p_filesz), len = map_end - start;
memset((void*)start, 0, len);
}
/* log load segment virtual address range */
if (P::log & proc_log_memory) {
debug("mmap-elf :%016" PRIxPTR "-%016" PRIxPTR " %s offset=%" PRIxPTR,
addr_t(map_vaddr), addr_t(map_vaddr + map_len),
elf_p_flags_name(phdr.p_flags).c_str(), addr_t(map_offset));
}
/* add the mmap to the emulator proxy_mmu */
P::mmu.mem->segments.push_back(std::pair<void*,size_t>((void*)map_vaddr, map_len));
/* set heap mmap area begin and end */
if (P::mmu.mem->heap_begin < map_end) {
P::mmu.mem->heap_begin = P::mmu.mem->heap_end = map_end;
}
/* set the program break */
if (P::mmu.mem->brk < brk) {
P::mmu.mem->brk = brk;
}
}
addr_t inst_csr(typename P::decode_type &dec, int op, int csr, typename P::ux value, addr_t pc_offset)
{
u32 fflags_mask = 0x1f;
u32 frm_mask = 0x3;
u32 fcsr_mask = 0xff;
switch (csr) {
case rv_csr_fflags: fenv_getflags(P::fcsr);
P::set_csr(dec, rv_mode_U, op, csr, P::fcsr, value,
fflags_mask, fflags_mask);
fenv_clearflags(P::fcsr); break;
case rv_csr_frm: P::set_csr(dec, rv_mode_U, op, csr, P::fcsr, value,
frm_mask, frm_mask, /* shift >> */ 5);
fenv_setrm((P::fcsr >> 5) & 0x7); break;
case rv_csr_fcsr: fenv_getflags(P::fcsr);
P::set_csr(dec, rv_mode_U, op, csr, P::fcsr, value,
fcsr_mask, fcsr_mask);
fenv_clearflags(P::fcsr);
fenv_setrm((P::fcsr >> 5) & 0x7); break;
case rv_csr_cycle: P::get_csr(dec, rv_mode_U, op, csr, P::instret, value); break;
case rv_csr_time: P::time = cpu_cycle_clock();
P::get_csr(dec, rv_mode_U, op, csr, P::time, value); break;
case rv_csr_instret: P::get_csr(dec, rv_mode_U, op, csr, P::instret, value); break;
case rv_csr_cycleh: P::get_csr_hi(dec, rv_mode_U, op, csr, P::instret, value); break;
case rv_csr_timeh: P::get_csr_hi(dec, rv_mode_U, op, csr, P::time, value); break;
case rv_csr_instreth: P::get_csr_hi(dec, rv_mode_U, op, csr, P::instret, value); break;
default: return -1; /* illegal instruction */
}
return pc_offset;
}
typename P::ux inst_priv(typename P::decode_type &dec, typename P::ux pc_offset)
{
switch (dec.op) {
case rv_op_fence:
case rv_op_fence_i: return pc_offset;
case rv_op_ecall: proxy_syscall(*this); return pc_offset;
case rv_op_csrrw: return inst_csr(dec, csr_rw, dec.imm, P::ireg[dec.rs1], pc_offset);
case rv_op_csrrs: return inst_csr(dec, csr_rs, dec.imm, P::ireg[dec.rs1], pc_offset);
case rv_op_csrrc: return inst_csr(dec, csr_rc, dec.imm, P::ireg[dec.rs1], pc_offset);
case rv_op_csrrwi: return inst_csr(dec, csr_rw, dec.imm, dec.rs1, pc_offset);
case rv_op_csrrsi: return inst_csr(dec, csr_rs, dec.imm, dec.rs1, pc_offset);
case rv_op_csrrci: return inst_csr(dec, csr_rc, dec.imm, dec.rs1, pc_offset);
default: break;
}
return -1; /* illegal instruction */
}
void isr() {}
void debug_enter() {}
void debug_leave() {}
void trap(typename P::decode_type &dec, int cause)
{
/* proxy processor unconditionally exits on trap */
P::print_log(dec, 0);
printf("TRAP :%s pc:0x%0llx badaddr:0x%0llx\n",
rv_cause_name_sym[cause],
addr_t(P::pc), addr_t(P::badaddr));
P::print_csr_registers();
P::print_int_registers();
P::raise(P::internal_cause_poweroff, P::pc);
}
void signal(int signum, siginfo_t *info)
{
/*
* NOTE: processor_proxy with the proxy_mmu is not able to
* recover enough information from SIGSEGV to issue a trap.
*
* SIGSEGV is a fatal error, and in the proxy_mmu which uses
* the process virtual address space, it can be caused by the
* interpreter referencing unmapped memory (however proxy_mmu
* masks all loads and stores below < 1GB).
*
* processor_priv MMU uses longjmp to communicate access
* faults which will result in a call to the trap handler.
*/
/* longjmp back to the step loop */
if (signum == SIGINT) {
P::raise(P::internal_cause_cli, P::pc);
} else if (signum == SIGTERM) {
P::raise(P::internal_cause_poweroff, P::pc);
} else {
P::raise(P::internal_cause_fatal, P::pc);
}
}
};
}
#endif
| 33.339207 | 104 | 0.626453 | [
"vector"
] |
834baecbdb81476995df1198aa3d3c9555f3c33e | 6,633 | h | C | include/wrapper/NamedCollection.h | Ahtkom/ccyy | 318bbdc819d94f3d3ec9a141058b6139159ca385 | [
"MIT"
] | null | null | null | include/wrapper/NamedCollection.h | Ahtkom/ccyy | 318bbdc819d94f3d3ec9a141058b6139159ca385 | [
"MIT"
] | null | null | null | include/wrapper/NamedCollection.h | Ahtkom/ccyy | 318bbdc819d94f3d3ec9a141058b6139159ca385 | [
"MIT"
] | null | null | null | #ifndef CCYY_WRAPPER_NAMEDCOLLECTION_H_
#define CCYY_WRAPPER_NAMEDCOLLECTION_H_
#include <wrapper/Collection.h>
#include <util/IllegalArgumentException.h>
#include <sstream>
#include <type_traits>
#include <algorithm>
#include <vector>
#include <string>
#include <memory>
#include <iostream>
namespace ccyy {
namespace wrapper {
/**
* @brief Class template NamedCollection: a container for objects based
* on vector, offering quick access and operations on their names.
*
* @note The name must be unique, not as the type T object.
*
* @tparam T
*/
template<typename T>
class NamedCollection : public Collection<T>
{
public:
NamedCollection() = default;
~NamedCollection() override = default;
// For name looking-ups.
using Collection<T>::operator[];
/**
* @brief A string repr of names.
*/
std::string toString() const;
std::string getName(std::size_t index) const;
T *operator[](std::string name);
const T *operator[](std::string name) const;
void push_back(std::unique_ptr<T> &&ptr, const std::string &name);
// For derived class object
template<typename D>
void push_back(const D &other, const std::string &name);
// For derived class object
template<typename D>
void push_back(D &&other, const std::string &name);
void updateByName(const std::string &name, std::unique_ptr<T> &&ptr);
// For derived class object
template<typename D>
void updateByName(const std::string &name, const D &other);
// For derived class object
template<typename D>
void updateByName(const std::string &name, D &&other);
void reserve(std::size_t n) override;
void eraseByName(const std::string &name);
bool existsName(const std::string &name) const;
void rename(const std::string &name, const std::string &nameNew);
protected:
void eraseByIndex(std::size_t index) override;
// Return -1 if the given name was not found.
int findIndexByName(const std::string &name) const;
void renameByIndex(std::size_t index, const std::string &nameNew);
private:
std::vector<std::string> names_;
};
template<typename T>
std::string NamedCollection<T>::toString() const
{
std::ostringstream s;
s << *this;
return s.str();
}
template<typename T>
std::string NamedCollection<T>::getName(std::size_t index) const
{
return index < Collection<T>::size() ? names_[index] : "";
}
template<typename T>
T *NamedCollection<T>::operator[](std::string name)
{
if (int index = findIndexByName(name) + 1) {
return operator[](static_cast<std::size_t>(index - 1));
}
return nullptr;
}
template<typename T>
const T *NamedCollection<T>::operator[](std::string name) const
{
if (int index = findIndexByName(name) + 1) {
return operator[](static_cast<std::size_t>(index - 1));
}
return nullptr;
}
template<typename T>
void NamedCollection<T>::push_back(std::unique_ptr<T> &&ptr, const std::string &name)
{
if (name.empty()) {
throw util::IllegalArgumentException(__PRETTY_FUNCTION__,
"Name in NamedCollection cannot be empty!");
}
if (!existsName(name)) {
Collection<T>::push_back(std::move(ptr));
names_.push_back(name);
}
}
template<typename T>
template<typename D>
void NamedCollection<T>::push_back(const D &other, const std::string &name)
{
if (name.empty()) {
throw util::IllegalArgumentException(__PRETTY_FUNCTION__,
"Name in NamedCollection cannot be empty!");
}
if (!existsName(name)) {
Collection<T>::push_back(other);
names_.push_back(name);
}
}
template<typename T>
template<typename D>
void NamedCollection<T>::push_back(D &&other, const std::string &name)
{
if (name.empty()) {
throw util::IllegalArgumentException(__PRETTY_FUNCTION__,
"Name in NamedCollection cannot be empty!");
}
if (!existsName(name)) {
Collection<T>::push_back(std::move(other));
names_.push_back(name);
}
}
template<typename T>
void NamedCollection<T>::updateByName(const std::string &name, std::unique_ptr<T> &&ptr)
{
if (int index = findIndexByName(name) + 1) {
Collection<T>::updateByIndex(static_cast<std::size_t>(index - 1), std::move(ptr));
}
}
template<typename T>
template<typename D>
void NamedCollection<T>::updateByName(const std::string &name, const D &other)
{
if (int index = findIndexByName(name) + 1) {
Collection<T>::updateByIndex(static_cast<std::size_t>(index - 1), other);
}
}
template<typename T>
template<typename D>
void NamedCollection<T>::updateByName(const std::string &name, D &&other)
{
if (int index = findIndexByName(name) + 1) {
Collection<T>::updateByIndex(static_cast<std::size_t>(index - 1), std::move(other));
}
}
template<typename T>
void NamedCollection<T>::reserve(std::size_t n)
{
Collection<T>::reserve(n);
names_.reserve(n);
}
template<typename T>
void NamedCollection<T>::eraseByName(const std::string &name)
{
if (int index = findIndexByName(name) + 1) {
eraseByIndex(static_cast<std::size_t>(index - 1));
}
}
template<typename T>
bool NamedCollection<T>::existsName(const std::string &name) const
{
return findIndexByName(name) != -1;
}
template<typename T>
void NamedCollection<T>::rename(const std::string &name, const std::string &nameNew)
{
if (int index = findIndexByName(name) + 1) {
renameByIndex(static_cast<std::size_t>(index - 1), nameNew);
}
}
template<typename T>
void NamedCollection<T>::eraseByIndex(std::size_t index)
{
Collection<T>::eraseByIndex(index);
names_.erase(names_.begin() + index);
}
template<typename T>
int NamedCollection<T>::findIndexByName(const std::string &name) const
{
auto iter = std::find(names_.cbegin(), names_.cend(), name);
return iter == names_.end() ? -1 : (iter - names_.begin());
}
template<typename T>
void NamedCollection<T>::renameByIndex(std::size_t index, const std::string &nameNew)
{
if (nameNew.empty()) {
throw util::IllegalArgumentException(__PRETTY_FUNCTION__,
"Name in NamedCollection cannot be empty!");
}
if (index < Collection<T>::size()) {
names_[index] = nameNew;
}
}
template<typename T>
std::ostream &operator<<(std::ostream &os, const NamedCollection<T> &nc)
{
int maxLength = log10(nc.size()) + 3;
for (std::size_t i = 0; i != nc.size(); ++i) {
os.width(maxLength);
os << std::left << i << nc.getName(i) << "\n";
}
return os;
}
} // namespace wrapper
} // namespace ccyy
#endif | 25.610039 | 92 | 0.663048 | [
"object",
"vector"
] |
8351ccc577d71f25050c1c61bc2f8b85a5c25164 | 24,894 | h | C | TDEngine2/plugins/ImGUIContext/include/CImGUIContext.h | bnoazx005/TDEngine2 | 93ebfecf8af791ff5ecd4f57525a6935e34cd05c | [
"Apache-2.0"
] | 1 | 2019-07-15T01:14:15.000Z | 2019-07-15T01:14:15.000Z | TDEngine2/plugins/ImGUIContext/include/CImGUIContext.h | bnoazx005/TDEngine2 | 93ebfecf8af791ff5ecd4f57525a6935e34cd05c | [
"Apache-2.0"
] | 76 | 2018-10-27T16:59:36.000Z | 2022-03-30T17:40:39.000Z | TDEngine2/plugins/ImGUIContext/include/CImGUIContext.h | bnoazx005/TDEngine2 | 93ebfecf8af791ff5ecd4f57525a6935e34cd05c | [
"Apache-2.0"
] | 1 | 2019-07-29T02:02:08.000Z | 2019-07-29T02:02:08.000Z | /*!
/file CImGUIContext.h
/date 01.12.2019
/authors Kasimov Ildar
*/
#pragma once
#include <core/IImGUIContext.h>
#include <math/TVector2.h>
#include <math/TVector4.h>
#include <math/TMatrix4.h>
#include <utils/Color.h>
#include <stack>
struct ImGuiIO;
struct ImDrawData;
struct ImDrawList;
namespace TDEngine2
{
class IGraphicsContext;
class IVertexBuffer;
class IIndexBuffer;
class CRenderQueue;
class IVertexDeclaration;
enum class TMaterialInstanceId : U32;
/*!
\brief A factory function for creation objects of CImGUIContext's type
\param[in, out] pWindowSystem A pointer to IWindowSystem implementation
\param[in, out] pRenderer A pointer to IRenderer implementation
\param[in, out] pGraphicsObjectManager A pointer to IGraphicsObjectManager implementation
\param[in, out] pResourceManager A pointer to IResourceManager implementation
\param[in, out] pInputContext A pointer to IInputContext implementation
\param[out] result Contains RC_OK if everything went ok, or some other code, which describes an error
\return A pointer to CImGUIContext's implementation
*/
TDE2_API IImGUIContext* CreateImGUIContext(IWindowSystem* pWindowSystem, IRenderer* pRenderer, IGraphicsObjectManager* pGraphicsObjectManager,
IResourceManager* pResourceManager, IInputContext* pInputContext, E_RESULT_CODE& result);
/*!
class CImGUIContext
\brief The class is an implementation of an immediate mode GUI for editor's stuffs
*/
class CImGUIContext : public IImGUIContext
{
public:
friend TDE2_API IImGUIContext* CreateImGUIContext(IWindowSystem* pWindowSystem, IRenderer* pRenderer, IGraphicsObjectManager* pGraphicsObjectManager,
IResourceManager* pResourceManager, IInputContext* pInputContext, E_RESULT_CODE& result);
public:
typedef std::stack<ImDrawList*> TDrawListsStack;
typedef std::vector<TResourceId> TResourceHandlesArray;
public:
/*!
\brief The method initializes an internal state of a context
\param[in, out] pWindowSystem A pointer to IWindowSystem implementation
\param[in, out] pRenderer A pointer to IRenderer implementation
\param[in, out] pGraphicsObjectManager A pointer to IGraphicsObjectManager implementation
\param[in, out] pResourceManager A pointer to IResourceManager implementation
\param[in, out] pInputContext A pointer to IInputContext implementation
\return RC_OK if everything went ok, or some other code, which describes an error
*/
TDE2_API E_RESULT_CODE Init(IWindowSystem* pWindowSystem, IRenderer* pRenderer, IGraphicsObjectManager* pGraphicsObjectManager,
IResourceManager* pResourceManager, IInputContext* pInputContext) override;
/*!
\brief The method frees all memory occupied by the object
\return RC_OK if everything went ok, or some other code, which describes an error
*/
TDE2_API E_RESULT_CODE Free() override;
/*!
\brief The method configures the immediate GUI context for WIN32 platform
\param[in] pWindowSystem A pointer to CWin32WindowSystem implementation
\return RC_OK if everything went ok, or some other code, which describes an error
*/
TDE2_API E_RESULT_CODE ConfigureForWin32Platform(const CWin32WindowSystem* pWindowSystem);
/*!
\brief The method configures the immediate GUI context for UNIX platform
\param[in] pWindowSystem A pointer to CUnixWindowSystem implementation
\return RC_OK if everything went ok, or some other code, which describes an error
*/
TDE2_API E_RESULT_CODE ConfigureForUnixPlatform(const CUnixWindowSystem* pWindowSystem);
/*!
\brief The method begins to populate immediage GUI state. Any UI element should be drawn during
BeginFrame/EndFrame scope
\param[in] dt Time elapsed from last frame was rendered
*/
TDE2_API void BeginFrame(float dt) override;
/*!
\brief The method flushes current state and send all the data onto GPU to render it
*/
TDE2_API void EndFrame() override;
/*!
\brief The method returns a type of the subsystem
\return A type, which is represented with E_ENGINE_SUBSYSTEM_TYPE's value
*/
TDE2_API E_ENGINE_SUBSYSTEM_TYPE GetType() const override;
/*!
\brief The method creates a label within current active window
\param[in] text A string which should be rendered onto the screen
*/
TDE2_API void Label(const std::string& text) override;
/*!
\brief The method creates a label within current active window
\param[in] text A string which should be rendered onto the screen
\param[in] color Text's color
*/
TDE2_API void Label(const std::string& text, const TColor32F& color) override;
/*!
\brief The method creates a label within current active window
\param[in] text A string which should be rendered onto the screen
\param[in] pos A position of a label
\param[in] color Text's color
*/
TDE2_API void Label(const std::string& text, const TVector2& pos, const TColor32F& color) override;
/*!
\brief The method creates a button with a given size and label
\param[in] text A text that will be displayed on top of the button
\param[in] sizes A vector that defines width and height of the button
\param[in] onClicked A callback that's called when a user clicks over the menu item
\param[in] makeInvisible If true the button won't be displayed, but still processes all clicks over it
\param[in] allowOverlapping If true the button will allow to overlap itself by other input elements
\return The method returns true if the button was pressed, false in other cases
*/
TDE2_API bool Button(const std::string& text, const TVector2& sizes, const std::function<void()>& onClicked = {}, bool makeInvisible = false, bool allowOverlapping = false) override;
/*!
\brief The method creates a check box
\param[in] text A text that will be displayed on top of the check box
\param[in, out] isSelected A flag that is set up to true if the check box is selected
\return
*/
TDE2_API bool Checkbox(const std::string& text, bool& isSelected) override;
/*!
\brief The method creates a slider for integers. If a value's changed onValueChanged
callback is called
\param[in] text A text that will be displayed with the slider
\param[in, out] value The current value for the slider
\param[in] minValue A minimal value that can be assigned with this slider
\param[in] maxValue A maximal value that can be assigned with this slider
\param[in] onValueChanged A callback that is called when the value of the slider has changed
*/
TDE2_API void IntSlider(const std::string& text, I32& value, I32 minValue, I32 maxValue,
const std::function<void()>& onValueChanged = {}) override;
/*!
\brief The method creates a slider for floating point values. If a value's changed onValueChanged
callback is called
\param[in] text A text that will be displayed with the slider
\param[in, out] value The current value for the slider
\param[in] minValue A minimal value that can be assigned with this slider
\param[in] maxValue A maximal value that can be assigned with this slider
\param[in] onValueChanged A callback that is called when the value of the slider has changed
*/
TDE2_API void FloatSlider(const std::string& text, F32& value, F32 minValue, F32 maxValue,
const std::function<void()>& onValueChanged = {}) override;
/*!
\brief The method creates a float field which is a text box specialized for float single precision numbers
\param[in] text A text that will be displayed with this text box
\param[in] value The current and output value for the text box
\param[in] onValueChanged A callback that is called when the value of the field has changed
*/
TDE2_API void FloatField(const std::string& text, F32& value, const std::function<void()>& onValueChanged = {}) override;
/*!
\brief The method creates a integer field which is a text box specialized for integral numbers
\param[in] text A text that will be displayed with this text box
\param[in] value The current and output value for the text box
\param[in] onValueChanged A callback that is called when the value of the field has changed
*/
TDE2_API void IntField(const std::string& text, I32& value, const std::function<void()>& onValueChanged = {}) override;
/*!
\brief The method creates a text box
\param[in] text A text that will be displayed with this text box
\param[in] value The current and output value for the text box
\param[in] onValueChanged A callback that is called when the value of the field has changed
*/
TDE2_API void TextField(const std::string& text, std::string& value, const std::function<void()>& onValueChanged = {}) override;
/*!
\brief The method creates a field for TVector2 type
\param[in] text A text that will be displayed with the field
\param[in, out] value A value of TVector2 type
\param[in] onValueChanged A callback that is called when the value of the slider has changed
*/
TDE2_API void Vector2Field(const std::string& text, TVector2& value, const std::function<void()>& onValueChanged = {}) override;
/*!
\brief The method creates a field for TVector3 type
\param[in] text A text that will be displayed with the field
\param[in, out] value A value of TVector3 type
\param[in] onValueChanged A callback that is called when the value of the slider has changed
*/
TDE2_API void Vector3Field(const std::string& text, TVector3& value, const std::function<void()>& onValueChanged = {}) override;
/*!
\brief The method creates a field for TVector4 type
\param[in] text A text that will be displayed with the field
\param[in, out] value A value of TVector4 type
\param[in] onValueChanged A callback that is called when the value of the slider has changed
*/
TDE2_API void Vector4Field(const std::string& text, TVector4& value, const std::function<void()>& onValueChanged = {}) override;
/*!
\brief The method displays a color picker for common RGBA color type
\param[in] text A text that will be displayed with the field
\param[in, out] color A value of TColor32F type
\param[in] onValueChanged A callback that is called when the value of the slider has changed
*/
TDE2_API void ColorPickerField(const std::string& text, TColor32F& color, const std::function<void()>& onValueChanged = {}) override;
TDE2_API void GradientColorPicker(const std::string& text, CGradientColor& color, const std::function<void()>& onValueChanged = {}) override;
/*!
\brief The method creates a main menu on top of the screen
\param[in] onDrawCallback A callback within which a user defines sub-menus of the menu
*/
TDE2_API void DisplayMainMenu(const std::function<void(IImGUIContext&)>& onDrawCallback) override;
/*!
\brief The method creates a context menu
\param[in] onDrawCallback A callback within which a user defines sub-menus of the menu
*/
TDE2_API void DisplayContextMenu(const std::string& id, const std::function<void(IImGUIContext&)>& onDrawCallback) override;
/*!
\brief The method creates a sub-menu
\param[in] name A name of the sub-menu
\param[in] onDrawCallback A callback within which a user defines menu items
*/
TDE2_API void MenuGroup(const std::string& name, const std::function<void(IImGUIContext&)>& onDrawCallback) override;
/*!
\brief The method creates a new menu item, should be called within MenuGroup's onDrawCallback
\param[in] name A name of the menu item
\param[in] shortcut A shortcut for keyboard to activate the menu item
\param[in] onClicked A callback that's called when a user clicks over the menu item
\return The method returns true when a user clicks over the menu item
*/
TDE2_API bool MenuItem(const std::string& name, const std::string& shortcut, const std::function<void()>& onClicked = {}) override;
/*!
\brief The method creates a histogram
\param[in] name A name of the histogram
\param[in] values An array of samples that should be drawn
\param[in] minScale Minimal scale's value
\param[in] maxScale Maximum scale's value
\param[in] sizes A sizes of the displayed histogram
\param[in] overlayedText Text that will be displayed over the histogram's samples
*/
TDE2_API void Histogram(const std::string& name, const std::vector<F32>& values, F32 minScale, F32 maxScale,
const TVector2& sizes = ZeroVector2, const std::string& overlayedText = "") override;
/*!
\brief The method creates a histogram
\param[in] name A name of the histogram
\param[in] pValues An array of samples that should be drawn
\param[in] valuesCount A size of the array
\param[in] minScale Minimal scale's value
\param[in] maxScale Maximum scale's value
\param[in] sizes A sizes of the displayed histogram
\param[in] overlayedText Text that will be displayed over the histogram's samples
*/
TDE2_API void Histogram(const std::string& name, const F32* pValues, U32 valuesCount, F32 minScale, F32 maxScale,
const TVector2& sizes = ZeroVector2, const std::string& overlayedText = "") override;
/*!
\brief The method draws a line within the current active window
\param[in] start An initial position of the line
\param[in] end Finish position of the line
\param[in] color The line's color
\param[in] thickness A line's thickness
*/
TDE2_API void DrawLine(const TVector2& start, const TVector2& end, const TColor32F& color, F32 thickness = 1.0f) override;
/*!
\brief The method draws a cubic Bezier line
*/
TDE2_API void DrawCubicBezier(const TVector2& p0, const TVector2& t0, const TVector2& p1, const TVector2& t1, const TColor32F& color, F32 thickness = 1.0f) override;
/*!
\brief The method draws a rectangle within the current active window
\param[in] rect A rectangle's parameters
\param[in] color The rectangle's color
*/
TDE2_API void DrawRect(const TRectF32& rect, const TColor32F& color, bool isFilled = true, F32 thickness = 1.0f) override;
TDE2_API void DrawCircle(const TVector2& center, F32 radius, bool isFilled, const TColor32F& color, F32 thickness = 1.0f) override;
TDE2_API void DrawTriangle(const TVector2& p0, const TVector2& p1, const TVector2& p2, const TColor32F& color, bool isFilled = false, F32 thickness = 1.0f) override;
/*!
\brief The method draws given text
*/
TDE2_API void DrawText(const TVector2& pos, const TColor32F& color, const std::string& text) override;
/*!
\brief The method draws manipulators for the transform based on ImGuizmo library
\return The method returns true when the gizmo is actually being moving or selected
*/
TDE2_API bool DrawGizmo(E_GIZMO_TYPE type, const TMatrix4& view, const TMatrix4& proj, const TMatrix4& transform,
const std::function<void(const TVector3&, const TQuaternion&, const TVector3)>& onUpdate) override;
/*!
\brief The method draws a plot's grid with input handling, scaling, moving, etc
*/
TDE2_API void DrawPlotGrid(const std::string& name, const TPlotGridParams& params, const std::function<void(const TVector2&)>& onGridCallback = {}) override;
/*!
\brief The method displays a combo box with a set of items
\param[in] label A caption of the combo box
\param[in] currSelectedItem An index of the item that is selected by default
\param[in] items A list of available items
\return The method returns an index of the selected item
*/
TDE2_API I32 Popup(const std::string& label, I32 currSelectedItem, const std::vector<std::string>& items) override;
/*!
\brief The method displays an image with the given parameters set
\param[in] textureHandle A pointer to resource handler that corresponds to texture that should be displayed
\param[in] sizes A sizes of displayed image
\param[in] uvRect A uv coordinates of displayed texture
*/
TDE2_API void Image(TResourceId textureHandle, const TVector2& sizes, const TRectF32& uvRect = { 0.0f, 0.0f, 1.0f, 1.0f }) override;
/*!
\brief The method displays selectable label item
\param[in] id A label of an item
\param[in] isSelected A flag determines whether or not the current node is highlighted
\param[in] shouldClosePopup A flag defines whether the selectable's input events cause closing of the pop up window
\return Returns true if the current item was selected, false in other cases
*/
TDE2_API bool SelectableItem(const std::string& id, bool isSelected, bool shouldClosePopup) override;
/*!
\brief The method display tree's element. Always should be called in pair with EndTreeNode at end
\param[in] id A label of a node
\param[in] isSelected A flag determines whether or not the current node is highlighted
\return A tuple the first argument is opened/hidden state of a node, the second is whether selected or not the node
*/
TDE2_API std::tuple<bool, bool> BeginTreeNode(const std::string& id, bool isSelected = false) override;
/*!
\brief The method should be called after BeginTreeNode
*/
TDE2_API void EndTreeNode() override;
/*!
\brief The method displays header which looks same as BeginTreeNode.
\param[in] id A label that will be displayed
\param[in] isOpened The flag defines whether or not the group is unwinded or not
\param[in] isSelected The flag defines whether the header be highlighted or not
\param[in] itemClicked The callback is called when a user clicks over the header
\param[in] contentAction You can invoke any ImGUIContext command there which should be displayed when the header is unwinded
\return The method return true if it was unwinded, false in other cases
*/
TDE2_API bool CollapsingHeader(const std::string& id, bool isOpened, bool isSelected = false,
const std::function<void()>& itemClicked = nullptr,
const std::function<void()>& contentAction = nullptr) override;
/*!
\brief The method creates a new window on the screen. Every call after this one
will be related with this window
\param[in] name A window's name
\param[in, out] isOpened A flag that determines whether the window is shown or not
\param[in] params A set of additonal parameters which can be applied to the window
\return The method returns false if the window is collapsed or not visible
*/
TDE2_API bool BeginWindow(const std::string& name, bool& isOpened, const TWindowParams& params) override;
/*!
\brief The method finishes populating of current window
*/
TDE2_API void EndWindow() override;
/*!
\brief The method starts horizontal group's layout. All elements that are
rendered between BeginHorizontal/EndHorizontal will be placed in the following
way
EL1 ... ELN
instead of
EL1
...
ELN
*/
TDE2_API void BeginHorizontal() override;
/*!
\brief The method closes a horizontal group
*/
TDE2_API void EndHorizontal() override;
/*!
\brief The method creates child window's region within the current one
\return The method returns true if the window is shown
*/
TDE2_API bool BeginChildWindow(const std::string& name, const TVector2& sizes) override;
/*!
\brief The method finalizes current child window
*/
TDE2_API void EndChildWindow() override;
TDE2_API void ShowModalWindow(const std::string& name) override;
TDE2_API void CloseCurrentModalWindow() override;
TDE2_API bool BeginModalWindow(const std::string& name, bool isNonBlocking = false) override;
TDE2_API void EndModalWindow() override;
TDE2_API void Tooltip(const std::string& message) override;
TDE2_API void VerticalSeparator(F32 initialLeftColumnWidth, const std::function<void(F32)>& leftRegionCallback, const std::function<void(F32)>& rightRegionCallback) override;
/*!
\brief The method moves current position of the cursor to given point
*/
TDE2_API void SetCursorScreenPos(const TVector2& pos) override;
/*!
\brief The method changes width of items that are called within action callbacks
*/
TDE2_API void SetItemWidth(F32 width, const std::function<void()>& action = {}) override;
TDE2_API void DisplayIDGroup(I32 id, const std::function<void()>& idGroupCallback = {}) override;
/*!
\brief The method provides implementation of drag & drop source
\param[in] action A callback in which all the stuff for register should be executed
*/
TDE2_API void RegisterDragAndDropSource(const std::function<void()>& action = nullptr) override;
/*!
\brief The method provides implementation of drag & drop target
\param[in] action A callback in which all the stuff for register should be executed
*/
TDE2_API void RegisterDragAndDropTarget(const std::function<void()>& action = nullptr) override;
/*!
\brief The method returns a width of current active window
\return The method returns a width of current active window
*/
TDE2_API F32 GetWindowWidth() const override;
/*!
\brief The method returns a height of current active window
\return The method returns a height of current active window
*/
TDE2_API F32 GetWindowHeight() const override;
/*!
\brief The method returns cursor position in a viewport space. The method is useful when
you work with DrawX methods
\return The method returns cursor position in a viewport space
*/
TDE2_API TVector2 GetCursorScreenPos() const override;
/*!
\brief The method returns sizes which a given text string occupies
\param[in] text A text string
\return The static function returns sizes which a given text string occupies
*/
TDE2_API TVector2 GetTextSizes(const std::string& text) const override;
TDE2_API bool IsItemActive() const override;
/*!
\return The method returns true when the cursor is over some ImGUI element
*/
TDE2_API bool IsMouseOverUI() const override;
TDE2_API bool IsItemHovered() const override;
TDE2_API bool IsMouseDoubleClicked(U8 buttonId) const override;
TDE2_API bool IsMouseClicked(U8 buttonId) const override;
TDE2_API bool IsMouseDragging(U8 buttonId) const override;
TDE2_API bool IsMouseReleased(U8 buttonId) const override;
TDE2_API TVector2 GetMouseDragDelta(U8 buttonId) const override;
TDE2_API TVector2 GetMousePosition() const override;
TDE2_API TVector2 GetScrollPosition() const override;
protected:
DECLARE_INTERFACE_IMPL_PROTECTED_MEMBERS(CImGUIContext)
TDE2_API E_RESULT_CODE _initInternalImGUIContext(ImGuiIO& io);
TDE2_API void _updateInputState(ImGuiIO& io, IInputContext* pInputContext);
TDE2_API E_RESULT_CODE _initGraphicsResources(ImGuiIO& io, IGraphicsContext* pGraphicsContext, IGraphicsObjectManager* pGraphicsManager,
IResourceManager* pResourceManager);
TDE2_API E_RESULT_CODE _initSystemFonts(ImGuiIO& io, IResourceManager* pResourceManager, IGraphicsObjectManager* pGraphicsManager);
TDE2_API void _engineInternalRender(ImDrawData* pImGUIData, CRenderQueue* pRenderQueue);
TDE2_API void _initInputMappings(ImGuiIO& io);
TDE2_API void _prepareLayout();
TDE2_API ImDrawList* _getCurrActiveDrawList() const;
TDE2_API void _setDragAndDropData(const std::string& id, const void* pData, U32 size) override;
TDE2_API const void* _getDragAndDropData(const std::string& id) const override;
TDE2_API void _drawGradientColorPreview(const std::string& text, CGradientColor& color, const TVector2& sizes);
TDE2_API void _drawGradientColorEditor(CGradientColor& color, const TVector2& windowSizes);
protected:
std::atomic_bool mIsInitialized;
IWindowSystem* mpWindowSystem;
IGraphicsContext* mpGraphicsContext;
IGraphicsObjectManager* mpGraphicsObjectManager;
IResourceManager* mpResourceManager;
IInputContext* mpInputContext;
ImGuiIO* mpIOContext;
TResourceId mFontTextureHandle;
TResourceHandlesArray mUsedResourcesRegistry;
TResourceId mDefaultEditorMaterialHandle;
IVertexBuffer* mpVertexBuffer;
IIndexBuffer* mpIndexBuffer;
CRenderQueue* mpEditorUIRenderQueue;
IVertexDeclaration* mpEditorUIVertexDeclaration;
bool mIsHorizontalGroupEnabled = false;
TDrawListsStack mpDrawListsContext;
std::unordered_map<uintptr_t, TMaterialInstanceId> mUsingMaterials;
// \todo Refactor this later
bool mIsGradientColorEditorOpened = false;
};
} | 36.28863 | 185 | 0.729252 | [
"render",
"object",
"vector",
"transform"
] |
83533f1d5832f18c8cca209983b23cd32c45d0e0 | 2,594 | h | C | cpp/CF++/include/CF++/CFPP-PropertyListType.h | vzaccaria/teasy-2.0 | a0ec0e020fb0b0517e4a250e2c3cae4494cef40a | [
"MIT"
] | 24 | 2016-04-13T10:40:16.000Z | 2016-12-20T04:19:10.000Z | cpp/CF++/include/CF++/CFPP-PropertyListType.h | vzaccaria/teasy-2.0 | a0ec0e020fb0b0517e4a250e2c3cae4494cef40a | [
"MIT"
] | null | null | null | cpp/CF++/include/CF++/CFPP-PropertyListType.h | vzaccaria/teasy-2.0 | a0ec0e020fb0b0517e4a250e2c3cae4494cef40a | [
"MIT"
] | null | null | null | /*******************************************************************************
* Copyright (c) 2014, Jean-David Gadina - www.xs-labs.com / www.digidna.net
* Distributed under the Boost Software License, Version 1.0.
*
* Boost Software License - Version 1.0 - August 17th, 2003
*
* Permission is hereby granted, free of charge, to any person or organization
* obtaining a copy of the software and accompanying documentation covered by
* this license (the "Software") to use, reproduce, display, distribute,
* execute, and transmit the Software, and to prepare derivative works of the
* Software, and to permit third-parties to whom the Software is furnished to
* do so, all subject to the following:
*
* The copyright notices in the Software and this entire statement, including
* the above license grant, this restriction and the following disclaimer,
* must be included in all copies of the Software, in whole or in part, and
* all derivative works of the Software, unless such copies or derivative
* works are solely in the form of machine-executable object code generated by
* a source language processor.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
* SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
* FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
******************************************************************************/
/*!
* @header CFPP-PropertyListType.h
* @copyright (c) 2014 - Jean-David Gadina - www.xs-labs.com / www.digidna.net
* @abstract CoreFoundation++ base class for property list compatible types
*/
#ifndef CFPP_PROPERTY_LIST_TYPE_H
#define CFPP_PROPERTY_LIST_TYPE_H
namespace CF
{
class Data;
typedef enum
{
PropertyListFormatXML = 0x00,
PropertyListFormatBinary = 0x01
}
PropertyListFormat;
template < class T >
class CFPP_EXPORT PropertyListType: public Type
{
public:
static T FromPropertyList( std::string path );
bool ToPropertyList( std::string path, PropertyListFormat format = PropertyListFormatXML ) const;
Data ToPropertyList( PropertyListFormat format = PropertyListFormatXML ) const;
};
}
#endif /* CFPP_PROPERTY_LIST_TYPE_H */
| 41.83871 | 109 | 0.680802 | [
"object"
] |
835c24e7befb88e079314401371edb6e35022714 | 1,597 | h | C | test/unittests/heap/cppgc/tests.h | hhggyy9988/forkgoogle_v8_84.0.4147.139 | 019de2dda2d87c30a90b9f235279ae9c7b3ddc4c | [
"BSD-3-Clause"
] | null | null | null | test/unittests/heap/cppgc/tests.h | hhggyy9988/forkgoogle_v8_84.0.4147.139 | 019de2dda2d87c30a90b9f235279ae9c7b3ddc4c | [
"BSD-3-Clause"
] | 5 | 2021-02-13T18:06:42.000Z | 2021-02-13T18:06:44.000Z | test/unittests/heap/cppgc/tests.h | hhggyy9988/forkgoogle_v8_84.0.4147.139 | 019de2dda2d87c30a90b9f235279ae9c7b3ddc4c | [
"BSD-3-Clause"
] | 3 | 2019-03-25T23:01:31.000Z | 2020-05-19T01:17:27.000Z | // Copyright 2020 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef V8_UNITTESTS_HEAP_CPPGC_TESTS_H_
#define V8_UNITTESTS_HEAP_CPPGC_TESTS_H_
#include "include/cppgc/heap.h"
#include "include/cppgc/platform.h"
#include "src/base/page-allocator.h"
#include "src/heap/cppgc/heap.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace cppgc {
namespace internal {
namespace testing {
class TestWithPlatform : public ::testing::Test {
protected:
static void SetUpTestSuite();
static void TearDownTestSuite();
private:
static std::unique_ptr<cppgc::PageAllocator> page_allocator_;
};
class TestWithHeap : public TestWithPlatform {
protected:
TestWithHeap();
void PreciseGC() {
heap_->ForceGarbageCollectionSlow(
"TestWithHeap", "Testing", Heap::GCConfig::StackState::kNoHeapPointers);
}
cppgc::Heap* GetHeap() const { return heap_.get(); }
private:
std::unique_ptr<cppgc::Heap> heap_;
};
// Restrictive test fixture that supports allocation but will make sure no
// garbage collection is triggered. This is useful for writing idiomatic
// tests where object are allocated on the managed heap while still avoiding
// far reaching test consquences of full garbage collection calls.
class TestSupportingAllocationOnly : public TestWithHeap {
protected:
TestSupportingAllocationOnly();
private:
Heap::NoGCScope no_gc_scope_;
};
} // namespace testing
} // namespace internal
} // namespace cppgc
#endif // V8_UNITTESTS_HEAP_CPPGC_TESTS_H_
| 27.067797 | 80 | 0.761428 | [
"object"
] |
835c87e727906be9ae21e6e960fe54ec2ddace1a | 6,041 | c | C | nitan/quest11/jiuyin/testjob.c | cantona/NT6 | 073f4d491b3cfe6bfbe02fbad12db8983c1b9201 | [
"MIT"
] | 1 | 2019-03-27T07:25:16.000Z | 2019-03-27T07:25:16.000Z | nitan/quest11/jiuyin/testjob.c | cantona/NT6 | 073f4d491b3cfe6bfbe02fbad12db8983c1b9201 | [
"MIT"
] | null | null | null | nitan/quest11/jiuyin/testjob.c | cantona/NT6 | 073f4d491b3cfe6bfbe02fbad12db8983c1b9201 | [
"MIT"
] | null | null | null | // houdian.c 後殿
inherit ROOM;
void create()
{
set("short", "後殿");
set("long",@long
這是峨嵋山華藏庵的後殿。是峨嵋派掌門人傳教弟子功夫的地方。這裏供
有一尊普賢菩薩像。兩旁靠牆放着幾張太師椅,地上放着幾個蒲團。掌門人正
在向幾個女弟子傳授武功。
long);
set("exits",([
"north" : __DIR__"daxiong",
]));
set("objects",([
// CLASS_D("emei") + "/mie-jue" : 1,
]));
// create_door("north", "小門", "south", DOOR_CLOSED);
setup();
}
void reset()
{
object here=this_object();
if (here->query("fighting") != 1) {
if (here->query("count") != 1)
here->set("count", random(4) );
if ((int)here->query("count") == 1){
remove_call_out("test");
call_out("test", 5, here);
}
}
::reset();
}
int sort(object obj1, object obj2)
{
int temp1,temp2;
temp1 = obj1->query("em_job1");
temp2 = obj2->query("em_job1");
if (temp1 > temp2) return 1;
else if (temp1 < temp2) return -1;
else return 0;
}
void test(object here)
{
string s;
object ob, ling, where;
object *list, *selected, *sorted;
int num0, num1, num2, num3;
int i, cnt = 0;
string* tgt= ({ "/d/emei/houshanty", "/d/emei/baoguosi", "/d/emei/sheshenya",
"/d/emei/zhongfengsi", "/d/emei/qianfoan", "/d/emei/chunyangdian",
"/d/emei/guanyinqiao", "/d/emei/jietuopo", "/d/emei/xianfengsi" });
string* tgtname= ({ "炭窯", "報國寺", "捨身崖", "中峯寺", "千佛庵",
"純陽殿", "觀音橋", "解脱坡", "仙峯寺"});
num0 = -1;
num2 = -1;
num3 = -1;
num1 = -1;
num0 = random(sizeof(tgt));
num1 = random(sizeof(tgt));
while (num0 == num1) {
num1 = random(sizeof(tgt));
}
num2 = random(sizeof(tgt));
while (num0 == num2 || num1 == num2) {
num2 = random(sizeof(tgt));
}
num3 = random(sizeof(tgt));
while (num0 == num3 || num1 == num3 || num2 == num3) {
num3 = random(sizeof(tgt));
}
if (!(ob = present("miejue shitai", here))) return;
list = filter_array(users(), (: $1->query_temp("emhsjob"):));
sorted = sort_array(list, (: sort :));
i = sizeof( sorted );
while( i-- ) {
if (!environment(list[i]) ) continue;
if (wizardp(list[i]) || list[i]->query("env/invisibility")) continue;
if ( !interactive(list[i]) ) continue;
if (query_idle(list[i]) > 2000) continue;
cnt++;
list[i]->set_temp("selected", 1);
}
if ( cnt < 2 ) {
here->set("count", random(2));
return;
}
selected = filter_array(list, (: $1->query_temp("selected") == 1 :));
i = 1;
if (!(where = find_object("fang ping")))
ling = new("/d/emei/npc/fang");
else ling = present("fang ping", where);
ling->move("/d/city/yltw");
ling->set("pl", selected[0]);
s = selected[0]->query("name")+"趕緊到揚州月老亭把方老前輩請來助陣,";
while( i < 5 ) { ling->set("pl"+i, ling); i++; }
ling->set("pl1",selected[1]);
ling->set("st1",tgt[num0]);
s = s + selected[1]->query("name")+"守住"+tgtname[num0]+",";
if( cnt > 2 ) {
ling->set("pl2",selected[2]);
ling->set("st2",tgt[num1]);
s = s + selected[2]->query("name")+"守住"+tgtname[num1]+",";
}
if( cnt > 3 ) {
ling->set("pl3",selected[3]);
ling->set("st3",tgt[num2]);
s = s + selected[3]->query("name")+"守住"+tgtname[num2]+",";
}
if( cnt > 4 ) {
ling->set("pl4",selected[4]);
ling->set("st4",tgt[num3]);
s = s + selected[4]->query("name")+"守住"+tgtname[num3]+",";
}
CHANNEL_D->do_channel(ob, "chat", "元兵攻山," + s + "等待援兵,殺退敵人!\n");
ling->apply_condition("em_job1", 30);
ling->apply_condition("job_busy", 30);
here->set("fighting", 1);
return;
}
void init()
{
add_action("do_swear", ({ "qishi", "fashi" }));
add_action("do_huzhuo", ({ "huzhuo" }));
add_action("do_nod", ({ "nod" }));
}
int do_swear()
{
object ob, me = this_player();
object where = environment(me);
if( !(ob = present("miejue shitai", where) ) )
return 0;
if( me->query_temp("jiuyin140") < 5 )
return 0;
if( me->query("gender") == "女性" )
message_vision("$N説道:小女子" + me->query("name") + "對天盟誓,日後我若對魔教教主張無忌這淫徒心存愛慕,\n"+
"倘若和他結成夫婦,我親身父母死在地下,屍骨不得安穩;我師父滅絕師太必成厲鬼,\n"+
"令我一生日夜不安,我若和他生下兒女,男子代代為奴,女子世世為娼。\n", me);
else
tell_room(where, me->query("name")+"説道:不才" + me->query("name") + "一定要實現師太的兩大願望,逐走韃子,\n"+
"光復漢家山河;率領峨嵋派領袖羣倫,蓋過少林、武當,成為中原武林中的第一門派。\n"+
"有違誓言者天打雷劈,萬劍穿身,死無葬身之地。\n");
tell_room(where, "滅絕師太臉上露出一絲笑容。\n");
me->set_temp("jiuyin140", 6);
tell_room(where, "滅絕師太説道:黃女俠在鑄刀鑄劍之前,和郭大俠兩人窮一月心力,繕寫了兵法和武功的\n"+
"精要,分別藏在刀劍之中。屠龍刀中藏的乃是兵法,此刀名為‘屠龍’,意為日後有人得\n"+
"到刀中兵書,當可驅除韃子,殺了韃子皇帝。倚天劍中藏的則是武學祕笈,其中最為寶貴\n"+
"的,乃是一部‘九陰真經’,一部‘降龍十八掌掌法精義’,盼望後人習得劍中武功,替\n"+
"天行道,為民除害。\n");
tell_room(where, "滅絕師太説道:你取到屠龍刀和倚天劍後,來到我這裏,一手執刀,一手持劍,運起內力,\n"+
"以刀劍互斫(huzhuo),寶刀寶劍便即同時斷折,即可取出藏在刀身和劍刃中的祕笈。這是\n"+
"取出祕笈的唯一法門,那寶刀寶劍可也從此毀了。你記住了麼?\n");
return 1;
}
int do_nod()
{
object me=this_player();
if( me->query_temp("jiuyin140") != 6 ) return 0;
me->set_temp("jiuyin140", 7);
message_vision("$N只聽得渾身熱血沸騰,一股浩然的正氣充滿胸襟。\n", me);
me->add("shen", me->query("combat_exp")/3);
return 0;
}
int do_huzhuo()
{
object ob, me=this_player();
object ob1, ob2, where = environment(me);
if( me->query_temp("jiuyin140") < 6 ) return 0;
if( !(ob1 = present("yitian jian", me)) ) return 0;
if( !(ob2 = present("tulong dao", me)) ) return 0;
if( me->query_temp("jiuyin140") != 7 )
return notify_fail("你答應了滅絕師太的要求了嗎?\n");
if ( !me->query("jiuyin/emeipass") || !me->query("jiuyin/emeijump"))
return notify_fail("嘿嘿!想作弊麼?\n");
if( !(ob = present("miejue shitai", where) ) )
return notify_fail("滅絕師太不在這裏,你最好先別這樣做。\n");
message_vision("只見$N一手執刀,一手持劍,運起內力,刀劍互斫。\n"+
"只聽見‘哧’的一聲輕響,這兩把舉世無雙的屠龍刀和倚天劍就此消失了。\n", me);
destruct(ob1);
destruct(ob2);
message_vision("滅絕師太從斷刀斷劍中取出了幾張帛卷,看了幾眼,拿出一張帛卷交給了$N。\n", me);
if( me->query_skill("xianglong-zhang", 1) > 0)
tell_room(where, "滅絕師太説道:降龍十八掌你已經學了,這張九陰白骨爪精解你就拿去學吧。\n");
else
tell_room(where, "滅絕師太説道:你的武學路子與降龍十八掌的剛陽勁力不符,這張九陰白骨爪精解你就拿去學吧。\n");
tell_room(where, "滅絕師太説道:待我覓得一個心地仁善、赤誠為國的志士,將兵書傳授於他,要他立誓驅除胡虜。\n");
tell_room(where, "滅絕師太又説道:我看這還是我先保管,你如果需要隨時來跟我要吧。\n");
me->set("jiuyin/emei",1);
log_file("quest/jiuyin",sprintf("%-18s在娥眉九陰部分失敗%s次後成功從滅絕師太處得到娥眉九陰。\n",
me->name(1)+"("+capitalize(getuid(me))+")",chinese_number(me->query("jiuyin/emeifail"))), me);
me->delete_temp("jiuyin140");
return 1;
}
| 30.054726 | 96 | 0.615958 | [
"object"
] |
835d8c7aaa057dd66bd01b1e6d160ed74218a65d | 3,322 | h | C | Tools/LSWindows/Src/Tab/LSWTab.h | L-Spiro/MhsX | 9cc71fbbac93ba54a01839db129cd9b47a68f29e | [
"BSD-2-Clause"
] | 19 | 2016-09-07T18:22:09.000Z | 2022-03-25T23:05:39.000Z | Tools/LSWindows/Src/Tab/LSWTab.h | L-Spiro/MhsX | 9cc71fbbac93ba54a01839db129cd9b47a68f29e | [
"BSD-2-Clause"
] | 1 | 2021-09-30T14:24:54.000Z | 2021-11-13T14:58:02.000Z | Tools/LSWindows/Src/Tab/LSWTab.h | L-Spiro/MhsX | 9cc71fbbac93ba54a01839db129cd9b47a68f29e | [
"BSD-2-Clause"
] | 5 | 2018-04-10T16:52:25.000Z | 2021-05-11T02:40:17.000Z | #pragma once
#include "../LSWWin.h"
#include "../Widget/LSWWidget.h"
namespace lsw {
class CTab : public CWidget {
public :
CTab( const LSW_WIDGET_LAYOUT &_wlLayout, CWidget * _pwParent, bool _bCreateWidget = true, HMENU _hMenu = NULL, uint64_t _ui64Data = 0 );
~CTab();
// == Functions.
// Virtual client rectangle. Can be used for things that need to be adjusted based on whether or not status bars, toolbars, etc. are present.
virtual const LSW_RECT VirtualClientRect( const CWidget * pwChild ) const;
// Calculates a tab control's display area given a window rectangle, or calculates the window rectangle that would correspond to a specified display area.
void AdjustRect( BOOL _bLarger, RECT * prRect ) const;
// Inserts a new tab in a tab control. Returns the index of the new tab if successful, or -1 otherwise.
int InsertItem( int _iItem, LPTCITEMW _piItem, CWidget * _pwWidget );
// Inserts a new tab in a tab control. Returns the index of the new tab if successful, or -1 otherwise.
int InsertItem( int _iItem, LPTCITEMA _piItem, CWidget * _pwWidget );
// Removes an item from a tab control.
void DeleteItem( int _iItem, bool _bDestroyChildWindow = true );
// Retrieves the number of tabs in the tab control.
int GetItemCount() const;
// Selects a tab in a tab control. Returns the index of the previously selected tab if successful, or -1 otherwise.
int SetCurSel( int _iItem );
// Determines the currently selected tab in a tab control.
int GetCurSel() const;
// Determines which tab, if any, is at a specified screen position. Returns the index of the tab, or -1 if no tab is at the specified position.
int HitTest( LPTCHITTESTINFO _lphtiInfo ) const;
// Gets the rectangle of a given tab.
LSW_RECT GetItemRect( INT _iTab ) const;
// Gets the width of the text in a given tab.
int GetTabTextWidth( INT _iTab ) const;
// Gets the width of the longest text in any tab.
int GetLongestTextWidth() const;
// Sets the rectangle of a given tab.
DWORD SetItemSize( int _iW, int _iH );
// Gets item text.
std::string GetItemTextA( int _iItem ) const;
// Gets item text.
std::wstring GetItemTextW( int _iItem ) const;
// Setting the HWND after the control has been created.
virtual void InitControl( HWND _hWnd );
// Gets the original tab proc.
WNDPROC OriginalProc() const { return reinterpret_cast<WNDPROC>(m_lpOriginProc); }
// Determines the type of control this is.
virtual uint32_t WidgetType() const { return LSW_LT_TAB; }
// Returns true if this is a CTab class.
virtual bool IsTab() const { return true; }
protected :
// == Types.
// A tab.
struct LSW_TAB {
CWidget * pwWidget;
size_t sTextLen;
};
// == Members.
// Data for each tab.
std::vector<LSW_TAB> m_vTabs;
// Original tab function.
LONG_PTR m_lpOriginProc;
// == Functions.
// Determines the close rectangle.
static LSW_RECT GetCloseRect( const LSW_RECT &_rTabRect, bool _bHasFocus );
// The custom tab message handler.
static LRESULT CALLBACK CustomTabProc( HWND _hWnd, UINT _uMsg, WPARAM _wParam, LPARAM _lParam );
};
} // namespace lsw
| 33.22 | 156 | 0.680313 | [
"vector"
] |
835f44aca879957bb7e97dcfa30b6a632c5d181e | 3,044 | h | C | Gems/AWSMetrics/Code/Include/Private/ClientConfiguration.h | aaarsene/o3de | 37e3b0226958974defd14dd6d808e8557dcd7345 | [
"Apache-2.0",
"MIT"
] | 1 | 2021-09-13T00:01:12.000Z | 2021-09-13T00:01:12.000Z | Gems/AWSMetrics/Code/Include/Private/ClientConfiguration.h | aaarsene/o3de | 37e3b0226958974defd14dd6d808e8557dcd7345 | [
"Apache-2.0",
"MIT"
] | null | null | null | Gems/AWSMetrics/Code/Include/Private/ClientConfiguration.h | aaarsene/o3de | 37e3b0226958974defd14dd6d808e8557dcd7345 | [
"Apache-2.0",
"MIT"
] | 1 | 2021-07-20T11:07:25.000Z | 2021-07-20T11:07:25.000Z | /*
* Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#pragma once
#include <AzCore/std/string/string.h>
namespace AWSMetrics
{
constexpr char AwsMetricsLocalFileDir[] = "@user@/AWSMetrics/";
constexpr char AwsMetricsLocalFileName[] = "metrics.json";
//! ClientConfiguration is used to retrieve and store client settings from a local configuration JSON file.
class ClientConfiguration
{
public:
static constexpr const char AWSMetricsMaxQueueSizeInMbKey[] = "/Gems/AWSMetrics/MaxQueueSizeInMb";
static constexpr const char AWSMetricsQueueFlushPeriodInSecondsKey[] = "/Gems/AWSMetrics/QueueFlushPeriodInSeconds";
static constexpr const char AWSMetricsOfflineRecordingEnabledKey[] = "/Gems/AWSMetrics/OfflineRecording";
static constexpr const char AWSMetricsMaxNumRetriesKey[] = "/Gems/AWSMetrics/MaxNumRetries";
ClientConfiguration();
//! Initialize the client settings based on the global setting registry.
//! @return whether the operation is successful
bool InitClientConfiguration();
//! Retrieve the max queue size setting.
//! @return Max queue size in bytes.
AZ::s64 GetMaxQueueSizeInBytes() const;
//! Retrieve the flush period setting.
//! @return Flush period in seconds.
AZ::s64 GetQueueFlushPeriodInSeconds() const;
//! Status of the offline recording. Metrics will be sent to a local file instead of the backend if the offline recording is enabled.
//! @return Whether the offline recording is enabled.
bool OfflineRecordingEnabled() const;
//! Retrieve the settings for the maximum number of retries.
//! @return Maximum number of retries.
AZ::s64 GetMaxNumRetries() const;
//! Retrieve the directory of the local metrics file
//! @return Directory of the local metrics file
const char* GetMetricsFileDir() const;
//! Retrieve the full path of the local metrics file
//! @return Full path of the local metrics file
const char* GetMetricsFileFullPath() const;
//! Enable/Disable the offline recording.
//! @param enable Whether to enable the offline recording.
void UpdateOfflineRecordingStatus(bool enable);
private:
bool ResolveMetricsFilePath();
double m_maxQueueSizeInMb; //< Default to 0.3MB on consideration of the Kinesis PutRecordBatch API limit (500 records/request).
AZ::s64 m_queueFlushPeriodInSeconds; //< Default to 60 seconds to guarantee the near real time data input.
AZStd::atomic_bool m_offlineRecordingEnabled; //< Default to false to disable the offline recording.
AZ::s64 m_maxNumRetries; //< Maximum number of retries for submission.
AZStd::string m_metricsDir;
AZStd::string m_metricsFilePath;
};
}
| 42.873239 | 158 | 0.700394 | [
"3d"
] |
8360ab12f790c4786c35bf0d7419f2a70b2e9d0c | 656 | h | C | include/interpreter.h | dvalim/pseudo-assembler | 6a0fc5690305c837d156047bae343bdeaf4a6926 | [
"MIT"
] | null | null | null | include/interpreter.h | dvalim/pseudo-assembler | 6a0fc5690305c837d156047bae343bdeaf4a6926 | [
"MIT"
] | null | null | null | include/interpreter.h | dvalim/pseudo-assembler | 6a0fc5690305c837d156047bae343bdeaf4a6926 | [
"MIT"
] | null | null | null | #ifndef INTERPRETER_H
#define INTERPRETER_H
#include "data_structures.h"
int current_line;
int state;
map variables;
map labels;
array memory;
int registry[16];
int prev_memory_change, prev_arg2;
typedef struct {
char code[MAX_LENGTH], arg1[MAX_LENGTH], arg2[MAX_LENGTH], arg3[MAX_LENGTH];
} command;
command makeCommand(char[], char[], char[], char[]);
typedef VECTOR(command) command_vector;
command_vector program;
void executeRegistry(command);
void executeJump(command);
void executeCommand(command);
string_vector label_names, variable_names;
array memory_history;
int registry_history[16];
void initMemory();
void freeMemory();
#endif | 18.742857 | 77 | 0.780488 | [
"vector"
] |
8363c18008378097233d8bd0f2ba2919476a7492 | 7,057 | h | C | gtsam/inference/Conditional.h | sdmiller/gtsam_pcl | 1e607bd75090d35e325a8fb37a6c5afe630f1207 | [
"BSD-3-Clause"
] | 11 | 2015-02-04T16:41:47.000Z | 2021-12-10T07:02:44.000Z | gtsam/inference/Conditional.h | sdmiller/gtsam_pcl | 1e607bd75090d35e325a8fb37a6c5afe630f1207 | [
"BSD-3-Clause"
] | null | null | null | gtsam/inference/Conditional.h | sdmiller/gtsam_pcl | 1e607bd75090d35e325a8fb37a6c5afe630f1207 | [
"BSD-3-Clause"
] | 6 | 2015-09-10T12:06:08.000Z | 2021-12-10T07:02:48.000Z | /* ----------------------------------------------------------------------------
* GTSAM Copyright 2010, Georgia Tech Research Corporation,
* Atlanta, Georgia 30332-0415
* All Rights Reserved
* Authors: Frank Dellaert, et al. (see THANKS for the full author list)
* See LICENSE for the license information
* -------------------------------------------------------------------------- */
/**
* @file Conditional.h
* @brief Base class for conditional densities
* @author Frank Dellaert
*/
// \callgraph
#pragma once
#include <iostream>
#include <boost/utility.hpp> // for noncopyable
#include <boost/foreach.hpp>
#include <boost/range/iterator_range.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/serialization/nvp.hpp>
#include <gtsam/inference/Factor.h>
namespace gtsam {
/**
* Base class for conditional densities, templated on KEY type. This class
* provides storage for the keys involved in a conditional, and iterators and
* access to the frontal and separator keys.
*
* Derived classes *must* redefine the Factor and shared_ptr typedefs to refer
* to the associated factor type and shared_ptr type of the derived class. See
* IndexConditional and GaussianConditional for examples.
* \nosubgrouping
*/
template<typename KEY>
class Conditional: public gtsam::Factor<KEY> {
private:
/** Create keys by adding key in front */
template<typename ITERATOR>
static std::vector<KEY> MakeKeys(KEY key, ITERATOR firstParent, ITERATOR lastParent) {
std::vector<KeyType> keys((lastParent - firstParent) + 1);
std::copy(firstParent, lastParent, keys.begin() + 1);
keys[0] = key;
return keys;
}
protected:
/** The first nFrontal variables are frontal and the rest are parents. */
size_t nrFrontals_;
// Calls the base class assertInvariants, which checks for unique keys
void assertInvariants() const { Factor<KEY>::assertInvariants(); }
public:
typedef KEY KeyType;
typedef Conditional<KeyType> This;
typedef Factor<KeyType> Base;
/**
* Typedef to the factor type that produces this conditional and that this
* conditional can be converted to using a factor constructor. Derived
* classes must redefine this.
*/
typedef gtsam::Factor<KeyType> FactorType;
/** A shared_ptr to this class. Derived classes must redefine this. */
typedef boost::shared_ptr<This> shared_ptr;
/** Iterator over keys */
typedef typename FactorType::iterator iterator;
/** Const iterator over keys */
typedef typename FactorType::const_iterator const_iterator;
/** View of the frontal keys (call frontals()) */
typedef boost::iterator_range<const_iterator> Frontals;
/** View of the separator keys (call parents()) */
typedef boost::iterator_range<const_iterator> Parents;
/// @name Standard Constructors
/// @{
/** Empty Constructor to make serialization possible */
Conditional() : nrFrontals_(0) { assertInvariants(); }
/** No parents */
Conditional(KeyType key) : FactorType(key), nrFrontals_(1) { assertInvariants(); }
/** Single parent */
Conditional(KeyType key, KeyType parent)
: FactorType(key, parent), nrFrontals_(1) { assertInvariants(); }
/** Two parents */
Conditional(KeyType key, KeyType parent1, KeyType parent2)
: FactorType(key, parent1, parent2), nrFrontals_(1) { assertInvariants(); }
/** Three parents */
Conditional(KeyType key, KeyType parent1, KeyType parent2, KeyType parent3)
: FactorType(key, parent1, parent2, parent3), nrFrontals_(1) { assertInvariants(); }
/// @}
/// @name Advanced Constructors
/// @{
/** Constructor from a frontal variable and a vector of parents */
Conditional(KeyType key, const std::vector<KeyType>& parents) :
FactorType(MakeKeys(key, parents.begin(), parents.end())), nrFrontals_(1) {
assertInvariants();
}
/** Constructor from keys and nr of frontal variables */
Conditional(const std::vector<Index>& keys, size_t nrFrontals) :
FactorType(keys), nrFrontals_(nrFrontals) {
assertInvariants();
}
/// @}
/// @name Testable
/// @{
/** print with optional formatter */
void print(const std::string& s = "Conditional", const IndexFormatter& formatter = DefaultIndexFormatter) const;
/** check equality */
template<class DERIVED>
bool equals(const DERIVED& c, double tol = 1e-9) const {
return nrFrontals_ == c.nrFrontals_ && FactorType::equals(c, tol); }
/// @}
/// @name Standard Interface
/// @{
/** return the number of frontals */
size_t nrFrontals() const { return nrFrontals_; }
/** return the number of parents */
size_t nrParents() const { return FactorType::size() - nrFrontals_; }
/** Special accessor when there is only one frontal variable. */
KeyType firstFrontalKey() const { assert(nrFrontals_>0); return FactorType::front(); }
KeyType lastFrontalKey() const { assert(nrFrontals_>0); return *(endFrontals()-1); }
/** return a view of the frontal keys */
Frontals frontals() const {
return boost::make_iterator_range(beginFrontals(), endFrontals()); }
/** return a view of the parent keys */
Parents parents() const {
return boost::make_iterator_range(beginParents(), endParents()); }
/** Iterators over frontal and parent variables. */
const_iterator beginFrontals() const { return FactorType::begin(); } ///<TODO: comment
const_iterator endFrontals() const { return FactorType::begin()+nrFrontals_; } ///<TODO: comment
const_iterator beginParents() const { return FactorType::begin()+nrFrontals_; } ///<TODO: comment
const_iterator endParents() const { return FactorType::end(); } ///<TODO: comment
/// @}
/// @name Advanced Interface
/// @{
/** Mutable iterators and accessors */
iterator beginFrontals() { return FactorType::begin(); } ///<TODO: comment
iterator endFrontals() { return FactorType::begin()+nrFrontals_; } ///<TODO: comment
iterator beginParents() { return FactorType::begin()+nrFrontals_; } ///<TODO: comment
iterator endParents() { return FactorType::end(); } ///<TODO: comment
///TODO: comment
boost::iterator_range<iterator> frontals() {
return boost::make_iterator_range(beginFrontals(), endFrontals()); }
///TODO: comment
boost::iterator_range<iterator> parents() {
return boost::make_iterator_range(beginParents(), endParents()); }
private:
/** Serialization function */
friend class boost::serialization::access;
template<class ARCHIVE>
void serialize(ARCHIVE & ar, const unsigned int version) {
ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP(Base);
ar & BOOST_SERIALIZATION_NVP(nrFrontals_);
}
/// @}
};
/* ************************************************************************* */
template<typename KEY>
void Conditional<KEY>::print(const std::string& s, const IndexFormatter& formatter) const {
std::cout << s << " P(";
BOOST_FOREACH(KeyType key, frontals()) std::cout << " " << formatter(key);
if (nrParents()>0) std::cout << " |";
BOOST_FOREACH(KeyType parent, parents()) std::cout << " " << formatter(parent);
std::cout << ")" << std::endl;
}
} // gtsam
| 33.287736 | 114 | 0.677625 | [
"vector"
] |
83667be486a9388ca907a2fea96c5979f2d970c1 | 2,358 | h | C | Engine/media/audio/openaldecoder.h | ericoporto/ags-old | da4f28d7cf700f5256f9b1295ee346e7a3cb39a4 | [
"Artistic-2.0"
] | null | null | null | Engine/media/audio/openaldecoder.h | ericoporto/ags-old | da4f28d7cf700f5256f9b1295ee346e7a3cb39a4 | [
"Artistic-2.0"
] | null | null | null | Engine/media/audio/openaldecoder.h | ericoporto/ags-old | da4f28d7cf700f5256f9b1295ee346e7a3cb39a4 | [
"Artistic-2.0"
] | null | null | null | //=============================================================================
//
// Adventure Game Studio (AGS)
//
// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
// The full list of copyright holders can be found in the Copyright.txt
// file, which is part of this source code distribution.
//
// The AGS source code is provided under the Artistic License 2.0.
// A copy of this license can be found in the file License.txt and at
// http://www.opensource.org/licenses/artistic-license-2.0.php
//
//=============================================================================
//
// OpenAL Decoder.
//
//=============================================================================
#ifndef __AGS_EE_MEDIA__OPENALDECODER_H
#define __AGS_EE_MEDIA__OPENALDECODER_H
#include <future>
#include "media/audio/openal.h"
#include <SDL_sound.h>
#include "media/audio/audio_core_defs.h"
#include "util/string.h"
struct SoundSampleDeleterFunctor {
void operator()(Sound_Sample* p) {
Sound_FreeSample(p);
#ifdef AUDIO_CORE_DEBUG
agsdbg::Printf(ags::kDbgMsg_Init, "SoundSampleDeleterFunctor");
#endif
}
};
using SoundSampleUniquePtr = std::unique_ptr<Sound_Sample, SoundSampleDeleterFunctor>;
class OpenALDecoder
{
public:
OpenALDecoder(ALuint source, std::future<std::vector<char>> sampleBufFuture, AGS::Common::String sampleExt, bool repeat);
OpenALDecoder(OpenALDecoder&& dec);
~OpenALDecoder();
void Poll();
void Play();
void Pause();
void Stop();
void Seek(float pos_ms);
AudioCorePlayState GetPlayState();
float GetPositionMs();
private:
ALuint source_;
bool repeat_;
AudioCorePlayState playState_ = PlayStateInitial;
std::future<std::vector<char>> sampleBufFuture_{};
std::vector<char> sampleData_{};
AGS::Common::String sampleExt_ = "";
ALenum sampleOpenAlFormat_ = 0;
SoundSampleUniquePtr sample_ = nullptr;
AudioCorePlayState onLoadPlayState_ = PlayStatePaused;
float onLoadPositionMs = 0.0f;
float processedBuffersDurationMs_ = 0.0f;
bool EOS_ = false;
static float buffer_duration_ms(ALuint bufferID);
static ALenum openalFormatFromSample(const SoundSampleUniquePtr &sample);
void DecoderUnqueueProcessedBuffers();
void PollBuffers();
};
void dump_al_errors();
#endif // __AGS_EE_MEDIA__OPENALDECODER_H
| 29.111111 | 125 | 0.657761 | [
"vector"
] |
83690080cffe2e8522236337b12355165b2adfa0 | 43,299 | c | C | src/nordugrid_gahp/globus_ftp_client_data.c | djw8605/condor | 391c85153e60cccfd201779ceae520d15561a8ea | [
"Apache-2.0"
] | null | null | null | src/nordugrid_gahp/globus_ftp_client_data.c | djw8605/condor | 391c85153e60cccfd201779ceae520d15561a8ea | [
"Apache-2.0"
] | null | null | null | src/nordugrid_gahp/globus_ftp_client_data.c | djw8605/condor | 391c85153e60cccfd201779ceae520d15561a8ea | [
"Apache-2.0"
] | 1 | 2021-08-29T14:03:10.000Z | 2021-08-29T14:03:10.000Z | /* Copied from Globus 5.0.0 for use with the NorduGrid GAHP server. */
/*
* Copyright 1999-2006 University of Chicago
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef GLOBUS_DONT_DOCUMENT_INTERNAL
/**
* @file globus_ftp_client_data.c Read/Write functions
*
* $RCSfile: globus_ftp_client_data.c,v $
* $Revision: 1.24 $
* $Date: 2008/04/04 01:51:47 $
*/
#endif
#include "globus_i_ftp_client.h"
#include <string.h>
#ifndef GLOBUS_DONT_DOCUMENT_INTERNAL
/**
* Data callback information structure.
*
* This structure is used to hold the data associated with a read or
* write operation. This structure will be stored in one of the
* stalled_blocks or active_blocks members of the control handle.
*
*/
typedef struct
{
/** The data buffer to be sent. */
globus_byte_t * buffer;
/** The size of the buffer. */
globus_size_t buffer_length;
/** The offset of the data block with respect to the entire file. */
globus_off_t offset;
/** Is this block the end-of-file? */
globus_bool_t eof;
/** The user's callback. */
globus_ftp_client_data_callback_t callback;
/** The user-supplied parameter to the callback. */
void * callback_arg;
/** handle this buffer is associated with (used for faking callbacks) */
globus_i_ftp_client_handle_t * i_handle;
}
globus_l_ftp_client_data_t;
static
void
globus_l_ftp_client_data_callback(
void * user_arg,
globus_ftp_control_handle_t * handle,
globus_object_t * error,
globus_byte_t * buffer,
globus_size_t length,
globus_off_t offset,
globus_bool_t eof);
static
void
globus_l_ftp_client_read_all_callback(
void * callback_arg,
globus_ftp_control_handle_t * handle,
globus_object_t * error,
globus_byte_t * buffer,
globus_size_t bytes_read,
globus_off_t offset_read,
globus_bool_t eof);
static
globus_l_ftp_client_data_t *
globus_l_ftp_client_data_new(
globus_byte_t * buffer,
globus_size_t buffer_length,
globus_off_t offset,
globus_bool_t eof,
globus_ftp_client_data_callback_t callback,
void * callback_arg);
static
void
globus_l_ftp_client_data_delete(
globus_l_ftp_client_data_t * data);
static
globus_size_t
globus_l_ftp_client_count_lf(const globus_byte_t * buf,
globus_size_t length);
#endif
/**
* Register a data buffer to handle a part of the FTP data transfer.
* @ingroup globus_ftp_client_data
*
* The data buffer will be associated with the current get being
* performed on this client handle.
*
* @param handle
* A pointer to a FTP Client handle which contains state information
* about the get operation.
* @param buffer
* A user-supplied buffer into which data from the FTP server
* will be stored.
* @param buffer_length
* The maximum amount of data that can be stored into the buffer.
* @param callback
* The function to be called once the data has been read.
* @param callback_arg
* Argument passed to the callback function
*
* @see globus_ftp_client_operationattr_set_read_all()
*/
globus_result_t
globus_ftp_client_register_read(
globus_ftp_client_handle_t * handle,
globus_byte_t * buffer,
globus_size_t buffer_length,
globus_ftp_client_data_callback_t callback,
void * callback_arg)
{
globus_object_t * err;
globus_l_ftp_client_data_t * data;
globus_result_t result;
globus_i_ftp_client_handle_t * i_handle;
GlobusFuncName(globus_ftp_client_register_read);
globus_i_ftp_client_debug_printf(3,
(stderr, "globus_ftp_client_register_read() entering\n"));
if(handle == GLOBUS_NULL)
{
err = GLOBUS_I_FTP_CLIENT_ERROR_NULL_PARAMETER("handle");
goto error;
}
if(buffer == GLOBUS_NULL)
{
err = GLOBUS_I_FTP_CLIENT_ERROR_NULL_PARAMETER("buffer");
goto error;
}
if(callback == GLOBUS_NULL)
{
err = GLOBUS_I_FTP_CLIENT_ERROR_NULL_PARAMETER("callback");
goto error;
}
if(GLOBUS_I_FTP_CLIENT_BAD_MAGIC(handle))
{
err = GLOBUS_I_FTP_CLIENT_ERROR_INVALID_PARAMETER("handle");
goto error;
}
i_handle = *handle;
globus_i_ftp_client_handle_lock(i_handle);
if(i_handle->op != GLOBUS_FTP_CLIENT_GET &&
i_handle->op != GLOBUS_FTP_CLIENT_LIST &&
i_handle->op != GLOBUS_FTP_CLIENT_NLST &&
i_handle->op != GLOBUS_FTP_CLIENT_MLSD )
{
err = GLOBUS_I_FTP_CLIENT_ERROR_INVALID_OPERATION(i_handle->op);
goto unlock_error;
}
if(((i_handle->state == GLOBUS_FTP_CLIENT_HANDLE_SOURCE_RETR_OR_ERET ||
i_handle->state == GLOBUS_FTP_CLIENT_HANDLE_SOURCE_LIST ||
i_handle->state == GLOBUS_FTP_CLIENT_HANDLE_FAILURE) &&
!(i_handle->source->state == GLOBUS_FTP_CLIENT_TARGET_READY_FOR_DATA ||
i_handle->source->state == GLOBUS_FTP_CLIENT_TARGET_NEED_LAST_BLOCK) &&
!(i_handle->source->state == GLOBUS_FTP_CLIENT_TARGET_RETR ||
i_handle->source->state == GLOBUS_FTP_CLIENT_TARGET_LIST ||
i_handle->source->state == GLOBUS_FTP_CLIENT_TARGET_GETPUT_PASV_GET)) ||
i_handle->state == GLOBUS_FTP_CLIENT_HANDLE_FINALIZE)
{
/* We've already hit EOF on the data channel. We'll just
* return that information to the user.
*/
err = GLOBUS_I_FTP_CLIENT_ERROR_EOF();
goto unlock_error;
}
data = globus_l_ftp_client_data_new(buffer,
buffer_length,
0,
GLOBUS_FALSE,
callback,
callback_arg);
if(data == GLOBUS_NULL)
{
err = GLOBUS_I_FTP_CLIENT_ERROR_OUT_OF_MEMORY();
goto unlock_error;
}
if((i_handle->state == GLOBUS_FTP_CLIENT_HANDLE_SOURCE_RETR_OR_ERET ||
i_handle->state == GLOBUS_FTP_CLIENT_HANDLE_SOURCE_LIST) &&
(i_handle->source->state == GLOBUS_FTP_CLIENT_TARGET_READY_FOR_DATA ||
i_handle->source->state == GLOBUS_FTP_CLIENT_TARGET_NEED_LAST_BLOCK)
&& globus_priority_q_empty(&i_handle->stalled_blocks))
{
/*
* The data block can be sent to the control library immediately if there is
* nothing left in the stalled queue and we're in the proper state.
*/
globus_hashtable_insert(&i_handle->active_blocks,
data->buffer,
data);
i_handle->num_active_blocks++;
globus_i_ftp_client_plugin_notify_read(i_handle,
data->buffer,
data->buffer_length);
result = globus_ftp_control_data_read(
i_handle->source->control_handle,
data->buffer,
data->buffer_length,
globus_l_ftp_client_data_callback,
i_handle);
if(result != GLOBUS_SUCCESS)
{
err = globus_error_get(result);
globus_hashtable_remove(&i_handle->active_blocks,
buffer);
i_handle->num_active_blocks--;
globus_l_ftp_client_data_delete(data);
/*
* Our block may have caused the "complete" callback to
* happen, as the data callback may have assumed that our
* data block was successfully registered
*/
if(i_handle->num_active_blocks == 0 &&
(i_handle->state == GLOBUS_FTP_CLIENT_HANDLE_SOURCE_RETR_OR_ERET ||
i_handle->state == GLOBUS_FTP_CLIENT_HANDLE_SOURCE_LIST ||
i_handle->state == GLOBUS_FTP_CLIENT_HANDLE_FAILURE))
{
if(i_handle->source->state ==
GLOBUS_FTP_CLIENT_TARGET_NEED_EMPTY_QUEUE)
{
/* We are finished, kick out a complete callback */
globus_reltime_t reltime;
i_handle->source->state =
GLOBUS_FTP_CLIENT_TARGET_COMPLETED_OPERATION;
GlobusTimeReltimeSet(reltime, 0, 0);
globus_callback_register_oneshot(
GLOBUS_NULL,
&reltime,
globus_l_ftp_client_complete_kickout,
(void *) i_handle);
}
else if(i_handle->source->state ==
GLOBUS_FTP_CLIENT_TARGET_NEED_EMPTY_AND_COMPLETE)
{
i_handle->source->state =
GLOBUS_FTP_CLIENT_TARGET_NEED_COMPLETE;
}
}
goto unlock_error;
}
}
else
{
/*
* Otherwise, enqueue the data in the block priority queue to
* be processed when the data channel is ready for it
*/
globus_priority_q_enqueue(&i_handle->stalled_blocks,
data,
&data->offset);
}
globus_i_ftp_client_handle_unlock(i_handle);
globus_i_ftp_client_debug_printf(3,
(stderr, "globus_ftp_client_register_read() exiting\n"));
return GLOBUS_SUCCESS;
unlock_error:
globus_i_ftp_client_handle_unlock(i_handle);
error:
globus_i_ftp_client_debug_printf(3,
(stderr, "globus_ftp_client_register_read() exiting with error\n"));
return globus_error_put(err);
}
/* globus_ftp_client_register_read() */
/**
* Register a data buffer to handle a part of the FTP data transfer.
* @ingroup globus_ftp_client_data
*
* The data buffer will be associated with the current "put" being
* performed on this client handle. Multiple data buffers may be
* registered on a handle at once. There is no guaranteed ordering of
* the data callbacks in extended block mode.
*
* @param handle
* A pointer to a FTP Client handle which contains state information
* about the put operation.
* @param buffer
* A user-supplied buffer containing the data to write to the server.
* @param buffer_length
* The size of the buffer to be written.
* @param offset
* The offset of the buffer to be written. In extended-block
* mode, the data does not need to be sent in order. In stream
* mode (the default), data must be sent in sequential
* order. The behavior is undefined if multiple writes overlap.
* @param callback
* The function to be called once the data has been written.
* @param callback_arg
* Argument passed to the callback function
*/
globus_result_t
globus_ftp_client_register_write(
globus_ftp_client_handle_t * handle,
globus_byte_t * buffer,
globus_size_t buffer_length,
globus_off_t offset,
globus_bool_t eof,
globus_ftp_client_data_callback_t callback,
void * callback_arg)
{
globus_object_t * err;
globus_l_ftp_client_data_t * data;
globus_result_t result;
globus_i_ftp_client_handle_t * i_handle;
GlobusFuncName(globus_ftp_client_register_write);
globus_i_ftp_client_debug_printf(3,
(stderr, "globus_ftp_client_register_write() entering\n"));
if(handle == GLOBUS_NULL)
{
err = GLOBUS_I_FTP_CLIENT_ERROR_NULL_PARAMETER("handle");
goto error;
}
if(buffer == GLOBUS_NULL)
{
err = GLOBUS_I_FTP_CLIENT_ERROR_NULL_PARAMETER("buffer");
goto error;
}
if(callback == GLOBUS_NULL)
{
err = GLOBUS_I_FTP_CLIENT_ERROR_NULL_PARAMETER("callback");
goto error;
}
if(GLOBUS_I_FTP_CLIENT_BAD_MAGIC(handle))
{
err = GLOBUS_I_FTP_CLIENT_ERROR_INVALID_PARAMETER("handle");
goto error;
}
i_handle = *(globus_i_ftp_client_handle_t **) handle;
globus_i_ftp_client_handle_lock(i_handle);
if(i_handle->op != GLOBUS_FTP_CLIENT_PUT)
{
err = GLOBUS_I_FTP_CLIENT_ERROR_INVALID_OPERATION(i_handle->op);
goto unlock_error;
}
if((i_handle->state == GLOBUS_FTP_CLIENT_HANDLE_DEST_STOR_OR_ESTO &&
!(i_handle->dest->state == GLOBUS_FTP_CLIENT_TARGET_READY_FOR_DATA ||
i_handle->dest->state == GLOBUS_FTP_CLIENT_TARGET_NEED_LAST_BLOCK) &&
i_handle->dest->state != GLOBUS_FTP_CLIENT_TARGET_STOR &&
i_handle->dest->state != GLOBUS_FTP_CLIENT_TARGET_GETPUT_PASV_PUT) ||
i_handle->state == GLOBUS_FTP_CLIENT_HANDLE_FINALIZE)
{
/* We've already sent EOF. We'll just return that information
* to the user.
*/
err = GLOBUS_I_FTP_CLIENT_ERROR_EOF();
goto unlock_error;
}
if(i_handle->partial_offset != -1)
{
offset -= i_handle->partial_offset;
}
data = globus_l_ftp_client_data_new(buffer,
buffer_length,
offset,
eof,
callback,
callback_arg);
if(data == GLOBUS_NULL)
{
err = GLOBUS_I_FTP_CLIENT_ERROR_OUT_OF_MEMORY();
goto unlock_error;
}
if(i_handle->state == GLOBUS_FTP_CLIENT_HANDLE_DEST_STOR_OR_ESTO &&
i_handle->dest->state == GLOBUS_FTP_CLIENT_TARGET_READY_FOR_DATA &&
globus_priority_q_empty(&i_handle->stalled_blocks))
{
/*
* The data block can be processed immediately if there is
* nothing left in the stalled queue and we're in the proper state.
*/
globus_hashtable_insert(&i_handle->active_blocks,
data->buffer,
data);
i_handle->num_active_blocks++;
globus_i_ftp_client_plugin_notify_write(i_handle,
data->buffer,
data->buffer_length,
data->offset,
data->eof);
/* We don't check for state changes here. Because we've
* already added this block to the hashtable and num_blocks,
* we don't need to, because the transfer can't finish without
* us.
*/
result = globus_ftp_control_data_write(
i_handle->dest->control_handle,
data->buffer,
data->buffer_length,
data->offset,
data->eof,
globus_l_ftp_client_data_callback,
i_handle);
if(result != GLOBUS_SUCCESS)
{
err = globus_error_get(result);
globus_hashtable_remove(&i_handle->active_blocks,
buffer);
i_handle->num_active_blocks--;
globus_l_ftp_client_data_delete(data);
/*
* Our block may have caused the "complete" callback to
* happen, as the data callback may have assumed that our
* data block was successfully registered
*/
if(i_handle->num_active_blocks == 0 &&
(i_handle->state == GLOBUS_FTP_CLIENT_HANDLE_DEST_STOR_OR_ESTO ||
i_handle->state == GLOBUS_FTP_CLIENT_HANDLE_FAILURE))
{
if(i_handle->dest->state ==
GLOBUS_FTP_CLIENT_TARGET_NEED_EMPTY_QUEUE)
{
/* We are finished, kick out a complete callback */
globus_reltime_t reltime;
i_handle->dest->state =
GLOBUS_FTP_CLIENT_TARGET_COMPLETED_OPERATION;
GlobusTimeReltimeSet(reltime, 0, 0);
globus_callback_register_oneshot(
GLOBUS_NULL,
&reltime,
globus_l_ftp_client_complete_kickout,
(void *) i_handle);
}
else if(i_handle->dest->state ==
GLOBUS_FTP_CLIENT_TARGET_NEED_EMPTY_AND_COMPLETE)
{
i_handle->dest->state =
GLOBUS_FTP_CLIENT_TARGET_NEED_COMPLETE;
}
}
goto unlock_error;
}
}
else
{
/*
* Otherwise, enqueue the data in the block priority queue to
* be processed when the data channel is ready for it
*/
globus_priority_q_enqueue(&i_handle->stalled_blocks,
data,
&data->offset);
}
globus_i_ftp_client_handle_unlock(i_handle);
globus_i_ftp_client_debug_printf(3,
(stderr, "globus_ftp_client_register_write() exiting\n"));
return GLOBUS_SUCCESS;
unlock_error:
globus_i_ftp_client_handle_unlock(i_handle);
error:
globus_i_ftp_client_debug_printf(3,
(stderr, "globus_ftp_client_register_write() exiting with error\n"));
return globus_error_put(err);
}
/* globus_ftp_client_register_write() */
#ifndef GLOBUS_DONT_DOCUMENT_INTERNAL
/*-----------------------------------------------------------------------------
* Local/Internal Functions.
*-----------------------------------------------------------------------------
*/
/**
* Priority queue comparison function.
*
* This function is called to decide where in the stalled_blocks
* priority queue to insert a data block.
*
* @param priority_1
* @param priority_2
*/
int
globus_i_ftp_client_data_cmp(
void * priority_1,
void * priority_2)
{
globus_off_t * offset1;
globus_off_t * offset2;
offset1 = (globus_off_t *) priority_1;
offset2 = (globus_off_t *) priority_2;
return ((*offset1) > (*offset2));
}
/* globus_i_ftp_client_data_cmp() */
/**
* Allocation and initialize a globus_l_ftp_client_data_t.
*
* @param buffer
* @param buffer_length
* @param offset
* @param eof
* @param callback
* User-supplied callback function.
* @param callback_arg
* User-supplied callback argument.
*/
static
globus_l_ftp_client_data_t *
globus_l_ftp_client_data_new(
globus_byte_t * buffer,
globus_size_t buffer_length,
globus_off_t offset,
globus_bool_t eof,
globus_ftp_client_data_callback_t callback,
void * callback_arg)
{
globus_l_ftp_client_data_t * d;
d = globus_libc_malloc(sizeof(globus_l_ftp_client_data_t));
if(!d)
{
return GLOBUS_NULL;
}
d->buffer = buffer;
d->buffer_length = buffer_length;
d->offset = offset;
d->callback = callback;
d->callback_arg = callback_arg;
d->eof = eof;
return d;
}
/* globus_l_ftp_client_data_new() */
/**
* Delete a globus_l_ftp_client_data_t.
*
* @param data
* The object to delete.
*/
static
void
globus_l_ftp_client_data_delete(
globus_l_ftp_client_data_t * data)
{
globus_libc_free(data);
}
/* globus_l_ftp_client_data_delete() */
/**
* Internal callback function to handle a data callback from the
* control library. This function notifies the plugins that the data
* block has been handled, and then calls the user callback
* associated with this data block.
*
* If any error occurs during data block handling in the control
* library, the data channels will be destroyed, so we should consider
* any error passed to this function as moving the handle into the
* failure state.
*
*/
static
void
globus_l_ftp_client_data_callback(
void * user_arg,
globus_ftp_control_handle_t * handle,
globus_object_t * error,
globus_byte_t * buffer,
globus_size_t length,
globus_off_t offset,
globus_bool_t eof)
{
globus_i_ftp_client_handle_t * client_handle;
globus_l_ftp_client_data_t * data;
globus_bool_t dispatch_final = GLOBUS_FALSE;
globus_i_ftp_client_target_t * target;
globus_i_ftp_client_target_t ** ptarget;
globus_off_t user_offset;
globus_bool_t user_eof;
globus_i_ftp_client_debug_printf(3, (stderr,
"globus_l_ftp_client_data_callback() entering\n"));
client_handle = (globus_i_ftp_client_handle_t *) user_arg;
globus_assert(!GLOBUS_I_FTP_CLIENT_BAD_MAGIC((&client_handle)));
globus_i_ftp_client_handle_lock(client_handle);
if(client_handle->op == GLOBUS_FTP_CLIENT_GET ||
client_handle->op == GLOBUS_FTP_CLIENT_LIST ||
client_handle->op == GLOBUS_FTP_CLIENT_NLST ||
client_handle->op == GLOBUS_FTP_CLIENT_MLSD)
{
ptarget = &client_handle->source;
}
else
{
ptarget = &client_handle->dest;
}
target = *ptarget;
globus_i_ftp_client_debug_states(4, client_handle);
if(target->mode == GLOBUS_FTP_CONTROL_MODE_STREAM)
{
offset += client_handle->base_offset;
}
user_offset = (client_handle->partial_offset != -1)
? offset + client_handle->partial_offset
: offset;
/* Don't update the stream_offset on 0 length buffers; these may come in
* with an offset of 0 when an error occurs or during restart,
* which will clobber what we've already seen
*/
if(target->mode == GLOBUS_FTP_CONTROL_MODE_STREAM && length != 0)
{
(void) globus_ftp_client_restart_marker_set_ascii_offset(
&client_handle->restart_marker,
offset+length,
offset+length+globus_l_ftp_client_count_lf(buffer, length));
}
else if(target->mode == GLOBUS_FTP_CONTROL_MODE_EXTENDED_BLOCK &&
length != 0)
{
(void) globus_ftp_client_restart_marker_insert_range(
&client_handle->restart_marker,
offset,
offset+length);
}
/* Notify plugins that this data block has been processed. The plugin
* gets the same (adjusted) view of the offset that the user gets. */
globus_i_ftp_client_plugin_notify_data(client_handle,
error,
buffer,
length,
user_offset,
eof);
data = (globus_l_ftp_client_data_t *)
globus_hashtable_remove(&client_handle->active_blocks,
buffer);
globus_assert(data);
/*
* Figure out if this was a fatal error.
* The plugins had a chance to restart when we notified them of the failure.
*/
if(error &&
(client_handle->state == GLOBUS_FTP_CLIENT_HANDLE_SOURCE_RETR_OR_ERET ||
client_handle->state == GLOBUS_FTP_CLIENT_HANDLE_DEST_STOR_OR_ESTO))
{
if(!client_handle->err)
{
client_handle->err = globus_object_copy(error);
}
client_handle->state = GLOBUS_FTP_CLIENT_HANDLE_FAILURE;
}
if(client_handle->state == GLOBUS_FTP_CLIENT_HANDLE_RESTART &&
(client_handle->op == GLOBUS_FTP_CLIENT_GET ||
client_handle->op == GLOBUS_FTP_CLIENT_LIST ||
client_handle->op == GLOBUS_FTP_CLIENT_NLST ||
client_handle->op == GLOBUS_FTP_CLIENT_MLSD ))
{
user_eof = GLOBUS_FALSE;
}
else
{
user_eof = eof;
}
/* Call back to the user */
globus_i_ftp_client_handle_unlock(client_handle);
data->callback(
data->callback_arg,
client_handle->handle,
error,
buffer,
length,
user_offset,
user_eof);
globus_l_ftp_client_data_delete(data);
globus_i_ftp_client_handle_lock(client_handle);
/* gave up lock, target could have gone bad, reload */
target = *ptarget;
/*
* Figure out if we need to call the completion function
* once this block's callback has been done
*/
client_handle->num_active_blocks--;
/* if eof now, or eof was received before */
if(eof ||
(target && (target->state == GLOBUS_FTP_CLIENT_TARGET_NEED_EMPTY_QUEUE ||
target->state == GLOBUS_FTP_CLIENT_TARGET_NEED_EMPTY_AND_COMPLETE ||
target->state == GLOBUS_FTP_CLIENT_TARGET_FAULT)))
{
if(client_handle->state == GLOBUS_FTP_CLIENT_HANDLE_SOURCE_RETR_OR_ERET ||
client_handle->state == GLOBUS_FTP_CLIENT_HANDLE_DEST_STOR_OR_ESTO ||
client_handle->state == GLOBUS_FTP_CLIENT_HANDLE_SOURCE_LIST ||
client_handle->state == GLOBUS_FTP_CLIENT_HANDLE_FAILURE)
{
if(target->state == GLOBUS_FTP_CLIENT_TARGET_READY_FOR_DATA ||
target->state ==
GLOBUS_FTP_CLIENT_TARGET_NEED_EMPTY_AND_COMPLETE)
{
if(client_handle->num_active_blocks == 0)
{
/*
* This is the last data block, and the response to the RETR,
* ERET, STOR, or ESTO operation has not been received,
* change state to prevent any subsequent data blocks being
* queued.
*/
target->state =
GLOBUS_FTP_CLIENT_TARGET_NEED_COMPLETE;
}
else
{
target->state =
GLOBUS_FTP_CLIENT_TARGET_NEED_EMPTY_AND_COMPLETE;
}
}
else if(target->state == GLOBUS_FTP_CLIENT_TARGET_NEED_LAST_BLOCK ||
target->state == GLOBUS_FTP_CLIENT_TARGET_NEED_EMPTY_QUEUE ||
target->state == GLOBUS_FTP_CLIENT_TARGET_FAULT)
{
/*
* If this is the last data block, and the response to the RETR,
* ERET, STOR, or ESTO operation has been received, then we
* must clean up after dispatching this callback.
*/
if(client_handle->num_active_blocks == 0)
{
dispatch_final = GLOBUS_TRUE;
target->state = GLOBUS_FTP_CLIENT_TARGET_COMPLETED_OPERATION;
}
else if(target->state != GLOBUS_FTP_CLIENT_TARGET_FAULT)
{
target->state = GLOBUS_FTP_CLIENT_TARGET_NEED_EMPTY_QUEUE;
}
}
}
}
if(dispatch_final)
{
/*
* This is the end of the transfer. We call into the transfer
* code to clean up things and call back to the user.
*
* This function is a bit weird in that you call it locked,
* and it returns unlocked.
*/
globus_i_ftp_client_transfer_complete(client_handle);
}
else
{
globus_i_ftp_client_handle_unlock(client_handle);
}
globus_i_ftp_client_debug_printf(3, (stderr,
"globus_l_ftp_client_data_callback() exiting\n"));
globus_i_ftp_client_debug_states(4, client_handle);
return;
}
/* globus_l_ftp_client_data_callback() */
/**
* Internal callback function to handle a read_all data callback from the
* control library. This function notifies the plugins that the data
* block has been handled, and then calls the user callback
* associated with this data block.
*
* When processing a read_all, intermediate callbacks may be issued if the
* user has requested it by setting the callback for the read_all attribute.
*
* If any error occurs during data block handling in the control
* library, the data channels will be destroyed, so we should consider
* any error passed to this function as moving the handle into the
* failure state.
*
*/
static
void
globus_l_ftp_client_read_all_callback(
void * callback_arg,
globus_ftp_control_handle_t * handle,
globus_object_t * error,
globus_byte_t * buffer,
globus_size_t bytes_read,
globus_off_t offset_read,
globus_bool_t eof)
{
globus_i_ftp_client_handle_t * client_handle;
globus_l_ftp_client_data_t * data;
globus_bool_t dispatch_final = GLOBUS_FALSE;
globus_i_ftp_client_target_t * target;
globus_ftp_client_data_callback_t read_all_callback = GLOBUS_NULL;
void * read_all_callback_arg = GLOBUS_NULL;
globus_off_t total_bytes_read;
globus_off_t user_offset;
client_handle = (globus_i_ftp_client_handle_t *) callback_arg;
globus_assert(!GLOBUS_I_FTP_CLIENT_BAD_MAGIC((&client_handle)));
globus_i_ftp_client_handle_lock(client_handle);
target = client_handle->source;
globus_assert(client_handle->op == GLOBUS_FTP_CLIENT_GET ||
client_handle->op == GLOBUS_FTP_CLIENT_LIST ||
client_handle->op == GLOBUS_FTP_CLIENT_NLST ||
client_handle->op == GLOBUS_FTP_CLIENT_MLSD );
globus_i_ftp_client_debug_printf(3, (stderr,
"globus_l_ftp_client_read_all_callback() entering\n"));
globus_i_ftp_client_debug_states(4, client_handle);
if(target->mode == GLOBUS_FTP_CONTROL_MODE_STREAM)
{
offset_read += client_handle->base_offset;
}
if(bytes_read > 0 &&
offset_read + bytes_read > client_handle->read_all_biggest_offset)
{
client_handle->read_all_biggest_offset = offset_read + bytes_read;
}
user_offset = (client_handle->partial_offset == -1)
? offset_read
: offset_read + client_handle->partial_offset;
/* Notify plugins that this data block has been processed. */
globus_i_ftp_client_plugin_notify_data(client_handle,
error,
buffer + offset_read,
bytes_read,
user_offset,
eof);
if(!eof)
{
data = (globus_l_ftp_client_data_t *)
globus_hashtable_lookup(&client_handle->active_blocks,
buffer);
}
else
{
data = (globus_l_ftp_client_data_t *)
globus_hashtable_remove(&client_handle->active_blocks,
buffer);
}
globus_assert(data);
/*
* Figure out if this was a fatal error.
* The plugins had a chance to restart when we notified them of the failure.
*/
if(error &&
(client_handle->state == GLOBUS_FTP_CLIENT_HANDLE_SOURCE_RETR_OR_ERET ||
client_handle->state == GLOBUS_FTP_CLIENT_HANDLE_DEST_STOR_OR_ESTO))
{
if(!client_handle->err)
{
client_handle->err = globus_object_copy(error);
}
client_handle->state = GLOBUS_FTP_CLIENT_HANDLE_FAILURE;
}
/*
* Figure out if we need to call the completion function
* once this block's callback has been done
*/
if(eof)
{
client_handle->num_active_blocks--;
if(client_handle->state == GLOBUS_FTP_CLIENT_HANDLE_SOURCE_RETR_OR_ERET ||
client_handle->state == GLOBUS_FTP_CLIENT_HANDLE_DEST_STOR_OR_ESTO ||
client_handle->state == GLOBUS_FTP_CLIENT_HANDLE_SOURCE_LIST ||
client_handle->state == GLOBUS_FTP_CLIENT_HANDLE_FAILURE)
{
if(target->state == GLOBUS_FTP_CLIENT_TARGET_READY_FOR_DATA ||
target->state ==
GLOBUS_FTP_CLIENT_TARGET_NEED_EMPTY_AND_COMPLETE)
{
if(client_handle->num_active_blocks == 0)
{
/*
* This is the last data block, and the response to the RETR,
* ERET, STOR, or ESTO operation has not been received,
* change state to prevent any subsequent data blocks being
* queued.
*/
target->state =
GLOBUS_FTP_CLIENT_TARGET_NEED_COMPLETE;
}
else
{
target->state =
GLOBUS_FTP_CLIENT_TARGET_NEED_EMPTY_AND_COMPLETE;
}
}
else if(target->state == GLOBUS_FTP_CLIENT_TARGET_NEED_LAST_BLOCK ||
target->state == GLOBUS_FTP_CLIENT_TARGET_NEED_EMPTY_QUEUE ||
target->state == GLOBUS_FTP_CLIENT_TARGET_FAULT)
{
/*
* If this is the last data block, and the response to the RETR,
* ERET, STOR, or ESTO operation has been received, then we
* must clean up after dispatching this callback.
*/
if(client_handle->num_active_blocks == 0)
{
dispatch_final = GLOBUS_TRUE;
target->state = GLOBUS_FTP_CLIENT_TARGET_COMPLETED_OPERATION;
}
else if(target->state != GLOBUS_FTP_CLIENT_TARGET_FAULT)
{
target->state = GLOBUS_FTP_CLIENT_TARGET_NEED_EMPTY_QUEUE;
}
}
}
}
if(client_handle->state == GLOBUS_FTP_CLIENT_HANDLE_RESTART)
{
if(client_handle->op == GLOBUS_FTP_CLIENT_GET ||
client_handle->op == GLOBUS_FTP_CLIENT_LIST ||
client_handle->op == GLOBUS_FTP_CLIENT_NLST ||
client_handle->op == GLOBUS_FTP_CLIENT_MLSD)
{
eof = GLOBUS_FALSE;
dispatch_final = GLOBUS_FALSE;
}
}
globus_assert(
client_handle->state == GLOBUS_FTP_CLIENT_HANDLE_SOURCE_RETR_OR_ERET
|| client_handle->state == GLOBUS_FTP_CLIENT_HANDLE_DEST_STOR_OR_ESTO
|| client_handle->state == GLOBUS_FTP_CLIENT_HANDLE_SOURCE_LIST
|| client_handle->state == GLOBUS_FTP_CLIENT_HANDLE_FAILURE
|| client_handle->state == GLOBUS_FTP_CLIENT_HANDLE_ABORT
|| client_handle->state == GLOBUS_FTP_CLIENT_HANDLE_RESTART);
/* Don't update the stream_offset on 0 length buffers; these may come in
* with an offset of 0 when an error occurs or during restart,
* which will clobber what we've already seen
*/
if(target->mode == GLOBUS_FTP_CONTROL_MODE_STREAM && bytes_read != 0)
{
client_handle->restart_marker.stream.offset = bytes_read;
client_handle->restart_marker.stream.ascii_offset =
bytes_read +
globus_l_ftp_client_count_lf(buffer + offset_read, bytes_read);
}
if(target->attr->read_all)
{
read_all_callback = target->attr->read_all_intermediate_callback;
read_all_callback_arg =
target->attr->read_all_intermediate_callback_arg;
}
total_bytes_read = client_handle->read_all_biggest_offset;
globus_i_ftp_client_handle_unlock(client_handle);
if(read_all_callback)
{
(*read_all_callback)(read_all_callback_arg,
client_handle->handle,
error,
buffer + offset_read,
bytes_read,
user_offset,
eof);
}
user_offset = (client_handle->partial_offset == -1)
? 0
: client_handle->partial_offset;
if(eof)
{
data->callback(
data->callback_arg,
client_handle->handle,
error,
buffer,
total_bytes_read,
user_offset,
eof);
globus_l_ftp_client_data_delete(data);
}
if(dispatch_final)
{
/*
* This is the end of the transfer. We call into the transfer
* code to clean up things and call back to the user.
*
* This function is a bit weird in that you call it locked,
* and it returns unlocked.
*/
globus_i_ftp_client_handle_lock(client_handle);
globus_i_ftp_client_transfer_complete(client_handle);
}
globus_i_ftp_client_debug_printf(3, (stderr,
"globus_l_ftp_client_read_all_callback() exiting\n"));
globus_i_ftp_client_debug_states(4, client_handle);
return;
}
/* globus_l_ftp_client_read_all_callback() */
/**
* Dispatch buffers from the stalled_blocks queue to the control API.
*
* This function is called once we know that the data connection has
* been established for a get or put request (via a 125 or 150
* response). This code relies on the control library's being able to
* deal with multiple blocks queued with it at once.
*
* The blocks are sent in the order of their starting offset. If
* blocks overlap, then the behavior will probably not be correct.
*
* @param handle
* The client handle associated with this request.
*/
globus_object_t *
globus_i_ftp_client_data_dispatch_queue(
globus_i_ftp_client_handle_t * handle)
{
globus_i_ftp_client_target_t * target;
globus_result_t result;
globus_object_t * err;
globus_i_ftp_client_debug_printf(1,
(stderr, "globus_i_ftp_client_data_dispatch_queue() entering\n"));
if(handle->op == GLOBUS_FTP_CLIENT_GET ||
handle->op == GLOBUS_FTP_CLIENT_LIST ||
handle->op == GLOBUS_FTP_CLIENT_NLST ||
handle->op == GLOBUS_FTP_CLIENT_MLSD)
{
target = handle->source;
}
else
{
target = handle->dest;
}
while(! globus_priority_q_empty(&handle->stalled_blocks) &&
handle->state != GLOBUS_FTP_CLIENT_HANDLE_RESTART &&
handle->state != GLOBUS_FTP_CLIENT_HANDLE_ABORT)
{
globus_l_ftp_client_data_t * data;
/*
* Do not remove from the queue until the block is sent to the
* control library. This makes any block which is being
* handled by register_read or register_write in another
* thread get sent to the control library after the current
* head of the queue.
*/
data = (globus_l_ftp_client_data_t *)
globus_priority_q_first(&handle->stalled_blocks);
globus_hashtable_insert(&handle->active_blocks,
data->buffer,
data);
handle->num_active_blocks++;
globus_assert(handle->op == GLOBUS_FTP_CLIENT_LIST ||
handle->op == GLOBUS_FTP_CLIENT_NLST ||
handle->op == GLOBUS_FTP_CLIENT_MLSD ||
handle->op == GLOBUS_FTP_CLIENT_GET ||
handle->op == GLOBUS_FTP_CLIENT_PUT);
switch(handle->op)
{
case GLOBUS_FTP_CLIENT_GET:
case GLOBUS_FTP_CLIENT_LIST:
case GLOBUS_FTP_CLIENT_NLST:
case GLOBUS_FTP_CLIENT_MLSD:
globus_i_ftp_client_plugin_notify_read(handle,
data->buffer,
data->buffer_length);
if(target->attr->read_all)
{
globus_i_ftp_client_target_t * target;
/* The base offset is used in stream mode to keep track of
* any restart marker's influence on the offset of the data
* coming on a data channel. In extended block mode, this
* is explicit in the extended block headers
*/
handle->base_offset = 0;
target = handle->source;
if(handle->restart_marker.type ==
GLOBUS_FTP_CLIENT_RESTART_STREAM &&
handle->restart_marker.stream.offset > handle->base_offset)
{
handle->base_offset = handle->restart_marker.stream.offset;
}
result = globus_ftp_control_data_read_all(
target->control_handle,
data->buffer,
data->buffer_length,
globus_l_ftp_client_read_all_callback,
handle);
}
else
{
result = globus_ftp_control_data_read(
handle->source->control_handle,
data->buffer,
data->buffer_length,
globus_l_ftp_client_data_callback,
handle);
}
break;
case GLOBUS_FTP_CLIENT_PUT:
globus_i_ftp_client_plugin_notify_write(handle,
data->buffer,
data->buffer_length,
data->offset,
data->eof);
result = globus_ftp_control_data_write(
handle->dest->control_handle,
data->buffer,
data->buffer_length,
data->offset,
data->eof,
globus_l_ftp_client_data_callback,
handle);
break;
default: /* No other states should occur */
globus_assert(0 && "Unexpected state");
}
if(result == GLOBUS_SUCCESS)
{
globus_priority_q_remove(&handle->stalled_blocks,
data);
}
else if((handle->state == GLOBUS_FTP_CLIENT_HANDLE_SOURCE_RETR_OR_ERET ||
handle->state == GLOBUS_FTP_CLIENT_HANDLE_DEST_STOR_OR_ESTO ||
handle->state == GLOBUS_FTP_CLIENT_HANDLE_FAILURE) &&
(target->state == GLOBUS_FTP_CLIENT_TARGET_NEED_COMPLETE ||
target->state == GLOBUS_FTP_CLIENT_TARGET_NEED_EMPTY_QUEUE ||
target->state ==
GLOBUS_FTP_CLIENT_TARGET_NEED_EMPTY_AND_COMPLETE))
{
/*
* Registration can fail if the data connection has been
* closed.
*
* In this case, the callback can be sent with no
* data and EOF set to true.
*/
err = globus_error_get(result);
globus_priority_q_remove(&handle->stalled_blocks,
data);
globus_hashtable_remove(&handle->active_blocks,
data->buffer);
handle->num_active_blocks--;
globus_i_ftp_client_plugin_notify_data(handle,
err,
data->buffer,
0,
0,
GLOBUS_TRUE);
globus_i_ftp_client_handle_unlock(handle);
data->callback(data->callback_arg,
handle->handle,
err,
data->buffer,
0,
0,
GLOBUS_TRUE);
globus_object_free(err);
err = GLOBUS_SUCCESS;
globus_i_ftp_client_handle_lock(handle);
}
else
{
globus_hashtable_remove(&handle->active_blocks,
data->buffer);
handle->num_active_blocks--;
err = globus_error_get(result);
if(handle->state == GLOBUS_FTP_CLIENT_HANDLE_RESTART)
{
globus_object_free(err);
err = GLOBUS_SUCCESS;
}
globus_i_ftp_client_debug_printf(1, (stderr,
"globus_i_ftp_client_data_dispatch_queue() exiting with error\n"));
return err;
}
}
globus_i_ftp_client_debug_printf(1, (stderr,
"globus_i_ftp_client_data_dispatch_queue() exiting\n"));
return GLOBUS_SUCCESS;
}
/* globus_i_ftp_client_data_dispatch_queue() */
/**
* Flush any queued-but-not-processed data buffers from the client
* handle.
*
* This function is called as part of the teardown after an operation
* fails. If the failure occurs before the control connection is ready
* for data blocks, then any data buffers from the user will be queued
* in the stalled blocks queue.
*
* @param handle
* Client handle to process.
*
*/
void
globus_i_ftp_client_data_flush(
globus_i_ftp_client_handle_t * handle)
{
globus_fifo_t tmp;
globus_i_ftp_client_debug_printf(1,
(stderr, "globus_i_ftp_client_data_flush() entering\n"));
globus_fifo_init(&tmp);
while(!globus_priority_q_empty(&handle->stalled_blocks))
{
globus_fifo_enqueue(&tmp,
globus_priority_q_dequeue(&handle->stalled_blocks));
}
while(!globus_fifo_empty(&tmp))
{
globus_l_ftp_client_data_t * data;
data = (globus_l_ftp_client_data_t *)
globus_fifo_dequeue(&tmp);
globus_i_ftp_client_plugin_notify_data(handle,
handle->err,
data->buffer,
0/*length*/,
0/*offset*/,
GLOBUS_TRUE /*eof*/);
globus_i_ftp_client_handle_unlock(handle);
data->callback(data->callback_arg,
handle->handle,
handle->err,
data->buffer,
0,
0,
GLOBUS_TRUE);
globus_i_ftp_client_handle_lock(handle);
globus_libc_free(data);
}
globus_fifo_destroy(&tmp);
globus_i_ftp_client_debug_printf(1,
(stderr, "globus_i_ftp_client_data_flush() exiting\n"));
}
/* globus_i_ftp_client_data_flush() */
void
globus_l_ftp_client_complete_kickout(
void * user_arg)
{
globus_i_ftp_client_handle_t * handle;
globus_i_ftp_client_debug_printf(1,
(stderr, "globus_l_ftp_client_complete_kickout() entering\n"));
handle = (globus_i_ftp_client_handle_t *) user_arg;
globus_assert(!GLOBUS_I_FTP_CLIENT_BAD_MAGIC((&handle)));
globus_i_ftp_client_handle_lock(handle);
globus_i_ftp_client_transfer_complete(handle);
globus_i_ftp_client_debug_printf(1,
(stderr, "globus_l_ftp_client_complete_kickout() exiting\n"));
}
/* globus_l_ftp_client_complete_kickout() */
/**
* Count the number of newline characters in a buffer.
*/
static
globus_size_t
globus_l_ftp_client_count_lf(
const globus_byte_t * buf,
globus_size_t length)
{
globus_size_t i;
globus_size_t count = 0;
for(i = 0; i < length; i++)
{
if(buf[i] == '\n') count++;
}
return count;
}
/* globus_l_ftp_client_count_lf() */
#endif
| 30.55681 | 83 | 0.651493 | [
"object"
] |
8370b8104ffcd1633ed19df65ebc75e78d555b37 | 13,394 | h | C | delta_performer.h | marineam/update_engine | 30e8455fb95d83fc6dae82a504c6d16273a7775e | [
"BSD-3-Clause"
] | 1 | 2017-09-20T14:03:29.000Z | 2017-09-20T14:03:29.000Z | delta_performer.h | marineam/update_engine | 30e8455fb95d83fc6dae82a504c6d16273a7775e | [
"BSD-3-Clause"
] | null | null | null | delta_performer.h | marineam/update_engine | 30e8455fb95d83fc6dae82a504c6d16273a7775e | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2010 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROMEOS_PLATFORM_UPDATE_ENGINE_DELTA_PERFORMER_H__
#define CHROMEOS_PLATFORM_UPDATE_ENGINE_DELTA_PERFORMER_H__
#include <inttypes.h>
#include <vector>
#include <base/time.h>
#include <google/protobuf/repeated_field.h>
#include <gtest/gtest_prod.h> // for FRIEND_TEST
#include "update_engine/file_writer.h"
#include "update_engine/install_plan.h"
#include "update_engine/omaha_hash_calculator.h"
#include "update_engine/system_state.h"
#include "update_engine/update_metadata.pb.h"
namespace chromeos_update_engine {
class PrefsInterface;
// This class performs the actions in a delta update synchronously. The delta
// update itself should be passed in in chunks as it is received.
class DeltaPerformer : public FileWriter {
public:
enum MetadataParseResult {
kMetadataParseSuccess,
kMetadataParseError,
kMetadataParseInsufficientData,
};
static const uint64_t kDeltaVersionSize;
static const uint64_t kDeltaManifestSizeSize;
static const char kUpdatePayloadPublicKeyPath[];
// Defines the granularity of progress logging in terms of how many "completed
// chunks" we want to report at the most.
static const unsigned kProgressLogMaxChunks;
// Defines a timeout since the last progress was logged after which we want to
// force another log message (even if the current chunk was not completed).
static const unsigned kProgressLogTimeoutSeconds;
// These define the relative weights (0-100) we give to the different work
// components associated with an update when computing an overall progress.
// Currently they include the download progress and the number of completed
// operations. They must add up to one hundred (100).
static const unsigned kProgressDownloadWeight;
static const unsigned kProgressOperationsWeight;
DeltaPerformer(PrefsInterface* prefs,
SystemState* system_state,
InstallPlan* install_plan)
: prefs_(prefs),
system_state_(system_state),
install_plan_(install_plan),
fd_(-1),
kernel_fd_(-1),
manifest_valid_(false),
manifest_metadata_size_(0),
next_operation_num_(0),
buffer_offset_(0),
last_updated_buffer_offset_(kuint64max),
block_size_(0),
public_key_path_(kUpdatePayloadPublicKeyPath),
total_bytes_received_(0),
num_rootfs_operations_(0),
num_total_operations_(0),
overall_progress_(0),
last_progress_chunk_(0),
forced_progress_log_wait_(
base::TimeDelta::FromSeconds(kProgressLogTimeoutSeconds)) {}
// Opens the kernel. Should be called before or after Open(), but before
// Write(). The kernel file will be close()d when Close() is called.
bool OpenKernel(const char* kernel_path);
// flags and mode ignored. Once Close()d, a DeltaPerformer can't be
// Open()ed again.
int Open(const char* path, int flags, mode_t mode);
// FileWriter's Write implementation where caller doesn't care about
// error codes.
bool Write(const void* bytes, size_t count) {
ActionExitCode error;
return Write(bytes, count, &error);
}
// FileWriter's Write implementation that returns a more specific |error| code
// in case of failures in Write operation.
bool Write(const void* bytes, size_t count, ActionExitCode *error);
// Wrapper around close. Returns 0 on success or -errno on error.
// Closes both 'path' given to Open() and the kernel path.
int Close();
// Verifies the downloaded payload against the signed hash included in the
// payload, against the update check hash (which is in base64 format) and
// size using the public key and returns kActionCodeSuccess on success, an
// error code on failure. This method should be called after closing the
// stream. Note this method skips the signed hash check if the public key is
// unavailable; it returns kActionCodeSignedDeltaPayloadExpectedError if the
// public key is available but the delta payload doesn't include a signature.
ActionExitCode VerifyPayload(const std::string& update_check_response_hash,
const uint64_t update_check_response_size);
// Reads from the update manifest the expected sizes and hashes of the target
// kernel and rootfs partitions. These values can be used for applied update
// hash verification. This method must be called after the update manifest has
// been parsed (e.g., after closing the stream). Returns true on success, and
// false on failure (e.g., when the values are not present in the update
// manifest).
bool GetNewPartitionInfo(uint64_t* kernel_size,
std::vector<char>* kernel_hash,
uint64_t* rootfs_size,
std::vector<char>* rootfs_hash);
// Converts an ordered collection of Extent objects which contain data of
// length full_length to a comma-separated string. For each Extent, the
// string will have the start offset and then the length in bytes.
// The length value of the last extent in the string may be short, since
// the full length of all extents in the string is capped to full_length.
// Also, an extent starting at kSparseHole, appears as -1 in the string.
// For example, if the Extents are {1, 1}, {4, 2}, {kSparseHole, 1},
// {0, 1}, block_size is 4096, and full_length is 5 * block_size - 13,
// the resulting string will be: "4096:4096,16384:8192,-1:4096,0:4083"
static bool ExtentsToBsdiffPositionsString(
const google::protobuf::RepeatedPtrField<Extent>& extents,
uint64_t block_size,
uint64_t full_length,
std::string* positions_string);
// Returns true if a previous update attempt can be continued based on the
// persistent preferences and the new update check response hash.
static bool CanResumeUpdate(PrefsInterface* prefs,
std::string update_check_response_hash);
// Resets the persistent update progress state to indicate that an update
// can't be resumed. Performs a quick update-in-progress reset if |quick| is
// true, otherwise resets all progress-related update state. Returns true on
// success, false otherwise.
static bool ResetUpdateProgress(PrefsInterface* prefs, bool quick);
// Attempts to parse the update metadata starting from the beginning of
// |payload| into |manifest|. On success, sets |metadata_size| to the total
// metadata bytes (including the delta magic and metadata size fields), and
// returns kMetadataParseSuccess. Returns kMetadataParseInsufficientData if
// more data is needed to parse the complete metadata. Returns
// kMetadataParseError if the metadata can't be parsed given the payload.
MetadataParseResult ParsePayloadMetadata(
const std::vector<char>& payload,
DeltaArchiveManifest* manifest,
uint64_t* metadata_size,
ActionExitCode* error);
void set_public_key_path(const std::string& public_key_path) {
public_key_path_ = public_key_path;
}
// Returns the byte offset at which the manifest protobuf begins in a
// payload.
static uint64_t GetManifestOffset();
// Returns the byte offset where the size of the manifest is stored in
// a payload. This offset precedes the actual start of the manifest
// that's returned by the GetManifestOffset method.
static uint64_t GetManifestSizeOffset();
private:
friend class DeltaPerformerTest;
FRIEND_TEST(DeltaPerformerTest, IsIdempotentOperationTest);
// Logs the progress of downloading/applying an update.
void LogProgress(const char* message_prefix);
// Update overall progress metrics, log as necessary.
void UpdateOverallProgress(bool force_log, const char* message_prefix);
static bool IsIdempotentOperation(
const DeltaArchiveManifest_InstallOperation& op);
// Verifies that the expected source partition hashes (if present) match the
// hashes for the current partitions. Returns true if there're no expected
// hashes in the payload (e.g., if it's a new-style full update) or if the
// hashes match; returns false otherwise.
bool VerifySourcePartitions();
// Returns true if enough of the delta file has been passed via Write()
// to be able to perform a given install operation.
bool CanPerformInstallOperation(
const DeltaArchiveManifest_InstallOperation& operation);
// Validates that the hash of the blobs corresponding to the given |operation|
// matches what's specified in the manifest in the payload.
// Returns kActionCodeSuccess on match or a suitable error code otherwise.
ActionExitCode ValidateOperationHash(
const DeltaArchiveManifest_InstallOperation& operation);
// Interprets the given |protobuf| as a DeltaArchiveManifest protocol buffer
// of the given protobuf_length and verifies that the signed hash of the
// metadata matches what's specified in the install plan from Omaha.
// Returns kActionCodeSuccess on match or a suitable error code otherwise.
// This method must be called before any part of the |protobuf| is parsed
// so that a man-in-the-middle attack on the SSL connection to the payload
// server doesn't exploit any vulnerability in the code that parses the
// protocol buffer.
ActionExitCode ValidateMetadataSignature(const char* protobuf,
uint64_t protobuf_length);
// Returns true on success.
bool PerformInstallOperation(
const DeltaArchiveManifest_InstallOperation& operation);
// These perform a specific type of operation and return true on success.
bool PerformReplaceOperation(
const DeltaArchiveManifest_InstallOperation& operation,
bool is_kernel_partition);
bool PerformMoveOperation(
const DeltaArchiveManifest_InstallOperation& operation,
bool is_kernel_partition);
bool PerformBsdiffOperation(
const DeltaArchiveManifest_InstallOperation& operation,
bool is_kernel_partition);
// Returns true if the payload signature message has been extracted from
// |operation|, false otherwise.
bool ExtractSignatureMessage(
const DeltaArchiveManifest_InstallOperation& operation);
// Updates the hash calculator with |count| bytes at the head of |buffer_| and
// then discards them.
void DiscardBufferHeadBytes(size_t count);
// Checkpoints the update progress into persistent storage to allow this
// update attempt to be resumed after reboot.
bool CheckpointUpdateProgress();
// Primes the required update state. Returns true if the update state was
// successfully initialized to a saved resume state or if the update is a new
// update. Returns false otherwise.
bool PrimeUpdateState();
// Sends UMA statistics for the given error code.
void SendUmaStat(ActionExitCode code);
// Update Engine preference store.
PrefsInterface* prefs_;
// Global context of the system.
SystemState* system_state_;
// Install Plan based on Omaha Response.
InstallPlan* install_plan_;
// File descriptor of open device.
int fd_;
// File descriptor of the kernel device
int kernel_fd_;
std::string path_; // Path that fd_ refers to.
std::string kernel_path_; // Path that kernel_fd_ refers to.
DeltaArchiveManifest manifest_;
bool manifest_valid_;
uint64_t manifest_metadata_size_;
// Index of the next operation to perform in the manifest.
size_t next_operation_num_;
// buffer_ is a window of the data that's been downloaded. At first,
// it contains the beginning of the download, but after the protobuf
// has been downloaded and parsed, it contains a sliding window of
// data blobs.
std::vector<char> buffer_;
// Offset of buffer_ in the binary blobs section of the update.
uint64_t buffer_offset_;
// Last |buffer_offset_| value updated as part of the progress update.
uint64_t last_updated_buffer_offset_;
// The block size (parsed from the manifest).
uint32_t block_size_;
// Calculates the payload hash.
OmahaHashCalculator hash_calculator_;
// Saves the signed hash context.
std::string signed_hash_context_;
// Signatures message blob extracted directly from the payload.
std::vector<char> signatures_message_data_;
// The public key to be used. Provided as a member so that tests can
// override with test keys.
std::string public_key_path_;
// The number of bytes received so far, used for progress tracking.
size_t total_bytes_received_;
// The number rootfs and total operations in a payload, once we know them.
size_t num_rootfs_operations_;
size_t num_total_operations_;
// An overall progress counter, which should reflect both download progress
// and the ratio of applied operations. Range is 0-100.
unsigned overall_progress_;
// The last progress chunk recorded.
unsigned last_progress_chunk_;
// The timeout after which we should force emitting a progress log (constant),
// and the actual point in time for the next forced log to be emitted.
const base::TimeDelta forced_progress_log_wait_;
base::Time forced_progress_log_time_;
DISALLOW_COPY_AND_ASSIGN(DeltaPerformer);
};
} // namespace chromeos_update_engine
#endif // CHROMEOS_PLATFORM_UPDATE_ENGINE_DELTA_PERFORMER_H__
| 41.08589 | 80 | 0.744363 | [
"vector"
] |
837fdfa1c2144f51863c61864d8b050f5854b849 | 942 | h | C | Assignment 2/a_2/ModelerView.h | YangZhou91/MIT6.837 | cec3e55045823d4e63a38465c7e22ceb5fc4a3a3 | [
"MIT"
] | null | null | null | Assignment 2/a_2/ModelerView.h | YangZhou91/MIT6.837 | cec3e55045823d4e63a38465c7e22ceb5fc4a3a3 | [
"MIT"
] | null | null | null | Assignment 2/a_2/ModelerView.h | YangZhou91/MIT6.837 | cec3e55045823d4e63a38465c7e22ceb5fc4a3a3 | [
"MIT"
] | null | null | null | // modelerview.h
// This is the base class for your view window. It contains
// a camera control for your use. The draw() function will
// set up default lighting and apply the projection.
#ifndef MODELERVIEW_H
#define MODELERVIEW_H
#ifdef WIN32
#include <windows.h>
#endif
#include <FL/Fl_Gl_Window.H>
#include <GL/gl.h>
class Camera;
class ModelerView;
#include "SkeletalModel.h"
using namespace std;
class ModelerView : public Fl_Gl_Window
{
public:
ModelerView(int x, int y, int w, int h, const char *label = 0);
void loadModel(int argc, char* argv[]);
virtual ~ModelerView ();
virtual int handle(int event);
virtual void update();
virtual void draw();
void updateJoints();
void drawAxes();
Camera *m_camera;
SkeletalModel model;
bool m_drawAxes;
bool m_drawSkeleton; // if false, the mesh is drawn instead.
};
#endif /* */
| 18.84 | 68 | 0.654989 | [
"mesh",
"model"
] |
838e5cc25972f9faadc300bd3857db56edf0e0ed | 18,175 | h | C | Code/Editor/EditorEngineProcessFramework/EngineProcess/EngineProcessMessages.h | asheraryam/ezEngine | bfe6d109b72d8fd6f13d043b11980796625c648e | [
"MIT"
] | null | null | null | Code/Editor/EditorEngineProcessFramework/EngineProcess/EngineProcessMessages.h | asheraryam/ezEngine | bfe6d109b72d8fd6f13d043b11980796625c648e | [
"MIT"
] | null | null | null | Code/Editor/EditorEngineProcessFramework/EngineProcess/EngineProcessMessages.h | asheraryam/ezEngine | bfe6d109b72d8fd6f13d043b11980796625c648e | [
"MIT"
] | null | null | null | #pragma once
#include <EditorEngineProcessFramework/EditorEngineProcessFrameworkDLL.h>
#include <Foundation/Application/Config/FileSystemConfig.h>
#include <Foundation/Application/Config/PluginConfig.h>
#include <Foundation/Communication/RemoteMessage.h>
#include <Foundation/Logging/LogEntry.h>
#include <RendererCore/Pipeline/Declarations.h>
#include <ToolsFoundation/Object/DocumentObjectMirror.h>
#include <ToolsFoundation/Reflection/ReflectedType.h>
///////////////////////////////////// ezProcessMessages /////////////////////////////////////
///////////////////////////////////// Curator /////////////////////////////////////
class EZ_EDITORENGINEPROCESSFRAMEWORK_DLL ezProcessAssetMsg : public ezProcessMessage
{
EZ_ADD_DYNAMIC_REFLECTION(ezProcessAssetMsg, ezProcessMessage);
public:
ezUuid m_AssetGuid;
ezUInt64 m_AssetHash = 0;
ezUInt64 m_ThumbHash = 0;
ezString m_sAssetPath;
ezString m_sPlatform;
};
class EZ_EDITORENGINEPROCESSFRAMEWORK_DLL ezProcessAssetResponseMsg : public ezProcessMessage
{
EZ_ADD_DYNAMIC_REFLECTION(ezProcessAssetResponseMsg, ezProcessMessage);
public:
mutable ezDynamicArray<ezLogEntry> m_LogEntries;
bool m_bSuccess = false;
};
///////////////////////////////////// ezEditorEngineMsg /////////////////////////////////////
/// \brief Base class for all messages between editor and engine that are not bound to any document
class EZ_EDITORENGINEPROCESSFRAMEWORK_DLL ezEditorEngineMsg : public ezProcessMessage
{
EZ_ADD_DYNAMIC_REFLECTION(ezEditorEngineMsg, ezProcessMessage);
public:
ezEditorEngineMsg() {}
};
class EZ_EDITORENGINEPROCESSFRAMEWORK_DLL ezUpdateReflectionTypeMsgToEditor : public ezEditorEngineMsg
{
EZ_ADD_DYNAMIC_REFLECTION(ezUpdateReflectionTypeMsgToEditor, ezEditorEngineMsg);
public:
// Mutable because it is eaten up by ezPhantomRttiManager.
mutable ezReflectedTypeDescriptor m_desc;
};
class EZ_EDITORENGINEPROCESSFRAMEWORK_DLL ezSetupProjectMsgToEngine : public ezEditorEngineMsg
{
EZ_ADD_DYNAMIC_REFLECTION(ezSetupProjectMsgToEngine, ezEditorEngineMsg);
public:
ezString m_sProjectDir;
ezApplicationFileSystemConfig m_FileSystemConfig;
ezApplicationPluginConfig m_PluginConfig;
ezString m_sFileserveAddress; ///< Optionally used for remote processes to tell them with which IP address to connect to the host
ezString m_sAssetProfile;
};
/// \brief Sent to remote processes to shut them down.
/// Local processes are simply killed through QProcess::close, but remote processes have to close themselves.
class EZ_EDITORENGINEPROCESSFRAMEWORK_DLL ezShutdownProcessMsgToEngine : public ezEditorEngineMsg
{
EZ_ADD_DYNAMIC_REFLECTION(ezShutdownProcessMsgToEngine, ezEditorEngineMsg);
public:
};
class EZ_EDITORENGINEPROCESSFRAMEWORK_DLL ezProjectReadyMsgToEditor : public ezEditorEngineMsg
{
EZ_ADD_DYNAMIC_REFLECTION(ezProjectReadyMsgToEditor, ezEditorEngineMsg);
public:
};
class EZ_EDITORENGINEPROCESSFRAMEWORK_DLL ezSimpleConfigMsgToEngine : public ezEditorEngineMsg
{
EZ_ADD_DYNAMIC_REFLECTION(ezSimpleConfigMsgToEngine, ezEditorEngineMsg);
public:
ezString m_sWhatToDo;
ezString m_sPayload;
};
class EZ_EDITORENGINEPROCESSFRAMEWORK_DLL ezResourceUpdateMsgToEngine : public ezEditorEngineMsg
{
EZ_ADD_DYNAMIC_REFLECTION(ezResourceUpdateMsgToEngine, ezEditorEngineMsg);
public:
ezString m_sResourceType;
ezString m_sResourceID;
ezDataBuffer m_Data;
};
class EZ_EDITORENGINEPROCESSFRAMEWORK_DLL ezRestoreResourceMsgToEngine : public ezEditorEngineMsg
{
EZ_ADD_DYNAMIC_REFLECTION(ezRestoreResourceMsgToEngine, ezEditorEngineMsg);
public:
ezString m_sResourceType;
ezString m_sResourceID;
};
class EZ_EDITORENGINEPROCESSFRAMEWORK_DLL ezChangeCVarMsgToEngine : public ezEditorEngineMsg
{
EZ_ADD_DYNAMIC_REFLECTION(ezChangeCVarMsgToEngine, ezEditorEngineMsg);
public:
ezString m_sCVarName;
ezVariant m_NewValue;
};
///////////////////////////////////// ezEditorEngineDocumentMsg /////////////////////////////////////
/// \brief Base class for all messages that are tied to some document.
class EZ_EDITORENGINEPROCESSFRAMEWORK_DLL ezEditorEngineDocumentMsg : public ezProcessMessage
{
EZ_ADD_DYNAMIC_REFLECTION(ezEditorEngineDocumentMsg, ezProcessMessage);
public:
ezUuid m_DocumentGuid;
};
class EZ_EDITORENGINEPROCESSFRAMEWORK_DLL ezSimpleDocumentConfigMsgToEngine : public ezEditorEngineDocumentMsg
{
EZ_ADD_DYNAMIC_REFLECTION(ezSimpleDocumentConfigMsgToEngine, ezEditorEngineDocumentMsg);
public:
ezString m_sWhatToDo;
ezString m_sPayload;
};
class EZ_EDITORENGINEPROCESSFRAMEWORK_DLL ezSyncWithProcessMsgToEngine : public ezEditorEngineDocumentMsg
{
EZ_ADD_DYNAMIC_REFLECTION(ezSyncWithProcessMsgToEngine, ezEditorEngineDocumentMsg);
public:
ezUInt32 m_uiRedrawCount;
};
class EZ_EDITORENGINEPROCESSFRAMEWORK_DLL ezSyncWithProcessMsgToEditor : public ezEditorEngineDocumentMsg
{
EZ_ADD_DYNAMIC_REFLECTION(ezSyncWithProcessMsgToEditor, ezEditorEngineDocumentMsg);
public:
ezUInt32 m_uiRedrawCount;
};
class EZ_EDITORENGINEPROCESSFRAMEWORK_DLL ezEditorEngineViewMsg : public ezEditorEngineDocumentMsg
{
EZ_ADD_DYNAMIC_REFLECTION(ezEditorEngineViewMsg, ezEditorEngineDocumentMsg);
public:
ezEditorEngineViewMsg() { m_uiViewID = 0xFFFFFFFF; }
ezUInt32 m_uiViewID;
};
/// \brief For very simple uses cases where a custom message would be too much
class EZ_EDITORENGINEPROCESSFRAMEWORK_DLL ezDocumentConfigMsgToEngine : public ezEditorEngineDocumentMsg
{
EZ_ADD_DYNAMIC_REFLECTION(ezDocumentConfigMsgToEngine, ezEditorEngineDocumentMsg);
public:
ezString m_sWhatToDo;
int m_iValue;
float m_fValue;
ezString m_sValue;
};
class EZ_EDITORENGINEPROCESSFRAMEWORK_DLL ezDocumentOpenMsgToEngine : public ezEditorEngineDocumentMsg
{
EZ_ADD_DYNAMIC_REFLECTION(ezDocumentOpenMsgToEngine, ezEditorEngineDocumentMsg);
public:
ezDocumentOpenMsgToEngine() { m_bDocumentOpen = false; }
bool m_bDocumentOpen;
ezString m_sDocumentType;
};
/// \brief Used to reset the engine side to an empty document before sending the full document state over
class EZ_EDITORENGINEPROCESSFRAMEWORK_DLL ezDocumentClearMsgToEngine : public ezEditorEngineDocumentMsg
{
EZ_ADD_DYNAMIC_REFLECTION(ezDocumentClearMsgToEngine, ezEditorEngineDocumentMsg);
public:
ezDocumentClearMsgToEngine() {}
};
class EZ_EDITORENGINEPROCESSFRAMEWORK_DLL ezDocumentOpenResponseMsgToEditor : public ezEditorEngineDocumentMsg
{
EZ_ADD_DYNAMIC_REFLECTION(ezDocumentOpenResponseMsgToEditor, ezEditorEngineDocumentMsg);
public:
ezDocumentOpenResponseMsgToEditor() {}
};
class EZ_EDITORENGINEPROCESSFRAMEWORK_DLL ezViewDestroyedMsgToEngine : public ezEditorEngineViewMsg
{
EZ_ADD_DYNAMIC_REFLECTION(ezViewDestroyedMsgToEngine, ezEditorEngineViewMsg);
};
class EZ_EDITORENGINEPROCESSFRAMEWORK_DLL ezViewRedrawMsgToEngine : public ezEditorEngineViewMsg
{
EZ_ADD_DYNAMIC_REFLECTION(ezViewRedrawMsgToEngine, ezEditorEngineViewMsg);
public:
ezUInt64 m_uiHWND;
ezUInt16 m_uiWindowWidth;
ezUInt16 m_uiWindowHeight;
bool m_bUpdatePickingData;
bool m_bEnablePickingSelected;
bool m_bEnablePickTransparent;
bool m_bUseCameraTransformOnDevice = true;
ezInt8 m_iCameraMode; ///< ezCameraMode::Enum
float m_fNearPlane;
float m_fFarPlane;
float m_fFovOrDim;
ezUInt8 m_uiRenderMode; ///< ezViewRenderMode::Enum
ezVec3 m_vPosition;
ezVec3 m_vDirForwards;
ezVec3 m_vDirUp;
ezVec3 m_vDirRight;
ezMat4 m_ViewMatrix;
ezMat4 m_ProjMatrix;
};
class EZ_EDITORENGINEPROCESSFRAMEWORK_DLL ezViewScreenshotMsgToEngine : public ezEditorEngineViewMsg
{
EZ_ADD_DYNAMIC_REFLECTION(ezViewScreenshotMsgToEngine, ezEditorEngineViewMsg);
public:
ezString m_sOutputFile;
};
class EZ_EDITORENGINEPROCESSFRAMEWORK_DLL ezActivateRemoteViewMsgToEngine : public ezEditorEngineViewMsg
{
EZ_ADD_DYNAMIC_REFLECTION(ezActivateRemoteViewMsgToEngine, ezEditorEngineViewMsg);
public:
};
class EZ_EDITORENGINEPROCESSFRAMEWORK_DLL ezEntityMsgToEngine : public ezEditorEngineDocumentMsg
{
EZ_ADD_DYNAMIC_REFLECTION(ezEntityMsgToEngine, ezEditorEngineDocumentMsg);
public:
ezObjectChange m_change;
};
class EZ_EDITORENGINEPROCESSFRAMEWORK_DLL ezExportDocumentMsgToEngine : public ezEditorEngineDocumentMsg
{
EZ_ADD_DYNAMIC_REFLECTION(ezExportDocumentMsgToEngine, ezEditorEngineDocumentMsg);
public:
ezExportDocumentMsgToEngine()
: m_uiAssetHash(0)
, m_uiVersion(0)
{
}
ezString m_sOutputFile;
ezUInt64 m_uiAssetHash;
ezUInt16 m_uiVersion;
};
class EZ_EDITORENGINEPROCESSFRAMEWORK_DLL ezExportDocumentMsgToEditor : public ezEditorEngineDocumentMsg
{
EZ_ADD_DYNAMIC_REFLECTION(ezExportDocumentMsgToEditor, ezEditorEngineDocumentMsg);
public:
ezExportDocumentMsgToEditor()
: m_bOutputSuccess(false)
{
}
bool m_bOutputSuccess;
};
class EZ_EDITORENGINEPROCESSFRAMEWORK_DLL ezCreateThumbnailMsgToEngine : public ezEditorEngineDocumentMsg
{
EZ_ADD_DYNAMIC_REFLECTION(ezCreateThumbnailMsgToEngine, ezEditorEngineDocumentMsg);
public:
ezCreateThumbnailMsgToEngine()
: m_uiWidth(256)
, m_uiHeight(256)
{
}
ezUInt16 m_uiWidth;
ezUInt16 m_uiHeight;
};
class EZ_EDITORENGINEPROCESSFRAMEWORK_DLL ezCreateThumbnailMsgToEditor : public ezEditorEngineDocumentMsg
{
EZ_ADD_DYNAMIC_REFLECTION(ezCreateThumbnailMsgToEditor, ezEditorEngineDocumentMsg);
public:
ezCreateThumbnailMsgToEditor() {}
ezDataBuffer m_ThumbnailData; ///< Raw 8-bit RGBA data (256x256x4 bytes)
};
class EZ_EDITORENGINEPROCESSFRAMEWORK_DLL ezViewPickingMsgToEngine : public ezEditorEngineViewMsg
{
EZ_ADD_DYNAMIC_REFLECTION(ezViewPickingMsgToEngine, ezEditorEngineViewMsg);
public:
ezUInt16 m_uiPickPosX;
ezUInt16 m_uiPickPosY;
};
class EZ_EDITORENGINEPROCESSFRAMEWORK_DLL ezViewPickingResultMsgToEditor : public ezEditorEngineViewMsg
{
EZ_ADD_DYNAMIC_REFLECTION(ezViewPickingResultMsgToEditor, ezEditorEngineViewMsg);
public:
ezUuid m_ObjectGuid;
ezUuid m_ComponentGuid;
ezUuid m_OtherGuid;
ezUInt32 m_uiPartIndex;
ezVec3 m_vPickedPosition;
ezVec3 m_vPickedNormal;
ezVec3 m_vPickingRayStartPosition;
};
class EZ_EDITORENGINEPROCESSFRAMEWORK_DLL ezViewMarqueePickingMsgToEngine : public ezEditorEngineViewMsg
{
EZ_ADD_DYNAMIC_REFLECTION(ezViewMarqueePickingMsgToEngine, ezEditorEngineViewMsg);
public:
ezUInt16 m_uiPickPosX0;
ezUInt16 m_uiPickPosY0;
ezUInt16 m_uiPickPosX1;
ezUInt16 m_uiPickPosY1;
ezUInt8 m_uiWhatToDo; // 0 == select, 1 == add, 2 == remove
ezUInt32 m_uiActionIdentifier;
};
class EZ_EDITORENGINEPROCESSFRAMEWORK_DLL ezViewMarqueePickingResultMsgToEditor : public ezEditorEngineViewMsg
{
EZ_ADD_DYNAMIC_REFLECTION(ezViewMarqueePickingResultMsgToEditor, ezEditorEngineViewMsg);
public:
ezDynamicArray<ezUuid> m_ObjectGuids;
ezUInt8 m_uiWhatToDo; // 0 == select, 1 == add, 2 == remove
ezUInt32 m_uiActionIdentifier;
};
class ezEditorEngineConnection;
class EZ_EDITORENGINEPROCESSFRAMEWORK_DLL ezViewHighlightMsgToEngine : public ezEditorEngineDocumentMsg
{
EZ_ADD_DYNAMIC_REFLECTION(ezViewHighlightMsgToEngine, ezEditorEngineDocumentMsg);
public:
ezUuid m_HighlightObject;
// currently used for highlighting which object the mouse hovers over
// extend this message if other types of highlighting become necessary
};
class EZ_EDITORENGINEPROCESSFRAMEWORK_DLL ezLogMsgToEditor : public ezEditorEngineMsg
{
EZ_ADD_DYNAMIC_REFLECTION(ezLogMsgToEditor, ezEditorEngineMsg);
public:
ezLogEntry m_Entry;
};
class EZ_EDITORENGINEPROCESSFRAMEWORK_DLL ezCVarMsgToEditor : public ezEditorEngineMsg
{
EZ_ADD_DYNAMIC_REFLECTION(ezCVarMsgToEditor, ezEditorEngineMsg);
public:
ezString m_sName;
ezString m_sPlugin;
ezString m_sDescription;
ezVariant m_Value;
};
class EZ_EDITORENGINEPROCESSFRAMEWORK_DLL ezLongOpReplicationMsg : public ezEditorEngineMsg
{
EZ_ADD_DYNAMIC_REFLECTION(ezLongOpReplicationMsg, ezEditorEngineMsg);
public:
ezUuid m_OperationGuid;
ezUuid m_DocumentGuid;
ezString m_sReplicationType;
ezDataBuffer m_ReplicationData;
};
class EZ_EDITORENGINEPROCESSFRAMEWORK_DLL ezLongOpProgressMsg : public ezEditorEngineMsg
{
EZ_ADD_DYNAMIC_REFLECTION(ezLongOpProgressMsg, ezEditorEngineMsg);
public:
ezUuid m_OperationGuid;
float m_fCompletion;
};
class EZ_EDITORENGINEPROCESSFRAMEWORK_DLL ezLongOpResultMsg : public ezEditorEngineMsg
{
EZ_ADD_DYNAMIC_REFLECTION(ezLongOpResultMsg, ezEditorEngineMsg);
public:
ezUuid m_OperationGuid;
bool m_bSuccess;
ezDataBuffer m_ResultData;
};
class EZ_EDITORENGINEPROCESSFRAMEWORK_DLL ezEditorEngineSyncObjectMsg : public ezEditorEngineDocumentMsg
{
EZ_ADD_DYNAMIC_REFLECTION(ezEditorEngineSyncObjectMsg, ezEditorEngineDocumentMsg);
public:
ezUuid m_ObjectGuid;
ezString m_sObjectType;
ezDataBuffer m_ObjectData;
const ezDataBuffer& GetObjectData() const { return m_ObjectData; }
void SetObjectData(const ezDataBuffer& s) { m_ObjectData = s; }
};
class EZ_EDITORENGINEPROCESSFRAMEWORK_DLL ezObjectTagMsgToEngine : public ezEditorEngineDocumentMsg
{
EZ_ADD_DYNAMIC_REFLECTION(ezObjectTagMsgToEngine, ezEditorEngineDocumentMsg);
public:
ezObjectTagMsgToEngine()
{
m_bSetTag = false;
m_bApplyOnAllChildren = false;
}
ezUuid m_ObjectGuid;
ezString m_sTag;
bool m_bSetTag;
bool m_bApplyOnAllChildren;
};
class EZ_EDITORENGINEPROCESSFRAMEWORK_DLL ezObjectSelectionMsgToEngine : public ezEditorEngineDocumentMsg
{
EZ_ADD_DYNAMIC_REFLECTION(ezObjectSelectionMsgToEngine, ezEditorEngineDocumentMsg);
public:
ezString m_sSelection;
};
class EZ_EDITORENGINEPROCESSFRAMEWORK_DLL ezSimulationSettingsMsgToEngine : public ezEditorEngineDocumentMsg
{
EZ_ADD_DYNAMIC_REFLECTION(ezSimulationSettingsMsgToEngine, ezEditorEngineDocumentMsg);
public:
bool m_bSimulateWorld = false;
float m_fSimulationSpeed = 1.0f;
};
class EZ_EDITORENGINEPROCESSFRAMEWORK_DLL ezGridSettingsMsgToEngine : public ezEditorEngineDocumentMsg
{
EZ_ADD_DYNAMIC_REFLECTION(ezGridSettingsMsgToEngine, ezEditorEngineDocumentMsg);
public:
float m_fGridDensity = 0.0f;
ezVec3 m_vGridCenter;
ezVec3 m_vGridTangent1;
ezVec3 m_vGridTangent2;
};
class EZ_EDITORENGINEPROCESSFRAMEWORK_DLL ezGlobalSettingsMsgToEngine : public ezEditorEngineDocumentMsg
{
EZ_ADD_DYNAMIC_REFLECTION(ezGlobalSettingsMsgToEngine, ezEditorEngineDocumentMsg);
public:
float m_fGizmoScale = 0.0f;
};
class EZ_EDITORENGINEPROCESSFRAMEWORK_DLL ezWorldSettingsMsgToEngine : public ezEditorEngineDocumentMsg
{
EZ_ADD_DYNAMIC_REFLECTION(ezWorldSettingsMsgToEngine, ezEditorEngineDocumentMsg);
public:
bool m_bRenderOverlay = false;
bool m_bRenderShapeIcons = false;
bool m_bRenderSelectionBoxes = false;
bool m_bAddAmbientLight = false;
};
class EZ_EDITORENGINEPROCESSFRAMEWORK_DLL ezGameModeMsgToEngine : public ezEditorEngineDocumentMsg
{
EZ_ADD_DYNAMIC_REFLECTION(ezGameModeMsgToEngine, ezEditorEngineDocumentMsg);
public:
bool m_bEnablePTG = false;
bool m_bUseStartPosition = false;
ezVec3 m_vStartPosition;
ezVec3 m_vStartDirection;
};
class EZ_EDITORENGINEPROCESSFRAMEWORK_DLL ezGameModeMsgToEditor : public ezEditorEngineDocumentMsg
{
EZ_ADD_DYNAMIC_REFLECTION(ezGameModeMsgToEditor, ezEditorEngineDocumentMsg);
public:
bool m_bRunningPTG;
};
class EZ_EDITORENGINEPROCESSFRAMEWORK_DLL ezQuerySelectionBBoxMsgToEngine : public ezEditorEngineDocumentMsg
{
EZ_ADD_DYNAMIC_REFLECTION(ezQuerySelectionBBoxMsgToEngine, ezEditorEngineDocumentMsg);
public:
ezUInt32 m_uiViewID; /// passed through to ezQuerySelectionBBoxResultMsgToEditor
ezInt32 m_iPurpose; /// passed through to ezQuerySelectionBBoxResultMsgToEditor
};
class EZ_EDITORENGINEPROCESSFRAMEWORK_DLL ezQuerySelectionBBoxResultMsgToEditor : public ezEditorEngineDocumentMsg
{
EZ_ADD_DYNAMIC_REFLECTION(ezQuerySelectionBBoxResultMsgToEditor, ezEditorEngineDocumentMsg);
public:
ezVec3 m_vCenter;
ezVec3 m_vHalfExtents;
ezUInt32 m_uiViewID; /// passed through from ezQuerySelectionBBoxMsgToEngine
ezInt32 m_iPurpose; /// passed through from ezQuerySelectionBBoxMsgToEngine
};
/// \brief Send by the runtime scene whenever a visual script with debug output enabled does anything.
class EZ_EDITORENGINEPROCESSFRAMEWORK_DLL ezVisualScriptActivityMsgToEditor : public ezEditorEngineDocumentMsg
{
EZ_ADD_DYNAMIC_REFLECTION(ezVisualScriptActivityMsgToEditor, ezEditorEngineDocumentMsg);
public:
ezUuid m_ComponentGuid;
ezDataBuffer m_Activity;
};
/// \brief Send between editor documents, such that one document can know about objects in another document.
class EZ_EDITORENGINEPROCESSFRAMEWORK_DLL ezGatherObjectsOfTypeMsgInterDoc : public ezReflectedClass
{
EZ_ADD_DYNAMIC_REFLECTION(ezGatherObjectsOfTypeMsgInterDoc, ezReflectedClass);
public:
const ezRTTI* m_pType;
struct Result
{
const ezDocument* m_pDocument;
ezUuid m_ObjectGuid;
ezString m_sDisplayName;
};
ezDynamicArray<Result> m_Results;
};
/// Send by the editor scene document to all other editor documents, to gather on which objects debug visualization should be enabled during
/// play-the-game.
class EZ_EDITORENGINEPROCESSFRAMEWORK_DLL ezGatherObjectsForDebugVisMsgInterDoc : public ezReflectedClass
{
EZ_ADD_DYNAMIC_REFLECTION(ezGatherObjectsForDebugVisMsgInterDoc, ezReflectedClass);
public:
ezDynamicArray<ezUuid> m_Objects;
};
/// Send by the editor scene document to the runtime scene document, to tell it about the poll results (see ezGatherObjectsForDebugVisMsgInterDoc).
class EZ_EDITORENGINEPROCESSFRAMEWORK_DLL ezObjectsForDebugVisMsgToEngine : public ezEditorEngineDocumentMsg
{
EZ_ADD_DYNAMIC_REFLECTION(ezObjectsForDebugVisMsgToEngine, ezEditorEngineDocumentMsg);
public:
ezDataBuffer m_Objects;
};
| 30.701014 | 148 | 0.799945 | [
"object"
] |
838ecd423e9201c96f8d8504a19c455a378a4b85 | 2,377 | h | C | module/param.h | papan-singh/cortx-motr-1 | 79351a56dffcb3968db9a6d4fee685a5443ed2f7 | [
"Apache-2.0"
] | 45 | 2020-09-25T09:33:23.000Z | 2022-02-23T02:54:10.000Z | module/param.h | mbcortx/cortx-motr | 8d45476d627d0f82047e88dff317db64cc142f58 | [
"Apache-2.0"
] | 1,057 | 2020-09-24T15:29:24.000Z | 2022-03-31T20:48:17.000Z | module/param.h | mbcortx/cortx-motr | 8d45476d627d0f82047e88dff317db64cc142f58 | [
"Apache-2.0"
] | 178 | 2020-09-24T13:38:26.000Z | 2022-03-31T07:50:58.000Z | /*
* Copyright (c) 2014-2020 Seagate Technology LLC and/or its Affiliates
*
* 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.
*
* For any questions about this software or licensing,
* please email opensource@seagate.com or cortx-questions@seagate.com.
*
*/
#pragma once
#ifndef __MOTR_MODULE_PARAM_H__
#define __MOTR_MODULE_PARAM_H__
#include "lib/tlist.h" /* m0_tlink */
/**
* @addtogroup module
*
* m0_param API is used to configure initialisation: Motr modules use
* m0_param_get() to obtain external information.
*
* @{
*/
/**
* Obtains the value of parameter associated with given key.
* Returns NULL if no such value exists or an error occurs.
*/
M0_INTERNAL void *m0_param_get(const char *key);
/**
* Source of parameters.
*
* Some (but not all) possible sources of parameters are:
*
* - "env": ->ps_param_get() uses getenv(3) to obtain the values of
* environment variables;
*
* - "kv pairs": ->ps_param_get() scans a set of KV pairs, which is
* accessible through an object ambient to m0_param_source;
*
* - "confc": ->ps_param_get() translates the key into confc path
* (a sequence of m0_fids) and accesses conf object and/or its field;
*
* - "argv": ->ps_param_get() looks for `-K key=val' in argv[]
* and returns the pointer to `val'.
*/
struct m0_param_source {
void *(*ps_param_get)(const struct m0_param_source *src,
const char *key);
/** Linkage to m0::i_param_sources. */
struct m0_tlink ps_link;
uint64_t ps_magic;
};
M0_TL_DECLARE(m0_param_sources, M0_INTERNAL, struct m0_param_source);
/** Appends new element to m0::i_param_sources. */
M0_INTERNAL void m0_param_source_add(struct m0_param_source *src);
/** Deletes `src' from m0::i_param_sources. */
M0_INTERNAL void m0_param_source_del(struct m0_param_source *src);
/** @} module */
#endif /* __MOTR_MODULE_PARAM_H__ */
| 30.87013 | 75 | 0.717291 | [
"object"
] |
838f527a60e1ece4f392783177adfe86981fc427 | 6,714 | h | C | src/cascade/verilog/analyze/resolve.h | 3Nigma/cascade | 44f7cf20719822f2cba5df7065083a15db217c30 | [
"BSD-2-Clause"
] | 425 | 2018-10-17T19:47:32.000Z | 2021-06-16T18:03:08.000Z | src/cascade/verilog/analyze/resolve.h | 3Nigma/cascade | 44f7cf20719822f2cba5df7065083a15db217c30 | [
"BSD-2-Clause"
] | 196 | 2018-09-17T20:42:33.000Z | 2020-05-15T00:00:24.000Z | src/cascade/verilog/analyze/resolve.h | 3Nigma/cascade | 44f7cf20719822f2cba5df7065083a15db217c30 | [
"BSD-2-Clause"
] | 39 | 2018-11-07T21:16:21.000Z | 2021-06-08T16:24:12.000Z | // Copyright 2017-2019 VMware, Inc.
// SPDX-License-Identifier: BSD-2-Clause
//
// The BSD-2 license (the License) set forth below applies to all parts of the
// Cascade project. You may not use this file except in compliance with the
// License.
//
// BSD-2 License
//
// 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 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.
#ifndef CASCADE_SRC_VERILOG_ANALYZE_RESOLVE_H
#define CASCADE_SRC_VERILOG_ANALYZE_RESOLVE_H
#include <string>
#include "common/vector.h"
#include "verilog/ast/visitors/editor.h"
namespace cascade {
// This class is used to associate variable uses with their declarations in the
// AST. This class attaches decorations to the AST to reduce the overhead of
// repeated invocations and relies on up-to-date scope decorations (see
// navigate.h). If the decorations associated with a scope are invalidated or
// if the variables within a scope are transformed in any way, this class must
// invalidate the resolution decorations for any variables that refer to that
// scope before it will work correctly.
class Resolve {
public:
// Typedefs:
typedef typename Vector<const Expression*>::const_iterator use_iterator;
// Cache Maintenance:
//
// Removes dependency references for this node and all of the nodes below
// it in the AST.
void invalidate(const Node* n);
// Resolution:
//
// Returns a pointer to the declaration of this variable. Returns nullptr
// on failure.
const Identifier* get_resolution(const Identifier* id);
// Returns the fully-qualified name of this variable. For example, eg
// get_full_id(x) might return root.f[0].x. The caller of this method
// takes responsibility for the resulting memory.
Identifier* get_full_id(const Identifier* id);
// Convenience method. Converts an id to a full id, transforms it to a
// string and deletes the intermediate memory.
std::string get_readable_full_id(const Identifier* id);
// Returns a pointer to the ModuleDeclaration that this identifier appears
// in. Returns nullptr on failure. For example, for variables that are not
// part of the AST.
const ModuleDeclaration* get_parent(const Identifier* id);
// Returns a pointer to the ModuleDeclaration that this identifier was
// declared in. Equivalent to calling get_origin(get_resolution(id)).
const ModuleDeclaration* get_origin(const Identifier* id);
// Variable Properties:
//
// Returns true if this variable contains a slicing subscript. This method
// is undefined for identifiers which cannot be resolved.
bool is_slice(const Identifier* id);
// Returns true for any variable which does not resolve to itself (ie a
// reference) or a variable which is part of a scalar declaration.
bool is_scalar(const Identifier* id);
// Returns false for any variable which does not resolve to itself (ie a
// reference) or true for a variable which is part of an array
// declaration.
bool is_array(const Identifier* id);
// Iterators Interface:
//
// Iterators over the set of expressions that refer to this variable. For
// example, the expression i+1 uses the value of i. Invoking this method on
// a variable which cannot be resolved is undefined.
use_iterator use_begin(const Identifier* id);
use_iterator use_end(const Identifier* id);
private:
// Cached accessor helpers:
const Identifier* cache_resolution(const Identifier* id);
void cache_uses(const Declaration* d);
// Examines every declaration below this node and inserts an empty use set
struct InitCacheUses : Editor {
~InitCacheUses() override = default;
void edit(CaseGenerateConstruct* cgc) override;
void edit(IfGenerateConstruct* igc) override;
void edit(LoopGenerateConstruct* lgc) override;
void edit(GenvarDeclaration* gd) override;
void edit(LocalparamDeclaration* ld) override;
void edit(NetDeclaration* nd) override;
void edit(ParameterDeclaration* pd) override;
void edit(RegDeclaration* rd) override;
void edit(ModuleInstantiation* mi) override;
};
// Populates use sets
struct CacheUses : Editor {
~CacheUses() override = default;
void edit(Attributes* as) override;
void edit(Identifier* i) override;
void edit(CaseGenerateConstruct* cgc) override;
void edit(IfGenerateConstruct* igc) override;
void edit(LoopGenerateConstruct* lgc) override;
void edit(GenvarDeclaration* gd) override;
void edit(LocalparamDeclaration* ld) override;
void edit(NetDeclaration* nd) override;
void edit(ParameterDeclaration* pd) override;
void edit(RegDeclaration* rd) override;
void edit(ModuleInstantiation* mi) override;
};
// Invalidation cache information:
struct Invalidate : Editor {
~Invalidate() override = default;
void edit(Attributes* as) override;
void edit(Identifier* id) override;
void edit(CaseGenerateConstruct* cgc) override;
void edit(IfGenerateConstruct* igc) override;
void edit(LoopGenerateConstruct* lgc) override;
void edit(GenvarDeclaration* gd) override;
void edit(LocalparamDeclaration* ld) override;
void edit(NetDeclaration* nd) override;
void edit(ParameterDeclaration* pd) override;
void edit(RegDeclaration* rd) override;
void edit(ModuleInstantiation* mi) override;
};
};
} // namespace cascade
#endif
| 43.882353 | 81 | 0.731606 | [
"vector"
] |
839675ba9639c3c170e4e89a972a02e3c617fec9 | 1,965 | h | C | Graphics-Engine/Graphics-Engine/libraries/MyMath/Quaternion/Quaternion.h | Hernibyte/TSDV_Graphics-Engine-2D | 4c6aeaf0eb33a98ab4812101f7db97d45ae525cf | [
"MIT"
] | null | null | null | Graphics-Engine/Graphics-Engine/libraries/MyMath/Quaternion/Quaternion.h | Hernibyte/TSDV_Graphics-Engine-2D | 4c6aeaf0eb33a98ab4812101f7db97d45ae525cf | [
"MIT"
] | null | null | null | Graphics-Engine/Graphics-Engine/libraries/MyMath/Quaternion/Quaternion.h | Hernibyte/TSDV_Graphics-Engine-2D | 4c6aeaf0eb33a98ab4812101f7db97d45ae525cf | [
"MIT"
] | null | null | null | #ifndef QUATERNION_H
#define QUATERNION_H
#include "../MathEx/MathEx.h"
#include "../Vector3/vector3.h"
using namespace My;
namespace My
{
struct Quaternion
{
float x;
float y;
float z;
float w;
float Get(int index);
void Set(int index, float value);
static Quaternion identity;
Quaternion Normalized();
Vector3 EulerAngles();
void EulerAngles(Vector3 value);
Quaternion();
Quaternion(float x, float y, float z, float w);
Quaternion(const Quaternion& quaternion);
Quaternion(Vector3 vector, float w);
void Set(float x, float y, float z, float w);
void Set(Quaternion quaternion);
void Normalize();
void SetFromToRotation(Vector3 fromDirection, Vector3 toDirection);
void SetLookRotation(Vector3 view);
void SetLookRotation(Vector3 view, Vector3 up);
//void ToAngleAxis();
//Static methods
static float Angle(Quaternion a, Quaternion b);
static Quaternion AngleAxis(float angle, Vector3 axis);
static float Dot(Quaternion a, Quaternion b);
static Quaternion Euler(Vector3 euler);
static Quaternion FromToRotation(Vector3 fromDirection, Vector3 toDirection);
static Quaternion Inverse(Quaternion& rotation);
static Quaternion Lerp(Quaternion a, Quaternion b, float t);
static Quaternion LerpUnclamped(Quaternion a, Quaternion b, float t);
static Quaternion LookRotation(Vector3 forward);
static Quaternion LookRotation(Vector3& forward, Vector3& up);
static Quaternion Normalize(Quaternion& quaternion);
static Quaternion RotateTowards(Quaternion from, Quaternion to, float maxDegreesDelta);
static Quaternion Slerp(Quaternion a, Quaternion b, float t);
static Quaternion SlerpUnclamped(Quaternion a, Quaternion b, float t);
// Operators
};
//Vector3 operator*(Quaternion a, Quaternion b);
Quaternion operator*(Quaternion a, Quaternion b);
bool operator==(Quaternion a, Quaternion b);
bool operator!=(Quaternion a, Quaternion b);
}
#endif // !QUATERNION_H
| 23.674699 | 89 | 0.747074 | [
"vector"
] |
83a10488e0c3f86c97b4dca8f22ec818182e02ba | 7,797 | h | C | Android/NDK/android-ndk-r20b-win/toolchains/llvm/prebuilt/windows-x86_64/sysroot/usr/include/android/binder_interface_utils.h | X018/CCTOOL | 989af4d7edab82bf540400eb72eca4e7447d722c | [
"MIT"
] | 5 | 2020-12-17T06:55:53.000Z | 2021-09-30T13:06:58.000Z | Android/NDK/android-ndk-r20b-win/toolchains/llvm/prebuilt/windows-x86_64/sysroot/usr/include/android/binder_interface_utils.h | X018/CCTOOL | 989af4d7edab82bf540400eb72eca4e7447d722c | [
"MIT"
] | 1 | 2022-01-04T21:53:07.000Z | 2022-03-30T11:16:05.000Z | Android/NDK/android-ndk-r20b-win/toolchains/llvm/prebuilt/windows-x86_64/sysroot/usr/include/android/binder_interface_utils.h | X018/CCTOOL | 989af4d7edab82bf540400eb72eca4e7447d722c | [
"MIT"
] | 8 | 2020-09-30T10:06:31.000Z | 2022-03-29T21:17:21.000Z | /*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @addtogroup NdkBinder
* @{
*/
/**
* @file binder_interface_utils.h
* @brief This provides common C++ classes for common operations and as base classes for C++
* interfaces.
*/
#pragma once
#include <android/binder_auto_utils.h>
#include <android/binder_ibinder.h>
#include <assert.h>
#include <memory>
#include <mutex>
namespace ndk {
/**
* analog using std::shared_ptr for internally held refcount
*
* ref must be called at least one time during the lifetime of this object. The recommended way to
* construct this object is with SharedRefBase::make.
*/
class SharedRefBase {
public:
SharedRefBase() {}
virtual ~SharedRefBase() {
std::call_once(mFlagThis, [&]() {
__assert(__FILE__, __LINE__, "SharedRefBase: no ref created during lifetime");
});
}
/**
* A shared_ptr must be held to this object when this is called. This must be called once during
* the lifetime of this object.
*/
std::shared_ptr<SharedRefBase> ref() {
std::shared_ptr<SharedRefBase> thiz = mThis.lock();
std::call_once(mFlagThis, [&]() { mThis = thiz = std::shared_ptr<SharedRefBase>(this); });
return thiz;
}
/**
* Convenience method for a ref (see above) which automatically casts to the desired child type.
*/
template <typename CHILD>
std::shared_ptr<CHILD> ref() {
return std::static_pointer_cast<CHILD>(ref());
}
/**
* Convenience method for making an object directly with a reference.
*/
template <class T, class... Args>
static std::shared_ptr<T> make(Args&&... args) {
T* t = new T(std::forward<Args>(args)...);
return t->template ref<T>();
}
private:
std::once_flag mFlagThis;
std::weak_ptr<SharedRefBase> mThis;
};
/**
* wrapper analog to IInterface
*/
class ICInterface : public SharedRefBase {
public:
ICInterface() {}
virtual ~ICInterface() {}
/**
* This either returns the single existing implementation or creates a new implementation.
*/
virtual SpAIBinder asBinder() = 0;
/**
* Returns whether this interface is in a remote process. If it cannot be determined locally,
* this will be checked using AIBinder_isRemote.
*/
virtual bool isRemote() = 0;
/**
* Dumps information about the interface. By default, dumps nothing.
*/
virtual inline binder_status_t dump(int /*fd*/, const char** /*args*/, uint32_t /*numArgs*/);
/**
* Interprets this binder as this underlying interface if this has stored an ICInterface in the
* binder's user data.
*
* This does not do type checking and should only be used when the binder is known to originate
* from ICInterface. Most likely, you want to use I*::fromBinder.
*/
static inline std::shared_ptr<ICInterface> asInterface(AIBinder* binder);
/**
* Helper method to create a class
*/
static inline AIBinder_Class* defineClass(const char* interfaceDescriptor,
AIBinder_Class_onTransact onTransact);
private:
class ICInterfaceData {
public:
std::shared_ptr<ICInterface> interface;
static inline std::shared_ptr<ICInterface> getInterface(AIBinder* binder);
static inline void* onCreate(void* args);
static inline void onDestroy(void* userData);
static inline binder_status_t onDump(AIBinder* binder, int fd, const char** args,
uint32_t numArgs);
};
};
/**
* implementation of IInterface for server (n = native)
*/
template <typename INTERFACE>
class BnCInterface : public INTERFACE {
public:
BnCInterface() {}
virtual ~BnCInterface() {}
SpAIBinder asBinder() override;
bool isRemote() override { return false; }
protected:
/**
* This function should only be called by asBinder. Otherwise, there is a possibility of
* multiple AIBinder* objects being created for the same instance of an object.
*/
virtual SpAIBinder createBinder() = 0;
private:
std::mutex mMutex; // for asBinder
ScopedAIBinder_Weak mWeakBinder;
};
/**
* implementation of IInterface for client (p = proxy)
*/
template <typename INTERFACE>
class BpCInterface : public INTERFACE {
public:
explicit BpCInterface(const SpAIBinder& binder) : mBinder(binder) {}
virtual ~BpCInterface() {}
SpAIBinder asBinder() override;
bool isRemote() override { return AIBinder_isRemote(mBinder.get()); }
binder_status_t dump(int fd, const char** args, uint32_t numArgs) override {
return AIBinder_dump(asBinder().get(), fd, args, numArgs);
}
private:
SpAIBinder mBinder;
};
// END OF CLASS DECLARATIONS
binder_status_t ICInterface::dump(int /*fd*/, const char** /*args*/, uint32_t /*numArgs*/) {
return STATUS_OK;
}
std::shared_ptr<ICInterface> ICInterface::asInterface(AIBinder* binder) {
return ICInterfaceData::getInterface(binder);
}
AIBinder_Class* ICInterface::defineClass(const char* interfaceDescriptor,
AIBinder_Class_onTransact onTransact) {
AIBinder_Class* clazz = AIBinder_Class_define(interfaceDescriptor, ICInterfaceData::onCreate,
ICInterfaceData::onDestroy, onTransact);
if (clazz == nullptr) {
return nullptr;
}
// We can't know if this method is overriden by a subclass interface, so we must register
// ourselves. The default (nothing to dump) is harmless.
AIBinder_Class_setOnDump(clazz, ICInterfaceData::onDump);
return clazz;
}
std::shared_ptr<ICInterface> ICInterface::ICInterfaceData::getInterface(AIBinder* binder) {
if (binder == nullptr) return nullptr;
void* userData = AIBinder_getUserData(binder);
if (userData == nullptr) return nullptr;
return static_cast<ICInterfaceData*>(userData)->interface;
}
void* ICInterface::ICInterfaceData::onCreate(void* args) {
std::shared_ptr<ICInterface> interface = static_cast<ICInterface*>(args)->ref<ICInterface>();
ICInterfaceData* data = new ICInterfaceData{interface};
return static_cast<void*>(data);
}
void ICInterface::ICInterfaceData::onDestroy(void* userData) {
delete static_cast<ICInterfaceData*>(userData);
}
binder_status_t ICInterface::ICInterfaceData::onDump(AIBinder* binder, int fd, const char** args,
uint32_t numArgs) {
std::shared_ptr<ICInterface> interface = getInterface(binder);
return interface->dump(fd, args, numArgs);
}
template <typename INTERFACE>
SpAIBinder BnCInterface<INTERFACE>::asBinder() {
std::lock_guard<std::mutex> l(mMutex);
SpAIBinder binder;
if (mWeakBinder.get() != nullptr) {
binder.set(AIBinder_Weak_promote(mWeakBinder.get()));
}
if (binder.get() == nullptr) {
binder = createBinder();
mWeakBinder.set(AIBinder_Weak_new(binder.get()));
}
return binder;
}
template <typename INTERFACE>
SpAIBinder BpCInterface<INTERFACE>::asBinder() {
return mBinder;
}
} // namespace ndk
/** @} */
| 29.873563 | 100 | 0.666538 | [
"object"
] |
83a33f3f30ba64e4cf86cfbf2070efefa290b5e6 | 11,664 | h | C | include/sys/cbprintf.h | tomaszkob89/sdk-zephyr | a9423cbce69a5df78140a2cf3ba11aa56d395cfc | [
"Apache-2.0"
] | 1 | 2021-07-14T12:48:13.000Z | 2021-07-14T12:48:13.000Z | include/sys/cbprintf.h | tomaszkob89/sdk-zephyr | a9423cbce69a5df78140a2cf3ba11aa56d395cfc | [
"Apache-2.0"
] | 4 | 2022-03-10T10:11:21.000Z | 2022-03-21T11:41:17.000Z | include/sys/cbprintf.h | tomaszkob89/sdk-zephyr | a9423cbce69a5df78140a2cf3ba11aa56d395cfc | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2020 Nordic Semiconductor ASA
*
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef ZEPHYR_INCLUDE_SYS_CBPRINTF_H_
#define ZEPHYR_INCLUDE_SYS_CBPRINTF_H_
#include <stdarg.h>
#include <stddef.h>
#include <stdint.h>
#include <toolchain.h>
#ifdef CONFIG_CBPRINTF_LIBC_SUBSTS
#include <stdio.h>
#endif /* CONFIG_CBPRINTF_LIBC_SUBSTS */
#ifdef __cplusplus
extern "C" {
#endif
/**
* @defgroup cbprintf_apis Formatted Output APIs
* @ingroup support_apis
* @{
*/
/** @brief Signature for a cbprintf callback function.
*
* This function expects two parameters:
*
* * @p c a character to output. The output behavior should be as if
* this was cast to an unsigned char.
* * @p ctx a pointer to an object that provides context for the
* output operation.
*
* The declaration does not specify the parameter types. This allows a
* function like @c fputc to be used without requiring all context pointers to
* be to a @c FILE object.
*
* @return the value of @p c cast to an unsigned char then back to
* int, or a negative error code that will be returned from
* cbprintf().
*/
typedef int (*cbprintf_cb)(/* int c, void *ctx */);
/** @brief Capture state required to output formatted data later.
*
* Like cbprintf() but instead of processing the arguments and emitting the
* formatted results immediately all arguments are captured so this can be
* done in a different context, e.g. when the output function can block.
*
* In addition to the values extracted from arguments this will ensure that
* copies are made of the necessary portions of any string parameters that are
* not confirmed to be stored in read-only memory (hence assumed to be safe to
* refer to directly later).
*
* @param packaged pointer to where the packaged data can be stored. Pass a
* null pointer to store nothing but still calculate the total space required.
* The data stored here is relocatable, that is it can be moved to another
* contiguous block of memory. The pointer must be aligned to a multiple of
* the largest element in the argument list.
*
* @param len this must be set to the number of bytes available at @p packaged.
* Ignored if @p packaged is NULL.
*
* @param format a standard ISO C format string with characters and conversion
* specifications.
*
* @param ... arguments corresponding to the conversion specifications found
* within @p format.
*
* @retval nonegative the number of bytes successfully stored at @p packaged.
* This will not exceed @p len.
* @retval -EINVAL if @p format is not acceptable
* @retval -ENOSPC if @p packaged was not null and the space required to store
* exceed @p len.
*/
__printf_like(3, 4)
int cbprintf_package(void *packaged,
size_t len,
const char *format,
...);
/** @brief Capture state required to output formatted data later.
*
* Like cbprintf() but instead of processing the arguments and emitting the
* formatted results immediately all arguments are captured so this can be
* done in a different context, e.g. when the output function can block.
*
* In addition to the values extracted from arguments this will ensure that
* copies are made of the necessary portions of any string parameters that are
* not confirmed to be stored in read-only memory (hence assumed to be safe to
* refer to directly later).
*
* @param packaged pointer to where the packaged data can be stored. Pass a
* null pointer to store nothing but still calculate the total space required.
* The data stored here is relocatable, that is it can be moved to another
* contiguous block of memory. The pointer must be aligned to a multiple of
* the largest element in the argument list.
*
* @param len this must be set to the number of bytes available at @p packaged.
* Ignored if @p packaged is NULL.
*
* @param format a standard ISO C format string with characters and conversion
* specifications.
*
* @param ap captured stack arguments corresponding to the conversion
* specifications found within @p format.
*
* @retval nonegative the number of bytes successfully stored at @p packaged.
* This will not exceed @p len.
* @retval -EINVAL if @p format is not acceptable
* @retval -ENOSPC if @p packaged was not null and the space required to store
* exceed @p len.
*/
int cbvprintf_package(void *packaged,
size_t len,
const char *format,
va_list ap);
/** @brief Generate the output for a previously captured format
* operation.
*
* @param out the function used to emit each generated character.
*
* @param ctx context provided when invoking out
*
* @param packaged the data required to generate the formatted output, as
* captured by cbprintf_package() or cbvprintf_package(). The alignment
* requirement on this data is the same as when it was initially created.
*
* @note Memory indicated by @p packaged will be modified in a non-destructive
* way, meaning that it could still be reused with this function again.
*
* @return the number of characters printed, or a negative error value
* returned from invoking @p out.
*/
int cbpprintf(cbprintf_cb out,
void *ctx,
void *packaged);
/** @brief *printf-like output through a callback.
*
* This is essentially printf() except the output is generated
* character-by-character using the provided @p out function. This allows
* formatting text of unbounded length without incurring the cost of a
* temporary buffer.
*
* All formatting specifiers of C99 are recognized, and most are supported if
* the functionality is enabled.
*
* @note The functionality of this function is significantly reduced
* when @option{CONFIG_CBPRINTF_NANO} is selected.
*
* @param out the function used to emit each generated character.
*
* @param ctx context provided when invoking out
*
* @param format a standard ISO C format string with characters and conversion
* specifications.
*
* @param ... arguments corresponding to the conversion specifications found
* within @p format.
*
* @return the number of characters printed, or a negative error value
* returned from invoking @p out.
*/
__printf_like(3, 4)
int cbprintf(cbprintf_cb out, void *ctx, const char *format, ...);
/** @brief varargs-aware *printf-like output through a callback.
*
* This is essentially vsprintf() except the output is generated
* character-by-character using the provided @p out function. This allows
* formatting text of unbounded length without incurring the cost of a
* temporary buffer.
*
* @note This function is available only when
* @option{CONFIG_CBPRINTF_LIBC_SUBSTS} is selected.
*
* @note The functionality of this function is significantly reduced when
* @option{CONFIG_CBPRINTF_NANO} is selected.
*
* @param out the function used to emit each generated character.
*
* @param ctx context provided when invoking out
*
* @param format a standard ISO C format string with characters and conversion
* specifications.
*
* @param ap a reference to the values to be converted.
*
* @return the number of characters generated, or a negative error value
* returned from invoking @p out.
*/
int cbvprintf(cbprintf_cb out, void *ctx, const char *format, va_list ap);
#ifdef CONFIG_CBPRINTF_LIBC_SUBSTS
/** @brief fprintf using Zephyrs cbprintf infrastructure.
*
* @note This function is available only when
* @option{CONFIG_CBPRINTF_LIBC_SUBSTS} is selected.
*
* @note The functionality of this function is significantly reduced
* when @option{CONFIG_CBPRINTF_NANO} is selected.
*
* @param stream the stream to which the output should be written.
*
* @param format a standard ISO C format string with characters and
* conversion specifications.
*
* @param ... arguments corresponding to the conversion specifications found
* within @p format.
*
* return The number of characters printed.
*/
__printf_like(2, 3)
int fprintfcb(FILE * stream, const char *format, ...);
/** @brief vfprintf using Zephyrs cbprintf infrastructure.
*
* @note This function is available only when
* @option{CONFIG_CBPRINTF_LIBC_SUBSTS} is selected.
*
* @note The functionality of this function is significantly reduced when
* @option{CONFIG_CBPRINTF_NANO} is selected.
*
* @param stream the stream to which the output should be written.
*
* @param format a standard ISO C format string with characters and conversion
* specifications.
*
* @param ap a reference to the values to be converted.
*
* @return The number of characters printed.
*/
int vfprintfcb(FILE *stream, const char *format, va_list ap);
/** @brief printf using Zephyrs cbprintf infrastructure.
*
* @note This function is available only when
* @option{CONFIG_CBPRINTF_LIBC_SUBSTS} is selected.
*
* @note The functionality of this function is significantly reduced
* when @option{CONFIG_CBPRINTF_NANO} is selected.
*
* @param format a standard ISO C format string with characters and
* conversion specifications.
*
* @param ... arguments corresponding to the conversion specifications found
* within @p format.
*
* @return The number of characters printed.
*/
__printf_like(1, 2)
int printfcb(const char *format, ...);
/** @brief vprintf using Zephyrs cbprintf infrastructure.
*
* @note This function is available only when
* @option{CONFIG_CBPRINTF_LIBC_SUBSTS} is selected.
*
* @note The functionality of this function is significantly reduced when
* @option{CONFIG_CBPRINTF_NANO} is selected.
*
* @param format a standard ISO C format string with characters and conversion
* specifications.
*
* @param ap a reference to the values to be converted.
*
* @return The number of characters printed.
*/
int vprintfcb(const char *format, va_list ap);
/** @brief snprintf using Zephyrs cbprintf infrastructure.
*
* @note This function is available only when
* @option{CONFIG_CBPRINTF_LIBC_SUBSTS} is selected.
*
* @note The functionality of this function is significantly reduced
* when @option{CONFIG_CBPRINTF_NANO} is selected.
*
* @param str where the formatted content should be written
*
* @param size maximum number of chaacters for the formatted output,
* including the terminating null byte.
*
* @param format a standard ISO C format string with characters and
* conversion specifications.
*
* @param ... arguments corresponding to the conversion specifications found
* within @p format.
*
* @return The number of characters that would have been written to @p
* str, excluding the terminating null byte. This is greater than the
* number actually written if @p size is too small.
*/
__printf_like(3, 4)
int snprintfcb(char *str, size_t size, const char *format, ...);
/** @brief vsnprintf using Zephyrs cbprintf infrastructure.
*
* @note This function is available only when
* @option{CONFIG_CBPRINTF_LIBC_SUBSTS} is selected.
*
* @note The functionality of this function is significantly reduced when
* @option{CONFIG_CBPRINTF_NANO} is selected.
*
* @param str where the formatted content should be written
*
* @param size maximum number of chaacters for the formatted output, including
* the terminating null byte.
*
* @param format a standard ISO C format string with characters and conversion
* specifications.
*
* @param ap a reference to the values to be converted.
*
* @return The number of characters that would have been written to @p
* str, excluding the terminating null byte. This is greater than the
* number actually written if @p size is too small.
*/
int vsnprintfcb(char *str, size_t size, const char *format, va_list ap);
#endif /* CONFIG_CBPRINTF_LIBC_SUBSTS */
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* ZEPHYR_INCLUDE_SYS_CBPRINTF_H_ */
| 34.40708 | 79 | 0.742198 | [
"object"
] |
83a3c3ea86d17cf6ac02ddae8425f7661a922b88 | 1,556 | h | C | src/stx/astf/trex_astf.h | alialnu/trex-core | ae4ab05a6215fd0a859adde40dac6afa8bf0f950 | [
"Apache-2.0"
] | 1 | 2020-11-06T08:50:08.000Z | 2020-11-06T08:50:08.000Z | src/stx/astf/trex_astf.h | alialnu/trex-core | ae4ab05a6215fd0a859adde40dac6afa8bf0f950 | [
"Apache-2.0"
] | 3 | 2018-04-25T20:28:49.000Z | 2018-07-16T13:45:40.000Z | src/stx/astf/trex_astf.h | alialnu/trex-core | ae4ab05a6215fd0a859adde40dac6afa8bf0f950 | [
"Apache-2.0"
] | null | null | null | /*
Itay Marom
Cisco Systems, Inc.
*/
/*
Copyright (c) 2015-2015 Cisco Systems, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef __TREX_ASTF_H__
#define __TREX_ASTF_H__
#include <stdint.h>
#include "common/trex_stx.h"
/**
* TRex adavanced stateful interactive object
*
*/
class TrexAstf : public TrexSTX {
public:
/**
* create ASTF object
*/
TrexAstf(const TrexSTXCfg &cfg);
virtual ~TrexAstf();
/**
* ASTF control plane
*
*/
void launch_control_plane();
/**
* shutdown ASTF
*
*/
void shutdown();
/**
* async data sent for ASTF
*
*/
void publish_async_data();
/**
* create a ASTF DP core
*
*/
TrexDpCore *create_dp_core(uint32_t thread_id, CFlowGenListPerThread *core);
protected:
};
/**
* returns the ASTF object
* if mode is not ASTF, will return NULL
*/
static inline TrexAstf * get_astf_object() {
return dynamic_cast<TrexAstf *>(get_stx());
}
#endif /* __TREX_STL_H__ */
| 18.305882 | 80 | 0.650386 | [
"object"
] |
83a506fa6e8222ef47617f4a6654d1b7e5b9c267 | 2,286 | c | C | kubernetes/unit-test/test_v1_downward_api_volume_file.c | minerba/c | 8eb6593e55d0e5d57a2dd3153c15c9645de677bc | [
"Apache-2.0"
] | 69 | 2020-03-17T13:47:05.000Z | 2022-03-30T08:25:05.000Z | kubernetes/unit-test/test_v1_downward_api_volume_file.c | minerba/c | 8eb6593e55d0e5d57a2dd3153c15c9645de677bc | [
"Apache-2.0"
] | 115 | 2020-03-17T14:53:19.000Z | 2022-03-31T11:31:30.000Z | kubernetes/unit-test/test_v1_downward_api_volume_file.c | minerba/c | 8eb6593e55d0e5d57a2dd3153c15c9645de677bc | [
"Apache-2.0"
] | 28 | 2020-03-17T13:42:21.000Z | 2022-03-19T23:37:16.000Z | #ifndef v1_downward_api_volume_file_TEST
#define v1_downward_api_volume_file_TEST
// the following is to include only the main from the first c file
#ifndef TEST_MAIN
#define TEST_MAIN
#define v1_downward_api_volume_file_MAIN
#endif // TEST_MAIN
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <stdbool.h>
#include "../external/cJSON.h"
#include "../model/v1_downward_api_volume_file.h"
v1_downward_api_volume_file_t* instantiate_v1_downward_api_volume_file(int include_optional);
#include "test_v1_object_field_selector.c"
#include "test_v1_resource_field_selector.c"
v1_downward_api_volume_file_t* instantiate_v1_downward_api_volume_file(int include_optional) {
v1_downward_api_volume_file_t* v1_downward_api_volume_file = NULL;
if (include_optional) {
v1_downward_api_volume_file = v1_downward_api_volume_file_create(
// false, not to have infinite recursion
instantiate_v1_object_field_selector(0),
56,
"0",
// false, not to have infinite recursion
instantiate_v1_resource_field_selector(0)
);
} else {
v1_downward_api_volume_file = v1_downward_api_volume_file_create(
NULL,
56,
"0",
NULL
);
}
return v1_downward_api_volume_file;
}
#ifdef v1_downward_api_volume_file_MAIN
void test_v1_downward_api_volume_file(int include_optional) {
v1_downward_api_volume_file_t* v1_downward_api_volume_file_1 = instantiate_v1_downward_api_volume_file(include_optional);
cJSON* jsonv1_downward_api_volume_file_1 = v1_downward_api_volume_file_convertToJSON(v1_downward_api_volume_file_1);
printf("v1_downward_api_volume_file :\n%s\n", cJSON_Print(jsonv1_downward_api_volume_file_1));
v1_downward_api_volume_file_t* v1_downward_api_volume_file_2 = v1_downward_api_volume_file_parseFromJSON(jsonv1_downward_api_volume_file_1);
cJSON* jsonv1_downward_api_volume_file_2 = v1_downward_api_volume_file_convertToJSON(v1_downward_api_volume_file_2);
printf("repeating v1_downward_api_volume_file:\n%s\n", cJSON_Print(jsonv1_downward_api_volume_file_2));
}
int main() {
test_v1_downward_api_volume_file(1);
test_v1_downward_api_volume_file(0);
printf("Hello world \n");
return 0;
}
#endif // v1_downward_api_volume_file_MAIN
#endif // v1_downward_api_volume_file_TEST
| 33.130435 | 141 | 0.812773 | [
"model"
] |
83a7c962d20e6de68c3ba51a7126d67d12d36780 | 6,804 | h | C | lib/cocos2d-x/extensions/DragonBones/animation/Animation.h | hdzhang/quick-cocos2d-x | ed11ec8ba273fa0d6e67b882387cc7637d34fe0e | [
"MIT"
] | 1 | 2020-06-05T09:24:43.000Z | 2020-06-05T09:24:43.000Z | lib/cocos2d-x/extensions/DragonBones/animation/Animation.h | hdzhang/quick-cocos2d-x | ed11ec8ba273fa0d6e67b882387cc7637d34fe0e | [
"MIT"
] | null | null | null | lib/cocos2d-x/extensions/DragonBones/animation/Animation.h | hdzhang/quick-cocos2d-x | ed11ec8ba273fa0d6e67b882387cc7637d34fe0e | [
"MIT"
] | null | null | null | #ifndef __ANIMATION_H__
#define __ANIMATION_H__
#include "utils/preDB.h"
namespace dragonBones
{
class AnimationData;
class AnimationState;
class Armature;
/**
* An Animation instance is used to control the animation state of an Armature.
* @example
* <p>Download the example files <a href='http://dragonbones.github.com/downloads/DragonBones_Tutorial_Assets.zip'>here</a>: </p>
* <listing>
* package
* {
* import dragonBones.Armature;
* import dragonBones.factorys.NativeFactory;
* import flash.display.Sprite;
* import flash.events.Event;
*
* public class DragonAnimation extends Sprite
* {
* [Embed(source = "Dragon1.swf", mimeType = "application/octet-stream")]
* private static const ResourcesData:Class;
*
* private var factory:NativeFactory;
* private var armature:Armature;
*
* public function DragonAnimation()
* {
* factory = new NativeFactory();
* factory.addEventListener(Event.COMPLETE, handleParseData);
* factory.parseData(new ResourcesData(), 'Dragon');
* }
*
* private function handleParseData(e:Event):void
* {
* armature = factory.buildArmature('Dragon');
* addChild(armature.display as Sprite);
* armature.animation.play();
* addEventListener(Event.ENTER_FRAME, updateAnimation);
* }
*
* private function updateAnimation(e:Event):void
* {
* armature.advanceTime(stage.frameRate / 1000);
* }
* }
* }
* </listing>
* @see dragonBones.Armature
* @see dragonBones.animation.Animation
* @see dragonBones.animation.AnimationState
*/
class Animation
{
public:
static const String NONE;
static const String SAME_LAYER;
static const String SAME_GROUP;
static const String SAME_LAYER_AND_GROUP;
static const String ALL;
/**
* Whether animation tweening is enabled or not.
*/
bool tweenEnabled;
/** @private */
std::vector<std::vector<AnimationState*>* > _animationLayer;
Armature* _armature;
bool _isActive;
/**
* An vector containing all AnimationData names the Animation can play.
* @see dragonBones.objects.animationData->
*/
const std::vector<String> &getMovementList();
/**
* The name of the last AnimationData played.
* @see dragonBones.objects.animationData->
*/
const String &getMovementID();
AnimationState *_lastAnimationState;
/**
* The last AnimationData this Animation played.
* @see dragonBones.objects.animationData->
*/
AnimationState *getLastAnimationState();
std::vector<String> _animationList;
/**
* An vector containing all AnimationData names the Animation can play.
* @see dragonBones.objects.animationData->
*/
const std::vector<String> &getAnimationList();
bool _isPlaying;
bool getIsPlaying();
bool getIsComplete();
std::vector<AnimationData*> _animationDataList;
/**
* The AnimationData list associated with this Animation instance.
* @see dragonBones.objects.animationData->
*/
const std::vector<AnimationData*>& getAnimationDataList();
void setAnimationDataList(const std::vector<AnimationData*> &value);
AnimationData* getAnimationData(std::string &name);
Number _timeScale;
/**
* The amount by which passed time should be scaled. Used to slow down or speed up animations. Defaults to 1.
*/
Number getTimeScale();
void setTimeScale(Number value);
/**
* Creates a new Animation instance and attaches it to the passed Armature.
* @param An Armature to attach this Animation instance to.
*/
Animation(Armature *armature);
/**
* Qualifies all resources used by this Animation instance for garbage collection.
*/
void dispose();
/**
* Move the playhead to that AnimationData
* @param animationName The name of the AnimationData to play.
* @param fadeInTime A fade time to apply (> 0)
* @param duration The duration of that animationData->
* @param loop Loop(0:loop forever, 1~+∞:loop times, -1~-∞:will fade animation after loop complete).
* @param layer The layer of the animation.
* @param group The group of the animation.
* @param fadeOutMode Fade out mode.
* @param displayControl Display control.
* @param pauseFadeOut Pause other animation playing.
* @param pauseFadeIn Pause this animation playing before fade in complete.
* @see dragonBones.objects.animationData->
* @see dragonBones.animation.animationState->
*/
AnimationState* gotoAndPlay(
const String &animationName,
Number fadeInTime = -1,
Number duration = -1,
Number loop = NaN,
uint layer = 0,
const String &group = "",
const String &fadeOutMode = SAME_LAYER_AND_GROUP,
bool displayControl = true,
bool pauseFadeOut = true,
bool pauseFadeIn = true
);
/**
* Play the animation from the current position.
*/
void play();
void stop();
/**
* Returns the AnimationState named name.
* @return A AnimationState instance.
* @see dragonBones.animation.animationState->
*/
AnimationState* getState(const String &name, uint layer = 0);
bool hasAnimation(const String &animationName);
void advanceTime(Number passedTime);
/** @private */
void setActive(AnimationState *animationState, bool active);
uint addLayer(uint layer);
void addState(AnimationState *animationState);
void removeState(AnimationState *animationState);
};
};
#endif // __ANIMATION_H__
| 35.623037 | 133 | 0.555409 | [
"vector"
] |
83aae15b6ee49912c659144a019f47705756b61a | 1,535 | h | C | SRC/engine/catvoldata.h | usnistgov/OOF3D | 4fd423a48aea9c5dc207520f02de53ae184be74c | [
"X11"
] | 31 | 2015-04-01T15:59:36.000Z | 2022-03-18T20:21:47.000Z | SRC/engine/catvoldata.h | usnistgov/OOF3D | 4fd423a48aea9c5dc207520f02de53ae184be74c | [
"X11"
] | 3 | 2015-02-06T19:30:24.000Z | 2017-05-25T14:14:31.000Z | SRC/engine/catvoldata.h | usnistgov/OOF3D | 4fd423a48aea9c5dc207520f02de53ae184be74c | [
"X11"
] | 7 | 2015-01-23T15:19:22.000Z | 2021-06-09T09:03:59.000Z | // -*- C++ -*-
/* This software was produced by NIST, an agency of the U.S. government,
* and by statute is not subject to copyright in the United States.
* Recipients of this software assume all responsibilities associated
* with its operation, modification and maintenance. However, to
* facilitate maintenance we ask that before distributing modified
* versions of this software, you first contact the authors at
* oof_manager@nist.gov.
*/
// This is used to transfer data from
// CSkeletonBase::checkCategoryVolumes when measuring how well the
// category volumes code is working.
#ifndef CATVOLDATA_H
#define CATVOLDATA_H
#include <oofconfig.h>
#include <vector>
#include "common/doublevec.h"
#include "engine/cskeleton2.h"
class CategoryVolumesData {
private:
double avgerr; // average per element error in volume
double rmserr; // rms deviation of error
double maxerr; // max error overa all elements
std::vector<int> catCounts; // no. of voxels in each category
DoubleVec catVolumes; // computed volume in each category
DoubleVec catErrors; // total error in each category
public:
int nCategories() const { return catCounts.size(); }
double avgError() const { return avgerr; }
double rmsError() const { return rmserr; }
double maxError() const { return maxerr; }
int catCount(int i) const { return catCounts[i]; }
double catVolume(int i) const { return catVolumes[i]; }
double catError(int i) const { return catErrors[i]; }
friend class CSkeletonBase;
};
#endif // CATVOLDATA_H
| 34.886364 | 72 | 0.738111 | [
"vector"
] |
39eb2cba63fbc433e7e131d6ead789acbb2b2d27 | 6,251 | h | C | exercise 2/RestConference/Pods/Headers/RestKit/RestKit/Network/RKRoute.h | cmoulton/kwiostraining | c39bb40c1c4443d338dbb1f090a471deb1e32157 | [
"MIT"
] | 1,074 | 2015-01-04T22:43:08.000Z | 2022-03-29T11:11:50.000Z | exercise 2/RestConference/Pods/Headers/RestKit/RestKit/Network/RKRoute.h | cmoulton/kwiostraining | c39bb40c1c4443d338dbb1f090a471deb1e32157 | [
"MIT"
] | 66 | 2015-03-11T14:40:35.000Z | 2022-01-17T21:59:02.000Z | exercise 2/RestConference/Pods/Headers/RestKit/RestKit/Network/RKRoute.h | cmoulton/kwiostraining | c39bb40c1c4443d338dbb1f090a471deb1e32157 | [
"MIT"
] | 192 | 2015-01-05T16:58:04.000Z | 2022-02-09T01:37:09.000Z | //
// RKRoute.h
// RestKit
//
// Created by Blake Watters on 5/31/12.
// Copyright (c) 2012 RestKit. 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.
//
#import <RestKit/ObjectMapping/RKHTTPUtilities.h>
/**
The `RKRoute` class models a single routable path pattern in use by the application. A route can be combined with an `NSURL` base URL and interpolated with an object to produce a new fully hydrated URL object. Routes are always instantiated with a path pattern and metadata to provide for the subsequent identification of the defined route.
There are three types of routes modeled by the RKRoute class:
1. **Named Routes**: A named route represents a single path and optional request method within the application. The route is not affiliated with any particular class. For example, one might define a route with the name `@"airlines_list"` as a GET to the path '/airlines.json'.
1. **Class Routes**: An class route represents a single path that is identified by object class and request method for which it is appropriate. For example, one might define a route for the class `RKArticle` for a POST to the path '/articles.json'.
1. **Relationship Routes**: A relationship route represents a single path through which the relationship of a parent object can be manipulated. For example, given an `RKArticle` and `RKComment` class, one might define a relationship route for the `RKArticle` class's `@"comments"` relationship as pointing to a GET to the path `@"/articles/:articleID/comments".
The RKRoute class is internally implemented as a class cluster and is not to be directly instantiated via alloc and init.
@see RKRouter
@see RKRouteSet
*/
@interface RKRoute : NSObject
///---------------------------
/// @name Instantiating Routes
///---------------------------
/**
Creates and returns a new named route object with the given name, path pattern and method.
@param name A unique identifying name for the route.
@param pathPattern A SOCKit pattern describing the format of URL paths generated from the route.
@param method The request method of the route. The method given must specify a single HTTP method to be used for requests using the route.
@return A new named route object with the given name, path pattern and request method.
@raise NSInvalidArgumentException Raised if the given HTTP request method is not an exact match of the RKRequestMethod enum
*/
+ (instancetype)routeWithName:(NSString *)name pathPattern:(NSString *)pathPattern method:(RKRequestMethod)method;
/**
Creates and returns a new class route object with the given object class, path pattern and method.
@param objectClass The class that is represented by the route.
@param pathPattern A SOCKit pattern describing the format of URL paths generated from the route.
@param method The request method of the route. More than one method may be specified via a bitwise OR.
@return A new class route object with the given object class, path pattern and request method.
*/
+ (instancetype)routeWithClass:(Class)objectClass pathPattern:(NSString *)pathPattern method:(RKRequestMethod)method;
/**
Creates and returns a new relationship route object with the given relationship name, object class, path pattern and method.
@param name The name of the relationship represented by the route.
@param objectClass The class containing the relationship represented by the route.
@param pathPattern A SOCKit pattern describing the format of URL paths generated from the route.
@param method The request method of the route. More than one method may be specified via a bitwise OR.
@return A new class route object with the given object class, path pattern and request method.
*/
+ (instancetype)routeWithRelationshipName:(NSString *)name objectClass:(Class)objectClass pathPattern:(NSString *)pathPattern method:(RKRequestMethod)method;
///---------------------------------
/// @name Accessing Route Attributes
///---------------------------------
/**
The name of the receiver.
The name is used to identify named and relationship routes and is always `nil` for object routes.
*/
@property (nonatomic, strong, readonly) NSString *name;
/**
The object class of the receiver.
Defines the class for which the route is appropriate. Always returns `nil` for named routes.
*/
@property (nonatomic, strong, readonly) Class objectClass;
/**
The request method of the receiver.
Appropriate for all route types. If the route is appropriate for any HTTP request method, then the `RKRequestMethodAny` value is used.
*/
@property (nonatomic, assign, readonly) RKRequestMethod method;
/**
The path pattern of the receiver.
A SOCKit pattern that describes the format of the path portion of URL's generated from the receiver. Required and used by all route types.
@see `SOCPattern`
*/
@property (nonatomic, strong, readonly) NSString *pathPattern;
/**
A Boolean value that determines if the path pattern should be escaped when evaluated.
*Default*: `NO`
*/
@property (nonatomic, assign) BOOL shouldEscapePath;
///-----------------------------
/// @name Inspecting Route Types
///-----------------------------
/**
Determines if the receiver is a named route.
@return YES if the receiver is a named route, else NO.
*/
@property (nonatomic, getter=isNamedRoute, readonly) BOOL namedRoute;
/**
Determines if the receiver is a class route.
@return YES if the receiver is a class route, else NO.
*/
@property (nonatomic, getter=isClassRoute, readonly) BOOL classRoute;
/**
Determines if the receiver is a relationship route.
@return YES if the receiver is a relationship route, else NO.
*/
@property (nonatomic, getter=isRelationshipRoute, readonly) BOOL relationshipRoute;
@end
| 44.021127 | 362 | 0.744201 | [
"object"
] |
39ee26b19981cb93fffc7a2606dede24a01e13f8 | 52,986 | h | C | ti_simplelink_sdk/kernel/tirtos/packages/ti/sysbios/family/arm/cc26xx/Timer.h | intrepidcs/OBD2LC_WIFI_CC32XX | c4ba5f7c6751e7ead204bbdd8d272c6ceb64f4ce | [
"Unlicense"
] | null | null | null | ti_simplelink_sdk/kernel/tirtos/packages/ti/sysbios/family/arm/cc26xx/Timer.h | intrepidcs/OBD2LC_WIFI_CC32XX | c4ba5f7c6751e7ead204bbdd8d272c6ceb64f4ce | [
"Unlicense"
] | 1 | 2022-02-07T22:05:30.000Z | 2022-02-08T14:23:04.000Z | ti_simplelink_sdk/kernel/tirtos/packages/ti/sysbios/family/arm/cc26xx/Timer.h | intrepidcs/OBD2LC_WIFI_CC32XX | c4ba5f7c6751e7ead204bbdd8d272c6ceb64f4ce | [
"Unlicense"
] | 1 | 2022-01-31T22:21:50.000Z | 2022-01-31T22:21:50.000Z | /*
* Do not modify this file; it is automatically
* generated and any modifications will be overwritten.
*
* @(#) xdc-H25
*/
/*
* ======== GENERATED SECTIONS ========
*
* PROLOGUE
* INCLUDES
*
* CREATE ARGS
* INTERNAL DEFINITIONS
* MODULE-WIDE CONFIGS
* PER-INSTANCE TYPES
* VIRTUAL FUNCTIONS
* FUNCTION DECLARATIONS
* CONVERTORS
* SYSTEM FUNCTIONS
*
* EPILOGUE
* STATE STRUCTURES
* PREFIX ALIASES
*/
/*
* ======== PROLOGUE ========
*/
#ifndef ti_sysbios_family_arm_cc26xx_Timer__include
#define ti_sysbios_family_arm_cc26xx_Timer__include
#ifndef __nested__
#define __nested__
#define ti_sysbios_family_arm_cc26xx_Timer__top__
#endif
#ifndef __extern
#ifdef __cplusplus
#define __extern extern "C"
#else
#define __extern extern
#endif
#endif
#define ti_sysbios_family_arm_cc26xx_Timer___VERS 200
/*
* ======== INCLUDES ========
*/
#include <xdc/std.h>
#include <xdc/runtime/xdc.h>
#include <xdc/runtime/Types.h>
#include <xdc/runtime/IInstance.h>
#include <ti/sysbios/family/arm/cc26xx/package/package.defs.h>
#include <xdc/runtime/Types.h>
#include <xdc/runtime/Error.h>
#include <ti/sysbios/interfaces/ITimer.h>
#include <ti/sysbios/family/arm/m3/Hwi.h>
/*
* ======== AUXILIARY DEFINITIONS ========
*/
/* FuncPtr */
typedef ti_sysbios_interfaces_ITimer_FuncPtr ti_sysbios_family_arm_cc26xx_Timer_FuncPtr;
/* ANY */
#define ti_sysbios_family_arm_cc26xx_Timer_ANY (~0)
/* StartMode */
typedef ti_sysbios_interfaces_ITimer_StartMode ti_sysbios_family_arm_cc26xx_Timer_StartMode;
/* RunMode */
typedef ti_sysbios_interfaces_ITimer_RunMode ti_sysbios_family_arm_cc26xx_Timer_RunMode;
/* Status */
typedef ti_sysbios_interfaces_ITimer_Status ti_sysbios_family_arm_cc26xx_Timer_Status;
/* PeriodType */
typedef ti_sysbios_interfaces_ITimer_PeriodType ti_sysbios_family_arm_cc26xx_Timer_PeriodType;
/* MAX_PERIOD */
#define ti_sysbios_family_arm_cc26xx_Timer_MAX_PERIOD (0xFFFFFFFF)
/* MIN_SWEEP_PERIOD */
#define ti_sysbios_family_arm_cc26xx_Timer_MIN_SWEEP_PERIOD (1)
/* StartMode_AUTO */
#define ti_sysbios_family_arm_cc26xx_Timer_StartMode_AUTO ti_sysbios_interfaces_ITimer_StartMode_AUTO
/* StartMode_USER */
#define ti_sysbios_family_arm_cc26xx_Timer_StartMode_USER ti_sysbios_interfaces_ITimer_StartMode_USER
/* RunMode_CONTINUOUS */
#define ti_sysbios_family_arm_cc26xx_Timer_RunMode_CONTINUOUS ti_sysbios_interfaces_ITimer_RunMode_CONTINUOUS
/* RunMode_ONESHOT */
#define ti_sysbios_family_arm_cc26xx_Timer_RunMode_ONESHOT ti_sysbios_interfaces_ITimer_RunMode_ONESHOT
/* RunMode_DYNAMIC */
#define ti_sysbios_family_arm_cc26xx_Timer_RunMode_DYNAMIC ti_sysbios_interfaces_ITimer_RunMode_DYNAMIC
/* Status_INUSE */
#define ti_sysbios_family_arm_cc26xx_Timer_Status_INUSE ti_sysbios_interfaces_ITimer_Status_INUSE
/* Status_FREE */
#define ti_sysbios_family_arm_cc26xx_Timer_Status_FREE ti_sysbios_interfaces_ITimer_Status_FREE
/* PeriodType_MICROSECS */
#define ti_sysbios_family_arm_cc26xx_Timer_PeriodType_MICROSECS ti_sysbios_interfaces_ITimer_PeriodType_MICROSECS
/* PeriodType_COUNTS */
#define ti_sysbios_family_arm_cc26xx_Timer_PeriodType_COUNTS ti_sysbios_interfaces_ITimer_PeriodType_COUNTS
/*
* ======== CREATE ARGS ========
*/
/* Args__create */
typedef struct ti_sysbios_family_arm_cc26xx_Timer_Args__create {
xdc_Int id;
ti_sysbios_interfaces_ITimer_FuncPtr tickFxn;
} ti_sysbios_family_arm_cc26xx_Timer_Args__create;
/*
* ======== INTERNAL DEFINITIONS ========
*/
/*
* ======== MODULE-WIDE CONFIGS ========
*/
/* Module__diagsEnabled */
typedef xdc_Bits32 CT__ti_sysbios_family_arm_cc26xx_Timer_Module__diagsEnabled;
__extern __FAR__ const CT__ti_sysbios_family_arm_cc26xx_Timer_Module__diagsEnabled ti_sysbios_family_arm_cc26xx_Timer_Module__diagsEnabled__C;
#ifdef ti_sysbios_family_arm_cc26xx_Timer_Module__diagsEnabled__CR
#define ti_sysbios_family_arm_cc26xx_Timer_Module__diagsEnabled__C (*((CT__ti_sysbios_family_arm_cc26xx_Timer_Module__diagsEnabled*)(xdcRomConstPtr + ti_sysbios_family_arm_cc26xx_Timer_Module__diagsEnabled__C_offset)))
#else
#define ti_sysbios_family_arm_cc26xx_Timer_Module__diagsEnabled (ti_sysbios_family_arm_cc26xx_Timer_Module__diagsEnabled__C)
#endif
/* Module__diagsIncluded */
typedef xdc_Bits32 CT__ti_sysbios_family_arm_cc26xx_Timer_Module__diagsIncluded;
__extern __FAR__ const CT__ti_sysbios_family_arm_cc26xx_Timer_Module__diagsIncluded ti_sysbios_family_arm_cc26xx_Timer_Module__diagsIncluded__C;
#ifdef ti_sysbios_family_arm_cc26xx_Timer_Module__diagsIncluded__CR
#define ti_sysbios_family_arm_cc26xx_Timer_Module__diagsIncluded__C (*((CT__ti_sysbios_family_arm_cc26xx_Timer_Module__diagsIncluded*)(xdcRomConstPtr + ti_sysbios_family_arm_cc26xx_Timer_Module__diagsIncluded__C_offset)))
#else
#define ti_sysbios_family_arm_cc26xx_Timer_Module__diagsIncluded (ti_sysbios_family_arm_cc26xx_Timer_Module__diagsIncluded__C)
#endif
/* Module__diagsMask */
typedef xdc_Bits16 *CT__ti_sysbios_family_arm_cc26xx_Timer_Module__diagsMask;
__extern __FAR__ const CT__ti_sysbios_family_arm_cc26xx_Timer_Module__diagsMask ti_sysbios_family_arm_cc26xx_Timer_Module__diagsMask__C;
#ifdef ti_sysbios_family_arm_cc26xx_Timer_Module__diagsMask__CR
#define ti_sysbios_family_arm_cc26xx_Timer_Module__diagsMask__C (*((CT__ti_sysbios_family_arm_cc26xx_Timer_Module__diagsMask*)(xdcRomConstPtr + ti_sysbios_family_arm_cc26xx_Timer_Module__diagsMask__C_offset)))
#else
#define ti_sysbios_family_arm_cc26xx_Timer_Module__diagsMask (ti_sysbios_family_arm_cc26xx_Timer_Module__diagsMask__C)
#endif
/* Module__gateObj */
typedef xdc_Ptr CT__ti_sysbios_family_arm_cc26xx_Timer_Module__gateObj;
__extern __FAR__ const CT__ti_sysbios_family_arm_cc26xx_Timer_Module__gateObj ti_sysbios_family_arm_cc26xx_Timer_Module__gateObj__C;
#ifdef ti_sysbios_family_arm_cc26xx_Timer_Module__gateObj__CR
#define ti_sysbios_family_arm_cc26xx_Timer_Module__gateObj__C (*((CT__ti_sysbios_family_arm_cc26xx_Timer_Module__gateObj*)(xdcRomConstPtr + ti_sysbios_family_arm_cc26xx_Timer_Module__gateObj__C_offset)))
#else
#define ti_sysbios_family_arm_cc26xx_Timer_Module__gateObj (ti_sysbios_family_arm_cc26xx_Timer_Module__gateObj__C)
#endif
/* Module__gatePrms */
typedef xdc_Ptr CT__ti_sysbios_family_arm_cc26xx_Timer_Module__gatePrms;
__extern __FAR__ const CT__ti_sysbios_family_arm_cc26xx_Timer_Module__gatePrms ti_sysbios_family_arm_cc26xx_Timer_Module__gatePrms__C;
#ifdef ti_sysbios_family_arm_cc26xx_Timer_Module__gatePrms__CR
#define ti_sysbios_family_arm_cc26xx_Timer_Module__gatePrms__C (*((CT__ti_sysbios_family_arm_cc26xx_Timer_Module__gatePrms*)(xdcRomConstPtr + ti_sysbios_family_arm_cc26xx_Timer_Module__gatePrms__C_offset)))
#else
#define ti_sysbios_family_arm_cc26xx_Timer_Module__gatePrms (ti_sysbios_family_arm_cc26xx_Timer_Module__gatePrms__C)
#endif
/* Module__id */
typedef xdc_runtime_Types_ModuleId CT__ti_sysbios_family_arm_cc26xx_Timer_Module__id;
__extern __FAR__ const CT__ti_sysbios_family_arm_cc26xx_Timer_Module__id ti_sysbios_family_arm_cc26xx_Timer_Module__id__C;
#ifdef ti_sysbios_family_arm_cc26xx_Timer_Module__id__CR
#define ti_sysbios_family_arm_cc26xx_Timer_Module__id__C (*((CT__ti_sysbios_family_arm_cc26xx_Timer_Module__id*)(xdcRomConstPtr + ti_sysbios_family_arm_cc26xx_Timer_Module__id__C_offset)))
#else
#define ti_sysbios_family_arm_cc26xx_Timer_Module__id (ti_sysbios_family_arm_cc26xx_Timer_Module__id__C)
#endif
/* Module__loggerDefined */
typedef xdc_Bool CT__ti_sysbios_family_arm_cc26xx_Timer_Module__loggerDefined;
__extern __FAR__ const CT__ti_sysbios_family_arm_cc26xx_Timer_Module__loggerDefined ti_sysbios_family_arm_cc26xx_Timer_Module__loggerDefined__C;
#ifdef ti_sysbios_family_arm_cc26xx_Timer_Module__loggerDefined__CR
#define ti_sysbios_family_arm_cc26xx_Timer_Module__loggerDefined__C (*((CT__ti_sysbios_family_arm_cc26xx_Timer_Module__loggerDefined*)(xdcRomConstPtr + ti_sysbios_family_arm_cc26xx_Timer_Module__loggerDefined__C_offset)))
#else
#define ti_sysbios_family_arm_cc26xx_Timer_Module__loggerDefined (ti_sysbios_family_arm_cc26xx_Timer_Module__loggerDefined__C)
#endif
/* Module__loggerObj */
typedef xdc_Ptr CT__ti_sysbios_family_arm_cc26xx_Timer_Module__loggerObj;
__extern __FAR__ const CT__ti_sysbios_family_arm_cc26xx_Timer_Module__loggerObj ti_sysbios_family_arm_cc26xx_Timer_Module__loggerObj__C;
#ifdef ti_sysbios_family_arm_cc26xx_Timer_Module__loggerObj__CR
#define ti_sysbios_family_arm_cc26xx_Timer_Module__loggerObj__C (*((CT__ti_sysbios_family_arm_cc26xx_Timer_Module__loggerObj*)(xdcRomConstPtr + ti_sysbios_family_arm_cc26xx_Timer_Module__loggerObj__C_offset)))
#else
#define ti_sysbios_family_arm_cc26xx_Timer_Module__loggerObj (ti_sysbios_family_arm_cc26xx_Timer_Module__loggerObj__C)
#endif
/* Module__loggerFxn0 */
typedef xdc_runtime_Types_LoggerFxn0 CT__ti_sysbios_family_arm_cc26xx_Timer_Module__loggerFxn0;
__extern __FAR__ const CT__ti_sysbios_family_arm_cc26xx_Timer_Module__loggerFxn0 ti_sysbios_family_arm_cc26xx_Timer_Module__loggerFxn0__C;
#ifdef ti_sysbios_family_arm_cc26xx_Timer_Module__loggerFxn0__CR
#define ti_sysbios_family_arm_cc26xx_Timer_Module__loggerFxn0__C (*((CT__ti_sysbios_family_arm_cc26xx_Timer_Module__loggerFxn0*)(xdcRomConstPtr + ti_sysbios_family_arm_cc26xx_Timer_Module__loggerFxn0__C_offset)))
#else
#define ti_sysbios_family_arm_cc26xx_Timer_Module__loggerFxn0 (ti_sysbios_family_arm_cc26xx_Timer_Module__loggerFxn0__C)
#endif
/* Module__loggerFxn1 */
typedef xdc_runtime_Types_LoggerFxn1 CT__ti_sysbios_family_arm_cc26xx_Timer_Module__loggerFxn1;
__extern __FAR__ const CT__ti_sysbios_family_arm_cc26xx_Timer_Module__loggerFxn1 ti_sysbios_family_arm_cc26xx_Timer_Module__loggerFxn1__C;
#ifdef ti_sysbios_family_arm_cc26xx_Timer_Module__loggerFxn1__CR
#define ti_sysbios_family_arm_cc26xx_Timer_Module__loggerFxn1__C (*((CT__ti_sysbios_family_arm_cc26xx_Timer_Module__loggerFxn1*)(xdcRomConstPtr + ti_sysbios_family_arm_cc26xx_Timer_Module__loggerFxn1__C_offset)))
#else
#define ti_sysbios_family_arm_cc26xx_Timer_Module__loggerFxn1 (ti_sysbios_family_arm_cc26xx_Timer_Module__loggerFxn1__C)
#endif
/* Module__loggerFxn2 */
typedef xdc_runtime_Types_LoggerFxn2 CT__ti_sysbios_family_arm_cc26xx_Timer_Module__loggerFxn2;
__extern __FAR__ const CT__ti_sysbios_family_arm_cc26xx_Timer_Module__loggerFxn2 ti_sysbios_family_arm_cc26xx_Timer_Module__loggerFxn2__C;
#ifdef ti_sysbios_family_arm_cc26xx_Timer_Module__loggerFxn2__CR
#define ti_sysbios_family_arm_cc26xx_Timer_Module__loggerFxn2__C (*((CT__ti_sysbios_family_arm_cc26xx_Timer_Module__loggerFxn2*)(xdcRomConstPtr + ti_sysbios_family_arm_cc26xx_Timer_Module__loggerFxn2__C_offset)))
#else
#define ti_sysbios_family_arm_cc26xx_Timer_Module__loggerFxn2 (ti_sysbios_family_arm_cc26xx_Timer_Module__loggerFxn2__C)
#endif
/* Module__loggerFxn4 */
typedef xdc_runtime_Types_LoggerFxn4 CT__ti_sysbios_family_arm_cc26xx_Timer_Module__loggerFxn4;
__extern __FAR__ const CT__ti_sysbios_family_arm_cc26xx_Timer_Module__loggerFxn4 ti_sysbios_family_arm_cc26xx_Timer_Module__loggerFxn4__C;
#ifdef ti_sysbios_family_arm_cc26xx_Timer_Module__loggerFxn4__CR
#define ti_sysbios_family_arm_cc26xx_Timer_Module__loggerFxn4__C (*((CT__ti_sysbios_family_arm_cc26xx_Timer_Module__loggerFxn4*)(xdcRomConstPtr + ti_sysbios_family_arm_cc26xx_Timer_Module__loggerFxn4__C_offset)))
#else
#define ti_sysbios_family_arm_cc26xx_Timer_Module__loggerFxn4 (ti_sysbios_family_arm_cc26xx_Timer_Module__loggerFxn4__C)
#endif
/* Module__loggerFxn8 */
typedef xdc_runtime_Types_LoggerFxn8 CT__ti_sysbios_family_arm_cc26xx_Timer_Module__loggerFxn8;
__extern __FAR__ const CT__ti_sysbios_family_arm_cc26xx_Timer_Module__loggerFxn8 ti_sysbios_family_arm_cc26xx_Timer_Module__loggerFxn8__C;
#ifdef ti_sysbios_family_arm_cc26xx_Timer_Module__loggerFxn8__CR
#define ti_sysbios_family_arm_cc26xx_Timer_Module__loggerFxn8__C (*((CT__ti_sysbios_family_arm_cc26xx_Timer_Module__loggerFxn8*)(xdcRomConstPtr + ti_sysbios_family_arm_cc26xx_Timer_Module__loggerFxn8__C_offset)))
#else
#define ti_sysbios_family_arm_cc26xx_Timer_Module__loggerFxn8 (ti_sysbios_family_arm_cc26xx_Timer_Module__loggerFxn8__C)
#endif
/* Object__count */
typedef xdc_Int CT__ti_sysbios_family_arm_cc26xx_Timer_Object__count;
__extern __FAR__ const CT__ti_sysbios_family_arm_cc26xx_Timer_Object__count ti_sysbios_family_arm_cc26xx_Timer_Object__count__C;
#ifdef ti_sysbios_family_arm_cc26xx_Timer_Object__count__CR
#define ti_sysbios_family_arm_cc26xx_Timer_Object__count__C (*((CT__ti_sysbios_family_arm_cc26xx_Timer_Object__count*)(xdcRomConstPtr + ti_sysbios_family_arm_cc26xx_Timer_Object__count__C_offset)))
#else
#define ti_sysbios_family_arm_cc26xx_Timer_Object__count (ti_sysbios_family_arm_cc26xx_Timer_Object__count__C)
#endif
/* Object__heap */
typedef xdc_runtime_IHeap_Handle CT__ti_sysbios_family_arm_cc26xx_Timer_Object__heap;
__extern __FAR__ const CT__ti_sysbios_family_arm_cc26xx_Timer_Object__heap ti_sysbios_family_arm_cc26xx_Timer_Object__heap__C;
#ifdef ti_sysbios_family_arm_cc26xx_Timer_Object__heap__CR
#define ti_sysbios_family_arm_cc26xx_Timer_Object__heap__C (*((CT__ti_sysbios_family_arm_cc26xx_Timer_Object__heap*)(xdcRomConstPtr + ti_sysbios_family_arm_cc26xx_Timer_Object__heap__C_offset)))
#else
#define ti_sysbios_family_arm_cc26xx_Timer_Object__heap (ti_sysbios_family_arm_cc26xx_Timer_Object__heap__C)
#endif
/* Object__sizeof */
typedef xdc_SizeT CT__ti_sysbios_family_arm_cc26xx_Timer_Object__sizeof;
__extern __FAR__ const CT__ti_sysbios_family_arm_cc26xx_Timer_Object__sizeof ti_sysbios_family_arm_cc26xx_Timer_Object__sizeof__C;
#ifdef ti_sysbios_family_arm_cc26xx_Timer_Object__sizeof__CR
#define ti_sysbios_family_arm_cc26xx_Timer_Object__sizeof__C (*((CT__ti_sysbios_family_arm_cc26xx_Timer_Object__sizeof*)(xdcRomConstPtr + ti_sysbios_family_arm_cc26xx_Timer_Object__sizeof__C_offset)))
#else
#define ti_sysbios_family_arm_cc26xx_Timer_Object__sizeof (ti_sysbios_family_arm_cc26xx_Timer_Object__sizeof__C)
#endif
/* Object__table */
typedef xdc_Ptr CT__ti_sysbios_family_arm_cc26xx_Timer_Object__table;
__extern __FAR__ const CT__ti_sysbios_family_arm_cc26xx_Timer_Object__table ti_sysbios_family_arm_cc26xx_Timer_Object__table__C;
#ifdef ti_sysbios_family_arm_cc26xx_Timer_Object__table__CR
#define ti_sysbios_family_arm_cc26xx_Timer_Object__table__C (*((CT__ti_sysbios_family_arm_cc26xx_Timer_Object__table*)(xdcRomConstPtr + ti_sysbios_family_arm_cc26xx_Timer_Object__table__C_offset)))
#else
#define ti_sysbios_family_arm_cc26xx_Timer_Object__table (ti_sysbios_family_arm_cc26xx_Timer_Object__table__C)
#endif
/* E_invalidTimer */
typedef xdc_runtime_Error_Id CT__ti_sysbios_family_arm_cc26xx_Timer_E_invalidTimer;
__extern __FAR__ const CT__ti_sysbios_family_arm_cc26xx_Timer_E_invalidTimer ti_sysbios_family_arm_cc26xx_Timer_E_invalidTimer__C;
#ifdef ti_sysbios_family_arm_cc26xx_Timer_E_invalidTimer__CR
#define ti_sysbios_family_arm_cc26xx_Timer_E_invalidTimer (*((CT__ti_sysbios_family_arm_cc26xx_Timer_E_invalidTimer*)(xdcRomConstPtr + ti_sysbios_family_arm_cc26xx_Timer_E_invalidTimer__C_offset)))
#else
#define ti_sysbios_family_arm_cc26xx_Timer_E_invalidTimer (ti_sysbios_family_arm_cc26xx_Timer_E_invalidTimer__C)
#endif
/* E_notAvailable */
typedef xdc_runtime_Error_Id CT__ti_sysbios_family_arm_cc26xx_Timer_E_notAvailable;
__extern __FAR__ const CT__ti_sysbios_family_arm_cc26xx_Timer_E_notAvailable ti_sysbios_family_arm_cc26xx_Timer_E_notAvailable__C;
#ifdef ti_sysbios_family_arm_cc26xx_Timer_E_notAvailable__CR
#define ti_sysbios_family_arm_cc26xx_Timer_E_notAvailable (*((CT__ti_sysbios_family_arm_cc26xx_Timer_E_notAvailable*)(xdcRomConstPtr + ti_sysbios_family_arm_cc26xx_Timer_E_notAvailable__C_offset)))
#else
#define ti_sysbios_family_arm_cc26xx_Timer_E_notAvailable (ti_sysbios_family_arm_cc26xx_Timer_E_notAvailable__C)
#endif
/* E_cannotSupport */
typedef xdc_runtime_Error_Id CT__ti_sysbios_family_arm_cc26xx_Timer_E_cannotSupport;
__extern __FAR__ const CT__ti_sysbios_family_arm_cc26xx_Timer_E_cannotSupport ti_sysbios_family_arm_cc26xx_Timer_E_cannotSupport__C;
#ifdef ti_sysbios_family_arm_cc26xx_Timer_E_cannotSupport__CR
#define ti_sysbios_family_arm_cc26xx_Timer_E_cannotSupport (*((CT__ti_sysbios_family_arm_cc26xx_Timer_E_cannotSupport*)(xdcRomConstPtr + ti_sysbios_family_arm_cc26xx_Timer_E_cannotSupport__C_offset)))
#else
#define ti_sysbios_family_arm_cc26xx_Timer_E_cannotSupport (ti_sysbios_family_arm_cc26xx_Timer_E_cannotSupport__C)
#endif
/* anyMask */
typedef xdc_UInt CT__ti_sysbios_family_arm_cc26xx_Timer_anyMask;
__extern __FAR__ const CT__ti_sysbios_family_arm_cc26xx_Timer_anyMask ti_sysbios_family_arm_cc26xx_Timer_anyMask__C;
#ifdef ti_sysbios_family_arm_cc26xx_Timer_anyMask__CR
#define ti_sysbios_family_arm_cc26xx_Timer_anyMask (*((CT__ti_sysbios_family_arm_cc26xx_Timer_anyMask*)(xdcRomConstPtr + ti_sysbios_family_arm_cc26xx_Timer_anyMask__C_offset)))
#else
#ifdef ti_sysbios_family_arm_cc26xx_Timer_anyMask__D
#define ti_sysbios_family_arm_cc26xx_Timer_anyMask (ti_sysbios_family_arm_cc26xx_Timer_anyMask__D)
#else
#define ti_sysbios_family_arm_cc26xx_Timer_anyMask (ti_sysbios_family_arm_cc26xx_Timer_anyMask__C)
#endif
#endif
/* funcHookCH1 */
typedef ti_sysbios_family_arm_cc26xx_Timer_FuncPtr CT__ti_sysbios_family_arm_cc26xx_Timer_funcHookCH1;
__extern __FAR__ const CT__ti_sysbios_family_arm_cc26xx_Timer_funcHookCH1 ti_sysbios_family_arm_cc26xx_Timer_funcHookCH1__C;
#ifdef ti_sysbios_family_arm_cc26xx_Timer_funcHookCH1__CR
#define ti_sysbios_family_arm_cc26xx_Timer_funcHookCH1 (*((CT__ti_sysbios_family_arm_cc26xx_Timer_funcHookCH1*)(xdcRomConstPtr + ti_sysbios_family_arm_cc26xx_Timer_funcHookCH1__C_offset)))
#else
#define ti_sysbios_family_arm_cc26xx_Timer_funcHookCH1 (ti_sysbios_family_arm_cc26xx_Timer_funcHookCH1__C)
#endif
/* funcHookCH2 */
typedef ti_sysbios_family_arm_cc26xx_Timer_FuncPtr CT__ti_sysbios_family_arm_cc26xx_Timer_funcHookCH2;
__extern __FAR__ const CT__ti_sysbios_family_arm_cc26xx_Timer_funcHookCH2 ti_sysbios_family_arm_cc26xx_Timer_funcHookCH2__C;
#ifdef ti_sysbios_family_arm_cc26xx_Timer_funcHookCH2__CR
#define ti_sysbios_family_arm_cc26xx_Timer_funcHookCH2 (*((CT__ti_sysbios_family_arm_cc26xx_Timer_funcHookCH2*)(xdcRomConstPtr + ti_sysbios_family_arm_cc26xx_Timer_funcHookCH2__C_offset)))
#else
#define ti_sysbios_family_arm_cc26xx_Timer_funcHookCH2 (ti_sysbios_family_arm_cc26xx_Timer_funcHookCH2__C)
#endif
/* startupNeeded */
typedef xdc_UInt CT__ti_sysbios_family_arm_cc26xx_Timer_startupNeeded;
__extern __FAR__ const CT__ti_sysbios_family_arm_cc26xx_Timer_startupNeeded ti_sysbios_family_arm_cc26xx_Timer_startupNeeded__C;
#ifdef ti_sysbios_family_arm_cc26xx_Timer_startupNeeded__CR
#define ti_sysbios_family_arm_cc26xx_Timer_startupNeeded (*((CT__ti_sysbios_family_arm_cc26xx_Timer_startupNeeded*)(xdcRomConstPtr + ti_sysbios_family_arm_cc26xx_Timer_startupNeeded__C_offset)))
#else
#ifdef ti_sysbios_family_arm_cc26xx_Timer_startupNeeded__D
#define ti_sysbios_family_arm_cc26xx_Timer_startupNeeded (ti_sysbios_family_arm_cc26xx_Timer_startupNeeded__D)
#else
#define ti_sysbios_family_arm_cc26xx_Timer_startupNeeded (ti_sysbios_family_arm_cc26xx_Timer_startupNeeded__C)
#endif
#endif
/*
* ======== PER-INSTANCE TYPES ========
*/
/* Params */
struct ti_sysbios_family_arm_cc26xx_Timer_Params {
size_t __size;
const void *__self;
void *__fxns;
xdc_runtime_IInstance_Params *instance;
ti_sysbios_interfaces_ITimer_RunMode runMode;
ti_sysbios_interfaces_ITimer_StartMode startMode;
xdc_UArg arg;
xdc_UInt32 period;
ti_sysbios_interfaces_ITimer_PeriodType periodType;
xdc_runtime_Types_FreqHz extFreq;
ti_sysbios_family_arm_m3_Hwi_Params *hwiParams;
xdc_runtime_IInstance_Params __iprms;
};
/* Struct */
struct ti_sysbios_family_arm_cc26xx_Timer_Struct {
const ti_sysbios_family_arm_cc26xx_Timer_Fxns__ *__fxns;
xdc_Bool f0;
xdc_Int f1;
ti_sysbios_interfaces_ITimer_StartMode f2;
xdc_UInt32 f3;
xdc_UArg f4;
ti_sysbios_family_arm_m3_Hwi_FuncPtr f5;
xdc_runtime_Types_FreqHz f6;
ti_sysbios_family_arm_m3_Hwi_Handle f7;
xdc_UInt64 f8;
xdc_UInt64 f9;
xdc_UInt64 f10;
xdc_UInt64 f11;
xdc_runtime_Types_CordAddr __name;
};
/*
* ======== VIRTUAL FUNCTIONS ========
*/
/* Fxns__ */
struct ti_sysbios_family_arm_cc26xx_Timer_Fxns__ {
const xdc_runtime_Types_Base* __base;
const xdc_runtime_Types_SysFxns2* __sysp;
xdc_UInt (*getNumTimers)(void);
ti_sysbios_interfaces_ITimer_Status (*getStatus)(xdc_UInt id);
xdc_Void (*startup)(void);
xdc_UInt32 (*getMaxTicks)(ti_sysbios_family_arm_cc26xx_Timer_Handle inst);
xdc_Void (*setNextTick)(ti_sysbios_family_arm_cc26xx_Timer_Handle inst, xdc_UInt32 ticks);
xdc_Void (*start)(ti_sysbios_family_arm_cc26xx_Timer_Handle inst);
xdc_Void (*stop)(ti_sysbios_family_arm_cc26xx_Timer_Handle inst);
xdc_Void (*setPeriod)(ti_sysbios_family_arm_cc26xx_Timer_Handle inst, xdc_UInt32 period);
xdc_Bool (*setPeriodMicroSecs)(ti_sysbios_family_arm_cc26xx_Timer_Handle inst, xdc_UInt32 microsecs);
xdc_UInt32 (*getPeriod)(ti_sysbios_family_arm_cc26xx_Timer_Handle inst);
xdc_UInt32 (*getCount)(ti_sysbios_family_arm_cc26xx_Timer_Handle inst);
xdc_Void (*getFreq)(ti_sysbios_family_arm_cc26xx_Timer_Handle inst, xdc_runtime_Types_FreqHz* freq);
ti_sysbios_interfaces_ITimer_FuncPtr (*getFunc)(ti_sysbios_family_arm_cc26xx_Timer_Handle inst, xdc_UArg* arg);
xdc_Void (*setFunc)(ti_sysbios_family_arm_cc26xx_Timer_Handle inst, ti_sysbios_interfaces_ITimer_FuncPtr fxn, xdc_UArg arg);
xdc_Void (*trigger)(ti_sysbios_family_arm_cc26xx_Timer_Handle inst, xdc_UInt32 cycles);
xdc_UInt32 (*getExpiredCounts)(ti_sysbios_family_arm_cc26xx_Timer_Handle inst);
xdc_UInt32 (*getExpiredTicks)(ti_sysbios_family_arm_cc26xx_Timer_Handle inst, xdc_UInt32 tickPeriod);
xdc_UInt32 (*getCurrentTick)(ti_sysbios_family_arm_cc26xx_Timer_Handle inst, xdc_Bool save);
xdc_runtime_Types_SysFxns2 __sfxns;
};
#ifndef ti_sysbios_family_arm_cc26xx_Timer_Module__FXNS__CR
/* Module__FXNS__C */
__extern const ti_sysbios_family_arm_cc26xx_Timer_Fxns__ ti_sysbios_family_arm_cc26xx_Timer_Module__FXNS__C;
#else
#define ti_sysbios_family_arm_cc26xx_Timer_Module__FXNS__C (*(xdcRomConstPtr + ti_sysbios_family_arm_cc26xx_Timer_Module__FXNS__C_offset))
#endif
/*
* ======== FUNCTION DECLARATIONS ========
*/
/* Module_startup */
#define ti_sysbios_family_arm_cc26xx_Timer_Module_startup ti_sysbios_family_arm_cc26xx_Timer_Module_startup__E
xdc__CODESECT(ti_sysbios_family_arm_cc26xx_Timer_Module_startup__E, "ti_sysbios_family_arm_cc26xx_Timer_Module_startup")
__extern xdc_Int ti_sysbios_family_arm_cc26xx_Timer_Module_startup__E( xdc_Int state );
xdc__CODESECT(ti_sysbios_family_arm_cc26xx_Timer_Module_startup__F, "ti_sysbios_family_arm_cc26xx_Timer_Module_startup")
__extern xdc_Int ti_sysbios_family_arm_cc26xx_Timer_Module_startup__F( xdc_Int state );
/* Instance_init__E */
xdc__CODESECT(ti_sysbios_family_arm_cc26xx_Timer_Instance_init__E, "ti_sysbios_family_arm_cc26xx_Timer_Instance_init")
__extern xdc_Int ti_sysbios_family_arm_cc26xx_Timer_Instance_init__E(ti_sysbios_family_arm_cc26xx_Timer_Object *obj, xdc_Int id, ti_sysbios_interfaces_ITimer_FuncPtr tickFxn, const ti_sysbios_family_arm_cc26xx_Timer_Params *prms, xdc_runtime_Error_Block *eb);
/* Instance_finalize__E */
xdc__CODESECT(ti_sysbios_family_arm_cc26xx_Timer_Instance_finalize__E, "ti_sysbios_family_arm_cc26xx_Timer_Instance_finalize")
__extern void ti_sysbios_family_arm_cc26xx_Timer_Instance_finalize__E(ti_sysbios_family_arm_cc26xx_Timer_Object *obj, int ec);
/* create */
xdc__CODESECT(ti_sysbios_family_arm_cc26xx_Timer_create, "ti_sysbios_family_arm_cc26xx_Timer_create")
__extern ti_sysbios_family_arm_cc26xx_Timer_Handle ti_sysbios_family_arm_cc26xx_Timer_create( xdc_Int id, ti_sysbios_interfaces_ITimer_FuncPtr tickFxn, const ti_sysbios_family_arm_cc26xx_Timer_Params *prms, xdc_runtime_Error_Block *eb);
/* construct */
xdc__CODESECT(ti_sysbios_family_arm_cc26xx_Timer_construct, "ti_sysbios_family_arm_cc26xx_Timer_construct")
__extern void ti_sysbios_family_arm_cc26xx_Timer_construct(ti_sysbios_family_arm_cc26xx_Timer_Struct *obj, xdc_Int id, ti_sysbios_interfaces_ITimer_FuncPtr tickFxn, const ti_sysbios_family_arm_cc26xx_Timer_Params *prms, xdc_runtime_Error_Block *eb);
/* delete */
xdc__CODESECT(ti_sysbios_family_arm_cc26xx_Timer_delete, "ti_sysbios_family_arm_cc26xx_Timer_delete")
__extern void ti_sysbios_family_arm_cc26xx_Timer_delete(ti_sysbios_family_arm_cc26xx_Timer_Handle *instp);
/* destruct */
xdc__CODESECT(ti_sysbios_family_arm_cc26xx_Timer_destruct, "ti_sysbios_family_arm_cc26xx_Timer_destruct")
__extern void ti_sysbios_family_arm_cc26xx_Timer_destruct(ti_sysbios_family_arm_cc26xx_Timer_Struct *obj);
/* Handle__label__S */
xdc__CODESECT(ti_sysbios_family_arm_cc26xx_Timer_Handle__label__S, "ti_sysbios_family_arm_cc26xx_Timer_Handle__label__S")
__extern xdc_runtime_Types_Label *ti_sysbios_family_arm_cc26xx_Timer_Handle__label__S( xdc_Ptr obj, xdc_runtime_Types_Label *lab);
/* Module__startupDone__S */
xdc__CODESECT(ti_sysbios_family_arm_cc26xx_Timer_Module__startupDone__S, "ti_sysbios_family_arm_cc26xx_Timer_Module__startupDone__S")
__extern xdc_Bool ti_sysbios_family_arm_cc26xx_Timer_Module__startupDone__S( void);
/* Object__create__S */
xdc__CODESECT(ti_sysbios_family_arm_cc26xx_Timer_Object__create__S, "ti_sysbios_family_arm_cc26xx_Timer_Object__create__S")
__extern xdc_Ptr ti_sysbios_family_arm_cc26xx_Timer_Object__create__S( xdc_CPtr aa, const xdc_UChar *pa, xdc_SizeT psz, xdc_runtime_Error_Block *eb);
/* Object__delete__S */
xdc__CODESECT(ti_sysbios_family_arm_cc26xx_Timer_Object__delete__S, "ti_sysbios_family_arm_cc26xx_Timer_Object__delete__S")
__extern xdc_Void ti_sysbios_family_arm_cc26xx_Timer_Object__delete__S( xdc_Ptr instp);
/* Object__get__S */
xdc__CODESECT(ti_sysbios_family_arm_cc26xx_Timer_Object__get__S, "ti_sysbios_family_arm_cc26xx_Timer_Object__get__S")
__extern xdc_Ptr ti_sysbios_family_arm_cc26xx_Timer_Object__get__S( xdc_Ptr oarr, xdc_Int i);
/* Object__first__S */
xdc__CODESECT(ti_sysbios_family_arm_cc26xx_Timer_Object__first__S, "ti_sysbios_family_arm_cc26xx_Timer_Object__first__S")
__extern xdc_Ptr ti_sysbios_family_arm_cc26xx_Timer_Object__first__S( void);
/* Object__next__S */
xdc__CODESECT(ti_sysbios_family_arm_cc26xx_Timer_Object__next__S, "ti_sysbios_family_arm_cc26xx_Timer_Object__next__S")
__extern xdc_Ptr ti_sysbios_family_arm_cc26xx_Timer_Object__next__S( xdc_Ptr obj);
/* Params__init__S */
xdc__CODESECT(ti_sysbios_family_arm_cc26xx_Timer_Params__init__S, "ti_sysbios_family_arm_cc26xx_Timer_Params__init__S")
__extern xdc_Void ti_sysbios_family_arm_cc26xx_Timer_Params__init__S( xdc_Ptr dst, const xdc_Void *src, xdc_SizeT psz, xdc_SizeT isz);
/* getNumTimers__E */
#define ti_sysbios_family_arm_cc26xx_Timer_getNumTimers ti_sysbios_family_arm_cc26xx_Timer_getNumTimers__E
xdc__CODESECT(ti_sysbios_family_arm_cc26xx_Timer_getNumTimers__E, "ti_sysbios_family_arm_cc26xx_Timer_getNumTimers")
__extern xdc_UInt ti_sysbios_family_arm_cc26xx_Timer_getNumTimers__E( void);
/* getStatus__E */
#define ti_sysbios_family_arm_cc26xx_Timer_getStatus ti_sysbios_family_arm_cc26xx_Timer_getStatus__E
xdc__CODESECT(ti_sysbios_family_arm_cc26xx_Timer_getStatus__E, "ti_sysbios_family_arm_cc26xx_Timer_getStatus")
__extern ti_sysbios_interfaces_ITimer_Status ti_sysbios_family_arm_cc26xx_Timer_getStatus__E( xdc_UInt id);
/* startup__E */
#define ti_sysbios_family_arm_cc26xx_Timer_startup ti_sysbios_family_arm_cc26xx_Timer_startup__E
xdc__CODESECT(ti_sysbios_family_arm_cc26xx_Timer_startup__E, "ti_sysbios_family_arm_cc26xx_Timer_startup")
__extern xdc_Void ti_sysbios_family_arm_cc26xx_Timer_startup__E( void);
/* getMaxTicks__E */
#define ti_sysbios_family_arm_cc26xx_Timer_getMaxTicks ti_sysbios_family_arm_cc26xx_Timer_getMaxTicks__E
xdc__CODESECT(ti_sysbios_family_arm_cc26xx_Timer_getMaxTicks__E, "ti_sysbios_family_arm_cc26xx_Timer_getMaxTicks")
__extern xdc_UInt32 ti_sysbios_family_arm_cc26xx_Timer_getMaxTicks__E( ti_sysbios_family_arm_cc26xx_Timer_Handle instp);
/* setNextTick__E */
#define ti_sysbios_family_arm_cc26xx_Timer_setNextTick ti_sysbios_family_arm_cc26xx_Timer_setNextTick__E
xdc__CODESECT(ti_sysbios_family_arm_cc26xx_Timer_setNextTick__E, "ti_sysbios_family_arm_cc26xx_Timer_setNextTick")
__extern xdc_Void ti_sysbios_family_arm_cc26xx_Timer_setNextTick__E( ti_sysbios_family_arm_cc26xx_Timer_Handle instp, xdc_UInt32 ticks);
/* start__E */
#define ti_sysbios_family_arm_cc26xx_Timer_start ti_sysbios_family_arm_cc26xx_Timer_start__E
xdc__CODESECT(ti_sysbios_family_arm_cc26xx_Timer_start__E, "ti_sysbios_family_arm_cc26xx_Timer_start")
__extern xdc_Void ti_sysbios_family_arm_cc26xx_Timer_start__E( ti_sysbios_family_arm_cc26xx_Timer_Handle instp);
/* stop__E */
#define ti_sysbios_family_arm_cc26xx_Timer_stop ti_sysbios_family_arm_cc26xx_Timer_stop__E
xdc__CODESECT(ti_sysbios_family_arm_cc26xx_Timer_stop__E, "ti_sysbios_family_arm_cc26xx_Timer_stop")
__extern xdc_Void ti_sysbios_family_arm_cc26xx_Timer_stop__E( ti_sysbios_family_arm_cc26xx_Timer_Handle instp);
/* setPeriod__E */
#define ti_sysbios_family_arm_cc26xx_Timer_setPeriod ti_sysbios_family_arm_cc26xx_Timer_setPeriod__E
xdc__CODESECT(ti_sysbios_family_arm_cc26xx_Timer_setPeriod__E, "ti_sysbios_family_arm_cc26xx_Timer_setPeriod")
__extern xdc_Void ti_sysbios_family_arm_cc26xx_Timer_setPeriod__E( ti_sysbios_family_arm_cc26xx_Timer_Handle instp, xdc_UInt32 period);
/* setPeriodMicroSecs__E */
#define ti_sysbios_family_arm_cc26xx_Timer_setPeriodMicroSecs ti_sysbios_family_arm_cc26xx_Timer_setPeriodMicroSecs__E
xdc__CODESECT(ti_sysbios_family_arm_cc26xx_Timer_setPeriodMicroSecs__E, "ti_sysbios_family_arm_cc26xx_Timer_setPeriodMicroSecs")
__extern xdc_Bool ti_sysbios_family_arm_cc26xx_Timer_setPeriodMicroSecs__E( ti_sysbios_family_arm_cc26xx_Timer_Handle instp, xdc_UInt32 microsecs);
/* getPeriod__E */
#define ti_sysbios_family_arm_cc26xx_Timer_getPeriod ti_sysbios_family_arm_cc26xx_Timer_getPeriod__E
xdc__CODESECT(ti_sysbios_family_arm_cc26xx_Timer_getPeriod__E, "ti_sysbios_family_arm_cc26xx_Timer_getPeriod")
__extern xdc_UInt32 ti_sysbios_family_arm_cc26xx_Timer_getPeriod__E( ti_sysbios_family_arm_cc26xx_Timer_Handle instp);
/* getCount__E */
#define ti_sysbios_family_arm_cc26xx_Timer_getCount ti_sysbios_family_arm_cc26xx_Timer_getCount__E
xdc__CODESECT(ti_sysbios_family_arm_cc26xx_Timer_getCount__E, "ti_sysbios_family_arm_cc26xx_Timer_getCount")
__extern xdc_UInt32 ti_sysbios_family_arm_cc26xx_Timer_getCount__E( ti_sysbios_family_arm_cc26xx_Timer_Handle instp);
/* getFreq__E */
#define ti_sysbios_family_arm_cc26xx_Timer_getFreq ti_sysbios_family_arm_cc26xx_Timer_getFreq__E
xdc__CODESECT(ti_sysbios_family_arm_cc26xx_Timer_getFreq__E, "ti_sysbios_family_arm_cc26xx_Timer_getFreq")
__extern xdc_Void ti_sysbios_family_arm_cc26xx_Timer_getFreq__E( ti_sysbios_family_arm_cc26xx_Timer_Handle instp, xdc_runtime_Types_FreqHz *freq);
/* getFunc__E */
#define ti_sysbios_family_arm_cc26xx_Timer_getFunc ti_sysbios_family_arm_cc26xx_Timer_getFunc__E
xdc__CODESECT(ti_sysbios_family_arm_cc26xx_Timer_getFunc__E, "ti_sysbios_family_arm_cc26xx_Timer_getFunc")
__extern ti_sysbios_interfaces_ITimer_FuncPtr ti_sysbios_family_arm_cc26xx_Timer_getFunc__E( ti_sysbios_family_arm_cc26xx_Timer_Handle instp, xdc_UArg *arg);
/* setFunc__E */
#define ti_sysbios_family_arm_cc26xx_Timer_setFunc ti_sysbios_family_arm_cc26xx_Timer_setFunc__E
xdc__CODESECT(ti_sysbios_family_arm_cc26xx_Timer_setFunc__E, "ti_sysbios_family_arm_cc26xx_Timer_setFunc")
__extern xdc_Void ti_sysbios_family_arm_cc26xx_Timer_setFunc__E( ti_sysbios_family_arm_cc26xx_Timer_Handle instp, ti_sysbios_interfaces_ITimer_FuncPtr fxn, xdc_UArg arg);
/* trigger__E */
#define ti_sysbios_family_arm_cc26xx_Timer_trigger ti_sysbios_family_arm_cc26xx_Timer_trigger__E
xdc__CODESECT(ti_sysbios_family_arm_cc26xx_Timer_trigger__E, "ti_sysbios_family_arm_cc26xx_Timer_trigger")
__extern xdc_Void ti_sysbios_family_arm_cc26xx_Timer_trigger__E( ti_sysbios_family_arm_cc26xx_Timer_Handle instp, xdc_UInt32 cycles);
/* getExpiredCounts__E */
#define ti_sysbios_family_arm_cc26xx_Timer_getExpiredCounts ti_sysbios_family_arm_cc26xx_Timer_getExpiredCounts__E
xdc__CODESECT(ti_sysbios_family_arm_cc26xx_Timer_getExpiredCounts__E, "ti_sysbios_family_arm_cc26xx_Timer_getExpiredCounts")
__extern xdc_UInt32 ti_sysbios_family_arm_cc26xx_Timer_getExpiredCounts__E( ti_sysbios_family_arm_cc26xx_Timer_Handle instp);
/* getExpiredTicks__E */
#define ti_sysbios_family_arm_cc26xx_Timer_getExpiredTicks ti_sysbios_family_arm_cc26xx_Timer_getExpiredTicks__E
xdc__CODESECT(ti_sysbios_family_arm_cc26xx_Timer_getExpiredTicks__E, "ti_sysbios_family_arm_cc26xx_Timer_getExpiredTicks")
__extern xdc_UInt32 ti_sysbios_family_arm_cc26xx_Timer_getExpiredTicks__E( ti_sysbios_family_arm_cc26xx_Timer_Handle instp, xdc_UInt32 tickPeriod);
/* getCurrentTick__E */
#define ti_sysbios_family_arm_cc26xx_Timer_getCurrentTick ti_sysbios_family_arm_cc26xx_Timer_getCurrentTick__E
xdc__CODESECT(ti_sysbios_family_arm_cc26xx_Timer_getCurrentTick__E, "ti_sysbios_family_arm_cc26xx_Timer_getCurrentTick")
__extern xdc_UInt32 ti_sysbios_family_arm_cc26xx_Timer_getCurrentTick__E( ti_sysbios_family_arm_cc26xx_Timer_Handle instp, xdc_Bool save);
/* dynamicStub__E */
#define ti_sysbios_family_arm_cc26xx_Timer_dynamicStub ti_sysbios_family_arm_cc26xx_Timer_dynamicStub__E
xdc__CODESECT(ti_sysbios_family_arm_cc26xx_Timer_dynamicStub__E, "ti_sysbios_family_arm_cc26xx_Timer_dynamicStub")
__extern xdc_Void ti_sysbios_family_arm_cc26xx_Timer_dynamicStub__E( xdc_UArg arg);
/* dynamicMultiStub__E */
#define ti_sysbios_family_arm_cc26xx_Timer_dynamicMultiStub ti_sysbios_family_arm_cc26xx_Timer_dynamicMultiStub__E
xdc__CODESECT(ti_sysbios_family_arm_cc26xx_Timer_dynamicMultiStub__E, "ti_sysbios_family_arm_cc26xx_Timer_dynamicMultiStub")
__extern xdc_Void ti_sysbios_family_arm_cc26xx_Timer_dynamicMultiStub__E( xdc_UArg arg);
/* periodicStub__E */
#define ti_sysbios_family_arm_cc26xx_Timer_periodicStub ti_sysbios_family_arm_cc26xx_Timer_periodicStub__E
xdc__CODESECT(ti_sysbios_family_arm_cc26xx_Timer_periodicStub__E, "ti_sysbios_family_arm_cc26xx_Timer_periodicStub")
__extern xdc_Void ti_sysbios_family_arm_cc26xx_Timer_periodicStub__E( xdc_UArg arg);
/* getCount64__E */
#define ti_sysbios_family_arm_cc26xx_Timer_getCount64 ti_sysbios_family_arm_cc26xx_Timer_getCount64__E
xdc__CODESECT(ti_sysbios_family_arm_cc26xx_Timer_getCount64__E, "ti_sysbios_family_arm_cc26xx_Timer_getCount64")
__extern xdc_UInt64 ti_sysbios_family_arm_cc26xx_Timer_getCount64__E( ti_sysbios_family_arm_cc26xx_Timer_Object *timer);
/* getExpiredCounts64__E */
#define ti_sysbios_family_arm_cc26xx_Timer_getExpiredCounts64 ti_sysbios_family_arm_cc26xx_Timer_getExpiredCounts64__E
xdc__CODESECT(ti_sysbios_family_arm_cc26xx_Timer_getExpiredCounts64__E, "ti_sysbios_family_arm_cc26xx_Timer_getExpiredCounts64")
__extern xdc_UInt64 ti_sysbios_family_arm_cc26xx_Timer_getExpiredCounts64__E( ti_sysbios_family_arm_cc26xx_Timer_Object *timer);
/* getHandle__E */
#define ti_sysbios_family_arm_cc26xx_Timer_getHandle ti_sysbios_family_arm_cc26xx_Timer_getHandle__E
xdc__CODESECT(ti_sysbios_family_arm_cc26xx_Timer_getHandle__E, "ti_sysbios_family_arm_cc26xx_Timer_getHandle")
__extern ti_sysbios_family_arm_cc26xx_Timer_Handle ti_sysbios_family_arm_cc26xx_Timer_getHandle__E( xdc_UInt id);
/* initDevice__I */
#define ti_sysbios_family_arm_cc26xx_Timer_initDevice ti_sysbios_family_arm_cc26xx_Timer_initDevice__I
xdc__CODESECT(ti_sysbios_family_arm_cc26xx_Timer_initDevice__I, "ti_sysbios_family_arm_cc26xx_Timer_initDevice")
__extern xdc_Void ti_sysbios_family_arm_cc26xx_Timer_initDevice__I( ti_sysbios_family_arm_cc26xx_Timer_Object *timer);
/* postInit__I */
#define ti_sysbios_family_arm_cc26xx_Timer_postInit ti_sysbios_family_arm_cc26xx_Timer_postInit__I
xdc__CODESECT(ti_sysbios_family_arm_cc26xx_Timer_postInit__I, "ti_sysbios_family_arm_cc26xx_Timer_postInit")
__extern xdc_Int ti_sysbios_family_arm_cc26xx_Timer_postInit__I( ti_sysbios_family_arm_cc26xx_Timer_Object *timer, xdc_runtime_Error_Block *eb);
/* setThreshold__I */
#define ti_sysbios_family_arm_cc26xx_Timer_setThreshold ti_sysbios_family_arm_cc26xx_Timer_setThreshold__I
xdc__CODESECT(ti_sysbios_family_arm_cc26xx_Timer_setThreshold__I, "ti_sysbios_family_arm_cc26xx_Timer_setThreshold")
__extern xdc_Void ti_sysbios_family_arm_cc26xx_Timer_setThreshold__I( ti_sysbios_family_arm_cc26xx_Timer_Object *timer, xdc_UInt32 next, xdc_Bool wrap);
/*
* ======== CONVERTORS ========
*/
/* Module_upCast */
static inline ti_sysbios_interfaces_ITimer_Module ti_sysbios_family_arm_cc26xx_Timer_Module_upCast(void);
static inline ti_sysbios_interfaces_ITimer_Module ti_sysbios_family_arm_cc26xx_Timer_Module_upCast(void)
{
return (ti_sysbios_interfaces_ITimer_Module)&ti_sysbios_family_arm_cc26xx_Timer_Module__FXNS__C;
}
/* Module_to_ti_sysbios_interfaces_ITimer */
#define ti_sysbios_family_arm_cc26xx_Timer_Module_to_ti_sysbios_interfaces_ITimer ti_sysbios_family_arm_cc26xx_Timer_Module_upCast
/* Handle_upCast */
static inline ti_sysbios_interfaces_ITimer_Handle ti_sysbios_family_arm_cc26xx_Timer_Handle_upCast(ti_sysbios_family_arm_cc26xx_Timer_Handle i);
static inline ti_sysbios_interfaces_ITimer_Handle ti_sysbios_family_arm_cc26xx_Timer_Handle_upCast(ti_sysbios_family_arm_cc26xx_Timer_Handle i)
{
return (ti_sysbios_interfaces_ITimer_Handle)i;
}
/* Handle_to_ti_sysbios_interfaces_ITimer */
#define ti_sysbios_family_arm_cc26xx_Timer_Handle_to_ti_sysbios_interfaces_ITimer ti_sysbios_family_arm_cc26xx_Timer_Handle_upCast
/* Handle_downCast */
static inline ti_sysbios_family_arm_cc26xx_Timer_Handle ti_sysbios_family_arm_cc26xx_Timer_Handle_downCast(ti_sysbios_interfaces_ITimer_Handle i);
static inline ti_sysbios_family_arm_cc26xx_Timer_Handle ti_sysbios_family_arm_cc26xx_Timer_Handle_downCast(ti_sysbios_interfaces_ITimer_Handle i)
{
ti_sysbios_interfaces_ITimer_Handle i2 = (ti_sysbios_interfaces_ITimer_Handle)i;
return ((const void*)i2->__fxns == (const void*)&ti_sysbios_family_arm_cc26xx_Timer_Module__FXNS__C) ? (ti_sysbios_family_arm_cc26xx_Timer_Handle)i : (ti_sysbios_family_arm_cc26xx_Timer_Handle)NULL;
}
/* Handle_from_ti_sysbios_interfaces_ITimer */
#define ti_sysbios_family_arm_cc26xx_Timer_Handle_from_ti_sysbios_interfaces_ITimer ti_sysbios_family_arm_cc26xx_Timer_Handle_downCast
/*
* ======== SYSTEM FUNCTIONS ========
*/
/* Module_startupDone */
#define ti_sysbios_family_arm_cc26xx_Timer_Module_startupDone() ti_sysbios_family_arm_cc26xx_Timer_Module__startupDone__S()
/* Object_heap */
#define ti_sysbios_family_arm_cc26xx_Timer_Object_heap() ti_sysbios_family_arm_cc26xx_Timer_Object__heap__C
/* Module_heap */
#define ti_sysbios_family_arm_cc26xx_Timer_Module_heap() ti_sysbios_family_arm_cc26xx_Timer_Object__heap__C
/* Module_id */
static inline CT__ti_sysbios_family_arm_cc26xx_Timer_Module__id ti_sysbios_family_arm_cc26xx_Timer_Module_id(void);
static inline CT__ti_sysbios_family_arm_cc26xx_Timer_Module__id ti_sysbios_family_arm_cc26xx_Timer_Module_id( void )
{
return ti_sysbios_family_arm_cc26xx_Timer_Module__id__C;
}
/* Module_hasMask */
static inline xdc_Bool ti_sysbios_family_arm_cc26xx_Timer_Module_hasMask(void);
static inline xdc_Bool ti_sysbios_family_arm_cc26xx_Timer_Module_hasMask(void)
{
return (xdc_Bool)(ti_sysbios_family_arm_cc26xx_Timer_Module__diagsMask__C != (CT__ti_sysbios_family_arm_cc26xx_Timer_Module__diagsMask)NULL);
}
/* Module_getMask */
static inline xdc_Bits16 ti_sysbios_family_arm_cc26xx_Timer_Module_getMask(void);
static inline xdc_Bits16 ti_sysbios_family_arm_cc26xx_Timer_Module_getMask(void)
{
return (ti_sysbios_family_arm_cc26xx_Timer_Module__diagsMask__C != (CT__ti_sysbios_family_arm_cc26xx_Timer_Module__diagsMask)NULL) ? *ti_sysbios_family_arm_cc26xx_Timer_Module__diagsMask__C : (xdc_Bits16)0;
}
/* Module_setMask */
static inline xdc_Void ti_sysbios_family_arm_cc26xx_Timer_Module_setMask(xdc_Bits16 mask);
static inline xdc_Void ti_sysbios_family_arm_cc26xx_Timer_Module_setMask(xdc_Bits16 mask)
{
if (ti_sysbios_family_arm_cc26xx_Timer_Module__diagsMask__C != (CT__ti_sysbios_family_arm_cc26xx_Timer_Module__diagsMask)NULL) {
*ti_sysbios_family_arm_cc26xx_Timer_Module__diagsMask__C = mask;
}
}
/* Params_init */
static inline void ti_sysbios_family_arm_cc26xx_Timer_Params_init(ti_sysbios_family_arm_cc26xx_Timer_Params *prms);
static inline void ti_sysbios_family_arm_cc26xx_Timer_Params_init( ti_sysbios_family_arm_cc26xx_Timer_Params *prms )
{
if (prms != NULL) {
ti_sysbios_family_arm_cc26xx_Timer_Params__init__S(prms, NULL, sizeof(ti_sysbios_family_arm_cc26xx_Timer_Params), sizeof(xdc_runtime_IInstance_Params));
}
}
/* Params_copy */
static inline void ti_sysbios_family_arm_cc26xx_Timer_Params_copy(ti_sysbios_family_arm_cc26xx_Timer_Params *dst, const ti_sysbios_family_arm_cc26xx_Timer_Params *src);
static inline void ti_sysbios_family_arm_cc26xx_Timer_Params_copy(ti_sysbios_family_arm_cc26xx_Timer_Params *dst, const ti_sysbios_family_arm_cc26xx_Timer_Params *src)
{
if (dst != NULL) {
ti_sysbios_family_arm_cc26xx_Timer_Params__init__S(dst, (const void *)src, sizeof(ti_sysbios_family_arm_cc26xx_Timer_Params), sizeof(xdc_runtime_IInstance_Params));
}
}
/* Object_count */
#define ti_sysbios_family_arm_cc26xx_Timer_Object_count() ti_sysbios_family_arm_cc26xx_Timer_Object__count__C
/* Object_sizeof */
#define ti_sysbios_family_arm_cc26xx_Timer_Object_sizeof() ti_sysbios_family_arm_cc26xx_Timer_Object__sizeof__C
/* Object_get */
static inline ti_sysbios_family_arm_cc26xx_Timer_Handle ti_sysbios_family_arm_cc26xx_Timer_Object_get(ti_sysbios_family_arm_cc26xx_Timer_Object *oarr, int i);
static inline ti_sysbios_family_arm_cc26xx_Timer_Handle ti_sysbios_family_arm_cc26xx_Timer_Object_get(ti_sysbios_family_arm_cc26xx_Timer_Object *oarr, int i)
{
return (ti_sysbios_family_arm_cc26xx_Timer_Handle)ti_sysbios_family_arm_cc26xx_Timer_Object__get__S(oarr, i);
}
/* Object_first */
static inline ti_sysbios_family_arm_cc26xx_Timer_Handle ti_sysbios_family_arm_cc26xx_Timer_Object_first(void);
static inline ti_sysbios_family_arm_cc26xx_Timer_Handle ti_sysbios_family_arm_cc26xx_Timer_Object_first(void)
{
return (ti_sysbios_family_arm_cc26xx_Timer_Handle)ti_sysbios_family_arm_cc26xx_Timer_Object__first__S();
}
/* Object_next */
static inline ti_sysbios_family_arm_cc26xx_Timer_Handle ti_sysbios_family_arm_cc26xx_Timer_Object_next(ti_sysbios_family_arm_cc26xx_Timer_Object *obj);
static inline ti_sysbios_family_arm_cc26xx_Timer_Handle ti_sysbios_family_arm_cc26xx_Timer_Object_next(ti_sysbios_family_arm_cc26xx_Timer_Object *obj)
{
return (ti_sysbios_family_arm_cc26xx_Timer_Handle)ti_sysbios_family_arm_cc26xx_Timer_Object__next__S(obj);
}
/* Handle_label */
static inline xdc_runtime_Types_Label *ti_sysbios_family_arm_cc26xx_Timer_Handle_label(ti_sysbios_family_arm_cc26xx_Timer_Handle inst, xdc_runtime_Types_Label *lab);
static inline xdc_runtime_Types_Label *ti_sysbios_family_arm_cc26xx_Timer_Handle_label(ti_sysbios_family_arm_cc26xx_Timer_Handle inst, xdc_runtime_Types_Label *lab)
{
return ti_sysbios_family_arm_cc26xx_Timer_Handle__label__S(inst, lab);
}
/* Handle_name */
static inline xdc_String ti_sysbios_family_arm_cc26xx_Timer_Handle_name(ti_sysbios_family_arm_cc26xx_Timer_Handle inst);
static inline xdc_String ti_sysbios_family_arm_cc26xx_Timer_Handle_name(ti_sysbios_family_arm_cc26xx_Timer_Handle inst)
{
xdc_runtime_Types_Label lab;
return ti_sysbios_family_arm_cc26xx_Timer_Handle__label__S(inst, &lab)->iname;
}
/* handle */
static inline ti_sysbios_family_arm_cc26xx_Timer_Handle ti_sysbios_family_arm_cc26xx_Timer_handle(ti_sysbios_family_arm_cc26xx_Timer_Struct *str);
static inline ti_sysbios_family_arm_cc26xx_Timer_Handle ti_sysbios_family_arm_cc26xx_Timer_handle(ti_sysbios_family_arm_cc26xx_Timer_Struct *str)
{
return (ti_sysbios_family_arm_cc26xx_Timer_Handle)str;
}
/* struct */
static inline ti_sysbios_family_arm_cc26xx_Timer_Struct *ti_sysbios_family_arm_cc26xx_Timer_struct(ti_sysbios_family_arm_cc26xx_Timer_Handle inst);
static inline ti_sysbios_family_arm_cc26xx_Timer_Struct *ti_sysbios_family_arm_cc26xx_Timer_struct(ti_sysbios_family_arm_cc26xx_Timer_Handle inst)
{
return (ti_sysbios_family_arm_cc26xx_Timer_Struct*)inst;
}
/*
* ======== EPILOGUE ========
*/
#ifdef ti_sysbios_family_arm_cc26xx_Timer__top__
#undef __nested__
#endif
#endif /* ti_sysbios_family_arm_cc26xx_Timer__include */
/*
* ======== STATE STRUCTURES ========
*/
#if defined(__config__) || (!defined(__nested__) && defined(ti_sysbios_family_arm_cc26xx_Timer__internalaccess))
#ifndef ti_sysbios_family_arm_cc26xx_Timer__include_state
#define ti_sysbios_family_arm_cc26xx_Timer__include_state
/* Module_State */
struct ti_sysbios_family_arm_cc26xx_Timer_Module_State {
xdc_UInt availMask;
ti_sysbios_family_arm_cc26xx_Timer_Handle handle;
};
/* Module__state__V */
#ifndef ti_sysbios_family_arm_cc26xx_Timer_Module__state__VR
extern struct ti_sysbios_family_arm_cc26xx_Timer_Module_State__ ti_sysbios_family_arm_cc26xx_Timer_Module__state__V;
#else
#define ti_sysbios_family_arm_cc26xx_Timer_Module__state__V (*((struct ti_sysbios_family_arm_cc26xx_Timer_Module_State__*)(xdcRomStatePtr + ti_sysbios_family_arm_cc26xx_Timer_Module__state__V_offset)))
#endif
/* Object */
struct ti_sysbios_family_arm_cc26xx_Timer_Object {
const ti_sysbios_family_arm_cc26xx_Timer_Fxns__ *__fxns;
xdc_Bool staticInst;
xdc_Int id;
ti_sysbios_interfaces_ITimer_StartMode startMode;
xdc_UInt32 period;
xdc_UArg arg;
ti_sysbios_family_arm_m3_Hwi_FuncPtr tickFxn;
xdc_runtime_Types_FreqHz frequency;
ti_sysbios_family_arm_m3_Hwi_Handle hwi;
xdc_UInt64 period64;
xdc_UInt64 savedCurrCount;
xdc_UInt64 prevThreshold;
xdc_UInt64 nextThreshold;
};
#endif /* ti_sysbios_family_arm_cc26xx_Timer__include_state */
#endif
/*
* ======== PREFIX ALIASES ========
*/
#if !defined(__nested__) && !defined(ti_sysbios_family_arm_cc26xx_Timer__nolocalnames)
#ifndef ti_sysbios_family_arm_cc26xx_Timer__localnames__done
#define ti_sysbios_family_arm_cc26xx_Timer__localnames__done
/* module prefix */
#define Timer_Instance ti_sysbios_family_arm_cc26xx_Timer_Instance
#define Timer_Handle ti_sysbios_family_arm_cc26xx_Timer_Handle
#define Timer_Module ti_sysbios_family_arm_cc26xx_Timer_Module
#define Timer_Object ti_sysbios_family_arm_cc26xx_Timer_Object
#define Timer_Struct ti_sysbios_family_arm_cc26xx_Timer_Struct
#define Timer_FuncPtr ti_sysbios_family_arm_cc26xx_Timer_FuncPtr
#define Timer_ANY ti_sysbios_family_arm_cc26xx_Timer_ANY
#define Timer_StartMode ti_sysbios_family_arm_cc26xx_Timer_StartMode
#define Timer_RunMode ti_sysbios_family_arm_cc26xx_Timer_RunMode
#define Timer_Status ti_sysbios_family_arm_cc26xx_Timer_Status
#define Timer_PeriodType ti_sysbios_family_arm_cc26xx_Timer_PeriodType
#define Timer_MAX_PERIOD ti_sysbios_family_arm_cc26xx_Timer_MAX_PERIOD
#define Timer_MIN_SWEEP_PERIOD ti_sysbios_family_arm_cc26xx_Timer_MIN_SWEEP_PERIOD
#define Timer_Instance_State ti_sysbios_family_arm_cc26xx_Timer_Instance_State
#define Timer_Module_State ti_sysbios_family_arm_cc26xx_Timer_Module_State
#define Timer_StartMode_AUTO ti_sysbios_family_arm_cc26xx_Timer_StartMode_AUTO
#define Timer_StartMode_USER ti_sysbios_family_arm_cc26xx_Timer_StartMode_USER
#define Timer_RunMode_CONTINUOUS ti_sysbios_family_arm_cc26xx_Timer_RunMode_CONTINUOUS
#define Timer_RunMode_ONESHOT ti_sysbios_family_arm_cc26xx_Timer_RunMode_ONESHOT
#define Timer_RunMode_DYNAMIC ti_sysbios_family_arm_cc26xx_Timer_RunMode_DYNAMIC
#define Timer_Status_INUSE ti_sysbios_family_arm_cc26xx_Timer_Status_INUSE
#define Timer_Status_FREE ti_sysbios_family_arm_cc26xx_Timer_Status_FREE
#define Timer_PeriodType_MICROSECS ti_sysbios_family_arm_cc26xx_Timer_PeriodType_MICROSECS
#define Timer_PeriodType_COUNTS ti_sysbios_family_arm_cc26xx_Timer_PeriodType_COUNTS
#define Timer_E_invalidTimer ti_sysbios_family_arm_cc26xx_Timer_E_invalidTimer
#define Timer_E_notAvailable ti_sysbios_family_arm_cc26xx_Timer_E_notAvailable
#define Timer_E_cannotSupport ti_sysbios_family_arm_cc26xx_Timer_E_cannotSupport
#define Timer_anyMask ti_sysbios_family_arm_cc26xx_Timer_anyMask
#define Timer_funcHookCH1 ti_sysbios_family_arm_cc26xx_Timer_funcHookCH1
#define Timer_funcHookCH2 ti_sysbios_family_arm_cc26xx_Timer_funcHookCH2
#define Timer_startupNeeded ti_sysbios_family_arm_cc26xx_Timer_startupNeeded
#define Timer_Params ti_sysbios_family_arm_cc26xx_Timer_Params
#define Timer_getNumTimers ti_sysbios_family_arm_cc26xx_Timer_getNumTimers
#define Timer_getStatus ti_sysbios_family_arm_cc26xx_Timer_getStatus
#define Timer_startup ti_sysbios_family_arm_cc26xx_Timer_startup
#define Timer_getMaxTicks ti_sysbios_family_arm_cc26xx_Timer_getMaxTicks
#define Timer_setNextTick ti_sysbios_family_arm_cc26xx_Timer_setNextTick
#define Timer_start ti_sysbios_family_arm_cc26xx_Timer_start
#define Timer_stop ti_sysbios_family_arm_cc26xx_Timer_stop
#define Timer_setPeriod ti_sysbios_family_arm_cc26xx_Timer_setPeriod
#define Timer_setPeriodMicroSecs ti_sysbios_family_arm_cc26xx_Timer_setPeriodMicroSecs
#define Timer_getPeriod ti_sysbios_family_arm_cc26xx_Timer_getPeriod
#define Timer_getCount ti_sysbios_family_arm_cc26xx_Timer_getCount
#define Timer_getFreq ti_sysbios_family_arm_cc26xx_Timer_getFreq
#define Timer_getFunc ti_sysbios_family_arm_cc26xx_Timer_getFunc
#define Timer_setFunc ti_sysbios_family_arm_cc26xx_Timer_setFunc
#define Timer_trigger ti_sysbios_family_arm_cc26xx_Timer_trigger
#define Timer_getExpiredCounts ti_sysbios_family_arm_cc26xx_Timer_getExpiredCounts
#define Timer_getExpiredTicks ti_sysbios_family_arm_cc26xx_Timer_getExpiredTicks
#define Timer_getCurrentTick ti_sysbios_family_arm_cc26xx_Timer_getCurrentTick
#define Timer_dynamicStub ti_sysbios_family_arm_cc26xx_Timer_dynamicStub
#define Timer_dynamicMultiStub ti_sysbios_family_arm_cc26xx_Timer_dynamicMultiStub
#define Timer_periodicStub ti_sysbios_family_arm_cc26xx_Timer_periodicStub
#define Timer_getCount64 ti_sysbios_family_arm_cc26xx_Timer_getCount64
#define Timer_getExpiredCounts64 ti_sysbios_family_arm_cc26xx_Timer_getExpiredCounts64
#define Timer_getHandle ti_sysbios_family_arm_cc26xx_Timer_getHandle
#define Timer_Module_name ti_sysbios_family_arm_cc26xx_Timer_Module_name
#define Timer_Module_id ti_sysbios_family_arm_cc26xx_Timer_Module_id
#define Timer_Module_startup ti_sysbios_family_arm_cc26xx_Timer_Module_startup
#define Timer_Module_startupDone ti_sysbios_family_arm_cc26xx_Timer_Module_startupDone
#define Timer_Module_hasMask ti_sysbios_family_arm_cc26xx_Timer_Module_hasMask
#define Timer_Module_getMask ti_sysbios_family_arm_cc26xx_Timer_Module_getMask
#define Timer_Module_setMask ti_sysbios_family_arm_cc26xx_Timer_Module_setMask
#define Timer_Object_heap ti_sysbios_family_arm_cc26xx_Timer_Object_heap
#define Timer_Module_heap ti_sysbios_family_arm_cc26xx_Timer_Module_heap
#define Timer_construct ti_sysbios_family_arm_cc26xx_Timer_construct
#define Timer_create ti_sysbios_family_arm_cc26xx_Timer_create
#define Timer_handle ti_sysbios_family_arm_cc26xx_Timer_handle
#define Timer_struct ti_sysbios_family_arm_cc26xx_Timer_struct
#define Timer_Handle_label ti_sysbios_family_arm_cc26xx_Timer_Handle_label
#define Timer_Handle_name ti_sysbios_family_arm_cc26xx_Timer_Handle_name
#define Timer_Instance_init ti_sysbios_family_arm_cc26xx_Timer_Instance_init
#define Timer_Object_count ti_sysbios_family_arm_cc26xx_Timer_Object_count
#define Timer_Object_get ti_sysbios_family_arm_cc26xx_Timer_Object_get
#define Timer_Object_first ti_sysbios_family_arm_cc26xx_Timer_Object_first
#define Timer_Object_next ti_sysbios_family_arm_cc26xx_Timer_Object_next
#define Timer_Object_sizeof ti_sysbios_family_arm_cc26xx_Timer_Object_sizeof
#define Timer_Params_copy ti_sysbios_family_arm_cc26xx_Timer_Params_copy
#define Timer_Params_init ti_sysbios_family_arm_cc26xx_Timer_Params_init
#define Timer_Instance_finalize ti_sysbios_family_arm_cc26xx_Timer_Instance_finalize
#define Timer_delete ti_sysbios_family_arm_cc26xx_Timer_delete
#define Timer_destruct ti_sysbios_family_arm_cc26xx_Timer_destruct
#define Timer_Module_upCast ti_sysbios_family_arm_cc26xx_Timer_Module_upCast
#define Timer_Module_to_ti_sysbios_interfaces_ITimer ti_sysbios_family_arm_cc26xx_Timer_Module_to_ti_sysbios_interfaces_ITimer
#define Timer_Handle_upCast ti_sysbios_family_arm_cc26xx_Timer_Handle_upCast
#define Timer_Handle_to_ti_sysbios_interfaces_ITimer ti_sysbios_family_arm_cc26xx_Timer_Handle_to_ti_sysbios_interfaces_ITimer
#define Timer_Handle_downCast ti_sysbios_family_arm_cc26xx_Timer_Handle_downCast
#define Timer_Handle_from_ti_sysbios_interfaces_ITimer ti_sysbios_family_arm_cc26xx_Timer_Handle_from_ti_sysbios_interfaces_ITimer
#endif /* ti_sysbios_family_arm_cc26xx_Timer__localnames__done */
#endif
| 55.251303 | 259 | 0.896256 | [
"object"
] |
39fc05a5a650a06d288a722e539fb84bb773da99 | 2,194 | h | C | ash/public/cpp/message_center/arc_notification_manager_base.h | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | ash/public/cpp/message_center/arc_notification_manager_base.h | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 113 | 2015-05-04T09:58:14.000Z | 2022-01-31T19:35:03.000Z | ash/public/cpp/message_center/arc_notification_manager_base.h | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright 2020 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.
#ifndef ASH_PUBLIC_CPP_MESSAGE_CENTER_ARC_NOTIFICATION_MANAGER_BASE_H_
#define ASH_PUBLIC_CPP_MESSAGE_CENTER_ARC_NOTIFICATION_MANAGER_BASE_H_
#include <string>
#include "ash/public/cpp/ash_public_export.h"
#include "base/observer_list_types.h"
class AccountId;
namespace message_center {
class MessageCenter;
}
namespace ash {
class ArcNotificationManagerDelegate;
// Interface for ash ArcNotificationManager.
class ASH_PUBLIC_EXPORT ArcNotificationManagerBase {
public:
class Observer : public base::CheckedObserver {
public:
// Invoked when the notification for the given |notification_id| is posted
// or updated.
virtual void OnNotificationUpdated(const std::string& notification_id,
const std::string& app_id) = 0;
// Invoked when the notification for the given |notification_id| is removed.
virtual void OnNotificationRemoved(const std::string& notification_id) = 0;
// Invoked when the ArcNotificationManagerBase object (the thing that this
// observer observes) will be destroyed. In response, the observer, |this|,
// should call "RemoveObserver(this)", whether directly or indirectly (e.g.
// via ScopedObservation::Reset).
virtual void OnArcNotificationManagerDestroyed(
ArcNotificationManagerBase* arc_notification_manager) = 0;
};
ArcNotificationManagerBase();
virtual ~ArcNotificationManagerBase();
ArcNotificationManagerBase(const ArcNotificationManagerBase&) = delete;
ArcNotificationManagerBase& operator=(const ArcNotificationManagerBase&) =
delete;
virtual void Init(std::unique_ptr<ArcNotificationManagerDelegate> delegate,
const AccountId& profile_id,
message_center::MessageCenter* message_center) = 0;
// Adds and removes an observer.
virtual void AddObserver(Observer* observer) = 0;
virtual void RemoveObserver(Observer* observer) = 0;
};
} // namespace ash
#endif // ASH_PUBLIC_CPP_MESSAGE_CENTER_ARC_NOTIFICATION_MANAGER_BASE_H_
| 35.967213 | 80 | 0.755242 | [
"object"
] |
2607c824c5c5dfd3804ff20b702f02b40e711ab0 | 2,109 | h | C | code/transient.h | casseveritt/spacejunk | e831d7b7c396575927c86939d6b74c8832da97db | [
"Apache-2.0"
] | null | null | null | code/transient.h | casseveritt/spacejunk | e831d7b7c396575927c86939d6b74c8832da97db | [
"Apache-2.0"
] | null | null | null | code/transient.h | casseveritt/spacejunk | e831d7b7c396575927c86939d6b74c8832da97db | [
"Apache-2.0"
] | null | null | null | /*
* transient
*/
/*
Copyright (c) 2010 Cass Everitt
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.
* The names of contributors to this software may not 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
REGENTS 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.
Cass Everitt
*/
#ifndef __STAR3MAP_TRANSIENT_H__
#define __STAR3MAP_TRANSIENT_H__
#include "r3/linear.h"
#include "drawstring.h"
#include "render.h"
namespace star3map {
void AgeDynamicLabels();
void AgeDynamicLines();
void DrawDynamicLabels( DrawNonOverlappingStrings * nos );
void DrawDynamicLines();
void DynamicLinesInView( Lines * lines, r3::Vec4f color, r3::Vec4f labelColor, r3::Vec3f lookDir );
void DynamicLabelInView( DrawNonOverlappingStrings *nos, const std::string & label, r3::Vec3f dir, r3::Vec4f c, r3::Vec3f lookDir, float limit );
}
#endif //__STAR3MAP_TRANSIENT_H__
| 34.016129 | 146 | 0.780465 | [
"render"
] |
260859788177ba7b9758987bacc7da343f064612 | 8,981 | h | C | 10.0.16299.0/winrt/impl/Windows.Devices.Sms.2.h | Scottj1s/cppwinrt | 6b7266d14678141b4f42395e8d6e81aab0395808 | [
"MIT"
] | null | null | null | 10.0.16299.0/winrt/impl/Windows.Devices.Sms.2.h | Scottj1s/cppwinrt | 6b7266d14678141b4f42395e8d6e81aab0395808 | [
"MIT"
] | null | null | null | 10.0.16299.0/winrt/impl/Windows.Devices.Sms.2.h | Scottj1s/cppwinrt | 6b7266d14678141b4f42395e8d6e81aab0395808 | [
"MIT"
] | 1 | 2019-11-22T07:17:34.000Z | 2019-11-22T07:17:34.000Z | // C++/WinRT v1.0.171013.2
// Copyright (c) 2017 Microsoft Corporation. All rights reserved.
#pragma once
#include "winrt/impl/Windows.Storage.Streams.1.h"
#include "winrt/impl/Windows.Devices.Sms.1.h"
WINRT_EXPORT namespace winrt::Windows::Devices::Sms {
struct [[deprecated("SmsDeviceStatusChangedEventHandler may be altered or unavailable for releases after Windows 10.")]] SmsDeviceStatusChangedEventHandler : Windows::Foundation::IUnknown
{
SmsDeviceStatusChangedEventHandler(std::nullptr_t = nullptr) noexcept {}
template <typename L> SmsDeviceStatusChangedEventHandler(L lambda);
template <typename F> SmsDeviceStatusChangedEventHandler(F* function);
template <typename O, typename M> SmsDeviceStatusChangedEventHandler(O* object, M method);
void operator()(Windows::Devices::Sms::SmsDevice const& sender) const;
};
struct [[deprecated("SmsMessageReceivedEventHandler may be altered or unavailable for releases after Windows 10.")]] SmsMessageReceivedEventHandler : Windows::Foundation::IUnknown
{
SmsMessageReceivedEventHandler(std::nullptr_t = nullptr) noexcept {}
template <typename L> SmsMessageReceivedEventHandler(L lambda);
template <typename F> SmsMessageReceivedEventHandler(F* function);
template <typename O, typename M> SmsMessageReceivedEventHandler(O* object, M method);
void operator()(Windows::Devices::Sms::SmsDevice const& sender, Windows::Devices::Sms::SmsMessageReceivedEventArgs const& e) const;
};
struct SmsEncodedLength
{
uint32_t SegmentCount;
uint32_t CharacterCountLastSegment;
uint32_t CharactersPerSegment;
uint32_t ByteCountLastSegment;
uint32_t BytesPerSegment;
};
}
namespace winrt::impl {
template <> struct is_struct<Windows::Devices::Sms::SmsEncodedLength>
{
static constexpr bool value{ true };
};
}
WINRT_EXPORT namespace winrt::Windows::Devices::Sms {
struct WINRT_EBO [[deprecated("DeleteSmsMessageOperation may be altered or unavailable for releases after Windows 10.")]] DeleteSmsMessageOperation :
Windows::Foundation::IAsyncAction
{
DeleteSmsMessageOperation(std::nullptr_t) noexcept {}
};
struct WINRT_EBO [[deprecated("DeleteSmsMessagesOperation may be altered or unavailable for releases after Windows 10.")]] DeleteSmsMessagesOperation :
Windows::Foundation::IAsyncAction
{
DeleteSmsMessagesOperation(std::nullptr_t) noexcept {}
};
struct WINRT_EBO [[deprecated("GetSmsDeviceOperation may be altered or unavailable for releases after Windows 10.")]] GetSmsDeviceOperation :
Windows::Foundation::IAsyncOperation<Windows::Devices::Sms::SmsDevice>
{
GetSmsDeviceOperation(std::nullptr_t) noexcept {}
};
struct WINRT_EBO [[deprecated("GetSmsMessageOperation may be altered or unavailable for releases after Windows 10.")]] GetSmsMessageOperation :
Windows::Foundation::IAsyncOperation<Windows::Devices::Sms::ISmsMessage>
{
GetSmsMessageOperation(std::nullptr_t) noexcept {}
};
struct WINRT_EBO [[deprecated("GetSmsMessagesOperation may be altered or unavailable for releases after Windows 10.")]] GetSmsMessagesOperation :
Windows::Foundation::IAsyncOperationWithProgress<Windows::Foundation::Collections::IVectorView<Windows::Devices::Sms::ISmsMessage>, int32_t>
{
GetSmsMessagesOperation(std::nullptr_t) noexcept {}
};
struct WINRT_EBO [[deprecated("SendSmsMessageOperation may be altered or unavailable for releases after Windows 10.")]] SendSmsMessageOperation :
Windows::Foundation::IAsyncAction
{
SendSmsMessageOperation(std::nullptr_t) noexcept {}
};
struct WINRT_EBO SmsAppMessage :
Windows::Devices::Sms::ISmsAppMessage
{
SmsAppMessage(std::nullptr_t) noexcept {}
SmsAppMessage();
};
struct WINRT_EBO [[deprecated("SmsBinaryMessage may be altered or unavailable for releases after Windows 10. Instead, use SmsAppMessage.")]] SmsBinaryMessage :
Windows::Devices::Sms::ISmsBinaryMessage
{
SmsBinaryMessage(std::nullptr_t) noexcept {}
SmsBinaryMessage();
};
struct WINRT_EBO SmsBroadcastMessage :
Windows::Devices::Sms::ISmsBroadcastMessage
{
SmsBroadcastMessage(std::nullptr_t) noexcept {}
};
struct WINRT_EBO [[deprecated("SmsDevice may be altered or unavailable for releases after Windows 10. Instead, use SmsDevice2.")]] SmsDevice :
Windows::Devices::Sms::ISmsDevice
{
SmsDevice(std::nullptr_t) noexcept {}
[[deprecated("ISmsDeviceStatics may be altered or unavailable for releases after Windows 10.")]] static hstring GetDeviceSelector();
[[deprecated("ISmsDeviceStatics may be altered or unavailable for releases after Windows 10.")]] static Windows::Foundation::IAsyncOperation<Windows::Devices::Sms::SmsDevice> FromIdAsync(param::hstring const& deviceId);
[[deprecated("ISmsDeviceStatics may be altered or unavailable for releases after Windows 10.")]] static Windows::Foundation::IAsyncOperation<Windows::Devices::Sms::SmsDevice> GetDefaultAsync();
[[deprecated("ISmsDeviceStatics2 may be altered or unavailable for releases after Windows 10.")]] static Windows::Foundation::IAsyncOperation<Windows::Devices::Sms::SmsDevice> FromNetworkAccountIdAsync(param::hstring const& networkAccountId);
};
struct WINRT_EBO SmsDevice2 :
Windows::Devices::Sms::ISmsDevice2
{
SmsDevice2(std::nullptr_t) noexcept {}
static hstring GetDeviceSelector();
static Windows::Devices::Sms::SmsDevice2 FromId(param::hstring const& deviceId);
static Windows::Devices::Sms::SmsDevice2 GetDefault();
static Windows::Devices::Sms::SmsDevice2 FromParentId(param::hstring const& parentDeviceId);
};
struct WINRT_EBO [[deprecated("SmsDeviceMessageStore may be altered or unavailable for releases after Windows 10.")]] SmsDeviceMessageStore :
Windows::Devices::Sms::ISmsDeviceMessageStore
{
SmsDeviceMessageStore(std::nullptr_t) noexcept {}
};
struct WINRT_EBO SmsFilterRule :
Windows::Devices::Sms::ISmsFilterRule
{
SmsFilterRule(std::nullptr_t) noexcept {}
SmsFilterRule(Windows::Devices::Sms::SmsMessageType const& messageType);
};
struct WINRT_EBO SmsFilterRules :
Windows::Devices::Sms::ISmsFilterRules
{
SmsFilterRules(std::nullptr_t) noexcept {}
SmsFilterRules(Windows::Devices::Sms::SmsFilterActionType const& actionType);
};
struct WINRT_EBO [[deprecated("SmsMessageReceivedEventArgs may be altered or unavailable for releases after Windows 10.")]] SmsMessageReceivedEventArgs :
Windows::Devices::Sms::ISmsMessageReceivedEventArgs
{
SmsMessageReceivedEventArgs(std::nullptr_t) noexcept {}
};
struct WINRT_EBO SmsMessageReceivedTriggerDetails :
Windows::Devices::Sms::ISmsMessageReceivedTriggerDetails
{
SmsMessageReceivedTriggerDetails(std::nullptr_t) noexcept {}
};
struct WINRT_EBO SmsMessageRegistration :
Windows::Devices::Sms::ISmsMessageRegistration
{
SmsMessageRegistration(std::nullptr_t) noexcept {}
static Windows::Foundation::Collections::IVectorView<Windows::Devices::Sms::SmsMessageRegistration> AllRegistrations();
static Windows::Devices::Sms::SmsMessageRegistration Register(param::hstring const& id, Windows::Devices::Sms::SmsFilterRules const& filterRules);
};
struct WINRT_EBO [[deprecated("SmsReceivedEventDetails may be altered or unavailable for releases after Windows 10. Instead, use SmsMessageReceivedTriggerDetails.")]] SmsReceivedEventDetails :
Windows::Devices::Sms::ISmsReceivedEventDetails,
impl::require<SmsReceivedEventDetails, Windows::Devices::Sms::ISmsReceivedEventDetails2>
{
SmsReceivedEventDetails(std::nullptr_t) noexcept {}
};
struct WINRT_EBO SmsSendMessageResult :
Windows::Devices::Sms::ISmsSendMessageResult
{
SmsSendMessageResult(std::nullptr_t) noexcept {}
};
struct WINRT_EBO SmsStatusMessage :
Windows::Devices::Sms::ISmsStatusMessage
{
SmsStatusMessage(std::nullptr_t) noexcept {}
};
struct WINRT_EBO [[deprecated("SmsTextMessage may be altered or unavailable for releases after Windows 10. Instead, use SmsTextMessage2.")]] SmsTextMessage :
Windows::Devices::Sms::ISmsTextMessage
{
SmsTextMessage(std::nullptr_t) noexcept {}
SmsTextMessage();
[[deprecated("ISmsTextMessageStatics may be altered or unavailable for releases after Windows 10.")]] static Windows::Devices::Sms::SmsTextMessage FromBinaryMessage(Windows::Devices::Sms::SmsBinaryMessage const& binaryMessage);
[[deprecated("ISmsTextMessageStatics may be altered or unavailable for releases after Windows 10.")]] static Windows::Devices::Sms::SmsTextMessage FromBinaryData(Windows::Devices::Sms::SmsDataFormat const& format, array_view<uint8_t const> value);
};
struct WINRT_EBO SmsTextMessage2 :
Windows::Devices::Sms::ISmsTextMessage2
{
SmsTextMessage2(std::nullptr_t) noexcept {}
SmsTextMessage2();
};
struct WINRT_EBO SmsVoicemailMessage :
Windows::Devices::Sms::ISmsVoicemailMessage
{
SmsVoicemailMessage(std::nullptr_t) noexcept {}
};
struct WINRT_EBO SmsWapMessage :
Windows::Devices::Sms::ISmsWapMessage
{
SmsWapMessage(std::nullptr_t) noexcept {}
};
}
| 41.96729 | 251 | 0.775526 | [
"object"
] |
260af2bb2519bdaa8f9c92eacdca6568252582e9 | 2,060 | h | C | Sail/src/Sail.h | BTH-StoraSpel-DXR/SPLASH | 1bf4c9b96cbcce570ed3a97f30a556a992e1ad08 | [
"MIT"
] | 12 | 2019-09-11T15:52:31.000Z | 2021-11-14T20:33:35.000Z | Sail/src/Sail.h | BTH-StoraSpel-DXR/Game | 1bf4c9b96cbcce570ed3a97f30a556a992e1ad08 | [
"MIT"
] | 227 | 2019-09-11T08:40:24.000Z | 2020-06-26T14:12:07.000Z | Sail/src/Sail.h | BTH-StoraSpel-DXR/Game | 1bf4c9b96cbcce570ed3a97f30a556a992e1ad08 | [
"MIT"
] | 2 | 2020-10-26T02:35:18.000Z | 2020-10-26T02:36:01.000Z | #pragma once
// Settings
//#define _SAIL_BREAK_ON_WARNING
#define _SAIL_BREAK_ON_ERROR
// Disable "Variable uninitialized" warning
// 218 of these in the fbx sdk
#pragma warning(disable:26495)
// TODO: only define GLM_FORCE_DEPTH_ZERO_TO_ONE if directx or vulkan (not opengl)
#define GLM_FORCE_DEPTH_ZERO_TO_ONE
#include <glm/glm.hpp>
#include "Sail/KeyCodes.h"
#include "Sail/MouseButtonCodes.h"
#include "Sail/KeyBinds.h"
#include "Sail/Application.h"
#include "Sail/Utils/Utils.h"
#include "Sail/graphics/text/Text.h"
#include "Sail/graphics/text/SailFont.h"
#include "Sail/graphics/camera/PerspectiveCamera.h"
#include "Sail/graphics/camera/OrthographicCamera.h"
#include "Sail/graphics/camera/FlyingCameraController.h"
#include "Sail/graphics/geometry/Model.h"
#include "Sail/graphics/light/LightSetup.h"
#include "Sail/graphics/shader/material/MaterialShader.h"
#include "Sail/graphics/shader/material/WireframeShader.h"
#include "Sail/graphics/shader/dxr/GBufferOutShader.h"
#include "Sail/graphics/shader/dxr/GBufferWireframe.h"
#include "Sail/graphics/shader/gui/GuiShader.h"
#include "Sail/graphics/geometry/factory/CubeModel.h"
#include "Sail/graphics/geometry/factory/ConeModel.h"
#include "Sail/graphics/geometry/factory/PlaneModel.h"
#include "Sail/states/StateStack.h"
#include "Sail/events/Events.h"
#include "Sail/entities/ECS.h"
#include "Sail/entities/components/Components.h"
#include "Sail/graphics/geometry/Transform.h"
#include "Sail/utils/SailImGui/ConsoleCommands.h"
#include "Sail/utils/SailImGui/Profiler.h"
#include "Sail/utils/SailImGui/RenderSettingsWindow.h"
#include "Sail/utils/SailImGui/LightDebugWindow.h"
#include "Sail/utils/SailImGui/PlayerInfoWindow.h"
#include "Sail/utils/SailImGui/WasDroppedWindow.h"
#include "Sail/utils/SailImGui/KillFeedWindow.h"
#include "Sail/utils/SailImGui/ECS_SystemInfoImGuiWindow.h"
#include "Sail/utils/SailImGui/InGameGui.h"
#include "Sail/utils/SailImGui/PlayerNamesImGui.h"
#include "Sail/utils/SailImGui/NetworkInfoWindow.h"
#include "Sail/utils/SailImGui/WaitingForPlayersWindow.h" | 40.392157 | 82 | 0.806796 | [
"geometry",
"model",
"transform"
] |
260bcabac2172bc56ad0f0922442dd5b802302ce | 5,950 | h | C | iPhoneOS15.2.sdk/System/Library/Frameworks/SceneKit.framework/Headers/SCNHitTest.h | bakedpotato191/sdks | 7b5c8c299a8afcb6d68b356668b4949a946734d9 | [
"MIT"
] | 6 | 2021-12-13T03:09:30.000Z | 2022-03-09T15:18:16.000Z | iPhoneOS15.0.sdk/System/Library/Frameworks/SceneKit.framework/Headers/SCNHitTest.h | chrisharper22/sdks | 9b2f79c4a48fd5ca9a602044e617231d639a3f57 | [
"MIT"
] | null | null | null | iPhoneOS15.0.sdk/System/Library/Frameworks/SceneKit.framework/Headers/SCNHitTest.h | chrisharper22/sdks | 9b2f79c4a48fd5ca9a602044e617231d639a3f57 | [
"MIT"
] | null | null | null | //
// SCNHitTest.h
// SceneKit
//
// Copyright © 2012-2021 Apple Inc. All rights reserved.
//
#import <SceneKit/SceneKitTypes.h>
NS_ASSUME_NONNULL_BEGIN
@class SCNNode;
/*! @enum SCNHitTestSearchMode
@abstract hit test modes
*/
typedef NS_ENUM(NSInteger, SCNHitTestSearchMode) {
SCNHitTestSearchModeClosest = 0, // The closest object found.
SCNHitTestSearchModeAll = 1, // All found objects sorted from nearest to farthest.
SCNHitTestSearchModeAny = 2 // The first object found. This object is not necessarily the nearest.
} API_AVAILABLE(macos(10.13), ios(11.0), tvos(11.0), watchos(4.0));
/*! @group Hit-test options */
typedef NSString * SCNHitTestOption NS_STRING_ENUM;
SCN_EXPORT SCNHitTestOption const SCNHitTestClipToZRangeKey; // If set to YES ignores the objects clipped by the zNear/zFar range of the current point of view. Defaults to YES.
SCN_EXPORT SCNHitTestOption const SCNHitTestBackFaceCullingKey; // If set to YES ignores the faces not facing to the camera. Defaults to YES.
SCN_EXPORT SCNHitTestOption const SCNHitTestBoundingBoxOnlyKey; // If set to YES only tests the bounding boxes of the 3D objects. Defaults to NO.
SCN_EXPORT SCNHitTestOption const SCNHitTestIgnoreChildNodesKey; // Determines whether the child nodes are ignored. Defaults to NO.
SCN_EXPORT SCNHitTestOption const SCNHitTestRootNodeKey; // Specifies the root node to use for the hit test. Defaults to the root node of the scene.
SCN_EXPORT SCNHitTestOption const SCNHitTestIgnoreHiddenNodesKey API_AVAILABLE(macos(10.9)); // Determines whether hidden nodes should be ignored. Defaults to YES.
SCN_EXPORT SCNHitTestOption const SCNHitTestOptionCategoryBitMask API_AVAILABLE(macos(10.12), ios(10.0), tvos(10.0)); // Determines the node categories to test. Defaults to all bits set.
SCN_EXPORT SCNHitTestOption const SCNHitTestOptionSearchMode API_AVAILABLE(macos(10.13), ios(11.0), tvos(11.0), watchos(4.0)); // Determines whether the search should be exhaustive. Defaults to SCNHitTestSearchModeClosest.
SCN_EXPORT SCNHitTestOption const SCNHitTestOptionIgnoreLightArea API_AVAILABLE(macos(10.15), ios(13.0), tvos(13.0), watchos(6.0)); // Determines whether the shape of an area light should not be taken into account. Defaults to YES.
SCN_EXPORT SCNHitTestOption const SCNHitTestFirstFoundOnlyKey; // Deprecated, use SCNHitTestSearchModeAny for the SCNHitTestOptionSearchMode option instead
SCN_EXPORT SCNHitTestOption const SCNHitTestSortResultsKey; // Deprecated, use SCNHitTestSearchModeAll for the SCNHitTestOptionSearchMode option instead
#define SCNHitTestOptionFirstFoundOnly SCNHitTestFirstFoundOnlyKey
#define SCNHitTestOptionSortResults SCNHitTestSortResultsKey
#define SCNHitTestOptionClipToZRange SCNHitTestClipToZRangeKey
#define SCNHitTestOptionBackFaceCulling SCNHitTestBackFaceCullingKey
#define SCNHitTestOptionBoundingBoxOnly SCNHitTestBoundingBoxOnlyKey
#define SCNHitTestOptionIgnoreChildNodes SCNHitTestIgnoreChildNodesKey
#define SCNHitTestOptionRootNode SCNHitTestRootNodeKey
#define SCNHitTestOptionIgnoreHiddenNodes SCNHitTestIgnoreHiddenNodesKey
/*! @class SCNHitTestResult
@abstract Results returned by the hit-test methods.
*/
SCN_EXPORT
@interface SCNHitTestResult : NSObject
/*! The hit node. */
@property(nonatomic, readonly) SCNNode *node;
/*! Index of the hit geometry element. */
@property(nonatomic, readonly) NSInteger geometryIndex;
/*! Index of the hit primitive of the geometry element. */
@property(nonatomic, readonly) NSInteger faceIndex;
/*! Intersection point in the node's local coordinate system. */
@property(nonatomic, readonly) SCNVector3 localCoordinates;
/*! Intersection point in the world coordinate system. */
@property(nonatomic, readonly) SCNVector3 worldCoordinates;
/*! Intersection normal in the node's local coordinate system. */
@property(nonatomic, readonly) SCNVector3 localNormal;
/*! Intersection normal in the world coordinate system. */
@property(nonatomic, readonly) SCNVector3 worldNormal;
/*! World transform of the hit node. */
@property(nonatomic, readonly) SCNMatrix4 modelTransform;
/*! The hit bone. Only available if the node hit has a SCNSkinner attached. */
@property(nonatomic, readonly, nullable) SCNNode *boneNode API_AVAILABLE(macos(10.12), ios(10.0), tvos(10.0));
/*!
@method textureCoordinatesWithMappingChannel:
@abstract Returns the texture coordinates at the point of intersection, for a given mapping channel.
@param channel The texture coordinates source index of the geometry to use. The channel must exists on the geometry otherwise {0,0} will be returned.
*/
- (CGPoint)textureCoordinatesWithMappingChannel:(NSInteger)channel;
@end
@interface SCNHitTestResult (SIMD)
@property(nonatomic, readonly) simd_float3 simdLocalCoordinates API_AVAILABLE(macos(10.15), ios(13.0), tvos(13.0), watchos(6.0));
@property(nonatomic, readonly) simd_float3 simdWorldCoordinates API_AVAILABLE(macos(10.15), ios(13.0), tvos(13.0), watchos(6.0));
@property(nonatomic, readonly) simd_float3 simdLocalNormal API_AVAILABLE(macos(10.15), ios(13.0), tvos(13.0), watchos(6.0));
@property(nonatomic, readonly) simd_float3 simdWorldNormal API_AVAILABLE(macos(10.15), ios(13.0), tvos(13.0), watchos(6.0));
@property(nonatomic, readonly) simd_float4x4 simdModelTransform API_AVAILABLE(macos(10.15), ios(13.0), tvos(13.0), watchos(6.0));
@end
NS_ASSUME_NONNULL_END
| 58.333333 | 247 | 0.724034 | [
"geometry",
"object",
"shape",
"transform",
"3d"
] |
260ef95f59fbd6f3d919faae55b27d9544b0e9ef | 12,526 | h | C | cocos2d/cocos/2d/CCSpriteFrameCache.h | NIKEA-SOFT/TestGame | 04f13e5f1324bca9f1e47f02037ea1eddd3bcc8f | [
"MIT"
] | 56 | 2016-05-29T11:47:07.000Z | 2022-02-04T12:53:56.000Z | cocos2d/cocos/2d/CCSpriteFrameCache.h | NIKEA-SOFT/TestGame | 04f13e5f1324bca9f1e47f02037ea1eddd3bcc8f | [
"MIT"
] | 32 | 2016-07-06T06:22:18.000Z | 2020-08-02T04:02:32.000Z | cocos2d/cocos/2d/CCSpriteFrameCache.h | NIKEA-SOFT/TestGame | 04f13e5f1324bca9f1e47f02037ea1eddd3bcc8f | [
"MIT"
] | 25 | 2016-07-07T16:30:23.000Z | 2021-04-19T17:27:57.000Z | /****************************************************************************
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2009 Jason Booth
Copyright (c) 2009 Robert J Payne
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2011 Zynga Inc.
Copyright (c) 2013-2016 Chukong Technologies Inc.
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos2d-x.org
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.
****************************************************************************/
#ifndef __SPRITE_CCSPRITE_FRAME_CACHE_H__
#define __SPRITE_CCSPRITE_FRAME_CACHE_H__
#include <set>
#include <unordered_map>
#include <string>
#include "2d/CCSpriteFrame.h"
#include "base/CCRef.h"
#include "base/CCValue.h"
#include "base/CCMap.h"
NS_CC_BEGIN
class Sprite;
class Texture2D;
class PolygonInfo;
/**
* @addtogroup _2d
* @{
*/
/** @class SpriteFrameCache
* @brief Singleton that handles the loading of the sprite frames.
The SpriteFrameCache loads SpriteFrames from a .plist file.
A SpriteFrame contains information about how to use a sprite
located in a sprite sheet.
The .plist file contains the following elements:
- `frames`:
Dictionary of sprites. Key is the sprite's name, value a dict containing the sprite frame data.
A sprite frame consists of the following values:
- `spriteOffset`: difference vector between the original sprite's center and the center of the trimmed sprite
- `spriteSize`: size of the trimmed sprite
- `spriteSourceSize`: size of the original sprite
- `textureRect`: the position of the sprite in the sprite sheet
- `textureRotated`: true if the sprite is rotated clockwise
- `anchor`: anchor point in normalized coordinates (optional)
Optional values when using polygon outlines
- `triangles`: 3 indices per triangle, pointing to vertices and verticesUV coordinates
- `vertices`: vertices in sprite coordinates, each vertex consists of a pair of x and y coordinates
- `verticesUV`: vertices in the sprite sheet, each vertex consists of a pair of x and y coordinates
- `metadata`:
Dictionary containing additional information about the sprite sheet:
- `format`: plist file format, currently 3
- `size`: size of the texture (optional)
- `textureFileName`: name of the texture's image file
Use one of the following tools to create the .plist file and sprite sheet:
- [TexturePacker](https://www.codeandweb.com/texturepacker/cocos2d)
- [Zwoptex](https://zwopple.com/zwoptex/)
@since v0.9
@js cc.spriteFrameCache
*/
class CC_DLL SpriteFrameCache : public Ref
{
protected:
/**
* used to wrap plist & frame names & SpriteFrames
*/
class PlistFramesCache {
public:
PlistFramesCache() { }
void init() {
_spriteFrames.reserve(20); clear();
}
/** Record SpriteFrame with plist and frame name, add frame name
* and plist to index
*/
void insertFrame(const std::string &plist, const std::string &frame, SpriteFrame *frameObj);
/** Delete frame from cache, rebuild index
*/
bool eraseFrame(const std::string &frame);
/** Delete a list of frames from cache, rebuild index
*/
bool eraseFrames(const std::vector<std::string> &frame);
/** Delete frame from index and SpriteFrame is kept.
*/
bool erasePlistIndex(const std::string &frame);
/** Clear index and all SpriteFrames.
*/
void clear();
inline bool hasFrame(const std::string &frame) const;
inline bool isPlistUsed(const std::string &plist) const;
inline SpriteFrame *at(const std::string &frame);
inline Map<std::string, SpriteFrame*>& getSpriteFrames();
void markPlistFull(const std::string &plist, bool full) { _isPlistFull[plist] = full; }
bool isPlistFull(const std::string &plist) const
{
auto it = _isPlistFull.find(plist);
return it == _isPlistFull.end() ? false : it->second;
}
private:
Map<std::string, SpriteFrame*> _spriteFrames;
std::unordered_map<std::string, std::set<std::string>> _indexPlist2Frames;
std::unordered_map<std::string, std::string> _indexFrame2plist;
std::unordered_map<std::string, bool> _isPlistFull;
};
public:
/** Returns the shared instance of the Sprite Frame cache.
*
* @return The instance of the Sprite Frame Cache.
* @js NA
*/
static SpriteFrameCache* getInstance();
/** @deprecated Use getInstance() instead
@js NA
*/
CC_DEPRECATED_ATTRIBUTE static SpriteFrameCache* sharedSpriteFrameCache() { return SpriteFrameCache::getInstance(); }
/** Destroys the cache. It releases all the Sprite Frames and the retained instance.
* @js NA
*/
static void destroyInstance();
/** @deprecated Use destroyInstance() instead
* @js NA
*/
CC_DEPRECATED_ATTRIBUTE static void purgeSharedSpriteFrameCache() { return SpriteFrameCache::destroyInstance(); }
/** Destructor.
* @js NA
* @lua NA
*/
virtual ~SpriteFrameCache();
/** Initialize method.
*
* @return if success return true.
*/
bool init();
/** Adds multiple Sprite Frames from a plist file.
* A texture will be loaded automatically. The texture name will composed by replacing the .plist suffix with .png.
* If you want to use another texture, you should use the addSpriteFramesWithFile(const std::string& plist, const std::string& textureFileName) method.
* @js addSpriteFrames
* @lua addSpriteFrames
*
* @param plist Plist file name.
*/
void addSpriteFramesWithFile(const std::string& plist);
/** Adds multiple Sprite Frames from a plist file. The texture will be associated with the created sprite frames.
@since v0.99.5
* @js addSpriteFrames
* @lua addSpriteFrames
*
* @param plist Plist file name.
* @param textureFileName Texture file name.
*/
void addSpriteFramesWithFile(const std::string& plist, const std::string& textureFileName);
/** Adds multiple Sprite Frames from a plist file. The texture will be associated with the created sprite frames.
* @js addSpriteFrames
* @lua addSpriteFrames
*
* @param plist Plist file name.
* @param texture Texture pointer.
*/
void addSpriteFramesWithFile(const std::string&plist, Texture2D *texture);
/** Adds multiple Sprite Frames from a plist file content. The texture will be associated with the created sprite frames.
* @js NA
* @lua addSpriteFrames
*
* @param plist_content Plist file content string.
* @param texture Texture pointer.
*/
void addSpriteFramesWithFileContent(const std::string& plist_content, Texture2D *texture);
/** Adds an sprite frame with a given name.
If the name already exists, then the contents of the old name will be replaced with the new one.
*
* @param frame A certain sprite frame.
* @param frameName The name of the sprite frame.
*/
void addSpriteFrame(SpriteFrame *frame, const std::string& frameName);
/** Check if multiple Sprite Frames from a plist file have been loaded.
* @js NA
* @lua NA
*
* @param plist Plist file name.
* @return True if the file is loaded.
*/
bool isSpriteFramesWithFileLoaded(const std::string& plist) const;
/** Purges the dictionary of loaded sprite frames.
* Call this method if you receive the "Memory Warning".
* In the short term: it will free some resources preventing your app from being killed.
* In the medium term: it will allocate more resources.
* In the long term: it will be the same.
*/
void removeSpriteFrames();
/** Removes unused sprite frames.
* Sprite Frames that have a retain count of 1 will be deleted.
* It is convenient to call this method after when starting a new Scene.
* @js NA
*/
void removeUnusedSpriteFrames();
/** Deletes an sprite frame from the sprite frame cache.
*
* @param name The name of the sprite frame that needs to removed.
*/
void removeSpriteFrameByName(const std::string& name);
/** Removes multiple Sprite Frames from a plist file.
* Sprite Frames stored in this file will be removed.
* It is convenient to call this method when a specific texture needs to be removed.
* @since v0.99.5
*
* @param plist The name of the plist that needs to removed.
*/
void removeSpriteFramesFromFile(const std::string& plist);
/** Removes multiple Sprite Frames from a plist file content.
* Sprite Frames stored in this file will be removed.
* It is convenient to call this method when a specific texture needs to be removed.
*
* @param plist_content The string of the plist content that needs to removed.
* @js NA
*/
void removeSpriteFramesFromFileContent(const std::string& plist_content);
/** Removes all Sprite Frames associated with the specified textures.
* It is convenient to call this method when a specific texture needs to be removed.
* @since v0.995.
*
* @param texture The texture that needs to removed.
*/
void removeSpriteFramesFromTexture(Texture2D* texture);
/** Returns an Sprite Frame that was previously added.
If the name is not found it will return nil.
You should retain the returned copy if you are going to use it.
* @js getSpriteFrame
* @lua getSpriteFrame
*
* @param name A certain sprite frame name.
* @return The sprite frame.
*/
SpriteFrame* getSpriteFrameByName(const std::string& name);
/** @deprecated use getSpriteFrameByName() instead */
CC_DEPRECATED_ATTRIBUTE SpriteFrame* spriteFrameByName(const std::string&name) { return getSpriteFrameByName(name); }
bool reloadTexture(const std::string& plist);
protected:
// MARMALADE: Made this protected not private, as deriving from this class is pretty useful
SpriteFrameCache(){}
/*Adds multiple Sprite Frames with a dictionary. The texture will be associated with the created sprite frames.
*/
void addSpriteFramesWithDictionary(ValueMap& dictionary, Texture2D *texture, const std::string &plist);
/*Adds multiple Sprite Frames with a dictionary. The texture will be associated with the created sprite frames.
*/
void addSpriteFramesWithDictionary(ValueMap& dictionary, const std::string &texturePath, const std::string &plist);
/** Removes multiple Sprite Frames from Dictionary.
* @since v0.99.5
*/
void removeSpriteFramesFromDictionary(ValueMap& dictionary);
/** Configures PolygonInfo class with the passed sizes + triangles */
void initializePolygonInfo(const Size &textureSize,
const Size &spriteSize,
const std::vector<int> &vertices,
const std::vector<int> &verticesUV,
const std::vector<int> &triangleIndices,
PolygonInfo &polygonInfo);
void reloadSpriteFramesWithDictionary(ValueMap& dictionary, Texture2D *texture, const std::string &plist);
ValueMap _spriteFramesAliases;
PlistFramesCache _spriteFramesCache;
};
// end of _2d group
/// @}
NS_CC_END
#endif // __SPRITE_CCSPRITE_FRAME_CACHE_H__
| 38.30581 | 155 | 0.679147 | [
"vector"
] |
2613cbb7c4f511a1a072170b27321a3efc3543ad | 14,923 | c | C | src/sys/boot/mips/beri/boot2/boot2.c | dnybz/MeshBSD | 5c6c0539ce13d7cda9e2645e2e9e916e371f87b2 | [
"BSD-3-Clause"
] | null | null | null | src/sys/boot/mips/beri/boot2/boot2.c | dnybz/MeshBSD | 5c6c0539ce13d7cda9e2645e2e9e916e371f87b2 | [
"BSD-3-Clause"
] | null | null | null | src/sys/boot/mips/beri/boot2/boot2.c | dnybz/MeshBSD | 5c6c0539ce13d7cda9e2645e2e9e916e371f87b2 | [
"BSD-3-Clause"
] | null | null | null | /*-
* Copyright (c) 2013-2014 Robert N. M. Watson
* All rights reserved.
*
* This software was developed by SRI International and the University of
* Cambridge Computer Laboratory under DARPA/AFRL contract (FA8750-10-C-0237)
* ("CTSRD"), as part of the DARPA CRASH research programme.
*
* 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 AUTHOR 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 AUTHOR 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.
*
* Copyright (c) 1998 Robert Nordier
* All rights reserved.
*
* Redistribution and use in source and binary forms are freely
* permitted provided that the above copyright notice and this
* paragraph and the following disclaimer are duplicated in all
* such forms.
*
* This software is provided "AS IS" and without any express or
* implied warranties, including, without limitation, the implied
* warranties of merchantability and fitness for a particular
* purpose.
*/
#include <sys/cdefs.h>
__FBSDID("$FreeBSD: releng/11.0/sys/boot/mips/beri/boot2/boot2.c 298309 2016-04-19 23:44:33Z pfg $");
#include <sys/param.h>
#include <sys/disklabel.h>
#include <sys/diskmbr.h>
#include <sys/dirent.h>
#include <sys/endian.h>
#include <sys/reboot.h>
#include <machine/bootinfo.h>
#include <machine/elf.h>
#include <stand.h>
#include <stdarg.h>
#include <string.h>
#include <beri.h>
#include <cfi.h>
#include <cons.h>
#include <mips.h>
#include <sdcard.h>
#include "paths.h"
#include "rbx.h"
static int beri_argc;
static const char **beri_argv, **beri_envv;
static uint64_t beri_memsize;
#define IO_KEYBOARD 1
#define IO_SERIAL 2
#define SECOND 1 /* Circa that many ticks in a second. */
#define ARGS 0x900
#define NOPT 14
#define MEM_BASE 0x12
#define MEM_EXT 0x15
/*
* XXXRW: I think this has to do with whether boot2 expects a partition
* table?
*/
#define DRV_HARD 0x80
#define DRV_MASK 0x7f
/* Default to using CFI flash. */
#define TYPE_DEFAULT BOOTINFO_DEV_TYPE_SDCARD
/* Hard-coded assumption about location of JTAG-loaded kernel. */
#define DRAM_KERNEL_ADDR ((void *)mips_phys_to_cached(0x20000))
extern uint32_t _end;
static const char optstr[NOPT] = "DhaCcdgmnpqrsv"; /* Also 'P', 'S' */
static const unsigned char flags[NOPT] = {
RBX_DUAL,
RBX_SERIAL,
RBX_ASKNAME,
RBX_CDROM,
RBX_CONFIG,
RBX_KDB,
RBX_GDB,
RBX_MUTE,
RBX_NOINTR,
RBX_PAUSE,
RBX_QUIET,
RBX_DFLTROOT,
RBX_SINGLE,
RBX_VERBOSE
};
/* These must match BOOTINFO_DEV_TYPE constants. */
static const char *const dev_nm[] = {"dram", "cfi", "sdcard"};
static const u_int dev_nm_count = nitems(dev_nm);
static struct dmadat __dmadat;
static struct dsk {
unsigned type; /* BOOTINFO_DEV_TYPE_x object type. */
uintptr_t unitptr; /* Unit number or pointer to object. */
uint8_t slice;
uint8_t part;
#if 0
unsigned start;
int init;
#endif
} dsk;
static char cmd[512], cmddup[512], knamebuf[1024];
static const char *kname;
uint32_t opts;
#if 0
static int comspeed = SIOSPD;
#endif
struct bootinfo bootinfo;
static uint8_t ioctrl = IO_KEYBOARD;
void exit(int);
void putchar(int);
static void boot_fromdram(void);
static void boot_fromfs(void);
static void load(void);
static int parse(void);
static int dskread(void *, unsigned, unsigned);
static int xputc(int);
static int xgetc(int);
#define UFS_SMALL_CGBASE
#include "ufsread.c"
static inline int
xfsread(ufs_ino_t inode, void *buf, size_t nbyte)
{
if ((size_t)fsread(inode, buf, nbyte) != nbyte) {
printf("Invalid %s\n", "format");
return -1;
}
return 0;
}
static inline void
getstr(void)
{
char *s;
int c;
s = cmd;
for (;;) {
switch (c = xgetc(0)) {
case 0:
break;
case '\177':
case '\b':
if (s > cmd) {
s--;
printf("\b \b");
}
break;
case '\n':
case '\r':
putchar('\n');
*s = 0;
return;
default:
if (s - cmd < sizeof(cmd) - 1)
*s++ = c;
putchar(c);
}
}
}
int
main(u_int argc, const char *argv[], const char *envv[], uint64_t memsize)
{
uint8_t autoboot;
ufs_ino_t ino;
size_t nbyte;
/* Arguments from Miniboot. */
beri_argc = argc;
beri_argv = argv;
beri_envv = envv;
beri_memsize = memsize;
dmadat = &__dmadat;
#if 0
/* XXXRW: more here. */
v86.ctl = V86_FLAGS;
v86.efl = PSL_RESERVED_DEFAULT | PSL_I;
dsk.drive = *(uint8_t *)PTOV(ARGS);
#endif
dsk.type = TYPE_DEFAULT;
#if 0
dsk.unit = dsk.drive & DRV_MASK;
dsk.slice = *(uint8_t *)PTOV(ARGS + 1) + 1;
#endif
bootinfo.bi_version = BOOTINFO_VERSION;
bootinfo.bi_size = sizeof(bootinfo);
/* Process configuration file */
autoboot = 1;
if ((ino = lookup(PATH_CONFIG)) ||
(ino = lookup(PATH_DOTCONFIG))) {
nbyte = fsread(ino, cmd, sizeof(cmd) - 1);
cmd[nbyte] = '\0';
}
if (*cmd) {
memcpy(cmddup, cmd, sizeof(cmd));
if (parse())
autoboot = 0;
if (!OPT_CHECK(RBX_QUIET))
printf("%s: %s", PATH_CONFIG, cmddup);
/* Do not process this command twice */
*cmd = 0;
}
/*
* Try to exec stage 3 boot loader. If interrupted by a keypress,
* or in case of failure, try to load a kernel directly instead.
*/
if (!kname) {
kname = PATH_LOADER;
if (autoboot && !keyhit(3*SECOND)) {
boot_fromfs();
kname = PATH_KERNEL;
}
}
/* Present the user with the boot2 prompt. */
for (;;) {
if (!autoboot || !OPT_CHECK(RBX_QUIET))
printf("\nFreeBSD/mips boot\n"
"Default: %s%ju:%s\n"
"boot: ",
dev_nm[dsk.type], dsk.unitptr, kname);
#if 0
if (ioctrl & IO_SERIAL)
sio_flush();
#endif
if (!autoboot || keyhit(3*SECOND))
getstr();
else if (!autoboot || !OPT_CHECK(RBX_QUIET))
putchar('\n');
autoboot = 0;
if (parse())
putchar('\a');
else
load();
}
}
/* XXX - Needed for btxld to link the boot2 binary; do not remove. */
void
exit(int x)
{
}
static void
boot(void *entryp, int argc, const char *argv[], const char *envv[])
{
bootinfo.bi_kernelname = (bi_ptr_t)kname;
bootinfo.bi_boot2opts = opts & RBX_MASK;
bootinfo.bi_boot_dev_type = dsk.type;
bootinfo.bi_boot_dev_unitptr = dsk.unitptr;
bootinfo.bi_memsize = beri_memsize;
#if 0
/*
* XXXRW: A possible future way to distinguish Miniboot passing a memory
* size vs DTB..?
*/
if (beri_memsize <= BERI_MEMVSDTB)
bootinfo.bi_memsize = beri_memsize;
else
bootinfo.bi_dtb = beri_memsize;
#endif
((void(*)(int, const char **, const char **, void *))entryp)(argc, argv,
envv, &bootinfo);
}
/*
* Boot a kernel that has mysteriously (i.e., by JTAG) appeared in DRAM;
* assume that it is already properly relocated, etc, and invoke its entry
* address without question or concern.
*/
static void
boot_fromdram(void)
{
void *kaddr = DRAM_KERNEL_ADDR; /* XXXRW: Something better here. */
Elf64_Ehdr *ehp = kaddr;
if (!IS_ELF(*ehp)) {
printf("Invalid %s\n", "format");
return;
}
boot((void *)ehp->e_entry, beri_argc, beri_argv, beri_envv);
}
static void
boot_fromfs(void)
{
union {
Elf64_Ehdr eh;
} hdr;
static Elf64_Phdr ep[2];
#if 0
static Elf64_Shdr es[2];
#endif
caddr_t p;
ufs_ino_t ino;
uint64_t addr;
int i, j;
if (!(ino = lookup(kname))) {
if (!ls)
printf("No %s\n", kname);
return;
}
if (xfsread(ino, &hdr, sizeof(hdr)))
return;
if (IS_ELF(hdr.eh)) {
fs_off = hdr.eh.e_phoff;
for (j = i = 0; i < hdr.eh.e_phnum && j < 2; i++) {
if (xfsread(ino, ep + j, sizeof(ep[0])))
return;
if (ep[j].p_type == PT_LOAD)
j++;
}
for (i = 0; i < 2; i++) {
p = (caddr_t)ep[i].p_paddr;
fs_off = ep[i].p_offset;
if (xfsread(ino, p, ep[i].p_filesz))
return;
}
p += roundup2(ep[1].p_memsz, PAGE_SIZE);
#if 0
bootinfo.bi_symtab = VTOP(p);
if (hdr.eh.e_shnum == hdr.eh.e_shstrndx + 3) {
fs_off = hdr.eh.e_shoff + sizeof(es[0]) *
(hdr.eh.e_shstrndx + 1);
if (xfsread(ino, &es, sizeof(es)))
return;
for (i = 0; i < 2; i++) {
*(Elf32_Word *)p = es[i].sh_size;
p += sizeof(es[i].sh_size);
fs_off = es[i].sh_offset;
if (xfsread(ino, p, es[i].sh_size))
return;
p += es[i].sh_size;
}
}
#endif
addr = hdr.eh.e_entry;
#if 0
bootinfo.bi_esymtab = VTOP(p);
#endif
} else {
printf("Invalid %s\n", "format");
return;
}
boot((void *)addr, beri_argc, beri_argv, beri_envv);
}
static void
load(void)
{
switch (dsk.type) {
case BOOTINFO_DEV_TYPE_DRAM:
boot_fromdram();
break;
default:
boot_fromfs();
break;
}
}
static int
parse()
{
char *arg = cmd;
char *ep, *p, *q;
char unit;
size_t len;
const char *cp;
#if 0
int c, i, j;
#else
int c, i;
#endif
while ((c = *arg++)) {
if (c == ' ' || c == '\t' || c == '\n')
continue;
for (p = arg; *p && *p != '\n' && *p != ' ' && *p != '\t'; p++);
ep = p;
if (*p)
*p++ = 0;
if (c == '-') {
while ((c = *arg++)) {
if (c == 'P') {
cp = "yes";
#if 0
} else {
opts |= OPT_SET(RBX_DUAL) | OPT_SET(RBX_SERIAL);
cp = "no";
}
#endif
printf("Keyboard: %s\n", cp);
continue;
#if 0
} else if (c == 'S') {
j = 0;
while ((unsigned int)(i = *arg++ - '0') <= 9)
j = j * 10 + i;
if (j > 0 && i == -'0') {
comspeed = j;
break;
}
/* Fall through to error below ('S' not in optstr[]). */
#endif
}
for (i = 0; c != optstr[i]; i++)
if (i == NOPT - 1)
return -1;
opts ^= OPT_SET(flags[i]);
}
ioctrl = OPT_CHECK(RBX_DUAL) ? (IO_SERIAL|IO_KEYBOARD) :
OPT_CHECK(RBX_SERIAL) ? IO_SERIAL : IO_KEYBOARD;
#if 0
if (ioctrl & IO_SERIAL) {
if (sio_init(115200 / comspeed) != 0)
ioctrl &= ~IO_SERIAL;
}
#endif
} else {
/*-
* Parse a device/kernel name. Format(s):
*
* path
* deviceX:path
*
* NB: Utterly incomprehensible but space-efficient ARM/i386
* parsing removed in favour of larger but easier-to-read C. This
* is still not great, however -- e.g., relating to unit handling.
*
* TODO: it would be nice if a DRAM pointer could be specified
* here.
*
* XXXRW: Pick up pieces here.
*/
/*
* Search for a parens; if none, then it's just a path.
* Otherwise, it's a devicename.
*/
arg--;
q = strsep(&arg, ":");
if (arg != NULL) {
len = strlen(q);
if (len < 2) {
printf("Invalid device: name too short\n");
return (-1);
}
/*
* First, handle one-digit unit.
*/
unit = q[len-1];
if (unit < '0' || unit > '9') {
printf("Invalid device: invalid unit\n", q,
unit);
return (-1);
}
unit -= '0';
q[len-1] = '\0';
/*
* Next, find matching device.
*/
for (i = 0; i < dev_nm_count; i++) {
if (strcmp(q, dev_nm[i]) == 0)
break;
}
if (i == dev_nm_count) {
printf("Invalid device: no driver match\n");
return (-1);
}
dsk.type = i;
dsk.unitptr = unit; /* Someday: also a DRAM pointer? */
} else
arg = q;
if ((i = ep - arg)) {
if ((size_t)i >= sizeof(knamebuf))
return -1;
memcpy(knamebuf, arg, i + 1);
kname = knamebuf;
}
}
arg = p;
}
return 0;
}
static int
drvread(void *buf, unsigned lba, unsigned nblk)
{
/* XXXRW: eventually, we may want to pass 'drive' and 'unit' here. */
switch (dsk.type) {
case BOOTINFO_DEV_TYPE_CFI:
return (cfi_read(buf, lba, nblk));
case BOOTINFO_DEV_TYPE_SDCARD:
return (altera_sdcard_read(buf, lba, nblk));
default:
return (-1);
}
}
static int
dskread(void *buf, unsigned lba, unsigned nblk)
{
#if 0
/*
* XXXRW: For now, assume no partition table around the file system; it's
* just in raw flash.
*/
struct dos_partition *dp;
struct disklabel *d;
char *sec;
unsigned i;
uint8_t sl;
if (!dsk_meta) {
sec = dmadat->secbuf;
dsk.start = 0;
if (drvread(sec, DOSBBSECTOR, 1))
return -1;
dp = (void *)(sec + DOSPARTOFF);
sl = dsk.slice;
if (sl < BASE_SLICE) {
for (i = 0; i < NDOSPART; i++)
if (dp[i].dp_typ == DOSPTYP_386BSD &&
(dp[i].dp_flag & 0x80 || sl < BASE_SLICE)) {
sl = BASE_SLICE + i;
if (dp[i].dp_flag & 0x80 ||
dsk.slice == COMPATIBILITY_SLICE)
break;
}
if (dsk.slice == WHOLE_DISK_SLICE)
dsk.slice = sl;
}
if (sl != WHOLE_DISK_SLICE) {
if (sl != COMPATIBILITY_SLICE)
dp += sl - BASE_SLICE;
if (dp->dp_typ != DOSPTYP_386BSD) {
printf("Invalid %s\n", "slice");
return -1;
}
dsk.start = le32toh(dp->dp_start);
}
if (drvread(sec, dsk.start + LABELSECTOR, 1))
return -1;
d = (void *)(sec + LABELOFFSET);
if (le32toh(d->d_magic) != DISKMAGIC ||
le32toh(d->d_magic2) != DISKMAGIC) {
if (dsk.part != RAW_PART) {
printf("Invalid %s\n", "label");
return -1;
}
} else {
if (!dsk.init) {
if (le16toh(d->d_type) == DTYPE_SCSI)
dsk.type = TYPE_DA;
dsk.init++;
}
if (dsk.part >= le16toh(d->d_npartitions) ||
!(le32toh(d->d_partitions[dsk.part].p_size))) {
printf("Invalid %s\n", "partition");
return -1;
}
dsk.start += le32toh(d->d_partitions[dsk.part].p_offset);
dsk.start -= le32toh(d->d_partitions[RAW_PART].p_offset);
}
}
return drvread(buf, dsk.start + lba, nblk);
#else
return drvread(buf, lba, nblk);
#endif
}
void
putchar(int c)
{
if (c == '\n')
xputc('\r');
xputc(c);
}
static int
xputc(int c)
{
if (ioctrl & IO_KEYBOARD)
putc(c);
#if 0
if (ioctrl & IO_SERIAL)
sio_putc(c);
#endif
return c;
}
static int
xgetc(int fn)
{
if (OPT_CHECK(RBX_NOINTR))
return 0;
for (;;) {
if (ioctrl & IO_KEYBOARD && keyhit(0))
return fn ? 1 : getc();
#if 0
if (ioctrl & IO_SERIAL && sio_ischar())
return fn ? 1 : sio_getc();
#endif
if (fn)
return 0;
}
}
| 22.542296 | 101 | 0.61308 | [
"object"
] |
26168366bd286a7195eded2d4331b879f9f8e80a | 3,806 | h | C | Libraries/xcexecution/Headers/xcexecution/Parameters.h | njzhangyifei/xcbuild | f379277103ac2e457342b2b290ffa02d4293b74e | [
"BSD-2-Clause-NetBSD"
] | 2,077 | 2016-03-02T18:28:39.000Z | 2020-12-30T06:55:17.000Z | Libraries/xcexecution/Headers/xcexecution/Parameters.h | njzhangyifei/xcbuild | f379277103ac2e457342b2b290ffa02d4293b74e | [
"BSD-2-Clause-NetBSD"
] | 235 | 2016-03-02T18:05:40.000Z | 2020-12-22T09:31:01.000Z | Libraries/xcexecution/Headers/xcexecution/Parameters.h | njzhangyifei/xcbuild | f379277103ac2e457342b2b290ffa02d4293b74e | [
"BSD-2-Clause-NetBSD"
] | 183 | 2016-03-02T19:25:10.000Z | 2020-12-24T11:05:15.000Z | /**
Copyright (c) 2015-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.
*/
#ifndef __xcexecution_Parameters_h
#define __xcexecution_Parameters_h
#include <pbxsetting/Level.h>
#include <pbxbuild/Build/Context.h>
#include <pbxbuild/DirectedGraph.h>
#include <pbxbuild/WorkspaceContext.h>
#include <string>
#include <vector>
#include <ext/optional>
namespace libutil { class Filesystem; }
namespace xcexecution {
/*
* All of the inputs for a build. Can load the workspace on-demand and create
* a build context for a build action. This data is kept at this level to avoid
* loading the workspace when the parameters have not changed to an executor.
*/
class Parameters {
private:
ext::optional<std::string> _workspace;
ext::optional<std::string> _project;
ext::optional<std::string> _scheme;
ext::optional<std::vector<std::string>> _target;
bool _allTargets;
std::vector<std::string> _actions;
ext::optional<std::string> _configuration;
std::vector<pbxsetting::Level> _overrideLevels;
public:
Parameters(
ext::optional<std::string> const &workspace,
ext::optional<std::string> const &project,
ext::optional<std::string> const &scheme,
ext::optional<std::vector<std::string>> const &target,
bool allTargets,
std::vector<std::string> const &actions,
ext::optional<std::string> const &configuration,
std::vector<pbxsetting::Level> const &overrideLevels);
public:
/*
* The workspace to build.
*/
ext::optional<std::string> const &workspace() const
{ return _workspace; }
/*
* The project to build.
*/
ext::optional<std::string> const &project() const
{ return _project; }
/*
* The scheme to build.
*/
ext::optional<std::string> const &scheme() const
{ return _scheme; }
/*
* The target to build.
*/
ext::optional<std::vector<std::string>> const &target() const
{ return _target; }
/*
* Build all targets.
*/
bool allTargets() const
{ return _allTargets; }
/*
* The specified actions to build.
*/
std::vector<std::string> const &actions() const
{ return _actions; }
/*
* The configuration to build.
*/
ext::optional<std::string> const &configuration() const
{ return _configuration; }
/*
* Build setting overrides.
*/
std::vector<pbxsetting::Level> const &overrideLevels() const
{ return _overrideLevels; }
public:
/*
* The canonical set of arguments to reproduce these parameters.
*/
std::vector<std::string> canonicalArguments() const;
/*
* A stable hash of the parameters. Useful as a cache key.
*/
std::string canonicalHash() const;
public:
/*
* Loads the workspace from the build parameters.
*/
ext::optional<pbxbuild::WorkspaceContext> loadWorkspace(
libutil::Filesystem const *filesystem,
std::string const &userName,
pbxbuild::Build::Environment const &buildEnvironment,
std::string const &workingDirectory) const;
/*
* Creates the build context for a specific action.
*/
ext::optional<pbxbuild::Build::Context> createBuildContext(
pbxbuild::WorkspaceContext const &workspaceContext) const;
/*
* Resolve inter-target dependencies.
*/
ext::optional<pbxbuild::DirectedGraph<pbxproj::PBX::Target::shared_ptr>>
resolveDependencies(
pbxbuild::Build::Environment const &buildEnvironment,
pbxbuild::Build::Context const &buildContext) const;
};
}
#endif // !__xcexecution_Parameters_h
| 27.185714 | 79 | 0.653442 | [
"vector"
] |
261be2b5db72321c7539568af27972feb139437b | 2,597 | h | C | src/Physics_SoftBody.h | JJL772/vphysics_module_base | de732ae58cb64f3e1d92c8f1b5d07021b2f84af0 | [
"WTFPL"
] | 61 | 2015-02-12T14:58:08.000Z | 2022-01-31T22:15:35.000Z | src/Physics_SoftBody.h | JJL772/vphysics_module_base | de732ae58cb64f3e1d92c8f1b5d07021b2f84af0 | [
"WTFPL"
] | 21 | 2015-01-10T21:09:49.000Z | 2021-01-03T16:12:23.000Z | src/Physics_SoftBody.h | JJL772/vphysics_module_base | de732ae58cb64f3e1d92c8f1b5d07021b2f84af0 | [
"WTFPL"
] | 22 | 2015-03-04T11:17:24.000Z | 2022-03-05T18:56:57.000Z | #ifndef PHYSICS_SOFTBODY_H
#define PHYSICS_SOFTBODY_H
#if defined(_MSC_VER) || (defined(__GNUC__) && __GNUC__ > 3)
#pragma once
#endif
#include "vphysics/softbodyV32.h"
// Purpose: Dynamically deforming meshes (blankets, dents in objects, etc.)
// Class declarations
class CPhysicsEnvironment;
class CPhysicsObject;
class btSoftBody;
class CPhysicsSoftBody : public IPhysicsSoftBody {
public:
CPhysicsSoftBody();
~CPhysicsSoftBody();
bool IsAsleep() const;
void SetTotalMass(float fMass, bool bFromFaces = false);
void Anchor(int node, IPhysicsObject *pObj);
int GetNodeCount() const;
int GetFaceCount() const;
int GetLinkCount() const;
softbodynode_t GetNode(int i) const;
softbodylink_t GetLink(int i) const;
softbodyface_t GetFace(int i) const;
void SetNode(int i, softbodynode_t &node);
void AddNode(const Vector &pos, float mass); // Appends a new node to the end of the list (size-1)
void AddLink(int node1, int node2, bool bCheckExist = false);
void RemoveNode(int i);
void RemoveLink(int i);
void RemoveFace(int i);
// Get soft body AABB (cannot be implemented in collision interface because soft bodies change shape)
void GetAABB(Vector *mins, Vector *maxs) const;
void RayTest(Ray_t &ray, trace_t *pTrace) const;
void BoxTest(Ray_t &ray, trace_t *pTrace) const;
void Transform(const matrix3x4_t &mat);
void Transform(const Vector *vec, const QAngle *ang);
void Scale(const Vector &scale);
IPhysicsEnvironment32 *GetPhysicsEnvironment() const { return (IPhysicsEnvironment32 *)m_pEnv; }
// UNEXPOSED FUNCTIONS
public:
void Init(CPhysicsEnvironment *pEnv, btSoftBody *pSoftBody, const softbodyparams_t *pParams);
btSoftBody * GetSoftBody();
private:
CPhysicsEnvironment * m_pEnv;
btSoftBody * m_pSoftBody;
};
CPhysicsSoftBody *CreateSoftBody(CPhysicsEnvironment *pEnv);
CPhysicsSoftBody *CreateSoftBodyFromTriMesh(CPhysicsEnvironment *pEnv); // TODO: Not complete
// Vertices are in world space! (You can create this in local space then call Transform to move this to the start position)
CPhysicsSoftBody *CreateSoftBodyFromVertices(CPhysicsEnvironment *pEnv, const Vector *vertices, int numVertices, const softbodyparams_t *pParams);
CPhysicsSoftBody *CreateSoftBodyRope(CPhysicsEnvironment *pEnv, const Vector &position, const Vector &end, int resolution, const softbodyparams_t *pParams);
CPhysicsSoftBody *CreateSoftBodyPatch(CPhysicsEnvironment *pEnv, const Vector *corners, int resx, int resy, const softbodyparams_t *pParams);
#endif // PHYSICS_SOFTBODY_H | 35.575342 | 156 | 0.758183 | [
"shape",
"vector",
"transform"
] |
261daf815ac66358ae07c9c8765d7911c023c246 | 9,182 | h | C | sumo/src/utils/vehicle/IntermodalEdge.h | iltempe/osmosi | c0f54ecdbb7c7b5602d587768617d0dc50f1d75d | [
"MIT"
] | null | null | null | sumo/src/utils/vehicle/IntermodalEdge.h | iltempe/osmosi | c0f54ecdbb7c7b5602d587768617d0dc50f1d75d | [
"MIT"
] | null | null | null | sumo/src/utils/vehicle/IntermodalEdge.h | iltempe/osmosi | c0f54ecdbb7c7b5602d587768617d0dc50f1d75d | [
"MIT"
] | 2 | 2017-12-14T16:41:59.000Z | 2020-10-16T17:51:27.000Z | /****************************************************************************/
/// @file IntermodalEdge.h
/// @author Jakob Erdmann
/// @author Michael Behrisch
/// @author Robert Hilbrich
/// @date Mon, 03 March 2014
/// @version $Id$
///
// The Edge definition for the Intermodal Router
/****************************************************************************/
// SUMO, Simulation of Urban MObility; see http://sumo.dlr.de/
// Copyright (C) 2001-2017 DLR (http://www.dlr.de/) and contributors
/****************************************************************************/
//
// This file is part of SUMO.
// SUMO is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
/****************************************************************************/
#ifndef IntermodalEdge_h
#define IntermodalEdge_h
// ===========================================================================
// included modules
// ===========================================================================
#ifdef _MSC_VER
#include <windows_config.h>
#else
#include <config.h>
#endif
#include <string>
#include <vector>
#include <algorithm>
#include <assert.h>
#include <utils/common/SUMOTime.h>
#include <utils/common/ToString.h>
#include <utils/common/Named.h>
#define TL_RED_PENALTY 20
//#define IntermodalRouter_DEBUG_EFFORTS
template <class E, class L>
inline const L* getSidewalk(const E* edge) {
if (edge == 0) {
return 0;
}
const std::vector<L*>& lanes = edge->getLanes();
for (typename std::vector<L*>::const_iterator it = lanes.begin(); it != lanes.end(); ++it) {
if ((*it)->allowsVehicleClass(SVC_PEDESTRIAN)) {
return *it;
}
}
return 0;
}
// ===========================================================================
// class definitions
// ===========================================================================
/// @brief the "vehicle" type that is given to the internal router (SUMOAbstractRouter)
template<class E, class N, class V>
struct IntermodalTrip {
IntermodalTrip(const E* _from, const E* _to, double _departPos, double _arrivalPos,
double _speed, SUMOTime _departTime, const N* _node,
const V* _vehicle = 0, const SVCPermissions _modeSet = SVC_PEDESTRIAN) :
from(_from),
to(_to),
departPos(_departPos < 0 ? _from->getLength() + _departPos : _departPos),
arrivalPos(_arrivalPos < 0 ? _to->getLength() + _arrivalPos : _arrivalPos),
speed(_speed),
departTime(_departTime),
node(_node),
vehicle(_vehicle),
modeSet(_modeSet) {
}
// exists just for debugging purposes
std::string getID() const {
return from->getID() + ":" + to->getID() + ":" + time2string(departTime);
}
inline SUMOVehicleClass getVClass() const {
return vehicle != 0 ? vehicle->getVClass() : SVC_PEDESTRIAN;
}
const E* const from;
const E* const to;
const double departPos;
const double arrivalPos;
const double speed;
const SUMOTime departTime;
const N* const node; // indicates whether only routing across this node shall be performed
const V* const vehicle; // indicates which vehicle may be used
const SVCPermissions modeSet;
private:
/// @brief Invalidated assignment operator.
IntermodalTrip& operator=(const IntermodalTrip&);
};
/// @brief the base edge type that is given to the internal router (SUMOAbstractRouter)
template<class E, class L, class N, class V>
class IntermodalEdge : public Named {
public:
IntermodalEdge(const std::string id, int numericalID, const E* edge, const std::string& line) :
Named(id),
myNumericalID(numericalID),
myEdge(edge),
myLine(line),
myLength(edge->getLength()) { }
virtual ~IntermodalEdge() {}
virtual bool includeInRoute(bool /* allEdges */) const {
return false;
}
inline const std::string& getLine() const {
return myLine;
}
inline const E* getEdge() const {
return myEdge;
}
int getNumericalID() const {
return myNumericalID;
}
void addSuccessor(IntermodalEdge* s) {
myFollowingEdges.push_back(s);
}
void setSuccessors(const std::vector<IntermodalEdge*>& edges) {
myFollowingEdges = edges;
}
void clearSuccessors() {
myFollowingEdges.clear();
}
void removeSuccessor(const IntermodalEdge* const edge) {
myFollowingEdges.erase(std::find(myFollowingEdges.begin(), myFollowingEdges.end(), edge));
}
virtual const std::vector<IntermodalEdge*>& getSuccessors(SUMOVehicleClass /*vClass*/) const {
// the network is already tailored for pedestrians. No need to check for permissions here
return myFollowingEdges;
}
virtual bool prohibits(const IntermodalTrip<E, N, V>* const /* trip */) const {
return false;
}
virtual double getTravelTime(const IntermodalTrip<E, N, V>* const /* trip */, double /* time */) const {
return 0;
}
static double getTravelTimeStatic(const IntermodalEdge* const edge, const IntermodalTrip<E, N, V>* const trip, double time) {
return edge->getTravelTime(trip, time);
}
inline double getLength() const {
return myLength;
}
inline void setLength(const double length) {
myLength = length;
}
protected:
/// @brief List of edges that may be approached from this edge
std::vector<IntermodalEdge*> myFollowingEdges;
private:
/// @brief the index in myEdges
const int myNumericalID;
/// @brief the original edge
const E* const myEdge;
/// @brief public transport line or ped vs car
const std::string myLine;
/// @brief adaptable length (for splitted edges)
double myLength;
private:
/// @brief Invalidated copy constructor
IntermodalEdge(const IntermodalEdge& src);
/// @brief Invalidated assignment operator
IntermodalEdge& operator=(const IntermodalEdge& src);
};
/// @brief the pedestrian edge type that is given to the internal router (SUMOAbstractRouter)
template<class E, class L, class N, class V>
class PedestrianEdge : public IntermodalEdge<E, L, N, V> {
public:
PedestrianEdge(int numericalID, const E* edge, const L* lane, bool forward, const double pos = -1.) :
IntermodalEdge<E, L, N, V>(edge->getID() + (edge->isWalkingArea() ? "" : (forward ? "_fwd" : "_bwd")) + toString(pos), numericalID, edge, "!ped"),
myLane(lane),
myForward(forward),
myStartPos(pos >= 0 ? pos : 0.) { }
bool includeInRoute(bool allEdges) const {
return allEdges || (!this->getEdge()->isCrossing() && !this->getEdge()->isWalkingArea());
}
bool prohibits(const IntermodalTrip<E, N, V>* const trip) const {
if (trip->node == 0) {
// network only includes IntermodalEdges
return false;
} else {
// limit routing to the surroundings of the specified node
return (this->getEdge()->getFromJunction() != trip->node
&& this->getEdge()->getToJunction() != trip->node);
}
}
virtual double getTravelTime(const IntermodalTrip<E, N, V>* const trip, double time) const {
double length = this->getLength();
if (this->getEdge() == trip->from && !myForward) {
length = trip->departPos - myStartPos;
}
if (this->getEdge() == trip->to && myForward) {
length = trip->arrivalPos - myStartPos;
}
if (this->getEdge() == trip->from && myForward) {
length -= (trip->departPos - myStartPos);
}
if (this->getEdge() == trip->to && !myForward) {
length -= (trip->arrivalPos - myStartPos);
}
// ensure that 'normal' edges always have a higher weight than connector edges
length = MAX2(length, POSITION_EPS);
double tlsDelay = 0;
// @note pedestrian traffic lights should never have LINKSTATE_TL_REDYELLOW
if (this->getEdge()->isCrossing() && myLane->getIncomingLinkState() == LINKSTATE_TL_RED) {
// red traffic lights occurring later in the route may be green by the time we arive
tlsDelay += MAX2(double(0), TL_RED_PENALTY - (time - STEPS2TIME(trip->departTime)));
}
#ifdef IntermodalRouter_DEBUG_EFFORTS
std::cout << " effort for " << trip->getID() << " at " << time << " edge=" << edge->getID() << " effort=" << length / trip->speed + tlsDelay << " l=" << length << " s=" << trip->speed << " tlsDelay=" << tlsDelay << "\n";
#endif
return length / trip->speed + tlsDelay;
}
private:
/// @brief the original edge
const L* myLane;
/// @brief the direction of this edge
const bool myForward;
/// @brief the starting position for split edges
const double myStartPos;
};
#endif
/****************************************************************************/
| 33.268116 | 228 | 0.587127 | [
"vector"
] |
26289928fe2f3a63e3b2ea5ea41684853dfca0b6 | 4,540 | h | C | dev/Gems/EMotionFX/Code/Tests/AnimGraphFixture.h | brianherrera/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | [
"AML"
] | 1,738 | 2017-09-21T10:59:12.000Z | 2022-03-31T21:05:46.000Z | dev/Gems/EMotionFX/Code/Tests/AnimGraphFixture.h | ArchitectureStudios/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | [
"AML"
] | 427 | 2017-09-29T22:54:36.000Z | 2022-02-15T19:26:50.000Z | dev/Gems/EMotionFX/Code/Tests/AnimGraphFixture.h | ArchitectureStudios/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | [
"AML"
] | 671 | 2017-09-21T08:04:01.000Z | 2022-03-29T14:30:07.000Z | /*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#pragma once
#include "SystemComponentFixture.h"
#include <EMotionFX/Source/MotionSet.h>
#include <AzCore/Debug/TraceMessageBus.h>
#include <AzCore/Outcome/Outcome.h>
#include <AzCore/std/smart_ptr/unique_ptr.h>
#include <AzCore/std/string/string.h>
#include <MCore/Source/Attribute.h>
#include <Tests/TestAssetCode/AnimGraphFactory.h>
namespace EMotionFX
{
class Actor;
class ActorInstance;
class AnimGraph;
class AnimGraphStateMachine;
class AnimGraphStateTransition;
class AnimGraphInstance;
class AnimGraphTimeCondition;
class Transform;
class AnimGraphFixture
: public SystemComponentFixture
, public AZ::Debug::TraceMessageBus::Handler
{
public:
void SetUp() override;
void TearDown() override;
// Derived classes should override and construct the rest of the graph at this point.
// They should call this base ConstructGraph to get the anim graph and root state machine created.
virtual void ConstructGraph();
virtual void ConstructActor();
AZStd::string SerializeAnimGraph() const;
// Evaluates the graph
void Evaluate();
const Transform& GetOutputTransform(uint32 nodeIndex = 0);
void AddValueParameter(const AZ::TypeId& typeId, const AZStd::string& name);
template <class ParamType, class InputType>
void ParamSetValue(const AZStd::string& paramName, const InputType& value)
{
const AZ::Outcome<size_t> parameterIndex = m_animGraphInstance->FindParameterIndex(paramName);
const AZ::u32 paramIndex = static_cast<AZ::u32>(parameterIndex.GetValue());
MCore::Attribute* param = m_animGraphInstance->GetParameterValue(paramIndex);
ParamType* typeParam = static_cast<ParamType*>(param);
typeParam->SetValue(value);
}
// Helper functions for state machine construction (Works on m_rootStateMachine).
AnimGraphStateTransition* AddTransition(AnimGraphNode* source, AnimGraphNode* target, float time);
AnimGraphTimeCondition* AddTimeCondition(AnimGraphStateTransition* transition, float countDownTime);
AnimGraphStateTransition* AddTransitionWithTimeCondition(AnimGraphNode* source, AnimGraphNode* target, float blendTime, float countDownTime);
// Helper function for motion set construction (Works on m_motionSet).
MotionSet::MotionEntry* AddMotionEntry(const AZStd::string& motionId, float motionMaxTime);
// TraceMessageBus - Intercepting to prevent dialog popup in AnimGraphReferenceNodeWithNoContentsTest.
virtual bool OnError(const char* /*window*/, const char* /*message*/) override { return true; }
using SimulateFrameCallback = std::function<void(AnimGraphInstance*, /*time*/ float, /*timeDelta*/ float, /*frame*/ int)>;
using SimulateCallback = std::function<void(AnimGraphInstance*)>;
/**
* Simulation helper with callbacks before and after starting the simulation as well as
* callbakcs before and after the anim graph update.
* Example: expectedFps = 60, fpsVariance = 10 -> actual framerate = [55, 65]
* @param[in] simulationTime Simulation time in seconds.
* @param[in] expectedFps is the targeted frame rate
* @param[in] fpsVariance is the range in which the instabilities happen.
*/
void Simulate(float simulationTime, float expectedFps, float fpsVariance,
SimulateCallback preCallback,
SimulateCallback postCallback,
SimulateFrameCallback preUpdateCallback,
SimulateFrameCallback postUpdateCallback);
protected:
AZStd::unique_ptr<Actor> m_actor;
ActorInstance* m_actorInstance = nullptr;
AZStd::unique_ptr<AnimGraph> m_animGraph;
AnimGraphStateMachine* m_rootStateMachine = nullptr;
AnimGraphInstance* m_animGraphInstance = nullptr;
MotionSet* m_motionSet = nullptr;
};
}
| 42.429907 | 149 | 0.709912 | [
"transform"
] |
262b8db329f267815140f0be5d5995c77989bdab | 2,432 | h | C | database/bench/BenchmarkInitiator.h | charles-typ/gam | 779f9d1287533977e22fd7180daf23fe1db8a586 | [
"Apache-2.0"
] | 53 | 2018-12-07T04:12:28.000Z | 2022-03-18T08:41:58.000Z | database/bench/BenchmarkInitiator.h | charles-typ/gam | 779f9d1287533977e22fd7180daf23fe1db8a586 | [
"Apache-2.0"
] | 3 | 2020-05-05T12:02:38.000Z | 2021-05-20T19:51:21.000Z | database/bench/BenchmarkInitiator.h | charles-typ/gam | 779f9d1287533977e22fd7180daf23fe1db8a586 | [
"Apache-2.0"
] | 26 | 2018-12-19T14:42:21.000Z | 2022-03-25T06:11:00.000Z | #ifndef __DATABASE_BENCHMARK_INITIATOR_H__
#define __DATABASE_BENCHMARK_INITIATOR_H__
#include "gallocator.h"
#include "ClusterHelper.h"
#include "ClusterConfig.h"
#include "StorageManager.h"
#include "Profiler.h"
#include "PerfStatistics.h"
namespace Database {
class BenchmarkInitiator {
public:
BenchmarkInitiator(const size_t& thread_count,
ClusterConfig* config)
: thread_count_(thread_count),
config_(config) {
}
void InitGAllocator() {
ServerInfo master = config_->GetMasterHostInfo();
ServerInfo myhost = config_->GetMyHostInfo();
Conf* conf = new Conf();
conf->loglevel = LOG_WARNING;
conf->size = 1024 * 1024L * 512 * 2 * 16;
conf->is_master = config_->IsMaster();
conf->master_ip = ClusterHelper::GetIpByHostName(master.addr_);
conf->worker_ip = ClusterHelper::GetIpByHostName(myhost.addr_);
int partition_id = config_->GetMyPartitionId();
// to avoid port conflicts on the same node
conf->worker_port += partition_id;
std::cout << "GAllocator config info: is_master=" << conf->is_master
<< ",master_ip=" << conf->master_ip << ",master_port="
<< conf->master_port << ",worker_ip=" << conf->worker_ip
<< ",worker_port=" << conf->worker_port << std::endl;
default_gallocator = GAllocFactory::CreateAllocator(conf);
std::cout << "create default gallocator" << std::endl;
gallocators = new GAlloc*[thread_count_];
for (size_t i = 0; i < thread_count_; ++i) {
gallocators[i] = GAllocFactory::CreateAllocator(conf);
}
}
GAddr InitStorage() {
GAddr storage_addr = Gnullptr;
int my_partition_id = config_->GetMyPartitionId();
int partition_num = config_->GetPartitionNum();
if (config_->IsMaster()) {
// RecordSchema
std::vector<RecordSchema*> schemas;
this->RegisterSchemas(schemas);
// StorageManager
storage_addr = default_gallocator->AlignedMalloc(
StorageManager::GetSerializeSize());
this->RegisterTables(storage_addr, schemas);
}
return storage_addr;
}
protected:
virtual void RegisterTables(const GAddr& storage_addr,
const std::vector<RecordSchema*>& schemas) {}
virtual void RegisterSchemas(std::vector<RecordSchema*>& schemas) {}
const size_t thread_count_;
ClusterConfig* config_;
};
}
#endif
| 32.426667 | 73 | 0.661184 | [
"vector"
] |
262c01d616aa1923be5daad85d5c6684f830a76e | 4,749 | h | C | src/util/CNFFormula.h | sat-clique/cnftools | 12593a524a5a5699d6ec29c300432a28e7873b76 | [
"MIT"
] | null | null | null | src/util/CNFFormula.h | sat-clique/cnftools | 12593a524a5a5699d6ec29c300432a28e7873b76 | [
"MIT"
] | null | null | null | src/util/CNFFormula.h | sat-clique/cnftools | 12593a524a5a5699d6ec29c300432a28e7873b76 | [
"MIT"
] | null | null | null | /*************************************************************************************************
CNFTools -- Copyright (c) 2021, Markus Iser, KIT - Karlsruhe Institute of Technology
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.
**************************************************************************************************/
#ifndef SRC_UTIL_CNFFORMULA_H_
#define SRC_UTIL_CNFFORMULA_H_
#include <vector>
#include <algorithm>
#include <memory>
#include <string>
#include "src/util/StreamBuffer.h"
#include "src/util/SolverTypes.h"
#include "src/util/ResourceLimits.h"
class CNFFormula {
For formula;
unsigned variables;
public:
CNFFormula() : formula(), variables(0) { }
explicit CNFFormula(const char* filename) : CNFFormula() {
readDimacsFromFile(filename);
}
~CNFFormula() {
for (Cl* clause : formula) {
delete clause;
}
}
typedef For::const_iterator const_iterator;
inline const_iterator begin() const {
return formula.begin();
}
inline const_iterator end() const {
return formula.end();
}
inline const Cl* operator[] (int i) const {
return formula[i];
}
inline size_t nVars() const {
return variables;
}
inline size_t nClauses() const {
return formula.size();
}
inline int newVar() {
return ++variables;
}
inline void clear() {
formula.clear();
}
// create gapless representation of variables
void normalizeVariableNames() {
std::vector<unsigned> name;
name.resize(variables+1, 0);
unsigned int max = 0;
for (Cl* clause : formula) {
for (Lit& lit : *clause) {
if (name[lit.var()] == 0) name[lit.var()] = max++;
lit = Lit(name[lit.var()], lit.sign());
}
}
variables = max;
}
void readDimacsFromFile(const char* filename) {
StreamBuffer in(filename);
Cl clause;
while (!in.eof()) {
in.skipWhitespace();
if (in.eof()) {
break;
}
if (*in == 'p' || *in == 'c') {
in.skipLine();
} else {
for (int plit = in.readInteger(); plit != 0; plit = in.readInteger()) {
clause.push_back(Lit(abs(plit), plit < 0));
}
readClause(clause.begin(), clause.end());
clause.clear();
}
}
}
void readClause(std::initializer_list<Lit> list) {
readClause(list.begin(), list.end());
}
void readClauses(const For& formula) {
for (Cl* clause : formula) {
readClause(clause->begin(), clause->end());
}
}
template <typename Iterator>
void readClause(Iterator begin, Iterator end) {
Cl* clause = new Cl { begin, end };
if (clause->size() > 0) {
// remove redundant literals
std::sort(clause->begin(), clause->end());
unsigned dup = 0;
for (auto it = clause->begin(), jt = clause->begin()+1; jt != clause->end(); ++jt) {
if (*it != *jt) { // unique
if (it->var() == jt->var()) {
delete clause;
return; // no tautologies
}
++it;
*it = *jt;
} else {
++dup;
}
}
clause->resize(clause->size() - dup);
clause->shrink_to_fit();
variables = std::max(variables, (unsigned int)clause->back().var());
}
formula.push_back(clause);
}
};
#endif // SRC_UTIL_CNFFORMULA_H_
| 31.243421 | 100 | 0.547063 | [
"vector"
] |
262edf08517da3aca1e3b98d2453a1b9e644407a | 18,200 | h | C | php/include/php/ext/apcu/apc_cache_api.h | BERRYVOOGD/prestashop-1.7.0.4-1 | 5c4d8aa453844019fa9616aa1f9b380f743ee825 | [
"ECL-2.0",
"Apache-2.0",
"BSD-3-Clause"
] | 1 | 2015-11-27T08:46:38.000Z | 2015-11-27T08:46:38.000Z | php/include/php/ext/apcu/apc_cache_api.h | BERRYVOOGD/prestashop-1.7.0.4-1 | 5c4d8aa453844019fa9616aa1f9b380f743ee825 | [
"ECL-2.0",
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | php/include/php/ext/apcu/apc_cache_api.h | BERRYVOOGD/prestashop-1.7.0.4-1 | 5c4d8aa453844019fa9616aa1f9b380f743ee825 | [
"ECL-2.0",
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | /*
+----------------------------------------------------------------------+
| APC |
+----------------------------------------------------------------------+
| Copyright (c) 2006-2011 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Daniel Cowgill <dcowgill@communityconnect.com> |
| Rasmus Lerdorf <rasmus@php.net> |
+----------------------------------------------------------------------+
This software was contributed to PHP by Community Connect Inc. in 2002
and revised in 2005 by Yahoo! Inc. to add support for PHP 5.1.
Future revisions and derivatives of this source code must acknowledge
Community Connect Inc. as the original contributor of this module by
leaving this note intact in the source code.
All other licensing and usage conditions are those of the PHP Group.
*/
/* $Id: apc_cache.h 328172 2012-10-28 21:44:47Z rasmus $ */
#ifndef APC_CACHE_API_H
#define APC_CACHE_API_H
/* {{{ used for slam defense to determine the context which created any key */
#ifdef ZTS
typedef void*** apc_cache_owner_t;
#else
typedef pid_t apc_cache_owner_t;
#endif /* }}} */
/* {{{ struct definition: apc_cache_key_t */
typedef struct apc_cache_key_t apc_cache_key_t;
struct apc_cache_key_t {
const char *str; /* pointer to constant string key */
zend_uint len; /* length of data at str */
zend_ulong h; /* pre-computed hash of key */
time_t mtime; /* the mtime of this cached entry */
apc_cache_owner_t owner; /* the context that created this key */
}; /* }}} */
/* {{{ struct definition: apc_cache_entry_t */
typedef struct apc_cache_entry_t apc_cache_entry_t;
struct apc_cache_entry_t {
zval *val; /* the zval copied at store time */
zend_uint ttl; /* the ttl on this specific entry */
int ref_count; /* the reference count of this entry */
size_t mem_size; /* memory used */
apc_pool *pool; /* pool which allocated the value */
};
/* }}} */
/* {{{ struct definition: apc_cache_slot_t */
typedef struct apc_cache_slot_t apc_cache_slot_t;
struct apc_cache_slot_t {
apc_cache_key_t key; /* slot key */
apc_cache_entry_t* value; /* slot value */
apc_cache_slot_t* next; /* next slot in linked list */
zend_ulong nhits; /* number of hits to this slot */
time_t ctime; /* time slot was initialized */
time_t dtime; /* time slot was removed from cache */
time_t atime; /* time slot was last accessed */
};
/* }}} */
/* {{{ state constants */
#define APC_CACHE_ST_NONE 0
#define APC_CACHE_ST_BUSY 0x00000001 /* }}} */
/* {{{ struct definition: apc_cache_header_t
Any values that must be shared among processes should go in here. */
typedef struct _apc_cache_header_t {
apc_lock_t lock; /* header lock */
zend_ulong nhits; /* hit count */
zend_ulong nmisses; /* miss count */
zend_ulong ninserts; /* insert count */
zend_ulong nexpunges; /* expunge count */
zend_ulong nentries; /* entry count */
zend_ulong mem_size; /* used */
time_t stime; /* start time */
zend_ushort state; /* cache state */
apc_cache_key_t lastkey; /* last key inserted (not necessarily without error) */
apc_cache_slot_t* gc; /* gc list */
} apc_cache_header_t; /* }}} */
/* {{{ struct definition: apc_cache_t */
typedef struct _apc_cache_t {
void* shmaddr; /* process (local) address of shared cache */
apc_cache_header_t* header; /* cache header (stored in SHM) */
apc_cache_slot_t** slots; /* array of cache slots (stored in SHM) */
apc_sma_t* sma; /* shared memory allocator */
apc_serializer_t* serializer; /* serializer */
zend_ulong nslots; /* number of slots in cache */
zend_ulong gc_ttl; /* maximum time on GC list for a slot */
zend_ulong ttl; /* if slot is needed and entry's access time is older than this ttl, remove it */
zend_ulong smart; /* smart parameter for gc */
zend_bool defend; /* defense parameter for runtime */
} apc_cache_t; /* }}} */
/* {{{ typedef: apc_cache_updater_t */
typedef zend_bool (*apc_cache_updater_t)(apc_cache_t*, apc_cache_entry_t*, void* data); /* }}} */
/*
* apc_cache_create creates the shared memory cache.
*
* This function should be called once per process per cache
*
* serializer for APCu is set by globals on MINIT and ensured with apc_cache_serializer
* during execution. Using apc_cache_serializer avoids race conditions between MINIT/RINIT of
* APCU and the third party serializer. API users can choose to leave this null to use default
* PHP serializers, or search the list of serializers for the preferred serializer
*
* size_hint is a "hint" at the total number entries that will be expected.
* It determines the physical size of the hash table. Passing 0 for
* this argument will use a reasonable default value
*
* gc_ttl is the maximum time a cache entry may speed on the garbage
* collection list. This is basically a work around for the inherent
* unreliability of our reference counting mechanism (see apc_cache_release).
*
* ttl is the maximum time a cache entry can idle in a slot in case the slot
* is needed. This helps in cleaning up the cache and ensuring that entries
* hit frequently stay cached and ones not hit very often eventually disappear.
*
* for an explanation of smart, see apc_cache_default_expunge
*
* defend enables/disables slam defense for this particular cache
*/
PHP_APCU_API apc_cache_t* apc_cache_create(apc_sma_t* sma,
apc_serializer_t* serializer,
int size_hint,
int gc_ttl,
int ttl,
long smart,
zend_bool defend TSRMLS_DC);
/*
* apc_cache_preload preloads the data at path into the specified cache
*/
PHP_APCU_API zend_bool apc_cache_preload(apc_cache_t* cache,
const char* path TSRMLS_DC);
/*
* apc_cache_destroy releases any OS resources associated with a cache object.
* Under apache, this function can be safely called by the child processes
* when they exit.
*/
PHP_APCU_API void apc_cache_destroy(apc_cache_t* cache TSRMLS_DC);
/*
* apc_cache_clear empties a cache. This can safely be called at any time.
*/
PHP_APCU_API void apc_cache_clear(apc_cache_t* cache TSRMLS_DC);
/*
* apc_cache_make_context initializes a context with an appropriate pool and options provided
*
* Some of the APC API requires a context in which to operate
*
* The type of context required depends on the operation being performed, for example
* an insert should happen in a shared context, a fetch should happen in a nonshared context
*/
PHP_APCU_API zend_bool apc_cache_make_context(apc_cache_t* cache,
apc_context_t* context,
apc_context_type context_type,
apc_pool_type pool_type,
apc_copy_type copy_type,
uint force_update TSRMLS_DC);
/*
* apc_cache_make_context_ex is an advanced/external version of make_context
*/
PHP_APCU_API zend_bool apc_cache_make_context_ex(apc_context_t* context,
apc_serializer_t* serializer,
apc_malloc_t _malloc,
apc_free_t _free,
apc_protect_t _protect,
apc_unprotect_t _unprotect,
apc_pool_type pool_type,
apc_copy_type copy_type,
uint force_update TSRMLS_DC);
/*
* apc_context_destroy should be called when a context is finished being used
*/
PHP_APCU_API zend_bool apc_cache_destroy_context(apc_context_t* context TSRMLS_DC);
/*
* apc_cache_insert adds an entry to the cache.
* Returns true if the entry was successfully inserted, false otherwise.
* If false is returned, the caller must free the cache entry by calling
* apc_cache_free_entry (see below).
*
* key is the value created by apc_cache_make_key
*
* value is a cache entry returned by apc_cache_make_entry (see below).
*
* an easier API exists in the form of apc_cache_store
*/
PHP_APCU_API zend_bool apc_cache_insert(apc_cache_t* cache,
apc_cache_key_t key,
apc_cache_entry_t* value,
apc_context_t* ctxt,
time_t t,
zend_bool exclusive TSRMLS_DC);
/*
* apc_cache_store creates key, entry and context in which to make an insertion of val into the specified cache
*/
PHP_APCU_API zend_bool apc_cache_store(apc_cache_t* cache,
char *strkey,
zend_uint keylen,
const zval *val,
const zend_uint ttl,
const zend_bool exclusive TSRMLS_DC);
/*
* apc_cache_update updates an entry in place, this is used for rfc1867 and inc/dec/cas
*/
PHP_APCU_API zend_bool apc_cache_update(apc_cache_t* cache,
char *strkey,
zend_uint keylen,
apc_cache_updater_t updater,
void* data TSRMLS_DC);
/*
* apc_cache_find searches for a cache entry by its hashed identifier,
* and returns a pointer to the entry if found, NULL otherwise.
*
*/
PHP_APCU_API apc_cache_entry_t* apc_cache_find(apc_cache_t* cache,
char* strkey,
zend_uint keylen,
time_t t TSRMLS_DC);
/*
* apc_cache_fetch fetches an entry from the cache directly into dst
*
*/
PHP_APCU_API zend_bool apc_cache_fetch(apc_cache_t* cache,
char* strkey,
zend_uint keylen,
time_t t,
zval **dst TSRMLS_DC);
/*
* apc_cache_exists searches for a cache entry by its hashed identifier,
* and returns a pointer to the entry if found, NULL otherwise. This is a
* quick non-locking version of apc_cache_find that does not modify the
* shared memory segment in any way.
*
*/
PHP_APCU_API apc_cache_entry_t* apc_cache_exists(apc_cache_t* cache,
char* strkey,
zend_uint keylen,
time_t t TSRMLS_DC);
/*
* apc_cache_delete and apc_cache_delete finds an entry in the cache and deletes it.
*/
PHP_APCU_API zend_bool apc_cache_delete(apc_cache_t* cache,
char *strkey,
zend_uint keylen TSRMLS_DC);
/* apc_cach_fetch_zval takes a zval in the cache and reconstructs a runtime
* zval from it.
*
*/
PHP_APCU_API zval* apc_cache_fetch_zval(apc_context_t* ctxt,
zval* dst,
const zval* src TSRMLS_DC);
/*
* apc_cache_release decrements the reference count associated with a cache
* entry. Calling apc_cache_find automatically increments the reference count,
* and this function must be called post-execution to return the count to its
* original value. Failing to do so will prevent the entry from being
* garbage-collected.
*
* entry is the cache entry whose ref count you want to decrement.
*/
PHP_APCU_API void apc_cache_release(apc_cache_t* cache,
apc_cache_entry_t* entry TSRMLS_DC);
/*
* apc_cache_make_key creates an apc_cache_key_t from an identifier, it's length and the current time
*/
PHP_APCU_API zend_bool apc_cache_make_key(apc_cache_key_t* key,
char* str,
zend_ulong len TSRMLS_DC);
/*
* apc_cache_make_entry creates an apc_cache_entry_t given a zval, context and ttl
*/
PHP_APCU_API apc_cache_entry_t* apc_cache_make_entry(apc_context_t* ctxt,
apc_cache_key_t* key,
const zval *val,
const zend_uint ttl TSRMLS_DC);
/*
fetches information about the cache provided for userland status functions
*/
PHP_APCU_API zval* apc_cache_info(apc_cache_t* cache,
zend_bool limited TSRMLS_DC);
/*
fetches information about the key provided
*/
PHP_APCU_API zval* apc_cache_stat(apc_cache_t* cache,
char *strkey,
zend_uint keylen TSRMLS_DC);
/*
* apc_cache_busy returns true while the cache is busy
*
* a cache is considered busy when any of the following occur:
* a) the cache becomes busy when the allocator beneath it is running out of resources
* b) a clear of the cache was requested
* c) garbage collection is in progress
*
* Note: garbage collection can be invoked by the SMA and is invoked on insert
*/
PHP_APCU_API zend_bool apc_cache_busy(apc_cache_t* cache TSRMLS_DC);
/*
* apc_cache_defense: guard against slamming a key
* will return true if the following conditions are met:
* the key provided has a matching hash and length to the last key inserted into cache
* the last key has a different owner
* in ZTS mode, TSRM determines owner
* in non-ZTS mode, PID determines owner
* Note: this function sets the owner of key during execution
*/
PHP_APCU_API zend_bool apc_cache_defense(apc_cache_t* cache,
apc_cache_key_t* key TSRMLS_DC);
/*
* apc_cache_serializer
* sets the serializer for a cache, and by proxy contexts created for the cache
* Note: this avoids race conditions between third party serializers and APCu
*/
PHP_APCU_API void apc_cache_serializer(apc_cache_t* cache, const char* name TSRMLS_DC);
/*
* The remaining functions allow a third party to reimplement expunge
*
* Look at the source of apc_cache_default_expunge for what is expected of this function
*
* The default behaviour of expunge is explained below, should no combination of those options
* be suitable, you will need to reimplement apc_cache_default_expunge and pass it to your
* call to apc_sma_api_impl, this will replace the default functionality.
* The functions below you can use during your own implementation of expunge to gain more
* control over how the expunge process works ...
*
* Note: beware of locking (copy it exactly), setting states is also important
*/
/* {{{ apc_cache_default_expunge
* Where smart is not set:
* Where no ttl is set on cache:
* 1) Perform cleanup of stale entries
* 2) Expunge if available memory is less than sma->size/2
* Where ttl is set on cache:
* 1) Perform cleanup of stale entries
* 2) If available memory if less than the size requested, run full expunge
*
* Where smart is set:
* Where no ttl is set on cache:
* 1) Perform cleanup of stale entries
* 2) Expunge is available memory is less than size * smart
* Where ttl is set on cache:
* 1) Perform cleanup of stale entries
* 2) If available memory if less than the size requested, run full expunge
*
* The TTL of an entry takes precedence over the TTL of a cache
*/
PHP_APCU_API void apc_cache_default_expunge(apc_cache_t* cache, size_t size TSRMLS_DC);
/*
* The remaining functions are used during the APCu implementation of expunge
*/
/*
* apc_cache_real_expunge: trashes the whole cache
*
* Note: it is assumed you have a write lock on the header when you enter real expunge
*/
PHP_APCU_API void apc_cache_real_expunge(apc_cache_t* cache TSRMLS_DC);
/*
* apc_cache_gc: runs garbage collection on cache
*
* Note: it is assumed you have a write lock on the header when you enter gc
*/
PHP_APCU_API void apc_cache_gc(apc_cache_t* cache TSRMLS_DC);
/*
* apc_cache_remove_slot: removes slot
*
* if no references remain, the slot is free'd immediately
* if there are references remaining, the slot is trashed
*
* Note: it is assumed you have a write lock on the header when you remove slots
*/
PHP_APCU_API void apc_cache_remove_slot(apc_cache_t* cache, apc_cache_slot_t** slot TSRMLS_DC);
#endif
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim>600: expandtab sw=4 ts=4 sts=4 fdm=marker
* vim<600: expandtab sw=4 ts=4 sts=4
*/
| 43.127962 | 115 | 0.606758 | [
"object"
] |
2635e2f3aaa8f95f7a4b3bb24b14c200984b4f72 | 19,611 | h | C | native/avos/external/android/include/16/frameworks/native/include/gui/SurfaceTexture.h | goyourfly/NovaCustom | c55265060a84b7b5b1f4b42ae096370205c66ad7 | [
"Apache-2.0"
] | 23 | 2015-11-13T08:30:55.000Z | 2022-02-24T05:45:43.000Z | native/avos/external/android/include/16/frameworks/native/include/gui/SurfaceTexture.h | goyourfly/NovaCustom | c55265060a84b7b5b1f4b42ae096370205c66ad7 | [
"Apache-2.0"
] | 2 | 2016-09-12T03:17:46.000Z | 2017-03-20T06:33:36.000Z | native/avos/external/android/include/16/frameworks/native/include/gui/SurfaceTexture.h | goyourfly/NovaCustom | c55265060a84b7b5b1f4b42ae096370205c66ad7 | [
"Apache-2.0"
] | 18 | 2015-11-14T00:54:38.000Z | 2021-08-23T11:44:52.000Z | /*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ANDROID_GUI_SURFACETEXTURE_H
#define ANDROID_GUI_SURFACETEXTURE_H
#include <EGL/egl.h>
#include <EGL/eglext.h>
#include <GLES2/gl2.h>
#include <GLES2/gl2ext.h>
#include <gui/ISurfaceTexture.h>
#include <gui/BufferQueue.h>
#include <ui/GraphicBuffer.h>
#include <utils/String8.h>
#include <utils/Vector.h>
#include <utils/threads.h>
#define ANDROID_GRAPHICS_SURFACETEXTURE_JNI_ID "mSurfaceTexture"
namespace android {
// ----------------------------------------------------------------------------
class String8;
class SurfaceTexture : public virtual RefBase,
protected BufferQueue::ConsumerListener {
public:
struct FrameAvailableListener : public virtual RefBase {
// onFrameAvailable() is called each time an additional frame becomes
// available for consumption. This means that frames that are queued
// while in asynchronous mode only trigger the callback if no previous
// frames are pending. Frames queued while in synchronous mode always
// trigger the callback.
//
// This is called without any lock held and can be called concurrently
// by multiple threads.
virtual void onFrameAvailable() = 0;
};
// SurfaceTexture constructs a new SurfaceTexture object. tex indicates the
// name of the OpenGL ES texture to which images are to be streamed.
// allowSynchronousMode specifies whether or not synchronous mode can be
// enabled. texTarget specifies the OpenGL ES texture target to which the
// texture will be bound in updateTexImage. useFenceSync specifies whether
// fences should be used to synchronize access to buffers if that behavior
// is enabled at compile-time. A custom bufferQueue can be specified
// if behavior for queue/dequeue/connect etc needs to be customized.
// Otherwise a default BufferQueue will be created and used.
//
// For legacy reasons, the SurfaceTexture is created in a state where it is
// considered attached to an OpenGL ES context for the purposes of the
// attachToContext and detachFromContext methods. However, despite being
// considered "attached" to a context, the specific OpenGL ES context
// doesn't get latched until the first call to updateTexImage. After that
// point, all calls to updateTexImage must be made with the same OpenGL ES
// context current.
//
// A SurfaceTexture may be detached from one OpenGL ES context and then
// attached to a different context using the detachFromContext and
// attachToContext methods, respectively. The intention of these methods is
// purely to allow a SurfaceTexture to be transferred from one consumer
// context to another. If such a transfer is not needed there is no
// requirement that either of these methods be called.
SurfaceTexture(GLuint tex, bool allowSynchronousMode = true,
GLenum texTarget = GL_TEXTURE_EXTERNAL_OES, bool useFenceSync = true,
const sp<BufferQueue> &bufferQueue = 0);
virtual ~SurfaceTexture();
// updateTexImage sets the image contents of the target texture to that of
// the most recently queued buffer.
//
// This call may only be made while the OpenGL ES context to which the
// target texture belongs is bound to the calling thread.
status_t updateTexImage();
// setBufferCountServer set the buffer count. If the client has requested
// a buffer count using setBufferCount, the server-buffer count will
// take effect once the client sets the count back to zero.
status_t setBufferCountServer(int bufferCount);
// getTransformMatrix retrieves the 4x4 texture coordinate transform matrix
// associated with the texture image set by the most recent call to
// updateTexImage.
//
// This transform matrix maps 2D homogeneous texture coordinates of the form
// (s, t, 0, 1) with s and t in the inclusive range [0, 1] to the texture
// coordinate that should be used to sample that location from the texture.
// Sampling the texture outside of the range of this transform is undefined.
//
// This transform is necessary to compensate for transforms that the stream
// content producer may implicitly apply to the content. By forcing users of
// a SurfaceTexture to apply this transform we avoid performing an extra
// copy of the data that would be needed to hide the transform from the
// user.
//
// The matrix is stored in column-major order so that it may be passed
// directly to OpenGL ES via the glLoadMatrixf or glUniformMatrix4fv
// functions.
void getTransformMatrix(float mtx[16]);
// getTimestamp retrieves the timestamp associated with the texture image
// set by the most recent call to updateTexImage.
//
// The timestamp is in nanoseconds, and is monotonically increasing. Its
// other semantics (zero point, etc) are source-dependent and should be
// documented by the source.
int64_t getTimestamp();
// setFrameAvailableListener sets the listener object that will be notified
// when a new frame becomes available.
void setFrameAvailableListener(const sp<FrameAvailableListener>& listener);
// getAllocator retrieves the binder object that must be referenced as long
// as the GraphicBuffers dequeued from this SurfaceTexture are referenced.
// Holding this binder reference prevents SurfaceFlinger from freeing the
// buffers before the client is done with them.
sp<IBinder> getAllocator();
// setDefaultBufferSize is used to set the size of buffers returned by
// requestBuffers when a with and height of zero is requested.
// A call to setDefaultBufferSize() may trigger requestBuffers() to
// be called from the client.
// The width and height parameters must be no greater than the minimum of
// GL_MAX_VIEWPORT_DIMS and GL_MAX_TEXTURE_SIZE (see: glGetIntegerv).
// An error due to invalid dimensions might not be reported until
// updateTexImage() is called.
status_t setDefaultBufferSize(uint32_t width, uint32_t height);
// setFilteringEnabled sets whether the transform matrix should be computed
// for use with bilinear filtering.
void setFilteringEnabled(bool enabled);
// getCurrentBuffer returns the buffer associated with the current image.
sp<GraphicBuffer> getCurrentBuffer() const;
// getCurrentTextureTarget returns the texture target of the current
// texture as returned by updateTexImage().
GLenum getCurrentTextureTarget() const;
// getCurrentCrop returns the cropping rectangle of the current buffer.
Rect getCurrentCrop() const;
// getCurrentTransform returns the transform of the current buffer.
uint32_t getCurrentTransform() const;
// getCurrentScalingMode returns the scaling mode of the current buffer.
uint32_t getCurrentScalingMode() const;
// isSynchronousMode returns whether the SurfaceTexture is currently in
// synchronous mode.
bool isSynchronousMode() const;
// abandon frees all the buffers and puts the SurfaceTexture into the
// 'abandoned' state. Once put in this state the SurfaceTexture can never
// leave it. When in the 'abandoned' state, all methods of the
// ISurfaceTexture interface will fail with the NO_INIT error.
//
// Note that while calling this method causes all the buffers to be freed
// from the perspective of the the SurfaceTexture, if there are additional
// references on the buffers (e.g. if a buffer is referenced by a client or
// by OpenGL ES as a texture) then those buffer will remain allocated.
void abandon();
// set the name of the SurfaceTexture that will be used to identify it in
// log messages.
void setName(const String8& name);
// These functions call the corresponding BufferQueue implementation
// so the refactoring can proceed smoothly
status_t setDefaultBufferFormat(uint32_t defaultFormat);
status_t setConsumerUsageBits(uint32_t usage);
status_t setTransformHint(uint32_t hint);
virtual status_t setSynchronousMode(bool enabled);
// getBufferQueue returns the BufferQueue object to which this
// SurfaceTexture is connected.
sp<BufferQueue> getBufferQueue() const;
// detachFromContext detaches the SurfaceTexture from the calling thread's
// current OpenGL ES context. This context must be the same as the context
// that was current for previous calls to updateTexImage.
//
// Detaching a SurfaceTexture from an OpenGL ES context will result in the
// deletion of the OpenGL ES texture object into which the images were being
// streamed. After a SurfaceTexture has been detached from the OpenGL ES
// context calls to updateTexImage will fail returning INVALID_OPERATION
// until the SurfaceTexture is attached to a new OpenGL ES context using the
// attachToContext method.
status_t detachFromContext();
// attachToContext attaches a SurfaceTexture that is currently in the
// 'detached' state to the current OpenGL ES context. A SurfaceTexture is
// in the 'detached' state iff detachFromContext has successfully been
// called and no calls to attachToContext have succeeded since the last
// detachFromContext call. Calls to attachToContext made on a
// SurfaceTexture that is not in the 'detached' state will result in an
// INVALID_OPERATION error.
//
// The tex argument specifies the OpenGL ES texture object name in the
// new context into which the image contents will be streamed. A successful
// call to attachToContext will result in this texture object being bound to
// the texture target and populated with the image contents that were
// current at the time of the last call to detachFromContext.
status_t attachToContext(GLuint tex);
// dump our state in a String
virtual void dump(String8& result) const;
virtual void dump(String8& result, const char* prefix, char* buffer, size_t SIZE) const;
protected:
// Implementation of the BufferQueue::ConsumerListener interface. These
// calls are used to notify the SurfaceTexture of asynchronous events in the
// BufferQueue.
virtual void onFrameAvailable();
virtual void onBuffersReleased();
static bool isExternalFormat(uint32_t format);
private:
// this version of updateTexImage() takes a functor used to reject or not
// the newly acquired buffer.
// this API is TEMPORARY and intended to be used by SurfaceFlinger only,
// which is why class Layer is made a friend of SurfaceTexture below.
class BufferRejecter {
friend class SurfaceTexture;
virtual bool reject(const sp<GraphicBuffer>& buf,
const BufferQueue::BufferItem& item) = 0;
protected:
virtual ~BufferRejecter() { }
};
friend class Layer;
status_t updateTexImage(BufferRejecter* rejecter);
// createImage creates a new EGLImage from a GraphicBuffer.
EGLImageKHR createImage(EGLDisplay dpy,
const sp<GraphicBuffer>& graphicBuffer);
// freeBufferLocked frees up the given buffer slot. If the slot has been
// initialized this will release the reference to the GraphicBuffer in that
// slot and destroy the EGLImage in that slot. Otherwise it has no effect.
//
// This method must be called with mMutex locked.
void freeBufferLocked(int slotIndex);
// computeCurrentTransformMatrix computes the transform matrix for the
// current texture. It uses mCurrentTransform and the current GraphicBuffer
// to compute this matrix and stores it in mCurrentTransformMatrix.
void computeCurrentTransformMatrix();
// syncForReleaseLocked performs the synchronization needed to release the
// current slot from an OpenGL ES context. If needed it will set the
// current slot's fence to guard against a producer accessing the buffer
// before the outstanding accesses have completed.
status_t syncForReleaseLocked(EGLDisplay dpy);
// The default consumer usage flags that SurfaceTexture always sets on its
// BufferQueue instance; these will be OR:d with any additional flags passed
// from the SurfaceTexture user. In particular, SurfaceTexture will always
// consume buffers as hardware textures.
static const uint32_t DEFAULT_USAGE_FLAGS = GraphicBuffer::USAGE_HW_TEXTURE;
// mCurrentTextureBuf is the graphic buffer of the current texture. It's
// possible that this buffer is not associated with any buffer slot, so we
// must track it separately in order to support the getCurrentBuffer method.
sp<GraphicBuffer> mCurrentTextureBuf;
// mCurrentCrop is the crop rectangle that applies to the current texture.
// It gets set each time updateTexImage is called.
Rect mCurrentCrop;
// mCurrentTransform is the transform identifier for the current texture. It
// gets set each time updateTexImage is called.
uint32_t mCurrentTransform;
// mCurrentScalingMode is the scaling mode for the current texture. It gets
// set to each time updateTexImage is called.
uint32_t mCurrentScalingMode;
// mCurrentTransformMatrix is the transform matrix for the current texture.
// It gets computed by computeTransformMatrix each time updateTexImage is
// called.
float mCurrentTransformMatrix[16];
// mCurrentTimestamp is the timestamp for the current texture. It
// gets set each time updateTexImage is called.
int64_t mCurrentTimestamp;
uint32_t mDefaultWidth, mDefaultHeight;
// mFilteringEnabled indicates whether the transform matrix is computed for
// use with bilinear filtering. It defaults to true and is changed by
// setFilteringEnabled().
bool mFilteringEnabled;
// mTexName is the name of the OpenGL texture to which streamed images will
// be bound when updateTexImage is called. It is set at construction time
// and can be changed with a call to attachToContext.
GLuint mTexName;
// mUseFenceSync indicates whether creation of the EGL_KHR_fence_sync
// extension should be used to prevent buffers from being dequeued before
// it's safe for them to be written. It gets set at construction time and
// never changes.
const bool mUseFenceSync;
// mTexTarget is the GL texture target with which the GL texture object is
// associated. It is set in the constructor and never changed. It is
// almost always GL_TEXTURE_EXTERNAL_OES except for one use case in Android
// Browser. In that case it is set to GL_TEXTURE_2D to allow
// glCopyTexSubImage to read from the texture. This is a hack to work
// around a GL driver limitation on the number of FBO attachments, which the
// browser's tile cache exceeds.
const GLenum mTexTarget;
// EGLSlot contains the information and object references that
// SurfaceTexture maintains about a BufferQueue buffer slot.
struct EGLSlot {
EGLSlot()
: mEglImage(EGL_NO_IMAGE_KHR),
mFence(EGL_NO_SYNC_KHR) {
}
sp<GraphicBuffer> mGraphicBuffer;
// mEglImage is the EGLImage created from mGraphicBuffer.
EGLImageKHR mEglImage;
// mFence is the EGL sync object that must signal before the buffer
// associated with this buffer slot may be dequeued. It is initialized
// to EGL_NO_SYNC_KHR when the buffer is created and (optionally, based
// on a compile-time option) set to a new sync object in updateTexImage.
EGLSyncKHR mFence;
};
// mEglDisplay is the EGLDisplay with which this SurfaceTexture is currently
// associated. It is intialized to EGL_NO_DISPLAY and gets set to the
// current display when updateTexImage is called for the first time and when
// attachToContext is called.
EGLDisplay mEglDisplay;
// mEglContext is the OpenGL ES context with which this SurfaceTexture is
// currently associated. It is initialized to EGL_NO_CONTEXT and gets set
// to the current GL context when updateTexImage is called for the first
// time and when attachToContext is called.
EGLContext mEglContext;
// mEGLSlots stores the buffers that have been allocated by the BufferQueue
// for each buffer slot. It is initialized to null pointers, and gets
// filled in with the result of BufferQueue::acquire when the
// client dequeues a buffer from a
// slot that has not yet been used. The buffer allocated to a slot will also
// be replaced if the requested buffer usage or geometry differs from that
// of the buffer allocated to a slot.
EGLSlot mEGLSlots[BufferQueue::NUM_BUFFER_SLOTS];
// mAbandoned indicates that the BufferQueue will no longer be used to
// consume images buffers pushed to it using the ISurfaceTexture interface.
// It is initialized to false, and set to true in the abandon method. A
// BufferQueue that has been abandoned will return the NO_INIT error from
// all ISurfaceTexture methods capable of returning an error.
bool mAbandoned;
// mName is a string used to identify the SurfaceTexture in log messages.
// It can be set by the setName method.
String8 mName;
// mFrameAvailableListener is the listener object that will be called when a
// new frame becomes available. If it is not NULL it will be called from
// queueBuffer.
sp<FrameAvailableListener> mFrameAvailableListener;
// mCurrentTexture is the buffer slot index of the buffer that is currently
// bound to the OpenGL texture. It is initialized to INVALID_BUFFER_SLOT,
// indicating that no buffer slot is currently bound to the texture. Note,
// however, that a value of INVALID_BUFFER_SLOT does not necessarily mean
// that no buffer is bound to the texture. A call to setBufferCount will
// reset mCurrentTexture to INVALID_BUFFER_SLOT.
int mCurrentTexture;
// The SurfaceTexture has-a BufferQueue and is responsible for creating this object
// if none is supplied
sp<BufferQueue> mBufferQueue;
// mAttached indicates whether the SurfaceTexture is currently attached to
// an OpenGL ES context. For legacy reasons, this is initialized to true,
// indicating that the SurfaceTexture is considered to be attached to
// whatever context is current at the time of the first updateTexImage call.
// It is set to false by detachFromContext, and then set to true again by
// attachToContext.
bool mAttached;
// mMutex is the mutex used to prevent concurrent access to the member
// variables of SurfaceTexture objects. It must be locked whenever the
// member variables are accessed.
mutable Mutex mMutex;
};
// ----------------------------------------------------------------------------
}; // namespace android
#endif // ANDROID_GUI_SURFACETEXTURE_H
| 46.581948 | 92 | 0.727755 | [
"geometry",
"object",
"vector",
"transform"
] |
2637543821cfec8b022618e18226743ecab504bf | 7,130 | h | C | sysroot/usr/include/gtk-2.0/gtk/gtksignal.h | 219-design/sysroot_qt5.15.0_binaries_armv6zk_rpizero | c3ad917b65b970c451148391ef1c2483593702ed | [
"MIT"
] | 1 | 2022-02-11T23:14:31.000Z | 2022-02-11T23:14:31.000Z | vendor/mono/osx/include/gtk-2.0/gtk/gtksignal.h | njchensl/ASQUI | 285d42a94573457dc7772a6a1d05b06ffb9a6398 | [
"MIT"
] | null | null | null | vendor/mono/osx/include/gtk-2.0/gtk/gtksignal.h | njchensl/ASQUI | 285d42a94573457dc7772a6a1d05b06ffb9a6398 | [
"MIT"
] | 1 | 2020-02-04T15:39:06.000Z | 2020-02-04T15:39:06.000Z | /* GTK - The GIMP Toolkit
* Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* 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 GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
/*
* Modified by the GTK+ Team and others 1997-2000. See the AUTHORS
* file for a list of people on the GTK+ Team. See the ChangeLog
* files for a list of changes. These files are distributed with
* GTK+ at ftp://ftp.gtk.org/pub/gtk/.
*/
#ifndef GTK_DISABLE_DEPRECATED
#ifndef __GTK_SIGNAL_H__
#define __GTK_SIGNAL_H__
#include <gtk/gtkenums.h>
#include <gtk/gtktypeutils.h>
#include <gtk/gtkobject.h>
#include <gtk/gtkmarshal.h>
G_BEGIN_DECLS
#define gtk_signal_default_marshaller g_cclosure_marshal_VOID__VOID
/* --- compat defines --- */
#define GTK_SIGNAL_OFFSET G_STRUCT_OFFSET
#define gtk_signal_lookup(name,object_type) \
g_signal_lookup ((name), (object_type))
#define gtk_signal_name(signal_id) \
g_signal_name (signal_id)
#define gtk_signal_emit_stop(object,signal_id) \
g_signal_stop_emission ((object), (signal_id), 0)
#define gtk_signal_connect(object,name,func,func_data) \
gtk_signal_connect_full ((object), (name), (func), NULL, (func_data), NULL, 0, 0)
#define gtk_signal_connect_after(object,name,func,func_data) \
gtk_signal_connect_full ((object), (name), (func), NULL, (func_data), NULL, 0, 1)
#define gtk_signal_connect_object(object,name,func,slot_object) \
gtk_signal_connect_full ((object), (name), (func), NULL, (slot_object), NULL, 1, 0)
#define gtk_signal_connect_object_after(object,name,func,slot_object) \
gtk_signal_connect_full ((object), (name), (func), NULL, (slot_object), NULL, 1, 1)
#define gtk_signal_disconnect(object,handler_id) \
g_signal_handler_disconnect ((object), (handler_id))
#define gtk_signal_handler_block(object,handler_id) \
g_signal_handler_block ((object), (handler_id))
#define gtk_signal_handler_unblock(object,handler_id) \
g_signal_handler_unblock ((object), (handler_id))
#define gtk_signal_disconnect_by_func(object,func,data) \
gtk_signal_compat_matched ((object), (func), (data), \
(GSignalMatchType)(G_SIGNAL_MATCH_FUNC | \
G_SIGNAL_MATCH_DATA), 0)
#define gtk_signal_disconnect_by_data(object,data) \
gtk_signal_compat_matched ((object), 0, (data), G_SIGNAL_MATCH_DATA, 0)
#define gtk_signal_handler_block_by_func(object,func,data) \
gtk_signal_compat_matched ((object), (func), (data), \
(GSignalMatchType)(G_SIGNAL_MATCH_FUNC | \
G_SIGNAL_MATCH_DATA), 1)
#define gtk_signal_handler_block_by_data(object,data) \
gtk_signal_compat_matched ((object), 0, (data), G_SIGNAL_MATCH_DATA, 1)
#define gtk_signal_handler_unblock_by_func(object,func,data) \
gtk_signal_compat_matched ((object), (func), (data), \
(GSignalMatchType)(G_SIGNAL_MATCH_FUNC | \
G_SIGNAL_MATCH_DATA), 2)
#define gtk_signal_handler_unblock_by_data(object,data) \
gtk_signal_compat_matched ((object), 0, (data), G_SIGNAL_MATCH_DATA, 2)
#define gtk_signal_handler_pending(object,signal_id,may_be_blocked) \
g_signal_has_handler_pending ((object), (signal_id), 0, (may_be_blocked))
#define gtk_signal_handler_pending_by_func(object,signal_id,may_be_blocked,func,data) \
(g_signal_handler_find ((object), \
(GSignalMatchType)(G_SIGNAL_MATCH_ID | \
G_SIGNAL_MATCH_FUNC | \
G_SIGNAL_MATCH_DATA | \
((may_be_blocked) ? 0 : G_SIGNAL_MATCH_UNBLOCKED)),\
(signal_id), 0, 0, (func), (data)) != 0)
/* --- compat functions --- */
guint gtk_signal_newv (const gchar *name,
GtkSignalRunType signal_flags,
GType object_type,
guint function_offset,
GSignalCMarshaller marshaller,
GType return_val,
guint n_args,
GType *args);
guint gtk_signal_new (const gchar *name,
GtkSignalRunType signal_flags,
GType object_type,
guint function_offset,
GSignalCMarshaller marshaller,
GType return_val,
guint n_args,
...);
void gtk_signal_emit_stop_by_name (GtkObject *object,
const gchar *name);
void gtk_signal_connect_object_while_alive (GtkObject *object,
const gchar *name,
GCallback func,
GtkObject *alive_object);
void gtk_signal_connect_while_alive (GtkObject *object,
const gchar *name,
GCallback func,
gpointer func_data,
GtkObject *alive_object);
gulong gtk_signal_connect_full (GtkObject *object,
const gchar *name,
GCallback func,
GtkCallbackMarshal unsupported,
gpointer data,
GDestroyNotify destroy_func,
gint object_signal,
gint after);
void gtk_signal_emitv (GtkObject *object,
guint signal_id,
GtkArg *args);
void gtk_signal_emit (GtkObject *object,
guint signal_id,
...);
void gtk_signal_emit_by_name (GtkObject *object,
const gchar *name,
...);
void gtk_signal_emitv_by_name (GtkObject *object,
const gchar *name,
GtkArg *args);
void gtk_signal_compat_matched (GtkObject *object,
GCallback func,
gpointer data,
GSignalMatchType match,
guint action);
G_END_DECLS
#endif /* __GTK_SIGNAL_H__ */
#endif /* GTK_DISABLE_DEPRECATED */
| 46.907895 | 98 | 0.595933 | [
"object"
] |
2639bc8e68452e2f7043335516bb645510043d04 | 1,985 | h | C | plugins/mmstd_datatools/src/table/TableFlagFilter.h | voei/megamol | 569b7b58c1f9bc5405b79549b86f84009329f668 | [
"BSD-3-Clause"
] | null | null | null | plugins/mmstd_datatools/src/table/TableFlagFilter.h | voei/megamol | 569b7b58c1f9bc5405b79549b86f84009329f668 | [
"BSD-3-Clause"
] | null | null | null | plugins/mmstd_datatools/src/table/TableFlagFilter.h | voei/megamol | 569b7b58c1f9bc5405b79549b86f84009329f668 | [
"BSD-3-Clause"
] | null | null | null | /*
* TableFlagFilter.h
*
* Copyright (C) 2020 by VISUS (University of Stuttgart)
* Alle Rechte vorbehalten.
*/
#ifndef MEGAMOL_DATATOOLS_FLOATTABLE_FLOATTABLEFLAGFILTER_H_INCLUDED
#define MEGAMOL_DATATOOLS_FLOATTABLE_FLOATTABLEFLAGFILTER_H_INCLUDED
#include "mmcore/Module.h"
#include "mmcore/CalleeSlot.h"
#include "mmcore/CallerSlot.h"
#include "mmcore/FlagCall_GL.h"
#include "mmcore/param/ParamSlot.h"
#include "mmstd_datatools/table/TableDataCall.h"
namespace megamol {
namespace stdplugin {
namespace datatools {
namespace table {
/*
* Module to filter rows from a table based on a flag storage.
*/
class TableFlagFilter : public core::Module {
public:
/** Return module class name */
static const char* ClassName() { return "TableFlagFilter"; }
/** Return module class description */
static const char* Description() { return "Filters rows from a table based on a flag storage."; }
/** Module is always available */
static bool IsAvailable() { return true; }
/** Ctor */
TableFlagFilter();
/** Dtor */
~TableFlagFilter() override;
protected:
bool create() override;
void release() override;
bool getData(core::Call &call);
bool getHash(core::Call &call);
bool handleCall(core::Call &call);
private:
enum FilterMode {
FILTERED = 0,
SELECTED = 1
};
core::CallerSlot tableInSlot;
core::CallerSlot flagStorageInSlot;
core::CalleeSlot tableOutSlot;
core::param::ParamSlot filterModeParam;
// input table properties
unsigned int tableInFrameCount;
size_t tableInDataHash;
size_t tableInColCount;
// filtered table
size_t dataHash;
size_t rowCount;
std::vector<TableDataCall::ColumnInfo> colInfos;
std::vector<float> data;
};
} /* end namespace table */
} /* end namespace datatools */
} /* end namespace stdplugin */
} /* end namespace megamol */
#endif /* MEGAMOL_DATATOOLS_FLOATTABLE_FLOATTABLEFLAGFILTER_H_INCLUDED */
| 23.630952 | 101 | 0.704282 | [
"vector"
] |
263e2b0436fdb50dec907ed4d7b0080282b824ed | 398 | h | C | src/turn_cluster_distance.h | sammiya/poker-hand-clustering | 2a302242f977d35b1adf0087fbe0cc958a194dda | [
"MIT"
] | 6 | 2020-02-09T11:13:58.000Z | 2021-09-04T02:43:52.000Z | src/turn_cluster_distance.h | sammiya/poker-hand-clustering | 2a302242f977d35b1adf0087fbe0cc958a194dda | [
"MIT"
] | 2 | 2021-01-13T17:52:51.000Z | 2021-01-26T15:56:54.000Z | src/turn_cluster_distance.h | sammiya/poker-hand-clustering | 2a302242f977d35b1adf0087fbe0cc958a194dda | [
"MIT"
] | 1 | 2020-12-23T07:31:28.000Z | 2020-12-23T07:31:28.000Z | #ifndef POKER_HAND_CLUSTERING_TURN_CLUSTER_DISTANCE_H_
#define POKER_HAND_CLUSTERING_TURN_CLUSTER_DISTANCE_H_
#include <inttypes.h>
#include <vector>
namespace poker {
std::vector<std::vector<double>> turn_cluster_distance(
const std::vector<std::vector<int32_t>>& turn_histograms,
const std::vector<size_t>& turn_clustering);
}
#endif // POKER_HAND_CLUSTERING_TURN_CLUSTER_DISTANCE_H_
| 28.428571 | 61 | 0.811558 | [
"vector"
] |
2649e8847de4a8e78885338456e72a9da3cb6ee7 | 2,419 | h | C | src/libxively/xi_types.h | Rhunter1/xively-client-c | bbb0a472c7b2f592c8d167eedf46221626f881df | [
"BSD-3-Clause"
] | null | null | null | src/libxively/xi_types.h | Rhunter1/xively-client-c | bbb0a472c7b2f592c8d167eedf46221626f881df | [
"BSD-3-Clause"
] | null | null | null | src/libxively/xi_types.h | Rhunter1/xively-client-c | bbb0a472c7b2f592c8d167eedf46221626f881df | [
"BSD-3-Clause"
] | 2 | 2019-09-18T11:26:52.000Z | 2019-10-25T19:27:31.000Z | /* Copyright (c) 2003-2018, Xively All rights reserved.
*
* This is part of the Xively C Client library,
* it is licensed under the BSD 3-Clause license.
*/
#ifndef __XI_TYPES_H__
#define __XI_TYPES_H__
#include "xi_layer_chain.h"
#include "xi_connection_data.h"
#include "xi_vector.h"
#include "xi_event_dispatcher_api.h"
#include <xively_types.h>
#ifdef __cplusplus
extern "C" {
#endif
/* -----------------------------------------------------------------------
* TYPES AND STRUCTURES
* ----------------------------------------------------------------------- */
typedef enum xi_protocol_e {
XI_MQTT,
} xi_protocol_t;
typedef enum xi_shutdown_state_e {
XI_SHUTDOWN_UNINITIALISED,
XI_SHUTDOWN_STARTED,
} xi_shutdown_state_t;
/**
* @brief holds context sensitive data
*
*
**/
typedef struct xi_context_data_s
{
/* atm this switch contains only the MQTT data
* but it may happen that we will add more protocols
* so the idea is to keep each protocol part here and make
* it enable/disable via some flags or defines so for now
* let's use that simplified form */
#if 1 /* MQTT context part */
xi_vector_t* copy_of_handlers_for_topics;
void* copy_of_q12_unacked_messages_queue; /* we have to use void* cause we don't want
to
create mqtt logic layer dependency */
void ( *copy_of_q12_unacked_messages_queue_dtor_ptr )(
void** ); /* this is dstr for unacked messages, just a very simplified
solution to the problem of not binding xively interface with
layers directly */
uint16_t copy_of_last_msg_id; /* value of the msg_id for continious session */
#endif
/* this is the common part */
xi_time_event_handle_t connect_handler;
/* vector or a list of timeouts */
xi_vector_t* io_timeouts;
xi_connection_data_t* connection_data;
xi_evtd_instance_t* evtd_instance;
xi_event_handle_t connection_callback;
xi_shutdown_state_t shutdown_state;
char** updateable_files;
uint16_t updateable_files_count;
xi_sft_url_handler_callback_t* sft_url_handler_callback;
} xi_context_data_t;
typedef struct xi_context_s
{
xi_protocol_t protocol;
xi_layer_chain_t layer_chain;
xi_context_data_t context_data;
} xi_context_t;
#ifdef __cplusplus
}
#endif
#endif /* __XI_TYPES_H__ */
| 29.5 | 89 | 0.660604 | [
"vector"
] |
26574568f56c7e02f6d624d805276b684365defb | 740 | h | C | OPHD/UI/Core/CheckBox.h | belgianguy/OPHD | d59009d63b6f10fc9a95c36c392d72509e52a21c | [
"BSD-3-Clause"
] | null | null | null | OPHD/UI/Core/CheckBox.h | belgianguy/OPHD | d59009d63b6f10fc9a95c36c392d72509e52a21c | [
"BSD-3-Clause"
] | null | null | null | OPHD/UI/Core/CheckBox.h | belgianguy/OPHD | d59009d63b6f10fc9a95c36c392d72509e52a21c | [
"BSD-3-Clause"
] | null | null | null | #pragma once
#include "TextControl.h"
#include <NAS2D/Signal.h>
#include <NAS2D/EventHandler.h>
#include <NAS2D/Resources/Image.h>
#include <string>
class CheckBox : public TextControl
{
public:
using ClickCallback = NAS2D::Signals::Signal<>;
CheckBox(std::string newText = "");
~CheckBox() override;
void checked(bool toggle);
bool checked() const;
ClickCallback& click();
void update() override;
protected:
void onMouseDown(NAS2D::EventHandler::MouseButton button, int x, int y);
void onSizeChanged() override;
void onTextChanged() override;
private:
const NAS2D::Font& mFont;
const NAS2D::Image& mSkin;
ClickCallback mCallback; /**< Object to notify when the Button is activated. */
bool mChecked = false;
};
| 18.04878 | 80 | 0.725676 | [
"object"
] |
2657f335a0d2d3ce7446b91d6b8e1bd3750f01f5 | 11,055 | h | C | libraries/input-plugins/src/input-plugins/UserInputMapper.h | thoys/hifi | a42bb5f53373f0c4ba7eee2de912d8fed522b46a | [
"Apache-2.0"
] | null | null | null | libraries/input-plugins/src/input-plugins/UserInputMapper.h | thoys/hifi | a42bb5f53373f0c4ba7eee2de912d8fed522b46a | [
"Apache-2.0"
] | 1 | 2015-09-25T19:11:03.000Z | 2015-09-25T22:04:36.000Z | libraries/input-plugins/src/input-plugins/UserInputMapper.h | thoys/hifi | a42bb5f53373f0c4ba7eee2de912d8fed522b46a | [
"Apache-2.0"
] | null | null | null | //
// UserInputMapper.h
// input-plugins/src/input-plugins
//
// Created by Sam Gateau on 4/27/15.
// Copyright 2015 High Fidelity, Inc.
//
// Distributed under the Apache License, Version 2.0.
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
//
#ifndef hifi_UserInputMapper_h
#define hifi_UserInputMapper_h
#include <glm/glm.hpp>
#include <unordered_set>
#include <functional>
#include <memory>
#include <DependencyManager.h>
#include <RegisteredMetaTypes.h>
class UserInputMapper : public QObject, public Dependency {
Q_OBJECT
SINGLETON_DEPENDENCY
Q_ENUMS(Action)
public:
typedef unsigned short uint16;
typedef unsigned int uint32;
enum class ChannelType {
UNKNOWN = 0,
BUTTON = 1,
AXIS,
POSE,
};
// Input is the unique identifier to find a n input channel of a particular device
// Devices are responsible for registering to the UseInputMapper so their input channels can be sued and mapped
// to the Action channels
class Input {
public:
union {
struct {
uint16 _device; // Up to 64K possible devices
uint16 _channel : 14; // 2^14 possible channel per Device
uint16 _type : 2; // 2 bits to store the Type directly in the ID
};
uint32 _id = 0; // by default Input is 0 meaning invalid
};
bool isValid() const { return (_id != 0); }
uint16 getDevice() const { return _device; }
uint16 getChannel() const { return _channel; }
uint32 getID() const { return _id; }
ChannelType getType() const { return (ChannelType) _type; }
void setDevice(uint16 device) { _device = device; }
void setChannel(uint16 channel) { _channel = channel; }
void setType(uint16 type) { _type = type; }
void setID(uint32 ID) { _id = ID; }
bool isButton() const { return getType() == ChannelType::BUTTON; }
bool isAxis() const { return getType() == ChannelType::AXIS; }
bool isPose() const { return getType() == ChannelType::POSE; }
// WORKAROUND: the explicit initializer here avoids a bug in GCC-4.8.2 (but not found in 4.9.2)
// where the default initializer (a C++-11ism) for the union data above is not applied.
explicit Input() : _id(0) {}
explicit Input(uint32 id) : _id(id) {}
explicit Input(uint16 device, uint16 channel, ChannelType type) : _device(device), _channel(channel), _type(uint16(type)) {}
Input(const Input& src) : _id(src._id) {}
Input& operator = (const Input& src) { _id = src._id; return (*this); }
bool operator ==(const Input& right) const { return _id == right._id; }
bool operator < (const Input& src) const { return _id < src._id; }
};
// Modifiers are just button inputID
typedef std::vector< Input > Modifiers;
class PoseValue {
public:
glm::vec3 _translation{ 0.0f };
glm::quat _rotation;
bool _valid;
PoseValue() : _valid(false) {};
PoseValue(glm::vec3 translation, glm::quat rotation) : _translation(translation), _rotation(rotation), _valid(true) {}
PoseValue(const PoseValue&) = default;
PoseValue& operator = (const PoseValue&) = default;
bool operator ==(const PoseValue& right) const { return _translation == right.getTranslation() && _rotation == right.getRotation() && _valid == right.isValid(); }
bool isValid() const { return _valid; }
glm::vec3 getTranslation() const { return _translation; }
glm::quat getRotation() const { return _rotation; }
};
typedef std::function<bool (const Input& input, int timestamp)> ButtonGetter;
typedef std::function<float (const Input& input, int timestamp)> AxisGetter;
typedef std::function<PoseValue (const Input& input, int timestamp)> PoseGetter;
typedef QPair<Input, QString> InputPair;
typedef std::function<QVector<InputPair> ()> AvailableInputGetter;
typedef std::function<bool ()> ResetBindings;
typedef QVector<InputPair> AvailableInput;
class DeviceProxy {
public:
DeviceProxy(QString name) { _name = name; }
QString _name;
ButtonGetter getButton = [] (const Input& input, int timestamp) -> bool { return false; };
AxisGetter getAxis = [] (const Input& input, int timestamp) -> float { return 0.0f; };
PoseGetter getPose = [] (const Input& input, int timestamp) -> PoseValue { return PoseValue(); };
AvailableInputGetter getAvailabeInputs = [] () -> AvailableInput { return QVector<InputPair>(); };
ResetBindings resetDeviceBindings = [] () -> bool { return true; };
typedef std::shared_ptr<DeviceProxy> Pointer;
};
// GetFreeDeviceID should be called before registering a device to use an ID not used by a different device.
uint16 getFreeDeviceID() { return _nextFreeDeviceID++; }
bool registerDevice(uint16 deviceID, const DeviceProxy::Pointer& device);
DeviceProxy::Pointer getDeviceProxy(const Input& input);
QString getDeviceName(uint16 deviceID);
QVector<InputPair> getAvailableInputs(uint16 deviceID) { return _registeredDevices[deviceID]->getAvailabeInputs(); }
void resetAllDeviceBindings();
void resetDevice(uint16 deviceID);
int findDevice(QString name);
QVector<QString> getDeviceNames();
// Actions are the output channels of the Mapper, that's what the InputChannel map to
// For now the Actions are hardcoded, this is bad, but we will fix that in the near future
enum Action {
LONGITUDINAL_BACKWARD = 0,
LONGITUDINAL_FORWARD,
LATERAL_LEFT,
LATERAL_RIGHT,
VERTICAL_DOWN,
VERTICAL_UP,
YAW_LEFT,
YAW_RIGHT,
PITCH_DOWN,
PITCH_UP,
BOOM_IN,
BOOM_OUT,
LEFT_HAND,
RIGHT_HAND,
LEFT_HAND_CLICK,
RIGHT_HAND_CLICK,
SHIFT,
ACTION1,
ACTION2,
CONTEXT_MENU,
TOGGLE_MUTE,
NUM_ACTIONS,
};
std::vector<QString> _actionNames = std::vector<QString>(NUM_ACTIONS);
void createActionNames();
QVector<Action> getAllActions() const;
QString getActionName(Action action) const { return UserInputMapper::_actionNames[(int) action]; }
float getActionState(Action action) const { return _actionStates[action]; }
PoseValue getPoseState(Action action) const { return _poseStates[action]; }
int findAction(const QString& actionName) const;
QVector<QString> getActionNames() const;
void assignDefaulActionScales();
// Add input channel to the mapper and check that all the used channels are registered.
// Return true if theinput channel is created correctly, false either
bool addInputChannel(Action action, const Input& input, float scale = 1.0f);
bool addInputChannel(Action action, const Input& input, const Input& modifer, float scale = 1.0f);
// Under the hood, the input channels are organized in map sorted on the _output
// The InputChannel class is just the full values describing the input channel in one object
class InputChannel {
public:
Input _input;
Input _modifier = Input(); // make it invalid by default, meaning no modifier
Action _action = LONGITUDINAL_BACKWARD;
float _scale = 0.0f;
Input getInput() const { return _input; }
Input getModifier() const { return _modifier; }
Action getAction() const { return _action; }
float getScale() const { return _scale; }
void setInput(Input input) { _input = input; }
void setModifier(Input modifier) { _modifier = modifier; }
void setAction(Action action) { _action = action; }
void setScale(float scale) { _scale = scale; }
InputChannel() {}
InputChannel(const Input& input, const Input& modifier, Action action, float scale = 1.0f) :
_input(input), _modifier(modifier), _action(action), _scale(scale) {}
InputChannel(const InputChannel& src) : InputChannel(src._input, src._modifier, src._action, src._scale) {}
InputChannel& operator = (const InputChannel& src) { _input = src._input; _modifier = src._modifier; _action = src._action; _scale = src._scale; return (*this); }
bool operator ==(const InputChannel& right) const { return _input == right._input && _modifier == right._modifier && _action == right._action && _scale == right._scale; }
bool hasModifier() { return _modifier.isValid(); }
};
typedef std::vector< InputChannel > InputChannels;
// Add a bunch of input channels, return the true number of channels that successfully were added
int addInputChannels(const InputChannels& channels);
// Remove the first found instance of the input channel from the input mapper, true if found
bool removeInputChannel(InputChannel channel);
void removeAllInputChannels();
void removeAllInputChannelsForDevice(uint16 device);
void removeDevice(int device);
//Grab all the input channels currently in use, return the number
int getInputChannels(InputChannels& channels) const;
QVector<InputChannel> getAllInputsForDevice(uint16 device);
QVector<InputChannel> getInputChannelsForAction(UserInputMapper::Action action);
std::multimap<Action, InputChannel> getActionToInputsMap() { return _actionToInputsMap; }
// Update means go grab all the device input channels and update the output channel values
void update(float deltaTime);
void setSensorToWorldMat(glm::mat4 sensorToWorldMat) { _sensorToWorldMat = sensorToWorldMat; }
glm::mat4 getSensorToWorldMat() { return _sensorToWorldMat; }
UserInputMapper();
signals:
void actionEvent(int action, float state);
protected:
typedef std::map<int, DeviceProxy::Pointer> DevicesMap;
DevicesMap _registeredDevices;
uint16 _nextFreeDeviceID = 1;
typedef std::map<int, Modifiers> InputToMoModifiersMap;
InputToMoModifiersMap _inputToModifiersMap;
typedef std::multimap<Action, InputChannel> ActionToInputsMap;
ActionToInputsMap _actionToInputsMap;
std::vector<float> _actionStates = std::vector<float>(NUM_ACTIONS, 0.0f);
std::vector<float> _actionScales = std::vector<float>(NUM_ACTIONS, 1.0f);
std::vector<float> _lastActionStates = std::vector<float>(NUM_ACTIONS, 0.0f);
std::vector<PoseValue> _poseStates = std::vector<PoseValue>(NUM_ACTIONS);
glm::mat4 _sensorToWorldMat;
};
Q_DECLARE_METATYPE(UserInputMapper::InputPair)
Q_DECLARE_METATYPE(QVector<UserInputMapper::InputPair>)
Q_DECLARE_METATYPE(UserInputMapper::Input)
Q_DECLARE_METATYPE(UserInputMapper::InputChannel)
Q_DECLARE_METATYPE(QVector<UserInputMapper::InputChannel>)
Q_DECLARE_METATYPE(UserInputMapper::Action)
Q_DECLARE_METATYPE(QVector<UserInputMapper::Action>)
#endif // hifi_UserInputMapper_h
| 41.096654 | 178 | 0.678155 | [
"object",
"vector"
] |
2660643bd3e4aec47c283834558969466a7d6535 | 603 | h | C | OpenGL/Mesh.h | CyberPlaton/OpenGL | 79afbb1356a2bdebfa4b3f11197c6fe7dd568a19 | [
"MIT"
] | null | null | null | OpenGL/Mesh.h | CyberPlaton/OpenGL | 79afbb1356a2bdebfa4b3f11197c6fe7dd568a19 | [
"MIT"
] | null | null | null | OpenGL/Mesh.h | CyberPlaton/OpenGL | 79afbb1356a2bdebfa4b3f11197c6fe7dd568a19 | [
"MIT"
] | null | null | null | #pragma once
#include<vector>
#include<string>
#include<GL/glew.h>
#include<glm/glm.hpp>
#include"ColorConsole.h"
struct Vertex {
glm::vec3 position;
glm::vec3 normal;
glm::vec2 texCoords;
};
class Mesh{
public:
Mesh();
~Mesh();
bool LoadOBJ(const std::string& fileName);
void DrawMesh();
//void SetTexture(const std::string& fileName);
//Texture2D* GetTexture();
private:
bool m_IsLoaded = false;
std::vector<Vertex> m_Vertices;
GLuint m_VBO, m_VAO; // Vertexarray objet and vertexbuffer object.
//Texture2D* m_MeshTexture = nullptr;
private:
void _initBuffers();
};
| 12.5625 | 67 | 0.698176 | [
"mesh",
"object",
"vector"
] |
266f4d626428f7db4b7d38d4d321cf742cf7132b | 962 | h | C | src/simulation/Simulation/src/graphics/VertexArray.h | ncl-ROVers/surface-2019-20 | 209c06008803971d0430fd3993ef36f9a4686646 | [
"MIT"
] | 3 | 2021-01-21T07:18:30.000Z | 2021-12-20T11:09:29.000Z | src/simulation/Simulation/src/graphics/VertexArray.h | ncl-ROVers/surface-2019-20 | 209c06008803971d0430fd3993ef36f9a4686646 | [
"MIT"
] | null | null | null | src/simulation/Simulation/src/graphics/VertexArray.h | ncl-ROVers/surface-2019-20 | 209c06008803971d0430fd3993ef36f9a4686646 | [
"MIT"
] | 3 | 2020-11-24T11:46:23.000Z | 2021-08-05T18:02:07.000Z | #pragma once
#include "Common.h"
#include <vector>
class VertexArray
{
private:
GLuint m_vertexArray;
std::vector<std::pair<GLuint, GLuint>> m_buffers;
public:
VertexArray() {}
void init();
size_t createBuffer(GLenum type, void* data, size_t size);
void bindAttribute(size_t bufferIndex, GLuint attribIndex, GLint componentCount, GLenum type, bool normalized, GLsizei stride, size_t offset);
inline GLuint getBufferId(size_t index) const
{
return (index >= m_buffers.size()) ? 0 : m_buffers[index].second;
}
inline GLenum getBufferType(size_t index) const
{
return (index >= m_buffers.size()) ? 0 : m_buffers[index].first;
}
inline void bind() const { glBindVertexArray(m_vertexArray); }
inline void bindBuffer(size_t index) const { glBindBuffer(getBufferType(index), getBufferId(index)); }
inline void unbindBuffer(GLenum type) const { glBindBuffer(type, 0); }
inline void unbind() const { glBindVertexArray(0); }
void destroy();
}; | 27.485714 | 143 | 0.738046 | [
"vector"
] |
26707802619a337cdff252c2ad6b15296dd749e3 | 66,276 | c | C | src/lib/encoding/dns_wireformat.c | chrisss404/tor | d6e288d8ace62e2fa9718db457086d4dc42837e6 | [
"BSD-2-Clause-NetBSD"
] | null | null | null | src/lib/encoding/dns_wireformat.c | chrisss404/tor | d6e288d8ace62e2fa9718db457086d4dc42837e6 | [
"BSD-2-Clause-NetBSD"
] | null | null | null | src/lib/encoding/dns_wireformat.c | chrisss404/tor | d6e288d8ace62e2fa9718db457086d4dc42837e6 | [
"BSD-2-Clause-NetBSD"
] | null | null | null | /* Copyright (c) 2019 Christian Hofer.
* Copyright (c) 2019-2020, The Tor Project, Inc. */
/* See LICENSE for licensing information */
/**
* \file dns_wireformat.c
* \brief Encode DNS messages to wire-format and decode DNS messages from
* wire-format.
**/
#define DNS_WIREFORMAT_PRIVATE
#include "lib/encoding/dns_wireformat.h"
#include "lib/buf/buffers.h"
#include "lib/container/dns_message.h"
#include "lib/container/dns_message_st.h"
#include "lib/container/smartlist.h"
#include "lib/defs/dns_types.h"
#include "lib/encoding/binascii.h"
#include "lib/encoding/dns_string.h"
#include "lib/log/log.h"
#include "lib/log/util_bug.h"
#include "lib/malloc/malloc.h"
#include "lib/net/inaddr.h"
#include "lib/string/util_string.h"
#ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h>
#endif
#include <string.h>
#ifdef _WIN32
#include <winsock2.h>
#include <ws2tcpip.h>
#endif
//
// Header
/** Pack the given header <b>dh</b> to wire-format. */
int
dns_pack_header(buf_t *buf, const dns_header_t *dh)
{
// LCOV_EXCL_START
tor_assert(buf);
tor_assert(dh);
// LCOV_EXCL_STOP
char *res = NULL;
size_t res_len = 0;
log_debug(LD_GENERAL, "pack: %s", dns_header_str(dh));
struct dns_header_wireformat_s wire;
wire.id = htons(dh->id);
wire.qr = dh->qr ? 1 : 0;
wire.opcode = dh->opcode;
wire.aa = dh->aa ? 1 : 0;
wire.tc = dh->tc ? 1 : 0;
wire.rd = dh->rd ? 1 : 0;
wire.ra = dh->ra ? 1 : 0;
wire.z = dh->z ? 1 : 0;
wire.ad = dh->ad ? 1 : 0;
wire.cd = dh->cd ? 1 : 0;
wire.rcode = dh->rcode;
wire.qdcount = htons(dh->qdcount);
wire.ancount = htons(dh->ancount);
wire.nscount = htons(dh->nscount);
wire.arcount = htons(dh->arcount);
res = (char *) &wire;
res_len = sizeof(struct dns_header_wireformat_s);
buf_add(buf, (const char *) res, res_len);
log_debug(LD_GENERAL, "packed (%d): %s", (int) res_len,
hex_str((const char *) res, res_len));
return (int) res_len;
}
/** Consume wire-format data and interpret it as header. */
int
dns_consume_header(dns_header_t *dh, uint8_t **ptr, const uint8_t *data,
const size_t size)
{
// LCOV_EXCL_START
tor_assert(dh);
tor_assert(ptr);
tor_assert(data);
// LCOV_EXCL_STOP
size_t pos = (*ptr - data);
int consumed = 0;
if (pos > size) {
log_debug(LD_GENERAL, "no data left");
return -1;
}
log_debug(LD_GENERAL, "consume: %s", hex_str((const char *) *ptr,
size - pos));
size_t header_len = sizeof(struct dns_header_wireformat_s);
if (header_len > size - pos) {
log_debug(LD_GENERAL, "invalid length: wanted %d, got %d",
(int) header_len, (int) (size - pos));
return -2;
}
struct dns_header_wireformat_s *wire =
(struct dns_header_wireformat_s *) *ptr;
consumed += header_len;
*ptr += header_len;
dh->id = ntohs(wire->id);
dh->qr = wire->qr == 1 ? true : false;
dh->opcode = wire->opcode;
dh->aa = wire->aa == 1 ? true : false;
dh->tc = wire->tc == 1 ? true : false;
dh->rd = wire->rd == 1 ? true : false;
dh->ra = wire->ra == 1 ? true : false;
dh->z = wire->z == 1 ? true : false;
dh->ad = wire->ad == 1 ? true : false;
dh->cd = wire->cd == 1 ? true : false;
dh->rcode = wire->rcode;
dh->qdcount = ntohs(wire->qdcount);
dh->ancount = ntohs(wire->ancount);
dh->nscount = ntohs(wire->nscount);
dh->arcount = ntohs(wire->arcount);
log_debug(LD_GENERAL, "consumed (%d):\n%s", consumed, dns_header_str(dh));
return consumed;
}
//
// Question
/** Pack the given question <b>dq</b> to wire-format. */
int
dns_pack_question(buf_t *buf, const dns_question_t *dq)
{
// LCOV_EXCL_START
tor_assert(buf);
tor_assert(dq);
// LCOV_EXCL_STOP
buf_t *stash = buf_new();
char *res = NULL;
size_t res_len = 0;
if (!dq->qtype) {
log_debug(LD_GENERAL, "missing question type");
res_len = -1;
goto cleanup;
}
log_debug(LD_GENERAL, "pack: %s", dns_question_str(dq));
if (dns_pack_name(stash, dq->qname) < 0) {
log_debug(LD_GENERAL, "failed packing name");
res_len = -2;
goto cleanup;
}
struct dns_question_wireformat_s wire;
wire.qtype = htons(dq->qtype->value);
wire.qclass = htons(dq->qclass);
buf_add(stash, (const char *)&wire,
sizeof(struct dns_question_wireformat_s));
res = buf_extract(stash, &res_len);
buf_add(buf, (const char *) res, res_len);
log_debug(LD_GENERAL, "packed (%d): %s", (int) res_len,
hex_str((const char *) res, res_len));
cleanup:
buf_free(stash);
tor_free(res);
return (int) res_len;
}
/** Consume wire-format data and interpret it as question. */
int
dns_consume_question(dns_question_t *dq, uint8_t **ptr, const uint8_t *data,
const size_t size)
{
// LCOV_EXCL_START
tor_assert(dq);
tor_assert(ptr);
tor_assert(data);
// LCOV_EXCL_STOP
size_t pos = (*ptr - data);
int consumed = 0;
if (pos > size) {
log_debug(LD_GENERAL, "no data left");
return -1;
}
log_debug(LD_GENERAL, "consume: %s", hex_str((const char *) *ptr,
size - pos));
dns_name_free(dq->qname);
dq->qname = dns_name_new();
consumed = dns_consume_name(dq->qname, ptr, data, size);
if (consumed < 0) {
log_debug(LD_GENERAL, "failed consuming name");
return -2;
}
pos = (*ptr - data);
size_t question_len = sizeof(struct dns_question_wireformat_s);
if (question_len > size - pos) {
log_debug(LD_GENERAL, "invalid length: wanted %d, got %d",
(int) question_len, (int) (size - pos));
return -3;
}
struct dns_question_wireformat_s *wire =
(struct dns_question_wireformat_s *) *ptr;
consumed += question_len;
*ptr += question_len;
dq->qtype = dns_type_of(ntohs(wire->qtype));
dq->qclass = ntohs(wire->qclass);
log_debug(LD_GENERAL, "consumed (%d): %s", consumed, dns_question_str(dq));
return consumed;
}
//
// Resource Record - A
/** Encode the given A record in <b>drr</b> to wire-format. */
int
dns_encode_a(dns_rr_t *drr)
{
// LCOV_EXCL_START
tor_assert(drr);
// LCOV_EXCL_STOP
if (!drr->a) {
log_debug(LD_GENERAL, "missing rdata");
return -1;
}
log_debug(LD_GENERAL, "encode: %s", dns_a_str(drr->a));
struct sockaddr_in addr;
if (!tor_inet_pton(AF_INET, drr->a, &addr.sin_addr)) {
log_debug(LD_GENERAL, "inet_ntop conversion error");
return -2;
}
tor_free(drr->rdata);
drr->rdlength = sizeof(addr.sin_addr.s_addr);
drr->rdata = tor_memdup((const char *) &addr.sin_addr.s_addr, drr->rdlength);
log_debug(LD_GENERAL, "encoded: %s", hex_str((const char *) drr->rdata,
drr->rdlength));
return 0;
}
/** Decode wire-format data and interpret it as A record. */
int
dns_decode_a(dns_rr_t *drr, uint8_t *ptr, const uint8_t *data,
const size_t size)
{
// LCOV_EXCL_START
tor_assert(drr);
tor_assert(ptr);
tor_assert(data);
// LCOV_EXCL_STOP
size_t pos = (ptr - data);
if (pos > size) {
log_debug(LD_GENERAL, "no data left");
return -1;
}
log_debug(LD_GENERAL, "decode: %s", hex_str((const char *) ptr, size - pos));
struct sockaddr_in addr;
size_t a_len = sizeof(addr.sin_addr.s_addr);
if (a_len > size - pos) {
log_debug(LD_GENERAL, "invalid length: wanted %d, got %d", (int) a_len,
(int) (size - pos));
return -2;
}
memcpy(&addr.sin_addr.s_addr, ptr, a_len);
char address[INET_ADDRSTRLEN];
tor_inet_ntop(AF_INET, &addr.sin_addr, address, INET_ADDRSTRLEN);
tor_free(drr->a);
drr->a = tor_strdup(address);
log_debug(LD_GENERAL, "decoded: %s", dns_a_str(drr->a));
return 0;
}
//
// Resource Record - NS
/** Encode the given NS record in <b>drr</b> to wire-format. */
int
dns_encode_ns(dns_rr_t *drr)
{
// LCOV_EXCL_START
tor_assert(drr);
// LCOV_EXCL_STOP
buf_t *stash = buf_new();
int ret = 0;
if (!drr->ns) {
log_debug(LD_GENERAL, "missing rdata");
ret = -1;
goto cleanup;
}
log_debug(LD_GENERAL, "encode: %s", dns_ns_str(drr->ns));
if (dns_pack_name(stash, drr->ns) < 0) {
log_debug(LD_GENERAL, "failed packing name");
ret = -2;
goto cleanup;
}
size_t sz_out = 0;
tor_free(drr->rdata);
drr->rdata = (uint8_t *) buf_extract(stash, &sz_out);
drr->rdlength = (uint16_t) sz_out;
log_debug(LD_GENERAL, "encoded: %s",
hex_str((const char *) drr->rdata, drr->rdlength));
cleanup:
buf_free(stash);
return ret;
}
/** Decode wire-format data and interpret it as NS record. */
int
dns_decode_ns(dns_rr_t *drr, uint8_t *ptr, const uint8_t *data,
const size_t size)
{
// LCOV_EXCL_START
tor_assert(drr);
tor_assert(ptr);
tor_assert(data);
// LCOV_EXCL_STOP
size_t pos = (ptr - data);
if (pos > size) {
log_debug(LD_GENERAL, "no data left");
return -1;
}
log_debug(LD_GENERAL, "decode: %s", hex_str((const char *) ptr, size - pos));
dns_name_free(drr->ns);
drr->ns = dns_name_new();
if (dns_consume_name(drr->ns, &ptr, data, size) < 0) {
log_debug(LD_GENERAL, "failed consuming name");
return -2;
}
log_debug(LD_GENERAL, "decoded: %s", dns_ns_str(drr->ns));
return 0;
}
//
// Resource Record - CNAME
/** Encode the given CNAME record in <b>drr</b> to wire-format. */
int
dns_encode_cname(dns_rr_t *drr)
{
// LCOV_EXCL_START
tor_assert(drr);
// LCOV_EXCL_STOP
buf_t *stash = buf_new();
int ret = 0;
if (!drr->cname) {
log_debug(LD_GENERAL, "missing rdata");
ret = -1;
goto cleanup;
}
log_debug(LD_GENERAL, "encode: %s", dns_cname_str(drr->cname));
if (dns_pack_name(stash, drr->cname) < 0) {
log_debug(LD_GENERAL, "failed packing name");
ret = -2;
goto cleanup;
}
size_t sz_out = 0;
tor_free(drr->rdata);
drr->rdata = (uint8_t *) buf_extract(stash, &sz_out);
drr->rdlength = (uint16_t) sz_out;
log_debug(LD_GENERAL, "encoded: %s",
hex_str((const char *) drr->rdata, drr->rdlength));
cleanup:
buf_free(stash);
return ret;
}
/** Decode wire-format data and interpret it as CNAME record. */
int
dns_decode_cname(dns_rr_t *drr, uint8_t *ptr, const uint8_t *data,
const size_t size)
{
// LCOV_EXCL_START
tor_assert(drr);
tor_assert(ptr);
tor_assert(data);
// LCOV_EXCL_STOP
size_t pos = (ptr - data);
if (pos > size) {
log_debug(LD_GENERAL, "no data left");
return -1;
}
log_debug(LD_GENERAL, "decode: %s", hex_str((const char *) ptr, size - pos));
dns_name_free(drr->cname);
drr->cname = dns_name_new();
if (dns_consume_name(drr->cname, &ptr, data, size) < 0) {
log_debug(LD_GENERAL, "failed consuming name");
return -2;
}
log_debug(LD_GENERAL, "decoded: %s", dns_cname_str(drr->cname));
return 0;
}
//
// Resource Record - SOA
/** Encode the given SOA record in <b>drr</b> to wire-format. */
int
dns_encode_soa(dns_rr_t *drr)
{
// LCOV_EXCL_START
tor_assert(drr);
// LCOV_EXCL_STOP
buf_t *stash = buf_new();
int ret = 0;
if (!drr->soa) {
log_debug(LD_GENERAL, "missing rdata");
ret = -1;
goto cleanup;
}
log_debug(LD_GENERAL, "encode: %s", dns_soa_str(drr->soa));
if (dns_pack_name(stash, drr->soa->mname) < 0) {
log_debug(LD_GENERAL, "failed packing mname");
ret = -2;
goto cleanup;
}
if (dns_pack_name(stash, drr->soa->rname) < 0) {
log_debug(LD_GENERAL, "failed packing rname");
ret = -3;
goto cleanup;
}
struct dns_soa_wireformat_s wire;
wire.serial = htonl(drr->soa->serial);
wire.refresh = htonl(drr->soa->refresh);
wire.retry = htonl(drr->soa->retry);
wire.expire = htonl(drr->soa->expire);
wire.minimum = htonl(drr->soa->minimum);
buf_add(stash, (const char *) &wire, sizeof(struct dns_soa_wireformat_s));
size_t sz_out = 0;
tor_free(drr->rdata);
drr->rdata = (uint8_t *) buf_extract(stash, &sz_out);
drr->rdlength = (uint16_t) sz_out;
log_debug(LD_GENERAL, "encoded: %s",
hex_str((const char *) drr->rdata, drr->rdlength));
cleanup:
buf_free(stash);
return ret;
}
/** Decode wire-format data and interpret it as SOA record. */
int
dns_decode_soa(dns_rr_t *drr, uint8_t *ptr, const uint8_t *data,
const size_t size)
{
// LCOV_EXCL_START
tor_assert(drr);
tor_assert(ptr);
tor_assert(data);
// LCOV_EXCL_STOP
size_t pos = (ptr - data);
if (pos > size) {
log_debug(LD_GENERAL, "no data left");
return -1;
}
log_debug(LD_GENERAL, "decode: %s", hex_str((const char *) ptr, size - pos));
dns_soa_free(drr->soa);
drr->soa = dns_soa_new();
drr->soa->mname = dns_name_new();
if (dns_consume_name(drr->soa->mname, &ptr, data, size) < 0) {
log_debug(LD_GENERAL, "failed consuming mname");
return -2;
}
drr->soa->rname = dns_name_new();
if (dns_consume_name(drr->soa->rname, &ptr, data, size) < 0) {
log_debug(LD_GENERAL, "failed consuming rname");
return -3;
}
size_t soa_len = sizeof(struct dns_soa_wireformat_s);
if (soa_len > size - pos) {
log_debug(LD_GENERAL, "invalid length: wanted %d, got %d", (int) soa_len,
(int) (size - pos));
return -4;
}
struct dns_soa_wireformat_s *wire =
(struct dns_soa_wireformat_s *) ptr;
drr->soa->serial = ntohl(wire->serial);
drr->soa->refresh = ntohl(wire->refresh);
drr->soa->retry = ntohl(wire->retry);
drr->soa->expire = ntohl(wire->expire);
drr->soa->minimum = ntohl(wire->minimum);
log_debug(LD_GENERAL, "decoded: %s", dns_soa_str(drr->soa));
return 0;
}
//
// Resource Record - PTR
/** Encode the given PTR record in <b>drr</b> to wire-format. */
int
dns_encode_ptr(dns_rr_t *drr)
{
// LCOV_EXCL_START
tor_assert(drr);
// LCOV_EXCL_STOP
buf_t *stash = buf_new();
int ret = 0;
if (!drr->ptr) {
log_debug(LD_GENERAL, "missing rdata");
ret = -1;
goto cleanup;
}
log_debug(LD_GENERAL, "encode: %s", dns_ptr_str(drr->ptr));
if (dns_pack_name(stash, drr->ptr) < 0) {
log_debug(LD_GENERAL, "failed packing name");
ret = -2;
goto cleanup;
}
size_t sz_out = 0;
tor_free(drr->rdata);
drr->rdata = (uint8_t *) buf_extract(stash, &sz_out);
drr->rdlength = (uint16_t) sz_out;
log_debug(LD_GENERAL, "encoded: %s",
hex_str((const char *) drr->rdata, drr->rdlength));
cleanup:
buf_free(stash);
return ret;
}
/** Decode wire-format data and interpret it as PTR record. */
int
dns_decode_ptr(dns_rr_t *drr, uint8_t *ptr, const uint8_t *data,
const size_t size)
{
// LCOV_EXCL_START
tor_assert(drr);
tor_assert(ptr);
tor_assert(data);
// LCOV_EXCL_STOP
size_t pos = (ptr - data);
if (pos > size) {
log_debug(LD_GENERAL, "no data left");
return -1;
}
log_debug(LD_GENERAL, "decode: %s", hex_str((const char *) ptr, size - pos));
dns_name_free(drr->ptr);
drr->ptr = dns_name_new();
if (dns_consume_name(drr->ptr, &ptr, data, size) < 0) {
log_debug(LD_GENERAL, "failed consuming name");
return -2;
}
log_debug(LD_GENERAL, "decoded: %s", dns_ptr_str(drr->ptr));
return 0;
}
//
// Resource Record - MX
/** Encode the given MX record in <b>drr</b> to wire-format. */
int
dns_encode_mx(dns_rr_t *drr)
{
// LCOV_EXCL_START
tor_assert(drr);
// LCOV_EXCL_STOP
buf_t *stash = buf_new();
int ret = 0;
if (!drr->mx) {
log_debug(LD_GENERAL, "missing rdata");
ret = -1;
goto cleanup;
}
log_debug(LD_GENERAL, "encode: %s", dns_mx_str(drr->mx));
struct dns_mx_wireformat_s wire;
wire.preference = htons(drr->mx->preference);
buf_add(stash, (const char *) &wire, sizeof(struct dns_mx_wireformat_s));
if (dns_pack_name(stash, drr->mx->exchange) < 0) {
log_debug(LD_GENERAL, "failed packing name");
ret = -2;
goto cleanup;
}
size_t sz_out = 0;
tor_free(drr->rdata);
drr->rdata = (uint8_t *) buf_extract(stash, &sz_out);
drr->rdlength = (uint16_t) sz_out;
log_debug(LD_GENERAL, "encoded: %s",
hex_str((const char *) drr->rdata, drr->rdlength));
cleanup:
buf_free(stash);
return ret;
}
/** Decode wire-format data and interpret it as MX record. */
int
dns_decode_mx(dns_rr_t *drr, uint8_t *ptr, const uint8_t *data,
const size_t size)
{
// LCOV_EXCL_START
tor_assert(drr);
tor_assert(ptr);
tor_assert(data);
// LCOV_EXCL_STOP
size_t pos = (ptr - data);
if (pos > size) {
log_debug(LD_GENERAL, "no data left");
return -1;
}
log_debug(LD_GENERAL, "decode: %s", hex_str((const char *) ptr, size - pos));
size_t mx_len = sizeof(struct dns_mx_wireformat_s);
if (mx_len > size - pos) {
log_debug(LD_GENERAL, "invalid length: wanted %d, got %d", (int) mx_len,
(int) (size - pos));
return -2;
}
struct dns_mx_wireformat_s *wire =
(struct dns_mx_wireformat_s *) ptr;
ptr += mx_len;
dns_mx_free(drr->mx);
drr->mx = dns_mx_new();
drr->mx->preference = ntohs(wire->preference);
drr->mx->exchange = dns_name_new();
if (dns_consume_name(drr->mx->exchange, &ptr, data, size) < 0) {
log_debug(LD_GENERAL, "failed consuming name");
return -3;
}
log_debug(LD_GENERAL, "decoded: %s", dns_mx_str(drr->mx));
return 0;
}
//
// Resource Record - KEY
/** Encode KEY record in <b>drr</b> to wire-format. */
int
dns_encode_key(dns_rr_t *drr)
{
// LCOV_EXCL_START
tor_assert(drr);
// LCOV_EXCL_STOP
buf_t *stash = buf_new();
int ret = 0;
if (!drr->key) {
log_debug(LD_GENERAL, "missing rdata");
ret = -1;
goto cleanup;
}
log_debug(LD_GENERAL, "encode: %s", dns_key_str(drr->key));
struct dns_key_wireformat_s wire;
wire.flags = htons(drr->key->flags);
wire.protocol = drr->key->protocol;
wire.algorithm = drr->key->algorithm;
buf_add(stash, (const char *) &wire, sizeof(struct dns_key_wireformat_s));
buf_add(stash, (const char *) drr->key->public_key,
drr->key->public_key_len);
size_t sz_out = 0;
tor_free(drr->rdata);
drr->rdata = (uint8_t *) buf_extract(stash, &sz_out);
drr->rdlength = (uint16_t) sz_out;
log_debug(LD_GENERAL, "encoded: %s",
hex_str((const char *) drr->rdata, drr->rdlength));
cleanup:
buf_free(stash);
return ret;
}
/** Decode wire-format data and interpret it as KEY record. */
int
dns_decode_key(dns_rr_t *drr, uint8_t *ptr, const uint8_t *data,
const size_t size)
{
// LCOV_EXCL_START
tor_assert(drr);
tor_assert(ptr);
tor_assert(data);
// LCOV_EXCL_STOP
size_t pos = (ptr - data);
if (pos > size) {
log_debug(LD_GENERAL, "decode: no data left");
return -1;
}
log_debug(LD_GENERAL, "decode: %s", hex_str((const char *) ptr, size - pos));
size_t key_len = sizeof(struct dns_key_wireformat_s);
if (key_len > size - pos) {
log_debug(LD_GENERAL, "invalid length: wanted %d, got %d", (int) key_len,
(int) (size - pos));
return -2;
}
struct dns_key_wireformat_s *wire =
(struct dns_key_wireformat_s *) ptr;
ptr += key_len;
dns_key_free(drr->key);
drr->key = dns_key_new();
drr->key->flags = ntohs(wire->flags);
drr->key->protocol = wire->protocol;
drr->key->algorithm = wire->algorithm;
pos = (ptr - data);
uint16_t public_key_len = size - (ptr - data);
drr->key->public_key = tor_memdup(ptr, public_key_len);
drr->key->public_key_len = public_key_len;
ptr += public_key_len;
log_debug(LD_GENERAL, "decoded: %s", dns_key_str(drr->key));
return 0;
}
//
// Resource Record - AAAA
/** Encode the given AAAA record in <b>drr</b> to wire-format. */
int
dns_encode_aaaa(dns_rr_t *drr)
{
// LCOV_EXCL_START
tor_assert(drr);
// LCOV_EXCL_STOP
if (!drr->aaaa) {
log_debug(LD_GENERAL, "missing rdata");
return -1;
}
log_debug(LD_GENERAL, "encode: %s", dns_aaaa_str(drr->aaaa));
struct sockaddr_in6 addr;
if (!tor_inet_pton(AF_INET6, drr->aaaa, &addr.sin6_addr)) {
log_debug(LD_GENERAL, "inet_ntop conversion error");
return -2;
}
tor_free(drr->rdata);
drr->rdlength = sizeof(addr.sin6_addr.s6_addr);
drr->rdata = tor_memdup((const char *) &addr.sin6_addr.s6_addr,
drr->rdlength);
log_debug(LD_GENERAL, "encoded: %s", hex_str((const char *) drr->rdata,
drr->rdlength));
return 0;
}
/** Decode wire-format data and interpret it as AAAA record. */
int
dns_decode_aaaa(dns_rr_t *drr, uint8_t *ptr, const uint8_t *data,
const size_t size)
{
// LCOV_EXCL_START
tor_assert(drr);
tor_assert(ptr);
tor_assert(data);
// LCOV_EXCL_STOP
size_t pos = (ptr - data);
if (pos > size) {
log_debug(LD_GENERAL, "no data left");
return -1;
}
log_debug(LD_GENERAL, "decode: %s", hex_str((const char *) ptr, size - pos));
struct sockaddr_in6 addr;
size_t aaaa_len = sizeof(addr.sin6_addr.s6_addr);
if (aaaa_len > size - pos) {
log_debug(LD_GENERAL, "invalid length: wanted %d, got %d", (int) aaaa_len,
(int) (size - pos));
return -2;
}
memcpy(&addr.sin6_addr.s6_addr, ptr, aaaa_len);
char address[INET6_ADDRSTRLEN];
tor_inet_ntop(AF_INET6, &addr.sin6_addr, address, INET6_ADDRSTRLEN);
tor_free(drr->aaaa);
drr->aaaa = tor_strdup(address);
log_debug(LD_GENERAL, "decoded: %s", dns_aaaa_str(drr->aaaa));
return 0;
}
//
// Resource Record - DS
/** Encode the given DS record in <b>drr</b> to wire-format. */
int
dns_encode_ds(dns_rr_t *drr)
{
// LCOV_EXCL_START
tor_assert(drr);
// LCOV_EXCL_STOP
buf_t *stash = buf_new();
int ret = 0;
if (!drr->ds) {
log_debug(LD_GENERAL, "missing rdata");
ret = -1;
goto cleanup;
}
log_debug(LD_GENERAL, "encode: %s", dns_ds_str(drr->ds));
struct dns_ds_wireformat_s wire;
wire.key_tag = htons(drr->ds->key_tag);
wire.algorithm = drr->ds->algorithm;
wire.digest_type = drr->ds->digest_type;
buf_add(stash, (const char *) &wire, sizeof(struct dns_ds_wireformat_s));
buf_add(stash, (const char *) drr->ds->digest, drr->ds->digest_len);
size_t sz_out = 0;
tor_free(drr->rdata);
drr->rdata = (uint8_t *) buf_extract(stash, &sz_out);
drr->rdlength = (uint16_t) sz_out;
log_debug(LD_GENERAL, "encoded: %s",
hex_str((const char *) drr->rdata, drr->rdlength));
cleanup:
buf_free(stash);
return ret;
}
/** Decode wire-format data and interpret it as DS record. */
int
dns_decode_ds(dns_rr_t *drr, uint8_t *ptr, const uint8_t *data,
const size_t size)
{
// LCOV_EXCL_START
tor_assert(drr);
tor_assert(ptr);
tor_assert(data);
// LCOV_EXCL_STOP
size_t pos = (ptr - data);
if (pos > size) {
log_debug(LD_GENERAL, "no data left");
return -1;
}
log_debug(LD_GENERAL, "decode: %s", hex_str((const char *) ptr, size - pos));
size_t ds_len = sizeof(struct dns_ds_wireformat_s);
if (ds_len > size - pos) {
log_debug(LD_GENERAL, "invalid length: wanted %d, got %d", (int) ds_len,
(int) (size - pos));
return -2;
}
struct dns_ds_wireformat_s *wire =
(struct dns_ds_wireformat_s *) ptr;
ptr += ds_len;
dns_ds_free(drr->ds);
drr->ds = dns_ds_new();
drr->ds->key_tag = ntohs(wire->key_tag);
drr->ds->algorithm = wire->algorithm;
drr->ds->digest_type = wire->digest_type;
pos = (ptr - data);
uint16_t digest_len = size - (ptr - data);
drr->ds->digest = tor_memdup(ptr, digest_len);
drr->ds->digest_len = digest_len;
ptr += digest_len;
log_debug(LD_GENERAL, "decoded: %s", dns_ds_str(drr->ds));
return 0;
}
//
// Resource Record - RRSIG
/** Encode the given RRSIG record in <b>drr</b> to wire-format. */
int
dns_encode_rrsig(dns_rr_t *drr)
{
// LCOV_EXCL_START
tor_assert(drr);
// LCOV_EXCL_STOP
buf_t *stash = buf_new();
int ret = 0;
if (!drr->rrsig || !drr->rrsig->type_covered) {
log_debug(LD_GENERAL, "missing rdata");
ret = -1;
goto cleanup;
}
log_debug(LD_GENERAL, "encode: %s", dns_rrsig_str(drr->rrsig));
struct dns_rrsig_wireformat_s wire;
wire.type_covered = htons(drr->rrsig->type_covered->value);
wire.algorithm = drr->rrsig->algorithm;
wire.labels = drr->rrsig->labels;
wire.original_ttl = htonl(drr->rrsig->original_ttl);
wire.signature_expiration = htonl(drr->rrsig->signature_expiration);
wire.signature_inception = htonl(drr->rrsig->signature_inception);
wire.key_tag = htons(drr->rrsig->key_tag);
buf_add(stash, (const char *) &wire, sizeof(struct dns_rrsig_wireformat_s));
if (dns_pack_name(stash, drr->rrsig->signer_name) < 0) {
log_debug(LD_GENERAL, "failed packing name");
ret = -2;
goto cleanup;
}
buf_add(stash, (const char *) drr->rrsig->signature,
drr->rrsig->signature_len);
size_t sz_out = 0;
tor_free(drr->rdata);
drr->rdata = (uint8_t *) buf_extract(stash, &sz_out);
drr->rdlength = (uint16_t) sz_out;
log_debug(LD_GENERAL, "encoded: %s",
hex_str((const char *) drr->rdata, drr->rdlength));
cleanup:
buf_free(stash);
return ret;
}
/** Decode wire-format data and interpret it as RRSIG record. */
int
dns_decode_rrsig(dns_rr_t *drr, uint8_t *ptr, const uint8_t *data,
const size_t size)
{
// LCOV_EXCL_START
tor_assert(drr);
tor_assert(ptr);
tor_assert(data);
// LCOV_EXCL_STOP
size_t pos = (ptr - data);
if (pos > size) {
log_debug(LD_GENERAL, "no data left");
return -1;
}
log_debug(LD_GENERAL, "decode: %s", hex_str((const char *) ptr, size - pos));
size_t rrsig_len = sizeof(struct dns_rrsig_wireformat_s);
if (rrsig_len > size - pos) {
log_debug(LD_GENERAL, "invalid length: wanted %d, got %d", (int) rrsig_len,
(int) (size - pos));
return -2;
}
struct dns_rrsig_wireformat_s *wire =
(struct dns_rrsig_wireformat_s *) ptr;
ptr += rrsig_len;
dns_rrsig_free(drr->rrsig);
drr->rrsig = dns_rrsig_new();
drr->rrsig->type_covered = dns_type_of(ntohs(wire->type_covered));
drr->rrsig->algorithm = wire->algorithm;
drr->rrsig->labels = wire->labels;
drr->rrsig->original_ttl = ntohl(wire->original_ttl);
drr->rrsig->signature_expiration = ntohl(wire->signature_expiration);
drr->rrsig->signature_inception = ntohl(wire->signature_inception);
drr->rrsig->key_tag = ntohs(wire->key_tag);
drr->rrsig->signer_name = dns_name_new();
if (dns_consume_name(drr->rrsig->signer_name, &ptr, data, size) < 0) {
log_debug(LD_GENERAL, "failed consuming name");
return -3;
}
pos = (ptr - data);
uint16_t signature_len = size - (ptr - data);
drr->rrsig->signature = tor_memdup(ptr, signature_len);
drr->rrsig->signature_len = signature_len;
ptr += signature_len;
log_debug(LD_GENERAL, "decoded: %s", dns_rrsig_str(drr->rrsig));
return 0;
}
//
// Resource Record - NSEC
/** Encode the given NSEC record in <b>drr</b> to wire-format. */
int
dns_encode_nsec(dns_rr_t *drr)
{
// LCOV_EXCL_START
tor_assert(drr);
// LCOV_EXCL_STOP
buf_t *stash = buf_new();
int ret = 0;
if (!drr->nsec) {
log_debug(LD_GENERAL, "missing rdata");
ret = -1;
goto cleanup;
}
log_debug(LD_GENERAL, "encode: %s", dns_nsec_str(drr->nsec));
if (dns_pack_name(stash, drr->nsec->next_domain_name) < 0) {
log_debug(LD_GENERAL, "failed packing next domain name");
ret = -2;
goto cleanup;
}
if (dns_pack_type_bitmaps(stash, drr->nsec->types) < 0) {
// LCOV_EXCL_START
log_debug(LD_GENERAL, "failed packing type bitmaps");
ret = -3;
goto cleanup;
// LCOV_EXCL_STOP
}
size_t sz_out = 0;
tor_free(drr->rdata);
drr->rdata = (uint8_t *) buf_extract(stash, &sz_out);
drr->rdlength = (uint16_t) sz_out;
log_debug(LD_GENERAL, "encoded: %s",
hex_str((const char *) drr->rdata, drr->rdlength));
cleanup:
buf_free(stash);
return ret;
}
/** Decode wire-format data and interpret it as NSEC record. */
int
dns_decode_nsec(dns_rr_t *drr, uint8_t *ptr, const uint8_t *data,
const size_t size)
{
// LCOV_EXCL_START
tor_assert(drr);
tor_assert(ptr);
tor_assert(data);
// LCOV_EXCL_STOP
size_t pos = (ptr - data);
if (pos > size) {
log_debug(LD_GENERAL, "no data left");
return -1;
}
log_debug(LD_GENERAL, "decode: %s", hex_str((const char *) ptr, size - pos));
dns_nsec_free(drr->nsec);
drr->nsec = dns_nsec_new();
drr->nsec->next_domain_name = dns_name_new();
if (dns_consume_name(drr->nsec->next_domain_name, &ptr, data, size) < 0) {
log_debug(LD_GENERAL, "failed consuming next domain name");
return -2;
}
if (dns_consume_type_bitmaps(drr->nsec->types, &ptr, data, size) < 0) {
log_debug(LD_GENERAL, "failed consuming type bitmaps");
return -3;
}
log_debug(LD_GENERAL, "decoded: %s", dns_nsec_str(drr->nsec));
return 0;
}
//
// Resource Record - DNSKEY
/** Encode the given DNSKEY record in <b>drr</b> to wire-format. */
int
dns_encode_dnskey(dns_rr_t *drr)
{
// LCOV_EXCL_START
tor_assert(drr);
// LCOV_EXCL_STOP
buf_t *stash = buf_new();
int ret = 0;
if (!drr->dnskey) {
log_debug(LD_GENERAL, "missing rdata");
ret = -1;
goto cleanup;
}
log_debug(LD_GENERAL, "encode: %s", dns_dnskey_str(drr->dnskey));
struct dns_dnskey_wireformat_s wire;
wire.flags = htons(drr->dnskey->flags);
wire.protocol = drr->dnskey->protocol;
wire.algorithm = drr->dnskey->algorithm;
buf_add(stash, (const char *) &wire, sizeof(struct dns_dnskey_wireformat_s));
buf_add(stash, (const char *) drr->dnskey->public_key,
drr->dnskey->public_key_len);
size_t sz_out = 0;
tor_free(drr->rdata);
drr->rdata = (uint8_t *) buf_extract(stash, &sz_out);
drr->rdlength = (uint16_t) sz_out;
log_debug(LD_GENERAL, "encoded: %s", hex_str((const char *) drr->rdata,
drr->rdlength));
cleanup:
buf_free(stash);
return ret;
}
/** Decode wire-format data and interpret it as DNSKEY record. */
int
dns_decode_dnskey(dns_rr_t *drr, uint8_t *ptr, const uint8_t *data,
const size_t size)
{
// LCOV_EXCL_START
tor_assert(drr);
tor_assert(ptr);
tor_assert(data);
// LCOV_EXCL_STOP
size_t pos = (ptr - data);
if (pos > size) {
log_debug(LD_GENERAL, "decode: no data left");
return -1;
}
log_debug(LD_GENERAL, "decode: %s", hex_str((const char *) ptr, size - pos));
size_t dnskey_len = sizeof(struct dns_dnskey_wireformat_s);
if (dnskey_len > size - pos) {
log_debug(LD_GENERAL, "invalid length: wanted %d, got %d",
(int) dnskey_len, (int) (size - pos));
return -2;
}
struct dns_dnskey_wireformat_s *wire =
(struct dns_dnskey_wireformat_s *) ptr;
ptr += dnskey_len;
dns_dnskey_free(drr->dnskey);
drr->dnskey = dns_dnskey_new();
drr->dnskey->flags = ntohs(wire->flags);
drr->dnskey->protocol = wire->protocol;
drr->dnskey->algorithm = wire->algorithm;
pos = (ptr - data);
uint16_t public_key_len = size - (ptr - data);
drr->dnskey->public_key = tor_memdup(ptr, public_key_len);
drr->dnskey->public_key_len = public_key_len;
ptr += public_key_len;
log_debug(LD_GENERAL, "decoded: %s", dns_dnskey_str(drr->dnskey));
return 0;
}
//
// Resource Record - NSEC3
/** Encode the given NSEC3 record in <b>drr</b> to wire-format. */
int
dns_encode_nsec3(dns_rr_t *drr)
{
// LCOV_EXCL_START
tor_assert(drr);
// LCOV_EXCL_STOP
buf_t *stash = buf_new();
int ret = 0;
if (!drr->nsec3) {
log_debug(LD_GENERAL, "missing rdata");
ret = -1;
goto cleanup;
}
log_debug(LD_GENERAL, "encode: %s", dns_nsec3_str(drr->nsec3));
struct dns_nsec3_wireformat_s wire;
wire.hash_algorithm = drr->nsec3->hash_algorithm;
wire.flags = drr->nsec3->flags;
wire.iterations = htons(drr->nsec3->iterations);
buf_add(stash, (const char *) &wire, sizeof(struct dns_nsec3_wireformat_s));
buf_add(stash, (const char *) &drr->nsec3->salt_length, 1);
buf_add(stash, (const char *) drr->nsec3->salt,
drr->nsec3->salt_length);
buf_add(stash, (const char *) &drr->nsec3->hash_length, 1);
buf_add(stash, (const char *) drr->nsec3->next_hashed_owner_name,
drr->nsec3->hash_length);
if (dns_pack_type_bitmaps(stash, drr->nsec3->types) < 0) {
// LCOV_EXCL_START
log_debug(LD_GENERAL, "failed packing type bitmaps");
ret = -2;
goto cleanup;
// LCOV_EXCL_STOP
}
size_t sz_out = 0;
tor_free(drr->rdata);
drr->rdata = (uint8_t *) buf_extract(stash, &sz_out);
drr->rdlength = (uint16_t) sz_out;
log_debug(LD_GENERAL, "encoded: %s", hex_str((const char *) drr->rdata,
drr->rdlength));
cleanup:
buf_free(stash);
return ret;
}
/** Decode wire-format data and interpret it as NSEC3 record. */
int
dns_decode_nsec3(dns_rr_t *drr, uint8_t *ptr, const uint8_t *data,
const size_t size)
{
// LCOV_EXCL_START
tor_assert(drr);
tor_assert(ptr);
tor_assert(data);
// LCOV_EXCL_STOP
size_t pos = (ptr - data);
if (pos > size) {
log_debug(LD_GENERAL, "no data left");
return -1;
}
log_debug(LD_GENERAL, "decode: %s", hex_str((const char *) ptr, size - pos));
size_t nsec3_len = sizeof(struct dns_nsec3_wireformat_s);
if (nsec3_len > size - pos) {
log_debug(LD_GENERAL, "invalid length: wanted %d, got %d", (int) nsec3_len,
(int) (size - pos));
return -2;
}
struct dns_nsec3_wireformat_s *wire =
(struct dns_nsec3_wireformat_s *) ptr;
ptr += nsec3_len;
pos = (ptr - data);
dns_nsec3_free(drr->nsec3);
drr->nsec3 = dns_nsec3_new();
drr->nsec3->hash_algorithm = wire->hash_algorithm;
drr->nsec3->flags = wire->flags;
drr->nsec3->iterations = ntohs(wire->iterations);
if (1 > size - pos) {
log_debug(LD_GENERAL, "invalid length: wanted %d, got %d", 1,
(int) (size - pos));
return -3;
}
uint8_t salt_length = *ptr;
ptr += 1;
pos = (ptr - data);
if (salt_length > size - pos) {
log_debug(LD_GENERAL, "invalid length: wanted %d, got %d",
(int) salt_length, (int) (size - pos));
return -4;
}
drr->nsec3->salt = tor_memdup(ptr, salt_length);
drr->nsec3->salt_length = salt_length;
ptr += salt_length;
pos = (ptr - data);
if (1 > size - pos) {
log_debug(LD_GENERAL, "invalid length: wanted %d, got %d", 1,
(int) (size - pos));
return -5;
}
uint8_t hash_length = *ptr;
ptr += 1;
pos = (ptr - data);
if (hash_length > size - pos) {
log_debug(LD_GENERAL, "invalid length: wanted %d, got %d",
(int) hash_length, (int) (size - pos));
return -6;
}
drr->nsec3->next_hashed_owner_name = tor_memdup(ptr, hash_length);
drr->nsec3->hash_length = hash_length;
ptr += hash_length;
if (dns_consume_type_bitmaps(drr->nsec3->types, &ptr, data, size) < 0) {
log_debug(LD_GENERAL, "failed consuming type bitmaps");
return -7;
}
log_debug(LD_GENERAL, "decoded: %s", dns_nsec3_str(drr->nsec3));
return 0;
}
//
// Resource Record - NSEC3PARAM
/** Encode the given NSEC3PARAM record in <b>drr</b> to wire-format. */
int
dns_encode_nsec3param(dns_rr_t *drr)
{
// LCOV_EXCL_START
tor_assert(drr);
// LCOV_EXCL_STOP
buf_t *stash = buf_new();
int ret = 0;
if (!drr->nsec3param) {
log_debug(LD_GENERAL, "missing rdata");
ret = -1;
goto cleanup;
}
log_debug(LD_GENERAL, "encode: %s", dns_nsec3param_str(drr->nsec3param));
struct dns_nsec3param_wireformat_s wire;
wire.hash_algorithm = drr->nsec3param->hash_algorithm;
wire.flags = drr->nsec3param->flags;
wire.iterations = htons(drr->nsec3param->iterations);
buf_add(stash, (const char *) &wire,
sizeof(struct dns_nsec3param_wireformat_s));
buf_add(stash, (const char *) &drr->nsec3param->salt_length, 1);
buf_add(stash, (const char *) drr->nsec3param->salt,
drr->nsec3param->salt_length);
size_t sz_out = 0;
tor_free(drr->rdata);
drr->rdata = (uint8_t *) buf_extract(stash, &sz_out);
drr->rdlength = (uint16_t) sz_out;
log_debug(LD_GENERAL, "encoded: %s",
hex_str((const char *) drr->rdata, drr->rdlength));
cleanup:
buf_free(stash);
return ret;
}
/** Decode wire-format data and interpret it as NSEC3PARAM record. */
int
dns_decode_nsec3param(dns_rr_t *drr, uint8_t *ptr, const uint8_t *data,
const size_t size)
{
// LCOV_EXCL_START
tor_assert(drr);
tor_assert(ptr);
tor_assert(data);
// LCOV_EXCL_STOP
size_t pos = (ptr - data);
if (pos > size) {
log_debug(LD_GENERAL, "no data left");
return -1;
}
log_debug(LD_GENERAL, "decode: %s", hex_str((const char *) ptr, size - pos));
size_t nsec3param_len = sizeof(struct dns_nsec3param_wireformat_s);
if (nsec3param_len > size - pos) {
log_debug(LD_GENERAL, "invalid length: wanted %d, got %d",
(int) nsec3param_len, (int) (size - pos));
return -2;
}
struct dns_nsec3param_wireformat_s *wire =
(struct dns_nsec3param_wireformat_s *) ptr;
ptr += nsec3param_len;
pos = (ptr - data);
dns_nsec3param_free(drr->nsec3param);
drr->nsec3param = dns_nsec3param_new();
drr->nsec3param->hash_algorithm = wire->hash_algorithm;
drr->nsec3param->flags = wire->flags;
drr->nsec3param->iterations = ntohs(wire->iterations);
if (1 > size - pos) {
log_debug(LD_GENERAL, "invalid length: wanted %d, got %d", 1,
(int) (size - pos));
return -3;
}
uint8_t salt_length = *ptr;
ptr += 1;
pos = (ptr - data);
if (salt_length > size - pos) {
log_debug(LD_GENERAL, "invalid length: wanted %d, got %d",
(int) salt_length, (int) (size - pos));
return -4;
}
drr->nsec3param->salt = tor_memdup(ptr, salt_length);
drr->nsec3param->salt_length = salt_length;
ptr += salt_length;
log_debug(LD_GENERAL, "decoded: %s", dns_nsec3param_str(drr->nsec3param));
return 0;
}
//
// Resource Record - URI
/** Encode the given URI record in <b>drr</b> to wire-format. */
int
dns_encode_uri(dns_rr_t *drr)
{
// LCOV_EXCL_START
tor_assert(drr);
// LCOV_EXCL_STOP
buf_t *stash = buf_new();
int ret = 0;
if (!drr->uri) {
log_debug(LD_GENERAL, "missing rdata");
ret = -1;
goto cleanup;
}
log_debug(LD_GENERAL, "encode: %s", dns_uri_str(drr->uri));
struct dns_uri_wireformat_s wire;
wire.priority = htons(drr->uri->priority);
wire.weight = htons(drr->uri->weight);
buf_add(stash, (const char *) &wire, sizeof(struct dns_uri_wireformat_s));
buf_add_string(stash, (const char *) drr->uri->target);
size_t sz_out = 0;
tor_free(drr->rdata);
drr->rdata = (uint8_t *) buf_extract(stash, &sz_out);
drr->rdlength = (uint16_t) sz_out;
log_debug(LD_GENERAL, "encoded: %s",
hex_str((const char *) drr->rdata, drr->rdlength));
cleanup:
buf_free(stash);
return ret;
}
/** Decode wire-format data and interpret it as URI record. */
int
dns_decode_uri(dns_rr_t *drr, uint8_t *ptr, const uint8_t *data,
const size_t size)
{
// LCOV_EXCL_START
tor_assert(drr);
tor_assert(ptr);
tor_assert(data);
// LCOV_EXCL_STOP
size_t pos = (ptr - data);
if (pos > size) {
log_debug(LD_GENERAL, "no data left");
return -1;
}
log_debug(LD_GENERAL, "decode: %s", hex_str((const char *) ptr, size - pos));
size_t uri_len = sizeof(struct dns_uri_wireformat_s);
if (uri_len > size - pos) {
log_debug(LD_GENERAL, "invalid length: wanted %d, got %d", (int) uri_len,
(int) (size - pos));
return -2;
}
struct dns_uri_wireformat_s *wire =
(struct dns_uri_wireformat_s *) ptr;
ptr += uri_len;
dns_uri_free(drr->uri);
drr->uri = dns_uri_new();
drr->uri->priority = ntohs(wire->priority);
drr->uri->weight = ntohs(wire->weight);
size_t target_len = size - (ptr - data);
drr->uri->target = tor_memdup_nulterm(ptr, target_len);
log_debug(LD_GENERAL, "decoded: %s", dns_uri_str(drr->uri));
return 0;
}
//
// Resource Record
/** Pack the given RR in <b>drr</b> to wire-format. */
int
dns_pack_rr(buf_t *buf, const dns_rr_t *drr)
{
// LCOV_EXCL_START
tor_assert(buf);
tor_assert(drr);
// LCOV_EXCL_STOP
buf_t *stash = buf_new();
char *res = NULL;
size_t res_len = 0;
if (!drr->rrtype) {
log_debug(LD_GENERAL, "missing rr type");
res_len = -1;
goto cleanup;
}
log_debug(LD_GENERAL, "pack: %s", dns_rr_str(drr));
if (dns_encode_rr_rdata((dns_rr_t *) drr) < 0) {
log_debug(LD_GENERAL, "failed encoding rdata");
res_len = -2;
goto cleanup;
}
if (dns_pack_name(stash, drr->name) < 0) {
log_debug(LD_GENERAL, "failed packing name");
res_len = -3;
goto cleanup;
}
struct dns_rr_wireformat_s wire;
wire.rrtype = htons(drr->rrtype->value);
wire.rrclass = htons(drr->rrclass);
wire.ttl = htonl(drr->ttl);
wire.rdlength = htons(drr->rdlength);
buf_add(stash, (const char *)&wire,
sizeof(struct dns_rr_wireformat_s));
buf_add(stash, (const char *)drr->rdata, drr->rdlength);
res = buf_extract(stash, &res_len);
buf_add(buf, (const char *) res, res_len);
log_debug(LD_GENERAL, "packed (%d): %s", (int) res_len,
hex_str((const char *) res, res_len));
cleanup:
buf_free(stash);
tor_free(res);
return (int) res_len;
}
/** Encode RR rdata to wire-format. */
int
dns_encode_rr_rdata(dns_rr_t *drr)
{
// LCOV_EXCL_START
tor_assert(drr);
tor_assert(drr->rrtype);
// LCOV_EXCL_STOP
switch (drr->rrtype->value) {
case DNS_TYPE_A:
return dns_encode_a(drr);
case DNS_TYPE_NS:
return dns_encode_ns(drr);
case DNS_TYPE_CNAME:
return dns_encode_cname(drr);
case DNS_TYPE_SOA:
return dns_encode_soa(drr);
case DNS_TYPE_PTR:
return dns_encode_ptr(drr);
case DNS_TYPE_MX:
return dns_encode_mx(drr);
case DNS_TYPE_KEY:
return dns_encode_key(drr);
case DNS_TYPE_AAAA:
return dns_encode_aaaa(drr);
case DNS_TYPE_DS:
return dns_encode_ds(drr);
case DNS_TYPE_RRSIG:
return dns_encode_rrsig(drr);
case DNS_TYPE_NSEC:
return dns_encode_nsec(drr);
case DNS_TYPE_DNSKEY:
return dns_encode_dnskey(drr);
case DNS_TYPE_NSEC3:
return dns_encode_nsec3(drr);
case DNS_TYPE_NSEC3PARAM:
return dns_encode_nsec3param(drr);
case DNS_TYPE_URI:
return dns_encode_uri(drr);
default:
log_debug(LD_GENERAL, "dns encode rdata: %s not implemented",
drr->rrtype->name);
return 0;
}
}
/** Consume wire-format data and interpret it as RR. */
int
dns_consume_rr(dns_rr_t *drr, uint8_t **ptr, const uint8_t *data,
const size_t size)
{
// LCOV_EXCL_START
tor_assert(drr);
tor_assert(ptr);
tor_assert(data);
// LCOV_EXCL_STOP
size_t pos = (*ptr - data);
int consumed = 0;
if (pos > size) {
log_debug(LD_GENERAL, "no data left");
return -1;
}
log_debug(LD_GENERAL, "consume: %s",
hex_str((const char *) *ptr, size - pos));
dns_name_free(drr->name);
drr->name = dns_name_new();
consumed = dns_consume_name(drr->name, ptr, data, size);
if (consumed < 0) {
log_debug(LD_GENERAL, "failed consuming name");
return -2;
}
pos = (*ptr - data);
size_t rr_len = sizeof(struct dns_rr_wireformat_s);
if (rr_len > size - pos) {
log_debug(LD_GENERAL, "invalid length: wanted %d, got %d", (int) rr_len,
(int) (size - pos));
return -3;
}
struct dns_rr_wireformat_s *wire =
(struct dns_rr_wireformat_s *) *ptr;
consumed += rr_len;
*ptr += rr_len;
drr->rrtype = dns_type_of(ntohs(wire->rrtype));
drr->rrclass = ntohs(wire->rrclass);
drr->ttl = ntohl(wire->ttl);
drr->rdlength = ntohs(wire->rdlength);
pos = (*ptr - data);
if (drr->rdlength > size - pos) {
log_debug(LD_GENERAL, "invalid length: wanted %d, got %d",
(int) drr->rdlength, (int) (size - pos));
return -4;
}
uint8_t *rdata_ptr = *ptr;
drr->rdata = tor_memdup(*ptr, drr->rdlength);
consumed += drr->rdlength;
*ptr += drr->rdlength;
if (dns_decode_rr_rdata(drr, rdata_ptr, data, pos + drr->rdlength) < 0) {
log_debug(LD_GENERAL, "failed decoding rdata");
return -5;
}
log_debug(LD_GENERAL, "consumed (%d): %s", consumed, dns_rr_str(drr));
return consumed;
}
/** Decode wire-format data and interpret it as RR rdata. */
int
dns_decode_rr_rdata(dns_rr_t *drr, uint8_t *ptr, const uint8_t *data,
const size_t size)
{
// LCOV_EXCL_START
tor_assert(drr);
tor_assert(drr->rrtype);
// LCOV_EXCL_STOP
switch (drr->rrtype->value) {
case DNS_TYPE_A:
return dns_decode_a(drr, ptr, data, size);
case DNS_TYPE_NS:
return dns_decode_ns(drr, ptr, data, size);
case DNS_TYPE_CNAME:
return dns_decode_cname(drr, ptr, data, size);
case DNS_TYPE_SOA:
return dns_decode_soa(drr, ptr, data, size);
case DNS_TYPE_PTR:
return dns_decode_ptr(drr, ptr, data, size);
case DNS_TYPE_MX:
return dns_decode_mx(drr, ptr, data, size);
case DNS_TYPE_KEY:
return dns_decode_key(drr, ptr, data, size);
case DNS_TYPE_AAAA:
return dns_decode_aaaa(drr, ptr, data, size);
case DNS_TYPE_DS:
return dns_decode_ds(drr, ptr, data, size);
case DNS_TYPE_RRSIG:
return dns_decode_rrsig(drr, ptr, data, size);
case DNS_TYPE_NSEC:
return dns_decode_nsec(drr, ptr, data, size);
case DNS_TYPE_DNSKEY:
return dns_decode_dnskey(drr, ptr, data, size);
case DNS_TYPE_NSEC3:
return dns_decode_nsec3(drr, ptr, data, size);
case DNS_TYPE_NSEC3PARAM:
return dns_decode_nsec3param(drr, ptr, data, size);
case DNS_TYPE_URI:
return dns_decode_uri(drr, ptr, data, size);
default:
log_debug(LD_GENERAL, "dns decode rdata: %s not implemented",
drr->rrtype->name);
return 0;
}
}
//
// Message
/** Encode the given message <b>dm</b> to wire-format when using TCP sockets.*/
int
dns_encode_message_tcp(buf_t *buf, const dns_message_t *dm)
{
// LCOV_EXCL_START
tor_assert(buf);
tor_assert(dm);
// LCOV_EXCL_STOP
uint8_t *data = NULL;
size_t size = 0;
int ret = 0;
buf_t *stash = buf_new();
ret = dns_encode_message_udp(stash, dm);
if (ret >= 0) {
data = (uint8_t *) buf_extract(stash, &size);
uint16_t bytes = htons((uint16_t) size);
buf_add(buf, (const char *) &bytes, 2);
buf_add(buf, (const char *) data, size);
tor_free(data);
}
buf_free(stash);
return ret;
}
/** Encode the given message <b>dm</b> to wire-format when using UDP sockets.*/
int
dns_encode_message_udp(buf_t *buf, const dns_message_t *dm)
{
// LCOV_EXCL_START
tor_assert(buf);
tor_assert(dm);
// LCOV_EXCL_STOP
buf_t *stash = buf_new();
char *res = NULL;
size_t res_len = 0;
log_debug(LD_GENERAL, "pack:\n%s", dns_message_str(dm));
if (dns_pack_header(stash, dm->header) < 0) {
log_debug(LD_GENERAL, "failed packing header");
res_len = -1;
goto cleanup;
}
SMARTLIST_FOREACH_BEGIN(dm->question_list, dns_question_t *, dq) {
if (dns_pack_question(stash, dq) < 0) {
log_debug(LD_GENERAL, "failed packing question");
res_len = -2;
goto cleanup;
}
} SMARTLIST_FOREACH_END(dq);
SMARTLIST_FOREACH_BEGIN(dm->answer_list, dns_rr_t *, dan) {
if (dns_pack_rr(stash, dan) < 0) {
log_debug(LD_GENERAL, "failed packing answer");
res_len = -3;
goto cleanup;
}
} SMARTLIST_FOREACH_END(dan);
SMARTLIST_FOREACH_BEGIN(dm->name_server_list, dns_rr_t *, dns) {
if (dns_pack_rr(stash, dns) < 0) {
log_debug(LD_GENERAL, "failed packing name server");
res_len = -4;
goto cleanup;
}
} SMARTLIST_FOREACH_END(dns);
SMARTLIST_FOREACH_BEGIN(dm->additional_record_list, dns_rr_t *, drr) {
if (dns_pack_rr(stash, drr) < 0) {
log_debug(LD_GENERAL, "failed packing additional record");
res_len = -5;
goto cleanup;
}
} SMARTLIST_FOREACH_END(drr);
res = buf_extract(stash, &res_len);
buf_add(buf, (const char *) res, res_len);
log_debug(LD_GENERAL, "packed (%d): %s", (int) res_len,
hex_str((const char *) res, res_len));
cleanup:
buf_free(stash);
tor_free(res);
return (int) res_len;
}
/** Decode the given message <b>dm</b> from wire-format when using TCP sockets.
*/
int
dns_decode_message_tcp(dns_message_t *dm, buf_t *buf)
{
// LCOV_EXCL_START
tor_assert(dm);
tor_assert(buf);
// LCOV_EXCL_STOP
const uint8_t *data = NULL;
size_t size = 0;
buf_pullup(buf, 2, (const char **) &data, &size);
if (size < 2) {
log_debug(LD_GENERAL, "there is no message waiting");
return -1;
}
size_t bytes = ntohs(*((uint16_t *) data));
if (bytes != size - 2) {
log_debug(LD_GENERAL, "invalid message size: wanted %d, got %d",
(int) bytes, (int) size - 2);
return -2;
}
buf_drain(buf, 2);
return dns_decode_message_udp(dm, buf);
}
/** Decode the given message <b>dm</b> from wire-format when using UDP sockets.
*/
int
dns_decode_message_udp(dns_message_t *dm, buf_t *buf)
{
// LCOV_EXCL_START
tor_assert(dm);
tor_assert(buf);
// LCOV_EXCL_STOP
int consumed = 0;
size_t size = 0;
uint8_t *data = (uint8_t *) buf_extract(buf, &size);
uint8_t *ptr = (uint8_t *) data;
log_debug(LD_GENERAL, "consume: %s", hex_str((const char *) ptr, size));
consumed = dns_consume_header(dm->header, &ptr, data, size);
if (consumed < 0) {
log_debug(LD_GENERAL, "failed consuming header");
consumed = -1;
goto cleanup;
}
SMARTLIST_FOREACH(dm->question_list, dns_question_t *, dq,
dns_question_free(dq));
SMARTLIST_FOREACH(dm->answer_list, dns_rr_t *, dan, dns_rr_free(dan));
SMARTLIST_FOREACH(dm->name_server_list, dns_rr_t *, dns, dns_rr_free(dns));
SMARTLIST_FOREACH(dm->additional_record_list, dns_rr_t *, dar,
dns_rr_free(dar));
smartlist_clear(dm->question_list);
smartlist_clear(dm->answer_list);
smartlist_clear(dm->name_server_list);
smartlist_clear(dm->additional_record_list);
for (uint16_t i = 0; i < dm->header->qdcount; i++) {
dns_question_t *dq = dns_question_new();
smartlist_add(dm->question_list, dq);
int question_len = dns_consume_question(dq, &ptr, data, size);
consumed += question_len;
if (question_len < 0) {
log_debug(LD_GENERAL, "failed consuming question");
consumed = -2;
goto cleanup;
}
}
for (uint16_t i = 0; i < dm->header->ancount; i++) {
dns_rr_t *drr = dns_rr_new();
smartlist_add(dm->answer_list, drr);
int rr_len = dns_consume_rr(drr, &ptr, data, size);
consumed += rr_len;
if (rr_len < 0) {
log_debug(LD_GENERAL, "failed consuming answer");
consumed = -3;
goto cleanup;
}
}
for (uint16_t i = 0; i < dm->header->nscount; i++) {
dns_rr_t *drr = dns_rr_new();
smartlist_add(dm->name_server_list, drr);
int rr_len = dns_consume_rr(drr, &ptr, data, size);
consumed += rr_len;
if (rr_len < 0) {
log_debug(LD_GENERAL, "failed consuming name server");
consumed = -4;
goto cleanup;
}
}
for (uint16_t i = 0; i < dm->header->arcount; i++) {
dns_rr_t *dar = dns_rr_new();
smartlist_add(dm->additional_record_list, dar);
int rr_len = dns_consume_rr(dar, &ptr, data, size);
consumed += rr_len;
if (rr_len < 0) {
log_debug(LD_GENERAL, "failed consuming additional record");
consumed = -5;
goto cleanup;
}
}
if (consumed != (int) size) {
log_debug(LD_GENERAL, "failed decoding message: wanted %d, got %d",
(int) size, consumed);
consumed = -6;
goto cleanup;
}
log_debug(LD_GENERAL, "decoded:\n%s", dns_message_str(dm));
cleanup:
buf_drain(buf, size);
tor_free(data);
return consumed;
}
//
// Utilities
/** Encode signed data to wire-format. */
int
dns_encode_signed_data(uint8_t **data, size_t *size, const dns_rr_t *crrsig,
const smartlist_t *crrset)
{
// LCOV_EXCL_START
tor_assert(data);
tor_assert(size);
tor_assert(crrsig);
tor_assert(crrset);
// LCOV_EXCL_STOP
tor_free(*data);
*size = 0;
int ret = 0;
buf_t *buf = buf_new();
ret = dns_encode_signed_data_to_buf(buf, crrsig, crrset);
if (ret >= 0) {
*data = (uint8_t *) buf_extract(buf, size);
}
buf_free(buf);
return ret;
}
/** Encode signed data to wire-format. */
int
dns_encode_signed_data_to_buf(buf_t *buf, const dns_rr_t *crrsig,
const smartlist_t *crrset)
{
// LCOV_EXCL_START
tor_assert(buf);
tor_assert(crrsig);
tor_assert(crrset);
// LCOV_EXCL_STOP
buf_t *stash = buf_new();
char *res = NULL;
size_t res_len = 0;
log_debug(LD_GENERAL, "pack sig: %s", dns_rr_str(crrsig));
buf_add(stash, (const char *) crrsig->rdata, crrsig->rdlength);
SMARTLIST_FOREACH_BEGIN(crrset, dns_rr_t *, crr) {
log_debug(LD_GENERAL, "pack rr: %s", dns_rr_str(crr));
if (dns_pack_rr(stash, crr) < 0) {
log_debug(LD_GENERAL, "failed packing rr");
res_len = -1;
goto cleanup;
}
} SMARTLIST_FOREACH_END(crr);
res = buf_extract(stash, &res_len);
buf_add(buf, (const char *) res, res_len);
log_debug(LD_GENERAL, "packed (%d): %s", (int) res_len,
hex_str((const char *) res, res_len));
cleanup:
buf_free(stash);
tor_free(res);
return (int) res_len;
}
/** Get canonical form of name. First transform the name to meet the following
* criterions: it is fully expanded, it contains only lowercase letters, and no
* wildcard expansion is applied.
* Then the name is converted to wire-format. */
uint8_t *
dns_encode_canonical_name(const dns_name_t *owner_name, size_t *sz_out)
{
// LCOV_EXCL_START
tor_assert(owner_name);
// LCOV_EXCL_STOP
*sz_out = 0;
uint8_t *data = NULL;
buf_t *buf = buf_new();
dns_name_t *name = dns_name_dup(owner_name);
tor_strlower(name->value);
if (dns_pack_name(buf, name) < 0) {
log_debug(LD_GENERAL, "failed packing name");
data = NULL;
goto cleanup;
}
data = (uint8_t *) buf_extract(buf, sz_out);
cleanup:
dns_name_free(name);
buf_free(buf);
return data;
}
/** Get canonical form of resource record. The record name is converted to
* lowercase, additionally all names within record types are converted to
* lowercase as well. For RRsig records the signature is removed. */
dns_rr_t *
dns_encode_canonical_rr(const dns_rr_t *drr, const dns_name_t *name,
const uint32_t original_ttl)
{
// LCOV_EXCL_START
tor_assert(drr);
tor_assert(drr->rrtype);
tor_assert(name);
// LCOV_EXCL_STOP
log_debug(LD_GENERAL, "canonicalize: %s", dns_rr_str(drr));
dns_rr_t *dcrr = dns_rr_dup(drr);
dns_name_free(dcrr->name);
dcrr->name = dns_name_dup(name);
tor_strlower(dcrr->name->value);
dcrr->ttl = original_ttl;
switch (dcrr->rrtype->value) {
case DNS_TYPE_NS:
if (dcrr->ns && dcrr->ns->value) {
tor_strlower(dcrr->ns->value);
}
break;
case DNS_TYPE_MD:
case DNS_TYPE_MF:
log_debug(LD_GENERAL, "dns canonical encode rdata: %s not implemented",
dcrr->rrtype->name);
break;
case DNS_TYPE_CNAME:
if (dcrr->cname && dcrr->cname->value) {
tor_strlower(dcrr->cname->value);
}
break;
case DNS_TYPE_SOA:
if (dcrr->soa->mname && dcrr->soa->mname->value) {
tor_strlower(dcrr->soa->mname->value);
}
if (dcrr->soa->rname && dcrr->soa->rname->value) {
tor_strlower(dcrr->soa->rname->value);
}
break;
case DNS_TYPE_MB:
case DNS_TYPE_MG:
case DNS_TYPE_MR:
log_debug(LD_GENERAL, "dns canonical encode rdata: %s not implemented",
dcrr->rrtype->name);
break;
case DNS_TYPE_PTR:
if (dcrr->ptr && dcrr->ptr->value) {
tor_strlower(dcrr->ptr->value);
}
break;
case DNS_TYPE_HINFO:
case DNS_TYPE_MINFO:
log_debug(LD_GENERAL, "dns canonical encode rdata: %s not implemented",
dcrr->rrtype->name);
break;
case DNS_TYPE_MX:
if (dcrr->mx->exchange && dcrr->mx->exchange->value) {
tor_strlower(dcrr->mx->exchange->value);
}
break;
case DNS_TYPE_RP:
case DNS_TYPE_AFSDB:
case DNS_TYPE_RT:
case DNS_TYPE_SIG:
case DNS_TYPE_PX:
case DNS_TYPE_NXT:
case DNS_TYPE_NAPTR:
case DNS_TYPE_KX:
case DNS_TYPE_SRV:
case DNS_TYPE_A6:
case DNS_TYPE_DNAME:
log_debug(LD_GENERAL, "dns canonical encode rdata: %s not implemented",
dcrr->rrtype->name);
break;
case DNS_TYPE_RRSIG:
if (dcrr->rrsig && dcrr->rrsig->signer_name &&
dcrr->rrsig->signer_name->value) {
tor_strlower(dcrr->rrsig->signer_name->value);
}
if (dcrr->rrsig && dcrr->rrsig->signature &&
dcrr->rrsig->signature_len > 0) {
tor_free(dcrr->rrsig->signature);
dcrr->rrsig->signature = NULL;
dcrr->rrsig->signature_len = 0;
}
break;
case DNS_TYPE_NSEC:
if (dcrr->nsec->next_domain_name &&
dcrr->nsec->next_domain_name->value) {
tor_strlower(dcrr->nsec->next_domain_name->value);
}
break;
default:
log_debug(LD_GENERAL, "unknown type: %s", dcrr->rrtype->name);
}
if (dns_encode_rr_rdata(dcrr) < 0) {
log_debug(LD_GENERAL, "failed encoding rdata");
}
return dcrr;
}
/** Get data from DNSKEY that is used for verifying the DNSSEC digest. */
uint8_t *
dns_encode_digest_data(const dns_rr_t *drr, size_t *sz_out)
{
// LCOV_EXCL_START
tor_assert(drr);
// LCOV_EXCL_STOP
*sz_out = 0;
uint8_t *data = NULL;
buf_t *buf = buf_new();
dns_name_t *name = dns_name_dup(drr->name);
tor_strlower(name->value);
if (dns_pack_name(buf, name) < 0) {
log_debug(LD_GENERAL, "failed packing name");
goto cleanup;
}
buf_add(buf, (const char *) drr->rdata, drr->rdlength);
data = (uint8_t *) buf_extract(buf, sz_out);
cleanup:
dns_name_free(name);
buf_free(buf);
return data;
}
/** Calculate the key tag of the given DNSKEY in <b>drr</b>. */
uint16_t
dns_encode_key_tag(const dns_rr_t *drr)
{
uint32_t ac = 0;
for (uint16_t i = 0; i < drr->rdlength; ++i) {
ac += (i & 1) ? drr->rdata[i] : drr->rdata[i] << 8;
}
ac += (ac >> 16) & 0xFFFF;
return (uint16_t) (ac & 0xFFFF);
}
/** Pack the given DNS <b>name</b> to wire-format. */
int
dns_pack_name(buf_t *buf, const dns_name_t *name)
{
// LCOV_EXCL_START
tor_assert(buf);
// LCOV_EXCL_STOP
buf_t *stash = buf_new();
char *res = NULL;
size_t res_len = 0;
log_debug(LD_GENERAL, "pack: %s", dns_name_str(name));
if (name && name->value && name->length > 1) {
char *ptr = name->value;
for (uint8_t i = 0; i < name->length; i++) {
if (i == name->length - 1 || name->value[i + 1] == '.') {
int label_len = (int) (&(name->value[i + 1]) - ptr);
if (label_len > 0) {
if (label_len > DNS_MAX_LABEL_LEN) {
log_debug(LD_GENERAL, "label too long: len %d, max: %d", label_len,
DNS_MAX_LABEL_LEN);
res_len = -1;
goto cleanup;
}
buf_add_printf(stash, "%c", (char) label_len);
buf_add(stash, ptr, label_len);
ptr = &(name->value[i + 2]);
}
}
}
}
buf_add(stash, "\0", 1);
res = buf_extract(stash, &res_len);
buf_add(buf, (const char *) res, res_len);
log_debug(LD_GENERAL, "packed (%d): %s", (int) res_len,
hex_str((const char *) res, res_len));
cleanup:
buf_free(stash);
tor_free(res);
return (int) res_len;
}
/** Consume wire-format data and interpret it as DNS name. */
int
dns_consume_name(dns_name_t *name, uint8_t **ptr, const uint8_t *data,
const size_t size)
{
return dns_consume_name_impl(name, ptr, 0, data, size);
}
int
dns_consume_name_impl(dns_name_t *name, uint8_t **ptr, uint8_t recursions,
const uint8_t *data, const size_t size)
{
// LCOV_EXCL_START
tor_assert(name);
tor_assert(*ptr);
tor_assert(data);
// LCOV_EXCL_STOP
size_t pos = (*ptr - data);
int consumed = 0;
buf_t *stash = buf_new();
size_t label_len;
dns_name_t *compr_name = dns_name_new();
if (recursions > 10) {
log_debug(LD_GENERAL, "too many pointers, maybe there's a loop");
consumed = -1;
goto cleanup;
}
if (pos > size) {
log_debug(LD_GENERAL, "no data left");
consumed = -2;
goto cleanup;
}
log_debug(LD_GENERAL, "consume: %s",
hex_str((const char *) *ptr, size - pos));
bool done = false;
while (!done) {
pos = (*ptr - data);
if (1 > size - pos) {
log_debug(LD_GENERAL, "invalid length: wanted %d, got %d", 1,
(int) (size - pos));
consumed = -3;
goto cleanup;
}
label_len = **ptr;
consumed += 1;
*ptr += 1;
if (label_len == 0x00) {
buf_add_string(stash, ".");
done = true;
} else if ((label_len & 0xc0) == 0xc0) {
pos = (*ptr - data);
if (1 > size - pos) {
log_debug(LD_GENERAL, "invalid length: wanted %d, got %d", 1,
(int) (size - pos));
consumed = -4;
goto cleanup;
}
uint16_t name_pos = ((label_len & DNS_MAX_LABEL_LEN) << 8) + **ptr;
consumed += 1;
*ptr += 1;
if (name_pos > size) {
log_debug(LD_GENERAL, "invalid name position: pos %d, max %d",
(int) name_pos, (int) size);
consumed = -5;
goto cleanup;
}
uint8_t *compr_ptr = (uint8_t *) &data[name_pos];
if (dns_consume_name_impl(compr_name, &compr_ptr, recursions + 1, data,
size) < 0) {
log_debug(LD_GENERAL, "invalid name compression");
consumed = -6;
goto cleanup;
}
if (buf_datalen(stash) > 0) {
buf_add_string(stash, ".");
}
buf_add_string(stash, compr_name->value);
done = true;
} else {
pos = (*ptr - data);
if (label_len > size - pos) {
log_debug(LD_GENERAL, "invalid length: wanted %d, got %d",
(int) label_len, (int) (size - pos));
consumed = -7;
goto cleanup;
}
if (buf_datalen(stash) > 0) {
buf_add_string(stash, ".");
}
buf_add(stash, (const char *) *ptr, label_len);
consumed += label_len;
*ptr += label_len;
}
}
size_t sz_out = 0;
tor_free(name->value);
name->value = buf_extract(stash, &sz_out);
name->length = (uint8_t) sz_out;
log_debug(LD_GENERAL, "consumed (%d): %s", consumed, name->value);
cleanup:
buf_free(stash);
dns_name_free(compr_name);
return consumed;
}
/** Comparator for sorting DNS types in ascending order. */
static int
dns_comperator_for_sorting_types_in_ascending_order(const void **a_,
const void **b_)
{
const dns_type_t *a = *a_,
*b = *b_;
return a->value - b->value;
}
/** Pack the given list of DNS <b>types</b> to wire-format. */
int
dns_pack_type_bitmaps(buf_t *buf, smartlist_t *types)
{
// LCOV_EXCL_START
tor_assert(buf);
tor_assert(types);
// LCOV_EXCL_STOP
buf_t *stash = buf_new();
uint8_t *bitmap = tor_malloc_zero(DNS_MAX_TYPE_BITMAP_LEN);
char *res = NULL;
size_t res_len = 0;
log_debug(LD_GENERAL, "pack: %s", dns_types_str(types));
if (smartlist_len(types) > 0) {
uint8_t active_window = 0;
uint8_t window = 0;
uint8_t subtype = 0;
smartlist_sort(types, dns_comperator_for_sorting_types_in_ascending_order);
SMARTLIST_FOREACH_BEGIN(types, dns_type_t *, type) {
window = type->value >> 8;
subtype = type->value & 0xff;
if (active_window != window) {
dns_buf_add_type_bitmap_field(stash, active_window, bitmap);
active_window = window;
memset(bitmap, 0, DNS_MAX_TYPE_BITMAP_LEN);
}
bitmap[subtype / 8] |= (0x80 >> (subtype % 8));
} SMARTLIST_FOREACH_END(type);
dns_buf_add_type_bitmap_field(stash, active_window, bitmap);
}
res = buf_extract(stash, &res_len);
buf_add(buf, (const char *) res, res_len);
log_debug(LD_GENERAL, "packed (%d): %s", (int) res_len,
hex_str((const char *) res, res_len));
buf_free(stash);
tor_free(bitmap);
tor_free(res);
return (int) res_len;
}
/** Write type bitmap to buffer. */
int
dns_buf_add_type_bitmap_field(buf_t *buf, const uint8_t window,
const uint8_t *bitmap)
{
// LCOV_EXCL_START
tor_assert(buf);
tor_assert(bitmap);
// LCOV_EXCL_STOP
uint8_t len = 0;
for (uint8_t i = 0; i < DNS_MAX_TYPE_BITMAP_LEN; i++) {
if (bitmap[i] && (i + 1) > len) {
len = (i + 1);
}
}
char *field = tor_malloc_zero(len + 2);
field[0] = window;
field[1] = len;
for (uint8_t i = 0; i < len; i++) {
field[i + 2] = bitmap[i];
}
buf_add(buf, field, len + 2);
tor_free(field);
return len + 2;
}
/** Consume wire-format data and interpret it as DNS types. */
int
dns_consume_type_bitmaps(smartlist_t *types, uint8_t **ptr,
const uint8_t *data, const size_t size)
{
// LCOV_EXCL_START
tor_assert(types);
tor_assert(*ptr);
tor_assert(data);
// LCOV_EXCL_STOP
size_t pos = (*ptr - data);
int consumed = 0;
if (pos > size) {
log_debug(LD_GENERAL, "no data left");
return -1;
}
log_debug(LD_GENERAL, "consume: %s",
hex_str((const char *) *ptr, size - pos));
smartlist_clear(types);
uint8_t window = 0;
uint8_t bitmap_len = 0;
bool done = (pos == size);
while (!done) {
if (2 > size - pos) {
log_debug(LD_GENERAL, "invalid length: wanted %d, got %d", 2,
(int) (size - pos));
return -2;
}
window = (*ptr)[0];
bitmap_len = (*ptr)[1];
consumed += 2;
*ptr += 2;
pos = (*ptr - data);
if (bitmap_len > size - pos) {
log_debug(LD_GENERAL, "invalid length: wanted %d, got %d",
(int) bitmap_len, (int) (size - pos));
return -3;
}
for (uint8_t byte = 0; byte < bitmap_len; byte++) {
for (uint8_t bit = 0; bit < 8; bit++) {
if ((*ptr)[byte] & (0x80 >> bit)) {
uint16_t value = (window * 256) + (byte * 8) + bit;
dns_type_t *type = dns_type_of(value);
smartlist_add(types, type);
}
}
}
consumed += bitmap_len;
*ptr += bitmap_len;
pos = (*ptr - data);
done = (size - pos) == 0;
}
log_debug(LD_GENERAL, "consumed (%d): %s", consumed, dns_types_str(types));
return consumed;
}
| 25.393103 | 79 | 0.635494 | [
"transform"
] |
2672a3c9d3220a77f9a925ea7e06f27c4cbe3918 | 1,788 | c | C | src/camera.c | matthewcpp/n64-sandbox | 7a4fb89b72468caaa436f387ffeb9161cf9b62e1 | [
"MIT"
] | 1 | 2021-05-28T05:54:04.000Z | 2021-05-28T05:54:04.000Z | src/camera.c | matthewcpp/n64-sandbox | 7a4fb89b72468caaa436f387ffeb9161cf9b62e1 | [
"MIT"
] | 1 | 2021-11-16T05:20:22.000Z | 2021-11-16T05:20:22.000Z | src/camera.c | matthewcpp/n64-sandbox | 7a4fb89b72468caaa436f387ffeb9161cf9b62e1 | [
"MIT"
] | 1 | 2021-09-29T12:54:51.000Z | 2021-09-29T12:54:51.000Z | #include "framework64/camera.h"
#include "framework64/matrix.h"
#include <string.h>
void fw64_camera_init(fw64Camera* camera) {
fw64_transform_init(&camera->transform);
camera->near = 0.1f;
camera->far = 1000.0f;
camera->fovy = 45.0f;
camera->aspect = 1.33f;
camera->transform.position.z = 5.0f;
fw64_camera_update_projection_matrix(camera);
fw64_camera_update_view_matrix(camera);
}
void fw64_camera_update_projection_matrix(fw64Camera* camera) {
#ifdef PLATFORM_N64
guPerspective(&camera->projection, &camera->perspNorm,
camera->fovy, camera->aspect, camera->near, camera->far, 1.0f);
#else
matrix_perspective(&camera->projection.m[0], camera->fovy, camera->aspect, camera->near, camera->far);
#endif
}
void fw64_camera_update_view_matrix(fw64Camera* camera) {
Vec3 forward, up, target;
fw64_transform_forward(&camera->transform, &forward);
fw64_transform_up(&camera->transform, &up);
vec3_add(&target, &camera->transform.position, &forward);
#ifdef PLATFORM_N64
guLookAt(&camera->view,
camera->transform.position.x, camera->transform.position.y, camera->transform.position.z,
target.x, target.y, target.z, up.x, up.y, up.z);
#else
matrix_camera_look_at(&camera->view.m[0], &camera->transform.position, &target, &up);
#endif
}
void fw64_camera_extract_frustum_planes(fw64Camera* camera, fw64Frustum* frustum) {
float projScreenMatrix[16];
#ifdef PLATFORM_N64
Mtx projViewMatrix;
guMtxCatL(&camera->view, &camera->projection, &projViewMatrix);
guMtxL2F((void*)&projScreenMatrix[0], &projViewMatrix);
#else
matrix_multiply(&projScreenMatrix[0], &camera->projection.m[0], &camera->view.m[0]);
#endif
fw64_frustum_set_from_matrix(frustum, &projScreenMatrix[0]);
}
| 30.827586 | 106 | 0.720917 | [
"transform"
] |
2674c82b14e6c2d28aff30329ef1216cf4e639d9 | 4,789 | h | C | src/prop/sat_solver_types.h | HasibShakur/CVC4 | 7a303390a65fd395a53085833d504acc312dc6a6 | [
"BSL-1.0"
] | null | null | null | src/prop/sat_solver_types.h | HasibShakur/CVC4 | 7a303390a65fd395a53085833d504acc312dc6a6 | [
"BSL-1.0"
] | null | null | null | src/prop/sat_solver_types.h | HasibShakur/CVC4 | 7a303390a65fd395a53085833d504acc312dc6a6 | [
"BSL-1.0"
] | null | null | null | /********************* */
/*! \file sat_solver_types.h
** \verbatim
** Original author: Dejan Jovanovic
** Major contributors: none
** Minor contributors (to current version): Morgan Deters, Liana Hadarean, Kshitij Bansal
** This file is part of the CVC4 project.
** Copyright (c) 2009-2013 New York University and The University of Iowa
** See the file COPYING in the top-level source directory for licensing
** information.\endverbatim
**
** \brief This class transforms a sequence of formulas into clauses.
**
** This class takes a sequence of formulas.
** It outputs a stream of clauses that is propositionally
** equi-satisfiable with the conjunction of the formulas.
** This stream is maintained in an online fashion.
**
** Unlike other parts of the system it is aware of the PropEngine's
** internals such as the representation and translation of [??? -Chris]
**/
#pragma once
#include "cvc4_private.h"
#include <string>
#include <sstream>
namespace CVC4 {
namespace prop {
/**
* Boolean values of the SAT solver.
*/
enum SatValue {
SAT_VALUE_UNKNOWN,
SAT_VALUE_TRUE,
SAT_VALUE_FALSE
};
/** Helper function for inverting a SatValue */
inline SatValue invertValue(SatValue v)
{
if(v == SAT_VALUE_UNKNOWN) return SAT_VALUE_UNKNOWN;
else if(v == SAT_VALUE_TRUE) return SAT_VALUE_FALSE;
else return SAT_VALUE_TRUE;
}
/**
* A variable of the SAT solver.
*/
typedef uint64_t SatVariable;
/**
* Undefined SAT solver variable.
*/
const SatVariable undefSatVariable = SatVariable(-1);
/**
* A SAT literal is a variable or an negated variable.
*/
class SatLiteral {
/**
* The value holds the variable and a bit noting if the variable is negated.
*/
uint64_t d_value;
public:
/**
* Construct an undefined SAT literal.
*/
SatLiteral()
: d_value(undefSatVariable)
{}
/**
* Construct a literal given a possible negated variable.
*/
SatLiteral(SatVariable var, bool negated = false) {
d_value = var + var + (int)negated;
}
/**
* Returns the variable of the literal.
*/
SatVariable getSatVariable() const {
return d_value >> 1;
}
/**
* Returns true if the literal is a negated variable.
*/
bool isNegated() const {
return d_value & 1;
}
/**
* Negate the given literal.
*/
SatLiteral operator ~ () const {
return SatLiteral(getSatVariable(), !isNegated());
}
/**
* Compare two literals for equality.
*/
bool operator == (const SatLiteral& other) const {
return d_value == other.d_value;
}
/**
* Compare two literals for dis-equality.
*/
bool operator != (const SatLiteral& other) const {
return !(*this == other);
}
/**
* Returns a string representation of the literal.
*/
std::string toString() const {
std::ostringstream os;
os << (isNegated()? "~" : "") << getSatVariable() << " ";
return os.str();
}
/**
* Returns the hash value of a literal.
*/
size_t hash() const {
return (size_t)d_value;
}
uint64_t toInt() const {
return d_value;
}
/**
* Returns true if the literal is undefined.
*/
bool isNull() const {
return getSatVariable() == undefSatVariable;
}
};
/**
* A constant representing a undefined literal.
*/
const SatLiteral undefSatLiteral = SatLiteral(undefSatVariable);
/**
* Helper for hashing the literals.
*/
struct SatLiteralHashFunction {
inline size_t operator() (const SatLiteral& literal) const {
return literal.hash();
}
};
/**
* A SAT clause is a vector of literals.
*/
typedef std::vector<SatLiteral> SatClause;
/**
* Each object in the SAT solver, such as as variables and clauses, can be assigned a life span,
* so that the SAT solver can (or should) remove them when the lifespan is over.
*/
enum SatSolverLifespan
{
/**
* The object should stay forever and never be removed
*/
SAT_LIFESPAN_PERMANENT,
/**
* The object can be removed at any point when it becomes unnecessary.
*/
SAT_LIFESPAN_REMOVABLE,
/**
* The object must be removed as soon as the SAT solver exits the search context
* where the object got introduced.
*/
SAT_LIFESPAN_SEARCH_CONTEXT_STRICT,
/**
* The object can be removed when SAT solver exits the search context where the object
* got introduced, but can be kept at the solver discretion.
*/
SAT_LIFESPAN_SEARCH_CONTEXT_LENIENT,
/**
* The object must be removed as soon as the SAT solver exits the user-level context where
* the object got introduced.
*/
SAT_LIFESPAN_USER_CONTEXT_STRICT,
/**
* The object can be removed when the SAT solver exits the user-level context where
* the object got introduced.
*/
SAT_LIFESPAN_USER_CONTEXT_LENIENT
};
}
}
| 22.913876 | 96 | 0.669033 | [
"object",
"vector"
] |
2677bffe6d9fe389b09df6a170d1debac2a5cb5f | 9,696 | h | C | trtlab/nvrpc/include/nvrpc/life_cycle_batching.h | ryanolson/yais | 67b870ae0766c97e81eb3fb2abb7cdebee26ed38 | [
"BSD-3-Clause"
] | 226 | 2019-01-29T14:33:00.000Z | 2022-03-25T09:22:48.000Z | trtlab/nvrpc/include/nvrpc/life_cycle_batching.h | ryanolson/yais | 67b870ae0766c97e81eb3fb2abb7cdebee26ed38 | [
"BSD-3-Clause"
] | 18 | 2019-02-01T03:38:33.000Z | 2021-01-14T08:06:13.000Z | trtlab/nvrpc/include/nvrpc/life_cycle_batching.h | ryanolson/yais | 67b870ae0766c97e81eb3fb2abb7cdebee26ed38 | [
"BSD-3-Clause"
] | 40 | 2019-01-30T07:53:49.000Z | 2022-02-16T02:55:21.000Z | /* Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of NVIDIA CORPORATION nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#pragma once
#include "nvrpc/interfaces.h"
#include "nvrpc/life_cycle_streaming.h"
namespace nvrpc {
template<typename Request, typename Response>
class LifeCycleBatchingNew : public LifeCycleStreaming<Request, Response>
{
public:
using LifeCycleStreaming<Request, Response>::LifeCycleStreaming;
using Stream = typename LifeCycleStreaming<Request, Response>::ServerStream;
protected:
virtual void ExecuteRPC(std::vector<Request>&, std::shared_ptr<Stream>) = 0;
private:
void RequestReceived(Request&&, std::shared_ptr<Stream>) final override;
void RequestsFinished(std::shared_ptr<Stream>) final override;
std::vector<Request> m_Requests;
};
template<class Request, class Response>
void LifeCycleBatchingNew<Request, Response>::RequestReceived(Request&& request,
std::shared_ptr<Stream> stream)
{
m_Requests.push_back(std::move(request));
}
template<class Request, class Response>
void LifeCycleBatchingNew<Request, Response>::RequestsFinished(std::shared_ptr<Stream> stream)
{
ExecuteRPC(m_Requests, stream);
}
/**
* @brief LifeCycle State Machine All-In, then All-Out BATCHING
*
* Client sends message until it says it is done, then execute the RPC
* on all received items, then for each item, return a response on the
* stream in the same order the requests were received.
*
* @tparam Request
* @tparam Response
*/
template<class Request, class Response>
class LifeCycleBatching : public IContextLifeCycle
{
public:
using RequestType = Request;
using ResponseType = Response;
using ServiceQueueFuncType = std::function<void(
::grpc::ServerContext*, ::grpc_impl::ServerAsyncReaderWriter<ResponseType, RequestType>*,
::grpc::CompletionQueue*, ::grpc::ServerCompletionQueue*, void*)>;
using ExecutorQueueFuncType =
std::function<void(::grpc::ServerContext*,
::grpc_impl::ServerAsyncReaderWriter<ResponseType, RequestType>*, void*)>;
virtual ~LifeCycleBatching() override {}
protected:
LifeCycleBatching() = default;
void SetQueueFunc(ExecutorQueueFuncType q_fn) { m_QueuingFunc = q_fn; }
virtual void ExecuteRPC(std::vector<RequestType>&, std::vector<ResponseType>&) = 0;
virtual void OnRequestReceived(const RequestType&) {}
void FinishResponse() final override;
void CancelResponse() final override;
private:
// IContext Methods
bool RunNextState(bool ok) final override;
void Reset() final override;
bool StateRequestDone(bool);
bool StateReadDone(bool);
bool StateWriteDone(bool);
bool StateFinishedDone(bool);
// Function pointers
ExecutorQueueFuncType m_QueuingFunc;
bool (LifeCycleBatching<RequestType, ResponseType>::*m_NextState)(bool);
std::vector<RequestType> m_Requests;
std::vector<ResponseType> m_Responses;
std::unique_ptr<::grpc::ServerContext> m_Context;
std::unique_ptr<::grpc_impl::ServerAsyncReaderWriter<ResponseType, RequestType>> m_Stream;
typename std::vector<ResponseType>::const_iterator m_ResponseIterator;
public:
template<class RequestFuncType, class ServiceType>
static ServiceQueueFuncType BindServiceQueueFunc(
/*
std::function<void(
ServiceType*, ServerContextType*,
ServerAsyncReaderWriter<ResponseType, RequestType>*,
CompletionQueue*, ServerCompletionQueue*, void*)>
*/
RequestFuncType request_fn, ServiceType* service_type)
{
return std::bind(request_fn, service_type,
std::placeholders::_1, // ServerContext*
std::placeholders::_2, // AsyncReaderWriter<ResponseType, RequestType>*
std::placeholders::_3, // CQ*
std::placeholders::_4, // ServerCQ*
std::placeholders::_5 // Tag
);
}
static ExecutorQueueFuncType BindExecutorQueueFunc(ServiceQueueFuncType service_q_fn,
::grpc::ServerCompletionQueue* cq)
{
return std::bind(service_q_fn,
std::placeholders::_1, // ServerContext*
std::placeholders::_2, // AsyncReaderWriter<ResponseType, RequestType>*
cq, cq,
std::placeholders::_3 // Tag
);
}
};
// Implementations
template<class Request, class Response>
bool LifeCycleBatching<Request, Response>::RunNextState(bool ok)
{
return (this->*m_NextState)(ok);
}
template<class Request, class Response>
void LifeCycleBatching<Request, Response>::Reset()
{
OnLifeCycleReset();
m_Requests.clear();
m_Responses.clear();
m_Context.reset(new ::grpc::ServerContext);
m_Stream.reset(new ::grpc_impl::ServerAsyncReaderWriter<ResponseType, RequestType>(m_Context.get()));
m_NextState = &LifeCycleBatching<RequestType, ResponseType>::StateRequestDone;
m_QueuingFunc(m_Context.get(), m_Stream.get(), IContext::Tag());
}
template<class Request, class Response>
bool LifeCycleBatching<Request, Response>::StateRequestDone(bool ok)
{
if(!ok) return false;
OnLifeCycleStart();
m_Requests.emplace(m_Requests.end());
m_NextState = &LifeCycleBatching<RequestType, ResponseType>::StateReadDone;
m_Stream->Read(&m_Requests.back(), IContext::Tag());
return true;
}
template<class Request, class Response>
bool LifeCycleBatching<Request, Response>::StateReadDone(bool ok)
{
if(ok)
{
// Execute Callback for the Request item received
OnRequestReceived(m_Requests.back());
// Stream is still open, so pull off another request
m_Requests.emplace(m_Requests.end());
m_NextState = &LifeCycleBatching<RequestType, ResponseType>::StateReadDone;
m_Stream->Read(&m_Requests.back(), IContext::Tag());
}
else
{
// Client has signaled it will not send any more requests
// Remove the Request we didn't actually use
m_Requests.pop_back();
// Execute Batched RPC on all Requests
ExecuteRPC(m_Requests, m_Responses);
}
return true;
}
template<class Request, class Response>
bool LifeCycleBatching<Request, Response>::StateWriteDone(bool ok)
{
if(!ok) return false;
if(m_ResponseIterator != m_Responses.cend())
{
if(m_ResponseIterator + 1 != m_Responses.cend())
{
m_NextState = &LifeCycleBatching<RequestType, ResponseType>::StateWriteDone;
m_Stream->Write(*m_ResponseIterator, IContext::Tag());
// The following hangs even though the client is guaranteed to have sent WritesDone();
// thus, all the response writes from the server should not rely on any of the previous
// messages https://grpc.io/grpc/cpp/md_doc_cpp_perf_notes.html
// m_Stream->Write(*m_ResponseIterator, ::grpc::WriteOptions().set_buffer_hint(),
// IContext::Tag());
m_ResponseIterator++;
}
else
{
m_NextState = &LifeCycleBatching<RequestType, ResponseType>::StateFinishedDone;
m_Stream->WriteAndFinish(*m_ResponseIterator, ::grpc::WriteOptions(),
::grpc::Status::OK, IContext::Tag());
}
}
else
{
m_NextState = &LifeCycleBatching<RequestType, ResponseType>::StateFinishedDone;
m_Stream->Finish(::grpc::Status::OK, IContext::Tag());
}
return true;
}
template<class Request, class Response>
bool LifeCycleBatching<Request, Response>::StateFinishedDone(bool ok)
{
return false;
}
template<class Request, class Response>
void LifeCycleBatching<Request, Response>::FinishResponse()
{
m_ResponseIterator = m_Responses.cbegin();
StateWriteDone(true);
}
template<class Request, class Response>
void LifeCycleBatching<Request, Response>::CancelResponse()
{
m_NextState = &LifeCycleBatching<RequestType, ResponseType>::StateFinishedDone;
m_Stream->Finish(::grpc::Status::CANCELLED, IContext::Tag());
}
} // namespace nvrpc
| 37.581395 | 105 | 0.689872 | [
"vector"
] |
b7f2382be8da381a2d9ee67b85fed57df9853a4a | 3,375 | c | C | ej2/main.c | shirosweets/Lab3 | 3e3d2bac0de5473c1941f7b2518c4fe19d5e43ce | [
"MIT"
] | null | null | null | ej2/main.c | shirosweets/Lab3 | 3e3d2bac0de5473c1941f7b2518c4fe19d5e43ce | [
"MIT"
] | null | null | null | ej2/main.c | shirosweets/Lab3 | 3e3d2bac0de5473c1941f7b2518c4fe19d5e43ce | [
"MIT"
] | null | null | null | /* First, the standard lib includes, alphabetically ordered */
#include <stdio.h>
#include <stdlib.h>
/* Then, this project's includes, alphabetically ordered */
#include "array_helpers.h"
#include "list.h"
/* Maximum allowed length of the array */
static const unsigned int MAX_SIZE = 100000u;
void print_help(char *program_name) {
/* Print the usage help of this program. */
printf("Usage: %s <input file path>\n\n"
"Compute average for the list of numbers in file.\n"
"\n",
program_name);
}
char *parse_filepath(int argc, char *argv[]) {
/* Parse the filepath given by command line argument. */
char *result = NULL;
if (argc < 2) {
print_help(argv[0]);
exit(EXIT_FAILURE);
}
result = argv[1];
return (result);
}
/* Ejemplo de uso del TAD Lista
fun promedio (l : List of float)ret r : float
var largo : nat
var elem : float
var laux : List of float
laux := copy(l)
r := 0.0
largo := length(l)
do(not is_empty(laux))
elem := head(laux)
r := r + elem
tail(laux)
od
destroy(laux)
r := r / largo
end proc
*/
float average(list l) { // Función promedio
//Needs implementation.
if(length(l)==0){
return 0; // Retorna 0
}
type_elem largo;
float r;
float elem;
list laux=NULL; // La inicializo en NULL
laux=copy_list(l); // Copia la lista l
//laux=copy_list(l, laux); // Copia la lista l tomada de argumento a laux
r=0.0;
largo=length(l);
while(laux!=NULL){
elem=head(laux);
r=r+elem;
laux=tail(laux);
}
destroy(laux); // Destruye la lista auxiliar
r=r/largo;
return r;
}
list array_to_list(int array[], unsigned int length) { // Convierte de array a lista (?)
list l=empty(); // Initialize the list
for (unsigned int i = 0u; i < length; ++i) {
l=addL(l, array[i]);
}
return l; // Return list
}
int main(int argc, char *argv[]) {
printf(" ********* Inicio programa *********\n\n");
char *filepath = NULL;
//FILE *file = NULL;
/* parse the filepath given in command line arguments */
filepath = parse_filepath(argc, argv);
/* create an array of MAX_SIZE elements */
int array[MAX_SIZE];
/* parse the file to fill the array and obtain the actual length */
unsigned int length = array_from_file(array, MAX_SIZE, filepath);
/* show the array in the screen */
array_dump(array, length);
/* transform from array to our list type */
list l = array_to_list(array, length);
/* call the average function */
printf("\n The average is: %.2f \n", average(l)); // ACA
destroy(l);
printf("\n ********* Fin programa *********\n");
return (EXIT_SUCCESS);
}
/* PARA CORRER
gcc -Wall -Werror -Wextra -pedantic -std=c99 -c list.c array_helpers.c
gcc -Wall -Werror -Wextra -pedantic -std=c99 -o average *.o main.c
./average input/all-negative-100.in
./average input/all-positive-100.in
./average input/example-sorted.in
./average input/empty.in
./average input/example-unsorted.in
DEBUGEAR
gcc -Wall -Werror -Wextra -pedantic -std=c99 -g -c list.c array_helpers.c
gcc -Wall -Werror -Wextra -pedantic -std=c99 -g -o average *.o main.c
gdb ./average input/all-negative-100.in
*/ | 25.763359 | 88 | 0.606519 | [
"transform"
] |
b7f92e7db7c0a25233c511c1224efed1ae48dc40 | 20,200 | c | C | src/framing/src/framesync64.c | daveol/liquid-dsp | f11733208e3d0da928a0dc2111cdb2b0c4817cef | [
"MIT"
] | 2 | 2020-02-02T16:16:45.000Z | 2020-02-03T16:32:58.000Z | src/framing/src/framesync64.c | daveol/liquid-dsp | f11733208e3d0da928a0dc2111cdb2b0c4817cef | [
"MIT"
] | null | null | null | src/framing/src/framesync64.c | daveol/liquid-dsp | f11733208e3d0da928a0dc2111cdb2b0c4817cef | [
"MIT"
] | 1 | 2020-01-20T04:55:05.000Z | 2020-01-20T04:55:05.000Z | /*
* Copyright (c) 2007 - 2019 Joseph Gaeddert
*
* 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.
*/
//
// framesync64.c
//
// basic frame synchronizer
//
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <complex.h>
#include <assert.h>
#include "liquid.internal.h"
#define DEBUG_FRAMESYNC64 1
#define DEBUG_FRAMESYNC64_PRINT 0
#define DEBUG_FILENAME "framesync64_internal_debug.m"
#define DEBUG_BUFFER_LEN (1600)
#define FRAMESYNC64_ENABLE_EQ 0
// push samples through detection stage
void framesync64_execute_seekpn(framesync64 _q,
float complex _x);
// step receiver mixer, matched filter, decimator
// _q : frame synchronizer
// _x : input sample
// _y : output symbol
int framesync64_step(framesync64 _q,
float complex _x,
float complex * _y);
// push samples through synchronizer, saving received p/n symbols
void framesync64_execute_rxpreamble(framesync64 _q,
float complex _x);
// receive payload symbols
void framesync64_execute_rxpayload(framesync64 _q,
float complex _x);
// framesync64 object structure
struct framesync64_s {
// callback
framesync_callback callback; // user-defined callback function
void * userdata; // user-defined data structure
framesyncstats_s framesyncstats; // frame statistic object (synchronizer)
framedatastats_s framedatastats; // frame statistic object (packet statistics)
// synchronizer objects
unsigned int m; // filter delay (symbols)
float beta; // filter excess bandwidth factor
qdetector_cccf detector; // pre-demod detector
float tau_hat; // fractional timing offset estimate
float dphi_hat; // carrier frequency offset estimate
float phi_hat; // carrier phase offset estimate
float gamma_hat; // channel gain estimate
nco_crcf mixer; // coarse carrier frequency recovery
// timing recovery objects, states
firpfb_crcf mf; // matched filter decimator
unsigned int npfb; // number of filters in symsync
int mf_counter; // matched filter output timer
unsigned int pfb_index; // filterbank index
#if FRAMESYNC64_ENABLE_EQ
eqlms_cccf equalizer; // equalizer (trained on p/n sequence)
#endif
// preamble
float complex preamble_pn[64]; // known 64-symbol p/n sequence
float complex preamble_rx[64]; // received p/n symbols
// payload decoder
float complex payload_rx [630]; // received payload symbols with pilots
float complex payload_sym[600]; // received payload symbols
unsigned char payload_dec[ 72]; // decoded payload bytes
qpacketmodem dec; // packet demodulator/decoder
qpilotsync pilotsync; // pilot extraction, carrier recovery
int payload_valid; // did payload pass crc?
// status variables
enum {
FRAMESYNC64_STATE_DETECTFRAME=0, // detect frame (seek p/n sequence)
FRAMESYNC64_STATE_RXPREAMBLE, // receive p/n sequence
FRAMESYNC64_STATE_RXPAYLOAD, // receive payload data
} state;
unsigned int preamble_counter; // counter: num of p/n syms received
unsigned int payload_counter; // counter: num of payload syms received
#if DEBUG_FRAMESYNC64
int debug_enabled; // debugging enabled?
int debug_objects_created; // debugging objects created?
windowcf debug_x; // debug: raw input samples
#endif
};
// create framesync64 object
// _callback : callback function invoked when frame is received
// _userdata : user-defined data object passed to callback
framesync64 framesync64_create(framesync_callback _callback,
void * _userdata)
{
framesync64 q = (framesync64) malloc(sizeof(struct framesync64_s));
q->callback = _callback;
q->userdata = _userdata;
q->m = 7; // filter delay (symbols)
q->beta = 0.3f; // excess bandwidth factor
unsigned int i;
// generate p/n sequence
msequence ms = msequence_create(7, 0x0089, 1);
for (i=0; i<64; i++) {
q->preamble_pn[i] = (msequence_advance(ms) ? M_SQRT1_2 : -M_SQRT1_2);
q->preamble_pn[i] += (msequence_advance(ms) ? M_SQRT1_2 : -M_SQRT1_2)*_Complex_I;
}
msequence_destroy(ms);
// create frame detector
unsigned int k = 2; // samples/symbol
q->detector = qdetector_cccf_create_linear(q->preamble_pn, 64, LIQUID_FIRFILT_ARKAISER, k, q->m, q->beta);
qdetector_cccf_set_threshold(q->detector, 0.5f);
// create symbol timing recovery filters
q->npfb = 32; // number of filters in the bank
q->mf = firpfb_crcf_create_rnyquist(LIQUID_FIRFILT_ARKAISER, q->npfb,k,q->m,q->beta);
#if FRAMESYNC64_ENABLE_EQ
// create equalizer
unsigned int p = 3;
q->equalizer = eqlms_cccf_create_lowpass(2*k*p+1, 0.4f);
eqlms_cccf_set_bw(q->equalizer, 0.05f);
#endif
// create down-coverters for carrier phase tracking
q->mixer = nco_crcf_create(LIQUID_NCO);
// create payload demodulator/decoder object
int check = LIQUID_CRC_24;
int fec0 = LIQUID_FEC_NONE;
int fec1 = LIQUID_FEC_GOLAY2412;
int mod_scheme = LIQUID_MODEM_QPSK;
q->dec = qpacketmodem_create();
qpacketmodem_configure(q->dec, 72, check, fec0, fec1, mod_scheme);
//qpacketmodem_print(q->dec);
assert( qpacketmodem_get_frame_len(q->dec)==600 );
// create pilot synchronizer
q->pilotsync = qpilotsync_create(600, 21);
assert( qpilotsync_get_frame_len(q->pilotsync)==630);
// reset global data counters
framesync64_reset_framedatastats(q);
#if DEBUG_FRAMESYNC64
// set debugging flags, objects to NULL
q->debug_enabled = 0;
q->debug_objects_created = 0;
q->debug_x = NULL;
#endif
// reset state and return
framesync64_reset(q);
return q;
}
// destroy frame synchronizer object, freeing all internal memory
void framesync64_destroy(framesync64 _q)
{
#if DEBUG_FRAMESYNC64
// clean up debug objects (if created)
if (_q->debug_objects_created) {
windowcf_destroy(_q->debug_x);
}
#endif
// destroy synchronization objects
qdetector_cccf_destroy(_q->detector); // frame detector
firpfb_crcf_destroy (_q->mf); // matched filter
nco_crcf_destroy (_q->mixer); // coarse NCO
qpacketmodem_destroy (_q->dec); // payload demodulator
qpilotsync_destroy (_q->pilotsync); // pilot synchronizer
#if FRAMESYNC64_ENABLE_EQ
eqlms_cccf_destroy (_q->equalizer); // LMS equalizer
#endif
// free main object memory
free(_q);
}
// print frame synchronizer object internals
void framesync64_print(framesync64 _q)
{
printf("framesync64:\n");
framedatastats_print(&_q->framedatastats);
}
// reset frame synchronizer object
void framesync64_reset(framesync64 _q)
{
// reset binary pre-demod synchronizer
qdetector_cccf_reset(_q->detector);
// reset carrier recovery objects
nco_crcf_reset(_q->mixer);
// reset symbol timing recovery state
firpfb_crcf_reset(_q->mf);
// reset state
_q->state = FRAMESYNC64_STATE_DETECTFRAME;
_q->preamble_counter= 0;
_q->payload_counter = 0;
// reset frame statistics
_q->framesyncstats.evm = 0.0f;
}
// execute frame synchronizer
// _q : frame synchronizer object
// _x : input sample array [size: _n x 1]
// _n : number of input samples
void framesync64_execute(framesync64 _q,
float complex * _x,
unsigned int _n)
{
unsigned int i;
for (i=0; i<_n; i++) {
#if DEBUG_FRAMESYNC64
if (_q->debug_enabled)
windowcf_push(_q->debug_x, _x[i]);
#endif
switch (_q->state) {
case FRAMESYNC64_STATE_DETECTFRAME:
// detect frame (look for p/n sequence)
framesync64_execute_seekpn(_q, _x[i]);
break;
case FRAMESYNC64_STATE_RXPREAMBLE:
// receive p/n sequence symbols
framesync64_execute_rxpreamble(_q, _x[i]);
break;
case FRAMESYNC64_STATE_RXPAYLOAD:
// receive payload symbols
framesync64_execute_rxpayload(_q, _x[i]);
break;
default:
fprintf(stderr,"error: framesync64_exeucte(), unknown/unsupported state\n");
exit(1);
}
}
}
//
// internal methods
//
// execute synchronizer, seeking p/n sequence
// _q : frame synchronizer object
// _x : input sample
// _sym : demodulated symbol
void framesync64_execute_seekpn(framesync64 _q,
float complex _x)
{
// push through pre-demod synchronizer
float complex * v = qdetector_cccf_execute(_q->detector, _x);
// check if frame has been detected
if (v != NULL) {
// get estimates
_q->tau_hat = qdetector_cccf_get_tau (_q->detector);
_q->gamma_hat = qdetector_cccf_get_gamma(_q->detector);
_q->dphi_hat = qdetector_cccf_get_dphi (_q->detector);
_q->phi_hat = qdetector_cccf_get_phi (_q->detector);
#if DEBUG_FRAMESYNC64_PRINT
printf("***** frame detected! tau-hat:%8.4f, dphi-hat:%8.4f, gamma:%8.2f dB\n",
_q->tau_hat, _q->dphi_hat, 20*log10f(_q->gamma_hat));
#endif
// set appropriate filterbank index
if (_q->tau_hat > 0) {
_q->pfb_index = (unsigned int)( _q->tau_hat * _q->npfb) % _q->npfb;
_q->mf_counter = 0;
} else {
_q->pfb_index = (unsigned int)((1.0f+_q->tau_hat) * _q->npfb) % _q->npfb;
_q->mf_counter = 1;
}
// output filter scale
firpfb_crcf_set_scale(_q->mf, 0.5f / _q->gamma_hat);
// set frequency/phase of mixer
nco_crcf_set_frequency(_q->mixer, _q->dphi_hat);
nco_crcf_set_phase (_q->mixer, _q->phi_hat );
// update state
_q->state = FRAMESYNC64_STATE_RXPREAMBLE;
// run buffered samples through synchronizer
unsigned int buf_len = qdetector_cccf_get_buf_len(_q->detector);
framesync64_execute(_q, v, buf_len);
}
}
// step receiver mixer, matched filter, decimator
// _q : frame synchronizer
// _x : input sample
// _y : output symbol
int framesync64_step(framesync64 _q,
float complex _x,
float complex * _y)
{
// mix sample down
float complex v;
nco_crcf_mix_down(_q->mixer, _x, &v);
nco_crcf_step (_q->mixer);
// push sample into filterbank
firpfb_crcf_push (_q->mf, v);
firpfb_crcf_execute(_q->mf, _q->pfb_index, &v);
#if FRAMESYNC64_ENABLE_EQ
// push sample through equalizer
eqlms_cccf_push(_q->equalizer, v);
#endif
// increment counter to determine if sample is available
_q->mf_counter++;
int sample_available = (_q->mf_counter >= 1) ? 1 : 0;
// set output sample if available
if (sample_available) {
#if FRAMESYNC64_ENABLE_EQ
// compute equalizer output
eqlms_cccf_execute(_q->equalizer, &v);
#endif
// set output
*_y = v;
// decrement counter by k=2 samples/symbol
_q->mf_counter -= 2;
}
// return flag
return sample_available;
}
// execute synchronizer, receiving p/n sequence
// _q : frame synchronizer object
// _x : input sample
// _sym : demodulated symbol
void framesync64_execute_rxpreamble(framesync64 _q,
float complex _x)
{
// step synchronizer
float complex mf_out = 0.0f;
int sample_available = framesync64_step(_q, _x, &mf_out);
// compute output if timeout
if (sample_available) {
// save output in p/n symbols buffer
#if FRAMESYNC64_ENABLE_EQ
unsigned int delay = 2*_q->m + 3; // delay from matched filter and equalizer
#else
unsigned int delay = 2*_q->m; // delay from matched filter
#endif
if (_q->preamble_counter >= delay) {
unsigned int index = _q->preamble_counter-delay;
_q->preamble_rx[index] = mf_out;
#if FRAMESYNC64_ENABLE_EQ
// train equalizer
eqlms_cccf_step(_q->equalizer, _q->preamble_pn[index], mf_out);
#endif
}
// update p/n counter
_q->preamble_counter++;
// update state
if (_q->preamble_counter == 64 + delay)
_q->state = FRAMESYNC64_STATE_RXPAYLOAD;
}
}
// execute synchronizer, receiving payload
// _q : frame synchronizer object
// _x : input sample
// _sym : demodulated symbol
void framesync64_execute_rxpayload(framesync64 _q,
float complex _x)
{
// step synchronizer
float complex mf_out = 0.0f;
int sample_available = framesync64_step(_q, _x, &mf_out);
// compute output if timeout
if (sample_available) {
// save payload symbols (modem input/output)
_q->payload_rx[_q->payload_counter] = mf_out;
// increment counter
_q->payload_counter++;
if (_q->payload_counter == 630) {
// recover data symbols from pilots
qpilotsync_execute(_q->pilotsync, _q->payload_rx, _q->payload_sym);
// decode payload
_q->payload_valid = qpacketmodem_decode(_q->dec,
_q->payload_sym,
_q->payload_dec);
// update statistics
_q->framedatastats.num_frames_detected++;
_q->framedatastats.num_headers_valid += _q->payload_valid;
_q->framedatastats.num_payloads_valid += _q->payload_valid;
_q->framedatastats.num_bytes_received += _q->payload_valid ? 64 : 0;
// invoke callback
if (_q->callback != NULL) {
// set framesyncstats internals
_q->framesyncstats.evm = qpilotsync_get_evm(_q->pilotsync);
_q->framesyncstats.rssi = 20*log10f(_q->gamma_hat);
_q->framesyncstats.cfo = nco_crcf_get_frequency(_q->mixer);
_q->framesyncstats.framesyms = _q->payload_sym;
_q->framesyncstats.num_framesyms = 600;
_q->framesyncstats.mod_scheme = LIQUID_MODEM_QPSK;
_q->framesyncstats.mod_bps = 2;
_q->framesyncstats.check = LIQUID_CRC_24;
_q->framesyncstats.fec0 = LIQUID_FEC_NONE;
_q->framesyncstats.fec1 = LIQUID_FEC_GOLAY2412;
// invoke callback method
_q->callback(&_q->payload_dec[0], // header is first 8 bytes
_q->payload_valid,
&_q->payload_dec[8], // payload is last 64 bytes
64,
_q->payload_valid,
_q->framesyncstats,
_q->userdata);
}
// reset frame synchronizer
framesync64_reset(_q);
return;
}
}
}
// enable debugging
void framesync64_debug_enable(framesync64 _q)
{
// create debugging objects if necessary
#if DEBUG_FRAMESYNC64
if (_q->debug_objects_created)
return;
// create debugging objects
_q->debug_x = windowcf_create(DEBUG_BUFFER_LEN);
// set debugging flags
_q->debug_enabled = 1;
_q->debug_objects_created = 1;
#else
fprintf(stderr,"framesync64_debug_enable(): compile-time debugging disabled\n");
#endif
}
// disable debugging
void framesync64_debug_disable(framesync64 _q)
{
// disable debugging
#if DEBUG_FRAMESYNC64
_q->debug_enabled = 0;
#else
fprintf(stderr,"framesync64_debug_enable(): compile-time debugging disabled\n");
#endif
}
// print debugging information
void framesync64_debug_print(framesync64 _q,
const char * _filename)
{
#if DEBUG_FRAMESYNC64
if (!_q->debug_objects_created) {
fprintf(stderr,"error: framesync64_debug_print(), debugging objects don't exist; enable debugging first\n");
return;
}
unsigned int i;
float complex * rc;
FILE* fid = fopen(_filename,"w");
fprintf(fid,"%% %s: auto-generated file", _filename);
fprintf(fid,"\n\n");
fprintf(fid,"clear all;\n");
fprintf(fid,"close all;\n\n");
fprintf(fid,"n = %u;\n", DEBUG_BUFFER_LEN);
// write x
fprintf(fid,"x = zeros(1,n);\n");
windowcf_read(_q->debug_x, &rc);
for (i=0; i<DEBUG_BUFFER_LEN; i++)
fprintf(fid,"x(%4u) = %12.4e + j*%12.4e;\n", i+1, crealf(rc[i]), cimagf(rc[i]));
fprintf(fid,"\n\n");
fprintf(fid,"figure;\n");
fprintf(fid,"plot(1:length(x),real(x), 1:length(x),imag(x));\n");
fprintf(fid,"ylabel('received signal, x');\n");
// write p/n sequence
fprintf(fid,"preamble_pn = zeros(1,64);\n");
rc = _q->preamble_pn;
for (i=0; i<64; i++)
fprintf(fid,"preamble_pn(%4u) = %12.4e + 1i*%12.4e;\n", i+1, crealf(rc[i]), cimagf(rc[i]));
// write p/n symbols
fprintf(fid,"preamble_rx = zeros(1,64);\n");
rc = _q->preamble_rx;
for (i=0; i<64; i++)
fprintf(fid,"preamble_rx(%4u) = %12.4e + 1i*%12.4e;\n", i+1, crealf(rc[i]), cimagf(rc[i]));
// write raw payload symbols
unsigned int payload_sym_len = 600;
fprintf(fid,"payload_rx = zeros(1,%u);\n", payload_sym_len);
rc = _q->payload_rx;
for (i=0; i<payload_sym_len; i++)
fprintf(fid,"payload_rx(%4u) = %12.4e + j*%12.4e;\n", i+1, crealf(rc[i]), cimagf(rc[i]));
// write payload symbols
fprintf(fid,"payload_syms = zeros(1,%u);\n", payload_sym_len);
rc = _q->payload_sym;
for (i=0; i<payload_sym_len; i++)
fprintf(fid,"payload_syms(%4u) = %12.4e + j*%12.4e;\n", i+1, crealf(rc[i]), cimagf(rc[i]));
fprintf(fid,"figure;\n");
fprintf(fid,"plot(real(payload_syms),imag(payload_syms),'o');\n");
fprintf(fid,"xlabel('in-phase');\n");
fprintf(fid,"ylabel('quadrature phase');\n");
fprintf(fid,"grid on;\n");
fprintf(fid,"axis([-1 1 -1 1]*1.5);\n");
fprintf(fid,"axis square;\n");
fprintf(fid,"\n\n");
fclose(fid);
printf("framesync64/debug: results written to %s\n", _filename);
#else
fprintf(stderr,"framesync64_debug_print(): compile-time debugging disabled\n");
#endif
}
// reset frame data statistics
void framesync64_reset_framedatastats(framesync64 _q)
{
framedatastats_reset(&_q->framedatastats);
}
// retrieve frame data statistics
framedatastats_s framesync64_get_framedatastats(framesync64 _q)
{
return _q->framedatastats;
}
| 34.295416 | 116 | 0.620545 | [
"object"
] |
b7fa8fc7cd831a0460c34776eafc6977d819c382 | 2,438 | h | C | Zwicky18/mainwindow.h | christian-kardach/Zwicky18 | e3cd8cd43902f94c5f17c5c711fc9cbc93589ea9 | [
"MIT"
] | null | null | null | Zwicky18/mainwindow.h | christian-kardach/Zwicky18 | e3cd8cd43902f94c5f17c5c711fc9cbc93589ea9 | [
"MIT"
] | null | null | null | Zwicky18/mainwindow.h | christian-kardach/Zwicky18 | e3cd8cd43902f94c5f17c5c711fc9cbc93589ea9 | [
"MIT"
] | null | null | null | #ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QThread>
#include <QFileDialog>
#include "opencv2/core.hpp"
#include "opencv2/opencv.hpp"
#include "opencv2/imgcodecs/imgcodecs.hpp"
#include "opencv2/videoio/videoio.hpp"
#include "usbcameras.h"
#include "previewscenewidget.h"
#include "previewscene.h"
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
struct CachedImages
{
CachedImages() {}
CachedImages(cv::Mat *_sourceImage, cv::Mat *_stabilizedImage)
{
sourceImage = _sourceImage;
stabilizedImage = _stabilizedImage;
}
bool cached = false;
bool cachedStabalized = false;
cv::Mat *sourceImage;
cv::Mat *stabilizedImage;
cv::Mat T;
};
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private:
Ui::MainWindow *ui;
// QThread* usbCamerasThread;
USBCameras* usbCameras;
PreviewSceneWidget* previewScene;
std::vector<CachedImages> cachedImages;
cv::VideoCapture* videoSource;
int activeFrame = 0;
public slots:
void addCamera(QString name, QVariant v);
void changeCamera(int index);
void hasBrightness(bool enabled, int emin, int emax);
void hasExposure(bool enabled, int emin, int emax);
void hasGamma(bool enabled, int emin, int emax);
void hasWhiteBalance(bool enabled, int emin, int emax);
void hasGain(bool enabled, int emin, int emax);
void hasContrast(bool enabled, int emin, int emax);
void hasSaturation(bool enabled, int emin, int emax);
void hasFocus(bool enabled, int emin, int emax);
void hasZoom(bool enabled, int emin, int emax);
void hasHue(bool enabled, int emin, int emax);
void hasSharpness(bool enabled, int emin, int emax);
void hasBacklightcomp(bool enabled, int emin, int emax);
void hasPowerlineFreq(bool enabled, int emin, int emax);
void hasAutoExposure(bool enabled, int checked);
void hasAutoGain(bool enabled, int checked);
void hasAutoWhiteBalance(bool enabled, int checked);
void hasAutoFocus(bool enabled, int checked);
void updateStatusBar(QString message);
QImage cvMatToQImageVideo(const cv::Mat *inMat);
QImage cvMatToQImage( const cv::Mat *inMat );
void actionOpenVideoFile();
void getSourceVideoInfo();
void frameChanged(int);
void mainUpdateLoop();
};
#endif // MAINWINDOW_H
| 26.215054 | 66 | 0.71329 | [
"vector"
] |
b7fd153688d30649ae8a504eeb4f95f396b4092d | 1,002 | h | C | src/dfm/protocol/STParsedJSON.h | dfm-official/dfm | 97f133aa87b17c760b90f2358d6ba10bc7ad9d1f | [
"ISC"
] | null | null | null | src/dfm/protocol/STParsedJSON.h | dfm-official/dfm | 97f133aa87b17c760b90f2358d6ba10bc7ad9d1f | [
"ISC"
] | null | null | null | src/dfm/protocol/STParsedJSON.h | dfm-official/dfm | 97f133aa87b17c760b90f2358d6ba10bc7ad9d1f | [
"ISC"
] | null | null | null |
#ifndef RIPPLE_PROTOCOL_STPARSEDJSON_H_INCLUDED
#define RIPPLE_PROTOCOL_STPARSEDJSON_H_INCLUDED
#include <ripple/protocol/STArray.h>
#include <boost/optional.hpp>
namespace ripple {
class STParsedJSONObject
{
public:
STParsedJSONObject (std::string const& name, Json::Value const& json);
STParsedJSONObject () = delete;
STParsedJSONObject (STParsedJSONObject const&) = delete;
STParsedJSONObject& operator= (STParsedJSONObject const&) = delete;
~STParsedJSONObject () = default;
boost::optional <STObject> object;
Json::Value error;
};
class STParsedJSONArray
{
public:
STParsedJSONArray (std::string const& name, Json::Value const& json);
STParsedJSONArray () = delete;
STParsedJSONArray (STParsedJSONArray const&) = delete;
STParsedJSONArray& operator= (STParsedJSONArray const&) = delete;
~STParsedJSONArray () = default;
boost::optional <STArray> array;
Json::Value error;
};
}
#endif
| 16.16129 | 74 | 0.700599 | [
"object"
] |
b7ff91d0c40c12f295a5a471339fc24b012e0e44 | 4,677 | h | C | pubsuber/src/Executor.h | sandvikcode/pubsuber | 1083c20e71fc057accf1bc0e7fbb31008efaf885 | [
"MIT"
] | 8 | 2019-12-20T14:18:39.000Z | 2021-05-16T04:26:14.000Z | pubsuber/src/Executor.h | sandvikcode/pubsuber | 1083c20e71fc057accf1bc0e7fbb31008efaf885 | [
"MIT"
] | 2 | 2019-12-20T14:18:14.000Z | 2020-07-20T10:13:09.000Z | pubsuber/src/Executor.h | sandvikcode/pubsuber | 1083c20e71fc057accf1bc0e7fbb31008efaf885 | [
"MIT"
] | 2 | 2020-02-18T17:56:38.000Z | 2022-02-01T21:33:53.000Z | #pragma once
#include <grpc++/grpc++.h>
#include <atomic>
#include <chrono>
#include <functional>
#include <list>
#include <memory>
#include <thread>
#include <unordered_map>
#include <utility>
#include <vector>
#include "ModAckIterator.h"
#include "SubscriptionPullIterator.h"
#include "Trimpl.h"
#include "google/pubsub/v1/pubsub.grpc.pb.h"
#include "pubsuber/Pubsuber.h"
#include "PSLog.h"
namespace pubsuber {
const auto kSoManyMilliseconds = 1000000000ms;
const auto kSoManySeconds = 1000000000s;
//**********************************************************************************************************************
/**
* Implementation of this class is thread safe unless otherwise noted
*/
struct Executor : public std::enable_shared_from_this<Executor> {
using SubscriptionName = std::string;
using IteratorMap = std::unordered_map<SubscriptionName, ModAckIteratorPtr>;
using PullIteratorMap = std::unordered_map<SubscriptionName, SubscriptionPullIteratorPtr>;
using Callback = Subscription::Callback;
template <class IteratorContainerType>
struct ThreadDataBlock {
template <class Block>
void ExecuteUnderMutex(Block b, bool notify) {
if (std::unique_lock l(_condMutex); true) {
b();
}
if (notify) {
_cond.notify_all();
}
}
void Stop();
// Called under lock inside
void ClearInput();
void ClearRemoved();
// Called without lock inside
void MergeInputToActive();
// Called under lock inside
void RemoveFromActive();
template <typename Lambda>
void ForEachActive(Lambda b) {
for (auto &it : _activeIterators) {
b(it);
}
}
// Called under lock inside with notify
template <class IteratorType>
void AddIterator(const std::string &subscription, IteratorType &&it) {
if (std::unique_lock l(_condMutex); true) {
_inputIterators.insert_or_assign(subscription, std::forward<IteratorType>(it));
}
_cond.notify_one();
}
// Called under lock inside with notify
void RemoveIterator(const std::string &subscription) {
if (std::unique_lock l(_condMutex); true) {
_removedIterators.push_back(subscription);
}
_cond.notify_one();
}
std::unique_ptr<google::pubsub::v1::Subscriber::Stub> _subscriber;
std::atomic<bool> _needStop{false};
std::mutex _condMutex;
std::condition_variable _cond;
// managed under the lock on any thread
IteratorContainerType _inputIterators;
// managed under the lock on any thread
std::list<SubscriptionName> _removedIterators;
// Managed on current thread only
IteratorContainerType _activeIterators;
// Must be certainly last one, i.e. after all the fields that can be used in the thread func
// So the rule of thumb: it is last one.
std::thread _thread;
};
private:
Executor(const Executor &) = delete;
Executor(Executor &&) = delete;
Executor &operator=(const Executor &) = delete;
Executor &operator=(Executor &&) = delete;
// PULL thread
void PullThreadFunc();
// ACK thread
void AckThreadFunc();
// Must be called on PULL thread only
std::chrono::milliseconds Pull();
// Must be called on ACK thread only
std::chrono::milliseconds ProcessModAcks();
void SetupLogger(ClientOptions &opts);
public:
Executor(ClientOptions &&opts);
void ApplyPolicies(const RetryCountPolicy &countPolicy, const MaxRetryTimePolicy &timePolicy, ExponentialBackoffPolicy &backoffPolicy);
// Thread safe
void StopThreads();
// Thread safe
void AddIterator(const std::string &fullSubscriptionName, Callback &cb);
// Thread safe
void RemoveIterator(const std::string &fullSubscriptionName) noexcept(true);
// Thread safe
template <class Block>
void ExecuteUnderAckMutex(Block b, bool notify) {
_ackThread.ExecuteUnderMutex(std::forward<Block>(b), notify);
}
// Must be called from ACK thread
void ReportKeepAliveMetric(size_t count);
public:
ClientOptions _options;
Trimpl _tr;
RetryCountPolicy _countPolicy;
MaxRetryTimePolicy _timePolicy;
ExponentialBackoffPolicy _backoffPolicy;
// Ack thread data
ThreadDataBlock<IteratorMap> _ackThread;
// Pull thread data
ThreadDataBlock<PullIteratorMap> _pullThread;
// Be aware under which lock this field is managed
// WARNING: Could only be used from one thread so far, ACK
std::shared_ptr<MetricSink> _metricsSinks;
};
} // namespace pubsuber
| 30.769737 | 139 | 0.66068 | [
"vector"
] |
4d002ae6e5e6cfba8c35eb7303784c0f3dbdab7f | 665 | h | C | src/AsyncLog.h | hfq0219/cppSocketServer | d291c6bfe1d0eaa64837dce5211a1c98ae78462c | [
"Apache-2.0"
] | null | null | null | src/AsyncLog.h | hfq0219/cppSocketServer | d291c6bfe1d0eaa64837dce5211a1c98ae78462c | [
"Apache-2.0"
] | null | null | null | src/AsyncLog.h | hfq0219/cppSocketServer | d291c6bfe1d0eaa64837dce5211a1c98ae78462c | [
"Apache-2.0"
] | null | null | null | #pragma once
#include <string>
#include <memory>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <fstream>
#include <vector>
#include "Buffer.h"
class AsyncLog
{
private:
std::string log_file;
std::shared_ptr<Buffer> cur_buff;
std::shared_ptr<Buffer> next_buff;
std::vector<std::shared_ptr<Buffer>> buffs;
std::vector<std::shared_ptr<Buffer>> buffs_to_write;
std::mutex lock_;
std::condition_variable cond_;
std::thread thread_;
static bool thread_running;
public:
AsyncLog(std::string log_file);
~AsyncLog();
void append(std::string str);
void thread_fun();
void thread_exit();
}; | 22.166667 | 56 | 0.696241 | [
"vector"
] |
4d05f6de8b9e655da3509b03b0ae2b48c129619f | 4,381 | h | C | tools/fconv/include/convMx1.h | avr-aics-riken/CIOlib | f8c844284db0075f47ca8d97e69a70da6e54b2d0 | [
"BSD-2-Clause"
] | 2 | 2015-03-17T17:31:24.000Z | 2019-01-31T15:16:58.000Z | tools/fconv/include/convMx1.h | avr-aics-riken/CIOlib | f8c844284db0075f47ca8d97e69a70da6e54b2d0 | [
"BSD-2-Clause"
] | null | null | null | tools/fconv/include/convMx1.h | avr-aics-riken/CIOlib | f8c844284db0075f47ca8d97e69a70da6e54b2d0 | [
"BSD-2-Clause"
] | null | null | null | #ifndef _CONVMX1_H_
#define _CONVMX1_H_
/*
* fconv (File Converter)
*
* CIOlib - Cartesian Input / Output library
*
* Copyright (c) 2013-2014 Advanced Institute for Computational Science, RIKEN.
* All rights reserved.
*
*/
#include "conv.h"
#include "convOutput.h"
/**
* @file convMx1.h
* @brief convMx1 Class Header
* @author aics
* @date 2013/11/14
*/
class convMx1 : public CONV {
public:
convOutput *ConvOut;
typedef std::map<int,int> headT;
//vector<stepinfo> m_stepList; ///<並列処理用インデックスリスト
vector<step_rank_info> m_StepRankList; ///<並列処理用インデックスリスト
public:
/** コンストラクタ */
convMx1();
/** デストラクタ */
~convMx1();
public:
/**
* @brief Mx1の実行
* @return エラーコード
*/
bool exec();
/**
* @brief 並列形状 nijkをnijkでコンバートして出力
* @param[in] fp 出力ファイルポインタ
* @param[in] inPath dfiのディレクトリパス
* @param[in] l_step 出力step番号
* @param[in] l_dtime 出力時刻
* @param[in] d_type データタイプ
* @param[in] mio 分割出力指示
* @param[in] div 分割数
* @param[in] sz サイズ
* @param[in] dfi dfi
* @param[in] DFI_Process cio_Process
* @param[in] mapHeadX
* @param[in] mapHeadY
* @param[in] mapHeadZ
* @param[out] min 最小値
* @param[out] max 最大値
*/
bool
convMx1_out_nijk(FILE* fp,
std::string inPath,
int l_step,
double l_dtime,
CIO::E_CIO_DTYPE d_type,
bool mio,
int div[3],
int sz[3],
cio_DFI* dfi,
cio_Process* DFI_Process,
headT mapHeadX,
headT mapHeadY,
headT mapHeadZ,
double* min,
double* max);
/**
* @brief 並列形状 nijkをijknまたは ijknをijknにコンバートして出力
* @param[in] fp 出力ファイルポインタ
* @param[in] inPath dfiのディレクトリパス
* @param[in] l_step 出力step番号
* @param[in] l_dtime 出力時刻
* @param[in] d_type データタイプ
* @param[in] mio 分割出力指示
* @param[in] div 分割数
* @param[in] sz サイズ
* @param[in] dfi dfi
* @param[in] DFI_Process cio_Process
* @param[in] mapHeadX
* @param[in] mapHeadY
* @param[in] mapHeadZ
* @param[out] min 最小値
* @param[out] max 最大値
*/
bool
convMx1_out_ijkn(FILE* fp,
std::string inPath,
int l_step,
double l_dtime,
CIO::E_CIO_DTYPE d_type,
bool mio,
int div[3],
int sz[3],
cio_DFI* dfi,
cio_Process* DFI_Process,
headT mapHeadX,
headT mapHeadY,
headT mapHeadZ,
double* min,
double* max);
/**
* @brief 補間処理
* @param[in] src_old 1つ前の層
* @param[in] src 処理する層
* @param[out] outArray 足しこむ配列
* @param[in] ivar_src 図心データの コンポーネント位置
* @param[in] ivar_out 格子データの コンポーネント位置
*/
bool InterPolate(cio_Array* src_old, cio_Array* src, cio_Array* outArray,
int ivar_src, int ivar_out);
/**
* @brief 配列のゼロクリア
* @param[out] data 配列
* @param[in] ivar_out コンポーネント位置
*/
template<class T>
void zeroClearArray(cio_TypeArray<T>* data, int ivar_out);
/**
* @brief 図心データを格子点に補間
* @param[out] O 格子点データ
* @param[in] S 図心データ
* @param[in] ivar_out 格子データの コンポーネント位置
* @param[in] ivar_src 図心データの コンポーネント位置
*/
template<class T>
bool setGridData_XY(cio_TypeArray<T>* O,
cio_TypeArray<T>* S,
int ivar_out,
int ivar_src);
/**
* @brief 内部の格子点のデータを重み付けでで割る
* @param[out] O 格子点データ
* @param[in] ivar_out コンポーネント位置
*/
template<class T>
void VolumeDataDivide8(cio_TypeArray<T> *O, int ivar_out);
/**
* @brief NIJK配列をスカラーのIJK配列にコピーコントロール
* @param[in] src コピー元配列
* @param[in] ivar コピーするコンポーネント位置
* @return IJKにコピーされて配列ポインタ
*/
cio_Array* nijk_to_ijk(cio_Array* src, int ivar);
/**
* @brief NIJK配列をスカラーのIJK配列にコピー
* @param[in] S コピー元配列
* @param[in] O コピー先配列
* @param[in] ivar コピーするコンポーネント位置
*/
template<class T>
void copyArray_nijk_ijk(cio_TypeArray<T> *S, cio_TypeArray<T> *O, int ivar);
};
//inline関数
#include "inline/convMx1_inline.h"
#endif // _CONVMX1_H_
| 23.809783 | 79 | 0.551244 | [
"vector"
] |
4d0b37b92df644461cd6f08c20540ecd6b63ecdc | 1,002 | h | C | inc/header.h | david-c-miller/coordinate-conversion | e84cd40ceef53feb9ca95a007057618c5625b0ec | [
"Apache-2.0"
] | null | null | null | inc/header.h | david-c-miller/coordinate-conversion | e84cd40ceef53feb9ca95a007057618c5625b0ec | [
"Apache-2.0"
] | 1 | 2016-12-16T22:15:05.000Z | 2016-12-16T22:15:05.000Z | inc/header.h | david-c-miller/coordinate-conversion | e84cd40ceef53feb9ca95a007057618c5625b0ec | [
"Apache-2.0"
] | null | null | null | /*
Copyright 2016-2017 David C. Miller
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.
*/
/* *************************************
header.h
coded by David Miller
mill2723 at msu dot edu
this file contains important header
files used through this program
****************************************/
#ifndef HEADER_H
#define HEADER_H
#include <iostream>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <cstdlib>
#include <string>
#include <vector>
#include <cmath>
#endif
| 23.857143 | 74 | 0.687625 | [
"vector"
] |
4d0b3d1d4715fdb7b35fc6a2bc76d783f8a65324 | 12,742 | c | C | libs/asset/test/test_loader_mesh_obj.c | BastianBlokland/volo | bcb037a84fdb8a45d5bf05dc83048f2879527f7a | [
"MIT"
] | 1 | 2022-02-25T10:28:49.000Z | 2022-02-25T10:28:49.000Z | libs/asset/test/test_loader_mesh_obj.c | BastianBlokland/volo | bcb037a84fdb8a45d5bf05dc83048f2879527f7a | [
"MIT"
] | null | null | null | libs/asset/test/test_loader_mesh_obj.c | BastianBlokland/volo | bcb037a84fdb8a45d5bf05dc83048f2879527f7a | [
"MIT"
] | null | null | null | #include "asset.h"
#include "check_spec.h"
#include "core_alloc.h"
#include "core_array.h"
#include "ecs.h"
#include "utils_internal.h"
static const struct {
String id;
String text;
AssetMeshVertex vertices[16];
usize vertexCount;
AssetMeshIndex indices[16];
usize indexCount;
} g_testData[] = {
{
.id = string_static("vert_positions.obj"),
.text = string_static("v 1.0 4.0 7.0 \n"
"v 2.0 5.0 8.0 \n"
"v 3.0 6.0 9.0 \n"
"f 1 2 3 \n"),
.vertices =
{
{{1, 4, 7}, .normal = {0, 0, 1}, .tangent = {1, 0, 0, 1}},
{{2, 5, 8}, .normal = {0, 0, 1}, .tangent = {1, 0, 0, 1}},
{{3, 6, 9}, .normal = {0, 0, 1}, .tangent = {1, 0, 0, 1}},
},
.vertexCount = 3,
.indices = {0, 1, 2},
.indexCount = 3,
},
{
.id = string_static("vert_normals.obj"),
.text = string_static("v 1.0 4.0 7.0\n"
"v 2.0 5.0 8.0\n"
"v 3.0 6.0 9.0\n"
"vn 1.0 0.0 0.0\n"
"vn 0.0 1.0 0.0\n"
"vn 0.0 0.0 1.0\n"
"f 1//1 2//2 3//3 \n"),
.vertices =
{
{{1, 4, 7}, .normal = {1, 0, 0}, .tangent = {1, 0, 0, 1}},
{{2, 5, 8}, .normal = {0, 1, 0}, .tangent = {1, 0, 0, 1}},
{{3, 6, 9}, .normal = {0, 0, 1}, .tangent = {1, 0, 0, 1}},
},
.vertexCount = 3,
.indices = {0, 1, 2},
.indexCount = 3,
},
{
.id = string_static("vert_texcoords.obj"),
.text = string_static("v 1.0 4.0 7.0\n"
"v 2.0 5.0 8.0\n"
"v 3.0 6.0 9.0\n"
"vt 0.1 0.5\n"
"vt 0.3 0.5\n"
"vt 0.5 0.5\n"
"f 1/1 2/2 3/3 \n"),
.vertices =
{
{{1, 4, 7}, .normal = {0, 0, 1}, .tangent = {1, 0, 0, 1}, .texcoord = {0.1f, 0.5f}},
{{2, 5, 8}, .normal = {0, 0, 1}, .tangent = {1, 0, 0, 1}, .texcoord = {0.3f, 0.5f}},
{{3, 6, 9}, .normal = {0, 0, 1}, .tangent = {1, 0, 0, 1}, .texcoord = {0.5f, 0.5f}},
},
.vertexCount = 3,
.indices = {0, 1, 2},
.indexCount = 3,
},
{
.id = string_static("prefixed_face_elems.obj"),
.text = string_static("v 1.0 4.0 7.0\n"
"v 2.0 5.0 8.0\n"
"v 3.0 6.0 9.0\n"
"vt 0.1 0.5\n"
"vt 0.3 0.5\n"
"vt 0.5 0.5\n"
"vn 1.0 0.0 0.0\n"
"vn 0.0 1.0 0.0\n"
"vn 0.0 0.0 1.0\n"
"f v1/vt1/vn-3 v2/vt2/vn-2 v3/vt3/vn-1\n"),
.vertices =
{
{{1, 4, 7}, .normal = {1, 0, 0}, .tangent = {1, 0, 0, 1}, .texcoord = {0.1f, 0.5f}},
{{2, 5, 8}, .normal = {0, 1, 0}, .tangent = {1, 0, 0, 1}, .texcoord = {0.3f, 0.5f}},
{{3, 6, 9}, .normal = {0, 0, 1}, .tangent = {1, 0, 0, 1}, .texcoord = {0.5f, 0.5f}},
},
.vertexCount = 3,
.indices = {0, 1, 2},
.indexCount = 3,
},
{
.id = string_static("deduplicate_vertices.obj"),
.text = string_static("v 1.0 4.0 7.0\n"
"v 2.0 5.0 8.0\n"
"v 3.0 6.0 9.0\n"
"v 1.0 4.0 7.0\n"
"v 2.0 5.0 8.0\n"
"v 3.0 6.0 9.0\n"
"f 1 2 3 \n"
"f 4 5 6 \n"
"f 1 2 3 \n"),
.vertices =
{
{{1, 4, 7}, .normal = {0, 0, 1}, .tangent = {1, 0, 0, 1}},
{{2, 5, 8}, .normal = {0, 0, 1}, .tangent = {1, 0, 0, 1}},
{{3, 6, 9}, .normal = {0, 0, 1}, .tangent = {1, 0, 0, 1}},
},
.vertexCount = 3,
.indices = {0, 1, 2, 0, 1, 2, 0, 1, 2},
.indexCount = 9,
},
{
.id = string_static("triangulate.obj"),
.text = string_static("v -0.5 -0.5 0.0 \n"
"v 0.5 -0.5 0.0 \n"
"v -0.5 0.5 0.0 \n"
"v 0.5 0.5 0.0 \n"
"f 1 2 3 4 \n"),
.vertices =
{
{{-0.5, -0.5, 0}, .normal = {0, 0, 1}, .tangent = {1, 0, 0, 1}},
{{+0.5, -0.5, 0}, .normal = {0, 0, 1}, .tangent = {1, 0, 0, 1}},
{{-0.5, +0.5, 0}, .normal = {0, 0, 1}, .tangent = {1, 0, 0, 1}},
{{+0.5, +0.5, 0}, .normal = {0, 0, 1}, .tangent = {1, 0, 0, 1}},
},
.vertexCount = 4,
.indices = {0, 1, 2, 0, 2, 3},
.indexCount = 6,
},
{
.id = string_static("negative_indices.obj"),
.text = string_static("v 1.0 2.0 3.0 \n"
"v 4.0 5.0 6.0 \n"
"v 7.0 8.0 9.0 \n"
"f -3 -2 -1 \n"
"v 10.0 11.0 12.0 \n"
"v 13.0 14.0 15.0 \n"
"v 16.0 17.0 18.0 \n"
"f -1 -2 -3 \n"),
.vertices =
{
{{1, 2, 3}, .normal = {0, 0, 1}, .tangent = {1, 0, 0, 1}},
{{4, 5, 6}, .normal = {0, 0, 1}, .tangent = {1, 0, 0, 1}},
{{7, 8, 9}, .normal = {0, 0, 1}, .tangent = {1, 0, 0, 1}},
{{16, 17, 18}, .normal = {0, 0, 1}, .tangent = {1, 0, 0, 1}},
{{13, 14, 15}, .normal = {0, 0, 1}, .tangent = {1, 0, 0, 1}},
{{10, 11, 12}, .normal = {0, 0, 1}, .tangent = {1, 0, 0, 1}},
},
.vertexCount = 6,
.indices = {0, 1, 2, 3, 4, 5},
.indexCount = 6,
},
{
.id = string_static("comments.obj"),
.text = string_static("# Hello World\n"
"v 1.0 4.0 7.0 \n"
"#Another comment\n"
"v 2.0 5.0 8.0 \n"
"#Another comment\n"
"#Another comment\n"
"v 3.0 6.0 9.0 \n"
"f 1 2 3 \n"
"# Comment at the end"),
.vertices =
{
{{1, 4, 7}, .normal = {0, 0, 1}, .tangent = {1, 0, 0, 1}},
{{2, 5, 8}, .normal = {0, 0, 1}, .tangent = {1, 0, 0, 1}},
{{3, 6, 9}, .normal = {0, 0, 1}, .tangent = {1, 0, 0, 1}},
},
.vertexCount = 3,
.indices = {0, 1, 2},
.indexCount = 3,
},
{
.id = string_static("whitespace.obj"),
.text = string_static(" v \t 1.0 \t 4.0 7.0 \r\n"
"\tv\t2.0\t5.0\t8.0\n"
"\t\t v \t 3.0 6.0 9.0 \n"
"f\t 1 \t2 \t3 \r\n"),
.vertices =
{
{{1, 4, 7}, .normal = {0, 0, 1}, .tangent = {1, 0, 0, 1}},
{{2, 5, 8}, .normal = {0, 0, 1}, .tangent = {1, 0, 0, 1}},
{{3, 6, 9}, .normal = {0, 0, 1}, .tangent = {1, 0, 0, 1}},
},
.vertexCount = 3,
.indices = {0, 1, 2},
.indexCount = 3,
},
};
static const struct {
String id;
String text;
} g_errorTestData[] = {
{
.id = string_static("positive-out-of-bounds-index.obj"),
.text = string_static("v 1.0 4.0 7.0 \n"
"v 2.0 5.0 8.0 \n"
"v 3.0 6.0 9.0 \n"
"f 1 2 4 \n"),
},
{
.id = string_static("negative-out-of-bounds-index.obj"),
.text = string_static("v 1.0 4.0 7.0 \n"
"v 2.0 5.0 8.0 \n"
"v 3.0 6.0 9.0 \n"
"f 1 2 -4 \n"),
},
{
.id = string_static("no-faces.obj"),
.text = string_static("v -0.5 -0.5 0.0 \n"
"v 0.5 -0.5 0.0 \n"
"v -0.5 0.5 0.0 \n"
"v 0.5 0.5 0.0 \n"),
},
{
.id = string_static("invalid.obj"),
.text = string_static("Hello World"),
},
};
ecs_view_define(ManagerView) { ecs_access_write(AssetManagerComp); }
ecs_view_define(AssetView) { ecs_access_read(AssetMeshComp); }
ecs_module_init(loader_mesh_obj_test_module) {
ecs_register_view(ManagerView);
ecs_register_view(AssetView);
}
spec(loader_mesh_obj) {
EcsDef* def = null;
EcsWorld* world = null;
EcsRunner* runner = null;
setup() {
def = ecs_def_create(g_alloc_heap);
asset_register(def);
ecs_register_module(def, loader_mesh_obj_test_module);
world = ecs_world_create(g_alloc_heap, def);
runner = ecs_runner_create(g_alloc_heap, world, EcsRunnerFlags_None);
}
it("can load obj meshes") {
AssetMemRecord records[array_elems(g_testData)];
for (usize i = 0; i != array_elems(g_testData); ++i) {
records[i] = (AssetMemRecord){.id = g_testData[i].id, .data = g_testData[i].text};
}
asset_manager_create_mem(world, AssetManagerFlags_None, records, array_elems(g_testData));
ecs_world_flush(world);
for (usize i = 0; i != array_elems(g_testData); ++i) {
AssetManagerComp* manager = ecs_utils_write_first_t(world, ManagerView, AssetManagerComp);
const EcsEntityId asset = asset_lookup(world, manager, records[i].id);
asset_acquire(world, asset);
asset_test_wait(runner);
check_require(ecs_world_has_t(world, asset, AssetLoadedComp));
const AssetMeshComp* mesh = ecs_utils_read_t(world, AssetView, asset, AssetMeshComp);
// Verify the vertices.
check_require(mesh->vertexCount == g_testData[i].vertexCount);
for (usize j = 0; j != g_testData[i].vertexCount; ++j) {
const AssetMeshVertex* vert = &mesh->vertices[j];
const AssetMeshVertex* vertExpected = &g_testData[i].vertices[j];
check(geo_vector_equal(vert->position, vertExpected->position, 1e-6f));
check(geo_vector_equal(vert->normal, vertExpected->normal, 1e-6f));
check(geo_vector_equal(vert->tangent, vertExpected->tangent, 1e-6f));
check(geo_vector_equal(vert->texcoord, vertExpected->texcoord, 1e-6f));
}
// Verify the indices.
check_require(mesh->indexCount == g_testData[i].indexCount);
for (usize j = 0; j != g_testData[i].indexCount; ++j) {
check_eq_int(mesh->indices[j], g_testData[i].indices[j]);
}
};
}
it("can unload obj mesh assets") {
const AssetMemRecord record = {.id = string_lit("mesh.obj"), .data = g_testData[0].text};
asset_manager_create_mem(world, AssetManagerFlags_None, &record, 1);
ecs_world_flush(world);
AssetManagerComp* manager = ecs_utils_write_first_t(world, ManagerView, AssetManagerComp);
const EcsEntityId asset = asset_lookup(world, manager, string_lit("mesh.obj"));
asset_acquire(world, asset);
asset_test_wait(runner);
check(ecs_world_has_t(world, asset, AssetMeshComp));
asset_release(world, asset);
asset_test_wait(runner);
check(!ecs_world_has_t(world, asset, AssetMeshComp));
}
it("fails when loading invalid obj files") {
AssetMemRecord records[array_elems(g_errorTestData)];
for (usize i = 0; i != array_elems(g_errorTestData); ++i) {
records[i] = (AssetMemRecord){.id = g_errorTestData[i].id, .data = g_errorTestData[i].text};
}
asset_manager_create_mem(world, AssetManagerFlags_None, records, array_elems(g_errorTestData));
ecs_world_flush(world);
for (usize i = 0; i != array_elems(g_errorTestData); ++i) {
AssetManagerComp* manager = ecs_utils_write_first_t(world, ManagerView, AssetManagerComp);
const EcsEntityId asset = asset_lookup(world, manager, records[i].id);
asset_acquire(world, asset);
asset_test_wait(runner);
check(ecs_world_has_t(world, asset, AssetFailedComp));
check(!ecs_world_has_t(world, asset, AssetMeshComp));
}
}
teardown() {
ecs_runner_destroy(runner);
ecs_world_destroy(world);
ecs_def_destroy(def);
}
}
| 39.08589 | 100 | 0.431957 | [
"mesh"
] |
4d0f8ebfed0f99384e791fcb2a7537e927e11a13 | 3,734 | h | C | saber/funcs/impl/arm/saber_slice.h | vin-huang/Anakin | 8fc4b82ebaf974a6e052fe3690e41d678de4aa03 | [
"Apache-2.0"
] | null | null | null | saber/funcs/impl/arm/saber_slice.h | vin-huang/Anakin | 8fc4b82ebaf974a6e052fe3690e41d678de4aa03 | [
"Apache-2.0"
] | null | null | null | saber/funcs/impl/arm/saber_slice.h | vin-huang/Anakin | 8fc4b82ebaf974a6e052fe3690e41d678de4aa03 | [
"Apache-2.0"
] | null | null | null | /* Copyright (c) 2018 Anakin Authors, Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef ANAKIN_SABER_FUNCS_IMPL_ARM_SABER_SLICE_H
#define ANAKIN_SABER_FUNCS_IMPL_ARM_SABER_SLICE_H
#include "saber/funcs/impl/impl_slice.h"
#ifdef USE_ARM_PLACE
namespace anakin{
namespace saber{
template <DataType OpDtype,
DataType inDtype,
DataType outDtype,
typename LayOutType_op,
typename LayOutType_in,
typename LayOutType_out>
class SaberSlice<ARM, OpDtype, inDtype, outDtype, \
LayOutType_op, LayOutType_in, LayOutType_out>:\
public ImplBase<
Tensor<ARM, inDtype, LayOutType_in>,
Tensor<ARM, outDtype, LayOutType_out>,
Tensor<ARM, OpDtype, LayOutType_op>,
SliceParam<Tensor<ARM, OpDtype, LayOutType_op>>> {
public:
typedef Tensor<ARM, inDtype, LayOutType_in> DataTensor_in;
typedef Tensor<ARM, outDtype, LayOutType_out> DataTensor_out;
typedef Tensor<ARM, OpDtype, LayOutType_op> OpTensor;
typedef typename DataTensor_in::Dtype InDataType;
typedef typename DataTensor_out::Dtype OutDataType;
typedef typename OpTensor::Dtype OpDataType;
SaberSlice() {
_slice_num = 4;
_slice_size = 0;
}
~SaberSlice() {}
virtual SaberStatus init(const std::vector<DataTensor_in*>& inputs,
std::vector<DataTensor_out*>& outputs,
SliceParam<OpTensor> ¶m, Context<ARM> &ctx) override {
// get context
return create(inputs, outputs, param, ctx);
}
virtual SaberStatus create(const std::vector<DataTensor_in*>& inputs,
std::vector<DataTensor_out*>& outputs,
SliceParam<OpTensor> ¶m, Context<ARM> &ctx) override {
this->_ctx = &ctx;
_slice_num = inputs[0]->count_valid(0, param.axis);
_slice_size = inputs[0]->count_valid(param.axis + 1, inputs[0]->dims());
return SaberSuccess;
}
virtual SaberStatus dispatch(const std::vector<DataTensor_in*>& inputs,
std::vector<DataTensor_out*>& outputs,
SliceParam<OpTensor> ¶m) override {
int offset_slice_axis = 0;
const InDataType* din = inputs[0]->data();
const int in_slice_axis = inputs[0]->valid_shape()[param.axis];
for (int i = 0; i < outputs.size(); ++i) {
OutDataType* dout = outputs[i]->mutable_data();
const int out_slice_axis = outputs[i]->valid_shape()[param.axis];
for (int n = 0; n < _slice_num; ++n) {
const int out_offset = n * out_slice_axis * _slice_size;
const int in_offset = (n * in_slice_axis + offset_slice_axis) * _slice_size;
memcpy((void*)(dout + out_offset), (void*)(din + in_offset), \
sizeof(OutDataType) * out_slice_axis * _slice_size);
}
offset_slice_axis += out_slice_axis;
}
return SaberSuccess;
}
private:
int _slice_num;
int _slice_size;
};
} //namespace saber
} //namespace anakin
#endif // USE_ARM_PLACE
#endif //ANAKIN_SABER_FUNCS_IMPL_ARM_SABER_POOLING_H
| 37.34 | 92 | 0.648902 | [
"vector"
] |
4d161db93d2e8a909cff0edbc796510a8445430b | 4,562 | h | C | ThirdParty/bullet-2.75/Extras/COLLADA_DOM/include/dae/daeIOPlugin.h | CarysT/medusa | 8e79f7738534d8cf60577ec42ed86621533ac269 | [
"MIT"
] | 32 | 2016-05-22T23:09:19.000Z | 2022-03-13T03:32:27.000Z | ThirdParty/bullet-2.75/Extras/COLLADA_DOM/include/dae/daeIOPlugin.h | CarysT/medusa | 8e79f7738534d8cf60577ec42ed86621533ac269 | [
"MIT"
] | 2 | 2016-05-30T19:45:58.000Z | 2018-01-24T22:29:51.000Z | ThirdParty/bullet-2.75/Extras/COLLADA_DOM/include/dae/daeIOPlugin.h | CarysT/medusa | 8e79f7738534d8cf60577ec42ed86621533ac269 | [
"MIT"
] | 17 | 2016-05-27T11:01:42.000Z | 2022-03-13T03:32:30.000Z | /*
* Copyright 2006 Sony Computer Entertainment Inc.
*
* Licensed under the SCEA Shared Source License, Version 1.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://research.scea.com/scea_shared_source_license.html
*
* 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 __DAE_IOPLUGIN__
#define __DAE_IOPLUGIN__
#include <dae/daeTypes.h>
class daeDatabase;
class daeMetaElement;
class daeURI;
class daeDocument;
/**
* The @c daeIOPlugin class provides the input/output plugin interface, which is
* the interface between the COLLADA runtime and the backend storage. A native
* COLLADA XML plugin implementation is provided along with this interface.
*/
class daeIOPlugin
{
public:
/**
* Destructor
*/
virtual ~daeIOPlugin() {}
/**
* Sets the top meta object.
* Called by @c dae::setIOPlugin() when the IO plugin changes. It passes to this function the
* top meta object, which is the root of a
* hierarchy of @c daeMetaElement objects. This top meta object is capable of creating
* any of the root objects in the DOM tree.
* @param topMeta Top meta object to use to create objects to fill the database.
* @return Returns DAE_OK if successful, otherwise returns a negative value defined in daeError.h.
*/
virtual DLLSPEC daeInt setMeta(daeMetaElement *topMeta) = 0;
/** @name Database setup */
//@{
/**
* Sets the database to use.
* All @c daeIOPlugins use the same interface to the @c daeDatabase,
* @c setDatabase() tells the @c daeIOPlugin which @c daeDatabase object it should use
* for storage and queries.
* @param database Database to set.
*/
virtual DLLSPEC void setDatabase(daeDatabase* database) = 0;
//@}
/** @name Operations */
//@{
/**
* Imports content into the database from an input.
* The input can be a file, a database or another runtime.
* @param uri the URI of the COLLADA document to load, not all plugins accept all types of URIs,
* check the documentation for the IO plugin you are using.
* @param docBuffer A string containing the text of the document to load. This is an optional attribute
* and should only be used if the document has already been loaded into memory.
* @return Returns DAE_OK if successfully loaded, otherwise returns a negative value defined in daeError.h.
* @see @c daeInterface::load().
*/
virtual DLLSPEC daeInt read(daeURI& uri, daeString docBuffer) = 0;
/** @name Operations */
//@{
/**
* Writes a specific document to an output.
* @param name URI to write the document to, not all IO plugins support all types of URIs
* check the documentation for the IO plugin you are using.
* @param document Pointer to the document that we're going to write out.
* @param replace True if write should overwrite an existing file. False otherwise.
* @return Returns DAE_OK if success, a negative value defined in daeError.h otherwise.
* @see @c daeInterface::saveAS()
*/
virtual DLLSPEC daeInt write(daeURI *name, daeDocument *document, daeBool replace) = 0;
//@}
/** @name Load/Save Progress */
//@{
/**
* Gets the progress of @c load() operation.
* This function can be used from another thread to check the progress of a @c load()
* operation. The user can update a progress bar <tt> bytesParsed/totalBytes </tt> gives the
* percentage of progress of the operation.
* @param bytesParsed Pointer to an integer that receives the number of bytes already
* consumed from the file, can be NULL if the user don't want to retrieve this information.
* @param lineNumber Pointer to an integer that receives the number of lines read so far,
* can be NULL.
* @param totalBytes Pointer to an integer that receives the total number of bytes in the
* file currently beeing loaded, can be NULL.
* @param reset Indicates whether to reset the counters. A value of false is the default behaviour
* that fits most usage. Set it to true to reset
* the <tt><i> bytesParsed </i></tt> and <tt><i> lineNumber </i></tt> counters. The system resets the counter at the beginning of
* each file.
*/
virtual DLLSPEC void getProgress(daeInt* bytesParsed,
daeInt* lineNumber,
daeInt* totalBytes,
daeBool reset = false ) = 0;
//@}
};
#endif // __DAE_IOPLUGIN__
| 40.371681 | 130 | 0.731477 | [
"object"
] |
4d29857620d33dde36c4855cb504758a94bb45f3 | 5,153 | h | C | crypto/store/store_local.h | jpboivin/openssl | a227ff336fc934b4a52c4659ae423dfa10efd5f3 | [
"Apache-2.0"
] | 118 | 2021-01-21T16:36:13.000Z | 2022-03-18T09:05:18.000Z | crypto/store/store_local.h | jpboivin/openssl | a227ff336fc934b4a52c4659ae423dfa10efd5f3 | [
"Apache-2.0"
] | 684 | 2021-01-21T06:51:06.000Z | 2022-03-31T14:34:42.000Z | crypto/store/store_local.h | jpboivin/openssl | a227ff336fc934b4a52c4659ae423dfa10efd5f3 | [
"Apache-2.0"
] | 26 | 2021-01-26T22:53:45.000Z | 2022-02-11T09:19:31.000Z | /*
* Copyright 2016-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <openssl/core_dispatch.h>
#include "internal/thread_once.h"
#include "internal/refcount.h"
#include <openssl/dsa.h>
#include <openssl/engine.h>
#include <openssl/evp.h>
#include <openssl/lhash.h>
#include <openssl/x509.h>
#include <openssl/store.h>
#include "internal/passphrase.h"
/*-
* OSSL_STORE_INFO stuff
* ---------------------
*/
struct ossl_store_info_st {
int type;
union {
void *data; /* used internally as generic pointer */
struct {
char *name;
char *desc;
} name; /* when type == OSSL_STORE_INFO_NAME */
EVP_PKEY *params; /* when type == OSSL_STORE_INFO_PARAMS */
EVP_PKEY *pubkey; /* when type == OSSL_STORE_INFO_PUBKEY */
EVP_PKEY *pkey; /* when type == OSSL_STORE_INFO_PKEY */
X509 *x509; /* when type == OSSL_STORE_INFO_CERT */
X509_CRL *crl; /* when type == OSSL_STORE_INFO_CRL */
} _;
};
DEFINE_STACK_OF(OSSL_STORE_INFO)
/*-
* OSSL_STORE_SEARCH stuff
* -----------------------
*/
struct ossl_store_search_st {
int search_type;
/*
* Used by OSSL_STORE_SEARCH_BY_NAME and
* OSSL_STORE_SEARCH_BY_ISSUER_SERIAL
*/
X509_NAME *name; /* TODO constify this; leads to API incompatibility */
/* Used by OSSL_STORE_SEARCH_BY_ISSUER_SERIAL */
const ASN1_INTEGER *serial;
/* Used by OSSL_STORE_SEARCH_BY_KEY_FINGERPRINT */
const EVP_MD *digest;
/*
* Used by OSSL_STORE_SEARCH_BY_KEY_FINGERPRINT and
* OSSL_STORE_SEARCH_BY_ALIAS
*/
const unsigned char *string;
size_t stringlength;
};
/*-
* OSSL_STORE_LOADER stuff
* -----------------------
*/
int ossl_store_register_loader_int(OSSL_STORE_LOADER *loader);
OSSL_STORE_LOADER *ossl_store_unregister_loader_int(const char *scheme);
/* loader stuff */
struct ossl_store_loader_st {
#ifndef OPENSSL_NO_DEPRECATED_3_0
/* Legacy stuff */
const char *scheme;
ENGINE *engine;
OSSL_STORE_open_fn open;
OSSL_STORE_attach_fn attach;
OSSL_STORE_ctrl_fn ctrl;
OSSL_STORE_expect_fn expect;
OSSL_STORE_find_fn find;
OSSL_STORE_load_fn load;
OSSL_STORE_eof_fn eof;
OSSL_STORE_error_fn error;
OSSL_STORE_close_fn close;
OSSL_STORE_open_ex_fn open_ex;
#endif
/* Provider stuff */
OSSL_PROVIDER *prov;
int scheme_id;
const char *propdef;
const char *description;
CRYPTO_REF_COUNT refcnt;
CRYPTO_RWLOCK *lock;
OSSL_FUNC_store_open_fn *p_open;
OSSL_FUNC_store_attach_fn *p_attach;
OSSL_FUNC_store_settable_ctx_params_fn *p_settable_ctx_params;
OSSL_FUNC_store_set_ctx_params_fn *p_set_ctx_params;
OSSL_FUNC_store_load_fn *p_load;
OSSL_FUNC_store_eof_fn *p_eof;
OSSL_FUNC_store_close_fn *p_close;
OSSL_FUNC_store_export_object_fn *p_export_object;
};
DEFINE_LHASH_OF(OSSL_STORE_LOADER);
const OSSL_STORE_LOADER *ossl_store_get0_loader_int(const char *scheme);
void ossl_store_destroy_loaders_int(void);
#ifdef OPENSSL_NO_DEPRECATED_3_0
/* struct ossl_store_loader_ctx_st is defined differently by each loader */
typedef struct ossl_store_loader_ctx_st OSSL_STORE_LOADER_CTX;
#endif
/*-
* OSSL_STORE_CTX stuff
* ---------------------
*/
struct ossl_store_ctx_st {
const OSSL_STORE_LOADER *loader; /* legacy */
OSSL_STORE_LOADER *fetched_loader;
OSSL_STORE_LOADER_CTX *loader_ctx;
OSSL_STORE_post_process_info_fn post_process;
void *post_process_data;
int expected_type;
char *properties;
/* 0 before the first STORE_load(), 1 otherwise */
int loading;
/* 1 on load error, only valid for fetched loaders */
int error_flag;
/*
* Cache of stuff, to be able to return the contents of a PKCS#12
* blob, one object at a time.
*/
STACK_OF(OSSL_STORE_INFO) *cached_info;
struct ossl_passphrase_data_st pwdata;
};
/*-
* 'file' scheme stuff
* -------------------
*/
OSSL_STORE_LOADER_CTX *ossl_store_file_attach_pem_bio_int(BIO *bp);
int ossl_store_file_detach_pem_bio_int(OSSL_STORE_LOADER_CTX *ctx);
/*-
* Provider stuff
* -------------------
*/
OSSL_STORE_LOADER *ossl_store_loader_fetch(OSSL_LIB_CTX *libctx,
const char *scheme,
const char *properties);
OSSL_STORE_LOADER *ossl_store_loader_fetch_by_number(OSSL_LIB_CTX *libctx,
int scheme_id,
const char *properties);
/* Standard function to handle the result from OSSL_FUNC_store_load() */
struct ossl_load_result_data_st {
OSSL_STORE_INFO *v; /* To be filled in */
OSSL_STORE_CTX *ctx;
};
OSSL_CALLBACK ossl_store_handle_load_result;
| 28.469613 | 77 | 0.668154 | [
"object"
] |
4d2fc5855a9da4b1f682e7336aed657c726de693 | 24,488 | h | C | test/e2e/test_master/wxWidgets/include/wx/prntbase.h | BlueCannonBall/cppparser | 9ae5f0c21268be6696532cf5b90c0384d6eb4940 | [
"MIT"
] | null | null | null | test/e2e/test_master/wxWidgets/include/wx/prntbase.h | BlueCannonBall/cppparser | 9ae5f0c21268be6696532cf5b90c0384d6eb4940 | [
"MIT"
] | null | null | null | test/e2e/test_master/wxWidgets/include/wx/prntbase.h | BlueCannonBall/cppparser | 9ae5f0c21268be6696532cf5b90c0384d6eb4940 | [
"MIT"
] | null | null | null | /////////////////////////////////////////////////////////////////////////////
// Name: wx/prntbase.h
// Purpose: Base classes for printing framework
// Author: Julian Smart
// Modified by:
// Created: 01/02/97
// Copyright: (c) Julian Smart
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
#ifndef _WX_PRNTBASEH__
# define _WX_PRNTBASEH__
# include "wx/defs.h"
# if wxUSE_PRINTING_ARCHITECTURE
# include "wx/event.h"
# include "wx/cmndata.h"
# include "wx/panel.h"
# include "wx/scrolwin.h"
# include "wx/dialog.h"
# include "wx/frame.h"
# include "wx/dc.h"
class WXDLLIMPEXP_FWD_CORE wxDC;
class WXDLLIMPEXP_FWD_CORE wxButton;
class WXDLLIMPEXP_FWD_CORE wxChoice;
class WXDLLIMPEXP_FWD_CORE wxPrintout;
class WXDLLIMPEXP_FWD_CORE wxPrinterBase;
class WXDLLIMPEXP_FWD_CORE wxPrintDialogBase;
class WXDLLIMPEXP_FWD_CORE wxPrintDialog;
class WXDLLIMPEXP_FWD_CORE wxPageSetupDialogBase;
class WXDLLIMPEXP_FWD_CORE wxPageSetupDialog;
class WXDLLIMPEXP_FWD_CORE wxPrintPreviewBase;
class WXDLLIMPEXP_FWD_CORE wxPreviewCanvas;
class WXDLLIMPEXP_FWD_CORE wxPreviewControlBar;
class WXDLLIMPEXP_FWD_CORE wxPreviewFrame;
class WXDLLIMPEXP_FWD_CORE wxPrintFactory;
class WXDLLIMPEXP_FWD_CORE wxPrintNativeDataBase;
class WXDLLIMPEXP_FWD_CORE wxPrintPreview;
class WXDLLIMPEXP_FWD_CORE wxPrintAbortDialog;
class WXDLLIMPEXP_FWD_CORE wxStaticText;
class wxPrintPageMaxCtrl;
class wxPrintPageTextCtrl;
//----------------------------------------------------------------------------
// error consts
//----------------------------------------------------------------------------
enum wxPrinterError {
wxPRINTER_NO_ERROR = 0,
wxPRINTER_CANCELLED,
wxPRINTER_ERROR
};
// Preview frame modality kind used with wxPreviewFrame::Initialize()
enum wxPreviewFrameModalityKind {
// Disable all the other top level windows while the preview is shown.
wxPreviewFrame_AppModal,
// Disable only the parent window while the preview is shown.
wxPreviewFrame_WindowModal,
// Don't disable any windows.
wxPreviewFrame_NonModal
};
//----------------------------------------------------------------------------
// wxPrintFactory
//----------------------------------------------------------------------------
class WXDLLIMPEXP_CORE wxPrintFactory
{
public:
wxPrintFactory()
{
}
virtual ~wxPrintFactory()
{
}
virtual wxPrinterBase* CreatePrinter(wxPrintDialogData* data) = 0;
virtual wxPrintPreviewBase* CreatePrintPreview(wxPrintout* preview, wxPrintout* printout = NULL, wxPrintDialogData* data = NULL) = 0;
virtual wxPrintPreviewBase* CreatePrintPreview(wxPrintout* preview, wxPrintout* printout, wxPrintData* data) = 0;
virtual wxPrintDialogBase* CreatePrintDialog(wxWindow* parent, wxPrintDialogData* data = NULL) = 0;
virtual wxPrintDialogBase* CreatePrintDialog(wxWindow* parent, wxPrintData* data) = 0;
virtual wxPageSetupDialogBase* CreatePageSetupDialog(wxWindow* parent, wxPageSetupDialogData* data = NULL) = 0;
virtual wxDCImpl* CreatePrinterDCImpl(wxPrinterDC* owner, const wxPrintData& data) = 0;
// What to do and what to show in the wxPrintDialog
// a) Use the generic print setup dialog or a native one?
virtual bool HasPrintSetupDialog() = 0;
virtual wxDialog* CreatePrintSetupDialog(wxWindow* parent, wxPrintData* data) = 0;
// b) Provide the "print to file" option ourselves or via print setup?
virtual bool HasOwnPrintToFile() = 0;
// c) Show current printer
virtual bool HasPrinterLine() = 0;
virtual wxString CreatePrinterLine() = 0;
// d) Show Status line for current printer?
virtual bool HasStatusLine() = 0;
virtual wxString CreateStatusLine() = 0;
virtual wxPrintNativeDataBase* CreatePrintNativeData() = 0;
static void SetPrintFactory(wxPrintFactory* factory);
static wxPrintFactory* GetFactory();
private:
static wxPrintFactory* m_factory;
};
class WXDLLIMPEXP_CORE wxNativePrintFactory : public wxPrintFactory
{
public:
wxPrinterBase* CreatePrinter(wxPrintDialogData* data) override;
wxPrintPreviewBase* CreatePrintPreview(wxPrintout* preview, wxPrintout* printout = NULL, wxPrintDialogData* data = NULL) override;
wxPrintPreviewBase* CreatePrintPreview(wxPrintout* preview, wxPrintout* printout, wxPrintData* data) override;
wxPrintDialogBase* CreatePrintDialog(wxWindow* parent, wxPrintDialogData* data = NULL) override;
wxPrintDialogBase* CreatePrintDialog(wxWindow* parent, wxPrintData* data) override;
wxPageSetupDialogBase* CreatePageSetupDialog(wxWindow* parent, wxPageSetupDialogData* data = NULL) override;
wxDCImpl* CreatePrinterDCImpl(wxPrinterDC* owner, const wxPrintData& data) override;
bool HasPrintSetupDialog() override;
wxDialog* CreatePrintSetupDialog(wxWindow* parent, wxPrintData* data) override;
bool HasOwnPrintToFile() override;
bool HasPrinterLine() override;
wxString CreatePrinterLine() override;
bool HasStatusLine() override;
wxString CreateStatusLine() override;
wxPrintNativeDataBase* CreatePrintNativeData() override;
};
//----------------------------------------------------------------------------
// wxPrintNativeDataBase
//----------------------------------------------------------------------------
class WXDLLIMPEXP_CORE wxPrintNativeDataBase : public wxObject
{
public:
wxPrintNativeDataBase();
virtual ~wxPrintNativeDataBase()
{
}
virtual bool TransferTo(wxPrintData& data) = 0;
virtual bool TransferFrom(const wxPrintData& data) = 0;
// in order to expose functionality already to the result type of the ..PrintData->GetNativeData()
virtual bool Ok() const
{
return IsOk();
}
virtual bool IsOk() const = 0;
int m_ref;
private:
wxDECLARE_CLASS(wxPrintNativeDataBase);
wxDECLARE_NO_COPY_CLASS(wxPrintNativeDataBase);
};
//----------------------------------------------------------------------------
// wxPrinterBase
//----------------------------------------------------------------------------
/*
* Represents the printer: manages printing a wxPrintout object
*/
class WXDLLIMPEXP_CORE wxPrinterBase : public wxObject
{
public:
wxPrinterBase(wxPrintDialogData* data = NULL);
virtual ~wxPrinterBase();
virtual wxPrintAbortDialog* CreateAbortWindow(wxWindow* parent, wxPrintout* printout);
virtual void ReportError(wxWindow* parent, wxPrintout* printout, const wxString& message);
virtual wxPrintDialogData& GetPrintDialogData() const;
bool GetAbort() const
{
return sm_abortIt;
}
static wxPrinterError GetLastError()
{
return sm_lastError;
}
///////////////////////////////////////////////////////////////////////////
// OVERRIDES
virtual bool Setup(wxWindow* parent) = 0;
virtual bool Print(wxWindow* parent, wxPrintout* printout, bool prompt = true) = 0;
virtual wxDC* PrintDialog(wxWindow* parent) = 0;
protected:
wxPrintDialogData m_printDialogData;
wxPrintout* m_currentPrintout;
static wxPrinterError sm_lastError;
public:
static wxWindow* sm_abortWindow;
static bool sm_abortIt;
private:
wxDECLARE_CLASS(wxPrinterBase);
wxDECLARE_NO_COPY_CLASS(wxPrinterBase);
};
//----------------------------------------------------------------------------
// wxPrinter
//----------------------------------------------------------------------------
class WXDLLIMPEXP_CORE wxPrinter : public wxPrinterBase
{
public:
wxPrinter(wxPrintDialogData* data = NULL);
virtual ~wxPrinter();
wxPrintAbortDialog* CreateAbortWindow(wxWindow* parent, wxPrintout* printout) override;
void ReportError(wxWindow* parent, wxPrintout* printout, const wxString& message) override;
bool Setup(wxWindow* parent) override;
bool Print(wxWindow* parent, wxPrintout* printout, bool prompt = true) override;
wxDC* PrintDialog(wxWindow* parent) override;
wxPrintDialogData& GetPrintDialogData() const override;
protected:
wxPrinterBase* m_pimpl;
private:
wxDECLARE_CLASS(wxPrinter);
wxDECLARE_NO_COPY_CLASS(wxPrinter);
};
//----------------------------------------------------------------------------
// wxPrintout
//----------------------------------------------------------------------------
/*
* Represents an object via which a document may be printed.
* The programmer derives from this, overrides (at least) OnPrintPage,
* and passes it to a wxPrinter object for printing, or a wxPrintPreview
* object for previewing.
*/
class WXDLLIMPEXP_CORE wxPrintout : public wxObject
{
public:
wxPrintout(const wxString& title = wxGetTranslation("Printout"));
virtual ~wxPrintout();
virtual bool OnBeginDocument(int startPage, int endPage);
virtual void OnEndDocument();
virtual void OnBeginPrinting();
virtual void OnEndPrinting();
// Guaranteed to be before any other functions are called
virtual void OnPreparePrinting()
{
}
virtual bool HasPage(int page);
virtual bool OnPrintPage(int page) = 0;
virtual void GetPageInfo(int* minPage, int* maxPage, int* pageFrom, int* pageTo);
virtual wxString GetTitle() const
{
return m_printoutTitle;
}
// Port-specific code should call this function to initialize this object
// with everything it needs, instead of using individual accessors below.
bool SetUp(wxDC& dc);
wxDC* GetDC() const
{
return m_printoutDC;
}
void SetDC(wxDC* dc)
{
m_printoutDC = dc;
}
void FitThisSizeToPaper(const wxSize& imageSize);
void FitThisSizeToPage(const wxSize& imageSize);
void FitThisSizeToPageMargins(const wxSize& imageSize, const wxPageSetupDialogData& pageSetupData);
void MapScreenSizeToPaper();
void MapScreenSizeToPage();
void MapScreenSizeToPageMargins(const wxPageSetupDialogData& pageSetupData);
void MapScreenSizeToDevice();
wxRect GetLogicalPaperRect() const;
wxRect GetLogicalPageRect() const;
wxRect GetLogicalPageMarginsRect(const wxPageSetupDialogData& pageSetupData) const;
void SetLogicalOrigin(wxCoord x, wxCoord y);
void OffsetLogicalOrigin(wxCoord xoff, wxCoord yoff);
void SetPageSizePixels(int w, int h)
{
m_pageWidthPixels = w;
m_pageHeightPixels = h;
}
void GetPageSizePixels(int* w, int* h) const
{
*w = m_pageWidthPixels;
*h = m_pageHeightPixels;
}
void SetPageSizeMM(int w, int h)
{
m_pageWidthMM = w;
m_pageHeightMM = h;
}
void GetPageSizeMM(int* w, int* h) const
{
*w = m_pageWidthMM;
*h = m_pageHeightMM;
}
void SetPPIScreen(int x, int y)
{
m_PPIScreenX = x;
m_PPIScreenY = y;
}
void SetPPIScreen(const wxSize& ppi)
{
SetPPIScreen(ppi.x, ppi.y);
}
void GetPPIScreen(int* x, int* y) const
{
*x = m_PPIScreenX;
*y = m_PPIScreenY;
}
void SetPPIPrinter(int x, int y)
{
m_PPIPrinterX = x;
m_PPIPrinterY = y;
}
void SetPPIPrinter(const wxSize& ppi)
{
SetPPIPrinter(ppi.x, ppi.y);
}
void GetPPIPrinter(int* x, int* y) const
{
*x = m_PPIPrinterX;
*y = m_PPIPrinterY;
}
void SetPaperRectPixels(const wxRect& paperRectPixels)
{
m_paperRectPixels = paperRectPixels;
}
wxRect GetPaperRectPixels() const
{
return m_paperRectPixels;
}
// This must be called by wxPrintPreview to associate itself with the
// printout it uses.
virtual void SetPreview(wxPrintPreview* preview)
{
m_preview = preview;
}
wxPrintPreview* GetPreview() const
{
return m_preview;
}
virtual bool IsPreview() const
{
return GetPreview() != NULL;
}
private:
wxString m_printoutTitle;
wxDC* m_printoutDC;
wxPrintPreview* m_preview;
int m_pageWidthPixels;
int m_pageHeightPixels;
int m_pageWidthMM;
int m_pageHeightMM;
int m_PPIScreenX;
int m_PPIScreenY;
int m_PPIPrinterX;
int m_PPIPrinterY;
wxRect m_paperRectPixels;
wxDECLARE_ABSTRACT_CLASS(wxPrintout);
wxDECLARE_NO_COPY_CLASS(wxPrintout);
};
//----------------------------------------------------------------------------
// wxPreviewCanvas
//----------------------------------------------------------------------------
/*
* Canvas upon which a preview is drawn.
*/
class WXDLLIMPEXP_CORE wxPreviewCanvas : public wxScrolledWindow
{
public:
wxPreviewCanvas(wxPrintPreviewBase* preview, wxWindow* parent, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = 0, const wxString& name = wxT("canvas"));
virtual ~wxPreviewCanvas();
void SetPreview(wxPrintPreviewBase* preview)
{
m_printPreview = preview;
}
void OnPaint(wxPaintEvent& event);
void OnChar(wxKeyEvent& event);
// Responds to colour changes
void OnSysColourChanged(wxSysColourChangedEvent& event);
# if wxUSE_MOUSEWHEEL
private:
void OnMouseWheel(wxMouseEvent& event);
# endif
void OnIdle(wxIdleEvent& event);
wxPrintPreviewBase* m_printPreview;
wxDECLARE_CLASS(wxPreviewCanvas);
wxDECLARE_EVENT_TABLE();
wxDECLARE_NO_COPY_CLASS(wxPreviewCanvas);
};
//----------------------------------------------------------------------------
// wxPreviewFrame
//----------------------------------------------------------------------------
/*
* Default frame for showing preview.
*/
class WXDLLIMPEXP_CORE wxPreviewFrame : public wxFrame
{
public:
wxPreviewFrame(wxPrintPreviewBase* preview, wxWindow* parent, const wxString& title = wxGetTranslation(wxASCII_STR("Print Preview")), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxDEFAULT_FRAME_STYLE | wxFRAME_FLOAT_ON_PARENT, const wxString& name = wxASCII_STR(wxFrameNameStr));
virtual ~wxPreviewFrame();
// Either Initialize() or InitializeWithModality() must be called before
// showing the preview frame, the former being just a particular case of
// the latter initializing the frame for being showing app-modally.
// Notice that we must keep Initialize() with its existing signature to
// avoid breaking the old code that overrides it and we can't reuse the
// same name for the other functions to avoid virtual function hiding
// problem and the associated warnings given by some compilers (e.g. from
// g++ with -Woverloaded-virtual).
virtual void Initialize()
{
InitializeWithModality(wxPreviewFrame_AppModal);
}
// Also note that this method is not virtual as it doesn't need to be
// overridden: it's never called by wxWidgets (of course, the same is true
// for Initialize() but, again, it must remain virtual for compatibility).
void InitializeWithModality(wxPreviewFrameModalityKind kind);
void OnCloseWindow(wxCloseEvent& event);
virtual void CreateCanvas();
virtual void CreateControlBar();
inline wxPreviewControlBar* GetControlBar() const
{
return m_controlBar;
}
protected:
wxPreviewCanvas* m_previewCanvas;
wxPreviewControlBar* m_controlBar;
wxPrintPreviewBase* m_printPreview;
wxWindowDisabler* m_windowDisabler;
wxPreviewFrameModalityKind m_modalityKind;
private:
void OnChar(wxKeyEvent& event);
wxDECLARE_EVENT_TABLE();
wxDECLARE_CLASS(wxPreviewFrame);
wxDECLARE_NO_COPY_CLASS(wxPreviewFrame);
};
//----------------------------------------------------------------------------
// wxPreviewControlBar
//----------------------------------------------------------------------------
/*
* A panel with buttons for controlling a print preview.
* The programmer may wish to use other means for controlling
* the print preview.
*/
# define wxPREVIEW_PRINT 1
# define wxPREVIEW_PREVIOUS 2
# define wxPREVIEW_NEXT 4
# define wxPREVIEW_ZOOM 8
# define wxPREVIEW_FIRST 16
# define wxPREVIEW_LAST 32
# define wxPREVIEW_GOTO 64
# define wxPREVIEW_DEFAULT(wxPREVIEW_PREVIOUS|wxPREVIEW_NEXT|wxPREVIEW_ZOOM\
|wxPREVIEW_FIRST|wxPREVIEW_GOTO|wxPREVIEW_LAST)
// Ids for controls
# define wxID_PREVIEW_CLOSE 1
# define wxID_PREVIEW_NEXT 2
# define wxID_PREVIEW_PREVIOUS 3
# define wxID_PREVIEW_PRINT 4
# define wxID_PREVIEW_ZOOM 5
# define wxID_PREVIEW_FIRST 6
# define wxID_PREVIEW_LAST 7
# define wxID_PREVIEW_GOTO 8
# define wxID_PREVIEW_ZOOM_IN 9
# define wxID_PREVIEW_ZOOM_OUT 10
class WXDLLIMPEXP_CORE wxPreviewControlBar : public wxPanel
{
wxDECLARE_CLASS(wxPreviewControlBar);
public:
wxPreviewControlBar(wxPrintPreviewBase* preview, long buttons, wxWindow* parent, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxTAB_TRAVERSAL, const wxString& name = wxT("panel"));
virtual ~wxPreviewControlBar();
virtual void CreateButtons();
virtual void SetPageInfo(int minPage, int maxPage);
virtual void SetZoomControl(int zoom);
virtual int GetZoomControl();
virtual wxPrintPreviewBase* GetPrintPreview() const
{
return m_printPreview;
}
// Implementation only from now on.
void OnWindowClose(wxCommandEvent& event);
void OnNext();
void OnPrevious();
void OnFirst();
void OnLast();
void OnGotoPage();
void OnPrint();
void OnPrintButton(wxCommandEvent&)
{
OnPrint();
}
void OnNextButton(wxCommandEvent&)
{
OnNext();
}
void OnPreviousButton(wxCommandEvent&)
{
OnPrevious();
}
void OnFirstButton(wxCommandEvent&)
{
OnFirst();
}
void OnLastButton(wxCommandEvent&)
{
OnLast();
}
void OnPaint(wxPaintEvent& event);
void OnUpdateNextButton(wxUpdateUIEvent& event)
{
event.Enable(IsNextEnabled());
}
void OnUpdatePreviousButton(wxUpdateUIEvent& event)
{
event.Enable(IsPreviousEnabled());
}
void OnUpdateFirstButton(wxUpdateUIEvent& event)
{
event.Enable(IsFirstEnabled());
}
void OnUpdateLastButton(wxUpdateUIEvent& event)
{
event.Enable(IsLastEnabled());
}
void OnUpdateZoomInButton(wxUpdateUIEvent& event)
{
event.Enable(IsZoomInEnabled());
}
void OnUpdateZoomOutButton(wxUpdateUIEvent& event)
{
event.Enable(IsZoomOutEnabled());
}
// These methods are not private because they are called by wxPreviewCanvas.
void DoZoomIn();
void DoZoomOut();
protected:
wxPrintPreviewBase* m_printPreview;
wxButton* m_closeButton;
wxChoice* m_zoomControl;
wxPrintPageTextCtrl* m_currentPageText;
wxPrintPageMaxCtrl* m_maxPageText;
long m_buttonFlags;
private:
void DoGotoPage(int page);
void DoZoom();
bool IsNextEnabled() const;
bool IsPreviousEnabled() const;
bool IsFirstEnabled() const;
bool IsLastEnabled() const;
bool IsZoomInEnabled() const;
bool IsZoomOutEnabled() const;
void OnZoomInButton(wxCommandEvent&)
{
DoZoomIn();
}
void OnZoomOutButton(wxCommandEvent&)
{
DoZoomOut();
}
void OnZoomChoice(wxCommandEvent&)
{
DoZoom();
}
wxDECLARE_EVENT_TABLE();
wxDECLARE_NO_COPY_CLASS(wxPreviewControlBar);
};
//----------------------------------------------------------------------------
// wxPrintPreviewBase
//----------------------------------------------------------------------------
/*
* Programmer creates an object of this class to preview a wxPrintout.
*/
class WXDLLIMPEXP_CORE wxPrintPreviewBase : public wxObject
{
public:
wxPrintPreviewBase(wxPrintout* printout, wxPrintout* printoutForPrinting = NULL, wxPrintDialogData* data = NULL);
wxPrintPreviewBase(wxPrintout* printout, wxPrintout* printoutForPrinting, wxPrintData* data);
virtual ~wxPrintPreviewBase();
virtual bool SetCurrentPage(int pageNum);
virtual int GetCurrentPage() const;
virtual void SetPrintout(wxPrintout* printout);
virtual wxPrintout* GetPrintout() const;
virtual wxPrintout* GetPrintoutForPrinting() const;
virtual void SetFrame(wxFrame* frame);
virtual void SetCanvas(wxPreviewCanvas* canvas);
virtual wxFrame* GetFrame() const;
virtual wxPreviewCanvas* GetCanvas() const;
// This is a helper routine, used by the next 4 routines.
virtual void CalcRects(wxPreviewCanvas* canvas, wxRect& printableAreaRect, wxRect& paperRect);
// The preview canvas should call this from OnPaint
virtual bool PaintPage(wxPreviewCanvas* canvas, wxDC& dc);
// Updates rendered page by calling RenderPage() if needed, returns true
// if there was some change. Preview canvas should call it at idle time
virtual bool UpdatePageRendering();
// This draws a blank page onto the preview canvas
virtual bool DrawBlankPage(wxPreviewCanvas* canvas, wxDC& dc);
// Adjusts the scrollbars for the current scale
virtual void AdjustScrollbars(wxPreviewCanvas* canvas);
// This is called by wxPrintPreview to render a page into a wxMemoryDC.
virtual bool RenderPage(int pageNum);
virtual void SetZoom(int percent);
virtual int GetZoom() const;
virtual wxPrintDialogData& GetPrintDialogData();
virtual int GetMaxPage() const;
virtual int GetMinPage() const;
virtual bool Ok() const
{
return IsOk();
}
virtual bool IsOk() const;
virtual void SetOk(bool ok);
///////////////////////////////////////////////////////////////////////////
// OVERRIDES
// If we own a wxPrintout that can be used for printing, this
// will invoke the actual printing procedure. Called
// by the wxPreviewControlBar.
virtual bool Print(bool interactive) = 0;
// Calculate scaling that needs to be done to get roughly
// the right scaling for the screen pretending to be
// the currently selected printer.
virtual void DetermineScaling() = 0;
protected:
// helpers for RenderPage():
virtual bool RenderPageIntoDC(wxDC& dc, int pageNum);
// renders preview into m_previewBitmap
virtual bool RenderPageIntoBitmap(wxBitmap& bmp, int pageNum);
void InvalidatePreviewBitmap();
wxPrintDialogData m_printDialogData;
wxPreviewCanvas* m_previewCanvas;
wxFrame* m_previewFrame;
wxBitmap* m_previewBitmap;
bool m_previewFailed;
wxPrintout* m_previewPrintout;
wxPrintout* m_printPrintout;
int m_currentPage;
int m_currentZoom;
float m_previewScaleX;
float m_previewScaleY;
int m_topMargin;
int m_leftMargin;
int m_pageWidth;
int m_pageHeight;
int m_minPage;
int m_maxPage;
bool m_isOk;
bool m_printingPrepared;
private:
void Init(wxPrintout* printout, wxPrintout* printoutForPrinting);
wxDECLARE_NO_COPY_CLASS(wxPrintPreviewBase);
wxDECLARE_CLASS(wxPrintPreviewBase);
};
//----------------------------------------------------------------------------
// wxPrintPreview
//----------------------------------------------------------------------------
class WXDLLIMPEXP_CORE wxPrintPreview : public wxPrintPreviewBase
{
public:
wxPrintPreview(wxPrintout* printout, wxPrintout* printoutForPrinting = NULL, wxPrintDialogData* data = NULL);
wxPrintPreview(wxPrintout* printout, wxPrintout* printoutForPrinting, wxPrintData* data);
virtual ~wxPrintPreview();
bool SetCurrentPage(int pageNum) override;
int GetCurrentPage() const override;
void SetPrintout(wxPrintout* printout) override;
wxPrintout* GetPrintout() const override;
wxPrintout* GetPrintoutForPrinting() const override;
void SetFrame(wxFrame* frame) override;
void SetCanvas(wxPreviewCanvas* canvas) override;
wxFrame* GetFrame() const override;
wxPreviewCanvas* GetCanvas() const override;
bool PaintPage(wxPreviewCanvas* canvas, wxDC& dc) override;
bool UpdatePageRendering() override;
bool DrawBlankPage(wxPreviewCanvas* canvas, wxDC& dc) override;
void AdjustScrollbars(wxPreviewCanvas* canvas) override;
bool RenderPage(int pageNum) override;
void SetZoom(int percent) override;
int GetZoom() const override;
bool Print(bool interactive) override;
void DetermineScaling() override;
wxPrintDialogData& GetPrintDialogData() override;
int GetMaxPage() const override;
int GetMinPage() const override;
bool Ok() const override
{
return IsOk();
}
bool IsOk() const override;
void SetOk(bool ok) override;
private:
wxPrintPreviewBase* m_pimpl;
wxDECLARE_CLASS(wxPrintPreview);
wxDECLARE_NO_COPY_CLASS(wxPrintPreview);
};
//----------------------------------------------------------------------------
// wxPrintAbortDialog
//----------------------------------------------------------------------------
class WXDLLIMPEXP_CORE wxPrintAbortDialog : public wxDialog
{
public:
wxPrintAbortDialog(wxWindow* parent, const wxString& documentTitle, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxDEFAULT_DIALOG_STYLE, const wxString& name = wxT("dialog"));
void SetProgress(int currentPage, int totalPages, int currentCopy, int totalCopies);
void OnCancel(wxCommandEvent& event);
private:
wxStaticText* m_progress;
wxDECLARE_EVENT_TABLE();
wxDECLARE_NO_COPY_CLASS(wxPrintAbortDialog);
};
# endif
#endif
// _WX_PRNTBASEH__
| 35.489855 | 326 | 0.688541 | [
"render",
"object"
] |
4d34263bafd67c66bb6a44c84c0b93bd73c9c872 | 894 | h | C | EngineGL/Render/Mesh.h | Jodacam/EngineGL | 271b5fd386081d2cefc72d06da3d71c0be4e8e84 | [
"Apache-2.0"
] | 1 | 2019-01-17T20:32:25.000Z | 2019-01-17T20:32:25.000Z | examples/OpenGLScene/lib/include/EngineGL/Render/Mesh.h | Jodacam/EngineGL | 271b5fd386081d2cefc72d06da3d71c0be4e8e84 | [
"Apache-2.0"
] | null | null | null | examples/OpenGLScene/lib/include/EngineGL/Render/Mesh.h | Jodacam/EngineGL | 271b5fd386081d2cefc72d06da3d71c0be4e8e84 | [
"Apache-2.0"
] | null | null | null | #pragma once
#ifndef MESH_H_
#define MESH_H_
class Mesh {
private:
//Identifiers of the VBO
std::vector<unsigned int> miVertexIndex2;
std::vector<float> miVertexPos2;
std::vector<float> miModelColor2;
std::vector<float> miNormals2;
std::vector<float> miTexCoord2;
std::vector<float> miVertexTang2;
Assimp::Importer importer;
const aiScene* scene;
unsigned int vaoID;
unsigned int posVBO;
unsigned int TangVBO;
unsigned int colorVBO;
unsigned int normalVBO;
unsigned int texCoordVBO;
unsigned int triangleIndexVBO;
int NTindex;
void initMesh(const int NVertex, const float* VertexPos, const float* VertexColor, const float* VertexNormal, const float* VertexTexCoord,
const int NTriangleIndex, const unsigned int *TriangleIndex, const float *VertexTang);
public:
Mesh(const char* fileName);
void DrawMesh();
Mesh();
~Mesh();
};
#endif | 24.162162 | 140 | 0.736018 | [
"mesh",
"vector"
] |
4d364688688cd63c7b5ba18738166dcba039d19d | 2,109 | h | C | includes/CpInfo.h | Markuus13/jvm-sb | 01e53e6201fb128ab78a7df5a159d13c193414d4 | [
"MIT"
] | 6 | 2018-03-27T12:11:10.000Z | 2021-03-29T22:40:39.000Z | includes/CpInfo.h | Markuus13/jvm-sb | 01e53e6201fb128ab78a7df5a159d13c193414d4 | [
"MIT"
] | 4 | 2018-05-12T14:40:12.000Z | 2018-07-07T02:46:35.000Z | includes/CpInfo.h | Markuus13/jvm-sb | 01e53e6201fb128ab78a7df5a159d13c193414d4 | [
"MIT"
] | 1 | 2020-11-08T21:43:52.000Z | 2020-11-08T21:43:52.000Z | /** @file CpInfo.h
* @brief ...
* @bug No know bugs.
*/
#ifndef JVM_CPP_CONSTANTPOOLINFO_H
#define JVM_CPP_CONSTANTPOOLINFO_H
/** @cond */
#include <cstdio>
#include <string>
/** @endcond */
#include "JavaClass.h"
/**
* @brief Estrutura de classe para unidade da Constant Pool.
**/
class CpInfo {
public:
u2 tag;
union {
// class or interface representation
struct {
u2 type_class_info;
} Class;
// field representation
struct {
u2 class_index;
u2 name_and_type_index;
} FieldRef;
// field or method without the class or interface which belongs
struct {
u2 name_index;
u2 descriptor_index;
} NameAndType;
// constant string, unicode included
struct {
u2 size;
// not allowed zero values or value between the interval 0xf0 to 0xff,
// that means, [240, 255]
u1 *bytes;
} UTF8;
// method representation
struct {
u2 index;
u2 name_and_type;
} MethodRef;
// interface method representation
struct {
u2 index;
u2 name_and_type;
} InterfaceMethodRef;
// constant object string
struct {
u2 bytes;
} String;
// integer constant of 4 bytes (big-endian)
struct {
u4 bytes;
} Integer;
// float constant of 4 bytes (big-endian, IEEE-754)
struct {
u4 bytes;
} Float;
// integer constant of 8 bytes (big-endian), occupies 2 indexes
// in constant_pool table
struct {
u4 high_bytes;
u4 low_bytes;
} Long;
// float constant of 8 bytes (big-endian, IEEE-754), occupies
// 2 indexes in constant_pool table
struct {
u4 high_bytes;
u4 low_bytes;
} Double;
};
void read(FILE*, JavaClass);
std::string get_utf8_constant_pool(CpInfo *cp_info, u2 pos_info);
};
#endif
| 21.742268 | 82 | 0.537221 | [
"object"
] |
4d3cfc384e32e4b15c3722c4b9988d3abb7c3032 | 88,091 | c | C | src/hg/cirm/cdw/lib/cdwLib.c | psteinb/kent | 3ff439f4e5194805359405bb4452c8d96a343932 | [
"IJG"
] | null | null | null | src/hg/cirm/cdw/lib/cdwLib.c | psteinb/kent | 3ff439f4e5194805359405bb4452c8d96a343932 | [
"IJG"
] | null | null | null | src/hg/cirm/cdw/lib/cdwLib.c | psteinb/kent | 3ff439f4e5194805359405bb4452c8d96a343932 | [
"IJG"
] | null | null | null | /* cdwLib - routines shared by various cdw programs. See also cdw
* module for tables and routines to access structs built on tables. */
/* Copyright (C) 2014 The Regents of the University of California
* See README in this or parent directory for licensing information. */
#include "common.h"
#include "hash.h"
#include "dystring.h"
#include "jksql.h"
#include "errAbort.h"
#include "cheapcgi.h"
#include "hex.h"
#include "openssl/sha.h"
#include "base64.h"
#include "basicBed.h"
#include "bigBed.h"
#include "portable.h"
#include "filePath.h"
#include "genomeRangeTree.h"
#include "md5.h"
#include "htmshell.h"
#include "obscure.h"
#include "bamFile.h"
#include "raToStruct.h"
#include "web.h"
#include "hdb.h"
#include "cdwValid.h"
#include "cdw.h"
#include "cdwFastqFileFromRa.h"
#include "cdwBamFileFromRa.h"
#include "cdwQaWigSpotFromRa.h"
#include "cdwVcfFileFromRa.h"
#include "rql.h"
#include "intValTree.h"
#include "tagStorm.h"
#include "cdwLib.h"
#include "trashDir.h"
#include "wikiLink.h"
#include "hgConfig.h"
/* System globals - just a few ... for now. Please seriously not too many more. */
char *cdwDatabase = "cdw";
int cdwSingleFileTimeout = 4*60*60; // How many seconds we give ourselves to fetch a single file
char *cdwRootDir = "/data/cirm/cdw/";
char *eapRootDir = "/data/cirm/encodeAnalysisPipeline/";
char *cdwValDataDir = "/data/cirm/valData/";
char *cdwDaemonEmail = "cdw@cirm-01.sdsc.edu";
struct sqlConnection *cdwConnect()
/* Returns a read only connection to database. */
{
return sqlConnect(cdwDatabase);
}
struct sqlConnection *cdwConnectReadWrite()
/* Returns read/write connection to database. */
{
return sqlConnectProfile("cdw", cdwDatabase);
}
char *cdwPathForFileId(struct sqlConnection *conn, long long fileId)
/* Return full path (which eventually should be freeMem'd) for fileId */
{
char query[256];
char fileName[PATH_LEN];
sqlSafef(query, sizeof(query), "select cdwFileName from cdwFile where id=%lld", fileId);
sqlNeedQuickQuery(conn, query, fileName, sizeof(fileName));
char path[512];
safef(path, sizeof(path), "%s%s", cdwRootDir, fileName);
return cloneString(path);
}
char *cdwTempDir()
/* Returns pointer to cdwTempDir. This is shared, so please don't modify. */
{
static char path[PATH_LEN];
if (path[0] == 0)
{
/* Note code elsewhere depends on tmp dir being inside of cdwRootDir - also good
* to have it there so move to a permanent file is quick and unlikely to fail. */
safef(path, sizeof(path), "%s%s", cdwRootDir, "tmp");
makeDirsOnPath(path);
strcat(path, "/");
}
return path;
}
char *cdwTempDirForToday(char dir[PATH_LEN])
/* Fills in dir with temp dir of the day, and returns a pointer to it. */
{
char dayDir[PATH_LEN];
cdwDirForTime(cdwNow(), dayDir);
safef(dir, PATH_LEN, "%s%stmp/", cdwRootDir, dayDir);
/* Bracket time consuming call to makeDirsOnPath with check that we didn't just do same
* thing. */
static char lastDayDir[PATH_LEN] = "";
if (!sameString(dayDir, lastDayDir))
{
strcpy(lastDayDir, dayDir);
int len = strlen(dir);
dir[len-1] = 0;
makeDirsOnPath(dir);
dir[len-1] = '/';
}
return dir;
}
long long cdwGettingFile(struct sqlConnection *conn, char *submitDir, char *submitFileName)
/* See if we are in process of getting file. Return file record id if it exists even if
* it's not complete. Return -1 if record does not exist. */
{
/* First see if we have even got the directory. */
char query[PATH_LEN+512];
sqlSafef(query, sizeof(query), "select id from cdwSubmitDir where url='%s'", submitDir);
int submitDirId = sqlQuickNum(conn, query);
if (submitDirId <= 0)
return -1;
/* Then see if we have file that matches submitDir and submitFileName. */
sqlSafef(query, sizeof(query),
"select id from cdwFile "
"where submitFileName='%s' and submitDirId = %d and errorMessage = '' and deprecated=''"
" and (endUploadTime >= startUploadTime or startUploadTime < %lld) "
"order by submitId desc limit 1"
, submitFileName, submitDirId
, (long long)cdwNow() - cdwSingleFileTimeout);
long long id = sqlQuickLongLong(conn, query);
if (id == 0)
return -1;
return id;
}
long long cdwGotFile(struct sqlConnection *conn, char *submitDir, char *submitFileName,
char *md5, long long size)
/* See if we already got file. Return fileId if we do, otherwise -1. This returns
* TRUE based mostly on the MD5sum. For short files (less than 100k) then we also require
* the submitDir and submitFileName to match. This is to cover the case where you might
* have legitimate empty files duplicated even though they were computed based on different
* things. For instance coming up with no peaks is a legitimate result for many chip-seq
* experiments. */
{
/* For large files just rely on MD5. */
char query[PATH_LEN+512];
if (size > 100000)
{
sqlSafef(query, sizeof(query),
"select id from cdwFile where md5='%s' order by submitId desc limit 1" , md5);
long long result = sqlQuickLongLong(conn, query);
if (result == 0)
result = -1;
return result;
}
/* Rest of the routine deals with smaller files, which we are less worried about
* duplicating, and indeed expect a little duplication of the empty file if none
* other. */
/* First see if we have even got the directory. */
sqlSafef(query, sizeof(query), "select id from cdwSubmitDir where url='%s'", submitDir);
int submitDirId = sqlQuickNum(conn, query);
if (submitDirId <= 0)
return -1;
/* The complex truth is that we may have gotten this file multiple times.
* We return the most recent version where it got uploaded and passed the post-upload
* MD5 sum, and thus where the MD5 field is filled in the database. */
sqlSafef(query, sizeof(query),
"select md5,id from cdwFile "
"where submitFileName='%s' and submitDirId = %d and md5 != '' "
"order by submitId desc limit 1"
, submitFileName, submitDirId);
struct sqlResult *sr = sqlGetResult(conn, query);
char **row;
long fileId = -1;
if ((row = sqlNextRow(sr)) != NULL)
{
char *dbMd5 = row[0];
if (sameWord(md5, dbMd5))
fileId = sqlLongLong(row[1]);
}
sqlFreeResult(&sr);
return fileId;
}
long long cdwNow()
/* Return current time in seconds since Epoch. */
{
return time(NULL);
}
/* This is size of base64 encoded hash plus 1 for the terminating zero. */
#define CDW_SID_SIZE 65
static void makeShaBase64(unsigned char *inputBuf, int inputSize, char out[CDW_SID_SIZE])
/* Make zero terminated printable cryptographic hash out of in */
{
unsigned char shaBuf[48];
SHA384(inputBuf, inputSize, shaBuf);
char *base64 = base64Encode((char*)shaBuf, sizeof(shaBuf));
memcpy(out, base64, CDW_SID_SIZE);
out[CDW_SID_SIZE-1] = 0;
freeMem(base64);
}
void cdwMakeSid(char *user, char sid[CDW_SID_SIZE])
/* Convert users to sid */
{
/* Salt it well with stuff that is reproducible but hard to guess */
unsigned char inputBuf[512];
memset(inputBuf, 0, sizeof(inputBuf));
int i;
for (i=0; i<ArraySize(inputBuf); i += 2)
{
inputBuf[i] = i ^ 0x29;
inputBuf[i+1] = ~i;
}
safef((char*)inputBuf, sizeof(inputBuf),
"186ED79BAEXzeusdioIsdklnw88e86cd73%s<*#$*(#)!DSDFOUIHLjksdf", user);
makeShaBase64(inputBuf, sizeof(inputBuf), sid);
}
static void cdwVerifySid(char *user, char *sidToCheck)
/* Make sure sid/user combo is good. */
{
char sid[CDW_SID_SIZE];
cdwMakeSid(user, sid);
if (sidToCheck == NULL || memcmp(sidToCheck, sid, CDW_SID_SIZE) != 0)
errAbort("Authentication failed, sid %s", (sidToCheck ? "fail" : "miss"));
}
char *cdwGetEmailAndVerify()
/* Get email from persona-managed cookies and validate them.
* Return email address if all is good and user is logged in.
* If user not logged in return NULL. If user logged in but
* otherwise things are wrong abort. */
{
char *email = findCookieData("email");
if (email)
{
char *sid = findCookieData("sid");
cdwVerifySid(email, sid);
}
return email;
}
struct cdwUser *cdwUserFromUserName(struct sqlConnection *conn, char* userName)
/* Return user associated with that username or NULL if not found */
{
char *email = NULL;
// if the username is already an email address, then there is no need to go through the
// gbMembers table
if (strstr(userName, "@")!=NULL)
email = userName;
else
{
struct sqlConnection *cc = hConnectCentral();
char query[512];
sqlSafef(query, sizeof(query), "select email from gbMembers where userName='%s'", userName);
email = sqlQuickString(cc, query);
hDisconnectCentral(&cc);
}
struct cdwUser *user = cdwUserFromEmail(conn, email);
return user;
}
struct cdwUser *cdwUserFromEmail(struct sqlConnection *conn, char *email)
/* Return user associated with that email or NULL if not found */
{
char query[256];
sqlSafef(query, sizeof(query), "select * from cdwUser where email='%s'", email);
struct cdwUser *user = cdwUserLoadByQuery(conn, query);
return user;
}
struct cdwUser *cdwUserFromId(struct sqlConnection *conn, int id)
/* Return user associated with that id or NULL if not found */
{
char query[256];
sqlSafef(query, sizeof(query), "select * from cdwUser where id='%d'", id);
struct cdwUser *user = cdwUserLoadByQuery(conn, query);
return user;
}
int cdwUserIdFromFileId(struct sqlConnection *conn, int fId)
/* Return user id who submit the file originally */
{
char query[256];
sqlSafef(query, sizeof(query), "select s.userId from cdwSubmit s, cdwFile f where f.submitId=s.id and f.id='%d'", fId);
int sId = sqlQuickNum(conn, query);
sqlSafef(query, sizeof(query), "select u.id from cdwSubmit s, cdwUser u where u.id=s.id and s.id='%d'", sId);
return sqlQuickNum(conn, query);
}
struct cdwUser *cdwFindUserFromFileId(struct sqlConnection *conn, int fId)
/* Return user who submit the file originally */
{
int uId = cdwUserIdFromFileId(conn, fId);
struct cdwUser *user=cdwUserFromId(conn, uId);
return user;
}
char *cdwFindOwnerNameFromFileId(struct sqlConnection *conn, int fId)
/* Return name of submitter. Return "an unknown user" if name is NULL */
{
struct cdwUser *owner = cdwFindUserFromFileId(conn, fId);
if (owner == NULL)
return ("an unknown user");
return cloneString(owner->email);
}
int cdwFindUserIdFromEmail(struct sqlConnection *conn, char *userEmail)
/* Return true id of this user */
{
char query[256];
sqlSafef(query, sizeof(query), "select id from cdwUser where email = '%s'", userEmail);
return sqlQuickNum(conn, query);
}
boolean cdwUserIsAdmin(struct sqlConnection *conn, char *userEmail)
/* Return true if the user is an admin */
{
char query[256];
sqlSafef(query, sizeof(query), "select isAdmin from cdwUser where email = '%s'", userEmail);
int isAdmin = sqlQuickNum(conn, query);
if (isAdmin == 1) return TRUE;
return FALSE;
}
void cdwWarnUnregisteredUser(char *email)
/* Put up warning message about unregistered user and tell them how to register. */
{
warn("No user exists with email %s. If you need an account please contact your "
"CIRM DCC data wrangler and have them create an account for you."
, email);
}
struct cdwUser *cdwMustGetUserFromEmail(struct sqlConnection *conn, char *email)
/* Return user associated with email or put up error message. */
{
struct cdwUser *user = cdwUserFromEmail(conn, email);
if (user == NULL)
{
cdwWarnUnregisteredUser(email);
noWarnAbort();
}
return user;
}
struct cdwGroup *cdwGroupFromName(struct sqlConnection *conn, char *name)
/* Return cdwGroup of given name or NULL if not found. */
{
char query[256];
sqlSafef(query, sizeof(query), "select * from cdwGroup where name='%s'", name);
return cdwGroupLoadByQuery(conn, query);
}
struct cdwGroup *cdwNeedGroupFromName(struct sqlConnection *conn, char *groupName)
/* Get named group or die trying */
{
struct cdwGroup *group = cdwGroupFromName(conn, groupName);
if (group == NULL)
errAbort("Group %s doesn't exist", groupName);
return group;
}
boolean cdwFileInGroup(struct sqlConnection *conn, unsigned int fileId, unsigned int groupId)
/* Return TRUE if file is in group */
{
char query[256];
sqlSafef(query, sizeof(query), "select count(*) from cdwGroupFile where fileId=%u and groupId=%u",
fileId, groupId);
return sqlQuickNum(conn, query) > 0;
}
int cdwUserFileGroupsIntersect(struct sqlConnection *conn, long long fileId, int userId)
/* Return the number of groups file and user have in common, zero for no match */
{
char query[512];
sqlSafef(query, sizeof(query),
"select count(*) from cdwGroupUser,cdwGroupFile "
" where cdwGroupUser.groupId = cdwGroupFile.groupId "
" and cdwGroupUser.userId = %d and cdwGroupFile.fileId = %lld"
, userId, fileId);
verbose(2, "%s\n", query);
return sqlQuickNum(conn, query);
}
struct rbTree *cdwFilesWithSharedGroup(struct sqlConnection *conn, int userId)
/* Make an intVal type tree where the keys are fileIds and the val is null
* This contains all files that are associated with any group that user is part of.
* Can be used to do quicker version of cdwCheckAccess. */
{
struct rbTree *groupedFiles = intValTreeNew();
char query[256];
sqlSafef(query, sizeof(query),
"select distinct(fileId) from cdwGroupFile,cdwGroupUser "
" where cdwGroupUser.groupId = cdwGroupFile.groupId "
" and cdwGroupUser.userId = %d", userId);
struct sqlResult *sr = sqlGetResult(conn, query);
char **row;
while ((row = sqlNextRow(sr)) != NULL)
{
long long fileId = sqlLongLong(row[0]);
intValTreeAdd(groupedFiles, fileId, NULL);
}
sqlFreeResult(&sr);
return groupedFiles;
}
static boolean checkAccess(struct rbTree *groupedFiles, struct sqlConnection *conn,
struct cdwFile *ef, struct cdwUser *user, int accessType)
/* See if user should be allowed this level of access. The accessType is one of
* cdwAccessRead or cdwAccessWrite. Write access implies read access too.
* This can be called with user as NULL, in which case only access to shared-with-all
* files is granted.
* Since the most time consuming part of the operation involved the group access
* check, parts of this can be precomputed in the groupedFiles tree. */
{
/* First check for public access. */
if (ef->allAccess >= accessType)
return TRUE;
/* Everything else requires an actual user */
if (user == NULL)
return FALSE;
/* Check for user individual access */
if (ef->userId == user->id && ef->userAccess >= accessType)
return TRUE;
/* Check admin-level access */
if (user->isAdmin)
return TRUE;
/* Check group access, this involves SQL query */
if (ef->groupAccess >= accessType)
{
if (groupedFiles != NULL)
return intValTreeLookup(groupedFiles, ef->id) != NULL;
else
return cdwUserFileGroupsIntersect(conn, ef->id, user->id);
}
return FALSE;
}
boolean cdwCheckAccess(struct sqlConnection *conn, struct cdwFile *ef,
struct cdwUser *user, int accessType)
/* See if user should be allowed this level of access. The accessType is one of
* cdwAccessRead or cdwAccessWrite. Write access implies read access too.
* This can be called with user as NULL, in which case only access to shared-with-all
* files is granted. This function takes almost a millisecond. If you are doing it
* to many files consider using cdwQuickCheckAccess instead. */
{
return checkAccess(NULL, conn, ef, user, accessType);
}
boolean cdwQuickCheckAccess(struct rbTree *groupedFiles, struct cdwFile *ef,
struct cdwUser *user, int accessType)
/* See if user should be allowed this level of access. The groupedFiles is
* the result of a call to cdwFilesWithSharedGroup. The other parameters are as
* cdwCheckAccess. If you are querying thousands of files, this function is hundreds
* of times faster though. */
{
return checkAccess(groupedFiles, NULL, ef, user, accessType);
}
long long cdwCountAccessible(struct sqlConnection *conn, struct cdwUser *user)
/* Return total number of files associated user can access */
{
long long count = 0;
if (user == NULL)
{
char query[256];
sqlSafef(query, sizeof(query),
"select count(*) from cdwFile,cdwValidFile "
" where cdwFile.id = cdwValidFile.fileId and allAccess > 0"
" and (errorMessage='' or errorMessage is null)"
);
count = sqlQuickLongLong(conn, query);
}
else
{
struct rbTree *groupedFiles = cdwFilesWithSharedGroup(conn, user->id);
char query[256];
sqlSafef(query, sizeof(query),
"select cdwFile.* from cdwFile,cdwValidFile "
" where cdwFile.id = cdwValidFile.fileId "
" and (errorMessage='' or errorMessage is null)"
);
struct cdwFile *ef, *efList = cdwFileLoadByQuery(conn, query);
for (ef = efList; ef != NULL; ef = ef->next)
{
if (cdwQuickCheckAccess(groupedFiles, ef, user, cdwAccessRead))
++count;
}
cdwFileFree(&efList);
rbTreeFree(&groupedFiles);
}
return count;
}
struct cdwFile *cdwAccessibleFileList(struct sqlConnection *conn, struct cdwUser *user)
/* Get list of all files user can access. Null user means just publicly accessible. */
{
if (user == NULL) // No user, just publicly readable files then
{
char query[256];
sqlSafef(query, sizeof(query),
"select cdwFile.* from cdwFile,cdwValidFile "
" where cdwFile.id = cdwValidFile.fileId and allAccess > 0"
" and (errorMessage='' or errorMessage is null)");
return cdwFileLoadByQuery(conn, query);
}
else // Load all valid files and check access one at a time
{
struct rbTree *groupedFiles = cdwFilesWithSharedGroup(conn, user->id);
struct cdwFile *accessibleList = NULL, *validList = cdwFileLoadAllValid(conn);
struct cdwFile *ef, *next;
for (ef = validList; ef != NULL; ef = next)
{
next = ef->next;
if (cdwQuickCheckAccess(groupedFiles, ef, user, cdwAccessRead))
{
slAddHead(&accessibleList, ef);
}
else
{
cdwFileFree(&ef);
}
}
rbTreeFree(&groupedFiles);
slReverse(&accessibleList);
return accessibleList;
}
}
struct rbTree *cdwAccessTreeForUser(struct sqlConnection *conn, struct cdwUser *user,
struct cdwFile *efList, struct rbTree *groupedFiles)
/* Construct intVal tree of files from efList that we have access to. The
* key is the fileId, the value is the cdwFile object */
{
struct rbTree *accessTree = intValTreeNew(0);
struct cdwFile *ef;
for (ef = efList; ef != NULL; ef = ef->next)
{
if (cdwQuickCheckAccess(groupedFiles, ef, user, cdwAccessRead))
intValTreeAdd(accessTree, ef->id, ef);
}
return accessTree;
}
int cdwGetHost(struct sqlConnection *conn, char *hostName)
/* Look up host name in table and return associated ID. If not found
* make up new table entry. */
{
/* If it's already in table, just return ID. */
char query[512];
sqlSafef(query, sizeof(query), "select id from cdwHost where name='%s'", hostName);
int hostId = sqlQuickNum(conn, query);
if (hostId > 0)
return hostId;
sqlSafef(query, sizeof(query), "insert cdwHost (name, firstAdded, paraFetchStreams) values('%s', %lld, 10)",
hostName, cdwNow());
sqlUpdate(conn, query);
return sqlLastAutoId(conn);
}
int cdwGetSubmitDir(struct sqlConnection *conn, int hostId, char *submitDir)
/* Get submitDir from database, creating it if it doesn't already exist. */
{
/* If it's already in table, just return ID. */
char query[512];
sqlSafef(query, sizeof(query), "select id from cdwSubmitDir where url='%s'", submitDir);
int dirId = sqlQuickNum(conn, query);
if (dirId > 0)
return dirId;
sqlSafef(query, sizeof(query),
"insert cdwSubmitDir (url, firstAdded, hostId) values('%s', %lld, %d)",
submitDir, cdwNow(), hostId);
sqlUpdate(conn, query);
return sqlLastAutoId(conn);
}
void cdwMakeLicensePlate(char *prefix, int ix, char *out, int outSize)
/* Make a license-plate type string composed of prefix + funky coding of ix
* and put result in out. */
{
int maxIx = 10*10*10*26*26*26;
if (ix < 0)
errAbort("ix must be positive in cdwMakeLicensePlate");
if (ix > maxIx)
errAbort("ix exceeds max in cdwMakeLicensePlate. ix %d, max %d\n", ix, maxIx);
int prefixSize = strlen(prefix);
int minSize = prefixSize + 6 + 1;
if (outSize < minSize)
errAbort("outSize (%d) not big enough in cdwMakeLicensePlate", outSize);
/* Copy in prefix. */
strcpy(out, prefix);
/* Generate the 123ABC part of license plate backwards. */
char *s = out+minSize;
int x = ix - 1; // -1 so start with AAA not AAB
*(--s) = 0; // zero tag at end;
int i;
for (i=0; i<3; ++i)
{
int remainder = x%26;
*(--s) = 'A' + remainder;
x /= 26;
}
for (i=0; i<3; ++i)
{
int remainder = x%10;
*(--s) = '0' + remainder;
x /= 10;
}
}
void cdwDirForTime(time_t sinceEpoch, char dir[PATH_LEN])
/* Return the output directory for a given time. */
{
/* Get current time parsed into struct tm */
struct tm now;
gmtime_r(&sinceEpoch, &now);
/* make directory string out of year/month/day/ */
safef(dir, PATH_LEN, "%d/%d/%d/", now.tm_year+1900, now.tm_mon+1, now.tm_mday);
}
char *lastMatchCharExcept(char *start, char *end, char match, char except)
/* Return last char between start up to but not including end that is match.
* However if except occurs between end and this match, return NULL instead.
* Also return NULL if there is no match */
{
char *e = end;
while (--e >= start)
{
char c = *e;
if (c == except)
return NULL;
if (c == match)
return e;
}
return NULL;
}
void cdwMakeBabyName(unsigned long id, char *baseName, int baseNameSize)
/* Given a numerical ID, make an easy to pronouce file name */
{
char *consonants = "bdfghjklmnprstvwxyz"; // Avoid c and q because make sound ambiguous
char *vowels = "aeiou";
int consonantCount = strlen(consonants);
int vowelCount = strlen(vowels);
assert(id >= 1);
unsigned long ix = id - 1; /* We start at zero not 1 */
int basePos = 0;
do
{
char v = vowels[ix%vowelCount];
ix /= vowelCount;
char c = consonants[ix%consonantCount];
ix /= consonantCount;
if (basePos + 2 >= baseNameSize)
errAbort("Not enough room for %lu in %d letters in cdwMakeBabyName", id, baseNameSize);
baseName[basePos] = c;
baseName[basePos+1] = v;
basePos += 2;
}
while (ix > 0);
baseName[basePos] = 0;
}
char *cdwFindDoubleFileSuffix(char *path)
/* Return pointer to second from last '.' in part of path between last / and end.
* If there aren't two dots, just return pointer to normal single dot suffix. */
{
int nameSize = strlen(path);
char *suffix = lastMatchCharExcept(path, path + nameSize, '.', '/');
if (suffix != NULL)
{
if (sameString(suffix, ".gz") || sameString(suffix, ".bigBed"))
{
char *secondSuffix = lastMatchCharExcept(path, suffix, '.', '/');
if (secondSuffix != NULL)
suffix = secondSuffix;
}
}
else
suffix = path + nameSize;
return suffix;
}
void cdwMakeFileNameAndPath(int cdwFileId, char *submitFileName, char cdwFile[PATH_LEN], char serverPath[PATH_LEN])
/* Convert file id to local file name, and full file path. Make any directories needed
* along serverPath. */
{
/* Preserve suffix. Give ourselves up to two suffixes. */
char *suffix = cdwFindDoubleFileSuffix(submitFileName);
/* Figure out cdw file name, starting with baseName. */
char baseName[32];
cdwMakeBabyName(cdwFileId, baseName, sizeof(baseName));
/* Figure out directory and make any components not already there. */
char cdwDir[PATH_LEN];
cdwDirForTime(cdwNow(), cdwDir);
char uploadDir[PATH_LEN];
safef(uploadDir, sizeof(uploadDir), "%s%s", cdwRootDir, cdwDir);
makeDirsOnPath(uploadDir);
/* Figure out full file names */
safef(cdwFile, PATH_LEN, "%s%s%s", cdwDir, baseName, suffix);
safef(serverPath, PATH_LEN, "%s%s", cdwRootDir, cdwFile);
}
char *cdwSetting(struct sqlConnection *conn, char *name)
/* Return named settings value, or NULL if setting doesn't exist. FreeMem when done. */
{
char query[256];
sqlSafef(query, sizeof(query), "select val from cdwSettings where name='%s'", name);
return sqlQuickString(conn, query);
}
char *cdwRequiredSetting(struct sqlConnection *conn, char *name)
/* Returns setting, abort if it isn't found. FreeMem when done. */
{
char *val = cdwSetting(conn, name);
if (val == NULL)
errAbort("Required %s setting is not defined in cdwSettings table", name);
return val;
}
char *cdwLicensePlateHead(struct sqlConnection *conn)
/* Return license plate prefix for current database - something like TSTFF or DEVFF or ENCFF */
{
static char head[32];
if (head[0] == 0)
{
char *prefix = cdwRequiredSetting(conn, "prefix");
safef(head, sizeof(head), "%s", prefix);
}
return head;
}
static char *localHostName = "localhost";
static char *localHostDir = "";
static int getLocalHost(struct sqlConnection *conn)
/* Make up record for local host if it is not there already. */
{
char query[256];
sqlSafef(query, sizeof(query), "select id from cdwHost where name = '%s'", localHostName);
int hostId = sqlQuickNum(conn, query);
if (hostId == 0)
{
sqlSafef(query, sizeof(query), "insert cdwHost(name, firstAdded) values('%s', %lld)",
localHostName, cdwNow());
sqlUpdate(conn, query);
hostId = sqlLastAutoId(conn);
}
return hostId;
}
static int getLocalSubmitDir(struct sqlConnection *conn)
/* Get submit dir for local submissions, making it up if it does not exist. */
{
int hostId = getLocalHost(conn);
char query[256];
sqlSafef(query, sizeof(query), "select id from cdwSubmitDir where url='%s' and hostId=%d",
localHostDir, hostId);
int dirId = sqlQuickNum(conn, query);
if (dirId == 0)
{
sqlSafef(query, sizeof(query), "insert cdwSubmitDir(url,hostId,firstAdded) values('%s',%d,%lld)",
localHostDir, hostId, cdwNow());
sqlUpdate(conn, query);
dirId = sqlLastAutoId(conn);
}
return dirId;
}
static int getLocalSubmit(struct sqlConnection *conn)
/* Get the submission that covers all of our local additions. */
{
int dirId = getLocalSubmitDir(conn);
char query[256];
sqlSafef(query, sizeof(query), "select id from cdwSubmit where submitDirId='%d'", dirId);
int submitId = sqlQuickNum(conn, query);
if (submitId == 0)
{
sqlSafef(query, sizeof(query), "insert cdwSubmit (submitDirId,startUploadTime) values(%d,%lld)",
dirId, cdwNow());
sqlUpdate(conn, query);
submitId = sqlLastAutoId(conn);
}
return submitId;
}
char **sqlNeedNextRow(struct sqlResult *sr)
/* Get next row or die trying. Since the error reporting is not good, please only
* use when an error would be unusual. */
{
char **row = sqlNextRow(sr);
if (row == NULL)
errAbort("Unexpected empty result from database.");
return row;
}
void cdwUpdateFileTags(struct sqlConnection *conn, long long fileId, struct dyString *tags)
/* Update tags field in cdwFile with given value */
{
struct dyString *query = dyStringNew(0);
sqlDyStringPrintf(query, "update cdwFile set tags='%s' ", tags->string);
sqlDyStringPrintf(query, " where id=%lld", fileId);
sqlUpdate(conn, query->string);
dyStringFree(&query);
}
struct cdwFile *cdwGetLocalFile(struct sqlConnection *conn, char *localAbsolutePath,
char *givenMd5Sum)
/* Get record of local file from database, adding it if it doesn't already exist.
* Can make it a symLink rather than a copy in which case pass in valid MD5 sum
* for symLinkM5dSum. */
{
/* First do a reality check on the local absolute path. Is there a file there? */
if (localAbsolutePath[0] != '/')
errAbort("Using relative path in cdwAddLocalFile.");
long long size = fileSize(localAbsolutePath);
if (size == -1)
errAbort("%s does not exist", localAbsolutePath);
long long updateTime = fileModTime(localAbsolutePath);
/* Get file if it's in database already. */
int submitDirId = getLocalSubmitDir(conn);
int submitId = getLocalSubmit(conn);
char query[256+PATH_LEN];
sqlSafef(query, sizeof(query), "select * from cdwFile where submitId=%d and submitFileName='%s'",
submitId, localAbsolutePath);
struct cdwFile *ef = cdwFileLoadByQuery(conn, query);
/* If we got something in database, check update time and size, and if it's no change just
* return existing database id. */
if (ef != NULL && ef->updateTime == updateTime && ef->size == size)
return ef;
/* If we got here, then we need to make a new file record. Start with pretty empty record
* that just has file ID, submitted file name and a few things*/
sqlSafef(query, sizeof(query),
"insert cdwFile (submitId,submitDirId,submitFileName,startUploadTime) "
" values(%d, %d, '%s', %lld)"
, submitId, submitDirId, localAbsolutePath, cdwNow());
sqlUpdate(conn, query);
long long fileId = sqlLastAutoId(conn);
/* Create big data warehouse file/path name. */
char cdwFile[PATH_LEN], cdwPath[PATH_LEN];
cdwMakeFileNameAndPath(fileId, localAbsolutePath, cdwFile, cdwPath);
/* We're a little paranoid so md5 it */
char *md5;
/* Do copy or symbolic linking of file into warehouse managed dir. */
if (givenMd5Sum)
{
md5 = givenMd5Sum;
}
else
{
md5 = md5HexForFile(localAbsolutePath);
}
copyFile(localAbsolutePath, cdwPath);
touchFileFromFile(localAbsolutePath, cdwPath);
chmod(cdwPath, 0444);
replaceOriginalWithSymlink(localAbsolutePath, "", cdwPath);
/* Update file record. */
sqlSafef(query, sizeof(query),
"update cdwFile set cdwFileName='%s', endUploadTime=%lld,"
"updateTime=%lld, size=%lld, md5='%s' where id=%lld"
, cdwFile, cdwNow(), updateTime, size, md5, fileId);
sqlUpdate(conn, query);
/* Now, it's a bit of a time waste, but cheap in code, to just load it back from DB. */
sqlSafef(query, sizeof(query), "select * from cdwFile where id=%lld", fileId);
return cdwFileLoadByQuery(conn, query);
}
struct cdwFile *cdwFileLoadAllValid(struct sqlConnection *conn)
/* Get list of cdwFiles that have been validated with no error */
{
char query[256];
sqlSafef(query, sizeof(query),
"select cdwFile.* from cdwFile,cdwValidFile "
" where cdwFile.id=cdwValidFile.fileId "
" and (cdwFile.errorMessage='' or cdwFile.errorMessage is null)");
return cdwFileLoadByQuery(conn, query);
}
struct cdwFile *cdwFileAllIntactBetween(struct sqlConnection *conn, int startId, int endId)
/* Return list of all files that are intact (finished uploading and MD5 checked)
* with file IDs between startId and endId - including endId */
{
char query[256];
sqlSafef(query, sizeof(query),
"select * from cdwFile where id>=%d and id<=%d and endUploadTime != 0 "
"and updateTime != 0 and (errorMessage = '' or errorMessage is NULL) and deprecated = ''",
startId, endId);
return cdwFileLoadByQuery(conn, query);
}
long long cdwFindInSameSubmitDir(struct sqlConnection *conn,
struct cdwFile *ef, char *submitFileName)
/* Return fileId of most recent file of given submitFileName from submitDir
* associated with file */
{
char query[3*PATH_LEN];
sqlSafef(query, sizeof(query),
"select cdwFile.id from cdwFile,cdwSubmitDir "
"where cdwFile.submitDirId = cdwSubmitDir.id and "
"cdwSubmitDir.id = %d and "
"cdwFile.submitFileName = '%s' order by cdwFile.id desc"
, ef->submitDirId, submitFileName);
return sqlQuickLongLong(conn, query);
}
struct cdwFile *cdwFileFromId(struct sqlConnection *conn, long long fileId)
/* Return cdwValidFile given fileId - return NULL if not found. */
{
char query[128];
sqlSafef(query, sizeof(query), "select * from cdwFile where id=%lld", fileId);
return cdwFileLoadByQuery(conn, query);
}
struct cdwFile *cdwFileFromIdOrDie(struct sqlConnection *conn, long long fileId)
/* Return cdwValidFile given fileId - aborts if not found. */
{
struct cdwFile *ef = cdwFileFromId(conn, fileId);
if (ef == NULL)
errAbort("Couldn't find file for id %lld\n", fileId);
return ef;
}
int cdwFileIdFromPathSuffix(struct sqlConnection *conn, char *suf)
/* return most recent fileId for file where submitDir.url+submitFname ends with suf. 0 if not found. */
{
char query[4096];
int sufLen = strlen(suf);
sqlSafef(query, sizeof(query), "SELECT cdwFile.id FROM cdwSubmitDir, cdwFile "
"WHERE cdwFile.submitDirId=cdwSubmitDir.id AND RIGHT(CONCAT_WS('/', cdwSubmitDir.url, submitFileName), %d)='%s' "
"ORDER BY cdwFile.id DESC LIMIT 1;", sufLen, suf);
int fileId = sqlQuickNum(conn, query);
return fileId;
}
struct cdwValidFile *cdwValidFileFromFileId(struct sqlConnection *conn, long long fileId)
/* Return cdwValidFile give fileId - returns NULL if not validated. */
{
char query[128];
sqlSafef(query, sizeof(query), "select * from cdwValidFile where fileId=%lld", fileId);
return cdwValidFileLoadByQuery(conn, query);
}
struct cdwValidFile *cdwValidFileFromLicensePlate(struct sqlConnection *conn, char *licensePlate)
/* Return cdwValidFile from license plate - returns NULL if not found. */
{
char query[128];
sqlSafef(query, sizeof(query), "select * from cdwValidFile where licensePlate='%s'", licensePlate);
return cdwValidFileLoadByQuery(conn, query);
}
struct cdwExperiment *cdwExperimentFromAccession(struct sqlConnection *conn, char *acc)
/* Given something like 'ENCSR123ABC' return associated experiment. */
{
char query[128];
sqlSafef(query, sizeof(query), "select * from cdwExperiment where accession='%s'", acc);
return cdwExperimentLoadByQuery(conn, query);
}
struct genomeRangeTree *cdwMakeGrtFromBed3List(struct bed3 *bedList)
/* Make up a genomeRangeTree around bed file. */
{
struct genomeRangeTree *grt = genomeRangeTreeNew();
struct bed3 *bed;
for (bed = bedList; bed != NULL; bed = bed->next)
genomeRangeTreeAdd(grt, bed->chrom, bed->chromStart, bed->chromEnd);
return grt;
}
struct cdwAssembly *cdwAssemblyForUcscDb(struct sqlConnection *conn, char *ucscDb)
/* Get assembly for given UCSC ID or die trying */
{
char query[256];
sqlSafef(query, sizeof(query), "select * from cdwAssembly where ucscDb='%s'", ucscDb);
struct cdwAssembly *assembly = cdwAssemblyLoadByQuery(conn, query);
if (assembly == NULL)
errAbort("Can't find assembly for %s", ucscDb);
return assembly;
}
struct cdwAssembly *cdwAssemblyForId(struct sqlConnection *conn, long long id)
/* Get assembly of given ID. */
{
char query[128];
sqlSafef(query, sizeof(query), "select * from cdwAssembly where id=%lld", id);
struct cdwAssembly *assembly = cdwAssemblyLoadByQuery(conn, query);
if (assembly == NULL)
errAbort("Can't find assembly for %lld", id);
return assembly;
}
char *cdwSimpleAssemblyName(char *assembly)
/* Given compound name like male.hg19 return just hg19 */
/* Given name of assembly return name where we want to do enrichment calcs. */
{
/* If it ends with one of our common assembly suffix, then do enrichment calcs
* in that space, rather than some subspace such as male, female, etc. */
static char *specialAsm[] = {".hg19",".hg38",".mm9",".mm10",".dm3",".ce10",".dm6"};
int i;
for (i=0; i<ArraySize(specialAsm); ++i)
{
char *special = specialAsm[i];
if (endsWith(assembly, special))
return special+1;
}
return assembly;
}
struct genomeRangeTree *cdwGrtFromBigBed(char *fileName)
/* Return genome range tree for simple (unblocked) bed */
{
struct bbiFile *bbi = bigBedFileOpen(fileName);
struct bbiChromInfo *chrom, *chromList = bbiChromList(bbi);
struct genomeRangeTree *grt = genomeRangeTreeNew();
for (chrom = chromList; chrom != NULL; chrom = chrom->next)
{
struct rbTree *tree = genomeRangeTreeFindOrAddRangeTree(grt, chrom->name);
struct lm *lm = lmInit(0);
struct bigBedInterval *iv, *ivList = NULL;
ivList = bigBedIntervalQuery(bbi, chrom->name, 0, chrom->size, 0, lm);
for (iv = ivList; iv != NULL; iv = iv->next)
rangeTreeAdd(tree, iv->start, iv->end);
lmCleanup(&lm);
}
bigBedFileClose(&bbi);
bbiChromInfoFreeList(&chromList);
return grt;
}
boolean cdwIsSupportedBigBedFormat(char *format)
/* Return TRUE if it's one of the bigBed formats we support. */
{
int i;
if (sameString(format, "bigBed")) // Generic bigBed ok
return TRUE;
for (i=0; i<cdwBedTypeCount; ++i)
{
if (sameString(format, cdwBedTypeTable[i].name))
return TRUE;
}
return FALSE;
}
void cdwWriteErrToTable(struct sqlConnection *conn, char *table, int id, char *err)
/* Write out error message to errorMessage field of table. */
{
char *trimmedError = trimSpaces(err);
struct dyString *query = dyStringNew(0);
sqlDyStringPrintf(query, "update %s set errorMessage='%s' where id=%d",
table, trimmedError, id);
sqlUpdate(conn, query->string);
dyStringFree(&query);
}
void cdwWriteErrToStderrAndTable(struct sqlConnection *conn, char *table, int id, char *err)
/* Write out error message to errorMessage field of table and through stderr. */
{
warn("%s", trimSpaces(err));
cdwWriteErrToTable(conn, table, id, err);
}
void cdwAddJob(struct sqlConnection *conn, char *command, int submitId)
/* Add job to queue to run. */
{
char query[256+strlen(command)];
sqlSafef(query, sizeof(query), "insert into cdwJob (commandLine,submitId) values('%s',%d)",
command, submitId);
sqlUpdate(conn, query);
}
void cdwAddQaJob(struct sqlConnection *conn, long long fileId, int submitId)
/* Create job to do QA on this and add to queue */
{
char command[64];
safef(command, sizeof(command), "cdwQaAgent %lld", fileId);
cdwAddJob(conn, command, submitId);
}
int cdwSubmitPositionInQueue(struct sqlConnection *conn, char *url, unsigned *retJobId)
/* Return position of our URL in submission queue. Optionally return id in cdwSubmitJob
* table of job. */
{
char query[256];
sqlSafef(query, sizeof(query), "select id,commandLine from cdwSubmitJob where startTime = 0");
struct sqlResult *sr = sqlGetResult(conn, query);
char **row;
int aheadOfUs = -1;
int pos = 0;
unsigned jobId = 0;
while ((row = sqlNextRow(sr)) != NULL)
{
jobId = sqlUnsigned(row[0]);
char *line = row[1];
char *cdwSubmit = nextQuotedWord(&line);
char *lineUrl = nextQuotedWord(&line);
if (sameOk(cdwSubmit, "cdwSubmit") && sameOk(url, lineUrl))
{
aheadOfUs = pos;
break;
}
++pos;
}
sqlFreeResult(&sr);
if (retJobId != NULL)
*retJobId = jobId;
return aheadOfUs;
}
struct cdwSubmitDir *cdwSubmitDirFromId(struct sqlConnection *conn, long long id)
/* Return submissionDir with given ID or NULL if no such submission. */
{
char query[256];
sqlSafef(query, sizeof(query), "select * from cdwSubmitDir where id=%lld", id);
return cdwSubmitDirLoadByQuery(conn, query);
}
struct cdwSubmit *cdwSubmitFromId(struct sqlConnection *conn, long long id)
/* Return submission with given ID or NULL if no such submission. */
{
char query[256];
sqlSafef(query, sizeof(query), "select * from cdwSubmit where id=%lld", id);
return cdwSubmitLoadByQuery(conn, query);
}
struct cdwSubmit *cdwMostRecentSubmission(struct sqlConnection *conn, char *url)
/* Return most recent submission, possibly in progress, from this url */
{
int urlSize = strlen(url);
char query[128 + 2*urlSize + 1];
sqlSafef(query, sizeof(query),
"select * from cdwSubmit where url='%s' order by id desc limit 1", url);
return cdwSubmitLoadByQuery(conn, query);
}
long long cdwSubmitMaxStartTime(struct cdwSubmit *submit, struct sqlConnection *conn)
/* Figure out when we started most recent single file in the upload, or when
* we started if not files started yet. */
{
char query[256];
sqlSafef(query, sizeof(query),
"select max(startUploadTime) from cdwFile where submitId=%u", submit->id);
long long maxStartTime = sqlQuickLongLong(conn, query);
if (maxStartTime == 0)
maxStartTime = submit->startUploadTime;
return maxStartTime;
}
int cdwSubmitCountNewValid(struct cdwSubmit *submit, struct sqlConnection *conn)
/* Count number of new files in submission that have been validated. */
{
char query[256];
sqlSafef(query, sizeof(query),
"select count(*) from cdwFile e,cdwValidFile v where e.id = v.fileId and e.submitId=%u",
submit->id);
return sqlQuickNum(conn, query);
}
int cdwSubmitCountErrors(struct cdwSubmit *submit, struct sqlConnection *conn)
/* Count number of errors with submitted files */
{
char query[256];
sqlSafef(query, sizeof(query),
"select count(*) from cdwFile where submitId=%u and errorMessage != '' and errorMessage is not null",
submit->id);
return sqlQuickNum(conn, query);
}
boolean cdwSubmitIsValidated(struct cdwSubmit *submit, struct sqlConnection *conn)
/* Return TRUE if validation has run. This does not mean that they all passed validation.
* It just means the validator has run and has made a decision on each file in the submission. */
{
/* Is this off by one because of the validated.txt being in the submission but never validated? */
return cdwSubmitCountErrors(submit,conn) + cdwSubmitCountNewValid(submit, conn) == submit->newFiles;
}
void cdwAddSubmitJob(struct sqlConnection *conn, char *userEmail, char *url, boolean update)
/* Add submission job to table and wake up daemon. */
{
/* Create command and add it to cdwSubmitJob table. */
char command[strlen(url) + strlen(userEmail) + 256];
safef(command, sizeof(command), "cdwSubmit %s'%s' %s", (update ? "-update " : ""), url, userEmail);
char query[strlen(command)+128];
sqlSafef(query, sizeof(query), "insert cdwSubmitJob (commandLine) values('%s')", command);
sqlUpdate(conn, query);
/* Write sync signal (any string ending with newline) to fifo to wake up daemon. */
FILE *fifo = mustOpen("../userdata/cdwSubmit.fifo", "w");
fputc('\n', fifo);
carefulClose(&fifo);
}
struct cdwValidFile *cdwFindElderReplicates(struct sqlConnection *conn, struct cdwValidFile *vf)
/* Find all replicates of same output and format type for experiment that are elder
* (fileId less than your file Id). Younger replicates are responsible for taking care
* of correlations with older ones. Sorry younguns, it's like social security. */
{
if (sameString(vf->format, "unknown"))
return NULL;
char query[256];
sqlSafef(query, sizeof(query),
"select * from cdwValidFile where id<%d and experiment='%s' and format='%s'"
" and outputType='%s'"
, vf->id, vf->experiment, vf->format, vf->outputType);
return cdwValidFileLoadByQuery(conn, query);
}
#ifdef OLD
void cdwWebHeaderWithPersona(char *title)
/* Print out HTTP and HTML header through <BODY> tag with persona info */
{
printf("Content-Type:text/html\r\n");
printf("\r\n\r\n");
puts("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" "
"\"http://www.w3.org/TR/html4/loose.dtd\">");
printf("<HTML><HEAD><TITLE>%s</TITLE>\n", "CIRM Data Warehouse");
puts("<meta http-equiv='X-UA-Compatible' content='IE=Edge'>");
// Use CIRM3 CSS for common look
puts("<link rel='stylesheet' href='/style/cirm.css' type='text/css'>");
puts("<link rel='stylesheet' href='/style/cirmUcsc.css' type='text/css'>");
// external link icon (box with arrow) is from FontAwesome (fa-external-link)
puts("<link href='//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css' rel='stylesheet'>");
puts("<script type='text/javascript' SRC='/js/jquery.js'></script>");
puts("<script type='text/javascript' SRC='/js/jquery.cookie.js'></script>");
puts("<script type='text/javascript' src='https://login.persona.org/include.js'></script>");
puts("<script type='text/javascript' src='/js/cdwPersona.js'></script>");
puts("<script type='text/javascript' src='https://cdnjs.cloudflare.com/ajax/libs/bowser/1.6.1/bowser.min.js'></script>");
puts("</HEAD>");
/* layout with navigation bar */
puts("<BODY>\n");
cdwWebNavBarStart();
}
#endif /* OLD */
#ifdef OLD
void cdwWebFooterWithPersona()
/* Print out end tags and persona script stuff */
{
cdwWebNavBarEnd();
htmlEnd();
}
#endif /* OLD */
void cdwCreateNewUser(char *email)
/* Create new user, checking that user does not already exist. */
{
/* Now make sure user is not already in user table. */
struct sqlConnection *conn = cdwConnectReadWrite();
struct dyString *query = dyStringNew(0);
sqlDyStringPrintf(query, "select count(*) from cdwUser where email = '%s'", email);
if (sqlQuickNum(conn, query->string) > 0)
errAbort("User %s already exists", email);
/* Do database insert. */
dyStringClear(query);
sqlDyStringPrintf(query, "insert into cdwUser (email) values('%s')", email);
sqlUpdate(conn, query->string);
sqlDisconnect(&conn);
}
void cdwPrintLogOutButton()
/* Print log out button */
{
printf("<INPUT TYPE=button NAME=\"signOut\" VALUE=\"sign out\" id=\"signout\">");
}
struct dyString *cdwFormatDuration(long long seconds)
/* Convert seconds to days/hours/minutes. Return result in a dyString you can free */
{
struct dyString *dy = dyStringNew(0);
int days = seconds/(3600*24);
if (days > 0)
dyStringPrintf(dy, "%d days, ", days);
seconds -= days*3600*24;
int hours = seconds/3600;
if (hours > 0 || days > 0)
dyStringPrintf(dy, "%d hours", hours);
seconds -= hours*3600;
if (days == 0)
{
int minutes = seconds/60;
if (minutes > 0)
{
if (hours > 0)
dyStringPrintf(dy, ", ");
dyStringPrintf(dy, "%d minutes", minutes);
}
if (hours == 0)
{
if (minutes > 0)
dyStringPrintf(dy, ", ");
seconds -= minutes*60;
dyStringPrintf(dy, "%d seconds", (int)seconds);
}
}
return dy;
}
struct cdwFile *cdwFileInProgress(struct sqlConnection *conn, int submitId)
/* Return file in submission in process of being uploaded if any. */
{
char query[256];
sqlSafef(query, sizeof(query), "select fileIdInTransit from cdwSubmit where id=%u", submitId);
long long fileId = sqlQuickLongLong(conn, query);
if (fileId == 0)
return NULL;
sqlSafef(query, sizeof(query), "select * from cdwFile where id=%lld", (long long)fileId);
return cdwFileLoadByQuery(conn, query);
}
static void accessDenied()
/* Sleep a bit and then deny access. */
{
sleep(5);
errAbort("Access denied!");
}
struct cdwScriptRegistry *cdwScriptRegistryFromCgi()
/* Get script registery from cgi variables. Does authentication too. */
{
struct sqlConnection *conn = cdwConnect();
char *user = sqlEscapeString(cgiString("user"));
char *password = sqlEscapeString(cgiString("password"));
char query[256];
sqlSafef(query, sizeof(query), "select * from cdwScriptRegistry where name='%s'", user);
struct cdwScriptRegistry *reg = cdwScriptRegistryLoadByQuery(conn, query);
if (reg == NULL)
accessDenied();
char key[CDW_SID_SIZE];
cdwMakeSid(password, key);
if (!sameString(reg->secretHash, key))
accessDenied();
sqlDisconnect(&conn);
return reg;
}
void cdwValidFileUpdateDb(struct sqlConnection *conn, struct cdwValidFile *el, long long id)
/* Save cdwValidFile as a row to the table specified by tableName, replacing existing record at
* id. */
{
struct dyString *dy = newDyString(512);
sqlDyStringPrintf(dy, "update cdwValidFile set ");
// omit id and licensePlate fields - one autoupdates and the other depends on this
// also omit fileId which also really can't change.
sqlDyStringPrintf(dy, " format='%s',", el->format);
sqlDyStringPrintf(dy, " outputType='%s',", el->outputType);
sqlDyStringPrintf(dy, " experiment='%s',", el->experiment);
sqlDyStringPrintf(dy, " replicate='%s',", el->replicate);
sqlDyStringPrintf(dy, " enrichedIn='%s',", el->enrichedIn);
sqlDyStringPrintf(dy, " ucscDb='%s',", el->ucscDb);
sqlDyStringPrintf(dy, " itemCount=%lld,", (long long)el->itemCount);
sqlDyStringPrintf(dy, " basesInItems=%lld,", (long long)el->basesInItems);
sqlDyStringPrintf(dy, " sampleCount=%lld,", (long long)el->sampleCount);
sqlDyStringPrintf(dy, " basesInSample=%lld,", (long long)el->basesInSample);
sqlDyStringPrintf(dy, " sampleBed='%s',", el->sampleBed);
sqlDyStringPrintf(dy, " mapRatio=%g,", el->mapRatio);
sqlDyStringPrintf(dy, " sampleCoverage=%g,", el->sampleCoverage);
sqlDyStringPrintf(dy, " depth=%g,", el->depth);
sqlDyStringPrintf(dy, " singleQaStatus=0,");
sqlDyStringPrintf(dy, " replicateQaStatus=0,");
sqlDyStringPrintf(dy, " part='%s',", el->part);
sqlDyStringPrintf(dy, " pairedEnd='%s',", el->pairedEnd);
sqlDyStringPrintf(dy, " qaVersion='%d',", el->qaVersion);
sqlDyStringPrintf(dy, " uniqueMapRatio=%g,", el->uniqueMapRatio);
sqlDyStringPrintf(dy, " lane='%s'", el->lane);
#if (CDWVALIDFILE_NUM_COLS != 24)
#error "Please update this routine with new column"
#endif
sqlDyStringPrintf(dy, " where id=%lld\n", (long long)id);
sqlUpdate(conn, dy->string);
freeDyString(&dy);
}
char *cdwLookupTag(struct cgiParsedVars *list, char *tag)
/* Return first occurence of tag on list, or empty string if not found */
{
char *ret = "";
struct cgiParsedVars *tags;
for (tags = list; tags != NULL; tags = tags->next)
{
char *val = hashFindVal(tags->hash, tag);
if (val != NULL && !sameString(val, "n/a"))
{
ret = val;
break;
}
}
return ret;
}
void cdwValidFileFieldsFromTags(struct cdwValidFile *vf, struct cgiParsedVars *tags)
/* Fill in many of vf's fields from tags. */
{
// Most fields are just taken directly from tags, converted from underbar to camelCased
// separation conventions.
vf->format = cloneString(cdwLookupTag(tags, "format"));
vf->outputType = cloneString(cdwLookupTag(tags, "output_type"));
vf->replicate = cloneString(cdwLookupTag(tags, "replicate"));
vf->enrichedIn = cloneString(cdwLookupTag(tags, "enriched_in"));
vf->ucscDb = cloneString(cdwLookupTag(tags, "ucsc_db"));
vf->part = cloneString(cdwLookupTag(tags, "file_part"));
vf->pairedEnd = cloneString(cdwLookupTag(tags, "paired_end"));
vf->lane = cloneString(cdwLookupTag(tags, "lane"));
// Experiment field defaults to same as meta, but sometimes needs to be different.
// Experiment field drives replicate comparisons.
char *experiment = cdwLookupTag(tags, "experiment");
if (isEmpty(experiment))
experiment = cdwLookupTag(tags, "meta");
vf->experiment = cloneString(experiment);
// Make sure we update this routine if we add fields to cdwValidFile
#if (CDWVALIDFILE_NUM_COLS != 24)
#error "Please update this routine with new column"
#endif
}
void cdwRemoveQaRecords(struct sqlConnection *conn, long long fileId)
/* Remove records associated with a file from all of the cdwQaXxx and cdwXxxFile
* tables */
{
char query[1024];
sqlSafef(query, sizeof(query), "delete from cdwFastqFile where fileId=%lld", fileId);
sqlUpdate(conn, query);
sqlSafef(query, sizeof(query), "delete from cdwBamFile where fileId=%lld", fileId);
sqlUpdate(conn, query);
sqlSafef(query, sizeof(query), "delete from cdwVcfFile where fileId=%lld", fileId);
sqlUpdate(conn, query);
sqlSafef(query, sizeof(query),
"delete from cdwQaPairSampleOverlap where elderFileId=%lld or youngerFileId=%lld",
fileId, fileId);
sqlUpdate(conn, query);
sqlSafef(query, sizeof(query),
"delete from cdwQaPairCorrelation where elderFileId=%lld or youngerFileId=%lld",
fileId, fileId);
sqlUpdate(conn, query);
sqlSafef(query, sizeof(query), "delete from cdwQaEnrich where fileId=%lld", fileId);
sqlUpdate(conn, query);
sqlSafef(query, sizeof(query), "delete from cdwQaContam where fileId=%lld", fileId);
sqlUpdate(conn, query);
sqlSafef(query, sizeof(query), "delete from cdwQaRepeat where fileId=%lld", fileId);
sqlUpdate(conn, query);
sqlSafef(query, sizeof(query),
"delete from cdwQaPairedEndFastq where fileId1=%lld or fileId2=%lld",
fileId, fileId);
sqlUpdate(conn, query);
}
int findSubmitSymlinkExt(char *submitFileName, char *submitDir, char **pPath, char **pLastPath, int *pSymlinkLevels)
/* Find the last symlink and real file in the chain from submitDir/submitFileName.
* This is useful for when target of symlink in cdw/ gets renamed
* (e.g. license plate after passes validation), or removed (e.g. cdwReallyRemove* commands).
* Returns 0 for success. /
* Returns -1 if path does not exist. */
{
int result = 0;
struct stat sb;
char *lastPath = NULL;
char *path = mustExpandRelativePath(submitDir, submitFileName);
int symlinkLevels = 0;
while (TRUE)
{
if (!fileExists(path))
{
//path=does not exist
result = -1;
break;
}
if (lstat(path, &sb) == -1)
errnoAbort("lstat failure on %s", path);
if ((sb.st_mode & S_IFMT) != S_IFLNK)
break;
// follow the symlink
++symlinkLevels;
if (symlinkLevels > 10)
errAbort("Too many symlinks followed: %d symlinks. Probably a symlink loop.", symlinkLevels);
// read the symlink
char *symPath = mustReadSymlinkExt(path, &sb);
// apply symPath to path
char *newPath = mustPathRelativeToFile(path, symPath);
freeMem(lastPath);
lastPath = path;
freeMem(symPath);
path = newPath;
}
if (result == 0 && ((sb.st_mode & S_IFMT) != S_IFREG))
errAbort("Expecting regular file. Followed symlinks to %s but it is not a regular file.", path);
*pPath = path;
*pLastPath = lastPath;
*pSymlinkLevels = symlinkLevels;
return result;
}
char *testOriginalSymlink(char *submitFileName, char *submitDir)
/* Follows submitted symlinks to real file.
* Aborts if real file path starts with cdwRootDir
* since it should not point to a file already under cdwRoot. */
{
char *lastPath = NULL;
char *path = NULL;
int symlinkLevels = 0;
int result = findSubmitSymlinkExt(submitFileName, submitDir, &path, &lastPath, &symlinkLevels);
if (result == -1) // path does not exist
{
errAbort("path=[%s] does not exist following submitDir/submitFileName through symlinks.", path);
}
if (startsWith(cdwRootDir, path))
errAbort("Unexpected operation. The symlink %s points to %s. It should not point to a file already under cdwRoot %s",
submitFileName, path, cdwRootDir);
freeMem(lastPath);
return path;
}
void replaceOriginalWithSymlink(char *submitFileName, char *submitDir, char *cdwPath)
/* For a file that was just copied, remove original and symlink to new one instead
* to save space. Follows symlinks if any to the real file and replaces it with a symlink */
{
char *path = testOriginalSymlink(submitFileName, submitDir);
if (unlink(path) == -1) // save space
errnoAbort("unlink failure %s", path);
makeSymLink(cdwPath, path);
verbose(1, "%s converted to symlink to %s\n", path, cdwPath);
freeMem(path);
}
char *findSubmitSymlink(char *submitFileName, char *submitDir, char *oldPath)
/* Find the last symlink in the chain from submitDir/submitFileName.
* This is useful for when target of symlink in cdw/ gets renamed
* (e.g. license plate after passes validation), or removed (e.g. cdwReallyRemove* commands). */
{
char *lastPath = NULL;
char *path = NULL;
int symlinkLevels = 0;
int result = findSubmitSymlinkExt(submitFileName, submitDir, &path, &lastPath, &symlinkLevels);
if (result == -1) // path does not exist
{
warn("path=[%s] does not exist following submitDir/submitFileName through symlinks.", path);
return NULL;
}
if (symlinkLevels < 1)
{
warn("Too few symlinks followed: %d symlinks. Where is the symlink created by cdwSubmit?", symlinkLevels);
return NULL;
}
if (!sameString(path, oldPath))
{
warn("Found symlinks point to %s, expecting to find symlink pointing to old path %s", path, oldPath);
return NULL;
}
freeMem(path);
return lastPath;
}
void cdwReallyRemoveFile(struct sqlConnection *conn, char *submitDir, long long fileId, boolean unSymlinkOnly, boolean really)
/* If unSymlinkOnly is NOT specified, removes all records of file from database and from Unix file system if
* the really flag is set. Otherwise just print some info on the file.
* Tries to find original submitdir and replace symlink with real file to restore it. */
{
struct cdwFile *ef = cdwFileFromId(conn, fileId);
char *path = cdwPathForFileId(conn, fileId);
verbose(1, "%s id=%u, submitFileName=%s, path=%s\n",
unSymlinkOnly ? "unlocking" : "removing", ef->id, ef->submitFileName, path);
if (really)
{
char query[1024];
struct cdwSubmit *es = cdwSubmitFromId(conn, ef->submitId);
if (!unSymlinkOnly)
{
cdwRemoveQaRecords(conn, fileId);
sqlSafef(query, sizeof(query),
"delete from cdwGroupFile where fileId=%lld", fileId);
sqlUpdate(conn, query);
sqlSafef(query, sizeof(query), "delete from cdwValidFile where fileId=%lld", fileId);
sqlUpdate(conn, query);
sqlSafef(query, sizeof(query), "delete from cdwFile where id=%lld", fileId);
sqlUpdate(conn, query);
}
char *lastPath = NULL;
// skip symlink check if meta or manifest which do not get validated or license plate or symlink
if (!((fileId == es->manifestFileId) || (fileId == es->metaFileId)))
lastPath = findSubmitSymlink(ef->submitFileName, submitDir, path);
if (lastPath)
{
verbose(3, "lastPath=%s path=%s\n", lastPath, path);
if (unlink(lastPath) == -1) // drop about to be invalid symlink
errnoAbort("unlink failure %s", lastPath);
copyFile(path, lastPath);
touchFileFromFile(path, lastPath);
chmod(lastPath, 0664);
freeMem(lastPath);
}
if (!unSymlinkOnly)
mustRemove(path);
}
freez(&path);
cdwFileFree(&ef);
}
void cdwFileResetTags(struct sqlConnection *conn, struct cdwFile *ef, char *newTags,
boolean revalidate, int submitId)
/* Reset tags on file, strip out old validation and QA, schedule new validation and QA. */
/* Remove existing QA records and rerun QA agent on given file. */
{
long long fileId = ef->id;
/* Update database to let people know format revalidation is in progress. */
char query[4*1024];
/* Update tags for file in cdwFile table. */
sqlSafef(query, sizeof(query), "update cdwFile set tags='%s' where id=%lld", newTags, fileId);
sqlUpdate(conn, query);
if (revalidate)
{
sqlSafef(query, sizeof(query), "update cdwFile set errorMessage = '%s' where id=%lld",
"Revalidation in progress.", fileId);
sqlUpdate(conn, query);
/* Get rid of records referring to file in other validation and qa tables. */
cdwRemoveQaRecords(conn, fileId);
/* schedule validator */
cdwAddQaJob(conn, ef->id, submitId);
}
else
{
/* The revalidation case relies on cdwMakeValidFile to update the cdwValidFile table.
* Here we must do it ourselves. */
struct cdwValidFile *vf = cdwValidFileFromFileId(conn, ef->id);
if (vf != NULL)
{
struct cgiParsedVars *tags = cdwMetaVarsList(conn, ef);
cdwValidFileFieldsFromTags(vf, tags);
cdwValidFileUpdateDb(conn, vf, vf->id);
cgiParsedVarsFreeList(&tags);
cdwValidFileFree(&vf);
}
}
}
static void scanSam(char *samIn, FILE *f, struct genomeRangeTree *grt, long long *retHit,
long long *retMiss, long long *retTotalBasesInHits, long long *retUniqueHitCount)
/* Scan through sam file doing several things:counting how many reads hit and how many
* miss target during mapping phase, copying those that hit to a little bed file, and
* also defining regions covered in a genomeRangeTree. */
{
samfile_t *sf = samopen(samIn, "r", NULL);
bam_hdr_t *bamHeader = sam_hdr_read(sf);
bam1_t one;
ZeroVar(&one);
int err;
long long hit = 0, miss = 0, unique = 0, totalBasesInHits = 0;
while ((err = sam_read1(sf, bamHeader, &one)) >= 0)
{
int32_t tid = one.core.tid;
if (tid < 0)
{
++miss;
continue;
}
++hit;
if (one.core.qual > cdwMinMapQual)
++unique;
char *chrom = bamHeader->target_name[tid];
// Approximate here... can do better if parse cigar.
int start = one.core.pos;
int size = one.core.l_qseq;
int end = start + size;
totalBasesInHits += size;
boolean isRc = (one.core.flag & BAM_FREVERSE);
char strand = (isRc ? '-' : '+');
if (start < 0) start=0;
if (f != NULL)
fprintf(f, "%s\t%d\t%d\t.\t0\t%c\n", chrom, start, end, strand);
genomeRangeTreeAdd(grt, chrom, start, end);
}
if (err < 0 && err != -1)
errnoAbort("samread err %d", err);
samclose(sf);
*retHit = hit;
*retMiss = miss;
*retTotalBasesInHits = totalBasesInHits;
*retUniqueHitCount = unique;
}
void cdwReserveTempFile(char *path)
/* Call mkstemp on path. This will fill in terminal XXXXXX in path with file name
* and create an empty file of that name. Generally that empty file doesn't stay empty for long. */
{
int fd = mkstemp(path);
if (fd == -1)
errnoAbort("Couldn't create temp file %s", path);
if (fchmod(fd, 0664) == -1)
errnoAbort("Couldn't change permissions on temp file %s", path);
mustCloseFd(&fd);
}
void cdwIndexPath(struct cdwAssembly *assembly, char indexPath[PATH_LEN])
/* Fill in path to BWA/Bowtie index. */
{
safef(indexPath, PATH_LEN, "/dev/shm/btData/%s", assembly->ucscDb);
}
void cdwAsPath(char *format, char path[PATH_LEN])
/* Convert something like "narrowPeak" in format to full path involving
* encValDir/as/narrowPeak.as */
{
safef(path, PATH_LEN, "%sas/%s.as", cdwValDataDir, format);
}
boolean cdwTrimReadsForAssay(char *fastqPath, char trimmedPath[PATH_LEN], char *assay)
/* Look at assay and see if it's one that needs trimming. If so make a new trimmed
* file and put file name in trimmedPath. Otherwise just copy fastqPath to trimmed
* path and return FALSE. */
{
if (sameString(assay, "long-RNA-seq"))
{
char cmd[3*PATH_LEN];
// Make up temp file name for poly-A trimmed file
safef(trimmedPath, PATH_LEN, "%scdwFastqPolyFilterXXXXXX", cdwTempDir());
cdwReserveTempFile(trimmedPath);
// Run cdwFastqPolyFilter on the new file then pass the output into BWA.
safef(cmd, sizeof(cmd), "cdwFastqPolyFilter %s %s",
fastqPath, trimmedPath);
mustSystem(cmd);
return TRUE;
}
else
{
strcpy(trimmedPath, fastqPath);
return FALSE;
}
}
void cdwCleanupTrimReads(char *fastqPath, char trimmedPath[PATH_LEN])
/* Remove trimmed sample file. Does nothing if fastqPath and trimmedPath the same. */
{
if (!sameString(fastqPath, trimmedPath))
remove(trimmedPath);
}
void cdwAlignFastqMakeBed(struct cdwFile *ef, struct cdwAssembly *assembly,
char *fastqPath, struct cdwValidFile *vf, FILE *bedF,
double *retMapRatio, double *retDepth, double *retSampleCoverage,
double *retUniqueMapRatio, char *assay)
/* Take a sample fastq, run the aligner on it and then convert that file to a bed.
* bedF and all the ret parameters can be NULL. */
{
// Figure out BWA index
char genoFile[PATH_LEN];
cdwIndexPath(assembly, genoFile);
// Trim reads if need be
char trimmedFile[PATH_LEN];
cdwTrimReadsForAssay(fastqPath, trimmedFile, assay);
char *samName;
samName = cloneString(rTempName(cdwTempDir(), "ewdSample1", ".sam"));
char cmd[3*PATH_LEN];
// We used to use bwa backtrack here ("bwa aln"), but this mode does not allow mmap indices
// BWA mem allows preloaded mmap'ed indices, but it is very slow to start, like bowtie2
// Also BWA mem and bowtie2 are local aligners, so their stats are very different and they do not seem
// to have a "require 99% identity option", which is very, very strange.
// So bowtie seemed like the best of both worlds, mmap and also global alignment
// Max did various comparisons with 80 sample fastq files and the count of aligned reads were very very similar
// for those files that have enough reads in them. Plots were in email to Jim/Clay.
// -l 40 is seed length. Makes it a lot faster. Today's reads should be longer than 40 bp
// -n 1 is the number of mismatches in the seed. lower this to 1 makes it a lot faster.
// -mm activates mmap for the index, which is now in ramdisk
// -S is for SAM output (so no more useless .sai temp files)
// these options require a decently recent bowtie version, I used 1.2.2
safef(cmd, sizeof(cmd), "bowtie -l 40 -n 1 --mm --threads 3 %s %s -S > %s", genoFile, trimmedFile, samName);
mustSystem(cmd);
/* Scan sam file to calculate vf->mapRatio, vf->sampleCoverage and vf->depth.
* and also to produce little bed file for enrichment step. */
struct genomeRangeTree *grt = genomeRangeTreeNew();
long long hitCount=0, missCount=0, uniqueHitCount, totalBasesInHits=0;
scanSam(samName, bedF, grt, &hitCount, &missCount, &totalBasesInHits, &uniqueHitCount);
verbose(1, "hitCount=%lld, missCount=%lld, totalBasesInHits=%lld, grt=%p\n",
hitCount, missCount, totalBasesInHits, grt);
if (retMapRatio)
*retMapRatio = (double)hitCount/(hitCount+missCount);
if (retDepth)
*retDepth = (double)totalBasesInHits/assembly->baseCount
* (double)vf->itemCount/vf->sampleCount;
long long basesHitBySample = genomeRangeTreeSumRanges(grt);
if (retSampleCoverage)
*retSampleCoverage = (double)basesHitBySample/assembly->baseCount;
if (retUniqueMapRatio)
*retUniqueMapRatio = (double)uniqueHitCount/(hitCount+missCount);
// Clean up and go home
cdwCleanupTrimReads(fastqPath, trimmedFile);
genomeRangeTreeFree(&grt);
remove(samName);
}
struct cdwFastqFile *cdwFastqFileFromFileId(struct sqlConnection *conn, long long fileId)
/* Get cdwFastqFile with given fileId or NULL if none such */
{
char query[256];
sqlSafef(query, sizeof(query), "select * from cdwFastqFile where fileId=%lld", fileId);
return cdwFastqFileLoadByQuery(conn, query);
}
struct cdwVcfFile *cdwVcfFileFromFileId(struct sqlConnection *conn, long long fileId)
/* Get cdwVcfFile with given fileId or NULL if none such */
{
char query[256];
sqlSafef(query, sizeof(query), "select * from cdwVcfFile where fileId=%lld", fileId);
return cdwVcfFileLoadByQuery(conn, query);
}
static int mustMkstemp(char *template)
/* Call mkstemp to make a temp file with name based on template (which is altered)
* by the call to be the file name. Return unix file descriptor. */
{
int fd = mkstemp(template);
if (fd == -1)
errnoAbort("Couldn't make temp file based on %s", template);
return fd;
}
void cdwMakeTempFastqSample(char *source, int size, char dest[PATH_LEN])
/* Copy size records from source into a new temporary dest. Fills in dest */
{
/* Make temporary file to save us a unique place in file system. */
safef(dest, PATH_LEN, "%scdwSampleFastqXXXXXX", cdwTempDir());
int fd = mustMkstemp(dest);
close(fd);
char command[3*PATH_LEN];
safef(command, sizeof(command),
"fastqStatsAndSubsample %s /dev/null %s -smallOk -sampleSize=%d", source, dest, size);
verbose(2, "command: %s\n", command);
mustSystem(command);
}
void cdwMakeFastqStatsAndSample(struct sqlConnection *conn, long long fileId)
/* Run fastqStatsAndSubsample, and put results into cdwFastqFile table. */
{
struct cdwFastqFile *fqf = cdwFastqFileFromFileId(conn, fileId);
if (fqf == NULL)
{
char *path = cdwPathForFileId(conn, fileId);
char statsFile[PATH_LEN], sampleFile[PATH_LEN];
char command[3*PATH_LEN];
// Cut adapt on RNA seq files.
safef(statsFile, PATH_LEN, "%scdwFastqStatsXXXXXX", cdwTempDir());
cdwReserveTempFile(statsFile);
char dayTempDir[PATH_LEN];
safef(sampleFile, PATH_LEN, "%scdwFastqSampleXXXXXX", cdwTempDirForToday(dayTempDir));
cdwReserveTempFile(sampleFile);
// For RNA seq files run on the fastqTrimmed output, otherwise run on the unaltered CDW file.
safef(command, sizeof(command), "fastqStatsAndSubsample -sampleSize=%d -smallOk %s %s %s",
cdwSampleTargetSize, path, statsFile, sampleFile);
mustSystem(command);
safef(command, sizeof(command), "gzip -c %s > %s.fastq.gz", sampleFile, sampleFile);
mustSystem(command);
strcat(sampleFile, ".fastq.gz");
fqf = cdwFastqFileOneFromRa(statsFile);
fqf->fileId = fileId;
fqf->sampleFileName = cloneString(sampleFile);
cdwFastqFileSaveToDb(conn, fqf, "cdwFastqFile", 1024);
remove(statsFile);
freez(&path);
}
cdwFastqFileFree(&fqf);
}
struct cdwQaWigSpot *cdwMakeWigSpot(struct sqlConnection *conn, long long wigId, long long spotId)
/* Create a new cdwQaWigSpot record in database based on comparing wig file to spot file
* (specified by id's in cdwFile table). */
{
/* Get valid files from fileIds and check format */
struct cdwValidFile *wigVf = cdwValidFileFromFileId(conn, wigId);
if (!sameString(wigVf->format, "bigWig"))
errAbort("%lld is not a bigWig file, is %s instead", wigId, wigVf->format);
struct cdwValidFile *spotVf = cdwValidFileFromFileId(conn, spotId);
if (!sameString(spotVf->format, "narrowPeak") && !sameString(spotVf->format, "broadPeak") &&
!sameString(spotVf->format, "bigBed"))
errAbort("%lld is not a recognized peak type format, is %s", spotId, spotVf->format);
/* Remove any old record for files. */
char query[256];
sqlSafef(query, sizeof(query),
"delete from cdwQaWigSpot where wigId=%lld and spotId=%lld", wigId, spotId);
sqlUpdate(conn, query);
/* Figure out file names */
char *wigPath = cdwPathForFileId(conn, wigId);
char *spotPath = cdwPathForFileId(conn, spotId);
char statsFile[PATH_LEN];
safef(statsFile, PATH_LEN, "%scdwQaWigSpotXXXXXX", cdwTempDir());
cdwReserveTempFile(statsFile);
char peakFile[PATH_LEN];
safef(peakFile, PATH_LEN, "%scdwQaWigSpotXXXXXX", cdwTempDir());
cdwReserveTempFile(peakFile);
/* Convert narrowPeak input into a temporary bed4 file */
char command[3*PATH_LEN];
safef(command, sizeof(command), "bigBedToBed %s stdout | cut -f 1-4 > %s", spotPath, peakFile);
mustSystem(command);
/* Call on bigWigAverageOverBed on peaks */
safef(command, sizeof(command),
"bigWigAverageOverBed %s %s /dev/null -stats=%s", wigPath, peakFile, statsFile);
mustSystem(command);
remove(peakFile);
/* Parse out ra file, save it to database, and remove ra file. */
struct cdwQaWigSpot *spot = cdwQaWigSpotOneFromRa(statsFile);
spot->wigId = wigId;
spot->spotId = spotId;
cdwQaWigSpotSaveToDb(conn, spot, "cdwQaWigSpot", 1024);
spot->id = sqlLastAutoId(conn);
/* Clean up and go home. */
cdwQaWigSpotFree(&spot);
cdwValidFileFree(&wigVf);
cdwValidFileFree(&spotVf);
freez(&wigPath);
freez(&spotPath);
return spot;
}
struct cdwQaWigSpot *cdwQaWigSpotFor(struct sqlConnection *conn,
long long wigFileId, long long spotFileId)
/* Return wigSpot relationship if any we have in database for these two files. */
{
char query[256];
sqlSafef(query, sizeof(query),
"select * from cdwQaWigSpot where wigId=%lld and spotId=%lld", wigFileId, spotFileId);
return cdwQaWigSpotLoadByQuery(conn, query);
}
struct cdwBamFile *cdwBamFileFromFileId(struct sqlConnection *conn, long long fileId)
/* Get cdwBamFile with given fileId or NULL if none such */
{
char query[256];
sqlSafef(query, sizeof(query), "select * from cdwBamFile where fileId=%lld", fileId);
return cdwBamFileLoadByQuery(conn, query);
}
struct cdwBamFile * cdwMakeBamStatsAndSample(struct sqlConnection *conn, long long fileId,
char sampleBed[PATH_LEN])
/* Run cdwBamStats and put results into cdwBamFile table, and also a sample bed.
* The sampleBed will be filled in by this routine. */
{
/* Remove any old record for file. */
char query[256];
sqlSafef(query, sizeof(query), "delete from cdwBamFile where fileId=%lld", fileId);
sqlUpdate(conn, query);
/* Figure out file names */
char *path = cdwPathForFileId(conn, fileId);
char statsFile[PATH_LEN];
safef(statsFile, PATH_LEN, "%scdwBamStatsXXXXXX", cdwTempDir());
cdwReserveTempFile(statsFile);
char dayTempDir[PATH_LEN];
safef(sampleBed, PATH_LEN, "%scdwBamSampleXXXXXX", cdwTempDirForToday(dayTempDir));
cdwReserveTempFile(sampleBed);
/* Make system call to make ra and bed, and then another system call to zip bed.*/
char command[3*PATH_LEN];
safef(command, sizeof(command), "edwBamStats -sampleBed=%s -sampleBedSize=%d %s %s",
sampleBed, cdwSampleTargetSize, path, statsFile);
mustSystem(command);
safef(command, sizeof(command), "gzip %s", sampleBed);
mustSystem(command);
strcat(sampleBed, ".gz");
/* Parse out ra file, save it to database, and remove ra file. */
struct cdwBamFile *ebf = cdwBamFileOneFromRa(statsFile);
ebf->fileId = fileId;
cdwBamFileSaveToDb(conn, ebf, "cdwBamFile", 1024);
remove(statsFile);
/* Clean up and go home. */
freez(&path);
return ebf;
}
struct cdwVcfFile * cdwMakeVcfStatsAndSample(struct sqlConnection *conn, long long fileId,
char sampleBed[PATH_LEN])
/* Run cdwVcfStats and put results into cdwVcfFile table, and also a sample bed.
* The sampleBed will be filled in by this routine. */
{
/* Remove any old record for file. */
char query[256];
sqlSafef(query, sizeof(query), "delete from cdwVcfFile where fileId=%lld", fileId);
sqlUpdate(conn, query);
/* Figure out file names */
char *path = cdwPathForFileId(conn, fileId);
char statsFile[PATH_LEN];
safef(statsFile, PATH_LEN, "%scdwVcfStatsXXXXXX", cdwTempDir());
cdwReserveTempFile(statsFile);
char dayTempDir[PATH_LEN];
safef(sampleBed, PATH_LEN, "%scdwVcfSampleXXXXXX", cdwTempDirForToday(dayTempDir));
cdwReserveTempFile(sampleBed);
/* Make system call to make ra and bed, and then another system call to zip bed.*/
char command[3*PATH_LEN];
safef(command, sizeof(command), "cdwVcfStats -bed=%s %s %s",
sampleBed, path, statsFile);
mustSystem(command);
safef(command, sizeof(command), "gzip %s", sampleBed);
mustSystem(command);
strcat(sampleBed, ".gz");
/* Parse out ra file, save it to database, and remove ra file. */
struct cdwVcfFile *vcf = cdwVcfFileOneFromRa(statsFile);
vcf->fileId = fileId;
cdwVcfFileSaveToDb(conn, vcf, "cdwVcfFile", 1024);
remove(statsFile);
/* Clean up and go home. */
freez(&path);
return vcf;
}
char *cdwOppositePairedEndString(char *end)
/* Return "1" for "2" and vice versa */
{
if (sameString(end, "1"))
return "2";
else if (sameString(end, "2"))
return "1";
else
{
errAbort("Expecting 1 or 2, got %s in oppositeEnd", end);
return NULL;
}
}
struct cdwValidFile *cdwOppositePairedEnd(struct sqlConnection *conn, struct cdwFile *ef, struct cdwValidFile *vf)
/* Given one file of a paired end set of fastqs, find the file with opposite ends. */
{
char *otherEnd = cdwOppositePairedEndString(vf->pairedEnd);
char query[1024];
sqlSafef(query, sizeof(query),
"select cdwValidFile.* from cdwValidFile join cdwFile on cdwValidFile.fileId=cdwFile.id"
" where experiment='%s' and submitDirId=%d and outputType='%s' and replicate='%s' "
" and part='%s' and pairedEnd='%s' and itemCount=%lld and deprecated=''"
, vf->experiment, ef->submitDirId, vf->outputType, vf->replicate, vf->part, otherEnd
, vf->itemCount);
struct cdwValidFile *otherVf = cdwValidFileLoadByQuery(conn, query);
if (otherVf == NULL)
return NULL;
if (otherVf->next != NULL)
errAbort("Multiple results from pairedEnd query %s", query);
return otherVf;
}
struct cdwQaPairedEndFastq *cdwQaPairedEndFastqFromVfs(struct sqlConnection *conn,
struct cdwValidFile *vfA, struct cdwValidFile *vfB,
struct cdwValidFile **retVf1, struct cdwValidFile **retVf2)
/* Return pair record if any for the two fastq files. */
{
/* Sort the two ends. */
struct cdwValidFile *vf1 = NULL, *vf2 = NULL;
if (sameString(vfA->pairedEnd, "1"))
{
vf1 = vfA;
vf2 = vfB;
}
else
{
vf1 = vfB;
vf2 = vfA;
}
if (retVf1 != NULL)
*retVf1 = vf1;
if (retVf2 != NULL)
*retVf2 = vf2;
/* See if we already have a record for these two. */
/* Return record for these two. */
char query[1024];
sqlSafef(query, sizeof(query),
"select * from cdwQaPairedEndFastq where fileId1=%u and fileId2=%u",
vf1->fileId, vf2->fileId);
return cdwQaPairedEndFastqLoadByQuery(conn, query);
}
FILE *cdwPopen(char *command, char *mode)
/* do popen or die trying */
{
/* Because of bugs with popen(...,"r") and programs that use stdin otherwise
* it's probably better to use Mark's pipeline library, but it is ever so
* much harder to use... */
FILE *f = popen(command, mode);
if (f == NULL)
errnoAbort("Can't popen(%s, %s)", command, mode);
return f;
}
boolean cdwOneLineSystemAttempt(char *command, char *line, int maxLineSize)
/* Execute system command and return one line result from it in line */
{
FILE *f = popen(command, "r");
boolean ok = FALSE;
if (f != NULL)
{
char *result = fgets(line, maxLineSize, f);
if (result != NULL)
ok = TRUE;
pclose(f);
}
else
{
errnoWarn("failed popen %s", command);
}
return ok;
}
void cdwOneLineSystemResult(char *command, char *line, int maxLineSize)
/* Execute system command and return one line result from it in line */
{
if (!cdwOneLineSystemAttempt(command, line, maxLineSize) )
errAbort("Can't get line from %s", command);
}
void cdwMd5File(char *fileName, char md5Hex[33])
/* call md5sum utility to calculate md5 for file and put result in hex format md5Hex
* This ends up being about 30% faster than library routine md5HexForFile,
* however since there's popen() weird interactions with stdin involved
* it's not suitable for a general purpose library. Environment inside cdw
* is controlled enough it should be ok. */
{
char command[PATH_LEN + 16];
safef(command, sizeof(command), "md5sum %s", fileName);
char line[2*PATH_LEN];
cdwOneLineSystemResult(command, line, sizeof(line));
memcpy(md5Hex, line, 32);
md5Hex[32] = 0;
}
void cdwPokeFifo(char *fifoName)
/* Send '\n' to fifo to wake up associated daemon */
{
/* Sadly we loop through places it might be since it varies. It has to live somewhere
* that web CGIs can poke is the problem. */
char *places[] = {"/data/www/userdata/", "/usr/local/apache/userdata/"};
int i;
for (i=0; i<ArraySize(places); ++i)
{
char path[PATH_LEN];
safef(path, sizeof(path), "%s%s", places[i], fifoName);
if (fileExists(path))
{
char *message = "\n";
writeGulp(path, message, strlen(message));
break;
}
}
}
/***/
/* Shared functions for CDW web CGI's.
Mostly wrappers for javascript tweaks */
void cdwWebAutoRefresh(int msec)
/* Refresh page after msec. Use 0 to cancel autorefresh */
{
if (msec > 0)
{
// set timeout to refresh page (saving/restoring scroll position via cookie)
printf("<script type='text/javascript'>var cdwRefresh = setTimeout(function() { $.cookie('cdwWeb.scrollTop', $(window).scrollTop()); $('form').submit(); }, %d);</script>", msec);
puts("<script type='text/javascript'>$(document).ready(function() {$(document).scrollTop($.cookie('cdwWeb.scrollTop'))});</script>");
// disable autorefresh when user is changing page settings
puts("<script type='text/javascript'>$('form').click(function() {clearTimeout(cdwRefresh); $.cookie('cdwWeb.scrollTop', null);});</script>");
}
else if (msec == 0)
puts("clearTimeout(cdwRefresh);</script>");
// Negative msec ignored
}
/***/
/* Navigation bar */
void cdwWebNavBarStart()
/* Layout navigation bar */
{
puts("<div id='layout'>");
puts("<div id='navbar' class='navbar navbar-fixed-top navbar-inverse'>");
webIncludeFile("/inc/cdwNavBar.html");
puts("</div>");
puts("<div id='content' class='container'><div>");
}
void cdwWebNavBarEnd()
/* Close layout after navigation bar */
{
puts("</div></div></div>");
}
void cdwWebBrowseMenuItem(boolean on)
/* Toggle visibility of 'Browse submissions' link on navigation menu */
{
printf("<script type='text/javascript'>$('#cdw-browse').%s();</script>", on ? "show" : "hide");
}
void cdwWebSubmitMenuItem(boolean on)
/* Toggle visibility of 'Submit data' link on navigation menu */
{
printf("<script type='text/javascript'>$('#cdw-submit').%s();</script>", on ? "show" : "hide");
}
char *cdwRqlLookupField(void *record, char *key)
/* Lookup a field in a tagStanza. */
{
struct tagStanza *stanza = record;
return tagFindVal(stanza, key);
}
boolean cdwRqlStatementMatch(struct rqlStatement *rql, struct tagStanza *stanza,
struct lm *lm)
/* Return TRUE if where clause and tableList in statement evaluates true for stanza. */
{
struct rqlParse *whereClause = rql->whereClause;
if (whereClause == NULL)
return TRUE;
else
{
struct rqlEval res = rqlEvalOnRecord(whereClause, stanza, cdwRqlLookupField, lm);
res = rqlEvalCoerceToBoolean(res);
return res.val.b;
}
}
static void rBuildStanzaRefList(struct tagStorm *tags, struct tagStanza *stanzaList,
struct rqlStatement *rql, struct lm *lm, int *pMatchCount, struct slRef **pList)
/* Recursively add stanzas that match query to list */
{
struct tagStanza *stanza;
for (stanza = stanzaList; stanza != NULL; stanza = stanza->next)
{
if (rql->limit < 0 || rql->limit > *pMatchCount)
{
if (cdwRqlStatementMatch(rql, stanza, lm))
{
refAdd(pList, stanza);
*pMatchCount += 1;
}
if (stanza->children != NULL)
rBuildStanzaRefList(tags, stanza->children, rql, lm, pMatchCount, pList);
}
}
}
void cdwCheckRqlFields(struct rqlStatement *rql, struct slName *tagFieldList)
/* Make sure that rql query only includes fields that exist in tags */
{
struct hash *hash = hashFromSlNameList(tagFieldList);
rqlCheckFieldsExist(rql, hash, "cdwFileTags table");
hashFree(&hash);
}
struct slRef *tagStanzasMatchingQuery(struct tagStorm *tags, char *query)
/* Return list of references to stanzas that match RQL query */
{
struct rqlStatement *rql = rqlStatementParseString(query);
struct slName *tagFieldList = tagStormFieldList(tags);
cdwCheckRqlFields(rql, tagFieldList);
slFreeList(&tagFieldList);
int matchCount = 0;
struct slRef *list = NULL;
struct lm *lm = lmInit(0);
rBuildStanzaRefList(tags, tags->forest, rql, lm, &matchCount, &list);
rqlStatementFree(&rql);
lmCleanup(&lm);
return list;
}
struct cgiParsedVars *cdwMetaVarsList(struct sqlConnection *conn, struct cdwFile *ef)
/* Return list of cgiParsedVars dictionaries for metadata for file. Free this up
* with cgiParsedVarsFreeList() */
{
struct cgiParsedVars *tagsList = cgiParsedVarsNew(ef->tags);
struct cgiParsedVars *parentTags = NULL;
char query[256];
sqlSafef(query, sizeof(query),
"select tags from cdwMetaTags where id=%u", ef->metaTagsId);
char *metaCgi = sqlQuickString(conn, query);
if (metaCgi != NULL)
{
parentTags = cgiParsedVarsNew(metaCgi);
tagsList->next = parentTags;
freez(&metaCgi);
}
return tagsList;
}
static int gMatchCount = 0;
static boolean gDoSelect = FALSE;
static boolean gFirst = TRUE;
static void rMatchesToRa(struct tagStorm *tags, struct tagStanza *list,
struct rqlStatement *rql, struct lm *lm)
/* Recursively traverse stanzas on list outputting matching stanzas as ra. */
{
struct tagStanza *stanza;
for (stanza = list; stanza != NULL; stanza = stanza->next)
{
if (rql->limit < 0 || rql->limit > gMatchCount)
{
if (stanza->children)
rMatchesToRa(tags, stanza->children, rql, lm);
else /* Just apply query to leaves */
{
if (cdwRqlStatementMatch(rql, stanza, lm))
{
++gMatchCount;
if (gDoSelect)
{
struct slName *field;
for (field = rql->fieldList; field != NULL; field = field->next)
{
char *val = tagFindVal(stanza, field->name);
if (val != NULL)
printf("%s\t%s\n", field->name, val);
}
printf("\n");
}
}
}
}
}
}
static void printQuotedTsv(char *val)
/* Print out tab separated value inside of double quotes. Escape any existing quotes with quotes. */
{
putchar('"');
char c;
while ((c = *val++) != 0)
{
if (c == '"')
putchar(c);
putchar(c);
}
putchar('"');
}
static void rMatchesToCsv(struct tagStorm *tags, struct tagStanza *list,
struct rqlStatement *rql, struct lm *lm)
/* Recursively traverse stanzas on list outputting matching stanzas as
* a comma separated values file. */
{
struct tagStanza *stanza;
for (stanza = list; stanza != NULL; stanza = stanza->next)
{
if (rql->limit < 0 || rql->limit > gMatchCount) // We are inside the acceptable limit
{
if (stanza->children) // Recurse till we have just leaves.
rMatchesToCsv(tags, stanza->children, rql, lm);
else /* Just apply query to leaves */
{
if (cdwRqlStatementMatch(rql, stanza, lm))
{
++gMatchCount;
if (gDoSelect)
{
struct slName *field;
if (gFirst)// For the first stanza print out a header line.
{
char *sep = "";
gFirst = FALSE;
for (field = rql->fieldList; field != NULL; field = field->next)
{
printf("%s%s", sep, field->name);
sep = ",";
}
printf("\n");
}
char *sep = "";
for (field = rql->fieldList; field != NULL; field = field->next)
{
fputs(sep, stdout);
sep = ",";
char *val = emptyForNull(tagFindVal(stanza, field->name));
// Check for embedded comma or existing quotes
if (strchr(val, ',') == NULL && strchr(val, '"') == NULL)
fputs(val, stdout);
else
{
printQuotedTsv(val);
}
}
printf("\n");
}
}
}
}
}
}
static void rMatchesToTsv(struct tagStorm *tags, struct tagStanza *list,
struct rqlStatement *rql, struct lm *lm)
/* Recursively traverse stanzas on list outputting matching stanzas as a tab separated values file. */
{
struct tagStanza *stanza;
for (stanza = list; stanza != NULL; stanza = stanza->next)
{
if (rql->limit < 0 || rql->limit > gMatchCount) // We are inside the acceptable limit
{
if (stanza->children) // Recurse till we have just leaves.
rMatchesToTsv(tags, stanza->children, rql, lm);
else /* Just apply query to leaves */
{
if (cdwRqlStatementMatch(rql, stanza, lm))
{
++gMatchCount;
if (gDoSelect)
{
struct slName *field;
if (gFirst)// For the first stanza print out a header line.
{
gFirst = FALSE;
printf("#");
char *sep = "";
for (field = rql->fieldList; field != NULL; field = field->next)
{
printf("%s%s", sep, field->name);
sep = "\t";
}
printf("\n");
}
char *sep = "";
for (field = rql->fieldList; field != NULL; field = field->next)
{
char *val = naForNull(tagFindVal(stanza, field->name));
printf("%s%s", sep, val);
sep = "\t";
}
printf("\n");
}
}
}
}
}
}
void cdwPrintMatchingStanzas(char *rqlQuery, int limit, struct tagStorm *tags, char *format)
/* Show stanzas that match query */
{
struct dyString *dy = dyStringCreate("%s", rqlQuery);
int maxLimit = 10000;
if (limit > maxLimit)
limit = maxLimit;
struct rqlStatement *rql = rqlStatementParseString(dy->string);
/* Get list of all tag types in tree and use it to expand wildcards in the query
* field list. */
struct slName *allFieldList = tagStormFieldList(tags);
slSort(&allFieldList, slNameCmpCase);
rql->fieldList = wildExpandList(allFieldList, rql->fieldList, TRUE);
/* Traverse tag tree outputting when rql statement matches in select case, just
* updateing count in count case. */
gDoSelect = sameWord(rql->command, "select");
if (gDoSelect)
rql->limit = limit;
struct lm *lm = lmInit(0);
if (sameString(format, "ra"))
rMatchesToRa(tags, tags->forest, rql, lm);
else if (sameString(format, "tsv"))
rMatchesToTsv(tags, tags->forest, rql, lm);
else if (sameString(format, "csv"))
rMatchesToCsv(tags, tags->forest, rql, lm);
if (sameWord(rql->command, "count"))
printf("%d\n", gMatchCount);
}
static struct dyString *getLoginBits(struct cart *cart)
/* Get a little HTML fragment that has login/logout bit of menu */
{
/* Construct URL to return back to this page */
char *command = cartUsualString(cart, "cdwCommand", "home");
char *sidString = cartSidUrlString(cart);
char returnUrl[PATH_LEN*2];
safef(returnUrl, sizeof(returnUrl), "/cgi-bin/cdwWebBrowse?cdwCommand=%s&%s",
command, sidString );
char *encodedReturn = cgiEncode(returnUrl);
/* Write a little html into loginBits */
struct dyString *loginBits = dyStringNew(0);
dyStringAppend(loginBits, "<li id=\"query\"><a href=\"");
char *userName = wikiLinkUserName();
if (userName == NULL)
{
dyStringPrintf(loginBits, "../cgi-bin/hgLogin?hgLogin.do.displayLoginPage=1&returnto=%s&%s",
encodedReturn, sidString);
dyStringPrintf(loginBits, "\">Login</a></li>");
}
else
{
dyStringPrintf(loginBits, "../cgi-bin/hgLogin?hgLogin.do.displayLogout=1&returnto=%s&%s",
encodedReturn, sidString);
dyStringPrintf(loginBits, "\" id=\"logoutLink\">Logout %s</a></li>", userName);
if (loginUseBasicAuth())
wikiFixLogoutLinkWithJs();
}
/* Clean up and go home */
freez(&encodedReturn);
return loginBits;
}
char *cdwLocalMenuBar(struct cart *cart, boolean makeAbsolute)
/* Return menu bar string. Optionally make links in menubar to point to absolute URLs, not relative. */
{
struct dyString *loginBits = getLoginBits(cart);
// menu bar html is in a stringified .h file
struct dyString *dy = dyStringNew(4*1024);
dyStringPrintf(dy,
#include "cdwNavBar.h"
, loginBits->string);
char *menubarStr = menuBarAddUiVars(dy->string, "/cgi-bin/cdw", cartSidUrlString(cart));
if (!makeAbsolute)
return menubarStr;
char *menubarStr2 = replaceChars(menubarStr, "../", "/");
freez(&menubarStr);
return menubarStr2;
}
char *fileExtFromFormat(char *format)
/* return file extension given the cdwFile format as defined in cdwValid.c. Result has to be freed */
{
if (sameWord(format, "vcf"))
return cloneString(".vcf.gz");
if (sameWord(format, "fasta"))
return cloneString(".fa.gz");
if (sameWord(format, "fastq"))
return cloneString(".fastq.gz");
if (sameWord(format, "unknown"))
return cloneString("");
return catTwoStrings(".", format);
}
| 33.635357 | 182 | 0.708256 | [
"object"
] |
645d449c547a91deed144d24e499f886e92afb65 | 23,807 | h | C | middleware/legato/library/src/gfx/legato/core/legato_state.h | automaate/gfx3.8 | 55bf94302f00c8d513c84d910185cef2ca6b5be2 | [
"0BSD"
] | 4 | 2021-07-23T18:37:34.000Z | 2022-01-09T17:31:40.000Z | middleware/legato/library/src/gfx/legato/core/legato_state.h | automaate/gfx3.8 | 55bf94302f00c8d513c84d910185cef2ca6b5be2 | [
"0BSD"
] | 1 | 2020-12-31T22:40:10.000Z | 2020-12-31T22:40:10.000Z | middleware/legato/library/src/gfx/legato/core/legato_state.h | automaate/gfx3.8 | 55bf94302f00c8d513c84d910185cef2ca6b5be2 | [
"0BSD"
] | 3 | 2021-01-20T19:16:00.000Z | 2021-07-27T08:06:14.000Z | /*******************************************************************************
* Copyright (C) 2020 Microchip Technology Inc. and its subsidiaries.
*
* Subject to your compliance with these terms, you may use Microchip software
* and any derivatives exclusively with Microchip products. It is your
* responsibility to comply with third party license terms applicable to your
* use of third party software (including open source software) that may
* accompany Microchip software.
*
* THIS SOFTWARE IS SUPPLIED BY MICROCHIP "AS IS". NO WARRANTIES, WHETHER
* EXPRESS, IMPLIED OR STATUTORY, APPLY TO THIS SOFTWARE, INCLUDING ANY IMPLIED
* WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY, AND FITNESS FOR A
* PARTICULAR PURPOSE.
*
* IN NO EVENT WILL MICROCHIP BE LIABLE FOR ANY INDIRECT, SPECIAL, PUNITIVE,
* INCIDENTAL OR CONSEQUENTIAL LOSS, DAMAGE, COST OR EXPENSE OF ANY KIND
* WHATSOEVER RELATED TO THE SOFTWARE, HOWEVER CAUSED, EVEN IF MICROCHIP HAS
* BEEN ADVISED OF THE POSSIBILITY OR THE DAMAGES ARE FORESEEABLE. TO THE
* FULLEST EXTENT ALLOWED BY LAW, MICROCHIP'S TOTAL LIABILITY ON ALL CLAIMS IN
* ANY WAY RELATED TO THIS SOFTWARE WILL NOT EXCEED THE AMOUNT OF FEES, IF ANY,
* THAT YOU HAVE PAID DIRECTLY TO MICROCHIP FOR THIS SOFTWARE.
*******************************************************************************/
/** \file legato_state.h
* @brief .
*
* @details .
*/
#ifndef LEGATO_STATE_H
#define LEGATO_STATE_H
#include "gfx/legato/common/legato_common.h"
#include "gfx/driver/gfx_driver.h"
#include "gfx/legato/core/legato_input.h"
#include "gfx/legato/core/legato_scheme.h"
#include "gfx/legato/string/legato_stringtable.h"
#include "gfx/legato/widget/legato_editwidget.h"
// *****************************************************************************
/**
* @brief This function pointer represents a language change callback.
* @details A language change callback is called when
* when the language change event occurs.
*/
typedef void (*leLanguageChangedCallback_FnPtr)(uint32_t);
// *****************************************************************************
/**
* @brief This struct describes the layer state for a layer.
* @details This struct contains useful information about a layer such as color mode,
* rendering options, etc.
*/
typedef struct
{
leColorMode colorMode;
leBool renderHorizontal;
lePoint driverPosition;
} leLayerState;
// *****************************************************************************
/**
* @brief This struct represents the state of the library.
* @details The state of the libary is a global structure.
*/
typedef struct leState
{
const leStringTable* stringTable; /**< the string table for the instance */
uint32_t languageID; /**< the currently active language */
uint32_t widgetIDs; /**< the next unique widget ID */
leScheme defaultScheme; /**< an internal default scheme that widgets use by */
/**< default if the user doesn't set one */
leWidget* focus; /**< the widget that currently has focus */
leEditWidget* edit; /**< the widget that is currently receiving edit events */
leLanguageChangedCallback_FnPtr languageChangedCB; /**< language changed callback */
leWidget rootWidget[LE_LAYER_COUNT]; /**< root widgets of the scene */
leLayerState layerStates[LE_LAYER_COUNT]; /**< layer states */
#if LE_STREAMING_ENABLED == 1
leStreamManager* activeStream; /**< active stream state */
#endif
} leState;
/* internal use only */
/**
* @cond INTERNAL
*/
leState* leGetState(void);
/**
* @endcond
*
*/
// *****************************************************************************
/**
* @brief Initialize Legato library.
* @details This function performs basic initialization of the Legato
* library state.
* It accepts and intializes a display controller driver specified
* by <span class="param">dispDriver</span>
* @pre Must be called before any other library operations are performed.
* @code
* leResult res = leInitialize(dispDriver);
* @endcode
* @param dispDriver is the display controller driver.
* @returns LE_SUCCESS if set, otherwise LE_FAILURE.
*/
leResult leInitialize(const gfxDisplayDriver* dispDriver,
const gfxGraphicsProcessor* gpuDriver);
// *****************************************************************************
/**
* @brief Shutdown Legato library.
* @details Shutdowns the active Legato library state.
* @code
* leShutdown();
* @endcode
* @return void.
*/
void leShutdown(void);
// *****************************************************************************
/**
* @brief Shutdown Legato library.
* @details Shutdown the Legato library in <span class="param">dt</span>
* milliseconds after the last leUpdate() was called. If the value
* of dt is zero then time-dependent features will not advance.
* the active Legato library state.
* This function updates the active Legato library context state.
* It performs event processing as well as servicing of the widget paint loop.
* It should be called often.
* @code
* uint32_t dt=2000;
* leResult res = leUpdateleShutdown(dt);
* @endcode
* @param dt is a delta time.
* @returns LE_SUCCESS if set, otherwise LE_FAILURE.
*/
leResult leUpdate(uint32_t dt);
// *****************************************************************************
/**
* @brief Get color mode.
* @details Gets the the color mode of the current context.
* @code
* leColorMode mode = leGetColorMode();
* @endcode
* @param void.
* @return the color mode of the current context.
*/
leColorMode leGetColorMode(void);
/**
* @brief Get layer color mode.
* @details Gets the the layer color mode
* @code
* leColorMode mode = leGetLayerColorMode(0);
* @endcode
* @param lyrIdx is the index of the layer to query
* @return the color mode of layer.
*/
leColorMode leGetLayerColorMode(uint32_t lyrIdx);
/**
* @brief Set layer color mode.
* @details Sets the the layer color mode at index
* @code
* leResult res = leGetLayerColorMode(0, LE_RGB_565);
* @endcode
* @param lyrIdx is the index of the layer to query
* @param mode is the color mode to set
* @return result.
*/
leResult leSetLayerColorMode(uint32_t lyrIdx, leColorMode mode);
/**
* @brief Get layer render direction.
* @details Gets the the layer render direction
* @code
* bool horz = leGetLayerRenderHorizontal(0);
* @endcode
* @param lyrIdx is the index of the layer to query
* @return true if the layer is set to render horizontally.
*/
leBool leGetLayerRenderHorizontal(uint32_t lyrIdx);
/**
* @brief Set layer render direction.
* @details Sets the the layer render direction at index. By default a layer
* is rendered from top-down with dirty rectangles sliced favoring height. In
* horizontal mode layers are rendered from left to right with rectangles
* sliced favoring width. This can help reduce tearing for scenes that have
* horizontal movement.
* @code
* leResult res = leSetLayerRenderHorizontal(0, true);
* @endcode
* @param lyrIdx is the index of the layer to modify
* @param true if the layer should use horizontal mode
* @return result.
*/
leResult leSetLayerRenderHorizontal(uint32_t lyrIdx, leBool horz);
#if 0
// *****************************************************************************
/**
* @brief Get display rectangle.
* @details Gets the display rectangles width height and upper left
* corner coordinates of the physical display.
* @code
* leRect rect = leGetDisplayRect();
* @endcode
* @return the display rectangle.
*/
leRect leGetDisplayRect();
#endif
// *****************************************************************************
/**
* @brief Get string table.
* @details Get a pointer to the leStringTable structure that
* maintains the strings, associated fonts, etc.
* @code
* leStringTable* tbl = leGetStringTable();
* @endcode
* @param void.
* @return leStringTable pointer.
*/
leStringTable* leGetStringTable(void);
// *****************************************************************************
/* Function:
void leSetStringTable(leStringTable* table)
Summary:
Set the StringTable pointer to the specified new StringTableAsset structure
Description:
Set the StringTable pointer to the specified new StringTableAsset structure
Precondition:
Parameters:
leStringTable*
Returns:
void
Remarks:
*/
/**
* @brief Set string table.
* @details Set string table to <span class="param">table</span>.
* @code
* leStringTable* table
* leSetStringTable(table);
* @endcode
* @param table is pointer to a string table.
* @return void.
*/
void leSetStringTable(const leStringTable* table);
// *****************************************************************************
/* Function:
uint32_t leGetStringLanguage()
Summary:
Returns the language index of the current context
Description:
Returns the language index of the current context
Precondition:
Parameters:
Returns:
uint32_t
Remarks:
*/
/**
* @brief Get language index.
* @details Returns the language index of the current context.
* @code
* uint32_t idx = leGetStringLanguage();
* @endcode
* @param void.
* @return void.
*/
uint32_t leGetStringLanguage(void);
// *****************************************************************************
/* Function:
void leSetStringLanguage(uint32_t id)
Summary:
Sets the current language index
Description:
Sets the current language index
Precondition:
Parameters:
uint32_t
Returns:
void
Remarks:
*/
/**
* @brief Get language by index.
* @details Returns the language at the location specified by <span class="param">idx</span>.
* @code
* uint32_t id;
* leSetStringLanguage(id);
* @endcode
* @param void.
* @return void.
*/
void leSetStringLanguage(uint32_t id);
// *****************************************************************************
/* Function:
leScheme* leGetDefaultScheme()
Summary:
Returns the pointer to the current default scheme
Description:
Returns the pointer to the current default scheme
Precondition:
Parameters:
Returns:
leScheme*
Remarks:
*/
/**
* @brief Get default scheme.
* @details Returns the pointer to the current default scheme.
* @code
* leScheme* scheme = leGetDefaultScheme();
* @endcode
* @param void.
* @return void.
*/
leScheme* leGetDefaultScheme(void);
// *****************************************************************************
/* Function:
leWidget* leGetFocusWidget()
Summary:
Return a pointer to the widget in focus
Description:
The focus widget is the widget that is currently receiving all input events.
This can happen when the user initiates a touch down event on the widget
and is currently dragging their finger on the display. The widget will
receive all touch moved events until a touch up event is received.
Precondition:
Parameters:
Returns:
leWidget*
Remarks:
*/
/**
* @brief Get focus widget.
* @details The focus widget is the widget that is currently receiving all input
* events. This can happen when the user initiates a touch down event on the widget
* and is currently dragging their finger on the display. The widget will
* receive all touch moved events until a touch up event is received.
* @code
* leWidget* widget = leGetFocusWidget();
* @endcode
* @param void.
* @return void.
*/
leWidget* leGetFocusWidget(void);
// *****************************************************************************
/* Function:
leResult leSetFocusWidget(leWidget* widget)
Summary:
Set into focus the widget specified as the argument
Description:
Set into focus the widget specified as the argument
Precondition:
Parameters:
leWidget*
Returns:
leResult
Remarks:
*/
/**
* @brief Get language by index.
* @details Sets the focus widget to <span class="param">widget</span>.
* @code
* uint32_t id;
* leResult res = leSetFocusWidget(id);
* @endcode
* @param void.
* @return void.
*/
leResult leSetFocusWidget(leWidget* widget);
// *****************************************************************************
/* Function:
leEditWidget* leGetEditWidget()
Summary:
Gets the widget that is currently recieving all widget edit events.
Description:
Edit widgets are widgets that inherit the 'edit widget' API function list.
These widgets are capable of receiving edit events from other widgets
that are edit event broadcasters. A broadcaster could be a 'key pad' and
a receiver could be a 'text edit' box.
Precondition:
Parameters:
void
Returns:
leEditWidget*
Remarks:
*/
/**
* @brief Get edit widget.
* @details Edit widgets are widgets that inherit the 'edit widget' API function
* list. These widgets are capable of receiving edit events from other widgets
* that are edit event broadcasters. A broadcaster could be a 'key pad' and a
* receiver could be a 'text edit' box.
* @code
* leEditWidget* widget = leGetEditWidget();
* @endcode
* @param void.
* @return leEditWidget pointer.
*/
leEditWidget* leGetEditWidget(void);
// *****************************************************************************
/* Function:
leResult leSetEditWidget(leEditWidget* widget)
Summary:
Sets the currently active edit widget.
Precondition:
Parameters:
leEditWidget* - a widget that inherits the edit widget API
Returns:
leResult
Remarks:
*/
/**
* @brief Set edit widget.
* @details Sets the active edit widget to <span class="param">widget</span>. Edit widgets are widgets that inherit the 'edit widget' API function
* list. These widgets are capable of receiving edit events from other widgets
* that are edit event broadcasters. A broadcaster could be a 'key pad' and a
* receiver could be a 'text edit' box.
* @code
* leEditWidget* widget = leSetEditWidget(widget);
* @endcode
* @param void.
* @return leEditWidget pointer.
*/
leResult leSetEditWidget(leEditWidget* widget);
// *****************************************************************************
/* Function:
leResult leSetLanguageChangedCallback(leLanguageChangedCallback_FnPtr cb)
Summary:
Set the callback function pointer when the language change event occurs
Description:
Set the callback function pointer when the language change event occurs
Precondition:
Parameters:
leLanguageChangedCallback_FnPtr
Returns:
leResult
Remarks:
*/
/**
* @brief Set language change callback.
* @details Sets the callback function to <span class="param">cb</span>
* to handle the language change event.
* @code
* leLanguageChangedCallback_FnPtr cb;
* leResult res = leSetLanguageChangedCallback(cb);
* @endcode
* @param cb is the new callback function.
* @return leResult.
*/
leResult leSetLanguageChangedCallback(leLanguageChangedCallback_FnPtr cb);
// *****************************************************************************
/* Function:
void leRedrawAll()
Summary:
Forces the library to redraw the currently active scene in its entirety.
Precondition:
Parameters:
Returns:
void
Remarks:
*/
/**
* @brief Redraw All.
* @details Forces the library to redraw the currently active scene in its entirety.
* @code
* leRedrawAll();
* @endcode
* @param void.
* @return void.
*/
void leRedrawAll(void);
/* Function:
leBool leIsDrawing()
Summary:
Indicates if any layers of the active screen are currently drawing a
frame.
Description:
Indicates if the library currently drawing a frame. Because frame updates
can asynchronous to making changes to the UI state it is best to only make
updates to the state of a widget only when the layer is not drawing.
Returns:
leResult
*/
/**
* @brief Check active screen drawing state.
* @details Indicates if the library currently drawing a frame. Because frame
* updates can asynchronous to making changes to the UI state it is best to only
* make updates to the state of a widget only when the layer is not drawing.
* @code
* leBool flag = leIsDrawing();
* @endcode
* @param void.
* @return true.
*/
leBool leIsDrawing(void);
/* Function:
leResult leAddRootWidget(leWidget* wgt, uint32_t layer)
Summary:
Adds a custom widget to a static scene root widget.
Description:
The library maintains a static list of widgets that are considered
to be scene roots. The library treats these roots as layers and
the display driver may configure itself to render these roots
to different hardware layers.
This API adds a child widget to one of the static roots.
Returns:
leResult
*/
/**
* @brief Add root widget to layer.
* @details Adds the root widget <span class="param">wgt</span>
* to the layer <span class="param">layer</span>.
* The library maintains a static list of widgets that are considered
* to be scene roots. The library treats these roots as layers and
* the display driver may configure itself to render these roots
* to different hardware layers.
* This API adds a child widget to one of the static roots.
* @code
* leResult res = leAddRootWidget(wgt, layer);
* @endcode
* @param void.
* @return leResult.
*/
leResult leAddRootWidget(leWidget* wgt,
uint32_t layer);
/* Function:
leResult leRemoveRootWidget(leWidget* wgt, uint32_t layer)
Summary:
Removes a custom widget from a static scene root widget.
Description:
The library maintains a static list of widgets that are considered
to be scene roots. This API removes a child widget from one of the
static roots.
Returns:
leResult
*/
/**
* @brief Remove root widget to layer.
* @details Remove the root widget <span class="param">wgt</span>
* from the layer <span class="param">layer</span>.
* The library maintains a static list of widgets that are considered
* to be scene roots. The library treats these roots as layers and
* the display driver may configure itself to render these roots
* to different hardware layers.
* This API adds a child widget to one of the static roots.
* @code
* leResult res = leRemoveRootWidget(wgt, layer);
* @endcode
* @param void.
* @return leResult.
*/
leResult leRemoveRootWidget(leWidget* wgt,
uint32_t layer);
/* Function:
leBool leWidgetIsInScene(const leWidget* wgt)
Summary:
Searches the active scene for a given widget.
Description:
Searches the active scene for a given widget.
Returns:
leResult - LE_TRUE if the widget is in the current scene
*/
/**
* @brief Determines whether the widget is in the scene.
* @details Determines if <span class="param">wgt</span>
* is in he current scheme.
* Searches the active scene for a given widget.
* @code
* leBool flag = leWidgetIsInScene(wgt);
* @endcode
* @param void.
* @returns LE_SUCCESS if set, otherwise LE_FAILURE.
*/
leBool leWidgetIsInScene(const leWidget* wgt);
int32_t leGetWidgetLayer(const leWidget* wgt);
/* Function:
leResult leEdit_StartEdit(const leWidget* wgt)
Summary:
Passes a 'start edit' command to the current edit widget,
if one exists
Description:
The edit widget is the widget in the scene that is currently receiving
edit events.
Returns:
leResult - LE_TRUE the command was processed successfully
*/
/**
* @brief Send start edit command.
* @details Passes a 'start edit' command to the current edit widget, if one exists.
* @code
* leResult res = leEdit_StartEdit();
* @endcode
* @param void.
* @returns LE_SUCCESS if set, otherwise LE_FAILURE.
*/
leResult leEdit_StartEdit(void);
/**
* @brief Send end edit command.
* @details Sends an 'end edit' command to the current edit widget, if one exists.
* @code
* leEdit_EndEdit();
* @endcode
* @return void.
*/
void leEdit_EndEdit(void);
/**
* @brief Send clear command.
* @details Sends a 'clear' command to the current edit widget, if one exists.
* @code
* leEdit_Clear();
* @endcode
* @return void.
*/
void leEdit_Clear(void);
/**
* @brief Send accept command.
* @details Passes a 'accept' command to the current edit widget, if one exists.
* @code
* leEdit_Accept();
* @endcode
* @return void.
*/
void leEdit_Accept(void);
/* Function:
leResult leEdit_Accept(const leWidget* wgt)
Summary:
Passes a 'set' command and a string to the current edit widget,
if one exists
Description:
Passes a 'set' command and a string to the current edit widget,
if one exists
Returns:
*/
/**
* @brief Send set command.
* @details Passes a 'set' command and string <span class="param">str</span> to the current edit widget, if one exists.
* @code
* leEdit_Set(str);
* @endcode
* @param void.
* @return leResult.
*/
void leEdit_Set(leString* str);
/* Function:
leResult leEdit_Append(const leWidget* wgt)
Summary:
Passes an 'append' command and a string to the current edit widget,
if one exists
Description:
Passes an 'append' command and a string to the current edit widget,
if one exists
Returns:
*/
/**
* @brief Send start edit command.
* @details Passes a 'append' command and string <span class="param">str</span> to the current edit widget, if one exists.
* @code
* leString* str;
* leEdit_Append(str);
* @endcode
* @param void.
* @return void.
*/
void leEdit_Append(leString* str);
/* Function:
leResult leEdit_Append(const leWidget* wgt)
Summary:
Passes a 'backspace' command to the current edit widget,
if one exists
Description:
Passes a 'backspace' command to the current edit widget,
if one exists
Returns:
*/
/**
* @brief Send backspace command.
* @details Passes a 'backspace' command to the current edit widget, if one exists.
* @code
* leEdit_Backspace();
* @endcode
* @param void.
* @return void.
*/
void leEdit_Backspace(void);
#if LE_STREAMING_ENABLED == 1
/* Function:
leStreamManager* leGetActiveStream()
Summary:
Gets the global active data stream manager for the library.
Description:
A data stream manager is a state machine that is currently
attempting to stream data from a source that is external
to the library and possibly local memory. This stream must
be handled to completion before any further rendering can take place.
Returns:
*/
leStreamManager* leGetActiveStream(void);
/* Function:
leResult leRunActiveStream()
Summary:
Allows the current active data stream to run until it preempts or
completes.
Description:
Allows the current active data stream to run until it preempts or
completes.
Returns:
*/
leResult leRunActiveStream(void);
/* Function:
void leAbortActiveStream
Summary:
Terminates the current active data stream regardless of whether
it still has data to receive.
Description:
Terminates the current active data stream regardless of whether
it still has data to receive. It will likely attempt to clean itself up
as best it can. Care should be taken in the application to not send data
to the stream after it has been aborted.
Returns:
*/
void leAbortActiveStream(void);
#endif
#endif /* LEGATO_STATE_H */
| 27.053409 | 146 | 0.649221 | [
"render"
] |
6468fd9bec0c24acdda450648f3a97bb065bd6e9 | 9,773 | h | C | common/utils/vector.h | shastry/nbdkit | f94ec336fb0f5878aa335d0fc7dd03ed340e86c2 | [
"TCL",
"Ruby"
] | null | null | null | common/utils/vector.h | shastry/nbdkit | f94ec336fb0f5878aa335d0fc7dd03ed340e86c2 | [
"TCL",
"Ruby"
] | null | null | null | common/utils/vector.h | shastry/nbdkit | f94ec336fb0f5878aa335d0fc7dd03ed340e86c2 | [
"TCL",
"Ruby"
] | null | null | null | /* nbdkit
* Copyright (C) 2020 Red Hat Inc.
*
* 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 Red Hat 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 RED HAT 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 RED HAT 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.
*/
/* Simple implementation of a vector. It can be cheaply appended, and
* more expensively inserted. There are two main use-cases we
* consider: lists of strings (either with a defined length, or
* NULL-terminated), and lists of numbers. It is generic so could be
* used for lists of anything (eg. structs) where being able to append
* easily is important.
*/
#ifndef NBDKIT_VECTOR_H
#define NBDKIT_VECTOR_H
#include <assert.h>
#include <string.h>
/* Use of this macro defines a new type called ‘name’ containing an
* extensible vector of ‘type’ elements. For example:
*
* DEFINE_VECTOR_TYPE(string_vector, char *)
*
* defines a new type called ‘string_vector’ as a vector of ‘char *’.
* You can create variables of this type:
*
* string_vector names = empty_vector;
*
* where ‘names.ptr[]’ will be an array of strings and ‘names.size’
* will be the number of strings. There are no get/set accessors. To
* iterate over the strings you can use the ‘.ptr’ field directly:
*
* for (size_t i = 0; i < names.size; ++i)
* printf ("%s\n", names.ptr[i]);
*
* Initializing with ‘empty_vector’ sets ‘.ptr = NULL’ and ‘.size = 0’.
*
* DEFINE_VECTOR_TYPE also defines utility functions. For the full
* list see the definition below, but useful functions include:
*
* ‘name’_append (eg. ‘string_vector_append’)
* - Append a new element at the end. This operation is cheap.
*
* ‘name’_insert (eg. ‘string_vector_insert’)
* - Insert a new element at the beginning, middle or end. This
* operation is more expensive because existing elements may need
* to be copied around.
*
* Both functions extend the vector if required, and so both may fail
* (returning -1) which you must check for.
*/
#define DEFINE_VECTOR_TYPE(name, type) \
struct name { \
type *ptr; /* Pointer to array of items. */ \
size_t size; /* Number of valid items in the array. */ \
size_t alloc; /* Number of items allocated. */ \
}; \
typedef struct name name; \
\
/* Reserve n elements at the end of the vector. Note space is \
* allocated but the vector size is not increased and the new \
* elements are not initialized. \
*/ \
static inline int \
name##_reserve (name *v, size_t n) \
{ \
return generic_vector_reserve ((struct generic_vector *)v, n, \
sizeof (type)); \
} \
\
/* Insert at i'th element. i=0 => beginning i=size => append */ \
static inline int \
name##_insert (name *v, type elem, size_t i) \
{ \
assert (i <= v->size); \
if (v->size >= v->alloc) { \
if (name##_reserve (v, 1) == -1) return -1; \
} \
memmove (&v->ptr[i+1], &v->ptr[i], (v->size-i) * sizeof (elem)); \
v->ptr[i] = elem; \
v->size++; \
return 0; \
} \
\
/* Append a new element to the end of the vector. */ \
static inline int \
name##_append (name *v, type elem) \
{ \
return name##_insert (v, elem, v->size); \
} \
\
/* Remove i'th element. i=0 => beginning i=size-1 => end */ \
static inline void \
name##_remove (name *v, size_t i) \
{ \
assert (i < v->size); \
memmove (&v->ptr[i], &v->ptr[i+1], (v->size-i) * sizeof (type)); \
v->size--; \
} \
\
/* Remove all elements and deallocate the vector. */ \
static inline void \
name##_reset (name *v) \
{ \
free (v->ptr); \
v->ptr = NULL; \
v->size = v->alloc = 0; \
} \
\
/* Iterate over the vector, calling f() on each element. */ \
static inline void \
name##_iter (name *v, void (*f) (type elem)) \
{ \
size_t i; \
for (i = 0; i < v->size; ++i) \
f (v->ptr[i]); \
} \
\
/* Sort the elements of the vector. */ \
static inline void \
name##_sort (name *v, \
int (*compare) (const type *p1, const type *p2)) \
{ \
qsort (v->ptr, v->size, sizeof (type), (void *) compare); \
} \
\
/* Search for an exactly matching element in the vector using a \
* binary search. Returns a pointer to the element or NULL. \
*/ \
static inline type * \
name##_search (const name *v, const void *key, \
int (*compare) (const void *key, const type *v)) \
{ \
return bsearch (key, v->ptr, v->size, sizeof (type), \
(void *) compare); \
}
#define empty_vector { .ptr = NULL, .size = 0, .alloc = 0 }
struct generic_vector {
void *ptr;
size_t size;
size_t alloc;
};
extern int generic_vector_reserve (struct generic_vector *v,
size_t n, size_t itemsize);
#endif /* NBDKIT_VECTOR_H */
| 54.904494 | 74 | 0.400287 | [
"vector"
] |
64737198218ad5d045563d7569cea43742f15023 | 3,037 | h | C | Wrapping/PythonCore/vtkSmartPyObject.h | michaelchanwahyan/vtk-7.0.0 | 770166bbe1f28a99d776b47624c6f6955b9aaaec | [
"BSD-3-Clause"
] | 1 | 2019-04-22T09:09:17.000Z | 2019-04-22T09:09:17.000Z | Wrapping/PythonCore/vtkSmartPyObject.h | michaelchanwahyan/vtk-7.0.0 | 770166bbe1f28a99d776b47624c6f6955b9aaaec | [
"BSD-3-Clause"
] | null | null | null | Wrapping/PythonCore/vtkSmartPyObject.h | michaelchanwahyan/vtk-7.0.0 | 770166bbe1f28a99d776b47624c6f6955b9aaaec | [
"BSD-3-Clause"
] | 1 | 2019-08-30T08:41:21.000Z | 2019-08-30T08:41:21.000Z | /*=========================================================================
Program: Visualization Toolkit
Module: vtkSmartPyObject.h
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
// .NAME vtkSmartPyObject
// .SECTION Description
// The vtkSmartPyObject class serves as a smart pointer for PyObjects.
#ifndef vtkSmartPyObject_h
#define vtkSmartPyObject_h
// this must be included first
#include "vtkPython.h" // PyObject can't be forward declared
#include "vtkWrappingPythonCoreModule.h"
class VTKWRAPPINGPYTHONCORE_EXPORT vtkSmartPyObject {
public:
// Description:
// Creates a new vtkSmartPyObject managing the existing reference
// to the object given
vtkSmartPyObject(PyObject *obj = NULL);
// Description:
// Creates a new vtkSmartPyObject to the object in the other smart
// pointer and increments the reference count to the object
vtkSmartPyObject(const vtkSmartPyObject &other);
// Description:
// Decrements the reference count to the object
~vtkSmartPyObject();
// Description:
// The internal pointer is copied from the other vtkSmartPyObject.
// The reference count on the old object is decremented and the
// reference count on the new object is incremented
vtkSmartPyObject& operator=(const vtkSmartPyObject &other);
// Description:
// Sets the internal pointer to the given PyObject. The reference
// count on the PyObject is incremented. To take a reference without
// incrementing the reference count use TakeReference.
vtkSmartPyObject& operator=(PyObject *obj);
// Description:
// Sets the internal pointer to the given PyObject without incrementing
// the reference count
void TakeReference(PyObject* obj);
// Description:
// Provides normal pointer target member access using operator ->.
PyObject *operator->() const;
// Description:
// Get the contained pointer.
operator PyObject*() const;
// Description:
// Returns true if the internal pointer is to a valid PyObject.
operator bool() const;
// Description:
// Returns the pointer to a PyObject stored internally and clears the
// internally stored pointer. The caller is responsible for calling
// Py_DECREF on the returned object when finished with it as this
// does not change the reference count.
PyObject* ReleaseReference();
// Description:
// Returns the internal pointer to a PyObject with no effect on its
// reference count
PyObject *GetPointer() const;
// Description:
// Returns the internal pointer to a PyObject and incrments its reference
// count
PyObject* GetAndIncreaseReferenceCount();
private:
PyObject *Object;
};
#endif
| 34.511364 | 75 | 0.712545 | [
"object"
] |
647816747a65a8360a77edadc9dd27790fc5d4b7 | 3,893 | h | C | include/espressif/airkiss.h | YufengZhangMyself/use_jinyun | 62395e75cf6e4faf3ef577eab1d90186a67aedf5 | [
"BSD-3-Clause"
] | null | null | null | include/espressif/airkiss.h | YufengZhangMyself/use_jinyun | 62395e75cf6e4faf3ef577eab1d90186a67aedf5 | [
"BSD-3-Clause"
] | null | null | null | include/espressif/airkiss.h | YufengZhangMyself/use_jinyun | 62395e75cf6e4faf3ef577eab1d90186a67aedf5 | [
"BSD-3-Clause"
] | null | null | null | /*
* airkiss.h
*
* Created on: 2015-1-26
* Author: peterfan
*/
#ifndef _AIRKISS_H_
#define _AIRKISS_H_
#ifdef __cplusplus
extern "C" {
#endif
typedef void* (*airkiss_memset_fn) (void* ptr, int value, unsigned int num);
typedef void* (*airkiss_memcpy_fn) (void* dst, const void* src, unsigned int num);
typedef int (*airkiss_memcmp_fn) (const void* ptr1, const void* ptr2, unsigned int num);
typedef int (*airkiss_printf_fn) (const char* format, ...);
typedef struct
{
airkiss_memset_fn memset;
airkiss_memcpy_fn memcpy;
airkiss_memcmp_fn memcmp;
airkiss_printf_fn printf;
} airkiss_config_t;
/** \defgroup WiFi_APIs WiFi Related APIs
* @brief WiFi APIs
*/
/** @addtogroup WiFi_APIs
* @{
*/
/** \defgroup AirKiss_APIs AirKiss APIs
* @brief AirKiss APIs
*
* API airkiss_lan_recv and airkiss_lan_pack are provided for the function that AirKiss can detect
* the ESP8266 devices in LAN, more details about AirKiss please refer to WeChat : http://iot.weixin.qq.com.
*
* Workflow : Create a UDP transmission. When UDP data is received, call API airkiss_lan_recv and
* input the UDP data, if the airkiss_lan_recv returns AIRKISS_LAN_SSDP_REQ, airkiss_lan_pack
* can be called to make a response packet.
*
*/
/** @addtogroup AirKiss_APIs
* @{
*/
/**
* @brief Get the version information of AirKiss lib.
*
* @attention The lenth of version is unknown
*
* @param null.
*
* @return the version information of AirKiss lib
*/
const char* airkiss_version(void);
typedef enum
{
/** the length of the data buffer is lack*/
AIRKISS_LAN_ERR_OVERFLOW = -5,
/** Do not support the type of instruction */
AIRKISS_LAN_ERR_CMD = -4,
/** Error reading data package */
AIRKISS_LAN_ERR_PAKE = -3,
/** Error function passing parameters */
AIRKISS_LAN_ERR_PARA = -2,
/** Packet data error */
AIRKISS_LAN_ERR_PKG = -1,
/** Message format is correct */
AIRKISS_LAN_CONTINUE = 0,
/** Find equipment request packet is received */
AIRKISS_LAN_SSDP_REQ = 1,
/** Packet packaging complete */
AIRKISS_LAN_PAKE_READY = 2
} airkiss_lan_ret_t;
typedef enum
{
AIRKISS_LAN_SSDP_REQ_CMD = 0x1,
AIRKISS_LAN_SSDP_RESP_CMD = 0x1001,
AIRKISS_LAN_SSDP_NOTIFY_CMD = 0x1002
} airkiss_lan_cmdid_t;
/**
* @brief Parse the UDP packet sent by AirKiss.
*
* @param const void* body : the start of the UDP message body data pointer.
* @param unsigned short length : the effective length of data.
* @param const airkiss_config_t* config : input struct airkiss_config_t
*
* @return >=0 : succeed (reference airkiss_lan_ret_t)
* @return <0 : error code (reference airkiss_lan_ret_t)
*/
int airkiss_lan_recv(const void* body, unsigned short length, const airkiss_config_t* config);
/**
* @brief Packaging the UDP packet.
*
* @param airkiss_lan_cmdid_t ak_lan_cmdid : type of the packet.
* @param void* appid : Vendor's Wechat public number id, got from WeChat.
* @param void* deviceid : device model id, got from WeChat.
* @param void* _datain : user data waiting for packet assembly.
* @param unsigned short inlength : the lenth of user data.
* @param void* _dataout : data buffer addr, to store the packet got by _datain packet assembly.
* @param unsigned short* outlength : the size of data buffer.
* @param const airkiss_config_t* config : input struct airkiss_config_t
*
* @return >=0 : succeed (reference airkiss_lan_ret_t)
* @return <0 : error code (reference airkiss_lan_ret_t)
*/
int airkiss_lan_pack(airkiss_lan_cmdid_t ak_lan_cmdid, void* appid, void* deviceid, void* _datain, unsigned short inlength, void* _dataout, unsigned short* outlength, const airkiss_config_t* config);
/**
* @}
*/
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* AIRKISS_H_ */
| 25.781457 | 199 | 0.694066 | [
"model"
] |
647d1fccd0e56953070b8c22e4892e0a4bbba359 | 533 | h | C | RingedOrb/Graphics/GUI/roGUIData.h | JohnCKangwa/RingedOrb | 7aa8ab642e8938838c86a8d9951b589976f3ebd9 | [
"MIT"
] | null | null | null | RingedOrb/Graphics/GUI/roGUIData.h | JohnCKangwa/RingedOrb | 7aa8ab642e8938838c86a8d9951b589976f3ebd9 | [
"MIT"
] | null | null | null | RingedOrb/Graphics/GUI/roGUIData.h | JohnCKangwa/RingedOrb | 7aa8ab642e8938838c86a8d9951b589976f3ebd9 | [
"MIT"
] | null | null | null | #pragma once
#include "..\..\Core\pch.h"
struct roGUIREntity {
UINT ID;
float Translation[3];
};
struct roGUIData {
static bool GetOpenModelDialogState();
static void SetOpenModelDialogState(bool state);
static bool GetAddEnityState();
static void SetAddEnityState(bool state);
static void AddGUIMeshName(std::string);
public:
static std::vector<std::pair<std::string, bool>> sm_MeshData;
static std::vector<roGUIREntity> sm_GUIREntities;
private:
static bool sm_bIsOpenModelDialog;
static bool sm_bIsAddEntity;
};
| 19.740741 | 62 | 0.763602 | [
"vector"
] |
647d4d4b075b18ecec96b1f2568beeca5824c11b | 6,074 | h | C | src/rvpt/window.h | tigrazone/RVPT | fce7712cd8f00b69464a48cd9cef93e9bae66973 | [
"Apache-2.0"
] | 51 | 2020-04-22T22:59:57.000Z | 2022-01-02T18:18:17.000Z | src/rvpt/window.h | tigrazone/RVPT | fce7712cd8f00b69464a48cd9cef93e9bae66973 | [
"Apache-2.0"
] | 28 | 2020-05-26T19:26:41.000Z | 2022-02-02T19:31:19.000Z | src/rvpt/window.h | tigrazone/RVPT | fce7712cd8f00b69464a48cd9cef93e9bae66973 | [
"Apache-2.0"
] | 9 | 2020-08-20T07:07:44.000Z | 2021-11-11T14:00:28.000Z | //
// Created by legend on 5/20/20.
//
#pragma once
#include <array>
#include <vector>
#include <functional>
#define GLFW_INCLUDE_NONE
#include <GLFW/glfw3.h>
class Window
{
public:
enum class KeyCode
{
SPACE = 32, // I can't wait to write all of these out
APOSTROPHE = 39,
COMMA = 44,
MINUS = 45,
PERIOD = 46,
SLASH = 47,
KEY_0 = 48,
KEY_1 = 49,
KEY_2 = 50,
KEY_3 = 51,
KEY_4 = 52,
KEY_5 = 53,
KEY_6 = 54,
KEY_7 = 55,
KEY_8 = 56,
KEY_9 = 57, // This is starting to get really annoying
SEMICOLON = 59,
EQUAL = 61,
KEY_A = 65,
KEY_B = 66,
KEY_C = 67,
KEY_D = 68,
KEY_E = 69,
KEY_F = 70,
KEY_G = 71,
KEY_H = 72,
KEY_I = 73,
KEY_J = 74,
KEY_K = 75,
KEY_L = 76,
KEY_M = 77,
KEY_N = 78,
KEY_O = 79,
KEY_P = 80,
KEY_Q = 81,
KEY_R = 82,
KEY_S = 83,
KEY_T = 84,
KEY_U = 85,
KEY_V = 86,
KEY_W = 87,
KEY_X = 88,
KEY_Y = 89,
KEY_Z = 90,
KEY_LEFT_BRACKET = 91, /* [ */
KEY_BACKSLASH = 92, /* \ */
KEY_RIGHT_BRACKET = 93, /* ] */
KEY_GRAVE_ACCENT = 96, /* ` */
KEY_WORLD_1 = 161, /* non-US #1 */
KEY_WORLD_2 = 162, /* non-US #2 */
KEY_ESCAPE = 256,
KEY_ENTER = 257,
KEY_TAB = 258,
KEY_BACKSPACE = 259,
KEY_INSERT = 260,
KEY_DELETE = 261,
KEY_RIGHT = 262,
KEY_LEFT = 263,
KEY_DOWN = 264,
KEY_UP = 265,
KEY_PAGE_UP = 266,
KEY_PAGE_DOWN = 267,
KEY_HOME = 268,
KEY_END = 269,
KEY_CAPS_LOCK = 280,
KEY_SCROLL_LOCK = 281,
KEY_NUM_LOCK = 282,
KEY_PRINT_SCREEN = 283,
KEY_PAUSE = 284,
KEY_F1 = 290,
KEY_F2 = 291,
KEY_F3 = 292,
KEY_F4 = 293,
KEY_F5 = 294,
KEY_F6 = 295,
KEY_F7 = 296,
KEY_F8 = 297,
KEY_F9 = 298,
KEY_F10 = 299,
KEY_F11 = 300,
KEY_F12 = 301,
KEY_F13 = 302,
KEY_F14 = 303,
KEY_F15 = 304,
KEY_F16 = 305,
KEY_F17 = 306,
KEY_F18 = 307,
KEY_F19 = 308,
KEY_F20 = 309,
KEY_F21 = 310,
KEY_F22 = 311,
KEY_F23 = 312,
KEY_F24 = 313,
KEY_F25 = 314,
KEY_KP_0 = 320,
KEY_KP_1 = 321,
KEY_KP_2 = 322,
KEY_KP_3 = 323,
KEY_KP_4 = 324,
KEY_KP_5 = 325,
KEY_KP_6 = 326,
KEY_KP_7 = 327,
KEY_KP_8 = 328,
KEY_KP_9 = 329,
KEY_KP_DECIMAL = 330,
KEY_KP_DIVIDE = 331,
KEY_KP_MULTIPLY = 332,
KEY_KP_SUBTRACT = 333,
KEY_KP_ADD = 334,
KEY_KP_ENTER = 335,
KEY_KP_EQUAL = 336,
KEY_LEFT_SHIFT = 340,
KEY_LEFT_CONTROL = 341,
KEY_LEFT_ALT = 342,
KEY_LEFT_SUPER = 343,
KEY_RIGHT_SHIFT = 344,
KEY_RIGHT_CONTROL = 345,
KEY_RIGHT_ALT = 346,
KEY_RIGHT_SUPER = 347,
KEY_MENU = 348,
MAX_KEY = 1024,
};
enum class Action
{
RELEASE,
PRESS,
REPEAT,
UNKNOWN
};
enum class Mouse
{
LEFT,
RIGHT,
MIDDLE,
OTHER
};
using MouseClickCallback = std::function<void(Mouse button, Action action)>;
using MouseMoveCallback = std::function<void(double x, double y)>;
using MouseScrollCallback = std::function<void(double x, double y)>;
struct Settings
{
int width = 800;
int height = 600;
const char* title = "RVPT";
bool resizeable = false;
bool fullscreen = false;
bool vsync = true;
};
explicit Window(Settings settings);
~Window();
void setup_imgui();
[[nodiscard]] float get_aspect_ratio() const noexcept;
void add_mouse_click_callback(MouseClickCallback callback);
void add_mouse_move_callback(MouseMoveCallback callback);
void add_scroll_callback(MouseScrollCallback callback);
void poll_events();
[[nodiscard]] bool is_key_down(KeyCode keycode) const noexcept;
[[nodiscard]] bool is_key_up(KeyCode keycode) const noexcept;
[[nodiscard]] bool is_key_held(KeyCode keycode) const noexcept;
[[nodiscard]] Settings get_settings();
[[nodiscard]] GLFWwindow* get_window_pointer();
[[nodiscard]] bool should_close() const noexcept;
void set_close();
[[nodiscard]] bool is_mouse_locked_to_window() const noexcept;
void set_mouse_window_lock(bool locked);
private:
Settings active_settings;
GLFWwindow* window_ptr;
enum class KeyState
{
none, // no input
pressed, // set on frame key is pressed
held, // set on frame after key is pressed while not released
repeat, // equivalent to held but OS triggered
released // set on frame key is released, cleared after one frame
};
std::array<KeyState, static_cast<size_t>(KeyCode::MAX_KEY)> key_states;
std::vector<MouseClickCallback> mouse_click_callbacks;
std::vector<MouseMoveCallback> mouse_move_callbacks;
std::vector<MouseScrollCallback> scroll_callbacks;
double mouse_position_x{}, mouse_position_y{};
double mouse_position_previous_x{}, mouse_position_previous_y{};
double mouse_change_in_previous_x{}, mouse_change_in_previous_y{};
bool mouse_locked_to_window = true;
double last_mouse_position_x{}, last_mouse_position_y{};
static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods);
static void char_callback(GLFWwindow* window, uint32_t codepoint);
static void mouse_click_callback(GLFWwindow* window, int button, int action, int mods);
static void mouse_move_callback(GLFWwindow* window, double x, double y);
static void scroll_callback(GLFWwindow* window, double x, double y);
};
| 26.640351 | 94 | 0.568818 | [
"vector"
] |
64853a1e3adbe38573a6b55d38e42b35bfcf0d6e | 6,192 | h | C | src/Components/PolygonCollisionShapeComponent.h | NerdThings/Ngine | e5c4754d07ec38e727d8baaf7250dbb996cad49e | [
"Apache-2.0"
] | 2 | 2019-05-24T15:20:14.000Z | 2019-06-12T11:55:27.000Z | src/Components/PolygonCollisionShapeComponent.h | NerdThings/Ngine | e5c4754d07ec38e727d8baaf7250dbb996cad49e | [
"Apache-2.0"
] | 23 | 2019-06-05T12:52:33.000Z | 2020-03-11T15:23:00.000Z | src/Components/PolygonCollisionShapeComponent.h | NerdThings/Ngine | e5c4754d07ec38e727d8baaf7250dbb996cad49e | [
"Apache-2.0"
] | 1 | 2019-10-02T20:31:12.000Z | 2019-10-02T20:31:12.000Z | /**********************************************************************************************
*
* Ngine - The 2D game engine.
*
* Copyright (C) 2019 NerdThings
*
* LICENSE: Apache License 2.0
* View: https://github.com/NerdThings/Ngine/blob/master/LICENSE
*
**********************************************************************************************/
#ifndef POLYGONCOLLISIONSHAPECOMPONENT_H
#define POLYGONCOLLISIONSHAPECOMPONENT_H
#include "../Ngine.h"
#include "Graphics/Renderer.h"
#include "../Physics/BoundingBox.h"
#include "../Physics/Polygon.h"
#include "../Vector2.h"
#include "BaseCollisionShapeComponent.h"
#include "CircleCollisionShapeComponent.h"
namespace NerdThings::Ngine::Components {
/*
* Polygon collider component
*/
class PolygonCollisionShapeComponent : public BaseCollisionShapeComponent {
// Private Fields
/*
* The polygon used
*/
Physics::Polygon _Polygon;
/*
* Polygon vertices
*/
std::vector<Vector2> _Vertices;
// Private Methods
bool CollisionCheck(BaseCollisionShapeComponent *b) override {
auto col = false;
auto bbox = dynamic_cast<BoundingBoxCollisionShapeComponent*>(b);
auto circle = dynamic_cast<CircleCollisionShapeComponent*>(b);
auto polygon = dynamic_cast<PolygonCollisionShapeComponent*>(b);
if (bbox != nullptr) {
auto box = bbox->GetBoundingBox();
col = CollisionCheck(&box);
}
if (circle != nullptr) {
auto c = circle->GetCircle();
col = CollisionCheck(&c);
}
if (polygon != nullptr) {
col = CollisionCheck(&polygon->_Polygon);
}
return col;
}
bool CollisionCheck(Physics::ICollisionShape *b) override {
return _Polygon.CheckCollision(b);
}
void DrawDebug() override {
// Determine color
auto col = Graphics::Color::Red;
if (CheckCollision<BaseEntity>())
col = Graphics::Color::Green;
// Draw every vertex of the polygon
Graphics::Renderer::DrawLine(_Polygon.Vertices[0], _Polygon.Vertices[1], col);
for (auto i = 1; i < _Polygon.VertexCount - 1; i++) {
Graphics::Renderer::DrawLine(_Polygon.Vertices[i], _Polygon.Vertices[i + 1], col);
}
Graphics::Renderer::DrawLine(_Polygon.Vertices[_Polygon.VertexCount - 1], _Polygon.Vertices[0], col);
}
bool IsCompatible(BaseCollisionShapeComponent *b) override {
// We handle collisions with bounding boxes, circles and ourselves
auto bbox = dynamic_cast<BoundingBoxCollisionShapeComponent*>(b);
auto circle = dynamic_cast<CircleCollisionShapeComponent*>(b);
auto polygon = dynamic_cast<PolygonCollisionShapeComponent*>(b);
if (bbox != nullptr)
return true;
if (circle != nullptr)
return true;
if (polygon != nullptr)
return true;
return false;
}
void Offset(Vector2 offset_) override {
const auto par = GetParent<BaseEntity>();
// Offset vertices
std::vector<Vector2> vertices(_Vertices.size());
for (auto i = 0; i < _Vertices.size(); i++) {
vertices[i] = _Vertices[i];
vertices[i] *= par->GetScale();
vertices[i] = vertices[i].Rotate(par->GetOrigin(), par->GetRotation());
vertices[i] += par->GetPosition() - par->GetOrigin() + offset_;
}
_Polygon = Physics::Polygon(vertices);
}
void UpdateShape(EntityTransformChangedEventArgs e) override {
std::vector<Vector2> vertices(_Vertices.size());
for (auto i = 0; i < _Vertices.size(); i++) {
vertices[i] = _Vertices[i];
vertices[i] *= e.EntityScale;
vertices[i] = vertices[i].Rotate(e.EntityOrigin, e.EntityRotation);
vertices[i] += e.EntityPosition - e.EntityOrigin;
}
_Polygon = Physics::Polygon(vertices);
}
public:
// Public Constructor(s)
PolygonCollisionShapeComponent(BaseEntity *parent_, std::vector<Vector2> vertices_,
std::string collisionGroup_ = "General")
: BaseCollisionShapeComponent(parent_, std::move(collisionGroup_)), _Vertices(std::move(vertices_)) {
const auto par = GetParent<BaseEntity>();
// Create polygon
SetPolygon(Physics::Polygon(_Vertices));
}
PolygonCollisionShapeComponent(BaseEntity *parent_, Physics::Polygon polygon_,
std::string collisionGroup_ = "General")
: BaseCollisionShapeComponent(parent_, std::move(collisionGroup_)) {
const auto par = GetParent<BaseEntity>();
SetPolygon(std::move(polygon_));
}
// Public Methods
Physics::Polygon GetPolygon() const {
return _Polygon;
}
std::vector<Vector2> GetSourceVertices() {
return _Vertices;
}
void SetPolygon(const Physics::Polygon &polygon_) {
const auto par = GetParent<BaseEntity>();
// Grab vertices
_Vertices.resize(polygon_.VertexCount);
for (auto i = 0; i < polygon_.VertexCount; i++) {
_Vertices[i] = polygon_.Vertices[i];
}
std::vector<Vector2> vertices(_Vertices.size());
for (auto i = 0; i < _Vertices.size(); i++) {
vertices[i] = _Vertices[i];
vertices[i] *= par->GetScale();
vertices[i] = vertices[i].Rotate(par->GetOrigin(), par->GetRotation());
vertices[i] += par->GetPosition() - par->GetOrigin();
}
_Polygon = Physics::Polygon(vertices);
}
};
}
#endif //POLYGONCOLLISIONSHAPECOMPONENT_H
| 34.786517 | 113 | 0.546835 | [
"vector"
] |
648fe5ac4d108b8ffa188a5d5d1ff885d0d7241f | 32,735 | c | C | src/hwloc/hwloc.c | wickberg/prrte | fa518422adbe43e75cd8125da10c20461e7a547b | [
"BSD-3-Clause-Open-MPI"
] | null | null | null | src/hwloc/hwloc.c | wickberg/prrte | fa518422adbe43e75cd8125da10c20461e7a547b | [
"BSD-3-Clause-Open-MPI"
] | null | null | null | src/hwloc/hwloc.c | wickberg/prrte | fa518422adbe43e75cd8125da10c20461e7a547b | [
"BSD-3-Clause-Open-MPI"
] | null | null | null | /*
* Copyright (c) 2011-2020 Cisco Systems, Inc. All rights reserved
* Copyright (c) 2013-2020 Intel, Inc. All rights reserved.
* Copyright (c) 2016-2017 Research Organization for Information Science
* and Technology (RIST). All rights reserved.
* Copyright (c) 2021-2022 Nanook Consulting. All rights reserved.
* $COPYRIGHT$
*
* Additional copyrights may follow
*
* $HEADER$
*/
#include "prte_config.h"
#include "src/hwloc/hwloc-internal.h"
#include "src/include/constants.h"
#include "src/mca/base/base.h"
#include "src/mca/mca.h"
#include "src/mca/rmaps/rmaps_types.h"
#include "src/mca/schizo/schizo.h"
#include "src/runtime/prte_globals.h"
#include "src/threads/pmix_tsd.h"
#include "src/util/pmix_argv.h"
#include "src/util/output.h"
#include "src/util/show_help.h"
/*
* Globals
*/
bool prte_hwloc_base_inited = false;
hwloc_topology_t prte_hwloc_topology = NULL;
hwloc_cpuset_t prte_hwloc_my_cpuset = NULL;
prte_hwloc_base_map_t prte_hwloc_base_map = PRTE_HWLOC_BASE_MAP_NONE;
prte_hwloc_base_mbfa_t prte_hwloc_base_mbfa = PRTE_HWLOC_BASE_MBFA_WARN;
prte_binding_policy_t prte_hwloc_default_binding_policy = 0;
char *prte_hwloc_default_cpu_list = NULL;
char *prte_hwloc_base_topo_file = NULL;
int prte_hwloc_base_output = -1;
bool prte_hwloc_default_use_hwthread_cpus = false;
hwloc_obj_type_t prte_hwloc_levels[] = {
HWLOC_OBJ_MACHINE,
HWLOC_OBJ_NUMANODE,
HWLOC_OBJ_PACKAGE,
HWLOC_OBJ_L3CACHE,
HWLOC_OBJ_L2CACHE,
HWLOC_OBJ_L1CACHE,
HWLOC_OBJ_CORE,
HWLOC_OBJ_PU
};
static prte_mca_base_var_enum_value_t hwloc_base_map[] = {
{PRTE_HWLOC_BASE_MAP_NONE, "none"},
{PRTE_HWLOC_BASE_MAP_LOCAL_ONLY, "local_only"},
{0, NULL}
};
static prte_mca_base_var_enum_value_t hwloc_failure_action[] = {
{PRTE_HWLOC_BASE_MBFA_SILENT, "silent"},
{PRTE_HWLOC_BASE_MBFA_WARN, "warn"},
{PRTE_HWLOC_BASE_MBFA_ERROR, "error"},
{0, NULL}
};
static char *prte_hwloc_base_binding_policy = NULL;
static int verbosity = 0;
static char *default_cpu_list = NULL;
static bool bind_to_core = false;
static bool bind_to_socket = false;
int prte_hwloc_base_register(void)
{
prte_mca_base_var_enum_t *new_enum;
int ret;
char *ptr;
/* debug output */
ret = prte_mca_base_var_register("prte", "hwloc", "base", "verbose", "Debug verbosity",
PRTE_MCA_BASE_VAR_TYPE_INT, NULL, 0,
PRTE_MCA_BASE_VAR_FLAG_NONE, PRTE_INFO_LVL_9,
PRTE_MCA_BASE_VAR_SCOPE_READONLY, &verbosity);
prte_mca_base_var_register_synonym(ret, "opal", "hwloc", "base", "verbose",
PRTE_MCA_BASE_VAR_SYN_FLAG_DEPRECATED);
if (0 < verbosity) {
prte_hwloc_base_output = prte_output_open(NULL);
prte_output_set_verbosity(prte_hwloc_base_output, verbosity);
}
/* handle some deprecated options */
prte_hwloc_default_use_hwthread_cpus = false;
(void) prte_mca_base_var_register("prte", "hwloc", "base", "use_hwthreads_as_cpus",
"Use hardware threads as independent cpus",
PRTE_MCA_BASE_VAR_TYPE_BOOL,
NULL, 0, PRTE_MCA_BASE_VAR_FLAG_DEPRECATED,
PRTE_INFO_LVL_9,
PRTE_MCA_BASE_VAR_SCOPE_READONLY,
&prte_hwloc_default_use_hwthread_cpus);
(void) prte_mca_base_var_register("prte", "hwloc", "base", "bind_to_core",
"Bind processes to cores",
PRTE_MCA_BASE_VAR_TYPE_BOOL,
NULL, 0, PRTE_MCA_BASE_VAR_FLAG_DEPRECATED,
PRTE_INFO_LVL_9,
PRTE_MCA_BASE_VAR_SCOPE_READONLY,
&bind_to_core);
(void) prte_mca_base_var_register("prte", "hwloc", "base", "bind_to_socket",
"Bind processes to sockets",
PRTE_MCA_BASE_VAR_TYPE_BOOL,
NULL, 0, PRTE_MCA_BASE_VAR_FLAG_DEPRECATED,
PRTE_INFO_LVL_9,
PRTE_MCA_BASE_VAR_SCOPE_READONLY,
&bind_to_socket);
/* hwloc_base_mbind_policy */
prte_hwloc_base_map = PRTE_HWLOC_BASE_MAP_NONE;
prte_mca_base_var_enum_create("hwloc memory allocation policy", hwloc_base_map, &new_enum);
ret = prte_mca_base_var_register("prte", "hwloc", "default", "mem_alloc_policy",
"Default general memory allocations placement policy (this is not memory binding). "
"\"none\" means that no memory policy is applied. \"local_only\" means that a process' "
"memory allocations will be restricted to its local NUMA domain. "
"If using direct launch, this policy will not be in effect until after MPI_INIT. "
"Note that operating system paging policies are unaffected by this setting. For "
"example, if \"local_only\" is used and local NUMA domain memory is exhausted, a new "
"memory allocation may cause paging.",
PRTE_MCA_BASE_VAR_TYPE_INT, new_enum, 0,
PRTE_MCA_BASE_VAR_FLAG_DEPRECATED, PRTE_INFO_LVL_9,
PRTE_MCA_BASE_VAR_SCOPE_READONLY, &prte_hwloc_base_map);
PMIX_RELEASE(new_enum);
if (0 > ret) {
return ret;
}
prte_mca_base_var_register_synonym(ret, "opal", "hwloc", "base", "mem_alloc_policy",
PRTE_MCA_BASE_VAR_SYN_FLAG_DEPRECATED);
/* hwloc_base_bind_failure_action */
prte_hwloc_base_mbfa = PRTE_HWLOC_BASE_MBFA_WARN;
prte_mca_base_var_enum_create("hwloc memory bind failure action", hwloc_failure_action,
&new_enum);
ret = prte_mca_base_var_register("prte", "hwloc", "default", "mem_bind_failure_action",
"What PRTE will do if it explicitly tries to bind memory to a specific NUMA "
"location, and fails. Note that this is a different case than the general "
"allocation policy described by mem_alloc_policy. A value of \"silent\" "
"means that PRTE will proceed without comment. A value of \"warn\" means that "
"PRTE will warn the first time this happens, but allow the job to continue "
"(possibly with degraded performance). A value of \"error\" means that PRTE "
"will abort the job if this happens.",
PRTE_MCA_BASE_VAR_TYPE_INT, new_enum, 0,
PRTE_MCA_BASE_VAR_FLAG_NONE, PRTE_INFO_LVL_9,
PRTE_MCA_BASE_VAR_SCOPE_READONLY, &prte_hwloc_base_mbfa);
PMIX_RELEASE(new_enum);
if (0 > ret) {
return ret;
}
prte_mca_base_var_register_synonym(ret, "opal", "hwloc", "base", "mem_bind_failure_action",
PRTE_MCA_BASE_VAR_SYN_FLAG_DEPRECATED);
/* NOTE: for future developers and readers of this code, the binding policies are strictly
* limited to none, hwthread, core, l1cache, l2cache, l3cache, package, and numa
*
* The default binding policy can be modified by any combination of the following:
* * overload-allowed - multiple processes can be bound to the same PU (core or HWT)
* * if-supported - perform the binding if it is supported by the OS, but do not
* generate an error if it cannot be done
*/
prte_hwloc_base_binding_policy = NULL;
ret = prte_mca_base_var_register("prte", "hwloc", "default", "binding_policy",
"Default policy for binding processes. Allowed values: none, hwthread, core, l1cache, "
"l2cache, "
"l3cache, numa, package, (\"none\" is the default when oversubscribed, \"core\" is "
"the default when np<=2, and \"numa\" is the default when np>2). Allowed "
"colon-delimited qualifiers: "
"overload-allowed, if-supported",
PRTE_MCA_BASE_VAR_TYPE_STRING, NULL, 0,
PRTE_MCA_BASE_VAR_FLAG_NONE, PRTE_INFO_LVL_9,
PRTE_MCA_BASE_VAR_SCOPE_READONLY, &prte_hwloc_base_binding_policy);
prte_mca_base_var_register_synonym(ret, "opal", "hwloc", "base", "binding_policy",
PRTE_MCA_BASE_VAR_SYN_FLAG_DEPRECATED);
if (NULL == prte_hwloc_base_binding_policy) {
if (bind_to_core) {
prte_hwloc_base_binding_policy = "core";
} else if (bind_to_socket) {
prte_hwloc_base_binding_policy = "package";
}
}
/* Allow specification of a default CPU list - a comma-delimited list of cpu ranges that
* are the default PUs for this DVM. CPUs are to be specified as LOGICAL indices. If a
* cpuset is provided, then all process placements and bindings will be constrained to the
* identified CPUs. IN ESSENCE, THIS IS A USER-DEFINED "SOFT" CGROUP.
*
* Example: if the default binding policy is "core", then each process will be bound to the
* first unused core underneath the topological object upon which it has been mapped. In other
* words, if two processes are mapped to a given package, then the first process will be bound
* to core0 of that package, and the second process will be bound to core1.
*
* If the cpuset specified that only cores 10, 12, and 14 were to be used, then the first
* process would be bound to core10 and the second process would be bound to core12.
*
* If the default binding policy had been set to "package", and if cores 10, 12, and 14 are all
* on the same package, then both processes would be bound to cores 10, 12, and 14. Note that
* they would have been bound to all PUs on the package if the cpuset had not been given.
*
* If cores 10 and 12 are on package0, and core14 is on package1, then if the first process is
* mapped to package0 and we are using a binding policy of "package", the first process would be
* bound to core10 and core12. If the second process were mapped to package1, then it would be
* bound only to core14 as that is the only PU in the cpuset that lies in package1.
*/
default_cpu_list = NULL;
ret = prte_mca_base_var_register("prte", "hwloc", "default", "cpu_list",
"Comma-separated list of ranges specifying logical cpus to be used by the DVM. "
"Supported modifier:HWTCPUS (ranges specified in hwthreads) or CORECPUS "
"(default: ranges specified in cores)",
PRTE_MCA_BASE_VAR_TYPE_STRING, NULL, 0, PRTE_MCA_BASE_VAR_FLAG_NONE, PRTE_INFO_LVL_9,
PRTE_MCA_BASE_VAR_SCOPE_READONLY, &default_cpu_list);
prte_mca_base_var_register_synonym(ret, "opal", "hwloc", "base", "cpu_list",
PRTE_MCA_BASE_VAR_SYN_FLAG_DEPRECATED);
prte_mca_base_var_register_synonym(ret, "opal", "hwloc", "base", "slot_list",
PRTE_MCA_BASE_VAR_SYN_FLAG_DEPRECATED);
prte_mca_base_var_register_synonym(ret, "opal", "hwloc", "base", "cpu_set",
PRTE_MCA_BASE_VAR_SYN_FLAG_DEPRECATED);
if (NULL != default_cpu_list) {
if (NULL != (ptr = strrchr(default_cpu_list, ':'))) {
*ptr = '\0';
prte_hwloc_default_cpu_list = strdup(default_cpu_list);
++ptr;
if (0 == strcasecmp(ptr, "HWTCPUS")) {
prte_hwloc_default_use_hwthread_cpus = true;
} else if (0 == strcasecmp(ptr, "CORECPUS")) {
prte_hwloc_default_use_hwthread_cpus = false;
} else {
prte_show_help("help-prte-hwloc-base.txt", "bad-processor-type", true,
default_cpu_list, ptr);
return PRTE_ERR_BAD_PARAM;
}
} else {
prte_hwloc_default_cpu_list = strdup(default_cpu_list);
}
}
prte_hwloc_base_topo_file = NULL;
ret = prte_mca_base_var_register("prte", "hwloc", "use", "topo_file",
"Read local topology from file instead of directly sensing it",
PRTE_MCA_BASE_VAR_TYPE_STRING, NULL, 0,
PRTE_MCA_BASE_VAR_FLAG_NONE, PRTE_INFO_LVL_9,
PRTE_MCA_BASE_VAR_SCOPE_READONLY, &prte_hwloc_base_topo_file);
(void) prte_mca_base_var_register_synonym(ret, "prte", "ras", "simulator", "topo_files",
PRTE_MCA_BASE_VAR_SYN_FLAG_DEPRECATED | PRTE_MCA_BASE_VAR_SYN_FLAG_INTERNAL);
(void) prte_mca_base_var_register_synonym(ret, "opal", "hwloc", "base", "topo_file",
PRTE_MCA_BASE_VAR_SYN_FLAG_DEPRECATED | PRTE_MCA_BASE_VAR_SYN_FLAG_INTERNAL);
/* register parameters */
return PRTE_SUCCESS;
}
int prte_hwloc_base_open(void)
{
int rc;
if (prte_hwloc_base_inited) {
return PRTE_SUCCESS;
}
prte_hwloc_base_inited = true;
/* check the provided default binding policy for correctness - specifically want to ensure
* there are no disallowed qualifiers and setup the global param */
if (PRTE_SUCCESS
!= (rc = prte_hwloc_base_set_binding_policy(NULL, prte_hwloc_base_binding_policy))) {
return rc;
}
return PRTE_SUCCESS;
}
void prte_hwloc_base_close(void)
{
if (!prte_hwloc_base_inited) {
return;
}
/* free memory */
if (NULL != prte_hwloc_my_cpuset) {
hwloc_bitmap_free(prte_hwloc_my_cpuset);
prte_hwloc_my_cpuset = NULL;
}
if (NULL != prte_hwloc_default_cpu_list) {
free(prte_hwloc_default_cpu_list);
}
/* destroy the topology */
if (NULL != prte_hwloc_topology) {
prte_hwloc_base_free_topology(prte_hwloc_topology);
prte_hwloc_topology = NULL;
}
/* All done */
prte_hwloc_base_inited = false;
}
int prte_hwloc_base_set_default_binding(void *jd, void *opt)
{
prte_job_t *jdata = (prte_job_t*)jd;
prte_schizo_options_t *options = (prte_schizo_options_t*)opt;
prte_mapping_policy_t mpol;
if (prte_get_attribute(&jdata->attributes, PRTE_JOB_PES_PER_PROC, NULL, PMIX_UINT16)) {
/* bind to cpus */
if (options->use_hwthreads) {
/* if we are using hwthread cpus, then bind to those */
prte_output_verbose(options->verbosity, options->stream,
"setdefaultbinding[%d] binding not given - using byhwthread",
__LINE__);
PRTE_SET_DEFAULT_BINDING_POLICY(jdata->map->binding, PRTE_BIND_TO_HWTHREAD);
} else {
/* bind to core */
prte_output_verbose(options->verbosity, options->stream,
"setdefaultbinding[%d] binding not given - using bycore", __LINE__);
PRTE_SET_DEFAULT_BINDING_POLICY(jdata->map->binding, PRTE_BIND_TO_CORE);
}
} else {
/* if the user explicitly mapped-by some object, then we default
* to binding to that object */
mpol = PRTE_GET_MAPPING_POLICY(jdata->map->mapping);
if (PRTE_MAPPING_GIVEN & PRTE_GET_MAPPING_DIRECTIVE(jdata->map->mapping)) {
if (PRTE_MAPPING_BYHWTHREAD == mpol) {
prte_output_verbose(options->verbosity, options->stream,
"setdefaultbinding[%d] binding not given - using byhwthread", __LINE__);
PRTE_SET_DEFAULT_BINDING_POLICY(jdata->map->binding, PRTE_BIND_TO_HWTHREAD);
} else if (PRTE_MAPPING_BYCORE == mpol) {
prte_output_verbose(options->verbosity, options->stream,
"setdefaultbinding[%d] binding not given - using bycore", __LINE__);
PRTE_SET_DEFAULT_BINDING_POLICY(jdata->map->binding, PRTE_BIND_TO_CORE);
} else if (PRTE_MAPPING_BYL1CACHE == mpol) {
prte_output_verbose(options->verbosity, options->stream,
"setdefaultbinding[%d] binding not given - using byL1", __LINE__);
PRTE_SET_DEFAULT_BINDING_POLICY(jdata->map->binding, PRTE_BIND_TO_L1CACHE);
} else if (PRTE_MAPPING_BYL2CACHE == mpol) {
prte_output_verbose(options->verbosity, options->stream,
"setdefaultbinding[%d] binding not given - using byL2", __LINE__);
PRTE_SET_DEFAULT_BINDING_POLICY(jdata->map->binding, PRTE_BIND_TO_L2CACHE);
} else if (PRTE_MAPPING_BYL3CACHE == mpol) {
prte_output_verbose(options->verbosity, options->stream,
"setdefaultbinding[%d] binding not given - using byL3", __LINE__);
PRTE_SET_DEFAULT_BINDING_POLICY(jdata->map->binding, PRTE_BIND_TO_L3CACHE);
} else if (PRTE_MAPPING_BYNUMA == mpol) {
prte_output_verbose(options->verbosity, options->stream,
"setdefaultbinding[%d] binding not given - using bynuma",
__LINE__);
PRTE_SET_DEFAULT_BINDING_POLICY(jdata->map->binding, PRTE_BIND_TO_NUMA);
} else if (PRTE_MAPPING_BYPACKAGE == mpol) {
prte_output_verbose(options->verbosity, options->stream,
"setdefaultbinding[%d] binding not given - using bypackage", __LINE__);
PRTE_SET_DEFAULT_BINDING_POLICY(jdata->map->binding, PRTE_BIND_TO_PACKAGE);
} else {
/* we are mapping by node or some other non-object method */
if (options->nprocs <= 2) {
if (options->use_hwthreads) {
/* if we are using hwthread cpus, then bind to those */
prte_output_verbose(options->verbosity, options->stream,
"setdefaultbinding[%d] binding not given - using byhwthread", __LINE__);
PRTE_SET_DEFAULT_BINDING_POLICY(jdata->map->binding,
PRTE_BIND_TO_HWTHREAD);
} else {
/* for performance, bind to core */
prte_output_verbose(options->verbosity, options->stream,
"setdefaultbinding[%d] binding not given - using bycore", __LINE__);
PRTE_SET_DEFAULT_BINDING_POLICY(jdata->map->binding,
PRTE_BIND_TO_CORE);
}
} else {
/* bind to numa (if present), or by package (if numa isn't present and package is) */
if (NULL != hwloc_get_obj_by_type(prte_hwloc_topology, HWLOC_OBJ_NUMANODE, 0)) {
prte_output_verbose(options->verbosity, options->stream,
"setdefaultbinding[%d] binding not given - using bynuma", __LINE__);
PRTE_SET_DEFAULT_BINDING_POLICY(jdata->map->binding, PRTE_BIND_TO_NUMA);
} else if (NULL != hwloc_get_obj_by_type(prte_hwloc_topology, HWLOC_OBJ_PACKAGE, 0)) {
prte_output_verbose(options->verbosity, options->stream,
"setdefaultbinding[%d] binding not given - using bypackage", __LINE__);
PRTE_SET_DEFAULT_BINDING_POLICY(jdata->map->binding, PRTE_BIND_TO_PACKAGE);
} else {
/* if we have neither, then just don't bind */
prte_output_verbose(options->verbosity, options->stream,
"setdefaultbinding[%d] binding not given and no NUMA "
"or packages - not binding",
__LINE__);
PRTE_SET_BINDING_POLICY(jdata->map->binding, PRTE_BIND_TO_NONE);
}
}
}
} else if (options->nprocs <= 2) {
if (options->use_hwthreads) {
/* if we are using hwthread cpus, then bind to those */
prte_output_verbose(options->verbosity, options->stream,
"setdefaultbinding[%d] binding not given - using byhwthread",
__LINE__);
PRTE_SET_DEFAULT_BINDING_POLICY(jdata->map->binding, PRTE_BIND_TO_HWTHREAD);
} else {
/* for performance, bind to core */
prte_output_verbose(options->verbosity, options->stream,
"setdefaultbinding[%d] binding not given - using bycore",
__LINE__);
PRTE_SET_DEFAULT_BINDING_POLICY(jdata->map->binding, PRTE_BIND_TO_CORE);
}
} else {
/* for performance, bind to numa, if available, else try package */
if (NULL != hwloc_get_obj_by_type(prte_hwloc_topology, HWLOC_OBJ_NUMANODE, 0)) {
prte_output_verbose(options->verbosity, options->stream,
"setdefaultbinding[%d] binding not given - using bynuma",
__LINE__);
PRTE_SET_DEFAULT_BINDING_POLICY(jdata->map->binding, PRTE_BIND_TO_NUMA);
} else if (NULL != hwloc_get_obj_by_type(prte_hwloc_topology, HWLOC_OBJ_PACKAGE, 0)) {
prte_output_verbose(options->verbosity, options->stream,
"setdefaultbinding[%d] binding not given - using bypackage",
__LINE__);
PRTE_SET_DEFAULT_BINDING_POLICY(jdata->map->binding, PRTE_BIND_TO_PACKAGE);
} else {
/* just don't bind */
prte_output_verbose(options->verbosity, options->stream,
"setdefaultbinding[%d] binding not given and no packages - not binding",
__LINE__);
PRTE_SET_BINDING_POLICY(jdata->map->binding, PRTE_BIND_TO_NONE);
}
}
}
/* they might have set the overload-allowed flag while wanting PRRTE
* to set the default binding - don't override it */
if (!PRTE_BIND_OVERLOAD_SET(jdata->map->binding)) {
if (PRTE_BIND_OVERLOAD_ALLOWED(prte_hwloc_default_binding_policy)) {
jdata->map->binding |= PRTE_BIND_ALLOW_OVERLOAD;
}
}
return PRTE_SUCCESS;
}
static bool fns_init = false;
static pmix_tsd_key_t print_tsd_key;
char *prte_hwloc_print_null = "NULL";
static void buffer_cleanup(void *value)
{
int i;
prte_hwloc_print_buffers_t *ptr;
if (NULL != value) {
ptr = (prte_hwloc_print_buffers_t *) value;
for (i = 0; i < PRTE_HWLOC_PRINT_NUM_BUFS; i++) {
free(ptr->buffers[i]);
}
free(ptr);
}
}
prte_hwloc_print_buffers_t *prte_hwloc_get_print_buffer(void)
{
prte_hwloc_print_buffers_t *ptr;
int ret, i;
if (!fns_init) {
/* setup the print_args function */
if (PRTE_SUCCESS != (ret = pmix_tsd_key_create(&print_tsd_key, buffer_cleanup))) {
return NULL;
}
fns_init = true;
}
ret = pmix_tsd_getspecific(print_tsd_key, (void **) &ptr);
if (PRTE_SUCCESS != ret)
return NULL;
if (NULL == ptr) {
ptr = (prte_hwloc_print_buffers_t *) malloc(sizeof(prte_hwloc_print_buffers_t));
for (i = 0; i < PRTE_HWLOC_PRINT_NUM_BUFS; i++) {
ptr->buffers[i] = (char *) malloc((PRTE_HWLOC_PRINT_MAX_SIZE + 1) * sizeof(char));
}
ptr->cntr = 0;
ret = pmix_tsd_setspecific(print_tsd_key, (void *) ptr);
}
return (prte_hwloc_print_buffers_t *) ptr;
}
char *prte_hwloc_base_print_locality(prte_hwloc_locality_t locality)
{
prte_hwloc_print_buffers_t *ptr;
int idx;
ptr = prte_hwloc_get_print_buffer();
if (NULL == ptr) {
return prte_hwloc_print_null;
}
/* cycle around the ring */
if (PRTE_HWLOC_PRINT_NUM_BUFS == ptr->cntr) {
ptr->cntr = 0;
}
idx = 0;
if (PRTE_PROC_ON_LOCAL_CLUSTER(locality)) {
ptr->buffers[ptr->cntr][idx++] = 'C';
ptr->buffers[ptr->cntr][idx++] = 'L';
ptr->buffers[ptr->cntr][idx++] = ':';
}
if (PRTE_PROC_ON_LOCAL_CU(locality)) {
ptr->buffers[ptr->cntr][idx++] = 'C';
ptr->buffers[ptr->cntr][idx++] = 'U';
ptr->buffers[ptr->cntr][idx++] = ':';
}
if (PRTE_PROC_ON_LOCAL_NODE(locality)) {
ptr->buffers[ptr->cntr][idx++] = 'N';
ptr->buffers[ptr->cntr][idx++] = ':';
}
if (PRTE_PROC_ON_LOCAL_PACKAGE(locality)) {
ptr->buffers[ptr->cntr][idx++] = 'S';
ptr->buffers[ptr->cntr][idx++] = ':';
}
if (PRTE_PROC_ON_LOCAL_NUMA(locality)) {
ptr->buffers[ptr->cntr][idx++] = 'N';
ptr->buffers[ptr->cntr][idx++] = 'M';
ptr->buffers[ptr->cntr][idx++] = ':';
}
if (PRTE_PROC_ON_LOCAL_L3CACHE(locality)) {
ptr->buffers[ptr->cntr][idx++] = 'L';
ptr->buffers[ptr->cntr][idx++] = '3';
ptr->buffers[ptr->cntr][idx++] = ':';
}
if (PRTE_PROC_ON_LOCAL_L2CACHE(locality)) {
ptr->buffers[ptr->cntr][idx++] = 'L';
ptr->buffers[ptr->cntr][idx++] = '2';
ptr->buffers[ptr->cntr][idx++] = ':';
}
if (PRTE_PROC_ON_LOCAL_L1CACHE(locality)) {
ptr->buffers[ptr->cntr][idx++] = 'L';
ptr->buffers[ptr->cntr][idx++] = '1';
ptr->buffers[ptr->cntr][idx++] = ':';
}
if (PRTE_PROC_ON_LOCAL_CORE(locality)) {
ptr->buffers[ptr->cntr][idx++] = 'C';
ptr->buffers[ptr->cntr][idx++] = ':';
}
if (PRTE_PROC_ON_LOCAL_HWTHREAD(locality)) {
ptr->buffers[ptr->cntr][idx++] = 'H';
ptr->buffers[ptr->cntr][idx++] = 'w';
ptr->buffers[ptr->cntr][idx++] = 't';
ptr->buffers[ptr->cntr][idx++] = ':';
}
if (0 < idx) {
ptr->buffers[ptr->cntr][idx - 1] = '\0';
} else if (PRTE_PROC_NON_LOCAL & locality) {
ptr->buffers[ptr->cntr][idx++] = 'N';
ptr->buffers[ptr->cntr][idx++] = 'O';
ptr->buffers[ptr->cntr][idx++] = 'N';
ptr->buffers[ptr->cntr][idx++] = '\0';
} else {
/* must be an unknown locality */
ptr->buffers[ptr->cntr][idx++] = 'U';
ptr->buffers[ptr->cntr][idx++] = 'N';
ptr->buffers[ptr->cntr][idx++] = 'K';
ptr->buffers[ptr->cntr][idx++] = '\0';
}
return ptr->buffers[ptr->cntr];
}
static void obj_data_const(prte_hwloc_obj_data_t *ptr)
{
ptr->npus_calculated = false;
ptr->npus = 0;
ptr->idx = UINT_MAX;
ptr->num_bound = 0;
}
PMIX_CLASS_INSTANCE(prte_hwloc_obj_data_t, pmix_object_t, obj_data_const, NULL);
static void sum_const(prte_hwloc_summary_t *ptr)
{
ptr->num_objs = 0;
PMIX_CONSTRUCT(&ptr->sorted_by_dist_list, pmix_list_t);
}
static void sum_dest(prte_hwloc_summary_t *ptr)
{
pmix_list_item_t *item;
while (NULL != (item = pmix_list_remove_first(&ptr->sorted_by_dist_list))) {
PMIX_RELEASE(item);
}
PMIX_DESTRUCT(&ptr->sorted_by_dist_list);
}
PMIX_CLASS_INSTANCE(prte_hwloc_summary_t, pmix_list_item_t, sum_const, sum_dest);
static void topo_data_const(prte_hwloc_topo_data_t *ptr)
{
ptr->available = NULL;
PMIX_CONSTRUCT(&ptr->summaries, pmix_list_t);
ptr->numas = NULL;
ptr->num_numas = 0;
}
static void topo_data_dest(prte_hwloc_topo_data_t *ptr)
{
pmix_list_item_t *item;
if (NULL != ptr->available) {
hwloc_bitmap_free(ptr->available);
}
while (NULL != (item = pmix_list_remove_first(&ptr->summaries))) {
PMIX_RELEASE(item);
}
PMIX_DESTRUCT(&ptr->summaries);
if (NULL != ptr->numas) {
free(ptr->numas);
}
}
PMIX_CLASS_INSTANCE(prte_hwloc_topo_data_t, pmix_object_t, topo_data_const, topo_data_dest);
PMIX_CLASS_INSTANCE(prte_rmaps_numa_node_t, pmix_list_item_t, NULL, NULL);
int prte_hwloc_base_set_binding_policy(void *jdat, char *spec)
{
int i;
prte_binding_policy_t tmp;
char **quals, *myspec, *ptr;
prte_job_t *jdata = (prte_job_t *) jdat;
size_t len;
/* set default */
tmp = 0;
/* binding specification */
if (NULL == spec) {
return PRTE_SUCCESS;
}
myspec = strdup(spec); // protect the input
/* check for qualifiers */
ptr = strchr(myspec, ':');
if (NULL != ptr) {
*ptr = '\0';
++ptr;
quals = pmix_argv_split(ptr, ':');
for (i = 0; NULL != quals[i]; i++) {
if (0 == strcasecmp(quals[i], "if-supported")) {
tmp |= PRTE_BIND_IF_SUPPORTED;
} else if (0 == strcasecmp(quals[i], "overload-allowed")) {
tmp |= (PRTE_BIND_ALLOW_OVERLOAD | PRTE_BIND_OVERLOAD_GIVEN);
} else if (0 == strcasecmp(quals[i], "no-overload")) {
tmp = (tmp & ~PRTE_BIND_ALLOW_OVERLOAD);
tmp |= PRTE_BIND_OVERLOAD_GIVEN;
} else if (0 == strcasecmp(quals[i], "ordered")) {
tmp |= PRTE_BIND_ORDERED;
} else if (0 == strcasecmp(quals[i], "REPORT")) {
if (NULL == jdata) {
prte_show_help("help-prte-rmaps-base.txt", "unsupported-default-modifier", true,
"binding policy", quals[i]);
free(myspec);
return PRTE_ERR_SILENT;
}
prte_set_attribute(&jdata->attributes, PRTE_JOB_REPORT_BINDINGS, PRTE_ATTR_GLOBAL,
NULL, PMIX_BOOL);
} else {
/* unknown option */
prte_show_help("help-prte-hwloc-base.txt", "unrecognized-modifier", true, spec);
pmix_argv_free(quals);
free(myspec);
return PRTE_ERR_BAD_PARAM;
}
}
pmix_argv_free(quals);
}
len = strlen(myspec);
if (0 < len) {
if (0 == strncasecmp(myspec, "none", len)) {
PRTE_SET_BINDING_POLICY(tmp, PRTE_BIND_TO_NONE);
} else if (0 == strncasecmp(myspec, "hwthread", len)) {
PRTE_SET_BINDING_POLICY(tmp, PRTE_BIND_TO_HWTHREAD);
} else if (0 == strncasecmp(myspec, "core", len)) {
PRTE_SET_BINDING_POLICY(tmp, PRTE_BIND_TO_CORE);
} else if (0 == strncasecmp(myspec, "l1cache", len)) {
PRTE_SET_BINDING_POLICY(tmp, PRTE_BIND_TO_L1CACHE);
} else if (0 == strncasecmp(myspec, "l2cache", len)) {
PRTE_SET_BINDING_POLICY(tmp, PRTE_BIND_TO_L2CACHE);
} else if (0 == strncasecmp(myspec, "l3cache", len)) {
PRTE_SET_BINDING_POLICY(tmp, PRTE_BIND_TO_L3CACHE);
} else if (0 == strncasecmp(myspec, "numa", len)) {
PRTE_SET_BINDING_POLICY(tmp, PRTE_BIND_TO_NUMA);
} else if (0 == strncasecmp(myspec, "package", len)) {
PRTE_SET_BINDING_POLICY(tmp, PRTE_BIND_TO_PACKAGE);
} else {
prte_show_help("help-prte-hwloc-base.txt", "invalid binding_policy", true, "binding",
spec);
free(myspec);
return PRTE_ERR_BAD_PARAM;
}
}
free(myspec);
if (NULL == jdata) {
prte_hwloc_default_binding_policy = tmp;
} else {
if (NULL == jdata->map) {
PRTE_ERROR_LOG(PRTE_ERR_BAD_PARAM);
return PRTE_ERR_BAD_PARAM;
}
jdata->map->binding = tmp;
}
return PRTE_SUCCESS;
}
| 46.105634 | 125 | 0.581396 | [
"object"
] |
6495222cac59ea0cf90b447a3724a58bf4983f76 | 4,179 | h | C | Source/igtlMessageFactory.h | kamilcolo/OpenIGTLink | 39d1f6573c30660edc52d6f90e9f2149866209ab | [
"BSD-3-Clause"
] | null | null | null | Source/igtlMessageFactory.h | kamilcolo/OpenIGTLink | 39d1f6573c30660edc52d6f90e9f2149866209ab | [
"BSD-3-Clause"
] | null | null | null | Source/igtlMessageFactory.h | kamilcolo/OpenIGTLink | 39d1f6573c30660edc52d6f90e9f2149866209ab | [
"BSD-3-Clause"
] | 1 | 2021-07-04T18:12:14.000Z | 2021-07-04T18:12:14.000Z | /*=========================================================================
Program: The OpenIGTLink Library
Language: C++
Web page: http://openigtlink.org/
Copyright (c) Insight Software Consortium. All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#ifndef __igtlMessageFactory_h
#define __igtlMessageFactory_h
#include "igtlMacro.h"
#include "igtlMessageBase.h"
#include "igtlMessageHeader.h"
#include "igtlObject.h"
#include "igtl_header.h"
#include <map>
namespace igtl
{
class IGTLCommon_EXPORT MessageFactory: public Object
{
public:
typedef MessageFactory Self;
typedef Object Superclass;
typedef SmartPointer<Self> Pointer;
typedef SmartPointer<const Self> ConstPointer;
igtlTypeMacro(MessageFactory, Object)
igtlNewMacro(MessageFactory);
/*! Function pointer for storing New() static methods of igtl::MessageBase classes */
typedef igtl::MessageBase::Pointer (*PointerToMessageBaseNew)();
/// Add message type name and pointer to IGTL message new function
/// Usage: AddMessageType( "IMAGE", (PointerToMessageBaseNew)&igtl::ImageMessage::New );
/// \param messageTypeName The name of the message type
/// \param messageTypeNewPointer Function pointer to the message type new function (e.g. (PointerToMessageBaseNew)&igtl::ImageMessage::New )
virtual void AddMessageType(const std::string& messageTypeName, MessageFactory::PointerToMessageBaseNew messageTypeNewPointer);
/// Get pointer to message type new function, or NULL if the message type not registered
/// Usage: igtl::MessageBase::Pointer message = GetMessageTypeNewPointer("IMAGE")();
/// Returns NULL if message type is not found
virtual MessageFactory::PointerToMessageBaseNew GetMessageTypeNewPointer(const std::string& messageTypeName) const;
/// Checks that headerMsg is not null and the headerMsg->GetDeviceType() refers to a valid type, returning true if valid, and false otherwise.
bool IsValid(igtl::MessageHeader::Pointer headerMsg);
/// Checks that headerMsg is not null and the headerMsg->GetDeviceType() refers to a valid type, returning true if valid, and false otherwise.
bool IsValid(igtl::MessageHeader::Pointer headerMsg) const;
/// LEGACY method, use CreateReceiveMessage instead
/// Constructs a message from the given header.
/// Returns NULL if headerMsg is NULL.
/// Returns NULL if this->IsValid(headerMsg) returns false.
/// Creates message, sets header onto message and calls AllocateBuffer() on the message.
igtl::MessageBase::Pointer GetMessage(igtl::MessageHeader::Pointer headerMsg);
/// Constructs a message header.
/// Returns NULL if headerMsg is NULL.
/// Returns NULL if this->IsValid(headerMsg) returns false.
/// Creates message, calls InitBuffer()
igtl::MessageHeader::Pointer CreateHeaderMessage(int headerVersion) const;
/// Constructs a message from the given populated header.
/// Returns NULL if headerMsg is NULL.
/// Returns NULL if this->IsValid(headerMsg) returns false.
/// Creates message, sets header onto message and calls AllocatePack() on the message.
igtl::MessageBase::Pointer CreateReceiveMessage(igtl::MessageHeader::Pointer headerMsg) const;
/// Constructs an empty message from the given message type.
/// Returns NULL if messageType is empty.
/// Creates message, sets header onto message and calls AllocatePack() on the message.
igtl::MessageBase::Pointer CreateSendMessage(const std::string& messageType, int headerVersion) const;
/// Return the list of known message types
void GetAvailableMessageTypes(std::vector<std::string>& types) const;
protected:
MessageFactory();
~MessageFactory();
private:
/*! Map igt message types and the New() static methods of igtl::MessageBase classes */
std::map<std::string, PointerToMessageBaseNew> IgtlMessageTypes;
}; // end class
} // end namespace
#endif // __igtlMessageFactory_h
| 41.79 | 144 | 0.727925 | [
"object",
"vector"
] |
649b812a118bab7de5da9e5682950859a09730c3 | 720 | h | C | verify.h | astro/node-crypto | d9c1f046a1402c8c5e7d1de90fb1977798fb1ecc | [
"MIT"
] | 1 | 2015-11-05T18:57:22.000Z | 2015-11-05T18:57:22.000Z | verify.h | astro/node-crypto | d9c1f046a1402c8c5e7d1de90fb1977798fb1ecc | [
"MIT"
] | null | null | null | verify.h | astro/node-crypto | d9c1f046a1402c8c5e7d1de90fb1977798fb1ecc | [
"MIT"
] | null | null | null | #include <node.h>
#include <openssl/evp.h>
using namespace v8;
using namespace node;
class Verify : public ObjectWrap {
public:
static void
Initialize (v8::Handle<v8::Object> target);
bool VerifyInit (const char* verifyType);
int VerifyUpdate(char* data, int len);
int VerifyFinal(char* keyPem, int keyPemLen, unsigned char* sig, int siglen);
protected:
static Handle<Value>
New (const Arguments& args);
static Handle<Value>
VerifyInit(const Arguments& args);
static Handle<Value>
VerifyUpdate(const Arguments& args);
static Handle<Value>
VerifyFinal(const Arguments& args);
Verify ();
~Verify ();
private:
EVP_MD_CTX mdctx;
const EVP_MD *md;
bool initialised;
};
| 20.571429 | 79 | 0.705556 | [
"object"
] |
649d9df113ac292f0c76c37eb42cab33016d0e52 | 657 | h | C | Engine/Plugins/UnrealCS/Source/MonoPlugin/Private/MonoCallbackScheduler.h | RobertAcksel/UnrealCS | 16d6f4989ef2f8622363009ebc6509b67c35a57e | [
"MIT"
] | 1 | 2017-11-21T01:25:19.000Z | 2017-11-21T01:25:19.000Z | Engine/Plugins/UnrealCS/Source/MonoPlugin/Private/MonoCallbackScheduler.h | RobertAcksel/UnrealCS | 16d6f4989ef2f8622363009ebc6509b67c35a57e | [
"MIT"
] | null | null | null | Engine/Plugins/UnrealCS/Source/MonoPlugin/Private/MonoCallbackScheduler.h | RobertAcksel/UnrealCS | 16d6f4989ef2f8622363009ebc6509b67c35a57e | [
"MIT"
] | null | null | null | #pragma once
#include <mono/metadata/object.h>
#include "Array.h"
struct MonoCallbackScheduler {
public:
bool AddTickableObject(MonoObject * obj);
bool RemoveTickableObject(MonoObject * obj);
void Tick(float DeltaTime);
void HotReload();
private:
//C# Object Tickable Support
struct TickObject
{
//C# Object Pointer
MonoObject* Obj;
//C# Object Handle
uint32 gc_handle;
//C# Object Tick Method
MonoMethod* TickMethod;
//If Marked As Removed
bool removed;
};
//Tick Object Array
TArray<struct TickObject> TickObjects;
};
| 21.9 | 49 | 0.61035 | [
"object"
] |
649f9c3b80903251f9f1c0c44171c7f1398bea70 | 3,667 | h | C | Gems/Atom/RHI/Vulkan/Code/Source/RHI/MergedShaderResourceGroup.h | cypherdotXd/o3de | bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676 | [
"Apache-2.0",
"MIT"
] | 11 | 2021-07-08T09:58:26.000Z | 2022-03-17T17:59:26.000Z | Gems/Atom/RHI/Vulkan/Code/Source/RHI/MergedShaderResourceGroup.h | RoddieKieley/o3de | e804fd2a4241b039a42d9fa54eaae17dc94a7a92 | [
"Apache-2.0",
"MIT"
] | 29 | 2021-07-06T19:33:52.000Z | 2022-03-22T10:27:49.000Z | Gems/Atom/RHI/Vulkan/Code/Source/RHI/MergedShaderResourceGroup.h | RoddieKieley/o3de | e804fd2a4241b039a42d9fa54eaae17dc94a7a92 | [
"Apache-2.0",
"MIT"
] | 4 | 2021-07-06T19:24:43.000Z | 2022-03-31T12:42:27.000Z | /*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#pragma once
#include <RHI/ShaderResourceGroup.h>
#include <AzCore/std/parallel/shared_mutex.h>
namespace AZ
{
namespace Vulkan
{
class MergedShaderResourceGroupPool;
//! Represents a group of ShaderResourceGroups that were merged together due to device limitations.
//! At submit time (the moment that we know all SRGs being used), a MergedShaderResourceGroup is created
//! and the compiled data from the ShaderResourceGroups is copied (compiled) to the MergedShaderResourceGroup.
//! This process is automatic and it happens transparent to the user. MergedShaderResourceGroup are cached in
//! the MergedShaderResourceGroupPool so they can be reused as much as possible.
class MergedShaderResourceGroup final
: public ShaderResourceGroup
{
using Base = ShaderResourceGroup;
friend class MergedShaderResourceGroupPool;
public:
AZ_CLASS_ALLOCATOR(MergedShaderResourceGroup, AZ::SystemAllocator, 0);
AZ_RTTI(MergedShaderResourceGroup, "{5A98B01F-E5AC-4648-B307-08371FD8AA56}", Base);
~MergedShaderResourceGroup() = default;
//! Returns if the MergedShaderResourceGroup needs to be compiled (copy compile data from original SRGs) before it can be used.
bool NeedsCompile() const;
//! Compile the MergedShaderResourceGroup synchronously using the compiled data of the ShaderResourceGroups instances.
void Compile();
//! Generates the name of a merged Shader Input.
static AZ::Name GenerateMergedShaderInputName(const AZ::Name& shaderInputName, uint32_t bindinSlot);
using ShaderResourceGroupArray = AZStd::array<const ShaderResourceGroup*, RHI::Limits::Pipeline::ShaderResourceGroupCountMax>;
//! Suffix name used for a constant buffer that will contain the constant data of a merged SRG.
static const char* ConstantDataBufferName;
private:
MergedShaderResourceGroup() = default;
// Helper struct for easy initialization of the frame iteration.
struct FrameIteration
{
uint64_t m_frameIteration = std::numeric_limits<uint64_t>::max();
};
// Utility function that merges multiple ShaderResoruceGroup data into one.
RHI::ShaderResourceGroupData MergeShaderResourceData(const ShaderResourceGroupArray& srgList) const;
// List of the ShaderResourceGroup instances that are being merged.
ShaderResourceGroupArray m_mergedShaderResourceGroupList = {};
// Keeps track of the frame iteration for each ShaderResourceGroup when the last compile happens. This is used
// to calculate if we need to compile again.
AZStd::array<FrameIteration, RHI::Limits::Pipeline::ShaderResourceGroupCountMax> m_lastCompileFrameIteration;
mutable AZStd::shared_mutex m_compileMutex;
};
}
}
namespace AZStd
{
template<>
struct hash<AZ::Vulkan::MergedShaderResourceGroup::ShaderResourceGroupArray>
{
using argument_type = AZ::Vulkan::MergedShaderResourceGroup::ShaderResourceGroupArray;
using result_type = AZStd::size_t;
inline result_type operator()(const argument_type& value) const { return AZStd::hash_range(value.begin(), value.end()); }
};
} // namespace AZStd
| 44.719512 | 139 | 0.6973 | [
"3d"
] |
64a26ebf36b67f91cf3336145c5a5bd003f20147 | 2,994 | h | C | src/software/backend/output/radio/mrf/usb/device.h | scveloso/Software | ac882d3df0aa0d108e5157c076c82c030d023e12 | [
"MIT"
] | null | null | null | src/software/backend/output/radio/mrf/usb/device.h | scveloso/Software | ac882d3df0aa0d108e5157c076c82c030d023e12 | [
"MIT"
] | null | null | null | src/software/backend/output/radio/mrf/usb/device.h | scveloso/Software | ac882d3df0aa0d108e5157c076c82c030d023e12 | [
"MIT"
] | null | null | null | #pragma once
#include <libusb/libusb.h>
#include <cstddef>
#include <cstdint>
#include <string>
#include "software/backend/output/radio/mrf/usb/devicehandle.h"
#include "software/backend/output/radio/mrf/util/noncopyable.h"
namespace USB
{
/* Forward declaration of the libusb context */
class Context;
class DeviceHandle;
/**
* A collection of information about a USB device.
*/
class Device final
{
public:
/**
* Makes a copy of a device record.
*
* @param[in] copyref the object to copy
*/
Device(const Device ©ref);
/**
* Destroys the device information record.
*/
~Device();
/**
* Assigns a device information record.
*
* @param[in] assgref the object to copy from
*
* @return this object
*/
Device &operator=(const Device &assgref);
/**
* Returns the 16-bit vendor ID from the device’s device descriptor.
*
* @return the vendor ID
*/
unsigned int vendor_id() const
{
return device_descriptor.idVendor;
}
/**
* Returns the 16-bit product ID from the device’s device descriptor.
*
* @return the product ID
*/
unsigned int product_id() const
{
return device_descriptor.idProduct;
}
/**
* Returns the serial number from the device’s device and string
* descriptors.
*
* @return the serial number, or an empty string if the device does not
* expose a serial number
*/
std::string serial_number() const;
private:
friend class DeviceList;
friend class DeviceHandle;
libusb_context *context;
libusb_device *device;
libusb_device_descriptor device_descriptor;
explicit Device(libusb_device *device);
};
/**
* A list of USB devices.
*/
class DeviceList final : public NonCopyable
{
public:
/**
* Constructs a list of all USB devices attached to the system.
*
* @param[in] context the library context in which to operate
*/
explicit DeviceList(Context &context);
/**
* Frees the list of devices.
*/
~DeviceList();
/**
* Returns the size of the list.
*
* @return the number of devices in the list
*/
std::size_t size() const
{
return size_;
}
/**
* Returns a device from the list.
*
* @param[in] i the index of the device to return, counting from zero
*
* @return the device
*/
Device operator[](const std::size_t i) const;
private:
std::size_t size_;
libusb_device **devices;
};
} // namespace USB
| 23.574803 | 79 | 0.537074 | [
"object"
] |
64a70b9d6a9fe844d34cd21792d1433179050986 | 7,955 | h | C | hphp/runtime/vm/jit/fixup.h | jazzdan/hhvm | f968e49bb25a9ac0b2fb728ae3b185ce3079e69a | [
"PHP-3.01",
"Zend-2.0"
] | null | null | null | hphp/runtime/vm/jit/fixup.h | jazzdan/hhvm | f968e49bb25a9ac0b2fb728ae3b185ce3079e69a | [
"PHP-3.01",
"Zend-2.0"
] | null | null | null | hphp/runtime/vm/jit/fixup.h | jazzdan/hhvm | f968e49bb25a9ac0b2fb728ae3b185ce3079e69a | [
"PHP-3.01",
"Zend-2.0"
] | null | null | null | /*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-2014 Facebook, Inc. (http://www.facebook.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#ifndef incl_HPHP_FIXUP_H_
#define incl_HPHP_FIXUP_H_
#include <vector>
#include "hphp/runtime/vm/jit/types.h"
#include "hphp/runtime/base/execution-context.h"
#include "hphp/runtime/vm/tread-hash-map.h"
#include "hphp/util/atomic.h"
#include "hphp/util/data-block.h"
namespace HPHP {
struct ExecutionContext;
}
namespace HPHP { namespace jit {
//////////////////////////////////////////////////////////////////////
/*
* The Fixup map allows us to reconstruct the state of the VM registers (fp,
* sp, and pc) from an up-stack invocation record. Each range of bytes in the
* translation cache is associated with a "distance" in both stack cells and
* opcode bytes from the beginning of the function. These are known at
* translation time.
*
* The way this works is by chasing the native rbp chain to find a rbp that we
* know is a VM frame (i.e. is actually a full ActRec). Once we find that,
* regsFromActRec is called, which looks to see if the return ip for the frame
* before the VM frame has an entry in the fixup map (i.e. if it points into
* the translation cache)---if so, it finds the fixup information in one of two
* ways:
*
* - Fixup: the normal case.
*
* The Fixup record just stores an offset relative to the ActRec* for vmsp,
* and an offset from the start of the func for pc. In the case of
* resumable frames the sp offset is relative to Stack::resumableStackBase.
*
* - IndirectFixup: this is used for some shared stubs in the TC.
*
* In this case, some JIT'd code associated with the ActRec* we found made
* a call to a shared stub, and then that stub called C++. The
* IndirectFixup record stores an offset to the saved frame pointer *two*
* levels deeper in C++, that says where the return IP for the call to the
* shared stub can be found. I.e., we're trying to chase back two return
* ips into the TC.
*
* Note that this means IndirectFixups will not work for C++ code paths
* that need to do a fixup without making at least one other C++ call, but
* for the current use case this is fine.
*
* Here's a picture of the native stack in the indirect fixup situation:
*
* |..............................|
* |..............................|
* +------------------------------+ __enterTCHelper
* | RetIP to enterTC() |
* |-- --|
* | savedRbp |
* |-- --|
* | <other junk> |
* +------------------------------+ TC code
* | RetIP to enterTCHelper |
* |-- --|
* | saved %rdi | <from callUnaryStub>
* +------------------------------+ STUB (e.g. decRefGeneric)
* | RetIP to caller of dtor stub |
* |-- --|
* | <pushes in dtor stub> |
* +------------------------------+ <call to C++>
* | RetIP to the dtor stub |
* |-- --|
* | saved rVmFp | push %rbp; mov %rsp, %rbp
* +-->|-- --|
* | | < C++ local variables> |
* | +------------------------------+
* | | RetIP to first C++ callee | C++ calls another function
* | |-- --|
* +---| saved native %rbp (*) | points as shown, from mov above
* |-- --|
* |..............................|
* |..............................|
*
* The offset in IndirectFixup is how to get to the "RetIP to caller of
* dtor stub", relative to the value in the starred stack slot shown. We
* then look that IP up in the fixup map again to find a normal
* (non-indirect) Fixup record.
*
*/
//////////////////////////////////////////////////////////////////////
struct Fixup {
Fixup(int32_t pcOff, int32_t spOff) : pcOffset{pcOff}, spOffset{spOff} {
assertx(pcOffset >= 0);
assertx(spOffset >= 0);
}
Fixup() {}
bool isValid() const { return pcOffset >= 0 && spOffset >= 0; }
int32_t pcOffset{-1};
int32_t spOffset{-1};
};
struct IndirectFixup {
explicit IndirectFixup(int retIpDisp) : returnIpDisp{retIpDisp} {}
/* FixupEntry uses magic to differentiate between IndirectFixup and Fixup. */
int32_t magic{-1};
int32_t returnIpDisp;
};
inline Fixup makeIndirectFixup(int dwordsPushed) {
Fixup fix;
fix.spOffset = (2 + dwordsPushed) * 8;
return fix;
}
struct FixupMap {
static constexpr unsigned kInitCapac = 128;
TRACE_SET_MOD(fixup);
struct VMRegs {
const Op* pc;
TypedValue* sp;
const ActRec* fp;
};
FixupMap() : m_fixups(kInitCapac) {}
void recordFixup(CTCA tca, const Fixup& fixup) {
TRACE(3, "FixupMapImpl::recordFixup: tca %p -> (pcOff %d, spOff %d)\n",
tca, fixup.pcOffset, fixup.spOffset);
if (auto pos = m_fixups.find(tca)) {
*pos = FixupEntry(fixup);
} else {
m_fixups.insert(tca, FixupEntry(fixup));
}
}
const Fixup* findFixup(CTCA tca) const {
auto ent = m_fixups.find(tca);
if (!ent) return nullptr;
return &ent->fixup;
}
bool getFrameRegs(const ActRec* ar, const ActRec* prevAr,
VMRegs* outVMRegs) const;
void fixup(ExecutionContext* ec) const;
void fixupWork(ExecutionContext* ec, ActRec* rbp) const;
void fixupWorkSimulated(ExecutionContext* ec) const;
static bool eagerRecord(const Func* func);
private:
union FixupEntry {
explicit FixupEntry(Fixup f) : fixup(f) {}
/* Depends on the magic field in an IndirectFixup being -1. */
bool isIndirect() const {
static_assert(
offsetof(IndirectFixup, magic) == offsetof(FixupEntry, firstElem),
"Differentiates between Fixup and IndirectFixup by looking at magic."
);
return firstElem < 0;
}
int32_t firstElem;
Fixup fixup;
IndirectFixup indirect;
};
private:
PC pc(const ActRec* ar, const Func* f, const Fixup& fixup) const {
assertx(f);
return f->getEntry() + fixup.pcOffset;
}
void regsFromActRec(CTCA tca, const ActRec* ar, const Fixup& fixup,
VMRegs* outRegs) const {
const Func* f = ar->m_func;
assertx(f);
TRACE(3, "regsFromActRec:: tca %p -> (pcOff %d, spOff %d)\n",
(void*)tca, fixup.pcOffset, fixup.spOffset);
assertx(fixup.spOffset >= 0);
outRegs->pc = reinterpret_cast<const Op*>(pc(ar, f, fixup));
outRegs->fp = ar;
if (UNLIKELY(ar->resumed())) {
TypedValue* stackBase = Stack::resumableStackBase(ar);
outRegs->sp = stackBase - fixup.spOffset;
} else {
outRegs->sp = (TypedValue*)ar - fixup.spOffset;
}
}
private:
TreadHashMap<CTCA,FixupEntry,ctca_identity_hash> m_fixups;
};
//////////////////////////////////////////////////////////////////////
}}
#endif
| 35.044053 | 79 | 0.534507 | [
"vector"
] |
64aa6af9cee3310163443d2490e3910b879a5ece | 65,100 | c | C | sys/cddl/contrib/opensolaris/uts/common/fs/zfs/metaslab.c | dcui/FreeBSD-9.3_kernel | 39d9caaa6ba320e2f8e910b1f5f01efc24ca4a92 | [
"BSD-3-Clause"
] | 3 | 2015-12-15T00:56:39.000Z | 2018-01-11T01:01:38.000Z | sys/cddl/contrib/opensolaris/uts/common/fs/zfs/metaslab.c | dcui/FreeBSD-9.3_kernel | 39d9caaa6ba320e2f8e910b1f5f01efc24ca4a92 | [
"BSD-3-Clause"
] | null | null | null | sys/cddl/contrib/opensolaris/uts/common/fs/zfs/metaslab.c | dcui/FreeBSD-9.3_kernel | 39d9caaa6ba320e2f8e910b1f5f01efc24ca4a92 | [
"BSD-3-Clause"
] | 2 | 2018-01-11T01:01:12.000Z | 2020-11-19T03:07:29.000Z | /*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* or http://www.opensolaris.org/os/licensing.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2011, 2014 by Delphix. All rights reserved.
* Copyright (c) 2013 by Saso Kiselkov. All rights reserved.
*/
#include <sys/zfs_context.h>
#include <sys/dmu.h>
#include <sys/dmu_tx.h>
#include <sys/space_map.h>
#include <sys/metaslab_impl.h>
#include <sys/vdev_impl.h>
#include <sys/zio.h>
#include <sys/spa_impl.h>
SYSCTL_DECL(_vfs_zfs);
SYSCTL_NODE(_vfs_zfs, OID_AUTO, metaslab, CTLFLAG_RW, 0, "ZFS metaslab");
/*
* Allow allocations to switch to gang blocks quickly. We do this to
* avoid having to load lots of space_maps in a given txg. There are,
* however, some cases where we want to avoid "fast" ganging and instead
* we want to do an exhaustive search of all metaslabs on this device.
* Currently we don't allow any gang, slog, or dump device related allocations
* to "fast" gang.
*/
#define CAN_FASTGANG(flags) \
(!((flags) & (METASLAB_GANG_CHILD | METASLAB_GANG_HEADER | \
METASLAB_GANG_AVOID)))
#define METASLAB_WEIGHT_PRIMARY (1ULL << 63)
#define METASLAB_WEIGHT_SECONDARY (1ULL << 62)
#define METASLAB_ACTIVE_MASK \
(METASLAB_WEIGHT_PRIMARY | METASLAB_WEIGHT_SECONDARY)
uint64_t metaslab_aliquot = 512ULL << 10;
uint64_t metaslab_gang_bang = SPA_MAXBLOCKSIZE + 1; /* force gang blocks */
TUNABLE_QUAD("vfs.zfs.metaslab.gang_bang", &metaslab_gang_bang);
SYSCTL_QUAD(_vfs_zfs_metaslab, OID_AUTO, gang_bang, CTLFLAG_RWTUN,
&metaslab_gang_bang, 0,
"Force gang block allocation for blocks larger than or equal to this value");
/*
* The in-core space map representation is more compact than its on-disk form.
* The zfs_condense_pct determines how much more compact the in-core
* space_map representation must be before we compact it on-disk.
* Values should be greater than or equal to 100.
*/
int zfs_condense_pct = 200;
TUNABLE_INT("vfs.zfs.condense_pct", &zfs_condense_pct);
SYSCTL_INT(_vfs_zfs, OID_AUTO, condense_pct, CTLFLAG_RWTUN,
&zfs_condense_pct, 0,
"Condense on-disk spacemap when it is more than this many percents"
" of in-memory counterpart");
/*
* The zfs_mg_noalloc_threshold defines which metaslab groups should
* be eligible for allocation. The value is defined as a percentage of
* a free space. Metaslab groups that have more free space than
* zfs_mg_noalloc_threshold are always eligible for allocations. Once
* a metaslab group's free space is less than or equal to the
* zfs_mg_noalloc_threshold the allocator will avoid allocating to that
* group unless all groups in the pool have reached zfs_mg_noalloc_threshold.
* Once all groups in the pool reach zfs_mg_noalloc_threshold then all
* groups are allowed to accept allocations. Gang blocks are always
* eligible to allocate on any metaslab group. The default value of 0 means
* no metaslab group will be excluded based on this criterion.
*/
int zfs_mg_noalloc_threshold = 0;
TUNABLE_INT("vfs.zfs.mg_noalloc_threshold", &zfs_mg_noalloc_threshold);
SYSCTL_INT(_vfs_zfs, OID_AUTO, mg_noalloc_threshold, CTLFLAG_RWTUN,
&zfs_mg_noalloc_threshold, 0,
"Percentage of metaslab group size that should be free"
" to make it eligible for allocation");
/*
* When set will load all metaslabs when pool is first opened.
*/
int metaslab_debug_load = 0;
TUNABLE_INT("vfs.zfs.metaslab.debug_load", &metaslab_debug_load);
SYSCTL_INT(_vfs_zfs_metaslab, OID_AUTO, debug_load, CTLFLAG_RWTUN,
&metaslab_debug_load, 0,
"Load all metaslabs when pool is first opened");
/*
* When set will prevent metaslabs from being unloaded.
*/
int metaslab_debug_unload = 0;
TUNABLE_INT("vfs.zfs.metaslab.debug_unload", &metaslab_debug_unload);
SYSCTL_INT(_vfs_zfs_metaslab, OID_AUTO, debug_unload, CTLFLAG_RWTUN,
&metaslab_debug_unload, 0,
"Prevent metaslabs from being unloaded");
/*
* Minimum size which forces the dynamic allocator to change
* it's allocation strategy. Once the space map cannot satisfy
* an allocation of this size then it switches to using more
* aggressive strategy (i.e search by size rather than offset).
*/
uint64_t metaslab_df_alloc_threshold = SPA_MAXBLOCKSIZE;
TUNABLE_QUAD("vfs.zfs.metaslab.df_alloc_threshold",
&metaslab_df_alloc_threshold);
SYSCTL_QUAD(_vfs_zfs_metaslab, OID_AUTO, df_alloc_threshold, CTLFLAG_RWTUN,
&metaslab_df_alloc_threshold, 0,
"Minimum size which forces the dynamic allocator to change it's allocation strategy");
/*
* The minimum free space, in percent, which must be available
* in a space map to continue allocations in a first-fit fashion.
* Once the space_map's free space drops below this level we dynamically
* switch to using best-fit allocations.
*/
int metaslab_df_free_pct = 4;
TUNABLE_INT("vfs.zfs.metaslab.df_free_pct", &metaslab_df_free_pct);
SYSCTL_INT(_vfs_zfs_metaslab, OID_AUTO, df_free_pct, CTLFLAG_RWTUN,
&metaslab_df_free_pct, 0,
"The minimum free space, in percent, which must be available in a space map to continue allocations in a first-fit fashion");
/*
* A metaslab is considered "free" if it contains a contiguous
* segment which is greater than metaslab_min_alloc_size.
*/
uint64_t metaslab_min_alloc_size = DMU_MAX_ACCESS;
TUNABLE_QUAD("vfs.zfs.metaslab.min_alloc_size",
&metaslab_min_alloc_size);
SYSCTL_QUAD(_vfs_zfs_metaslab, OID_AUTO, min_alloc_size, CTLFLAG_RWTUN,
&metaslab_min_alloc_size, 0,
"A metaslab is considered \"free\" if it contains a contiguous segment which is greater than vfs.zfs.metaslab.min_alloc_size");
/*
* Percentage of all cpus that can be used by the metaslab taskq.
*/
int metaslab_load_pct = 50;
TUNABLE_INT("vfs.zfs.metaslab.load_pct", &metaslab_load_pct);
SYSCTL_INT(_vfs_zfs_metaslab, OID_AUTO, load_pct, CTLFLAG_RWTUN,
&metaslab_load_pct, 0,
"Percentage of cpus that can be used by the metaslab taskq");
/*
* Determines how many txgs a metaslab may remain loaded without having any
* allocations from it. As long as a metaslab continues to be used we will
* keep it loaded.
*/
int metaslab_unload_delay = TXG_SIZE * 2;
TUNABLE_INT("vfs.zfs.metaslab.unload_delay", &metaslab_unload_delay);
SYSCTL_INT(_vfs_zfs_metaslab, OID_AUTO, unload_delay, CTLFLAG_RWTUN,
&metaslab_unload_delay, 0,
"Number of TXGs that an unused metaslab can be kept in memory");
/*
* Should we be willing to write data to degraded vdevs?
*/
boolean_t zfs_write_to_degraded = B_FALSE;
SYSCTL_INT(_vfs_zfs, OID_AUTO, write_to_degraded, CTLFLAG_RW,
&zfs_write_to_degraded, 0,
"Allow writing data to degraded vdevs");
TUNABLE_INT("vfs.zfs.write_to_degraded", &zfs_write_to_degraded);
/*
* Max number of metaslabs per group to preload.
*/
int metaslab_preload_limit = SPA_DVAS_PER_BP;
TUNABLE_INT("vfs.zfs.metaslab.preload_limit", &metaslab_preload_limit);
SYSCTL_INT(_vfs_zfs_metaslab, OID_AUTO, preload_limit, CTLFLAG_RWTUN,
&metaslab_preload_limit, 0,
"Max number of metaslabs per group to preload");
/*
* Enable/disable preloading of metaslab.
*/
boolean_t metaslab_preload_enabled = B_TRUE;
TUNABLE_INT("vfs.zfs.metaslab.preload_enabled", &metaslab_preload_enabled);
SYSCTL_INT(_vfs_zfs_metaslab, OID_AUTO, preload_enabled, CTLFLAG_RWTUN,
&metaslab_preload_enabled, 0,
"Max number of metaslabs per group to preload");
/*
* Enable/disable additional weight factor for each metaslab.
*/
boolean_t metaslab_weight_factor_enable = B_FALSE;
TUNABLE_INT("vfs.zfs.metaslab.weight_factor_enable",
&metaslab_weight_factor_enable);
SYSCTL_INT(_vfs_zfs_metaslab, OID_AUTO, weight_factor_enable, CTLFLAG_RWTUN,
&metaslab_weight_factor_enable, 0,
"Enable additional weight factor for each metaslab");
/*
* ==========================================================================
* Metaslab classes
* ==========================================================================
*/
metaslab_class_t *
metaslab_class_create(spa_t *spa, metaslab_ops_t *ops)
{
metaslab_class_t *mc;
mc = kmem_zalloc(sizeof (metaslab_class_t), KM_SLEEP);
mc->mc_spa = spa;
mc->mc_rotor = NULL;
mc->mc_ops = ops;
return (mc);
}
void
metaslab_class_destroy(metaslab_class_t *mc)
{
ASSERT(mc->mc_rotor == NULL);
ASSERT(mc->mc_alloc == 0);
ASSERT(mc->mc_deferred == 0);
ASSERT(mc->mc_space == 0);
ASSERT(mc->mc_dspace == 0);
kmem_free(mc, sizeof (metaslab_class_t));
}
int
metaslab_class_validate(metaslab_class_t *mc)
{
metaslab_group_t *mg;
vdev_t *vd;
/*
* Must hold one of the spa_config locks.
*/
ASSERT(spa_config_held(mc->mc_spa, SCL_ALL, RW_READER) ||
spa_config_held(mc->mc_spa, SCL_ALL, RW_WRITER));
if ((mg = mc->mc_rotor) == NULL)
return (0);
do {
vd = mg->mg_vd;
ASSERT(vd->vdev_mg != NULL);
ASSERT3P(vd->vdev_top, ==, vd);
ASSERT3P(mg->mg_class, ==, mc);
ASSERT3P(vd->vdev_ops, !=, &vdev_hole_ops);
} while ((mg = mg->mg_next) != mc->mc_rotor);
return (0);
}
void
metaslab_class_space_update(metaslab_class_t *mc, int64_t alloc_delta,
int64_t defer_delta, int64_t space_delta, int64_t dspace_delta)
{
atomic_add_64(&mc->mc_alloc, alloc_delta);
atomic_add_64(&mc->mc_deferred, defer_delta);
atomic_add_64(&mc->mc_space, space_delta);
atomic_add_64(&mc->mc_dspace, dspace_delta);
}
void
metaslab_class_minblocksize_update(metaslab_class_t *mc)
{
metaslab_group_t *mg;
vdev_t *vd;
uint64_t minashift = UINT64_MAX;
if ((mg = mc->mc_rotor) == NULL) {
mc->mc_minblocksize = SPA_MINBLOCKSIZE;
return;
}
do {
vd = mg->mg_vd;
if (vd->vdev_ashift < minashift)
minashift = vd->vdev_ashift;
} while ((mg = mg->mg_next) != mc->mc_rotor);
mc->mc_minblocksize = 1ULL << minashift;
}
uint64_t
metaslab_class_get_alloc(metaslab_class_t *mc)
{
return (mc->mc_alloc);
}
uint64_t
metaslab_class_get_deferred(metaslab_class_t *mc)
{
return (mc->mc_deferred);
}
uint64_t
metaslab_class_get_space(metaslab_class_t *mc)
{
return (mc->mc_space);
}
uint64_t
metaslab_class_get_dspace(metaslab_class_t *mc)
{
return (spa_deflate(mc->mc_spa) ? mc->mc_dspace : mc->mc_space);
}
uint64_t
metaslab_class_get_minblocksize(metaslab_class_t *mc)
{
return (mc->mc_minblocksize);
}
/*
* ==========================================================================
* Metaslab groups
* ==========================================================================
*/
static int
metaslab_compare(const void *x1, const void *x2)
{
const metaslab_t *m1 = x1;
const metaslab_t *m2 = x2;
if (m1->ms_weight < m2->ms_weight)
return (1);
if (m1->ms_weight > m2->ms_weight)
return (-1);
/*
* If the weights are identical, use the offset to force uniqueness.
*/
if (m1->ms_start < m2->ms_start)
return (-1);
if (m1->ms_start > m2->ms_start)
return (1);
ASSERT3P(m1, ==, m2);
return (0);
}
/*
* Update the allocatable flag and the metaslab group's capacity.
* The allocatable flag is set to true if the capacity is below
* the zfs_mg_noalloc_threshold. If a metaslab group transitions
* from allocatable to non-allocatable or vice versa then the metaslab
* group's class is updated to reflect the transition.
*/
static void
metaslab_group_alloc_update(metaslab_group_t *mg)
{
vdev_t *vd = mg->mg_vd;
metaslab_class_t *mc = mg->mg_class;
vdev_stat_t *vs = &vd->vdev_stat;
boolean_t was_allocatable;
ASSERT(vd == vd->vdev_top);
mutex_enter(&mg->mg_lock);
was_allocatable = mg->mg_allocatable;
mg->mg_free_capacity = ((vs->vs_space - vs->vs_alloc) * 100) /
(vs->vs_space + 1);
mg->mg_allocatable = (mg->mg_free_capacity > zfs_mg_noalloc_threshold);
/*
* The mc_alloc_groups maintains a count of the number of
* groups in this metaslab class that are still above the
* zfs_mg_noalloc_threshold. This is used by the allocating
* threads to determine if they should avoid allocations to
* a given group. The allocator will avoid allocations to a group
* if that group has reached or is below the zfs_mg_noalloc_threshold
* and there are still other groups that are above the threshold.
* When a group transitions from allocatable to non-allocatable or
* vice versa we update the metaslab class to reflect that change.
* When the mc_alloc_groups value drops to 0 that means that all
* groups have reached the zfs_mg_noalloc_threshold making all groups
* eligible for allocations. This effectively means that all devices
* are balanced again.
*/
if (was_allocatable && !mg->mg_allocatable)
mc->mc_alloc_groups--;
else if (!was_allocatable && mg->mg_allocatable)
mc->mc_alloc_groups++;
mutex_exit(&mg->mg_lock);
}
metaslab_group_t *
metaslab_group_create(metaslab_class_t *mc, vdev_t *vd)
{
metaslab_group_t *mg;
mg = kmem_zalloc(sizeof (metaslab_group_t), KM_SLEEP);
mutex_init(&mg->mg_lock, NULL, MUTEX_DEFAULT, NULL);
avl_create(&mg->mg_metaslab_tree, metaslab_compare,
sizeof (metaslab_t), offsetof(struct metaslab, ms_group_node));
mg->mg_vd = vd;
mg->mg_class = mc;
mg->mg_activation_count = 0;
mg->mg_taskq = taskq_create("metaslab_group_taskq", metaslab_load_pct,
minclsyspri, 10, INT_MAX, TASKQ_THREADS_CPU_PCT);
return (mg);
}
void
metaslab_group_destroy(metaslab_group_t *mg)
{
ASSERT(mg->mg_prev == NULL);
ASSERT(mg->mg_next == NULL);
/*
* We may have gone below zero with the activation count
* either because we never activated in the first place or
* because we're done, and possibly removing the vdev.
*/
ASSERT(mg->mg_activation_count <= 0);
taskq_destroy(mg->mg_taskq);
avl_destroy(&mg->mg_metaslab_tree);
mutex_destroy(&mg->mg_lock);
kmem_free(mg, sizeof (metaslab_group_t));
}
void
metaslab_group_activate(metaslab_group_t *mg)
{
metaslab_class_t *mc = mg->mg_class;
metaslab_group_t *mgprev, *mgnext;
ASSERT(spa_config_held(mc->mc_spa, SCL_ALLOC, RW_WRITER));
ASSERT(mc->mc_rotor != mg);
ASSERT(mg->mg_prev == NULL);
ASSERT(mg->mg_next == NULL);
ASSERT(mg->mg_activation_count <= 0);
if (++mg->mg_activation_count <= 0)
return;
mg->mg_aliquot = metaslab_aliquot * MAX(1, mg->mg_vd->vdev_children);
metaslab_group_alloc_update(mg);
if ((mgprev = mc->mc_rotor) == NULL) {
mg->mg_prev = mg;
mg->mg_next = mg;
} else {
mgnext = mgprev->mg_next;
mg->mg_prev = mgprev;
mg->mg_next = mgnext;
mgprev->mg_next = mg;
mgnext->mg_prev = mg;
}
mc->mc_rotor = mg;
metaslab_class_minblocksize_update(mc);
}
void
metaslab_group_passivate(metaslab_group_t *mg)
{
metaslab_class_t *mc = mg->mg_class;
metaslab_group_t *mgprev, *mgnext;
ASSERT(spa_config_held(mc->mc_spa, SCL_ALLOC, RW_WRITER));
if (--mg->mg_activation_count != 0) {
ASSERT(mc->mc_rotor != mg);
ASSERT(mg->mg_prev == NULL);
ASSERT(mg->mg_next == NULL);
ASSERT(mg->mg_activation_count < 0);
return;
}
taskq_wait(mg->mg_taskq);
mgprev = mg->mg_prev;
mgnext = mg->mg_next;
if (mg == mgnext) {
mc->mc_rotor = NULL;
} else {
mc->mc_rotor = mgnext;
mgprev->mg_next = mgnext;
mgnext->mg_prev = mgprev;
}
mg->mg_prev = NULL;
mg->mg_next = NULL;
metaslab_class_minblocksize_update(mc);
}
static void
metaslab_group_add(metaslab_group_t *mg, metaslab_t *msp)
{
mutex_enter(&mg->mg_lock);
ASSERT(msp->ms_group == NULL);
msp->ms_group = mg;
msp->ms_weight = 0;
avl_add(&mg->mg_metaslab_tree, msp);
mutex_exit(&mg->mg_lock);
}
static void
metaslab_group_remove(metaslab_group_t *mg, metaslab_t *msp)
{
mutex_enter(&mg->mg_lock);
ASSERT(msp->ms_group == mg);
avl_remove(&mg->mg_metaslab_tree, msp);
msp->ms_group = NULL;
mutex_exit(&mg->mg_lock);
}
static void
metaslab_group_sort(metaslab_group_t *mg, metaslab_t *msp, uint64_t weight)
{
/*
* Although in principle the weight can be any value, in
* practice we do not use values in the range [1, 510].
*/
ASSERT(weight >= SPA_MINBLOCKSIZE-1 || weight == 0);
ASSERT(MUTEX_HELD(&msp->ms_lock));
mutex_enter(&mg->mg_lock);
ASSERT(msp->ms_group == mg);
avl_remove(&mg->mg_metaslab_tree, msp);
msp->ms_weight = weight;
avl_add(&mg->mg_metaslab_tree, msp);
mutex_exit(&mg->mg_lock);
}
/*
* Determine if a given metaslab group should skip allocations. A metaslab
* group should avoid allocations if its used capacity has crossed the
* zfs_mg_noalloc_threshold and there is at least one metaslab group
* that can still handle allocations.
*/
static boolean_t
metaslab_group_allocatable(metaslab_group_t *mg)
{
vdev_t *vd = mg->mg_vd;
spa_t *spa = vd->vdev_spa;
metaslab_class_t *mc = mg->mg_class;
/*
* A metaslab group is considered allocatable if its free capacity
* is greater than the set value of zfs_mg_noalloc_threshold, it's
* associated with a slog, or there are no other metaslab groups
* with free capacity greater than zfs_mg_noalloc_threshold.
*/
return (mg->mg_free_capacity > zfs_mg_noalloc_threshold ||
mc != spa_normal_class(spa) || mc->mc_alloc_groups == 0);
}
/*
* ==========================================================================
* Range tree callbacks
* ==========================================================================
*/
/*
* Comparison function for the private size-ordered tree. Tree is sorted
* by size, larger sizes at the end of the tree.
*/
static int
metaslab_rangesize_compare(const void *x1, const void *x2)
{
const range_seg_t *r1 = x1;
const range_seg_t *r2 = x2;
uint64_t rs_size1 = r1->rs_end - r1->rs_start;
uint64_t rs_size2 = r2->rs_end - r2->rs_start;
if (rs_size1 < rs_size2)
return (-1);
if (rs_size1 > rs_size2)
return (1);
if (r1->rs_start < r2->rs_start)
return (-1);
if (r1->rs_start > r2->rs_start)
return (1);
return (0);
}
/*
* Create any block allocator specific components. The current allocators
* rely on using both a size-ordered range_tree_t and an array of uint64_t's.
*/
static void
metaslab_rt_create(range_tree_t *rt, void *arg)
{
metaslab_t *msp = arg;
ASSERT3P(rt->rt_arg, ==, msp);
ASSERT(msp->ms_tree == NULL);
avl_create(&msp->ms_size_tree, metaslab_rangesize_compare,
sizeof (range_seg_t), offsetof(range_seg_t, rs_pp_node));
}
/*
* Destroy the block allocator specific components.
*/
static void
metaslab_rt_destroy(range_tree_t *rt, void *arg)
{
metaslab_t *msp = arg;
ASSERT3P(rt->rt_arg, ==, msp);
ASSERT3P(msp->ms_tree, ==, rt);
ASSERT0(avl_numnodes(&msp->ms_size_tree));
avl_destroy(&msp->ms_size_tree);
}
static void
metaslab_rt_add(range_tree_t *rt, range_seg_t *rs, void *arg)
{
metaslab_t *msp = arg;
ASSERT3P(rt->rt_arg, ==, msp);
ASSERT3P(msp->ms_tree, ==, rt);
VERIFY(!msp->ms_condensing);
avl_add(&msp->ms_size_tree, rs);
}
static void
metaslab_rt_remove(range_tree_t *rt, range_seg_t *rs, void *arg)
{
metaslab_t *msp = arg;
ASSERT3P(rt->rt_arg, ==, msp);
ASSERT3P(msp->ms_tree, ==, rt);
VERIFY(!msp->ms_condensing);
avl_remove(&msp->ms_size_tree, rs);
}
static void
metaslab_rt_vacate(range_tree_t *rt, void *arg)
{
metaslab_t *msp = arg;
ASSERT3P(rt->rt_arg, ==, msp);
ASSERT3P(msp->ms_tree, ==, rt);
/*
* Normally one would walk the tree freeing nodes along the way.
* Since the nodes are shared with the range trees we can avoid
* walking all nodes and just reinitialize the avl tree. The nodes
* will be freed by the range tree, so we don't want to free them here.
*/
avl_create(&msp->ms_size_tree, metaslab_rangesize_compare,
sizeof (range_seg_t), offsetof(range_seg_t, rs_pp_node));
}
static range_tree_ops_t metaslab_rt_ops = {
metaslab_rt_create,
metaslab_rt_destroy,
metaslab_rt_add,
metaslab_rt_remove,
metaslab_rt_vacate
};
/*
* ==========================================================================
* Metaslab block operations
* ==========================================================================
*/
/*
* Return the maximum contiguous segment within the metaslab.
*/
uint64_t
metaslab_block_maxsize(metaslab_t *msp)
{
avl_tree_t *t = &msp->ms_size_tree;
range_seg_t *rs;
if (t == NULL || (rs = avl_last(t)) == NULL)
return (0ULL);
return (rs->rs_end - rs->rs_start);
}
uint64_t
metaslab_block_alloc(metaslab_t *msp, uint64_t size)
{
uint64_t start;
range_tree_t *rt = msp->ms_tree;
VERIFY(!msp->ms_condensing);
start = msp->ms_ops->msop_alloc(msp, size);
if (start != -1ULL) {
vdev_t *vd = msp->ms_group->mg_vd;
VERIFY0(P2PHASE(start, 1ULL << vd->vdev_ashift));
VERIFY0(P2PHASE(size, 1ULL << vd->vdev_ashift));
VERIFY3U(range_tree_space(rt) - size, <=, msp->ms_size);
range_tree_remove(rt, start, size);
}
return (start);
}
/*
* ==========================================================================
* Common allocator routines
* ==========================================================================
*/
/*
* This is a helper function that can be used by the allocator to find
* a suitable block to allocate. This will search the specified AVL
* tree looking for a block that matches the specified criteria.
*/
static uint64_t
metaslab_block_picker(avl_tree_t *t, uint64_t *cursor, uint64_t size,
uint64_t align)
{
range_seg_t *rs, rsearch;
avl_index_t where;
rsearch.rs_start = *cursor;
rsearch.rs_end = *cursor + size;
rs = avl_find(t, &rsearch, &where);
if (rs == NULL)
rs = avl_nearest(t, where, AVL_AFTER);
while (rs != NULL) {
uint64_t offset = P2ROUNDUP(rs->rs_start, align);
if (offset + size <= rs->rs_end) {
*cursor = offset + size;
return (offset);
}
rs = AVL_NEXT(t, rs);
}
/*
* If we know we've searched the whole map (*cursor == 0), give up.
* Otherwise, reset the cursor to the beginning and try again.
*/
if (*cursor == 0)
return (-1ULL);
*cursor = 0;
return (metaslab_block_picker(t, cursor, size, align));
}
/*
* ==========================================================================
* The first-fit block allocator
* ==========================================================================
*/
static uint64_t
metaslab_ff_alloc(metaslab_t *msp, uint64_t size)
{
/*
* Find the largest power of 2 block size that evenly divides the
* requested size. This is used to try to allocate blocks with similar
* alignment from the same area of the metaslab (i.e. same cursor
* bucket) but it does not guarantee that other allocations sizes
* may exist in the same region.
*/
uint64_t align = size & -size;
uint64_t *cursor = &msp->ms_lbas[highbit64(align) - 1];
avl_tree_t *t = &msp->ms_tree->rt_root;
return (metaslab_block_picker(t, cursor, size, align));
}
/* ARGSUSED */
static boolean_t
metaslab_ff_fragmented(metaslab_t *msp)
{
return (B_TRUE);
}
static metaslab_ops_t metaslab_ff_ops = {
metaslab_ff_alloc,
metaslab_ff_fragmented
};
/*
* ==========================================================================
* Dynamic block allocator -
* Uses the first fit allocation scheme until space get low and then
* adjusts to a best fit allocation method. Uses metaslab_df_alloc_threshold
* and metaslab_df_free_pct to determine when to switch the allocation scheme.
* ==========================================================================
*/
static uint64_t
metaslab_df_alloc(metaslab_t *msp, uint64_t size)
{
/*
* Find the largest power of 2 block size that evenly divides the
* requested size. This is used to try to allocate blocks with similar
* alignment from the same area of the metaslab (i.e. same cursor
* bucket) but it does not guarantee that other allocations sizes
* may exist in the same region.
*/
uint64_t align = size & -size;
uint64_t *cursor = &msp->ms_lbas[highbit64(align) - 1];
range_tree_t *rt = msp->ms_tree;
avl_tree_t *t = &rt->rt_root;
uint64_t max_size = metaslab_block_maxsize(msp);
int free_pct = range_tree_space(rt) * 100 / msp->ms_size;
ASSERT(MUTEX_HELD(&msp->ms_lock));
ASSERT3U(avl_numnodes(t), ==, avl_numnodes(&msp->ms_size_tree));
if (max_size < size)
return (-1ULL);
/*
* If we're running low on space switch to using the size
* sorted AVL tree (best-fit).
*/
if (max_size < metaslab_df_alloc_threshold ||
free_pct < metaslab_df_free_pct) {
t = &msp->ms_size_tree;
*cursor = 0;
}
return (metaslab_block_picker(t, cursor, size, 1ULL));
}
static boolean_t
metaslab_df_fragmented(metaslab_t *msp)
{
range_tree_t *rt = msp->ms_tree;
uint64_t max_size = metaslab_block_maxsize(msp);
int free_pct = range_tree_space(rt) * 100 / msp->ms_size;
if (max_size >= metaslab_df_alloc_threshold &&
free_pct >= metaslab_df_free_pct)
return (B_FALSE);
return (B_TRUE);
}
static metaslab_ops_t metaslab_df_ops = {
metaslab_df_alloc,
metaslab_df_fragmented
};
/*
* ==========================================================================
* Cursor fit block allocator -
* Select the largest region in the metaslab, set the cursor to the beginning
* of the range and the cursor_end to the end of the range. As allocations
* are made advance the cursor. Continue allocating from the cursor until
* the range is exhausted and then find a new range.
* ==========================================================================
*/
static uint64_t
metaslab_cf_alloc(metaslab_t *msp, uint64_t size)
{
range_tree_t *rt = msp->ms_tree;
avl_tree_t *t = &msp->ms_size_tree;
uint64_t *cursor = &msp->ms_lbas[0];
uint64_t *cursor_end = &msp->ms_lbas[1];
uint64_t offset = 0;
ASSERT(MUTEX_HELD(&msp->ms_lock));
ASSERT3U(avl_numnodes(t), ==, avl_numnodes(&rt->rt_root));
ASSERT3U(*cursor_end, >=, *cursor);
if ((*cursor + size) > *cursor_end) {
range_seg_t *rs;
rs = avl_last(&msp->ms_size_tree);
if (rs == NULL || (rs->rs_end - rs->rs_start) < size)
return (-1ULL);
*cursor = rs->rs_start;
*cursor_end = rs->rs_end;
}
offset = *cursor;
*cursor += size;
return (offset);
}
static boolean_t
metaslab_cf_fragmented(metaslab_t *msp)
{
return (metaslab_block_maxsize(msp) < metaslab_min_alloc_size);
}
static metaslab_ops_t metaslab_cf_ops = {
metaslab_cf_alloc,
metaslab_cf_fragmented
};
/*
* ==========================================================================
* New dynamic fit allocator -
* Select a region that is large enough to allocate 2^metaslab_ndf_clump_shift
* contiguous blocks. If no region is found then just use the largest segment
* that remains.
* ==========================================================================
*/
/*
* Determines desired number of contiguous blocks (2^metaslab_ndf_clump_shift)
* to request from the allocator.
*/
uint64_t metaslab_ndf_clump_shift = 4;
static uint64_t
metaslab_ndf_alloc(metaslab_t *msp, uint64_t size)
{
avl_tree_t *t = &msp->ms_tree->rt_root;
avl_index_t where;
range_seg_t *rs, rsearch;
uint64_t hbit = highbit64(size);
uint64_t *cursor = &msp->ms_lbas[hbit - 1];
uint64_t max_size = metaslab_block_maxsize(msp);
ASSERT(MUTEX_HELD(&msp->ms_lock));
ASSERT3U(avl_numnodes(t), ==, avl_numnodes(&msp->ms_size_tree));
if (max_size < size)
return (-1ULL);
rsearch.rs_start = *cursor;
rsearch.rs_end = *cursor + size;
rs = avl_find(t, &rsearch, &where);
if (rs == NULL || (rs->rs_end - rs->rs_start) < size) {
t = &msp->ms_size_tree;
rsearch.rs_start = 0;
rsearch.rs_end = MIN(max_size,
1ULL << (hbit + metaslab_ndf_clump_shift));
rs = avl_find(t, &rsearch, &where);
if (rs == NULL)
rs = avl_nearest(t, where, AVL_AFTER);
ASSERT(rs != NULL);
}
if ((rs->rs_end - rs->rs_start) >= size) {
*cursor = rs->rs_start + size;
return (rs->rs_start);
}
return (-1ULL);
}
static boolean_t
metaslab_ndf_fragmented(metaslab_t *msp)
{
return (metaslab_block_maxsize(msp) <=
(metaslab_min_alloc_size << metaslab_ndf_clump_shift));
}
static metaslab_ops_t metaslab_ndf_ops = {
metaslab_ndf_alloc,
metaslab_ndf_fragmented
};
metaslab_ops_t *zfs_metaslab_ops = &metaslab_df_ops;
/*
* ==========================================================================
* Metaslabs
* ==========================================================================
*/
/*
* Wait for any in-progress metaslab loads to complete.
*/
void
metaslab_load_wait(metaslab_t *msp)
{
ASSERT(MUTEX_HELD(&msp->ms_lock));
while (msp->ms_loading) {
ASSERT(!msp->ms_loaded);
cv_wait(&msp->ms_load_cv, &msp->ms_lock);
}
}
int
metaslab_load(metaslab_t *msp)
{
int error = 0;
ASSERT(MUTEX_HELD(&msp->ms_lock));
ASSERT(!msp->ms_loaded);
ASSERT(!msp->ms_loading);
msp->ms_loading = B_TRUE;
/*
* If the space map has not been allocated yet, then treat
* all the space in the metaslab as free and add it to the
* ms_tree.
*/
if (msp->ms_sm != NULL)
error = space_map_load(msp->ms_sm, msp->ms_tree, SM_FREE);
else
range_tree_add(msp->ms_tree, msp->ms_start, msp->ms_size);
msp->ms_loaded = (error == 0);
msp->ms_loading = B_FALSE;
if (msp->ms_loaded) {
for (int t = 0; t < TXG_DEFER_SIZE; t++) {
range_tree_walk(msp->ms_defertree[t],
range_tree_remove, msp->ms_tree);
}
}
cv_broadcast(&msp->ms_load_cv);
return (error);
}
void
metaslab_unload(metaslab_t *msp)
{
ASSERT(MUTEX_HELD(&msp->ms_lock));
range_tree_vacate(msp->ms_tree, NULL, NULL);
msp->ms_loaded = B_FALSE;
msp->ms_weight &= ~METASLAB_ACTIVE_MASK;
}
metaslab_t *
metaslab_init(metaslab_group_t *mg, uint64_t id, uint64_t object, uint64_t txg)
{
vdev_t *vd = mg->mg_vd;
objset_t *mos = vd->vdev_spa->spa_meta_objset;
metaslab_t *msp;
msp = kmem_zalloc(sizeof (metaslab_t), KM_SLEEP);
mutex_init(&msp->ms_lock, NULL, MUTEX_DEFAULT, NULL);
cv_init(&msp->ms_load_cv, NULL, CV_DEFAULT, NULL);
msp->ms_id = id;
msp->ms_start = id << vd->vdev_ms_shift;
msp->ms_size = 1ULL << vd->vdev_ms_shift;
/*
* We only open space map objects that already exist. All others
* will be opened when we finally allocate an object for it.
*/
if (object != 0) {
VERIFY0(space_map_open(&msp->ms_sm, mos, object, msp->ms_start,
msp->ms_size, vd->vdev_ashift, &msp->ms_lock));
ASSERT(msp->ms_sm != NULL);
}
/*
* We create the main range tree here, but we don't create the
* alloctree and freetree until metaslab_sync_done(). This serves
* two purposes: it allows metaslab_sync_done() to detect the
* addition of new space; and for debugging, it ensures that we'd
* data fault on any attempt to use this metaslab before it's ready.
*/
msp->ms_tree = range_tree_create(&metaslab_rt_ops, msp, &msp->ms_lock);
metaslab_group_add(mg, msp);
msp->ms_ops = mg->mg_class->mc_ops;
/*
* If we're opening an existing pool (txg == 0) or creating
* a new one (txg == TXG_INITIAL), all space is available now.
* If we're adding space to an existing pool, the new space
* does not become available until after this txg has synced.
*/
if (txg <= TXG_INITIAL)
metaslab_sync_done(msp, 0);
/*
* If metaslab_debug_load is set and we're initializing a metaslab
* that has an allocated space_map object then load the its space
* map so that can verify frees.
*/
if (metaslab_debug_load && msp->ms_sm != NULL) {
mutex_enter(&msp->ms_lock);
VERIFY0(metaslab_load(msp));
mutex_exit(&msp->ms_lock);
}
if (txg != 0) {
vdev_dirty(vd, 0, NULL, txg);
vdev_dirty(vd, VDD_METASLAB, msp, txg);
}
return (msp);
}
void
metaslab_fini(metaslab_t *msp)
{
metaslab_group_t *mg = msp->ms_group;
metaslab_group_remove(mg, msp);
mutex_enter(&msp->ms_lock);
VERIFY(msp->ms_group == NULL);
vdev_space_update(mg->mg_vd, -space_map_allocated(msp->ms_sm),
0, -msp->ms_size);
space_map_close(msp->ms_sm);
metaslab_unload(msp);
range_tree_destroy(msp->ms_tree);
for (int t = 0; t < TXG_SIZE; t++) {
range_tree_destroy(msp->ms_alloctree[t]);
range_tree_destroy(msp->ms_freetree[t]);
}
for (int t = 0; t < TXG_DEFER_SIZE; t++) {
range_tree_destroy(msp->ms_defertree[t]);
}
ASSERT0(msp->ms_deferspace);
mutex_exit(&msp->ms_lock);
cv_destroy(&msp->ms_load_cv);
mutex_destroy(&msp->ms_lock);
kmem_free(msp, sizeof (metaslab_t));
}
/*
* Apply a weighting factor based on the histogram information for this
* metaslab. The current weighting factor is somewhat arbitrary and requires
* additional investigation. The implementation provides a measure of
* "weighted" free space and gives a higher weighting for larger contiguous
* regions. The weighting factor is determined by counting the number of
* sm_shift sectors that exist in each region represented by the histogram.
* That value is then multiplied by the power of 2 exponent and the sm_shift
* value.
*
* For example, assume the 2^21 histogram bucket has 4 2MB regions and the
* metaslab has an sm_shift value of 9 (512B):
*
* 1) calculate the number of sm_shift sectors in the region:
* 2^21 / 2^9 = 2^12 = 4096 * 4 (number of regions) = 16384
* 2) multiply by the power of 2 exponent and the sm_shift value:
* 16384 * 21 * 9 = 3096576
* This value will be added to the weighting of the metaslab.
*/
static uint64_t
metaslab_weight_factor(metaslab_t *msp)
{
uint64_t factor = 0;
uint64_t sectors;
int i;
/*
* A null space map means that the entire metaslab is free,
* calculate a weight factor that spans the entire size of the
* metaslab.
*/
if (msp->ms_sm == NULL) {
vdev_t *vd = msp->ms_group->mg_vd;
i = highbit64(msp->ms_size) - 1;
sectors = msp->ms_size >> vd->vdev_ashift;
return (sectors * i * vd->vdev_ashift);
}
if (msp->ms_sm->sm_dbuf->db_size != sizeof (space_map_phys_t))
return (0);
for (i = 0; i < SPACE_MAP_HISTOGRAM_SIZE(msp->ms_sm); i++) {
if (msp->ms_sm->sm_phys->smp_histogram[i] == 0)
continue;
/*
* Determine the number of sm_shift sectors in the region
* indicated by the histogram. For example, given an
* sm_shift value of 9 (512 bytes) and i = 4 then we know
* that we're looking at an 8K region in the histogram
* (i.e. 9 + 4 = 13, 2^13 = 8192). To figure out the
* number of sm_shift sectors (512 bytes in this example),
* we would take 8192 / 512 = 16. Since the histogram
* is offset by sm_shift we can simply use the value of
* of i to calculate this (i.e. 2^i = 16 where i = 4).
*/
sectors = msp->ms_sm->sm_phys->smp_histogram[i] << i;
factor += (i + msp->ms_sm->sm_shift) * sectors;
}
return (factor * msp->ms_sm->sm_shift);
}
static uint64_t
metaslab_weight(metaslab_t *msp)
{
metaslab_group_t *mg = msp->ms_group;
vdev_t *vd = mg->mg_vd;
uint64_t weight, space;
ASSERT(MUTEX_HELD(&msp->ms_lock));
/*
* This vdev is in the process of being removed so there is nothing
* for us to do here.
*/
if (vd->vdev_removing) {
ASSERT0(space_map_allocated(msp->ms_sm));
ASSERT0(vd->vdev_ms_shift);
return (0);
}
/*
* The baseline weight is the metaslab's free space.
*/
space = msp->ms_size - space_map_allocated(msp->ms_sm);
weight = space;
/*
* Modern disks have uniform bit density and constant angular velocity.
* Therefore, the outer recording zones are faster (higher bandwidth)
* than the inner zones by the ratio of outer to inner track diameter,
* which is typically around 2:1. We account for this by assigning
* higher weight to lower metaslabs (multiplier ranging from 2x to 1x).
* In effect, this means that we'll select the metaslab with the most
* free bandwidth rather than simply the one with the most free space.
*/
weight = 2 * weight - (msp->ms_id * weight) / vd->vdev_ms_count;
ASSERT(weight >= space && weight <= 2 * space);
msp->ms_factor = metaslab_weight_factor(msp);
if (metaslab_weight_factor_enable)
weight += msp->ms_factor;
if (msp->ms_loaded && !msp->ms_ops->msop_fragmented(msp)) {
/*
* If this metaslab is one we're actively using, adjust its
* weight to make it preferable to any inactive metaslab so
* we'll polish it off.
*/
weight |= (msp->ms_weight & METASLAB_ACTIVE_MASK);
}
return (weight);
}
static int
metaslab_activate(metaslab_t *msp, uint64_t activation_weight)
{
ASSERT(MUTEX_HELD(&msp->ms_lock));
if ((msp->ms_weight & METASLAB_ACTIVE_MASK) == 0) {
metaslab_load_wait(msp);
if (!msp->ms_loaded) {
int error = metaslab_load(msp);
if (error) {
metaslab_group_sort(msp->ms_group, msp, 0);
return (error);
}
}
metaslab_group_sort(msp->ms_group, msp,
msp->ms_weight | activation_weight);
}
ASSERT(msp->ms_loaded);
ASSERT(msp->ms_weight & METASLAB_ACTIVE_MASK);
return (0);
}
static void
metaslab_passivate(metaslab_t *msp, uint64_t size)
{
/*
* If size < SPA_MINBLOCKSIZE, then we will not allocate from
* this metaslab again. In that case, it had better be empty,
* or we would be leaving space on the table.
*/
ASSERT(size >= SPA_MINBLOCKSIZE || range_tree_space(msp->ms_tree) == 0);
metaslab_group_sort(msp->ms_group, msp, MIN(msp->ms_weight, size));
ASSERT((msp->ms_weight & METASLAB_ACTIVE_MASK) == 0);
}
static void
metaslab_preload(void *arg)
{
metaslab_t *msp = arg;
spa_t *spa = msp->ms_group->mg_vd->vdev_spa;
mutex_enter(&msp->ms_lock);
metaslab_load_wait(msp);
if (!msp->ms_loaded)
(void) metaslab_load(msp);
/*
* Set the ms_access_txg value so that we don't unload it right away.
*/
msp->ms_access_txg = spa_syncing_txg(spa) + metaslab_unload_delay + 1;
mutex_exit(&msp->ms_lock);
}
static void
metaslab_group_preload(metaslab_group_t *mg)
{
spa_t *spa = mg->mg_vd->vdev_spa;
metaslab_t *msp;
avl_tree_t *t = &mg->mg_metaslab_tree;
int m = 0;
if (spa_shutting_down(spa) || !metaslab_preload_enabled) {
taskq_wait(mg->mg_taskq);
return;
}
mutex_enter(&mg->mg_lock);
/*
* Prefetch the next potential metaslabs
*/
for (msp = avl_first(t); msp != NULL; msp = AVL_NEXT(t, msp)) {
/* If we have reached our preload limit then we're done */
if (++m > metaslab_preload_limit)
break;
VERIFY(taskq_dispatch(mg->mg_taskq, metaslab_preload,
msp, TQ_SLEEP) != 0);
}
mutex_exit(&mg->mg_lock);
}
/*
* Determine if the space map's on-disk footprint is past our tolerance
* for inefficiency. We would like to use the following criteria to make
* our decision:
*
* 1. The size of the space map object should not dramatically increase as a
* result of writing out the free space range tree.
*
* 2. The minimal on-disk space map representation is zfs_condense_pct/100
* times the size than the free space range tree representation
* (i.e. zfs_condense_pct = 110 and in-core = 1MB, minimal = 1.1.MB).
*
* Checking the first condition is tricky since we don't want to walk
* the entire AVL tree calculating the estimated on-disk size. Instead we
* use the size-ordered range tree in the metaslab and calculate the
* size required to write out the largest segment in our free tree. If the
* size required to represent that segment on disk is larger than the space
* map object then we avoid condensing this map.
*
* To determine the second criterion we use a best-case estimate and assume
* each segment can be represented on-disk as a single 64-bit entry. We refer
* to this best-case estimate as the space map's minimal form.
*/
static boolean_t
metaslab_should_condense(metaslab_t *msp)
{
space_map_t *sm = msp->ms_sm;
range_seg_t *rs;
uint64_t size, entries, segsz;
ASSERT(MUTEX_HELD(&msp->ms_lock));
ASSERT(msp->ms_loaded);
/*
* Use the ms_size_tree range tree, which is ordered by size, to
* obtain the largest segment in the free tree. If the tree is empty
* then we should condense the map.
*/
rs = avl_last(&msp->ms_size_tree);
if (rs == NULL)
return (B_TRUE);
/*
* Calculate the number of 64-bit entries this segment would
* require when written to disk. If this single segment would be
* larger on-disk than the entire current on-disk structure, then
* clearly condensing will increase the on-disk structure size.
*/
size = (rs->rs_end - rs->rs_start) >> sm->sm_shift;
entries = size / (MIN(size, SM_RUN_MAX));
segsz = entries * sizeof (uint64_t);
return (segsz <= space_map_length(msp->ms_sm) &&
space_map_length(msp->ms_sm) >= (zfs_condense_pct *
sizeof (uint64_t) * avl_numnodes(&msp->ms_tree->rt_root)) / 100);
}
/*
* Condense the on-disk space map representation to its minimized form.
* The minimized form consists of a small number of allocations followed by
* the entries of the free range tree.
*/
static void
metaslab_condense(metaslab_t *msp, uint64_t txg, dmu_tx_t *tx)
{
spa_t *spa = msp->ms_group->mg_vd->vdev_spa;
range_tree_t *freetree = msp->ms_freetree[txg & TXG_MASK];
range_tree_t *condense_tree;
space_map_t *sm = msp->ms_sm;
ASSERT(MUTEX_HELD(&msp->ms_lock));
ASSERT3U(spa_sync_pass(spa), ==, 1);
ASSERT(msp->ms_loaded);
spa_dbgmsg(spa, "condensing: txg %llu, msp[%llu] %p, "
"smp size %llu, segments %lu", txg, msp->ms_id, msp,
space_map_length(msp->ms_sm), avl_numnodes(&msp->ms_tree->rt_root));
/*
* Create an range tree that is 100% allocated. We remove segments
* that have been freed in this txg, any deferred frees that exist,
* and any allocation in the future. Removing segments should be
* a relatively inexpensive operation since we expect these trees to
* have a small number of nodes.
*/
condense_tree = range_tree_create(NULL, NULL, &msp->ms_lock);
range_tree_add(condense_tree, msp->ms_start, msp->ms_size);
/*
* Remove what's been freed in this txg from the condense_tree.
* Since we're in sync_pass 1, we know that all the frees from
* this txg are in the freetree.
*/
range_tree_walk(freetree, range_tree_remove, condense_tree);
for (int t = 0; t < TXG_DEFER_SIZE; t++) {
range_tree_walk(msp->ms_defertree[t],
range_tree_remove, condense_tree);
}
for (int t = 1; t < TXG_CONCURRENT_STATES; t++) {
range_tree_walk(msp->ms_alloctree[(txg + t) & TXG_MASK],
range_tree_remove, condense_tree);
}
/*
* We're about to drop the metaslab's lock thus allowing
* other consumers to change it's content. Set the
* metaslab's ms_condensing flag to ensure that
* allocations on this metaslab do not occur while we're
* in the middle of committing it to disk. This is only critical
* for the ms_tree as all other range trees use per txg
* views of their content.
*/
msp->ms_condensing = B_TRUE;
mutex_exit(&msp->ms_lock);
space_map_truncate(sm, tx);
mutex_enter(&msp->ms_lock);
/*
* While we would ideally like to create a space_map representation
* that consists only of allocation records, doing so can be
* prohibitively expensive because the in-core free tree can be
* large, and therefore computationally expensive to subtract
* from the condense_tree. Instead we sync out two trees, a cheap
* allocation only tree followed by the in-core free tree. While not
* optimal, this is typically close to optimal, and much cheaper to
* compute.
*/
space_map_write(sm, condense_tree, SM_ALLOC, tx);
range_tree_vacate(condense_tree, NULL, NULL);
range_tree_destroy(condense_tree);
space_map_write(sm, msp->ms_tree, SM_FREE, tx);
msp->ms_condensing = B_FALSE;
}
/*
* Write a metaslab to disk in the context of the specified transaction group.
*/
void
metaslab_sync(metaslab_t *msp, uint64_t txg)
{
metaslab_group_t *mg = msp->ms_group;
vdev_t *vd = mg->mg_vd;
spa_t *spa = vd->vdev_spa;
objset_t *mos = spa_meta_objset(spa);
range_tree_t *alloctree = msp->ms_alloctree[txg & TXG_MASK];
range_tree_t **freetree = &msp->ms_freetree[txg & TXG_MASK];
range_tree_t **freed_tree =
&msp->ms_freetree[TXG_CLEAN(txg) & TXG_MASK];
dmu_tx_t *tx;
uint64_t object = space_map_object(msp->ms_sm);
ASSERT(!vd->vdev_ishole);
/*
* This metaslab has just been added so there's no work to do now.
*/
if (*freetree == NULL) {
ASSERT3P(alloctree, ==, NULL);
return;
}
ASSERT3P(alloctree, !=, NULL);
ASSERT3P(*freetree, !=, NULL);
ASSERT3P(*freed_tree, !=, NULL);
if (range_tree_space(alloctree) == 0 &&
range_tree_space(*freetree) == 0)
return;
/*
* The only state that can actually be changing concurrently with
* metaslab_sync() is the metaslab's ms_tree. No other thread can
* be modifying this txg's alloctree, freetree, freed_tree, or
* space_map_phys_t. Therefore, we only hold ms_lock to satify
* space_map ASSERTs. We drop it whenever we call into the DMU,
* because the DMU can call down to us (e.g. via zio_free()) at
* any time.
*/
tx = dmu_tx_create_assigned(spa_get_dsl(spa), txg);
if (msp->ms_sm == NULL) {
uint64_t new_object;
new_object = space_map_alloc(mos, tx);
VERIFY3U(new_object, !=, 0);
VERIFY0(space_map_open(&msp->ms_sm, mos, new_object,
msp->ms_start, msp->ms_size, vd->vdev_ashift,
&msp->ms_lock));
ASSERT(msp->ms_sm != NULL);
}
mutex_enter(&msp->ms_lock);
if (msp->ms_loaded && spa_sync_pass(spa) == 1 &&
metaslab_should_condense(msp)) {
metaslab_condense(msp, txg, tx);
} else {
space_map_write(msp->ms_sm, alloctree, SM_ALLOC, tx);
space_map_write(msp->ms_sm, *freetree, SM_FREE, tx);
}
range_tree_vacate(alloctree, NULL, NULL);
if (msp->ms_loaded) {
/*
* When the space map is loaded, we have an accruate
* histogram in the range tree. This gives us an opportunity
* to bring the space map's histogram up-to-date so we clear
* it first before updating it.
*/
space_map_histogram_clear(msp->ms_sm);
space_map_histogram_add(msp->ms_sm, msp->ms_tree, tx);
} else {
/*
* Since the space map is not loaded we simply update the
* exisiting histogram with what was freed in this txg. This
* means that the on-disk histogram may not have an accurate
* view of the free space but it's close enough to allow
* us to make allocation decisions.
*/
space_map_histogram_add(msp->ms_sm, *freetree, tx);
}
/*
* For sync pass 1, we avoid traversing this txg's free range tree
* and instead will just swap the pointers for freetree and
* freed_tree. We can safely do this since the freed_tree is
* guaranteed to be empty on the initial pass.
*/
if (spa_sync_pass(spa) == 1) {
range_tree_swap(freetree, freed_tree);
} else {
range_tree_vacate(*freetree, range_tree_add, *freed_tree);
}
ASSERT0(range_tree_space(msp->ms_alloctree[txg & TXG_MASK]));
ASSERT0(range_tree_space(msp->ms_freetree[txg & TXG_MASK]));
mutex_exit(&msp->ms_lock);
if (object != space_map_object(msp->ms_sm)) {
object = space_map_object(msp->ms_sm);
dmu_write(mos, vd->vdev_ms_array, sizeof (uint64_t) *
msp->ms_id, sizeof (uint64_t), &object, tx);
}
dmu_tx_commit(tx);
}
/*
* Called after a transaction group has completely synced to mark
* all of the metaslab's free space as usable.
*/
void
metaslab_sync_done(metaslab_t *msp, uint64_t txg)
{
metaslab_group_t *mg = msp->ms_group;
vdev_t *vd = mg->mg_vd;
range_tree_t **freed_tree;
range_tree_t **defer_tree;
int64_t alloc_delta, defer_delta;
ASSERT(!vd->vdev_ishole);
mutex_enter(&msp->ms_lock);
/*
* If this metaslab is just becoming available, initialize its
* alloctrees, freetrees, and defertree and add its capacity to
* the vdev.
*/
if (msp->ms_freetree[TXG_CLEAN(txg) & TXG_MASK] == NULL) {
for (int t = 0; t < TXG_SIZE; t++) {
ASSERT(msp->ms_alloctree[t] == NULL);
ASSERT(msp->ms_freetree[t] == NULL);
msp->ms_alloctree[t] = range_tree_create(NULL, msp,
&msp->ms_lock);
msp->ms_freetree[t] = range_tree_create(NULL, msp,
&msp->ms_lock);
}
for (int t = 0; t < TXG_DEFER_SIZE; t++) {
ASSERT(msp->ms_defertree[t] == NULL);
msp->ms_defertree[t] = range_tree_create(NULL, msp,
&msp->ms_lock);
}
vdev_space_update(vd, 0, 0, msp->ms_size);
}
freed_tree = &msp->ms_freetree[TXG_CLEAN(txg) & TXG_MASK];
defer_tree = &msp->ms_defertree[txg % TXG_DEFER_SIZE];
alloc_delta = space_map_alloc_delta(msp->ms_sm);
defer_delta = range_tree_space(*freed_tree) -
range_tree_space(*defer_tree);
vdev_space_update(vd, alloc_delta + defer_delta, defer_delta, 0);
ASSERT0(range_tree_space(msp->ms_alloctree[txg & TXG_MASK]));
ASSERT0(range_tree_space(msp->ms_freetree[txg & TXG_MASK]));
/*
* If there's a metaslab_load() in progress, wait for it to complete
* so that we have a consistent view of the in-core space map.
*/
metaslab_load_wait(msp);
/*
* Move the frees from the defer_tree back to the free
* range tree (if it's loaded). Swap the freed_tree and the
* defer_tree -- this is safe to do because we've just emptied out
* the defer_tree.
*/
range_tree_vacate(*defer_tree,
msp->ms_loaded ? range_tree_add : NULL, msp->ms_tree);
range_tree_swap(freed_tree, defer_tree);
space_map_update(msp->ms_sm);
msp->ms_deferspace += defer_delta;
ASSERT3S(msp->ms_deferspace, >=, 0);
ASSERT3S(msp->ms_deferspace, <=, msp->ms_size);
if (msp->ms_deferspace != 0) {
/*
* Keep syncing this metaslab until all deferred frees
* are back in circulation.
*/
vdev_dirty(vd, VDD_METASLAB, msp, txg + 1);
}
if (msp->ms_loaded && msp->ms_access_txg < txg) {
for (int t = 1; t < TXG_CONCURRENT_STATES; t++) {
VERIFY0(range_tree_space(
msp->ms_alloctree[(txg + t) & TXG_MASK]));
}
if (!metaslab_debug_unload)
metaslab_unload(msp);
}
metaslab_group_sort(mg, msp, metaslab_weight(msp));
mutex_exit(&msp->ms_lock);
}
void
metaslab_sync_reassess(metaslab_group_t *mg)
{
metaslab_group_alloc_update(mg);
/*
* Preload the next potential metaslabs
*/
metaslab_group_preload(mg);
}
static uint64_t
metaslab_distance(metaslab_t *msp, dva_t *dva)
{
uint64_t ms_shift = msp->ms_group->mg_vd->vdev_ms_shift;
uint64_t offset = DVA_GET_OFFSET(dva) >> ms_shift;
uint64_t start = msp->ms_id;
if (msp->ms_group->mg_vd->vdev_id != DVA_GET_VDEV(dva))
return (1ULL << 63);
if (offset < start)
return ((start - offset) << ms_shift);
if (offset > start)
return ((offset - start) << ms_shift);
return (0);
}
static uint64_t
metaslab_group_alloc(metaslab_group_t *mg, uint64_t psize, uint64_t asize,
uint64_t txg, uint64_t min_distance, dva_t *dva, int d)
{
spa_t *spa = mg->mg_vd->vdev_spa;
metaslab_t *msp = NULL;
uint64_t offset = -1ULL;
avl_tree_t *t = &mg->mg_metaslab_tree;
uint64_t activation_weight;
uint64_t target_distance;
int i;
activation_weight = METASLAB_WEIGHT_PRIMARY;
for (i = 0; i < d; i++) {
if (DVA_GET_VDEV(&dva[i]) == mg->mg_vd->vdev_id) {
activation_weight = METASLAB_WEIGHT_SECONDARY;
break;
}
}
for (;;) {
boolean_t was_active;
mutex_enter(&mg->mg_lock);
for (msp = avl_first(t); msp; msp = AVL_NEXT(t, msp)) {
if (msp->ms_weight < asize) {
spa_dbgmsg(spa, "%s: failed to meet weight "
"requirement: vdev %llu, txg %llu, mg %p, "
"msp %p, psize %llu, asize %llu, "
"weight %llu", spa_name(spa),
mg->mg_vd->vdev_id, txg,
mg, msp, psize, asize, msp->ms_weight);
mutex_exit(&mg->mg_lock);
return (-1ULL);
}
/*
* If the selected metaslab is condensing, skip it.
*/
if (msp->ms_condensing)
continue;
was_active = msp->ms_weight & METASLAB_ACTIVE_MASK;
if (activation_weight == METASLAB_WEIGHT_PRIMARY)
break;
target_distance = min_distance +
(space_map_allocated(msp->ms_sm) != 0 ? 0 :
min_distance >> 1);
for (i = 0; i < d; i++)
if (metaslab_distance(msp, &dva[i]) <
target_distance)
break;
if (i == d)
break;
}
mutex_exit(&mg->mg_lock);
if (msp == NULL)
return (-1ULL);
mutex_enter(&msp->ms_lock);
/*
* Ensure that the metaslab we have selected is still
* capable of handling our request. It's possible that
* another thread may have changed the weight while we
* were blocked on the metaslab lock.
*/
if (msp->ms_weight < asize || (was_active &&
!(msp->ms_weight & METASLAB_ACTIVE_MASK) &&
activation_weight == METASLAB_WEIGHT_PRIMARY)) {
mutex_exit(&msp->ms_lock);
continue;
}
if ((msp->ms_weight & METASLAB_WEIGHT_SECONDARY) &&
activation_weight == METASLAB_WEIGHT_PRIMARY) {
metaslab_passivate(msp,
msp->ms_weight & ~METASLAB_ACTIVE_MASK);
mutex_exit(&msp->ms_lock);
continue;
}
if (metaslab_activate(msp, activation_weight) != 0) {
mutex_exit(&msp->ms_lock);
continue;
}
/*
* If this metaslab is currently condensing then pick again as
* we can't manipulate this metaslab until it's committed
* to disk.
*/
if (msp->ms_condensing) {
mutex_exit(&msp->ms_lock);
continue;
}
if ((offset = metaslab_block_alloc(msp, asize)) != -1ULL)
break;
metaslab_passivate(msp, metaslab_block_maxsize(msp));
mutex_exit(&msp->ms_lock);
}
if (range_tree_space(msp->ms_alloctree[txg & TXG_MASK]) == 0)
vdev_dirty(mg->mg_vd, VDD_METASLAB, msp, txg);
range_tree_add(msp->ms_alloctree[txg & TXG_MASK], offset, asize);
msp->ms_access_txg = txg + metaslab_unload_delay;
mutex_exit(&msp->ms_lock);
return (offset);
}
/*
* Allocate a block for the specified i/o.
*/
static int
metaslab_alloc_dva(spa_t *spa, metaslab_class_t *mc, uint64_t psize,
dva_t *dva, int d, dva_t *hintdva, uint64_t txg, int flags)
{
metaslab_group_t *mg, *rotor;
vdev_t *vd;
int dshift = 3;
int all_zero;
int zio_lock = B_FALSE;
boolean_t allocatable;
uint64_t offset = -1ULL;
uint64_t asize;
uint64_t distance;
ASSERT(!DVA_IS_VALID(&dva[d]));
/*
* For testing, make some blocks above a certain size be gang blocks.
*/
if (psize >= metaslab_gang_bang && (ddi_get_lbolt() & 3) == 0)
return (SET_ERROR(ENOSPC));
/*
* Start at the rotor and loop through all mgs until we find something.
* Note that there's no locking on mc_rotor or mc_aliquot because
* nothing actually breaks if we miss a few updates -- we just won't
* allocate quite as evenly. It all balances out over time.
*
* If we are doing ditto or log blocks, try to spread them across
* consecutive vdevs. If we're forced to reuse a vdev before we've
* allocated all of our ditto blocks, then try and spread them out on
* that vdev as much as possible. If it turns out to not be possible,
* gradually lower our standards until anything becomes acceptable.
* Also, allocating on consecutive vdevs (as opposed to random vdevs)
* gives us hope of containing our fault domains to something we're
* able to reason about. Otherwise, any two top-level vdev failures
* will guarantee the loss of data. With consecutive allocation,
* only two adjacent top-level vdev failures will result in data loss.
*
* If we are doing gang blocks (hintdva is non-NULL), try to keep
* ourselves on the same vdev as our gang block header. That
* way, we can hope for locality in vdev_cache, plus it makes our
* fault domains something tractable.
*/
if (hintdva) {
vd = vdev_lookup_top(spa, DVA_GET_VDEV(&hintdva[d]));
/*
* It's possible the vdev we're using as the hint no
* longer exists (i.e. removed). Consult the rotor when
* all else fails.
*/
if (vd != NULL) {
mg = vd->vdev_mg;
if (flags & METASLAB_HINTBP_AVOID &&
mg->mg_next != NULL)
mg = mg->mg_next;
} else {
mg = mc->mc_rotor;
}
} else if (d != 0) {
vd = vdev_lookup_top(spa, DVA_GET_VDEV(&dva[d - 1]));
mg = vd->vdev_mg->mg_next;
} else {
mg = mc->mc_rotor;
}
/*
* If the hint put us into the wrong metaslab class, or into a
* metaslab group that has been passivated, just follow the rotor.
*/
if (mg->mg_class != mc || mg->mg_activation_count <= 0)
mg = mc->mc_rotor;
rotor = mg;
top:
all_zero = B_TRUE;
do {
ASSERT(mg->mg_activation_count == 1);
vd = mg->mg_vd;
/*
* Don't allocate from faulted devices.
*/
if (zio_lock) {
spa_config_enter(spa, SCL_ZIO, FTAG, RW_READER);
allocatable = vdev_allocatable(vd);
spa_config_exit(spa, SCL_ZIO, FTAG);
} else {
allocatable = vdev_allocatable(vd);
}
/*
* Determine if the selected metaslab group is eligible
* for allocations. If we're ganging or have requested
* an allocation for the smallest gang block size
* then we don't want to avoid allocating to the this
* metaslab group. If we're in this condition we should
* try to allocate from any device possible so that we
* don't inadvertently return ENOSPC and suspend the pool
* even though space is still available.
*/
if (allocatable && CAN_FASTGANG(flags) &&
psize > SPA_GANGBLOCKSIZE)
allocatable = metaslab_group_allocatable(mg);
if (!allocatable)
goto next;
/*
* Avoid writing single-copy data to a failing vdev
* unless the user instructs us that it is okay.
*/
if ((vd->vdev_stat.vs_write_errors > 0 ||
vd->vdev_state < VDEV_STATE_HEALTHY) &&
d == 0 && dshift == 3 &&
!(zfs_write_to_degraded && vd->vdev_state ==
VDEV_STATE_DEGRADED)) {
all_zero = B_FALSE;
goto next;
}
ASSERT(mg->mg_class == mc);
distance = vd->vdev_asize >> dshift;
if (distance <= (1ULL << vd->vdev_ms_shift))
distance = 0;
else
all_zero = B_FALSE;
asize = vdev_psize_to_asize(vd, psize);
ASSERT(P2PHASE(asize, 1ULL << vd->vdev_ashift) == 0);
offset = metaslab_group_alloc(mg, psize, asize, txg, distance,
dva, d);
if (offset != -1ULL) {
/*
* If we've just selected this metaslab group,
* figure out whether the corresponding vdev is
* over- or under-used relative to the pool,
* and set an allocation bias to even it out.
*/
if (mc->mc_aliquot == 0) {
vdev_stat_t *vs = &vd->vdev_stat;
int64_t vu, cu;
vu = (vs->vs_alloc * 100) / (vs->vs_space + 1);
cu = (mc->mc_alloc * 100) / (mc->mc_space + 1);
/*
* Calculate how much more or less we should
* try to allocate from this device during
* this iteration around the rotor.
* For example, if a device is 80% full
* and the pool is 20% full then we should
* reduce allocations by 60% on this device.
*
* mg_bias = (20 - 80) * 512K / 100 = -307K
*
* This reduces allocations by 307K for this
* iteration.
*/
mg->mg_bias = ((cu - vu) *
(int64_t)mg->mg_aliquot) / 100;
}
if (atomic_add_64_nv(&mc->mc_aliquot, asize) >=
mg->mg_aliquot + mg->mg_bias) {
mc->mc_rotor = mg->mg_next;
mc->mc_aliquot = 0;
}
DVA_SET_VDEV(&dva[d], vd->vdev_id);
DVA_SET_OFFSET(&dva[d], offset);
DVA_SET_GANG(&dva[d], !!(flags & METASLAB_GANG_HEADER));
DVA_SET_ASIZE(&dva[d], asize);
return (0);
}
next:
mc->mc_rotor = mg->mg_next;
mc->mc_aliquot = 0;
} while ((mg = mg->mg_next) != rotor);
if (!all_zero) {
dshift++;
ASSERT(dshift < 64);
goto top;
}
if (!allocatable && !zio_lock) {
dshift = 3;
zio_lock = B_TRUE;
goto top;
}
bzero(&dva[d], sizeof (dva_t));
return (SET_ERROR(ENOSPC));
}
/*
* Free the block represented by DVA in the context of the specified
* transaction group.
*/
static void
metaslab_free_dva(spa_t *spa, const dva_t *dva, uint64_t txg, boolean_t now)
{
uint64_t vdev = DVA_GET_VDEV(dva);
uint64_t offset = DVA_GET_OFFSET(dva);
uint64_t size = DVA_GET_ASIZE(dva);
vdev_t *vd;
metaslab_t *msp;
ASSERT(DVA_IS_VALID(dva));
if (txg > spa_freeze_txg(spa))
return;
if ((vd = vdev_lookup_top(spa, vdev)) == NULL ||
(offset >> vd->vdev_ms_shift) >= vd->vdev_ms_count) {
cmn_err(CE_WARN, "metaslab_free_dva(): bad DVA %llu:%llu",
(u_longlong_t)vdev, (u_longlong_t)offset);
ASSERT(0);
return;
}
msp = vd->vdev_ms[offset >> vd->vdev_ms_shift];
if (DVA_GET_GANG(dva))
size = vdev_psize_to_asize(vd, SPA_GANGBLOCKSIZE);
mutex_enter(&msp->ms_lock);
if (now) {
range_tree_remove(msp->ms_alloctree[txg & TXG_MASK],
offset, size);
VERIFY(!msp->ms_condensing);
VERIFY3U(offset, >=, msp->ms_start);
VERIFY3U(offset + size, <=, msp->ms_start + msp->ms_size);
VERIFY3U(range_tree_space(msp->ms_tree) + size, <=,
msp->ms_size);
VERIFY0(P2PHASE(offset, 1ULL << vd->vdev_ashift));
VERIFY0(P2PHASE(size, 1ULL << vd->vdev_ashift));
range_tree_add(msp->ms_tree, offset, size);
} else {
if (range_tree_space(msp->ms_freetree[txg & TXG_MASK]) == 0)
vdev_dirty(vd, VDD_METASLAB, msp, txg);
range_tree_add(msp->ms_freetree[txg & TXG_MASK],
offset, size);
}
mutex_exit(&msp->ms_lock);
}
/*
* Intent log support: upon opening the pool after a crash, notify the SPA
* of blocks that the intent log has allocated for immediate write, but
* which are still considered free by the SPA because the last transaction
* group didn't commit yet.
*/
static int
metaslab_claim_dva(spa_t *spa, const dva_t *dva, uint64_t txg)
{
uint64_t vdev = DVA_GET_VDEV(dva);
uint64_t offset = DVA_GET_OFFSET(dva);
uint64_t size = DVA_GET_ASIZE(dva);
vdev_t *vd;
metaslab_t *msp;
int error = 0;
ASSERT(DVA_IS_VALID(dva));
if ((vd = vdev_lookup_top(spa, vdev)) == NULL ||
(offset >> vd->vdev_ms_shift) >= vd->vdev_ms_count)
return (SET_ERROR(ENXIO));
msp = vd->vdev_ms[offset >> vd->vdev_ms_shift];
if (DVA_GET_GANG(dva))
size = vdev_psize_to_asize(vd, SPA_GANGBLOCKSIZE);
mutex_enter(&msp->ms_lock);
if ((txg != 0 && spa_writeable(spa)) || !msp->ms_loaded)
error = metaslab_activate(msp, METASLAB_WEIGHT_SECONDARY);
if (error == 0 && !range_tree_contains(msp->ms_tree, offset, size))
error = SET_ERROR(ENOENT);
if (error || txg == 0) { /* txg == 0 indicates dry run */
mutex_exit(&msp->ms_lock);
return (error);
}
VERIFY(!msp->ms_condensing);
VERIFY0(P2PHASE(offset, 1ULL << vd->vdev_ashift));
VERIFY0(P2PHASE(size, 1ULL << vd->vdev_ashift));
VERIFY3U(range_tree_space(msp->ms_tree) - size, <=, msp->ms_size);
range_tree_remove(msp->ms_tree, offset, size);
if (spa_writeable(spa)) { /* don't dirty if we're zdb(1M) */
if (range_tree_space(msp->ms_alloctree[txg & TXG_MASK]) == 0)
vdev_dirty(vd, VDD_METASLAB, msp, txg);
range_tree_add(msp->ms_alloctree[txg & TXG_MASK], offset, size);
}
mutex_exit(&msp->ms_lock);
return (0);
}
int
metaslab_alloc(spa_t *spa, metaslab_class_t *mc, uint64_t psize, blkptr_t *bp,
int ndvas, uint64_t txg, blkptr_t *hintbp, int flags)
{
dva_t *dva = bp->blk_dva;
dva_t *hintdva = hintbp->blk_dva;
int error = 0;
ASSERT(bp->blk_birth == 0);
ASSERT(BP_PHYSICAL_BIRTH(bp) == 0);
spa_config_enter(spa, SCL_ALLOC, FTAG, RW_READER);
if (mc->mc_rotor == NULL) { /* no vdevs in this class */
spa_config_exit(spa, SCL_ALLOC, FTAG);
return (SET_ERROR(ENOSPC));
}
ASSERT(ndvas > 0 && ndvas <= spa_max_replication(spa));
ASSERT(BP_GET_NDVAS(bp) == 0);
ASSERT(hintbp == NULL || ndvas <= BP_GET_NDVAS(hintbp));
for (int d = 0; d < ndvas; d++) {
error = metaslab_alloc_dva(spa, mc, psize, dva, d, hintdva,
txg, flags);
if (error != 0) {
for (d--; d >= 0; d--) {
metaslab_free_dva(spa, &dva[d], txg, B_TRUE);
bzero(&dva[d], sizeof (dva_t));
}
spa_config_exit(spa, SCL_ALLOC, FTAG);
return (error);
}
}
ASSERT(error == 0);
ASSERT(BP_GET_NDVAS(bp) == ndvas);
spa_config_exit(spa, SCL_ALLOC, FTAG);
BP_SET_BIRTH(bp, txg, txg);
return (0);
}
void
metaslab_free(spa_t *spa, const blkptr_t *bp, uint64_t txg, boolean_t now)
{
const dva_t *dva = bp->blk_dva;
int ndvas = BP_GET_NDVAS(bp);
ASSERT(!BP_IS_HOLE(bp));
ASSERT(!now || bp->blk_birth >= spa_syncing_txg(spa));
spa_config_enter(spa, SCL_FREE, FTAG, RW_READER);
for (int d = 0; d < ndvas; d++)
metaslab_free_dva(spa, &dva[d], txg, now);
spa_config_exit(spa, SCL_FREE, FTAG);
}
int
metaslab_claim(spa_t *spa, const blkptr_t *bp, uint64_t txg)
{
const dva_t *dva = bp->blk_dva;
int ndvas = BP_GET_NDVAS(bp);
int error = 0;
ASSERT(!BP_IS_HOLE(bp));
if (txg != 0) {
/*
* First do a dry run to make sure all DVAs are claimable,
* so we don't have to unwind from partial failures below.
*/
if ((error = metaslab_claim(spa, bp, 0)) != 0)
return (error);
}
spa_config_enter(spa, SCL_ALLOC, FTAG, RW_READER);
for (int d = 0; d < ndvas; d++)
if ((error = metaslab_claim_dva(spa, &dva[d], txg)) != 0)
break;
spa_config_exit(spa, SCL_ALLOC, FTAG);
ASSERT(error == 0 || txg == 0);
return (error);
}
void
metaslab_check_free(spa_t *spa, const blkptr_t *bp)
{
if ((zfs_flags & ZFS_DEBUG_ZIO_FREE) == 0)
return;
spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
for (int i = 0; i < BP_GET_NDVAS(bp); i++) {
uint64_t vdev = DVA_GET_VDEV(&bp->blk_dva[i]);
vdev_t *vd = vdev_lookup_top(spa, vdev);
uint64_t offset = DVA_GET_OFFSET(&bp->blk_dva[i]);
uint64_t size = DVA_GET_ASIZE(&bp->blk_dva[i]);
metaslab_t *msp = vd->vdev_ms[offset >> vd->vdev_ms_shift];
if (msp->ms_loaded)
range_tree_verify(msp->ms_tree, offset, size);
for (int j = 0; j < TXG_SIZE; j++)
range_tree_verify(msp->ms_freetree[j], offset, size);
for (int j = 0; j < TXG_DEFER_SIZE; j++)
range_tree_verify(msp->ms_defertree[j], offset, size);
}
spa_config_exit(spa, SCL_VDEV, FTAG);
}
| 28.602812 | 131 | 0.688111 | [
"object"
] |
64ab1e621a13a80794cf56ec13ed15a8b5ae67ef | 43,787 | h | C | groups/bsl/bslstl/bslstl_stack_cpp03.h | AlisdairM/bde | bc65db208c32513aa545080f57090cc39c608be0 | [
"Apache-2.0"
] | null | null | null | groups/bsl/bslstl/bslstl_stack_cpp03.h | AlisdairM/bde | bc65db208c32513aa545080f57090cc39c608be0 | [
"Apache-2.0"
] | null | null | null | groups/bsl/bslstl/bslstl_stack_cpp03.h | AlisdairM/bde | bc65db208c32513aa545080f57090cc39c608be0 | [
"Apache-2.0"
] | null | null | null | // bslstl_stack_cpp03.h -*-C++-*-
// Automatically generated file. **DO NOT EDIT**
#ifndef INCLUDED_BSLSTL_STACK_CPP03
#define INCLUDED_BSLSTL_STACK_CPP03
//@PURPOSE: Provide C++03 implementation for bslstl_stack.h
//
//@CLASSES: See bslstl_stack.h for list of classes
//
//@SEE_ALSO: bslstl_stack
//
//@DESCRIPTION: This component is the C++03 translation of a C++11 component,
// generated by the 'sim_cpp11_features.pl' program. If the original header
// contains any specially delimited regions of C++11 code, then this generated
// file contains the C++03 equivalent, i.e., with variadic templates expanded
// and rvalue-references replaced by 'bslmf::MovableRef' objects. The header
// code in this file is designed to be '#include'd into the original header
// when compiling with a C++03 compiler. If there are no specially delimited
// regions of C++11 code, then this header contains no code and is not
// '#include'd in the original header.
//
// Generated on Wed Dec 1 08:45:19 2021
// Command line: sim_cpp11_features.pl bslstl_stack.h
#ifdef COMPILING_BSLSTL_STACK_H
namespace bsl {
// ===========
// class stack
// ===========
template <class VALUE, class CONTAINER = deque<VALUE> >
class stack {
// This 'class' defines a container adapter which supports access primarily
// via 'push', 'pop', and 'top'. This type can be based on a variety of
// other container types, including 'deque', 'vector', and 'list'. This
// type is value-semantic if the supporting 'CONTAINER' and 'VALUE' are
// value-semantic.
//
// Note that we never use 'VALUE' in the implementation except in the
// default argument of 'CONTAINER'. We use 'CONTAINER::value_type' for
// everything, which means that if 'CONTAINER' is specified, then 'VALUE'
// is ignored.
private:
// PRIVATE TYPES
typedef BloombergLP::bslmf::MovableRefUtil MoveUtil;
// This 'typedef' is a convenient alias for the utility associated with
// movable references.
public:
// PUBLIC TYPES
typedef typename CONTAINER::value_type value_type;
typedef typename CONTAINER::reference reference;
typedef typename CONTAINER::const_reference const_reference;
typedef typename CONTAINER::size_type size_type;
typedef CONTAINER container_type;
protected:
// PROTECTED DATA
container_type c; // We are required by the standard to have the
// container be a protected variable named 'c'.
private:
// FRIENDS
template <class VAL, class CONT>
friend bool operator==(const stack<VAL, CONT>&, const stack<VAL, CONT>&);
template <class VAL, class CONT>
friend bool operator!=(const stack<VAL, CONT>&, const stack<VAL, CONT>&);
template <class VAL, class CONT>
friend bool operator< (const stack<VAL, CONT>&, const stack<VAL, CONT>&);
template <class VAL, class CONT>
friend bool operator> (const stack<VAL, CONT>&, const stack<VAL, CONT>&);
template <class VAL, class CONT>
friend bool operator<=(const stack<VAL, CONT>&, const stack<VAL, CONT>&);
template <class VAL, class CONT>
friend bool operator>=(const stack<VAL, CONT>&, const stack<VAL, CONT>&);
public:
// TRAITS
BSLMF_NESTED_TRAIT_DECLARATION_IF(
stack,
BloombergLP::bslma::UsesBslmaAllocator,
BloombergLP::bslma::UsesBslmaAllocator<container_type>::value);
// CREATORS
explicit stack();
// Create an empty stack. No allocator will be provided to the
// underlying container. That container's memory allocation will be
// provided by the default allocator of its type.
stack(const stack& original);
// Create a stack having the value of the specified 'original'. The
// currently installed default allocator is used to supply memory.
stack(BloombergLP::bslmf::MovableRef<stack> original);
// Create a stack having the value of the specified 'original' by
// moving the contents of 'original' to the new stack. The allocator
// associated with 'original' is propagated for use in the new stack.
// 'original' is left in a valid but unspecified state.
explicit
stack(const CONTAINER& container);
// Create a stack whose underlying container has the value of the
// specified 'container'. The currently installed default allocator is
// used to supply memory.
explicit
stack(BloombergLP::bslmf::MovableRef<CONTAINER> container);
// Create a stack whose underlying container has the value of the
// specified 'container' (on entry) by moving the contents of
// 'container' to the new stack. The allocator associated with
// 'container' is propagated for use in the new stack. 'container' is
// left in a valid but unspecified state.
template <class ALLOCATOR>
explicit
stack(const ALLOCATOR& basicAllocator,
typename enable_if<bsl::uses_allocator<CONTAINER, ALLOCATOR>::value,
ALLOCATOR>::type * = 0);
// Create an empty stack, and use the specified 'basicAllocator' to
// supply memory. If 'CONTAINER::allocator_type' does not exist, this
// constructor may not be used.
template <class ALLOCATOR>
stack(const CONTAINER& container,
const ALLOCATOR& basicAllocator,
typename enable_if<bsl::uses_allocator<CONTAINER, ALLOCATOR>::value,
ALLOCATOR>::type * = 0);
// Create a stack whose underlying container has the value of the
// specified 'container', and use the specified 'basicAllocator' to
// supply memory. If 'CONTAINER::allocator_type' does not exist, this
// constructor may not be used.
template <class ALLOCATOR>
stack(const stack& original,
const ALLOCATOR& basicAllocator,
typename enable_if<bsl::uses_allocator<CONTAINER, ALLOCATOR>::value,
ALLOCATOR>::type * = 0);
// Create a stack having the value of the specified stack 'original'
// and use the specified 'basicAllocator' to supply memory. If
// 'CONTAINER::allocator_type' does not exist, this constructor may not
// be used.
template <class ALLOCATOR>
stack(BloombergLP::bslmf::MovableRef<CONTAINER> container,
const ALLOCATOR& basicAllocator,
typename enable_if<bsl::uses_allocator<CONTAINER, ALLOCATOR>::value,
ALLOCATOR>::type * = 0);
// Create a stack whose underlying container has the value of the
// specified 'container' (on entry) that uses 'basicAllocator' to
// supply memory by using the allocator-extended move constructor of
// 'CONTAINER. 'container' is left in a valid but unspecified state.
// A 'bslma::Allocator *' can be supplied for 'basicAllocator' if the
// (template parameter) 'ALLOCATOR' is 'bsl::allocator' (the default).
// This method assumes that 'CONTAINER' has a move constructor. If
// 'CONTAINER::allocator_type' does not exist, this constructor may not
// be used.
template <class ALLOCATOR>
stack(BloombergLP::bslmf::MovableRef<stack> original,
const ALLOCATOR& basicAllocator,
typename enable_if<bsl::uses_allocator<CONTAINER, ALLOCATOR>::value,
ALLOCATOR>::type * = 0);
// Create a stack having the value of the specified 'original' (on
// entry) that uses 'basicAllocator' to supply memory by using the
// allocator-extended moved constructor of 'CONTAINER'. 'original' is
// left in a valid but unspecified state. Note that a
// 'bslma::Allocator *' can be supplied for 'basicAllocator' if the
// (template parameter) 'ALLOCATOR' is 'bsl::allocator' (the default).
// Also note that this method assumes that 'CONTAINER' has a move
// constructor. Also note that if 'CONTAINER::allocator_type' does not
// exist, this constructor may not be used.
// MANIPULATORS
stack& operator=(const stack& rhs);
// Assign to this object the value of the specified 'rhs' object, and
// return a reference providing modifiable access to this object.
stack& operator=(BloombergLP::bslmf::MovableRef<stack> rhs)
BSLS_KEYWORD_NOEXCEPT_SPECIFICATION(false);
// Assign to this object the value of the specified 'rhs' object, and
// return a reference providing modifiable access to this object. The
// contents of 'rhs' are moved to this stack using the move-assignment
// operator of 'CONTAINER'. 'rhs' is left in a valid but unspecified
// state, and if an exception is thrown, '*this' is left in a valid but
// unspecified state.
#if BSLS_COMPILERFEATURES_SIMULATE_VARIADIC_TEMPLATES
// {{{ BEGIN GENERATED CODE
// Command line: sim_cpp11_features.pl bslstl_stack.h
#ifndef BSLSTL_STACK_VARIADIC_LIMIT
#define BSLSTL_STACK_VARIADIC_LIMIT 10
#endif
#ifndef BSLSTL_STACK_VARIADIC_LIMIT_A
#define BSLSTL_STACK_VARIADIC_LIMIT_A BSLSTL_STACK_VARIADIC_LIMIT
#endif
#if BSLSTL_STACK_VARIADIC_LIMIT_A >= 0
reference emplace();
#endif // BSLSTL_STACK_VARIADIC_LIMIT_A >= 0
#if BSLSTL_STACK_VARIADIC_LIMIT_A >= 1
template <class Args_01>
reference emplace(BSLS_COMPILERFEATURES_FORWARD_REF(Args_01) args_01);
#endif // BSLSTL_STACK_VARIADIC_LIMIT_A >= 1
#if BSLSTL_STACK_VARIADIC_LIMIT_A >= 2
template <class Args_01,
class Args_02>
reference emplace(BSLS_COMPILERFEATURES_FORWARD_REF(Args_01) args_01,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_02) args_02);
#endif // BSLSTL_STACK_VARIADIC_LIMIT_A >= 2
#if BSLSTL_STACK_VARIADIC_LIMIT_A >= 3
template <class Args_01,
class Args_02,
class Args_03>
reference emplace(BSLS_COMPILERFEATURES_FORWARD_REF(Args_01) args_01,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_02) args_02,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_03) args_03);
#endif // BSLSTL_STACK_VARIADIC_LIMIT_A >= 3
#if BSLSTL_STACK_VARIADIC_LIMIT_A >= 4
template <class Args_01,
class Args_02,
class Args_03,
class Args_04>
reference emplace(BSLS_COMPILERFEATURES_FORWARD_REF(Args_01) args_01,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_02) args_02,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_03) args_03,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_04) args_04);
#endif // BSLSTL_STACK_VARIADIC_LIMIT_A >= 4
#if BSLSTL_STACK_VARIADIC_LIMIT_A >= 5
template <class Args_01,
class Args_02,
class Args_03,
class Args_04,
class Args_05>
reference emplace(BSLS_COMPILERFEATURES_FORWARD_REF(Args_01) args_01,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_02) args_02,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_03) args_03,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_04) args_04,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_05) args_05);
#endif // BSLSTL_STACK_VARIADIC_LIMIT_A >= 5
#if BSLSTL_STACK_VARIADIC_LIMIT_A >= 6
template <class Args_01,
class Args_02,
class Args_03,
class Args_04,
class Args_05,
class Args_06>
reference emplace(BSLS_COMPILERFEATURES_FORWARD_REF(Args_01) args_01,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_02) args_02,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_03) args_03,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_04) args_04,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_05) args_05,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_06) args_06);
#endif // BSLSTL_STACK_VARIADIC_LIMIT_A >= 6
#if BSLSTL_STACK_VARIADIC_LIMIT_A >= 7
template <class Args_01,
class Args_02,
class Args_03,
class Args_04,
class Args_05,
class Args_06,
class Args_07>
reference emplace(BSLS_COMPILERFEATURES_FORWARD_REF(Args_01) args_01,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_02) args_02,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_03) args_03,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_04) args_04,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_05) args_05,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_06) args_06,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_07) args_07);
#endif // BSLSTL_STACK_VARIADIC_LIMIT_A >= 7
#if BSLSTL_STACK_VARIADIC_LIMIT_A >= 8
template <class Args_01,
class Args_02,
class Args_03,
class Args_04,
class Args_05,
class Args_06,
class Args_07,
class Args_08>
reference emplace(BSLS_COMPILERFEATURES_FORWARD_REF(Args_01) args_01,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_02) args_02,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_03) args_03,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_04) args_04,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_05) args_05,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_06) args_06,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_07) args_07,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_08) args_08);
#endif // BSLSTL_STACK_VARIADIC_LIMIT_A >= 8
#if BSLSTL_STACK_VARIADIC_LIMIT_A >= 9
template <class Args_01,
class Args_02,
class Args_03,
class Args_04,
class Args_05,
class Args_06,
class Args_07,
class Args_08,
class Args_09>
reference emplace(BSLS_COMPILERFEATURES_FORWARD_REF(Args_01) args_01,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_02) args_02,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_03) args_03,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_04) args_04,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_05) args_05,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_06) args_06,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_07) args_07,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_08) args_08,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_09) args_09);
#endif // BSLSTL_STACK_VARIADIC_LIMIT_A >= 9
#if BSLSTL_STACK_VARIADIC_LIMIT_A >= 10
template <class Args_01,
class Args_02,
class Args_03,
class Args_04,
class Args_05,
class Args_06,
class Args_07,
class Args_08,
class Args_09,
class Args_10>
reference emplace(BSLS_COMPILERFEATURES_FORWARD_REF(Args_01) args_01,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_02) args_02,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_03) args_03,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_04) args_04,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_05) args_05,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_06) args_06,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_07) args_07,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_08) args_08,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_09) args_09,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_10) args_10);
#endif // BSLSTL_STACK_VARIADIC_LIMIT_A >= 10
#else
// The generated code below is a workaround for the absence of perfect
// forwarding in some compilers.
template <class... Args>
reference emplace(BSLS_COMPILERFEATURES_FORWARD_REF(Args)... args);
// }}} END GENERATED CODE
#endif
void pop();
// Remove the top element from this stack. The behavior is undefined
// if this stack is empty.
void push(const value_type& value);
// Push the specified 'value' onto the top of this stack.
void push(BloombergLP::bslmf::MovableRef<value_type> value);
// Push onto this stack a 'value_type' object having the value of the
// specified 'value' (on entry) by moving the contents of 'value' to
// the new object on this stack. 'value' is left in a valid but
// unspecified state.
void swap(stack& other) BSLS_KEYWORD_NOEXCEPT_SPECIFICATION(false);
// Exchange the value of this stack with the value of the specified
// 'other' stack.
reference top();
// Return a reference to the element at the top of this stack. The
// behavior is undefined if this stack is empty.
// ACCESSORS
bool empty() const;
// Return 'true' if this stack contains no elements and 'false'
// otherwise.
size_type size() const;
// Return the number of elements contained in this stack.
const_reference top() const;
// Return a reference providing non-modifiable access to the element at
// the top of this stack. The behavior is undefined if the stack is
// empty.
};
#ifdef BSLS_COMPILERFEATURES_SUPPORT_CTAD
// CLASS TEMPLATE DEDUCTION GUIDES
template<class CONTAINER,
class = bsl::enable_if_t<!bsl::IsStdAllocator_v<CONTAINER>>
>
stack(CONTAINER) -> stack<typename CONTAINER::value_type, CONTAINER>;
// Deduce the template parameters 'VALUE' and 'CONTAINER' from the
// parameters supplied to the constructor of 'stack'. This deduction guide
// does not participate if the parameter meets the requirements for a
// standard allocator.
template<
class CONTAINER,
class ALLOCATOR,
class = bsl::enable_if_t<bsl::uses_allocator<CONTAINER, ALLOCATOR>::value>
>
stack(CONTAINER, ALLOCATOR)
-> stack<typename CONTAINER::value_type, CONTAINER>;
// Deduce the template parameters 'VALUE' and 'CONTAINER' from the
// parameters supplied to the constructor of 'stack'. This deduction guide
// does not participate if the specified 'CONTAINER' is not an
// allocator-aware container.
template<
class CONTAINER,
class ALLOC,
class ALLOCATOR = typename CONTAINER::allocator_type,
class = bsl::enable_if_t<bsl::is_convertible<ALLOC *, ALLOCATOR>::value>
>
stack(CONTAINER, ALLOC *) -> stack<typename CONTAINER::value_type, CONTAINER>;
// Deduce the template parameters 'VALUE' and 'CONTAINER' from the
// parameters supplied to the constructor of 'stack'. This deduction
// guide does not participate unless the supplied allocator is convertible
// to the underlying container's 'allocator_type'.
#endif
// FREE OPERATORS
template <class VALUE, class CONTAINER>
bool operator==(const stack<VALUE, CONTAINER>& lhs,
const stack<VALUE, CONTAINER>& rhs);
// Return 'true' if the specified 'lhs' and 'rhs' objects have the same
// value, and 'false' otherwise. Two 'stack' objects 'lhs' and 'rhs' have
// the same value if they have the same number of elements, and each
// element in the ordered sequence of elements of 'lhs' has the same value
// as the corresponding element in the ordered sequence of elements of
// 'rhs'. This method requires that the (template parameter) type 'VALUE'
// be 'equality-comparable' (see {Requirements on 'VALUE'}).
template <class VALUE, class CONTAINER>
bool operator!=(const stack<VALUE, CONTAINER>& lhs,
const stack<VALUE, CONTAINER>& rhs);
// Return 'true' if the specified 'lhs' and 'rhs' objects do not have the
// same value, and 'false' otherwise. Two 'stack' objects 'lhs' and 'rhs'
// do not have the same value if they do not have the same number of
// elements, or some element in the ordered sequence of elements of 'lhs'
// does not have the same value as the corresponding element in the ordered
// sequence of elements of 'rhs'. This method requires that the (template
// parameter) type 'VALUE' be 'equality-comparable' (see {Requirements on
// 'VALUE'}).
template <class VALUE, class CONTAINER>
bool operator< (const stack<VALUE, CONTAINER>& lhs,
const stack<VALUE, CONTAINER>& rhs);
// Return 'true' if the value of the specified 'lhs' stack is
// lexicographically less than that of the specified 'rhs' stack, and
// 'false' otherwise. Given iterators 'i' and 'j' over the respective
// sequences '[lhs.begin() .. lhs.end())' and '[rhs.begin() .. rhs.end())',
// the value of stack 'lhs' is lexicographically less than that of stack
// 'rhs' if 'true == *i < *j' for the first pair of corresponding iterator
// positions where '*i < *j' and '*j < *i' are not both 'false'. If no
// such corresponding iterator position exists, the value of 'lhs' is
// lexicographically less than that of 'rhs' if 'lhs.size() < rhs.size()'.
// This method requires that 'operator<', inducing a total order, be
// defined for 'value_type'.
template <class VALUE, class CONTAINER>
bool operator> (const stack<VALUE, CONTAINER>& lhs,
const stack<VALUE, CONTAINER>& rhs);
// Return 'true' if the value of the specified 'lhs' stack is
// lexicographically greater than that of the specified 'rhs' stack, and
// 'false' otherwise. The value of stack 'lhs' is lexicographically
// greater than that of stack 'rhs' if 'rhs' is lexicographically less than
// 'lhs' (see 'operator<'). This method requires that 'operator<',
// inducing a total order, be defined for 'value_type'. Note that this
// operator returns 'rhs < lhs'.
template <class VALUE, class CONTAINER>
bool operator<=(const stack<VALUE, CONTAINER>& lhs,
const stack<VALUE, CONTAINER>& rhs);
// Return 'true' if the value of the specified 'lhs' stack is
// lexicographically less than or equal to that of the specified 'rhs'
// stack, and 'false' otherwise. The value of stack 'lhs' is
// lexicographically less than or equal to that of stack 'rhs' if 'rhs' is
// not lexicographically less than 'lhs' (see 'operator<'). This method
// requires that 'operator<', inducing a total order, be defined for
// 'value_type'. Note that this operator returns '!(rhs < lhs)'.
template <class VALUE, class CONTAINER>
bool operator>=(const stack<VALUE, CONTAINER>& lhs,
const stack<VALUE, CONTAINER>& rhs);
// Return 'true' if the value of the specified 'lhs' stack is
// lexicographically greater than or equal to that of the specified 'rhs'
// stack, and 'false' otherwise. The value of stack 'lhs' is
// lexicographically greater than or equal to that of stack 'rhs' if 'lhs'
// is not lexicographically less than 'rhs' (see 'operator<'). This method
// requires that 'operator<', inducing a total order, be defined for
// 'value_type'. Note that this operator returns '!(lhs < rhs)'.
// FREE FUNCTIONS
template <class VALUE, class CONTAINER>
void swap(stack<VALUE, CONTAINER>& lhs,
stack<VALUE, CONTAINER>& rhs)
BSLS_KEYWORD_NOEXCEPT_SPECIFICATION(false);
// Swap the value of the specified 'lhs' stack with the value of the
// specified 'rhs' stack.
//=============================================================================
// TEMPLATE AND INLINE FUNCTION DEFINITIONS
//=============================================================================
// -----------
// class stack
// -----------
// CREATORS
template <class VALUE, class CONTAINER>
inline
stack<VALUE, CONTAINER>::stack()
: c()
{
}
template <class VALUE, class CONTAINER>
inline
stack<VALUE, CONTAINER>::stack(const CONTAINER& container)
: c(container)
{
}
template <class VALUE, class CONTAINER>
inline
stack<VALUE, CONTAINER>::stack(BloombergLP::bslmf::MovableRef<stack> original)
: c(MoveUtil::move(MoveUtil::access(original).c))
{
}
template <class VALUE, class CONTAINER>
template <class ALLOCATOR>
inline
stack<VALUE, CONTAINER>::stack(const ALLOCATOR& basicAllocator,
typename enable_if<bsl::uses_allocator<CONTAINER, ALLOCATOR>::value,
ALLOCATOR>::type *)
: c(basicAllocator)
{
}
template <class VALUE, class CONTAINER>
template <class ALLOCATOR>
inline
stack<VALUE, CONTAINER>::stack(
const CONTAINER& container,
const ALLOCATOR& basicAllocator,
typename enable_if<bsl::uses_allocator<CONTAINER, ALLOCATOR>::value,
ALLOCATOR>::type *)
: c(container, basicAllocator)
{
}
template <class VALUE, class CONTAINER>
inline
stack<VALUE, CONTAINER>::stack(const stack& original)
: c(original.c)
{
}
template <class VALUE, class CONTAINER>
template <class ALLOCATOR>
inline
stack<VALUE, CONTAINER>::stack(
const stack& original,
const ALLOCATOR& basicAllocator,
typename enable_if<bsl::uses_allocator<CONTAINER, ALLOCATOR>::value,
ALLOCATOR>::type *)
: c(original.c, basicAllocator)
{
}
template <class VALUE, class CONTAINER>
inline
stack<VALUE, CONTAINER>::stack(BloombergLP::bslmf::MovableRef<CONTAINER>
container)
: c(MoveUtil::move(container))
{
}
template <class VALUE, class CONTAINER>
template <class ALLOCATOR>
inline
stack<VALUE, CONTAINER>::stack(
BloombergLP::bslmf::MovableRef<CONTAINER> container,
const ALLOCATOR& basicAllocator,
typename enable_if<bsl::uses_allocator<CONTAINER, ALLOCATOR>::value,
ALLOCATOR>::type *)
: c(MoveUtil::move(container), basicAllocator)
{
}
template <class VALUE, class CONTAINER>
template <class ALLOCATOR>
inline
stack<VALUE, CONTAINER>::stack(
BloombergLP::bslmf::MovableRef<stack> original,
const ALLOCATOR& basicAllocator,
typename enable_if<bsl::uses_allocator<CONTAINER, ALLOCATOR>::value,
ALLOCATOR>::type *)
: c(MoveUtil::move(MoveUtil::access(original).c), basicAllocator)
{
}
// MANIPULATORS
template <class VALUE, class CONTAINER>
inline
stack<VALUE, CONTAINER>& stack<VALUE, CONTAINER>::operator=(const stack& rhs)
{
c = rhs.c;
return *this;
}
template <class VALUE, class CONTAINER>
inline
stack<VALUE, CONTAINER>& stack<VALUE, CONTAINER>::operator=(
BloombergLP::bslmf::MovableRef<stack> rhs)
BSLS_KEYWORD_NOEXCEPT_SPECIFICATION(false)
{
c = MoveUtil::move(MoveUtil::access(rhs).c);
return *this;
}
#if BSLS_COMPILERFEATURES_SIMULATE_VARIADIC_TEMPLATES
// {{{ BEGIN GENERATED CODE
// Command line: sim_cpp11_features.pl bslstl_stack.h
#ifndef BSLSTL_STACK_VARIADIC_LIMIT
#define BSLSTL_STACK_VARIADIC_LIMIT 10
#endif
#ifndef BSLSTL_STACK_VARIADIC_LIMIT_B
#define BSLSTL_STACK_VARIADIC_LIMIT_B BSLSTL_STACK_VARIADIC_LIMIT
#endif
#if BSLSTL_STACK_VARIADIC_LIMIT_B >= 0
template <class VALUE, class CONTAINER>
inline
typename stack<VALUE, CONTAINER>::reference
stack<VALUE, CONTAINER>::emplace(
)
{
c.emplace_back();
return top();
}
#endif // BSLSTL_STACK_VARIADIC_LIMIT_B >= 0
#if BSLSTL_STACK_VARIADIC_LIMIT_B >= 1
template <class VALUE, class CONTAINER>
template <class Args_01>
inline
typename stack<VALUE, CONTAINER>::reference
stack<VALUE, CONTAINER>::emplace(
BSLS_COMPILERFEATURES_FORWARD_REF(Args_01) args_01)
{
c.emplace_back(BSLS_COMPILERFEATURES_FORWARD(Args_01,args_01));
return top();
}
#endif // BSLSTL_STACK_VARIADIC_LIMIT_B >= 1
#if BSLSTL_STACK_VARIADIC_LIMIT_B >= 2
template <class VALUE, class CONTAINER>
template <class Args_01,
class Args_02>
inline
typename stack<VALUE, CONTAINER>::reference
stack<VALUE, CONTAINER>::emplace(
BSLS_COMPILERFEATURES_FORWARD_REF(Args_01) args_01,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_02) args_02)
{
c.emplace_back(BSLS_COMPILERFEATURES_FORWARD(Args_01,args_01),
BSLS_COMPILERFEATURES_FORWARD(Args_02,args_02));
return top();
}
#endif // BSLSTL_STACK_VARIADIC_LIMIT_B >= 2
#if BSLSTL_STACK_VARIADIC_LIMIT_B >= 3
template <class VALUE, class CONTAINER>
template <class Args_01,
class Args_02,
class Args_03>
inline
typename stack<VALUE, CONTAINER>::reference
stack<VALUE, CONTAINER>::emplace(
BSLS_COMPILERFEATURES_FORWARD_REF(Args_01) args_01,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_02) args_02,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_03) args_03)
{
c.emplace_back(BSLS_COMPILERFEATURES_FORWARD(Args_01,args_01),
BSLS_COMPILERFEATURES_FORWARD(Args_02,args_02),
BSLS_COMPILERFEATURES_FORWARD(Args_03,args_03));
return top();
}
#endif // BSLSTL_STACK_VARIADIC_LIMIT_B >= 3
#if BSLSTL_STACK_VARIADIC_LIMIT_B >= 4
template <class VALUE, class CONTAINER>
template <class Args_01,
class Args_02,
class Args_03,
class Args_04>
inline
typename stack<VALUE, CONTAINER>::reference
stack<VALUE, CONTAINER>::emplace(
BSLS_COMPILERFEATURES_FORWARD_REF(Args_01) args_01,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_02) args_02,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_03) args_03,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_04) args_04)
{
c.emplace_back(BSLS_COMPILERFEATURES_FORWARD(Args_01,args_01),
BSLS_COMPILERFEATURES_FORWARD(Args_02,args_02),
BSLS_COMPILERFEATURES_FORWARD(Args_03,args_03),
BSLS_COMPILERFEATURES_FORWARD(Args_04,args_04));
return top();
}
#endif // BSLSTL_STACK_VARIADIC_LIMIT_B >= 4
#if BSLSTL_STACK_VARIADIC_LIMIT_B >= 5
template <class VALUE, class CONTAINER>
template <class Args_01,
class Args_02,
class Args_03,
class Args_04,
class Args_05>
inline
typename stack<VALUE, CONTAINER>::reference
stack<VALUE, CONTAINER>::emplace(
BSLS_COMPILERFEATURES_FORWARD_REF(Args_01) args_01,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_02) args_02,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_03) args_03,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_04) args_04,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_05) args_05)
{
c.emplace_back(BSLS_COMPILERFEATURES_FORWARD(Args_01,args_01),
BSLS_COMPILERFEATURES_FORWARD(Args_02,args_02),
BSLS_COMPILERFEATURES_FORWARD(Args_03,args_03),
BSLS_COMPILERFEATURES_FORWARD(Args_04,args_04),
BSLS_COMPILERFEATURES_FORWARD(Args_05,args_05));
return top();
}
#endif // BSLSTL_STACK_VARIADIC_LIMIT_B >= 5
#if BSLSTL_STACK_VARIADIC_LIMIT_B >= 6
template <class VALUE, class CONTAINER>
template <class Args_01,
class Args_02,
class Args_03,
class Args_04,
class Args_05,
class Args_06>
inline
typename stack<VALUE, CONTAINER>::reference
stack<VALUE, CONTAINER>::emplace(
BSLS_COMPILERFEATURES_FORWARD_REF(Args_01) args_01,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_02) args_02,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_03) args_03,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_04) args_04,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_05) args_05,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_06) args_06)
{
c.emplace_back(BSLS_COMPILERFEATURES_FORWARD(Args_01,args_01),
BSLS_COMPILERFEATURES_FORWARD(Args_02,args_02),
BSLS_COMPILERFEATURES_FORWARD(Args_03,args_03),
BSLS_COMPILERFEATURES_FORWARD(Args_04,args_04),
BSLS_COMPILERFEATURES_FORWARD(Args_05,args_05),
BSLS_COMPILERFEATURES_FORWARD(Args_06,args_06));
return top();
}
#endif // BSLSTL_STACK_VARIADIC_LIMIT_B >= 6
#if BSLSTL_STACK_VARIADIC_LIMIT_B >= 7
template <class VALUE, class CONTAINER>
template <class Args_01,
class Args_02,
class Args_03,
class Args_04,
class Args_05,
class Args_06,
class Args_07>
inline
typename stack<VALUE, CONTAINER>::reference
stack<VALUE, CONTAINER>::emplace(
BSLS_COMPILERFEATURES_FORWARD_REF(Args_01) args_01,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_02) args_02,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_03) args_03,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_04) args_04,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_05) args_05,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_06) args_06,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_07) args_07)
{
c.emplace_back(BSLS_COMPILERFEATURES_FORWARD(Args_01,args_01),
BSLS_COMPILERFEATURES_FORWARD(Args_02,args_02),
BSLS_COMPILERFEATURES_FORWARD(Args_03,args_03),
BSLS_COMPILERFEATURES_FORWARD(Args_04,args_04),
BSLS_COMPILERFEATURES_FORWARD(Args_05,args_05),
BSLS_COMPILERFEATURES_FORWARD(Args_06,args_06),
BSLS_COMPILERFEATURES_FORWARD(Args_07,args_07));
return top();
}
#endif // BSLSTL_STACK_VARIADIC_LIMIT_B >= 7
#if BSLSTL_STACK_VARIADIC_LIMIT_B >= 8
template <class VALUE, class CONTAINER>
template <class Args_01,
class Args_02,
class Args_03,
class Args_04,
class Args_05,
class Args_06,
class Args_07,
class Args_08>
inline
typename stack<VALUE, CONTAINER>::reference
stack<VALUE, CONTAINER>::emplace(
BSLS_COMPILERFEATURES_FORWARD_REF(Args_01) args_01,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_02) args_02,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_03) args_03,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_04) args_04,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_05) args_05,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_06) args_06,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_07) args_07,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_08) args_08)
{
c.emplace_back(BSLS_COMPILERFEATURES_FORWARD(Args_01,args_01),
BSLS_COMPILERFEATURES_FORWARD(Args_02,args_02),
BSLS_COMPILERFEATURES_FORWARD(Args_03,args_03),
BSLS_COMPILERFEATURES_FORWARD(Args_04,args_04),
BSLS_COMPILERFEATURES_FORWARD(Args_05,args_05),
BSLS_COMPILERFEATURES_FORWARD(Args_06,args_06),
BSLS_COMPILERFEATURES_FORWARD(Args_07,args_07),
BSLS_COMPILERFEATURES_FORWARD(Args_08,args_08));
return top();
}
#endif // BSLSTL_STACK_VARIADIC_LIMIT_B >= 8
#if BSLSTL_STACK_VARIADIC_LIMIT_B >= 9
template <class VALUE, class CONTAINER>
template <class Args_01,
class Args_02,
class Args_03,
class Args_04,
class Args_05,
class Args_06,
class Args_07,
class Args_08,
class Args_09>
inline
typename stack<VALUE, CONTAINER>::reference
stack<VALUE, CONTAINER>::emplace(
BSLS_COMPILERFEATURES_FORWARD_REF(Args_01) args_01,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_02) args_02,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_03) args_03,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_04) args_04,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_05) args_05,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_06) args_06,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_07) args_07,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_08) args_08,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_09) args_09)
{
c.emplace_back(BSLS_COMPILERFEATURES_FORWARD(Args_01,args_01),
BSLS_COMPILERFEATURES_FORWARD(Args_02,args_02),
BSLS_COMPILERFEATURES_FORWARD(Args_03,args_03),
BSLS_COMPILERFEATURES_FORWARD(Args_04,args_04),
BSLS_COMPILERFEATURES_FORWARD(Args_05,args_05),
BSLS_COMPILERFEATURES_FORWARD(Args_06,args_06),
BSLS_COMPILERFEATURES_FORWARD(Args_07,args_07),
BSLS_COMPILERFEATURES_FORWARD(Args_08,args_08),
BSLS_COMPILERFEATURES_FORWARD(Args_09,args_09));
return top();
}
#endif // BSLSTL_STACK_VARIADIC_LIMIT_B >= 9
#if BSLSTL_STACK_VARIADIC_LIMIT_B >= 10
template <class VALUE, class CONTAINER>
template <class Args_01,
class Args_02,
class Args_03,
class Args_04,
class Args_05,
class Args_06,
class Args_07,
class Args_08,
class Args_09,
class Args_10>
inline
typename stack<VALUE, CONTAINER>::reference
stack<VALUE, CONTAINER>::emplace(
BSLS_COMPILERFEATURES_FORWARD_REF(Args_01) args_01,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_02) args_02,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_03) args_03,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_04) args_04,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_05) args_05,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_06) args_06,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_07) args_07,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_08) args_08,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_09) args_09,
BSLS_COMPILERFEATURES_FORWARD_REF(Args_10) args_10)
{
c.emplace_back(BSLS_COMPILERFEATURES_FORWARD(Args_01,args_01),
BSLS_COMPILERFEATURES_FORWARD(Args_02,args_02),
BSLS_COMPILERFEATURES_FORWARD(Args_03,args_03),
BSLS_COMPILERFEATURES_FORWARD(Args_04,args_04),
BSLS_COMPILERFEATURES_FORWARD(Args_05,args_05),
BSLS_COMPILERFEATURES_FORWARD(Args_06,args_06),
BSLS_COMPILERFEATURES_FORWARD(Args_07,args_07),
BSLS_COMPILERFEATURES_FORWARD(Args_08,args_08),
BSLS_COMPILERFEATURES_FORWARD(Args_09,args_09),
BSLS_COMPILERFEATURES_FORWARD(Args_10,args_10));
return top();
}
#endif // BSLSTL_STACK_VARIADIC_LIMIT_B >= 10
#else
// The generated code below is a workaround for the absence of perfect
// forwarding in some compilers.
template <class VALUE, class CONTAINER>
template <class... Args>
inline
typename stack<VALUE, CONTAINER>::reference
stack<VALUE, CONTAINER>::emplace(
BSLS_COMPILERFEATURES_FORWARD_REF(Args)... args)
{
c.emplace_back(BSLS_COMPILERFEATURES_FORWARD(Args,args)...);
return top();
}
// }}} END GENERATED CODE
#endif
template <class VALUE, class CONTAINER>
inline
void stack<VALUE, CONTAINER>::pop()
{
BSLS_ASSERT_SAFE(!empty());
c.pop_back();
}
template <class VALUE, class CONTAINER>
inline
void stack<VALUE, CONTAINER>::push(const value_type& value)
{
c.push_back(value);
}
template <class VALUE, class CONTAINER>
inline
void stack<VALUE, CONTAINER>::push(BloombergLP::bslmf::MovableRef<value_type>
value)
{
c.push_back(MoveUtil::move(value));
}
template <class VALUE, class CONTAINER>
inline
void stack<VALUE, CONTAINER>::swap(stack& other)
BSLS_KEYWORD_NOEXCEPT_SPECIFICATION(false)
{
BloombergLP::bslalg::SwapUtil::swap(&c, &other.c);
}
template <class VALUE, class CONTAINER>
inline
typename CONTAINER::reference stack<VALUE, CONTAINER>::top()
{
BSLS_ASSERT_SAFE(!empty());
return c.back();
}
// ACCESSORS
template <class VALUE, class CONTAINER>
inline
bool stack<VALUE, CONTAINER>::empty() const
{
return 0 == c.size();
}
template <class VALUE, class CONTAINER>
inline
typename CONTAINER::size_type stack<VALUE, CONTAINER>::size() const
{
return c.size();
}
template <class VALUE, class CONTAINER>
inline
typename CONTAINER::const_reference stack<VALUE, CONTAINER>::top() const
{
return c.back();
}
// FREE OPERATORS
template <class VALUE, class CONTAINER>
inline
bool operator==(const stack<VALUE, CONTAINER>& lhs,
const stack<VALUE, CONTAINER>& rhs)
{
return lhs.c == rhs.c;
}
template <class VALUE, class CONTAINER>
inline
bool operator!=(const stack<VALUE, CONTAINER>& lhs,
const stack<VALUE, CONTAINER>& rhs)
{
return lhs.c != rhs.c;
}
template <class VALUE, class CONTAINER>
inline
bool operator< (const stack<VALUE, CONTAINER>& lhs,
const stack<VALUE, CONTAINER>& rhs)
{
return lhs.c < rhs.c;
}
template <class VALUE, class CONTAINER>
inline
bool operator> (const stack<VALUE, CONTAINER>& lhs,
const stack<VALUE, CONTAINER>& rhs)
{
return lhs.c > rhs.c;
}
template <class VALUE, class CONTAINER>
inline
bool operator<=(const stack<VALUE, CONTAINER>& lhs,
const stack<VALUE, CONTAINER>& rhs)
{
return lhs.c <= rhs.c;
}
template <class VALUE, class CONTAINER>
inline
bool operator>=(const stack<VALUE, CONTAINER>& lhs,
const stack<VALUE, CONTAINER>& rhs)
{
return lhs.c >= rhs.c;
}
// FREE FUNCTIONS
template <class VALUE, class CONTAINER>
inline
void swap(stack<VALUE, CONTAINER>& lhs,
stack<VALUE, CONTAINER>& rhs)
BSLS_KEYWORD_NOEXCEPT_SPECIFICATION(false)
{
lhs.swap(rhs);
}
} // close namespace bsl
#else // if ! defined(DEFINED_BSLSTL_STACK_H)
# error Not valid except when included from bslstl_stack.h
#endif // ! defined(COMPILING_BSLSTL_STACK_H)
#endif // ! defined(INCLUDED_BSLSTL_STACK_CPP03)
// ----------------------------------------------------------------------------
// Copyright 2021 Bloomberg Finance L.P.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------- END-OF-FILE ----------------------------------
| 40.694238 | 79 | 0.652477 | [
"object",
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.