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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d050183eb7838bed803995985383e0ee4e9731a1 | 1,698 | h | C | paddle/legacy/gserver/layers/CudnnConvBaseLayer.h | jerrywgz/Paddle | 85c4912755b783dd7554a9d6b9dae4a7e40371bc | [
"Apache-2.0"
] | 9 | 2017-12-04T02:58:01.000Z | 2020-12-03T14:46:30.000Z | paddle/legacy/gserver/layers/CudnnConvBaseLayer.h | jerrywgz/Paddle | 85c4912755b783dd7554a9d6b9dae4a7e40371bc | [
"Apache-2.0"
] | 7 | 2017-12-05T20:29:08.000Z | 2018-10-15T08:57:40.000Z | paddle/legacy/gserver/layers/CudnnConvBaseLayer.h | jerrywgz/Paddle | 85c4912755b783dd7554a9d6b9dae4a7e40371bc | [
"Apache-2.0"
] | 6 | 2018-03-19T22:38:46.000Z | 2019-11-01T22:28:27.000Z | /* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
#pragma once
#include <vector>
#include "ConvBaseLayer.h"
#include "Projection.h"
#include "paddle/legacy/math/Matrix.h"
namespace paddle {
/**
* @brief A 2-dimension conv layer implemented by cuDNN. It only
* supports GPU mode. We automatic select CudnnConvLayer for GPU
* mode and ExpandConvLayer for CPU mode if you set type of "conv".
* User also can specfiy type of "exconv" or "cudnn_conv" for
* particular type.
*
* The config file api is img_conv_layer.
*/
class CudnnConvBaseLayer : public ConvBaseLayer {
protected:
std::vector<std::unique_ptr<ProjectionConfig>> projConf_;
std::vector<std::unique_ptr<Projection>> projections_;
hl_tensor_descriptor biasDesc_;
hl_tensor_descriptor outputDesc_;
public:
explicit CudnnConvBaseLayer(const LayerConfig& config)
: ConvBaseLayer(config) {}
~CudnnConvBaseLayer();
void forward(PassType passType) override;
void backward(const UpdateCallback& callback) override;
bool init(const LayerMap& layerMap,
const ParameterMap& parameterMap) override;
};
} // namespace paddle
| 31.444444 | 74 | 0.748528 | [
"vector"
] |
d0501ff4a8fbc176233be0642ec00c637b35bc20 | 1,798 | h | C | inc/script.h | WRansohoff/Berilia | 9dec2082f2066a358c94ff2460991b0484a33f00 | [
"MIT"
] | null | null | null | inc/script.h | WRansohoff/Berilia | 9dec2082f2066a358c94ff2460991b0484a33f00 | [
"MIT"
] | null | null | null | inc/script.h | WRansohoff/Berilia | 9dec2082f2066a358c94ff2460991b0484a33f00 | [
"MIT"
] | null | null | null | #ifndef BRLA_SCRIPT_H
#define BRLA_SCRIPT_H
#include "game.h"
#include "math3d.h"
#include "unity.h"
#include "util.h"
#include <random>
#include <string>
#include <vector>
using std::mt19937;
using std::string;
using std::uniform_real_distribution;
using std::vector;
class game;
class unity;
/**
* 'Script' object class. These objects store arbitrary
* state variables, and contain a function call which
* accepts one argument: the elapsed time since the last frame.
* They also keep track of a 'parent' game object.
* Basically, they're small functions which run during
* gameplay and can keep track of state over time.
*/
class script {
public:
/** The game object associated with this script, if any. */
unity* parent = 0;
/**
* The script type. This is an abstract class, so
* different script types will have different 'call' functions.
*/
string type = "";
/** Array of boolean state variables to track. */
vector<bool> state_flags;
/** Array of integer state variables to track. */
vector<int> state_ints;
/** Array of float state variables to track. */
vector<float> state_floats;
/** Array of string state variables to track. */
vector<string> state_strings;
/** Array of pointer state variables to track. */
vector<void*> state_pointers;
script(unity* p);
virtual ~script();
virtual void call(float dt);
};
/**
* Test 'on-use' script; show a GUI panel with some text.
*/
class s_test_use : public script {
public:
/** The text string to display. */
string my_text = "";
/** Constructor - just set the 'type' string. */
s_test_use( unity* p ) : script( p ) {
type = "s_test_use";
}
void call( float dt );
void set_text_contents_to( string text );
void set_text_contents_from( const char* fn );
};
#endif
| 24.297297 | 65 | 0.689099 | [
"object",
"vector"
] |
d0516b986a78ef49edd3b1055500e3749bcd09e0 | 43,626 | h | C | slang32/prelude/slang-cuda-prelude.h | dfranx/PluginSlang | f613f0843bd59a03bb7049875455f2be62526060 | [
"MIT"
] | 7 | 2020-07-11T22:05:42.000Z | 2021-11-08T12:09:33.000Z | slang64/prelude/slang-cuda-prelude.h | dfranx/PluginSlang | f613f0843bd59a03bb7049875455f2be62526060 | [
"MIT"
] | null | null | null | slang64/prelude/slang-cuda-prelude.h | dfranx/PluginSlang | f613f0843bd59a03bb7049875455f2be62526060 | [
"MIT"
] | 1 | 2020-12-14T16:46:32.000Z | 2020-12-14T16:46:32.000Z | #ifdef SLANG_CUDA_ENABLE_OPTIX
#include <optix.h>
#endif
// Must be large enough to cause overflow and therefore infinity
#ifndef SLANG_INFINITY
# define SLANG_INFINITY ((float)(1e+300 * 1e+300))
#endif
// For now we'll disable any asserts in this prelude
#define SLANG_PRELUDE_ASSERT(x)
#ifndef SLANG_CUDA_WARP_SIZE
# define SLANG_CUDA_WARP_SIZE 32
#endif
#define SLANG_CUDA_WARP_MASK (SLANG_CUDA_WARP_SIZE - 1)
//
#define SLANG_FORCE_INLINE inline
#define SLANG_CUDA_CALL __device__
#define SLANG_FORCE_INLINE inline
#define SLANG_INLINE inline
// Bound checks. Can be replaced by defining before including header.
// NOTE!
// The default behaviour, if out of bounds is to index 0. This is of course quite wrong - and different
// behavior to hlsl typically. The problem here though is more around a write reference. That unless
// some kind of proxy is used it is hard and/or slow to emulate the typical GPU behavior.
#ifndef SLANG_CUDA_BOUND_CHECK
# define SLANG_CUDA_BOUND_CHECK(index, count) SLANG_PRELUDE_ASSERT(index < count); index = (index < count) ? index : 0;
#endif
#ifndef SLANG_CUDA_BYTE_ADDRESS_BOUND_CHECK
# define SLANG_CUDA_BYTE_ADDRESS_BOUND_CHECK(index, size, count) SLANG_PRELUDE_ASSERT(index + 4 <= sizeInBytes && (index & 3) == 0); index = (index + 4 <= sizeInBytes) ? index : 0;
#endif
// Here we don't have the index zeroing behavior, as such bounds checks are generally not on GPU targets either.
#ifndef SLANG_CUDA_FIXED_ARRAY_BOUND_CHECK
# define SLANG_CUDA_FIXED_ARRAY_BOUND_CHECK(index, count) SLANG_PRELUDE_ASSERT(index < count);
#endif
// This macro handles how out-of-range surface coordinates are handled;
// I can equal
// cudaBoundaryModeClamp, in which case out-of-range coordinates are clamped to the valid range
// cudaBoundaryModeZero, in which case out-of-range reads return zero and out-of-range writes are ignored
// cudaBoundaryModeTrap, in which case out-of-range accesses cause the kernel execution to fail.
#ifndef SLANG_CUDA_BOUNDARY_MODE
# define SLANG_CUDA_BOUNDARY_MODE cudaBoundaryModeZero
#endif
template <typename T, size_t SIZE>
struct FixedArray
{
SLANG_CUDA_CALL const T& operator[](size_t index) const { SLANG_CUDA_FIXED_ARRAY_BOUND_CHECK(index, SIZE); return m_data[index]; }
SLANG_CUDA_CALL T& operator[](size_t index) { SLANG_CUDA_FIXED_ARRAY_BOUND_CHECK(index, SIZE); return m_data[index]; }
T m_data[SIZE];
};
// An array that has no specified size, becomes a 'Array'. This stores the size so it can potentially
// do bounds checking.
template <typename T>
struct Array
{
SLANG_CUDA_CALL const T& operator[](size_t index) const { SLANG_CUDA_BOUND_CHECK(index, count); return data[index]; }
SLANG_CUDA_CALL T& operator[](size_t index) { SLANG_CUDA_BOUND_CHECK(index, count); return data[index]; }
T* data;
size_t count;
};
// Typically defined in cuda.h, but we can't ship/rely on that, so just define here
typedef unsigned long long CUtexObject;
typedef unsigned long long CUsurfObject;
// On CUDA sampler state is actually bound up with the texture object. We have a SamplerState type,
// backed as a pointer, to simplify code generation, with the downside that such a binding will take up
// uniform space, even though it will have no effect.
// TODO(JS): Consider ways to strip use of variables of this type so have no binding,
struct SamplerStateUnused;
typedef SamplerStateUnused* SamplerState;
// TODO(JS): Not clear yet if this can be handled on CUDA, by just ignoring.
// For now, just map to the index type.
typedef size_t NonUniformResourceIndex;
// Code generator will generate the specific type
template <typename T, int ROWS, int COLS>
struct Matrix;
typedef bool bool1;
typedef int2 bool2;
typedef int3 bool3;
typedef int4 bool4;
typedef signed char int8_t;
typedef short int16_t;
typedef int int32_t;
typedef long long int64_t;
typedef unsigned char uint8_t;
typedef unsigned short uint16_t;
typedef unsigned int uint32_t;
typedef unsigned long long uint64_t;
typedef long long longlong;
typedef unsigned long long ulonglong;
typedef unsigned char uchar;
typedef unsigned short ushort;
typedef unsigned int uint;
union Union32
{
uint32_t u;
int32_t i;
float f;
};
union Union64
{
uint64_t u;
int64_t i;
double d;
};
// ----------------------------- F32 -----------------------------------------
// Unary
SLANG_CUDA_CALL float F32_ceil(float f) { return ::ceilf(f); }
SLANG_CUDA_CALL float F32_floor(float f) { return ::floorf(f); }
SLANG_CUDA_CALL float F32_round(float f) { return ::roundf(f); }
SLANG_CUDA_CALL float F32_sin(float f) { return ::sinf(f); }
SLANG_CUDA_CALL float F32_cos(float f) { return ::cosf(f); }
SLANG_CUDA_CALL void F32_sincos(float f, float* s, float* c) { ::sincosf(f, s, c); }
SLANG_CUDA_CALL float F32_tan(float f) { return ::tanf(f); }
SLANG_CUDA_CALL float F32_asin(float f) { return ::asinf(f); }
SLANG_CUDA_CALL float F32_acos(float f) { return ::acosf(f); }
SLANG_CUDA_CALL float F32_atan(float f) { return ::atanf(f); }
SLANG_CUDA_CALL float F32_sinh(float f) { return ::sinhf(f); }
SLANG_CUDA_CALL float F32_cosh(float f) { return ::coshf(f); }
SLANG_CUDA_CALL float F32_tanh(float f) { return ::tanhf(f); }
SLANG_CUDA_CALL float F32_log2(float f) { return ::log2f(f); }
SLANG_CUDA_CALL float F32_log(float f) { return ::logf(f); }
SLANG_CUDA_CALL float F32_log10(float f) { return ::log10f(f); }
SLANG_CUDA_CALL float F32_exp2(float f) { return ::exp2f(f); }
SLANG_CUDA_CALL float F32_exp(float f) { return ::expf(f); }
SLANG_CUDA_CALL float F32_abs(float f) { return ::fabsf(f); }
SLANG_CUDA_CALL float F32_trunc(float f) { return ::truncf(f); }
SLANG_CUDA_CALL float F32_sqrt(float f) { return ::sqrtf(f); }
SLANG_CUDA_CALL float F32_rsqrt(float f) { return ::rsqrtf(f); }
SLANG_CUDA_CALL float F32_sign(float f) { return ( f == 0.0f) ? f : (( f < 0.0f) ? -1.0f : 1.0f); }
SLANG_CUDA_CALL float F32_frac(float f) { return f - F32_floor(f); }
SLANG_CUDA_CALL bool F32_isnan(float f) { return isnan(f); }
SLANG_CUDA_CALL bool F32_isfinite(float f) { return isfinite(f); }
SLANG_CUDA_CALL bool F32_isinf(float f) { return isinf(f); }
// Binary
SLANG_CUDA_CALL float F32_min(float a, float b) { return ::fminf(a, b); }
SLANG_CUDA_CALL float F32_max(float a, float b) { return ::fmaxf(a, b); }
SLANG_CUDA_CALL float F32_pow(float a, float b) { return ::powf(a, b); }
SLANG_CUDA_CALL float F32_fmod(float a, float b) { return ::fmodf(a, b); }
SLANG_CUDA_CALL float F32_remainder(float a, float b) { return ::remainderf(a, b); }
SLANG_CUDA_CALL float F32_atan2(float a, float b) { return float(::atan2(a, b)); }
SLANG_CUDA_CALL float F32_frexp(float x, float* e)
{
int ei;
float m = ::frexpf(x, &ei);
*e = ei;
return m;
}
SLANG_CUDA_CALL float F32_modf(float x, float* ip)
{
return ::modff(x, ip);
}
SLANG_CUDA_CALL uint32_t F32_asuint(float f) { Union32 u; u.f = f; return u.u; }
SLANG_CUDA_CALL int32_t F32_asint(float f) { Union32 u; u.f = f; return u.i; }
// Ternary
SLANG_CUDA_CALL float F32_fma(float a, float b, float c) { return ::fmaf(a, b, c); }
// ----------------------------- F64 -----------------------------------------
// Unary
SLANG_CUDA_CALL double F64_ceil(double f) { return ::ceil(f); }
SLANG_CUDA_CALL double F64_floor(double f) { return ::floor(f); }
SLANG_CUDA_CALL double F64_round(double f) { return ::round(f); }
SLANG_CUDA_CALL double F64_sin(double f) { return ::sin(f); }
SLANG_CUDA_CALL double F64_cos(double f) { return ::cos(f); }
SLANG_CUDA_CALL void F64_sincos(double f, double* s, double* c) { ::sincos(f, s, c); }
SLANG_CUDA_CALL double F64_tan(double f) { return ::tan(f); }
SLANG_CUDA_CALL double F64_asin(double f) { return ::asin(f); }
SLANG_CUDA_CALL double F64_acos(double f) { return ::acos(f); }
SLANG_CUDA_CALL double F64_atan(double f) { return ::atan(f); }
SLANG_CUDA_CALL double F64_sinh(double f) { return ::sinh(f); }
SLANG_CUDA_CALL double F64_cosh(double f) { return ::cosh(f); }
SLANG_CUDA_CALL double F64_tanh(double f) { return ::tanh(f); }
SLANG_CUDA_CALL double F64_log2(double f) { return ::log2(f); }
SLANG_CUDA_CALL double F64_log(double f) { return ::log(f); }
SLANG_CUDA_CALL double F64_log10(float f) { return ::log10(f); }
SLANG_CUDA_CALL double F64_exp2(double f) { return ::exp2(f); }
SLANG_CUDA_CALL double F64_exp(double f) { return ::exp(f); }
SLANG_CUDA_CALL double F64_abs(double f) { return ::fabs(f); }
SLANG_CUDA_CALL double F64_trunc(double f) { return ::trunc(f); }
SLANG_CUDA_CALL double F64_sqrt(double f) { return ::sqrt(f); }
SLANG_CUDA_CALL double F64_rsqrt(double f) { return ::rsqrt(f); }
SLANG_CUDA_CALL double F64_sign(double f) { return (f == 0.0) ? f : ((f < 0.0) ? -1.0 : 1.0); }
SLANG_CUDA_CALL double F64_frac(double f) { return f - F64_floor(f); }
SLANG_CUDA_CALL bool F64_isnan(double f) { return isnan(f); }
SLANG_CUDA_CALL bool F64_isfinite(double f) { return isfinite(f); }
SLANG_CUDA_CALL bool F64_isinf(double f) { return isinf(f); }
// Binary
SLANG_CUDA_CALL double F64_min(double a, double b) { return ::fmin(a, b); }
SLANG_CUDA_CALL double F64_max(double a, double b) { return ::fmax(a, b); }
SLANG_CUDA_CALL double F64_pow(double a, double b) { return ::pow(a, b); }
SLANG_CUDA_CALL double F64_fmod(double a, double b) { return ::fmod(a, b); }
SLANG_CUDA_CALL double F64_remainder(double a, double b) { return ::remainder(a, b); }
SLANG_CUDA_CALL double F64_atan2(double a, double b) { return ::atan2(a, b); }
SLANG_CUDA_CALL double F64_frexp(double x, double* e)
{
int ei;
double m = ::frexp(x, &ei);
*e = ei;
return m;
}
SLANG_CUDA_CALL double F64_modf(double x, double* ip)
{
return ::modf(x, ip);
}
SLANG_CUDA_CALL void F64_asuint(double d, uint32_t* low, uint32_t* hi)
{
Union64 u;
u.d = d;
*low = uint32_t(u.u);
*hi = uint32_t(u.u >> 32);
}
SLANG_CUDA_CALL void F64_asint(double d, int32_t* low, int32_t* hi)
{
Union64 u;
u.d = d;
*low = int32_t(u.u);
*hi = int32_t(u.u >> 32);
}
// Ternary
SLANG_CUDA_CALL double F64_fma(double a, double b, double c) { return ::fma(a, b, c); }
// ----------------------------- I32 -----------------------------------------
// Unary
SLANG_CUDA_CALL int32_t I32_abs(int32_t f) { return (f < 0) ? -f : f; }
// Binary
SLANG_CUDA_CALL int32_t I32_min(int32_t a, int32_t b) { return a < b ? a : b; }
SLANG_CUDA_CALL int32_t I32_max(int32_t a, int32_t b) { return a > b ? a : b; }
SLANG_CUDA_CALL float I32_asfloat(int32_t x) { Union32 u; u.i = x; return u.f; }
SLANG_CUDA_CALL uint32_t I32_asuint(int32_t x) { return uint32_t(x); }
SLANG_CUDA_CALL double I32_asdouble(int32_t low, int32_t hi )
{
Union64 u;
u.u = (uint64_t(hi) << 32) | uint32_t(low);
return u.d;
}
// ----------------------------- U32 -----------------------------------------
// Unary
SLANG_CUDA_CALL uint32_t U32_abs(uint32_t f) { return f; }
// Binary
SLANG_CUDA_CALL uint32_t U32_min(uint32_t a, uint32_t b) { return a < b ? a : b; }
SLANG_CUDA_CALL uint32_t U32_max(uint32_t a, uint32_t b) { return a > b ? a : b; }
SLANG_CUDA_CALL float U32_asfloat(uint32_t x) { Union32 u; u.u = x; return u.f; }
SLANG_CUDA_CALL uint32_t U32_asint(int32_t x) { return uint32_t(x); }
SLANG_CUDA_CALL double U32_asdouble(uint32_t low, uint32_t hi)
{
Union64 u;
u.u = (uint64_t(hi) << 32) | low;
return u.d;
}
SLANG_CUDA_CALL uint32_t U32_countbits(uint32_t v)
{
// https://docs.nvidia.com/cuda/cuda-math-api/group__CUDA__MATH__INTRINSIC__INT.html#group__CUDA__MATH__INTRINSIC__INT_1g43c9c7d2b9ebf202ff1ef5769989be46
return __popc(v);
}
// ----------------------------- I64 -----------------------------------------
SLANG_CUDA_CALL int64_t I64_abs(int64_t f) { return (f < 0) ? -f : f; }
SLANG_CUDA_CALL int64_t I64_min(int64_t a, int64_t b) { return a < b ? a : b; }
SLANG_CUDA_CALL int64_t I64_max(int64_t a, int64_t b) { return a > b ? a : b; }
// ----------------------------- U64 -----------------------------------------
SLANG_CUDA_CALL int64_t U64_abs(uint64_t f) { return f; }
SLANG_CUDA_CALL int64_t U64_min(uint64_t a, uint64_t b) { return a < b ? a : b; }
SLANG_CUDA_CALL int64_t U64_max(uint64_t a, uint64_t b) { return a > b ? a : b; }
SLANG_CUDA_CALL uint32_t U64_countbits(uint64_t v)
{
// https://docs.nvidia.com/cuda/cuda-math-api/group__CUDA__MATH__INTRINSIC__INT.html#group__CUDA__MATH__INTRINSIC__INT_1g43c9c7d2b9ebf202ff1ef5769989be46
return __popcll(v);
}
// ----------------------------- ResourceType -----------------------------------------
// https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/sm5-object-structuredbuffer-getdimensions
// Missing Load(_In_ int Location, _Out_ uint Status);
template <typename T>
struct RWStructuredBuffer
{
SLANG_CUDA_CALL T& operator[](size_t index) const { SLANG_CUDA_BOUND_CHECK(index, count); return data[index]; }
SLANG_CUDA_CALL const T& Load(size_t index) const { SLANG_CUDA_BOUND_CHECK(index, count); return data[index]; }
SLANG_CUDA_CALL void GetDimensions(uint32_t* outNumStructs, uint32_t* outStride) { *outNumStructs = uint32_t(count); *outStride = uint32_t(sizeof(T)); }
T* data;
size_t count;
};
template <typename T>
struct StructuredBuffer
{
SLANG_CUDA_CALL const T& operator[](size_t index) const { SLANG_CUDA_BOUND_CHECK(index, count); return data[index]; }
SLANG_CUDA_CALL const T& Load(size_t index) const { SLANG_CUDA_BOUND_CHECK(index, count); return data[index]; }
SLANG_CUDA_CALL void GetDimensions(uint32_t* outNumStructs, uint32_t* outStride) { *outNumStructs = uint32_t(count); *outStride = uint32_t(sizeof(T)); }
T* data;
size_t count;
};
// Missing Load(_In_ int Location, _Out_ uint Status);
struct ByteAddressBuffer
{
SLANG_CUDA_CALL void GetDimensions(uint32_t* outDim) const { *outDim = uint32_t(sizeInBytes); }
SLANG_CUDA_CALL uint32_t Load(size_t index) const
{
SLANG_CUDA_BYTE_ADDRESS_BOUND_CHECK(index, 4, sizeInBytes);
return data[index >> 2];
}
SLANG_CUDA_CALL uint2 Load2(size_t index) const
{
SLANG_CUDA_BYTE_ADDRESS_BOUND_CHECK(index, 8, sizeInBytes);
const size_t dataIdx = index >> 2;
return uint2{data[dataIdx], data[dataIdx + 1]};
}
SLANG_CUDA_CALL uint3 Load3(size_t index) const
{
SLANG_CUDA_BYTE_ADDRESS_BOUND_CHECK(index, 12, sizeInBytes);
const size_t dataIdx = index >> 2;
return uint3{data[dataIdx], data[dataIdx + 1], data[dataIdx + 2]};
}
SLANG_CUDA_CALL uint4 Load4(size_t index) const
{
SLANG_CUDA_BYTE_ADDRESS_BOUND_CHECK(index, 16, sizeInBytes);
const size_t dataIdx = index >> 2;
return uint4{data[dataIdx], data[dataIdx + 1], data[dataIdx + 2], data[dataIdx + 3]};
}
template<typename T>
SLANG_CUDA_CALL T Load(size_t offset) const
{
SLANG_PRELUDE_ASSERT(offset + sizeof(T) <= sizeInBytes && (offset & (alignof(T)-1)) == 0);
return *(T const*)((char*)data + offset);
}
const uint32_t* data;
size_t sizeInBytes; //< Must be multiple of 4
};
// https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/sm5-object-rwbyteaddressbuffer
// Missing support for Atomic operations
// Missing support for Load with status
struct RWByteAddressBuffer
{
SLANG_CUDA_CALL void GetDimensions(uint32_t* outDim) const { *outDim = uint32_t(sizeInBytes); }
SLANG_CUDA_CALL uint32_t Load(size_t index) const
{
SLANG_CUDA_BYTE_ADDRESS_BOUND_CHECK(index, 4, sizeInBytes);
return data[index >> 2];
}
SLANG_CUDA_CALL uint2 Load2(size_t index) const
{
SLANG_CUDA_BYTE_ADDRESS_BOUND_CHECK(index, 8, sizeInBytes);
const size_t dataIdx = index >> 2;
return uint2{data[dataIdx], data[dataIdx + 1]};
}
SLANG_CUDA_CALL uint3 Load3(size_t index) const
{
SLANG_CUDA_BYTE_ADDRESS_BOUND_CHECK(index, 12, sizeInBytes);
const size_t dataIdx = index >> 2;
return uint3{data[dataIdx], data[dataIdx + 1], data[dataIdx + 2]};
}
SLANG_CUDA_CALL uint4 Load4(size_t index) const
{
SLANG_CUDA_BYTE_ADDRESS_BOUND_CHECK(index, 16, sizeInBytes);
const size_t dataIdx = index >> 2;
return uint4{data[dataIdx], data[dataIdx + 1], data[dataIdx + 2], data[dataIdx + 3]};
}
template<typename T>
SLANG_CUDA_CALL T Load(size_t offset) const
{
SLANG_PRELUDE_ASSERT(offset + sizeof(T) <= sizeInBytes && (offset & (alignof(T)-1)) == 0);
return *(T const*)((char*)data + offset);
}
SLANG_CUDA_CALL void Store(size_t index, uint32_t v) const
{
SLANG_CUDA_BYTE_ADDRESS_BOUND_CHECK(index, 4, sizeInBytes);
data[index >> 2] = v;
}
SLANG_CUDA_CALL void Store2(size_t index, uint2 v) const
{
SLANG_CUDA_BYTE_ADDRESS_BOUND_CHECK(index, 8, sizeInBytes);
const size_t dataIdx = index >> 2;
data[dataIdx + 0] = v.x;
data[dataIdx + 1] = v.y;
}
SLANG_CUDA_CALL void Store3(size_t index, uint3 v) const
{
SLANG_CUDA_BYTE_ADDRESS_BOUND_CHECK(index, 12, sizeInBytes);
const size_t dataIdx = index >> 2;
data[dataIdx + 0] = v.x;
data[dataIdx + 1] = v.y;
data[dataIdx + 2] = v.z;
}
SLANG_CUDA_CALL void Store4(size_t index, uint4 v) const
{
SLANG_CUDA_BYTE_ADDRESS_BOUND_CHECK(index, 16, sizeInBytes);
const size_t dataIdx = index >> 2;
data[dataIdx + 0] = v.x;
data[dataIdx + 1] = v.y;
data[dataIdx + 2] = v.z;
data[dataIdx + 3] = v.w;
}
template<typename T>
SLANG_CUDA_CALL void Store(size_t offset, T const& value) const
{
SLANG_PRELUDE_ASSERT(offset + sizeof(T) <= sizeInBytes && (offset & (alignof(T)-1)) == 0);
*(T*)((char*)data + offset) = value;
}
uint32_t* data;
size_t sizeInBytes; //< Must be multiple of 4
};
// ---------------------- Wave --------------------------------------
// TODO(JS): It appears that cuda does not have a simple way to get a lane index.
//
// Another approach could be...
// laneId = ((threadIdx.z * blockDim.y + threadIdx.y) * blockDim.x + threadIdx.x) & SLANG_CUDA_WARP_MASK
// If that is really true another way to do this, would be for code generator to add this function
// with the [numthreads] baked in.
//
// For now I'll just assume you have a launch that makes the following correct if the kernel uses WaveGetLaneIndex()
#ifndef SLANG_USE_ASM_LANE_ID
__forceinline__ __device__ uint32_t _getLaneId()
{
// If the launch is (or I guess some multiple of the warp size)
// we try this mechanism, which is apparently faster.
return threadIdx.x & SLANG_CUDA_WARP_MASK;
}
#else
__forceinline__ __device__ uint32_t _getLaneId()
{
// https://stackoverflow.com/questions/44337309/whats-the-most-efficient-way-to-calculate-the-warp-id-lane-id-in-a-1-d-grid#
// This mechanism is not the fastest way to do it, and that is why the other mechanism
// is the default. But the other mechanism relies on a launch that makes the assumption
// true.
unsigned ret;
asm volatile ("mov.u32 %0, %laneid;" : "=r"(ret));
return ret;
}
#endif
typedef int WarpMask;
// It appears that the __activemask() cannot always be used because
// threads need to be converged.
//
// For CUDA the article claims mask has to be used carefully
// https://devblogs.nvidia.com/using-cuda-warp-level-primitives/
// With the Warp intrinsics there is no mask, and it's just the 'active lanes'.
// __activemask() though does not require there is convergence, so that doesn't work.
//
// '__ballot_sync' produces a convergance.
//
// From the CUDA docs:
// ```For __all_sync, __any_sync, and __ballot_sync, a mask must be passed that specifies the threads
// participating in the call. A bit, representing the thread's lane ID, must be set for each participating thread
// to ensure they are properly converged before the intrinsic is executed by the hardware. All active threads named
// in mask must execute the same intrinsic with the same mask, or the result is undefined.```
//
// Currently there isn't a mechanism to correctly get the mask without it being passed through.
// Doing so will most likely require some changes to slang code generation to track masks, for now then we use
// _getActiveMask.
// Return mask of all the lanes less than the current lane
__forceinline__ __device__ WarpMask _getLaneLtMask()
{
return (int(1) << _getLaneId()) - 1;
}
// TODO(JS):
// THIS IS NOT CORRECT! That determining the appropriate active mask requires appropriate
// mask tracking.
__forceinline__ __device__ WarpMask _getActiveMask()
{
return __ballot_sync(__activemask(), true);
}
// Return a mask suitable for the 'MultiPrefix' style functions
__forceinline__ __device__ WarpMask _getMultiPrefixMask(int mask)
{
return mask;
}
// Note! Note will return true if mask is 0, but thats okay, because there must be one
// lane active to execute anything
__inline__ __device__ bool _waveIsSingleLane(WarpMask mask)
{
return (mask & (mask - 1)) == 0;
}
// Returns the power of 2 size of run of set bits. Returns 0 if not a suitable run.
__inline__ __device__ int _waveCalcPow2Offset(WarpMask mask)
{
// This should be the most common case, so fast path it
if (mask == SLANG_CUDA_WARP_MASK)
{
return SLANG_CUDA_WARP_SIZE;
}
// Is it a contiguous run of bits?
if ((mask & (mask + 1)) == 0)
{
// const int offsetSize = __ffs(mask + 1) - 1;
const int offset = 32 - __clz(mask);
// Is it a power of 2 size
if ((offset & (offset - 1)) == 0)
{
return offset;
}
}
return 0;
}
__inline__ __device__ bool _waveIsFirstLane()
{
const WarpMask mask = __activemask();
// We special case bit 0, as that most warps are expected to be fully active.
// mask & -mask, isolates the lowest set bit.
//return (mask & 1 ) || ((mask & -mask) == (1 << _getLaneId()));
// This mechanism is most similar to what was in an nVidia post, so assume it is prefered.
return (mask & 1 ) || ((__ffs(mask) - 1) == _getLaneId());
}
template <typename T>
struct WaveOpOr
{
__inline__ __device__ static T getInitial(T a) { return 0; }
__inline__ __device__ static T doOp(T a, T b) { return a | b; }
};
template <typename T>
struct WaveOpAnd
{
__inline__ __device__ static T getInitial(T a) { return ~T(0); }
__inline__ __device__ static T doOp(T a, T b) { return a & b; }
};
template <typename T>
struct WaveOpXor
{
__inline__ __device__ static T getInitial(T a) { return 0; }
__inline__ __device__ static T doOp(T a, T b) { return a ^ b; }
__inline__ __device__ static T doInverse(T a, T b) { return a ^ b; }
};
template <typename T>
struct WaveOpAdd
{
__inline__ __device__ static T getInitial(T a) { return 0; }
__inline__ __device__ static T doOp(T a, T b) { return a + b; }
__inline__ __device__ static T doInverse(T a, T b) { return a - b; }
};
template <typename T>
struct WaveOpMul
{
__inline__ __device__ static T getInitial(T a) { return T(1); }
__inline__ __device__ static T doOp(T a, T b) { return a * b; }
// Using this inverse for int is probably undesirable - because in general it requires T to have more precision
// There is also a performance aspect to it, where divides are generally significantly slower
__inline__ __device__ static T doInverse(T a, T b) { return a / b; }
};
template <typename T>
struct WaveOpMax
{
__inline__ __device__ static T getInitial(T a) { return a; }
__inline__ __device__ static T doOp(T a, T b) { return a > b ? a : b; }
};
template <typename T>
struct WaveOpMin
{
__inline__ __device__ static T getInitial(T a) { return a; }
__inline__ __device__ static T doOp(T a, T b) { return a < b ? a : b; }
};
template <typename T>
struct ElementTypeTrait;
// Scalar
template <> struct ElementTypeTrait<int> { typedef int Type; };
template <> struct ElementTypeTrait<uint> { typedef uint Type; };
template <> struct ElementTypeTrait<float> { typedef float Type; };
template <> struct ElementTypeTrait<double> { typedef double Type; };
template <> struct ElementTypeTrait<uint64_t> { typedef uint64_t Type; };
template <> struct ElementTypeTrait<int64_t> { typedef int64_t Type; };
// Vector
template <> struct ElementTypeTrait<int1> { typedef int Type; };
template <> struct ElementTypeTrait<int2> { typedef int Type; };
template <> struct ElementTypeTrait<int3> { typedef int Type; };
template <> struct ElementTypeTrait<int4> { typedef int Type; };
template <> struct ElementTypeTrait<uint1> { typedef uint Type; };
template <> struct ElementTypeTrait<uint2> { typedef uint Type; };
template <> struct ElementTypeTrait<uint3> { typedef uint Type; };
template <> struct ElementTypeTrait<uint4> { typedef uint Type; };
template <> struct ElementTypeTrait<float1> { typedef float Type; };
template <> struct ElementTypeTrait<float2> { typedef float Type; };
template <> struct ElementTypeTrait<float3> { typedef float Type; };
template <> struct ElementTypeTrait<float4> { typedef float Type; };
template <> struct ElementTypeTrait<double1> { typedef double Type; };
template <> struct ElementTypeTrait<double2> { typedef double Type; };
template <> struct ElementTypeTrait<double3> { typedef double Type; };
template <> struct ElementTypeTrait<double4> { typedef double Type; };
// Matrix
template <typename T, int ROWS, int COLS>
struct ElementTypeTrait<Matrix<T, ROWS, COLS> >
{
typedef T Type;
};
// Scalar
template <typename INTF, typename T>
__device__ T _waveReduceScalar(WarpMask mask, T val)
{
const int offsetSize = _waveCalcPow2Offset(mask);
if (offsetSize > 0)
{
// Fast path O(log2(activeLanes))
for (int offset = offsetSize >> 1; offset > 0; offset >>= 1)
{
val = INTF::doOp(val, __shfl_xor_sync(mask, val, offset));
}
}
else if (!_waveIsSingleLane(mask))
{
T result = INTF::getInitial(val);
int remaining = mask;
while (remaining)
{
const int laneBit = remaining & -remaining;
// Get the sourceLane
const int srcLane = __ffs(laneBit) - 1;
// Broadcast (can also broadcast to self)
result = INTF::doOp(result, __shfl_sync(mask, val, srcLane));
remaining &= ~laneBit;
}
return result;
}
return val;
}
// Multiple values
template <typename INTF, typename T, size_t COUNT>
__device__ void _waveReduceMultiple(WarpMask mask, T* val)
{
const int offsetSize = _waveCalcPow2Offset(mask);
if (offsetSize > 0)
{
// Fast path O(log2(activeLanes))
for (int offset = offsetSize >> 1; offset > 0; offset >>= 1)
{
for (size_t i = 0; i < COUNT; ++i)
{
val[i] = INTF::doOp(val[i], __shfl_xor_sync(mask, val[i], offset));
}
}
}
else if (!_waveIsSingleLane(mask))
{
// Copy the original
T originalVal[COUNT];
for (size_t i = 0; i < COUNT; ++i)
{
const T v = val[i];
originalVal[i] = v;
val[i] = INTF::getInitial(v);
}
int remaining = mask;
while (remaining)
{
const int laneBit = remaining & -remaining;
// Get the sourceLane
const int srcLane = __ffs(laneBit) - 1;
// Broadcast (can also broadcast to self)
for (size_t i = 0; i < COUNT; ++i)
{
val[i] = INTF::doOp(val[i], __shfl_sync(mask, originalVal[i], srcLane));
}
remaining &= ~laneBit;
}
}
}
template <typename INTF, typename T>
__device__ void _waveReduceMultiple(WarpMask mask, T* val)
{
typedef typename ElementTypeTrait<T>::Type ElemType;
_waveReduceMultiple<INTF, ElemType, sizeof(T) / sizeof(ElemType)>(mask, (ElemType*)val);
}
template <typename T>
__inline__ __device__ T _waveOr(WarpMask mask, T val) { return _waveReduceScalar<WaveOpOr<T>, T>(mask, val); }
template <typename T>
__inline__ __device__ T _waveAnd(WarpMask mask, T val) { return _waveReduceScalar<WaveOpAnd<T>, T>(mask, val); }
template <typename T>
__inline__ __device__ T _waveXor(WarpMask mask, T val) { return _waveReduceScalar<WaveOpXor<T>, T>(mask, val); }
template <typename T>
__inline__ __device__ T _waveProduct(WarpMask mask, T val) { return _waveReduceScalar<WaveOpMul<T>, T>(mask, val); }
template <typename T>
__inline__ __device__ T _waveSum(WarpMask mask, T val) { return _waveReduceScalar<WaveOpAdd<T>, T>(mask, val); }
template <typename T>
__inline__ __device__ T _waveMin(WarpMask mask, T val) { return _waveReduceScalar<WaveOpMin<T>, T>(mask, val); }
template <typename T>
__inline__ __device__ T _waveMax(WarpMask mask, T val) { return _waveReduceScalar<WaveOpMax<T>, T>(mask, val); }
// Multiple
template <typename T>
__inline__ __device__ T _waveOrMultiple(WarpMask mask, T val) { typedef typename ElementTypeTrait<T>::Type ElemType; _waveReduceMultiple<WaveOpOr<ElemType> >(mask, &val); return val; }
template <typename T>
__inline__ __device__ T _waveAndMultiple(WarpMask mask, T val) { typedef typename ElementTypeTrait<T>::Type ElemType; _waveReduceMultiple<WaveOpAnd<ElemType> >(mask, &val); return val; }
template <typename T>
__inline__ __device__ T _waveXorMultiple(WarpMask mask, T val) { typedef typename ElementTypeTrait<T>::Type ElemType; _waveReduceMultiple<WaveOpXor<ElemType> >(mask, &val); return val; }
template <typename T>
__inline__ __device__ T _waveProductMultiple(WarpMask mask, T val) { typedef typename ElementTypeTrait<T>::Type ElemType; _waveReduceMultiple<WaveOpMul<ElemType> >(mask, &val); return val; }
template <typename T>
__inline__ __device__ T _waveSumMultiple(WarpMask mask, T val) { typedef typename ElementTypeTrait<T>::Type ElemType; _waveReduceMultiple<WaveOpAdd<ElemType> >(mask, &val); return val; }
template <typename T>
__inline__ __device__ T _waveMinMultiple(WarpMask mask, T val) { typedef typename ElementTypeTrait<T>::Type ElemType; _waveReduceMultiple<WaveOpMin<ElemType> >(mask, &val); return val; }
template <typename T>
__inline__ __device__ T _waveMaxMultiple(WarpMask mask, T val) { typedef typename ElementTypeTrait<T>::Type ElemType; _waveReduceMultiple<WaveOpMax<ElemType> >(mask, &val); return val; }
template <typename T>
__inline__ __device__ bool _waveAllEqual(WarpMask mask, T val)
{
int pred;
__match_all_sync(mask, val, &pred);
return pred != 0;
}
template <typename T>
__inline__ __device__ bool _waveAllEqualMultiple(WarpMask mask, T inVal)
{
typedef typename ElementTypeTrait<T>::Type ElemType;
const size_t count = sizeof(T) / sizeof(ElemType);
int pred;
const ElemType* src = (const ElemType*)&inVal;
for (size_t i = 0; i < count; ++i)
{
__match_all_sync(mask, src[i], &pred);
if (pred == 0)
{
return false;
}
}
return true;
}
template <typename T>
__inline__ __device__ T _waveReadFirst(WarpMask mask, T val)
{
const int lowestLaneId = __ffs(mask) - 1;
return __shfl_sync(mask, val, lowestLaneId);
}
template <typename T>
__inline__ __device__ T _waveReadFirstMultiple(WarpMask mask, T inVal)
{
typedef typename ElementTypeTrait<T>::Type ElemType;
const size_t count = sizeof(T) / sizeof(ElemType);
T outVal;
const ElemType* src = (const ElemType*)&inVal;
ElemType* dst = (ElemType*)&outVal;
const int lowestLaneId = __ffs(mask) - 1;
for (size_t i = 0; i < count; ++i)
{
dst[i] = __shfl_sync(mask, src[i], lowestLaneId);
}
return outVal;
}
template <typename T>
__inline__ __device__ T _waveShuffleMultiple(WarpMask mask, T inVal, int lane)
{
typedef typename ElementTypeTrait<T>::Type ElemType;
const size_t count = sizeof(T) / sizeof(ElemType);
T outVal;
const ElemType* src = (const ElemType*)&inVal;
ElemType* dst = (ElemType*)&outVal;
for (size_t i = 0; i < count; ++i)
{
dst[i] = __shfl_sync(mask, src[i], lane);
}
return outVal;
}
// Scalar
// Invertable means that when we get to the end of the reduce, we can remove val (to make exclusive), using
// the inverse of the op.
template <typename INTF, typename T>
__device__ T _wavePrefixInvertableScalar(WarpMask mask, T val)
{
const int offsetSize = _waveCalcPow2Offset(mask);
const int laneId = _getLaneId();
T result;
if (offsetSize > 0)
{
// Sum is calculated inclusive of this lanes value
result = val;
for (int i = 1; i < offsetSize; i += i)
{
const T readVal = __shfl_up_sync(mask, result, i, offsetSize);
if (laneId >= i)
{
result = INTF::doOp(result, readVal);
}
}
// Remove val from the result, by applyin inverse
result = INTF::doInverse(result, val);
}
else
{
result = INTF::getInitial(val);
if (!_waveIsSingleLane(mask))
{
int remaining = mask;
while (remaining)
{
const int laneBit = remaining & -remaining;
// Get the sourceLane
const int srcLane = __ffs(laneBit) - 1;
// Broadcast (can also broadcast to self)
const T readValue = __shfl_sync(mask, val, srcLane);
// Only accumulate if srcLane is less than this lane
if (srcLane < laneId)
{
result = INTF::doOp(result, readValue);
}
remaining &= ~laneBit;
}
}
}
return result;
}
// This implementation separately tracks the value to be propogated, and the value
// that is the final result
template <typename INTF, typename T>
__device__ T _wavePrefixScalar(WarpMask mask, T val)
{
const int offsetSize = _waveCalcPow2Offset(mask);
const int laneId = _getLaneId();
T result = INTF::getInitial(val);
if (offsetSize > 0)
{
// For transmitted value we will do it inclusively with this lanes value
// For the result we do not include the lanes value. This means an extra multiply for each iteration
// but means we don't need to have a divide at the end and also removes overflow issues in that scenario.
for (int i = 1; i < offsetSize; i += i)
{
const T readVal = __shfl_up_sync(mask, val, i, offsetSize);
if (laneId >= i)
{
result = INTF::doOp(result, readVal);
val = INTF::doOp(val, readVal);
}
}
}
else
{
if (!_waveIsSingleLane(mask))
{
int remaining = mask;
while (remaining)
{
const int laneBit = remaining & -remaining;
// Get the sourceLane
const int srcLane = __ffs(laneBit) - 1;
// Broadcast (can also broadcast to self)
const T readValue = __shfl_sync(mask, val, srcLane);
// Only accumulate if srcLane is less than this lane
if (srcLane < laneId)
{
result = INTF::doOp(result, readValue);
}
remaining &= ~laneBit;
}
}
}
return result;
}
template <typename INTF, typename T, size_t COUNT>
__device__ T _waveOpCopy(T* dst, const T* src)
{
for (size_t j = 0; j < COUNT; ++j)
{
dst[j] = src[j];
}
}
template <typename INTF, typename T, size_t COUNT>
__device__ T _waveOpDoInverse(T* inOut, const T* val)
{
for (size_t j = 0; j < COUNT; ++j)
{
inOut[j] = INTF::doInverse(inOut[j], val[j]);
}
}
template <typename INTF, typename T, size_t COUNT>
__device__ T _waveOpSetInitial(T* out, const T* val)
{
for (size_t j = 0; j < COUNT; ++j)
{
out[j] = INTF::getInitial(val[j]);
}
}
template <typename INTF, typename T, size_t COUNT>
__device__ T _wavePrefixInvertableMultiple(WarpMask mask, T* val)
{
const int offsetSize = _waveCalcPow2Offset(mask);
const int laneId = _getLaneId();
T originalVal[COUNT];
_waveOpCopy<INTF, T, COUNT>(originalVal, val);
if (offsetSize > 0)
{
// Sum is calculated inclusive of this lanes value
for (int i = 1; i < offsetSize; i += i)
{
// TODO(JS): Note that here I don't split the laneId outside so it's only tested once.
// This may be better but it would also mean that there would be shfl between lanes
// that are on different (albeit identical) instructions. So this seems more likely to
// work as expected with everything in lock step.
for (size_t j = 0; j < COUNT; ++j)
{
const T readVal = __shfl_up_sync(mask, val[j], i, offsetSize);
if (laneId >= i)
{
val[j] = INTF::doOp(val[j], readVal);
}
}
}
// Remove originalVal from the result, by applyin inverse
_waveOpDoInverse<INTF, T, COUNT>(val, originalVal);
}
else
{
_waveOpSetInitial<INTF, T, COUNT>(val, val);
if (!_waveIsSingleLane(mask))
{
int remaining = mask;
while (remaining)
{
const int laneBit = remaining & -remaining;
// Get the sourceLane
const int srcLane = __ffs(laneBit) - 1;
for (size_t j = 0; j < COUNT; ++j)
{
// Broadcast (can also broadcast to self)
const T readValue = __shfl_sync(mask, originalVal[j], srcLane);
// Only accumulate if srcLane is less than this lane
if (srcLane < laneId)
{
val[j] = INTF::doOp(val[j], readValue);
}
remaining &= ~laneBit;
}
}
}
}
}
template <typename INTF, typename T, size_t COUNT>
__device__ T _wavePrefixMultiple(WarpMask mask, T* val)
{
const int offsetSize = _waveCalcPow2Offset(mask);
const int laneId = _getLaneId();
T work[COUNT];
_waveOpCopy<INTF, T, COUNT>(work, val);
_waveOpSetInitial<INTF, T, COUNT>(val, val);
if (offsetSize > 0)
{
// For transmitted value we will do it inclusively with this lanes value
// For the result we do not include the lanes value. This means an extra op for each iteration
// but means we don't need to have a divide at the end and also removes overflow issues in that scenario.
for (int i = 1; i < offsetSize; i += i)
{
for (size_t j = 0; j < COUNT; ++j)
{
const T readVal = __shfl_up_sync(mask, work[j], i, offsetSize);
if (laneId >= i)
{
work[j] = INTF::doOp(work[j], readVal);
val[j] = INTF::doOp(val[j], readVal);
}
}
}
}
else
{
if (!_waveIsSingleLane(mask))
{
int remaining = mask;
while (remaining)
{
const int laneBit = remaining & -remaining;
// Get the sourceLane
const int srcLane = __ffs(laneBit) - 1;
for (size_t j = 0; j < COUNT; ++j)
{
// Broadcast (can also broadcast to self)
const T readValue = __shfl_sync(mask, work[j], srcLane);
// Only accumulate if srcLane is less than this lane
if (srcLane < laneId)
{
val[j] = INTF::doOp(val[j], readValue);
}
}
remaining &= ~laneBit;
}
}
}
}
template <typename T>
__inline__ __device__ T _wavePrefixProduct(WarpMask mask, T val) { return _wavePrefixScalar<WaveOpMul<T>, T>(mask, val); }
template <typename T>
__inline__ __device__ T _wavePrefixSum(WarpMask mask, T val) { return _wavePrefixInvertableScalar<WaveOpAdd<T>, T>(mask, val); }
template <typename T>
__inline__ __device__ T _wavePrefixXor(WarpMask mask, T val) { return _wavePrefixInvertableScalar<WaveOpXor<T>, T>(mask, val); }
template <typename T>
__inline__ __device__ T _wavePrefixOr(WarpMask mask, T val) { return _wavePrefixScalar<WaveOpOr<T>, T>(mask, val); }
template <typename T>
__inline__ __device__ T _wavePrefixAnd(WarpMask mask, T val) { return _wavePrefixScalar<WaveOpAnd<T>, T>(mask, val); }
template <typename T>
__inline__ __device__ T _wavePrefixProductMultiple(WarpMask mask, T val)
{
typedef typename ElementTypeTrait<T>::Type ElemType;
_wavePrefixInvertableMultiple<WaveOpMul<ElemType>, ElemType, sizeof(T) / sizeof(ElemType)>(mask, (ElemType*)&val);
return val;
}
template <typename T>
__inline__ __device__ T _wavePrefixSumMultiple(WarpMask mask, T val)
{
typedef typename ElementTypeTrait<T>::Type ElemType;
_wavePrefixInvertableMultiple<WaveOpAdd<ElemType>, ElemType, sizeof(T) / sizeof(ElemType)>(mask, (ElemType*)&val);
return val;
}
template <typename T>
__inline__ __device__ T _wavePrefixXorMultiple(WarpMask mask, T val)
{
typedef typename ElementTypeTrait<T>::Type ElemType;
_wavePrefixInvertableMultiple<WaveOpXor<ElemType>, ElemType, sizeof(T) / sizeof(ElemType)>(mask, (ElemType*)&val);
return val;
}
template <typename T>
__inline__ __device__ T _wavePrefixOrMultiple(WarpMask mask, T val)
{
typedef typename ElementTypeTrait<T>::Type ElemType;
_wavePrefixMultiple<WaveOpOr<ElemType>, ElemType, sizeof(T) / sizeof(ElemType)>(mask, (ElemType*)&val);
return val;
}
template <typename T>
__inline__ __device__ T _wavePrefixAndMultiple(WarpMask mask, T val)
{
typedef typename ElementTypeTrait<T>::Type ElemType;
_wavePrefixMultiple<WaveOpAnd<ElemType>, ElemType, sizeof(T) / sizeof(ElemType)>(mask, (ElemType*)&val);
return val;
}
template <typename T>
__inline__ __device__ uint4 _waveMatchScalar(WarpMask mask, T val)
{
int pred;
return make_uint4(__match_all_sync(mask, val, &pred), 0, 0, 0);
}
template <typename T>
__inline__ __device__ uint4 _waveMatchMultiple(WarpMask mask, const T& inVal)
{
typedef typename ElementTypeTrait<T>::Type ElemType;
const size_t count = sizeof(T) / sizeof(ElemType);
int pred;
const ElemType* src = (const ElemType*)&inVal;
uint matchBits = 0xffffffff;
for (size_t i = 0; i < count && matchBits; ++i)
{
matchBits = matchBits & __match_all_sync(mask, src[i], &pred);
}
return make_uint4(matchBits, 0, 0, 0);
}
/* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! */
/* Type that defines the uniform entry point params. The actual content of this type is dependent on the entry point parameters, and can be
found via reflection or defined such that it matches the shader appropriately.
*/
struct UniformEntryPointParams;
struct UniformState;
| 36.294509 | 191 | 0.651767 | [
"object",
"vector"
] |
d05216cb4f27a6254e323bf3e5c3c23d3ad2487d | 6,474 | h | C | GraphBLAS/Source/GB_AxB_saxpy3.h | kentbarber/SuiteSparse | 48ef9d3c2c2ae4192d14ef24fcb9cd5e8bc13ae2 | [
"Apache-2.0"
] | 1 | 2020-05-26T20:47:08.000Z | 2020-05-26T20:47:08.000Z | GraphBLAS/Source/GB_AxB_saxpy3.h | kentbarber/SuiteSparse | 48ef9d3c2c2ae4192d14ef24fcb9cd5e8bc13ae2 | [
"Apache-2.0"
] | null | null | null | GraphBLAS/Source/GB_AxB_saxpy3.h | kentbarber/SuiteSparse | 48ef9d3c2c2ae4192d14ef24fcb9cd5e8bc13ae2 | [
"Apache-2.0"
] | null | null | null | //------------------------------------------------------------------------------
// GB_AxB_saxpy3.h: definitions for C=A*B saxpy3 method
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
// GB_AxB_saxpy3 method uses a mix of Gustavson's method and the Hash method,
// combining the two for any given C=A*B computation.
#ifndef GB_AXB_SAXPY3_H
#define GB_AXB_SAXPY3_H
#include "GB.h"
//------------------------------------------------------------------------------
// functions for the Hash method for C=A*B
//------------------------------------------------------------------------------
#define GB_HASH_FACTOR 107
// initial hash function, for where to place the integer i in the hash table.
// hash_bits is a bit mask to compute the result modulo the hash table size,
// which is always a power of 2.
#define GB_HASH_FUNCTION(i) ((i * GB_HASH_FACTOR) & (hash_bits))
// rehash function, for subsequent hash lookups if the initial hash function
// refers to a hash entry that is already occupied. Linear probing is used,
// so the function does not currently depend on i. On input, hash is equal
// to the current value of the hash function, and on output, hash is set to
// the new hash value.
#define GB_REHASH(hash,i) hash = ((hash + 1) & (hash_bits))
// The hash functions and their parameters are from this paper:
// [2] Yusuke Nagasaka, Satoshi Matsuoka, Ariful Azad, and Aydın Buluç. 2018.
// High-Performance Sparse Matrix-Matrix Products on Intel KNL and Multicore
// Architectures. In Proc. 47th Intl. Conf. on Parallel Processing (ICPP '18).
// Association for Computing Machinery, New York, NY, USA, Article 34, 1–10.
// DOI:https://doi.org/10.1145/3229710.3229720
//------------------------------------------------------------------------------
// GB_saxpy3task_struct: task descriptor for GB_AxB_saxpy3
//------------------------------------------------------------------------------
// A coarse task computes C(:,j1:j2) = A*B(:,j1:j2), for a contiguous set of
// vectors j1:j2. A coarse taskid is denoted byTaskList [taskid].vector == -1,
// kfirst = TaskList [taskid].start, and klast = TaskList [taskid].end, and
// where j1 = (Bh == NULL) ? kstart : Bh [kstart] and likewise for j2. No
// summation is needed for the final result of each coarse task.
// A fine taskid computes A*B(k1:k2,j) for a single vector C(:,j), for a
// contiguous range k1:k2, where kk = Tasklist[taskid].vector (which is >= 0),
// k1 = Bi [TaskList [taskid].start], k2 = Bi [TaskList [taskid].end]. It sums
// its computations in a hash table shared by all fine tasks that compute
// C(:,j), via atomics. The vector index j is either kk if B is standard, or j
// = B->h [kk] if B is hypersparse.
// Both tasks use a hash table allocated uniquely for the task, in Hi, Hf, and
// Hx. The size of the hash table is determined by the maximum # of flops
// needed to compute any vector in C(:,j1:j2) for a coarse task, or the entire
// computation of the single vector in a fine task. For the Hash method, the
// table has a size that is twice the smallest a power of 2 larger than the
// flop count. If this size is a significant fraction of C->vlen, then the
// Hash method is not used, and Gustavson's method is used, with the hash size
// is set to C->vlen.
typedef struct
{
int64_t start ; // starting vector for coarse task, p for fine task
int64_t end ; // ending vector for coarse task, p for fine task
int64_t vector ; // -1 for coarse task, vector j for fine task
int64_t hsize ; // size of hash table
int64_t *Hi ; // Hi array for hash table (coarse hash tasks only)
GB_void *Hf ; // Hf array for hash table (int8_t or int64_t)
GB_void *Hx ; // Hx array for hash table
int64_t my_cjnz ; // # entries in C(:,j) found by this fine task
int64_t flops ; // # of flops in this task
int master ; // master fine task for the vector C(:,j)
int team_size ; // # of fine tasks in the team for vector C(:,j)
}
GB_saxpy3task_struct ;
//------------------------------------------------------------------------------
// GB_AxB_saxpy3_symbolic: symbolic analysis for GB_AxB_saxpy3
//------------------------------------------------------------------------------
void GB_AxB_saxpy3_symbolic
(
GrB_Matrix C, // Cp [k] is computed for coarse tasks
const GrB_Matrix M, // mask matrix M
bool Mask_comp, // M complemented, or not
bool Mask_struct, // M structural, or not
const GrB_Matrix A, // A matrix; only the pattern is accessed
const GrB_Matrix B, // B matrix; only the pattern is accessed
GB_saxpy3task_struct *TaskList, // list of tasks, and workspace
int ntasks, // total number of tasks
int nfine, // number of fine tasks
int nthreads // number of threads
) ;
//------------------------------------------------------------------------------
// GB_AxB_saxpy3_cumsum: cumulative sum of C->p for GB_AxB_saxpy3
//------------------------------------------------------------------------------
int64_t GB_AxB_saxpy3_cumsum // return cjnz_max for fine tasks
(
GrB_Matrix C, // finalize C->p
GB_saxpy3task_struct *TaskList, // list of tasks, and workspace
int nfine, // number of fine tasks
double chunk, // chunk size
int nthreads // number of threads
) ;
//------------------------------------------------------------------------------
// GB_AxB_saxpy3_generic: for any types and operators
//------------------------------------------------------------------------------
GrB_Info GB_AxB_saxpy3_generic
(
GrB_Matrix C,
const GrB_Matrix M, bool Mask_comp, const bool Mask_struct,
const GrB_Matrix A, bool A_is_pattern,
const GrB_Matrix B, bool B_is_pattern,
const GrB_Semiring semiring, // semiring that defines C=A*B
const bool flipxy, // if true, do z=fmult(b,a) vs fmult(a,b)
GB_saxpy3task_struct *GB_RESTRICT TaskList,
const int ntasks,
const int nfine,
const int nthreads,
GB_Context Context
) ;
#endif
| 47.255474 | 80 | 0.569509 | [
"vector"
] |
d0578341ede9035d2edd47b550ac998e5eb6915d | 8,682 | h | C | third_party/gecko-15/win32/include/nsIIDBTransaction.h | bwp/SeleniumWebDriver | 58221fbe59fcbbde9d9a033a95d45d576b422747 | [
"Apache-2.0"
] | 1 | 2018-02-05T04:23:18.000Z | 2018-02-05T04:23:18.000Z | third_party/gecko-15/win32/include/nsIIDBTransaction.h | bwp/SeleniumWebDriver | 58221fbe59fcbbde9d9a033a95d45d576b422747 | [
"Apache-2.0"
] | null | null | null | third_party/gecko-15/win32/include/nsIIDBTransaction.h | bwp/SeleniumWebDriver | 58221fbe59fcbbde9d9a033a95d45d576b422747 | [
"Apache-2.0"
] | null | null | null | /*
* DO NOT EDIT. THIS FILE IS GENERATED FROM e:/builds/moz2_slave/rel-m-rel-xr-w32-bld/build/dom/indexedDB/nsIIDBTransaction.idl
*/
#ifndef __gen_nsIIDBTransaction_h__
#define __gen_nsIIDBTransaction_h__
#ifndef __gen_nsISupports_h__
#include "nsISupports.h"
#endif
/* For IDL files that don't want to include root IDL files. */
#ifndef NS_NO_VTABLE
#define NS_NO_VTABLE
#endif
class nsIDOMEventListener; /* forward declaration */
class nsIIDBObjectStore; /* forward declaration */
class nsIIDBRequest; /* forward declaration */
class nsIIDBDatabase; /* forward declaration */
class nsIDOMDOMStringList; /* forward declaration */
/* starting interface: nsIIDBTransaction */
#define NS_IIDBTRANSACTION_IID_STR "e4927c76-4f1f-4d7d-80ad-8186e1677da6"
#define NS_IIDBTRANSACTION_IID \
{0xe4927c76, 0x4f1f, 0x4d7d, \
{ 0x80, 0xad, 0x81, 0x86, 0xe1, 0x67, 0x7d, 0xa6 }}
class NS_NO_VTABLE NS_SCRIPTABLE nsIIDBTransaction : public nsISupports {
public:
NS_DECLARE_STATIC_IID_ACCESSOR(NS_IIDBTRANSACTION_IID)
/* readonly attribute nsIIDBDatabase db; */
NS_SCRIPTABLE NS_IMETHOD GetDb(nsIIDBDatabase * *aDb) = 0;
/* readonly attribute DOMString mode; */
NS_SCRIPTABLE NS_IMETHOD GetMode(nsAString & aMode) = 0;
/* readonly attribute nsIDOMDOMStringList objectStoreNames; */
NS_SCRIPTABLE NS_IMETHOD GetObjectStoreNames(nsIDOMDOMStringList * *aObjectStoreNames) = 0;
/* nsIIDBObjectStore objectStore ([Null (Stringify)] in DOMString name); */
NS_SCRIPTABLE NS_IMETHOD ObjectStore(const nsAString & name, nsIIDBObjectStore * *_retval NS_OUTPARAM) = 0;
/* void abort (); */
NS_SCRIPTABLE NS_IMETHOD Abort(void) = 0;
/* attribute nsIDOMEventListener onerror; */
NS_SCRIPTABLE NS_IMETHOD GetOnerror(nsIDOMEventListener * *aOnerror) = 0;
NS_SCRIPTABLE NS_IMETHOD SetOnerror(nsIDOMEventListener *aOnerror) = 0;
/* attribute nsIDOMEventListener oncomplete; */
NS_SCRIPTABLE NS_IMETHOD GetOncomplete(nsIDOMEventListener * *aOncomplete) = 0;
NS_SCRIPTABLE NS_IMETHOD SetOncomplete(nsIDOMEventListener *aOncomplete) = 0;
/* attribute nsIDOMEventListener onabort; */
NS_SCRIPTABLE NS_IMETHOD GetOnabort(nsIDOMEventListener * *aOnabort) = 0;
NS_SCRIPTABLE NS_IMETHOD SetOnabort(nsIDOMEventListener *aOnabort) = 0;
};
NS_DEFINE_STATIC_IID_ACCESSOR(nsIIDBTransaction, NS_IIDBTRANSACTION_IID)
/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSIIDBTRANSACTION \
NS_SCRIPTABLE NS_IMETHOD GetDb(nsIIDBDatabase * *aDb); \
NS_SCRIPTABLE NS_IMETHOD GetMode(nsAString & aMode); \
NS_SCRIPTABLE NS_IMETHOD GetObjectStoreNames(nsIDOMDOMStringList * *aObjectStoreNames); \
NS_SCRIPTABLE NS_IMETHOD ObjectStore(const nsAString & name, nsIIDBObjectStore * *_retval NS_OUTPARAM); \
NS_SCRIPTABLE NS_IMETHOD Abort(void); \
NS_SCRIPTABLE NS_IMETHOD GetOnerror(nsIDOMEventListener * *aOnerror); \
NS_SCRIPTABLE NS_IMETHOD SetOnerror(nsIDOMEventListener *aOnerror); \
NS_SCRIPTABLE NS_IMETHOD GetOncomplete(nsIDOMEventListener * *aOncomplete); \
NS_SCRIPTABLE NS_IMETHOD SetOncomplete(nsIDOMEventListener *aOncomplete); \
NS_SCRIPTABLE NS_IMETHOD GetOnabort(nsIDOMEventListener * *aOnabort); \
NS_SCRIPTABLE NS_IMETHOD SetOnabort(nsIDOMEventListener *aOnabort);
/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSIIDBTRANSACTION(_to) \
NS_SCRIPTABLE NS_IMETHOD GetDb(nsIIDBDatabase * *aDb) { return _to GetDb(aDb); } \
NS_SCRIPTABLE NS_IMETHOD GetMode(nsAString & aMode) { return _to GetMode(aMode); } \
NS_SCRIPTABLE NS_IMETHOD GetObjectStoreNames(nsIDOMDOMStringList * *aObjectStoreNames) { return _to GetObjectStoreNames(aObjectStoreNames); } \
NS_SCRIPTABLE NS_IMETHOD ObjectStore(const nsAString & name, nsIIDBObjectStore * *_retval NS_OUTPARAM) { return _to ObjectStore(name, _retval); } \
NS_SCRIPTABLE NS_IMETHOD Abort(void) { return _to Abort(); } \
NS_SCRIPTABLE NS_IMETHOD GetOnerror(nsIDOMEventListener * *aOnerror) { return _to GetOnerror(aOnerror); } \
NS_SCRIPTABLE NS_IMETHOD SetOnerror(nsIDOMEventListener *aOnerror) { return _to SetOnerror(aOnerror); } \
NS_SCRIPTABLE NS_IMETHOD GetOncomplete(nsIDOMEventListener * *aOncomplete) { return _to GetOncomplete(aOncomplete); } \
NS_SCRIPTABLE NS_IMETHOD SetOncomplete(nsIDOMEventListener *aOncomplete) { return _to SetOncomplete(aOncomplete); } \
NS_SCRIPTABLE NS_IMETHOD GetOnabort(nsIDOMEventListener * *aOnabort) { return _to GetOnabort(aOnabort); } \
NS_SCRIPTABLE NS_IMETHOD SetOnabort(nsIDOMEventListener *aOnabort) { return _to SetOnabort(aOnabort); }
/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSIIDBTRANSACTION(_to) \
NS_SCRIPTABLE NS_IMETHOD GetDb(nsIIDBDatabase * *aDb) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetDb(aDb); } \
NS_SCRIPTABLE NS_IMETHOD GetMode(nsAString & aMode) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetMode(aMode); } \
NS_SCRIPTABLE NS_IMETHOD GetObjectStoreNames(nsIDOMDOMStringList * *aObjectStoreNames) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetObjectStoreNames(aObjectStoreNames); } \
NS_SCRIPTABLE NS_IMETHOD ObjectStore(const nsAString & name, nsIIDBObjectStore * *_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->ObjectStore(name, _retval); } \
NS_SCRIPTABLE NS_IMETHOD Abort(void) { return !_to ? NS_ERROR_NULL_POINTER : _to->Abort(); } \
NS_SCRIPTABLE NS_IMETHOD GetOnerror(nsIDOMEventListener * *aOnerror) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetOnerror(aOnerror); } \
NS_SCRIPTABLE NS_IMETHOD SetOnerror(nsIDOMEventListener *aOnerror) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetOnerror(aOnerror); } \
NS_SCRIPTABLE NS_IMETHOD GetOncomplete(nsIDOMEventListener * *aOncomplete) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetOncomplete(aOncomplete); } \
NS_SCRIPTABLE NS_IMETHOD SetOncomplete(nsIDOMEventListener *aOncomplete) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetOncomplete(aOncomplete); } \
NS_SCRIPTABLE NS_IMETHOD GetOnabort(nsIDOMEventListener * *aOnabort) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetOnabort(aOnabort); } \
NS_SCRIPTABLE NS_IMETHOD SetOnabort(nsIDOMEventListener *aOnabort) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetOnabort(aOnabort); }
#if 0
/* Use the code below as a template for the implementation class for this interface. */
/* Header file */
class nsIDBTransaction : public nsIIDBTransaction
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIIDBTRANSACTION
nsIDBTransaction();
private:
~nsIDBTransaction();
protected:
/* additional members */
};
/* Implementation file */
NS_IMPL_ISUPPORTS1(nsIDBTransaction, nsIIDBTransaction)
nsIDBTransaction::nsIDBTransaction()
{
/* member initializers and constructor code */
}
nsIDBTransaction::~nsIDBTransaction()
{
/* destructor code */
}
/* readonly attribute nsIIDBDatabase db; */
NS_IMETHODIMP nsIDBTransaction::GetDb(nsIIDBDatabase * *aDb)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* readonly attribute DOMString mode; */
NS_IMETHODIMP nsIDBTransaction::GetMode(nsAString & aMode)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* readonly attribute nsIDOMDOMStringList objectStoreNames; */
NS_IMETHODIMP nsIDBTransaction::GetObjectStoreNames(nsIDOMDOMStringList * *aObjectStoreNames)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* nsIIDBObjectStore objectStore ([Null (Stringify)] in DOMString name); */
NS_IMETHODIMP nsIDBTransaction::ObjectStore(const nsAString & name, nsIIDBObjectStore * *_retval NS_OUTPARAM)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* void abort (); */
NS_IMETHODIMP nsIDBTransaction::Abort()
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* attribute nsIDOMEventListener onerror; */
NS_IMETHODIMP nsIDBTransaction::GetOnerror(nsIDOMEventListener * *aOnerror)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP nsIDBTransaction::SetOnerror(nsIDOMEventListener *aOnerror)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* attribute nsIDOMEventListener oncomplete; */
NS_IMETHODIMP nsIDBTransaction::GetOncomplete(nsIDOMEventListener * *aOncomplete)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP nsIDBTransaction::SetOncomplete(nsIDOMEventListener *aOncomplete)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* attribute nsIDOMEventListener onabort; */
NS_IMETHODIMP nsIDBTransaction::GetOnabort(nsIDOMEventListener * *aOnabort)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP nsIDBTransaction::SetOnabort(nsIDOMEventListener *aOnabort)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* End of implementation class template. */
#endif
#endif /* __gen_nsIIDBTransaction_h__ */
| 41.342857 | 181 | 0.787607 | [
"object"
] |
d05944976942735ff77391447e74de3bfe621756 | 2,147 | h | C | ImageVis3D/UI/AboutDlg.h | JensDerKrueger/ImageVis3D | 699ab32132c899b7ea227bc87a9de80768ab879f | [
"MIT"
] | null | null | null | ImageVis3D/UI/AboutDlg.h | JensDerKrueger/ImageVis3D | 699ab32132c899b7ea227bc87a9de80768ab879f | [
"MIT"
] | null | null | null | ImageVis3D/UI/AboutDlg.h | JensDerKrueger/ImageVis3D | 699ab32132c899b7ea227bc87a9de80768ab879f | [
"MIT"
] | null | null | null | /*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2008 Scientific Computing and Imaging Institute,
University of Utah.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
//! File : AboutDlg.h
//! Author : Jens Krueger
//! SCI Institute
//! University of Utah
//! Date : January 2009
//
//! Copyright (C) 2008 SCI Institute
#ifndef ABOUTDLG_H
#define ABOUTDLG_H
#include <ui_About.h>
#include <vector>
#include <string>
#include <StdDefines.h>
class AboutDlg : public QDialog, protected Ui_About
{
Q_OBJECT
public:
AboutDlg(QString title, QString desc, QWidget* parent, Qt::WindowFlags flags = Qt::Tool);
virtual ~AboutDlg();
protected slots:
virtual void CheckUpdates();
virtual void OnlineVideoTut();
virtual void OnlineHelp();
virtual void ReportABug();
signals:
void CheckUpdatesClicked();
void OnlineVideoTutClicked();
void OnlineHelpClicked();
void ReportABugClicked();
};
#endif // ABOUTDLG_H
| 31.115942 | 94 | 0.700047 | [
"vector"
] |
d0683e007217e64718e060b6c267950cb4f70717 | 1,437 | h | C | src/ogl.h | leok7v/app.windows.gl | c996e2cd474494abdb4c3af750f4e57325a2d5db | [
"MIT"
] | null | null | null | src/ogl.h | leok7v/app.windows.gl | c996e2cd474494abdb4c3af750f4e57325a2d5db | [
"MIT"
] | null | null | null | src/ogl.h | leok7v/app.windows.gl | c996e2cd474494abdb4c3af750f4e57325a2d5db | [
"MIT"
] | null | null | null | #pragma once
#include "std.h"
// Open GL
#ifdef _MSC_VER
#ifndef WINGDIAPI
#define CALLBACK __stdcall
#define WINGDIAPI __declspec(dllimport)
#define APIENTRY __stdcall
#define CLEANUP_WINGDIAPI_DEFINES
#endif
#include <gl/gl.h>
#include <gl/glu.h>
#ifdef CLEANUP_WINGDIAPI_DEFINES
#undef CALLBACK
#undef WINGDIAPI
#undef APIENTRY
#endif
#else
#include <gl/gl.h>
#include <gl/glu.h>
#endif
BEGIN_C
#define gl_check(call) call; { \
int _gl_error_ = glGetError(); \
if (_gl_error_ != 0) { printf("%s(%d): %s %s glError=%d\n", __FILE__, __LINE__, __func__, #call, _gl_error_); } \
}
void glOrtho2D_np(float* mat, float left, float right, float bottom, float top); // GL ES does not have it
END_C
#ifdef IMPLEMENT_OGL
BEGIN_C
void glOrtho2D_np(float* mx, float left, float right, float bottom, float top) {
// this is straight from http://en.wikipedia.org/wiki/Orthographic_projection_(geometry)
const float znear = -1;
const float zfar = 1;
const float inv_z = 1 / (zfar - znear);
const float inv_y = 1 / (top - bottom);
const float inv_x = 1 / (right - left);
mx[0] = 2 * inv_x; mx[1] = 0; mx[2] = 0; mx[3] = 0;
mx[4] = 0; mx[5] = 2 * inv_y; mx[6] = 0; mx[7] = 0;
mx[8] = 0; mx[9] = 0; mx[10] = -2 * inv_z; mx[11] = 0;
mx[12] = -(right + left) * inv_x; mx[13] = -(top + bottom) * inv_y;
mx[14] = -(zfar + znear) * inv_z; mx[15] = 1;
}
END_C
#endif // IMPLEMENT_OGL
| 24.775862 | 117 | 0.641614 | [
"geometry"
] |
d069cb4e7157654681004babdd8819453b4a59cc | 24,401 | h | C | YBWLib2/Common/CommonWindows.h | yangbowen/YBWLib2 | 6c5ef8f77c4f3e3e3788fb8f8b984d6fe0bdb746 | [
"BSD-3-Clause",
"MIT"
] | null | null | null | YBWLib2/Common/CommonWindows.h | yangbowen/YBWLib2 | 6c5ef8f77c4f3e3e3788fb8f8b984d6fe0bdb746 | [
"BSD-3-Clause",
"MIT"
] | null | null | null | YBWLib2/Common/CommonWindows.h | yangbowen/YBWLib2 | 6c5ef8f77c4f3e3e3788fb8f8b984d6fe0bdb746 | [
"BSD-3-Clause",
"MIT"
] | null | null | null | #ifndef _WIN32_WINNT
#error This header file is only to be used when you're targeting Microsoft Windows. If you are, set the targetted windows version before including this header file.
#endif
#ifndef YBWLIB2_DYNAMIC_TYPE_MACROS_ENABLED
#define _MACRO_DEFINE_TEMP_YBWLIB2_DYNAMIC_TYPE_MACROS_ENABLED_83D6146A_4FDA_461C_84C5_8247F88A40CA
#define YBWLIB2_DYNAMIC_TYPE_MACROS_ENABLED
#endif
#ifndef YBWLIB2_EXCEPTION_MACROS_ENABLED
#define _MACRO_DEFINE_TEMP_YBWLIB2_EXCEPTION_MACROS_ENABLED_B2352359_1626_4CF1_AEBF_4F58A5F48AD7
#define YBWLIB2_EXCEPTION_MACROS_ENABLED
#endif
#ifndef _INCLUDE_GUARD_B9D2E995_F86E_4578_B986_64C314F7A9EE
#define _INCLUDE_GUARD_B9D2E995_F86E_4578_B986_64C314F7A9EE
#include <cstdint>
#include <type_traits>
#include <minwindef.h>
#include <objbase.h>
#include "CommonLowLevel.h"
#include "../DynamicType/DynamicType.h"
#include "../Exception/Exception.h"
#include "../Exception/ExceptionWindows.h"
#include "Common.h"
namespace YBWLib2 {
/// <summary>Converts an ANSI string into a UTF-16 string.</summary>
/// <param name="rawallocator">Pointer to an <c>rawallocator_t</c> object for allocating memory used by the function.</param>
/// <param name="str_out_ret">
/// Pointer to a pointer variable that receives a pointer to the output string, in UTF-16.
/// After successfully returning from this function, <c>*str_out_ret</c> will be set to the output string.
/// The caller is responsible for freeing the memory pointed to by <c>*str_out_ret</c>.
/// The memory will be allocated using <paramref name="rawallocator" />.
/// Any value originally in <c>*str_out_ret</c> will be discarded (without freeing the memory pointed to by it, if any).
/// </param>
/// <param name="size_str_out_ret">
/// Pointer to a variable that receives the size (in <c>char16_t</c>s) of the output string, in UTF-16.
/// After successfully returning from this function, <c>*size_str_out_ret</c> will be set to the size (in <c>char16_t</c>s) of the output string.
/// Any value originally in <c>*size_str_out_ret</c> will be discarded.
/// </param>
/// <param name="str_in">Pointer to the input string, in ANSI.</param>
/// <param name="size_str_in">The size, in <c>char</c>s, of the input string, in ANSI, pointed to by <c>str_in</c>.</param>
/// <returns>
/// Returns a pointer to the exception object if the function fails.
/// Returns an empty pointer otherwise.
/// The caller is responsible for destructing and freeing the object pointed to.
/// </returns>
[[nodiscard]] YBWLIB2_API IException* YBWLIB2_CALLTYPE AnsiStringToUtf16String(
const rawallocator_t* rawallocator,
char16_t** str_out_ret,
size_t* size_str_out_ret,
const char* str_in,
size_t size_str_in
) noexcept;
/// <summary>Converts a UTF-16 string into a ANSI string.</summary>
/// <param name="rawallocator">Pointer to an <c>rawallocator_t</c> object for allocating memory used by the function.</param>
/// <param name="str_out_ret">
/// Pointer to a pointer variable that receives a pointer to the output string, in ANSI.
/// After successfully returning from this function, <c>*str_out_ret</c> will be set to the output string.
/// The caller is responsible for freeing the memory pointed to by <c>*str_out_ret</c>.
/// The memory will be allocated using <paramref name="rawallocator" />.
/// Any value originally in <c>*str_out_ret</c> will be discarded (without freeing the memory pointed to by it, if any).
/// </param>
/// <param name="size_str_out_ret">
/// Pointer to a variable that receives the size (in <c>char</c>s) of the output string, in ANSI.
/// After successfully returning from this function, <c>*size_str_out_ret</c> will be set to the size (in <c>char</c>s) of the output string.
/// Any value originally in <c>*size_str_out_ret</c> will be discarded.
/// </param>
/// <param name="str_in">Pointer to the input string, in UTF-16.</param>
/// <param name="size_str_in">The size, in <c>char16_t</c>s, of the input string, in UTF-16, pointed to by <c>str_in</c>.</param>
/// <returns>
/// Returns a pointer to the exception object if the function fails.
/// Returns an empty pointer otherwise.
/// The caller is responsible for destructing and freeing the object pointed to.
/// </returns>
[[nodiscard]] YBWLIB2_API IException* YBWLIB2_CALLTYPE Utf16StringToAnsiString(
const rawallocator_t* rawallocator,
char** str_out_ret,
size_t* size_str_out_ret,
const char16_t* str_in,
size_t size_str_in
) noexcept;
/// <summary>Win32 handle holder.</summary>
class Win32HandleHolder final {
public:
struct view_handle_t {};
struct own_handle_t {};
struct no_eliminate_invalid_handle_value_t {};
struct change_desired_access_t {};
static constexpr view_handle_t view_handle {};
static constexpr own_handle_t own_handle {};
static constexpr no_eliminate_invalid_handle_value_t no_eliminate_invalid_handle_value {};
static constexpr change_desired_access_t change_desired_access {};
inline constexpr Win32HandleHolder() noexcept {}
inline constexpr Win32HandleHolder(view_handle_t, const HANDLE& _win32handle) noexcept : win32handle(_win32handle == INVALID_HANDLE_VALUE ? NULL : _win32handle), is_owned_handle(false) {}
inline constexpr Win32HandleHolder(view_handle_t, no_eliminate_invalid_handle_value_t, const HANDLE& _win32handle) noexcept : win32handle(_win32handle), is_owned_handle(false) {}
inline constexpr Win32HandleHolder(own_handle_t, HANDLE&& _win32handle) noexcept : win32handle(_win32handle == INVALID_HANDLE_VALUE ? NULL : _win32handle), is_owned_handle(true) {
_win32handle = NULL;
}
inline constexpr Win32HandleHolder(own_handle_t, no_eliminate_invalid_handle_value_t, HANDLE&& _win32handle) noexcept : win32handle(_win32handle), is_owned_handle(true) {
_win32handle = NULL;
}
inline Win32HandleHolder(const Win32HandleHolder& x) noexcept(false) {
if (x.win32handle) {
IException* err = Win32HandleHolder::CopyWin32Handle(x.win32handle, &this->win32handle);
if (err) throw(err);
this->is_owned_handle = true;
} else {
this->win32handle = NULL;
this->is_owned_handle = false;
}
}
inline Win32HandleHolder(const Win32HandleHolder& x, change_desired_access_t, DWORD _desiredaccess) noexcept(false) {
if (x.win32handle) {
IException* err = Win32HandleHolder::CopyWin32HandleChangeDesiredAccess(x.win32handle, &this->win32handle, _desiredaccess);
if (err) throw(err);
this->is_owned_handle = true;
} else {
this->win32handle = NULL;
this->is_owned_handle = false;
}
}
inline Win32HandleHolder(Win32HandleHolder&& x) noexcept {
this->win32handle = ::std::move(x.win32handle);
x.win32handle = NULL;
this->is_owned_handle = ::std::move(x.is_owned_handle);
x.is_owned_handle = false;
}
inline ~Win32HandleHolder() {
Win32HandleHolder::ClearWin32Handle(&this->win32handle, this->is_owned_handle);
this->is_owned_handle = false;
}
inline Win32HandleHolder& operator=(const Win32HandleHolder& x) noexcept(false) {
Win32HandleHolder::ClearWin32Handle(&this->win32handle, this->is_owned_handle);
this->is_owned_handle = false;
if (x.win32handle) {
IException* err = Win32HandleHolder::CopyWin32Handle(x.win32handle, &this->win32handle);
if (err) throw(err);
this->is_owned_handle = true;
} else {
this->win32handle = NULL;
this->is_owned_handle = false;
}
return *this;
}
inline Win32HandleHolder& operator=(Win32HandleHolder&& x) noexcept {
Win32HandleHolder::ClearWin32Handle(&this->win32handle, this->is_owned_handle);
this->is_owned_handle = false;
this->win32handle = ::std::move(x.win32handle);
x.win32handle = NULL;
this->is_owned_handle = ::std::move(x.is_owned_handle);
x.is_owned_handle = false;
return *this;
}
inline void swap(Win32HandleHolder& x) noexcept {
HANDLE win32handle_temp = this->win32handle;
bool is_owned_handle_temp = this->is_owned_handle;
this->win32handle = x.win32handle;
this->is_owned_handle = x.is_owned_handle;
x.win32handle = win32handle_temp;
x.is_owned_handle = is_owned_handle_temp;
}
inline void reset() noexcept {
Win32HandleHolder::ClearWin32Handle(&this->win32handle, this->is_owned_handle);
this->is_owned_handle = false;
}
inline void reset(view_handle_t, const HANDLE& _win32handle) noexcept {
Win32HandleHolder::ClearWin32Handle(&this->win32handle, this->is_owned_handle);
this->is_owned_handle = false;
this->win32handle = _win32handle == INVALID_HANDLE_VALUE ? NULL : _win32handle;
this->is_owned_handle = false;
}
inline void reset(view_handle_t, no_eliminate_invalid_handle_value_t, const HANDLE& _win32handle) noexcept {
Win32HandleHolder::ClearWin32Handle(&this->win32handle, this->is_owned_handle);
this->is_owned_handle = false;
this->win32handle = _win32handle;
this->is_owned_handle = false;
}
inline void reset(own_handle_t, HANDLE&& _win32handle) noexcept {
Win32HandleHolder::ClearWin32Handle(&this->win32handle, this->is_owned_handle);
this->is_owned_handle = false;
this->win32handle = _win32handle == INVALID_HANDLE_VALUE ? NULL : _win32handle;
_win32handle = NULL;
this->is_owned_handle = true;
}
inline void reset(own_handle_t, no_eliminate_invalid_handle_value_t, HANDLE&& _win32handle) noexcept {
Win32HandleHolder::ClearWin32Handle(&this->win32handle, this->is_owned_handle);
this->is_owned_handle = false;
this->win32handle = _win32handle;
_win32handle = NULL;
this->is_owned_handle = true;
}
inline HANDLE get() const noexcept { return this->win32handle; }
inline explicit operator bool() const noexcept { return this->win32handle; }
protected:
HANDLE win32handle = NULL;
bool is_owned_handle = false;
static YBWLIB2_API void YBWLIB2_CALLTYPE ClearWin32Handle(HANDLE* _win32handle, bool _is_owned_handle) noexcept;
[[nodiscard]] static YBWLIB2_API IException* YBWLIB2_CALLTYPE CopyWin32Handle(HANDLE _win32handle_from, HANDLE* _win32handle_to) noexcept;
[[nodiscard]] static YBWLIB2_API IException* YBWLIB2_CALLTYPE CopyWin32HandleChangeDesiredAccess(HANDLE _win32handle_from, HANDLE* _win32handle_to, DWORD _desiredaccess) noexcept;
};
static_assert(::std::is_standard_layout_v<Win32HandleHolder>, "Win32HandleHolder is not standard-layout.");
inline bool operator==(const Win32HandleHolder& l, const Win32HandleHolder& r) { return l.get() == r.get(); }
inline bool operator!=(const Win32HandleHolder& l, const Win32HandleHolder& r) { return l.get() != r.get(); }
inline bool operator<(const Win32HandleHolder& l, const Win32HandleHolder& r) { return l.get() < r.get(); }
inline bool operator<=(const Win32HandleHolder& l, const Win32HandleHolder& r) { return l.get() <= r.get(); }
inline bool operator>(const Win32HandleHolder& l, const Win32HandleHolder& r) { return l.get() > r.get(); }
inline bool operator>=(const Win32HandleHolder& l, const Win32HandleHolder& r) { return l.get() >= r.get(); }
inline ULONG STDMETHODCALLTYPE COMHelper_ReferenceCountedObject_AddRef(const IReferenceCountedObject* _obj) noexcept {
assert(_obj);
return _obj->GetReferenceCountControlBlock()->IncStrongReferenceCount() & ~(ULONG)0;
}
inline ULONG STDMETHODCALLTYPE COMHelper_ReferenceCountedObject_Release(const IReferenceCountedObject* _obj) noexcept {
assert(_obj);
return _obj->GetReferenceCountControlBlock()->DecStrongReferenceCount() & ~(ULONG)0;
}
template<typename T_Class, typename... T_Interface>
inline HRESULT STDMETHODCALLTYPE COMHelper_QueryInterface(
T_Class* _obj,
const IID& _iid,
_COM_Outptr_ void** _obj_ret
) {
static_assert(::std::conjunction_v<::std::is_base_of<IUnknown, T_Interface>...>, "At least one of the interface classes is not derived from IUnknown.");
static_assert(::std::conjunction_v<::std::is_convertible<T_Class*, T_Interface*>...>, "Pointer to at least one of the interface classes cannot be implicitly converted from pointer to the specified class.");
assert(_obj);
if (!_obj_ret) return E_POINTER;
using fnptr_cast_t = void* (__stdcall*)(T_Class* _ptr) noexcept;
using map_cast_t = ::std::unordered_map<IID, fnptr_cast_t, hash_trivially_copyable_t<IID, size_t>>;
static const map_cast_t map_cast(
{
{
__uuidof(T_Interface),
[](T_Class* _ptr) noexcept->void* { static_cast<T_Interface*>(_ptr)->AddRef(); return reinterpret_cast<void*>(static_cast<T_Interface*>(_ptr)); }
}...
}
);
typename map_cast_t::const_iterator it_map_cast = map_cast.find(_iid);
if (it_map_cast == map_cast.cend()) {
*_obj_ret = nullptr;
return E_NOINTERFACE;
} else {
*_obj_ret = (*it_map_cast->second)(_obj);
return S_OK;
}
}
template<class T_Element>
class COMObjectHolder {
public:
struct inc_ref_count_t {};
static constexpr inc_ref_count_t inc_ref_count {};
using element_type = T_Element;
static_assert(::std::is_base_of_v<IUnknown, element_type>, "The element class is not derived from IUnknown.");
inline constexpr COMObjectHolder() noexcept = default;
inline constexpr COMObjectHolder(nullptr_t) noexcept : COMObjectHolder() {}
/// <summary>
/// Constructs a <c>COMObjectHolder</c> that manages the COM object the specified pointer points to, without changing the object's reference count.
/// Use this function on a freshly obtained pointer that has one reference count reserved for the caller.
/// </summary>
template<typename T_Element_From, typename ::std::enable_if<::std::is_convertible_v<T_Element_From*, element_type*>, int>::type = 0>
inline explicit COMObjectHolder(T_Element_From*&& _ptr_element) noexcept : ptr_element(static_cast<element_type*&&>(_ptr_element)) {}
/// <summary>
/// Constructs a <c>COMObjectHolder</c> that manages the COM object the specified pointer points to, incrementing the object's reference count.
/// Use this function on an existing pointer that has no reference counts reserved for the caller.
/// </summary>
template<typename T_Element_From, typename ::std::enable_if<::std::is_convertible_v<T_Element_From*, element_type*>, int>::type = 0>
inline COMObjectHolder(T_Element_From* _ptr_element, inc_ref_count_t) noexcept {
if (_ptr_element) {
static_cast<element_type*>(_ptr_element)->AddRef();
this->ptr_element = static_cast<element_type*>(_ptr_element);
}
}
template<typename T_Element_From, typename ::std::enable_if<::std::is_convertible_v<T_Element_From*, element_type*>, int>::type = 0>
inline COMObjectHolder(const COMObjectHolder<T_Element_From>& x) noexcept {
if (x.ptr_element) {
x.ptr_element->AddRef();
this->ptr_element = static_cast<element_type*>(x.ptr_element);
}
}
template<typename T_Element_From, typename ::std::enable_if<::std::is_convertible_v<T_Element_From*, element_type*>, int>::type = 0>
inline COMObjectHolder(COMObjectHolder<T_Element_From>&& x) noexcept {
this->ptr_element = static_cast<element_type*&&>(::std::move(x.ptr_element));
x.ptr_element = nullptr;
}
template<typename T_Element_From, typename ::std::enable_if<!::std::is_convertible_v<T_Element_From*, element_type*>, int>::type = 0>
inline COMObjectHolder(const COMObjectHolder<T_Element_From>& x) noexcept(false) {
if (x.ptr_element) {
HRESULT hr = x->QueryInterface(__uuidof(element_type), &this->get_ref_ptr_element());
if (FAILED(hr)) {
if (hr != E_NOINTERFACE) {
throw(new ExternalAPIFailureWithHRESULTException(u8"IUnknown::QueryInterface", sizeof(u8"IUnknown::QueryInterface") / sizeof(char) - 1, nullptr, hr));
} else {
this->reset();
}
}
}
}
template<typename T_Element_From, typename ::std::enable_if<!::std::is_convertible_v<T_Element_From*, element_type*>, int>::type = 0>
inline COMObjectHolder(COMObjectHolder<T_Element_From>&& x) noexcept(false) {
if (x.ptr_element) {
HRESULT hr = x->QueryInterface(__uuidof(element_type), &this->get_ref_ptr_element());
if (FAILED(hr)) {
if (hr != E_NOINTERFACE) {
throw(new ExternalAPIFailureWithHRESULTException(u8"IUnknown::QueryInterface", sizeof(u8"IUnknown::QueryInterface") / sizeof(char) - 1, nullptr, hr));
} else {
this->reset();
}
}
}
::std::move(x).reset();
}
inline ~COMObjectHolder() {
this->reset();
}
template<typename T_Element_From, typename ::std::enable_if<::std::is_convertible_v<T_Element_From*, element_type*>, int>::type = 0>
inline COMObjectHolder& operator=(const COMObjectHolder<T_Element_From>& x) noexcept {
this->reset();
if (x.ptr_element) {
x.ptr_element->AddRef();
this->ptr_element = static_cast<element_type*>(x.ptr_element);
}
}
template<typename T_Element_From, typename ::std::enable_if<::std::is_convertible_v<T_Element_From*, element_type*>, int>::type = 0>
inline COMObjectHolder& operator=(COMObjectHolder<T_Element_From>&& x) noexcept {
this->reset();
this->ptr_element = static_cast<element_type*&&>(::std::move(x.ptr_element));
x.ptr_element = nullptr;
}
inline explicit operator bool() const noexcept { return this->ptr_element; }
inline element_type& operator*() const noexcept {
assert(this->ptr_element);
return *this->ptr_element;
}
inline element_type* operator->() const noexcept {
assert(this->ptr_element);
return this->ptr_element;
}
inline element_type* const& get() const noexcept { return this->ptr_element; }
inline void reset() noexcept {
if (this->ptr_element) {
this->ptr_element->Release();
this->ptr_element = nullptr;
}
}
inline void reset(nullptr_t) noexcept {
this->reset();
}
/// <summary>
/// Makes this object manage the object the specified pointer points to, without changing the object's reference count.
/// Use this function on a freshly obtained pointer that has one reference count reserved for the caller.
/// </summary>
template<typename T_Element_From, typename ::std::enable_if<::std::is_convertible_v<T_Element_From*, element_type*>, int>::type = 0>
inline void reset(T_Element_From*&& _ptr_element) noexcept {
this->reset();
this->ptr_element = static_cast<element_type*&&>(_ptr_element);
}
/// <summary>
/// Makes this object manage the object the specified pointer points to, incrementing the object's reference count.
/// Use this function on an existing pointer that has no reference counts reserved for the caller.
/// </summary>
template<typename T_Element_From, typename ::std::enable_if<::std::is_convertible_v<T_Element_From*, element_type*>, int>::type = 0>
inline void reset(T_Element_From* _ptr_element, inc_ref_count_t) noexcept {
this->reset();
if (_ptr_element) {
static_cast<element_type*>(_ptr_element)->AddRef();
this->ptr_element = static_cast<element_type*>(_ptr_element);
}
}
/// <summary>
/// Releases the stored pointer without changing the reference count.
/// </summary>
[[nodiscard]] inline element_type*&& release() noexcept {
element_type* ptr_element_old = this->ptr_element;
this->ptr_element = nullptr;
return ::std::move(ptr_element_old);
}
inline element_type*& get_ref_ptr_element() noexcept {
this->reset();
return this->ptr_element;
}
inline void swap(COMObjectHolder& x) noexcept {
element_type* ptr_element_temp = this->ptr_element;
this->ptr_element = x.ptr_element;
x.ptr_element = ptr_element_temp;
}
protected:
element_type* ptr_element = nullptr;
};
template<typename T_Element_L, typename T_Element_R>
inline bool operator==(const COMObjectHolder<T_Element_L>& l, const COMObjectHolder<T_Element_R>& r) noexcept {
if constexpr (::std::is_same_v<T_Element_L, T_Element_R>) {
return l.get() == r.get();
} else {
try {
return COMObjectHolder<IUnknown>(l).get() == COMObjectHolder<IUnknown>(r).get();
} catch (...) {
abort();
}
}
}
template<typename T_Element>
inline bool operator==(nullptr_t, const COMObjectHolder<T_Element>& r) noexcept { return nullptr == r.get(); }
template<typename T_Element>
inline bool operator==(const COMObjectHolder<T_Element>& l, nullptr_t) noexcept { return l.get() == nullptr; }
template<typename T_Element_L, typename T_Element_R>
inline bool operator!=(const COMObjectHolder<T_Element_L>& l, const COMObjectHolder<T_Element_R>& r) noexcept {
if constexpr (::std::is_same_v<T_Element_L, T_Element_R>) {
return l.get() != r.get();
} else {
try {
return COMObjectHolder<IUnknown>(l).get() != COMObjectHolder<IUnknown>(r).get();
} catch (...) {
abort();
}
}
}
template<typename T_Element>
inline bool operator!=(nullptr_t, const COMObjectHolder<T_Element>& r) noexcept { return nullptr != r.get(); }
template<typename T_Element>
inline bool operator!=(const COMObjectHolder<T_Element>& l, nullptr_t) noexcept { return l.get() != nullptr; }
template<typename T_Element_L, typename T_Element_R>
inline bool operator<(const COMObjectHolder<T_Element_L>& l, const COMObjectHolder<T_Element_R>& r) noexcept {
if constexpr (::std::is_same_v<T_Element_L, T_Element_R>) {
return l.get() < r.get();
} else {
try {
return COMObjectHolder<IUnknown>(l).get() < COMObjectHolder<IUnknown>(r).get();
} catch (...) {
abort();
}
}
}
template<typename T_Element>
inline bool operator<(nullptr_t, const COMObjectHolder<T_Element>& r) noexcept { return nullptr < r.get(); }
template<typename T_Element>
inline bool operator<(const COMObjectHolder<T_Element>& l, nullptr_t) noexcept { return l.get() < nullptr; }
template<typename T_Element_L, typename T_Element_R>
inline bool operator<=(const COMObjectHolder<T_Element_L>& l, const COMObjectHolder<T_Element_R>& r) noexcept {
if constexpr (::std::is_same_v<T_Element_L, T_Element_R>) {
return l.get() <= r.get();
} else {
try {
return COMObjectHolder<IUnknown>(l).get() <= COMObjectHolder<IUnknown>(r).get();
} catch (...) {
abort();
}
}
}
template<typename T_Element>
inline bool operator<=(nullptr_t, const COMObjectHolder<T_Element>& r) noexcept { return nullptr <= r.get(); }
template<typename T_Element>
inline bool operator<=(const COMObjectHolder<T_Element>& l, nullptr_t) noexcept { return l.get() <= nullptr; }
template<typename T_Element_L, typename T_Element_R>
inline bool operator>(const COMObjectHolder<T_Element_L>& l, const COMObjectHolder<T_Element_R>& r) noexcept {
if constexpr (::std::is_same_v<T_Element_L, T_Element_R>) {
return l.get() > r.get();
} else {
try {
return COMObjectHolder<IUnknown>(l).get() > COMObjectHolder<IUnknown>(r).get();
} catch (...) {
abort();
}
}
}
template<typename T_Element>
inline bool operator>(nullptr_t, const COMObjectHolder<T_Element>& r) noexcept { return nullptr > r.get(); }
template<typename T_Element>
inline bool operator>(const COMObjectHolder<T_Element>& l, nullptr_t) noexcept { return l.get() > nullptr; }
template<typename T_Element_L, typename T_Element_R>
inline bool operator>=(const COMObjectHolder<T_Element_L>& l, const COMObjectHolder<T_Element_R>& r) noexcept {
if constexpr (::std::is_same_v<T_Element_L, T_Element_R>) {
return l.get() >= r.get();
} else {
try {
return COMObjectHolder<IUnknown>(l).get() >= COMObjectHolder<IUnknown>(r).get();
} catch (...) {
abort();
}
}
}
template<typename T_Element>
inline bool operator>=(nullptr_t, const COMObjectHolder<T_Element>& r) noexcept { return nullptr >= r.get(); }
template<typename T_Element>
inline bool operator>=(const COMObjectHolder<T_Element>& l, nullptr_t) noexcept { return l.get() >= nullptr; }
void YBWLIB2_CALLTYPE CommonWindows_RealInitGlobal() noexcept;
void YBWLIB2_CALLTYPE CommonWindows_RealUnInitGlobal() noexcept;
void YBWLIB2_CALLTYPE CommonWindows_RealInitModuleLocal() noexcept;
void YBWLIB2_CALLTYPE CommonWindows_RealUnInitModuleLocal() noexcept;
}
#endif
#ifdef _MACRO_DEFINE_TEMP_YBWLIB2_EXCEPTION_MACROS_ENABLED_B2352359_1626_4CF1_AEBF_4F58A5F48AD7
#undef YBWLIB2_EXCEPTION_MACROS_ENABLED
#include "../Exception/ExceptionMacroUndef.h"
#undef _MACRO_DEFINE_TEMP_YBWLIB2_EXCEPTION_MACROS_ENABLED_B2352359_1626_4CF1_AEBF_4F58A5F48AD7
#endif
#ifdef _MACRO_DEFINE_TEMP_YBWLIB2_DYNAMIC_TYPE_MACROS_ENABLED_83D6146A_4FDA_461C_84C5_8247F88A40CA
#undef YBWLIB2_DYNAMIC_TYPE_MACROS_ENABLED
#include "../DynamicType/DynamicTypeMacroUndef.h"
#undef _MACRO_DEFINE_TEMP_YBWLIB2_DYNAMIC_TYPE_MACROS_ENABLED_83D6146A_4FDA_461C_84C5_8247F88A40CA
#endif
| 47.472763 | 208 | 0.740789 | [
"object"
] |
d06b8c2c8b8b40d689d1d12acc3d70cbd958e313 | 1,389 | h | C | Code/Tools/ProjectManager/Source/ProjectUtils.h | cypherdotXd/o3de | bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676 | [
"Apache-2.0",
"MIT"
] | 1 | 2022-03-12T14:13:45.000Z | 2022-03-12T14:13:45.000Z | Code/Tools/ProjectManager/Source/ProjectUtils.h | cypherdotXd/o3de | bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676 | [
"Apache-2.0",
"MIT"
] | 2 | 2022-01-13T04:29:38.000Z | 2022-03-12T01:05:31.000Z | Code/Tools/ProjectManager/Source/ProjectUtils.h | cypherdotXd/o3de | bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676 | [
"Apache-2.0",
"MIT"
] | null | null | null | /*
* 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 <ScreenDefs.h>
#include <ProjectInfo.h>
#include <QWidget>
#include <AzCore/Outcome/Outcome.h>
namespace O3DE::ProjectManager
{
namespace ProjectUtils
{
bool AddProjectDialog(QWidget* parent = nullptr);
bool RegisterProject(const QString& path);
bool UnregisterProject(const QString& path);
bool CopyProjectDialog(const QString& origPath, ProjectInfo& newProjectInfo, QWidget* parent = nullptr);
bool CopyProject(const QString& origPath, const QString& newPath, QWidget* parent, bool skipRegister = false);
bool DeleteProjectFiles(const QString& path, bool force = false);
bool MoveProject(QString origPath, QString newPath, QWidget* parent, bool skipRegister = false);
bool ReplaceFile(const QString& origFile, const QString& newFile, QWidget* parent = nullptr, bool interactive = true);
bool FindSupportedCompiler(QWidget* parent = nullptr);
AZ::Outcome<void, QString> FindSupportedCompilerForPlatform();
ProjectManagerScreen GetProjectManagerScreen(const QString& screen);
} // namespace ProjectUtils
} // namespace O3DE::ProjectManager
| 38.583333 | 126 | 0.729302 | [
"3d"
] |
d06d8444473ab45d967e44f263a6539681117903 | 1,512 | h | C | include/exec/redis_scan_node.h | lvxinup/BaikalDB | e1ca1e273156e64fd0c3aef047d6d9b639be0c7b | [
"Apache-2.0"
] | 984 | 2018-08-03T16:22:49.000Z | 2022-03-22T07:54:48.000Z | include/exec/redis_scan_node.h | lvxinup/BaikalDB | e1ca1e273156e64fd0c3aef047d6d9b639be0c7b | [
"Apache-2.0"
] | 100 | 2018-08-07T11:33:18.000Z | 2021-12-22T19:22:43.000Z | include/exec/redis_scan_node.h | lvxinup/BaikalDB | e1ca1e273156e64fd0c3aef047d6d9b639be0c7b | [
"Apache-2.0"
] | 157 | 2018-08-04T05:32:34.000Z | 2022-03-10T03:16:47.000Z | // Copyright (c) 2018-present Baidu, 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.
#pragma once
#include "exec_node.h"
#include "scan_node.h"
#include "table_record.h"
#ifdef BAIDU_INTERNAL
#include <baidu/rpc/channel.h>
#include <baidu/rpc/redis.h>
#else
#include <brpc/channel.h>
#include <brpc/redis.h>
#endif
namespace baikaldb {
// 一个支持redis get的简单示例
class RedisScanNode : public ScanNode {
public:
RedisScanNode() {
}
virtual int init(const pb::PlanNode& node);
virtual int get_next(RuntimeState* state, RowBatch* batch, bool* eos);
virtual int open(RuntimeState* state);
virtual void close(RuntimeState* state);
private:
// 对于kv来说,只需要改这个函数,就能支持其他的类似kv需求
// SmartRecord是kv数据源与BaikalDB的接口,是一个pb封装
// 与建表的字段一一对应
int get_by_key(SmartRecord record);
private:
brpc::Channel _redis_channel;
std::vector<SmartRecord> _primary_records;
size_t _idx = 0;
int64_t _index_id;
};
}
/* vim: set ts=4 sw=4 sts=4 tw=100 */
| 28.528302 | 75 | 0.725529 | [
"vector"
] |
d071d24e72291f2d3620fb53be5d594132ae7d49 | 4,790 | h | C | tools-src/gnu/binutils/binutils/coffgrok.h | enfoTek/tomato.linksys.e2000.nvram-mod | 2ce3a5217def49d6df7348522e2bfda702b56029 | [
"FSFAP"
] | 80 | 2015-01-02T10:14:04.000Z | 2021-06-07T06:29:49.000Z | tools-src/gnu/binutils/binutils/coffgrok.h | unforgiven512/tomato | 96f09fab4929c6ddde5c9113f1b2476ad37133c4 | [
"FSFAP"
] | 9 | 2015-05-14T11:03:12.000Z | 2018-01-04T07:12:58.000Z | tools-src/gnu/binutils/binutils/coffgrok.h | unforgiven512/tomato | 96f09fab4929c6ddde5c9113f1b2476ad37133c4 | [
"FSFAP"
] | 69 | 2015-01-02T10:45:56.000Z | 2021-09-06T07:52:13.000Z | /* coffgrok.h
Copyright 2001 Free Software Foundation, Inc.
This file is part of GNU Binutils.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
#define T_NULL 0
#define T_VOID 1 /* function argument (only used by compiler) */
#define T_CHAR 2 /* character */
#define T_SHORT 3 /* short integer */
#define T_INT 4 /* integer */
#define T_LONG 5 /* long integer */
#define T_FLOAT 6 /* floating point */
#define T_DOUBLE 7 /* double word */
#define T_STRUCT 8 /* structure */
#define T_UNION 9 /* union */
#define T_ENUM 10 /* enumeration */
#define T_MOE 11 /* member of enumeration*/
#define T_UCHAR 12 /* unsigned character */
#define T_USHORT 13 /* unsigned short */
#define T_UINT 14 /* unsigned integer */
#define T_ULONG 15 /* unsigned long */
#define T_LNGDBL 16 /* long double */
struct coff_reloc
{
int offset;
struct coff_symbol *symbol;
int addend;
};
struct coff_section
{
char *name;
int code;
int data;
int address;
int number; /* 0..n, .text = 0 */
int nrelocs;
int size;
struct coff_reloc *relocs;
struct sec *bfd_section;
};
struct coff_ofile
{
int nsources;
struct coff_sfile *source_head;
struct coff_sfile *source_tail;
int nsections;
struct coff_section *sections;
struct coff_symbol *symbol_list_head;
struct coff_symbol *symbol_list_tail;
};
struct coff_isection {
int low;
int high;
int init;
struct coff_section *parent;
};
struct coff_sfile
{
char *name;
struct coff_scope *scope;
struct coff_sfile *next;
/* Vector which maps where in each output section
the input file has it's data */
struct coff_isection *section;
};
struct coff_type
{
int size;
enum
{
coff_pointer_type, coff_function_type, coff_array_type, coff_structdef_type, coff_basic_type,
coff_structref_type, coff_enumref_type, coff_enumdef_type, coff_secdef_type
} type;
union
{
struct
{
int address;
int size;
} asecdef;
struct
{
int isstruct;
struct coff_scope *elements;
int idx;
}
astructdef;
struct
{
struct coff_symbol *ref;
} astructref;
struct
{
struct coff_scope *elements;
int idx;
} aenumdef;
struct
{
struct coff_symbol *ref;
} aenumref;
struct
{
struct coff_type *points_to;
} pointer;
struct
{
int dim;
struct coff_type *array_of;
} array;
struct
{
struct coff_type *function_returns;
struct coff_scope *parameters;
struct coff_scope *code;
struct coff_line *lines;
} function;
int basic; /* One of T_VOID.. T_UINT */
} u;
};
struct coff_line
{
int nlines;
int *lines;
int *addresses;
};
struct coff_scope
{
struct coff_section *sec; /* What section */
int offset; /* where */
int size; /* How big */
struct coff_scope *parent; /* one up */
struct coff_scope *next; /*next along */
int nvars;
struct coff_symbol *vars_head; /* symbols */
struct coff_symbol *vars_tail;
struct coff_scope *list_head; /* children */
struct coff_scope *list_tail;
};
struct coff_visible
{
enum coff_vis_type
{
coff_vis_ext_def,
coff_vis_ext_ref,
coff_vis_int_def,
coff_vis_common,
coff_vis_auto,
coff_vis_register,
coff_vis_tag,
coff_vis_member_of_struct,
coff_vis_member_of_enum,
coff_vis_autoparam,
coff_vis_regparam,
} type;
};
struct coff_where
{
enum
{
coff_where_stack, coff_where_memory, coff_where_register, coff_where_unknown,
coff_where_strtag, coff_where_member_of_struct,
coff_where_member_of_enum, coff_where_entag, coff_where_typedef
} where;
int offset;
int bitoffset;
int bitsize;
struct coff_section *section;
};
struct coff_symbol
{
char *name;
int tag;
struct coff_type *type;
struct coff_where *where;
struct coff_visible *visible;
struct coff_symbol *next;
struct coff_symbol *next_in_ofile_list; /* For the ofile list */
int number;
int er_number;
struct coff_sfile *sfile;
};
struct coff_ofile *coff_grok PARAMS ((bfd *));
| 21.19469 | 99 | 0.682046 | [
"vector"
] |
d0799da1c3555712dc0e58e09d5d779ef49b6d6b | 2,572 | h | C | DriveFusion/ContextMenuCBHandler.h | JadeTheFlame/google-drive-shell-extension | 917ada8e1a173e43e637db980ac4b9976a34acf9 | [
"Apache-2.0"
] | 155 | 2015-03-25T22:09:37.000Z | 2022-03-07T14:51:31.000Z | DriveFusion/ContextMenuCBHandler.h | Jason-Cooke/google-drive-shell-extension | 917ada8e1a173e43e637db980ac4b9976a34acf9 | [
"Apache-2.0"
] | 13 | 2015-04-01T17:51:45.000Z | 2021-08-21T13:36:39.000Z | DriveFusion/ContextMenuCBHandler.h | Jason-Cooke/google-drive-shell-extension | 917ada8e1a173e43e637db980ac4b9976a34acf9 | [
"Apache-2.0"
] | 73 | 2015-03-26T02:21:54.000Z | 2022-03-26T10:22:46.000Z | /*
Copyright 2014 Google 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.
*/
#pragma once
#include "stdafx.h"
#include "FusionGDShell_i.h"
#if defined(_WIN32_WCE) && !defined(_CE_DCOM) && !defined(_CE_ALLOW_SINGLE_THREADED_OBJECTS_IN_MTA)
#error "Single-threaded COM objects are not properly supported on Windows CE platform, such as the Windows Mobile platforms that do not include full DCOM support. Define _CE_ALLOW_SINGLE_THREADED_OBJECTS_IN_MTA to force ATL to support creating single-thread COM object's and allow use of it's single-threaded COM object implementations. The threading model in your rgs file was set to 'Free' as that is the only threading model supported in non DCOM Windows CE platforms."
#endif
using namespace ATL;
class CGDriveShlExt;
class CDriveItem;
class ContextMenuCBHandler :
public CComObjectRootEx<CComSingleThreadModel>,
public IContextMenuCB
{
public:
ContextMenuCBHandler()
{
Log::WriteOutput(LogType::Debug, L"GDriveCBHandler::GDriveCBHandler()");
_gDriveShlExt = NULL;
}
BEGIN_COM_MAP(ContextMenuCBHandler)
COM_INTERFACE_ENTRY(IContextMenuCB)
END_COM_MAP()
DECLARE_PROTECT_FINAL_CONSTRUCT()
static HRESULT CreateInstance(CGDriveShlExt *gDriveShlExt, __deref_out CComObject<ContextMenuCBHandler> **ppv);
HRESULT ReturnInterfaceTo(REFIID riid, __deref_out void **ppv);
HRESULT FinalConstruct()
{
return S_OK;
}
void FinalRelease();
// IContextMenuCB
IFACEMETHODIMP CallBack(__in_opt IShellFolder *psf, HWND hwndOwner, __in_opt IDataObject *pdtobj, UINT uiMsg, WPARAM wParam, LPARAM lParam);
void DownloadFiles();
private:
HRESULT _Initialize(CGDriveShlExt* gDriveShlExt);
HRESULT _ConvertDataObjectToVectorOfDriveItems(__in IDataObject *pdo, std::vector<CDriveItem>* driveItemList) const;
void _ReleaseContextMenuSelection();
void _DownloadFilesIfReady();
std::wstring _GetContextMenuCBString(UINT uiMsg, WPARAM wParam, LPARAM lParam);
bool _PdoIsGoogleDoc(IDataObject& pdo) const;
private:
CGDriveShlExt* _gDriveShlExt;
IDataObject* _pdo;
bool _downloadWhenReady;
};
| 32.15 | 472 | 0.78888 | [
"object",
"vector",
"model"
] |
d07b1a254ed5a1ba0458bb275b3ec1030893575f | 918 | h | C | examples/lecturedemos/lecturedemorefine.h | Pascal-So/lehrfempp | e2716e914169eec7ee59e822ea3ab303143eacd1 | [
"MIT"
] | null | null | null | examples/lecturedemos/lecturedemorefine.h | Pascal-So/lehrfempp | e2716e914169eec7ee59e822ea3ab303143eacd1 | [
"MIT"
] | null | null | null | examples/lecturedemos/lecturedemorefine.h | Pascal-So/lehrfempp | e2716e914169eec7ee59e822ea3ab303143eacd1 | [
"MIT"
] | null | null | null | #ifndef LF_LD_REF_H
#define LF_LD_REF_H
/**
* @file
* @brief Simple LehrFEM demo code for refinement
* @author Ralf Hiptmair
* @date March 2019
* @copyright MIT License
*/
#include <lf/assemble/assemble.h>
#include <lf/geometry/geometry.h>
#include <lf/io/io.h>
#include <lf/mesh/hybrid2d/hybrid2d.h>
#include <lf/refinement/refinement.h>
#include "lf/mesh/test_utils/test_meshes.h"
namespace lecturedemo {
/** @brief Creates a hierarchy of meshes by regular refinement
*
* @param mesh reference to a mesh object
*
* This function just creates a mesh hierarchy by regular refinement
* and outputs the numbers of various entities on different levels.
* Does not serve any other purpose.
*/
void regrefMeshSequence(std::shared_ptr<lf::mesh::Mesh> mesh_p, int refsteps);
/** @brief Demonstration of regular refinement: driver function
*/
void lecturedemorefine();
} // namespace lecturedemo
#endif
| 24.810811 | 78 | 0.745098 | [
"mesh",
"geometry",
"object"
] |
d0849c41b71f1e93515f8b3f38e37b30bb92aa0e | 29,034 | h | C | libs/math/matrix_svd.h | vaheta/ourmve | 8bc4c7ccadd1182d42d1c27be1196b4eef99d1f2 | [
"BSD-3-Clause"
] | null | null | null | libs/math/matrix_svd.h | vaheta/ourmve | 8bc4c7ccadd1182d42d1c27be1196b4eef99d1f2 | [
"BSD-3-Clause"
] | null | null | null | libs/math/matrix_svd.h | vaheta/ourmve | 8bc4c7ccadd1182d42d1c27be1196b4eef99d1f2 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (C) 2015, Daniel Thuerck, Simon Fuhrmann
* TU Darmstadt - Graphics, Capture and Massively Parallel Computing
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the BSD 3-Clause license. See the LICENSE.txt file for details.
*
* The matrix formats for this implementation are exemplary visualized:
*
* A A U U
* A A = U U * S S * V V
* A A U U S S V V
*
* S S S V V V
* A A A = U U U * S S S * V V V
* A A A U U U S S S V V V
*/
#ifndef MATH_MATRIX_SVD_HEADER
#define MATH_MATRIX_SVD_HEADER
#include <vector>
#include "math/defines.h"
#include "math/matrix.h"
#include "math/matrix_tools.h"
#include "math/matrix_qr.h"
MATH_NAMESPACE_BEGIN
/**
* SVD for dynamic-size matrices A of size MxN (M rows, N columns).
* The function decomposes input matrix A such that A = USV^T where
* A is MxN, U is MxN, S is a N-vector and V is NxN.
* Any of U, S or V can be NULL, however, this does not save operations.
*
* Usually, M >= N, i.e. the input matrix has more rows than columns.
* If M > 5/3 N, QR decomposition is used to do an economy SVD after Chan
* that saves some operations. This SVD also handles the case where M < N. In
* this case, zero rows are internally added to A until A is a square matrix.
*
* References:
* - "Matrix Computations" by Gloub and Loan (page 455, algo 8.6.2, [GK-SVD])
* - "An Improved Algorithm for Computing the SVD" by Chan (1987) [R-SVD].
*/
template <typename T>
void
matrix_svd (T const* mat_a, int rows, int cols,
T* mat_u, T* vec_s, T* mat_v, T const& epsilon = T(1e-12));
/**
* SVD for compile-time fixed-size matrices. The implementation of this
* function uses the dynamic-size matrices interface in the background.
* Any of the results can be NULL, however, this does not save operations.
*/
template <typename T, int M, int N>
void
matrix_svd (Matrix<T, M, N> const& mat_a, Matrix<T, M, N>* mat_u,
Matrix<T, N, N>* mat_s, Matrix<T, N, N>* mat_v,
T const& epsilon = T(1e-12));
/**
* Computes the Moore–Penrose pseudoinverse of matrix A using the SVD.
* Let the SVD of A be A = USV*, then the pseudoinverse is A' = VS'U*.
* The inverse S' of S is obtained by taking the reciprocal of non-zero
* diagonal elements, leaving zeros (up to the epsilon) in place.
*/
template <typename T, int M, int N>
void
matrix_pseudo_inverse (Matrix<T, M, N> const& A,
Matrix<T, N, M>* result, T const& epsilon = T(1e-12));
MATH_NAMESPACE_END
/* ------------------------ SVD Internals ------------------------- */
MATH_NAMESPACE_BEGIN
MATH_INTERNAL_NAMESPACE_BEGIN
/**
* Checks whether the lower-right square sub-matrix of size KxK is enclosed by
* zeros (up to some epsilon) within a square matrix of size MxM. This check
* is SVD specific and probably not very useful for other code.
* Note: K must be smaller than or equal to M.
*/
template <typename T>
bool
matrix_is_submatrix_zero_enclosed (T const* mat, int m, int k, T const& epsilon)
{
int const j = m - k - 1;
if (j < 0)
return true;
for (int i = m - k; i < m; ++i)
if (!MATH_EPSILON_EQ(mat[j * m + i], T(0), epsilon)
|| !MATH_EPSILON_EQ(mat[i * m + j], T(0), epsilon))
return false;
return true;
}
/**
* Checks whether the super-diagonal (above the diagonal) of a MxN matrix
* does not contain zeros up to some epsilon.
*/
template <typename T>
bool
matrix_is_superdiagonal_nonzero (T const* mat,
int rows, int cols, T const& epsilon)
{
int const n = std::min(rows, cols) - 1;
for (int i = 0; i < n; ++i)
if (MATH_EPSILON_EQ(T(0), mat[i * cols + i + 1], epsilon))
return false;
return true;
}
/**
* Returns the larger eigenvalue of the given 2x2 matrix. The eigenvalues of
* the matrix are assumed to be non-complex and a negative root set to zero.
*/
template <typename T>
void
matrix_2x2_eigenvalues (T const* mat, T* smaller_ev, T* larger_ev)
{
/* For matrix [a b; c d] solve (a+d) / 2 + sqrt((a+d)^2 / 4 - ad + bc). */
T const& a = mat[0];
T const& b = mat[1];
T const& c = mat[2];
T const& d = mat[3];
T x = MATH_POW2(a + d) / T(4) - a * d + b * c;
x = (x > T(0) ? std::sqrt(x) : T(0));
*smaller_ev = (a + d) / T(2) - x;
*larger_ev = (a + d) / T(2) + x;
}
/**
* Creates a householder transformation vector and the coefficient for
* householder matrix creation. As input, the function uses a column-frame
* in a given matrix, i.e. mat(subset_row_start:subset_row_end,
* subset_col).
*/
template <typename T>
void
matrix_householder_vector (T const* input, int length,
T* vector, T* beta, T const& epsilon, T const& norm_factor)
{
T sigma(0);
for (int i = 1; i < length; ++i)
sigma += MATH_POW2(input[i] / norm_factor);
vector[0] = T(1);
for (int i = 1; i < length; ++i)
vector[i] = input[i] / norm_factor;
if (MATH_EPSILON_EQ(sigma, T(0), epsilon))
{
*beta = T(0);
return;
}
T first = input[0] / norm_factor;
T mu = std::sqrt(MATH_POW2(first) + sigma);
if (first < epsilon)
vector[0] = first - mu;
else
vector[0] = -sigma / (first + mu);
first = vector[0];
*beta = T(2) * MATH_POW2(first) / (sigma + MATH_POW2(first));
for (int i = 0; i < length; ++i)
vector[i] /= first;
}
/**
* Given a Householder vector and beta coefficient, this function creates
* a transformation matrix to apply the Householder Transformation by simple
* matrix multiplication.
*/
template <typename T>
void
matrix_householder_matrix (T const* vector, int length, T const beta,
T* matrix)
{
std::fill(matrix, matrix + length * length, T(0));
for (int i = 0; i < length; ++i)
{
matrix[i * length + i] = T(1);
}
for (int i = 0; i < length; ++i)
{
for (int j = 0; j < length; ++j)
{
matrix[i * length + j] -= beta * vector[i] * vector[j];
}
}
}
/**
* Applies a given householder matrix to a frame in a given matrix with
* offset (offset_rows, offset_cols).
*/
template <typename T>
void
matrix_apply_householder_matrix (T* mat_a, int rows, int cols,
T const* house_mat, int house_length, int offset_rows, int offset_cols)
{
/* Save block from old matrix that will be modified. */
int house_length_n = house_length - (rows - cols);
std::vector<T> rhs(house_length * house_length_n);
for (int i = 0; i < house_length; ++i)
{
for (int j = 0; j < house_length_n; ++j)
{
rhs[i * house_length_n + j] = mat_a[(offset_rows + i) *
cols + (offset_cols + j)];
}
}
/* Multiply block matrices. */
for (int i = 0; i < (rows - offset_rows); ++i)
{
for (int j = 0; j < (cols - offset_cols); ++j)
{
T current(0);
for (int k = 0; k < house_length; ++k)
{
current += (house_mat[i * house_length + k] *
rhs[k * house_length_n + j]);
}
mat_a[(offset_rows + i) * cols + (offset_cols + j)] = current;
}
}
}
/**
* Bidiagonalizes a given MxN matrix, resulting in a MxN matrix U,
* a bidiagonal MxN matrix B and a NxN matrix V.
*
* Reference: "Matrix Computations" by Golub and Loan, 3rd edition,
* from page 252 (algorithm 5.4.2).
*/
template <typename T>
void
matrix_bidiagonalize (T const* mat_a, int rows, int cols, T* mat_u,
T* mat_b, T* mat_v, T const& epsilon)
{
/* Initialize U and V with identity matrices. */
matrix_set_identity(mat_u, rows);
matrix_set_identity(mat_v, cols);
/* Copy mat_a into mat_b. */
std::copy(mat_a, mat_a + rows * cols, mat_b);
int const steps = (rows == cols) ? (cols - 1) : cols;
for (int k = 0; k < steps; ++k)
{
int const sub_length = rows - k;
std::vector<T> buffer(sub_length // input_vec
+ sub_length // house_vec
+ sub_length * sub_length // house_mat
+ rows * rows // update_u
+ rows * rows); // mat_u_tmp
T* input_vec = &buffer[0];
T* house_vec = input_vec + sub_length;
T* house_mat = house_vec + sub_length;
T house_beta;
T* update_u = house_mat + sub_length * sub_length;
T* mat_u_tmp = update_u + rows * rows;
for (int i = 0; i < sub_length; ++i)
input_vec[i] = mat_b[(k + i) * cols + k];
matrix_householder_vector(input_vec, sub_length, house_vec,
&house_beta, epsilon, T(1));
matrix_householder_matrix(house_vec, sub_length,
house_beta, house_mat);
matrix_apply_householder_matrix(mat_b, rows, cols,
house_mat, sub_length, k, k);
for (int i = k + 1; i < rows; ++i)
mat_b[i * cols + k] = T(0);
/* Construct U update matrix and update U. */
std::fill(update_u, update_u + rows * rows, T(0));
for (int i = 0; i < k; ++i)
update_u[i * rows + i] = T(1);
for (int i = 0; i < sub_length; ++i)
{
for (int j = 0; j < sub_length; ++j)
{
update_u[(k + i) * rows + (k + j)] =
house_mat[i * sub_length + j];
}
}
/* Copy matrix U for multiplication. */
std::copy(mat_u, mat_u + rows * rows, mat_u_tmp);
matrix_multiply(mat_u_tmp, rows, rows, update_u, rows, mat_u);
if (k <= cols - 3)
{
/* Normalization constant for numerical stability. */
T norm(0);
for (int i = k + 1; i < cols; ++i)
norm += mat_b[k * cols + i];
if (MATH_EPSILON_EQ(norm, T(0), epsilon))
norm = T(1);
int const inner_sub_length = cols - (k + 1);
int const slice_rows = rows - k;
int const slice_cols = cols - k - 1;
std::vector<T> buffer2(inner_sub_length // inner_input_vec
+ inner_sub_length // inner_house_vec
+ inner_sub_length * inner_sub_length // inner_house_mat
+ slice_rows * slice_cols // mat_b_res
+ slice_rows * slice_cols // mat_b_tmp
+ cols * cols // update_v
+ cols * cols); // mat_v_tmp
T* inner_input_vec = &buffer2[0];
T* inner_house_vec = inner_input_vec + inner_sub_length;
T* inner_house_mat = inner_house_vec + inner_sub_length;
T inner_house_beta;
T* mat_b_res = inner_house_mat + inner_sub_length * inner_sub_length;
T* mat_b_tmp = mat_b_res + slice_rows * slice_cols;
T* update_v = mat_b_tmp + slice_rows * slice_cols;
T* mat_v_tmp = update_v + cols * cols;
for (int i = 0; i < cols - k - 1; ++i)
inner_input_vec[i] = mat_b[k * cols + (k + 1 + i)];
matrix_householder_vector(inner_input_vec, inner_sub_length,
inner_house_vec, &inner_house_beta, epsilon, norm);
matrix_householder_matrix(inner_house_vec, inner_sub_length,
inner_house_beta, inner_house_mat);
/* Cut out mat_b(k:m, (k+1):n). */
for (int i = 0; i < slice_rows; ++i)
{
for (int j = 0; j < slice_cols; ++j)
{
mat_b_tmp[i * slice_cols + j] =
mat_b[(k + i) * cols + (k + 1 + j)];
}
}
matrix_multiply(mat_b_tmp, slice_rows, slice_cols,
inner_house_mat, inner_sub_length, mat_b_res);
/* Write frame back into mat_b. */
for (int i = 0; i < slice_rows; ++i)
{
for (int j = 0; j < slice_cols; ++j)
{
mat_b[(k + i) * cols + (k + 1 + j)] =
mat_b_res[i * slice_cols + j];
}
}
for (int i = k + 2; i < cols; ++i)
mat_b[k * cols + i] = T(0);
std::fill(update_v, update_v + cols * cols, T(0));
for (int i = 0; i < k + 1; ++i)
update_v[i * cols + i] = T(1);
for (int i = 0; i < inner_sub_length; ++i)
{
for (int j = 0; j < inner_sub_length; ++j)
{
update_v[(k + i + 1) * cols + (k + j + 1)] =
inner_house_mat[i * inner_sub_length + j];
}
}
/* Copy matrix v for multiplication. */
std::copy(mat_v, mat_v + cols * cols, mat_v_tmp);
matrix_multiply(mat_v_tmp, cols, cols, update_v, cols, mat_v);
}
}
}
/**
* Single step in the [GK-SVD] method.
*/
template <typename T>
void
matrix_gk_svd_step (int rows, int cols, T* mat_b, T* mat_q, T* mat_p,
int p, int q, T const& epsilon)
{
int const slice_length = cols - q - p;
int const mat_sizes = slice_length * slice_length;
std::vector<T> buffer(3 * mat_sizes);
T* mat_b22 = &buffer[0];
T* mat_b22_t = mat_b22 + mat_sizes;
T* mat_tmp = mat_b22_t + mat_sizes;
for (int i = 0; i < slice_length; ++i)
for (int j = 0; j < slice_length; ++j)
mat_b22[i * slice_length + j] = mat_b[(p + i) * cols + (p + j)];
for (int i = 0; i < slice_length; ++i)
for (int j = 0; j < slice_length; ++j)
mat_b22_t[i * slice_length + j] = mat_b22[j * slice_length + i];
/* Slice outer product gives covariance matrix. */
matrix_multiply(mat_b22, slice_length, slice_length, mat_b22_t,
slice_length, mat_tmp);
T mat_c[2 * 2];
mat_c[0] = mat_tmp[(slice_length - 2) * slice_length + (slice_length - 2)];
mat_c[1] = mat_tmp[(slice_length - 2) * slice_length + (slice_length - 1)];
mat_c[2] = mat_tmp[(slice_length - 1) * slice_length + (slice_length - 2)];
mat_c[3] = mat_tmp[(slice_length - 1) * slice_length + (slice_length - 1)];
/* Use eigenvalue that is closer to the lower right entry of the slice. */
T eig_1, eig_2;
matrix_2x2_eigenvalues(mat_c, &eig_1, &eig_2);
T diff1 = std::abs(mat_c[3] - eig_1);
T diff2 = std::abs(mat_c[3] - eig_2);
T mu = (diff1 < diff2) ? eig_1 : eig_2;
/* Zero another entry bz applyting givens rotations. */
int k = p;
T alpha = mat_b[k * cols + k] * mat_b[k * cols + k] - mu;
T beta = mat_b[k * cols + k] * mat_b[k * cols + (k + 1)];
for (int k = p; k < cols - q - 1; ++k)
{
T givens_c, givens_s;
matrix_givens_rotation(alpha, beta, &givens_c, &givens_s, epsilon);
matrix_apply_givens_column(mat_b, cols, cols, k, k + 1, givens_c,
givens_s);
matrix_apply_givens_column(mat_p, cols, cols, k, k + 1, givens_c,
givens_s);
alpha = mat_b[k * cols + k];
beta = mat_b[(k + 1) * cols + k];
matrix_givens_rotation(alpha, beta, &givens_c, &givens_s, epsilon);
internal::matrix_apply_givens_row(mat_b, cols, cols, k, k + 1,
givens_c, givens_s);
internal::matrix_apply_givens_column(mat_q, rows, cols, k, k + 1,
givens_c, givens_s);
if (k < (cols - q - 2))
{
alpha = mat_b[k * cols + (k + 1)];
beta = mat_b[k * cols + (k + 2)];
}
}
}
template <typename T>
void
matrix_svd_clear_super_entry(int rows, int cols, T* mat_b, T* mat_q,
int row_index, T const& epsilon)
{
for (int i = row_index + 1; i < cols; ++i)
{
if (MATH_EPSILON_EQ(mat_b[row_index * cols + i], T(0), epsilon))
{
mat_b[row_index * cols + i] = T(0);
break;
}
T norm = MATH_POW2(mat_b[row_index * cols + i])
+ MATH_POW2(mat_b[i * cols + i]);
norm = std::sqrt(norm) * MATH_SIGN(mat_b[i * cols + i]);
T givens_c = mat_b[i * cols + i] / norm;
T givens_s = mat_b[row_index * cols + i] / norm;
matrix_apply_givens_row(mat_b, cols, cols, row_index,
i, givens_c, givens_s);
matrix_apply_givens_column(mat_q, rows, cols, row_index,
i, givens_c, givens_s);
}
}
/**
* Implementation of the [GK-SVD] method.
*/
template <typename T>
void
matrix_gk_svd (T const* mat_a, int rows, int cols,
T* mat_u, T* vec_s, T* mat_v, T const& epsilon)
{
/* Allocate memory for temp matrices. */
int const mat_q_full_size = rows * rows;
int const mat_b_full_size = rows * cols;
int const mat_p_size = cols * cols;
int const mat_q_size = rows * cols;
int const mat_b_size = cols * cols;
std::vector<T> buffer(mat_q_full_size + mat_b_full_size
+ mat_p_size + mat_q_size + mat_b_size);
T* mat_q_full = &buffer[0];
T* mat_b_full = mat_q_full + mat_q_full_size;
T* mat_p = mat_b_full + mat_b_full_size;
T* mat_q = mat_p + mat_p_size;
T* mat_b = mat_q + mat_q_size;
matrix_bidiagonalize(mat_a, rows, cols,
mat_q_full, mat_b_full, mat_p, epsilon);
/* Extract smaller matrices. */
for (int i = 0; i < rows; ++i)
{
for (int j = 0; j < cols; ++j)
{
mat_q[i * cols + j] = mat_q_full[i * rows + j];
}
}
std::copy(mat_b_full, mat_b_full + cols * cols, mat_b);
/* Avoid infinite loops and exit after maximum number of iterations. */
int const max_iterations = rows * cols;
int iteration = 0;
while (iteration < max_iterations)
{
iteration += 1;
/* Enforce exact zeros for numerical stability. */
for (int i = 0; i < cols * cols; ++i)
{
T const& entry = mat_b[i];
if (MATH_EPSILON_EQ(entry, T(0), epsilon))
mat_b[i] = T(0);
}
/* GK 2a. */
for (int i = 0; i < (cols - 1); ++i)
{
if (std::abs(mat_b[i * cols + (i + 1)]) <= epsilon *
std::abs(mat_b[i * cols + i] + mat_b[(i + 1) * cols + (i + 1)]))
{
mat_b[i * cols + (i + 1)] = T(0);
}
}
/* GK 2b. */
/* Select q such that b33 is diagonal and blocked by zeros. */
int q = 0;
for (int k = 0; k < cols; ++k)
{
int const slice_len = k + 1;
std::vector<T> mat_b33(slice_len * slice_len);
for (int i = 0; i < slice_len; ++i)
{
for (int j = 0; j < slice_len; ++j)
{
mat_b33[i * slice_len + j]
= mat_b[(cols - k - 1 + i) * cols + (cols - k - 1 + j)];
}
}
if (matrix_is_diagonal(&mat_b33[0], slice_len, slice_len, epsilon))
{
if (k < cols - 1)
{
if (matrix_is_submatrix_zero_enclosed(
mat_b, cols, k + 1, epsilon))
{
q = k + 1;
}
}
else
{
q = k + 1;
}
}
}
/* Select z := n-p-q such that B22 has no zero superdiagonal entry. */
int z = 0;
T* mat_b22_tmp = new T[(cols - q) * (cols - q)];
for (int k = 0; k < (cols - q); ++k)
{
int const slice_len = k + 1;
for (int i = 0; i < slice_len; ++i)
{
for (int j = 0; j < slice_len; ++j)
{
mat_b22_tmp[i * slice_len + j]
= mat_b[(cols - q - k - 1 + i)
* cols + (cols - q - k - 1 + j)];
}
}
if (matrix_is_superdiagonal_nonzero(
mat_b22_tmp, slice_len, slice_len, epsilon))
{
z = k + 1;
}
}
delete[] mat_b22_tmp;
int const p = cols - q - z;
/* GK 2c. */
if (q == cols)
break;
bool diagonal_non_zero = true;
int nz = 0;
for (nz = p; nz < (cols - q - 1); ++nz)
{
if (MATH_EPSILON_EQ(mat_b[nz * cols + nz], T(0), epsilon))
{
diagonal_non_zero = false;
mat_b[nz * cols + nz] = T(0);
break;
}
}
if (diagonal_non_zero)
matrix_gk_svd_step(rows, cols, mat_b, mat_q, mat_p, p, q, epsilon);
else
matrix_svd_clear_super_entry(rows, cols, mat_b, mat_q, nz, epsilon);
}
/* Create resulting matrices and vector from temporary entities. */
std::copy(mat_q, mat_q + rows * cols, mat_u);
std::copy(mat_p, mat_p + cols * cols, mat_v);
for (int i = 0; i < cols; ++i)
vec_s[i] = mat_b[i * cols + i];
/* Correct signs. */
for (int i = 0; i < cols; ++i)
{
if (vec_s[i] < epsilon)
{
vec_s[i] = -vec_s[i];
for (int j = 0; j < rows; ++j)
{
int index = j * cols + i;
mat_u[index] = -mat_u[index];
}
}
}
}
/**
* Implementation of the [R-SVD] method, uses [GK-SVD] as solver
* for the reduced problem.
*/
template <typename T>
void
matrix_r_svd (T const* mat_a, int rows, int cols,
T* mat_u, T* vec_s, T* mat_v, T const& epsilon)
{
/* Allocate memory for temp matrices. */
int const mat_q_size = rows * rows;
int const mat_r_size = rows * cols;
int const mat_u_tmp_size = rows * cols;
std::vector<T> buffer(mat_q_size + mat_r_size + mat_u_tmp_size);
T* mat_q = &buffer[0];
T* mat_r = mat_q + mat_q_size;
T* mat_u_tmp = mat_r + mat_r_size;
matrix_qr(mat_a, rows, cols, mat_q, mat_r, epsilon);
matrix_gk_svd(mat_r, cols, cols, mat_u_tmp, vec_s, mat_v, epsilon);
std::fill(mat_u_tmp + cols * cols, mat_u_tmp + rows * cols, T(0));
/* Adapt U for big matrices. */
matrix_multiply(mat_q, rows, rows, mat_u_tmp, cols, mat_u);
}
/**
* Returns the index of the largest eigenvalue. If all eigenvalues are
* zero, -1 is returned.
*/
template <typename T>
int
find_largest_ev_index (T const* values, int length)
{
T largest = T(0);
int index = -1;
for (int i = 0; i < length; ++i)
if (values[i] > largest)
{
largest = values[i];
index = i;
}
return index;
}
MATH_INTERNAL_NAMESPACE_END
MATH_NAMESPACE_END
/* ------------------------ Implementation ------------------------ */
MATH_NAMESPACE_BEGIN
template <typename T>
void
matrix_svd (T const* mat_a, int rows, int cols,
T* mat_u, T* vec_s, T* mat_v, T const& epsilon)
{
/* Allow for NULL result matrices. */
std::vector<T> mat_u_tmp;
std::vector<T> vec_s_tmp;
if (vec_s == NULL)
{
vec_s_tmp.resize(cols);
vec_s = &vec_s_tmp[0];
}
std::vector<T> mat_v_tmp;
if (mat_v == NULL)
{
mat_v_tmp.resize(cols * cols);
mat_v = &mat_v_tmp[0];
}
/*
* Handle two cases: The regular case, where M >= N (rows >= cols), and
* the irregular case, where M < N (rows < cols). In the latter one,
* zero rows are appended to A until A is a square matrix.
*/
if (rows >= cols)
{
/* Allow for NULL result U matrix. */
if (mat_u == NULL)
{
mat_u_tmp.resize(rows * cols);
mat_u = &mat_u_tmp[0];
}
/* Perform economy SVD if rows > 5/3 cols to save some operations. */
if (rows >= 5 * cols / 3)
{
internal::matrix_r_svd(mat_a, rows, cols,
mat_u, vec_s, mat_v, epsilon);
}
else
{
internal::matrix_gk_svd(mat_a, rows, cols,
mat_u, vec_s, mat_v, epsilon);
}
}
else
{
/* Append zero rows to A until A is square. */
std::vector<T> mat_a_tmp(cols * cols, T(0));
std::copy(mat_a, mat_a + cols * rows, &mat_a_tmp[0]);
/* Temporarily resize U, allow for NULL result matrices. */
mat_u_tmp.resize(cols * cols);
internal::matrix_gk_svd(&mat_a_tmp[0], cols, cols,
&mat_u_tmp[0], vec_s, mat_v, epsilon);
/* Copy the result back to U leaving out the last rows. */
if (mat_u != NULL)
std::copy(&mat_u_tmp[0], &mat_u_tmp[0] + rows * cols, mat_u);
else
mat_u = &mat_u_tmp[0];
}
/* Sort the eigenvalues in S and adapt the columns of U and V. */
for (int i = 0; i < cols; ++i)
{
int pos = internal::find_largest_ev_index(vec_s + i, cols - i);
if (pos < 0)
break;
if (pos == 0)
continue;
std::swap(vec_s[i], vec_s[i + pos]);
matrix_swap_columns(mat_u, rows, cols, i, i + pos);
matrix_swap_columns(mat_v, cols, cols, i, i + pos);
}
}
#if 0
template <typename T>
void
matrix_svd (T const* mat_a, int rows, int cols,
T* mat_u, T* vec_s, T* mat_v, T const& epsilon)
{
/* Allow for NULL result matrices. */
std::vector<T> mat_u_tmp;
std::vector<T> vec_s_tmp;
std::vector<T> mat_v_tmp;
if (mat_u == NULL)
{
mat_u_tmp.resize(rows * cols);
mat_u = &mat_u_tmp[0];
}
if (vec_s == NULL)
{
vec_s_tmp.resize(cols);
vec_s = &vec_s_tmp[0];
}
if (mat_v == NULL)
{
mat_v_tmp.resize(cols * cols);
mat_v = &mat_v_tmp[0];
}
/*
* The SVD can only handle systems where rows > cols. Thus, in case
* of cols > rows, the input matrix is transposed and the resulting
* solution converted to the desired solution:
*
* A* = (U S V*)* = V S* U* = V S U*
*
* In order to output same-sized matrices for every problem, many zero
* rows and columns can appear in systems with cols > rows.
*/
std::vector<T> mat_a_tmp;
bool was_transposed = false;
if (cols > rows)
{
mat_a_tmp.resize(rows * cols);
std::copy(mat_a, mat_a + rows * cols, mat_a_tmp.begin());
matrix_transpose(&mat_a_tmp[0], rows, cols);
std::swap(rows, cols);
std::swap(mat_u, mat_v);
mat_a = &mat_a_tmp[0];
was_transposed = true;
}
/* Perform economy SVD if rows > 5/3 cols to save some operations. */
if (rows >= 5 * cols / 3)
{
internal::matrix_r_svd(mat_a, rows, cols,
mat_u, vec_s, mat_v, epsilon);
}
else
{
internal::matrix_gk_svd(mat_a, rows, cols,
mat_u, vec_s, mat_v, epsilon);
}
if (was_transposed)
{
std::swap(rows, cols);
std::swap(mat_u, mat_v);
/* Fix S by appending zeros. */
for (int i = rows; i < cols; ++i)
vec_s[i] = T(0);
/* Fix U by reshaping the matrix. */
for (int i = rows * rows - 1, y = rows - 1; y >= 0; --y)
{
for (int x = rows - 1; x >= 0; --x, --i)
mat_u[y * cols + x] = mat_u[i];
for (int x = rows; x < cols; ++x)
mat_u[y * cols + x] = T(0);
}
/* Fix V by reshaping the matrix. */
for (int i = cols * rows - 1, y = cols - 1; y >= 0; --y)
{
for (int x = rows - 1; x >= 0; --x, --i)
mat_v[y * cols + x] = mat_v[i];
for (int x = rows; x < cols; ++x)
mat_v[y * cols + x] = T(0);
}
}
/* Sort the eigenvalues in S and adapt the columns of U and V. */
for (int i = 0; i < cols; ++i)
{
int pos = internal::find_largest_ev_index(vec_s + i, cols - i);
if (pos < 0)
break;
if (pos == 0)
continue;
std::swap(vec_s[i], vec_s[i + pos]);
matrix_swap_columns(mat_u, rows, cols, i, i + pos);
matrix_swap_columns(mat_v, cols, cols, i, i + pos);
}
}
#endif
template <typename T, int M, int N>
void
matrix_svd (Matrix<T, M, N> const& mat_a, Matrix<T, M, N>* mat_u,
Matrix<T, N, N>* mat_s, Matrix<T, N, N>* mat_v, T const& epsilon)
{
T* mat_u_ptr = mat_u ? mat_u->begin() : NULL;
T* mat_s_ptr = mat_s ? mat_s->begin() : NULL;
T* mat_v_ptr = mat_v ? mat_v->begin() : NULL;
matrix_svd<T>(mat_a.begin(), M, N,
mat_u_ptr, mat_s_ptr, mat_v_ptr, epsilon);
/* Swap elements of S into place. */
if (mat_s_ptr)
{
std::fill(mat_s_ptr + N, mat_s_ptr + N * N, T(0));
for (int x = 1, i = N + 1; x < N; ++x, i += N + 1)
std::swap(mat_s_ptr[x], mat_s_ptr[i]);
}
}
template <typename T, int M, int N>
void
matrix_pseudo_inverse (Matrix<T, M, N> const& A,
Matrix<T, N, M>* result, T const& epsilon)
{
Matrix<T, M, N> U;
Matrix<T, N, N> S;
Matrix<T, N, N> V;
matrix_svd(A, &U, &S, &V, epsilon);
/* Invert diagonal of S. */
for (int i = 0; i < N; ++i)
if (MATH_EPSILON_EQ(S(i, i), T(0), epsilon))
S(i, i) = T(0);
else
S(i, i) = T(1) / S(i, i);
*result = V * S * U.transposed();
}
MATH_NAMESPACE_END
#endif /* MATH_MATRIX_SVD_HEADER */
| 31.593036 | 82 | 0.534856 | [
"vector"
] |
d08b4ffab7c760cc284445fa4ae61cd2baa29081 | 1,836 | h | C | DataFormats/ParticleFlowReco/interface/ParticleFiltrationDecision.h | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 852 | 2015-01-11T21:03:51.000Z | 2022-03-25T21:14:00.000Z | DataFormats/ParticleFlowReco/interface/ParticleFiltrationDecision.h | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 30,371 | 2015-01-02T00:14:40.000Z | 2022-03-31T23:26:05.000Z | DataFormats/ParticleFlowReco/interface/ParticleFiltrationDecision.h | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 3,240 | 2015-01-02T05:53:18.000Z | 2022-03-31T17:24:21.000Z | #ifndef PARTICLEFILTRATIONDECISION_H_
#define PARTICLEFILTRATIONDECISION_H_
#include <string>
#include <vector>
#include "DataFormats/Common/interface/Ref.h"
#include "DataFormats/Common/interface/RefProd.h"
#include "DataFormats/Common/interface/RefVector.h"
#include "DataFormats/Common/interface/RefToBase.h"
namespace pftools {
/**
* @class ParticleFiltrationDecision
* @brief Articulates the decision of the ParticleFilter in RecoParticleFlow/PFAnalyses.
*
* Despite its generic name, it is currently only suitable for testbeam analysis and
* particle gun use. To be reworked for collisions.
*
* @author Jamie Ballin
* @since CMSSW 31X
* @date Added July 2009
*
*/
class ParticleFiltrationDecision {
public:
ParticleFiltrationDecision(){};
virtual ~ParticleFiltrationDecision(){};
/* Bit field to contain user-defined vetos */
char vetosPassed_;
/*User-defined string representing who made this */
std::string filtrationProvenance_;
enum TestbeamParticle { PION, PROTON_KAON, PROTON, KAON, ELECTRON, MUON, NOISE, OTHER };
/* This event contains a clean... */
TestbeamParticle type_;
};
//Usual framework & EDM incantations
typedef std::vector<pftools::ParticleFiltrationDecision> ParticleFiltrationDecisionCollection;
typedef edm::Ref<ParticleFiltrationDecisionCollection> ParticleFiltrationDecisionRef;
typedef edm::RefProd<ParticleFiltrationDecisionCollection> ParticleFiltrationDecisionRefProd;
typedef edm::RefVector<ParticleFiltrationDecisionCollection> ParticleFiltrationDecisionRefVector;
typedef ParticleFiltrationDecisionRefVector::iterator particleFiltrationDecision_iterator;
typedef edm::RefToBase<pftools::ParticleFiltrationDecision> ParticleFiltrationDecisionBaseRef;
} // namespace pftools
#endif /* PARTICLEFILTRATIONDECISION_H_ */
| 34.641509 | 99 | 0.789216 | [
"vector"
] |
d08bf526ee2ba2d0bdf629ec98f9482229860080 | 27,820 | h | C | tools/arachni/system/usr/include/cms_asn1.h | sravani-m/Web-Application-Security-Framework | d9f71538f5cba6fe1d8eabcb26c557565472f6a6 | [
"MIT"
] | 3 | 2019-04-09T22:59:33.000Z | 2019-06-14T09:23:24.000Z | tools/arachni/system/usr/include/cms_asn1.h | sravani-m/Web-Application-Security-Framework | d9f71538f5cba6fe1d8eabcb26c557565472f6a6 | [
"MIT"
] | null | null | null | tools/arachni/system/usr/include/cms_asn1.h | sravani-m/Web-Application-Security-Framework | d9f71538f5cba6fe1d8eabcb26c557565472f6a6 | [
"MIT"
] | null | null | null | /* Generated from ./cms.asn1 */
/* Do not edit */
#ifndef __cms_asn1_h__
#define __cms_asn1_h__
#include <stddef.h>
#include <time.h>
#ifndef __asn1_common_definitions__
#define __asn1_common_definitions__
typedef struct heim_integer {
size_t length;
void *data;
int negative;
} heim_integer;
typedef struct heim_octet_string {
size_t length;
void *data;
} heim_octet_string;
typedef char *heim_general_string;
typedef char *heim_utf8_string;
typedef struct heim_octet_string heim_printable_string;
typedef struct heim_octet_string heim_ia5_string;
typedef struct heim_bmp_string {
size_t length;
uint16_t *data;
} heim_bmp_string;
typedef struct heim_universal_string {
size_t length;
uint32_t *data;
} heim_universal_string;
typedef char *heim_visible_string;
typedef struct heim_oid {
size_t length;
unsigned *components;
} heim_oid;
typedef struct heim_bit_string {
size_t length;
void *data;
} heim_bit_string;
typedef struct heim_octet_string heim_any;
typedef struct heim_octet_string heim_any_set;
#define ASN1_MALLOC_ENCODE(T, B, BL, S, L, R) \
do { \
(BL) = length_##T((S)); \
(B) = malloc((BL)); \
if((B) == NULL) { \
(R) = ENOMEM; \
} else { \
(R) = encode_##T(((unsigned char*)(B)) + (BL) - 1, (BL), \
(S), (L)); \
if((R) != 0) { \
free((B)); \
(B) = NULL; \
} \
} \
} while (0)
#ifdef _WIN32
#ifndef ASN1_LIB
#define ASN1EXP __declspec(dllimport)
#else
#define ASN1EXP
#endif
#define ASN1CALL __stdcall
#else
#define ASN1EXP
#define ASN1CALL
#endif
struct units;
#endif
#include <rfc2459_asn1.h>
#include <heim_asn1.h>
/* OBJECT IDENTIFIER id-pkcs7 ::= { iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) pkcs7(7) } */
extern ASN1EXP const heim_oid asn1_oid_id_pkcs7;
#define ASN1_OID_ID_PKCS7 (&asn1_oid_id_pkcs7)
/* OBJECT IDENTIFIER id-pkcs7-data ::= { iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) pkcs7(7) label-less(1) } */
extern ASN1EXP const heim_oid asn1_oid_id_pkcs7_data;
#define ASN1_OID_ID_PKCS7_DATA (&asn1_oid_id_pkcs7_data)
/* OBJECT IDENTIFIER id-pkcs7-signedData ::= { iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) pkcs7(7) label-less(2) } */
extern ASN1EXP const heim_oid asn1_oid_id_pkcs7_signedData;
#define ASN1_OID_ID_PKCS7_SIGNEDDATA (&asn1_oid_id_pkcs7_signedData)
/* OBJECT IDENTIFIER id-pkcs7-envelopedData ::= { iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) pkcs7(7) label-less(3) } */
extern ASN1EXP const heim_oid asn1_oid_id_pkcs7_envelopedData;
#define ASN1_OID_ID_PKCS7_ENVELOPEDDATA (&asn1_oid_id_pkcs7_envelopedData)
/* OBJECT IDENTIFIER id-pkcs7-signedAndEnvelopedData ::= { iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) pkcs7(7) label-less(4) } */
extern ASN1EXP const heim_oid asn1_oid_id_pkcs7_signedAndEnvelopedData;
#define ASN1_OID_ID_PKCS7_SIGNEDANDENVELOPEDDATA (&asn1_oid_id_pkcs7_signedAndEnvelopedData)
/* OBJECT IDENTIFIER id-pkcs7-digestedData ::= { iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) pkcs7(7) label-less(5) } */
extern ASN1EXP const heim_oid asn1_oid_id_pkcs7_digestedData;
#define ASN1_OID_ID_PKCS7_DIGESTEDDATA (&asn1_oid_id_pkcs7_digestedData)
/* OBJECT IDENTIFIER id-pkcs7-encryptedData ::= { iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) pkcs7(7) label-less(6) } */
extern ASN1EXP const heim_oid asn1_oid_id_pkcs7_encryptedData;
#define ASN1_OID_ID_PKCS7_ENCRYPTEDDATA (&asn1_oid_id_pkcs7_encryptedData)
/*
CMSVersion ::= INTEGER {
CMSVersion_v0(0),
CMSVersion_v1(1),
CMSVersion_v2(2),
CMSVersion_v3(3),
CMSVersion_v4(4)
}
*/
typedef enum CMSVersion {
CMSVersion_v0 = 0,
CMSVersion_v1 = 1,
CMSVersion_v2 = 2,
CMSVersion_v3 = 3,
CMSVersion_v4 = 4
} CMSVersion;
ASN1EXP int ASN1CALL decode_CMSVersion(const unsigned char *, size_t, CMSVersion *, size_t *);
ASN1EXP int ASN1CALL encode_CMSVersion(unsigned char *, size_t, const CMSVersion *, size_t *);
ASN1EXP size_t ASN1CALL length_CMSVersion(const CMSVersion *);
ASN1EXP int ASN1CALL copy_CMSVersion (const CMSVersion *, CMSVersion *);
ASN1EXP void ASN1CALL free_CMSVersion (CMSVersion *);
/*
DigestAlgorithmIdentifier ::= AlgorithmIdentifier
*/
typedef AlgorithmIdentifier DigestAlgorithmIdentifier;
ASN1EXP int ASN1CALL decode_DigestAlgorithmIdentifier(const unsigned char *, size_t, DigestAlgorithmIdentifier *, size_t *);
ASN1EXP int ASN1CALL encode_DigestAlgorithmIdentifier(unsigned char *, size_t, const DigestAlgorithmIdentifier *, size_t *);
ASN1EXP size_t ASN1CALL length_DigestAlgorithmIdentifier(const DigestAlgorithmIdentifier *);
ASN1EXP int ASN1CALL copy_DigestAlgorithmIdentifier (const DigestAlgorithmIdentifier *, DigestAlgorithmIdentifier *);
ASN1EXP void ASN1CALL free_DigestAlgorithmIdentifier (DigestAlgorithmIdentifier *);
/*
DigestAlgorithmIdentifiers ::= SET OF DigestAlgorithmIdentifier
*/
typedef struct DigestAlgorithmIdentifiers {
unsigned int len;
DigestAlgorithmIdentifier *val;
} DigestAlgorithmIdentifiers;
ASN1EXP int ASN1CALL add_DigestAlgorithmIdentifiers (DigestAlgorithmIdentifiers *, const DigestAlgorithmIdentifier *);
ASN1EXP int ASN1CALL remove_DigestAlgorithmIdentifiers (DigestAlgorithmIdentifiers *, unsigned int);
ASN1EXP int ASN1CALL decode_DigestAlgorithmIdentifiers(const unsigned char *, size_t, DigestAlgorithmIdentifiers *, size_t *);
ASN1EXP int ASN1CALL encode_DigestAlgorithmIdentifiers(unsigned char *, size_t, const DigestAlgorithmIdentifiers *, size_t *);
ASN1EXP size_t ASN1CALL length_DigestAlgorithmIdentifiers(const DigestAlgorithmIdentifiers *);
ASN1EXP int ASN1CALL copy_DigestAlgorithmIdentifiers (const DigestAlgorithmIdentifiers *, DigestAlgorithmIdentifiers *);
ASN1EXP void ASN1CALL free_DigestAlgorithmIdentifiers (DigestAlgorithmIdentifiers *);
/*
SignatureAlgorithmIdentifier ::= AlgorithmIdentifier
*/
typedef AlgorithmIdentifier SignatureAlgorithmIdentifier;
ASN1EXP int ASN1CALL decode_SignatureAlgorithmIdentifier(const unsigned char *, size_t, SignatureAlgorithmIdentifier *, size_t *);
ASN1EXP int ASN1CALL encode_SignatureAlgorithmIdentifier(unsigned char *, size_t, const SignatureAlgorithmIdentifier *, size_t *);
ASN1EXP size_t ASN1CALL length_SignatureAlgorithmIdentifier(const SignatureAlgorithmIdentifier *);
ASN1EXP int ASN1CALL copy_SignatureAlgorithmIdentifier (const SignatureAlgorithmIdentifier *, SignatureAlgorithmIdentifier *);
ASN1EXP void ASN1CALL free_SignatureAlgorithmIdentifier (SignatureAlgorithmIdentifier *);
/*
ContentType ::= OBJECT IDENTIFIER
*/
typedef heim_oid ContentType;
ASN1EXP int ASN1CALL decode_ContentType(const unsigned char *, size_t, ContentType *, size_t *);
ASN1EXP int ASN1CALL encode_ContentType(unsigned char *, size_t, const ContentType *, size_t *);
ASN1EXP size_t ASN1CALL length_ContentType(const ContentType *);
ASN1EXP int ASN1CALL copy_ContentType (const ContentType *, ContentType *);
ASN1EXP void ASN1CALL free_ContentType (ContentType *);
/*
MessageDigest ::= OCTET STRING
*/
typedef heim_octet_string MessageDigest;
ASN1EXP int ASN1CALL decode_MessageDigest(const unsigned char *, size_t, MessageDigest *, size_t *);
ASN1EXP int ASN1CALL encode_MessageDigest(unsigned char *, size_t, const MessageDigest *, size_t *);
ASN1EXP size_t ASN1CALL length_MessageDigest(const MessageDigest *);
ASN1EXP int ASN1CALL copy_MessageDigest (const MessageDigest *, MessageDigest *);
ASN1EXP void ASN1CALL free_MessageDigest (MessageDigest *);
/*
ContentInfo ::= SEQUENCE {
contentType ContentType,
content [0] heim_any OPTIONAL,
}
*/
typedef struct ContentInfo {
ContentType contentType;
heim_any *content;
} ContentInfo;
ASN1EXP int ASN1CALL decode_ContentInfo(const unsigned char *, size_t, ContentInfo *, size_t *);
ASN1EXP int ASN1CALL encode_ContentInfo(unsigned char *, size_t, const ContentInfo *, size_t *);
ASN1EXP size_t ASN1CALL length_ContentInfo(const ContentInfo *);
ASN1EXP int ASN1CALL copy_ContentInfo (const ContentInfo *, ContentInfo *);
ASN1EXP void ASN1CALL free_ContentInfo (ContentInfo *);
/*
EncapsulatedContentInfo ::= SEQUENCE {
eContentType ContentType,
eContent [0] OCTET STRING OPTIONAL,
}
*/
typedef struct EncapsulatedContentInfo {
ContentType eContentType;
heim_octet_string *eContent;
} EncapsulatedContentInfo;
ASN1EXP int ASN1CALL decode_EncapsulatedContentInfo(const unsigned char *, size_t, EncapsulatedContentInfo *, size_t *);
ASN1EXP int ASN1CALL encode_EncapsulatedContentInfo(unsigned char *, size_t, const EncapsulatedContentInfo *, size_t *);
ASN1EXP size_t ASN1CALL length_EncapsulatedContentInfo(const EncapsulatedContentInfo *);
ASN1EXP int ASN1CALL copy_EncapsulatedContentInfo (const EncapsulatedContentInfo *, EncapsulatedContentInfo *);
ASN1EXP void ASN1CALL free_EncapsulatedContentInfo (EncapsulatedContentInfo *);
/*
CertificateSet ::= SET OF heim_any
*/
typedef struct CertificateSet {
unsigned int len;
heim_any *val;
} CertificateSet;
ASN1EXP int ASN1CALL decode_CertificateSet(const unsigned char *, size_t, CertificateSet *, size_t *);
ASN1EXP int ASN1CALL encode_CertificateSet(unsigned char *, size_t, const CertificateSet *, size_t *);
ASN1EXP size_t ASN1CALL length_CertificateSet(const CertificateSet *);
ASN1EXP int ASN1CALL copy_CertificateSet (const CertificateSet *, CertificateSet *);
ASN1EXP void ASN1CALL free_CertificateSet (CertificateSet *);
/*
CertificateList ::= Certificate
*/
typedef Certificate CertificateList;
ASN1EXP int ASN1CALL decode_CertificateList(const unsigned char *, size_t, CertificateList *, size_t *);
ASN1EXP int ASN1CALL encode_CertificateList(unsigned char *, size_t, const CertificateList *, size_t *);
ASN1EXP size_t ASN1CALL length_CertificateList(const CertificateList *);
ASN1EXP int ASN1CALL copy_CertificateList (const CertificateList *, CertificateList *);
ASN1EXP void ASN1CALL free_CertificateList (CertificateList *);
/*
CertificateRevocationLists ::= SET OF CertificateList
*/
typedef struct CertificateRevocationLists {
unsigned int len;
CertificateList *val;
} CertificateRevocationLists;
ASN1EXP int ASN1CALL decode_CertificateRevocationLists(const unsigned char *, size_t, CertificateRevocationLists *, size_t *);
ASN1EXP int ASN1CALL encode_CertificateRevocationLists(unsigned char *, size_t, const CertificateRevocationLists *, size_t *);
ASN1EXP size_t ASN1CALL length_CertificateRevocationLists(const CertificateRevocationLists *);
ASN1EXP int ASN1CALL copy_CertificateRevocationLists (const CertificateRevocationLists *, CertificateRevocationLists *);
ASN1EXP void ASN1CALL free_CertificateRevocationLists (CertificateRevocationLists *);
/*
IssuerAndSerialNumber ::= SEQUENCE {
issuer Name,
serialNumber CertificateSerialNumber,
}
*/
typedef struct IssuerAndSerialNumber {
Name issuer;
CertificateSerialNumber serialNumber;
} IssuerAndSerialNumber;
ASN1EXP int ASN1CALL decode_IssuerAndSerialNumber(const unsigned char *, size_t, IssuerAndSerialNumber *, size_t *);
ASN1EXP int ASN1CALL encode_IssuerAndSerialNumber(unsigned char *, size_t, const IssuerAndSerialNumber *, size_t *);
ASN1EXP size_t ASN1CALL length_IssuerAndSerialNumber(const IssuerAndSerialNumber *);
ASN1EXP int ASN1CALL copy_IssuerAndSerialNumber (const IssuerAndSerialNumber *, IssuerAndSerialNumber *);
ASN1EXP void ASN1CALL free_IssuerAndSerialNumber (IssuerAndSerialNumber *);
/*
CMSIdentifier ::= CHOICE {
issuerAndSerialNumber IssuerAndSerialNumber,
subjectKeyIdentifier [0] SubjectKeyIdentifier,
}
*/
typedef struct CMSIdentifier {
enum {
choice_CMSIdentifier_issuerAndSerialNumber = 1,
choice_CMSIdentifier_subjectKeyIdentifier
} element;
union {
IssuerAndSerialNumber issuerAndSerialNumber;
SubjectKeyIdentifier subjectKeyIdentifier;
} u;
} CMSIdentifier;
ASN1EXP int ASN1CALL decode_CMSIdentifier(const unsigned char *, size_t, CMSIdentifier *, size_t *);
ASN1EXP int ASN1CALL encode_CMSIdentifier(unsigned char *, size_t, const CMSIdentifier *, size_t *);
ASN1EXP size_t ASN1CALL length_CMSIdentifier(const CMSIdentifier *);
ASN1EXP int ASN1CALL copy_CMSIdentifier (const CMSIdentifier *, CMSIdentifier *);
ASN1EXP void ASN1CALL free_CMSIdentifier (CMSIdentifier *);
/*
SignerIdentifier ::= CMSIdentifier
*/
typedef CMSIdentifier SignerIdentifier;
ASN1EXP int ASN1CALL decode_SignerIdentifier(const unsigned char *, size_t, SignerIdentifier *, size_t *);
ASN1EXP int ASN1CALL encode_SignerIdentifier(unsigned char *, size_t, const SignerIdentifier *, size_t *);
ASN1EXP size_t ASN1CALL length_SignerIdentifier(const SignerIdentifier *);
ASN1EXP int ASN1CALL copy_SignerIdentifier (const SignerIdentifier *, SignerIdentifier *);
ASN1EXP void ASN1CALL free_SignerIdentifier (SignerIdentifier *);
/*
RecipientIdentifier ::= CMSIdentifier
*/
typedef CMSIdentifier RecipientIdentifier;
ASN1EXP int ASN1CALL decode_RecipientIdentifier(const unsigned char *, size_t, RecipientIdentifier *, size_t *);
ASN1EXP int ASN1CALL encode_RecipientIdentifier(unsigned char *, size_t, const RecipientIdentifier *, size_t *);
ASN1EXP size_t ASN1CALL length_RecipientIdentifier(const RecipientIdentifier *);
ASN1EXP int ASN1CALL copy_RecipientIdentifier (const RecipientIdentifier *, RecipientIdentifier *);
ASN1EXP void ASN1CALL free_RecipientIdentifier (RecipientIdentifier *);
/*
CMSAttributes ::= SET OF Attribute
*/
typedef struct CMSAttributes {
unsigned int len;
Attribute *val;
} CMSAttributes;
ASN1EXP int ASN1CALL decode_CMSAttributes(const unsigned char *, size_t, CMSAttributes *, size_t *);
ASN1EXP int ASN1CALL encode_CMSAttributes(unsigned char *, size_t, const CMSAttributes *, size_t *);
ASN1EXP size_t ASN1CALL length_CMSAttributes(const CMSAttributes *);
ASN1EXP int ASN1CALL copy_CMSAttributes (const CMSAttributes *, CMSAttributes *);
ASN1EXP void ASN1CALL free_CMSAttributes (CMSAttributes *);
/*
SignatureValue ::= OCTET STRING
*/
typedef heim_octet_string SignatureValue;
ASN1EXP int ASN1CALL decode_SignatureValue(const unsigned char *, size_t, SignatureValue *, size_t *);
ASN1EXP int ASN1CALL encode_SignatureValue(unsigned char *, size_t, const SignatureValue *, size_t *);
ASN1EXP size_t ASN1CALL length_SignatureValue(const SignatureValue *);
ASN1EXP int ASN1CALL copy_SignatureValue (const SignatureValue *, SignatureValue *);
ASN1EXP void ASN1CALL free_SignatureValue (SignatureValue *);
/*
SignerInfo ::= SEQUENCE {
version CMSVersion,
sid SignerIdentifier,
digestAlgorithm DigestAlgorithmIdentifier,
signedAttrs [0] IMPLICIT SET OF Attribute OPTIONAL,
signatureAlgorithm SignatureAlgorithmIdentifier,
signature SignatureValue,
unsignedAttrs [1] IMPLICIT SET OF Attribute OPTIONAL,
}
*/
typedef struct SignerInfo {
CMSVersion version;
SignerIdentifier sid;
DigestAlgorithmIdentifier digestAlgorithm;
struct SignerInfo_signedAttrs {
unsigned int len;
Attribute *val;
} *signedAttrs;
SignatureAlgorithmIdentifier signatureAlgorithm;
SignatureValue signature;
struct SignerInfo_unsignedAttrs {
unsigned int len;
Attribute *val;
} *unsignedAttrs;
} SignerInfo;
ASN1EXP int ASN1CALL decode_SignerInfo(const unsigned char *, size_t, SignerInfo *, size_t *);
ASN1EXP int ASN1CALL encode_SignerInfo(unsigned char *, size_t, const SignerInfo *, size_t *);
ASN1EXP size_t ASN1CALL length_SignerInfo(const SignerInfo *);
ASN1EXP int ASN1CALL copy_SignerInfo (const SignerInfo *, SignerInfo *);
ASN1EXP void ASN1CALL free_SignerInfo (SignerInfo *);
/*
SignerInfos ::= SET OF SignerInfo
*/
typedef struct SignerInfos {
unsigned int len;
SignerInfo *val;
} SignerInfos;
ASN1EXP int ASN1CALL decode_SignerInfos(const unsigned char *, size_t, SignerInfos *, size_t *);
ASN1EXP int ASN1CALL encode_SignerInfos(unsigned char *, size_t, const SignerInfos *, size_t *);
ASN1EXP size_t ASN1CALL length_SignerInfos(const SignerInfos *);
ASN1EXP int ASN1CALL copy_SignerInfos (const SignerInfos *, SignerInfos *);
ASN1EXP void ASN1CALL free_SignerInfos (SignerInfos *);
/*
SignedData ::= SEQUENCE {
version CMSVersion,
digestAlgorithms DigestAlgorithmIdentifiers,
encapContentInfo EncapsulatedContentInfo,
certificates [0] IMPLICIT SET OF heim_any OPTIONAL,
crls [1] IMPLICIT heim_any OPTIONAL,
signerInfos SignerInfos,
}
*/
typedef struct SignedData {
CMSVersion version;
DigestAlgorithmIdentifiers digestAlgorithms;
EncapsulatedContentInfo encapContentInfo;
struct SignedData_certificates {
unsigned int len;
heim_any *val;
} *certificates;
heim_any *crls;
SignerInfos signerInfos;
} SignedData;
ASN1EXP int ASN1CALL decode_SignedData(const unsigned char *, size_t, SignedData *, size_t *);
ASN1EXP int ASN1CALL encode_SignedData(unsigned char *, size_t, const SignedData *, size_t *);
ASN1EXP size_t ASN1CALL length_SignedData(const SignedData *);
ASN1EXP int ASN1CALL copy_SignedData (const SignedData *, SignedData *);
ASN1EXP void ASN1CALL free_SignedData (SignedData *);
/*
OriginatorInfo ::= SEQUENCE {
certs [0] IMPLICIT SET OF heim_any OPTIONAL,
crls [1] IMPLICIT heim_any OPTIONAL,
}
*/
typedef struct OriginatorInfo {
struct OriginatorInfo_certs {
unsigned int len;
heim_any *val;
} *certs;
heim_any *crls;
} OriginatorInfo;
ASN1EXP int ASN1CALL decode_OriginatorInfo(const unsigned char *, size_t, OriginatorInfo *, size_t *);
ASN1EXP int ASN1CALL encode_OriginatorInfo(unsigned char *, size_t, const OriginatorInfo *, size_t *);
ASN1EXP size_t ASN1CALL length_OriginatorInfo(const OriginatorInfo *);
ASN1EXP int ASN1CALL copy_OriginatorInfo (const OriginatorInfo *, OriginatorInfo *);
ASN1EXP void ASN1CALL free_OriginatorInfo (OriginatorInfo *);
/*
KeyEncryptionAlgorithmIdentifier ::= AlgorithmIdentifier
*/
typedef AlgorithmIdentifier KeyEncryptionAlgorithmIdentifier;
ASN1EXP int ASN1CALL decode_KeyEncryptionAlgorithmIdentifier(const unsigned char *, size_t, KeyEncryptionAlgorithmIdentifier *, size_t *);
ASN1EXP int ASN1CALL encode_KeyEncryptionAlgorithmIdentifier(unsigned char *, size_t, const KeyEncryptionAlgorithmIdentifier *, size_t *);
ASN1EXP size_t ASN1CALL length_KeyEncryptionAlgorithmIdentifier(const KeyEncryptionAlgorithmIdentifier *);
ASN1EXP int ASN1CALL copy_KeyEncryptionAlgorithmIdentifier (const KeyEncryptionAlgorithmIdentifier *, KeyEncryptionAlgorithmIdentifier *);
ASN1EXP void ASN1CALL free_KeyEncryptionAlgorithmIdentifier (KeyEncryptionAlgorithmIdentifier *);
/*
ContentEncryptionAlgorithmIdentifier ::= AlgorithmIdentifier
*/
typedef AlgorithmIdentifier ContentEncryptionAlgorithmIdentifier;
ASN1EXP int ASN1CALL decode_ContentEncryptionAlgorithmIdentifier(const unsigned char *, size_t, ContentEncryptionAlgorithmIdentifier *, size_t *);
ASN1EXP int ASN1CALL encode_ContentEncryptionAlgorithmIdentifier(unsigned char *, size_t, const ContentEncryptionAlgorithmIdentifier *, size_t *);
ASN1EXP size_t ASN1CALL length_ContentEncryptionAlgorithmIdentifier(const ContentEncryptionAlgorithmIdentifier *);
ASN1EXP int ASN1CALL copy_ContentEncryptionAlgorithmIdentifier (const ContentEncryptionAlgorithmIdentifier *, ContentEncryptionAlgorithmIdentifier *);
ASN1EXP void ASN1CALL free_ContentEncryptionAlgorithmIdentifier (ContentEncryptionAlgorithmIdentifier *);
/*
EncryptedKey ::= OCTET STRING
*/
typedef heim_octet_string EncryptedKey;
ASN1EXP int ASN1CALL decode_EncryptedKey(const unsigned char *, size_t, EncryptedKey *, size_t *);
ASN1EXP int ASN1CALL encode_EncryptedKey(unsigned char *, size_t, const EncryptedKey *, size_t *);
ASN1EXP size_t ASN1CALL length_EncryptedKey(const EncryptedKey *);
ASN1EXP int ASN1CALL copy_EncryptedKey (const EncryptedKey *, EncryptedKey *);
ASN1EXP void ASN1CALL free_EncryptedKey (EncryptedKey *);
/*
KeyTransRecipientInfo ::= SEQUENCE {
version CMSVersion,
rid RecipientIdentifier,
keyEncryptionAlgorithm KeyEncryptionAlgorithmIdentifier,
encryptedKey EncryptedKey,
}
*/
typedef struct KeyTransRecipientInfo {
CMSVersion version;
RecipientIdentifier rid;
KeyEncryptionAlgorithmIdentifier keyEncryptionAlgorithm;
EncryptedKey encryptedKey;
} KeyTransRecipientInfo;
ASN1EXP int ASN1CALL decode_KeyTransRecipientInfo(const unsigned char *, size_t, KeyTransRecipientInfo *, size_t *);
ASN1EXP int ASN1CALL encode_KeyTransRecipientInfo(unsigned char *, size_t, const KeyTransRecipientInfo *, size_t *);
ASN1EXP size_t ASN1CALL length_KeyTransRecipientInfo(const KeyTransRecipientInfo *);
ASN1EXP int ASN1CALL copy_KeyTransRecipientInfo (const KeyTransRecipientInfo *, KeyTransRecipientInfo *);
ASN1EXP void ASN1CALL free_KeyTransRecipientInfo (KeyTransRecipientInfo *);
/*
RecipientInfo ::= KeyTransRecipientInfo
*/
typedef KeyTransRecipientInfo RecipientInfo;
ASN1EXP int ASN1CALL decode_RecipientInfo(const unsigned char *, size_t, RecipientInfo *, size_t *);
ASN1EXP int ASN1CALL encode_RecipientInfo(unsigned char *, size_t, const RecipientInfo *, size_t *);
ASN1EXP size_t ASN1CALL length_RecipientInfo(const RecipientInfo *);
ASN1EXP int ASN1CALL copy_RecipientInfo (const RecipientInfo *, RecipientInfo *);
ASN1EXP void ASN1CALL free_RecipientInfo (RecipientInfo *);
/*
RecipientInfos ::= SET OF RecipientInfo
*/
typedef struct RecipientInfos {
unsigned int len;
RecipientInfo *val;
} RecipientInfos;
ASN1EXP int ASN1CALL decode_RecipientInfos(const unsigned char *, size_t, RecipientInfos *, size_t *);
ASN1EXP int ASN1CALL encode_RecipientInfos(unsigned char *, size_t, const RecipientInfos *, size_t *);
ASN1EXP size_t ASN1CALL length_RecipientInfos(const RecipientInfos *);
ASN1EXP int ASN1CALL copy_RecipientInfos (const RecipientInfos *, RecipientInfos *);
ASN1EXP void ASN1CALL free_RecipientInfos (RecipientInfos *);
/*
EncryptedContent ::= OCTET STRING
*/
typedef heim_octet_string EncryptedContent;
ASN1EXP int ASN1CALL decode_EncryptedContent(const unsigned char *, size_t, EncryptedContent *, size_t *);
ASN1EXP int ASN1CALL encode_EncryptedContent(unsigned char *, size_t, const EncryptedContent *, size_t *);
ASN1EXP size_t ASN1CALL length_EncryptedContent(const EncryptedContent *);
ASN1EXP int ASN1CALL copy_EncryptedContent (const EncryptedContent *, EncryptedContent *);
ASN1EXP void ASN1CALL free_EncryptedContent (EncryptedContent *);
/*
EncryptedContentInfo ::= SEQUENCE {
contentType ContentType,
contentEncryptionAlgorithm ContentEncryptionAlgorithmIdentifier,
encryptedContent [0] IMPLICIT OCTET STRING OPTIONAL,
}
*/
typedef struct EncryptedContentInfo {
ContentType contentType;
ContentEncryptionAlgorithmIdentifier contentEncryptionAlgorithm;
heim_octet_string *encryptedContent;
} EncryptedContentInfo;
ASN1EXP int ASN1CALL decode_EncryptedContentInfo(const unsigned char *, size_t, EncryptedContentInfo *, size_t *);
ASN1EXP int ASN1CALL encode_EncryptedContentInfo(unsigned char *, size_t, const EncryptedContentInfo *, size_t *);
ASN1EXP size_t ASN1CALL length_EncryptedContentInfo(const EncryptedContentInfo *);
ASN1EXP int ASN1CALL copy_EncryptedContentInfo (const EncryptedContentInfo *, EncryptedContentInfo *);
ASN1EXP void ASN1CALL free_EncryptedContentInfo (EncryptedContentInfo *);
/*
UnprotectedAttributes ::= SET OF Attribute
*/
typedef struct UnprotectedAttributes {
unsigned int len;
Attribute *val;
} UnprotectedAttributes;
ASN1EXP int ASN1CALL decode_UnprotectedAttributes(const unsigned char *, size_t, UnprotectedAttributes *, size_t *);
ASN1EXP int ASN1CALL encode_UnprotectedAttributes(unsigned char *, size_t, const UnprotectedAttributes *, size_t *);
ASN1EXP size_t ASN1CALL length_UnprotectedAttributes(const UnprotectedAttributes *);
ASN1EXP int ASN1CALL copy_UnprotectedAttributes (const UnprotectedAttributes *, UnprotectedAttributes *);
ASN1EXP void ASN1CALL free_UnprotectedAttributes (UnprotectedAttributes *);
/*
CMSEncryptedData ::= SEQUENCE {
version CMSVersion,
encryptedContentInfo EncryptedContentInfo,
unprotectedAttrs [1] IMPLICIT heim_any OPTIONAL,
}
*/
typedef struct CMSEncryptedData {
CMSVersion version;
EncryptedContentInfo encryptedContentInfo;
heim_any *unprotectedAttrs;
} CMSEncryptedData;
ASN1EXP int ASN1CALL decode_CMSEncryptedData(const unsigned char *, size_t, CMSEncryptedData *, size_t *);
ASN1EXP int ASN1CALL encode_CMSEncryptedData(unsigned char *, size_t, const CMSEncryptedData *, size_t *);
ASN1EXP size_t ASN1CALL length_CMSEncryptedData(const CMSEncryptedData *);
ASN1EXP int ASN1CALL copy_CMSEncryptedData (const CMSEncryptedData *, CMSEncryptedData *);
ASN1EXP void ASN1CALL free_CMSEncryptedData (CMSEncryptedData *);
/*
EnvelopedData ::= SEQUENCE {
version CMSVersion,
originatorInfo [0] IMPLICIT heim_any OPTIONAL,
recipientInfos RecipientInfos,
encryptedContentInfo EncryptedContentInfo,
unprotectedAttrs [1] IMPLICIT heim_any OPTIONAL,
}
*/
typedef struct EnvelopedData {
CMSVersion version;
heim_any *originatorInfo;
RecipientInfos recipientInfos;
EncryptedContentInfo encryptedContentInfo;
heim_any *unprotectedAttrs;
} EnvelopedData;
ASN1EXP int ASN1CALL decode_EnvelopedData(const unsigned char *, size_t, EnvelopedData *, size_t *);
ASN1EXP int ASN1CALL encode_EnvelopedData(unsigned char *, size_t, const EnvelopedData *, size_t *);
ASN1EXP size_t ASN1CALL length_EnvelopedData(const EnvelopedData *);
ASN1EXP int ASN1CALL copy_EnvelopedData (const EnvelopedData *, EnvelopedData *);
ASN1EXP void ASN1CALL free_EnvelopedData (EnvelopedData *);
/*
CMSRC2CBCParameter ::= SEQUENCE {
rc2ParameterVersion INTEGER (0..-1),
iv OCTET STRING,
}
*/
typedef struct CMSRC2CBCParameter {
unsigned int rc2ParameterVersion;
heim_octet_string iv;
} CMSRC2CBCParameter;
ASN1EXP int ASN1CALL decode_CMSRC2CBCParameter(const unsigned char *, size_t, CMSRC2CBCParameter *, size_t *);
ASN1EXP int ASN1CALL encode_CMSRC2CBCParameter(unsigned char *, size_t, const CMSRC2CBCParameter *, size_t *);
ASN1EXP size_t ASN1CALL length_CMSRC2CBCParameter(const CMSRC2CBCParameter *);
ASN1EXP int ASN1CALL copy_CMSRC2CBCParameter (const CMSRC2CBCParameter *, CMSRC2CBCParameter *);
ASN1EXP void ASN1CALL free_CMSRC2CBCParameter (CMSRC2CBCParameter *);
/*
CMSCBCParameter ::= OCTET STRING
*/
typedef heim_octet_string CMSCBCParameter;
ASN1EXP int ASN1CALL decode_CMSCBCParameter(const unsigned char *, size_t, CMSCBCParameter *, size_t *);
ASN1EXP int ASN1CALL encode_CMSCBCParameter(unsigned char *, size_t, const CMSCBCParameter *, size_t *);
ASN1EXP size_t ASN1CALL length_CMSCBCParameter(const CMSCBCParameter *);
ASN1EXP int ASN1CALL copy_CMSCBCParameter (const CMSCBCParameter *, CMSCBCParameter *);
ASN1EXP void ASN1CALL free_CMSCBCParameter (CMSCBCParameter *);
#endif /* __cms_asn1_h__ */
| 38.746518 | 154 | 0.765528 | [
"object"
] |
d08e5fc28a0381d2406f7f291d464090235e852f | 11,748 | h | C | d912pxy/d912pxy_config.h | Meme-sys/d912pxy | 97f2cdb618c84ed189c2e396865a60d6e5ea9753 | [
"MIT"
] | null | null | null | d912pxy/d912pxy_config.h | Meme-sys/d912pxy | 97f2cdb618c84ed189c2e396865a60d6e5ea9753 | [
"MIT"
] | null | null | null | d912pxy/d912pxy_config.h | Meme-sys/d912pxy | 97f2cdb618c84ed189c2e396865a60d6e5ea9753 | [
"MIT"
] | null | null | null | /*
MIT License
Copyright(c) 2018-2020 megai2
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.
*/
#pragma once
#include "stdafx.h"
typedef enum d912pxy_config_value {
PXY_CFG_POOLING_UPLOAD_ALLOC_STEP = 0,
PXY_CFG_POOLING_UPLOAD_LIMITS = 1,
PXY_CFG_POOLING_UPLOAD_LIMITS_BIG,
PXY_CFG_POOLING_VSTREAM_ALLOC_STEP,
PXY_CFG_POOLING_VSTREAM_ALLOC_STEP_BIG,
PXY_CFG_POOLING_VSTREAM_LIMITS,
PXY_CFG_POOLING_VSTREAM_LIMITS_BIG,
PXY_CFG_POOLING_SURFACE_ALLOC_STEP,
PXY_CFG_POOLING_SURFACE_LIMITS,
PXY_CFG_POOLING_LIFETIME,
PXY_CFG_POOLING_HOST_VA_RESERVE,
PXY_CFG_POOLING_KEEP_RESIDENT,
PXY_CFG_SAMPLERS_MIN_LOD,
PXY_CFG_CLEANUP_PERIOD,
PXY_CFG_CLEANUP_SUBSLEEP,
PXY_CFG_CLEANUP_SOFT_LIMIT,
PXY_CFG_CLEANUP_HARD_LIMIT,
PXY_CFG_CLEANUP_AFTER_RESET_MAID,
PXY_CFG_SDB_ALLOW_PP_SUFFIX,
PXY_CFG_SDB_FORCE_UNUSED_REGS,
PXY_CFG_SDB_NAN_GUARD_FLAG,
PXY_CFG_SDB_PRECOMPILE_LIMIT,
PXY_CFG_REPLAY_BEHAIVOUR,
PXY_CFG_REPLAY_THREADS,
PXY_CFG_REPLAY_ITEMS_PER_BATCH,
PXY_CFG_MT_VSTREAM_CTOR,
PXY_CFG_MT_SURFACE_CTOR,
PXY_CFG_MT_DXC_THREADS,
PXY_CFG_MT_PSO_THREADS,
PXY_CFG_LOG_P7CONFIG,
PXY_CFG_LOG_PERF_GRAPH,
PXY_CFG_LOG_DBG_MEM_MGR_SAVE_NEW_CALLER,
PXY_CFG_LOG_ENABLE_VEH,
PXY_CFG_LOG_LOAD_RDOC,
PXY_CFG_UPLOAD_TEX_ASYNC,
PXY_CFG_BATCHING_FORCE_NEW_BATCH,
PXY_CFG_BATCHING_RAW_GPUW,
PXY_CFG_BATCHING_MAX_WRITES_PER_BATCH,
PXY_CFG_BATCHING_MAX_BATCHES_PER_IFRAME,
PXY_CFG_DX_DBG_RUNTIME,
PXY_CFG_DX_FRAME_LATENCY,
PXY_CFG_DX_ROUTE_TO_DX9,
PXY_CFG_MISC_GPU_TIMEOUT,
PXY_CFG_MISC_NV_DISABLE_THROTTLE,
PXY_CFG_COMPAT_OCCLUSION,
PXY_CFG_COMPAT_OCCLUSION_OPT_CONSTRUCTOR,
PXY_CFG_COMPAT_CLEAR,
PXY_CFG_COMPAT_CPU_API_REDUCTION,
PXY_CFG_COMPAT_BATCH_COMMIT,
PXY_CFG_COMPAT_OMRT_VIEWPORT_RESET,
PXY_CFG_COMPAT_TRACK_RS,
PXY_CFG_COMPAT_DUP_UNSAFE,
PXY_CFG_COMPAT_DHEAP_MODE,
PXY_CFG_COMPAT_EXPLICIT_D3DCOMPILER,
PXY_CFG_VFS_ROOT,
PXY_CFG_VFS_MEMCACHE_MASK,
PXY_CFG_VFS_PACK_DATA,
PXY_CFG_VFS_WRITE_MASK,
PXY_CFG_EXTRAS_ENABLE,
PXY_CFG_EXTRAS_FPS_LIMIT,
PXY_CFG_EXTRAS_FPS_LIMIT_INACTIVE,
PXY_CFG_EXTRAS_SHOW_FPS,
PXY_CFG_EXTRAS_SHOW_DRAW_COUNT,
PXY_CFG_EXTRAS_SHOW_FPS_GRAPH,
PXY_CFG_EXTRAS_SHOW_TIMINGS,
PXY_CFG_EXTRAS_SHOW_PSO_COMPILE_QUE,
PXY_CFG_EXTRAS_SHOW_GC_QUE,
PXY_CFG_EXTRAS_OVERLAY_TOGGLE_KEY,
PXY_CFG_EXTRAS_FPS_GRAPH_MAX,
PXY_CFG_EXTRAS_FPS_GRAPH_MIN,
PXY_CFG_EXTRAS_FPS_GRAPH_W,
PXY_CFG_EXTRAS_FPS_GRAPH_H,
PXY_CFG_EXTRAS_ENABLE_CONFIG_EDITOR,
PXY_CFG_EXTRAS_FIRST_INSTALL_MESSAGE,
PXY_CFG_EXTRAS_IFRAME_MOD_SOURCE,
PXY_CFG_EXTRAS_TRACK_SHADER_PAIRS,
PXY_CFG_EXTRAS_SPAIR_SOURCE,
PXY_CFG_CNT
} d912pxy_config_value;
typedef struct d912pxy_config_value_dsc {
wchar_t section[255];
wchar_t name[255];
wchar_t value[255];
const wchar_t* limitation;
const wchar_t* shortDescription;
const wchar_t* longDescription;
char* newValue;
} d912pxy_config_value_dsc;
class d912pxy_config
{
public:
d912pxy_config();
~d912pxy_config();
void Init();
UINT64 GetValueXI64(d912pxy_config_value val);
UINT64 GetValueUI64(d912pxy_config_value val);
UINT32 GetValueUI32(d912pxy_config_value val);
bool GetValueB(d912pxy_config_value val);
wchar_t* GetValueRaw(d912pxy_config_value val);
void InitNewValueBuffers();
void UnInitNewValueBuffers();
void ValueToNewValueBuffers();
void SaveConfig();
d912pxy_config_value_dsc* GetEntryRaw(d912pxy_config_value val);
private:
d912pxy_config_value_dsc data[PXY_CFG_CNT] = {
{
L"pooling",
L"upload_alloc_step",
L"16",
L"u r:0,1024",
L"upload segment allocation step",
L"controls how much space will be allocated for segment that is used to take upload memory from",
nullptr
},//PXY_CFG_POOLING_UPLOAD_ALLOC_STEP
{L"pooling", L"upload_limit", L"128"},//PXY_CFG_POOLING_UPLOAD_LIMITS
{L"pooling", L"upload_limit_big", L"512"},//PXY_CFG_POOLING_UPLOAD_LIMITS_BIG
{L"pooling", L"vstream_alloc_step", L"16"},//PXY_CFG_POOLING_VSTREAM_ALLOC_STEP
{L"pooling", L"vstream_alloc_step_big", L"64"},//PXY_CFG_POOLING_VSTREAM_ALLOC_STEP_BIG
{L"pooling", L"vstream_limit", L"256"},//PXY_CFG_POOLING_VSTREAM_LIMITS
{L"pooling", L"vstream_limit_big", L"768"},//PXY_CFG_POOLING_VSTREAM_LIMITS_BIG
{L"pooling", L"surface_alloc_step",L"0"},//PXY_CFG_POOLING_SURFACE_ALLOC_STEP
{L"pooling", L"surface_limits",L"00000"},//PXY_CFG_POOLING_SURFACE_LIMITS
{L"pooling", L"lifetime",L"10000"},//PXY_CFG_POOLING_LIFETIME
{L"pooling", L"host_va_reserve",L"37"},//PXY_CFG_POOLING_HOST_VA_RESERVE
{L"pooling", L"keep_resident",L"0"},//PXY_CFG_POOLING_KEEP_RESIDENT
{L"samplers", L"min_lod", L"0"},//PXY_CFG_SAMPLERS_MIN_LOD
{L"cleanup", L"period",L"10000"},//PXY_CFG_CLEANUP_PERIOD
{L"cleanup", L"subsleep",L"50"},//PXY_CFG_CLEANUP_SUBSLEEP
{L"cleanup", L"soft_limit",L"3000"},//PXY_CFG_CLEANUP_SOFT_LIMIT
{L"cleanup", L"hard_limit",L"4000"},//PXY_CFG_CLEANUP_HARD_LIMIT
{L"cleanup", L"after_reset_maid",L"2"},//PXY_CFG_CLEANUP_AFTER_RESET_MAID
{L"sdb", L"allow_pp_suffix", L"1"},//PXY_CFG_SDB_ALLOW_PP_SUFFIX
{L"sdb", L"force_unused_regs", L"0"},//PXY_CFG_SDB_FORCE_UNUSED_REGS
{L"sdb", L"nan_guard_flag", L"81"},//PXY_CFG_SDB_NAN_GUARD_FLAG
{
L"sdb",
L"precompile_limit",
L"10000",
L"u r:0,+inf",
L"limit on how much shaders will be precompiled on startup",
L"increasing this value will reduce object pop-ins, but increase RAM usage and game startup time",
nullptr
},
//PXY_CFG_SDB_PRECOMPILE_LIMIT
{L"replay", L"replay", L"1"},//PXY_CFG_REPLAY_BEHAIVOUR
{L"replay", L"replay_threads", L"1"},//PXY_CFG_REPLAY_THREADS
{L"replay", L"items_per_batch", L"100"},//PXY_CFG_REPLAY_ITEMS_PER_BATCH
{L"mt", L"vstream_ctor", L"1"},//PXY_CFG_MT_VSTREAM_CTOR
{L"mt", L"surface_ctor", L"1"},//PXY_CFG_MT_SURFACE_CTOR
{L"mt", L"dxc_threads", L"-1"},//PXY_CFG_MT_DXC_THREADS
{L"mt", L"pso_threads", L"-1"},//PXY_CFG_MT_PSO_THREADS
{L"log", L"p7config", L"/P7.Pool=32768 /P7.Sink=FileBin"},//PXY_CFG_LOG_P7CONFIG
{L"log", L"perf_graph", L"0"},//PXY_CFG_LOG_PERF_GRAPH
{L"log", L"dbg_mem_mgr_save_new_caller", L"0"},//PXY_CFG_LOG_DBG_MEM_MGR_SAVE_NEW_CALLER
{L"log", L"enable_veh", L"1"}, //PXY_CFG_LOG_ENABLE_VEH
{L"log", L"load_rdoc", L"0"},//PXY_CFG_LOG_LOAD_RDOC
{L"upload",L"tex_async",L"0"},//PXY_CFG_UPLOAD_TEX_ASYNC
{L"batching",L"force_new",L"0"},//PXY_CFG_BATCHING_FORCE_NEW_BATCH
{L"batching",L"raw_gpuw",L"0"},//PXY_CFG_BATCHING_RAW_GPUW
{
L"batching",
L"maxWritesPerBatch",
L"128",
L"u r:10,+inf",
L"max GPU writes in one batch",
L"space that is allocated for GPU writes in batch buffer, affect RAM usage, low values can create crashes",
nullptr
},//PXY_CFG_BATCHING_MAX_WRITES_PER_BATCH,
{
L"batching",
L"maxBatchesPerIFrame",
L"8192",
L"u r:5,+inf",
L"max batches in internal frame",
L"limit of batches in internal frame, affects RAM&VRAM usage, low values reduce performance, high values improve performance in heavy loaded scenes",
nullptr
},//PXY_CFG_BATCHING_MAX_BATCHES_PER_IFRAME,
{L"dx",L"debug",L"0"},//PXY_CFG_DX_DBG_RUNTIME
{
L"dx",
L"dxgi_frame_latency",
L"0",
L"u r:0,3",
L"enables and configures dxgi frame latency feature",
L"0 disables swapchain waits, any other value enables swapchain waits and trying to set this value as max frame latency"
},//PXY_CFG_DX_FRAME_LATENCY
{L"dx",L"route_to_dx9",L"0"},//PXY_CFG_DX_ROUTE_TO_DX9
{L"misc",L"gpu_timeout",L"5000"},//PXY_CFG_MISC_GPU_TIMEOUT
{L"misc",L"nv_disable_throttle", L"0"},//PXY_CFG_MISC_NV_DISABLE_THROTTLE
{L"compat",L"occlusion",L"2"},//PXY_CFG_COMPAT_OCCLUSION
{L"compat",L"occlusion_opt_ctor",L"0"},//PXY_CFG_COMPAT_OCCLUSION_OPT_CONSTRUCTOR
{L"compat",L"clear",L"0"},//PXY_CFG_COMPAT_CLEAR
{L"compat",L"cpu_api_reduction",L"0"},//PXY_CFG_COMPAT_CPU_API_REDUCTION
{L"compat",L"batch_commit",L"0"},//PXY_CFG_COMPAT_BATCH_COMMIT
{L"compat",L"omrt_viewport_reset",L"0"},//PXY_CFG_COMPAT_OMRT_VIEWPORT_RESET
{L"compat",L"track_rs",L"0"},//PXY_CFG_COMPAT_TRACK_RS
{L"compat",L"unsafe_dup",L"0"},//PXY_CFG_COMPAT_DUP_UNSAFE
{L"compat",L"dheap_mode",L"0"},//PXY_CFG_COMPAT_DHEAP_MODE
{
L"compat",
L"explicit_d3dcompiler_dll",
L"0",
L"b r:0,1",
L"Allows to use d912pxy supplied d3d compiler dll",
L"If 1 uses d3d compiler 27 v10 lib from 12on7 instead of default one"
},//PXY_CFG_COMPAT_EXPLICIT_D3DCOMPILER
{L"vfs", L"root", L"./d912pxy/pck"},//PXY_CFG_VFS_ROOT
{L"vfs", L"memcache_mask", L"63"},//PXY_CFG_VFS_MEMCACHE_MASK
{L"vfs", L"pack_data", L"0"},//PXY_CFG_VFS_PACK_DATA
{L"vfs", L"write_mask", L"0"},//PXY_CFG_VFS_WRITE_MASK
{L"extras", L"enable", L"1"},//PXY_CFG_EXTRAS_ENABLE
{L"extras", L"fps_limit", L"0"},//PXY_CFG_EXTRAS_FPS_LIMIT,
{L"extras", L"fps_limit_inactive", L"0"},//PXY_CFG_EXTRAS_FPS_LIMIT_INACTIVE,
{L"extras", L"show_fps", L"1"},//PXY_CFG_EXTRAS_SHOW_FPS,
{L"extras", L"show_draw_count", L"1"},//PXY_CFG_EXTRAS_SHOW_DRAW_COUNT,
{L"extras", L"show_fps_graph", L"1"},//PXY_CFG_EXTRAS_SHOW_FPS_GRAPH,
{L"extras", L"show_timings", L"1"},//PXY_CFG_EXTRAS_SHOW_TIMINGS,
{L"extras", L"show_pso_compile_que", L"1"},//PXY_CFG_EXTRAS_SHOW_PSO_COMPILE_QUE,
{L"extras", L"show_gc_que", L"1"},//PXY_CFG_EXTRAS_SHOW_GC_QUE,
{L"extras", L"overlay_toggle_key", L"78"},//PXY_CFG_EXTRAS_OVERLAY_TOGGLE_KEY
{L"extras", L"fps_graph_max", L"80"},//PXY_CFG_EXTRAS_FPS_GRAPH_MAX
{L"extras", L"fps_graph_min", L"0"},//PXY_CFG_EXTRAS_FPS_GRAPH_MIN
{L"extras", L"fps_graph_w", L"512"},//PXY_CFG_EXTRAS_FPS_GRAPH_W
{L"extras", L"fps_graph_h", L"256"},//PXY_CFG_EXTRAS_FPS_GRAPH_H
{L"extras", L"enable_config_editor",L"1"},//PXY_CFG_EXTRAS_ENABLE_CONFIG_EDITOR
{L"extras", L"show_first_install_message",L"1"},//PXY_CFG_EXTRAS_FIRST_INSTALL_MESSAGE
{
L"extras",
L"iframe_mod_source",
L"none",
L"s r:valid path to file or \"none\" string"
L"source of iframe modifications",
L"defines source of iframe modifications scripts"
L"iframe modifications transform api stream to perform specific effects"
L"by default no modifications are used. modifications are strongly game dependant!"
L"builtin modifications live in d912pxy/shaders/mods"
},//PXY_CFG_EXTRAS_IFRAME_MOD_SOURCE
{
L"extras",
L"shader_pair_tracker",
L"0",
L"b r:[0-1]",
L"enable/disable shader pair tracker in overlay",
L"if enabled will record and show every draw shader pair with supplied marks if found in d912pxy/shaders/pairs/<cfg>"
L"iframe mods should be enabled for this feature to work"
},//PXY_CFG_EXTRAS_TRACK_SHADER_PAIRS
{
L"extras",
L"spair_source",
L"none",
L"s r:valid directory name or \"none\" string",
L"defines source for shader pair information",
L"will read data from d912pxy/shaders/pairs/<value> for shader pair info"
}//PXY_CFG_EXTRAS_SPAIR_SOURCE
};
};
| 39.959184 | 152 | 0.773408 | [
"object",
"transform"
] |
d08f1411a35370255ac06f91cb0fd730fb1dcfe8 | 2,137 | c | C | animal3D SDK/source/animal3D-DemoPlugin/A3_DEMO/a3_DemoMode0_Intro/a3_DemoMode0_Intro-idle-input.c | connorramsden/advanced-realtime-rendering | 973c23816093a22fc4f30de512df832a30ae75d6 | [
"Apache-2.0"
] | 1 | 2021-02-11T22:40:47.000Z | 2021-02-11T22:40:47.000Z | animal3D SDK/source/animal3D-DemoPlugin/A3_DEMO/a3_DemoMode0_Intro/a3_DemoMode0_Intro-idle-input.c | connorramsden/advanced-realtime-rendering | 973c23816093a22fc4f30de512df832a30ae75d6 | [
"Apache-2.0"
] | null | null | null | animal3D SDK/source/animal3D-DemoPlugin/A3_DEMO/a3_DemoMode0_Intro/a3_DemoMode0_Intro-idle-input.c | connorramsden/advanced-realtime-rendering | 973c23816093a22fc4f30de512df832a30ae75d6 | [
"Apache-2.0"
] | null | null | null | /*
Copyright 2011-2021 Daniel S. Buckstein
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.
*/
/*
animal3D SDK: Minimal 3D Animation Framework
By Daniel S. Buckstein
a3_DemoMode0_Intro-idle-input.c
Demo mode implementations: animation scene.
********************************************
*** INPUT FOR ANIMATION SCENE MODE ***
********************************************
*/
//-----------------------------------------------------------------------------
#include "../a3_DemoMode0_Intro.h"
typedef struct a3_DemoState a3_DemoState;
//#include "../a3_DemoState.h"
#include "../_a3_demo_utilities/a3_DemoMacros.h"
//-----------------------------------------------------------------------------
// CALLBACKS
// main demo mode callback
void a3intro_input_keyCharPress(a3_DemoState const* demoState, a3_DemoMode0_Intro* demoMode, a3i32 const asciiKey, a3i32 const state)
{
switch (asciiKey)
{
// toggle render program
a3demoCtrlCasesLoop(demoMode->renderMode, intro_renderMode_max, 'k', 'j');
}
}
void a3intro_input_keyCharHold(a3_DemoState const* demoState, a3_DemoMode0_Intro* demoMode, a3i32 const asciiKey, a3i32 const state)
{
// switch (asciiKey)
// {
//
// }
}
//-----------------------------------------------------------------------------
void a3intro_input(a3_DemoState* demoState, a3_DemoMode0_Intro* demoMode, a3f64 const dt)
{
void a3demo_input_controlProjector(a3_ProjectorComponent const* projector,
a3_DemoState const* demoState, a3f64 const dt);
a3demo_input_controlProjector(demoMode->proj_camera_main, demoState, dt);
}
//-----------------------------------------------------------------------------
| 29.273973 | 133 | 0.621432 | [
"render",
"3d"
] |
d09515240ab84f8ebd53c09e8a0393704ec718c2 | 4,989 | h | C | eos_lib/include/eos/fitting/detail/nonlinear_camera_estimation_detail.h | KeeganRen/eos_lib | 6ff8902721e3c03983dc45c2b7edfd81ef9e3507 | [
"Apache-2.0"
] | null | null | null | eos_lib/include/eos/fitting/detail/nonlinear_camera_estimation_detail.h | KeeganRen/eos_lib | 6ff8902721e3c03983dc45c2b7edfd81ef9e3507 | [
"Apache-2.0"
] | null | null | null | eos_lib/include/eos/fitting/detail/nonlinear_camera_estimation_detail.h | KeeganRen/eos_lib | 6ff8902721e3c03983dc45c2b7edfd81ef9e3507 | [
"Apache-2.0"
] | null | null | null | /*
* Eos - A 3D Morphable Model fitting library written in modern C++11/14.
*
* File: include/eos/fitting/detail/nonlinear_camera_estimation_detail.hpp
*
* Copyright 2015 Patrik Huber
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#ifndef NONLINEARCAMERAESTIMATION_DETAIL_HPP_
#define NONLINEARCAMERAESTIMATION_DETAIL_HPP_
#include "glm/gtc/matrix_transform.hpp"
#include "Eigen/Geometry"
#include "opencv2/core/core.hpp"
#include <vector>
namespace eos {
namespace fitting {
namespace detail {
// ret: 3rd entry is the z
// radians
// expects the landmark points to be in opencv convention, i.e. origin TL
glm::vec3 project_ortho(glm::vec3 point, float rot_x_pitch, float rot_y_yaw, float rot_z_roll, float tx, float ty, float frustum_scale, /* fixed params now: */ int width, int height);
//{
// // We could use quaternions in here, to be independent of the RPY... etc convention.
// // Then, the user can decompose the quaternion as he wishes to. But then we'd have to estimate 4 parameters?
// // This can of course be optimised, but we keep it this way while we're debugging and as long as it's not a performance issue.
// auto rot_mtx_x = glm::rotate(glm::mat4(1.0f), rot_x_pitch, glm::vec3{ 1.0f, 0.0f, 0.0f });
// auto rot_mtx_y = glm::rotate(glm::mat4(1.0f), rot_y_yaw, glm::vec3{ 0.0f, 1.0f, 0.0f });
// auto rot_mtx_z = glm::rotate(glm::mat4(1.0f), rot_z_roll, glm::vec3{ 0.0f, 0.0f, 1.0f });
// auto t_mtx = glm::translate(glm::mat4(1.0f), glm::vec3{ tx, ty, 0.0f }); // glm: Col-major memory layout. [] gives the column
// // Note/Todo: Is this the full ortho? n/f missing? or do we need to multiply it with Proj...? See Shirley CG!
// // glm::frustum()?
// const float aspect = static_cast<float>(width) / height;
// auto ortho_mtx = glm::ortho(-1.0f * aspect * frustum_scale, 1.0f * aspect * frustum_scale, -1.0f * frustum_scale, 1.0f * frustum_scale);
// glm::vec4 viewport(0, height, width, -height); // flips y, origin top-left, like in OpenCV
// // P = RPY * P
// glm::vec3 res = glm::project(point, t_mtx * rot_mtx_z * rot_mtx_x * rot_mtx_y, ortho_mtx, viewport);
// return res;
//};
/**
* @brief Generic functor for Eigen's optimisation algorithms.
*/
template<typename _Scalar, int NX = Eigen::Dynamic, int NY = Eigen::Dynamic>
struct Functor
{
typedef _Scalar Scalar;
enum {
InputsAtCompileTime = NX,
ValuesAtCompileTime = NY
};
typedef Eigen::Matrix<Scalar, InputsAtCompileTime, 1> InputType;
typedef Eigen::Matrix<Scalar, ValuesAtCompileTime, 1> ValueType;
typedef Eigen::Matrix<Scalar, ValuesAtCompileTime, InputsAtCompileTime> JacobianType;
const int m_inputs, m_values;
Functor() : m_inputs(InputsAtCompileTime), m_values(ValuesAtCompileTime) {}
Functor(int inputs, int values) : m_inputs(inputs), m_values(values) {}
int inputs() const { return m_inputs; }
int values() const { return m_values; }
};
/**
* @brief LevenbergMarquardt cost function for the orthographic camera estimation.
*/
struct OrthographicParameterProjection : Functor<double>
{
public:
// Creates a new OrthographicParameterProjection object with given data.
OrthographicParameterProjection(std::vector<cv::Vec2f> image_points, std::vector<cv::Vec4f> model_points, int width, int height) : Functor<double>(6, image_points.size()), image_points(image_points), model_points(model_points), width(width), height(height) {};
// x = current params, fvec = the errors/differences of the proj with current params and the GT (image_points)
int operator()(const Eigen::VectorXd& x, Eigen::VectorXd& fvec) const
{
const float aspect = static_cast<float>(width) / height;
for (int i = 0; i < values(); i++)
{
// opencv to glm:
glm::vec3 point_3d(model_points[i][0], model_points[i][1], model_points[i][2]);
// projection given current params x:
glm::vec3 proj_with_current_param_esti = project_ortho(point_3d, x[0], x[1], x[2], x[3], x[4], x[5], width, height);
cv::Vec2f proj_point_2d(proj_with_current_param_esti.x, proj_with_current_param_esti.y);
// diff of current proj to ground truth, our error
auto diff = cv::norm(proj_point_2d, image_points[i]);
// fvec should contain the differences
// don't square it.
fvec[i] = diff;
}
return 0;
};
private:
std::vector<cv::Vec2f> image_points;
std::vector<cv::Vec4f> model_points;
int width;
int height;
};
} /* namespace detail */
} /* namespace fitting */
} /* namespace eos */
#endif /* NONLINEARCAMERAESTIMATION_DETAIL_HPP_ */
| 39.283465 | 261 | 0.718581 | [
"geometry",
"object",
"vector",
"model",
"3d"
] |
d09836eab6fba69eb681eacdee3606d2781a4613 | 631 | h | C | cases/adaptative_surfers/param/post/objects/surfer__us_1o0__surftimeprefactor_0o25/py/group/all/parameters.h | C0PEP0D/sheld0n | 497d4ee8b6b1815cd5fa1b378d1b947ee259f4bc | [
"MIT"
] | null | null | null | cases/adaptative_surfers/param/post/objects/surfer__us_1o0__surftimeprefactor_0o25/py/group/all/parameters.h | C0PEP0D/sheld0n | 497d4ee8b6b1815cd5fa1b378d1b947ee259f4bc | [
"MIT"
] | null | null | null | cases/adaptative_surfers/param/post/objects/surfer__us_1o0__surftimeprefactor_0o25/py/group/all/parameters.h | C0PEP0D/sheld0n | 497d4ee8b6b1815cd5fa1b378d1b947ee259f4bc | [
"MIT"
] | null | null | null | #ifndef C0P_PARAM_POST_OBJECTS_SURFER__US_1O0__SURFTIMEPREFACTOR_0O25_PY_GROUP_ALL_PARAMETERS_H
#define C0P_PARAM_POST_OBJECTS_SURFER__US_1O0__SURFTIMEPREFACTOR_0O25_PY_GROUP_ALL_PARAMETERS_H
#pragma once
// app include
#include "core/post/objects/object/post/group/all/prop.h"
// post member choice
#include "param/post/objects/surfer__us_1o0__surftimeprefactor_0o25/py/group/_member/choice.h"
namespace c0p {
struct PostSurferUs1O0Surftimeprefactor0O25PyGroupAllParameters {
template<typename TypeMemberStep>
using TypePostPostMember = PostSurferUs1O0Surftimeprefactor0O25PyGroupMember<TypeMemberStep>;
};
}
#endif
| 30.047619 | 97 | 0.862124 | [
"object"
] |
d0988fecff65ef0913f87f76187e543397833b3f | 1,959 | h | C | llvm-2.9/lib/CodeGen/ConflictGraph.h | vidkidz/crossbridge | ba0bf94aee0ce6cf7eb5be882382e52bc57ba396 | [
"MIT"
] | 1 | 2016-04-09T02:58:13.000Z | 2016-04-09T02:58:13.000Z | llvm-2.9/lib/CodeGen/ConflictGraph.h | vidkidz/crossbridge | ba0bf94aee0ce6cf7eb5be882382e52bc57ba396 | [
"MIT"
] | null | null | null | llvm-2.9/lib/CodeGen/ConflictGraph.h | vidkidz/crossbridge | ba0bf94aee0ce6cf7eb5be882382e52bc57ba396 | [
"MIT"
] | null | null | null | // Copyright (c) 2013 Adobe Systems Inc
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#ifndef CONFLICTGRAPH_H
#define CONFLICTGRAPH_H
#include "llvm/Support/DataTypes.h"
#include <tr1/unordered_map>
#include <vector>
class ConflictGraphVertex;
// simple conflict graph class w/ greedy coloring
class ConflictGraph
{
// id => vertex
typedef std::tr1::unordered_map<uintptr_t, ConflictGraphVertex *> Vertices;
Vertices _vertices;
public:
// id => color numbered from [0..n]
typedef std::vector< std::pair<uintptr_t, unsigned> > Coloring;
~ConflictGraph();
// add a single vertex with an arbitrary id
// redundant vertex adds are legal
void addVertex(uintptr_t a);
// add an edge between two arbitrary vertex ids (which may have but need not have been addVertex-ed)
// redundant edge adds are legal
void addEdge(uintptr_t a, uintptr_t b);
void color(Coloring *result) const; // generate a coloring in result
};
#endif
| 36.962264 | 101 | 0.761613 | [
"vector"
] |
d0a729744152c6e859a07111defa166dae6c212f | 1,734 | h | C | class/app/automapa.h | TheMarlboroMan/go-fgj6 | fa1cdfcd5ecaf4f0ea25b23890310e76fd2504bd | [
"Beerware"
] | null | null | null | class/app/automapa.h | TheMarlboroMan/go-fgj6 | fa1cdfcd5ecaf4f0ea25b23890310e76fd2504bd | [
"Beerware"
] | null | null | null | class/app/automapa.h | TheMarlboroMan/go-fgj6 | fa1cdfcd5ecaf4f0ea25b23890310e76fd2504bd | [
"Beerware"
] | null | null | null | #ifndef AUTOMAPA_H
#define AUTOMAPA_H
#include <string>
#include <vector>
#include <class/dnot_parser.h>
namespace App
{
//Todos los valores de dimensiones no están en píxeles. sino en medidas de sala.
//Más o menos 1x equivale a un ancho de pantalla y 1y equivale a un alto.
//Las coordenadas están expresadas en formato de pantalla (w es hacia la derecha
//mientras que h es hacia abajo. 0,0 es la esquina superior izquierda.
//Estructura para representar una salida.
struct Automapa_salida
{
int x, y;
enum class torientaciones{nada, norte, oeste, sur, este} orientacion;
static torientaciones int_a_orientacion(int);
static int orientacion_a_int(torientaciones);
static Automapa_salida desde_token(const Herramientas_proyecto::Dnot_token&);
};
//Estructura para representar una sala.
struct Automapa_sala
{
enum class tmarcadores{nada, arbol, metal, madera, agua, fuego, tierra, velocidad};
int id, x, y, w, h;
std::vector<Automapa_salida> salidas;
std::vector<tmarcadores> marcadores;
static tmarcadores int_a_marcador(int);
static int marcador_a_int(tmarcadores);
static Automapa_sala desde_token(const Herramientas_proyecto::Dnot_token&);
};
//Clase de control de las salas. No tiene nada que ver con la representación:
//sólo contiene el mapa del mundo y se encarga de marcar las salas como
//visitadas o no.
class Automapa
{
public:
void cargar(const std::string&);
void visitar(int);
void reiniciar();
size_t size() const {return salas.size();}
std::vector<Automapa_sala> obtener_visitadas() const;
private:
struct sala{
Automapa_sala s;
bool visitada;
// sala(const Automapa_sala& s):s(s), visitada(false) {};
};
std::vector<sala> salas;
};
}
#endif
| 24.422535 | 84 | 0.743368 | [
"vector"
] |
d0a9da65ce723a9ce836d39c4ec7446576eee0dd | 8,512 | c | C | usr/src/cmd/backup/dump/lftw.c | AsahiOS/gate | 283d47da4e17a5871d9d575e7ffb81e8f6c52e51 | [
"MIT"
] | null | null | null | usr/src/cmd/backup/dump/lftw.c | AsahiOS/gate | 283d47da4e17a5871d9d575e7ffb81e8f6c52e51 | [
"MIT"
] | null | null | null | usr/src/cmd/backup/dump/lftw.c | AsahiOS/gate | 283d47da4e17a5871d9d575e7ffb81e8f6c52e51 | [
"MIT"
] | 1 | 2020-12-30T00:04:16.000Z | 2020-12-30T00:04:16.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 2005 Sun Microsystems, Inc. All rights reserved.
* Use is subject to license terms.
*/
/* Copyright (c) 1988 AT&T */
/* All Rights Reserved */
/* LINTLIBRARY */
/*
* ftw - file tree walk
*
* int ftw (path, fn, depth) char *path; int (*fn)(); int depth;
*
* Given a path name, ftw starts from the file given by that path
* name and visits each file and directory in the tree beneath
* that file. If a single file has multiple links within the
* structure, it will be visited once for each such link.
* For each object visited, fn is called with three arguments.
* The first contains the path name of the object, the second
* contains a pointer to a stat buffer which will usually hold
* appropriate information for the object and the third will
* contain an integer value giving additional information:
*
* FTW_F The object is a file for which stat was
* successful. It does not guarantee that the
* file can actually be read.
*
* FTW_D The object is a directory for which stat and
* open for read were both successful.
*
* FTW_DNR The object is a directory for which stat
* succeeded, but which cannot be read. Because
* the directory cannot be read, fn will not be
* called for any descendants of this directory.
*
* FTW_NS Stat failed on the object because of lack of
* appropriate permission. This indication will
* be given, for example, for each file in a
* directory with read but no execute permission.
* Because stat failed, it is not possible to
* determine whether this object is a file or a
* directory. The stat buffer passed to fn will
* contain garbage. Stat failure for any reason
* other than lack of permission will be
* considered an error and will cause ftw to stop
* and return -1 to its caller.
*
* If fn returns nonzero, ftw stops and returns the same value
* to its caller. If ftw gets into other trouble along the way,
* it returns -1 and leaves an indication of the cause in errno.
*
* The third argument to ftw does not limit the depth to which
* ftw will go. Rather, it limits the depth to which ftw will
* go before it starts recycling file descriptors. In general,
* it is necessary to use a file descriptor for each level of the
* tree, but they can be recycled for deep trees by saving the
* position, closing, re-opening, and seeking. It is possible
* to start recycling file descriptors by sensing when we have
* run out, but in general this will not be terribly useful if
* fn expects to be able to open files. We could also figure out
* how many file descriptors are available and guarantee a certain
* number to fn, but we would not know how many to guarantee,
* and we do not want to impose the extra overhead on a caller who
* knows how many are available without having to figure it out.
*
* It is possible for ftw to die with a memory fault in the event
* of a file system so deeply nested that the stack overflows.
*/
#include <sys/fs/ufs_inode.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <errno.h>
#include <malloc.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <ftw.h>
static int pwdfd;
static int lf_xftw(
const char *,
int (*)(const char *, const struct stat64 *, int),
int,
int (*)(const char *, struct stat64 *));
int
lf_lftw(
const char *path,
int (*fn)(const char *, const struct stat64 *, int),
int depth)
{
int rc;
if ((pwdfd = open(".", O_RDONLY)) < 0) {
return (-1);
} else {
rc = (lf_xftw(path, fn, depth, lstat64));
(void) close(pwdfd);
return (rc);
}
}
static int
#ifdef __STDC__
lf_xftw(
const char *path,
int (*fn)(const char *, const struct stat64 *, int),
int depth,
int (*statfn)(const char *, struct stat64 *))
#else
lf_xftw(char *path, int (*fn)(), int depth, int (*statfn)())
#endif
{
int n;
int rc, sublen, saverr, attrfd;
DIR *dirp;
char *subpath, *component;
struct stat64 sb;
struct dirent *dp;
extern dev_t partial_dev;
/*
* Try to get file status.
* If unsuccessful, errno will say why.
*/
if ((*statfn)(path, &sb) < 0)
return (errno == EACCES? (*fn)(path, &sb, FTW_NS): -1);
/*
* The stat succeeded, so we know the object exists.
* Make sure it is not a mount point for another filesystem.
* The following check must be made here because:
*
* + namefs can be mounted on anything, but a directory
* + all other filesystems must be mounted on a directory
*/
if (sb.st_dev != partial_dev) {
return (0);
}
/*
* Check for presence of attributes on file
*/
if (pathconf(path, _PC_XATTR_EXISTS) == 1) {
attrfd = attropen64(path, ".", O_RDONLY|O_NONBLOCK);
} else {
attrfd = -1;
}
/*
* If not a directory, call the user function and return.
*/
if ((sb.st_mode & S_IFMT) != S_IFDIR &&
(sb.st_mode & IFMT) != IFATTRDIR) {
rc = (*fn)(path, &sb, FTW_F);
if (rc == 0 && attrfd != -1) {
(void) fchdir(attrfd);
rc = lf_xftw(".", fn, depth-1, statfn);
(void) fchdir(pwdfd);
(void) close(attrfd);
}
return (rc);
}
/*
* The object was a directory and not a mount point.
*
* Open a file to read the directory
*/
dirp = opendir(path);
/*
* Call the user function, telling it whether
* the directory can be read. If it can't be read
* call the user function or indicate an error,
* depending on the reason it couldn't be read.
*/
if (dirp == NULL)
rc = (errno == EACCES? (*fn)(path, &sb, FTW_DNR): -1);
else
rc = (*fn)(path, &sb, FTW_D);
/*
* If the directory has attributes, process the
* attributes before processing the directory contents.
*/
if (rc == 0 && attrfd != -1) {
(void) fchdir(attrfd);
rc = lf_xftw(".", fn, depth-1, statfn);
(void) fchdir(pwdfd);
(void) close(attrfd);
}
if (rc != 0 || dirp == NULL)
return (rc);
/* Allocate a buffer to hold generated pathnames. */
/* LINTED: the length will fit into a signed integer */
n = (int)strlen(path);
sublen = n + MAXNAMLEN + 1; /* +1 for appended / */
subpath = malloc((unsigned)(sublen+1)); /* +1 for NUL */
if (subpath == NULL) {
saverr = errno;
(void) closedir(dirp);
errno = saverr;
return (-1);
}
/* Create a prefix to which we will append component names */
(void) strcpy(subpath, path);
if (subpath[0] != '\0' && subpath[n-1] != '/')
subpath[n++] = '/';
component = &subpath[n];
/* LINTED: result will fit into a 32-bit int */
sublen -= component - subpath;
/*
* Read the directory one component at a time.
* We must ignore "." and "..", but other than that,
* just create a path name and call self to check it out.
*/
while ((dp = readdir(dirp)) != NULL) {
if (strcmp(dp->d_name, ".") != 0 &&
strcmp(dp->d_name, "..") != 0) {
long here;
/* Append component name to the working path */
(void) strncpy(component, dp->d_name, sublen);
component[sublen - 1] = '\0';
/*
* If we are about to exceed our depth,
* remember where we are and close a file.
*/
if (depth <= 1) {
here = telldir(dirp);
(void) closedir(dirp);
}
/*
* Do a recursive call to process the file.
* (watch this, sports fans)
*/
rc = lf_xftw(subpath, fn, depth-1, statfn);
if (rc != 0) {
free(subpath);
if (depth > 1)
(void) closedir(dirp);
return (rc);
}
/*
* If we closed the file, try to reopen it.
*/
if (depth <= 1) {
dirp = opendir(path);
if (dirp == NULL) {
free(subpath);
return (-1);
}
seekdir(dirp, here);
}
}
}
/*
* We got out of the subdirectory loop. The return from
* the final readdir is in dp. Clean up.
*/
free(subpath);
(void) closedir(dirp);
return (0);
}
| 29.150685 | 70 | 0.658247 | [
"object"
] |
d0acb0f638a0bc87ecb9dcfa320d9f6047258d1c | 2,249 | h | C | tools/fidlcat/lib/fidlcat_printer.h | dahlia-os/fuchsia-pine64-pinephone | 57aace6f0b0bd75306426c98ab9eb3ff4524a61d | [
"BSD-3-Clause"
] | 10 | 2020-12-28T17:04:44.000Z | 2022-03-12T03:20:43.000Z | tools/fidlcat/lib/fidlcat_printer.h | oshunter/fuchsia | 2196fc8c176d01969466b97bba3f31ec55f7767b | [
"BSD-3-Clause"
] | 1 | 2022-01-14T23:38:40.000Z | 2022-01-14T23:38:40.000Z | tools/fidlcat/lib/fidlcat_printer.h | oshunter/fuchsia | 2196fc8c176d01969466b97bba3f31ec55f7767b | [
"BSD-3-Clause"
] | 4 | 2020-12-28T17:04:45.000Z | 2022-03-12T03:20:44.000Z | // Copyright 2020 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef TOOLS_FIDLCAT_LIB_FIDLCAT_PRINTER_H_
#define TOOLS_FIDLCAT_LIB_FIDLCAT_PRINTER_H_
#include <zircon/system/public/zircon/types.h>
#include "src/developer/debug/zxdb/client/process.h"
#include "src/lib/fidl_codec/wire_object.h"
#include "src/lib/fidl_codec/wire_types.h"
#include "tools/fidlcat/lib/inference.h"
#include "tools/fidlcat/lib/type_decoder.h"
namespace fidlcat {
class HandleInfo;
class Location;
class Process;
class SyscallDisplayDispatcher;
// Printer which allows us to print the infered data for handles.
class FidlcatPrinter : public fidl_codec::PrettyPrinter {
public:
FidlcatPrinter(SyscallDisplayDispatcher* dispatcher, Process* process, std::ostream& os,
const fidl_codec::Colors& colors, std::string_view line_header,
int tabulations = 0);
FidlcatPrinter(SyscallDisplayDispatcher* dispatcher, Process* process, std::ostream& os,
std::string_view line_header, int tabulations = 0);
bool display_stack_frame() const { return display_stack_frame_; }
bool DumpMessages() const override { return dump_messages_; }
void DisplayHandle(const zx_handle_info_t& handle) override;
void DisplayHandle(zx_handle_t handle) {
zx_handle_info_t info = {.handle = handle, .type = 0, .rights = 0};
DisplayHandle(info);
}
void DisplayHandleInfo(HandleInfo* handle_info);
void DisplayStatus(zx_status_t status);
void DisplayInline(
const std::vector<std::unique_ptr<fidl_codec::StructMember>>& members,
const std::map<const fidl_codec::StructMember*, std::unique_ptr<fidl_codec::Value>>& values);
void DisplayOutline(
const std::vector<std::unique_ptr<fidl_codec::StructMember>>& members,
const std::map<const fidl_codec::StructMember*, std::unique_ptr<fidl_codec::Value>>& values);
void DisplayStackFrame(const std::vector<Location>& stack_frame);
private:
const Inference& inference_;
Process* const process_;
const bool display_stack_frame_;
const bool dump_messages_;
};
} // namespace fidlcat
#endif // TOOLS_FIDLCAT_LIB_FIDLCAT_PRINTER_H_
| 36.868852 | 99 | 0.755447 | [
"vector"
] |
d0aeaa69803ab3bd82a2db06d3472e908d6429a6 | 4,234 | h | C | test/t-unit/html-report.h | Lavesson/api-mock | 07f0c3d2213df7be7699258d4273c58f13958763 | [
"MIT"
] | null | null | null | test/t-unit/html-report.h | Lavesson/api-mock | 07f0c3d2213df7be7699258d4273c58f13958763 | [
"MIT"
] | null | null | null | test/t-unit/html-report.h | Lavesson/api-mock | 07f0c3d2213df7be7699258d4273c58f13958763 | [
"MIT"
] | null | null | null | #ifndef T_UNIT_HTML_REPORT_H
#define T_UNIT_HTML_REPORT_H
#include "t-unit.h"
#include <sstream>
#include <fstream>
#include <string>
#include <vector>
#include <iostream>
std::ostream& operator<<(std::ostream& os, const test_result& test);
std::ostream& operator<<(std::ostream& os, const test_harness& harness);
std::ostream& operator<<(std::ostream& os, const test_fixture& fixture);
class html_report : public report_generator
{
private:
const std::string report_file;
public:
friend std::ostream& operator<<(std::ostream& os, const test_result& test);
friend std::ostream& operator<<(std::ostream& os, const test_harness& harness);
friend std::ostream& operator<<(std::ostream& os, const test_fixture& fixture);
void generate_for(const test_harness& harness) {
std::fstream file(report_file.c_str(), std::fstream::out);
file << harness;
file.flush();
file.close();
}
explicit html_report(const std::string& report_file)
: report_file(report_file) {}
};
std::ostream& operator<<(std::ostream& os, const test_harness& harness) {
// DTD+head
os << "<!doctype html>" << "<html lang=\"en\">";
os << "<head><title>Test Report [t-unit]</title>";
os << "<link rel=\"stylesheet\" href=\"report.css\">";
os << "<script src=\"details-shim.js\"></script></head>";
// Body
os << "<body><code>";
// Test harness header
os << "<details open=\"open\" id=\"header\">";
os << "<summary>Test Report [" << harness.t_unit_version() << "]</summary>";
os << "<div class=\"diagnostics\">";
os << "<div>" << harness.num_total_tests() << " tests in " << harness.num_fixtures() <<" fixtures. Ran in " << harness.duration_ms() << " ms.</div>";
os << "<div class=\"passed\">" << harness.num_passed_tests() << " passed</div>";
os << "<div class=\"failed\">" << harness.num_failed_tests() << " failed</div>";
os << "<div class=\"inconclusive\">" << harness.num_inconclusive_tests() << " inconclusive</div>";
os << "<div class=\"skipped\">" << harness.num_skipped_tests() << " skipped</div>";
os << "</div>";
os << "</details>";
// stream fixtures
for (auto f : harness.fixtures())
os << *f;
os << "</code></body>";
os << "</html>";
return os;
}
std::ostream& operator<<(std::ostream& os, const test_fixture& fixture) {
bool none_failed = fixture.failed_test_count() == 0;
std::string fixture_class = (none_failed ? "passed" : "failed");
std::string details_attribute = (none_failed ? "" : " open=\"open\"");
int dur = fixture.total_duration_ms();
os << "<div class=\"fixture\"><details" << details_attribute << ">";
os << "<summary>" << fixture.name << " - <span class=\"" << fixture_class << "\">"
<< (none_failed ? "Passed" : "Failed") << " [" << (dur == 0 ? "<1" : std::to_string(dur))
<< " ms]" << "</span>" << "</summary>";
os << "<div class=\"test-collection\">";
for (auto result : fixture.results)
os << result;
os << "</div>";
os << "</details>";
os << "</div>";
return os;
}
std::ostream& operator<<(std::ostream& os, const test_result& test) {
std::string case_class; std::string case_text;
std::string details_attribute = (test.ok ? "" : " open=\"open\"");
os << "<details class=\"test\"" << details_attribute << ">";
int dur = test.duration_ms;
switch (test.status) {
case test_status::ok: case_class = "passed"; case_text = "Passed [" + (dur == 0 ? "<1" : std::to_string(dur)) + " ms]"; break;
case test_status::not_ok: case_class = "failed"; case_text = "Failed [" + (dur == 0 ? "<1" : std::to_string(dur)) + " ms]"; break;
case test_status::skipped: case_class = "skipped"; case_text = "Skipped"; break;
case test_status::inconclusive: case_class = "inconclusive"; case_text = "Inconclusive"; break;
default: case_class = "[unknown]"; case_text = "[unknown]"; break;
}
os << "<summary>" << test.test_label << " - <span class=\"" << case_class << "\">" << case_text << "</span></summary>";
if (test.status == test_status::not_ok) {
auto d = test.diagnostics;
os << "<div class=\"diagnostics " << case_class << "\"><br>";
os << "# got: " << d.actual << "<br>";
os << "# expected: " << d.expected << "<br>";
if (d.comment != "") os << "# " << d.comment << "<br>";
os << "</div>";
}
os << "</details>";
return os;
}
#endif
| 34.991736 | 150 | 0.61573 | [
"vector"
] |
d0afed9ebd0ed9cac3a4803f6f1622959802c9d9 | 19,900 | c | C | security/apparmor/file.c | fergy/aplit_linux-5 | a6ef4cb0e17e1eec9743c064e65f730c49765711 | [
"MIT"
] | 1 | 2020-09-20T03:48:15.000Z | 2020-09-20T03:48:15.000Z | security/apparmor/file.c | fergy/aplit_linux-5 | a6ef4cb0e17e1eec9743c064e65f730c49765711 | [
"MIT"
] | null | null | null | security/apparmor/file.c | fergy/aplit_linux-5 | a6ef4cb0e17e1eec9743c064e65f730c49765711 | [
"MIT"
] | null | null | null | /*
* AppArmor security module
*
* This file contains AppArmor mediation of files
*
* Copyright (C) 1998-2008 Novell/SUSE
* Copyright 2009-2010 Canonical Ltd.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation, version 2 of the
* License.
*/
#include <linux/tty.h>
#include <linux/fdtable.h>
#include <linux/file.h>
#include "include/apparmor.h"
#include "include/audit.h"
#include "include/cred.h"
#include "include/file.h"
#include "include/match.h"
#include "include/net.h"
#include "include/path.h"
#include "include/policy.h"
#include "include/label.h"
static u32 map_mask_to_chr_mask(u32 mask)
{
u32 m = mask & PERMS_CHRS_MASK;
if (mask & AA_MAY_GETATTR)
m |= MAY_READ;
if (mask & (AA_MAY_SETATTR | AA_MAY_CHMOD | AA_MAY_CHOWN))
m |= MAY_WRITE;
return m;
}
/**
* audit_file_mask - convert mask to permission string
* @buffer: buffer to write string to (NOT NULL)
* @mask: permission mask to convert
*/
static void audit_file_mask(struct audit_buffer *ab, u32 mask)
{
char str[10];
aa_perm_mask_to_str(str, sizeof(str), aa_file_perm_chrs,
map_mask_to_chr_mask(mask));
audit_log_string(ab, str);
}
/**
* file_audit_cb - call back for file specific audit fields
* @ab: audit_buffer (NOT NULL)
* @va: audit struct to audit values of (NOT NULL)
*/
static void file_audit_cb(struct audit_buffer *ab, void *va)
{
struct common_audit_data *sa = va;
kuid_t fsuid = current_fsuid();
if (aad(sa)->request & AA_AUDIT_FILE_MASK) {
audit_log_format(ab, " requested_mask=");
audit_file_mask(ab, aad(sa)->request);
}
if (aad(sa)->denied & AA_AUDIT_FILE_MASK) {
audit_log_format(ab, " denied_mask=");
audit_file_mask(ab, aad(sa)->denied);
}
if (aad(sa)->request & AA_AUDIT_FILE_MASK) {
audit_log_format(ab, " fsuid=%d",
from_kuid(&init_user_ns, fsuid));
audit_log_format(ab, " ouid=%d",
from_kuid(&init_user_ns, aad(sa)->fs.ouid));
}
if (aad(sa)->peer) {
audit_log_format(ab, " target=");
aa_label_xaudit(ab, labels_ns(aad(sa)->label), aad(sa)->peer,
FLAG_VIEW_SUBNS, GFP_ATOMIC);
} else if (aad(sa)->fs.target) {
audit_log_format(ab, " target=");
audit_log_untrustedstring(ab, aad(sa)->fs.target);
}
}
/**
* aa_audit_file - handle the auditing of file operations
* @profile: the profile being enforced (NOT NULL)
* @perms: the permissions computed for the request (NOT NULL)
* @op: operation being mediated
* @request: permissions requested
* @name: name of object being mediated (MAYBE NULL)
* @target: name of target (MAYBE NULL)
* @tlabel: target label (MAY BE NULL)
* @ouid: object uid
* @info: extra information message (MAYBE NULL)
* @error: 0 if operation allowed else failure error code
*
* Returns: %0 or error on failure
*/
int aa_audit_file(struct aa_profile *profile, struct aa_perms *perms,
const char *op, u32 request, const char *name,
const char *target, struct aa_label *tlabel,
kuid_t ouid, const char *info, int error)
{
int type = AUDIT_APPARMOR_AUTO;
DEFINE_AUDIT_DATA(sa, LSM_AUDIT_DATA_TASK, op);
sa.u.tsk = NULL;
aad(&sa)->request = request;
aad(&sa)->name = name;
aad(&sa)->fs.target = target;
aad(&sa)->peer = tlabel;
aad(&sa)->fs.ouid = ouid;
aad(&sa)->info = info;
aad(&sa)->error = error;
sa.u.tsk = NULL;
if (likely(!aad(&sa)->error)) {
u32 mask = perms->audit;
if (unlikely(AUDIT_MODE(profile) == AUDIT_ALL))
mask = 0xffff;
/* mask off perms that are not being force audited */
aad(&sa)->request &= mask;
if (likely(!aad(&sa)->request))
return 0;
type = AUDIT_APPARMOR_AUDIT;
} else {
/* only report permissions that were denied */
aad(&sa)->request = aad(&sa)->request & ~perms->allow;
AA_BUG(!aad(&sa)->request);
if (aad(&sa)->request & perms->kill)
type = AUDIT_APPARMOR_KILL;
/* quiet known rejects, assumes quiet and kill do not overlap */
if ((aad(&sa)->request & perms->quiet) &&
AUDIT_MODE(profile) != AUDIT_NOQUIET &&
AUDIT_MODE(profile) != AUDIT_ALL)
aad(&sa)->request &= ~perms->quiet;
if (!aad(&sa)->request)
return aad(&sa)->error;
}
aad(&sa)->denied = aad(&sa)->request & ~perms->allow;
return aa_audit(type, profile, &sa, file_audit_cb);
}
/**
* is_deleted - test if a file has been completely unlinked
* @dentry: dentry of file to test for deletion (NOT NULL)
*
* Returns: %1 if deleted else %0
*/
static inline bool is_deleted(struct dentry *dentry)
{
if (d_unlinked(dentry) && d_backing_inode(dentry)->i_nlink == 0)
return 1;
return 0;
}
static int path_name(const char *op, struct aa_label *label,
const struct path *path, int flags, char *buffer,
const char **name, struct path_cond *cond, u32 request)
{
struct aa_profile *profile;
const char *info = NULL;
int error;
error = aa_path_name(path, flags, buffer, name, &info,
labels_profile(label)->disconnected);
if (error) {
fn_for_each_confined(label, profile,
aa_audit_file(profile, &nullperms, op, request, *name,
NULL, NULL, cond->uid, info, error));
return error;
}
return 0;
}
/**
* map_old_perms - map old file perms layout to the new layout
* @old: permission set in old mapping
*
* Returns: new permission mapping
*/
static u32 map_old_perms(u32 old)
{
u32 new = old & 0xf;
if (old & MAY_READ)
new |= AA_MAY_GETATTR | AA_MAY_OPEN;
if (old & MAY_WRITE)
new |= AA_MAY_SETATTR | AA_MAY_CREATE | AA_MAY_DELETE |
AA_MAY_CHMOD | AA_MAY_CHOWN | AA_MAY_OPEN;
if (old & 0x10)
new |= AA_MAY_LINK;
/* the old mapping lock and link_subset flags where overlaid
* and use was determined by part of a pair that they were in
*/
if (old & 0x20)
new |= AA_MAY_LOCK | AA_LINK_SUBSET;
if (old & 0x40) /* AA_EXEC_MMAP */
new |= AA_EXEC_MMAP;
return new;
}
/**
* aa_compute_fperms - convert dfa compressed perms to internal perms
* @dfa: dfa to compute perms for (NOT NULL)
* @state: state in dfa
* @cond: conditions to consider (NOT NULL)
*
* TODO: convert from dfa + state to permission entry, do computation conversion
* at load time.
*
* Returns: computed permission set
*/
struct aa_perms aa_compute_fperms(struct aa_dfa *dfa, unsigned int state,
struct path_cond *cond)
{
/* FIXME: change over to new dfa format
* currently file perms are encoded in the dfa, new format
* splits the permissions from the dfa. This mapping can be
* done at profile load
*/
struct aa_perms perms = { };
if (uid_eq(current_fsuid(), cond->uid)) {
perms.allow = map_old_perms(dfa_user_allow(dfa, state));
perms.audit = map_old_perms(dfa_user_audit(dfa, state));
perms.quiet = map_old_perms(dfa_user_quiet(dfa, state));
perms.xindex = dfa_user_xindex(dfa, state);
} else {
perms.allow = map_old_perms(dfa_other_allow(dfa, state));
perms.audit = map_old_perms(dfa_other_audit(dfa, state));
perms.quiet = map_old_perms(dfa_other_quiet(dfa, state));
perms.xindex = dfa_other_xindex(dfa, state);
}
perms.allow |= AA_MAY_GETATTR;
/* change_profile wasn't determined by ownership in old mapping */
if (ACCEPT_TABLE(dfa)[state] & 0x80000000)
perms.allow |= AA_MAY_CHANGE_PROFILE;
if (ACCEPT_TABLE(dfa)[state] & 0x40000000)
perms.allow |= AA_MAY_ONEXEC;
return perms;
}
/**
* aa_str_perms - find permission that match @name
* @dfa: to match against (MAYBE NULL)
* @state: state to start matching in
* @name: string to match against dfa (NOT NULL)
* @cond: conditions to consider for permission set computation (NOT NULL)
* @perms: Returns - the permissions found when matching @name
*
* Returns: the final state in @dfa when beginning @start and walking @name
*/
unsigned int aa_str_perms(struct aa_dfa *dfa, unsigned int start,
const char *name, struct path_cond *cond,
struct aa_perms *perms)
{
unsigned int state;
state = aa_dfa_match(dfa, start, name);
*perms = aa_compute_fperms(dfa, state, cond);
return state;
}
int __aa_path_perm(const char *op, struct aa_profile *profile, const char *name,
u32 request, struct path_cond *cond, int flags,
struct aa_perms *perms)
{
int e = 0;
if (profile_unconfined(profile))
return 0;
aa_str_perms(profile->file.dfa, profile->file.start, name, cond, perms);
if (request & ~perms->allow)
e = -EACCES;
return aa_audit_file(profile, perms, op, request, name, NULL, NULL,
cond->uid, NULL, e);
}
static int profile_path_perm(const char *op, struct aa_profile *profile,
const struct path *path, char *buffer, u32 request,
struct path_cond *cond, int flags,
struct aa_perms *perms)
{
const char *name;
int error;
if (profile_unconfined(profile))
return 0;
error = path_name(op, &profile->label, path,
flags | profile->path_flags, buffer, &name, cond,
request);
if (error)
return error;
return __aa_path_perm(op, profile, name, request, cond, flags,
perms);
}
/**
* aa_path_perm - do permissions check & audit for @path
* @op: operation being checked
* @label: profile being enforced (NOT NULL)
* @path: path to check permissions of (NOT NULL)
* @flags: any additional path flags beyond what the profile specifies
* @request: requested permissions
* @cond: conditional info for this request (NOT NULL)
*
* Returns: %0 else error if access denied or other error
*/
int aa_path_perm(const char *op, struct aa_label *label,
const struct path *path, int flags, u32 request,
struct path_cond *cond)
{
struct aa_perms perms = {};
struct aa_profile *profile;
char *buffer = NULL;
int error;
flags |= PATH_DELEGATE_DELETED | (S_ISDIR(cond->mode) ? PATH_IS_DIR :
0);
get_buffers(buffer);
error = fn_for_each_confined(label, profile,
profile_path_perm(op, profile, path, buffer, request,
cond, flags, &perms));
put_buffers(buffer);
return error;
}
/**
* xindex_is_subset - helper for aa_path_link
* @link: link permission set
* @target: target permission set
*
* test target x permissions are equal OR a subset of link x permissions
* this is done as part of the subset test, where a hardlink must have
* a subset of permissions that the target has.
*
* Returns: %1 if subset else %0
*/
static inline bool xindex_is_subset(u32 link, u32 target)
{
if (((link & ~AA_X_UNSAFE) != (target & ~AA_X_UNSAFE)) ||
((link & AA_X_UNSAFE) && !(target & AA_X_UNSAFE)))
return 0;
return 1;
}
static int profile_path_link(struct aa_profile *profile,
const struct path *link, char *buffer,
const struct path *target, char *buffer2,
struct path_cond *cond)
{
const char *lname, *tname = NULL;
struct aa_perms lperms = {}, perms;
const char *info = NULL;
u32 request = AA_MAY_LINK;
unsigned int state;
int error;
error = path_name(OP_LINK, &profile->label, link, profile->path_flags,
buffer, &lname, cond, AA_MAY_LINK);
if (error)
goto audit;
/* buffer2 freed below, tname is pointer in buffer2 */
error = path_name(OP_LINK, &profile->label, target, profile->path_flags,
buffer2, &tname, cond, AA_MAY_LINK);
if (error)
goto audit;
error = -EACCES;
/* aa_str_perms - handles the case of the dfa being NULL */
state = aa_str_perms(profile->file.dfa, profile->file.start, lname,
cond, &lperms);
if (!(lperms.allow & AA_MAY_LINK))
goto audit;
/* test to see if target can be paired with link */
state = aa_dfa_null_transition(profile->file.dfa, state);
aa_str_perms(profile->file.dfa, state, tname, cond, &perms);
/* force audit/quiet masks for link are stored in the second entry
* in the link pair.
*/
lperms.audit = perms.audit;
lperms.quiet = perms.quiet;
lperms.kill = perms.kill;
if (!(perms.allow & AA_MAY_LINK)) {
info = "target restricted";
lperms = perms;
goto audit;
}
/* done if link subset test is not required */
if (!(perms.allow & AA_LINK_SUBSET))
goto done_tests;
/* Do link perm subset test requiring allowed permission on link are
* a subset of the allowed permissions on target.
*/
aa_str_perms(profile->file.dfa, profile->file.start, tname, cond,
&perms);
/* AA_MAY_LINK is not considered in the subset test */
request = lperms.allow & ~AA_MAY_LINK;
lperms.allow &= perms.allow | AA_MAY_LINK;
request |= AA_AUDIT_FILE_MASK & (lperms.allow & ~perms.allow);
if (request & ~lperms.allow) {
goto audit;
} else if ((lperms.allow & MAY_EXEC) &&
!xindex_is_subset(lperms.xindex, perms.xindex)) {
lperms.allow &= ~MAY_EXEC;
request |= MAY_EXEC;
info = "link not subset of target";
goto audit;
}
done_tests:
error = 0;
audit:
return aa_audit_file(profile, &lperms, OP_LINK, request, lname, tname,
NULL, cond->uid, info, error);
}
/**
* aa_path_link - Handle hard link permission check
* @label: the label being enforced (NOT NULL)
* @old_dentry: the target dentry (NOT NULL)
* @new_dir: directory the new link will be created in (NOT NULL)
* @new_dentry: the link being created (NOT NULL)
*
* Handle the permission test for a link & target pair. Permission
* is encoded as a pair where the link permission is determined
* first, and if allowed, the target is tested. The target test
* is done from the point of the link match (not start of DFA)
* making the target permission dependent on the link permission match.
*
* The subset test if required forces that permissions granted
* on link are a subset of the permission granted to target.
*
* Returns: %0 if allowed else error
*/
int aa_path_link(struct aa_label *label, struct dentry *old_dentry,
const struct path *new_dir, struct dentry *new_dentry)
{
struct path link = { .mnt = new_dir->mnt, .dentry = new_dentry };
struct path target = { .mnt = new_dir->mnt, .dentry = old_dentry };
struct path_cond cond = {
d_backing_inode(old_dentry)->i_uid,
d_backing_inode(old_dentry)->i_mode
};
char *buffer = NULL, *buffer2 = NULL;
struct aa_profile *profile;
int error;
/* buffer freed below, lname is pointer in buffer */
get_buffers(buffer, buffer2);
error = fn_for_each_confined(label, profile,
profile_path_link(profile, &link, buffer, &target,
buffer2, &cond));
put_buffers(buffer, buffer2);
return error;
}
static void update_file_ctx(struct aa_file_ctx *fctx, struct aa_label *label,
u32 request)
{
struct aa_label *l, *old;
/* update caching of label on file_ctx */
spin_lock(&fctx->lock);
old = rcu_dereference_protected(fctx->label,
lockdep_is_held(&fctx->lock));
l = aa_label_merge(old, label, GFP_ATOMIC);
if (l) {
if (l != old) {
rcu_assign_pointer(fctx->label, l);
aa_put_label(old);
} else
aa_put_label(l);
fctx->allow |= request;
}
spin_unlock(&fctx->lock);
}
static int __file_path_perm(const char *op, struct aa_label *label,
struct aa_label *flabel, struct file *file,
u32 request, u32 denied)
{
struct aa_profile *profile;
struct aa_perms perms = {};
struct path_cond cond = {
.uid = file_inode(file)->i_uid,
.mode = file_inode(file)->i_mode
};
char *buffer;
int flags, error;
/* revalidation due to label out of date. No revocation at this time */
if (!denied && aa_label_is_subset(flabel, label))
/* TODO: check for revocation on stale profiles */
return 0;
flags = PATH_DELEGATE_DELETED | (S_ISDIR(cond.mode) ? PATH_IS_DIR : 0);
get_buffers(buffer);
/* check every profile in task label not in current cache */
error = fn_for_each_not_in_set(flabel, label, profile,
profile_path_perm(op, profile, &file->f_path, buffer,
request, &cond, flags, &perms));
if (denied && !error) {
/*
* check every profile in file label that was not tested
* in the initial check above.
*
* TODO: cache full perms so this only happens because of
* conditionals
* TODO: don't audit here
*/
if (label == flabel)
error = fn_for_each(label, profile,
profile_path_perm(op, profile, &file->f_path,
buffer, request, &cond, flags,
&perms));
else
error = fn_for_each_not_in_set(label, flabel, profile,
profile_path_perm(op, profile, &file->f_path,
buffer, request, &cond, flags,
&perms));
}
if (!error)
update_file_ctx(file_ctx(file), label, request);
put_buffers(buffer);
return error;
}
static int __file_sock_perm(const char *op, struct aa_label *label,
struct aa_label *flabel, struct file *file,
u32 request, u32 denied)
{
struct socket *sock = (struct socket *) file->private_data;
int error;
AA_BUG(!sock);
/* revalidation due to label out of date. No revocation at this time */
if (!denied && aa_label_is_subset(flabel, label))
return 0;
/* TODO: improve to skip profiles cached in flabel */
error = aa_sock_file_perm(label, op, request, sock);
if (denied) {
/* TODO: improve to skip profiles checked above */
/* check every profile in file label to is cached */
last_error(error, aa_sock_file_perm(flabel, op, request, sock));
}
if (!error)
update_file_ctx(file_ctx(file), label, request);
return error;
}
/**
* aa_file_perm - do permission revalidation check & audit for @file
* @op: operation being checked
* @label: label being enforced (NOT NULL)
* @file: file to revalidate access permissions on (NOT NULL)
* @request: requested permissions
*
* Returns: %0 if access allowed else error
*/
int aa_file_perm(const char *op, struct aa_label *label, struct file *file,
u32 request)
{
struct aa_file_ctx *fctx;
struct aa_label *flabel;
u32 denied;
int error = 0;
AA_BUG(!label);
AA_BUG(!file);
fctx = file_ctx(file);
rcu_read_lock();
flabel = rcu_dereference(fctx->label);
AA_BUG(!flabel);
/* revalidate access, if task is unconfined, or the cached cred
* doesn't match or if the request is for more permissions than
* was granted.
*
* Note: the test for !unconfined(flabel) is to handle file
* delegation from unconfined tasks
*/
denied = request & ~fctx->allow;
if (unconfined(label) || unconfined(flabel) ||
(!denied && aa_label_is_subset(flabel, label)))
goto done;
/* TODO: label cross check */
if (file->f_path.mnt && path_mediated_fs(file->f_path.dentry))
error = __file_path_perm(op, label, flabel, file, request,
denied);
else if (S_ISSOCK(file_inode(file)->i_mode))
error = __file_sock_perm(op, label, flabel, file, request,
denied);
done:
rcu_read_unlock();
return error;
}
static void revalidate_tty(struct aa_label *label)
{
struct tty_struct *tty;
int drop_tty = 0;
tty = get_current_tty();
if (!tty)
return;
spin_lock(&tty->files_lock);
if (!list_empty(&tty->tty_files)) {
struct tty_file_private *file_priv;
struct file *file;
/* TODO: Revalidate access to controlling tty. */
file_priv = list_first_entry(&tty->tty_files,
struct tty_file_private, list);
file = file_priv->file;
if (aa_file_perm(OP_INHERIT, label, file, MAY_READ | MAY_WRITE))
drop_tty = 1;
}
spin_unlock(&tty->files_lock);
tty_kref_put(tty);
if (drop_tty)
no_tty();
}
static int match_file(const void *p, struct file *file, unsigned int fd)
{
struct aa_label *label = (struct aa_label *)p;
if (aa_file_perm(OP_INHERIT, label, file, aa_map_file_to_perms(file)))
return fd + 1;
return 0;
}
/* based on selinux's flush_unauthorized_files */
void aa_inherit_files(const struct cred *cred, struct files_struct *files)
{
struct aa_label *label = aa_get_newest_cred_label(cred);
struct file *devnull = NULL;
unsigned int n;
revalidate_tty(label);
/* Revalidate access to inherited open files. */
n = iterate_fd(files, 0, match_file, label);
if (!n) /* none found? */
goto out;
devnull = dentry_open(&aa_null, O_RDWR, cred);
if (IS_ERR(devnull))
devnull = NULL;
/* replace all the matching ones with this */
do {
replace_fd(n - 1, devnull, 0);
} while ((n = iterate_fd(files, n, match_file, label)) != 0);
if (devnull)
fput(devnull);
out:
aa_put_label(label);
}
| 28.107345 | 80 | 0.692563 | [
"object"
] |
d0b192dbd4f3618c107191f8e91240b446ecd8c3 | 3,441 | h | C | message/generation/swift-mt-generation/repository/SR2018/parsers/SwiftMtParser_MT496BaseListener.h | Yanick-Salzmann/message-converter-c | 6dfdf56e12f19e0f0b63ee0354fda16968f36415 | [
"MIT"
] | null | null | null | message/generation/swift-mt-generation/repository/SR2018/parsers/SwiftMtParser_MT496BaseListener.h | Yanick-Salzmann/message-converter-c | 6dfdf56e12f19e0f0b63ee0354fda16968f36415 | [
"MIT"
] | null | null | null | message/generation/swift-mt-generation/repository/SR2018/parsers/SwiftMtParser_MT496BaseListener.h | Yanick-Salzmann/message-converter-c | 6dfdf56e12f19e0f0b63ee0354fda16968f36415 | [
"MIT"
] | null | null | null |
#include "repository/ISwiftMtParser.h"
#include "SwiftMtMessage.pb.h"
#include <vector>
#include <string>
#include "BaseErrorListener.h"
#include "SwiftMtParser_MT496Lexer.h"
// Generated from C:/programming/message-converter-c/message/generation/swift-mt-generation/repository/SR2018/grammars/SwiftMtParser_MT496.g4 by ANTLR 4.7.2
#pragma once
#include "antlr4-runtime.h"
#include "SwiftMtParser_MT496Listener.h"
namespace message::definition::swift::mt::parsers::sr2018 {
/**
* This class provides an empty implementation of SwiftMtParser_MT496Listener,
* which can be extended to create a listener which only needs to handle a subset
* of the available methods.
*/
class SwiftMtParser_MT496BaseListener : public SwiftMtParser_MT496Listener {
public:
virtual void enterMessage(SwiftMtParser_MT496Parser::MessageContext * /*ctx*/) override { }
virtual void exitMessage(SwiftMtParser_MT496Parser::MessageContext * /*ctx*/) override { }
virtual void enterBh(SwiftMtParser_MT496Parser::BhContext * /*ctx*/) override { }
virtual void exitBh(SwiftMtParser_MT496Parser::BhContext * /*ctx*/) override { }
virtual void enterBh_content(SwiftMtParser_MT496Parser::Bh_contentContext * /*ctx*/) override { }
virtual void exitBh_content(SwiftMtParser_MT496Parser::Bh_contentContext * /*ctx*/) override { }
virtual void enterAh(SwiftMtParser_MT496Parser::AhContext * /*ctx*/) override { }
virtual void exitAh(SwiftMtParser_MT496Parser::AhContext * /*ctx*/) override { }
virtual void enterAh_content(SwiftMtParser_MT496Parser::Ah_contentContext * /*ctx*/) override { }
virtual void exitAh_content(SwiftMtParser_MT496Parser::Ah_contentContext * /*ctx*/) override { }
virtual void enterUh(SwiftMtParser_MT496Parser::UhContext * /*ctx*/) override { }
virtual void exitUh(SwiftMtParser_MT496Parser::UhContext * /*ctx*/) override { }
virtual void enterTr(SwiftMtParser_MT496Parser::TrContext * /*ctx*/) override { }
virtual void exitTr(SwiftMtParser_MT496Parser::TrContext * /*ctx*/) override { }
virtual void enterSys_block(SwiftMtParser_MT496Parser::Sys_blockContext * /*ctx*/) override { }
virtual void exitSys_block(SwiftMtParser_MT496Parser::Sys_blockContext * /*ctx*/) override { }
virtual void enterSys_element(SwiftMtParser_MT496Parser::Sys_elementContext * /*ctx*/) override { }
virtual void exitSys_element(SwiftMtParser_MT496Parser::Sys_elementContext * /*ctx*/) override { }
virtual void enterSys_element_key(SwiftMtParser_MT496Parser::Sys_element_keyContext * /*ctx*/) override { }
virtual void exitSys_element_key(SwiftMtParser_MT496Parser::Sys_element_keyContext * /*ctx*/) override { }
virtual void enterSys_element_content(SwiftMtParser_MT496Parser::Sys_element_contentContext * /*ctx*/) override { }
virtual void exitSys_element_content(SwiftMtParser_MT496Parser::Sys_element_contentContext * /*ctx*/) override { }
virtual void enterMt(SwiftMtParser_MT496Parser::MtContext * /*ctx*/) override { }
virtual void exitMt(SwiftMtParser_MT496Parser::MtContext * /*ctx*/) override { }
virtual void enterEveryRule(antlr4::ParserRuleContext * /*ctx*/) override { }
virtual void exitEveryRule(antlr4::ParserRuleContext * /*ctx*/) override { }
virtual void visitTerminal(antlr4::tree::TerminalNode * /*node*/) override { }
virtual void visitErrorNode(antlr4::tree::ErrorNode * /*node*/) override { }
};
} // namespace message::definition::swift::mt::parsers::sr2018
| 46.5 | 156 | 0.771287 | [
"vector"
] |
d0b33d85ccb04fcf7ccc9434a09eab399300f60e | 3,445 | h | C | src/Params.h | Cinegy/CinecoderNodeJs | 9f9e932072b5b19ef786eb5bb2ee22381c6fed34 | [
"Apache-2.0"
] | 3 | 2019-02-07T15:42:49.000Z | 2019-12-07T22:17:50.000Z | src/Params.h | Cinegy/CinecoderNodeJs | 9f9e932072b5b19ef786eb5bb2ee22381c6fed34 | [
"Apache-2.0"
] | 3 | 2017-01-13T19:58:04.000Z | 2021-08-31T21:28:10.000Z | src/Params.h | Cinegy/CinecoderNodeJs | 9f9e932072b5b19ef786eb5bb2ee22381c6fed34 | [
"Apache-2.0"
] | 5 | 2017-01-13T17:09:56.000Z | 2019-12-07T22:17:53.000Z | /* Copyright 2017 Streampunk Media Ltd.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef PARAMS_H
#define PARAMS_H
#include <nan.h>
using namespace v8;
namespace streampunk {
class Params {
protected:
Params() {}
virtual ~Params() {}
Local<Value> getKey(Local<Object> tags, const std::string& key) {
Local<Value> val = Nan::Null();
Local<String> keyStr = Nan::New<String>(key).ToLocalChecked();
if (Nan::Has(tags, keyStr).FromJust())
val = Nan::Get(tags, keyStr).ToLocalChecked();
return val;
}
std::string unpackValue(Local<Value> val) {
Local<Array> valueArray = Local<Array>::Cast(val);
MaybeLocal<Value> value = Nan::Get(valueArray, 0);
Nan::Utf8String utf8_value(value.ToLocalChecked());
int len = utf8_value.length();
if (len <= 0) {
std::string err = std::string("arg must be a non-empty string");
throw std::runtime_error(err.c_str());
}
std::string string_copy(*utf8_value, len);
return string_copy;
}
bool unpackBool(Local<Object> tags, const std::string& key, bool dflt) {
bool result = dflt;
Local<Value> val = getKey(tags, key);
if (Nan::Null() != val) {
if (val->IsArray()) {
auto valStr = unpackValue(val);
if (!valStr.empty()) {
if ((0 == valStr.compare("1")) || (0 == valStr.compare("true")))
result = true;
else if ((0 == valStr.compare("0")) || (0 == valStr.compare("false")))
result = false;
}
}
else
result = Nan::To<bool>(val).FromJust();
}
return result;
}
uint32_t unpackNum(Local<Object> tags, const std::string& key, uint32_t dflt) {
uint32_t result = dflt;
Local<Value> val = getKey(tags, key);
if (Nan::Null() != val) {
if (val->IsArray()) {
std::string valStr = unpackValue(val);
result = valStr.empty()?dflt:std::stoi(valStr);
} else
result = Nan::To<uint32_t>(val).FromJust();
}
return result;
}
std::string unpackStr(Local<Object> tags, const std::string& key, std::string dflt) {
std::string result = dflt;
Local<Value> val = getKey(tags, key);
if (Nan::Null() != val) {
if (val->IsArray()) {
auto valStr = unpackValue(val);
result = valStr.empty() ? dflt : valStr;
}
else
{
Nan::Utf8String utf8_value(val);
int len = utf8_value.length();
if (len <= 0) {
std::string err = std::string("arg must be a non-empty string");
throw std::runtime_error(err.c_str());
}
std::string result(*utf8_value, len);
return result;
}
}
return result;
}
private:
Params(const Params &);
};
} // namespace streampunk
#endif
| 28.94958 | 88 | 0.577358 | [
"object"
] |
d0b612c5d973ebc09fa93ff654f24932835316d1 | 627 | h | C | Code/System/Render/RenderSettings.h | JuanluMorales/KRG | f3a11de469586a4ef0db835af4bc4589e6b70779 | [
"MIT"
] | 419 | 2022-01-27T19:37:43.000Z | 2022-03-31T06:14:22.000Z | Code/System/Render/RenderSettings.h | jagt/KRG | ba20cd8798997b0450491b0cc04dc817c4a4bc76 | [
"MIT"
] | 2 | 2022-01-28T20:35:33.000Z | 2022-03-13T17:42:52.000Z | Code/System/Render/RenderSettings.h | jagt/KRG | ba20cd8798997b0450491b0cc04dc817c4a4bc76 | [
"MIT"
] | 20 | 2022-01-27T20:41:02.000Z | 2022-03-26T16:16:57.000Z | #pragma once
#include "_Module/API.h"
#include "System/Core/Settings/ISettings.h"
#include "System/Core/Math/Math.h"
//-------------------------------------------------------------------------
namespace KRG::Render
{
class KRG_SYSTEM_RENDER_API Settings final : public ISettings
{
public:
KRG_SETTINGS_ID( KRG::Render::Settings );
protected:
virtual bool ReadSettings( IniFile const& ini ) override;
public:
Int2 m_resolution = Int2( 1280, 720 );
float m_refreshRate = 60.0f;
bool m_isFullscreen = false;
};
} | 23.222222 | 76 | 0.529506 | [
"render"
] |
d0c335425518f70090a022024c44ed374fae846c | 10,528 | h | C | aws-cpp-sdk-personalize-runtime/include/aws/personalize-runtime/PersonalizeRuntimeClient.h | crazecdwn/aws-sdk-cpp | e74b9181a56e82ee04cf36a4cb31686047f4be42 | [
"Apache-2.0"
] | 1 | 2020-03-11T05:36:20.000Z | 2020-03-11T05:36:20.000Z | aws-cpp-sdk-personalize-runtime/include/aws/personalize-runtime/PersonalizeRuntimeClient.h | novaquark/aws-sdk-cpp | a0969508545bec9ae2864c9e1e2bb9aff109f90c | [
"Apache-2.0"
] | null | null | null | aws-cpp-sdk-personalize-runtime/include/aws/personalize-runtime/PersonalizeRuntimeClient.h | novaquark/aws-sdk-cpp | a0969508545bec9ae2864c9e1e2bb9aff109f90c | [
"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/personalize-runtime/PersonalizeRuntime_EXPORTS.h>
#include <aws/personalize-runtime/PersonalizeRuntimeErrors.h>
#include <aws/core/client/AWSError.h>
#include <aws/core/client/ClientConfiguration.h>
#include <aws/core/client/AWSClient.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/personalize-runtime/model/GetPersonalizedRankingResult.h>
#include <aws/personalize-runtime/model/GetRecommendationsResult.h>
#include <aws/core/client/AsyncCallerContext.h>
#include <aws/core/http/HttpTypes.h>
#include <future>
#include <functional>
namespace Aws
{
namespace Http
{
class HttpClient;
class HttpClientFactory;
} // namespace Http
namespace Utils
{
template< typename R, typename E> class Outcome;
namespace Threading
{
class Executor;
} // namespace Threading
} // namespace Utils
namespace Auth
{
class AWSCredentials;
class AWSCredentialsProvider;
} // namespace Auth
namespace Client
{
class RetryStrategy;
} // namespace Client
namespace PersonalizeRuntime
{
namespace Model
{
class GetPersonalizedRankingRequest;
class GetRecommendationsRequest;
typedef Aws::Utils::Outcome<GetPersonalizedRankingResult, Aws::Client::AWSError<PersonalizeRuntimeErrors>> GetPersonalizedRankingOutcome;
typedef Aws::Utils::Outcome<GetRecommendationsResult, Aws::Client::AWSError<PersonalizeRuntimeErrors>> GetRecommendationsOutcome;
typedef std::future<GetPersonalizedRankingOutcome> GetPersonalizedRankingOutcomeCallable;
typedef std::future<GetRecommendationsOutcome> GetRecommendationsOutcomeCallable;
} // namespace Model
class PersonalizeRuntimeClient;
typedef std::function<void(const PersonalizeRuntimeClient*, const Model::GetPersonalizedRankingRequest&, const Model::GetPersonalizedRankingOutcome&, const std::shared_ptr<const Aws::Client::AsyncCallerContext>&) > GetPersonalizedRankingResponseReceivedHandler;
typedef std::function<void(const PersonalizeRuntimeClient*, const Model::GetRecommendationsRequest&, const Model::GetRecommendationsOutcome&, const std::shared_ptr<const Aws::Client::AsyncCallerContext>&) > GetRecommendationsResponseReceivedHandler;
/**
* <p/>
*/
class AWS_PERSONALIZERUNTIME_API PersonalizeRuntimeClient : public Aws::Client::AWSJsonClient
{
public:
typedef Aws::Client::AWSJsonClient BASECLASS;
/**
* Initializes client to use DefaultCredentialProviderChain, with default http client factory, and optional client config. If client config
* is not specified, it will be initialized to default values.
*/
PersonalizeRuntimeClient(const Aws::Client::ClientConfiguration& clientConfiguration = Aws::Client::ClientConfiguration());
/**
* Initializes client to use SimpleAWSCredentialsProvider, with default http client factory, and optional client config. If client config
* is not specified, it will be initialized to default values.
*/
PersonalizeRuntimeClient(const Aws::Auth::AWSCredentials& credentials, const Aws::Client::ClientConfiguration& clientConfiguration = Aws::Client::ClientConfiguration());
/**
* Initializes client to use specified credentials provider with specified client config. If http client factory is not supplied,
* the default http client factory will be used
*/
PersonalizeRuntimeClient(const std::shared_ptr<Aws::Auth::AWSCredentialsProvider>& credentialsProvider,
const Aws::Client::ClientConfiguration& clientConfiguration = Aws::Client::ClientConfiguration());
virtual ~PersonalizeRuntimeClient();
inline virtual const char* GetServiceClientName() const override { return "Personalize Runtime"; }
/**
* <p>Re-ranks a list of recommended items for the given user. The first item in
* the list is deemed the most likely item to be of interest to the user.</p>
* <note> <p>The solution backing the campaign must have been created using a
* recipe of type PERSONALIZED_RANKING.</p> </note><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/personalize-runtime-2018-05-22/GetPersonalizedRanking">AWS
* API Reference</a></p>
*/
virtual Model::GetPersonalizedRankingOutcome GetPersonalizedRanking(const Model::GetPersonalizedRankingRequest& request) const;
/**
* <p>Re-ranks a list of recommended items for the given user. The first item in
* the list is deemed the most likely item to be of interest to the user.</p>
* <note> <p>The solution backing the campaign must have been created using a
* recipe of type PERSONALIZED_RANKING.</p> </note><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/personalize-runtime-2018-05-22/GetPersonalizedRanking">AWS
* API Reference</a></p>
*
* returns a future to the operation so that it can be executed in parallel to other requests.
*/
virtual Model::GetPersonalizedRankingOutcomeCallable GetPersonalizedRankingCallable(const Model::GetPersonalizedRankingRequest& request) const;
/**
* <p>Re-ranks a list of recommended items for the given user. The first item in
* the list is deemed the most likely item to be of interest to the user.</p>
* <note> <p>The solution backing the campaign must have been created using a
* recipe of type PERSONALIZED_RANKING.</p> </note><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/personalize-runtime-2018-05-22/GetPersonalizedRanking">AWS
* API Reference</a></p>
*
* Queues the request into a thread executor and triggers associated callback when operation has finished.
*/
virtual void GetPersonalizedRankingAsync(const Model::GetPersonalizedRankingRequest& request, const GetPersonalizedRankingResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const;
/**
* <p>Returns a list of recommended items. The required input depends on the recipe
* type used to create the solution backing the campaign, as follows:</p> <ul> <li>
* <p>RELATED_ITEMS - <code>itemId</code> required, <code>userId</code> not
* used</p> </li> <li> <p>USER_PERSONALIZATION - <code>itemId</code> optional,
* <code>userId</code> required</p> </li> </ul> <note> <p>Campaigns that are backed
* by a solution created using a recipe of type PERSONALIZED_RANKING use the
* API.</p> </note><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/personalize-runtime-2018-05-22/GetRecommendations">AWS
* API Reference</a></p>
*/
virtual Model::GetRecommendationsOutcome GetRecommendations(const Model::GetRecommendationsRequest& request) const;
/**
* <p>Returns a list of recommended items. The required input depends on the recipe
* type used to create the solution backing the campaign, as follows:</p> <ul> <li>
* <p>RELATED_ITEMS - <code>itemId</code> required, <code>userId</code> not
* used</p> </li> <li> <p>USER_PERSONALIZATION - <code>itemId</code> optional,
* <code>userId</code> required</p> </li> </ul> <note> <p>Campaigns that are backed
* by a solution created using a recipe of type PERSONALIZED_RANKING use the
* API.</p> </note><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/personalize-runtime-2018-05-22/GetRecommendations">AWS
* API Reference</a></p>
*
* returns a future to the operation so that it can be executed in parallel to other requests.
*/
virtual Model::GetRecommendationsOutcomeCallable GetRecommendationsCallable(const Model::GetRecommendationsRequest& request) const;
/**
* <p>Returns a list of recommended items. The required input depends on the recipe
* type used to create the solution backing the campaign, as follows:</p> <ul> <li>
* <p>RELATED_ITEMS - <code>itemId</code> required, <code>userId</code> not
* used</p> </li> <li> <p>USER_PERSONALIZATION - <code>itemId</code> optional,
* <code>userId</code> required</p> </li> </ul> <note> <p>Campaigns that are backed
* by a solution created using a recipe of type PERSONALIZED_RANKING use the
* API.</p> </note><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/personalize-runtime-2018-05-22/GetRecommendations">AWS
* API Reference</a></p>
*
* Queues the request into a thread executor and triggers associated callback when operation has finished.
*/
virtual void GetRecommendationsAsync(const Model::GetRecommendationsRequest& request, const GetRecommendationsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const;
void OverrideEndpoint(const Aws::String& endpoint);
private:
void init(const Aws::Client::ClientConfiguration& clientConfiguration);
void GetPersonalizedRankingAsyncHelper(const Model::GetPersonalizedRankingRequest& request, const GetPersonalizedRankingResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const;
void GetRecommendationsAsyncHelper(const Model::GetRecommendationsRequest& request, const GetRecommendationsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const;
Aws::String m_uri;
Aws::String m_configScheme;
std::shared_ptr<Aws::Utils::Threading::Executor> m_executor;
};
} // namespace PersonalizeRuntime
} // namespace Aws
| 51.862069 | 265 | 0.714476 | [
"model"
] |
d0c8baaea91a6c5c194de23403cc0a465d658462 | 25,282 | c | C | svn-old/btmux/tags/0.6-rc3/src/create.c | murrayma/btmux | 3519fdbfb9d5d27b4ce8e46ee16796961f1a0bfa | [
"ClArtistic",
"Naumen",
"Condor-1.1",
"MS-PL"
] | 1 | 2020-07-09T17:37:42.000Z | 2020-07-09T17:37:42.000Z | svn-old/btmux/tags/0.6-rc3/src/create.c | murrayma/btmux | 3519fdbfb9d5d27b4ce8e46ee16796961f1a0bfa | [
"ClArtistic",
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | svn-old/btmux/tags/0.6-rc3/src/create.c | murrayma/btmux | 3519fdbfb9d5d27b4ce8e46ee16796961f1a0bfa | [
"ClArtistic",
"Naumen",
"Condor-1.1",
"MS-PL"
] | 1 | 2020-11-07T00:02:47.000Z | 2020-11-07T00:02:47.000Z |
/*
* create.c -- Commands that create new objects
*/
/*
* $Id: create.c,v 1.2 2005/08/08 09:43:06 murrayma Exp $
*/
#include "copyright.h"
#include "config.h"
#include "mudconf.h"
#include "config.h"
#include "db.h"
#include "interface.h"
#include "externs.h"
#include "match.h"
#include "command.h"
#include "alloc.h"
#include "attrs.h"
#include "powers.h"
/*
* ---------------------------------------------------------------------------
* * parse_linkable_room: Get a location to link to.
*/
static dbref parse_linkable_room(player, room_name)
dbref player;
char *room_name;
{
dbref room;
init_match(player, room_name, NOTYPE);
match_everything(MAT_NO_EXITS | MAT_NUMERIC | MAT_HOME);
room = match_result();
/*
* HOME is always linkable
*/
if (room == HOME)
return HOME;
/*
* Make sure we can link to it
*/
if (!Good_obj(room)) {
notify_quiet(player, "That's not a valid object.");
return NOTHING;
} else if (!Has_contents(room) || !Linkable(player, room)) {
notify_quiet(player, "You can't link to that.");
return NOTHING;
} else {
return room;
}
}
/*
* ---------------------------------------------------------------------------
* * open_exit, do_open: Open a new exit and optionally link it somewhere.
*/
static void open_exit(player, loc, direction, linkto)
dbref player, loc;
char *direction, *linkto;
{
dbref exit;
if (!Good_obj(loc))
return;
if (!direction || !*direction) {
notify_quiet(player, "Open where?");
return;
} else if (!controls(player, loc)) {
notify_quiet(player, "Permission denied.");
return;
}
exit = create_obj(player, TYPE_EXIT, direction, 0);
if (exit == NOTHING)
return;
/*
* Initialize everything and link it in.
*/
s_Exits(exit, loc);
s_Next(exit, Exits(loc));
s_Exits(loc, exit);
/*
* and we're done
*/
notify_quiet(player, "Opened.");
/*
* See if we should do a link
*/
if (!linkto || !*linkto)
return;
loc = parse_linkable_room(player, linkto);
if (loc != NOTHING) {
/*
* Make sure the player passes the link lock
*/
if (!could_doit(player, loc, A_LLINK)) {
notify_quiet(player, "You can't link to there.");
return;
}
/*
* Link it if the player can pay for it
*/
if (!payfor(player, mudconf.linkcost)) {
notify_quiet(player,
tprintf("You don't have enough %s to link.",
mudconf.many_coins));
} else {
s_Location(exit, loc);
notify_quiet(player, "Linked.");
}
}
}
void do_open(player, cause, key, direction, links, nlinks)
dbref player, cause;
int key, nlinks;
char *direction, *links[];
{
dbref loc, destnum;
char *dest;
/*
* Create the exit and link to the destination, if there is one
*/
if (nlinks >= 1)
dest = links[0];
else
dest = NULL;
if (key == OPEN_INVENTORY)
loc = player;
else
loc = Location(player);
open_exit(player, loc, direction, dest);
/*
* Open the back link if we can
*/
if (nlinks >= 2) {
destnum = parse_linkable_room(player, dest);
if (destnum != NOTHING) {
open_exit(player, destnum, links[1], tprintf("%d", loc));
}
}
}
/*
* ---------------------------------------------------------------------------
* * link_exit, do_link: Set destination(exits), dropto(rooms) or
* * home(player,thing)
*/
static void link_exit(player, exit, dest)
dbref player, exit, dest;
{
int cost, quot;
/*
* Make sure we can link there
*/
if ((dest != HOME) && ((!controls(player, dest) && !Link_ok(dest)) ||
!could_doit(player, dest, A_LLINK))) {
notify_quiet(player, "Permission denied.");
return;
}
/*
* Exit must be unlinked or controlled by you
*/
if ((Location(exit) != NOTHING) && !controls(player, exit)) {
notify_quiet(player, "Permission denied.");
return;
}
/*
* handle costs
*/
cost = mudconf.linkcost;
quot = 0;
if (Owner(exit) != Owner(player)) {
cost += mudconf.opencost;
quot += mudconf.exit_quota;
}
if (!canpayfees(player, player, cost, quot))
return;
/*
* Pay the owner for his loss
*/
if (Owner(exit) != Owner(player)) {
giveto(Owner(exit), mudconf.opencost);
add_quota(Owner(exit), quot);
s_Owner(exit, Owner(player));
s_Flags(exit, (Flags(exit) & ~(INHERIT | WIZARD)) | HALT);
}
/*
* link has been validated and paid for, do it and tell the player
*/
s_Location(exit, dest);
if (!Quiet(player))
notify_quiet(player, "Linked.");
}
void do_link(player, cause, key, what, where)
dbref player, cause;
int key;
char *what, *where;
{
dbref thing, room;
char *buff;
/*
* Find the thing to link
*/
init_match(player, what, TYPE_EXIT);
match_everything(0);
thing = noisy_match_result();
if (thing == NOTHING)
return;
/*
* Allow unlink if where is not specified
*/
if (!where || !*where) {
do_unlink(player, cause, key, what);
return;
}
switch (Typeof(thing)) {
case TYPE_EXIT:
/*
* Set destination
*/
room = parse_linkable_room(player, where);
if (room != NOTHING)
link_exit(player, thing, room);
break;
case TYPE_PLAYER:
case TYPE_THING:
/*
* Set home
*/
if (!Controls(player, thing)) {
notify_quiet(player, "Permission denied.");
break;
}
init_match(player, where, NOTYPE);
match_everything(MAT_NO_EXITS);
room = noisy_match_result();
if (!Good_obj(room))
break;
if (!Has_contents(room)) {
notify_quiet(player, "Can't link to an exit.");
break;
}
if (!can_set_home(player, thing, room) ||
!could_doit(player, room, A_LLINK)) {
notify_quiet(player, "Permission denied.");
} else if (room == HOME) {
notify_quiet(player, "Can't set home to home.");
} else {
s_Home(thing, room);
if (!Quiet(player))
notify_quiet(player, "Home set.");
}
break;
case TYPE_ROOM:
/*
* Set dropto
*/
if (!Controls(player, thing)) {
notify_quiet(player, "Permission denied.");
break;
}
room = parse_linkable_room(player, where);
if (!(Good_obj(room) || (room == HOME)))
break;
if ((room != HOME) && !isRoom(room)) {
notify_quiet(player, "That is not a room!");
} else if ((room != HOME) && ((!controls(player, room) &&
!Link_ok(room)) ||
!could_doit(player, room, A_LLINK))) {
notify_quiet(player, "Permission denied.");
} else {
s_Dropto(thing, room);
if (!Quiet(player))
notify_quiet(player, "Dropto set.");
}
break;
case TYPE_GARBAGE:
notify_quiet(player, "Permission denied.");
break;
default:
STARTLOG(LOG_BUGS, "BUG", "OTYPE") {
buff = alloc_mbuf("do_link.LOG.badtype");
sprintf(buff, "Strange object type: object #%d = %d", thing,
Typeof(thing));
log_text(buff);
free_mbuf(buff);
ENDLOG;
}
}
}
/*
* ---------------------------------------------------------------------------
* * do_parent: Set an object's parent field.
*/
void do_parent(player, cause, key, tname, pname)
dbref player, cause;
int key;
char *tname, *pname;
{
dbref thing, parent, curr;
int lev;
/*
* get victim
*/
init_match(player, tname, NOTYPE);
match_everything(0);
thing = noisy_match_result();
if (thing == NOTHING)
return;
/*
* Make sure we can do it
*/
if (!Controls(player, thing)) {
notify_quiet(player, "Permission denied.");
return;
}
/*
* Find out what the new parent is
*/
if (*pname) {
init_match(player, pname, Typeof(thing));
match_everything(0);
parent = noisy_match_result();
if (parent == NOTHING)
return;
/*
* Make sure we have rights to set parent
*/
if (!Parentable(player, parent)) {
notify_quiet(player, "Permission denied.");
return;
}
/*
* Verify no recursive reference
*/
ITER_PARENTS(parent, curr, lev) {
if (curr == thing) {
notify_quiet(player,
"You can't have yourself as a parent!");
return;
}
}
} else {
parent = NOTHING;
}
s_Parent(thing, parent);
if (!Quiet(thing) && !Quiet(player)) {
if (parent == NOTHING)
notify_quiet(player, "Parent cleared.");
else
notify_quiet(player, "Parent set.");
}
}
/*
* ---------------------------------------------------------------------------
* * do_dig: Create a new room.
*/
void do_dig(player, cause, key, name, args, nargs)
dbref player, cause;
int key, nargs;
char *name, *args[];
{
dbref room;
char *buff;
/*
* we don't need to know player's location! hooray!
*/
if (!name || !*name) {
notify_quiet(player, "Dig what?");
return;
}
room = create_obj(player, TYPE_ROOM, name, 0);
if (room == NOTHING)
return;
notify(player, tprintf("%s created with room number %d.", name, room));
buff = alloc_sbuf("do_dig");
if ((nargs >= 1) && args[0] && *args[0]) {
sprintf(buff, "%d", room);
open_exit(player, Location(player), args[0], buff);
}
if ((nargs >= 2) && args[1] && *args[1]) {
sprintf(buff, "%d", Location(player));
open_exit(player, room, args[1], buff);
}
free_sbuf(buff);
if (key == DIG_TELEPORT)
(void) move_via_teleport(player, room, cause, 0);
}
/*
* ---------------------------------------------------------------------------
* * do_create: Make a new object.
*/
void do_create(dbref player, dbref cause, int key, char *name, char *coststr) {
dbref thing;
int cost;
char clearbuffer[MBUF_SIZE];
cost = atoi(coststr);
strip_ansi_r(clearbuffer, name, MBUF_SIZE);
if (!name || !*name || (strlen(clearbuffer) == 0)) {
notify_quiet(player, "Create what?");
return;
} else if (cost < 0) {
notify_quiet(player,
"You can't create an object for less than nothing!");
return;
}
thing = create_obj(player, TYPE_THING, name, cost);
if (thing == NOTHING)
return;
move_via_generic(thing, player, NOTHING, 0);
s_Home(thing, new_home(player));
if (!Quiet(player)) {
notify(player, tprintf("%s created as object #%d", Name(thing),
thing));
}
}
/*
* ---------------------------------------------------------------------------
* * do_clone: Create a copy of an object.
*/
void do_clone(player, cause, key, name, arg2)
dbref player, cause;
int key;
char *name, *arg2;
{
dbref clone, thing, new_owner, loc;
FLAG rmv_flags;
int cost;
if ((key & CLONE_INVENTORY) || !Has_location(player))
loc = player;
else
loc = Location(player);
if (!Good_obj(loc))
return;
init_match(player, name, NOTYPE);
match_everything(0);
thing = noisy_match_result();
if ((thing == NOTHING) || (thing == AMBIGUOUS))
return;
/*
* Let players clone things set VISUAL. It's easier than retyping in
* all that data
*/
if (!Examinable(player, thing)) {
notify_quiet(player, "Permission denied.");
return;
}
if (isPlayer(thing)) {
notify_quiet(player, "You cannot clone players!");
return;
}
/*
* You can only make a parent link to what you control
*/
if (!Controls(player, thing) && !Parent_ok(thing) &&
(key & CLONE_PARENT)) {
notify_quiet(player,
tprintf("You don't control %s, ignoring /parent.",
Name(thing)));
key &= ~CLONE_PARENT;
}
/*
* Determine the cost of cloning
*/
new_owner = (key & CLONE_PRESERVE) ? Owner(thing) : Owner(player);
if (key & CLONE_SET_COST) {
cost = atoi(arg2);
if (cost < mudconf.createmin)
cost = mudconf.createmin;
if (cost > mudconf.createmax)
cost = mudconf.createmax;
arg2 = NULL;
} else {
cost = 1;
switch (Typeof(thing)) {
case TYPE_THING:
cost =
OBJECT_DEPOSIT((mudconf.
clone_copy_cost) ? Pennies(thing) : 1);
break;
case TYPE_ROOM:
cost = mudconf.digcost;
break;
case TYPE_EXIT:
if (!Controls(player, loc)) {
notify_quiet(player, "Permission denied.");
return;
}
cost = mudconf.digcost;
break;
}
}
/*
* Go make the clone object
*/
if ((arg2 && *arg2) && ok_name(arg2))
clone = create_obj(new_owner, Typeof(thing), arg2, cost);
else
clone = create_obj(new_owner, Typeof(thing), Name(thing), cost);
if (clone == NOTHING)
return;
/*
* Wipe out any old attributes and copy in the new data
*/
atr_free(clone);
if (key & CLONE_PARENT)
s_Parent(clone, thing);
else
atr_cpy(player, clone, thing);
/*
* Reset the name, since we cleared the attributes
*/
if ((arg2 && *arg2) && ok_name(arg2))
s_Name(clone, arg2);
else
s_Name(clone, Name(thing));
/*
* Clear out problem flags from the original
*/
rmv_flags = WIZARD;
if (!(key & CLONE_INHERIT) || (!Inherits(player)))
rmv_flags |= INHERIT | IMMORTAL;
s_Flags(clone, Flags(thing) & ~rmv_flags);
/*
* Tell creator about it
*/
if (!Quiet(player)) {
if (arg2 && *arg2)
notify(player,
tprintf("%s cloned as %s, new copy is object #%d.",
Name(thing), arg2, clone));
else
notify(player, tprintf("%s cloned, new copy is object #%d.",
Name(thing), clone));
}
/*
* Put the new thing in its new home. Break any dropto or link, then
* * * * * * * try to re-establish it.
*/
switch (Typeof(thing)) {
case TYPE_THING:
s_Home(clone, clone_home(player, thing));
move_via_generic(clone, loc, player, 0);
break;
case TYPE_ROOM:
s_Dropto(clone, NOTHING);
if (Dropto(thing) != NOTHING)
link_exit(player, clone, Dropto(thing));
break;
case TYPE_EXIT:
s_Exits(loc, insert_first(Exits(loc), clone));
s_Exits(clone, loc);
s_Location(clone, NOTHING);
if (Location(thing) != NOTHING)
link_exit(player, clone, Location(thing));
break;
}
/*
* If same owner run ACLONE, else halt it. Also copy parent * if we
* * * * * * can
*/
if (new_owner == Owner(thing)) {
if (!(key & CLONE_PARENT))
s_Parent(clone, Parent(thing));
did_it(player, clone, 0, NULL, 0, NULL, A_ACLONE, (char **) NULL,
0);
} else {
if (!(key & CLONE_PARENT) && (Controls(player, thing) ||
Parent_ok(thing)))
s_Parent(clone, Parent(thing));
s_Halted(clone);
}
}
/*
* ---------------------------------------------------------------------------
* * do_pcreate: Create new players and robots.
*/
void do_pcreate(player, cause, key, name, pass)
dbref player, cause;
int key;
char *name, *pass;
{
int isrobot;
dbref newplayer;
isrobot = (key == PCRE_ROBOT) ? 1 : 0;
newplayer = create_player(name, pass, player, isrobot, 0);
if (newplayer == NOTHING) {
notify_quiet(player, tprintf("Failure creating '%s'", name));
return;
}
if (isrobot) {
move_object(newplayer, Location(player));
notify_quiet(player,
tprintf("New robot '%s' created with password '%s'", name,
pass));
notify_quiet(player, "Your robot has arrived.");
STARTLOG(LOG_PCREATES, "CRE", "ROBOT") {
log_name(newplayer);
log_text((char *) " created by ");
log_name(player);
ENDLOG;
}} else {
move_object(newplayer, mudconf.start_room);
notify_quiet(player,
tprintf("New player '%s' created with password '%s'", name,
pass));
STARTLOG(LOG_PCREATES | LOG_WIZARD, "WIZ", "PCREA") {
log_name(newplayer);
log_text((char *) " created by ");
log_name(player);
ENDLOG;
}}
}
/*
* ---------------------------------------------------------------------------
* * can_destroy_exit, can_destroy_player, do_destroy:
* * Destroy things.
*/
static int can_destroy_exit(player, exit)
dbref player, exit;
{
dbref loc;
loc = Exits(exit);
if ((loc != Location(player)) && (loc != player) && !Wizard(player)) {
notify_quiet(player, "You can not destroy exits in another room.");
return 0;
}
return 1;
}
/*
* ---------------------------------------------------------------------------
* * destroyable: Indicates if target of a @destroy is a 'special' object in
* * the database.
*/
static int destroyable(victim)
dbref victim;
{
if ((victim == mudconf.default_home) || (victim == mudconf.start_home)
|| (victim == mudconf.start_room) ||
(victim == mudconf.master_room) || (victim == (dbref) 0) ||
(God(victim)))
return 0;
return 1;
}
static int can_destroy_player(player, victim)
dbref player, victim;
{
if (!Wizard(player)) {
notify_quiet(player, "Sorry, no suicide allowed.");
return 0;
}
if (Wizard(victim)) {
notify_quiet(player, "Even you can't do that!");
return 0;
}
return 1;
}
void do_destroy(player, cause, key, what)
dbref player, cause;
int key;
char *what;
{
dbref thing;
/*
* You can destroy anything you control
*/
thing = match_controlled_quiet(player, what);
/*
* If you own a location, you can destroy its exits
*/
if ((thing == NOTHING) && controls(player, Location(player))) {
init_match(player, what, TYPE_EXIT);
match_exit();
thing = last_match_result();
}
/*
* You may destroy DESTROY_OK things in your inventory
*/
if (thing == NOTHING) {
init_match(player, what, TYPE_THING);
match_possession();
thing = last_match_result();
if ((thing != NOTHING) && !(isThing(thing) && Destroy_ok(thing))) {
thing = NOPERM;
}
}
/*
* Return an error if we didn't find anything to destroy
*/
if (match_status(player, thing) == NOTHING) {
return;
}
/*
* Check SAFE and DESTROY_OK flags
*/
if (Safe(thing, player) && !(key & DEST_OVERRIDE) && !(isThing(thing)
&& Destroy_ok(thing))) {
notify_quiet(player,
"Sorry, that object is protected. Use @destroy/override to destroy it.");
return;
}
/*
* Make sure we're not trying to destroy a special object
*/
if (!destroyable(thing)) {
notify_quiet(player, "You can't destroy that!");
return;
}
/*
* Go do it
*/
switch (Typeof(thing)) {
case TYPE_EXIT:
if (can_destroy_exit(player, thing)) {
if (Going(thing)) {
notify_quiet(player, "No sense beating a dead exit.");
} else {
if (Hardcode(thing)) {
DisposeSpecialObject(player, thing);
c_Hardcode(thing);
}
if (Destroy_ok(thing) || Destroy_ok(Owner(thing))) {
destroy_exit(thing);
} else {
notify(player,
"The exit shakes and begins to crumble.");
if (!Quiet(thing) && !Quiet(Owner(thing)))
notify_quiet(Owner(thing),
tprintf
("You will be rewarded shortly for %s(#%d).",
Name(thing), thing));
if ((Owner(thing) != player) && !Quiet(player)) {
notify_quiet(player,
tprintf("Destroyed. #%d's %s(#%d)",
Owner(thing), Name(thing), thing));
s_Going(thing);
}
}
}
}
break;
case TYPE_THING:
if (Going(thing)) {
notify_quiet(player, "No sense beating a dead object.");
} else {
if (Hardcode(thing)) {
DisposeSpecialObject(player, thing);
c_Hardcode(thing);
}
if (Destroy_ok(thing) || Destroy_ok(Owner(thing))) {
destroy_thing(thing);
} else {
notify(player, "The object shakes and begins to crumble.");
if (!Quiet(thing) && !Quiet(Owner(thing)))
notify_quiet(Owner(thing),
tprintf
("You will be rewarded shortly for %s(#%d).",
Name(thing), thing));
if ((Owner(thing) != player) && !Quiet(player))
notify_quiet(player, tprintf("Destroyed. %s's %s(#%d)",
Name(Owner(thing)), Name(thing), thing));
s_Going(thing);
}
}
break;
case TYPE_PLAYER:
if (can_destroy_player(player, thing)) {
if (Going(thing)) {
notify_quiet(player, "No sense beating a dead player.");
} else {
if (Hardcode(thing)) {
DisposeSpecialObject(player, thing);
c_Hardcode(thing);
}
if (Destroy_ok(thing)) {
atr_add_raw(thing, A_DESTROYER, tprintf("%d", player));
destroy_player(thing);
} else {
notify(player,
"The player shakes and begins to crumble.");
s_Going(thing);
atr_add_raw(thing, A_DESTROYER, tprintf("%d", player));
}
}
}
break;
case TYPE_ROOM:
if (Going(thing)) {
notify_quiet(player, "No sense beating a dead room.");
} else {
if (Destroy_ok(thing) || Destroy_ok(Owner(thing))) {
empty_obj(thing);
destroy_obj(NOTHING, thing);
} else {
notify_all(thing, player,
"The room shakes and begins to crumble.");
if (!Quiet(thing) && !Quiet(Owner(thing)))
notify_quiet(Owner(thing),
tprintf
("You will be rewarded shortly for %s(#%d).",
Name(thing), thing));
if ((Owner(thing) != player) && !Quiet(player))
notify_quiet(player, tprintf("Destroyed. %s's %s(#%d)",
Name(Owner(thing)), Name(thing), thing));
s_Going(thing);
}
}
}
}
| 27.480435 | 90 | 0.479551 | [
"object"
] |
d0c99221387eb3b820441bfb43cdf9fe2bcd6ccd | 3,093 | c | C | solid/src/base/generic/fpe.c | kant/ocean-tensor-package | fb3fcff8bba7f4ef6cd8b8d02f0e1be1258da02d | [
"Apache-2.0"
] | 27 | 2018-08-16T21:32:49.000Z | 2021-11-30T10:31:08.000Z | solid/src/base/generic/fpe.c | kant/ocean-tensor-package | fb3fcff8bba7f4ef6cd8b8d02f0e1be1258da02d | [
"Apache-2.0"
] | null | null | null | solid/src/base/generic/fpe.c | kant/ocean-tensor-package | fb3fcff8bba7f4ef6cd8b8d02f0e1be1258da02d | [
"Apache-2.0"
] | 13 | 2018-08-17T17:33:16.000Z | 2021-11-30T10:31:09.000Z | /* ------------------------------------------------------------------------ */
/* Copyright 2018, IBM Corp. */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */
/* See the License for the specific language governing permissions and */
/* limitations under the License. */
/* ------------------------------------------------------------------------ */
#include "solid/base/generic/fpe.h"
/* -------------------------------------------------------------------- */
int solid_fpe_get_status(void)
/* -------------------------------------------------------------------- */
{ int status;
int result = 0;
/* Get the exception status */
status = fetestexcept(FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW | FE_INEXACT | FE_INVALID);
if (status & FE_DIVBYZERO) result |= SD_FPE_DIVIDE_BY_ZERO;
if (status & FE_OVERFLOW ) result |= SD_FPE_OVERFLOW;
if (status & FE_UNDERFLOW) result |= SD_FPE_UNDERFLOW;
if (status & FE_INEXACT ) result |= SD_FPE_INEXACT;
if (status & FE_INVALID ) result |= SD_FPE_INVALID;
return result;
}
/* -------------------------------------------------------------------- */
int solid_fpe_test_status(int exception)
/* -------------------------------------------------------------------- */
{ int status;
/* Get the status */
status = solid_fpe_get_status();
return ((status & exception) == exception) ? 1 : 0;
}
/* -------------------------------------------------------------------- */
void solid_fpe_clear(void)
/* -------------------------------------------------------------------- */
{
if (solid_fpe_get_status() != 0)
{ feclearexcept(FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW | FE_INEXACT | FE_INVALID);
}
}
/* -------------------------------------------------------------------- */
void solid_fpe_raise(int exception)
/* -------------------------------------------------------------------- */
{ int flags = 0;
if (exception & SD_FPE_DIVIDE_BY_ZERO) flags |= FE_DIVBYZERO;
if (exception & SD_FPE_OVERFLOW ) flags |= FE_OVERFLOW;
if (exception & SD_FPE_UNDERFLOW ) flags |= FE_UNDERFLOW;
if (exception & SD_FPE_INEXACT ) flags |= FE_INEXACT;
if (exception & SD_FPE_INVALID ) flags |= FE_INVALID;
if (flags != 0) feraiseexcept(flags);
}
| 41.797297 | 94 | 0.430003 | [
"solid"
] |
fd9b8e41c439230a7d7c166be0502e3c84bdf2af | 618 | h | C | VideoRender/include/videorender/RenderToDisplay.h | Ingerdev/TinyFaces_Tensorflow_Cpp | c473c40989568abdedcc4739d9730e73fffa4578 | [
"MIT"
] | 1 | 2020-04-08T00:18:55.000Z | 2020-04-08T00:18:55.000Z | VideoRender/include/videorender/RenderToDisplay.h | Ingerdev/TinyFaces_Tensorflow_Cpp | c473c40989568abdedcc4739d9730e73fffa4578 | [
"MIT"
] | 1 | 2018-12-24T08:14:32.000Z | 2018-12-24T08:14:32.000Z | VideoRender/include/videorender/RenderToDisplay.h | Ingerdev/TinyFaces_Tensorflow_Cpp | c473c40989568abdedcc4739d9730e73fffa4578 | [
"MIT"
] | 2 | 2019-12-11T09:08:44.000Z | 2020-08-25T09:05:04.000Z | #pragma once
#pragma warning(push, 0)
#include <memory>
#include <opencv2/core/mat.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc.hpp>
#pragma warning(pop)
#include "Prediction.h"
namespace videorender
{
class RenderToDisplay
{
public:
RenderToDisplay();
void process_faces(const std::vector<Prediction>& faces);
void process_frame(const cv::Mat& frame_image) const;
private:
void draw_face_rect(cv::Mat& frame_image, const Prediction& prediction) const;
std::vector<Prediction> predictions_;
const std::string window_name_ = "render_window";
};
}
| 23.769231 | 81 | 0.720065 | [
"vector"
] |
fda0ea24524b9c291412c8572d2478ab2e3db1cd | 2,963 | h | C | ArrtModel/ViewModel/ModelEditor/MaterialEditor/MaterialModel.h | AleksandarTomicMs2/azure-remote-rendering-asset-tool | c3962231e02af6ff90c2867f51e7a3b20af8c592 | [
"MIT"
] | 42 | 2020-06-12T19:10:52.000Z | 2022-03-04T02:20:59.000Z | ArrtModel/ViewModel/ModelEditor/MaterialEditor/MaterialModel.h | AleksandarTomicMs2/azure-remote-rendering-asset-tool | c3962231e02af6ff90c2867f51e7a3b20af8c592 | [
"MIT"
] | 91 | 2020-06-12T12:10:46.000Z | 2022-03-02T13:46:00.000Z | ArrtModel/ViewModel/ModelEditor/MaterialEditor/MaterialModel.h | AleksandarTomicMs2/azure-remote-rendering-asset-tool | c3962231e02af6ff90c2867f51e7a3b20af8c592 | [
"MIT"
] | 10 | 2020-07-29T21:19:14.000Z | 2021-09-22T11:48:27.000Z | #pragma once
#include <Model/IncludesAzureRemoteRendering.h>
#include <QObject>
class ArrSessionManager;
class ParameterModel;
// Qt model class for a material. It is used to wrap all of the properties in an ARR material
// with Qt properties (Q_PROPERTY) so that Qt reflection can be used to bind them in ParameterModels
// (see subclass MaterialPBR)
class MaterialModel : public QObject
{
public:
MaterialModel(ArrSessionManager* sessionManager, QObject* parent = nullptr)
: QObject(parent)
, m_sessionManager(sessionManager)
{
}
const QList<ParameterModel*>& getControls() const { return m_controls; }
void setMaterial(const RR::ApiHandle<RR::Material>& material) { m_material = material; }
protected:
QList<ParameterModel*> m_controls;
RR::ApiHandle<RR::Material> m_material = {};
ArrSessionManager* const m_sessionManager;
};
// macro used to create a Q_PROPERTY around a
// getMaterial()->Get[PropertyName]() and getMaterial()->Set[PropertyName]()
#define ARRT_PROPERTY(t, name) \
Q_PROPERTY(t name READ get##name WRITE set##name) \
t get##name() const \
{ \
if (const auto m = getMaterial()) \
{ \
return static_cast<t>(m->Get##name()); \
} \
return {}; \
} \
bool set##name(const t& value) \
{ \
if (auto m = getMaterial()) \
{ \
try \
{ \
m->Set##name(static_cast<decltype(m->Get##name())>(value)); \
} \
catch (...) \
{ \
return false; \
} \
return true; \
} \
return false; \
}
| 51.982456 | 100 | 0.335133 | [
"model"
] |
fdb336279fc270017c1ed20ecc032fdd3e5b4733 | 7,939 | c | C | Source/Lib/Codec/EbCabacContextModel.c | vaporwavy/SVT-HEVC | 4ec79463e8fb5065036bf3adb27f7e199d168744 | [
"BSD-2-Clause-Patent"
] | null | null | null | Source/Lib/Codec/EbCabacContextModel.c | vaporwavy/SVT-HEVC | 4ec79463e8fb5065036bf3adb27f7e199d168744 | [
"BSD-2-Clause-Patent"
] | 1 | 2019-01-11T01:07:59.000Z | 2019-01-11T01:07:59.000Z | Source/Lib/Codec/EbCabacContextModel.c | vaporwavy/SVT-HEVC | 4ec79463e8fb5065036bf3adb27f7e199d168744 | [
"BSD-2-Clause-Patent"
] | 1 | 2019-01-24T06:39:28.000Z | 2019-01-24T06:39:28.000Z | /*
* Copyright(c) 2018 Intel Corporation
* SPDX - License - Identifier: BSD - 2 - Clause - Patent
*/
#include "EbUtility.h"
#include "EbCabacContextModel.h"
#include "EbDefinitions.h"
/*****************************
* Context Model Tables for initial probabilities (slope)
*****************************/
static const EB_S16 cabacInitialProbabilityTableI[] = {
//splitFlag
139, 141, 157,
//skipFlag
CNU, CNU, CNU,
//mergeFlag
CNU,
//mergeIdx
CNU,
//mvpIdx
CNU, CNU,
//partSize
184, CNU, CNU, CNU,
//predMode
CNU,
//intraLumaMode
184,
//intraChromaMode
63, 139,
//deltaQp
154, 154, 154,
//interDir
CNU, CNU, CNU, CNU, CNU,
//refPic
CNU, CNU,
//mvdInit
CNU, CNU,
//cbf
111, 141, CNU, CNU, CNU, 94, 138, 182, CNU, CNU,
//rootCbf
CNU,
//transSubDiv
153, 138, 138,
//lastSigX
110, 110, 124, 125, 140, 153, 125, 127, 140, 109, 111, 143, 127, 111, 79,
108, 123, 63, CNU, CNU, CNU, CNU, CNU, CNU, CNU, CNU, CNU, CNU, CNU, CNU,
//lastSigY
110, 110, 124, 125, 140, 153, 125, 127, 140, 109, 111, 143, 127, 111, 79,
108, 123, 63, CNU, CNU, CNU, CNU, CNU, CNU, CNU, CNU, CNU, CNU, CNU, CNU,
//sigFlag
111, 111, 125, 110, 110, 94, 124, 108, 124, 107, 125, 141, 179, 153, 125,
107, 125, 141, 179, 153, 125, 107, 125, 141, 179, 153, 125, 140, 139, 182,
182, 152, 136, 152, 136, 153, 136, 139, 111, 136, 139, 111,
//coeffGroupSigFlag
91, 171, 134, 141,
//greaterThanOne
140, 92, 137, 138, 140, 152, 138, 139, 153, 74, 149, 92,
139, 107, 122, 152, 140, 179, 166, 182, 140, 227, 122, 197,
//greaterThanTwo
138, 153, 136, 167, 152, 152,
//alfCtrlFlag
200,
//alfFlag
153,
//alfUvlc
140, 154,
//alfSvlc
187, 154, 159,
// sao merge flag
153,
//saoTypeIndex
200,
//cuAmp
CNU
};
static const EB_S16 cabacInitialProbabilityTableP[] = {
//splitFlag
107, 139, 126,
//skipFlag
197, 185, 201,
//mergeFlag
110,
//mergeIdx
122,
//mvpIdx
168, CNU,
//partSize
154, 139, CNU, CNU,
//predMode
149,
//intraLumaMode
154,
//intraChromaMode
152, 139,
//deltaQp
154, 154, 154,
//interDir
95, 79, 63, 31, 31,
//refPic
153, 153,
//mvdInit
140, 198,
//cbf
153, 111, CNU, CNU, CNU, 149, 107, 167, CNU, CNU,
//rootCbf
79,
//transSubDiv
124, 138, 94,
//lastSigX
125, 110, 94, 110, 95, 79, 125, 111, 110, 78, 110, 111, 111, 95, 94,
108, 123, 108, CNU, CNU, CNU, CNU, CNU, CNU, CNU, CNU, CNU, CNU, CNU, CNU,
//lastSigY
125, 110, 94, 110, 95, 79, 125, 111, 110, 78, 110, 111, 111, 95, 94,
108, 123, 108, CNU, CNU, CNU, CNU, CNU, CNU, CNU, CNU, CNU, CNU, CNU, CNU,
//sigFlag
155, 154, 139, 153, 139, 123, 123, 63, 153, 166, 183, 140, 136, 153, 154,
166, 183, 140, 136, 153, 154, 166, 183, 140, 136, 153, 154, 170, 153, 123,
123, 107, 121, 107, 121, 167, 151, 183, 140, 151, 183, 140,
//coeffGroupSigFlag
121, 140, 61, 154,
//greaterThanOne
154, 196, 196, 167, 154, 152, 167, 182, 182, 134, 149, 136,
153, 121, 136, 137, 169, 194, 166, 167, 154, 167, 137, 182,
//greaterThanTwo
107, 167, 91, 122, 107, 167,
//alfCtrlFlag
139,
//alfFlag
153,
//alfUvlc
154, 154,
//alfSvlc
141, 154, 189,
// sao merge flag
153,
//saoTypeIndex
185,
//cuAmp
154
};
static const EB_S16 cabacInitialProbabilityTableB[] = {
//splitFlag
107, 139, 126,
//skipFlag
197, 185, 201,
//mergeFlag
154,
//mergeIdx
137,
//mvpIdx
168, CNU,
//partSize
154, 139, CNU, CNU,
//predMode
134,
//intraLumaMode
183,
//intraChromaMode
152, 139,
//deltaQp
154, 154, 154,
//interDir
95, 79, 63, 31, 31,
//refPic
153, 153,
//mvdInit
169, 198,
//cbf
153, 111, CNU, CNU, CNU, 149, 92, 167, CNU, CNU,
//rootCbf
79,
//transSubDiv
224, 167, 122,
//lastSigX
125, 110, 124, 110, 95, 94, 125, 111, 111, 79, 125, 126, 111, 111, 79,
108, 123, 93, CNU, CNU, CNU, CNU, CNU, CNU, CNU, CNU, CNU, CNU, CNU, CNU,
//lastSigY
125, 110, 124, 110, 95, 94, 125, 111, 111, 79, 125, 126, 111, 111, 79,
108, 123, 93, CNU, CNU, CNU, CNU, CNU, CNU, CNU, CNU, CNU, CNU, CNU, CNU,
//sigFlag
170, 154, 139, 153, 139, 123, 123, 63, 124, 166, 183, 140, 136, 153, 154,
166, 183, 140, 136, 153, 154, 166, 183, 140, 136, 153, 154, 170, 153, 138,
138, 122, 121, 122, 121, 167, 151, 183, 140, 151, 183, 140,
//coeffGroupSigFlag
121, 140, 61, 154,
//greaterThanOne
154, 196, 167, 167, 154, 152, 167, 182, 182, 134, 149, 136,
153, 121, 136, 122, 169, 208, 166, 167, 154, 152, 167, 182,
//greaterThanTwo
107, 167, 91, 107, 107, 167,
//alfCtrlFlag
169,
//alfFlag
153,
//alfUvlc
154, 154,
//alfSvlc
141, 154, 159,
// sao merge flag
153,
//saoTypeIndex
160,
//cuAmp
154
};
EB_ERRORTYPE EncodeCabacContextModelCtor(
ContextModelEncContext_t *cabacContextModelArray)
{
EB_U32 modelIndex;
EB_U32 sliceIdx;
EB_S32 qpIndex;
EB_U32 bufferOffset1;
EB_U32 bufferOffset2;
EB_S32 initialProbState;
EB_S32 initialProbSlope;
EB_S32 initialProbOffset;
EB_U32 mostProbSymbol;
EB_ContextModel *contextModelPtr;
EB_ContextModel tempContextModel;
const EB_S16 *cabacInitialProbabilityTable;
contextModelPtr = (EB_ContextModel*)cabacContextModelArray;
// Loop over all slice types
for(sliceIdx = 0; sliceIdx < TOTAL_NUMBER_OF_SLICE_TYPES; sliceIdx++) {
cabacInitialProbabilityTable =
(sliceIdx == EB_I_PICTURE) ? cabacInitialProbabilityTableI :
(sliceIdx == EB_P_PICTURE) ? cabacInitialProbabilityTableP :
cabacInitialProbabilityTableB;
bufferOffset1 = sliceIdx * TOTAL_NUMBER_OF_QP_VALUES * MAX_SIZE_OF_CABAC_CONTEXT_MODELS;
// Loop over all Qps
for(qpIndex = 0; qpIndex < TOTAL_NUMBER_OF_QP_VALUES; qpIndex++) {
bufferOffset2 = qpIndex * MAX_SIZE_OF_CABAC_CONTEXT_MODELS;
// Loop over all cabac context models
for(modelIndex = 0; modelIndex < TOTAL_NUMBER_OF_CABAC_CONTEXT_MODELS; modelIndex++) {
initialProbSlope = (EB_S32)((cabacInitialProbabilityTable[modelIndex] >> 4)*5 -45);
initialProbOffset = (EB_S32)(((cabacInitialProbabilityTable[modelIndex] & 15)<<3) -16);
initialProbState = CLIP3(1, 126, ( ( initialProbSlope * qpIndex ) >> 4 ) + initialProbOffset );
mostProbSymbol = (initialProbState >=64)? 1: 0;
tempContextModel = mostProbSymbol ? initialProbState - 64 : 63 - initialProbState;
contextModelPtr[modelIndex + bufferOffset1 + bufferOffset2] = (tempContextModel<<1) + mostProbSymbol;
}
// Initialise junkpad values to zero
// *Note - this code goes out of the array boundary
//EB_MEMSET(&contextModelPtr[TOTAL_NUMBER_OF_CABAC_CONTEXT_MODELS+bufferOffset1 + bufferOffset2], 0, NUMBER_OF_PAD_VALUES_IN_CONTEXT_MODELS*sizeof(EB_ContextModel));
}
}
return EB_ErrorNone;
}
| 30.186312 | 177 | 0.541126 | [
"model"
] |
fdbf0dd08fa5be3ee304efeff60b5ec009bcee9e | 111,611 | c | C | src/vnet/srv6/sr_policy_rewrite.c | xerothermic/vpp | 25a52a2c9c3e77acaf06a68a98be46fae254083d | [
"Apache-2.0"
] | null | null | null | src/vnet/srv6/sr_policy_rewrite.c | xerothermic/vpp | 25a52a2c9c3e77acaf06a68a98be46fae254083d | [
"Apache-2.0"
] | 1 | 2022-03-18T17:20:54.000Z | 2022-03-18T17:20:54.000Z | src/vnet/srv6/sr_policy_rewrite.c | xerothermic/vpp | 25a52a2c9c3e77acaf06a68a98be46fae254083d | [
"Apache-2.0"
] | null | null | null | /*
* sr_policy_rewrite.c: ipv6 sr policy creation
*
* Copyright (c) 2016 Cisco 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.
*/
/**
* @file
* @brief SR policy creation and application
*
* Create an SR policy.
* An SR policy can be either of 'default' type or 'spray' type
* An SR policy has attached a list of SID lists.
* In case the SR policy is a default one it will load balance among them.
* An SR policy has associated a BindingSID.
* In case any packet arrives with IPv6 DA == BindingSID then the SR policy
* associated to such bindingSID will be applied to such packet.
*
* SR policies can be applied either by using IPv6 encapsulation or
* SRH insertion. Both methods can be found on this file.
*
* Traffic input usually is IPv6 packets. However it is possible to have
* IPv4 packets or L2 frames. (that are encapsulated into IPv6 with SRH)
*
* This file provides the appropriate VPP graph nodes to do any of these
* methods.
*
*/
#include <vlib/vlib.h>
#include <vnet/vnet.h>
#include <vnet/srv6/sr.h>
#include <vnet/ip/ip4_inlines.h>
#include <vnet/ip/ip6_inlines.h>
#include <vnet/srv6/sr_packet.h>
#include <vnet/fib/ip6_fib.h>
#include <vnet/dpo/dpo.h>
#include <vnet/dpo/replicate_dpo.h>
#include <vppinfra/error.h>
#include <vppinfra/elog.h>
/**
* @brief SR policy rewrite trace
*/
typedef struct
{
ip6_address_t src, dst;
} sr_policy_rewrite_trace_t;
/* Graph arcs */
#define foreach_sr_policy_rewrite_next \
_(IP6_LOOKUP, "ip6-lookup") \
_(ERROR, "error-drop")
typedef enum
{
#define _(s,n) SR_POLICY_REWRITE_NEXT_##s,
foreach_sr_policy_rewrite_next
#undef _
SR_POLICY_REWRITE_N_NEXT,
} sr_policy_rewrite_next_t;
/* SR rewrite errors */
#define foreach_sr_policy_rewrite_error \
_(INTERNAL_ERROR, "Segment Routing undefined error") \
_(BSID_ZERO, "BSID with SL = 0") \
_(COUNTER_TOTAL, "SR steered IPv6 packets") \
_(COUNTER_ENCAP, "SR: Encaps packets") \
_(COUNTER_INSERT, "SR: SRH inserted packets") \
_(COUNTER_BSID, "SR: BindingSID steered packets")
typedef enum
{
#define _(sym,str) SR_POLICY_REWRITE_ERROR_##sym,
foreach_sr_policy_rewrite_error
#undef _
SR_POLICY_REWRITE_N_ERROR,
} sr_policy_rewrite_error_t;
static char *sr_policy_rewrite_error_strings[] = {
#define _(sym,string) string,
foreach_sr_policy_rewrite_error
#undef _
};
/**
* @brief Dynamically added SR SL DPO type
*/
static dpo_type_t sr_pr_encaps_dpo_type;
static dpo_type_t sr_pr_insert_dpo_type;
static dpo_type_t sr_pr_bsid_encaps_dpo_type;
static dpo_type_t sr_pr_bsid_insert_dpo_type;
/**
* @brief IPv6 SA for encapsulated packets
*/
static ip6_address_t sr_pr_encaps_src;
static u8 sr_pr_encaps_hop_limit = IPv6_DEFAULT_HOP_LIMIT;
/******************* SR rewrite set encaps IPv6 source addr *******************/
/* Note: This is temporal. We don't know whether to follow this path or
take the ip address of a loopback interface or even the OIF */
void
sr_set_source (ip6_address_t * address)
{
clib_memcpy_fast (&sr_pr_encaps_src, address, sizeof (sr_pr_encaps_src));
}
ip6_address_t *
sr_get_encaps_source ()
{
return &sr_pr_encaps_src;
}
static clib_error_t *
set_sr_src_command_fn (vlib_main_t * vm, unformat_input_t * input,
vlib_cli_command_t * cmd)
{
while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
{
if (unformat
(input, "addr %U", unformat_ip6_address, &sr_pr_encaps_src))
return 0;
else
return clib_error_return (0, "No address specified");
}
return clib_error_return (0, "No address specified");
}
/* *INDENT-OFF* */
VLIB_CLI_COMMAND (set_sr_src_command, static) = {
.path = "set sr encaps source",
.short_help = "set sr encaps source addr <ip6_addr>",
.function = set_sr_src_command_fn,
};
/* *INDENT-ON* */
/******************** SR rewrite set encaps IPv6 hop-limit ********************/
void
sr_set_hop_limit (u8 hop_limit)
{
sr_pr_encaps_hop_limit = hop_limit;
}
u8
sr_get_hop_limit (void)
{
return sr_pr_encaps_hop_limit;
}
static clib_error_t *
set_sr_hop_limit_command_fn (vlib_main_t * vm, unformat_input_t * input,
vlib_cli_command_t * cmd)
{
int hop_limit = sr_get_hop_limit ();
if (unformat_check_input (input) == UNFORMAT_END_OF_INPUT)
return clib_error_return (0, "No value specified");
if (!unformat (input, "%d", &hop_limit))
return clib_error_return (0, "Invalid value");
if (hop_limit <= 0 || hop_limit > 255)
return clib_error_return (0, "Value out of range [1-255]");
sr_pr_encaps_hop_limit = (u8) hop_limit;
return 0;
}
/* *INDENT-OFF* */
VLIB_CLI_COMMAND (set_sr_hop_limit_command, static) = {
.path = "set sr encaps hop-limit",
.short_help = "set sr encaps hop-limit <value>",
.function = set_sr_hop_limit_command_fn,
};
/* *INDENT-ON* */
/*********************** SR rewrite string computation ************************/
/**
* @brief SR rewrite string computation for IPv6 encapsulation (inline)
*
* @param sl is a vector of IPv6 addresses composing the Segment List
*
* @return precomputed rewrite string for encapsulation
*/
static inline u8 *
compute_rewrite_encaps (ip6_address_t *sl, u8 type)
{
ip6_header_t *iph;
ip6_sr_header_t *srh;
ip6_address_t *addrp, *this_address;
u32 header_length = 0;
u8 *rs = NULL;
header_length = 0;
header_length += IPv6_DEFAULT_HEADER_LENGTH;
if (vec_len (sl) > 1)
{
header_length += sizeof (ip6_sr_header_t);
header_length += vec_len (sl) * sizeof (ip6_address_t);
}
vec_validate (rs, header_length - 1);
iph = (ip6_header_t *) rs;
iph->ip_version_traffic_class_and_flow_label =
clib_host_to_net_u32 (0 | ((6 & 0xF) << 28));
iph->src_address.as_u64[0] = sr_pr_encaps_src.as_u64[0];
iph->src_address.as_u64[1] = sr_pr_encaps_src.as_u64[1];
iph->payload_length = header_length - IPv6_DEFAULT_HEADER_LENGTH;
iph->protocol = IP_PROTOCOL_IPV6;
iph->hop_limit = sr_pr_encaps_hop_limit;
if (vec_len (sl) > 1)
{
srh = (ip6_sr_header_t *) (iph + 1);
iph->protocol = IP_PROTOCOL_IPV6_ROUTE;
srh->protocol = IP_PROTOCOL_IPV6;
srh->type = ROUTING_HEADER_TYPE_SR;
srh->segments_left = vec_len (sl) - 1;
srh->last_entry = vec_len (sl) - 1;
srh->length = ((sizeof (ip6_sr_header_t) +
(vec_len (sl) * sizeof (ip6_address_t))) / 8) - 1;
srh->flags = 0x00;
srh->tag = 0x0000;
addrp = srh->segments + vec_len (sl) - 1;
vec_foreach (this_address, sl)
{
clib_memcpy_fast (addrp->as_u8, this_address->as_u8,
sizeof (ip6_address_t));
addrp--;
}
}
iph->dst_address.as_u64[0] = sl->as_u64[0];
iph->dst_address.as_u64[1] = sl->as_u64[1];
return rs;
}
/**
* @brief SR rewrite string computation for SRH insertion (inline)
*
* @param sl is a vector of IPv6 addresses composing the Segment List
*
* @return precomputed rewrite string for SRH insertion
*/
static inline u8 *
compute_rewrite_insert (ip6_address_t *sl, u8 type)
{
ip6_sr_header_t *srh;
ip6_address_t *addrp, *this_address;
u32 header_length = 0;
u8 *rs = NULL;
header_length = 0;
header_length += sizeof (ip6_sr_header_t);
header_length += (vec_len (sl) + 1) * sizeof (ip6_address_t);
vec_validate (rs, header_length - 1);
srh = (ip6_sr_header_t *) rs;
srh->type = ROUTING_HEADER_TYPE_SR;
srh->segments_left = vec_len (sl);
srh->last_entry = vec_len (sl);
srh->length = ((sizeof (ip6_sr_header_t) +
((vec_len (sl) + 1) * sizeof (ip6_address_t))) / 8) - 1;
srh->flags = 0x00;
srh->tag = 0x0000;
addrp = srh->segments + vec_len (sl);
vec_foreach (this_address, sl)
{
clib_memcpy_fast (addrp->as_u8, this_address->as_u8,
sizeof (ip6_address_t));
addrp--;
}
return rs;
}
/**
* @brief SR rewrite string computation for SRH insertion with BSID (inline)
*
* @param sl is a vector of IPv6 addresses composing the Segment List
*
* @return precomputed rewrite string for SRH insertion with BSID
*/
static inline u8 *
compute_rewrite_bsid (ip6_address_t * sl)
{
ip6_sr_header_t *srh;
ip6_address_t *addrp, *this_address;
u32 header_length = 0;
u8 *rs = NULL;
header_length = 0;
header_length += sizeof (ip6_sr_header_t);
header_length += vec_len (sl) * sizeof (ip6_address_t);
vec_validate (rs, header_length - 1);
srh = (ip6_sr_header_t *) rs;
srh->type = ROUTING_HEADER_TYPE_SR;
srh->segments_left = vec_len (sl) - 1;
srh->last_entry = vec_len (sl) - 1;
srh->length = ((sizeof (ip6_sr_header_t) +
(vec_len (sl) * sizeof (ip6_address_t))) / 8) - 1;
srh->flags = 0x00;
srh->tag = 0x0000;
addrp = srh->segments + vec_len (sl) - 1;
vec_foreach (this_address, sl)
{
clib_memcpy_fast (addrp->as_u8, this_address->as_u8,
sizeof (ip6_address_t));
addrp--;
}
return rs;
}
/*************************** SR LB helper functions **************************/
/**
* @brief Creates a Segment List and adds it to an SR policy
*
* Creates a Segment List and adds it to the SR policy. Notice that the SL are
* not necessarily unique. Hence there might be two Segment List within the
* same SR Policy with exactly the same segments and same weight.
*
* @param sr_policy is the SR policy where the SL will be added
* @param sl is a vector of IPv6 addresses composing the Segment List
* @param weight is the weight of the SegmentList (for load-balancing purposes)
* @param is_encap represents the mode (SRH insertion vs Encapsulation)
*
* @return pointer to the just created segment list
*/
static inline ip6_sr_sl_t *
create_sl (ip6_sr_policy_t * sr_policy, ip6_address_t * sl, u32 weight,
u8 is_encap)
{
ip6_sr_main_t *sm = &sr_main;
ip6_sr_sl_t *segment_list;
sr_policy_fn_registration_t *plugin = 0;
pool_get (sm->sid_lists, segment_list);
clib_memset (segment_list, 0, sizeof (*segment_list));
vec_add1 (sr_policy->segments_lists, segment_list - sm->sid_lists);
/* Fill in segment list */
segment_list->weight =
(weight != (u32) ~ 0 ? weight : SR_SEGMENT_LIST_WEIGHT_DEFAULT);
segment_list->segments = vec_dup (sl);
segment_list->policy_type = sr_policy->type;
segment_list->egress_fib_table =
ip6_fib_index_from_table_id (sr_policy->fib_table);
if (is_encap)
{
segment_list->rewrite = compute_rewrite_encaps (sl, sr_policy->type);
segment_list->rewrite_bsid = segment_list->rewrite;
}
else
{
segment_list->rewrite = compute_rewrite_insert (sl, sr_policy->type);
segment_list->rewrite_bsid = compute_rewrite_bsid (sl);
}
if (sr_policy->plugin)
{
plugin =
pool_elt_at_index (sm->policy_plugin_functions,
sr_policy->plugin - SR_BEHAVIOR_LAST);
segment_list->plugin = sr_policy->plugin;
segment_list->plugin_mem = sr_policy->plugin_mem;
plugin->creation (sr_policy);
}
/* Create DPO */
dpo_reset (&segment_list->bsid_dpo);
dpo_reset (&segment_list->ip6_dpo);
dpo_reset (&segment_list->ip4_dpo);
if (is_encap)
{
if (!sr_policy->plugin)
{
dpo_set (&segment_list->ip6_dpo, sr_pr_encaps_dpo_type,
DPO_PROTO_IP6, segment_list - sm->sid_lists);
dpo_set (&segment_list->ip4_dpo, sr_pr_encaps_dpo_type,
DPO_PROTO_IP4, segment_list - sm->sid_lists);
dpo_set (&segment_list->bsid_dpo, sr_pr_bsid_encaps_dpo_type,
DPO_PROTO_IP6, segment_list - sm->sid_lists);
}
else
{
dpo_set (&segment_list->ip6_dpo, plugin->dpo, DPO_PROTO_IP6,
segment_list - sm->sid_lists);
dpo_set (&segment_list->ip4_dpo, plugin->dpo, DPO_PROTO_IP4,
segment_list - sm->sid_lists);
dpo_set (&segment_list->bsid_dpo, plugin->dpo, DPO_PROTO_IP6,
segment_list - sm->sid_lists);
}
}
else
{
if (!sr_policy->plugin)
{
dpo_set (&segment_list->ip6_dpo, sr_pr_insert_dpo_type,
DPO_PROTO_IP6, segment_list - sm->sid_lists);
dpo_set (&segment_list->bsid_dpo, sr_pr_bsid_insert_dpo_type,
DPO_PROTO_IP6, segment_list - sm->sid_lists);
}
else
{
dpo_set (&segment_list->ip6_dpo, plugin->dpo, DPO_PROTO_IP6,
segment_list - sm->sid_lists);
dpo_set (&segment_list->bsid_dpo, plugin->dpo, DPO_PROTO_IP6,
segment_list - sm->sid_lists);
}
}
return segment_list;
}
/**
* @brief Updates the Load-Balancer after an SR Policy change
*
* @param sr_policy is the modified SR Policy
*/
static inline void
update_lb (ip6_sr_policy_t * sr_policy)
{
flow_hash_config_t fhc;
u32 *sl_index;
ip6_sr_sl_t *segment_list;
ip6_sr_main_t *sm = &sr_main;
load_balance_path_t path;
path.path_index = FIB_NODE_INDEX_INVALID;
load_balance_path_t *ip4_path_vector = 0;
load_balance_path_t *ip6_path_vector = 0;
load_balance_path_t *b_path_vector = 0;
/* In case LB does not exist, create it */
if (!dpo_id_is_valid (&sr_policy->bsid_dpo))
{
fib_prefix_t pfx = {
.fp_proto = FIB_PROTOCOL_IP6,
.fp_len = 128,
.fp_addr = {
.ip6 = sr_policy->bsid,
}
};
/* Add FIB entry for BSID */
fhc = fib_table_get_flow_hash_config (sr_policy->fib_table,
FIB_PROTOCOL_IP6);
dpo_set (&sr_policy->bsid_dpo, DPO_LOAD_BALANCE, DPO_PROTO_IP6,
load_balance_create (0, DPO_PROTO_IP6, fhc));
dpo_set (&sr_policy->ip6_dpo, DPO_LOAD_BALANCE, DPO_PROTO_IP6,
load_balance_create (0, DPO_PROTO_IP6, fhc));
/* Update FIB entry's to point to the LB DPO in the main FIB and hidden one */
fib_table_entry_special_dpo_update (fib_table_find (FIB_PROTOCOL_IP6,
sr_policy->fib_table),
&pfx, FIB_SOURCE_SR,
FIB_ENTRY_FLAG_EXCLUSIVE,
&sr_policy->bsid_dpo);
fib_table_entry_special_dpo_update (sm->fib_table_ip6,
&pfx,
FIB_SOURCE_SR,
FIB_ENTRY_FLAG_EXCLUSIVE,
&sr_policy->ip6_dpo);
if (sr_policy->is_encap)
{
dpo_set (&sr_policy->ip4_dpo, DPO_LOAD_BALANCE, DPO_PROTO_IP4,
load_balance_create (0, DPO_PROTO_IP4, fhc));
fib_table_entry_special_dpo_update (sm->fib_table_ip4,
&pfx,
FIB_SOURCE_SR,
FIB_ENTRY_FLAG_EXCLUSIVE,
&sr_policy->ip4_dpo);
}
}
/* Create the LB path vector */
vec_foreach (sl_index, sr_policy->segments_lists)
{
segment_list = pool_elt_at_index (sm->sid_lists, *sl_index);
path.path_dpo = segment_list->bsid_dpo;
path.path_weight = segment_list->weight;
vec_add1 (b_path_vector, path);
path.path_dpo = segment_list->ip6_dpo;
vec_add1 (ip6_path_vector, path);
if (sr_policy->is_encap)
{
path.path_dpo = segment_list->ip4_dpo;
vec_add1 (ip4_path_vector, path);
}
}
/* Update LB multipath */
load_balance_multipath_update (&sr_policy->bsid_dpo, b_path_vector,
LOAD_BALANCE_FLAG_NONE);
load_balance_multipath_update (&sr_policy->ip6_dpo, ip6_path_vector,
LOAD_BALANCE_FLAG_NONE);
if (sr_policy->is_encap)
load_balance_multipath_update (&sr_policy->ip4_dpo, ip4_path_vector,
LOAD_BALANCE_FLAG_NONE);
/* Cleanup */
vec_free (b_path_vector);
vec_free (ip6_path_vector);
vec_free (ip4_path_vector);
}
/**
* @brief Updates the Replicate DPO after an SR Policy change
*
* @param sr_policy is the modified SR Policy (type spray)
*/
static inline void
update_replicate (ip6_sr_policy_t * sr_policy)
{
u32 *sl_index;
ip6_sr_sl_t *segment_list;
ip6_sr_main_t *sm = &sr_main;
load_balance_path_t path;
path.path_index = FIB_NODE_INDEX_INVALID;
load_balance_path_t *b_path_vector = 0;
load_balance_path_t *ip6_path_vector = 0;
load_balance_path_t *ip4_path_vector = 0;
/* In case LB does not exist, create it */
if (!dpo_id_is_valid (&sr_policy->bsid_dpo))
{
dpo_set (&sr_policy->bsid_dpo, DPO_REPLICATE,
DPO_PROTO_IP6, replicate_create (0, DPO_PROTO_IP6));
dpo_set (&sr_policy->ip6_dpo, DPO_REPLICATE,
DPO_PROTO_IP6, replicate_create (0, DPO_PROTO_IP6));
/* Update FIB entry's DPO to point to SR without LB */
fib_prefix_t pfx = {
.fp_proto = FIB_PROTOCOL_IP6,
.fp_len = 128,
.fp_addr = {
.ip6 = sr_policy->bsid,
}
};
fib_table_entry_special_dpo_update (fib_table_find (FIB_PROTOCOL_IP6,
sr_policy->fib_table),
&pfx, FIB_SOURCE_SR,
FIB_ENTRY_FLAG_EXCLUSIVE,
&sr_policy->bsid_dpo);
fib_table_entry_special_dpo_update (sm->fib_table_ip6,
&pfx,
FIB_SOURCE_SR,
FIB_ENTRY_FLAG_EXCLUSIVE,
&sr_policy->ip6_dpo);
if (sr_policy->is_encap)
{
dpo_set (&sr_policy->ip4_dpo, DPO_REPLICATE, DPO_PROTO_IP4,
replicate_create (0, DPO_PROTO_IP4));
fib_table_entry_special_dpo_update (sm->fib_table_ip4,
&pfx,
FIB_SOURCE_SR,
FIB_ENTRY_FLAG_EXCLUSIVE,
&sr_policy->ip4_dpo);
}
}
/* Create the replicate path vector */
path.path_weight = 1;
vec_foreach (sl_index, sr_policy->segments_lists)
{
segment_list = pool_elt_at_index (sm->sid_lists, *sl_index);
path.path_dpo = segment_list->bsid_dpo;
vec_add1 (b_path_vector, path);
path.path_dpo = segment_list->ip6_dpo;
vec_add1 (ip6_path_vector, path);
if (sr_policy->is_encap)
{
path.path_dpo = segment_list->ip4_dpo;
vec_add1 (ip4_path_vector, path);
}
}
/* Update replicate multipath */
replicate_multipath_update (&sr_policy->bsid_dpo, b_path_vector);
replicate_multipath_update (&sr_policy->ip6_dpo, ip6_path_vector);
if (sr_policy->is_encap)
replicate_multipath_update (&sr_policy->ip4_dpo, ip4_path_vector);
}
/******************************* SR rewrite API *******************************/
/* Three functions for handling sr policies:
* -> sr_policy_add
* -> sr_policy_del
* -> sr_policy_mod
* All of them are API. CLI function on sr_policy_command_fn */
/**
* @brief Create a new SR policy
*
* @param bsid is the bindingSID of the SR Policy
* @param segments is a vector of IPv6 address composing the segment list
* @param weight is the weight of the sid list. optional.
* @param behavior is the behavior of the SR policy. (default//spray)
* @param fib_table is the VRF where to install the FIB entry for the BSID
* @param is_encap (bool) whether SR policy should behave as Encap/SRH Insertion
*
* @return 0 if correct, else error
*/
int
sr_policy_add (ip6_address_t *bsid, ip6_address_t *segments, u32 weight,
u8 type, u32 fib_table, u8 is_encap, u16 plugin,
void *ls_plugin_mem)
{
ip6_sr_main_t *sm = &sr_main;
ip6_sr_policy_t *sr_policy = 0;
uword *p;
/* Search for existing keys (BSID) */
p = mhash_get (&sm->sr_policies_index_hash, bsid);
if (p)
{
/* Add SR policy that already exists; complain */
return -12;
}
/* Search collision in FIB entries */
/* Explanation: It might be possible that some other entity has already
* created a route for the BSID. This in theory is impossible, but in
* practise we could see it. Assert it and scream if needed */
fib_prefix_t pfx = {
.fp_proto = FIB_PROTOCOL_IP6,
.fp_len = 128,
.fp_addr = {
.ip6 = *bsid,
}
};
/* Lookup the FIB index associated to the table selected */
u32 fib_index = fib_table_find (FIB_PROTOCOL_IP6,
(fib_table != (u32) ~ 0 ? fib_table : 0));
if (fib_index == ~0)
return -13;
/* Lookup whether there exists an entry for the BSID */
fib_node_index_t fei = fib_table_lookup_exact_match (fib_index, &pfx);
if (FIB_NODE_INDEX_INVALID != fei)
return -12; //There is an entry for such lookup
/* Add an SR policy object */
pool_get (sm->sr_policies, sr_policy);
clib_memset (sr_policy, 0, sizeof (*sr_policy));
clib_memcpy_fast (&sr_policy->bsid, bsid, sizeof (ip6_address_t));
sr_policy->type = type;
sr_policy->fib_table = (fib_table != (u32) ~ 0 ? fib_table : 0); //Is default FIB 0 ?
sr_policy->is_encap = is_encap;
if (plugin)
{
sr_policy->plugin = plugin;
sr_policy->plugin_mem = ls_plugin_mem;
}
/* Copy the key */
mhash_set (&sm->sr_policies_index_hash, bsid, sr_policy - sm->sr_policies,
NULL);
/* Create a segment list and add the index to the SR policy */
create_sl (sr_policy, segments, weight, is_encap);
/* If FIB doesnt exist, create them */
if (sm->fib_table_ip6 == (u32) ~ 0)
{
sm->fib_table_ip6 = fib_table_create_and_lock (FIB_PROTOCOL_IP6,
FIB_SOURCE_SR,
"SRv6 steering of IP6 prefixes through BSIDs");
sm->fib_table_ip4 = fib_table_create_and_lock (FIB_PROTOCOL_IP6,
FIB_SOURCE_SR,
"SRv6 steering of IP4 prefixes through BSIDs");
}
/* Create IPv6 FIB for the BindingSID attached to the DPO of the only SL */
if (sr_policy->type == SR_POLICY_TYPE_DEFAULT)
update_lb (sr_policy);
else if (sr_policy->type == SR_POLICY_TYPE_SPRAY)
update_replicate (sr_policy);
return 0;
}
/**
* @brief Delete a SR policy
*
* @param bsid is the bindingSID of the SR Policy
* @param index is the index of the SR policy
*
* @return 0 if correct, else error
*/
int
sr_policy_del (ip6_address_t * bsid, u32 index)
{
ip6_sr_main_t *sm = &sr_main;
ip6_sr_policy_t *sr_policy = 0;
ip6_sr_sl_t *segment_list;
u32 *sl_index;
uword *p;
if (bsid)
{
p = mhash_get (&sm->sr_policies_index_hash, bsid);
if (p)
sr_policy = pool_elt_at_index (sm->sr_policies, p[0]);
else
return -1;
}
else
{
sr_policy = pool_elt_at_index (sm->sr_policies, index);
}
/* Remove BindingSID FIB entry */
fib_prefix_t pfx = {
.fp_proto = FIB_PROTOCOL_IP6,
.fp_len = 128,
.fp_addr = {
.ip6 = sr_policy->bsid,
}
,
};
fib_table_entry_special_remove (fib_table_find (FIB_PROTOCOL_IP6,
sr_policy->fib_table),
&pfx, FIB_SOURCE_SR);
fib_table_entry_special_remove (sm->fib_table_ip6, &pfx, FIB_SOURCE_SR);
if (sr_policy->is_encap)
fib_table_entry_special_remove (sm->fib_table_ip4, &pfx, FIB_SOURCE_SR);
if (dpo_id_is_valid (&sr_policy->bsid_dpo))
{
dpo_reset (&sr_policy->bsid_dpo);
dpo_reset (&sr_policy->ip4_dpo);
dpo_reset (&sr_policy->ip6_dpo);
}
/* Clean SID Lists */
vec_foreach (sl_index, sr_policy->segments_lists)
{
segment_list = pool_elt_at_index (sm->sid_lists, *sl_index);
vec_free (segment_list->segments);
vec_free (segment_list->rewrite);
if (!sr_policy->is_encap)
vec_free (segment_list->rewrite_bsid);
pool_put_index (sm->sid_lists, *sl_index);
}
if (sr_policy->plugin)
{
sr_policy_fn_registration_t *plugin = 0;
plugin =
pool_elt_at_index (sm->policy_plugin_functions,
sr_policy->plugin - SR_BEHAVIOR_LAST);
plugin->removal (sr_policy);
sr_policy->plugin = 0;
sr_policy->plugin_mem = NULL;
}
/* Remove SR policy entry */
mhash_unset (&sm->sr_policies_index_hash, &sr_policy->bsid, NULL);
pool_put (sm->sr_policies, sr_policy);
/* If FIB empty unlock it */
if (!pool_elts (sm->sr_policies) && !pool_elts (sm->steer_policies))
{
fib_table_unlock (sm->fib_table_ip6, FIB_PROTOCOL_IP6, FIB_SOURCE_SR);
fib_table_unlock (sm->fib_table_ip4, FIB_PROTOCOL_IP6, FIB_SOURCE_SR);
sm->fib_table_ip6 = (u32) ~ 0;
sm->fib_table_ip4 = (u32) ~ 0;
}
return 0;
}
/**
* @brief Modify an existing SR policy
*
* The possible modifications are adding a new Segment List, modifying an
* existing Segment List (modify the weight only) and delete a given
* Segment List from the SR Policy.
*
* @param bsid is the bindingSID of the SR Policy
* @param index is the index of the SR policy
* @param fib_table is the VRF where to install the FIB entry for the BSID
* @param operation is the operation to perform (among the top ones)
* @param segments is a vector of IPv6 address composing the segment list
* @param sl_index is the index of the Segment List to modify/delete
* @param weight is the weight of the sid list. optional.
* @param is_encap Mode. Encapsulation or SRH insertion.
*
* @return 0 if correct, else error
*/
int
sr_policy_mod (ip6_address_t * bsid, u32 index, u32 fib_table,
u8 operation, ip6_address_t * segments, u32 sl_index,
u32 weight)
{
ip6_sr_main_t *sm = &sr_main;
ip6_sr_policy_t *sr_policy = 0;
ip6_sr_sl_t *segment_list;
u32 *sl_index_iterate;
uword *p;
if (bsid)
{
p = mhash_get (&sm->sr_policies_index_hash, bsid);
if (p)
sr_policy = pool_elt_at_index (sm->sr_policies, p[0]);
else
return -1;
}
else
{
sr_policy = pool_elt_at_index (sm->sr_policies, index);
}
if (operation == 1) /* Add SR List to an existing SR policy */
{
/* Create the new SL */
segment_list =
create_sl (sr_policy, segments, weight, sr_policy->is_encap);
/* Create a new LB DPO */
if (sr_policy->type == SR_POLICY_TYPE_DEFAULT)
update_lb (sr_policy);
else if (sr_policy->type == SR_POLICY_TYPE_SPRAY)
update_replicate (sr_policy);
}
else if (operation == 2) /* Delete SR List from an existing SR policy */
{
/* Check that currently there are more than one SID list */
if (vec_len (sr_policy->segments_lists) == 1)
return -21;
/* Check that the SR list does exist and is assigned to the sr policy */
vec_foreach (sl_index_iterate, sr_policy->segments_lists)
if (*sl_index_iterate == sl_index)
break;
if (*sl_index_iterate != sl_index)
return -22;
/* Remove the lucky SR list that is being kicked out */
segment_list = pool_elt_at_index (sm->sid_lists, sl_index);
vec_free (segment_list->segments);
vec_free (segment_list->rewrite);
if (!sr_policy->is_encap)
vec_free (segment_list->rewrite_bsid);
pool_put_index (sm->sid_lists, sl_index);
vec_del1 (sr_policy->segments_lists,
sl_index_iterate - sr_policy->segments_lists);
/* Create a new LB DPO */
if (sr_policy->type == SR_POLICY_TYPE_DEFAULT)
update_lb (sr_policy);
else if (sr_policy->type == SR_POLICY_TYPE_SPRAY)
update_replicate (sr_policy);
}
else if (operation == 3) /* Modify the weight of an existing SR List */
{
/* Find the corresponding SL */
vec_foreach (sl_index_iterate, sr_policy->segments_lists)
if (*sl_index_iterate == sl_index)
break;
if (*sl_index_iterate != sl_index)
return -32;
/* Change the weight */
segment_list = pool_elt_at_index (sm->sid_lists, sl_index);
segment_list->weight = weight;
/* Update LB */
if (sr_policy->type == SR_POLICY_TYPE_DEFAULT)
update_lb (sr_policy);
}
else /* Incorrect op. */
return -1;
return 0;
}
/**
* @brief CLI for 'sr policies' command family
*/
static clib_error_t *
sr_policy_command_fn (vlib_main_t * vm, unformat_input_t * input,
vlib_cli_command_t * cmd)
{
ip6_sr_main_t *sm = &sr_main;
int rv = -1;
char is_del = 0, is_add = 0, is_mod = 0;
char policy_set = 0;
ip6_address_t bsid, next_address;
u32 sr_policy_index = (u32) ~ 0, sl_index = (u32) ~ 0;
u32 weight = (u32) ~ 0, fib_table = (u32) ~ 0;
ip6_address_t *segments = 0, *this_seg;
u8 operation = 0;
char is_encap = 1;
u8 type = SR_POLICY_TYPE_DEFAULT;
u16 behavior = 0;
void *ls_plugin_mem = 0;
while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
{
if (!is_add && !is_mod && !is_del && unformat (input, "add"))
is_add = 1;
else if (!is_add && !is_mod && !is_del && unformat (input, "del"))
is_del = 1;
else if (!is_add && !is_mod && !is_del && unformat (input, "mod"))
is_mod = 1;
else if (!policy_set
&& unformat (input, "bsid %U", unformat_ip6_address, &bsid))
policy_set = 1;
else if (!is_add && !policy_set
&& unformat (input, "index %d", &sr_policy_index))
policy_set = 1;
else if (unformat (input, "weight %d", &weight));
else
if (unformat (input, "next %U", unformat_ip6_address, &next_address))
{
vec_add2 (segments, this_seg, 1);
clib_memcpy_fast (this_seg->as_u8, next_address.as_u8,
sizeof (*this_seg));
}
else if (unformat (input, "add sl"))
operation = 1;
else if (unformat (input, "del sl index %d", &sl_index))
operation = 2;
else if (unformat (input, "mod sl index %d", &sl_index))
operation = 3;
else if (fib_table == (u32) ~ 0
&& unformat (input, "fib-table %d", &fib_table));
else if (unformat (input, "encap"))
is_encap = 1;
else if (unformat (input, "insert"))
is_encap = 0;
else if (unformat (input, "spray"))
type = SR_POLICY_TYPE_SPRAY;
else if (!behavior && unformat (input, "behavior"))
{
sr_policy_fn_registration_t *plugin = 0, **vec_plugins = 0;
sr_policy_fn_registration_t **plugin_it = 0;
/* *INDENT-OFF* */
pool_foreach (plugin, sm->policy_plugin_functions)
{
vec_add1 (vec_plugins, plugin);
}
/* *INDENT-ON* */
vec_foreach (plugin_it, vec_plugins)
{
if (unformat
(input, "%U", (*plugin_it)->ls_unformat, &ls_plugin_mem))
{
behavior = (*plugin_it)->sr_policy_function_number;
break;
}
}
if (!behavior)
{
return clib_error_return (0, "Invalid behavior");
}
}
else
break;
}
if (!is_add && !is_mod && !is_del)
return clib_error_return (0, "Incorrect CLI");
if (!policy_set)
return clib_error_return (0, "No SR policy BSID or index specified");
if (is_add)
{
if (behavior && vec_len (segments) == 0)
{
vec_add2 (segments, this_seg, 1);
clib_memset (this_seg, 0, sizeof (*this_seg));
}
if (vec_len (segments) == 0)
return clib_error_return (0, "No Segment List specified");
rv = sr_policy_add (&bsid, segments, weight, type, fib_table, is_encap,
behavior, ls_plugin_mem);
vec_free (segments);
}
else if (is_del)
rv = sr_policy_del ((sr_policy_index != (u32) ~ 0 ? NULL : &bsid),
sr_policy_index);
else if (is_mod)
{
if (!operation)
return clib_error_return (0, "No SL modification specified");
if (operation != 1 && sl_index == (u32) ~ 0)
return clib_error_return (0, "No Segment List index specified");
if (operation == 1 && vec_len (segments) == 0)
return clib_error_return (0, "No Segment List specified");
if (operation == 3 && weight == (u32) ~ 0)
return clib_error_return (0, "No new weight for the SL specified");
rv = sr_policy_mod ((sr_policy_index != (u32) ~ 0 ? NULL : &bsid),
sr_policy_index, fib_table, operation, segments,
sl_index, weight);
if (segments)
vec_free (segments);
}
switch (rv)
{
case 0:
break;
case 1:
return 0;
case -12:
return clib_error_return (0,
"There is already a FIB entry for the BindingSID address.\n"
"The SR policy could not be created.");
case -13:
return clib_error_return (0, "The specified FIB table does not exist.");
case -21:
return clib_error_return (0,
"The selected SR policy only contains ONE segment list. "
"Please remove the SR policy instead");
case -22:
return clib_error_return (0,
"Could not delete the segment list. "
"It is not associated with that SR policy.");
case -32:
return clib_error_return (0,
"Could not modify the segment list. "
"The given SL is not associated with such SR policy.");
default:
return clib_error_return (0, "BUG: sr policy returns %d", rv);
}
return 0;
}
/* *INDENT-OFF* */
VLIB_CLI_COMMAND (sr_policy_command, static) = {
.path = "sr policy",
.short_help = "sr policy [add||del||mod] [bsid 2001::1||index 5] "
"next A:: next B:: next C:: (weight 1) (fib-table 2) (encap|insert)",
.long_help =
"Manipulation of SR policies.\n"
"A Segment Routing policy may contain several SID lists. Each SID list has\n"
"an associated weight (default 1), which will result in wECMP (uECMP).\n"
"Segment Routing policies might be of type encapsulation or srh insertion\n"
"Each SR policy will be associated with a unique BindingSID.\n"
"A BindingSID is a locally allocated SegmentID. For every packet that arrives\n"
"with IPv6_DA:BSID such traffic will be steered into the SR policy.\n"
"The add command will create a SR policy with its first segment list (sl)\n"
"The mod command allows you to add, remove, or modify the existing segment lists\n"
"within an SR policy.\n"
"The del command allows you to delete a SR policy along with all its associated\n"
"SID lists.\n",
.function = sr_policy_command_fn,
};
/* *INDENT-ON* */
/**
* @brief CLI to display onscreen all the SR policies
*/
static clib_error_t *
show_sr_policies_command_fn (vlib_main_t * vm, unformat_input_t * input,
vlib_cli_command_t * cmd)
{
ip6_sr_main_t *sm = &sr_main;
u32 *sl_index;
ip6_sr_sl_t *segment_list = 0;
ip6_sr_policy_t *sr_policy = 0;
ip6_sr_policy_t **vec_policies = 0;
ip6_address_t *addr;
u8 *s;
int i = 0;
vlib_cli_output (vm, "SR policies:");
/* *INDENT-OFF* */
pool_foreach (sr_policy, sm->sr_policies)
{vec_add1 (vec_policies, sr_policy); }
/* *INDENT-ON* */
vec_foreach_index (i, vec_policies)
{
sr_policy = vec_policies[i];
vlib_cli_output (vm, "[%u].-\tBSID: %U",
(u32) (sr_policy - sm->sr_policies),
format_ip6_address, &sr_policy->bsid);
vlib_cli_output (vm, "\tBehavior: %s",
(sr_policy->is_encap ? "Encapsulation" :
"SRH insertion"));
switch (sr_policy->type)
{
case SR_POLICY_TYPE_SPRAY:
vlib_cli_output (vm, "\tType: %s", "Spray");
break;
default:
vlib_cli_output (vm, "\tType: %s", "Default");
break;
}
vlib_cli_output (vm, "\tFIB table: %u",
(sr_policy->fib_table !=
(u32) ~ 0 ? sr_policy->fib_table : 0));
vlib_cli_output (vm, "\tSegment Lists:");
vec_foreach (sl_index, sr_policy->segments_lists)
{
s = NULL;
s = format (s, "\t[%u].- ", *sl_index);
segment_list = pool_elt_at_index (sm->sid_lists, *sl_index);
s = format (s, "< ");
vec_foreach (addr, segment_list->segments)
{
s = format (s, "%U, ", format_ip6_address, addr);
}
s = format (s, "\b\b > ");
s = format (s, "weight: %u", segment_list->weight);
vlib_cli_output (vm, " %v", s);
}
vlib_cli_output (vm, "-----------");
}
return 0;
}
/* *INDENT-OFF* */
VLIB_CLI_COMMAND (show_sr_policies_command, static) = {
.path = "show sr policies",
.short_help = "show sr policies",
.function = show_sr_policies_command_fn,
};
/* *INDENT-ON* */
/**
* @brief CLI to display onscreen the SR encaps source addr
*/
static clib_error_t *
show_sr_encaps_source_command_fn (vlib_main_t * vm, unformat_input_t * input,
vlib_cli_command_t * cmd)
{
vlib_cli_output (vm, "SR encaps source addr = %U", format_ip6_address,
sr_get_encaps_source ());
return 0;
}
/* *INDENT-OFF* */
VLIB_CLI_COMMAND (show_sr_encaps_source_command, static) = {
.path = "show sr encaps source addr",
.short_help = "show sr encaps source addr",
.function = show_sr_encaps_source_command_fn,
};
/* *INDENT-ON* */
/**
* @brief CLI to display onscreen the hop-limit value used for SRv6 encapsulation
*/
static clib_error_t *
show_sr_encaps_hop_limit_command_fn (vlib_main_t * vm,
unformat_input_t * input,
vlib_cli_command_t * cmd)
{
vlib_cli_output (vm, "SR encaps hop-limit = %u", sr_get_hop_limit ());
return 0;
}
/* *INDENT-OFF* */
VLIB_CLI_COMMAND (show_sr_encaps_hop_limit_command, static) = {
.path = "show sr encaps hop-limit",
.short_help = "show sr encaps hop-limit",
.function = show_sr_encaps_hop_limit_command_fn,
};
/* *INDENT-ON* */
/*************************** SR rewrite graph node ****************************/
/**
* @brief Trace for the SR Policy Rewrite graph node
*/
static u8 *
format_sr_policy_rewrite_trace (u8 * s, va_list * args)
{
//TODO
CLIB_UNUSED (vlib_main_t * vm) = va_arg (*args, vlib_main_t *);
CLIB_UNUSED (vlib_node_t * node) = va_arg (*args, vlib_node_t *);
sr_policy_rewrite_trace_t *t = va_arg (*args, sr_policy_rewrite_trace_t *);
s = format
(s, "SR-policy-rewrite: src %U dst %U",
format_ip6_address, &t->src, format_ip6_address, &t->dst);
return s;
}
/**
* @brief IPv6 encapsulation processing as per RFC2473
*/
static_always_inline void
encaps_processing_v6 (vlib_node_runtime_t *node, vlib_buffer_t *b0,
ip6_header_t *ip0, ip6_header_t *ip0_encap,
u8 policy_type)
{
u32 new_l0;
u32 flow_label;
ip0_encap->hop_limit -= 1;
new_l0 =
ip0->payload_length + sizeof (ip6_header_t) +
clib_net_to_host_u16 (ip0_encap->payload_length);
ip0->payload_length = clib_host_to_net_u16 (new_l0);
flow_label = ip6_compute_flow_hash (ip0_encap, IP_FLOW_HASH_DEFAULT);
ip0->ip_version_traffic_class_and_flow_label = clib_host_to_net_u32 (
0 |
(clib_net_to_host_u32 (
ip0_encap->ip_version_traffic_class_and_flow_label) &
0xfff00000) |
(flow_label & 0x0000ffff));
}
/**
* @brief Graph node for applying a SR policy into an IPv6 packet. Encapsulation
*/
static uword
sr_policy_rewrite_encaps (vlib_main_t * vm, vlib_node_runtime_t * node,
vlib_frame_t * from_frame)
{
ip6_sr_main_t *sm = &sr_main;
u32 n_left_from, next_index, *from, *to_next;
from = vlib_frame_vector_args (from_frame);
n_left_from = from_frame->n_vectors;
next_index = node->cached_next_index;
int encap_pkts = 0, bsid_pkts = 0;
while (n_left_from > 0)
{
u32 n_left_to_next;
vlib_get_next_frame (vm, node, next_index, to_next, n_left_to_next);
/* Quad - Loop */
while (n_left_from >= 8 && n_left_to_next >= 4)
{
u32 bi0, bi1, bi2, bi3;
vlib_buffer_t *b0, *b1, *b2, *b3;
u32 next0, next1, next2, next3;
next0 = next1 = next2 = next3 = SR_POLICY_REWRITE_NEXT_IP6_LOOKUP;
ip6_header_t *ip0, *ip1, *ip2, *ip3;
ip6_header_t *ip0_encap, *ip1_encap, *ip2_encap, *ip3_encap;
ip6_sr_sl_t *sl0, *sl1, *sl2, *sl3;
/* Prefetch next iteration. */
{
vlib_buffer_t *p4, *p5, *p6, *p7;
p4 = vlib_get_buffer (vm, from[4]);
p5 = vlib_get_buffer (vm, from[5]);
p6 = vlib_get_buffer (vm, from[6]);
p7 = vlib_get_buffer (vm, from[7]);
/* Prefetch the buffer header and packet for the N+2 loop iteration */
vlib_prefetch_buffer_header (p4, LOAD);
vlib_prefetch_buffer_header (p5, LOAD);
vlib_prefetch_buffer_header (p6, LOAD);
vlib_prefetch_buffer_header (p7, LOAD);
clib_prefetch_store (p4->data);
clib_prefetch_store (p5->data);
clib_prefetch_store (p6->data);
clib_prefetch_store (p7->data);
}
to_next[0] = bi0 = from[0];
to_next[1] = bi1 = from[1];
to_next[2] = bi2 = from[2];
to_next[3] = bi3 = from[3];
from += 4;
to_next += 4;
n_left_from -= 4;
n_left_to_next -= 4;
b0 = vlib_get_buffer (vm, bi0);
b1 = vlib_get_buffer (vm, bi1);
b2 = vlib_get_buffer (vm, bi2);
b3 = vlib_get_buffer (vm, bi3);
sl0 =
pool_elt_at_index (sm->sid_lists,
vnet_buffer (b0)->ip.adj_index[VLIB_TX]);
sl1 =
pool_elt_at_index (sm->sid_lists,
vnet_buffer (b1)->ip.adj_index[VLIB_TX]);
sl2 =
pool_elt_at_index (sm->sid_lists,
vnet_buffer (b2)->ip.adj_index[VLIB_TX]);
sl3 =
pool_elt_at_index (sm->sid_lists,
vnet_buffer (b3)->ip.adj_index[VLIB_TX]);
ASSERT (b0->current_data + VLIB_BUFFER_PRE_DATA_SIZE >=
vec_len (sl0->rewrite));
ASSERT (b1->current_data + VLIB_BUFFER_PRE_DATA_SIZE >=
vec_len (sl1->rewrite));
ASSERT (b2->current_data + VLIB_BUFFER_PRE_DATA_SIZE >=
vec_len (sl2->rewrite));
ASSERT (b3->current_data + VLIB_BUFFER_PRE_DATA_SIZE >=
vec_len (sl3->rewrite));
ip0_encap = vlib_buffer_get_current (b0);
ip1_encap = vlib_buffer_get_current (b1);
ip2_encap = vlib_buffer_get_current (b2);
ip3_encap = vlib_buffer_get_current (b3);
clib_memcpy_fast (((u8 *) ip0_encap) - vec_len (sl0->rewrite),
sl0->rewrite, vec_len (sl0->rewrite));
clib_memcpy_fast (((u8 *) ip1_encap) - vec_len (sl1->rewrite),
sl1->rewrite, vec_len (sl1->rewrite));
clib_memcpy_fast (((u8 *) ip2_encap) - vec_len (sl2->rewrite),
sl2->rewrite, vec_len (sl2->rewrite));
clib_memcpy_fast (((u8 *) ip3_encap) - vec_len (sl3->rewrite),
sl3->rewrite, vec_len (sl3->rewrite));
vlib_buffer_advance (b0, -(word) vec_len (sl0->rewrite));
vlib_buffer_advance (b1, -(word) vec_len (sl1->rewrite));
vlib_buffer_advance (b2, -(word) vec_len (sl2->rewrite));
vlib_buffer_advance (b3, -(word) vec_len (sl3->rewrite));
ip0 = vlib_buffer_get_current (b0);
ip1 = vlib_buffer_get_current (b1);
ip2 = vlib_buffer_get_current (b2);
ip3 = vlib_buffer_get_current (b3);
encaps_processing_v6 (node, b0, ip0, ip0_encap, sl0->policy_type);
encaps_processing_v6 (node, b1, ip1, ip1_encap, sl1->policy_type);
encaps_processing_v6 (node, b2, ip2, ip2_encap, sl2->policy_type);
encaps_processing_v6 (node, b3, ip3, ip3_encap, sl3->policy_type);
vnet_buffer (b0)->sw_if_index[VLIB_TX] = sl0->egress_fib_table;
vnet_buffer (b1)->sw_if_index[VLIB_TX] = sl1->egress_fib_table;
vnet_buffer (b2)->sw_if_index[VLIB_TX] = sl2->egress_fib_table;
vnet_buffer (b3)->sw_if_index[VLIB_TX] = sl3->egress_fib_table;
if (PREDICT_FALSE ((node->flags & VLIB_NODE_FLAG_TRACE)))
{
if (PREDICT_FALSE (b0->flags & VLIB_BUFFER_IS_TRACED))
{
sr_policy_rewrite_trace_t *tr =
vlib_add_trace (vm, node, b0, sizeof (*tr));
clib_memcpy_fast (tr->src.as_u8, ip0->src_address.as_u8,
sizeof (tr->src.as_u8));
clib_memcpy_fast (tr->dst.as_u8, ip0->dst_address.as_u8,
sizeof (tr->dst.as_u8));
}
if (PREDICT_FALSE (b1->flags & VLIB_BUFFER_IS_TRACED))
{
sr_policy_rewrite_trace_t *tr =
vlib_add_trace (vm, node, b1, sizeof (*tr));
clib_memcpy_fast (tr->src.as_u8, ip1->src_address.as_u8,
sizeof (tr->src.as_u8));
clib_memcpy_fast (tr->dst.as_u8, ip1->dst_address.as_u8,
sizeof (tr->dst.as_u8));
}
if (PREDICT_FALSE (b2->flags & VLIB_BUFFER_IS_TRACED))
{
sr_policy_rewrite_trace_t *tr =
vlib_add_trace (vm, node, b2, sizeof (*tr));
clib_memcpy_fast (tr->src.as_u8, ip2->src_address.as_u8,
sizeof (tr->src.as_u8));
clib_memcpy_fast (tr->dst.as_u8, ip2->dst_address.as_u8,
sizeof (tr->dst.as_u8));
}
if (PREDICT_FALSE (b3->flags & VLIB_BUFFER_IS_TRACED))
{
sr_policy_rewrite_trace_t *tr =
vlib_add_trace (vm, node, b3, sizeof (*tr));
clib_memcpy_fast (tr->src.as_u8, ip3->src_address.as_u8,
sizeof (tr->src.as_u8));
clib_memcpy_fast (tr->dst.as_u8, ip3->dst_address.as_u8,
sizeof (tr->dst.as_u8));
}
}
encap_pkts += 4;
vlib_validate_buffer_enqueue_x4 (vm, node, next_index, to_next,
n_left_to_next, bi0, bi1, bi2, bi3,
next0, next1, next2, next3);
}
/* Single loop for potentially the last three packets */
while (n_left_from > 0 && n_left_to_next > 0)
{
u32 bi0;
vlib_buffer_t *b0;
ip6_header_t *ip0 = 0, *ip0_encap = 0;
ip6_sr_sl_t *sl0;
u32 next0 = SR_POLICY_REWRITE_NEXT_IP6_LOOKUP;
bi0 = from[0];
to_next[0] = bi0;
from += 1;
to_next += 1;
n_left_from -= 1;
n_left_to_next -= 1;
b0 = vlib_get_buffer (vm, bi0);
sl0 =
pool_elt_at_index (sm->sid_lists,
vnet_buffer (b0)->ip.adj_index[VLIB_TX]);
ASSERT (b0->current_data + VLIB_BUFFER_PRE_DATA_SIZE >=
vec_len (sl0->rewrite));
ip0_encap = vlib_buffer_get_current (b0);
clib_memcpy_fast (((u8 *) ip0_encap) - vec_len (sl0->rewrite),
sl0->rewrite, vec_len (sl0->rewrite));
vlib_buffer_advance (b0, -(word) vec_len (sl0->rewrite));
ip0 = vlib_buffer_get_current (b0);
encaps_processing_v6 (node, b0, ip0, ip0_encap, sl0->policy_type);
vnet_buffer (b0)->sw_if_index[VLIB_TX] = sl0->egress_fib_table;
if (PREDICT_FALSE (node->flags & VLIB_NODE_FLAG_TRACE) &&
PREDICT_FALSE (b0->flags & VLIB_BUFFER_IS_TRACED))
{
sr_policy_rewrite_trace_t *tr =
vlib_add_trace (vm, node, b0, sizeof (*tr));
clib_memcpy_fast (tr->src.as_u8, ip0->src_address.as_u8,
sizeof (tr->src.as_u8));
clib_memcpy_fast (tr->dst.as_u8, ip0->dst_address.as_u8,
sizeof (tr->dst.as_u8));
}
encap_pkts++;
vlib_validate_buffer_enqueue_x1 (vm, node, next_index, to_next,
n_left_to_next, bi0, next0);
}
vlib_put_next_frame (vm, node, next_index, n_left_to_next);
}
/* Update counters */
vlib_node_increment_counter (vm, sr_policy_rewrite_encaps_node.index,
SR_POLICY_REWRITE_ERROR_COUNTER_TOTAL,
encap_pkts);
vlib_node_increment_counter (vm, sr_policy_rewrite_encaps_node.index,
SR_POLICY_REWRITE_ERROR_COUNTER_BSID,
bsid_pkts);
return from_frame->n_vectors;
}
/* *INDENT-OFF* */
VLIB_REGISTER_NODE (sr_policy_rewrite_encaps_node) = {
.function = sr_policy_rewrite_encaps,
.name = "sr-pl-rewrite-encaps",
.vector_size = sizeof (u32),
.format_trace = format_sr_policy_rewrite_trace,
.type = VLIB_NODE_TYPE_INTERNAL,
.n_errors = SR_POLICY_REWRITE_N_ERROR,
.error_strings = sr_policy_rewrite_error_strings,
.n_next_nodes = SR_POLICY_REWRITE_N_NEXT,
.next_nodes = {
#define _(s,n) [SR_POLICY_REWRITE_NEXT_##s] = n,
foreach_sr_policy_rewrite_next
#undef _
},
};
/* *INDENT-ON* */
/**
* @brief IPv4 encapsulation processing as per RFC2473
*/
static_always_inline void
encaps_processing_v4 (vlib_node_runtime_t * node,
vlib_buffer_t * b0,
ip6_header_t * ip0, ip4_header_t * ip0_encap)
{
u32 new_l0;
ip6_sr_header_t *sr0;
u32 checksum0;
u32 flow_label;
/* Inner IPv4: Decrement TTL & update checksum */
ip0_encap->ttl -= 1;
checksum0 = ip0_encap->checksum + clib_host_to_net_u16 (0x0100);
checksum0 += checksum0 >= 0xffff;
ip0_encap->checksum = checksum0;
/* Outer IPv6: Update length, FL, proto */
new_l0 = ip0->payload_length + clib_net_to_host_u16 (ip0_encap->length);
ip0->payload_length = clib_host_to_net_u16 (new_l0);
flow_label = ip4_compute_flow_hash (ip0_encap, IP_FLOW_HASH_DEFAULT);
ip0->ip_version_traffic_class_and_flow_label = clib_host_to_net_u32 (
0 | ((6 & 0xF) << 28) | ((ip0_encap->tos & 0xFF) << 20) |
(flow_label & 0x0000ffff));
if (ip0->protocol == IP_PROTOCOL_IPV6_ROUTE)
{
sr0 = (void *) (ip0 + 1);
sr0->protocol = IP_PROTOCOL_IP_IN_IP;
}
else
ip0->protocol = IP_PROTOCOL_IP_IN_IP;
}
/**
* @brief Graph node for applying a SR policy into an IPv4 packet. Encapsulation
*/
static uword
sr_policy_rewrite_encaps_v4 (vlib_main_t * vm, vlib_node_runtime_t * node,
vlib_frame_t * from_frame)
{
ip6_sr_main_t *sm = &sr_main;
u32 n_left_from, next_index, *from, *to_next;
from = vlib_frame_vector_args (from_frame);
n_left_from = from_frame->n_vectors;
next_index = node->cached_next_index;
int encap_pkts = 0, bsid_pkts = 0;
while (n_left_from > 0)
{
u32 n_left_to_next;
vlib_get_next_frame (vm, node, next_index, to_next, n_left_to_next);
/* Quad - Loop */
while (n_left_from >= 8 && n_left_to_next >= 4)
{
u32 bi0, bi1, bi2, bi3;
vlib_buffer_t *b0, *b1, *b2, *b3;
u32 next0, next1, next2, next3;
next0 = next1 = next2 = next3 = SR_POLICY_REWRITE_NEXT_IP6_LOOKUP;
ip6_header_t *ip0, *ip1, *ip2, *ip3;
ip4_header_t *ip0_encap, *ip1_encap, *ip2_encap, *ip3_encap;
ip6_sr_sl_t *sl0, *sl1, *sl2, *sl3;
/* Prefetch next iteration. */
{
vlib_buffer_t *p4, *p5, *p6, *p7;
p4 = vlib_get_buffer (vm, from[4]);
p5 = vlib_get_buffer (vm, from[5]);
p6 = vlib_get_buffer (vm, from[6]);
p7 = vlib_get_buffer (vm, from[7]);
/* Prefetch the buffer header and packet for the N+2 loop iteration */
vlib_prefetch_buffer_header (p4, LOAD);
vlib_prefetch_buffer_header (p5, LOAD);
vlib_prefetch_buffer_header (p6, LOAD);
vlib_prefetch_buffer_header (p7, LOAD);
clib_prefetch_store (p4->data);
clib_prefetch_store (p5->data);
clib_prefetch_store (p6->data);
clib_prefetch_store (p7->data);
}
to_next[0] = bi0 = from[0];
to_next[1] = bi1 = from[1];
to_next[2] = bi2 = from[2];
to_next[3] = bi3 = from[3];
from += 4;
to_next += 4;
n_left_from -= 4;
n_left_to_next -= 4;
b0 = vlib_get_buffer (vm, bi0);
b1 = vlib_get_buffer (vm, bi1);
b2 = vlib_get_buffer (vm, bi2);
b3 = vlib_get_buffer (vm, bi3);
sl0 =
pool_elt_at_index (sm->sid_lists,
vnet_buffer (b0)->ip.adj_index[VLIB_TX]);
sl1 =
pool_elt_at_index (sm->sid_lists,
vnet_buffer (b1)->ip.adj_index[VLIB_TX]);
sl2 =
pool_elt_at_index (sm->sid_lists,
vnet_buffer (b2)->ip.adj_index[VLIB_TX]);
sl3 =
pool_elt_at_index (sm->sid_lists,
vnet_buffer (b3)->ip.adj_index[VLIB_TX]);
ASSERT (b0->current_data + VLIB_BUFFER_PRE_DATA_SIZE >=
vec_len (sl0->rewrite));
ASSERT (b1->current_data + VLIB_BUFFER_PRE_DATA_SIZE >=
vec_len (sl1->rewrite));
ASSERT (b2->current_data + VLIB_BUFFER_PRE_DATA_SIZE >=
vec_len (sl2->rewrite));
ASSERT (b3->current_data + VLIB_BUFFER_PRE_DATA_SIZE >=
vec_len (sl3->rewrite));
ip0_encap = vlib_buffer_get_current (b0);
ip1_encap = vlib_buffer_get_current (b1);
ip2_encap = vlib_buffer_get_current (b2);
ip3_encap = vlib_buffer_get_current (b3);
clib_memcpy_fast (((u8 *) ip0_encap) - vec_len (sl0->rewrite),
sl0->rewrite, vec_len (sl0->rewrite));
clib_memcpy_fast (((u8 *) ip1_encap) - vec_len (sl1->rewrite),
sl1->rewrite, vec_len (sl1->rewrite));
clib_memcpy_fast (((u8 *) ip2_encap) - vec_len (sl2->rewrite),
sl2->rewrite, vec_len (sl2->rewrite));
clib_memcpy_fast (((u8 *) ip3_encap) - vec_len (sl3->rewrite),
sl3->rewrite, vec_len (sl3->rewrite));
vlib_buffer_advance (b0, -(word) vec_len (sl0->rewrite));
vlib_buffer_advance (b1, -(word) vec_len (sl1->rewrite));
vlib_buffer_advance (b2, -(word) vec_len (sl2->rewrite));
vlib_buffer_advance (b3, -(word) vec_len (sl3->rewrite));
ip0 = vlib_buffer_get_current (b0);
ip1 = vlib_buffer_get_current (b1);
ip2 = vlib_buffer_get_current (b2);
ip3 = vlib_buffer_get_current (b3);
encaps_processing_v4 (node, b0, ip0, ip0_encap);
encaps_processing_v4 (node, b1, ip1, ip1_encap);
encaps_processing_v4 (node, b2, ip2, ip2_encap);
encaps_processing_v4 (node, b3, ip3, ip3_encap);
vnet_buffer (b0)->sw_if_index[VLIB_TX] = sl0->egress_fib_table;
vnet_buffer (b1)->sw_if_index[VLIB_TX] = sl1->egress_fib_table;
vnet_buffer (b2)->sw_if_index[VLIB_TX] = sl2->egress_fib_table;
vnet_buffer (b3)->sw_if_index[VLIB_TX] = sl3->egress_fib_table;
if (PREDICT_FALSE ((node->flags & VLIB_NODE_FLAG_TRACE)))
{
if (PREDICT_FALSE (b0->flags & VLIB_BUFFER_IS_TRACED))
{
sr_policy_rewrite_trace_t *tr =
vlib_add_trace (vm, node, b0, sizeof (*tr));
clib_memcpy_fast (tr->src.as_u8, ip0->src_address.as_u8,
sizeof (tr->src.as_u8));
clib_memcpy_fast (tr->dst.as_u8, ip0->dst_address.as_u8,
sizeof (tr->dst.as_u8));
}
if (PREDICT_FALSE (b1->flags & VLIB_BUFFER_IS_TRACED))
{
sr_policy_rewrite_trace_t *tr =
vlib_add_trace (vm, node, b1, sizeof (*tr));
clib_memcpy_fast (tr->src.as_u8, ip1->src_address.as_u8,
sizeof (tr->src.as_u8));
clib_memcpy_fast (tr->dst.as_u8, ip1->dst_address.as_u8,
sizeof (tr->dst.as_u8));
}
if (PREDICT_FALSE (b2->flags & VLIB_BUFFER_IS_TRACED))
{
sr_policy_rewrite_trace_t *tr =
vlib_add_trace (vm, node, b2, sizeof (*tr));
clib_memcpy_fast (tr->src.as_u8, ip2->src_address.as_u8,
sizeof (tr->src.as_u8));
clib_memcpy_fast (tr->dst.as_u8, ip2->dst_address.as_u8,
sizeof (tr->dst.as_u8));
}
if (PREDICT_FALSE (b3->flags & VLIB_BUFFER_IS_TRACED))
{
sr_policy_rewrite_trace_t *tr =
vlib_add_trace (vm, node, b3, sizeof (*tr));
clib_memcpy_fast (tr->src.as_u8, ip3->src_address.as_u8,
sizeof (tr->src.as_u8));
clib_memcpy_fast (tr->dst.as_u8, ip3->dst_address.as_u8,
sizeof (tr->dst.as_u8));
}
}
encap_pkts += 4;
vlib_validate_buffer_enqueue_x4 (vm, node, next_index, to_next,
n_left_to_next, bi0, bi1, bi2, bi3,
next0, next1, next2, next3);
}
/* Single loop for potentially the last three packets */
while (n_left_from > 0 && n_left_to_next > 0)
{
u32 bi0;
vlib_buffer_t *b0;
ip6_header_t *ip0 = 0;
ip4_header_t *ip0_encap = 0;
ip6_sr_sl_t *sl0;
u32 next0 = SR_POLICY_REWRITE_NEXT_IP6_LOOKUP;
bi0 = from[0];
to_next[0] = bi0;
from += 1;
to_next += 1;
n_left_from -= 1;
n_left_to_next -= 1;
b0 = vlib_get_buffer (vm, bi0);
sl0 =
pool_elt_at_index (sm->sid_lists,
vnet_buffer (b0)->ip.adj_index[VLIB_TX]);
ASSERT (b0->current_data + VLIB_BUFFER_PRE_DATA_SIZE >=
vec_len (sl0->rewrite));
ip0_encap = vlib_buffer_get_current (b0);
clib_memcpy_fast (((u8 *) ip0_encap) - vec_len (sl0->rewrite),
sl0->rewrite, vec_len (sl0->rewrite));
vlib_buffer_advance (b0, -(word) vec_len (sl0->rewrite));
ip0 = vlib_buffer_get_current (b0);
encaps_processing_v4 (node, b0, ip0, ip0_encap);
vnet_buffer (b0)->sw_if_index[VLIB_TX] = sl0->egress_fib_table;
if (PREDICT_FALSE (node->flags & VLIB_NODE_FLAG_TRACE) &&
PREDICT_FALSE (b0->flags & VLIB_BUFFER_IS_TRACED))
{
sr_policy_rewrite_trace_t *tr =
vlib_add_trace (vm, node, b0, sizeof (*tr));
clib_memcpy_fast (tr->src.as_u8, ip0->src_address.as_u8,
sizeof (tr->src.as_u8));
clib_memcpy_fast (tr->dst.as_u8, ip0->dst_address.as_u8,
sizeof (tr->dst.as_u8));
}
encap_pkts++;
vlib_validate_buffer_enqueue_x1 (vm, node, next_index, to_next,
n_left_to_next, bi0, next0);
}
vlib_put_next_frame (vm, node, next_index, n_left_to_next);
}
/* Update counters */
vlib_node_increment_counter (vm, sr_policy_rewrite_encaps_node.index,
SR_POLICY_REWRITE_ERROR_COUNTER_TOTAL,
encap_pkts);
vlib_node_increment_counter (vm, sr_policy_rewrite_encaps_node.index,
SR_POLICY_REWRITE_ERROR_COUNTER_BSID,
bsid_pkts);
return from_frame->n_vectors;
}
/* *INDENT-OFF* */
VLIB_REGISTER_NODE (sr_policy_rewrite_encaps_v4_node) = {
.function = sr_policy_rewrite_encaps_v4,
.name = "sr-pl-rewrite-encaps-v4",
.vector_size = sizeof (u32),
.format_trace = format_sr_policy_rewrite_trace,
.type = VLIB_NODE_TYPE_INTERNAL,
.n_errors = SR_POLICY_REWRITE_N_ERROR,
.error_strings = sr_policy_rewrite_error_strings,
.n_next_nodes = SR_POLICY_REWRITE_N_NEXT,
.next_nodes = {
#define _(s,n) [SR_POLICY_REWRITE_NEXT_##s] = n,
foreach_sr_policy_rewrite_next
#undef _
},
};
/* *INDENT-ON* */
always_inline u32
ip_flow_hash (void *data)
{
ip4_header_t *iph = (ip4_header_t *) data;
if ((iph->ip_version_and_header_length & 0xF0) == 0x40)
return ip4_compute_flow_hash (iph, IP_FLOW_HASH_DEFAULT);
else
return ip6_compute_flow_hash ((ip6_header_t *) iph, IP_FLOW_HASH_DEFAULT);
}
always_inline u64
mac_to_u64 (u8 * m)
{
return (*((u64 *) m) & 0xffffffffffff);
}
always_inline u32
l2_flow_hash (vlib_buffer_t * b0)
{
ethernet_header_t *eh;
u64 a, b, c;
uword is_ip, eh_size;
u16 eh_type;
eh = vlib_buffer_get_current (b0);
eh_type = clib_net_to_host_u16 (eh->type);
eh_size = ethernet_buffer_header_size (b0);
is_ip = (eh_type == ETHERNET_TYPE_IP4 || eh_type == ETHERNET_TYPE_IP6);
/* since we have 2 cache lines, use them */
if (is_ip)
a = ip_flow_hash ((u8 *) vlib_buffer_get_current (b0) + eh_size);
else
a = eh->type;
b = mac_to_u64 ((u8 *) eh->dst_address);
c = mac_to_u64 ((u8 *) eh->src_address);
hash_mix64 (a, b, c);
return (u32) c;
}
/**
* @brief Graph node for applying a SR policy into a L2 frame
*/
static uword
sr_policy_rewrite_encaps_l2 (vlib_main_t * vm, vlib_node_runtime_t * node,
vlib_frame_t * from_frame)
{
ip6_sr_main_t *sm = &sr_main;
u32 n_left_from, next_index, *from, *to_next;
from = vlib_frame_vector_args (from_frame);
n_left_from = from_frame->n_vectors;
next_index = node->cached_next_index;
int encap_pkts = 0, bsid_pkts = 0;
while (n_left_from > 0)
{
u32 n_left_to_next;
vlib_get_next_frame (vm, node, next_index, to_next, n_left_to_next);
/* Quad - Loop */
while (n_left_from >= 8 && n_left_to_next >= 4)
{
u32 bi0, bi1, bi2, bi3;
vlib_buffer_t *b0, *b1, *b2, *b3;
u32 next0, next1, next2, next3;
next0 = next1 = next2 = next3 = SR_POLICY_REWRITE_NEXT_IP6_LOOKUP;
ethernet_header_t *en0, *en1, *en2, *en3;
ip6_header_t *ip0, *ip1, *ip2, *ip3;
ip6_sr_header_t *sr0, *sr1, *sr2, *sr3;
ip6_sr_policy_t *sp0, *sp1, *sp2, *sp3;
ip6_sr_sl_t *sl0, *sl1, *sl2, *sl3;
u32 flow_label0, flow_label1, flow_label2, flow_label3;
/* Prefetch next iteration. */
{
vlib_buffer_t *p4, *p5, *p6, *p7;
p4 = vlib_get_buffer (vm, from[4]);
p5 = vlib_get_buffer (vm, from[5]);
p6 = vlib_get_buffer (vm, from[6]);
p7 = vlib_get_buffer (vm, from[7]);
/* Prefetch the buffer header and packet for the N+2 loop iteration */
vlib_prefetch_buffer_header (p4, LOAD);
vlib_prefetch_buffer_header (p5, LOAD);
vlib_prefetch_buffer_header (p6, LOAD);
vlib_prefetch_buffer_header (p7, LOAD);
clib_prefetch_store (p4->data);
clib_prefetch_store (p5->data);
clib_prefetch_store (p6->data);
clib_prefetch_store (p7->data);
}
to_next[0] = bi0 = from[0];
to_next[1] = bi1 = from[1];
to_next[2] = bi2 = from[2];
to_next[3] = bi3 = from[3];
from += 4;
to_next += 4;
n_left_from -= 4;
n_left_to_next -= 4;
b0 = vlib_get_buffer (vm, bi0);
b1 = vlib_get_buffer (vm, bi1);
b2 = vlib_get_buffer (vm, bi2);
b3 = vlib_get_buffer (vm, bi3);
sp0 = pool_elt_at_index (sm->sr_policies,
sm->sw_iface_sr_policies[vnet_buffer
(b0)->sw_if_index
[VLIB_RX]]);
sp1 = pool_elt_at_index (sm->sr_policies,
sm->sw_iface_sr_policies[vnet_buffer
(b1)->sw_if_index
[VLIB_RX]]);
sp2 = pool_elt_at_index (sm->sr_policies,
sm->sw_iface_sr_policies[vnet_buffer
(b2)->sw_if_index
[VLIB_RX]]);
sp3 = pool_elt_at_index (sm->sr_policies,
sm->sw_iface_sr_policies[vnet_buffer
(b3)->sw_if_index
[VLIB_RX]]);
flow_label0 = l2_flow_hash (b0);
flow_label1 = l2_flow_hash (b1);
flow_label2 = l2_flow_hash (b2);
flow_label3 = l2_flow_hash (b3);
if (vec_len (sp0->segments_lists) == 1)
vnet_buffer (b0)->ip.adj_index[VLIB_TX] = sp0->segments_lists[0];
else
{
vnet_buffer (b0)->ip.flow_hash = flow_label0;
vnet_buffer (b0)->ip.adj_index[VLIB_TX] =
sp0->segments_lists[(vnet_buffer (b0)->ip.flow_hash &
(vec_len (sp0->segments_lists) - 1))];
}
if (vec_len (sp1->segments_lists) == 1)
vnet_buffer (b1)->ip.adj_index[VLIB_TX] = sp1->segments_lists[1];
else
{
vnet_buffer (b1)->ip.flow_hash = flow_label1;
vnet_buffer (b1)->ip.adj_index[VLIB_TX] =
sp1->segments_lists[(vnet_buffer (b1)->ip.flow_hash &
(vec_len (sp1->segments_lists) - 1))];
}
if (vec_len (sp2->segments_lists) == 1)
vnet_buffer (b2)->ip.adj_index[VLIB_TX] = sp2->segments_lists[2];
else
{
vnet_buffer (b2)->ip.flow_hash = flow_label2;
vnet_buffer (b2)->ip.adj_index[VLIB_TX] =
sp2->segments_lists[(vnet_buffer (b2)->ip.flow_hash &
(vec_len (sp2->segments_lists) - 1))];
}
if (vec_len (sp3->segments_lists) == 1)
vnet_buffer (b3)->ip.adj_index[VLIB_TX] = sp3->segments_lists[3];
else
{
vnet_buffer (b3)->ip.flow_hash = flow_label3;
vnet_buffer (b3)->ip.adj_index[VLIB_TX] =
sp3->segments_lists[(vnet_buffer (b3)->ip.flow_hash &
(vec_len (sp3->segments_lists) - 1))];
}
sl0 =
pool_elt_at_index (sm->sid_lists,
vnet_buffer (b0)->ip.adj_index[VLIB_TX]);
sl1 =
pool_elt_at_index (sm->sid_lists,
vnet_buffer (b1)->ip.adj_index[VLIB_TX]);
sl2 =
pool_elt_at_index (sm->sid_lists,
vnet_buffer (b2)->ip.adj_index[VLIB_TX]);
sl3 =
pool_elt_at_index (sm->sid_lists,
vnet_buffer (b3)->ip.adj_index[VLIB_TX]);
ASSERT (b0->current_data + VLIB_BUFFER_PRE_DATA_SIZE >=
vec_len (sl0->rewrite));
ASSERT (b1->current_data + VLIB_BUFFER_PRE_DATA_SIZE >=
vec_len (sl1->rewrite));
ASSERT (b2->current_data + VLIB_BUFFER_PRE_DATA_SIZE >=
vec_len (sl2->rewrite));
ASSERT (b3->current_data + VLIB_BUFFER_PRE_DATA_SIZE >=
vec_len (sl3->rewrite));
en0 = vlib_buffer_get_current (b0);
en1 = vlib_buffer_get_current (b1);
en2 = vlib_buffer_get_current (b2);
en3 = vlib_buffer_get_current (b3);
clib_memcpy_fast (((u8 *) en0) - vec_len (sl0->rewrite),
sl0->rewrite, vec_len (sl0->rewrite));
clib_memcpy_fast (((u8 *) en1) - vec_len (sl1->rewrite),
sl1->rewrite, vec_len (sl1->rewrite));
clib_memcpy_fast (((u8 *) en2) - vec_len (sl2->rewrite),
sl2->rewrite, vec_len (sl2->rewrite));
clib_memcpy_fast (((u8 *) en3) - vec_len (sl3->rewrite),
sl3->rewrite, vec_len (sl3->rewrite));
vlib_buffer_advance (b0, -(word) vec_len (sl0->rewrite));
vlib_buffer_advance (b1, -(word) vec_len (sl1->rewrite));
vlib_buffer_advance (b2, -(word) vec_len (sl2->rewrite));
vlib_buffer_advance (b3, -(word) vec_len (sl3->rewrite));
ip0 = vlib_buffer_get_current (b0);
ip1 = vlib_buffer_get_current (b1);
ip2 = vlib_buffer_get_current (b2);
ip3 = vlib_buffer_get_current (b3);
ip0->payload_length =
clib_host_to_net_u16 (b0->current_length - sizeof (ip6_header_t));
ip1->payload_length =
clib_host_to_net_u16 (b1->current_length - sizeof (ip6_header_t));
ip2->payload_length =
clib_host_to_net_u16 (b2->current_length - sizeof (ip6_header_t));
ip3->payload_length =
clib_host_to_net_u16 (b3->current_length - sizeof (ip6_header_t));
if (ip0->protocol == IP_PROTOCOL_IPV6_ROUTE)
{
sr0 = (void *) (ip0 + 1);
sr0->protocol = IP_PROTOCOL_IP6_ETHERNET;
}
else
ip0->protocol = IP_PROTOCOL_IP6_ETHERNET;
if (ip1->protocol == IP_PROTOCOL_IPV6_ROUTE)
{
sr1 = (void *) (ip1 + 1);
sr1->protocol = IP_PROTOCOL_IP6_ETHERNET;
}
else
ip1->protocol = IP_PROTOCOL_IP6_ETHERNET;
if (ip2->protocol == IP_PROTOCOL_IPV6_ROUTE)
{
sr2 = (void *) (ip2 + 1);
sr2->protocol = IP_PROTOCOL_IP6_ETHERNET;
}
else
ip2->protocol = IP_PROTOCOL_IP6_ETHERNET;
if (ip3->protocol == IP_PROTOCOL_IPV6_ROUTE)
{
sr3 = (void *) (ip3 + 1);
sr3->protocol = IP_PROTOCOL_IP6_ETHERNET;
}
else
ip3->protocol = IP_PROTOCOL_IP6_ETHERNET;
/* TC is set to 0 for all ethernet frames, should be taken from COS
* od DSCP of encapsulated packet in the future */
ip0->ip_version_traffic_class_and_flow_label = clib_host_to_net_u32 (
0 | ((6 & 0xF) << 28) | ((0x00) << 20) | (flow_label0 & 0xffff));
ip1->ip_version_traffic_class_and_flow_label = clib_host_to_net_u32 (
0 | ((6 & 0xF) << 28) | ((0x00) << 20) | (flow_label1 & 0xffff));
ip2->ip_version_traffic_class_and_flow_label = clib_host_to_net_u32 (
0 | ((6 & 0xF) << 28) | ((0x00) << 20) | (flow_label2 & 0xffff));
ip3->ip_version_traffic_class_and_flow_label = clib_host_to_net_u32 (
0 | ((6 & 0xF) << 28) | ((0x00) << 20) | (flow_label3 & 0xffff));
if (PREDICT_FALSE ((node->flags & VLIB_NODE_FLAG_TRACE)))
{
if (PREDICT_FALSE (b0->flags & VLIB_BUFFER_IS_TRACED))
{
sr_policy_rewrite_trace_t *tr =
vlib_add_trace (vm, node, b0, sizeof (*tr));
clib_memcpy_fast (tr->src.as_u8, ip0->src_address.as_u8,
sizeof (tr->src.as_u8));
clib_memcpy_fast (tr->dst.as_u8, ip0->dst_address.as_u8,
sizeof (tr->dst.as_u8));
}
if (PREDICT_FALSE (b1->flags & VLIB_BUFFER_IS_TRACED))
{
sr_policy_rewrite_trace_t *tr =
vlib_add_trace (vm, node, b1, sizeof (*tr));
clib_memcpy_fast (tr->src.as_u8, ip1->src_address.as_u8,
sizeof (tr->src.as_u8));
clib_memcpy_fast (tr->dst.as_u8, ip1->dst_address.as_u8,
sizeof (tr->dst.as_u8));
}
if (PREDICT_FALSE (b2->flags & VLIB_BUFFER_IS_TRACED))
{
sr_policy_rewrite_trace_t *tr =
vlib_add_trace (vm, node, b2, sizeof (*tr));
clib_memcpy_fast (tr->src.as_u8, ip2->src_address.as_u8,
sizeof (tr->src.as_u8));
clib_memcpy_fast (tr->dst.as_u8, ip2->dst_address.as_u8,
sizeof (tr->dst.as_u8));
}
if (PREDICT_FALSE (b3->flags & VLIB_BUFFER_IS_TRACED))
{
sr_policy_rewrite_trace_t *tr =
vlib_add_trace (vm, node, b3, sizeof (*tr));
clib_memcpy_fast (tr->src.as_u8, ip3->src_address.as_u8,
sizeof (tr->src.as_u8));
clib_memcpy_fast (tr->dst.as_u8, ip3->dst_address.as_u8,
sizeof (tr->dst.as_u8));
}
}
encap_pkts += 4;
vlib_validate_buffer_enqueue_x4 (vm, node, next_index, to_next,
n_left_to_next, bi0, bi1, bi2, bi3,
next0, next1, next2, next3);
}
/* Single loop for potentially the last three packets */
while (n_left_from > 0 && n_left_to_next > 0)
{
u32 bi0;
vlib_buffer_t *b0;
ip6_header_t *ip0 = 0;
ip6_sr_header_t *sr0;
ethernet_header_t *en0;
ip6_sr_policy_t *sp0;
ip6_sr_sl_t *sl0;
u32 next0 = SR_POLICY_REWRITE_NEXT_IP6_LOOKUP;
u32 flow_label0;
bi0 = from[0];
to_next[0] = bi0;
from += 1;
to_next += 1;
n_left_from -= 1;
n_left_to_next -= 1;
b0 = vlib_get_buffer (vm, bi0);
/* Find the SR policy */
sp0 = pool_elt_at_index (sm->sr_policies,
sm->sw_iface_sr_policies[vnet_buffer
(b0)->sw_if_index
[VLIB_RX]]);
flow_label0 = l2_flow_hash (b0);
/* In case there is more than one SL, LB among them */
if (vec_len (sp0->segments_lists) == 1)
vnet_buffer (b0)->ip.adj_index[VLIB_TX] = sp0->segments_lists[0];
else
{
vnet_buffer (b0)->ip.flow_hash = flow_label0;
vnet_buffer (b0)->ip.adj_index[VLIB_TX] =
sp0->segments_lists[(vnet_buffer (b0)->ip.flow_hash &
(vec_len (sp0->segments_lists) - 1))];
}
sl0 =
pool_elt_at_index (sm->sid_lists,
vnet_buffer (b0)->ip.adj_index[VLIB_TX]);
ASSERT (b0->current_data + VLIB_BUFFER_PRE_DATA_SIZE >=
vec_len (sl0->rewrite));
en0 = vlib_buffer_get_current (b0);
clib_memcpy_fast (((u8 *) en0) - vec_len (sl0->rewrite),
sl0->rewrite, vec_len (sl0->rewrite));
vlib_buffer_advance (b0, -(word) vec_len (sl0->rewrite));
ip0 = vlib_buffer_get_current (b0);
ip0->payload_length =
clib_host_to_net_u16 (b0->current_length - sizeof (ip6_header_t));
if (ip0->protocol == IP_PROTOCOL_IPV6_ROUTE)
{
sr0 = (void *) (ip0 + 1);
sr0->protocol = IP_PROTOCOL_IP6_ETHERNET;
}
else
ip0->protocol = IP_PROTOCOL_IP6_ETHERNET;
ip0->ip_version_traffic_class_and_flow_label = clib_host_to_net_u32 (
0 | ((6 & 0xF) << 28) | ((0x00) << 20) | (flow_label0 & 0xffff));
if (PREDICT_FALSE (node->flags & VLIB_NODE_FLAG_TRACE) &&
PREDICT_FALSE (b0->flags & VLIB_BUFFER_IS_TRACED))
{
sr_policy_rewrite_trace_t *tr =
vlib_add_trace (vm, node, b0, sizeof (*tr));
clib_memcpy_fast (tr->src.as_u8, ip0->src_address.as_u8,
sizeof (tr->src.as_u8));
clib_memcpy_fast (tr->dst.as_u8, ip0->dst_address.as_u8,
sizeof (tr->dst.as_u8));
}
encap_pkts++;
vlib_validate_buffer_enqueue_x1 (vm, node, next_index, to_next,
n_left_to_next, bi0, next0);
}
vlib_put_next_frame (vm, node, next_index, n_left_to_next);
}
/* Update counters */
vlib_node_increment_counter (vm, sr_policy_rewrite_encaps_node.index,
SR_POLICY_REWRITE_ERROR_COUNTER_TOTAL,
encap_pkts);
vlib_node_increment_counter (vm, sr_policy_rewrite_encaps_node.index,
SR_POLICY_REWRITE_ERROR_COUNTER_BSID,
bsid_pkts);
return from_frame->n_vectors;
}
/* *INDENT-OFF* */
VLIB_REGISTER_NODE (sr_policy_rewrite_encaps_l2_node) = {
.function = sr_policy_rewrite_encaps_l2,
.name = "sr-pl-rewrite-encaps-l2",
.vector_size = sizeof (u32),
.format_trace = format_sr_policy_rewrite_trace,
.type = VLIB_NODE_TYPE_INTERNAL,
.n_errors = SR_POLICY_REWRITE_N_ERROR,
.error_strings = sr_policy_rewrite_error_strings,
.n_next_nodes = SR_POLICY_REWRITE_N_NEXT,
.next_nodes = {
#define _(s,n) [SR_POLICY_REWRITE_NEXT_##s] = n,
foreach_sr_policy_rewrite_next
#undef _
},
};
/* *INDENT-ON* */
/**
* @brief Graph node for applying a SR policy into a packet. SRH insertion.
*/
static uword
sr_policy_rewrite_insert (vlib_main_t * vm, vlib_node_runtime_t * node,
vlib_frame_t * from_frame)
{
ip6_sr_main_t *sm = &sr_main;
u32 n_left_from, next_index, *from, *to_next;
from = vlib_frame_vector_args (from_frame);
n_left_from = from_frame->n_vectors;
next_index = node->cached_next_index;
int insert_pkts = 0, bsid_pkts = 0;
while (n_left_from > 0)
{
u32 n_left_to_next;
vlib_get_next_frame (vm, node, next_index, to_next, n_left_to_next);
/* Quad - Loop */
while (n_left_from >= 8 && n_left_to_next >= 4)
{
u32 bi0, bi1, bi2, bi3;
vlib_buffer_t *b0, *b1, *b2, *b3;
u32 next0, next1, next2, next3;
next0 = next1 = next2 = next3 = SR_POLICY_REWRITE_NEXT_IP6_LOOKUP;
ip6_header_t *ip0, *ip1, *ip2, *ip3;
ip6_sr_header_t *sr0, *sr1, *sr2, *sr3;
ip6_sr_sl_t *sl0, *sl1, *sl2, *sl3;
u16 new_l0, new_l1, new_l2, new_l3;
/* Prefetch next iteration. */
{
vlib_buffer_t *p4, *p5, *p6, *p7;
p4 = vlib_get_buffer (vm, from[4]);
p5 = vlib_get_buffer (vm, from[5]);
p6 = vlib_get_buffer (vm, from[6]);
p7 = vlib_get_buffer (vm, from[7]);
/* Prefetch the buffer header and packet for the N+2 loop iteration */
vlib_prefetch_buffer_header (p4, LOAD);
vlib_prefetch_buffer_header (p5, LOAD);
vlib_prefetch_buffer_header (p6, LOAD);
vlib_prefetch_buffer_header (p7, LOAD);
clib_prefetch_store (p4->data);
clib_prefetch_store (p5->data);
clib_prefetch_store (p6->data);
clib_prefetch_store (p7->data);
}
to_next[0] = bi0 = from[0];
to_next[1] = bi1 = from[1];
to_next[2] = bi2 = from[2];
to_next[3] = bi3 = from[3];
from += 4;
to_next += 4;
n_left_from -= 4;
n_left_to_next -= 4;
b0 = vlib_get_buffer (vm, bi0);
b1 = vlib_get_buffer (vm, bi1);
b2 = vlib_get_buffer (vm, bi2);
b3 = vlib_get_buffer (vm, bi3);
sl0 =
pool_elt_at_index (sm->sid_lists,
vnet_buffer (b0)->ip.adj_index[VLIB_TX]);
sl1 =
pool_elt_at_index (sm->sid_lists,
vnet_buffer (b1)->ip.adj_index[VLIB_TX]);
sl2 =
pool_elt_at_index (sm->sid_lists,
vnet_buffer (b2)->ip.adj_index[VLIB_TX]);
sl3 =
pool_elt_at_index (sm->sid_lists,
vnet_buffer (b3)->ip.adj_index[VLIB_TX]);
ASSERT (b0->current_data + VLIB_BUFFER_PRE_DATA_SIZE >=
vec_len (sl0->rewrite));
ASSERT (b1->current_data + VLIB_BUFFER_PRE_DATA_SIZE >=
vec_len (sl1->rewrite));
ASSERT (b2->current_data + VLIB_BUFFER_PRE_DATA_SIZE >=
vec_len (sl2->rewrite));
ASSERT (b3->current_data + VLIB_BUFFER_PRE_DATA_SIZE >=
vec_len (sl3->rewrite));
ip0 = vlib_buffer_get_current (b0);
ip1 = vlib_buffer_get_current (b1);
ip2 = vlib_buffer_get_current (b2);
ip3 = vlib_buffer_get_current (b3);
if (ip0->protocol == IP_PROTOCOL_IP6_HOP_BY_HOP_OPTIONS)
sr0 =
(ip6_sr_header_t *) (((void *) (ip0 + 1)) +
ip6_ext_header_len (ip0 + 1));
else
sr0 = (ip6_sr_header_t *) (ip0 + 1);
if (ip1->protocol == IP_PROTOCOL_IP6_HOP_BY_HOP_OPTIONS)
sr1 =
(ip6_sr_header_t *) (((void *) (ip1 + 1)) +
ip6_ext_header_len (ip1 + 1));
else
sr1 = (ip6_sr_header_t *) (ip1 + 1);
if (ip2->protocol == IP_PROTOCOL_IP6_HOP_BY_HOP_OPTIONS)
sr2 =
(ip6_sr_header_t *) (((void *) (ip2 + 1)) +
ip6_ext_header_len (ip2 + 1));
else
sr2 = (ip6_sr_header_t *) (ip2 + 1);
if (ip3->protocol == IP_PROTOCOL_IP6_HOP_BY_HOP_OPTIONS)
sr3 =
(ip6_sr_header_t *) (((void *) (ip3 + 1)) +
ip6_ext_header_len (ip3 + 1));
else
sr3 = (ip6_sr_header_t *) (ip3 + 1);
clib_memcpy_fast ((u8 *) ip0 - vec_len (sl0->rewrite), (u8 *) ip0,
(void *) sr0 - (void *) ip0);
clib_memcpy_fast ((u8 *) ip1 - vec_len (sl1->rewrite), (u8 *) ip1,
(void *) sr1 - (void *) ip1);
clib_memcpy_fast ((u8 *) ip2 - vec_len (sl2->rewrite), (u8 *) ip2,
(void *) sr2 - (void *) ip2);
clib_memcpy_fast ((u8 *) ip3 - vec_len (sl3->rewrite), (u8 *) ip3,
(void *) sr3 - (void *) ip3);
clib_memcpy_fast (((u8 *) sr0 - vec_len (sl0->rewrite)),
sl0->rewrite, vec_len (sl0->rewrite));
clib_memcpy_fast (((u8 *) sr1 - vec_len (sl1->rewrite)),
sl1->rewrite, vec_len (sl1->rewrite));
clib_memcpy_fast (((u8 *) sr2 - vec_len (sl2->rewrite)),
sl2->rewrite, vec_len (sl2->rewrite));
clib_memcpy_fast (((u8 *) sr3 - vec_len (sl3->rewrite)),
sl3->rewrite, vec_len (sl3->rewrite));
vlib_buffer_advance (b0, -(word) vec_len (sl0->rewrite));
vlib_buffer_advance (b1, -(word) vec_len (sl1->rewrite));
vlib_buffer_advance (b2, -(word) vec_len (sl2->rewrite));
vlib_buffer_advance (b3, -(word) vec_len (sl3->rewrite));
ip0 = ((void *) ip0) - vec_len (sl0->rewrite);
ip1 = ((void *) ip1) - vec_len (sl1->rewrite);
ip2 = ((void *) ip2) - vec_len (sl2->rewrite);
ip3 = ((void *) ip3) - vec_len (sl3->rewrite);
ip0->hop_limit -= 1;
ip1->hop_limit -= 1;
ip2->hop_limit -= 1;
ip3->hop_limit -= 1;
new_l0 =
clib_net_to_host_u16 (ip0->payload_length) +
vec_len (sl0->rewrite);
new_l1 =
clib_net_to_host_u16 (ip1->payload_length) +
vec_len (sl1->rewrite);
new_l2 =
clib_net_to_host_u16 (ip2->payload_length) +
vec_len (sl2->rewrite);
new_l3 =
clib_net_to_host_u16 (ip3->payload_length) +
vec_len (sl3->rewrite);
ip0->payload_length = clib_host_to_net_u16 (new_l0);
ip1->payload_length = clib_host_to_net_u16 (new_l1);
ip2->payload_length = clib_host_to_net_u16 (new_l2);
ip3->payload_length = clib_host_to_net_u16 (new_l3);
sr0 = ((void *) sr0) - vec_len (sl0->rewrite);
sr1 = ((void *) sr1) - vec_len (sl1->rewrite);
sr2 = ((void *) sr2) - vec_len (sl2->rewrite);
sr3 = ((void *) sr3) - vec_len (sl3->rewrite);
sr0->segments->as_u64[0] = ip0->dst_address.as_u64[0];
sr0->segments->as_u64[1] = ip0->dst_address.as_u64[1];
sr1->segments->as_u64[0] = ip1->dst_address.as_u64[0];
sr1->segments->as_u64[1] = ip1->dst_address.as_u64[1];
sr2->segments->as_u64[0] = ip2->dst_address.as_u64[0];
sr2->segments->as_u64[1] = ip2->dst_address.as_u64[1];
sr3->segments->as_u64[0] = ip3->dst_address.as_u64[0];
sr3->segments->as_u64[1] = ip3->dst_address.as_u64[1];
ip0->dst_address.as_u64[0] =
(sr0->segments + sr0->segments_left)->as_u64[0];
ip0->dst_address.as_u64[1] =
(sr0->segments + sr0->segments_left)->as_u64[1];
ip1->dst_address.as_u64[0] =
(sr1->segments + sr1->segments_left)->as_u64[0];
ip1->dst_address.as_u64[1] =
(sr1->segments + sr1->segments_left)->as_u64[1];
ip2->dst_address.as_u64[0] =
(sr2->segments + sr2->segments_left)->as_u64[0];
ip2->dst_address.as_u64[1] =
(sr2->segments + sr2->segments_left)->as_u64[1];
ip3->dst_address.as_u64[0] =
(sr3->segments + sr3->segments_left)->as_u64[0];
ip3->dst_address.as_u64[1] =
(sr3->segments + sr3->segments_left)->as_u64[1];
ip6_ext_header_t *ip_ext;
if (ip0 + 1 == (void *) sr0)
{
sr0->protocol = ip0->protocol;
ip0->protocol = IP_PROTOCOL_IPV6_ROUTE;
}
else
{
ip_ext = (void *) (ip0 + 1);
sr0->protocol = ip_ext->next_hdr;
ip_ext->next_hdr = IP_PROTOCOL_IPV6_ROUTE;
}
if (ip1 + 1 == (void *) sr1)
{
sr1->protocol = ip1->protocol;
ip1->protocol = IP_PROTOCOL_IPV6_ROUTE;
}
else
{
ip_ext = (void *) (ip2 + 1);
sr2->protocol = ip_ext->next_hdr;
ip_ext->next_hdr = IP_PROTOCOL_IPV6_ROUTE;
}
if (ip2 + 1 == (void *) sr2)
{
sr2->protocol = ip2->protocol;
ip2->protocol = IP_PROTOCOL_IPV6_ROUTE;
}
else
{
ip_ext = (void *) (ip2 + 1);
sr2->protocol = ip_ext->next_hdr;
ip_ext->next_hdr = IP_PROTOCOL_IPV6_ROUTE;
}
if (ip3 + 1 == (void *) sr3)
{
sr3->protocol = ip3->protocol;
ip3->protocol = IP_PROTOCOL_IPV6_ROUTE;
}
else
{
ip_ext = (void *) (ip3 + 1);
sr3->protocol = ip_ext->next_hdr;
ip_ext->next_hdr = IP_PROTOCOL_IPV6_ROUTE;
}
insert_pkts += 4;
if (PREDICT_FALSE ((node->flags & VLIB_NODE_FLAG_TRACE)))
{
if (PREDICT_FALSE (b0->flags & VLIB_BUFFER_IS_TRACED))
{
sr_policy_rewrite_trace_t *tr =
vlib_add_trace (vm, node, b0, sizeof (*tr));
clib_memcpy_fast (tr->src.as_u8, ip0->src_address.as_u8,
sizeof (tr->src.as_u8));
clib_memcpy_fast (tr->dst.as_u8, ip0->dst_address.as_u8,
sizeof (tr->dst.as_u8));
}
if (PREDICT_FALSE (b1->flags & VLIB_BUFFER_IS_TRACED))
{
sr_policy_rewrite_trace_t *tr =
vlib_add_trace (vm, node, b1, sizeof (*tr));
clib_memcpy_fast (tr->src.as_u8, ip1->src_address.as_u8,
sizeof (tr->src.as_u8));
clib_memcpy_fast (tr->dst.as_u8, ip1->dst_address.as_u8,
sizeof (tr->dst.as_u8));
}
if (PREDICT_FALSE (b2->flags & VLIB_BUFFER_IS_TRACED))
{
sr_policy_rewrite_trace_t *tr =
vlib_add_trace (vm, node, b2, sizeof (*tr));
clib_memcpy_fast (tr->src.as_u8, ip2->src_address.as_u8,
sizeof (tr->src.as_u8));
clib_memcpy_fast (tr->dst.as_u8, ip2->dst_address.as_u8,
sizeof (tr->dst.as_u8));
}
if (PREDICT_FALSE (b3->flags & VLIB_BUFFER_IS_TRACED))
{
sr_policy_rewrite_trace_t *tr =
vlib_add_trace (vm, node, b3, sizeof (*tr));
clib_memcpy_fast (tr->src.as_u8, ip3->src_address.as_u8,
sizeof (tr->src.as_u8));
clib_memcpy_fast (tr->dst.as_u8, ip3->dst_address.as_u8,
sizeof (tr->dst.as_u8));
}
}
vlib_validate_buffer_enqueue_x4 (vm, node, next_index, to_next,
n_left_to_next, bi0, bi1, bi2, bi3,
next0, next1, next2, next3);
}
/* Single loop for potentially the last three packets */
while (n_left_from > 0 && n_left_to_next > 0)
{
u32 bi0;
vlib_buffer_t *b0;
ip6_header_t *ip0 = 0;
ip6_sr_header_t *sr0 = 0;
ip6_sr_sl_t *sl0;
u32 next0 = SR_POLICY_REWRITE_NEXT_IP6_LOOKUP;
u16 new_l0 = 0;
bi0 = from[0];
to_next[0] = bi0;
from += 1;
to_next += 1;
n_left_from -= 1;
n_left_to_next -= 1;
b0 = vlib_get_buffer (vm, bi0);
sl0 =
pool_elt_at_index (sm->sid_lists,
vnet_buffer (b0)->ip.adj_index[VLIB_TX]);
ASSERT (b0->current_data + VLIB_BUFFER_PRE_DATA_SIZE >=
vec_len (sl0->rewrite));
ip0 = vlib_buffer_get_current (b0);
if (ip0->protocol == IP_PROTOCOL_IP6_HOP_BY_HOP_OPTIONS)
sr0 =
(ip6_sr_header_t *) (((void *) (ip0 + 1)) +
ip6_ext_header_len (ip0 + 1));
else
sr0 = (ip6_sr_header_t *) (ip0 + 1);
clib_memcpy_fast ((u8 *) ip0 - vec_len (sl0->rewrite), (u8 *) ip0,
(void *) sr0 - (void *) ip0);
clib_memcpy_fast (((u8 *) sr0 - vec_len (sl0->rewrite)),
sl0->rewrite, vec_len (sl0->rewrite));
vlib_buffer_advance (b0, -(word) vec_len (sl0->rewrite));
ip0 = ((void *) ip0) - vec_len (sl0->rewrite);
ip0->hop_limit -= 1;
new_l0 =
clib_net_to_host_u16 (ip0->payload_length) +
vec_len (sl0->rewrite);
ip0->payload_length = clib_host_to_net_u16 (new_l0);
sr0 = ((void *) sr0) - vec_len (sl0->rewrite);
sr0->segments->as_u64[0] = ip0->dst_address.as_u64[0];
sr0->segments->as_u64[1] = ip0->dst_address.as_u64[1];
ip0->dst_address.as_u64[0] =
(sr0->segments + sr0->segments_left)->as_u64[0];
ip0->dst_address.as_u64[1] =
(sr0->segments + sr0->segments_left)->as_u64[1];
if (ip0 + 1 == (void *) sr0)
{
sr0->protocol = ip0->protocol;
ip0->protocol = IP_PROTOCOL_IPV6_ROUTE;
}
else
{
ip6_ext_header_t *ip_ext = (void *) (ip0 + 1);
sr0->protocol = ip_ext->next_hdr;
ip_ext->next_hdr = IP_PROTOCOL_IPV6_ROUTE;
}
if (PREDICT_FALSE (node->flags & VLIB_NODE_FLAG_TRACE) &&
PREDICT_FALSE (b0->flags & VLIB_BUFFER_IS_TRACED))
{
sr_policy_rewrite_trace_t *tr =
vlib_add_trace (vm, node, b0, sizeof (*tr));
clib_memcpy_fast (tr->src.as_u8, ip0->src_address.as_u8,
sizeof (tr->src.as_u8));
clib_memcpy_fast (tr->dst.as_u8, ip0->dst_address.as_u8,
sizeof (tr->dst.as_u8));
}
insert_pkts++;
vlib_validate_buffer_enqueue_x1 (vm, node, next_index, to_next,
n_left_to_next, bi0, next0);
}
vlib_put_next_frame (vm, node, next_index, n_left_to_next);
}
/* Update counters */
vlib_node_increment_counter (vm, sr_policy_rewrite_insert_node.index,
SR_POLICY_REWRITE_ERROR_COUNTER_TOTAL,
insert_pkts);
vlib_node_increment_counter (vm, sr_policy_rewrite_insert_node.index,
SR_POLICY_REWRITE_ERROR_COUNTER_BSID,
bsid_pkts);
return from_frame->n_vectors;
}
/* *INDENT-OFF* */
VLIB_REGISTER_NODE (sr_policy_rewrite_insert_node) = {
.function = sr_policy_rewrite_insert,
.name = "sr-pl-rewrite-insert",
.vector_size = sizeof (u32),
.format_trace = format_sr_policy_rewrite_trace,
.type = VLIB_NODE_TYPE_INTERNAL,
.n_errors = SR_POLICY_REWRITE_N_ERROR,
.error_strings = sr_policy_rewrite_error_strings,
.n_next_nodes = SR_POLICY_REWRITE_N_NEXT,
.next_nodes = {
#define _(s,n) [SR_POLICY_REWRITE_NEXT_##s] = n,
foreach_sr_policy_rewrite_next
#undef _
},
};
/* *INDENT-ON* */
/**
* @brief Graph node for applying a SR policy into a packet. BSID - SRH insertion.
*/
static uword
sr_policy_rewrite_b_insert (vlib_main_t * vm, vlib_node_runtime_t * node,
vlib_frame_t * from_frame)
{
ip6_sr_main_t *sm = &sr_main;
u32 n_left_from, next_index, *from, *to_next;
from = vlib_frame_vector_args (from_frame);
n_left_from = from_frame->n_vectors;
next_index = node->cached_next_index;
int insert_pkts = 0, bsid_pkts = 0;
while (n_left_from > 0)
{
u32 n_left_to_next;
vlib_get_next_frame (vm, node, next_index, to_next, n_left_to_next);
/* Quad - Loop */
while (n_left_from >= 8 && n_left_to_next >= 4)
{
u32 bi0, bi1, bi2, bi3;
vlib_buffer_t *b0, *b1, *b2, *b3;
u32 next0, next1, next2, next3;
next0 = next1 = next2 = next3 = SR_POLICY_REWRITE_NEXT_IP6_LOOKUP;
ip6_header_t *ip0, *ip1, *ip2, *ip3;
ip6_sr_header_t *sr0, *sr1, *sr2, *sr3;
ip6_sr_sl_t *sl0, *sl1, *sl2, *sl3;
u16 new_l0, new_l1, new_l2, new_l3;
/* Prefetch next iteration. */
{
vlib_buffer_t *p4, *p5, *p6, *p7;
p4 = vlib_get_buffer (vm, from[4]);
p5 = vlib_get_buffer (vm, from[5]);
p6 = vlib_get_buffer (vm, from[6]);
p7 = vlib_get_buffer (vm, from[7]);
/* Prefetch the buffer header and packet for the N+2 loop iteration */
vlib_prefetch_buffer_header (p4, LOAD);
vlib_prefetch_buffer_header (p5, LOAD);
vlib_prefetch_buffer_header (p6, LOAD);
vlib_prefetch_buffer_header (p7, LOAD);
clib_prefetch_store (p4->data);
clib_prefetch_store (p5->data);
clib_prefetch_store (p6->data);
clib_prefetch_store (p7->data);
}
to_next[0] = bi0 = from[0];
to_next[1] = bi1 = from[1];
to_next[2] = bi2 = from[2];
to_next[3] = bi3 = from[3];
from += 4;
to_next += 4;
n_left_from -= 4;
n_left_to_next -= 4;
b0 = vlib_get_buffer (vm, bi0);
b1 = vlib_get_buffer (vm, bi1);
b2 = vlib_get_buffer (vm, bi2);
b3 = vlib_get_buffer (vm, bi3);
sl0 =
pool_elt_at_index (sm->sid_lists,
vnet_buffer (b0)->ip.adj_index[VLIB_TX]);
sl1 =
pool_elt_at_index (sm->sid_lists,
vnet_buffer (b1)->ip.adj_index[VLIB_TX]);
sl2 =
pool_elt_at_index (sm->sid_lists,
vnet_buffer (b2)->ip.adj_index[VLIB_TX]);
sl3 =
pool_elt_at_index (sm->sid_lists,
vnet_buffer (b3)->ip.adj_index[VLIB_TX]);
ASSERT (b0->current_data + VLIB_BUFFER_PRE_DATA_SIZE >=
vec_len (sl0->rewrite_bsid));
ASSERT (b1->current_data + VLIB_BUFFER_PRE_DATA_SIZE >=
vec_len (sl1->rewrite_bsid));
ASSERT (b2->current_data + VLIB_BUFFER_PRE_DATA_SIZE >=
vec_len (sl2->rewrite_bsid));
ASSERT (b3->current_data + VLIB_BUFFER_PRE_DATA_SIZE >=
vec_len (sl3->rewrite_bsid));
ip0 = vlib_buffer_get_current (b0);
ip1 = vlib_buffer_get_current (b1);
ip2 = vlib_buffer_get_current (b2);
ip3 = vlib_buffer_get_current (b3);
if (ip0->protocol == IP_PROTOCOL_IP6_HOP_BY_HOP_OPTIONS)
sr0 =
(ip6_sr_header_t *) (((void *) (ip0 + 1)) +
ip6_ext_header_len (ip0 + 1));
else
sr0 = (ip6_sr_header_t *) (ip0 + 1);
if (ip1->protocol == IP_PROTOCOL_IP6_HOP_BY_HOP_OPTIONS)
sr1 =
(ip6_sr_header_t *) (((void *) (ip1 + 1)) +
ip6_ext_header_len (ip1 + 1));
else
sr1 = (ip6_sr_header_t *) (ip1 + 1);
if (ip2->protocol == IP_PROTOCOL_IP6_HOP_BY_HOP_OPTIONS)
sr2 =
(ip6_sr_header_t *) (((void *) (ip2 + 1)) +
ip6_ext_header_len (ip2 + 1));
else
sr2 = (ip6_sr_header_t *) (ip2 + 1);
if (ip3->protocol == IP_PROTOCOL_IP6_HOP_BY_HOP_OPTIONS)
sr3 =
(ip6_sr_header_t *) (((void *) (ip3 + 1)) +
ip6_ext_header_len (ip3 + 1));
else
sr3 = (ip6_sr_header_t *) (ip3 + 1);
clib_memcpy_fast ((u8 *) ip0 - vec_len (sl0->rewrite_bsid),
(u8 *) ip0, (void *) sr0 - (void *) ip0);
clib_memcpy_fast ((u8 *) ip1 - vec_len (sl1->rewrite_bsid),
(u8 *) ip1, (void *) sr1 - (void *) ip1);
clib_memcpy_fast ((u8 *) ip2 - vec_len (sl2->rewrite_bsid),
(u8 *) ip2, (void *) sr2 - (void *) ip2);
clib_memcpy_fast ((u8 *) ip3 - vec_len (sl3->rewrite_bsid),
(u8 *) ip3, (void *) sr3 - (void *) ip3);
clib_memcpy_fast (((u8 *) sr0 - vec_len (sl0->rewrite_bsid)),
sl0->rewrite_bsid, vec_len (sl0->rewrite_bsid));
clib_memcpy_fast (((u8 *) sr1 - vec_len (sl1->rewrite_bsid)),
sl1->rewrite_bsid, vec_len (sl1->rewrite_bsid));
clib_memcpy_fast (((u8 *) sr2 - vec_len (sl2->rewrite_bsid)),
sl2->rewrite_bsid, vec_len (sl2->rewrite_bsid));
clib_memcpy_fast (((u8 *) sr3 - vec_len (sl3->rewrite_bsid)),
sl3->rewrite_bsid, vec_len (sl3->rewrite_bsid));
vlib_buffer_advance (b0, -(word) vec_len (sl0->rewrite_bsid));
vlib_buffer_advance (b1, -(word) vec_len (sl1->rewrite_bsid));
vlib_buffer_advance (b2, -(word) vec_len (sl2->rewrite_bsid));
vlib_buffer_advance (b3, -(word) vec_len (sl3->rewrite_bsid));
ip0 = ((void *) ip0) - vec_len (sl0->rewrite_bsid);
ip1 = ((void *) ip1) - vec_len (sl1->rewrite_bsid);
ip2 = ((void *) ip2) - vec_len (sl2->rewrite_bsid);
ip3 = ((void *) ip3) - vec_len (sl3->rewrite_bsid);
ip0->hop_limit -= 1;
ip1->hop_limit -= 1;
ip2->hop_limit -= 1;
ip3->hop_limit -= 1;
new_l0 =
clib_net_to_host_u16 (ip0->payload_length) +
vec_len (sl0->rewrite_bsid);
new_l1 =
clib_net_to_host_u16 (ip1->payload_length) +
vec_len (sl1->rewrite_bsid);
new_l2 =
clib_net_to_host_u16 (ip2->payload_length) +
vec_len (sl2->rewrite_bsid);
new_l3 =
clib_net_to_host_u16 (ip3->payload_length) +
vec_len (sl3->rewrite_bsid);
ip0->payload_length = clib_host_to_net_u16 (new_l0);
ip1->payload_length = clib_host_to_net_u16 (new_l1);
ip2->payload_length = clib_host_to_net_u16 (new_l2);
ip3->payload_length = clib_host_to_net_u16 (new_l3);
sr0 = ((void *) sr0) - vec_len (sl0->rewrite_bsid);
sr1 = ((void *) sr1) - vec_len (sl1->rewrite_bsid);
sr2 = ((void *) sr2) - vec_len (sl2->rewrite_bsid);
sr3 = ((void *) sr3) - vec_len (sl3->rewrite_bsid);
ip0->dst_address.as_u64[0] =
(sr0->segments + sr0->segments_left)->as_u64[0];
ip0->dst_address.as_u64[1] =
(sr0->segments + sr0->segments_left)->as_u64[1];
ip1->dst_address.as_u64[0] =
(sr1->segments + sr1->segments_left)->as_u64[0];
ip1->dst_address.as_u64[1] =
(sr1->segments + sr1->segments_left)->as_u64[1];
ip2->dst_address.as_u64[0] =
(sr2->segments + sr2->segments_left)->as_u64[0];
ip2->dst_address.as_u64[1] =
(sr2->segments + sr2->segments_left)->as_u64[1];
ip3->dst_address.as_u64[0] =
(sr3->segments + sr3->segments_left)->as_u64[0];
ip3->dst_address.as_u64[1] =
(sr3->segments + sr3->segments_left)->as_u64[1];
ip6_ext_header_t *ip_ext;
if (ip0 + 1 == (void *) sr0)
{
sr0->protocol = ip0->protocol;
ip0->protocol = IP_PROTOCOL_IPV6_ROUTE;
}
else
{
ip_ext = (void *) (ip0 + 1);
sr0->protocol = ip_ext->next_hdr;
ip_ext->next_hdr = IP_PROTOCOL_IPV6_ROUTE;
}
if (ip1 + 1 == (void *) sr1)
{
sr1->protocol = ip1->protocol;
ip1->protocol = IP_PROTOCOL_IPV6_ROUTE;
}
else
{
ip_ext = (void *) (ip2 + 1);
sr2->protocol = ip_ext->next_hdr;
ip_ext->next_hdr = IP_PROTOCOL_IPV6_ROUTE;
}
if (ip2 + 1 == (void *) sr2)
{
sr2->protocol = ip2->protocol;
ip2->protocol = IP_PROTOCOL_IPV6_ROUTE;
}
else
{
ip_ext = (void *) (ip2 + 1);
sr2->protocol = ip_ext->next_hdr;
ip_ext->next_hdr = IP_PROTOCOL_IPV6_ROUTE;
}
if (ip3 + 1 == (void *) sr3)
{
sr3->protocol = ip3->protocol;
ip3->protocol = IP_PROTOCOL_IPV6_ROUTE;
}
else
{
ip_ext = (void *) (ip3 + 1);
sr3->protocol = ip_ext->next_hdr;
ip_ext->next_hdr = IP_PROTOCOL_IPV6_ROUTE;
}
insert_pkts += 4;
if (PREDICT_FALSE ((node->flags & VLIB_NODE_FLAG_TRACE)))
{
if (PREDICT_FALSE (b0->flags & VLIB_BUFFER_IS_TRACED))
{
sr_policy_rewrite_trace_t *tr =
vlib_add_trace (vm, node, b0, sizeof (*tr));
clib_memcpy_fast (tr->src.as_u8, ip0->src_address.as_u8,
sizeof (tr->src.as_u8));
clib_memcpy_fast (tr->dst.as_u8, ip0->dst_address.as_u8,
sizeof (tr->dst.as_u8));
}
if (PREDICT_FALSE (b1->flags & VLIB_BUFFER_IS_TRACED))
{
sr_policy_rewrite_trace_t *tr =
vlib_add_trace (vm, node, b1, sizeof (*tr));
clib_memcpy_fast (tr->src.as_u8, ip1->src_address.as_u8,
sizeof (tr->src.as_u8));
clib_memcpy_fast (tr->dst.as_u8, ip1->dst_address.as_u8,
sizeof (tr->dst.as_u8));
}
if (PREDICT_FALSE (b2->flags & VLIB_BUFFER_IS_TRACED))
{
sr_policy_rewrite_trace_t *tr =
vlib_add_trace (vm, node, b2, sizeof (*tr));
clib_memcpy_fast (tr->src.as_u8, ip2->src_address.as_u8,
sizeof (tr->src.as_u8));
clib_memcpy_fast (tr->dst.as_u8, ip2->dst_address.as_u8,
sizeof (tr->dst.as_u8));
}
if (PREDICT_FALSE (b3->flags & VLIB_BUFFER_IS_TRACED))
{
sr_policy_rewrite_trace_t *tr =
vlib_add_trace (vm, node, b3, sizeof (*tr));
clib_memcpy_fast (tr->src.as_u8, ip3->src_address.as_u8,
sizeof (tr->src.as_u8));
clib_memcpy_fast (tr->dst.as_u8, ip3->dst_address.as_u8,
sizeof (tr->dst.as_u8));
}
}
vlib_validate_buffer_enqueue_x4 (vm, node, next_index, to_next,
n_left_to_next, bi0, bi1, bi2, bi3,
next0, next1, next2, next3);
}
/* Single loop for potentially the last three packets */
while (n_left_from > 0 && n_left_to_next > 0)
{
u32 bi0;
vlib_buffer_t *b0;
ip6_header_t *ip0 = 0;
ip6_sr_header_t *sr0 = 0;
ip6_sr_sl_t *sl0;
u32 next0 = SR_POLICY_REWRITE_NEXT_IP6_LOOKUP;
u16 new_l0 = 0;
bi0 = from[0];
to_next[0] = bi0;
from += 1;
to_next += 1;
n_left_from -= 1;
n_left_to_next -= 1;
b0 = vlib_get_buffer (vm, bi0);
sl0 =
pool_elt_at_index (sm->sid_lists,
vnet_buffer (b0)->ip.adj_index[VLIB_TX]);
ASSERT (b0->current_data + VLIB_BUFFER_PRE_DATA_SIZE >=
vec_len (sl0->rewrite_bsid));
ip0 = vlib_buffer_get_current (b0);
if (ip0->protocol == IP_PROTOCOL_IP6_HOP_BY_HOP_OPTIONS)
sr0 =
(ip6_sr_header_t *) (((void *) (ip0 + 1)) +
ip6_ext_header_len (ip0 + 1));
else
sr0 = (ip6_sr_header_t *) (ip0 + 1);
clib_memcpy_fast ((u8 *) ip0 - vec_len (sl0->rewrite_bsid),
(u8 *) ip0, (void *) sr0 - (void *) ip0);
clib_memcpy_fast (((u8 *) sr0 - vec_len (sl0->rewrite_bsid)),
sl0->rewrite_bsid, vec_len (sl0->rewrite_bsid));
vlib_buffer_advance (b0, -(word) vec_len (sl0->rewrite_bsid));
ip0 = ((void *) ip0) - vec_len (sl0->rewrite_bsid);
ip0->hop_limit -= 1;
new_l0 =
clib_net_to_host_u16 (ip0->payload_length) +
vec_len (sl0->rewrite_bsid);
ip0->payload_length = clib_host_to_net_u16 (new_l0);
sr0 = ((void *) sr0) - vec_len (sl0->rewrite_bsid);
ip0->dst_address.as_u64[0] =
(sr0->segments + sr0->segments_left)->as_u64[0];
ip0->dst_address.as_u64[1] =
(sr0->segments + sr0->segments_left)->as_u64[1];
if (ip0 + 1 == (void *) sr0)
{
sr0->protocol = ip0->protocol;
ip0->protocol = IP_PROTOCOL_IPV6_ROUTE;
}
else
{
ip6_ext_header_t *ip_ext = (void *) (ip0 + 1);
sr0->protocol = ip_ext->next_hdr;
ip_ext->next_hdr = IP_PROTOCOL_IPV6_ROUTE;
}
if (PREDICT_FALSE (node->flags & VLIB_NODE_FLAG_TRACE) &&
PREDICT_FALSE (b0->flags & VLIB_BUFFER_IS_TRACED))
{
sr_policy_rewrite_trace_t *tr =
vlib_add_trace (vm, node, b0, sizeof (*tr));
clib_memcpy_fast (tr->src.as_u8, ip0->src_address.as_u8,
sizeof (tr->src.as_u8));
clib_memcpy_fast (tr->dst.as_u8, ip0->dst_address.as_u8,
sizeof (tr->dst.as_u8));
}
insert_pkts++;
vlib_validate_buffer_enqueue_x1 (vm, node, next_index, to_next,
n_left_to_next, bi0, next0);
}
vlib_put_next_frame (vm, node, next_index, n_left_to_next);
}
/* Update counters */
vlib_node_increment_counter (vm, sr_policy_rewrite_insert_node.index,
SR_POLICY_REWRITE_ERROR_COUNTER_TOTAL,
insert_pkts);
vlib_node_increment_counter (vm, sr_policy_rewrite_insert_node.index,
SR_POLICY_REWRITE_ERROR_COUNTER_BSID,
bsid_pkts);
return from_frame->n_vectors;
}
/* *INDENT-OFF* */
VLIB_REGISTER_NODE (sr_policy_rewrite_b_insert_node) = {
.function = sr_policy_rewrite_b_insert,
.name = "sr-pl-rewrite-b-insert",
.vector_size = sizeof (u32),
.format_trace = format_sr_policy_rewrite_trace,
.type = VLIB_NODE_TYPE_INTERNAL,
.n_errors = SR_POLICY_REWRITE_N_ERROR,
.error_strings = sr_policy_rewrite_error_strings,
.n_next_nodes = SR_POLICY_REWRITE_N_NEXT,
.next_nodes = {
#define _(s,n) [SR_POLICY_REWRITE_NEXT_##s] = n,
foreach_sr_policy_rewrite_next
#undef _
},
};
/* *INDENT-ON* */
/**
* @brief Function BSID encapsulation
*/
static_always_inline void
end_bsid_encaps_srh_processing (vlib_node_runtime_t *node, vlib_buffer_t *b0,
ip6_header_t *ip0, ip6_sr_header_t *sr0,
u32 *next0, u8 policy_type)
{
ip6_address_t *new_dst0;
if (PREDICT_FALSE (!sr0))
goto error_bsid_encaps;
if (PREDICT_TRUE (sr0->type == ROUTING_HEADER_TYPE_SR))
{
if (PREDICT_TRUE (sr0->segments_left != 0))
{
sr0->segments_left -= 1;
new_dst0 = (ip6_address_t *) (sr0->segments);
new_dst0 += sr0->segments_left;
ip0->dst_address.as_u64[0] = new_dst0->as_u64[0];
ip0->dst_address.as_u64[1] = new_dst0->as_u64[1];
return;
}
}
error_bsid_encaps:
*next0 = SR_POLICY_REWRITE_NEXT_ERROR;
b0->error = node->errors[SR_POLICY_REWRITE_ERROR_BSID_ZERO];
}
/**
* @brief Graph node for applying a SR policy BSID - Encapsulation
*/
static uword
sr_policy_rewrite_b_encaps (vlib_main_t * vm, vlib_node_runtime_t * node,
vlib_frame_t * from_frame)
{
ip6_sr_main_t *sm = &sr_main;
u32 n_left_from, next_index, *from, *to_next;
from = vlib_frame_vector_args (from_frame);
n_left_from = from_frame->n_vectors;
next_index = node->cached_next_index;
int encap_pkts = 0, bsid_pkts = 0;
while (n_left_from > 0)
{
u32 n_left_to_next;
vlib_get_next_frame (vm, node, next_index, to_next, n_left_to_next);
/* Quad - Loop */
while (n_left_from >= 8 && n_left_to_next >= 4)
{
u32 bi0, bi1, bi2, bi3;
vlib_buffer_t *b0, *b1, *b2, *b3;
u32 next0, next1, next2, next3;
next0 = next1 = next2 = next3 = SR_POLICY_REWRITE_NEXT_IP6_LOOKUP;
ip6_header_t *ip0, *ip1, *ip2, *ip3;
ip6_header_t *ip0_encap, *ip1_encap, *ip2_encap, *ip3_encap;
ip6_sr_header_t *sr0, *sr1, *sr2, *sr3;
ip6_sr_sl_t *sl0, *sl1, *sl2, *sl3;
/* Prefetch next iteration. */
{
vlib_buffer_t *p4, *p5, *p6, *p7;
p4 = vlib_get_buffer (vm, from[4]);
p5 = vlib_get_buffer (vm, from[5]);
p6 = vlib_get_buffer (vm, from[6]);
p7 = vlib_get_buffer (vm, from[7]);
/* Prefetch the buffer header and packet for the N+2 loop iteration */
vlib_prefetch_buffer_header (p4, LOAD);
vlib_prefetch_buffer_header (p5, LOAD);
vlib_prefetch_buffer_header (p6, LOAD);
vlib_prefetch_buffer_header (p7, LOAD);
clib_prefetch_store (p4->data);
clib_prefetch_store (p5->data);
clib_prefetch_store (p6->data);
clib_prefetch_store (p7->data);
}
to_next[0] = bi0 = from[0];
to_next[1] = bi1 = from[1];
to_next[2] = bi2 = from[2];
to_next[3] = bi3 = from[3];
from += 4;
to_next += 4;
n_left_from -= 4;
n_left_to_next -= 4;
b0 = vlib_get_buffer (vm, bi0);
b1 = vlib_get_buffer (vm, bi1);
b2 = vlib_get_buffer (vm, bi2);
b3 = vlib_get_buffer (vm, bi3);
sl0 =
pool_elt_at_index (sm->sid_lists,
vnet_buffer (b0)->ip.adj_index[VLIB_TX]);
sl1 =
pool_elt_at_index (sm->sid_lists,
vnet_buffer (b1)->ip.adj_index[VLIB_TX]);
sl2 =
pool_elt_at_index (sm->sid_lists,
vnet_buffer (b2)->ip.adj_index[VLIB_TX]);
sl3 =
pool_elt_at_index (sm->sid_lists,
vnet_buffer (b3)->ip.adj_index[VLIB_TX]);
ASSERT (b0->current_data + VLIB_BUFFER_PRE_DATA_SIZE >=
vec_len (sl0->rewrite));
ASSERT (b1->current_data + VLIB_BUFFER_PRE_DATA_SIZE >=
vec_len (sl1->rewrite));
ASSERT (b2->current_data + VLIB_BUFFER_PRE_DATA_SIZE >=
vec_len (sl2->rewrite));
ASSERT (b3->current_data + VLIB_BUFFER_PRE_DATA_SIZE >=
vec_len (sl3->rewrite));
ip0_encap = vlib_buffer_get_current (b0);
ip1_encap = vlib_buffer_get_current (b1);
ip2_encap = vlib_buffer_get_current (b2);
ip3_encap = vlib_buffer_get_current (b3);
sr0 =
ip6_ext_header_find (vm, b0, ip0_encap, IP_PROTOCOL_IPV6_ROUTE,
NULL);
sr1 =
ip6_ext_header_find (vm, b1, ip1_encap, IP_PROTOCOL_IPV6_ROUTE,
NULL);
sr2 =
ip6_ext_header_find (vm, b2, ip2_encap, IP_PROTOCOL_IPV6_ROUTE,
NULL);
sr3 =
ip6_ext_header_find (vm, b3, ip3_encap, IP_PROTOCOL_IPV6_ROUTE,
NULL);
end_bsid_encaps_srh_processing (node, b0, ip0_encap, sr0, &next0,
sl0->policy_type);
end_bsid_encaps_srh_processing (node, b1, ip1_encap, sr1, &next1,
sl1->policy_type);
end_bsid_encaps_srh_processing (node, b2, ip2_encap, sr2, &next2,
sl2->policy_type);
end_bsid_encaps_srh_processing (node, b3, ip3_encap, sr3, &next3,
sl3->policy_type);
clib_memcpy_fast (((u8 *) ip0_encap) - vec_len (sl0->rewrite),
sl0->rewrite, vec_len (sl0->rewrite));
clib_memcpy_fast (((u8 *) ip1_encap) - vec_len (sl1->rewrite),
sl1->rewrite, vec_len (sl1->rewrite));
clib_memcpy_fast (((u8 *) ip2_encap) - vec_len (sl2->rewrite),
sl2->rewrite, vec_len (sl2->rewrite));
clib_memcpy_fast (((u8 *) ip3_encap) - vec_len (sl3->rewrite),
sl3->rewrite, vec_len (sl3->rewrite));
vlib_buffer_advance (b0, -(word) vec_len (sl0->rewrite));
vlib_buffer_advance (b1, -(word) vec_len (sl1->rewrite));
vlib_buffer_advance (b2, -(word) vec_len (sl2->rewrite));
vlib_buffer_advance (b3, -(word) vec_len (sl3->rewrite));
ip0 = vlib_buffer_get_current (b0);
ip1 = vlib_buffer_get_current (b1);
ip2 = vlib_buffer_get_current (b2);
ip3 = vlib_buffer_get_current (b3);
encaps_processing_v6 (node, b0, ip0, ip0_encap, sl0->policy_type);
encaps_processing_v6 (node, b1, ip1, ip1_encap, sl1->policy_type);
encaps_processing_v6 (node, b2, ip2, ip2_encap, sl2->policy_type);
encaps_processing_v6 (node, b3, ip3, ip3_encap, sl3->policy_type);
if (PREDICT_FALSE ((node->flags & VLIB_NODE_FLAG_TRACE)))
{
if (PREDICT_FALSE (b0->flags & VLIB_BUFFER_IS_TRACED))
{
sr_policy_rewrite_trace_t *tr =
vlib_add_trace (vm, node, b0, sizeof (*tr));
clib_memcpy_fast (tr->src.as_u8, ip0->src_address.as_u8,
sizeof (tr->src.as_u8));
clib_memcpy_fast (tr->dst.as_u8, ip0->dst_address.as_u8,
sizeof (tr->dst.as_u8));
}
if (PREDICT_FALSE (b1->flags & VLIB_BUFFER_IS_TRACED))
{
sr_policy_rewrite_trace_t *tr =
vlib_add_trace (vm, node, b1, sizeof (*tr));
clib_memcpy_fast (tr->src.as_u8, ip1->src_address.as_u8,
sizeof (tr->src.as_u8));
clib_memcpy_fast (tr->dst.as_u8, ip1->dst_address.as_u8,
sizeof (tr->dst.as_u8));
}
if (PREDICT_FALSE (b2->flags & VLIB_BUFFER_IS_TRACED))
{
sr_policy_rewrite_trace_t *tr =
vlib_add_trace (vm, node, b2, sizeof (*tr));
clib_memcpy_fast (tr->src.as_u8, ip2->src_address.as_u8,
sizeof (tr->src.as_u8));
clib_memcpy_fast (tr->dst.as_u8, ip2->dst_address.as_u8,
sizeof (tr->dst.as_u8));
}
if (PREDICT_FALSE (b3->flags & VLIB_BUFFER_IS_TRACED))
{
sr_policy_rewrite_trace_t *tr =
vlib_add_trace (vm, node, b3, sizeof (*tr));
clib_memcpy_fast (tr->src.as_u8, ip3->src_address.as_u8,
sizeof (tr->src.as_u8));
clib_memcpy_fast (tr->dst.as_u8, ip3->dst_address.as_u8,
sizeof (tr->dst.as_u8));
}
}
encap_pkts += 4;
vlib_validate_buffer_enqueue_x4 (vm, node, next_index, to_next,
n_left_to_next, bi0, bi1, bi2, bi3,
next0, next1, next2, next3);
}
/* Single loop for potentially the last three packets */
while (n_left_from > 0 && n_left_to_next > 0)
{
u32 bi0;
vlib_buffer_t *b0;
ip6_header_t *ip0 = 0, *ip0_encap = 0;
ip6_sr_header_t *sr0;
ip6_sr_sl_t *sl0;
u32 next0 = SR_POLICY_REWRITE_NEXT_IP6_LOOKUP;
bi0 = from[0];
to_next[0] = bi0;
from += 1;
to_next += 1;
n_left_from -= 1;
n_left_to_next -= 1;
b0 = vlib_get_buffer (vm, bi0);
sl0 =
pool_elt_at_index (sm->sid_lists,
vnet_buffer (b0)->ip.adj_index[VLIB_TX]);
ASSERT (b0->current_data + VLIB_BUFFER_PRE_DATA_SIZE >=
vec_len (sl0->rewrite));
ip0_encap = vlib_buffer_get_current (b0);
sr0 =
ip6_ext_header_find (vm, b0, ip0_encap, IP_PROTOCOL_IPV6_ROUTE,
NULL);
end_bsid_encaps_srh_processing (node, b0, ip0_encap, sr0, &next0,
sl0->policy_type);
clib_memcpy_fast (((u8 *) ip0_encap) - vec_len (sl0->rewrite),
sl0->rewrite, vec_len (sl0->rewrite));
vlib_buffer_advance (b0, -(word) vec_len (sl0->rewrite));
ip0 = vlib_buffer_get_current (b0);
encaps_processing_v6 (node, b0, ip0, ip0_encap, sl0->policy_type);
if (PREDICT_FALSE (node->flags & VLIB_NODE_FLAG_TRACE) &&
PREDICT_FALSE (b0->flags & VLIB_BUFFER_IS_TRACED))
{
sr_policy_rewrite_trace_t *tr =
vlib_add_trace (vm, node, b0, sizeof (*tr));
clib_memcpy_fast (tr->src.as_u8, ip0->src_address.as_u8,
sizeof (tr->src.as_u8));
clib_memcpy_fast (tr->dst.as_u8, ip0->dst_address.as_u8,
sizeof (tr->dst.as_u8));
}
encap_pkts++;
vlib_validate_buffer_enqueue_x1 (vm, node, next_index, to_next,
n_left_to_next, bi0, next0);
}
vlib_put_next_frame (vm, node, next_index, n_left_to_next);
}
/* Update counters */
vlib_node_increment_counter (vm, sr_policy_rewrite_encaps_node.index,
SR_POLICY_REWRITE_ERROR_COUNTER_TOTAL,
encap_pkts);
vlib_node_increment_counter (vm, sr_policy_rewrite_encaps_node.index,
SR_POLICY_REWRITE_ERROR_COUNTER_BSID,
bsid_pkts);
return from_frame->n_vectors;
}
/* *INDENT-OFF* */
VLIB_REGISTER_NODE (sr_policy_rewrite_b_encaps_node) = {
.function = sr_policy_rewrite_b_encaps,
.name = "sr-pl-rewrite-b-encaps",
.vector_size = sizeof (u32),
.format_trace = format_sr_policy_rewrite_trace,
.type = VLIB_NODE_TYPE_INTERNAL,
.n_errors = SR_POLICY_REWRITE_N_ERROR,
.error_strings = sr_policy_rewrite_error_strings,
.n_next_nodes = SR_POLICY_REWRITE_N_NEXT,
.next_nodes = {
#define _(s,n) [SR_POLICY_REWRITE_NEXT_##s] = n,
foreach_sr_policy_rewrite_next
#undef _
},
};
/* *INDENT-ON* */
/*************************** SR Policy plugins ******************************/
/**
* @brief SR Policy plugin registry
*/
int
sr_policy_register_function (vlib_main_t * vm, u8 * fn_name,
u8 * keyword_str, u8 * def_str,
u8 * params_str, u8 prefix_length,
dpo_type_t * dpo,
format_function_t * ls_format,
unformat_function_t * ls_unformat,
sr_p_plugin_callback_t * creation_fn,
sr_p_plugin_callback_t * removal_fn)
{
ip6_sr_main_t *sm = &sr_main;
uword *p;
sr_policy_fn_registration_t *plugin;
/* Did this function exist? If so update it */
p = hash_get_mem (sm->policy_plugin_functions_by_key, fn_name);
if (p)
{
plugin = pool_elt_at_index (sm->policy_plugin_functions, p[0]);
}
/* Else create a new one and set hash key */
else
{
pool_get (sm->policy_plugin_functions, plugin);
hash_set_mem (sm->policy_plugin_functions_by_key, fn_name,
plugin - sm->policy_plugin_functions);
}
clib_memset (plugin, 0, sizeof (*plugin));
plugin->sr_policy_function_number = (plugin - sm->policy_plugin_functions);
plugin->sr_policy_function_number += SR_BEHAVIOR_LAST;
plugin->prefix_length = prefix_length;
plugin->ls_format = ls_format;
plugin->ls_unformat = ls_unformat;
plugin->creation = creation_fn;
plugin->removal = removal_fn;
clib_memcpy (&plugin->dpo, dpo, sizeof (dpo_type_t));
plugin->function_name = format (0, "%s%c", fn_name, 0);
plugin->keyword_str = format (0, "%s%c", keyword_str, 0);
plugin->def_str = format (0, "%s%c", def_str, 0);
plugin->params_str = format (0, "%s%c", params_str, 0);
return plugin->sr_policy_function_number;
}
/**
* @brief CLI function to 'show' all available SR LocalSID behaviors
*/
static clib_error_t *
show_sr_policy_behaviors_command_fn (vlib_main_t * vm,
unformat_input_t * input,
vlib_cli_command_t * cmd)
{
ip6_sr_main_t *sm = &sr_main;
sr_policy_fn_registration_t *plugin;
sr_policy_fn_registration_t **plugins_vec = 0;
int i;
vlib_cli_output (vm, "SR Policy behaviors:\n-----------------------\n\n");
/* *INDENT-OFF* */
pool_foreach (plugin, sm->policy_plugin_functions)
{ vec_add1 (plugins_vec, plugin); }
/* *INDENT-ON* */
vlib_cli_output (vm, "Plugin behaviors:\n");
for (i = 0; i < vec_len (plugins_vec); i++)
{
plugin = plugins_vec[i];
vlib_cli_output (vm, "\t%s\t-> %s.\n", plugin->keyword_str,
plugin->def_str);
vlib_cli_output (vm, "\t\tParameters: '%s'\n", plugin->params_str);
}
return 0;
}
/* *INDENT-OFF* */
VLIB_CLI_COMMAND (show_sr_policy_behaviors_command, static) = {
.path = "show sr policy behaviors",
.short_help = "show sr policy behaviors",
.function = show_sr_policy_behaviors_command_fn,
};
/* *INDENT-ON* */
/*************************** SR Segment Lists DPOs ****************************/
static u8 *
format_sr_segment_list_dpo (u8 * s, va_list * args)
{
ip6_sr_main_t *sm = &sr_main;
ip6_address_t *addr;
ip6_sr_sl_t *sl;
index_t index = va_arg (*args, index_t);
CLIB_UNUSED (u32 indent) = va_arg (*args, u32);
s = format (s, "SR: Segment List index:[%d]", index);
s = format (s, "\n\tSegments:");
sl = pool_elt_at_index (sm->sid_lists, index);
s = format (s, "< ");
vec_foreach (addr, sl->segments)
{
s = format (s, "%U, ", format_ip6_address, addr);
}
s = format (s, "\b\b > - ");
s = format (s, "Weight: %u", sl->weight);
return s;
}
const static dpo_vft_t sr_policy_rewrite_vft = {
.dv_lock = sr_dpo_lock,
.dv_unlock = sr_dpo_unlock,
.dv_format = format_sr_segment_list_dpo,
};
const static char *const sr_pr_encaps_ip6_nodes[] = {
"sr-pl-rewrite-encaps",
NULL,
};
const static char *const sr_pr_encaps_ip4_nodes[] = {
"sr-pl-rewrite-encaps-v4",
NULL,
};
const static char *const *const sr_pr_encaps_nodes[DPO_PROTO_NUM] = {
[DPO_PROTO_IP6] = sr_pr_encaps_ip6_nodes,
[DPO_PROTO_IP4] = sr_pr_encaps_ip4_nodes,
};
const static char *const sr_pr_insert_ip6_nodes[] = {
"sr-pl-rewrite-insert",
NULL,
};
const static char *const *const sr_pr_insert_nodes[DPO_PROTO_NUM] = {
[DPO_PROTO_IP6] = sr_pr_insert_ip6_nodes,
};
const static char *const sr_pr_bsid_insert_ip6_nodes[] = {
"sr-pl-rewrite-b-insert",
NULL,
};
const static char *const *const sr_pr_bsid_insert_nodes[DPO_PROTO_NUM] = {
[DPO_PROTO_IP6] = sr_pr_bsid_insert_ip6_nodes,
};
const static char *const sr_pr_bsid_encaps_ip6_nodes[] = {
"sr-pl-rewrite-b-encaps",
NULL,
};
const static char *const *const sr_pr_bsid_encaps_nodes[DPO_PROTO_NUM] = {
[DPO_PROTO_IP6] = sr_pr_bsid_encaps_ip6_nodes,
};
/********************* SR Policy Rewrite initialization ***********************/
/**
* @brief SR Policy Rewrite initialization
*/
clib_error_t *
sr_policy_rewrite_init (vlib_main_t * vm)
{
ip6_sr_main_t *sm = &sr_main;
/* Init memory for sr policy keys (bsid <-> ip6_address_t) */
mhash_init (&sm->sr_policies_index_hash, sizeof (uword),
sizeof (ip6_address_t));
/* Init SR VPO DPOs type */
sr_pr_encaps_dpo_type =
dpo_register_new_type (&sr_policy_rewrite_vft, sr_pr_encaps_nodes);
sr_pr_insert_dpo_type =
dpo_register_new_type (&sr_policy_rewrite_vft, sr_pr_insert_nodes);
sr_pr_bsid_encaps_dpo_type =
dpo_register_new_type (&sr_policy_rewrite_vft, sr_pr_bsid_encaps_nodes);
sr_pr_bsid_insert_dpo_type =
dpo_register_new_type (&sr_policy_rewrite_vft, sr_pr_bsid_insert_nodes);
/* Register the L2 encaps node used in HW redirect */
sm->l2_sr_policy_rewrite_index = sr_policy_rewrite_encaps_node.index;
sm->fib_table_ip6 = (u32) ~ 0;
sm->fib_table_ip4 = (u32) ~ 0;
return 0;
}
VLIB_INIT_FUNCTION (sr_policy_rewrite_init);
/*
* fd.io coding-style-patch-verification: ON
*
* Local Variables:
* eval: (c-set-style "gnu")
* End:
*/
| 30.960055 | 87 | 0.659236 | [
"object",
"vector"
] |
fdbff90be9f763aa31550be4c6b2e94eae81fb1e | 2,186 | h | C | include/ARFFWriter.h | scanavan/GestureRecognition | f0761978b8f1a85544151adb1f1e30f3a9070984 | [
"MIT"
] | 2 | 2016-11-06T15:11:23.000Z | 2017-03-09T01:00:01.000Z | include/ARFFWriter.h | SRI2016/GestureRecognition | f0761978b8f1a85544151adb1f1e30f3a9070984 | [
"MIT"
] | null | null | null | include/ARFFWriter.h | SRI2016/GestureRecognition | f0761978b8f1a85544151adb1f1e30f3a9070984 | [
"MIT"
] | 3 | 2016-10-26T00:41:15.000Z | 2019-05-13T13:30:16.000Z | #ifndef ARFFWRITER_H
#define ARFFWRITER_H
#include "LeapData.h"
#include "KinectMotion.h"
class ARFFWriter {
public:
ARFFWriter(std::string path, std::vector<LeapData> data);
ARFFWriter(std::string path, std::vector<KinectMotion> data);
ARFFWriter(std::string path, std::vector<LeapData> data, bool val);
std::string getNumFingers(LeapData leap);
std::string getFingertipDist(LeapData leap);
std::string getFingertipInterDist(LeapData leap);
std::string getFingertipPosition(LeapData leap);
std::string getHandDirection(LeapData leap);
std::string getHandSphereCenter(LeapData leap);
std::string getHandSphereRadius(LeapData leap);
std::string getPalmNormal(LeapData leap);
std::string getPalmPosition(LeapData leap);
std::string getPalmPositionRefined(LeapData leap);
std::string getPalmVelocity(LeapData leap);
std::string getRotationAngle(LeapData leap);
std::string getRotationAxis(LeapData leap);
std::string getRotationMatrix(LeapData leap);
std::string getRotationProbability(LeapData leap);
std::string getTranslation(LeapData leap);
std::string getTranslationProbability(LeapData leap);
std::string getFingertipDistRefined(LeapData leap);
std::string ARFFWriter::getFingerDirection(LeapData leap);
//new attributes
std::string getNewScaleFactor(LeapData leap);
std::string getNewFingertipDistRefined(LeapData leap);
std::string getFingertipAngles(LeapData leap);
std::string getProjectionPoints(LeapData leap);
std::string getFingertipElevation(LeapData leap);
std::string getGesture(LeapData leap);
std::string getFingersExtends(LeapData leap);
std::string getFingersArea(LeapData leap);
std::string getRatio(LeapData leap);
std::string getMax_X(LeapData leap);
std::string getMax_Y(LeapData leap);
std::string getFingerAngles(LeapData leap);
std::string getSil(KinectMotion depth);
std::string getContourDist(KinectMotion depth);
std::string getHull(KinectMotion depth);
std::string getOccNonz(KinectMotion depth);
std::string getOccAvg(KinectMotion depth);
std::string getFingerAngle(KinectMotion depth);
std::string getFingerDist(KinectMotion depth);
std::string getGesture(KinectMotion kinect);
};
#endif // !ARFFWRITER_H
| 37.050847 | 68 | 0.795517 | [
"vector"
] |
fdbffcf32541052c1752f96d077b4d2b26a71378 | 599 | h | C | ZzbGameSDK/Classes/ZzbKindTemplate1Cell.h | guixingyu/ZzbGameSDK | ec1e833106b41d88906263008a0121788de0c224 | [
"MIT"
] | 2 | 2019-12-09T02:04:55.000Z | 2019-12-09T02:05:04.000Z | ZzbGameSDK/Classes/ZzbKindTemplate1Cell.h | guixingyu/ZzbGameSDK | ec1e833106b41d88906263008a0121788de0c224 | [
"MIT"
] | null | null | null | ZzbGameSDK/Classes/ZzbKindTemplate1Cell.h | guixingyu/ZzbGameSDK | ec1e833106b41d88906263008a0121788de0c224 | [
"MIT"
] | null | null | null | //
// ZzbKindTemplate1Cell.h
// Pods
//
// Created by mywl on 2019/11/29.
//
#import <UIKit/UIKit.h>
#import "ZzbModuleListModel.h"
NS_ASSUME_NONNULL_BEGIN
@interface Template1View : UIView
@property (nonatomic, copy) void(^SelectionBlock)(ZzbShowAllModel *model);
@end
@interface ZzbKindTemplate1Cell : UITableViewCell
@property (nonatomic, copy) void(^ShowAllByModule)(NSInteger moduleid);
@property (nonatomic, copy) void(^SelectionBlock)(ZzbShowAllModel *model);
- (void)setStyleId:(NSInteger)_moduleid;
- (void)setModel:(NSArray<ZzbShowAllModel> *)applets;
@end
NS_ASSUME_NONNULL_END
| 22.185185 | 74 | 0.767947 | [
"model"
] |
fdc394d518784fdedf45678422d2e3ef8dca8a33 | 4,354 | h | C | src/gpe_editor/path_resource.h | Libertus-Lab/Game-Pencil-Engine | e173b127a7618de7deace7c59192a42fbc0dec02 | [
"MIT"
] | 89 | 2017-10-06T16:27:08.000Z | 2022-02-13T05:13:09.000Z | src/gpe_editor/path_resource.h | Libertus-Lab/Game-Pencil-Engine | e173b127a7618de7deace7c59192a42fbc0dec02 | [
"MIT"
] | 29 | 2017-10-08T22:39:19.000Z | 2021-03-21T05:06:21.000Z | src/gpe_editor/path_resource.h | Libertus-Lab/Game-Pencil-Engine | e173b127a7618de7deace7c59192a42fbc0dec02 | [
"MIT"
] | 17 | 2017-10-06T05:16:48.000Z | 2022-01-21T22:20:54.000Z | /*
path_resource.h
This file is part of:
GAME PENCIL ENGINE
https://www.pawbyte.com/gamepencilengine
Copyright (c) 2014-2021 Nathan Hurde, Chase Lee.
Copyright (c) 2014-2021 PawByte LLC.
Copyright (c) 2014-2021 Game Pencil Engine contributors ( Contributors Page )
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.
-Game Pencil Engine <https://www.pawbyte.com/gamepencilengine>
*/
#ifndef GPE_PATH_RESOURCE_H
#define GPE_PATH_RESOURCE_H
#include "gpe_basic_resource_page.h"
#include "game_scene_resource.h"
#include "../gpe/gpe_path2d.h"
class gamePathResource: public standardEditableGameResource
{
public:
int pointPos;
int selectedPointPos;
gpe::game_path_point2d * selectedPathPoint;
pawgui::widget_input_number * currentPointX;
pawgui::widget_input_number * currentPointY;
pawgui::widget_input_number * currentPointSpeed;
gpe::shape_rect sceneEditorView;
gpe::shape_rect scenePreviewRect;
gpe::shape_rect sceneRect;
gpe::shape_rect editorCommentPane;
pawgui::widget_drop_down_resource_menu * sceneToPreview;
pawgui::widget_dropdown_menu * sceneZoomLevel;
float zoomValue;
std::vector < gpe::game_path_point2d * > pathPoints;
pawgui::widget_selectbox * pathOptions;
pawgui::widget_button_icon * point_settingsButtton;
pawgui::widget_button_icon * pointRemove_button;
pawgui::widget_button_icon * pointMoveUpButtton;
pawgui::widget_button_icon * pointMoveDown_button;
gpe::color * pathLineColor;
gpe::color * pathPointColor;
pawgui::widget_checkbox * pathTypeIsClosed;
pawgui::widget_radio_button_controller * pathShapeType;
bool scnPostProcessed;
pawgui::widget_scrollbar_xaxis * sceneXScroll;
pawgui::widget_scrollbar_yaxis * sceneYScroll;
bool areaIsScrollable;
pawgui::widget_panel_list * bottomPaneList;
gamePathResource(pawgui::widget_resource_container * pFolder = nullptr);
~gamePathResource();
gpe::game_path_point2d * add_point( int point_x, int point_y, float pointSpeed = 1);
bool build_intohtml5_file(std::ofstream * fileTarget, int leftTabAmount = 0);
bool build_intocpp_file(std::ofstream * fileTarget, int leftTabAmount = 0);
void clear_points();
void compile_cpp();
bool export_and_play_native( bool launchProgram = true);
bool get_mouse_coords( gpe::shape_rect * view_space = nullptr, gpe::shape_rect * cam = nullptr);
void handle_scrolling();
bool is_build_ready();
void integrate_into_syntax();
bool include_local_files( std::string pBuildDir , int buildType );
void open_code(int lineNumb, int colNumb, std::string codeTitle = "" );
void prerender_self( );
void load_resource(std::string file_path = "");
void process_self( gpe::shape_rect * view_space = nullptr, gpe::shape_rect * cam = nullptr);
bool remove_point( int pointId );
void render_self( gpe::shape_rect * view_space = nullptr, gpe::shape_rect * cam = nullptr);
void save_resource(std::string file_path = "", int backupId = -1);
int search_for_string(std::string needle);
int search_and_replace_string(std::string needle, std::string newStr = "");
void update_project_layers();
bool write_data_into_projectfile(std::ofstream * fileTarget, int nestedFoldersIn = 0);
};
#endif
| 43.108911 | 101 | 0.744603 | [
"vector"
] |
fdc8f71c23299c1f3e385d3385ab8d8bf4ffc92b | 2,756 | h | C | VTK/ThirdParty/vtkm/vtk-m/vtkm/rendering/raytracing/VolumeRendererStructured.h | brown-ccv/paraview-scalable | 64b221a540737d2ac94a120039bd8d1e661bdc8f | [
"Apache-2.0",
"BSD-3-Clause"
] | 1 | 2021-10-03T16:47:04.000Z | 2021-10-03T16:47:04.000Z | VTK/ThirdParty/vtkm/vtk-m/vtkm/rendering/raytracing/VolumeRendererStructured.h | brown-ccv/paraview-scalable | 64b221a540737d2ac94a120039bd8d1e661bdc8f | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | VTK/ThirdParty/vtkm/vtk-m/vtkm/rendering/raytracing/VolumeRendererStructured.h | brown-ccv/paraview-scalable | 64b221a540737d2ac94a120039bd8d1e661bdc8f | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | //=============================================================================
//
// Copyright (c) Kitware, Inc.
// All rights reserved.
// See LICENSE.txt for details.
//
// This software is distributed WITHOUT ANY WARRANTY; without even
// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the above copyright notice for more information.
//
// Copyright 2016 National Technology & Engineering Solutions of Sandia, LLC (NTESS).
// Copyright 2016 UT-Battelle, LLC.
// Copyright 2016 Los Alamos National Security.
//
// Under the terms of Contract DE-NA0003525 with NTESS,
// the U.S. Government retains certain rights in this software.
// Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National
// Laboratory (LANL), the U.S. Government retains certain rights in
// this software.
//
//=============================================================================
#ifndef vtk_m_rendering_raytracing_VolumeRendererStructured_h
#define vtk_m_rendering_raytracing_VolumeRendererStructured_h
#include <vtkm/cont/DataSet.h>
#include <vtkm/rendering/raytracing/Ray.h>
namespace vtkm
{
namespace rendering
{
namespace raytracing
{
class VolumeRendererStructured
{
public:
using DefaultHandle = vtkm::cont::ArrayHandle<vtkm::FloatDefault>;
using CartesianArrayHandle =
vtkm::cont::ArrayHandleCartesianProduct<DefaultHandle, DefaultHandle, DefaultHandle>;
VTKM_CONT
VolumeRendererStructured();
VTKM_CONT
void EnableCompositeBackground();
VTKM_CONT
void DisableCompositeBackground();
VTKM_CONT
void SetColorMap(const vtkm::cont::ArrayHandle<vtkm::Vec<vtkm::Float32, 4>>& colorMap);
VTKM_CONT
void SetData(const vtkm::cont::CoordinateSystem& coords,
const vtkm::cont::Field& scalarField,
const vtkm::cont::CellSetStructured<3>& cellset,
const vtkm::Range& scalarRange);
VTKM_CONT
void Render(vtkm::rendering::raytracing::Ray<vtkm::Float32>& rays);
//VTKM_CONT
///void Render(vtkm::rendering::raytracing::Ray<vtkm::Float64>& rays);
VTKM_CONT
void SetSampleDistance(const vtkm::Float32& distance);
protected:
template <typename Precision, typename Device>
VTKM_CONT void RenderOnDevice(vtkm::rendering::raytracing::Ray<Precision>& rays, Device);
template <typename Precision>
struct RenderFunctor;
bool IsSceneDirty;
bool IsUniformDataSet;
vtkm::Bounds SpatialExtent;
vtkm::cont::ArrayHandleVirtualCoordinates Coordinates;
vtkm::cont::CellSetStructured<3> Cellset;
const vtkm::cont::Field* ScalarField;
vtkm::cont::ArrayHandle<vtkm::Vec<vtkm::Float32, 4>> ColorMap;
vtkm::Float32 SampleDistance;
vtkm::Range ScalarRange;
};
}
}
} //namespace vtkm::rendering::raytracing
#endif
| 30.285714 | 91 | 0.706459 | [
"render"
] |
fdcaaf4788a36bdb66b2dc6064f04f721a691456 | 8,646 | c | C | src/liblsquic/lsquic_malo.c | vbajpai/lsquic-client | b131edfebabc0fef22f6042b7519db382fa097f8 | [
"BSD-3-Clause",
"MIT"
] | null | null | null | src/liblsquic/lsquic_malo.c | vbajpai/lsquic-client | b131edfebabc0fef22f6042b7519db382fa097f8 | [
"BSD-3-Clause",
"MIT"
] | null | null | null | src/liblsquic/lsquic_malo.c | vbajpai/lsquic-client | b131edfebabc0fef22f6042b7519db382fa097f8 | [
"BSD-3-Clause",
"MIT"
] | 1 | 2019-12-12T12:26:24.000Z | 2019-12-12T12:26:24.000Z | /* Copyright (c) 2017 - 2018 LiteSpeed Technologies Inc. See LICENSE. */
/*
* lsquic_malo.c -- malo allocator implementation.
*
* The malo allocator is a pool of objects of fixed size. It tries to
* allocate and deallocate objects as fast as possible. To do so, it
* does the following:
*
* 1. Allocations occur 4 KB at a time.
* 2. No division or multiplication operations are performed.
*
* (In recent testing, malo was about 2.7 times faster than malloc for
* 64-byte objects.)
*
* Besides speed, two other important characteristics distinguish it
* from other pool allocators:
*
* 1. To free (put) an object, one does not need a pointer to the malo
* object. This makes this allocator easy to use.
* 2. A built-in iterator is provided to iterate over all allocated
* objects (with ability to safely release objects while iterator
* is active). This may be useful in some circumstances.
*
* To gain all these advantages, there are trade-offs:
*
* 1. There are two memory penalties:
* a. Per object overhead. To avoid division and multiplication,
* the object sizes is rounded up to the nearest power or two,
* starting with 64 bytes (minumum) and up to 2 KB (maximum).
* Thus, a 104-byte object will have a 24-byte overhead; a
* 130-byte object will have 126-byte overhead. This is
* something to keep in mind.
* b. Per page overhead. Page links occupy some bytes in the
* page. To keep things fast, at least one slot per page is
* always occupied, independent of object size. Thus, for a
* 1 KB object size, 25% of the page is used for the page
* header.
* 2. 4 KB pages are not freed until the malo allocator is destroyed.
* This is something to keep in mind.
*
* P.S. In Russian, "malo" (мало) means "little" or "few". Thus, the
* malo allocator aims to perform its job in as few CPU cycles as
* possible.
*/
#include <assert.h>
#include <errno.h>
#include <stdint.h>
#include <stdlib.h>
#include <sys/queue.h>
#ifdef WIN32
#include <vc_compat.h>
#endif
#include "fiu-local.h"
#include "lsquic_malo.h"
/* 64 slots in a 4KB page means that the smallest object is 64 bytes.
* The largest object is 2KB.
*/
#define MALO_MIN_NBITS 6
#define MALO_MAX_NBITS 11
/* A "free page" is a page with free slots available.
*/
static unsigned find_free_slot (uint64_t slots);
static unsigned size_in_bits (size_t sz);
struct malo_page {
SLIST_ENTRY(malo_page) next_page;
LIST_ENTRY(malo_page) next_free_page;
struct malo *malo;
uint64_t slots,
full_slot_mask;
unsigned nbits;
unsigned initial_slot;
};
typedef char malo_header_fits_in_one_slot
[(sizeof(struct malo_page) > (1 << MALO_MAX_NBITS)) ? -1 : 1];
struct malo {
struct malo_page page_header;
SLIST_HEAD(, malo_page) all_pages;
LIST_HEAD(, malo_page) free_pages;
struct {
struct malo_page *cur_page;
unsigned next_slot;
} iter;
};
struct malo *
lsquic_malo_create (size_t obj_size)
{
unsigned nbits = size_in_bits(obj_size);
if (nbits < MALO_MIN_NBITS)
nbits = MALO_MIN_NBITS;
else if (nbits > MALO_MAX_NBITS)
{
errno = EOVERFLOW;
return NULL;
}
struct malo *malo;
if (0 != posix_memalign((void **) &malo, 0x1000, 0x1000))
return NULL;
SLIST_INIT(&malo->all_pages);
LIST_INIT(&malo->free_pages);
malo->iter.cur_page = &malo->page_header;
malo->iter.next_slot = 0;
int n_slots = sizeof(*malo) / (1 << nbits)
+ ((sizeof(*malo) % (1 << nbits)) > 0);
struct malo_page *const page = &malo->page_header;
SLIST_INSERT_HEAD(&malo->all_pages, page, next_page);
LIST_INSERT_HEAD(&malo->free_pages, page, next_free_page);
page->malo = malo;
if (nbits == MALO_MIN_NBITS)
page->full_slot_mask = ~0ULL;
else
page->full_slot_mask = (1ULL << (1 << (12 - nbits))) - 1;
page->slots = (1ULL << n_slots) - 1;
page->nbits = nbits;
page->initial_slot = n_slots;
return malo;
}
static struct malo_page *
allocate_page (struct malo *malo)
{
struct malo_page *page;
if (0 != posix_memalign((void **) &page, 0x1000, 0x1000))
return NULL;
SLIST_INSERT_HEAD(&malo->all_pages, page, next_page);
LIST_INSERT_HEAD(&malo->free_pages, page, next_free_page);
page->slots = 1;
page->full_slot_mask = malo->page_header.full_slot_mask;
page->nbits = malo->page_header.nbits;
page->malo = malo;
page->initial_slot = 1;
return page;
}
#define FAIL_NOMEM do { errno = ENOMEM; return NULL; } while (0)
/* Get a new object. */
void *
lsquic_malo_get (struct malo *malo)
{
fiu_do_on("malo/get", FAIL_NOMEM);
struct malo_page *page = LIST_FIRST(&malo->free_pages);
if (!page)
{
page = allocate_page(malo);
if (!page)
return NULL;
}
unsigned slot = find_free_slot(page->slots);
page->slots |= (1ULL << slot);
if (page->full_slot_mask == page->slots)
LIST_REMOVE(page, next_free_page);
return (char *) page + (slot << page->nbits);
}
/* Return obj to the pool */
void
lsquic_malo_put (void *obj)
{
uintptr_t page_addr = (uintptr_t) obj & ~((1 << 12) - 1);
struct malo_page *page = (void *) page_addr;
unsigned slot = ((uintptr_t) obj - page_addr) >> page->nbits;
if (page->full_slot_mask == page->slots)
LIST_INSERT_HEAD(&page->malo->free_pages, page, next_free_page);
page->slots &= ~(1ULL << slot);
}
void
lsquic_malo_destroy (struct malo *malo)
{
struct malo_page *page, *next;
page = SLIST_FIRST(&malo->all_pages);
while (page != &malo->page_header)
{
next = SLIST_NEXT(page, next_page);
#ifndef WIN32
free(page);
#else
_aligned_free(page);
#endif
page = next;
}
#ifndef WIN32
free(page);
#else
_aligned_free(page);
#endif
}
/* The iterator is built-in. Usage:
* void *obj;
* for (obj = lsquic_malo_first(malo); obj; lsquic_malo_next(malo))
* do_stuff(obj);
*/
void *
lsquic_malo_first (struct malo *malo)
{
malo->iter.cur_page = SLIST_FIRST(&malo->all_pages);
malo->iter.next_slot = malo->iter.cur_page->initial_slot;
return lsquic_malo_next(malo);
}
void *
lsquic_malo_next (struct malo *malo)
{
struct malo_page *page;
unsigned max_slot, slot;
page = malo->iter.cur_page;
if (page)
{
max_slot = 1 << (12 - page->nbits); /* Same for all pages */
slot = malo->iter.next_slot;
while (1)
{
for (; slot < max_slot; ++slot)
{
if (page->slots & (1ULL << slot))
{
malo->iter.cur_page = page;
malo->iter.next_slot = slot + 1;
return (char *) page + (slot << page->nbits);
}
}
page = SLIST_NEXT(page, next_page);
if (page)
slot = page->initial_slot;
else
{
malo->iter.cur_page = NULL; /* Stop iterator */
return NULL;
}
}
}
return NULL;
}
static unsigned
size_in_bits (size_t sz)
{
#if __GNUC__
unsigned clz = __builtin_clz(sz - 1);
return 32 - clz;
#else
unsigned clz;
size_t y;
--sz;
clz = 32;
y = sz >> 16; if (y) { clz -= 16; sz = y; }
y = sz >> 8; if (y) { clz -= 8; sz = y; }
y = sz >> 4; if (y) { clz -= 4; sz = y; }
y = sz >> 2; if (y) { clz -= 2; sz = y; }
y = sz >> 1; if (y) return 32 - clz + 1;
return 32 - clz + sz;
#endif
}
static unsigned
find_free_slot (uint64_t slots)
{
#if __GNUC__
return __builtin_ffsll(~slots) - 1;
#else
unsigned n;
slots =~ slots;
n = 0;
if (0 == (slots & ((1ULL << 32) - 1))) { n += 32; slots >>= 32; }
if (0 == (slots & ((1ULL << 16) - 1))) { n += 16; slots >>= 16; }
if (0 == (slots & ((1ULL << 8) - 1))) { n += 8; slots >>= 8; }
if (0 == (slots & ((1ULL << 4) - 1))) { n += 4; slots >>= 4; }
if (0 == (slots & ((1ULL << 2) - 1))) { n += 2; slots >>= 2; }
if (0 == (slots & ((1ULL << 1) - 1))) { n += 1; slots >>= 1; }
return n;
#endif
}
size_t
lsquic_malo_mem_used (const struct malo *malo)
{
const struct malo_page *page;
size_t size;
size = 0;
SLIST_FOREACH(page, &malo->all_pages, next_page)
size += sizeof(*page);
return size;
}
| 27.447619 | 73 | 0.590331 | [
"object"
] |
fdd226ba79a9d93bcda86f81a587bf712ed07dc1 | 51,329 | c | C | src/feature/hs/hs_circuit.c | Ademaove/tor | 6b0a40c81eddc1ab79ad71947f85a92206947c81 | [
"BSD-2-Clause-NetBSD"
] | 1 | 2020-03-10T20:15:25.000Z | 2020-03-10T20:15:25.000Z | src/feature/hs/hs_circuit.c | Ademaove/tor | 6b0a40c81eddc1ab79ad71947f85a92206947c81 | [
"BSD-2-Clause-NetBSD"
] | null | null | null | src/feature/hs/hs_circuit.c | Ademaove/tor | 6b0a40c81eddc1ab79ad71947f85a92206947c81 | [
"BSD-2-Clause-NetBSD"
] | null | null | null | /* Copyright (c) 2017-2020, The Tor Project, Inc. */
/* See LICENSE for licensing information */
/**
* \file hs_circuit.c
**/
#define HS_CIRCUIT_PRIVATE
#include "core/or/or.h"
#include "app/config/config.h"
#include "core/crypto/hs_ntor.h"
#include "core/or/circuitbuild.h"
#include "core/or/circuitlist.h"
#include "core/or/circuituse.h"
#include "core/or/policies.h"
#include "core/or/relay.h"
#include "core/or/crypt_path.h"
#include "feature/client/circpathbias.h"
#include "feature/hs/hs_cell.h"
#include "feature/hs/hs_circuit.h"
#include "feature/hs/hs_ob.h"
#include "feature/hs/hs_circuitmap.h"
#include "feature/hs/hs_client.h"
#include "feature/hs/hs_ident.h"
#include "feature/hs/hs_service.h"
#include "feature/nodelist/describe.h"
#include "feature/nodelist/nodelist.h"
#include "feature/rend/rendservice.h"
#include "feature/rend/rendclient.h"
#include "feature/stats/rephist.h"
#include "lib/crypt_ops/crypto_dh.h"
#include "lib/crypt_ops/crypto_rand.h"
#include "lib/crypt_ops/crypto_util.h"
/* Trunnel. */
#include "trunnel/ed25519_cert.h"
#include "trunnel/hs/cell_common.h"
#include "trunnel/hs/cell_establish_intro.h"
#include "core/or/cpath_build_state_st.h"
#include "core/or/crypt_path_st.h"
#include "feature/nodelist/node_st.h"
#include "core/or/origin_circuit_st.h"
/** A circuit is about to become an e2e rendezvous circuit. Check
* <b>circ_purpose</b> and ensure that it's properly set. Return true iff
* circuit purpose is properly set, otherwise return false. */
static int
circuit_purpose_is_correct_for_rend(unsigned int circ_purpose,
int is_service_side)
{
if (is_service_side) {
if (circ_purpose != CIRCUIT_PURPOSE_S_CONNECT_REND) {
log_warn(LD_BUG,
"HS e2e circuit setup with wrong purpose (%d)", circ_purpose);
return 0;
}
}
if (!is_service_side) {
if (circ_purpose != CIRCUIT_PURPOSE_C_REND_READY &&
circ_purpose != CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED) {
log_warn(LD_BUG,
"Client e2e circuit setup with wrong purpose (%d)", circ_purpose);
return 0;
}
}
return 1;
}
/** Create and return a crypt path for the final hop of a v3 prop224 rendezvous
* circuit. Initialize the crypt path crypto using the output material from the
* ntor key exchange at <b>ntor_key_seed</b>.
*
* If <b>is_service_side</b> is set, we are the hidden service and the final
* hop of the rendezvous circuit is the client on the other side. */
static crypt_path_t *
create_rend_cpath(const uint8_t *ntor_key_seed, size_t seed_len,
int is_service_side)
{
uint8_t keys[HS_NTOR_KEY_EXPANSION_KDF_OUT_LEN];
crypt_path_t *cpath = NULL;
/* Do the key expansion */
if (hs_ntor_circuit_key_expansion(ntor_key_seed, seed_len,
keys, sizeof(keys)) < 0) {
goto err;
}
/* Setup the cpath */
cpath = tor_malloc_zero(sizeof(crypt_path_t));
cpath->magic = CRYPT_PATH_MAGIC;
if (cpath_init_circuit_crypto(cpath, (char*)keys, sizeof(keys),
is_service_side, 1) < 0) {
tor_free(cpath);
goto err;
}
err:
memwipe(keys, 0, sizeof(keys));
return cpath;
}
/** We are a v2 legacy HS client: Create and return a crypt path for the hidden
* service on the other side of the rendezvous circuit <b>circ</b>. Initialize
* the crypt path crypto using the body of the RENDEZVOUS1 cell at
* <b>rend_cell_body</b> (which must be at least DH1024_KEY_LEN+DIGEST_LEN
* bytes).
*/
static crypt_path_t *
create_rend_cpath_legacy(origin_circuit_t *circ, const uint8_t *rend_cell_body)
{
crypt_path_t *hop = NULL;
char keys[DIGEST_LEN+CPATH_KEY_MATERIAL_LEN];
/* first DH1024_KEY_LEN bytes are g^y from the service. Finish the dh
* handshake...*/
tor_assert(circ->build_state);
tor_assert(circ->build_state->pending_final_cpath);
hop = circ->build_state->pending_final_cpath;
tor_assert(hop->rend_dh_handshake_state);
if (crypto_dh_compute_secret(LOG_PROTOCOL_WARN, hop->rend_dh_handshake_state,
(char*)rend_cell_body, DH1024_KEY_LEN,
keys, DIGEST_LEN+CPATH_KEY_MATERIAL_LEN)<0) {
log_warn(LD_GENERAL, "Couldn't complete DH handshake.");
goto err;
}
/* ... and set up cpath. */
if (cpath_init_circuit_crypto(hop,
keys+DIGEST_LEN, sizeof(keys)-DIGEST_LEN,
0, 0) < 0)
goto err;
/* Check whether the digest is right... */
if (tor_memneq(keys, rend_cell_body+DH1024_KEY_LEN, DIGEST_LEN)) {
log_warn(LD_PROTOCOL, "Incorrect digest of key material.");
goto err;
}
/* clean up the crypto stuff we just made */
crypto_dh_free(hop->rend_dh_handshake_state);
hop->rend_dh_handshake_state = NULL;
goto done;
err:
hop = NULL;
done:
memwipe(keys, 0, sizeof(keys));
return hop;
}
/** Append the final <b>hop</b> to the cpath of the rend <b>circ</b>, and mark
* <b>circ</b> ready for use to transfer HS relay cells. */
static void
finalize_rend_circuit(origin_circuit_t *circ, crypt_path_t *hop,
int is_service_side)
{
tor_assert(circ);
tor_assert(hop);
/* Notify the circuit state machine that we are splicing this circuit */
int new_circ_purpose = is_service_side ?
CIRCUIT_PURPOSE_S_REND_JOINED : CIRCUIT_PURPOSE_C_REND_JOINED;
circuit_change_purpose(TO_CIRCUIT(circ), new_circ_purpose);
/* All is well. Extend the circuit. */
hop->state = CPATH_STATE_OPEN;
/* Set the windows to default. */
hop->package_window = circuit_initial_package_window();
hop->deliver_window = CIRCWINDOW_START;
/* Now that this circuit has finished connecting to its destination,
* make sure circuit_get_open_circ_or_launch is willing to return it
* so we can actually use it. */
circ->hs_circ_has_timed_out = 0;
/* Append the hop to the cpath of this circuit */
cpath_extend_linked_list(&circ->cpath, hop);
/* In legacy code, 'pending_final_cpath' points to the final hop we just
* appended to the cpath. We set the original pointer to NULL so that we
* don't double free it. */
if (circ->build_state) {
circ->build_state->pending_final_cpath = NULL;
}
/* Finally, mark circuit as ready to be used for client streams */
if (!is_service_side) {
circuit_try_attaching_streams(circ);
}
}
/** For a given circuit and a service introduction point object, register the
* intro circuit to the circuitmap. This supports legacy intro point. */
static void
register_intro_circ(const hs_service_intro_point_t *ip,
origin_circuit_t *circ)
{
tor_assert(ip);
tor_assert(circ);
if (ip->base.is_only_legacy) {
hs_circuitmap_register_intro_circ_v2_service_side(circ,
ip->legacy_key_digest);
} else {
hs_circuitmap_register_intro_circ_v3_service_side(circ,
&ip->auth_key_kp.pubkey);
}
}
/** Return the number of opened introduction circuit for the given circuit that
* is matching its identity key. */
static unsigned int
count_opened_desc_intro_point_circuits(const hs_service_t *service,
const hs_service_descriptor_t *desc)
{
unsigned int count = 0;
tor_assert(service);
tor_assert(desc);
DIGEST256MAP_FOREACH(desc->intro_points.map, key,
const hs_service_intro_point_t *, ip) {
const circuit_t *circ;
const origin_circuit_t *ocirc = hs_circ_service_get_intro_circ(ip);
if (ocirc == NULL) {
continue;
}
circ = TO_CIRCUIT(ocirc);
tor_assert(circ->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO ||
circ->purpose == CIRCUIT_PURPOSE_S_INTRO);
/* Having a circuit not for the requested service is really bad. */
tor_assert(ed25519_pubkey_eq(&service->keys.identity_pk,
ô->hs_ident->identity_pk));
/* Only count opened circuit and skip circuit that will be closed. */
if (!circ->marked_for_close && circ->state == CIRCUIT_STATE_OPEN) {
count++;
}
} DIGEST256MAP_FOREACH_END;
return count;
}
/** From a given service, rendezvous cookie and handshake info, create a
* rendezvous point circuit identifier. This can't fail. */
STATIC hs_ident_circuit_t *
create_rp_circuit_identifier(const hs_service_t *service,
const uint8_t *rendezvous_cookie,
const curve25519_public_key_t *server_pk,
const hs_ntor_rend_cell_keys_t *keys)
{
hs_ident_circuit_t *ident;
uint8_t handshake_info[CURVE25519_PUBKEY_LEN + DIGEST256_LEN];
tor_assert(service);
tor_assert(rendezvous_cookie);
tor_assert(server_pk);
tor_assert(keys);
ident = hs_ident_circuit_new(&service->keys.identity_pk);
/* Copy the RENDEZVOUS_COOKIE which is the unique identifier. */
memcpy(ident->rendezvous_cookie, rendezvous_cookie,
sizeof(ident->rendezvous_cookie));
/* Build the HANDSHAKE_INFO which looks like this:
* SERVER_PK [32 bytes]
* AUTH_INPUT_MAC [32 bytes]
*/
memcpy(handshake_info, server_pk->public_key, CURVE25519_PUBKEY_LEN);
memcpy(handshake_info + CURVE25519_PUBKEY_LEN, keys->rend_cell_auth_mac,
DIGEST256_LEN);
tor_assert(sizeof(ident->rendezvous_handshake_info) ==
sizeof(handshake_info));
memcpy(ident->rendezvous_handshake_info, handshake_info,
sizeof(ident->rendezvous_handshake_info));
/* Finally copy the NTOR_KEY_SEED for e2e encryption on the circuit. */
tor_assert(sizeof(ident->rendezvous_ntor_key_seed) ==
sizeof(keys->ntor_key_seed));
memcpy(ident->rendezvous_ntor_key_seed, keys->ntor_key_seed,
sizeof(ident->rendezvous_ntor_key_seed));
return ident;
}
/** From a given service and service intro point, create an introduction point
* circuit identifier. This can't fail. */
static hs_ident_circuit_t *
create_intro_circuit_identifier(const hs_service_t *service,
const hs_service_intro_point_t *ip)
{
hs_ident_circuit_t *ident;
tor_assert(service);
tor_assert(ip);
ident = hs_ident_circuit_new(&service->keys.identity_pk);
ed25519_pubkey_copy(&ident->intro_auth_pk, &ip->auth_key_kp.pubkey);
return ident;
}
/** For a given introduction point and an introduction circuit, send the
* ESTABLISH_INTRO cell. The service object is used for logging. This can fail
* and if so, the circuit is closed and the intro point object is flagged
* that the circuit is not established anymore which is important for the
* retry mechanism. */
static void
send_establish_intro(const hs_service_t *service,
hs_service_intro_point_t *ip, origin_circuit_t *circ)
{
ssize_t cell_len;
uint8_t payload[RELAY_PAYLOAD_SIZE];
tor_assert(service);
tor_assert(ip);
tor_assert(circ);
/* Encode establish intro cell. */
cell_len = hs_cell_build_establish_intro(circ->cpath->prev->rend_circ_nonce,
&service->config, ip, payload);
if (cell_len < 0) {
log_warn(LD_REND, "Unable to encode ESTABLISH_INTRO cell for service %s "
"on circuit %u. Closing circuit.",
safe_str_client(service->onion_address),
TO_CIRCUIT(circ)->n_circ_id);
goto err;
}
/* Send the cell on the circuit. */
if (relay_send_command_from_edge(CONTROL_CELL_ID, TO_CIRCUIT(circ),
RELAY_COMMAND_ESTABLISH_INTRO,
(char *) payload, cell_len,
circ->cpath->prev) < 0) {
log_info(LD_REND, "Unable to send ESTABLISH_INTRO cell for service %s "
"on circuit %u.",
safe_str_client(service->onion_address),
TO_CIRCUIT(circ)->n_circ_id);
/* On error, the circuit has been closed. */
goto done;
}
/* Record the attempt to use this circuit. */
pathbias_count_use_attempt(circ);
goto done;
err:
circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_INTERNAL);
done:
memwipe(payload, 0, sizeof(payload));
}
/** Return a string constant describing the anonymity of service. */
static const char *
get_service_anonymity_string(const hs_service_t *service)
{
if (service->config.is_single_onion) {
return "single onion";
} else {
return "hidden";
}
}
/** For a given service, the ntor onion key and a rendezvous cookie, launch a
* circuit to the rendezvous point specified by the link specifiers. On
* success, a circuit identifier is attached to the circuit with the needed
* data. This function will try to open a circuit for a maximum value of
* MAX_REND_FAILURES then it will give up. */
MOCK_IMPL(STATIC void,
launch_rendezvous_point_circuit,(const hs_service_t *service,
const hs_service_intro_point_t *ip,
const hs_cell_introduce2_data_t *data))
{
int circ_needs_uptime;
time_t now = time(NULL);
extend_info_t *info = NULL;
origin_circuit_t *circ;
tor_assert(service);
tor_assert(ip);
tor_assert(data);
circ_needs_uptime = hs_service_requires_uptime_circ(service->config.ports);
/* Get the extend info data structure for the chosen rendezvous point
* specified by the given link specifiers. */
info = hs_get_extend_info_from_lspecs(data->link_specifiers,
&data->onion_pk,
service->config.is_single_onion);
if (info == NULL) {
/* We are done here, we can't extend to the rendezvous point. */
log_fn(LOG_PROTOCOL_WARN, LD_REND,
"Not enough info to open a circuit to a rendezvous point for "
"%s service %s.",
get_service_anonymity_string(service),
safe_str_client(service->onion_address));
goto end;
}
for (int i = 0; i < MAX_REND_FAILURES; i++) {
int circ_flags = CIRCLAUNCH_NEED_CAPACITY | CIRCLAUNCH_IS_INTERNAL;
if (circ_needs_uptime) {
circ_flags |= CIRCLAUNCH_NEED_UPTIME;
}
/* Firewall and policies are checked when getting the extend info.
*
* We only use a one-hop path on the first attempt. If the first attempt
* fails, we use a 3-hop path for reachability / reliability.
* See the comment in retry_service_rendezvous_point() for details. */
if (service->config.is_single_onion && i == 0) {
circ_flags |= CIRCLAUNCH_ONEHOP_TUNNEL;
}
circ = circuit_launch_by_extend_info(CIRCUIT_PURPOSE_S_CONNECT_REND, info,
circ_flags);
if (circ != NULL) {
/* Stop retrying, we have a circuit! */
break;
}
}
if (circ == NULL) {
log_warn(LD_REND, "Giving up on launching a rendezvous circuit to %s "
"for %s service %s",
safe_str_client(extend_info_describe(info)),
get_service_anonymity_string(service),
safe_str_client(service->onion_address));
goto end;
}
log_info(LD_REND, "Rendezvous circuit launched to %s with cookie %s "
"for %s service %s",
safe_str_client(extend_info_describe(info)),
safe_str_client(hex_str((const char *) data->rendezvous_cookie,
REND_COOKIE_LEN)),
get_service_anonymity_string(service),
safe_str_client(service->onion_address));
tor_assert(circ->build_state);
/* Rendezvous circuit have a specific timeout for the time spent on trying
* to connect to the rendezvous point. */
circ->build_state->expiry_time = now + MAX_REND_TIMEOUT;
/* Create circuit identifier and key material. */
{
hs_ntor_rend_cell_keys_t keys;
curve25519_keypair_t ephemeral_kp;
/* No need for extra strong, this is only for this circuit life time. This
* key will be used for the RENDEZVOUS1 cell that will be sent on the
* circuit once opened. */
curve25519_keypair_generate(&ephemeral_kp, 0);
if (hs_ntor_service_get_rendezvous1_keys(&ip->auth_key_kp.pubkey,
&ip->enc_key_kp,
&ephemeral_kp, &data->client_pk,
&keys) < 0) {
/* This should not really happened but just in case, don't make tor
* freak out, close the circuit and move on. */
log_info(LD_REND, "Unable to get RENDEZVOUS1 key material for "
"service %s",
safe_str_client(service->onion_address));
circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_INTERNAL);
goto end;
}
circ->hs_ident = create_rp_circuit_identifier(service,
data->rendezvous_cookie,
&ephemeral_kp.pubkey, &keys);
memwipe(&ephemeral_kp, 0, sizeof(ephemeral_kp));
memwipe(&keys, 0, sizeof(keys));
tor_assert(circ->hs_ident);
}
end:
extend_info_free(info);
}
/** Return true iff the given service rendezvous circuit circ is allowed for a
* relaunch to the rendezvous point. */
static int
can_relaunch_service_rendezvous_point(const origin_circuit_t *circ)
{
tor_assert(circ);
/* This is initialized when allocating an origin circuit. */
tor_assert(circ->build_state);
tor_assert(TO_CIRCUIT(circ)->purpose == CIRCUIT_PURPOSE_S_CONNECT_REND);
/* XXX: Retrying under certain condition. This is related to #22455. */
/* Avoid to relaunch twice a circuit to the same rendezvous point at the
* same time. */
if (circ->hs_service_side_rend_circ_has_been_relaunched) {
log_info(LD_REND, "Rendezvous circuit to %s has already been retried. "
"Skipping retry.",
safe_str_client(
extend_info_describe(circ->build_state->chosen_exit)));
goto disallow;
}
/* We check failure_count >= hs_get_service_max_rend_failures()-1 below, and
* the -1 is because we increment the failure count for our current failure
* *after* this clause. */
int max_rend_failures = hs_get_service_max_rend_failures() - 1;
/* A failure count that has reached maximum allowed or circuit that expired,
* we skip relaunching. */
if (circ->build_state->failure_count > max_rend_failures ||
circ->build_state->expiry_time <= time(NULL)) {
log_info(LD_REND, "Attempt to build a rendezvous circuit to %s has "
"failed with %d attempts and expiry time %ld. "
"Giving up building.",
safe_str_client(
extend_info_describe(circ->build_state->chosen_exit)),
circ->build_state->failure_count,
(long int) circ->build_state->expiry_time);
goto disallow;
}
/* Allowed to relaunch. */
return 1;
disallow:
return 0;
}
/** Retry the rendezvous point of circ by launching a new circuit to it. */
static void
retry_service_rendezvous_point(const origin_circuit_t *circ)
{
int flags = 0;
origin_circuit_t *new_circ;
cpath_build_state_t *bstate;
tor_assert(circ);
/* This is initialized when allocating an origin circuit. */
tor_assert(circ->build_state);
tor_assert(TO_CIRCUIT(circ)->purpose == CIRCUIT_PURPOSE_S_CONNECT_REND);
/* Ease our life. */
bstate = circ->build_state;
log_info(LD_REND, "Retrying rendezvous point circuit to %s",
safe_str_client(extend_info_describe(bstate->chosen_exit)));
/* Get the current build state flags for the next circuit. */
flags |= (bstate->need_uptime) ? CIRCLAUNCH_NEED_UPTIME : 0;
flags |= (bstate->need_capacity) ? CIRCLAUNCH_NEED_CAPACITY : 0;
flags |= (bstate->is_internal) ? CIRCLAUNCH_IS_INTERNAL : 0;
/* We do NOT add the onehop tunnel flag even though it might be a single
* onion service. The reason is that if we failed once to connect to the RP
* with a direct connection, we consider that chances are that we will fail
* again so try a 3-hop circuit and hope for the best. Because the service
* has no anonymity (single onion), this change of behavior won't affect
* security directly. */
new_circ = circuit_launch_by_extend_info(CIRCUIT_PURPOSE_S_CONNECT_REND,
bstate->chosen_exit, flags);
if (new_circ == NULL) {
log_warn(LD_REND, "Failed to launch rendezvous circuit to %s",
safe_str_client(extend_info_describe(bstate->chosen_exit)));
goto done;
}
/* Transfer build state information to the new circuit state in part to
* catch any other failures. */
new_circ->build_state->failure_count = bstate->failure_count+1;
new_circ->build_state->expiry_time = bstate->expiry_time;
new_circ->hs_ident = hs_ident_circuit_dup(circ->hs_ident);
done:
return;
}
/** Using the given descriptor intro point ip, the node of the
* rendezvous point rp_node and the service's subcredential, populate the
* already allocated intro1_data object with the needed key material and link
* specifiers.
*
* Return 0 on success or a negative value if we couldn't properly filled the
* introduce1 data from the RP node. In other word, it means the RP node is
* unusable to use in the introduction. */
static int
setup_introduce1_data(const hs_desc_intro_point_t *ip,
const node_t *rp_node,
const hs_subcredential_t *subcredential,
hs_cell_introduce1_data_t *intro1_data)
{
int ret = -1;
smartlist_t *rp_lspecs;
tor_assert(ip);
tor_assert(rp_node);
tor_assert(subcredential);
tor_assert(intro1_data);
/* Build the link specifiers from the node at the end of the rendezvous
* circuit that we opened for this introduction. */
rp_lspecs = node_get_link_specifier_smartlist(rp_node, 0);
if (smartlist_len(rp_lspecs) == 0) {
/* We can't rendezvous without link specifiers. */
smartlist_free(rp_lspecs);
goto end;
}
/* Populate the introduce1 data object. */
memset(intro1_data, 0, sizeof(hs_cell_introduce1_data_t));
if (ip->legacy.key != NULL) {
intro1_data->is_legacy = 1;
intro1_data->legacy_key = ip->legacy.key;
}
intro1_data->auth_pk = &ip->auth_key_cert->signed_key;
intro1_data->enc_pk = &ip->enc_key;
intro1_data->subcredential = subcredential;
intro1_data->link_specifiers = rp_lspecs;
intro1_data->onion_pk = node_get_curve25519_onion_key(rp_node);
if (intro1_data->onion_pk == NULL) {
/* We can't rendezvous without the curve25519 onion key. */
goto end;
}
/* Success, we have valid introduce data. */
ret = 0;
end:
return ret;
}
/** Helper: cleanup function for client circuit. This is for every HS version.
* It is called from hs_circ_cleanup_on_free() entry point. */
static void
cleanup_on_free_client_circ(circuit_t *circ)
{
tor_assert(circ);
if (circuit_is_hs_v2(circ)) {
rend_client_circuit_cleanup_on_free(circ);
} else if (circuit_is_hs_v3(circ)) {
hs_client_circuit_cleanup_on_free(circ);
}
/* It is possible the circuit has an HS purpose but no identifier (rend_data
* or hs_ident). Thus possible that this passess through. */
}
/* ========== */
/* Public API */
/* ========== */
/** Return an introduction point circuit matching the given intro point object.
* NULL is returned is no such circuit can be found. */
origin_circuit_t *
hs_circ_service_get_intro_circ(const hs_service_intro_point_t *ip)
{
tor_assert(ip);
if (ip->base.is_only_legacy) {
return hs_circuitmap_get_intro_circ_v2_service_side(ip->legacy_key_digest);
} else {
return hs_circuitmap_get_intro_circ_v3_service_side(
&ip->auth_key_kp.pubkey);
}
}
/** Return an introduction point established circuit matching the given intro
* point object. The circuit purpose has to be CIRCUIT_PURPOSE_S_INTRO. NULL
* is returned is no such circuit can be found. */
origin_circuit_t *
hs_circ_service_get_established_intro_circ(const hs_service_intro_point_t *ip)
{
origin_circuit_t *circ;
tor_assert(ip);
if (ip->base.is_only_legacy) {
circ = hs_circuitmap_get_intro_circ_v2_service_side(ip->legacy_key_digest);
} else {
circ = hs_circuitmap_get_intro_circ_v3_service_side(
&ip->auth_key_kp.pubkey);
}
/* Only return circuit if it is established. */
return (circ && TO_CIRCUIT(circ)->purpose == CIRCUIT_PURPOSE_S_INTRO) ?
circ : NULL;
}
/** Called when we fail building a rendezvous circuit at some point other than
* the last hop: launches a new circuit to the same rendezvous point. This
* supports legacy service.
*
* We currently relaunch connections to rendezvous points if:
* - A rendezvous circuit timed out before connecting to RP.
* - The rendezvous circuit failed to connect to the RP.
*
* We avoid relaunching a connection to this rendezvous point if:
* - We have already tried MAX_REND_FAILURES times to connect to this RP,
* - We've been trying to connect to this RP for more than MAX_REND_TIMEOUT
* seconds, or
* - We've already retried this specific rendezvous circuit.
*/
void
hs_circ_retry_service_rendezvous_point(origin_circuit_t *circ)
{
tor_assert(circ);
tor_assert(TO_CIRCUIT(circ)->purpose == CIRCUIT_PURPOSE_S_CONNECT_REND);
/* Check if we are allowed to relaunch to the rendezvous point of circ. */
if (!can_relaunch_service_rendezvous_point(circ)) {
goto done;
}
/* Flag the circuit that we are relaunching, to avoid to relaunch twice a
* circuit to the same rendezvous point at the same time. */
circ->hs_service_side_rend_circ_has_been_relaunched = 1;
/* Legacy services don't have a hidden service ident. */
if (circ->hs_ident) {
retry_service_rendezvous_point(circ);
} else {
rend_service_relaunch_rendezvous(circ);
}
done:
return;
}
/** For a given service and a service intro point, launch a circuit to the
* extend info ei. If the service is a single onion, and direct_conn is true,
* a one-hop circuit will be requested.
*
* Return 0 if the circuit was successfully launched and tagged
* with the correct identifier. On error, a negative value is returned. */
int
hs_circ_launch_intro_point(hs_service_t *service,
const hs_service_intro_point_t *ip,
extend_info_t *ei,
bool direct_conn)
{
/* Standard flags for introduction circuit. */
int ret = -1, circ_flags = CIRCLAUNCH_NEED_UPTIME | CIRCLAUNCH_IS_INTERNAL;
origin_circuit_t *circ;
tor_assert(service);
tor_assert(ip);
tor_assert(ei);
/* Update circuit flags in case of a single onion service that requires a
* direct connection. */
tor_assert_nonfatal(ip->circuit_retries > 0);
/* Only single onion services can make direct conns */
if (BUG(!service->config.is_single_onion && direct_conn)) {
goto end;
}
/* We only use a one-hop path on the first attempt. If the first attempt
* fails, we use a 3-hop path for reachability / reliability.
* (Unlike v2, retries is incremented by the caller before it calls this
* function.) */
if (direct_conn && ip->circuit_retries == 1) {
circ_flags |= CIRCLAUNCH_ONEHOP_TUNNEL;
}
log_info(LD_REND, "Launching a circuit to intro point %s for service %s.",
safe_str_client(extend_info_describe(ei)),
safe_str_client(service->onion_address));
/* Note down the launch for the retry period. Even if the circuit fails to
* be launched, we still want to respect the retry period to avoid stress on
* the circuit subsystem. */
service->state.num_intro_circ_launched++;
circ = circuit_launch_by_extend_info(CIRCUIT_PURPOSE_S_ESTABLISH_INTRO,
ei, circ_flags);
if (circ == NULL) {
goto end;
}
/* Setup the circuit identifier and attach it to it. */
circ->hs_ident = create_intro_circuit_identifier(service, ip);
tor_assert(circ->hs_ident);
/* Register circuit in the global circuitmap. */
register_intro_circ(ip, circ);
/* Success. */
ret = 0;
end:
return ret;
}
/** Called when a service introduction point circuit is done building. Given
* the service and intro point object, this function will send the
* ESTABLISH_INTRO cell on the circuit. Return 0 on success. Return 1 if the
* circuit has been repurposed to General because we already have too many
* opened. */
int
hs_circ_service_intro_has_opened(hs_service_t *service,
hs_service_intro_point_t *ip,
const hs_service_descriptor_t *desc,
origin_circuit_t *circ)
{
int ret = 0;
unsigned int num_intro_circ, num_needed_circ;
tor_assert(service);
tor_assert(ip);
tor_assert(desc);
tor_assert(circ);
/* Cound opened circuits that have sent ESTABLISH_INTRO cells or are already
* established introduction circuits */
num_intro_circ = count_opened_desc_intro_point_circuits(service, desc);
num_needed_circ = service->config.num_intro_points;
if (num_intro_circ > num_needed_circ) {
/* There are too many opened valid intro circuit for what the service
* needs so repurpose this one. */
/* XXX: Legacy code checks options->ExcludeNodes and if not NULL it just
* closes the circuit. I have NO idea why it does that so it hasn't been
* added here. I can only assume in case our ExcludeNodes list changes but
* in that case, all circuit are flagged unusable (config.c). --dgoulet */
log_info(LD_CIRC | LD_REND, "Introduction circuit just opened but we "
"have enough for service %s. Repurposing "
"it to general and leaving internal.",
safe_str_client(service->onion_address));
tor_assert(circ->build_state->is_internal);
/* Remove it from the circuitmap. */
hs_circuitmap_remove_circuit(TO_CIRCUIT(circ));
/* Cleaning up the hidden service identifier and repurpose. */
hs_ident_circuit_free(circ->hs_ident);
circ->hs_ident = NULL;
if (circuit_should_use_vanguards(TO_CIRCUIT(circ)->purpose))
circuit_change_purpose(TO_CIRCUIT(circ), CIRCUIT_PURPOSE_HS_VANGUARDS);
else
circuit_change_purpose(TO_CIRCUIT(circ), CIRCUIT_PURPOSE_C_GENERAL);
/* Inform that this circuit just opened for this new purpose. */
circuit_has_opened(circ);
/* This return value indicate to the caller that the IP object should be
* removed from the service because it's corresponding circuit has just
* been repurposed. */
ret = 1;
goto done;
}
log_info(LD_REND, "Introduction circuit %u established for service %s.",
TO_CIRCUIT(circ)->n_circ_id,
safe_str_client(service->onion_address));
circuit_log_path(LOG_INFO, LD_REND, circ);
/* Time to send an ESTABLISH_INTRO cell on this circuit. On error, this call
* makes sure the circuit gets closed. */
send_establish_intro(service, ip, circ);
done:
return ret;
}
/** Called when a service rendezvous point circuit is done building. Given the
* service and the circuit, this function will send a RENDEZVOUS1 cell on the
* circuit using the information in the circuit identifier. If the cell can't
* be sent, the circuit is closed. */
void
hs_circ_service_rp_has_opened(const hs_service_t *service,
origin_circuit_t *circ)
{
size_t payload_len;
uint8_t payload[RELAY_PAYLOAD_SIZE] = {0};
tor_assert(service);
tor_assert(circ);
tor_assert(circ->hs_ident);
/* Some useful logging. */
log_info(LD_REND, "Rendezvous circuit %u has opened with cookie %s "
"for service %s",
TO_CIRCUIT(circ)->n_circ_id,
hex_str((const char *) circ->hs_ident->rendezvous_cookie,
REND_COOKIE_LEN),
safe_str_client(service->onion_address));
circuit_log_path(LOG_INFO, LD_REND, circ);
/* This can't fail. */
payload_len = hs_cell_build_rendezvous1(
circ->hs_ident->rendezvous_cookie,
sizeof(circ->hs_ident->rendezvous_cookie),
circ->hs_ident->rendezvous_handshake_info,
sizeof(circ->hs_ident->rendezvous_handshake_info),
payload);
/* Pad the payload with random bytes so it matches the size of a legacy cell
* which is normally always bigger. Also, the size of a legacy cell is
* always smaller than the RELAY_PAYLOAD_SIZE so this is safe. */
if (payload_len < HS_LEGACY_RENDEZVOUS_CELL_SIZE) {
crypto_rand((char *) payload + payload_len,
HS_LEGACY_RENDEZVOUS_CELL_SIZE - payload_len);
payload_len = HS_LEGACY_RENDEZVOUS_CELL_SIZE;
}
if (relay_send_command_from_edge(CONTROL_CELL_ID, TO_CIRCUIT(circ),
RELAY_COMMAND_RENDEZVOUS1,
(const char *) payload, payload_len,
circ->cpath->prev) < 0) {
/* On error, circuit is closed. */
log_warn(LD_REND, "Unable to send RENDEZVOUS1 cell on circuit %u "
"for service %s",
TO_CIRCUIT(circ)->n_circ_id,
safe_str_client(service->onion_address));
goto done;
}
/* Setup end-to-end rendezvous circuit between the client and us. */
if (hs_circuit_setup_e2e_rend_circ(circ,
circ->hs_ident->rendezvous_ntor_key_seed,
sizeof(circ->hs_ident->rendezvous_ntor_key_seed),
1) < 0) {
log_warn(LD_GENERAL, "Failed to setup circ");
goto done;
}
done:
memwipe(payload, 0, sizeof(payload));
}
/** Circ has been expecting an INTRO_ESTABLISHED cell that just arrived. Handle
* the INTRO_ESTABLISHED cell payload of length payload_len arriving on the
* given introduction circuit circ. The service is only used for logging
* purposes. Return 0 on success else a negative value. */
int
hs_circ_handle_intro_established(const hs_service_t *service,
const hs_service_intro_point_t *ip,
origin_circuit_t *circ,
const uint8_t *payload, size_t payload_len)
{
int ret = -1;
tor_assert(service);
tor_assert(ip);
tor_assert(circ);
tor_assert(payload);
if (BUG(TO_CIRCUIT(circ)->purpose != CIRCUIT_PURPOSE_S_ESTABLISH_INTRO)) {
goto done;
}
/* Try to parse the payload into a cell making sure we do actually have a
* valid cell. For a legacy node, it's an empty payload so as long as we
* have the cell, we are good. */
if (!ip->base.is_only_legacy &&
hs_cell_parse_intro_established(payload, payload_len) < 0) {
log_warn(LD_REND, "Unable to parse the INTRO_ESTABLISHED cell on "
"circuit %u for service %s",
TO_CIRCUIT(circ)->n_circ_id,
safe_str_client(service->onion_address));
goto done;
}
/* Switch the purpose to a fully working intro point. */
circuit_change_purpose(TO_CIRCUIT(circ), CIRCUIT_PURPOSE_S_INTRO);
/* Getting a valid INTRODUCE_ESTABLISHED means we've successfully used the
* circuit so update our pathbias subsystem. */
pathbias_mark_use_success(circ);
/* Success. */
ret = 0;
done:
return ret;
}
/**
* Go into <b>data</b> and add the right subcredential to be able to handle
* this incoming cell.
*
* <b>desc_subcred</b> is the subcredential of the descriptor that corresponds
* to the intro point that received this intro request. This subcredential
* should be used if we are not an onionbalance instance.
*
* Return 0 if everything went well, or -1 in case of internal error.
*/
static int
get_subcredential_for_handling_intro2_cell(const hs_service_t *service,
hs_cell_introduce2_data_t *data,
const hs_subcredential_t *desc_subcred)
{
/* Handle the simple case first: We are not an onionbalance instance and we
* should just use the regular descriptor subcredential */
if (!hs_ob_service_is_instance(service)) {
data->n_subcredentials = 1;
data->subcredentials = desc_subcred;
return 0;
}
/* This should not happen since we should have made onionbalance
* subcredentials when we created our descriptors. */
if (BUG(!service->ob_subcreds)) {
return -1;
}
/* We are an onionbalance instance: */
data->n_subcredentials = service->n_ob_subcreds;
data->subcredentials = service->ob_subcreds;
return 0;
}
/** We just received an INTRODUCE2 cell on the established introduction circuit
* circ. Handle the INTRODUCE2 payload of size payload_len for the given
* circuit and service. This cell is associated with the intro point object ip
* and the subcredential. Return 0 on success else a negative value. */
int
hs_circ_handle_introduce2(const hs_service_t *service,
const origin_circuit_t *circ,
hs_service_intro_point_t *ip,
const hs_subcredential_t *subcredential,
const uint8_t *payload, size_t payload_len)
{
int ret = -1;
time_t elapsed;
hs_cell_introduce2_data_t data;
tor_assert(service);
tor_assert(circ);
tor_assert(ip);
tor_assert(subcredential);
tor_assert(payload);
/* Populate the data structure with everything we need for the cell to be
* parsed, decrypted and key material computed correctly. */
data.auth_pk = &ip->auth_key_kp.pubkey;
data.enc_kp = &ip->enc_key_kp;
data.payload = payload;
data.payload_len = payload_len;
data.link_specifiers = smartlist_new();
data.replay_cache = ip->replay_cache;
if (get_subcredential_for_handling_intro2_cell(service,
&data, subcredential)) {
goto done;
}
if (hs_cell_parse_introduce2(&data, circ, service) < 0) {
goto done;
}
/* Check whether we've seen this REND_COOKIE before to detect repeats. */
if (replaycache_add_test_and_elapsed(
service->state.replay_cache_rend_cookie,
data.rendezvous_cookie, sizeof(data.rendezvous_cookie),
&elapsed)) {
/* A Tor client will send a new INTRODUCE1 cell with the same REND_COOKIE
* as its previous one if its intro circ times out while in state
* CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT. If we received the first
* INTRODUCE1 cell (the intro-point relay converts it into an INTRODUCE2
* cell), we are already trying to connect to that rend point (and may
* have already succeeded); drop this cell. */
log_info(LD_REND, "We received an INTRODUCE2 cell with same REND_COOKIE "
"field %ld seconds ago. Dropping cell.",
(long int) elapsed);
goto done;
}
/* At this point, we just confirmed that the full INTRODUCE2 cell is valid
* so increment our counter that we've seen one on this intro point. */
ip->introduce2_count++;
/* Launch rendezvous circuit with the onion key and rend cookie. */
launch_rendezvous_point_circuit(service, ip, &data);
/* Success. */
ret = 0;
done:
link_specifier_smartlist_free(data.link_specifiers);
memwipe(&data, 0, sizeof(data));
return ret;
}
/** Circuit <b>circ</b> just finished the rend ntor key exchange. Use the key
* exchange output material at <b>ntor_key_seed</b> and setup <b>circ</b> to
* serve as a rendezvous end-to-end circuit between the client and the
* service. If <b>is_service_side</b> is set, then we are the hidden service
* and the other side is the client.
*
* Return 0 if the operation went well; in case of error return -1. */
int
hs_circuit_setup_e2e_rend_circ(origin_circuit_t *circ,
const uint8_t *ntor_key_seed, size_t seed_len,
int is_service_side)
{
if (BUG(!circuit_purpose_is_correct_for_rend(TO_CIRCUIT(circ)->purpose,
is_service_side))) {
return -1;
}
crypt_path_t *hop = create_rend_cpath(ntor_key_seed, seed_len,
is_service_side);
if (!hop) {
log_warn(LD_REND, "Couldn't get v3 %s cpath!",
is_service_side ? "service-side" : "client-side");
return -1;
}
finalize_rend_circuit(circ, hop, is_service_side);
return 0;
}
/** We are a v2 legacy HS client and we just received a RENDEZVOUS1 cell
* <b>rend_cell_body</b> on <b>circ</b>. Finish up the DH key exchange and then
* extend the crypt path of <b>circ</b> so that the hidden service is on the
* other side. */
int
hs_circuit_setup_e2e_rend_circ_legacy_client(origin_circuit_t *circ,
const uint8_t *rend_cell_body)
{
if (BUG(!circuit_purpose_is_correct_for_rend(
TO_CIRCUIT(circ)->purpose, 0))) {
return -1;
}
crypt_path_t *hop = create_rend_cpath_legacy(circ, rend_cell_body);
if (!hop) {
log_warn(LD_GENERAL, "Couldn't get v2 cpath.");
return -1;
}
finalize_rend_circuit(circ, hop, 0);
return 0;
}
/** Given the introduction circuit intro_circ, the rendezvous circuit
* rend_circ, a descriptor intro point object ip and the service's
* subcredential, send an INTRODUCE1 cell on intro_circ.
*
* This will also setup the circuit identifier on rend_circ containing the key
* material for the handshake and e2e encryption. Return 0 on success else
* negative value. Because relay_send_command_from_edge() closes the circuit
* on error, it is possible that intro_circ is closed on error. */
int
hs_circ_send_introduce1(origin_circuit_t *intro_circ,
origin_circuit_t *rend_circ,
const hs_desc_intro_point_t *ip,
const hs_subcredential_t *subcredential)
{
int ret = -1;
ssize_t payload_len;
uint8_t payload[RELAY_PAYLOAD_SIZE] = {0};
hs_cell_introduce1_data_t intro1_data;
tor_assert(intro_circ);
tor_assert(rend_circ);
tor_assert(ip);
tor_assert(subcredential);
/* It is undefined behavior in hs_cell_introduce1_data_clear() if intro1_data
* has been declared on the stack but not initialized. Here, we set it to 0.
*/
memset(&intro1_data, 0, sizeof(hs_cell_introduce1_data_t));
/* This takes various objects in order to populate the introduce1 data
* object which is used to build the content of the cell. */
const node_t *exit_node = build_state_get_exit_node(rend_circ->build_state);
if (exit_node == NULL) {
log_info(LD_REND, "Unable to get rendezvous point for circuit %u. "
"Failing.", TO_CIRCUIT(intro_circ)->n_circ_id);
goto done;
}
/* We should never select an invalid rendezvous point in theory but if we
* do, this function will fail to populate the introduce data. */
if (setup_introduce1_data(ip, exit_node, subcredential, &intro1_data) < 0) {
log_warn(LD_REND, "Unable to setup INTRODUCE1 data. The chosen rendezvous "
"point is unusable. Closing circuit.");
goto close;
}
/* Final step before we encode a cell, we setup the circuit identifier which
* will generate both the rendezvous cookie and client keypair for this
* connection. Those are put in the ident. */
intro1_data.rendezvous_cookie = rend_circ->hs_ident->rendezvous_cookie;
intro1_data.client_kp = &rend_circ->hs_ident->rendezvous_client_kp;
memcpy(intro_circ->hs_ident->rendezvous_cookie,
rend_circ->hs_ident->rendezvous_cookie,
sizeof(intro_circ->hs_ident->rendezvous_cookie));
/* From the introduce1 data object, this will encode the INTRODUCE1 cell
* into payload which is then ready to be sent as is. */
payload_len = hs_cell_build_introduce1(&intro1_data, payload);
if (BUG(payload_len < 0)) {
goto close;
}
if (relay_send_command_from_edge(CONTROL_CELL_ID, TO_CIRCUIT(intro_circ),
RELAY_COMMAND_INTRODUCE1,
(const char *) payload, payload_len,
intro_circ->cpath->prev) < 0) {
/* On error, circuit is closed. */
log_warn(LD_REND, "Unable to send INTRODUCE1 cell on circuit %u.",
TO_CIRCUIT(intro_circ)->n_circ_id);
goto done;
}
/* Success. */
ret = 0;
goto done;
close:
circuit_mark_for_close(TO_CIRCUIT(rend_circ), END_CIRC_REASON_INTERNAL);
done:
hs_cell_introduce1_data_clear(&intro1_data);
memwipe(payload, 0, sizeof(payload));
return ret;
}
/** Send an ESTABLISH_RENDEZVOUS cell along the rendezvous circuit circ. On
* success, 0 is returned else -1 and the circuit is marked for close. */
int
hs_circ_send_establish_rendezvous(origin_circuit_t *circ)
{
ssize_t cell_len = 0;
uint8_t cell[RELAY_PAYLOAD_SIZE] = {0};
tor_assert(circ);
tor_assert(TO_CIRCUIT(circ)->purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND);
log_info(LD_REND, "Send an ESTABLISH_RENDEZVOUS cell on circuit %u",
TO_CIRCUIT(circ)->n_circ_id);
/* Set timestamp_dirty, because circuit_expire_building expects it,
* and the rend cookie also means we've used the circ. */
TO_CIRCUIT(circ)->timestamp_dirty = time(NULL);
/* We've attempted to use this circuit. Probe it if we fail */
pathbias_count_use_attempt(circ);
/* Generate the RENDEZVOUS_COOKIE and place it in the identifier so we can
* complete the handshake when receiving the acknowledgement. */
crypto_rand((char *) circ->hs_ident->rendezvous_cookie, HS_REND_COOKIE_LEN);
/* Generate the client keypair. No need to be extra strong, not long term */
curve25519_keypair_generate(&circ->hs_ident->rendezvous_client_kp, 0);
cell_len =
hs_cell_build_establish_rendezvous(circ->hs_ident->rendezvous_cookie,
cell);
if (BUG(cell_len < 0)) {
goto err;
}
if (relay_send_command_from_edge(CONTROL_CELL_ID, TO_CIRCUIT(circ),
RELAY_COMMAND_ESTABLISH_RENDEZVOUS,
(const char *) cell, cell_len,
circ->cpath->prev) < 0) {
/* Circuit has been marked for close */
log_warn(LD_REND, "Unable to send ESTABLISH_RENDEZVOUS cell on "
"circuit %u", TO_CIRCUIT(circ)->n_circ_id);
memwipe(cell, 0, cell_len);
goto err;
}
memwipe(cell, 0, cell_len);
return 0;
err:
return -1;
}
/** Circuit cleanup strategy:
*
* What follows is a series of functions that notifies the HS subsystem of 3
* different circuit cleanup phase: close, free and repurpose.
*
* Tor can call any of those in any orders so they have to be safe between
* each other. In other words, the free should never depend on close to be
* called before.
*
* The "on_close()" is called from circuit_mark_for_close() which is
* considered the tor fast path and thus as little work as possible should
* done in that function. Currently, we only remove the circuit from the HS
* circuit map and move on.
*
* The "on_free()" is called from circuit circuit_free_() and it is very
* important that at the end of the function, no state or objects related to
* this circuit remains alive.
*
* The "on_repurpose()" is called from circuit_change_purpose() for which we
* simply remove it from the HS circuit map. We do not have other cleanup
* requirements after that.
*
* NOTE: The onion service code, specifically the service code, cleans up
* lingering objects or state if any of its circuit disappear which is why
* our cleanup strategy doesn't involve any service specific actions. As long
* as the circuit is removed from the HS circuit map, it won't be used.
*/
/** We are about to close this <b>circ</b>. Clean it up from any related HS
* data structures. This function can be called multiple times safely for the
* same circuit. */
void
hs_circ_cleanup_on_close(circuit_t *circ)
{
tor_assert(circ);
/* On close, we simply remove it from the circuit map. It can not be used
* anymore. We keep this code path fast and lean. */
if (circ->hs_token) {
hs_circuitmap_remove_circuit(circ);
}
}
/** We are about to free this <b>circ</b>. Clean it up from any related HS
* data structures. This function can be called multiple times safely for the
* same circuit. */
void
hs_circ_cleanup_on_free(circuit_t *circ)
{
tor_assert(circ);
/* NOTE: Bulk of the work of cleaning up a circuit is done here. */
if (circuit_purpose_is_hs_client(circ->purpose)) {
cleanup_on_free_client_circ(circ);
}
/* We have no assurance that the given HS circuit has been closed before and
* thus removed from the HS map. This actually happens in unit tests. */
if (circ->hs_token) {
hs_circuitmap_remove_circuit(circ);
}
}
/** We are about to repurpose this <b>circ</b>. Clean it up from any related
* HS data structures. This function can be called multiple times safely for
* the same circuit. */
void
hs_circ_cleanup_on_repurpose(circuit_t *circ)
{
tor_assert(circ);
/* On repurpose, we simply remove it from the circuit map but we do not do
* the on_free actions since we don't treat a repurpose as something we need
* to report in the client cache failure. */
if (circ->hs_token) {
hs_circuitmap_remove_circuit(circ);
}
}
/** Return true iff the given established client rendezvous circuit was sent
* into the INTRODUCE1 cell. This is called so we can take a decision on
* expiring or not the circuit.
*
* The caller MUST make sure the circuit is an established client rendezvous
* circuit (purpose: CIRCUIT_PURPOSE_C_REND_READY).
*
* This function supports all onion service versions. */
bool
hs_circ_is_rend_sent_in_intro1(const origin_circuit_t *circ)
{
tor_assert(circ);
/* This can only be called for a rendezvous circuit that is an established
* confirmed rendezsvous circuit but without an introduction ACK. */
tor_assert(TO_CIRCUIT(circ)->purpose == CIRCUIT_PURPOSE_C_REND_READY);
/* The v2 and v3 circuit are handled differently:
*
* v2: A circ's pending_final_cpath field is non-NULL iff it is a rend circ
* and we have tried to send an INTRODUCE1 cell specifying it. Thus, if the
* pending_final_cpath field *is* NULL, then we want to not spare it.
*
* v3: When the INTRODUCE1 cell is sent, the introduction encryption public
* key is copied in the rendezvous circuit hs identifier. If it is a valid
* key, we know that this circuit is waiting the ACK on the introduction
* circuit. We want to _not_ spare the circuit if the key was never set. */
if (circ->rend_data) {
/* v2. */
if (circ->build_state && circ->build_state->pending_final_cpath != NULL) {
return true;
}
} else if (circ->hs_ident) {
/* v3. */
if (curve25519_public_key_is_ok(&circ->hs_ident->intro_enc_pk)) {
return true;
}
} else {
/* A circuit with an HS purpose without an hs_ident or rend_data in theory
* can not happen. In case, scream loudly and return false to the caller
* that the rendezvous was not sent in the INTRO1 cell. */
tor_assert_nonfatal_unreached();
}
/* The rendezvous has not been specified in the INTRODUCE1 cell. */
return false;
}
| 36.953924 | 79 | 0.682421 | [
"object"
] |
fdd8f1be12964a9012c31c36a176ab572c1a01d3 | 7,238 | c | C | firmware/crypto/avr_aes_enc.c | google-admin/nfc-smart-tag | 8b4af0bf1e9613a9778475a1ae0efd0db5b97c95 | [
"Apache-2.0"
] | 13 | 2015-04-08T06:53:39.000Z | 2021-10-12T02:38:05.000Z | firmware/crypto/avr_aes_enc.c | google-admin/nfc-smart-tag | 8b4af0bf1e9613a9778475a1ae0efd0db5b97c95 | [
"Apache-2.0"
] | 1 | 2021-07-12T12:10:14.000Z | 2021-07-12T12:10:14.000Z | firmware/crypto/avr_aes_enc.c | google-admin/nfc-smart-tag | 8b4af0bf1e9613a9778475a1ae0efd0db5b97c95 | [
"Apache-2.0"
] | 9 | 2015-05-23T03:18:27.000Z | 2021-10-12T02:37:58.000Z | /*
* Copyright 2012 Google Inc. All Rights Reserved.
* Author: ghohpe@google.com (Gregor Hohpe)
*
* 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.
*
* http://csrc.nist.gov/publications/fips/fips197/fips-197.pdf
* AES-128 Encryption based on a naive implementation from the spec:
* and then optimized as described in the comments.
*
* Key expansion: ~4000 cycles (1.2ms @ 3.58MHz)
* Encrypting one block: ~6700 cycles (1.9ms @ 3.58MHz)
*
* Method names use a different convention as they are taken from the spec.
*/
#include <stdint.h>
#include <string.h>
#include <avr/io.h>
#include <avr/pgmspace.h>
#include "avr_aes_enc.h"
const uint8_t PROGMEM sbox[256] = {
0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5,
0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76,
0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0,
0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0,
0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc,
0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15,
0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a,
0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75,
0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0,
0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84,
0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b,
0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,
0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85,
0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8,
0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5,
0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2,
0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17,
0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73,
0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88,
0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb,
0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c,
0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79,
0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9,
0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08,
0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6,
0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a,
0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e,
0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e,
0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94,
0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf,
0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68,
0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16
};
#define BPOLY 0x1b // Lower 8 bits of (x^8+x^4+x^3+x+1), ie. (x^4+x^3+x+1).
#define KEYLENGTH 16
/*
* Substitute bytes.
*
* Optimization:
* - Use precomputed sbox
*/
static void SubBytes(uint8_t *data, uint8_t count)
{
do {
*data++ = pgm_read_byte(sbox + *data);
} while (--count);
}
/*
* Shift rows 1 -3 of state as per spec.
*/
static void ShiftRows(uint8_t *state)
{
uint8_t tmp;
// row 1
tmp = state[1];
state[1] = state[5];
state[5] = state[9];
state[9] = state[13];
state[13] = tmp;
// row 2
tmp = state[2];
state[2] = state [10];
state[10] = tmp;
tmp = state[6];
state[6] = state[14];
state[14] = tmp;
// row 3
tmp = state[15];
state[15] = state[11];
state[11] = state[7];
state[7] = state[3];
state[3] = tmp;
}
/*
* Multiply by 2 modulo 0x1b (see Spec 4.2.1)
* return (num << 1) ^ (num & 0x80 ? BPOLY : 0);
*
* Optimizations:
* - Rewritten in assembly using carry bit
*/
static uint8_t xtime(uint8_t num)
{
asm volatile(
"lsl %0\n\t"
"brcc L_%=\n\t"
"ldi r24, lo8(27)\n\t"
"eor %0, r24\n\t"
"L_%=:\n\t"
: "=r" (num) : "0" (num) : "r24");
return num;
}
/*
* Take dot products of each matrix row and the column vector.
* 02 03 01 01
* 01 02 03 01
* 01 01 02 03
* 03 01 01 02
*
* Optimizations:
* - Multiply by 2 using xtime
* - Implement mul(3,x) as mul(2,x) ^ x
* - Precompute xor for full column and undo the one not needed
* - Replace (mul(2,x) + mul(2,y)) with mul(2, x+y)
*/
static void MixColumn(uint8_t *column)
{
uint8_t result[4];
uint8_t sum = column[0] ^ column[1] ^ column[2] ^ column[3];
result[0] = xtime(column[0] ^ column[1]);
result[0] ^= sum ^ column[0];
result[1] = xtime(column[1] ^ column[2]);
result[1] ^= sum ^ column[1];
result[2] = xtime(column[2] ^ column[3]);
result[2] ^= sum ^ column[2];
result[3] = xtime(column[0] ^ column[3]);
result[3] ^= sum ^ column[3];
// Copy temporary result to original column.
column[0] = result[0];
column[1] = result[1];
column[2] = result[2];
column[3] = result[3];
}
static void MixColumns(uint8_t *state)
{
MixColumn(state + 0*4);
MixColumn(state + 1*4);
MixColumn(state + 2*4);
MixColumn(state + 3*4);
}
static void XORBytes(uint8_t *bytes1, uint8_t *bytes2, uint8_t count)
{
do {
*bytes1++ ^= *bytes2++;
} while(--count);
}
/*
* Encodes one 16 byte (128bit) block of data in place.
*/
void aes128_enc(uint8_t * block, aes128_ctx_t *ctx)
{
uint8_t round = AES128_ROUNDS - 1;
uint8_t *expandedKey = ctx->expanded_key;
XORBytes(block, expandedKey, 16); // AddRoundKey
expandedKey += BLOCKSIZE;
do {
SubBytes(block, 16);
ShiftRows(block);
MixColumns(block);
XORBytes(block, expandedKey, 16); // AddRoundKey
expandedKey += BLOCKSIZE;
} while(--round);
SubBytes(block, 16);
ShiftRows(block);
XORBytes(block, expandedKey, 16); // AddRoundkey
}
static void RotWord(uint8_t *word)
{
uint8_t temp = word[0];
word[0] = word[1];
word[1] = word[2];
word[2] = word[3];
word[3] = temp;
}
/*
* Key expansion from 16 bytes to 176 bytes.
*
* Optimizations:
* - Compute rcon on the fly
* - Only consider lowest byte of rcon as others are 0
* - Avoid MOD operation
* - Only consider 128bit key
*/
static void KeyExpansion(uint8_t *key, uint8_t *expandedKey)
{
uint8_t temp[4];
uint8_t i;
uint8_t next_i;
uint8_t rcon = 0x01; // Round constant.
// Copy key to start of expanded key.
memcpy(expandedKey, key, KEYLENGTH);
// Prepare last 4 bytes in temp.
expandedKey += KEYLENGTH - 4;
temp[0] = *(expandedKey++);
temp[1] = *(expandedKey++);
temp[2] = *(expandedKey++);
temp[3] = *(expandedKey++);
i = KEYLENGTH;
next_i = KEYLENGTH;
while (i < BLOCKSIZE*(AES128_ROUNDS+1)) {
// Are we at the start of the next key size?
if (i == next_i) {
// temp still contains last block
RotWord(temp);
SubBytes(temp, 4);
temp[0] ^= rcon;
rcon = xtime(rcon);
next_i += KEYLENGTH;
}
XORBytes(temp, expandedKey - KEYLENGTH, 4);
*(expandedKey++) = temp[0];
*(expandedKey++) = temp[1];
*(expandedKey++) = temp[2];
*(expandedKey++) = temp[3];
i += 4;
}
}
/*
* Expands the 16 byte (128bit) key into the context.
*/
void aes128_init(uint8_t *key, aes128_ctx_t *ctx)
{
KeyExpansion(key, ctx->expanded_key);
}
| 26.708487 | 75 | 0.625311 | [
"vector"
] |
fdde7f0e843cc53f2858d9b279c4d1d8c845a353 | 2,755 | h | C | include/cxxutil/rwlock.h | YJessicaGao/easydk | e62eecde91886c2679def95edafb48f97650edfa | [
"Apache-2.0"
] | 2 | 2021-09-14T09:00:35.000Z | 2021-09-16T01:34:35.000Z | include/cxxutil/rwlock.h | YJessicaGao/easydk | e62eecde91886c2679def95edafb48f97650edfa | [
"Apache-2.0"
] | null | null | null | include/cxxutil/rwlock.h | YJessicaGao/easydk | e62eecde91886c2679def95edafb48f97650edfa | [
"Apache-2.0"
] | null | null | null | /*************************************************************************
* Copyright (C) [2019] by Cambricon, 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
*
* 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 EDK_CXXUTIL_RWLOCK_H_
#define EDK_CXXUTIL_RWLOCK_H_
#include <pthread.h>
#include "cxxutil/noncopy.h"
namespace edk {
// FIXME(dmh): pthread return code is not handle
/**
* @brief Read Write lock based on pthread
*/
class RwLock : public NonCopyable {
public:
/**
* @brief Construct a new RwLock object
*/
RwLock() { pthread_rwlock_init(&rwlock_, NULL); }
/**
* @brief Destroy the RwLock object
*/
~RwLock() { pthread_rwlock_destroy(&rwlock_); }
/**
* @brief Lock with write access
*/
void WriteLock() { pthread_rwlock_wrlock(&rwlock_); }
/**
* @brief Lock with read access
*/
void ReadLock() { pthread_rwlock_rdlock(&rwlock_); }
/**
* @brief Unlock
*/
void Unlock() { pthread_rwlock_unlock(&rwlock_); }
private:
pthread_rwlock_t rwlock_;
};
/**
* @brief RAII guard of write lock
*/
class WriteLockGuard {
public:
/**
* @brief Construct a new Write Lock Guard object, and lock write
*
* @param lock Read write lock
*/
explicit WriteLockGuard(RwLock& lock) : lock_(lock) { lock_.WriteLock(); }
/**
* @brief Destroy the Write Lock Guard object, and unlock
*/
~WriteLockGuard() { lock_.Unlock(); }
private:
RwLock& lock_;
};
/**
* @brief RAII guard of read lock
*/
class ReadLockGuard {
public:
/**
* @brief Construct a new Read Lock Guard object, and lock read
*
* @param lock Read write lock
*/
explicit ReadLockGuard(RwLock& lock) : lock_(lock) { lock_.ReadLock(); }
/**
* @brief Destroy the Read Lock Guard object, and unlock
*/
~ReadLockGuard() { lock_.Unlock(); }
private:
RwLock& lock_;
};
} // namespace edk
#endif // EDK_CXXUTIL_RWLOCK_H_
| 26.747573 | 80 | 0.647913 | [
"object"
] |
fde680baec1f8869f8a4e94e1b76122437d390ef | 9,119 | h | C | nodejs/src/node_15_headers/crypto_keygen.h | mmdevries/eiows | aa4bab8f64ccd7bd315b55274f12a0b6c55719f2 | [
"MIT"
] | 50 | 2020-06-18T21:01:25.000Z | 2022-03-29T10:48:08.000Z | nodejs/src/node_15_headers/crypto_keygen.h | mmdevries/eiows | aa4bab8f64ccd7bd315b55274f12a0b6c55719f2 | [
"MIT"
] | 8 | 2020-06-22T07:58:15.000Z | 2021-11-15T13:55:08.000Z | nodejs/src/node_15_headers/crypto_keygen.h | mmdevries/eiows | aa4bab8f64ccd7bd315b55274f12a0b6c55719f2 | [
"MIT"
] | 2 | 2020-08-20T16:08:00.000Z | 2021-11-01T14:57:30.000Z | #ifndef SRC_CRYPTO_CRYPTO_KEYGEN_H_
#define SRC_CRYPTO_CRYPTO_KEYGEN_H_
#if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
#include "crypto/crypto_keys.h"
#include "crypto/crypto_util.h"
#include "allocated_buffer.h"
#include "async_wrap.h"
#include "base_object.h"
#include "env.h"
#include "memory_tracker.h"
#include "v8.h"
namespace node {
namespace crypto {
namespace Keygen {
void Initialize(Environment* env, v8::Local<v8::Object> target);
} // namespace Keygen
enum class KeyGenJobStatus {
ERR_OK,
ERR_FAILED
};
// A Base CryptoJob for generating secret keys or key pairs.
// The KeyGenTraits is largely responsible for the details of
// the implementation, while KeyGenJob handles the common
// mechanisms.
template <typename KeyGenTraits>
class KeyGenJob final : public CryptoJob<KeyGenTraits> {
public:
using AdditionalParams = typename KeyGenTraits::AdditionalParameters;
static void New(const v8::FunctionCallbackInfo<v8::Value>& args) {
Environment* env = Environment::GetCurrent(args);
CHECK(args.IsConstructCall());
CryptoJobMode mode = GetCryptoJobMode(args[0]);
unsigned int offset = 1;
AdditionalParams params;
if (KeyGenTraits::AdditionalConfig(mode, args, &offset, ¶ms)
.IsNothing()) {
// The KeyGenTraits::AdditionalConfig is responsible for
// calling an appropriate THROW_CRYPTO_* variant reporting
// whatever error caused initialization to fail.
return;
}
new KeyGenJob<KeyGenTraits>(env, args.This(), mode, std::move(params));
}
static void Initialize(
Environment* env,
v8::Local<v8::Object> target) {
CryptoJob<KeyGenTraits>::Initialize(New, env, target);
}
KeyGenJob(
Environment* env,
v8::Local<v8::Object> object,
CryptoJobMode mode,
AdditionalParams&& params)
: CryptoJob<KeyGenTraits>(
env,
object,
KeyGenTraits::Provider,
mode,
std::move(params)) {}
void DoThreadPoolWork() override {
// Make sure the the CSPRNG is properly seeded so the results are secure
CheckEntropy();
AdditionalParams* params = CryptoJob<KeyGenTraits>::params();
switch (KeyGenTraits::DoKeyGen(AsyncWrap::env(), params)) {
case KeyGenJobStatus::ERR_OK:
status_ = KeyGenJobStatus::ERR_OK;
// Success!
break;
case KeyGenJobStatus::ERR_FAILED: {
CryptoErrorVector* errors = CryptoJob<KeyGenTraits>::errors();
errors->Capture();
if (errors->empty())
errors->push_back(std::string("Key generation job failed"));
}
}
}
v8::Maybe<bool> ToResult(
v8::Local<v8::Value>* err,
v8::Local<v8::Value>* result) override {
Environment* env = AsyncWrap::env();
CryptoErrorVector* errors = CryptoJob<KeyGenTraits>::errors();
AdditionalParams* params = CryptoJob<KeyGenTraits>::params();
if (status_ == KeyGenJobStatus::ERR_OK &&
LIKELY(!KeyGenTraits::EncodeKey(env, params, result).IsNothing())) {
*err = Undefined(env->isolate());
return v8::Just(true);
}
if (errors->empty())
errors->Capture();
CHECK(!errors->empty());
*result = Undefined(env->isolate());
return v8::Just(errors->ToException(env).ToLocal(err));
}
SET_SELF_SIZE(KeyGenJob);
private:
KeyGenJobStatus status_ = KeyGenJobStatus::ERR_FAILED;
};
// A Base KeyGenTraits for Key Pair generation algorithms.
template <typename KeyPairAlgorithmTraits>
struct KeyPairGenTraits final {
using AdditionalParameters =
typename KeyPairAlgorithmTraits::AdditionalParameters;
static const AsyncWrap::ProviderType Provider =
AsyncWrap::PROVIDER_KEYPAIRGENREQUEST;
static constexpr const char* JobName = KeyPairAlgorithmTraits::JobName;
static v8::Maybe<bool> AdditionalConfig(
CryptoJobMode mode,
const v8::FunctionCallbackInfo<v8::Value>& args,
unsigned int* offset,
AdditionalParameters* params) {
// Notice that offset is a pointer. Each of the AdditionalConfig,
// GetPublicKeyEncodingFromJs, and GetPrivateKeyEncodingFromJs
// functions will update the value of the offset as they successfully
// process input parameters. This allows each job to have a variable
// number of input parameters specific to each job type.
if (KeyPairAlgorithmTraits::AdditionalConfig(mode, args, offset, params)
.IsNothing()) {
return v8::Just(false);
}
params->public_key_encoding = ManagedEVPPKey::GetPublicKeyEncodingFromJs(
args,
offset,
kKeyContextGenerate);
auto private_key_encoding =
ManagedEVPPKey::GetPrivateKeyEncodingFromJs(
args,
offset,
kKeyContextGenerate);
if (!private_key_encoding.IsEmpty())
params->private_key_encoding = private_key_encoding.Release();
return v8::Just(true);
}
static KeyGenJobStatus DoKeyGen(
Environment* env,
AdditionalParameters* params) {
EVPKeyCtxPointer ctx = KeyPairAlgorithmTraits::Setup(params);
if (!ctx || EVP_PKEY_keygen_init(ctx.get()) <= 0)
return KeyGenJobStatus::ERR_FAILED;
// Generate the key
EVP_PKEY* pkey = nullptr;
if (!EVP_PKEY_keygen(ctx.get(), &pkey))
return KeyGenJobStatus::ERR_FAILED;
params->key = ManagedEVPPKey(EVPKeyPointer(pkey));
return KeyGenJobStatus::ERR_OK;
}
static v8::Maybe<bool> EncodeKey(
Environment* env,
AdditionalParameters* params,
v8::Local<v8::Value>* result) {
v8::Local<v8::Value> keys[2];
if (ManagedEVPPKey::ToEncodedPublicKey(
env,
std::move(params->key),
params->public_key_encoding,
&keys[0]).IsNothing() ||
ManagedEVPPKey::ToEncodedPrivateKey(
env,
std::move(params->key),
params->private_key_encoding,
&keys[1]).IsNothing()) {
return v8::Nothing<bool>();
}
*result = v8::Array::New(env->isolate(), keys, arraysize(keys));
return v8::Just(true);
}
};
struct SecretKeyGenConfig final : public MemoryRetainer {
size_t length; // Expressed a a number of bits
char* out = nullptr; // Placeholder for the generated key bytes
void MemoryInfo(MemoryTracker* tracker) const override;
SET_MEMORY_INFO_NAME(SecretKeyGenConfig)
SET_SELF_SIZE(SecretKeyGenConfig)
};
struct SecretKeyGenTraits final {
using AdditionalParameters = SecretKeyGenConfig;
static const AsyncWrap::ProviderType Provider =
AsyncWrap::PROVIDER_KEYGENREQUEST;
static constexpr const char* JobName = "SecretKeyGenJob";
static v8::Maybe<bool> AdditionalConfig(
CryptoJobMode mode,
const v8::FunctionCallbackInfo<v8::Value>& args,
unsigned int* offset,
SecretKeyGenConfig* params);
static KeyGenJobStatus DoKeyGen(
Environment* env,
SecretKeyGenConfig* params);
static v8::Maybe<bool> EncodeKey(
Environment* env,
SecretKeyGenConfig* params,
v8::Local<v8::Value>* result);
};
template <typename AlgorithmParams>
struct KeyPairGenConfig final : public MemoryRetainer {
PublicKeyEncodingConfig public_key_encoding;
PrivateKeyEncodingConfig private_key_encoding;
ManagedEVPPKey key;
AlgorithmParams params;
KeyPairGenConfig() = default;
explicit KeyPairGenConfig(KeyPairGenConfig&& other) noexcept
: public_key_encoding(other.public_key_encoding),
private_key_encoding(
std::forward<PrivateKeyEncodingConfig>(
other.private_key_encoding)),
key(std::move(other.key)),
params(std::move(other.params)) {}
KeyPairGenConfig& operator=(KeyPairGenConfig&& other) noexcept {
if (&other == this) return *this;
this->~KeyPairGenConfig();
return *new (this) KeyPairGenConfig(std::move(other));
}
void MemoryInfo(MemoryTracker* tracker) const override {
tracker->TrackField("key", key);
tracker->TrackFieldWithSize("private_key_encoding.passphrase",
private_key_encoding.passphrase_.size());
tracker->TrackField("params", params);
}
SET_MEMORY_INFO_NAME(KeyPairGenConfig)
SET_SELF_SIZE(KeyPairGenConfig)
};
struct NidKeyPairParams final : public MemoryRetainer {
int id;
SET_NO_MEMORY_INFO()
SET_MEMORY_INFO_NAME(NidKeyPairParams)
SET_SELF_SIZE(NidKeyPairParams)
};
using NidKeyPairGenConfig = KeyPairGenConfig<NidKeyPairParams>;
struct NidKeyPairGenTraits final {
using AdditionalParameters = NidKeyPairGenConfig;
static constexpr const char* JobName = "NidKeyPairGenJob";
static EVPKeyCtxPointer Setup(NidKeyPairGenConfig* params);
static v8::Maybe<bool> AdditionalConfig(
CryptoJobMode mode,
const v8::FunctionCallbackInfo<v8::Value>& args,
unsigned int* offset,
NidKeyPairGenConfig* params);
};
using NidKeyPairGenJob = KeyGenJob<KeyPairGenTraits<NidKeyPairGenTraits>>;
using SecretKeyGenJob = KeyGenJob<SecretKeyGenTraits>;
} // namespace crypto
} // namespace node
#endif // !defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
#endif // SRC_CRYPTO_CRYPTO_KEYGEN_H_
| 31.122867 | 77 | 0.697335 | [
"object"
] |
fde9c0af3fc5df83c305d61352a787d2f274368c | 1,444 | h | C | src/rsyn/core/obj/data/Net.h | rsyn/rsyn.design | 99dc1241ef523c416be2617c7c7bdd3eec15413f | [
"Apache-2.0"
] | null | null | null | src/rsyn/core/obj/data/Net.h | rsyn/rsyn.design | 99dc1241ef523c416be2617c7c7bdd3eec15413f | [
"Apache-2.0"
] | null | null | null | src/rsyn/core/obj/data/Net.h | rsyn/rsyn.design | 99dc1241ef523c416be2617c7c7bdd3eec15413f | [
"Apache-2.0"
] | null | null | null | /* Copyright 2014-2017 Rsyn
*
* 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.
*/
namespace Rsyn {
struct NetTagData {
TristateFlag ideal;
NetTypeTag type;
NetTagData() :
type(NET_TYPE_TAG_NOT_SPECIFIED) {
} // end constructor
}; // end struct
// -----------------------------------------------------------------------------
struct NetData : ObjectData {
// Index in parent module.
Index mid;
// User tags.
NetTagData tag;
// Using a vector for fast traverse, but slow insertion and removal.
std::vector<Pin> pins;
// Driver. If multiple-drivers, store one of them without any assumptions.
Pin driver;
// Parent
Module parent;
std::array<int, NUM_SIGNAL_DIRECTIONS> numPinsOfType;
// Helper used for netlist traversals.
int sign;
NetData() :
mid(-1),
sign(-1),
driver(nullptr),
numPinsOfType({0, 0, 0, 0}),
parent(nullptr) {
} // end constructor
}; // end struct
} // end namespace | 24.474576 | 80 | 0.665512 | [
"vector"
] |
fdedd05c18cfd664ded3aa3932c97e364c28578a | 4,465 | h | C | mdl/include/tencentcloud/mdl/v20200326/model/LogInfo.h | TencentCloud/tencentcloud-sdk-cpp-intl-en | 752c031f5ad2c96868183c5931eae3a42dd5ae6c | [
"Apache-2.0"
] | 1 | 2022-01-27T09:27:34.000Z | 2022-01-27T09:27:34.000Z | mdl/include/tencentcloud/mdl/v20200326/model/LogInfo.h | TencentCloud/tencentcloud-sdk-cpp-intl-en | 752c031f5ad2c96868183c5931eae3a42dd5ae6c | [
"Apache-2.0"
] | null | null | null | mdl/include/tencentcloud/mdl/v20200326/model/LogInfo.h | TencentCloud/tencentcloud-sdk-cpp-intl-en | 752c031f5ad2c96868183c5931eae3a42dd5ae6c | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef TENCENTCLOUD_MDL_V20200326_MODEL_LOGINFO_H_
#define TENCENTCLOUD_MDL_V20200326_MODEL_LOGINFO_H_
#include <string>
#include <vector>
#include <map>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
#include <tencentcloud/core/AbstractModel.h>
#include <tencentcloud/mdl/v20200326/model/LogMessageInfo.h>
namespace TencentCloud
{
namespace Mdl
{
namespace V20200326
{
namespace Model
{
/**
* Log information.
*/
class LogInfo : public AbstractModel
{
public:
LogInfo();
~LogInfo() = default;
void ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const;
CoreInternalOutcome Deserialize(const rapidjson::Value &value);
/**
* 获取Log type.
It contains the value of `StreamStart` which refers to the push information.
* @return Type Log type.
It contains the value of `StreamStart` which refers to the push information.
*/
std::string GetType() const;
/**
* 设置Log type.
It contains the value of `StreamStart` which refers to the push information.
* @param Type Log type.
It contains the value of `StreamStart` which refers to the push information.
*/
void SetType(const std::string& _type);
/**
* 判断参数 Type 是否已赋值
* @return Type 是否已赋值
*/
bool TypeHasBeenSet() const;
/**
* 获取Time when the log is printed.
* @return Time Time when the log is printed.
*/
std::string GetTime() const;
/**
* 设置Time when the log is printed.
* @param Time Time when the log is printed.
*/
void SetTime(const std::string& _time);
/**
* 判断参数 Time 是否已赋值
* @return Time 是否已赋值
*/
bool TimeHasBeenSet() const;
/**
* 获取Log details.
* @return Message Log details.
*/
LogMessageInfo GetMessage() const;
/**
* 设置Log details.
* @param Message Log details.
*/
void SetMessage(const LogMessageInfo& _message);
/**
* 判断参数 Message 是否已赋值
* @return Message 是否已赋值
*/
bool MessageHasBeenSet() const;
private:
/**
* Log type.
It contains the value of `StreamStart` which refers to the push information.
*/
std::string m_type;
bool m_typeHasBeenSet;
/**
* Time when the log is printed.
*/
std::string m_time;
bool m_timeHasBeenSet;
/**
* Log details.
*/
LogMessageInfo m_message;
bool m_messageHasBeenSet;
};
}
}
}
}
#endif // !TENCENTCLOUD_MDL_V20200326_MODEL_LOGINFO_H_
| 32.830882 | 116 | 0.492945 | [
"vector",
"model"
] |
fdee841ac8c7ac2bd70ef26c7401f6ac4ba8fa79 | 7,221 | h | C | external-deps/folding-node/deps/openmm/include/opencl/OpenCLExpressionUtilities.h | FoldingAtHome/FAHAndroid | dfee3a9aa4540babf7a920ff8b10f93363903ebc | [
"MIT"
] | 14 | 2019-05-30T04:47:25.000Z | 2021-07-06T02:59:31.000Z | external-deps/folding-node/deps/openmm/include/opencl/OpenCLExpressionUtilities.h | FoldingAtHome/FAHAndroid | dfee3a9aa4540babf7a920ff8b10f93363903ebc | [
"MIT"
] | null | null | null | external-deps/folding-node/deps/openmm/include/opencl/OpenCLExpressionUtilities.h | FoldingAtHome/FAHAndroid | dfee3a9aa4540babf7a920ff8b10f93363903ebc | [
"MIT"
] | 9 | 2019-06-21T07:33:56.000Z | 2021-09-15T00:17:49.000Z | #ifndef OPENMM_OPENCLEXPRESSIONUTILITIES_H_
#define OPENMM_OPENCLEXPRESSIONUTILITIES_H_
/* -------------------------------------------------------------------------- *
* OpenMM *
* -------------------------------------------------------------------------- *
* This is part of the OpenMM molecular simulation toolkit originating from *
* Simbios, the NIH National Center for Physics-Based Simulation of *
* Biological Structures at Stanford, funded under the NIH Roadmap for *
* Medical Research, grant U54 GM072970. See https://simtk.org. *
* *
* Portions copyright (c) 2009-2011 Stanford University and the Authors. *
* Authors: Peter Eastman *
* Contributors: *
* *
* This program 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 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* -------------------------------------------------------------------------- */
#include "OpenCLContext.h"
#include "lepton/CustomFunction.h"
#include "lepton/ExpressionTreeNode.h"
#include "lepton/ParsedExpression.h"
#include <map>
#include <sstream>
#include <string>
#include <utility>
namespace OpenMM {
/**
* This class is used by various classes to generate OpenCL source code implementing
* user defined mathematical expressions.
*/
class OPENMM_EXPORT_OPENCL OpenCLExpressionUtilities {
public:
OpenCLExpressionUtilities(OpenCLContext& context) : context(context) {
}
/**
* Generate the source code for calculating a set of expressions.
*
* @param expressions the expressions to generate code for (keys are the variables to store the output values in)
* @param variables defines the source code to generate for each variable that may appear in the expressions. Keys are
* variable names, and the values are the code to generate for them.
* @param functions defines the variable name for each tabulated function that may appear in the expressions
* @param prefix a prefix to put in front of temporary variables
* @param functionParams the variable name containing the parameters for each tabulated function
* @param tempType the type of value to use for temporary variables (defaults to "real")
*/
std::string createExpressions(const std::map<std::string, Lepton::ParsedExpression>& expressions, const std::map<std::string, std::string>& variables,
const std::vector<std::pair<std::string, std::string> >& functions, const std::string& prefix, const std::string& functionParams, const std::string& tempType="real");
/**
* Generate the source code for calculating a set of expressions.
*
* @param expressions the expressions to generate code for (keys are the variables to store the output values in)
* @param variables defines the source code to generate for each variable or precomputed sub-expression that may appear in the expressions.
* Each entry is an ExpressionTreeNode, and the code to generate wherever an identical node appears.
* @param functions defines the variable name for each tabulated function that may appear in the expressions
* @param prefix a prefix to put in front of temporary variables
* @param functionParams the variable name containing the parameters for each tabulated function
* @param tempType the type of value to use for temporary variables (defaults to "float")
*/
std::string createExpressions(const std::map<std::string, Lepton::ParsedExpression>& expressions, const std::vector<std::pair<Lepton::ExpressionTreeNode, std::string> >& variables,
const std::vector<std::pair<std::string, std::string> >& functions, const std::string& prefix, const std::string& functionParams, const std::string& tempType="float");
/**
* Calculate the spline coefficients for a tabulated function that appears in expressions.
*
* @param values the tabulated values of the function
* @param min the value of the independent variable corresponding to the first element of values
* @param max the value of the independent variable corresponding to the last element of values
* @return the spline coefficients
*/
std::vector<mm_float4> computeFunctionCoefficients(const std::vector<double>& values, double min, double max);
class FunctionPlaceholder;
private:
void processExpression(std::stringstream& out, const Lepton::ExpressionTreeNode& node,
std::vector<std::pair<Lepton::ExpressionTreeNode, std::string> >& temps,
const std::vector<std::pair<std::string, std::string> >& functions, const std::string& prefix, const std::string& functionParams,
const std::vector<Lepton::ParsedExpression>& allExpressions, const std::string& tempType);
std::string getTempName(const Lepton::ExpressionTreeNode& node, const std::vector<std::pair<Lepton::ExpressionTreeNode, std::string> >& temps);
void findRelatedTabulatedFunctions(const Lepton::ExpressionTreeNode& node, const Lepton::ExpressionTreeNode& searchNode,
const Lepton::ExpressionTreeNode*& valueNode, const Lepton::ExpressionTreeNode*& derivNode);
void findRelatedPowers(const Lepton::ExpressionTreeNode& node, const Lepton::ExpressionTreeNode& searchNode,
std::map<int, const Lepton::ExpressionTreeNode*>& powers);
OpenCLContext& context;
};
/**
* This class serves as a placeholder for custom functions in expressions.
*/
class OpenCLExpressionUtilities::FunctionPlaceholder : public Lepton::CustomFunction {
public:
int getNumArguments() const {
return 1;
}
double evaluate(const double* arguments) const {
return 0.0;
}
double evaluateDerivative(const double* arguments, const int* derivOrder) const {
return 0.0;
}
CustomFunction* clone() const {
return new FunctionPlaceholder();
}
};
} // namespace OpenMM
#endif /*OPENMM_OPENCLEXPRESSIONUTILITIES_H_*/
| 59.188525 | 184 | 0.631907 | [
"vector"
] |
fdef6f13bd3d923aabdaff4e3d63cca7a4c59436 | 2,212 | h | C | Polynomial.h | jachappell/Polynomial | c53aa8b2e9228e081fe02b6608175646b6ff0254 | [
"MIT"
] | 2 | 2018-02-17T17:02:53.000Z | 2019-09-11T19:05:29.000Z | Polynomial.h | jachappell/Polynomial | c53aa8b2e9228e081fe02b6608175646b6ff0254 | [
"MIT"
] | null | null | null | Polynomial.h | jachappell/Polynomial | c53aa8b2e9228e081fe02b6608175646b6ff0254 | [
"MIT"
] | null | null | null | //
// Copyright (c) 2016 James A. Chappell (rlrrlrll@gmail.com)
//
// c++ class to evaluate polynomials
//
#pragma once
#include <vector>
namespace Storage_B
{
namespace Polynomials
{
template<typename T> class Polynomial
{
public:
Polynomial(const T& c = static_cast<T>(0),
typename std::vector<T>::size_type deg = 0)
: coeff_(deg + 1, c) {}
Polynomial(const std::vector<T>& c) : coeff_(c) {}
Polynomial(const T c[], typename std::vector<T>::size_type deg)
: coeff_(c, c + deg + 1) {}
Polynomial(const Polynomial<T>&) = default;
Polynomial(Polynomial<T>&&) = default;
Polynomial<T>& operator=(const Polynomial<T>&) = default;
Polynomial<T>& operator=(Polynomial<T>&&) = default;
~Polynomial() = default;
auto operator()(const T& x) const;
auto eval(const T& x) const;
auto degree() const
{
return coeff_.size() - 1;
}
void IncrementDegree(const T& new_coeff = static_cast<T>(0))
{
coeff_.push_back(new_coeff);
}
auto DecrementDegree()
{
auto val = coeff_.back();
coeff_.pop_back();
return val;
}
auto& operator[](typename std::vector<T>::size_type idx)
{
return coeff_[idx];
}
const auto& operator[](typename std::vector<T>::size_type idx) const
{
return coeff_[idx];
}
private:
std::vector<T> coeff_;
static auto eval(const T& y, const T&x, const T& c)
{
return (y * x) + c;
}
};
template <typename T> inline auto Polynomial<T>::operator()(const T &x) const
{
auto rit = std::rbegin(coeff_);
auto y(*rit++);
for (; rit!= std::rend(coeff_) ; ++rit)
{
y = eval(y, x, *rit);
}
return y;
}
template <typename T> inline auto Polynomial<T>::eval(const T& x) const
{
auto rit = std::rbegin(coeff_);
auto y(*rit++);
auto dy = static_cast<T>(0);
for (; rit!= std::rend(coeff_) ; ++rit)
{
dy = eval(dy, x, y);
y = eval(y, x, *rit);
}
return std::make_pair(y, dy);
}
}
}
| 21.066667 | 81 | 0.533906 | [
"vector"
] |
fdef9ccd5f44e6926a291ca3dd3e096d6b27c774 | 13,487 | h | C | snapgear_linux/lib/libldap/contrib/ldapc++/src/LDAPAsynConnection.h | impedimentToProgress/UCI-BlueChip | 53e5d48b79079eaf60d42f7cb65bb795743d19fc | [
"MIT"
] | null | null | null | snapgear_linux/lib/libldap/contrib/ldapc++/src/LDAPAsynConnection.h | impedimentToProgress/UCI-BlueChip | 53e5d48b79079eaf60d42f7cb65bb795743d19fc | [
"MIT"
] | null | null | null | snapgear_linux/lib/libldap/contrib/ldapc++/src/LDAPAsynConnection.h | impedimentToProgress/UCI-BlueChip | 53e5d48b79079eaf60d42f7cb65bb795743d19fc | [
"MIT"
] | 3 | 2016-06-13T13:20:56.000Z | 2019-12-05T02:31:23.000Z | /*
* Copyright 2000, OpenLDAP Foundation, All Rights Reserved.
* COPYING RESTRICTIONS APPLY, see COPYRIGHT file
*/
#ifndef LDAP_ASYN_CONNECTION_H
#define LDAP_ASYN_CONNECTION_H
#include<iostream>
#include<string>
#include<ldap.h>
#include<lber.h>
#include <LDAPMessageQueue.h>
#include <LDAPConstraints.h>
#include <LDAPModification.h>
#include <LDAPModList.h>
#include <LDAPUrl.h>
#include <LDAPUrlList.h>
class LDAPEntry;
class LDAPAttribute;
//* Main class for an asynchronous LDAP connection
/**
* This class represents an asynchronous connection to an LDAP-Server. It
* provides the methods for authentication, and all other LDAP-Operations
* (e.g. search, add, delete, etc.)
* All of the LDAP-Operations return a pointer to a LDAPMessageQueue-Object,
* which can be used to obtain the results of that operation.
* A basic example of this class could be like this: <BR>
* 1. Create a new LDAPAsynConnection Object: <BR>
* 2. Use the init-method to initialize the connection <BR>
* 3. Call the bind-method to authenticate to the directory <BR>
* 4. Obtain the bind results from the return LDAPMessageQueue-Object <BR>
* 5. Perform on of the operations on the directory (add, delete, search, ..)
* <BR>
* 6. Use the return LDAPMessageQueue to obtain the results of the operation
* <BR>
* 7. Close the connection (feature not implemented yet :) ) <BR>
*/
class LDAPAsynConnection{
public :
/**
* Constant for the Search-Operation to indicate a Base-Level
* Search
*/
static const int SEARCH_BASE=0;
/**
* Constant for the Search-Operation to indicate a One-Level
* Search
*/
static const int SEARCH_ONE=1;
/**
* Constant for the Search-Operation to indicate a subtree
* Search
*/
static const int SEARCH_SUB=2;
// static const int SEARCH_SUB=LDAP_SCOPE_SUBTREE;
// static const int SEARCH_ONE=LDAP_SCOPE_ONELEVEL;
// static const int SEARCH_SUB=LDAP_SCOPE_SUBTREE;
/** Construtor that initializes a connection to a server
* @param hostname Name (or IP-Adress) of the destination host
* @param port Port the LDAP server is running on
* @param cons Default constraints to use with operations over
* this connection
*/
LDAPAsynConnection(const std::string& hostname=std::string("localhost"),
int port=389, LDAPConstraints *cons=new LDAPConstraints() );
//* Destructor
virtual ~LDAPAsynConnection();
/**
* Initializes a connection to a server.
*
* There actually no
* communication to the server. Just the object is initialized
* (e.g. this method is called within the
* LDAPAsynConnection(char*,int,LDAPConstraints) constructor.)
* @param hostname The Name or IP-Address of the destination
* LDAP-Server
* @param port The Network Port the server is running on
*/
void init(const std::string& hostname, int port);
/**
* Start TLS on this connection. This isn't in the constructor,
* because it could fail (i.e. server doesn't have SSL cert, client
* api wasn't compiled against OpenSSL, etc.). If you need TLS,
* then you should error if this call fails with an error code.
*/
int start_tls();
/** Simple authentication to a LDAP-Server
*
* @throws LDAPException If the Request could not be sent to the
* destination server, a LDAPException-object contains the
* error that occured.
* This method does a simple (username, password) bind to the server.
* Other, saver, authentcation methods are provided later
* @param dn the distiguished name to bind as
* @param passwd cleartext password to use
*/
LDAPMessageQueue* bind(const std::string& dn="", const std::string& passwd="",
const LDAPConstraints *cons=0);
/** Performing a search on a directory tree.
*
* Use the search method to perform a search on the LDAP-Directory
* @throws LDAPException If the Request could not be sent to the
* destination server, a LDAPException-object contains the
* error that occured.
* @param base The distinguished name of the starting point for the
* search operation
* @param scope The scope of the search. Possible values: <BR>
* LDAPAsynConnection::SEARCH_BASE, <BR>
* LDAPAsynConnection::SEARCH_ONE, <BR>
* LDAPAsynConnection::SEARCH_SUB
* @param filter The std::string representation of a search filter to
* use with this operation
* @param attrsOnly true if only the attributes names (no values)
* should be returned
* @param cons A set of constraints that should be used with this
* request
*/
LDAPMessageQueue* search(const std::string& base="", int scope=0,
const std::string& filter="objectClass=*",
const StringList& attrs=StringList(),
bool attrsOnly=false,
const LDAPConstraints *cons=0);
/** Delete an entry from the directory
*
* This method sends a delete request to the server
* @throws LDAPException If the Request could not be sent to the
* destination server, a LDAPException-object contains the
* error that occured.
* @param dn Distinguished name of the entry that should be deleted
* @param cons A set of constraints that should be used with this
* request
*/
LDAPMessageQueue* del(const std::string& dn, const LDAPConstraints *cons=0);
/**
* Perform the COMPARE-operation on an attribute
*
* @throws LDAPException If the Request could not be sent to the
* destination server, a LDAPException-object contains the
* error that occured.
* @param dn Distinguished name of the entry for which the compare
* should be performed
* @param attr An Attribute (one (!) value) to use for the
* compare operation
* @param cons A set of constraints that should be used with this
* request
*/
LDAPMessageQueue* compare(const std::string& dn,
const LDAPAttribute& attr,
const LDAPConstraints *cons=0);
/** Add an entry to the directory
*
* @throws LDAPException If the Request could not be sent to the
* destination server, a LDAPException-object contains the
* error that occured.
* @param le The entry that will be added to the directory
*/
LDAPMessageQueue* add( const LDAPEntry* le,
const LDAPConstraints *const=0);
/** Apply modifications to attributes of an entry
*
* @throws LDAPException If the Request could not be sent to the
* destination server, a LDAPException-object contains the
* error that occured.
* @param dn Distiguished Name of the Entry to modify
* @param modlist A set of modification that should be applied
* to the Entry
* @param cons A set of constraints that should be used with this
* request
*/
LDAPMessageQueue* modify(const std::string& dn,
const LDAPModList *modlist,
const LDAPConstraints *cons=0);
/** modify the DN of an entry
*
* @throws LDAPException If the Request could not be sent to the
* destination server, a LDAPException-object contains the
* error that occured.
* @param dn DN to modify
* @param newRDN The new relative DN for the entry
* @param delOldRDN true=The old RDN will be removed from the
* attributes <BR>
* false=The old RDN will still be present in the
* attributes of the entry
* @param newParentDN The DN of the new parent entry of the entry
* 0 to keep the old one
*/
LDAPMessageQueue* rename(const std::string& dn,
const std::string& newRDN,
bool delOldRDN=false, const std::string& newParentDN="",
const LDAPConstraints* cons=0);
/** Perform a LDAP extended Operation
*
* @throws LDAPException If the Request could not be sent to the
* destination server, a LDAPException-object contains the
* error that occured.
* @param oid The dotted decimal representation of the extended
* Operation that should be performed
* @param value The data asociated with this operation
* @param cons A set of constraints that should be used with this
* request
*/
LDAPMessageQueue* extOperation(const std::string& oid,
const std::string& value="", const LDAPConstraints *cons=0);
/** End an outstanding request
*
* @param q All outstanding request related to this LDAPMessageQueue
* will be abandoned
*/
void abandon(LDAPMessageQueue *q);
/**
* Performs the UNBIND-operation on the destination server
*
* @throws LDAPException in any case of an error
*/
void unbind();
/**
* @returns The C-APIs LDAP-structure that is associated with the
* current connection
*/
LDAP* getSessionHandle() const ;
/**
* @returns The Hostname of the destination server of the
* connection.
*/
const std::string& getHost() const;
/**
* @returns The Port to which this connection is connecting to on
* the remote server.
*/
int getPort() const;
/** Change the default constraints of the connection
*
* @parameter cons cons New LDAPConstraints to use with the connection
*/
void setConstraints(LDAPConstraints *cons);
/** Get the default constraints of the connection
*
* @return Pointer to the LDAPConstraints-Object that is currently
* used with the Connection
*/
const LDAPConstraints* getConstraints() const;
/**
* This method is used internally for automatic referral chasing.
* It tries to bind to a destination server of the URLs of a
* referral.
*
* @throws LDAPException in any case of an error
* @param urls Contains a std::list of LDAP-Urls that indicate the
* destinations of a referral
* @param usedUrl After this method has successfully bind to one of
* the Destination URLs this parameter contains the URLs
* which was contacted.
* @param cons An LDAPConstraints-Object that should be used for
* the new connection. If this object contains a
* LDAPRebind-object it is used to bind to the new server
*/
LDAPAsynConnection* referralConnect(const LDAPUrlList& urls,
LDAPUrlList::const_iterator& usedUrl,
const LDAPConstraints* cons) const;
/**
* Turn on caching, maxmem is in MB and timeout is in seconds.
* maxmem can be zero if you want to restrict caching by timeout only.
*/
int enableCache(long timeout, long maxmem);
/// disable caching.
void disableCache();
/// is cacheEnabled?
bool getCacheEnabled() { return m_cacheEnabled;};
/// uncache a specific dn. Used internally by methods that write.
void uncache_entry(std::string &dn);
/// used to clear the cache. Probably should be used after creating
/// an object that a cached search should find.
void flush_cache();
private :
/**
* Private copy constructor. So nobody can call it.
*/
LDAPAsynConnection(const LDAPAsynConnection& lc){};
/**
* A pointer to the C-API LDAP-structure that is associated with
* this connection
*/
LDAP *cur_session;
/**
* A pointer to the default LDAPConstrains-object that is used when
* no LDAPConstraints-parameter is provided with a call for a
* LDAP-operation
*/
LDAPConstraints *m_constr;
/**
* The name of the destination host
*/
std::string m_host;
/**
* The port the destination server is running on.
*/
int m_port;
protected:
/**
* Is caching enabled?
*/
bool m_cacheEnabled;
};
#endif //LDAP_ASYN_CONNECTION_H
| 39.3207 | 86 | 0.588863 | [
"object"
] |
fdf1051d07a7df0f57a6a1bddd30596008d55d2c | 12,104 | h | C | mathgl-2.4.3/include/mgl2/qmathgl.h | angelamsj/cruise-control | 0fb94e86217afee2e637de694b0148b99b052ccf | [
"MIT"
] | null | null | null | mathgl-2.4.3/include/mgl2/qmathgl.h | angelamsj/cruise-control | 0fb94e86217afee2e637de694b0148b99b052ccf | [
"MIT"
] | null | null | null | mathgl-2.4.3/include/mgl2/qmathgl.h | angelamsj/cruise-control | 0fb94e86217afee2e637de694b0148b99b052ccf | [
"MIT"
] | null | null | null | /***************************************************************************
* qmathgl.h is part of Math Graphic Library
* Copyright (C) 2007-2016 Alexey Balakin <mathgl.abalakin@gmail.ru> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Library General Public License as *
* published by the Free Software Foundation; either version 3 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifndef _MGL_QMATHGL_H_
#define _MGL_QMATHGL_H_
//-----------------------------------------------------------------------------
#include <mgl2/wnd.h>
#include <QWidget>
#include <QPixmap>
//-----------------------------------------------------------------------------
class QTextEdit;
class QMenu;
class QMainWindow;
class QScrollArea;
class QSpinBox;
class QTimer;
class mglCanvas;
class mglTask;
//-----------------------------------------------------------------------------
/// Class is Qt widget which display MathGL graphics
class MGL_EXPORT QMathGL : public QWidget
{
Q_OBJECT
public:
QString appName; ///< Application name for message boxes
bool autoResize; ///< Allow auto resizing (default is false)
bool enableMouse; ///< Enable mouse handlers
bool enableWheel; ///< Enable mouse wheel handlers
QString primitives; ///< Manual primitives, defined by user
mglCanvas *gr; ///< Built-in mglCanvas instance (mglCanvasQT is used by default)
QMathGL(QWidget *parent = 0, Qt::WindowFlags f = 0);
virtual ~QMathGL();
double getRatio();
void setPopup(QMenu *p) { popup = p; } ///< Set popup menu pointer
void setSize(int w, int h); ///< Set window/picture sizes
void setGraph(HMGL GR); ///< Set grapher object
inline void setGraph(mglGraph *GR)
{ setGraph(GR->Self()); }
inline HMGL getGraph() { return (HMGL)gr; }
/// Set drawing functions and its parameter
void setDraw(int (*func)(mglBase *gr, void *par), void *par);
void setDraw(mglDraw *dr);
inline void setDraw(int (*func)(mglGraph *gr))
{ setDraw(func?mgl_draw_graph:0,(void*)func); }
inline void zoomRegion(mreal xx1,mreal xx2,mreal yy1, mreal yy2)
{ x1=xx1; y1=yy1; x2=xx2; y2=yy2; }
/// Get mglDraw pointer or NULL
inline mglDraw *getClass()
{ mglDraw *d=0;
if(draw_func==mgl_draw_class) d = (mglDraw*)draw_par;
if(draw) d = draw;
return d; }
int getPer() const {return int(per);} ///< Get perspective value
int getPhi() const {return int(phi);} ///< Get Phi-angle value
int getTet() const {return int(tet);} ///< Get Theta-angle value
bool getAlpha() const {return alpha;} ///< Get transparency state
bool getLight() const {return light;} ///< Get lightning state
bool getZoom() const {return zoom;} ///< Get mouse zooming state
bool getRotate() const {return rotate;}///< Get mouse rotation state
bool getViewYZ() const {return viewYZ;}///< Get mouse rotation axis
bool getPause() const {return pause;} ///< Get calculation pause state
bool isActive(int xs,int ys); ///< Check if active point is pressed
public slots:
void refresh(); ///< Redraw image with new zoom and view parameters
void refreshHQ(); ///< Redraw image with HQ (can be slower than refresh())
void update(); ///< Update picture
void copy(); ///< copy graphics to clipboard
void copyClickCoor(); ///< copy click coordinates to clipboard
void print(); ///< Print plot
void stop(); ///< Stop execution
void setPer(int p); ///< Set perspective value
void setPhi(int p); ///< Set Phi-angle value
void setTet(int t); ///< Set Theta-angle value
void setAlpha(bool a); ///< Switch on/off transparency
void setLight(bool l); ///< Switch on/off lightning
void setGrid(bool r); ///< Switch on/off grid drawing
void imgSize(int w, int h); ///< Set image size
void setViewYZ(bool v); ///< Switch on/off rotation around Y and Z axis
void setDotsPreview(bool d=true); ///< Set to use dots for image preview/rotation
void setCustZoom(bool a); ///< Switch on/off using custom zoom
void setCustDraw(bool a); ///< Switch on/off using custom draw
void setZoom(bool z); ///< Switch on/off mouse zooming
void setRotate(bool r); ///< Switch on/off mouse rotation
void setPause(bool p); ///< Switch on/off calculation pause
void zoomIn(); ///< Zoom in graphics
void zoomOut(); ///< Zoom out graphics
void restore(); ///< Restore zoom and rotation to default values
void setZoomScl(double s=0.5); ///< Set factor for zooming (must be s>0)
void setShiftScl(double s=0.25); ///< Set factor for shifting (must be s!=0)
// void reload(); ///< Reload data and execute script
void shiftLeft(); ///< Shift graphics to left direction
void shiftRight(); ///< Shift graphics to right direction
void shiftUp(); ///< Shift graphics to up direction
void shiftDown(); ///< Shift graphics to down direction
void exportPNG(QString fname=""); ///< export to PNG file
void exportPNGs(QString fname=""); ///< export to PNG file (no transparency)
void exportGIF(QString fname=""); ///< export to GIF file
void exportJPG(QString fname=""); ///< export to JPEG file
void exportBPS(QString fname=""); ///< export to bitmap EPS file
void exportEPS(QString fname=""); ///< export to vector EPS file
void exportSVG(QString fname=""); ///< export to SVG file
void exportTEX(QString fname=""); ///< export to SVG file
void exportTGA(QString fname=""); ///< export to TGA file
void exportXYZ(QString fname=""); ///< export to XYZ file
void exportOBJ(QString fname=""); ///< export to OBJ file
void exportSTL(QString fname=""); ///< export to STL file
void exportOFF(QString fname=""); ///< export to OFF file
// void exportX3D(QString fname=""); ///< export to XYZ file
void exportPRC(QString fname=""); ///< export to PRC file
void exportMGLD(QString fname=""); ///< export to MGLD file
void setMGLFont(QString path); ///< restore/load font for graphics
void addMark(); ///< add marker into primitives
void addLine(); ///< add line into primitives
void addRect(); ///< add rectangle into primitives
void addCurve(); ///< add curve into primitives
void addRhomb(); ///< add rhombus into primitives
void addEllipse(); ///< add ellipse into primitives
void addArc(); ///< add arc into primitives
void addPolygon(int n=-1); ///< add polygon into primitives
void addText(QString txt=""); ///< add text into primitives
void setStyle(int id, QString stl);///< set style for primitive with id
void adjust(); ///< Adjust plot size to fill entire window
void nextSlide(); ///< Show next slide
void prevSlide(); ///< Show previous slide
void animation(bool st=true); ///< Start animation
void about(); ///< Show about information
void aboutQt(); ///< Show information about Qt version
signals:
void gridChanged(int); ///< Grid drawing changed (by mouse or by toolbar)
void phiChanged(int); ///< Phi angle changed (by mouse or by toolbar)
void tetChanged(int); ///< Tet angle changed (by mouse or by toolbar)
void perChanged(int); ///< Perspective changed (by mouse or by toolbar)
void alphaChanged(bool); ///< Transparency changed (by toolbar)
void lightChanged(bool); ///< Lighting changed (by toolbar)
void zoomChanged(bool); ///< Zooming changed (by toolbar)
void rotateChanged(bool); ///< Rotation changed (by toolbar)
void pauseChanged(bool); ///< Pause changed (by toolbar)
void usePrimChanged(bool); ///< Use primitive changed (i.e. have or not drawing function)
void viewYZChanged(bool); ///< Rotation axis changed (by toolbar)
void mouseClick(mreal,mreal,mreal); ///< Position of mouse click
void frameChanged(int); ///< Need another frame to show
void showWarn(QString); ///< Show warnings
void posChanged(QString message); ///< user click to show mouse position
void objChanged(int objId); ///< User click to select object/line
void refreshData();
void doubleClick(int id); ///< Double mouse click by object with id
void askStyle(int id); ///< Update style
/// user can define its own zooming function
void customZoom(double x1, double y1, double x2, double y2, double tet, double phi, double per);
/// user can define its own drawing/setting function which will be called before main drawing
void customDraw(double x1, double y1, double x2, double y2, bool draw);
protected:
void paintEvent(QPaintEvent *);
void resizeEvent(QResizeEvent *);
void mousePressEvent(QMouseEvent *);
void mouseReleaseEvent(QMouseEvent *);
void mouseMoveEvent(QMouseEvent *);
void wheelEvent(QWheelEvent *);
void mouseDoubleClickEvent(QMouseEvent *);
void *draw_par; ///< Parameters for drawing function mglCanvasWnd::DrawFunc.
/// Drawing function for window procedure. It should return the number of frames.
int (*draw_func)(mglBase *gr, void *par);
mglDraw *draw; ///< Class for drawing -- need to call directly due to inheritance mechanism
QString mousePos; ///< Last mouse position
QPixmap pic; ///< Pixmap for drawing (changed by update)
QImage img; ///< Last used HQ image
double tet, phi; ///< Rotation angles
double per; ///< Value of perspective ( must be in [0,1) )
bool alpha; ///< Transparency state
bool light; ///< Lightning state
bool pause; ///< Pause state
bool custZoom; ///< Use custom zoom instead of built in
bool custDraw; ///< Use custom draw before main drawing
bool zoom; ///< Mouse zoom state
bool grid; ///< Grid drawing state
bool rotate; ///< Mouse rotation state
bool viewYZ; ///< Set mouse rotation around Y and Z axis (instead of X and Z)
bool dotsRefr; ///< Set dots for image preview/rotation
mreal x1,x2,y1,y2; ///< Zoom in region
mreal ax1,ax2,ay1,ay2; ///< Axis range zoom
QMenu *popup; ///< Pointer to pop-up menu
QTimer *timer; ///< Timer for animation
QTimer *timerRefr; ///< Timer for redrawing
private slots:
void afterPlot(); ///< minor tuning after plot was done
private:
int x0, y0, xe, ye; ///< Temporary variables for mouse
double sclZ; ///< Scale factor for zooming
double sclS; ///< Scale factor for shifting
uchar *grBuf;
void drawPrim();
int prevQuality;
// QThread *thread;
// mglTask *task;
};
//-----------------------------------------------------------------------------
/// Class for drawing the MGL script
class MGL_EXPORT mglDrawScript : public mglDraw
{
public:
HMPR par; ///< Parser to be used
QString text; ///< Script to be drawn
long line; ///< Line which will be highlighted
mglDrawScript(HMPR p):mglDraw() { par=p; line=-1; }
virtual ~mglDrawScript() {}
int Draw(mglGraph *gr)
{
wchar_t *wtext;
wtext = new wchar_t[text.size()+1];
text.toWCharArray(wtext);
wtext[text.size()] = 0;
gr->Highlight(line + 1);
mgl_parse_textw(gr->Self(), par, wtext);
delete[] wtext;
return 0;
}
};
//-----------------------------------------------------------------------------
/// Convert bitmap from mglCanvasWnd to QPixmap
void mglConvertFromGraph(QPixmap &pic, mglCanvas *gr, uchar **buf, QImage *out=NULL);
/// Make menu, toolbars and return popup menu for MainWindow
MGL_EXPORT QMenu *mglMakeMenu(QMainWindow* Wnd, QMathGL* QMGL, QSpinBox*& tet, QSpinBox*& phi);
//-----------------------------------------------------------------------------
#endif
| 47.841897 | 97 | 0.64111 | [
"object",
"vector"
] |
fdf2e69ca2433f2953993e009aa55ab2d5fbafbb | 1,237 | h | C | cclient/api/extended/broadcast_bundle.h | ed2k/entangled | cbcc7bbc4e22ed0010a0e63f0d313cec71e14d0b | [
"Apache-2.0"
] | null | null | null | cclient/api/extended/broadcast_bundle.h | ed2k/entangled | cbcc7bbc4e22ed0010a0e63f0d313cec71e14d0b | [
"Apache-2.0"
] | null | null | null | cclient/api/extended/broadcast_bundle.h | ed2k/entangled | cbcc7bbc4e22ed0010a0e63f0d313cec71e14d0b | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2019 IOTA Stiftung
* https://github.com/iotaledger/entangled
*
* Refer to the LICENSE file for licensing information
*/
#ifndef CCLIENT_API_BROADCAST_BUNDLE_H
#define CCLIENT_API_BROADCAST_BUNDLE_H
#include "cclient/http/http.h"
#include "common/model/bundle.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* Re-broadcasts all transactions in a bundle given the tail transaction hash.
* It might be useful when transactions did not properly propagate,
* particularly in the case of large bundles.
*
* @param {iota_client_service_t} serv - client service
* @param {flex_trit_t} tail_hash - Tail transaction hash
* @param {bundle_transactions_t} bundle - a bundle object
*
* @returns {retcode_t}
* - `INVALID_HASH`: Invalid tail transaction hash
* - `INVALID_BUNDLE`: Invalid bundle
*
* Refer:
* https://github.com/iotaledger/iota.js/blob/next/packages/core/src/createBroadcastBundle.ts#L38
*/
retcode_t iota_client_broadcast_bundle(iota_client_service_t const* const serv,
flex_trit_t const* const tail_hash,
bundle_transactions_t* const bundle);
#ifdef __cplusplus
}
#endif
#endif // CCLIENT_API_BROADCAST_BUNDLE_H
| 28.767442 | 97 | 0.719483 | [
"object",
"model"
] |
fdf35b279ddd0d9dfce6b4a61ee8ccbddb8181e5 | 20,934 | h | C | projects/02.3_simh/4.x+realcons/src/VAX/vax750_defs.h | wschaub/BlinkenBone | dd638c16fadbd3b8c8c3f22b5bd35597e094009f | [
"MIT"
] | null | null | null | projects/02.3_simh/4.x+realcons/src/VAX/vax750_defs.h | wschaub/BlinkenBone | dd638c16fadbd3b8c8c3f22b5bd35597e094009f | [
"MIT"
] | null | null | null | projects/02.3_simh/4.x+realcons/src/VAX/vax750_defs.h | wschaub/BlinkenBone | dd638c16fadbd3b8c8c3f22b5bd35597e094009f | [
"MIT"
] | null | null | null | /* vax750_defs.h: VAX 750 model-specific definitions file
Copyright (c) 2010-2011, Matt Burke
This module incorporates code from SimH, Copyright (c) 2004-2008, Robert M Supnik
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 AUTHOR(S) 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.
Except as contained in this notice, the name(s) of the author(s) shall not be
used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from the author(s).
21-Oct-2012 MB First Version
This file covers the VAX 11/750, the second VAX.
System memory map
00 0000 - 7F FFFF main memory
80 0000 - EF FFFF reserved
F0 0000 - F0 FFFF writeable control store
F1 0000 - F1 FFFF reserved
F2 0000 - F2 0010 memory controller
F2 0400 - F2 07FF bootstrap ROM
F2 8000 - F2 88FF Massbus adapter 0
F2 A000 - F2 A8FF Massbus adapter 1
F2 C000 - F2 C8FF Massbus adapter 2
F3 0000 - F3 09FF Unibus adapter 0
F3 2000 - F3 29FF Unibus adapter 1
*/
#ifndef FULL_VAX
#define FULL_VAX 1
#endif
#ifndef VAX_750_DEFS_H_
#define VAX_750_DEFS_H_ 1
/* Microcode constructs */
#define VAX750_SID (2 << 24) /* system ID */
#define VAX750_MICRO (99 << 8) /* ucode revision */
#define VAX750_HWREV (156) /* hw revision */
#define CON_HLTPIN 0x0200 /* external CPU halt */
#define CON_HLTINS 0x0600 /* HALT instruction */
#define MCHK_CSPE 0x01 /* control store parity error */
#define MCHK_BPE 0x02 /* bus error or tb/cache parity error */
#define VER_FPLA 0x0C /* FPLA version */
#define VER_WCSP (VER_FPLA) /* WCS primary version */
#define VER_WCSS 0x12 /* WCS secondary version */
#define VER_PCS ((VER_WCSS >> 4) & 0x3) /* PCS version */
/* Interrupts */
#define IPL_HMAX 0x17 /* highest hwre level */
#define IPL_HMIN 0x14 /* lowest hwre level */
#define IPL_HLVL (IPL_HMAX - IPL_HMIN + 1) /* # hardware levels */
#define IPL_SMAX 0xF /* highest swre level */
/* Nexus constants */
#define NEXUS_NUM 16 /* number of nexus */
#define MCTL_NUM 2 /* number of mem ctrl */
#define MBA_NUM 2 /* number of MBA's */
#define TR_MCTL 0 /* nexus assignments */
#define TR_MBA0 4
#define TR_MBA1 5
#define TR_UBA 8
#define TR_CI 15
#define NEXUS_HLVL (IPL_HMAX - IPL_HMIN + 1)
#define SCB_NEXUS 0x100 /* nexus intr base */
#define SBI_FAULTS 0xFC000000 /* SBI fault flags */
/* Internal I/O interrupts - relative except for clock and console */
#define IPL_CLKINT 0x18 /* clock IPL */
#define IPL_TTINT 0x14 /* console IPL */
#define IPL_MCTL0 (0x15 - IPL_HMIN)
#define IPL_MCTL1 (0x15 - IPL_HMIN)
#define IPL_UBA (0x15 - IPL_HMIN)
#define IPL_MBA0 (0x15 - IPL_HMIN)
#define IPL_MBA1 (0x15 - IPL_HMIN)
#define IPL_CI (0x15 - IPL_HMIN)
/* Nexus interrupt macros */
#define SET_NEXUS_INT(dv) nexus_req[IPL_##dv] |= (1 << TR_##dv)
#define CLR_NEXUS_INT(dv) nexus_req[IPL_##dv] &= ~(1 << TR_##dv)
/* Machine specific IPRs */
#define MT_CSRS 28 /* Console storage */
#define MT_CSRD 29
#define MT_CSTS 30
#define MT_CSTD 31
#define MT_CMIE 23 /* CMI error */
#define MT_TBDR 36 /* TB disable */
#define MT_CADR 37 /* Cache disable */
#define MT_MCESR 38 /* MCHK err sts */
#define MT_CAER 39 /* Cache error */
#define MT_ACCS 40 /* FPA control */
#define MT_IORESET 55 /* Unibus Init */
#define MT_MAX 63 /* last valid IPR */
/* Machine specific reserved operand tests */
/* 780 microcode patch 37 - only test LR<23:0> for appropriate length */
#define ML_LR_TEST(r) if (((uint32)((r) & 0xFFFFFF)) > 0x200000) RSVD_OPND_FAULT
/* 780 microcode patch 38 - only test PxBR<31>=1, PxBR<30> = 0, and xBR<1:0> = 0 */
#define ML_PXBR_TEST(r) if (((((uint32)(r)) & 0x80000000) == 0) || \
((((uint32)(r)) & 0x40000003) != 0)) RSVD_OPND_FAULT
#define ML_SBR_TEST(r) if ((((uint32)(r)) & 0x00000003) != 0) RSVD_OPND_FAULT
/* 780 microcode patch 78 - test xCBB<1:0> = 0 */
#define ML_PA_TEST(r) if ((((uint32)(r)) & 0x00000003) != 0) RSVD_OPND_FAULT
#define LP_AST_TEST(r) if ((r) > AST_MAX) RSVD_OPND_FAULT
#define LP_MBZ84_TEST(r) if ((((uint32)(r)) & 0xF8C00000) != 0) RSVD_OPND_FAULT
#define LP_MBZ92_TEST(r) if ((((uint32)(r)) & 0x7FC00000) != 0) RSVD_OPND_FAULT
#define MT_AST_TEST(r) r = (r) & 07; \
if ((r) > AST_MAX) RSVD_OPND_FAULT
/* Memory */
#define MAXMEMWIDTH 21 /* max mem, 16k chips */
#define MAXMEMSIZE (1 << MAXMEMWIDTH)
#define MAXMEMWIDTH_Y 23 /* max mem, 64k chips */
#define MAXMEMSIZE_Y (1 << MAXMEMWIDTH_Y)
#define MAXMEMWIDTH_X 24 /* max mem, 256k chips */
#define MAXMEMSIZE_X ((1 << MAXMEMWIDTH_X) - (1 << 20)) /* 15M Max before interfering with Register Space */
#define INITMEMSIZE (1 << MAXMEMWIDTH) /* initial memory size */
#define MEMSIZE (cpu_unit.capac)
#define ADDR_IS_MEM(x) (((uint32) (x)) < MEMSIZE)
#define MEM_MODIFIERS { UNIT_MSIZE, (1u << 20), NULL, "1M", &cpu_set_size, NULL, NULL, "Set Memory to 1M bytes" }, \
{ UNIT_MSIZE, (1u << 21), NULL, "2M", &cpu_set_size, NULL, NULL, "Set Memory to 2M bytes" }, \
{ UNIT_MSIZE, (1u << 22), NULL, "4M", &cpu_set_size, NULL, NULL, "Set Memory to 4M bytes" }, \
{ UNIT_MSIZE, (1u << 23), NULL, "8M", &cpu_set_size, NULL, NULL, "Set Memory to 8M bytes" }, \
{ UNIT_MSIZE, (1u << 23) + (1u << 22), NULL, "12M", &cpu_set_size, NULL, NULL, "Set Memory to 12M bytes" }, \
{ UNIT_MSIZE, (1u << 23) + (6u << 20), NULL, "14M", &cpu_set_size, NULL, NULL, "Set Memory to 14M bytes" }, \
{ UNIT_MSIZE, (1u << 23) + (7u << 20), NULL, "15M", &cpu_set_size, NULL, NULL, "Set Memory to 15M bytes" }, \
{ MTAB_XTD|MTAB_VDV|MTAB_NMO, 0, "MEMORY", NULL, NULL, &cpu_show_memory, NULL, "Display memory configuration" }
extern t_stat cpu_show_memory (FILE* st, UNIT* uptr, int32 val, CONST void* desc);
#define CPU_MODEL_MODIFIERS { MTAB_XTD|MTAB_VDV, 0, "MODEL", NULL, \
NULL, &cpu_show_model, NULL, "Display the simulator CPU Model" }, \
{ MTAB_XTD|MTAB_VDV, 0, "BOOTDEV", "BOOTDEV={A|B|C|D}", \
&vax750_set_bootdev, &vax750_show_bootdev, NULL, "Set Boot Device" }
extern t_stat vax750_set_bootdev (UNIT *uptr, int32 val, CONST char *cptr, void *desc);
extern t_stat vax750_show_bootdev (FILE *st, UNIT *uptr, int32 val, CONST void *desc);
/* Unibus I/O registers */
#define UBADDRWIDTH 18 /* Unibus addr width */
#define UBADDRSIZE (1u << UBADDRWIDTH) /* Unibus addr length */
#define UBADDRMASK (UBADDRSIZE - 1) /* Unibus addr mask */
#define IOPAGEAWIDTH 13 /* IO addr width */
#define IOPAGESIZE (1u << IOPAGEAWIDTH) /* IO page length */
#define IOPAGEMASK (IOPAGESIZE - 1) /* IO addr mask */
#define UBADDRBASE 0xFC0000 /* Unibus addr base */
#define IOPAGEBASE 0xFFE000 /* IO page base */
#define ADDR_IS_IO(x) ((((uint32) (x)) >= UBADDRBASE) && \
(((uint32) (x)) < (UBADDRBASE + UBADDRSIZE)))
#define ADDR_IS_IOP(x) (((uint32) (x)) >= IOPAGEBASE)
/* Nexus register space */
#define REGAWIDTH 19 /* REG addr width */
#define REG_V_NEXUS 13 /* nexus number */
#define REG_M_NEXUS 0xF
#define REG_V_OFS 2 /* register number */
#define REG_M_OFS 0x7FF
#define REGSIZE (1u << REGAWIDTH) /* REG length */
#define REGBASE 0xF00000 /* REG addr base */
#define ADDR_IS_REG(x) ((((uint32) (x)) >= REGBASE) && \
(((uint32) (x)) < (REGBASE + REGSIZE)))
#define NEXUSBASE (REGBASE + 0x20000)
#define NEXUS_GETNEX(x) (((x) >> REG_V_NEXUS) & REG_M_NEXUS)
#define NEXUS_GETOFS(x) (((x) >> REG_V_OFS) & REG_M_OFS)
/* ROM address space in memory controllers */
#define ROMAWIDTH 10 /* ROM addr width */
#define ROMSIZE (1u << ROMAWIDTH) /* ROM size */
#define ROMAMASK (ROMSIZE - 1) /* ROM addr mask */
#define ROMBASE (NEXUSBASE + 0x400)
#define ADDR_IS_ROM(x) ((((uint32) (x)) >= ROMBASE) && \
(((uint32) (x)) < (ROMBASE + ROMSIZE)))
/* Other address spaces */
#define ADDR_IS_CDG(x) (0)
#define ADDR_IS_NVR(x) (0)
/* Unibus I/O modes */
#define READ 0 /* PDP-11 compatibility */
#define WRITE (L_WORD)
#define WRITEB (L_BYTE)
/* Common CSI flags */
#define CSR_V_GO 0 /* go */
#define CSR_V_IE 6 /* interrupt enable */
#define CSR_V_DONE 7 /* done */
#define CSR_V_BUSY 11 /* busy */
#define CSR_V_ERR 15 /* error */
#define CSR_GO (1u << CSR_V_GO)
#define CSR_IE (1u << CSR_V_IE)
#define CSR_DONE (1u << CSR_V_DONE)
#define CSR_BUSY (1u << CSR_V_BUSY)
#define CSR_ERR (1u << CSR_V_ERR)
/* Timers */
#define TMR_CLK 0 /* 100Hz clock */
/* I/O system definitions */
#define DZ_MUXES 4 /* max # of DZV muxes */
#define DZ_LINES 8 /* lines per DZV mux */
#define VH_MUXES 4 /* max # of DHQ muxes */
#define DLX_LINES 16 /* max # of KL11/DL11's */
#define DCX_LINES 16 /* max # of DC11's */
#define MT_MAXFR (1 << 16) /* magtape max rec */
#define DEV_V_UBUS (DEV_V_UF + 0) /* Unibus */
#define DEV_V_MBUS (DEV_V_UF + 1) /* Massbus */
#define DEV_V_NEXUS (DEV_V_UF + 2) /* Nexus */
#define DEV_V_CI (DEV_V_UF + 3) /* CI */
#define DEV_V_FFUF (DEV_V_UF + 4) /* first free flag */
#define DEV_UBUS (1u << DEV_V_UBUS)
#define DEV_MBUS (1u << DEV_V_MBUS)
#define DEV_NEXUS (1u << DEV_V_NEXUS)
#define DEV_CI (1u << DEV_V_CI)
#define DEV_QBUS (0)
#define DEV_Q18 (0)
#define UNIBUS TRUE /* Unibus only */
#define DEV_RDX 16 /* default device radix */
/* Device information block
For Massbus devices,
ba = Massbus number
lnt = Massbus ctrl type
ack[0] = abort routine
For Nexus devices,
ba = Nexus number
lnt = number of consecutive nexi */
#define VEC_DEVMAX 4 /* max device vec */
typedef struct {
uint32 ba; /* base addr */
uint32 lnt; /* length */
t_stat (*rd)(int32 *dat, int32 ad, int32 md);
t_stat (*wr)(int32 dat, int32 ad, int32 md);
int32 vnum; /* vectors: number */
int32 vloc; /* locator */
int32 vec; /* value */
int32 (*ack[VEC_DEVMAX])(void); /* ack routine */
uint32 ulnt; /* IO length per-device */
/* Only need to be populated */
/* when numunits != num devices */
int32 numc; /* Number of controllers */
/* this field handles devices */
/* where multiple instances are */
/* simulated through a single */
/* DEVICE structure (e.g., DZ, VH, DL, DC). */
/* Populated by auto-configure */
} DIB;
/* Unibus I/O page layout - see pdp11_io_lib.c for address layout details
Massbus devices (RP, TU) do not appear in the Unibus IO page */
#define IOBA_AUTO (0) /* Assigned by Auto Configure */
/* Interrupt assignments; within each level, priority is right to left */
#define INT_V_DTA 0 /* BR6 */
#define INT_V_CR 1
#define INT_V_DZRX 0 /* BR5 */
#define INT_V_DZTX 1
#define INT_V_HK 2
#define INT_V_RL 3
#define INT_V_RQ 4
#define INT_V_TQ 5
#define INT_V_TS 6
#define INT_V_RY 7
#define INT_V_XU 8
#define INT_V_DMCRX 9
#define INT_V_DMCTX 10
#define INT_V_DUPRX 11
#define INT_V_DUPTX 12
#define INT_V_RK 13
#define INT_V_LPT 0 /* BR4 */
#define INT_V_PTR 1
#define INT_V_PTP 2
//#define XXXXXXXX 3 /* Former CR */
#define INT_V_VHRX 4
#define INT_V_VHTX 5
#define INT_V_TDRX 6
#define INT_V_TDTX 7
#define INT_DTA (1u << INT_V_DTA)
#define INT_CR (1u << INT_V_CR)
#define INT_DZRX (1u << INT_V_DZRX)
#define INT_DZTX (1u << INT_V_DZTX)
#define INT_HK (1u << INT_V_HK)
#define INT_RL (1u << INT_V_RL)
#define INT_RQ (1u << INT_V_RQ)
#define INT_TQ (1u << INT_V_TQ)
#define INT_TS (1u << INT_V_TS)
#define INT_RY (1u << INT_V_RY)
#define INT_XU (1u << INT_V_XU)
#define INT_LPT (1u << INT_V_LPT)
#define INT_VHRX (1u << INT_V_VHRX)
#define INT_VHTX (1u << INT_V_VHTX)
#define INT_PTR (1u << INT_V_PTR)
#define INT_PTP (1u << INT_V_PTP)
#define INT_DMCRX (1u << INT_V_DMCRX)
#define INT_DMCTX (1u << INT_V_DMCTX)
#define INT_DUPRX (1u << INT_V_DUPRX)
#define INT_DUPTX (1u << INT_V_DUPTX)
#define INT_RK (1u << INT_V_RK)
#define INT_TDRX (1u << INT_V_TDRX)
#define INT_TDTX (1u << INT_V_TDTX)
#define IPL_DTA (0x16 - IPL_HMIN)
#define IPL_CR (0x16 - IPL_HMIN)
#define IPL_DZRX (0x15 - IPL_HMIN)
#define IPL_DZTX (0x15 - IPL_HMIN)
#define IPL_HK (0x15 - IPL_HMIN)
#define IPL_RL (0x15 - IPL_HMIN)
#define IPL_RQ (0x15 - IPL_HMIN)
#define IPL_TQ (0x15 - IPL_HMIN)
#define IPL_TS (0x15 - IPL_HMIN)
#define IPL_RY (0x15 - IPL_HMIN)
#define IPL_XU (0x15 - IPL_HMIN)
#define IPL_LPT (0x14 - IPL_HMIN)
#define IPL_PTR (0x14 - IPL_HMIN)
#define IPL_PTP (0x14 - IPL_HMIN)
#define IPL_VHRX (0x14 - IPL_HMIN)
#define IPL_VHTX (0x14 - IPL_HMIN)
#define IPL_DMCRX (0x15 - IPL_HMIN)
#define IPL_DMCTX (0x15 - IPL_HMIN)
#define IPL_DUPRX (0x15 - IPL_HMIN)
#define IPL_DUPTX (0x15 - IPL_HMIN)
#define IPL_RK (0x15 - IPL_HMIN)
#define IPL_TDRX (0x14 - IPL_HMIN)
#define IPL_TDTX (0x14 - IPL_HMIN)
/* Device vectors */
#define VEC_AUTO (0) /* Assigned by Auto Configure */
#define VEC_FLOAT (0) /* Assigned by Auto Configure */
#define VEC_QBUS 0 /* Unibus system */
#define VEC_SET 0x200 /* Vector bits to set in Unibus vectors */
#define VEC_MASK 0x3FF /* Vector bits to return in Unibus vectors */
/* Interrupt macros */
#define IVCL(dv) ((IPL_##dv * 32) + INT_V_##dv)
#define NVCL(dv) ((IPL_##dv * 32) + TR_##dv)
#define IREQ(dv) int_req[IPL_##dv]
#define SET_INT(dv) int_req[IPL_##dv] = int_req[IPL_##dv] | (INT_##dv)
#define CLR_INT(dv) int_req[IPL_##dv] = int_req[IPL_##dv] & ~(INT_##dv)
#define IORETURN(f,v) ((f)? (v): SCPE_OK) /* cond error return */
/* Logging */
#define LOG_CPU_I 0x1 /* intexc */
#define LOG_CPU_R 0x2 /* REI */
#define LOG_CPU_P 0x4 /* context */
/* Massbus definitions */
#define MBA_RMASK 0x1F /* max 32 reg */
#define MBA_AUTO (uint32)0xFFFFFFFF /* Unassigned MBA */
#define MBE_NXD 1 /* nx drive */
#define MBE_NXR 2 /* nx reg */
#define MBE_GOE 3 /* err on GO */
/* Boot definitions */
#define BOOT_MB 0 /* device codes */
#define BOOT_HK 1 /* for VMB */
#define BOOT_RL 2
#define BOOT_UDA 17
#define BOOT_CI 32
#define BOOT_TD 64
/* Function prototypes for I/O */
int32 Map_ReadB (uint32 ba, int32 bc, uint8 *buf);
int32 Map_ReadW (uint32 ba, int32 bc, uint16 *buf);
int32 Map_WriteB (uint32 ba, int32 bc, const uint8 *buf);
int32 Map_WriteW (uint32 ba, int32 bc, const uint16 *buf);
int32 mba_rdbufW (uint32 mbus, int32 bc, uint16 *buf);
int32 mba_wrbufW (uint32 mbus, int32 bc, const uint16 *buf);
int32 mba_chbufW (uint32 mbus, int32 bc, uint16 *buf);
int32 mba_get_bc (uint32 mbus);
void mba_upd_ata (uint32 mbus, uint32 val);
void mba_set_exc (uint32 mbus);
void mba_set_don (uint32 mbus);
void mba_set_enbdis (DEVICE *dptr);
t_stat mba_show_num (FILE *st, UNIT *uptr, int32 val, CONST void *desc);
t_stat show_nexus (FILE *st, UNIT *uptr, int32 val, CONST void *desc);
void sbi_set_errcnf (void);
/* Function prototypes for system-specific unaligned support
11/750 treats unaligned like aligned */
#define ReadIOU(p,l) ReadIO (p,l)
#define ReadRegU(p,l) ReadReg (p,l)
#define WriteIOU(p,v,l) WriteIO (p, v, l)
#define WriteRegU(p,v,l) WriteReg (p, v, l)
#include "pdp11_io_lib.h"
/* Function prototypes for virtual and physical memory interface (inlined) */
#include "vax_mmu.h"
#endif
| 46.008791 | 135 | 0.519108 | [
"vector",
"model"
] |
fdf702650eb981277d08497e0a98b0e65eb304a6 | 16,057 | h | C | asylo/identity/sgx/fake_enclave.h | kevin405/mosl_vsgx_migration | 76ddd438c8caad1051ea9a7e2040bf6ccee996a2 | [
"Apache-2.0"
] | null | null | null | asylo/identity/sgx/fake_enclave.h | kevin405/mosl_vsgx_migration | 76ddd438c8caad1051ea9a7e2040bf6ccee996a2 | [
"Apache-2.0"
] | null | null | null | asylo/identity/sgx/fake_enclave.h | kevin405/mosl_vsgx_migration | 76ddd438c8caad1051ea9a7e2040bf6ccee996a2 | [
"Apache-2.0"
] | null | null | null | /*
*
* Copyright 2017 Asylo authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef ASYLO_IDENTITY_SGX_FAKE_ENCLAVE_H_
#define ASYLO_IDENTITY_SGX_FAKE_ENCLAVE_H_
#include <openssl/sha.h>
#include <vector>
#include "absl/base/attributes.h"
#include "asylo/crypto/util/bytes.h"
#include "asylo/crypto/util/trivial_object_util.h"
#include "asylo/identity/sgx/code_identity.pb.h"
#include "asylo/identity/sgx/hardware_interface.h"
#include "asylo/identity/sgx/identity_key_management_structs.h"
#include "asylo/util/status.h"
#include "asylo/util/statusor.h"
#ifdef __ASYLO__
#error \
"Must not link the fake-enclave library into a real or a simulated enclave"
#endif
namespace asylo {
namespace sgx {
// Size of the SGX owner epoch, which is defined to be 16 bytes by the Intel
// Software Developer's Manual (SDM).
constexpr size_t kOwnerEpochSize = 16;
// Size of the PKCS padding used in various key-derivations.
constexpr size_t kPkcs15PaddingSize = 352;
// Mask indicating the SECS attributes bits that the CPU will always include
// while deriving the sealing key. According to Intel SDM, the least-significant
// byte of this mask has a value of 0x3, while all other bytes are set to zero
// (i.e., INIT and DEBUG bits are always included, and other bits are optional).
constexpr SecsAttributeSet kRequiredSealingAttributesMask = {0x3, 0x0};
// The FakeEnclave class implements an enclave-like identity functionality that
// can be utilized by various unit and integration tests. The class includes
// data members to emulate various SGX-defined measurement registers,
// attributes, etc., as well as many other under-the-hood components such as
// CPUSVN, enclave's current KEYID for reporting purposes, seal-key-fuses, etc.
//
// The class implements a static pointer called current_, which stores the
// pointer to a fake-enclave instance that represents the "currently executing
// enclave". If current_ is set to nullptr, it indicates that the code is
// currently not executing inside any enclave. Enclave entry is simulated by the
// FakeEnclave::EnterEnclave static method. Similarly, enclave exit simulated by
// the FakeEnclave::ExitEnclave static method. Code can get access to the
// pointer to the currently executing FakeEnclave by calling the
// FakeEnclave::GetCurrentEnclave static method.
//
// The FakeEnclave class provides three public methods, GetHardwareRand64,
// GetHardwareKey, and GetHardwareReport. These methods are utilized by the fake
// hardware-interface implementation. Specifically, the fake hardware-interface
// implementation in fake_hardware_interface.cc relies on the enclave pointer in
// current_ to get enclave-specific hardware key and enclave-specific report.
//
// None of the SGX identity libraries directly use the FakeEnclave
// functionality. Those libraries instead utilize the hardware interface
// defined in the hardware_interface.h header. Any unit or integration tests
// that need to test such libraries using the FakeEnclave implementation should
// configure necessary FakeEnclave instances, use the EnterEnclave method to
// simulate entry into an appropriate enclave, and then test out the library
// interface. The fake_hardware_interface_test.cc file can be used as an example
// of how this functionality can be leveraged.
//
// This class is not thread-safe.
class FakeEnclave {
public:
FakeEnclave();
FakeEnclave(const FakeEnclave &other) = default;
FakeEnclave &operator=(const FakeEnclave &other) = default;
// Returns a pointer to the current static-scoped instance of FakeEnclave. The
// caller does not own the returned pointer, as a copy of the pointer is still
// retained in the static member current_, and may be returned to other
// callers of GetCurrent.
static FakeEnclave *GetCurrentEnclave();
// Simulates enclave entry by allocating a static-scoped instance of
// FakeEnclave, and copying the contents of |enclave| to it. Note that SGX
// forbids an enclave entry if the CPU is already inside an enclave. This
// function emulates that behavior by invoking LOG(FATAL) if a static-scoped
// FakeEnclave instance is already allocated.
static void EnterEnclave(const FakeEnclave &enclave);
// Simulates enclave exit by freeing the current static-scoped instance of
// FakeEnclave. Note that SGX forbids enclave exit if the CPU is already
// outside an enclave. This function emulates this behavior by invoking
// LOG(FATAL) if a static-scoped FakeEnclave instance is not allocated.
static void ExitEnclave();
// Mutators
void set_mrenclave(const UnsafeBytes<SHA256_DIGEST_LENGTH> &value) {
mrenclave_ = value;
}
void set_mrsigner(const UnsafeBytes<SHA256_DIGEST_LENGTH> &value) {
mrsigner_ = value;
}
void set_isvprodid(uint16_t value) { isvprodid_ = value; }
void set_isvsvn(uint16_t value) { isvsvn_ = value; }
void set_attributes(const SecsAttributeSet &value) {
attributes_ = (value & valid_attributes_) | required_attributes_;
}
void set_miscselect(uint32_t value) { miscselect_ = value; }
void set_configsvn(uint16_t value) { configsvn_ = value; }
void set_isvfamilyid(const UnsafeBytes<kIsvfamilyidSize> &value) {
isvfamilyid_ = value;
}
void set_isvextprodid(const UnsafeBytes<kIsvextprodidSize> &value) {
isvextprodid_ = value;
}
void set_configid(const UnsafeBytes<kConfigidSize> &value) {
configid_ = value;
}
void set_cpusvn(const UnsafeBytes<kCpusvnSize> &value) { cpusvn_ = value; }
void set_report_keyid(const UnsafeBytes<kReportKeyidSize> &value) {
report_keyid_ = value;
}
void set_ownerepoch(const SafeBytes<kOwnerEpochSize> &value) {
ownerepoch_ = value;
}
void set_root_key(const SafeBytes<SHA256_DIGEST_LENGTH> &value) {
root_key_ = value;
}
void set_seal_fuses(const SafeBytes<AES_BLOCK_SIZE> &value) {
seal_fuses_ = value;
}
void set_valid_attributes(const SecsAttributeSet &value) {
valid_attributes_ = value;
}
void add_valid_attribute(SecsAttributeBit bit) {
valid_attributes_ |= MakeSecsAttributeSet({bit}).ValueOrDie();
}
void remove_valid_attribute(SecsAttributeBit bit) {
valid_attributes_ &= ~MakeSecsAttributeSet({bit}).ValueOrDie();
}
void set_required_attributes(const SecsAttributeSet &value) {
required_attributes_ = value;
}
void add_required_attribute(SecsAttributeBit bit) {
required_attributes_ |= MakeSecsAttributeSet({bit}).ValueOrDie();
}
void remove_required_attribute(SecsAttributeBit bit) {
required_attributes_ &= ~MakeSecsAttributeSet({bit}).ValueOrDie();
}
// Accessors
const UnsafeBytes<SHA256_DIGEST_LENGTH> &get_mrenclave() const {
return mrenclave_;
}
const UnsafeBytes<SHA256_DIGEST_LENGTH> &get_mrsigner() const {
return mrsigner_;
}
uint16_t get_isvprodid() const { return isvprodid_; }
uint16_t get_isvsvn() const { return isvsvn_; }
const SecsAttributeSet &get_attributes() const { return attributes_; }
uint32_t get_miscselect() const { return miscselect_; }
uint16_t get_configsvn() const { return configsvn_; }
const UnsafeBytes<kIsvextprodidSize> &get_isvextprodid() const {
return isvextprodid_;
}
const UnsafeBytes<kIsvfamilyidSize> &get_isvfamilyid() const {
return isvfamilyid_;
}
const UnsafeBytes<kConfigidSize> &get_configid() const { return configid_; }
const UnsafeBytes<kCpusvnSize> &get_cpusvn() const { return cpusvn_; }
const UnsafeBytes<kReportKeyidSize> &get_report_keyid() const {
return report_keyid_;
}
const SafeBytes<kOwnerEpochSize> &get_ownerepoch() const {
return ownerepoch_;
}
const SafeBytes<SHA256_DIGEST_LENGTH> &get_root_key() const {
return root_key_;
}
const SafeBytes<AES_BLOCK_SIZE> &get_seal_fuses() const {
return seal_fuses_;
}
const SecsAttributeSet &get_valid_attributes() const {
return valid_attributes_;
}
const SecsAttributeSet &get_required_attributes() const {
return required_attributes_;
}
// Initializes data members that represent the enclave's identity to random
// values. Ensures that the random identity conforms to the various
// constraints specified by the SGX architecture.
void SetRandomIdentity();
// Initializes data members that represent the enclave's identity according to
// the |identity|. Does not perform any consistency checks on |identity|.
void SetIdentity(const CodeIdentity &identity);
// Gets a CodeIdentity representation of this enclave's identity.
StatusOr<CodeIdentity> GetIdentity() const;
// Equality operator--only needed for testing purposes.
bool operator==(const FakeEnclave &other) const;
// Equality operator--only needed for testing purposes.
bool operator!=(const FakeEnclave &other) const;
// Fake implementation of RdRand64.
static Status GetHardwareRand64(uint64_t *value);
// Fake implementation of the SGX EGETKEY instruction.
Status GetHardwareKey(const Keyrequest &request, HardwareKey *key) const;
// Fake implementation of the SGX EREPORT instruction.
Status GetHardwareReport(const Targetinfo &tinfo,
const Reportdata &reportdata, Report *report) const;
private:
// The Intel SDM (Software Developer's Manual) refers to a structure
// called the Key Dependencies structure that the CPU uses for deriving
// various keys. This structure is not explicitly documented in the SDM,
// however, the SDM is very explicit about how the CPU uses this structure
// for its key-derivation operations. The following structure is inferred
// from the various descriptions in the SDM.
//
// This structure is only used for the fake implementation, and the
// derivations performed using this structure will never be directly compared
// against those performed by a real CPU. Consequently, it is OK even if this
// structure deviates from the actual structure used by the CPU internally.
// Also, its alignment and packing does not matter.
//
// While a fake key-derivation implementation could be created without using
// this structure, it is probably best to follow the pseudo-code provided in
// the Intel SDM as much as possible.
//
// The KeyDependenciesBase structure below is defined based on the various
// key-dependency fields described in the Intel SDM.
struct KeyDependenciesBase {
KeyrequestKeyname keyname;
uint16_t isvprodid;
uint16_t isvsvn;
SafeBytes<kOwnerEpochSize> ownerepoch;
SecsAttributeSet attributes;
SecsAttributeSet attributemask;
UnsafeBytes<SHA256_DIGEST_LENGTH> mrenclave;
UnsafeBytes<SHA256_DIGEST_LENGTH> mrsigner;
UnsafeBytes<kKeyrequestKeyidSize> keyid;
SafeBytes<AES_BLOCK_SIZE> seal_key_fuses;
UnsafeBytes<kCpusvnSize> cpusvn;
UnsafeBytes<kPkcs15PaddingSize> padding;
uint32_t miscselect;
uint32_t miscmask;
uint16_t keypolicy;
uint16_t configsvn;
UnsafeBytes<kIsvextprodidSize> isvextprodid;
UnsafeBytes<kIsvfamilyidSize> isvfamilyid;
UnsafeBytes<kConfigidSize> configid;
} ABSL_ATTRIBUTE_PACKED;
// Since the KeyDependenciesBase structure is non-architectural, the size of
// that structure may increase over time. If such a structure were used
// directly for deriving FakeEnclave keys, the key-derivation algorithm for
// those keys would change with expansion of that structure. However, such a
// change would render any testdata generated by older implementation of that
// structure useless. To address this issue, the DeriveKey function in this
// library takes a fixed-size KeyDependencies as an input. KeyDependencies
// adds a zero-padding at the end of the KeyDependenciesBase structure and has
// a fixed size of 8192 bytes. This approach allows for growth of the
// KeyDependenciesBase structure without breaking backward compatibility.
using KeyDependenciesPadding =
UnsafeBytes<8192 - sizeof(KeyDependenciesBase)>;
struct KeyDependencies {
KeyDependencies() : padding(TrivialZeroObject<KeyDependenciesPadding>()) {}
KeyDependenciesBase dependencies;
const KeyDependenciesPadding padding;
} ABSL_ATTRIBUTE_PACKED;
static_assert(sizeof(KeyDependencies) == 8192,
"KeyDependencies has incorrect size");
// The Intel SDM refers to a DeriveKey function, without describing the exact
// cryptographic operations performed by that function. That function takes a
// KeyDependencies structure as its only input, which may or may not contain
// any randomness (depending on the key being derived). Consequently, it
// appears that the CPU must be providing some other "root key" as an input to
// this KDF (key-derivation function).
//
// The DeriveKey function below uses AES-128-CMAC as its KDF, as based on the
// description of the EGETKEY pseudo-code, it looks like this key-derivation
// function returns a 128-bit key. The fake key-derivation function also uses
// the "root key" stored in the FakeEnclave singleton as a key for this KDF.
Status DeriveKey(const KeyDependencies &key_dependencies,
HardwareKey *key) const;
// SGX-defined MRENCLAVE value of this fake enclave.
UnsafeBytes<SHA256_DIGEST_LENGTH> mrenclave_;
// SGX-defined MRSIGNER value of this fake enclave.
UnsafeBytes<SHA256_DIGEST_LENGTH> mrsigner_;
// SGX-defined ISVPRODID value of this fake enclave.
uint16_t isvprodid_;
// SGX-defined ISVSVN value of this fake enclave.
uint16_t isvsvn_;
// SGX-defined ATTRIBUTES value of this fake enclave.
SecsAttributeSet attributes_;
// SGX-defined MISCSELECT value of this fake enclave.
uint32_t miscselect_;
// SGX-defined CONFIGSVN value of this fake enclave.
uint16_t configsvn_;
// SGX-defined ISVEXTPRODID value of this fake enclave.
UnsafeBytes<kIsvextprodidSize> isvextprodid_;
// SGX-defined ISVFAMILYID value of this fake enclave.
UnsafeBytes<kIsvfamilyidSize> isvfamilyid_;
// SGX-defined CONFIGID value of this fake enclave.
UnsafeBytes<kConfigidSize> configid_;
// SGX-defined CPUSVN value.
UnsafeBytes<kCpusvnSize> cpusvn_;
// SGX-defined REPORT KEYID value.
UnsafeBytes<kReportKeyidSize> report_keyid_;
// SGX-defined OWNEREPOCH value.
SafeBytes<kOwnerEpochSize> ownerepoch_;
// Key at the root of the enclave's key hierarchy. All enclave-specific
// keys are derived from this key. The Intel SDM does not directly reference
// this key, nor does it mention its size.
SafeBytes<SHA256_DIGEST_LENGTH> root_key_;
// Value of the "Seal fuses" referenced by the EREPORT/EGETKEY pseudo code.
// The SDM describes this as a "package-wide control register that is 128 bits
// in size.
SafeBytes<AES_BLOCK_SIZE> seal_fuses_;
// Settable SECS attributes. Any attributes in this set that are clear cannot
// be set.
SecsAttributeSet valid_attributes_;
// SECS attribute bits that must be set for the enclave to be considered a
// valid enclave.
SecsAttributeSet required_attributes_;
// Current fake enclave.
static FakeEnclave *current_;
};
// Constructs a randomly-initialized FakeEnclave. This factory object is useful
// for creating a random FakeEnclave singleton.
struct RandomFakeEnclaveFactory {
using value_type = FakeEnclave;
static FakeEnclave *Construct() {
FakeEnclave *enclave = new FakeEnclave();
enclave->SetRandomIdentity();
return enclave;
}
static void Destruct(FakeEnclave *enclave) { delete enclave; }
};
} // namespace sgx
} // namespace asylo
#endif // ASYLO_IDENTITY_SGX_FAKE_ENCLAVE_H_
| 41.171795 | 80 | 0.76079 | [
"render",
"object",
"vector"
] |
fdf908c2268772df102b179998e3c97f84efa0f8 | 5,614 | c | C | crypto_kem/hqc-rmrs-256/clean/hqc.c | mkannwischer/PQClean | b04ced99788b09d9ae8cbecefe7bd259b6ecc932 | [
"OpenSSL",
"CC0-1.0",
"MIT"
] | 997 | 2016-08-13T14:14:56.000Z | 2022-03-29T15:22:30.000Z | crypto_kem/hqc-rmrs-256/clean/hqc.c | mkannwischer/PQClean | b04ced99788b09d9ae8cbecefe7bd259b6ecc932 | [
"OpenSSL",
"CC0-1.0",
"MIT"
] | 816 | 2016-08-14T20:22:14.000Z | 2022-03-22T14:13:09.000Z | crypto_kem/hqc-rmrs-256/clean/hqc.c | mkannwischer/PQClean | b04ced99788b09d9ae8cbecefe7bd259b6ecc932 | [
"OpenSSL",
"CC0-1.0",
"MIT"
] | 310 | 2016-08-17T16:16:53.000Z | 2022-03-25T19:46:30.000Z | #include "code.h"
#include "gf2x.h"
#include "hqc.h"
#include "nistseedexpander.h"
#include "parameters.h"
#include "parsing.h"
#include "randombytes.h"
#include "vector.h"
#include <stdint.h>
/**
* @file hqc.c
* @brief Implementation of hqc.h
*/
/**
* @brief Keygen of the HQC_PKE IND_CPA scheme
*
* The public key is composed of the syndrome <b>s</b> as well as the <b>seed</b> used to generate the vector <b>h</b>.
*
* The secret key is composed of the <b>seed</b> used to generate vectors <b>x</b> and <b>y</b>.
* As a technicality, the public key is appended to the secret key in order to respect NIST API.
*
* @param[out] pk String containing the public key
* @param[out] sk String containing the secret key
*/
void PQCLEAN_HQCRMRS256_CLEAN_hqc_pke_keygen(unsigned char *pk, unsigned char *sk) {
AES_XOF_struct sk_seedexpander;
AES_XOF_struct pk_seedexpander;
uint8_t sk_seed[SEED_BYTES] = {0};
uint8_t pk_seed[SEED_BYTES] = {0};
uint64_t x[VEC_N_SIZE_64] = {0};
uint32_t y[PARAM_OMEGA] = {0};
uint64_t h[VEC_N_SIZE_64] = {0};
uint64_t s[VEC_N_SIZE_64] = {0};
// Create seed_expanders for public key and secret key
randombytes(sk_seed, SEED_BYTES);
seedexpander_init(&sk_seedexpander, sk_seed, sk_seed + 32, SEEDEXPANDER_MAX_LENGTH);
randombytes(pk_seed, SEED_BYTES);
seedexpander_init(&pk_seedexpander, pk_seed, pk_seed + 32, SEEDEXPANDER_MAX_LENGTH);
// Compute secret key
PQCLEAN_HQCRMRS256_CLEAN_vect_set_random_fixed_weight(&sk_seedexpander, x, PARAM_OMEGA);
PQCLEAN_HQCRMRS256_CLEAN_vect_set_random_fixed_weight_by_coordinates(&sk_seedexpander, y, PARAM_OMEGA);
// Compute public key
PQCLEAN_HQCRMRS256_CLEAN_vect_set_random(&pk_seedexpander, h);
PQCLEAN_HQCRMRS256_CLEAN_vect_mul(s, y, h, PARAM_OMEGA, &sk_seedexpander);
PQCLEAN_HQCRMRS256_CLEAN_vect_add(s, x, s, VEC_N_SIZE_64);
// Parse keys to string
PQCLEAN_HQCRMRS256_CLEAN_hqc_public_key_to_string(pk, pk_seed, s);
PQCLEAN_HQCRMRS256_CLEAN_hqc_secret_key_to_string(sk, sk_seed, pk);
}
/**
* @brief Encryption of the HQC_PKE IND_CPA scheme
*
* The cihertext is composed of vectors <b>u</b> and <b>v</b>.
*
* @param[out] u Vector u (first part of the ciphertext)
* @param[out] v Vector v (second part of the ciphertext)
* @param[in] m Vector representing the message to encrypt
* @param[in] theta Seed used to derive randomness required for encryption
* @param[in] pk String containing the public key
*/
void PQCLEAN_HQCRMRS256_CLEAN_hqc_pke_encrypt(uint64_t *u, uint64_t *v, uint8_t *m, unsigned char *theta, const unsigned char *pk) {
AES_XOF_struct seedexpander;
uint64_t h[VEC_N_SIZE_64] = {0};
uint64_t s[VEC_N_SIZE_64] = {0};
uint64_t r1[VEC_N_SIZE_64] = {0};
uint32_t r2[PARAM_OMEGA_R] = {0};
uint64_t e[VEC_N_SIZE_64] = {0};
uint64_t tmp1[VEC_N_SIZE_64] = {0};
uint64_t tmp2[VEC_N_SIZE_64] = {0};
// Create seed_expander from theta
seedexpander_init(&seedexpander, theta, theta + 32, SEEDEXPANDER_MAX_LENGTH);
// Retrieve h and s from public key
PQCLEAN_HQCRMRS256_CLEAN_hqc_public_key_from_string(h, s, pk);
// Generate r1, r2 and e
PQCLEAN_HQCRMRS256_CLEAN_vect_set_random_fixed_weight(&seedexpander, r1, PARAM_OMEGA_R);
PQCLEAN_HQCRMRS256_CLEAN_vect_set_random_fixed_weight_by_coordinates(&seedexpander, r2, PARAM_OMEGA_R);
PQCLEAN_HQCRMRS256_CLEAN_vect_set_random_fixed_weight(&seedexpander, e, PARAM_OMEGA_E);
// Compute u = r1 + r2.h
PQCLEAN_HQCRMRS256_CLEAN_vect_mul(u, r2, h, PARAM_OMEGA_R, &seedexpander);
PQCLEAN_HQCRMRS256_CLEAN_vect_add(u, r1, u, VEC_N_SIZE_64);
// Compute v = m.G by encoding the message
PQCLEAN_HQCRMRS256_CLEAN_code_encode((uint8_t *)v, m);
PQCLEAN_HQCRMRS256_CLEAN_load8_arr(v, VEC_N1N2_SIZE_64, (uint8_t *)v, VEC_N1N2_SIZE_BYTES);
PQCLEAN_HQCRMRS256_CLEAN_vect_resize(tmp1, PARAM_N, v, PARAM_N1N2);
// Compute v = m.G + s.r2 + e
PQCLEAN_HQCRMRS256_CLEAN_vect_mul(tmp2, r2, s, PARAM_OMEGA_R, &seedexpander);
PQCLEAN_HQCRMRS256_CLEAN_vect_add(tmp2, e, tmp2, VEC_N_SIZE_64);
PQCLEAN_HQCRMRS256_CLEAN_vect_add(tmp2, tmp1, tmp2, VEC_N_SIZE_64);
PQCLEAN_HQCRMRS256_CLEAN_vect_resize(v, PARAM_N1N2, tmp2, PARAM_N);
}
/**
* @brief Decryption of the HQC_PKE IND_CPA scheme
*
* @param[out] m Vector representing the decrypted message
* @param[in] u Vector u (first part of the ciphertext)
* @param[in] v Vector v (second part of the ciphertext)
* @param[in] sk String containing the secret key
*/
void PQCLEAN_HQCRMRS256_CLEAN_hqc_pke_decrypt(uint8_t *m, const uint64_t *u, const uint64_t *v, const unsigned char *sk) {
uint8_t pk[PUBLIC_KEY_BYTES] = {0};
uint64_t tmp1[VEC_N_SIZE_64] = {0};
uint64_t tmp2[VEC_N_SIZE_64] = {0};
uint32_t y[PARAM_OMEGA] = {0};
AES_XOF_struct perm_seedexpander;
uint8_t perm_seed[SEED_BYTES] = {0};
// Retrieve x, y, pk from secret key
PQCLEAN_HQCRMRS256_CLEAN_hqc_secret_key_from_string(tmp1, y, pk, sk);
randombytes(perm_seed, SEED_BYTES);
seedexpander_init(&perm_seedexpander, perm_seed, perm_seed + 32, SEEDEXPANDER_MAX_LENGTH);
// Compute v - u.y
PQCLEAN_HQCRMRS256_CLEAN_vect_resize(tmp1, PARAM_N, v, PARAM_N1N2);
PQCLEAN_HQCRMRS256_CLEAN_vect_mul(tmp2, y, u, PARAM_OMEGA, &perm_seedexpander);
PQCLEAN_HQCRMRS256_CLEAN_vect_add(tmp2, tmp1, tmp2, VEC_N_SIZE_64);
// Compute m by decoding v - u.y
PQCLEAN_HQCRMRS256_CLEAN_store8_arr((uint8_t *)tmp1, VEC_N_SIZE_BYTES, tmp2, VEC_N_SIZE_64);
PQCLEAN_HQCRMRS256_CLEAN_code_decode(m, (uint8_t *)tmp1);
}
| 38.717241 | 132 | 0.738511 | [
"vector"
] |
fdf9150bc569e6b56da4483a2949234cfa0ebf9b | 3,965 | h | C | src/engine/utils/include/halley/text/i18n.h | amrezzd/halley | 5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4 | [
"Apache-2.0"
] | null | null | null | src/engine/utils/include/halley/text/i18n.h | amrezzd/halley | 5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4 | [
"Apache-2.0"
] | null | null | null | src/engine/utils/include/halley/text/i18n.h | amrezzd/halley | 5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include "halleystring.h"
#include <map>
#include "halley/core/resources/resources.h"
#include "halley/data_structures/maybe.h"
namespace Halley {
class ConfigNode;
class ConfigFile;
class ConfigObserver;
class I18N;
class LocalisedString
{
friend class I18N;
public:
LocalisedString();
LocalisedString(const LocalisedString& other) = default;
LocalisedString(LocalisedString&& other) noexcept = default;
LocalisedString& operator=(const LocalisedString& other) = default;
LocalisedString& operator=(LocalisedString&& other) noexcept = default;
LocalisedString& operator+=(const LocalisedString& str);
static LocalisedString fromHardcodedString(const char* str);
static LocalisedString fromHardcodedString(const String& str);
static LocalisedString fromUserString(const String& str);
static LocalisedString fromNumber(int number);
LocalisedString replaceTokens(const LocalisedString& tok0) const;
LocalisedString replaceTokens(const LocalisedString& tok0, const LocalisedString& tok1) const;
LocalisedString replaceTokens(const LocalisedString& tok0, const LocalisedString& tok1, const LocalisedString& tok2) const;
LocalisedString replaceTokens(const std::map<String, LocalisedString>& tokens);
const String& getString() const;
bool operator==(const LocalisedString& other) const;
bool operator!=(const LocalisedString& other) const;
bool operator<(const LocalisedString& other) const;
bool checkForUpdates();
private:
explicit LocalisedString(String string);
explicit LocalisedString(const I18N& i18n, String key, String string);
const I18N* i18n = nullptr;
String key;
String string;
int i18nVersion = 0;
};
enum class I18NLanguageMatch {
None,
Good,
Exact
};
class I18NLanguage {
public:
I18NLanguage();
explicit I18NLanguage(const String& code);
I18NLanguage(String languageCode, std::optional<String> countryCode);
void set(String languageCode, std::optional<String> countryCode);
const String& getLanguageCode() const;
const std::optional<String>& getCountryCode() const;
String getISOCode() const;
I18NLanguageMatch getMatch(const I18NLanguage& other) const;
static std::optional<I18NLanguage> getBestMatch(const Vector<I18NLanguage>& languages, const I18NLanguage& target, std::optional<I18NLanguage> fallback = {});
bool operator==(const I18NLanguage& other) const;
bool operator!=(const I18NLanguage& other) const;
bool operator<(const I18NLanguage& other) const;
private:
String languageCode;
std::optional<String> countryCode;
};
class II18N {
public:
virtual ~II18N() = default;
virtual LocalisedString get(const String& key) const = 0;
};
class I18N : public II18N {
public:
I18N();
I18N(Resources& resources, I18NLanguage currentLanguage = I18NLanguage("en-GB"));
void update();
void loadStrings(Resources& resources);
void loadLocalisationFile(const ConfigFile& config);
void setCurrentLanguage(const I18NLanguage& code);
void setFallbackLanguage(const I18NLanguage& code);
Vector<I18NLanguage> getLanguagesAvailable() const;
LocalisedString get(const String& key) const override;
std::optional<LocalisedString> get(const String& key, const I18NLanguage& language) const;
LocalisedString getPreProcessedUserString(const String& string) const;
template <typename T>
Vector<LocalisedString> getVector(const String& keyPrefix, const T& keys) const
{
Vector<LocalisedString> result;
for (auto& k: keys) {
result.push_back(get(keyPrefix + k));
}
return result;
}
const I18NLanguage& getCurrentLanguage() const;
int getVersion() const;
char getDecimalSeparator() const;
private:
I18NLanguage currentLanguage;
std::optional<I18NLanguage> fallbackLanguage;
std::map<I18NLanguage, std::map<String, String>> strings;
std::map<String, ConfigObserver> observers;
int version = 0;
void loadLocalisation(const ConfigNode& node);
};
}
| 28.52518 | 160 | 0.758638 | [
"vector"
] |
fdf93282a9d57e76b8d690cd745a3de1fecc2fa3 | 10,082 | h | C | geo3d/include/CGAL/Mesh_3/search_for_connected_components_in_labeled_image.h | vipuserr/vipuserr-Geological-hazard | 2b29c03cdac6f5e1ceac4cd2f15b594040ef909c | [
"MIT"
] | 187 | 2019-01-23T04:07:11.000Z | 2022-03-27T03:44:58.000Z | ext/libigl/external/cgal/src/CGAL_Project/include/CGAL/Mesh_3/search_for_connected_components_in_labeled_image.h | xiaoxie5002/OptCuts | 1f4168fc867f47face85fcfa3a572be98232786f | [
"MIT"
] | 8 | 2019-03-22T13:27:38.000Z | 2020-06-18T13:23:23.000Z | ext/libigl/external/cgal/src/CGAL_Project/include/CGAL/Mesh_3/search_for_connected_components_in_labeled_image.h | xiaoxie5002/OptCuts | 1f4168fc867f47face85fcfa3a572be98232786f | [
"MIT"
] | 34 | 2019-02-13T01:11:12.000Z | 2022-02-28T03:29:40.000Z | // Copyright (c) 2015,2016 GeometryFactory
// All rights reserved.
//
// This file is part of CGAL (www.cgal.org).
// 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.
//
// Licensees holding a valid commercial license may use this file in
// accordance with the commercial license agreement provided with the software.
//
// This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
// WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
//
// $URL$
// $Id$
//
//
// Author(s) : Laurent Rineau
#ifndef CGAL_MESH_3_SEARCH_FOR_CONNECTED_COMPONENTS_IN_LABELED_IMAGE_H
#define CGAL_MESH_3_SEARCH_FOR_CONNECTED_COMPONENTS_IN_LABELED_IMAGE_H
#include <CGAL/license/Mesh_3.h>
#include <CGAL/Image_3.h>
#include <cstdlib>
#include <vector>
#include <queue>
#include <utility>
#include <algorithm>
#include <boost/container/deque.hpp>
#include <boost/multi_array.hpp>
#include <boost/tuple/tuple.hpp>
#include <boost/tuple/tuple_comparison.hpp>
#include <boost/cstdint.hpp>
#ifdef CGAL_MESH_3_SEARCH_FOR_CONNECTED_COMPONENTS_IN_LABELED_IMAGE_VERBOSE
# include <iostream>
# include <boost/format.hpp>
#endif // CGAL_MESH_3_SEARCH_FOR_CONNECTED_COMPONENTS_IN_LABELED_IMAGE_VERBOSE
template <typename PointsOutputIterator,
typename DomainsOutputIterator,
typename TransformOperator,
typename Construct_point,
typename Image_word_type>
void
search_for_connected_components_in_labeled_image(const CGAL::Image_3& image,
PointsOutputIterator it,
DomainsOutputIterator dom_it,
TransformOperator transform,
Construct_point point,
Image_word_type)
{
const std::size_t nx = image.xdim();
const std::size_t ny = image.ydim();
const std::size_t nz = image.zdim();
const std::size_t size = nx * ny * nz;
typedef boost::uint16_t uint;
if(nx > 65535 || ny > 65535 || nz > 65535)
{
CGAL_error_msg("The dimensions of the image must be lower than 2^16");
}
typedef typename TransformOperator::result_type Label;
std::vector<bool> visited(size, false);
std::vector<bool> second_pass(size, false);
typedef boost::tuple<uint, uint, uint, uint> Indices;
typedef std::queue<Indices, boost::container::deque<Indices> > Indices_queue;
typedef std::vector<Indices> Border_vector;
#ifdef CGAL_MESH_3_SEARCH_FOR_CONNECTED_COMPONENTS_IN_LABELED_IMAGE_VERBOSE
int number_of_connected_components = 0;
#endif // CGAL_MESH_3_SEARCH_FOR_CONNECTED_COMPONENTS_IN_LABELED_IMAGE_VERBOSE
std::size_t voxel_index = 0;
for(uint k=0; k<nz; k++)
for(uint j=0; j<ny; j++)
for(uint i=0; i<nx; i++)
{
using CGAL::IMAGEIO::static_evaluate;
if(visited[voxel_index] | second_pass[voxel_index]) {
++voxel_index;
continue;
}
const Label current_label =
transform(static_evaluate<Image_word_type>(image.image(),
voxel_index));
*dom_it++ = current_label;
if(current_label == Label()) {
visited[voxel_index] = true;
second_pass[voxel_index] = true;
++voxel_index;
continue;
}
#ifdef CGAL_MESH_3_SEARCH_FOR_CONNECTED_COMPONENTS_IN_LABELED_IMAGE_VERBOSE
// if we reach here, (i, j, k) is a new connected component
++number_of_connected_components;
std::cerr << boost::format("Found new connected component (#%5%) "
"at voxel (%1%, %2%, %3%), value=%4%, volume id=%6%\n")
% i % j % k
% (long)static_evaluate<Image_word_type>(image.image(), i, j, k)
% number_of_connected_components
% (int)current_label;
#endif // CGAL_MESH_3_SEARCH_FOR_CONNECTED_COMPONENTS_IN_LABELED_IMAGE_VERBOSE
int nb_voxels = 0;
Indices_queue queue;
Indices indices(i, j ,k, 0);
queue.push(indices);
Border_vector border;
/*
* First pass is a BFS to retrieve all the connected component, and
* its border.
* Second pass is a BFS initialized with all voxel of the border.
* The last voxel of that BFS is used as the seed.
*/
int pass = 1; // pass will be equal to 2 in second pass
Indices bbox_min = indices;
Indices bbox_max = indices;
while(!queue.empty()) // walk through the connected component
{
Indices indices = queue.front();
queue.pop();
// warning: those indices i, j and k are local to the while loop
const uint i = boost::get<0>(indices);
const uint j = boost::get<1>(indices);
const uint k = boost::get<2>(indices);
const uint depth = boost::get<3>(indices);
const size_t offset = i + nx * (j + ny * k);
const int m = (visited[offset] ? 1 : 0) + (second_pass[offset] ? 2 : 0);
if(m < pass)
{
if(pass == 1 )
{
visited[offset] = true;
second_pass[offset] = false;
++nb_voxels;
boost::get<0>(bbox_min) = (std::min)(i, boost::get<0>(bbox_min));
boost::get<0>(bbox_max) = (std::max)(i, boost::get<0>(bbox_max));
boost::get<1>(bbox_min) = (std::min)(j, boost::get<1>(bbox_min));
boost::get<1>(bbox_max) = (std::max)(j, boost::get<1>(bbox_max));
boost::get<2>(bbox_min) = (std::min)(k, boost::get<2>(bbox_min));
boost::get<2>(bbox_max) = (std::max)(k, boost::get<2>(bbox_max));
} else
{
CGAL_assertion(pass == 2);
visited[offset] = false;
second_pass[offset] = true;
}
static const int neighbors_offset[6][3] = { { +1, 0, 0 },
{ -1, 0, 0 },
{ 0, +1, 0 },
{ 0, -1, 0 },
{ 0, 0, +1 },
{ 0, 0, -1 } };
bool voxel_is_on_border = false;
// Visit neighbors.
// (i_n, j_n, k_n) are indices of neighbors.
for(int n = 0; n < 6; ++n)
{
const ptrdiff_t i_n = i + neighbors_offset[n][0];
const ptrdiff_t j_n = j + neighbors_offset[n][1];
const ptrdiff_t k_n = k + neighbors_offset[n][2];
if(i_n < 0 || i_n >= static_cast<ptrdiff_t>(nx) ||
j_n < 0 || j_n >= static_cast<ptrdiff_t>(ny) ||
k_n < 0 || k_n >= static_cast<ptrdiff_t>(nz))
{
voxel_is_on_border = true;
continue;
}
else
{
const std::size_t offset_n = i_n + nx * (j_n + k_n * ny);
if(transform(static_evaluate<Image_word_type>(image.image(),
offset_n))
== current_label)
{
const int m_n = (visited[offset_n] ? 1 : 0) +
(second_pass[offset_n] ? 2 : 0);
if(m_n < pass) {
Indices indices(uint(i_n), uint(j_n), uint(k_n), uint(depth+1));
queue.push(indices);
}
}
else
voxel_is_on_border = true;
}
} // end for neighbors
if(pass == 1 && voxel_is_on_border)
border.push_back(indices);
} // end if voxel not already visited
if(queue.empty()) {
if(pass == 1)
{ // End of first pass. Begin second pass with the voxels of
// the border.
for(typename Border_vector::const_iterator
border_it = border.begin(), border_end = border.end();
border_it != border_end; ++border_it)
queue.push(*border_it);
pass = 2;
}
else // end of second pass, return the last visited voxel
{
// if(nb_voxels >= 100)
{
*it++ = std::make_pair(point(i, j, k),
depth+1);
#if CGAL_MESH_3_SEARCH_FOR_CONNECTED_COMPONENTS_IN_LABELED_IMAGE_VERBOSE > 1
std::cerr << boost::format("Found seed %5%, which is voxel "
"(%1%, %2%, %3%), value=%4%\n")
% i % j % k
% (long)static_evaluate<Image_word_type>(image.image(), i, j, k)
% point(i, j, k);
#endif // CGAL_MESH_3_SEARCH_FOR_CONNECTED_COMPONENTS_IN_LABELED_IMAGE_VERBOSE>1
}
}
} // end if queue.empty()
} // end while !queue.empty() (with local indices i, j, k)
#ifdef CGAL_MESH_3_SEARCH_FOR_CONNECTED_COMPONENTS_IN_LABELED_IMAGE_VERBOSE
std::cerr
<< boost::format("There was %1% voxel(s) in that component.\n"
"The bounding box is (%2% %3% %4%, %5% %6% %7%).\n"
"%8% voxel(s) on border\n")
% nb_voxels
% boost::get<0>(bbox_min) % boost::get<1>(bbox_min)
% boost::get<2>(bbox_min)
% boost::get<0>(bbox_max) % boost::get<1>(bbox_max)
% boost::get<2>(bbox_max)
% border.size();
#endif // CGAL_MESH_3_SEARCH_FOR_CONNECTED_COMPONENTS_IN_LABELED_IMAGE_VERBOSE
++voxel_index;
} // end for i,j,k
} // end function search_for_connected_components_in_labeled_image()
#endif // CGAL_MESH_3_SEARCH_FOR_CONNECTED_COMPONENTS_IN_LABELED_IMAGE_H
| 39.849802 | 90 | 0.548701 | [
"vector",
"transform"
] |
fdfc5328328cc3c915efb7677a735c5595928b6c | 4,805 | c | C | test/session-entry_unit.c | williamcroberts/tpm2-abrmd | 221784228f5d0d479a0de8153a452b10ab546bc8 | [
"BSD-2-Clause"
] | null | null | null | test/session-entry_unit.c | williamcroberts/tpm2-abrmd | 221784228f5d0d479a0de8153a452b10ab546bc8 | [
"BSD-2-Clause"
] | null | null | null | test/session-entry_unit.c | williamcroberts/tpm2-abrmd | 221784228f5d0d479a0de8153a452b10ab546bc8 | [
"BSD-2-Clause"
] | null | null | null | /*
* Copyright (c) 2017, Intel 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:
*
* 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.
*/
#include <glib.h>
#include <stdlib.h>
#include <setjmp.h>
#include <cmocka.h>
#include "session-entry.h"
#define CLIENT_ID 1ULL
#define TEST_HANDLE 0x03000000
typedef struct {
Connection *connection;
gint receive_fd;
gint send_fd;
HandleMap *handle_map;
SessionEntry *session_entry;
} test_data_t;
/*
* Setup function
*/
static void
session_entry_setup (void **state)
{
test_data_t *data = NULL;
data = calloc (1, sizeof (test_data_t));
data->handle_map = handle_map_new (TPM_HT_TRANSIENT, 100);
data->connection = connection_new (&data->receive_fd,
&data->send_fd,
CLIENT_ID,
data->handle_map);
data->session_entry = session_entry_new (data->connection, TEST_HANDLE);
*state = data;
}
/**
* Tear down all of the data from the setup function. We don't have to
* free the data buffer (data->buffer) since the Tpm2Command frees it as
* part of its finalize function.
*/
static void
session_entry_teardown (void **state)
{
test_data_t *data = (test_data_t*)*state;
g_object_unref (data->connection);
g_object_unref (data->handle_map);
g_object_unref (data->session_entry);
free (data);
}
/*
* This is a test for memory management / reference counting. The setup
* function does exactly that so when we get the Tpm2Command object we just
* check to be sure it's a GObject and then we unref it. This test will
* probably only fail when run under valgrind if the reference counting is
* off.
*/
static void
session_entry_type_test (void **state)
{
test_data_t *data = (test_data_t*)*state;
assert_true (G_IS_OBJECT (data->session_entry));
assert_true (IS_SESSION_ENTRY (data->session_entry));
}
static void
session_entry_get_context_test (void **state)
{
test_data_t *data = (test_data_t*)*state;
TPMS_CONTEXT *context = NULL;
context = session_entry_get_context (data->session_entry);
assert_non_null (context);
}
static void
session_entry_get_connection_test (void **state)
{
test_data_t *data = (test_data_t*)*state;
Connection *connection;
connection = session_entry_get_connection (data->session_entry);
assert_true (IS_CONNECTION (connection));
g_object_unref (connection);
}
static void
session_entry_get_handle_test (void **state)
{
test_data_t *data = (test_data_t*)*state;
TPM_HANDLE handle;
handle = session_entry_get_handle (data->session_entry);
assert_int_equal (handle, TEST_HANDLE);
}
gint
main (gint argc,
gchar *arvg[])
{
const UnitTest tests[] = {
unit_test_setup_teardown (session_entry_type_test,
session_entry_setup,
session_entry_teardown),
unit_test_setup_teardown (session_entry_get_context_test,
session_entry_setup,
session_entry_teardown),
unit_test_setup_teardown (session_entry_get_connection_test,
session_entry_setup,
session_entry_teardown),
unit_test_setup_teardown (session_entry_get_handle_test,
session_entry_setup,
session_entry_teardown),
};
return run_tests (tests);
}
| 33.137931 | 79 | 0.680333 | [
"object"
] |
a9000c56a7e554b7b1ed77f20c24cc7c7786fcb5 | 448 | h | C | includes/insertion.h | lucianefalcao/cvrp | a26dd2a33d90a1ecee879f2cb415151dca573778 | [
"Apache-2.0"
] | null | null | null | includes/insertion.h | lucianefalcao/cvrp | a26dd2a33d90a1ecee879f2cb415151dca573778 | [
"Apache-2.0"
] | null | null | null | includes/insertion.h | lucianefalcao/cvrp | a26dd2a33d90a1ecee879f2cb415151dca573778 | [
"Apache-2.0"
] | null | null | null | #ifndef INSERTION_H
#define INSERTION_H
#include "graph.h"
#include "client.h"
#include "vehicle.h"
#include <vector>
class Insertion
{
private:
/* data */
Graph *graph;
public:
Insertion(/* args */);
void setGraph(Graph *graph);
void buildSolution(std::vector<Vehicle*> v);
int getMovement(std::vector<Client>& route, int currentDistance);
std::vector<Client> move(std::vector<Client>&, int, int);
};
#endif | 16.592593 | 69 | 0.660714 | [
"vector"
] |
a903241e3000842a5d6e72a9d002169b1e76c076 | 19,119 | h | C | include/freetype/ftmm.h | nikramakrishnan/freetype2 | b532d7ce708cb5ca9bf88abaa2eb213ddcf9babb | [
"FTL"
] | 6 | 2018-10-20T10:53:55.000Z | 2021-12-25T07:58:57.000Z | include/freetype/ftmm.h | nikramakrishnan/freetype2 | b532d7ce708cb5ca9bf88abaa2eb213ddcf9babb | [
"FTL"
] | null | null | null | include/freetype/ftmm.h | nikramakrishnan/freetype2 | b532d7ce708cb5ca9bf88abaa2eb213ddcf9babb | [
"FTL"
] | 9 | 2018-10-31T03:07:11.000Z | 2021-08-06T08:53:21.000Z | /****************************************************************************
*
* ftmm.h
*
* FreeType Multiple Master font interface (specification).
*
* Copyright 1996-2018 by
* David Turner, Robert Wilhelm, and Werner Lemberg.
*
* This file is part of the FreeType project, and may only be used,
* modified, and distributed under the terms of the FreeType project
* license, LICENSE.TXT. By continuing to use, modify, or distribute
* this file you indicate that you have read the license and
* understand and accept it fully.
*
*/
#ifndef FTMM_H_
#define FTMM_H_
#include <ft2build.h>
#include FT_TYPE1_TABLES_H
FT_BEGIN_HEADER
/**************************************************************************
*
* @section:
* multiple_masters
*
* @title:
* Multiple Masters
*
* @abstract:
* How to manage Multiple Masters fonts.
*
* @description:
* The following types and functions are used to manage Multiple
* Master fonts, i.e., the selection of specific design instances by
* setting design axis coordinates.
*
* Besides Adobe MM fonts, the interface supports Apple's TrueType GX
* and OpenType variation fonts. Some of the routines only work with
* Adobe MM fonts, others will work with all three types. They are
* similar enough that a consistent interface makes sense.
*
*/
/**************************************************************************
*
* @struct:
* FT_MM_Axis
*
* @description:
* A structure to model a given axis in design space for Multiple
* Masters fonts.
*
* This structure can't be used for TrueType GX or OpenType variation
* fonts.
*
* @fields:
* name ::
* The axis's name.
*
* minimum ::
* The axis's minimum design coordinate.
*
* maximum ::
* The axis's maximum design coordinate.
*/
typedef struct FT_MM_Axis_
{
FT_String* name;
FT_Long minimum;
FT_Long maximum;
} FT_MM_Axis;
/**************************************************************************
*
* @struct:
* FT_Multi_Master
*
* @description:
* A structure to model the axes and space of a Multiple Masters
* font.
*
* This structure can't be used for TrueType GX or OpenType variation
* fonts.
*
* @fields:
* num_axis ::
* Number of axes. Cannot exceed~4.
*
* num_designs ::
* Number of designs; should be normally 2^num_axis
* even though the Type~1 specification strangely
* allows for intermediate designs to be present.
* This number cannot exceed~16.
*
* axis ::
* A table of axis descriptors.
*/
typedef struct FT_Multi_Master_
{
FT_UInt num_axis;
FT_UInt num_designs;
FT_MM_Axis axis[T1_MAX_MM_AXIS];
} FT_Multi_Master;
/**************************************************************************
*
* @struct:
* FT_Var_Axis
*
* @description:
* A structure to model a given axis in design space for Multiple
* Masters, TrueType GX, and OpenType variation fonts.
*
* @fields:
* name ::
* The axis's name.
* Not always meaningful for TrueType GX or OpenType
* variation fonts.
*
* minimum ::
* The axis's minimum design coordinate.
*
* def ::
* The axis's default design coordinate.
* FreeType computes meaningful default values for Adobe
* MM fonts.
*
* maximum ::
* The axis's maximum design coordinate.
*
* tag ::
* The axis's tag (the equivalent to `name' for TrueType
* GX and OpenType variation fonts). FreeType provides
* default values for Adobe MM fonts if possible.
*
* strid ::
* The axis name entry in the font's `name' table. This
* is another (and often better) version of the `name'
* field for TrueType GX or OpenType variation fonts. Not
* meaningful for Adobe MM fonts.
*
* @note:
* The fields `minimum', `def', and `maximum' are 16.16 fractional
* values for TrueType GX and OpenType variation fonts. For Adobe MM
* fonts, the values are integers.
*/
typedef struct FT_Var_Axis_
{
FT_String* name;
FT_Fixed minimum;
FT_Fixed def;
FT_Fixed maximum;
FT_ULong tag;
FT_UInt strid;
} FT_Var_Axis;
/**************************************************************************
*
* @struct:
* FT_Var_Named_Style
*
* @description:
* A structure to model a named instance in a TrueType GX or OpenType
* variation font.
*
* This structure can't be used for Adobe MM fonts.
*
* @fields:
* coords ::
* The design coordinates for this instance.
* This is an array with one entry for each axis.
*
* strid ::
* The entry in `name' table identifying this instance.
*
* psid ::
* The entry in `name' table identifying a PostScript name
* for this instance. Value 0xFFFF indicates a missing
* entry.
*/
typedef struct FT_Var_Named_Style_
{
FT_Fixed* coords;
FT_UInt strid;
FT_UInt psid; /* since 2.7.1 */
} FT_Var_Named_Style;
/**************************************************************************
*
* @struct:
* FT_MM_Var
*
* @description:
* A structure to model the axes and space of an Adobe MM, TrueType
* GX, or OpenType variation font.
*
* Some fields are specific to one format and not to the others.
*
* @fields:
* num_axis ::
* The number of axes. The maximum value is~4 for
* Adobe MM fonts; no limit in TrueType GX or
* OpenType variation fonts.
*
* num_designs ::
* The number of designs; should be normally
* 2^num_axis for Adobe MM fonts. Not meaningful
* for TrueType GX or OpenType variation fonts
* (where every glyph could have a different
* number of designs).
*
* num_namedstyles ::
* The number of named styles; a `named style' is
* a tuple of design coordinates that has a string
* ID (in the `name' table) associated with it.
* The font can tell the user that, for example,
* [Weight=1.5,Width=1.1] is `Bold'. Another name
* for `named style' is `named instance'.
*
* For Adobe Multiple Masters fonts, this value is
* always zero because the format does not support
* named styles.
*
* axis ::
* An axis descriptor table.
* TrueType GX and OpenType variation fonts
* contain slightly more data than Adobe MM fonts.
* Memory management of this pointer is done
* internally by FreeType.
*
* namedstyle ::
* A named style (instance) table.
* Only meaningful for TrueType GX and OpenType
* variation fonts. Memory management of this
* pointer is done internally by FreeType.
*/
typedef struct FT_MM_Var_
{
FT_UInt num_axis;
FT_UInt num_designs;
FT_UInt num_namedstyles;
FT_Var_Axis* axis;
FT_Var_Named_Style* namedstyle;
} FT_MM_Var;
/**************************************************************************
*
* @function:
* FT_Get_Multi_Master
*
* @description:
* Retrieve a variation descriptor of a given Adobe MM font.
*
* This function can't be used with TrueType GX or OpenType variation
* fonts.
*
* @input:
* face ::
* A handle to the source face.
*
* @output:
* amaster ::
* The Multiple Masters descriptor.
*
* @return:
* FreeType error code. 0~means success.
*/
FT_EXPORT( FT_Error )
FT_Get_Multi_Master( FT_Face face,
FT_Multi_Master *amaster );
/**************************************************************************
*
* @function:
* FT_Get_MM_Var
*
* @description:
* Retrieve a variation descriptor for a given font.
*
* This function works with all supported variation formats.
*
* @input:
* face ::
* A handle to the source face.
*
* @output:
* amaster ::
* The variation descriptor.
* Allocates a data structure, which the user must
* deallocate with a call to @FT_Done_MM_Var after use.
*
* @return:
* FreeType error code. 0~means success.
*/
FT_EXPORT( FT_Error )
FT_Get_MM_Var( FT_Face face,
FT_MM_Var* *amaster );
/**************************************************************************
*
* @function:
* FT_Done_MM_Var
*
* @description:
* Free the memory allocated by @FT_Get_MM_Var.
*
* @input:
* library ::
* A handle of the face's parent library object that was
* used in the call to @FT_Get_MM_Var to create `amaster'.
*
* @return:
* FreeType error code. 0~means success.
*/
FT_EXPORT( FT_Error )
FT_Done_MM_Var( FT_Library library,
FT_MM_Var *amaster );
/**************************************************************************
*
* @function:
* FT_Set_MM_Design_Coordinates
*
* @description:
* For Adobe MM fonts, choose an interpolated font design through
* design coordinates.
*
* This function can't be used with TrueType GX or OpenType variation
* fonts.
*
* @inout:
* face ::
* A handle to the source face.
*
* @input:
* num_coords ::
* The number of available design coordinates. If it
* is larger than the number of axes, ignore the excess
* values. If it is smaller than the number of axes,
* use default values for the remaining axes.
*
* coords ::
* An array of design coordinates.
*
* @return:
* FreeType error code. 0~means success.
*
* @note:
* [Since 2.8.1] To reset all axes to the default values, call the
* function with `num_coords' set to zero and `coords' set to NULL.
*
* [Since 2.9] If `num_coords' is larger than zero, this function
* sets the @FT_FACE_FLAG_VARIATION bit in @FT_Face's `face_flags'
* field (i.e., @FT_IS_VARIATION will return true). If `num_coords'
* is zero, this bit flag gets unset.
*/
FT_EXPORT( FT_Error )
FT_Set_MM_Design_Coordinates( FT_Face face,
FT_UInt num_coords,
FT_Long* coords );
/**************************************************************************
*
* @function:
* FT_Set_Var_Design_Coordinates
*
* @description:
* Choose an interpolated font design through design coordinates.
*
* This function works with all supported variation formats.
*
* @inout:
* face ::
* A handle to the source face.
*
* @input:
* num_coords ::
* The number of available design coordinates. If it
* is larger than the number of axes, ignore the excess
* values. If it is smaller than the number of axes,
* use default values for the remaining axes.
*
* coords ::
* An array of design coordinates.
*
* @return:
* FreeType error code. 0~means success.
*
* @note:
* [Since 2.8.1] To reset all axes to the default values, call the
* function with `num_coords' set to zero and `coords' set to NULL.
* [Since 2.9] `Default values' means the currently selected named
* instance (or the base font if no named instance is selected).
*
* [Since 2.9] If `num_coords' is larger than zero, this function
* sets the @FT_FACE_FLAG_VARIATION bit in @FT_Face's `face_flags'
* field (i.e., @FT_IS_VARIATION will return true). If `num_coords'
* is zero, this bit flag gets unset.
*/
FT_EXPORT( FT_Error )
FT_Set_Var_Design_Coordinates( FT_Face face,
FT_UInt num_coords,
FT_Fixed* coords );
/**************************************************************************
*
* @function:
* FT_Get_Var_Design_Coordinates
*
* @description:
* Get the design coordinates of the currently selected interpolated
* font.
*
* This function works with all supported variation formats.
*
* @input:
* face ::
* A handle to the source face.
*
* num_coords ::
* The number of design coordinates to retrieve. If it
* is larger than the number of axes, set the excess
* values to~0.
*
* @output:
* coords ::
* The design coordinates array.
*
* @return:
* FreeType error code. 0~means success.
*
* @since:
* 2.7.1
*/
FT_EXPORT( FT_Error )
FT_Get_Var_Design_Coordinates( FT_Face face,
FT_UInt num_coords,
FT_Fixed* coords );
/**************************************************************************
*
* @function:
* FT_Set_MM_Blend_Coordinates
*
* @description:
* Choose an interpolated font design through normalized blend
* coordinates.
*
* This function works with all supported variation formats.
*
* @inout:
* face ::
* A handle to the source face.
*
* @input:
* num_coords ::
* The number of available design coordinates. If it
* is larger than the number of axes, ignore the excess
* values. If it is smaller than the number of axes,
* use default values for the remaining axes.
*
* coords ::
* The design coordinates array (each element must be
* between 0 and 1.0 for Adobe MM fonts, and between
* -1.0 and 1.0 for TrueType GX and OpenType variation
* fonts).
*
* @return:
* FreeType error code. 0~means success.
*
* @note:
* [Since 2.8.1] To reset all axes to the default values, call the
* function with `num_coords' set to zero and `coords' set to NULL.
* [Since 2.9] `Default values' means the currently selected named
* instance (or the base font if no named instance is selected).
*
* [Since 2.9] If `num_coords' is larger than zero, this function
* sets the @FT_FACE_FLAG_VARIATION bit in @FT_Face's `face_flags'
* field (i.e., @FT_IS_VARIATION will return true). If `num_coords'
* is zero, this bit flag gets unset.
*/
FT_EXPORT( FT_Error )
FT_Set_MM_Blend_Coordinates( FT_Face face,
FT_UInt num_coords,
FT_Fixed* coords );
/**************************************************************************
*
* @function:
* FT_Get_MM_Blend_Coordinates
*
* @description:
* Get the normalized blend coordinates of the currently selected
* interpolated font.
*
* This function works with all supported variation formats.
*
* @input:
* face ::
* A handle to the source face.
*
* num_coords ::
* The number of normalized blend coordinates to
* retrieve. If it is larger than the number of axes,
* set the excess values to~0.5 for Adobe MM fonts, and
* to~0 for TrueType GX and OpenType variation fonts.
*
* @output:
* coords ::
* The normalized blend coordinates array.
*
* @return:
* FreeType error code. 0~means success.
*
* @since:
* 2.7.1
*/
FT_EXPORT( FT_Error )
FT_Get_MM_Blend_Coordinates( FT_Face face,
FT_UInt num_coords,
FT_Fixed* coords );
/**************************************************************************
*
* @function:
* FT_Set_Var_Blend_Coordinates
*
* @description:
* This is another name of @FT_Set_MM_Blend_Coordinates.
*/
FT_EXPORT( FT_Error )
FT_Set_Var_Blend_Coordinates( FT_Face face,
FT_UInt num_coords,
FT_Fixed* coords );
/**************************************************************************
*
* @function:
* FT_Get_Var_Blend_Coordinates
*
* @description:
* This is another name of @FT_Get_MM_Blend_Coordinates.
*
* @since:
* 2.7.1
*/
FT_EXPORT( FT_Error )
FT_Get_Var_Blend_Coordinates( FT_Face face,
FT_UInt num_coords,
FT_Fixed* coords );
/**************************************************************************
*
* @enum:
* FT_VAR_AXIS_FLAG_XXX
*
* @description:
* A list of bit flags used in the return value of
* @FT_Get_Var_Axis_Flags.
*
* @values:
* FT_VAR_AXIS_FLAG_HIDDEN ::
* The variation axis should not be exposed to user interfaces.
*
* @since:
* 2.8.1
*/
#define FT_VAR_AXIS_FLAG_HIDDEN 1
/**************************************************************************
*
* @function:
* FT_Get_Var_Axis_Flags
*
* @description:
* Get the `flags' field of an OpenType Variation Axis Record.
*
* Not meaningful for Adobe MM fonts (`*flags' is always zero).
*
* @input:
* master ::
* The variation descriptor.
*
* axis_index ::
* The index of the requested variation axis.
*
* @output:
* flags ::
* The `flags' field. See @FT_VAR_AXIS_FLAG_XXX for
* possible values.
*
* @return:
* FreeType error code. 0~means success.
*
* @since:
* 2.8.1
*/
FT_EXPORT( FT_Error )
FT_Get_Var_Axis_Flags( FT_MM_Var* master,
FT_UInt axis_index,
FT_UInt* flags );
/**************************************************************************
*
* @function:
* FT_Set_Named_Instance
*
* @description:
* Set or change the current named instance.
*
* @input:
* face ::
* A handle to the source face.
*
* instance_index ::
* The index of the requested instance, starting
* with value 1. If set to value 0, FreeType
* switches to font access without a named
* instance.
*
* @return:
* FreeType error code. 0~means success.
*
* @note:
* The function uses the value of `instance_index' to set bits 16-30
* of the face's `face_index' field. It also resets any variation
* applied to the font, and the @FT_FACE_FLAG_VARIATION bit of the
* face's `face_flags' field gets reset to zero (i.e.,
* @FT_IS_VARIATION will return false).
*
* For Adobe MM fonts (which don't have named instances) this
* function simply resets the current face to the default instance.
*
* @since:
* 2.9
*/
FT_EXPORT( FT_Error )
FT_Set_Named_Instance( FT_Face face,
FT_UInt instance_index );
/* */
FT_END_HEADER
#endif /* FTMM_H_ */
/* END */
| 27.951754 | 77 | 0.546106 | [
"object",
"model"
] |
a905732c2e3a6c2ac7e2a682bbf16ea16135bd63 | 91,853 | h | C | iPhoneOS14.2.sdk/System/Library/Frameworks/Security.framework/Headers/SecKey.h | Zi0P4tch0/sdks | 96951a2b5a0c0a58963a8f9c37bc44ec9991153b | [
"MIT"
] | 416 | 2016-08-20T03:40:59.000Z | 2022-03-30T14:27:47.000Z | iPhoneOS14.4.sdk/System/Library/Frameworks/Security.framework/Headers/SecKey.h | haoict/sdks | 40a7cee1dc15ae097d867ae0c5133709fa103040 | [
"MIT"
] | 41 | 2016-08-22T14:41:42.000Z | 2022-02-25T11:38:16.000Z | iPhoneOS14.4.sdk/System/Library/Frameworks/Security.framework/Headers/SecKey.h | haoict/sdks | 40a7cee1dc15ae097d867ae0c5133709fa103040 | [
"MIT"
] | 173 | 2016-08-28T15:09:18.000Z | 2022-03-23T15:42:52.000Z | /*
* Copyright (c) 2006-2014,2016 Apple Inc. All Rights Reserved.
*
* @APPLE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this
* file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_LICENSE_HEADER_END@
*/
/*!
@header SecKey
The functions provided in SecKey.h implement and manage a particular
type of keychain item that represents a key. A key can be stored in a
keychain, but a key can also be a transient object.
On OSX, you can use a SecKey as a SecKeychainItem in most functions.
*/
#ifndef _SECURITY_SECKEY_H_
#define _SECURITY_SECKEY_H_
#include <Availability.h>
#include <Security/SecBase.h>
#include <CoreFoundation/CoreFoundation.h>
#include <dispatch/dispatch.h>
#include <sys/types.h>
#if SEC_OS_OSX
#include <Security/SecAccess.h>
#include <Security/cssmtype.h>
#endif /* SEC_OS_OSX */
__BEGIN_DECLS
CF_ASSUME_NONNULL_BEGIN
CF_IMPLICIT_BRIDGING_ENABLED
#if SEC_OS_OSX
/*!
@enum KeyItemAttributeConstants
@abstract Specifies keychain item attributes for keys.
@constant kSecKeyKeyClass type uint32 (CSSM_KEYCLASS), value
is one of CSSM_KEYCLASS_PUBLIC_KEY, CSSM_KEYCLASS_PRIVATE_KEY
or CSSM_KEYCLASS_SESSION_KEY.
@constant kSecKeyPrintName type blob, human readable name of
the key. Same as kSecLabelItemAttr for normal keychain items.
@constant kSecKeyAlias type blob, currently unused.
@constant kSecKeyPermanent type uint32, value is nonzero iff
this key is permanent (stored in some keychain). This is always
1.
@constant kSecKeyPrivate type uint32, value is nonzero iff this
key is protected by a user login or a password, or both.
@constant kSecKeyModifiable type uint32, value is nonzero iff
attributes of this key can be modified.
@constant kSecKeyLabel type blob, for private and public keys
this contains the hash of the public key. This is used to
associate certificates and keys. Its value matches the value
of the kSecPublicKeyHashItemAttr of a certificate and it's used
to construct an identity from a certificate and a key.
For symmetric keys this is whatever the creator of the key
passed in during the generate key call.
@constant kSecKeyApplicationTag type blob, currently unused.
@constant kSecKeyKeyCreator type data, the data points to a
CSSM_GUID structure representing the moduleid of the csp owning
this key.
@constant kSecKeyKeyType type uint32, value is a CSSM_ALGORITHMS
representing the algorithm associated with this key.
@constant kSecKeyKeySizeInBits type uint32, value is the number
of bits in this key.
@constant kSecKeyEffectiveKeySize type uint32, value is the
effective number of bits in this key. For example a des key
has a kSecKeyKeySizeInBits of 64 but a kSecKeyEffectiveKeySize
of 56.
@constant kSecKeyStartDate type CSSM_DATE. Earliest date from
which this key may be used. If the value is all zeros or not
present, no restriction applies.
@constant kSecKeyEndDate type CSSM_DATE. Latest date at
which this key may be used. If the value is all zeros or not
present, no restriction applies.
@constant kSecKeySensitive type uint32, iff value is nonzero
this key cannot be wrapped with CSSM_ALGID_NONE.
@constant kSecKeyAlwaysSensitive type uint32, value is nonzero
iff this key has always been marked sensitive.
@constant kSecKeyExtractable type uint32, value is nonzero iff
this key can be wrapped.
@constant kSecKeyNeverExtractable type uint32, value is nonzero
iff this key was never marked extractable.
@constant kSecKeyEncrypt type uint32, value is nonzero iff this
key can be used in an encrypt operation.
@constant kSecKeyDecrypt type uint32, value is nonzero iff this
key can be used in a decrypt operation.
@constant kSecKeyDerive type uint32, value is nonzero iff this
key can be used in a deriveKey operation.
@constant kSecKeySign type uint32, value is nonzero iff this
key can be used in a sign operation.
@constant kSecKeyVerify type uint32, value is nonzero iff this
key can be used in a verify operation.
@constant kSecKeySignRecover type uint32.
@constant kSecKeyVerifyRecover type uint32.
key can unwrap other keys.
@constant kSecKeyWrap type uint32, value is nonzero iff this
key can wrap other keys.
@constant kSecKeyUnwrap type uint32, value is nonzero iff this
key can unwrap other keys.
@discussion
The use of these enumerations has been deprecated. Please
use the equivalent items defined in SecItem.h
@@@.
*/
CF_ENUM(int)
{
kSecKeyKeyClass = 0,
kSecKeyPrintName = 1,
kSecKeyAlias = 2,
kSecKeyPermanent = 3,
kSecKeyPrivate = 4,
kSecKeyModifiable = 5,
kSecKeyLabel = 6,
kSecKeyApplicationTag = 7,
kSecKeyKeyCreator = 8,
kSecKeyKeyType = 9,
kSecKeyKeySizeInBits = 10,
kSecKeyEffectiveKeySize = 11,
kSecKeyStartDate = 12,
kSecKeyEndDate = 13,
kSecKeySensitive = 14,
kSecKeyAlwaysSensitive = 15,
kSecKeyExtractable = 16,
kSecKeyNeverExtractable = 17,
kSecKeyEncrypt = 18,
kSecKeyDecrypt = 19,
kSecKeyDerive = 20,
kSecKeySign = 21,
kSecKeyVerify = 22,
kSecKeySignRecover = 23,
kSecKeyVerifyRecover = 24,
kSecKeyWrap = 25,
kSecKeyUnwrap = 26
};
/*!
@enum SecCredentialType
@abstract Determines the type of credential returned by SecKeyGetCredentials.
@constant kSecCredentialTypeWithUI Operations with this key are allowed to present UI if required.
@constant kSecCredentialTypeNoUI Operations with this key are not allowed to present UI, and will fail if UI is required.
@constant kSecCredentialTypeDefault The default setting for determining whether to present UI is used. This setting can be changed with a call to SecKeychainSetUserInteractionAllowed.
*/
typedef CF_ENUM(uint32, SecCredentialType)
{
kSecCredentialTypeDefault = 0,
kSecCredentialTypeWithUI,
kSecCredentialTypeNoUI
};
#endif /* SEC_OS_OSX */
/*!
@typedef SecPadding
@abstract Supported padding types.
*/
typedef CF_OPTIONS(uint32_t, SecPadding)
{
kSecPaddingNone = 0,
kSecPaddingPKCS1 = 1,
kSecPaddingOAEP = 2, // __OSX_UNAVAILABLE __IOS_AVAILABLE(2.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0),
/* For SecKeyRawSign/SecKeyRawVerify only,
ECDSA signature is raw byte format {r,s}, big endian.
First half is r, second half is s */
kSecPaddingSigRaw = 0x4000,
/* For SecKeyRawSign/SecKeyRawVerify only, data to be signed is an MD2
hash; standard ASN.1 padding will be done, as well as PKCS1 padding
of the underlying RSA operation. */
kSecPaddingPKCS1MD2 = 0x8000, // __OSX_DEPRECATED(10.0, 10.12, "MD2 is deprecated") __IOS_DEPRECATED(2.0, 5.0, "MD2 is deprecated") __TVOS_UNAVAILABLE __WATCHOS_UNAVAILABLE,
/* For SecKeyRawSign/SecKeyRawVerify only, data to be signed is an MD5
hash; standard ASN.1 padding will be done, as well as PKCS1 padding
of the underlying RSA operation. */
kSecPaddingPKCS1MD5 = 0x8001, // __OSX_DEPRECATED(10.0, 10.12, "MD5 is deprecated") __IOS_DEPRECATED(2.0, 5.0, "MD5 is deprecated") __TVOS_UNAVAILABLE __WATCHOS_UNAVAILABLE,
/* For SecKeyRawSign/SecKeyRawVerify only, data to be signed is a SHA1
hash; standard ASN.1 padding will be done, as well as PKCS1 padding
of the underlying RSA operation. */
kSecPaddingPKCS1SHA1 = 0x8002,
/* For SecKeyRawSign/SecKeyRawVerify only, data to be signed is a SHA224
hash; standard ASN.1 padding will be done, as well as PKCS1 padding
of the underlying RSA operation. */
kSecPaddingPKCS1SHA224 = 0x8003, // __OSX_UNAVAILABLE __IOS_AVAILABLE(2.0),
/* For SecKeyRawSign/SecKeyRawVerify only, data to be signed is a SHA256
hash; standard ASN.1 padding will be done, as well as PKCS1 padding
of the underlying RSA operation. */
kSecPaddingPKCS1SHA256 = 0x8004, // __OSX_UNAVAILABLE __IOS_AVAILABLE(2.0),
/* For SecKeyRawSign/SecKeyRawVerify only, data to be signed is a SHA384
hash; standard ASN.1 padding will be done, as well as PKCS1 padding
of the underlying RSA operation. */
kSecPaddingPKCS1SHA384 = 0x8005, // __OSX_UNAVAILABLE __IOS_AVAILABLE(2.0),
/* For SecKeyRawSign/SecKeyRawVerify only, data to be signed is a SHA512
hash; standard ASN.1 padding will be done, as well as PKCS1 padding
of the underlying RSA operation. */
kSecPaddingPKCS1SHA512 = 0x8006, // __OSX_UNAVAILABLE __IOS_AVAILABLE(2.0),
};
#if SEC_OS_OSX
/*!
@typedef SecKeySizes
@abstract Supported key lengths.
*/
typedef CF_ENUM(uint32_t, SecKeySizes)
{
kSecDefaultKeySize = 0,
// Symmetric Keysizes - default is currently kSecAES128 for AES.
kSec3DES192 = 192,
kSecAES128 = 128,
kSecAES192 = 192,
kSecAES256 = 256,
// Supported ECC Keys for Suite-B from RFC 4492 section 5.1.1.
// default is currently kSecp256r1
kSecp192r1 = 192,
kSecp256r1 = 256,
kSecp384r1 = 384,
kSecp521r1 = 521, // Yes, 521
// Boundaries for RSA KeySizes - default is currently 2048
// RSA keysizes must be multiples of 8
kSecRSAMin = 1024,
kSecRSAMax = 4096
};
#endif /* SEC_OS_OSX */
/*!
@enum Key Parameter Constants
@discussion Predefined key constants used to get or set values in a dictionary.
These are used to provide explicit parameters to key generation functions
when non-default values are desired. See the description of the
SecKeyGeneratePair API for usage information.
@constant kSecPrivateKeyAttrs The value for this key is a CFDictionaryRef
containing attributes specific for the private key to be generated.
@constant kSecPublicKeyAttrs The value for this key is a CFDictionaryRef
containing attributes specific for the public key to be generated.
*/
extern const CFStringRef kSecPrivateKeyAttrs
__OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_2_0);
extern const CFStringRef kSecPublicKeyAttrs
__OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_2_0);
/*!
@function SecKeyGetTypeID
@abstract Returns the type identifier of SecKey instances.
@result The CFTypeID of SecKey instances.
*/
CFTypeID SecKeyGetTypeID(void)
__OSX_AVAILABLE_STARTING(__MAC_10_3, __IPHONE_2_0);
#if SEC_OS_OSX
/*!
@function SecKeyCreatePair
@abstract Creates an asymmetric key pair and stores it in a specified keychain.
@param keychainRef A reference to the keychain in which to store the private and public key items. Specify NULL for the default keychain.
@param algorithm An algorithm for the key pair. This parameter is ignored if a valid (non-zero) contextHandle is supplied.
@param keySizeInBits A key size for the key pair. This parameter is ignored if a valid (non-zero) contextHandle is supplied.
@param contextHandle (optional) A CSSM_CC_HANDLE, or 0. If this argument is supplied, the algorithm and keySizeInBits parameters are ignored. If extra parameters are needed to generate a key (some algorithms require this), you should create a context using CSSM_CSP_CreateKeyGenContext, using the CSPHandle obtained by calling SecKeychainGetCSPHandle. Then use CSSM_UpdateContextAttributes to add parameters, and dispose of the context using CSSM_DeleteContext after calling this function.
@param publicKeyUsage A bit mask indicating all permitted uses for the new public key. CSSM_KEYUSE bit mask values are defined in cssmtype.h.
@param publicKeyAttr A bit mask defining attribute values for the new public key. The bit mask values are equivalent to a CSSM_KEYATTR_FLAGS and are defined in cssmtype.h.
@param privateKeyUsage A bit mask indicating all permitted uses for the new private key. CSSM_KEYUSE bit mask values are defined in cssmtype.h.
@param privateKeyAttr A bit mask defining attribute values for the new private key. The bit mask values are equivalent to a CSSM_KEYATTR_FLAGS and are defined in cssmtype.h.
@param initialAccess (optional) A SecAccess object that determines the initial access rights to the private key. The public key is given "any/any" access rights by default.
@param publicKey (optional) On return, the keychain item reference of the generated public key. Use the SecKeyGetCSSMKey function to obtain the CSSM_KEY. The caller must call CFRelease on this value if it is returned. Pass NULL if a reference to this key is not required.
@param privateKey (optional) On return, the keychain item reference of the generated private key. Use the SecKeyGetCSSMKey function to obtain the CSSM_KEY. The caller must call CFRelease on this value if it is returned. Pass NULL if a reference to this key is not required.
@result A result code. See "Security Error Codes" (SecBase.h).
@discussion This API is deprecated for 10.7. Please use the SecKeyGeneratePair API instead.
*/
OSStatus SecKeyCreatePair(
SecKeychainRef _Nullable keychainRef,
CSSM_ALGORITHMS algorithm,
uint32 keySizeInBits,
CSSM_CC_HANDLE contextHandle,
CSSM_KEYUSE publicKeyUsage,
uint32 publicKeyAttr,
CSSM_KEYUSE privateKeyUsage,
uint32 privateKeyAttr,
SecAccessRef _Nullable initialAccess,
SecKeyRef* _Nullable CF_RETURNS_RETAINED publicKey,
SecKeyRef* _Nullable CF_RETURNS_RETAINED privateKey)
CSSM_DEPRECATED;
/*!
@function SecKeyGenerate
@abstract Creates a symmetric key and optionally stores it in a specified keychain.
@param keychainRef (optional) A reference to the keychain in which to store the generated key. Specify NULL to generate a transient key.
@param algorithm An algorithm for the symmetric key. This parameter is ignored if a valid (non-zero) contextHandle is supplied.
@param keySizeInBits A key size for the key pair. This parameter is ignored if a valid (non-zero) contextHandle is supplied.
@param contextHandle (optional) A CSSM_CC_HANDLE, or 0. If this argument is supplied, the algorithm and keySizeInBits parameters are ignored. If extra parameters are needed to generate a key (some algorithms require this), you should create a context using CSSM_CSP_CreateKeyGenContext, using the CSPHandle obtained by calling SecKeychainGetCSPHandle. Then use CSSM_UpdateContextAttributes to add parameters, and dispose of the context using CSSM_DeleteContext after calling this function.
@param keyUsage A bit mask indicating all permitted uses for the new key. CSSM_KEYUSE bit mask values are defined in cssmtype.h.
@param keyAttr A bit mask defining attribute values for the new key. The bit mask values are equivalent to a CSSM_KEYATTR_FLAGS and are defined in cssmtype.h.
@param initialAccess (optional) A SecAccess object that determines the initial access rights for the key. This parameter is ignored if the keychainRef is NULL.
@param keyRef On return, a reference to the generated key. Use the SecKeyGetCSSMKey function to obtain the CSSM_KEY. The caller must call CFRelease on this value if it is returned.
@result A result code. See "Security Error Codes" (SecBase.h).
@discussion This API is deprecated for 10.7. Please use the SecKeyGenerateSymmetric API instead.
*/
OSStatus SecKeyGenerate(
SecKeychainRef _Nullable keychainRef,
CSSM_ALGORITHMS algorithm,
uint32 keySizeInBits,
CSSM_CC_HANDLE contextHandle,
CSSM_KEYUSE keyUsage,
uint32 keyAttr,
SecAccessRef _Nullable initialAccess,
SecKeyRef* _Nullable CF_RETURNS_RETAINED keyRef)
CSSM_DEPRECATED;
/*!
@function SecKeyGetCSSMKey
@abstract Returns a pointer to the CSSM_KEY for the given key item reference.
@param key A keychain key item reference. The key item must be of class type kSecPublicKeyItemClass, kSecPrivateKeyItemClass, or kSecSymmetricKeyItemClass.
@param cssmKey On return, a pointer to a CSSM_KEY structure for the given key. This pointer remains valid until the key reference is released. The caller should not attempt to modify or free this data.
@result A result code. See "Security Error Codes" (SecBase.h).
@discussion The CSSM_KEY is valid until the key item reference is released. This API is deprecated in 10.7. Its use should no longer be needed.
*/
OSStatus SecKeyGetCSSMKey(SecKeyRef key, const CSSM_KEY * _Nullable * __nonnull cssmKey)
DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER;;
/*!
@function SecKeyGetCSPHandle
@abstract Returns the CSSM_CSP_HANDLE for the given key reference. The handle is valid until the key reference is released.
@param keyRef A key reference.
@param cspHandle On return, the CSSM_CSP_HANDLE for the given keychain.
@result A result code. See "Security Error Codes" (SecBase.h).
@discussion This API is deprecated in 10.7. Its use should no longer be needed.
*/
OSStatus SecKeyGetCSPHandle(SecKeyRef keyRef, CSSM_CSP_HANDLE *cspHandle)
DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER;
/*!
@function SecKeyGetCredentials
@abstract For a given key, return a pointer to a CSSM_ACCESS_CREDENTIALS structure which will allow the key to be used.
@param keyRef The key for which a credential is requested.
@param operation The type of operation to be performed with this key. See "Authorization tag type" for defined operations (cssmtype.h).
@param credentialType The type of credential requested.
@param outCredentials On return, a pointer to a CSSM_ACCESS_CREDENTIALS structure. This pointer remains valid until the key reference is released. The caller should not attempt to modify or free this data.
@result A result code. See "Security Error Codes" (SecBase.h).
*/
OSStatus SecKeyGetCredentials(
SecKeyRef keyRef,
CSSM_ACL_AUTHORIZATION_TAG operation,
SecCredentialType credentialType,
const CSSM_ACCESS_CREDENTIALS * _Nullable * __nonnull outCredentials)
DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER;
/*!
@function SecKeyGenerateSymmetric
@abstract Generates a random symmetric key with the specified length
and algorithm type.
@param parameters A dictionary containing one or more key-value pairs.
See the discussion sections below for a complete overview of options.
@param error An optional pointer to a CFErrorRef. This value is set
if an error occurred. If not NULL, the caller is responsible for
releasing the CFErrorRef.
@result On return, a SecKeyRef reference to the symmetric key, or
NULL if the key could not be created.
@discussion In order to generate a symmetric key, the parameters dictionary
must at least contain the following keys:
* kSecAttrKeyType with a value of kSecAttrKeyTypeAES or any other
kSecAttrKeyType defined in SecItem.h
* kSecAttrKeySizeInBits with a value being a CFNumberRef containing
the requested key size in bits. Example sizes for AES keys are:
128, 192, 256, 512.
To store the generated symmetric key in a keychain, set these keys:
* kSecUseKeychain (value is a SecKeychainRef)
* kSecAttrLabel (a user-visible label whose value is a CFStringRef,
e.g. "My App's Encryption Key")
* kSecAttrApplicationLabel (a label defined by your application, whose
value is a CFDataRef and which can be used to find this key in a
subsequent call to SecItemCopyMatching, e.g. "ID-1234567890-9876-0151")
To specify the generated key's access control settings, set this key:
* kSecAttrAccess (value is a SecAccessRef)
The keys below may be optionally set in the parameters dictionary
(with a CFBooleanRef value) to override the default usage values:
* kSecAttrCanEncrypt (defaults to true if not explicitly specified)
* kSecAttrCanDecrypt (defaults to true if not explicitly specified)
* kSecAttrCanWrap (defaults to true if not explicitly specified)
* kSecAttrCanUnwrap (defaults to true if not explicitly specified)
*/
_Nullable CF_RETURNS_RETAINED
SecKeyRef SecKeyGenerateSymmetric(CFDictionaryRef parameters, CFErrorRef *error)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA);
/*!
@function SecKeyCreateFromData
@abstract Creates a symmetric key with the given data and sets the
algorithm type specified.
@param parameters A dictionary containing one or more key-value pairs.
See the discussion sections below for a complete overview of options.
@result On return, a SecKeyRef reference to the symmetric key.
@discussion In order to generate a symmetric key the parameters dictionary must
at least contain the following keys:
* kSecAttrKeyType with a value of kSecAttrKeyTypeAES or any other
kSecAttrKeyType defined in SecItem.h
The keys below may be optionally set in the parameters dictionary
(with a CFBooleanRef value) to override the default usage values:
* kSecAttrCanEncrypt (defaults to true if not explicitly specified)
* kSecAttrCanDecrypt (defaults to true if not explicitly specified)
* kSecAttrCanWrap (defaults to true if not explicitly specified)
* kSecAttrCanUnwrap (defaults to true if not explicitly specified)
*/
_Nullable
SecKeyRef SecKeyCreateFromData(CFDictionaryRef parameters,
CFDataRef keyData, CFErrorRef *error)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA);
#ifdef __BLOCKS__
/*!
@typedef SecKeyGeneratePairBlock
@abstract Delivers the result from an asynchronous key pair generation.
@param publicKey - the public key generated. You must retain publicKey if you wish to use it after your block returns.
@param privateKey - the private key generated. You must retain publicKey if you wish to use it after your block returns.
@param error - Any errors returned. You must retain error if you wish to use it after your block returns.
*/
typedef void (^SecKeyGeneratePairBlock)(SecKeyRef publicKey, SecKeyRef privateKey, CFErrorRef error);
/*!
@function SecKeyGeneratePairAsync
@abstract Generate a private/public keypair returning the values in a callback.
@param parameters A dictionary containing one or more key-value pairs.
@param deliveryQueue A dispatch queue to be used to deliver the results.
@param result A callback function to result when the operation has completed.
@discussion In order to generate a keypair the parameters dictionary must
at least contain the following keys:
* kSecAttrKeyType with a value being kSecAttrKeyTypeRSA or any other
kSecAttrKeyType defined in SecItem.h
* kSecAttrKeySizeInBits with a value being a CFNumberRef or CFStringRef
containing the requested key size in bits. Example sizes for RSA
keys are: 512, 768, 1024, 2048.
Setting the following attributes explicitly will override the defaults below.
See SecItem.h for detailed information on these attributes including the types
of the values.
* kSecAttrLabel default NULL
* kSecAttrIsPermanent if this key is present and has a Boolean
value of true, the key or key pair will be added to the default
keychain.
* kSecAttrApplicationTag default NULL
* kSecAttrEffectiveKeySize default NULL same as kSecAttrKeySizeInBits
* kSecAttrCanEncrypt default false for private keys, true for public keys
* kSecAttrCanDecrypt default true for private keys, false for public keys
* kSecAttrCanDerive default true
* kSecAttrCanSign default true for private keys, false for public keys
* kSecAttrCanVerify default false for private keys, true for public keys
* kSecAttrCanWrap default false for private keys, true for public keys
* kSecAttrCanUnwrap default true for private keys, false for public keys
*/
void SecKeyGeneratePairAsync(CFDictionaryRef parameters,
dispatch_queue_t deliveryQueue, SecKeyGeneratePairBlock result)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA);
#endif /* __BLOCKS__ */
// Derive, Wrap, and Unwrap
/*!
@function SecKeyDeriveFromPassword
@abstract Derives a symmetric key from a password.
@param password The password from which the keyis to be derived.
@param parameters A dictionary containing one or more key-value pairs.
@param error If the call fails this will contain the error code.
@discussion In order to derive a key the parameters dictionary must contain at least contain the following keys:
* kSecAttrSalt - a CFData for the salt value for mixing in the pseudo-random rounds.
* kSecAttrPRF - the algorithm to use for the pseudo-random-function.
If 0, this defaults to kSecAttrPRFHmacAlgSHA1. Possible values are:
* kSecAttrPRFHmacAlgSHA1
* kSecAttrPRFHmacAlgSHA224
* kSecAttrPRFHmacAlgSHA256
* kSecAttrPRFHmacAlgSHA384
* kSecAttrPRFHmacAlgSHA512
* kSecAttrRounds - the number of rounds to call the pseudo random function.
If 0, a count will be computed to average 1/10 of a second.
* kSecAttrKeySizeInBits with a value being a CFNumberRef
containing the requested key size in bits. Example sizes for RSA keys are:
512, 768, 1024, 2048.
@result On success a SecKeyRef is returned. On failure this result is NULL and the
error parameter contains the reason.
*/
_Nullable CF_RETURNS_RETAINED
SecKeyRef SecKeyDeriveFromPassword(CFStringRef password,
CFDictionaryRef parameters, CFErrorRef *error)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA);
/*!
@function SecKeyWrapSymmetric
@abstract Wraps a symmetric key with a symmetric key.
@param keyToWrap The key which is to be wrapped.
@param wrappingKey The key wrapping key.
@param parameters The parameter list to use for wrapping the key.
@param error If the call fails this will contain the error code.
@result On success a CFDataRef is returned. On failure this result is NULL and the
error parameter contains the reason.
@discussion In order to wrap a key the parameters dictionary may contain the following key:
* kSecSalt - a CFData for the salt value for the encrypt.
*/
_Nullable
CFDataRef SecKeyWrapSymmetric(SecKeyRef keyToWrap,
SecKeyRef wrappingKey, CFDictionaryRef parameters, CFErrorRef *error)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA);
/*!
@function SecKeyUnwrapSymmetric
@abstract Unwrap a wrapped symmetric key.
@param keyToUnwrap The wrapped key to unwrap.
@param unwrappingKey The key unwrapping key.
@param parameters The parameter list to use for unwrapping the key.
@param error If the call fails this will contain the error code.
@result On success a SecKeyRef is returned. On failure this result is NULL and the
error parameter contains the reason.
@discussion In order to unwrap a key the parameters dictionary may contain the following key:
* kSecSalt - a CFData for the salt value for the decrypt.
*/
_Nullable
SecKeyRef SecKeyUnwrapSymmetric(CFDataRef _Nullable * __nonnull keyToUnwrap,
SecKeyRef unwrappingKey, CFDictionaryRef parameters, CFErrorRef *error)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA);
#endif /* SEC_OS_OSX */
/*!
@function SecKeyGeneratePair
@abstract Generate a private/public keypair.
@param parameters A dictionary containing one or more key-value pairs.
See the discussion sections below for a complete overview of options.
@param publicKey On return, a SecKeyRef reference to the public key.
@param privateKey On return, a SecKeyRef reference to the private key.
@result A result code. See "Security Error Codes" (SecBase.h).
@discussion In order to generate a keypair the parameters dictionary must
at least contain the following keys:
* kSecAttrKeyType with a value of kSecAttrKeyTypeRSA or any other
kSecAttrKeyType defined in SecItem.h
* kSecAttrKeySizeInBits with a value being a CFNumberRef containing
the requested key size in bits. Example sizes for RSA keys are:
512, 768, 1024, 2048.
The values below may be set either in the top-level dictionary or in a
dictionary that is the value of the kSecPrivateKeyAttrs or
kSecPublicKeyAttrs key in the top-level dictionary. Setting these
attributes explicitly will override the defaults below. See SecItem.h
for detailed information on these attributes including the types of
the values.
* kSecAttrLabel default NULL
* kSecUseKeychain default NULL, which specifies the default keychain
* kSecAttrIsPermanent default false
if this key is present and has a Boolean value of true, the key or
key pair will be added to the keychain.
* kSecAttrTokenID default NULL
The CFStringRef ID of the token to generate the key or keypair on. This
attribute can contain CFStringRef and can be present only in the top-level
parameters dictionary.
* kSecAttrApplicationTag default NULL
* kSecAttrEffectiveKeySize default NULL same as kSecAttrKeySizeInBits
* kSecAttrCanEncrypt default false for private keys, true for public keys
* kSecAttrCanDecrypt default true for private keys, false for public keys
* kSecAttrCanDerive default true
* kSecAttrCanSign default true for private keys, false for public keys
* kSecAttrCanVerify default false for private keys, true for public keys
* kSecAttrCanWrap default false for private keys, true for public keys
* kSecAttrCanUnwrap default true for private keys, false for public keys
NOTE: The function always saves keys in the keychain on macOS and as such attribute
kSecAttrIsPermanent is ignored. The function respects attribute kSecAttrIsPermanent
on iOS, tvOS and watchOS.
It is recommended to use SecKeyCreateRandomKey() which respects kSecAttrIsPermanent
on all platforms.
*/
OSStatus SecKeyGeneratePair(CFDictionaryRef parameters,
SecKeyRef * _Nullable CF_RETURNS_RETAINED publicKey, SecKeyRef * _Nullable CF_RETURNS_RETAINED privateKey)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_2_0);
#if SEC_OS_IPHONE
/*!
@function SecKeyRawSign
@abstract Given a private key and data to sign, generate a digital
signature.
@param key Private key with which to sign.
@param padding See Padding Types above, typically kSecPaddingPKCS1SHA1.
@param dataToSign The data to be signed, typically the digest of the
actual data.
@param dataToSignLen Length of dataToSign in bytes.
@param sig Pointer to buffer in which the signature will be returned.
@param sigLen IN/OUT maximum length of sig buffer on input, actualy
length of sig on output.
@result A result code. See "Security Error Codes" (SecBase.h).
@discussion If the padding argument is kSecPaddingPKCS1, PKCS1 padding
will be performed prior to signing. If this argument is kSecPaddingNone,
the incoming data will be signed "as is".
When PKCS1 padding is performed, the maximum length of data that can
be signed is the value returned by SecKeyGetBlockSize() - 11.
NOTE: The behavior this function with kSecPaddingNone is undefined if the
first byte of dataToSign is zero; there is no way to verify leading zeroes
as they are discarded during the calculation.
If you want to generate a proper PKCS1 style signature with DER encoding
of the digest type - and the dataToSign is a SHA1 digest - use
kSecPaddingPKCS1SHA1.
*/
OSStatus SecKeyRawSign(
SecKeyRef key,
SecPadding padding,
const uint8_t *dataToSign,
size_t dataToSignLen,
uint8_t *sig,
size_t *sigLen)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_2_0);
/*!
@function SecKeyRawVerify
@abstract Given a public key, data which has been signed, and a signature,
verify the signature.
@param key Public key with which to verify the signature.
@param padding See Padding Types above, typically kSecPaddingPKCS1SHA1.
@param signedData The data over which sig is being verified, typically
the digest of the actual data.
@param signedDataLen Length of signedData in bytes.
@param sig Pointer to the signature to verify.
@param sigLen Length of sig in bytes.
@result A result code. See "Security Error Codes" (SecBase.h).
@discussion If the padding argument is kSecPaddingPKCS1, PKCS1 padding
will be checked during verification. If this argument is kSecPaddingNone,
the incoming data will be compared directly to sig.
If you are verifying a proper PKCS1-style signature, with DER encoding
of the digest type - and the signedData is a SHA1 digest - use
kSecPaddingPKCS1SHA1.
*/
OSStatus SecKeyRawVerify(
SecKeyRef key,
SecPadding padding,
const uint8_t *signedData,
size_t signedDataLen,
const uint8_t *sig,
size_t sigLen)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_2_0);
/*!
@function SecKeyEncrypt
@abstract Encrypt a block of plaintext.
@param key Public key with which to encrypt the data.
@param padding See Padding Types above, typically kSecPaddingPKCS1.
@param plainText The data to encrypt.
@param plainTextLen Length of plainText in bytes, this must be less
or equal to the value returned by SecKeyGetBlockSize().
@param cipherText Pointer to the output buffer.
@param cipherTextLen On input, specifies how much space is available at
cipherText; on return, it is the actual number of cipherText bytes written.
@result A result code. See "Security Error Codes" (SecBase.h).
@discussion If the padding argument is kSecPaddingPKCS1 or kSecPaddingOAEP,
PKCS1 (respectively kSecPaddingOAEP) padding will be performed prior to encryption.
If this argument is kSecPaddingNone, the incoming data will be encrypted "as is".
kSecPaddingOAEP is the recommended value. Other value are not recommended
for security reason (Padding attack or malleability).
When PKCS1 padding is performed, the maximum length of data that can
be encrypted is the value returned by SecKeyGetBlockSize() - 11.
When memory usage is a critical issue, note that the input buffer
(plainText) can be the same as the output buffer (cipherText).
*/
OSStatus SecKeyEncrypt(
SecKeyRef key,
SecPadding padding,
const uint8_t *plainText,
size_t plainTextLen,
uint8_t *cipherText,
size_t *cipherTextLen)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_2_0);
/*!
@function SecKeyDecrypt
@abstract Decrypt a block of ciphertext.
@param key Private key with which to decrypt the data.
@param padding See Padding Types above, typically kSecPaddingPKCS1.
@param cipherText The data to decrypt.
@param cipherTextLen Length of cipherText in bytes, this must be less
or equal to the value returned by SecKeyGetBlockSize().
@param plainText Pointer to the output buffer.
@param plainTextLen On input, specifies how much space is available at
plainText; on return, it is the actual number of plainText bytes written.
@result A result code. See "Security Error Codes" (SecBase.h).
@discussion If the padding argument is kSecPaddingPKCS1 or kSecPaddingOAEP,
the corresponding padding will be removed after decryption.
If this argument is kSecPaddingNone, the decrypted data will be returned "as is".
When memory usage is a critical issue, note that the input buffer
(plainText) can be the same as the output buffer (cipherText).
*/
OSStatus SecKeyDecrypt(
SecKeyRef key, /* Private key */
SecPadding padding, /* kSecPaddingNone,
kSecPaddingPKCS1,
kSecPaddingOAEP */
const uint8_t *cipherText,
size_t cipherTextLen, /* length of cipherText */
uint8_t *plainText,
size_t *plainTextLen) /* IN/OUT */
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_2_0);
#endif // SEC_OS_IPHONE
/*!
@function SecKeyCreateRandomKey
@abstract Generates a new public/private key pair.
@param parameters A dictionary containing one or more key-value pairs.
See the discussion sections below for a complete overview of options.
@param error On error, will be populated with an error object describing the failure.
See "Security Error Codes" (SecBase.h).
@return Newly generated private key. To get associated public key, use SecKeyCopyPublicKey().
@discussion In order to generate a keypair the parameters dictionary must
at least contain the following keys:
* kSecAttrKeyType with a value being kSecAttrKeyTypeRSA or any other
kSecAttrKeyType defined in SecItem.h
* kSecAttrKeySizeInBits with a value being a CFNumberRef or CFStringRef
containing the requested key size in bits. Example sizes for RSA
keys are: 512, 768, 1024, 2048.
The values below may be set either in the top-level dictionary or in a
dictionary that is the value of the kSecPrivateKeyAttrs or
kSecPublicKeyAttrs key in the top-level dictionary. Setting these
attributes explicitly will override the defaults below. See SecItem.h
for detailed information on these attributes including the types of
the values.
* kSecAttrLabel default NULL
* kSecAttrIsPermanent if this key is present and has a Boolean value of true,
the key or key pair will be added to the default keychain.
* kSecAttrTokenID if this key should be generated on specified token. This
attribute can contain CFStringRef and can be present only in the top-level
parameters dictionary.
* kSecAttrApplicationTag default NULL
* kSecAttrEffectiveKeySize default NULL same as kSecAttrKeySizeInBits
* kSecAttrCanEncrypt default false for private keys, true for public keys
* kSecAttrCanDecrypt default true for private keys, false for public keys
* kSecAttrCanDerive default true
* kSecAttrCanSign default true for private keys, false for public keys
* kSecAttrCanVerify default false for private keys, true for public keys
* kSecAttrCanWrap default false for private keys, true for public keys
* kSecAttrCanUnwrap default true for private keys, false for public keys
*/
SecKeyRef _Nullable SecKeyCreateRandomKey(CFDictionaryRef parameters, CFErrorRef *error)
__OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
/*!
@function SecKeyCreateWithData
@abstract Create a SecKey from a well-defined external representation.
@param keyData CFData representing the key. The format of the data depends on the type of key being created.
@param attributes Dictionary containing attributes describing the key to be imported. The keys in this dictionary
are kSecAttr* constants from SecItem.h. Mandatory attributes are:
* kSecAttrKeyType
* kSecAttrKeyClass
@param error On error, will be populated with an error object describing the failure.
See "Security Error Codes" (SecBase.h).
@result A SecKey object representing the key, or NULL on failure.
@discussion This function does not add keys to any keychain, but the SecKey object it returns can be added
to keychain using the SecItemAdd function.
The requested data format depend on the type of key (kSecAttrKeyType) being created:
* kSecAttrKeyTypeRSA PKCS#1 format, public key can be also in x509 public key format
* kSecAttrKeyTypeECSECPrimeRandom ANSI X9.63 format (04 || X || Y [ || K])
*/
SecKeyRef _Nullable SecKeyCreateWithData(CFDataRef keyData, CFDictionaryRef attributes, CFErrorRef *error)
__OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
/*!
@function SecKeyGetBlockSize
@abstract Returns block length of the key in bytes.
@param key The key for which the block length is requested.
@result The block length of the key in bytes.
@discussion If for example key is an RSA key the value returned by
this function is the size of the modulus.
*/
size_t SecKeyGetBlockSize(SecKeyRef key)
__OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_2_0);
/*!
@function SecKeyCopyExternalRepresentation
@abstract Create an external representation for the given key suitable for the key's type.
@param key The key to be exported.
@param error On error, will be populated with an error object describing the failure.
See "Security Error Codes" (SecBase.h).
@result A CFData representing the key in a format suitable for that key type.
@discussion This function may fail if the key is not exportable (e.g., bound to a smart card or Secure Enclave).
The format in which the key will be exported depends on the type of key:
* kSecAttrKeyTypeRSA PKCS#1 format
* kSecAttrKeyTypeECSECPrimeRandom ANSI X9.63 format (04 || X || Y [ || K])
*/
CFDataRef _Nullable SecKeyCopyExternalRepresentation(SecKeyRef key, CFErrorRef *error)
__OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
/*!
@function SecKeyCopyAttributes
@abstract Retrieve keychain attributes of a key.
@param key The key whose attributes are to be retrieved.
@result Dictionary containing attributes of the key. The keys that populate this dictionary are defined
and discussed in SecItem.h.
@discussion The attributes provided by this function are:
* kSecAttrCanEncrypt
* kSecAttrCanDecrypt
* kSecAttrCanDerive
* kSecAttrCanSign
* kSecAttrCanVerify
* kSecAttrKeyClass
* kSecAttrKeyType
* kSecAttrKeySizeInBits
* kSecAttrTokenID
* kSecAttrApplicationLabel
The set of values is not fixed. Future versions may return more values in this dictionary.
*/
CFDictionaryRef _Nullable SecKeyCopyAttributes(SecKeyRef key)
__OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
/*!
@function SecKeyCopyPublicKey
@abstract Retrieve the public key from a key pair or private key.
@param key The key from which to retrieve a public key.
@result The public key or NULL if public key is not available for specified key.
@discussion Fails if key does not contain a public key or no public key can be computed from it.
*/
SecKeyRef _Nullable SecKeyCopyPublicKey(SecKeyRef key)
__OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
/*!
@enum SecKeyAlgorithm
@abstract Available algorithms for performing cryptographic operations with SecKey object. String representation
of constant can be used for logging or debugging purposes, because they contain human readable names of the algorithm.
@constant kSecKeyAlgorithmRSASignatureRaw
Raw RSA sign/verify operation, size of input data must be the same as value returned by SecKeyGetBlockSize().
@constant kSecKeyAlgorithmRSASignatureDigestPKCS1v15Raw
RSA sign/verify operation, assumes that input data is digest and OID and digest algorithm as specified in PKCS# v1.5.
This algorithm is typically not used directly, instead use algorithm with specified digest, like
kSecKeyAlgorithmRSASignatureDigestPKCS1v15SHA256.
@constant kSecKeyAlgorithmRSASignatureDigestPKCS1v15SHA1
RSA signature with PKCS#1 padding, input data must be SHA-1 generated digest.
@constant kSecKeyAlgorithmRSASignatureDigestPKCS1v15SHA224
RSA signature with PKCS#1 padding, input data must be SHA-224 generated digest.
@constant kSecKeyAlgorithmRSASignatureDigestPKCS1v15SHA256
RSA signature with PKCS#1 padding, input data must be SHA-256 generated digest.
@constant kSecKeyAlgorithmRSASignatureDigestPKCS1v15SHA384
RSA signature with PKCS#1 padding, input data must be SHA-384 generated digest.
@constant kSecKeyAlgorithmRSASignatureDigestPKCS1v15SHA512
RSA signature with PKCS#1 padding, input data must be SHA-512 generated digest.
@constant kSecKeyAlgorithmRSASignatureMessagePKCS1v15SHA1
RSA signature with PKCS#1 padding, SHA-1 digest is generated by called function automatically from input data of any size.
@constant kSecKeyAlgorithmRSASignatureMessagePKCS1v15SHA224
RSA signature with PKCS#1 padding, SHA-224 digest is generated by called function automatically from input data of any size.
@constant kSecKeyAlgorithmRSASignatureMessagePKCS1v15SHA256
RSA signature with PKCS#1 padding, SHA-256 digest is generated by called function automatically from input data of any size.
@constant kSecKeyAlgorithmRSASignatureMessagePKCS1v15SHA384
RSA signature with PKCS#1 padding, SHA-384 digest is generated by called function automatically from input data of any size.
@constant kSecKeyAlgorithmRSASignatureMessagePKCS1v15SHA512
RSA signature with PKCS#1 padding, SHA-512 digest is generated by called function automatically from input data of any size.
@constant kSecKeyAlgorithmRSASignatureDigestPSSSHA1
RSA signature with RSASSA-PSS padding according to PKCS#1 v2.1, input data must be SHA-1 generated digest.
PSS padding is calculated using MGF1 with SHA1 and saltLength parameter is set to 20 (SHA-1 output size).
@constant kSecKeyAlgorithmRSASignatureDigestPSSSHA224
RSA signature with RSASSA-PSS padding according to PKCS#1 v2.1, input data must be SHA-224 generated digest.
PSS padding is calculated using MGF1 with SHA224 and saltLength parameter is set to 28 (SHA-224 output size).
@constant kSecKeyAlgorithmRSASignatureDigestPSSSHA256
RSA signature with RSASSA-PSS padding according to PKCS#1 v2.1, input data must be SHA-256 generated digest.
PSS padding is calculated using MGF1 with SHA256 and saltLength parameter is set to 32 (SHA-256 output size).
@constant kSecKeyAlgorithmRSASignatureDigestPSSSHA384
RSA signature with RSASSA-PSS padding according to PKCS#1 v2.1, input data must be SHA-384 generated digest.
PSS padding is calculated using MGF1 with SHA384 and saltLength parameter is set to 48 (SHA-384 output size).
@constant kSecKeyAlgorithmRSASignatureDigestPSSSHA512
RSA signature with RSASSA-PSS padding according to PKCS#1 v2.1, input data must be SHA-512 generated digest.
PSS padding is calculated using MGF1 with SHA512 and saltLength parameter is set to 64 (SHA-512 output size).
@constant kSecKeyAlgorithmRSASignatureMessagePSSSHA1
RSA signature with RSASSA-PSS padding according to PKCS#1 v2.1, SHA-1 digest is generated by called function automatically from input data of any size.
PSS padding is calculated using MGF1 with SHA1 and saltLength parameter is set to 20 (SHA-1 output size).
@constant kSecKeyAlgorithmRSASignatureMessagePSSSHA224
RSA signature with RSASSA-PSS padding according to PKCS#1 v2.1, SHA-224 digest is generated by called function automatically from input data of any size.
PSS padding is calculated using MGF1 with SHA224 and saltLength parameter is set to 28 (SHA-224 output size).
@constant kSecKeyAlgorithmRSASignatureMessagePSSSHA256
RSA signature with RSASSA-PSS padding according to PKCS#1 v2.1, SHA-256 digest is generated by called function automatically from input data of any size.
PSS padding is calculated using MGF1 with SHA256 and saltLength parameter is set to 32 (SHA-256 output size).
@constant kSecKeyAlgorithmRSASignatureMessagePSSSHA384
RSA signature with RSASSA-PSS padding according to PKCS#1 v2.1, SHA-384 digest is generated by called function automatically from input data of any size.
PSS padding is calculated using MGF1 with SHA384 and saltLength parameter is set to 48 (SHA-384 output size).
@constant kSecKeyAlgorithmRSASignatureMessagePSSSHA512
RSA signature with RSASSA-PSS padding according to PKCS#1 v2.1, SHA-512 digest is generated by called function automatically from input data of any size.
PSS padding is calculated using MGF1 with SHA512 and saltLength parameter is set to 64 (SHA-512 output size).
@constant kSecKeyAlgorithmECDSASignatureRFC4754
ECDSA algorithm, signature is concatenated r and s, big endian, input data must be message digest generated by some hash function.
@constant kSecKeyAlgorithmECDSASignatureDigestX962
ECDSA algorithm, signature is in DER x9.62 encoding, input data must be message digest generated by some hash functions.
@constant kSecKeyAlgorithmECDSASignatureDigestX962SHA1
ECDSA algorithm, signature is in DER x9.62 encoding, input data must be message digest created by SHA1 algorithm.
@constant kSecKeyAlgorithmECDSASignatureDigestX962SHA224
ECDSA algorithm, signature is in DER x9.62 encoding, input data must be message digest created by SHA224 algorithm.
@constant kSecKeyAlgorithmECDSASignatureDigestX962SHA256
ECDSA algorithm, signature is in DER x9.62 encoding, input data must be message digest created by SHA256 algorithm.
@constant kSecKeyAlgorithmECDSASignatureDigestX962SHA384
ECDSA algorithm, signature is in DER x9.62 encoding, input data must be message digest created by SHA384 algorithm.
@constant kSecKeyAlgorithmECDSASignatureDigestX962SHA512
ECDSA algorithm, signature is in DER x9.62 encoding, input data must be message digest created by SHA512 algorithm.
@constant kSecKeyAlgorithmECDSASignatureMessageX962SHA1
ECDSA algorithm, signature is in DER x9.62 encoding, SHA-1 digest is generated by called function automatically from input data of any size.
@constant kSecKeyAlgorithmECDSASignatureMessageX962SHA224
ECDSA algorithm, signature is in DER x9.62 encoding, SHA-224 digest is generated by called function automatically from input data of any size.
@constant kSecKeyAlgorithmECDSASignatureMessageX962SHA256
ECDSA algorithm, signature is in DER x9.62 encoding, SHA-256 digest is generated by called function automatically from input data of any size.
@constant kSecKeyAlgorithmECDSASignatureMessageX962SHA384
ECDSA algorithm, signature is in DER x9.62 encoding, SHA-384 digest is generated by called function automatically from input data of any size.
@constant kSecKeyAlgorithmECDSASignatureMessageX962SHA512
ECDSA algorithm, signature is in DER x9.62 encoding, SHA-512 digest is generated by called function automatically from input data of any size.
@constant kSecKeyAlgorithmRSAEncryptionRaw
Raw RSA encryption or decryption, size of data must match RSA key modulus size. Note that direct
use of this algorithm without padding is cryptographically very weak, it is important to always introduce
some kind of padding. Input data size must be less or equal to the key block size and returned block has always
the same size as block size, as returned by SecKeyGetBlockSize().
@constant kSecKeyAlgorithmRSAEncryptionPKCS1
RSA encryption or decryption, data is padded using PKCS#1 padding scheme. This algorithm should be used only for
backward compatibility with existing protocols and data. New implementations should choose cryptographically
stronger algorithm instead (see kSecKeyAlgorithmRSAEncryptionOAEP). Input data must be at most
"key block size - 11" bytes long and returned block has always the same size as block size, as returned
by SecKeyGetBlockSize().
@constant kSecKeyAlgorithmRSAEncryptionOAEPSHA1
RSA encryption or decryption, data is padded using OAEP padding scheme internally using SHA1. Input data must be at most
"key block size - 42" bytes long and returned block has always the same size as block size, as returned
by SecKeyGetBlockSize(). Use kSecKeyAlgorithmRSAEncryptionOAEPSHA1AESGCM to be able to encrypt and decrypt arbitrary long data.
@constant kSecKeyAlgorithmRSAEncryptionOAEPSHA224
RSA encryption or decryption, data is padded using OAEP padding scheme internally using SHA224. Input data must be at most
"key block size - 58" bytes long and returned block has always the same size as block size, as returned
by SecKeyGetBlockSize(). Use kSecKeyAlgorithmRSAEncryptionOAEPSHA224AESGCM to be able to encrypt and decrypt arbitrary long data.
@constant kSecKeyAlgorithmRSAEncryptionOAEPSHA256
RSA encryption or decryption, data is padded using OAEP padding scheme internally using SHA256. Input data must be at most
"key block size - 66" bytes long and returned block has always the same size as block size, as returned
by SecKeyGetBlockSize(). Use kSecKeyAlgorithmRSAEncryptionOAEPSHA256AESGCM to be able to encrypt and decrypt arbitrary long data.
@constant kSecKeyAlgorithmRSAEncryptionOAEPSHA384
RSA encryption or decryption, data is padded using OAEP padding scheme internally using SHA384. Input data must be at most
"key block size - 98" bytes long and returned block has always the same size as block size, as returned
by SecKeyGetBlockSize(). Use kSecKeyAlgorithmRSAEncryptionOAEPSHA384AESGCM to be able to encrypt and decrypt arbitrary long data.
@constant kSecKeyAlgorithmRSAEncryptionOAEPSHA512
RSA encryption or decryption, data is padded using OAEP padding scheme internally using SHA512. Input data must be at most
"key block size - 130" bytes long and returned block has always the same size as block size, as returned
by SecKeyGetBlockSize(). Use kSecKeyAlgorithmRSAEncryptionOAEPSHA512AESGCM to be able to encrypt and decrypt arbitrary long data.
@constant kSecKeyAlgorithmRSAEncryptionOAEPSHA1AESGCM
Randomly generated AES session key is encrypted by RSA with OAEP padding. User data are encrypted using session key in GCM
mode with all-zero 16 bytes long IV (initialization vector). Finally 16 byte AES-GCM tag is appended to ciphertext.
256bit AES key is used if RSA key is 4096bit or bigger, otherwise 128bit AES key is used. Raw public key data is used
as authentication data for AES-GCM encryption.
@constant kSecKeyAlgorithmRSAEncryptionOAEPSHA224AESGCM
Randomly generated AES session key is encrypted by RSA with OAEP padding. User data are encrypted using session key in GCM
mode with all-zero 16 bytes long IV (initialization vector). Finally 16 byte AES-GCM tag is appended to ciphertext.
256bit AES key is used if RSA key is 4096bit or bigger, otherwise 128bit AES key is used. Raw public key data is used
as authentication data for AES-GCM encryption.
@constant kSecKeyAlgorithmRSAEncryptionOAEPSHA256AESGCM
Randomly generated AES session key is encrypted by RSA with OAEP padding. User data are encrypted using session key in GCM
mode with all-zero 16 bytes long IV (initialization vector). Finally 16 byte AES-GCM tag is appended to ciphertext.
256bit AES key is used if RSA key is 4096bit or bigger, otherwise 128bit AES key is used. Raw public key data is used
as authentication data for AES-GCM encryption.
@constant kSecKeyAlgorithmRSAEncryptionOAEPSHA384AESGCM
Randomly generated AES session key is encrypted by RSA with OAEP padding. User data are encrypted using session key in GCM
mode with all-zero 16 bytes long IV (initialization vector). Finally 16 byte AES-GCM tag is appended to ciphertext.
256bit AES key is used if RSA key is 4096bit or bigger, otherwise 128bit AES key is used. Raw public key data is used
as authentication data for AES-GCM encryption.
@constant kSecKeyAlgorithmRSAEncryptionOAEPSHA512AESGCM
Randomly generated AES session key is encrypted by RSA with OAEP padding. User data are encrypted using session key in GCM
mode with all-zero 16 bytes long IV (initialization vector). Finally 16 byte AES-GCM tag is appended to ciphertext.
256bit AES key is used if RSA key is 4096bit or bigger, otherwise 128bit AES key is used. Raw public key data is used
as authentication data for AES-GCM encryption.
@constant kSecKeyAlgorithmECIESEncryptionStandardX963SHA1AESGCM
Legacy ECIES encryption or decryption, use kSecKeyAlgorithmECIESEncryptionStandardVariableIVX963SHA256AESGCM in new code.
Encryption is done using AES-GCM with key negotiated by kSecKeyAlgorithmECDHKeyExchangeStandardX963SHA1. AES Key size
is 128bit for EC keys <=256bit and 256bit for bigger EC keys. Ephemeral public key data is used as sharedInfo for KDF.
AES-GCM uses 16 bytes long TAG and all-zero 16 byte long IV (initialization vector).
@constant kSecKeyAlgorithmECIESEncryptionStandardX963SHA224AESGCM
Legacy ECIES encryption or decryption, use kSecKeyAlgorithmECIESEncryptionStandardVariableIVX963SHA224AESGCM in new code.
Encryption is done using AES-GCM with key negotiated by kSecKeyAlgorithmECDHKeyExchangeStandardX963SHA224. AES Key size
is 128bit for EC keys <=256bit and 256bit for bigger EC keys. Ephemeral public key data is used as sharedInfo for KDF.
AES-GCM uses 16 bytes long TAG and all-zero 16 byte long IV (initialization vector).
@constant kSecKeyAlgorithmECIESEncryptionStandardX963SHA256AESGCM
Legacy ECIES encryption or decryption, use kSecKeyAlgorithmECIESEncryptionStandardVariableIVX963SHA256AESGCM in new code.
Encryption is done using AES-GCM with key negotiated by kSecKeyAlgorithmECDHKeyExchangeStandardX963SHA256. AES Key size
is 128bit for EC keys <=256bit and 256bit for bigger EC keys. Ephemeral public key data is used as sharedInfo for KDF.
AES-GCM uses 16 bytes long TAG and all-zero 16 byte long IV (initialization vector).
@constant kSecKeyAlgorithmECIESEncryptionStandardX963SHA384AESGCM
Legacy ECIES encryption or decryption, use kSecKeyAlgorithmECIESEncryptionStandardVariableIVX963SHA384AESGCM in new code.
Encryption is done using AES-GCM with key negotiated by kSecKeyAlgorithmECDHKeyExchangeStandardX963SHA384. AES Key size
is 128bit for EC keys <=256bit and 256bit for bigger EC keys. Ephemeral public key data is used as sharedInfo for KDF.
AES-GCM uses 16 bytes long TAG and all-zero 16 byte long IV (initialization vector).
@constant kSecKeyAlgorithmECIESEncryptionStandardX963SHA512AESGCM
Legacy ECIES encryption or decryption, use kSecKeyAlgorithmECIESEncryptionStandardVariableIVX963SHA512AESGCM in new code.
Encryption is done using AES-GCM with key negotiated by kSecKeyAlgorithmECDHKeyExchangeStandardX963SHA512. AES Key size
is 128bit for EC keys <=256bit and 256bit for bigger EC keys. Ephemeral public key data is used as sharedInfo for KDF.
AES-GCM uses 16 bytes long TAG and all-zero 16 byte long IV (initialization vector).
@constant kSecKeyAlgorithmECIESEncryptionCofactorX963SHA1AESGCM
Legacy ECIES encryption or decryption, use kSecKeyAlgorithmECIESEncryptionCofactorVariableIVX963SHA256AESGCM in new code.
Encryption is done using AES-GCM with key negotiated by kSecKeyAlgorithmECDHKeyExchangeCofactorX963SHA1. AES Key size
is 128bit for EC keys <=256bit and 256bit for bigger EC keys. Ephemeral public key data is used as sharedInfo for KDF.
AES-GCM uses 16 bytes long TAG and all-zero 16 byte long IV (initialization vector).
@constant kSecKeyAlgorithmECIESEncryptionCofactorX963SHA224AESGCM
Legacy ECIES encryption or decryption, use kSecKeyAlgorithmECIESEncryptionCofactorVariableIVX963SHA224AESGCM in new code.
Encryption is done using AES-GCM with key negotiated by kSecKeyAlgorithmECDHKeyExchangeCofactorX963SHA224. AES Key size
is 128bit for EC keys <=256bit and 256bit for bigger EC keys. Ephemeral public key data is used as sharedInfo for KDF.
AES-GCM uses 16 bytes long TAG and all-zero 16 byte long IV (initialization vector).
@constant kSecKeyAlgorithmECIESEncryptionCofactorX963SHA256AESGCM
Legacy ECIES encryption or decryption, use kSecKeyAlgorithmECIESEncryptionCofactorVariableIVX963SHA256AESGCM in new code.
Encryption is done using AES-GCM with key negotiated by kSecKeyAlgorithmECDHKeyExchangeCofactorX963SHA256. AES Key size
is 128bit for EC keys <=256bit and 256bit for bigger EC keys. Ephemeral public key data is used as sharedInfo for KDF.
AES-GCM uses 16 bytes long TAG and all-zero 16 byte long IV (initialization vector).
@constant kSecKeyAlgorithmECIESEncryptionCofactorX963SHA384AESGCM
Legacy ECIES encryption or decryption, use kSecKeyAlgorithmECIESEncryptionCofactorVariableIVX963SHA384AESGCM in new code.
Encryption is done using AES-GCM with key negotiated by kSecKeyAlgorithmECDHKeyExchangeCofactorX963SHA384. AES Key size
is 128bit for EC keys <=256bit and 256bit for bigger EC keys. Ephemeral public key data is used as sharedInfo for KDF.
AES-GCM uses 16 bytes long TAG and all-zero 16 byte long IV (initialization vector).
@constant kSecKeyAlgorithmECIESEncryptionCofactorX963SHA512AESGCM
Legacy ECIES encryption or decryption, use kSecKeyAlgorithmECIESEncryptionCofactorVariableIVX963SHA512AESGCM in new code.
Encryption is done using AES-GCM with key negotiated by kSecKeyAlgorithmECDHKeyExchangeCofactorX963SHA512. AES Key size
is 128bit for EC keys <=256bit and 256bit for bigger EC keys. Ephemeral public key data is used as sharedInfo for KDF.
AES-GCM uses 16 bytes long TAG and all-zero 16 byte long IV (initialization vector).
@constant kSecKeyAlgorithmECIESEncryptionStandardVariableIVX963SHA224AESGCM
ECIES encryption or decryption. This algorithm does not limit the size of the message to be encrypted or decrypted.
Encryption is done using AES-GCM with key negotiated by kSecKeyAlgorithmECDHKeyExchangeStandardX963SHA224. AES Key size
is 128bit for EC keys <=256bit and 256bit for bigger EC keys. Ephemeral public key data is used as sharedInfo for KDF.
AES-GCM uses 16 bytes long TAG, AES key is first half of KDF output and 16 byte long IV (initialization vector) is second half
of KDF output.
@constant kSecKeyAlgorithmECIESEncryptionStandardVariableIVX963SHA256AESGCM
ECIES encryption or decryption. This algorithm does not limit the size of the message to be encrypted or decrypted.
Encryption is done using AES-GCM with key negotiated by kSecKeyAlgorithmECDHKeyExchangeStandardX963SHA256. AES Key size
is 128bit for EC keys <=256bit and 256bit for bigger EC keys. Ephemeral public key data is used as sharedInfo for KDF.
AES-GCM uses 16 bytes long TAG, AES key is first half of KDF output and 16 byte long IV (initialization vector) is second half
of KDF output.
@constant kSecKeyAlgorithmECIESEncryptionStandardVariableIVX963SHA384AESGCM
ECIES encryption or decryption. This algorithm does not limit the size of the message to be encrypted or decrypted.
Encryption is done using AES-GCM with key negotiated by kSecKeyAlgorithmECDHKeyExchangeStandardX963SHA384. AES Key size
is 128bit for EC keys <=256bit and 256bit for bigger EC keys. Ephemeral public key data is used as sharedInfo for KDF.
AES-GCM uses 16 bytes long TAG, AES key is first half of KDF output and 16 byte long IV (initialization vector) is second half
of KDF output.
@constant kSecKeyAlgorithmECIESEncryptionStandardVariableIVX963SHA512AESGCM
ECIES encryption or decryption. This algorithm does not limit the size of the message to be encrypted or decrypted.
Encryption is done using AES-GCM with key negotiated by kSecKeyAlgorithmECDHKeyExchangeStandardX963SHA512. AES Key size
is 128bit for EC keys <=256bit and 256bit for bigger EC keys. Ephemeral public key data is used as sharedInfo for KDF.
AES-GCM uses 16 bytes long TAG, AES key is first half of KDF output and 16 byte long IV (initialization vector) is second half
of KDF output.
@constant kSecKeyAlgorithmECIESEncryptionCofactorVariableIVX963SHA224AESGCM
ECIES encryption or decryption. This algorithm does not limit the size of the message to be encrypted or decrypted.
Encryption is done using AES-GCM with key negotiated by kSecKeyAlgorithmECDHKeyExchangeCofactorX963SHA224. AES Key size
is 128bit for EC keys <=256bit and 256bit for bigger EC keys. Ephemeral public key data is used as sharedInfo for KDF.
AES-GCM uses 16 bytes long TAG, AES key is first half of KDF output and 16 byte long IV (initialization vector) is second half
of KDF output.
@constant kSecKeyAlgorithmECIESEncryptionCofactorVariableIVX963SHA256AESGCM
ECIES encryption or decryption. This algorithm does not limit the size of the message to be encrypted or decrypted.
Encryption is done using AES-GCM with key negotiated by kSecKeyAlgorithmECDHKeyExchangeCofactorX963SHA256. AES Key size
is 128bit for EC keys <=256bit and 256bit for bigger EC keys. Ephemeral public key data is used as sharedInfo for KDF.
AES-GCM uses 16 bytes long TAG, AES key is first half of KDF output and 16 byte long IV (initialization vector) is second half
of KDF output.
@constant kSecKeyAlgorithmECIESEncryptionCofactorVariableIVX963SHA384AESGCM
ECIES encryption or decryption. This algorithm does not limit the size of the message to be encrypted or decrypted.
Encryption is done using AES-GCM with key negotiated by kSecKeyAlgorithmECDHKeyExchangeCofactorX963SHA384. AES Key size
is 128bit for EC keys <=256bit and 256bit for bigger EC keys. Ephemeral public key data is used as sharedInfo for KDF.
AES-GCM uses 16 bytes long TAG, AES key is first half of KDF output and 16 byte long IV (initialization vector) is second half
of KDF output.
@constant kSecKeyAlgorithmECIESEncryptionCofactorVariableIVX963SHA512AESGCM
ECIES encryption or decryption. This algorithm does not limit the size of the message to be encrypted or decrypted.
Encryption is done using AES-GCM with key negotiated by kSecKeyAlgorithmECDHKeyExchangeCofactorX963SHA512. AES Key size
is 128bit for EC keys <=256bit and 256bit for bigger EC keys. Ephemeral public key data is used as sharedInfo for KDF.
AES-GCM uses 16 bytes long TAG, AES key is first half of KDF output and 16 byte long IV (initialization vector) is second half
of KDF output.
@constant kSecKeyAlgorithmECDHKeyExchangeCofactor
Compute shared secret using ECDH cofactor algorithm, suitable only for kSecAttrKeyTypeECSECPrimeRandom keys.
This algorithm does not accept any parameters, length of output raw shared secret is given by the length of the key.
@constant kSecKeyAlgorithmECDHKeyExchangeCofactorX963SHA1
Compute shared secret using ECDH cofactor algorithm, suitable only for kSecAttrKeyTypeECSECPrimeRandom keys
and apply ANSI X9.63 KDF with SHA1 as hashing function. Requires kSecKeyKeyExchangeParameterRequestedSize and allows
kSecKeyKeyExchangeParameterSharedInfo parameters to be used.
@constant kSecKeyAlgorithmECDHKeyExchangeCofactorX963SHA224
Compute shared secret using ECDH cofactor algorithm, suitable only for kSecAttrKeyTypeECSECPrimeRandom keys
and apply ANSI X9.63 KDF with SHA224 as hashing function. Requires kSecKeyKeyExchangeParameterRequestedSize and allows
kSecKeyKeyExchangeParameterSharedInfo parameters to be used.
@constant kSecKeyAlgorithmECDHKeyExchangeCofactorX963SHA256
Compute shared secret using ECDH cofactor algorithm, suitable only for kSecAttrKeyTypeECSECPrimeRandom keys
and apply ANSI X9.63 KDF with SHA256 as hashing function. Requires kSecKeyKeyExchangeParameterRequestedSize and allows
kSecKeyKeyExchangeParameterSharedInfo parameters to be used.
@constant kSecKeyAlgorithmECDHKeyExchangeCofactorX963SHA384
Compute shared secret using ECDH cofactor algorithm, suitable only for kSecAttrKeyTypeECSECPrimeRandom keys
and apply ANSI X9.63 KDF with SHA384 as hashing function. Requires kSecKeyKeyExchangeParameterRequestedSize and allows
kSecKeyKeyExchangeParameterSharedInfo parameters to be used.
@constant kSecKeyAlgorithmECDHKeyExchangeCofactorX963SHA512
Compute shared secret using ECDH cofactor algorithm, suitable only for kSecAttrKeyTypeECSECPrimeRandom keys
and apply ANSI X9.63 KDF with SHA512 as hashing function. Requires kSecKeyKeyExchangeParameterRequestedSize and allows
kSecKeyKeyExchangeParameterSharedInfo parameters to be used.
@constant kSecKeyAlgorithmECDHKeyExchangeStandard
Compute shared secret using ECDH algorithm without cofactor, suitable only for kSecAttrKeyTypeECSECPrimeRandom keys.
This algorithm does not accept any parameters, length of output raw shared secret is given by the length of the key.
@constant kSecKeyAlgorithmECDHKeyExchangeStandardX963SHA1
Compute shared secret using ECDH algorithm without cofactor, suitable only for kSecAttrKeyTypeECSECPrimeRandom keys
and apply ANSI X9.63 KDF with SHA1 as hashing function. Requires kSecKeyKeyExchangeParameterRequestedSize and allows
kSecKeyKeyExchangeParameterSharedInfo parameters to be used.
@constant kSecKeyAlgorithmECDHKeyExchangeStandardX963SHA224
Compute shared secret using ECDH algorithm without cofactor, suitable only for kSecAttrKeyTypeECSECPrimeRandom keys
and apply ANSI X9.63 KDF with SHA224 as hashing function. Requires kSecKeyKeyExchangeParameterRequestedSize and allows
kSecKeyKeyExchangeParameterSharedInfo parameters to be used.
@constant kSecKeyAlgorithmECDHKeyExchangeStandardX963SHA256
Compute shared secret using ECDH algorithm without cofactor, suitable only for kSecAttrKeyTypeECSECPrimeRandom keys
and apply ANSI X9.63 KDF with SHA256 as hashing function. Requires kSecKeyKeyExchangeParameterRequestedSize and allows
kSecKeyKeyExchangeParameterSharedInfo parameters to be used.
@constant kSecKeyAlgorithmECDHKeyExchangeStandardX963SHA384
Compute shared secret using ECDH algorithm without cofactor, suitable only for kSecAttrKeyTypeECSECPrimeRandom keys
and apply ANSI X9.63 KDF with SHA384 as hashing function. Requires kSecKeyKeyExchangeParameterRequestedSize and allows
kSecKeyKeyExchangeParameterSharedInfo parameters to be used.
@constant kSecKeyAlgorithmECDHKeyExchangeStandardX963SHA512
Compute shared secret using ECDH algorithm without cofactor, suitable only for kSecAttrKeyTypeECSECPrimeRandom keys
and apply ANSI X9.63 KDF with SHA512 as hashing function. Requires kSecKeyKeyExchangeParameterRequestedSize and allows
kSecKeyKeyExchangeParameterSharedInfo parameters to be used.
*/
typedef CFStringRef SecKeyAlgorithm CF_STRING_ENUM
__OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
extern const SecKeyAlgorithm kSecKeyAlgorithmRSASignatureRaw
__OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
extern const SecKeyAlgorithm kSecKeyAlgorithmRSASignatureDigestPKCS1v15Raw
__OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
extern const SecKeyAlgorithm kSecKeyAlgorithmRSASignatureDigestPKCS1v15SHA1
__OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
extern const SecKeyAlgorithm kSecKeyAlgorithmRSASignatureDigestPKCS1v15SHA224
__OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
extern const SecKeyAlgorithm kSecKeyAlgorithmRSASignatureDigestPKCS1v15SHA256
__OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
extern const SecKeyAlgorithm kSecKeyAlgorithmRSASignatureDigestPKCS1v15SHA384
__OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
extern const SecKeyAlgorithm kSecKeyAlgorithmRSASignatureDigestPKCS1v15SHA512
__OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
extern const SecKeyAlgorithm kSecKeyAlgorithmRSASignatureMessagePKCS1v15SHA1
__OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
extern const SecKeyAlgorithm kSecKeyAlgorithmRSASignatureMessagePKCS1v15SHA224
__OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
extern const SecKeyAlgorithm kSecKeyAlgorithmRSASignatureMessagePKCS1v15SHA256
__OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
extern const SecKeyAlgorithm kSecKeyAlgorithmRSASignatureMessagePKCS1v15SHA384
__OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
extern const SecKeyAlgorithm kSecKeyAlgorithmRSASignatureMessagePKCS1v15SHA512
__OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
extern const SecKeyAlgorithm kSecKeyAlgorithmRSASignatureDigestPSSSHA1
__OSX_AVAILABLE(10.13) __IOS_AVAILABLE(11.0) __TVOS_AVAILABLE(11.0) __WATCHOS_AVAILABLE(4.0);
extern const SecKeyAlgorithm kSecKeyAlgorithmRSASignatureDigestPSSSHA224
__OSX_AVAILABLE(10.13) __IOS_AVAILABLE(11.0) __TVOS_AVAILABLE(11.0) __WATCHOS_AVAILABLE(4.0);
extern const SecKeyAlgorithm kSecKeyAlgorithmRSASignatureDigestPSSSHA256
__OSX_AVAILABLE(10.13) __IOS_AVAILABLE(11.0) __TVOS_AVAILABLE(11.0) __WATCHOS_AVAILABLE(4.0);
extern const SecKeyAlgorithm kSecKeyAlgorithmRSASignatureDigestPSSSHA384
__OSX_AVAILABLE(10.13) __IOS_AVAILABLE(11.0) __TVOS_AVAILABLE(11.0) __WATCHOS_AVAILABLE(4.0);
extern const SecKeyAlgorithm kSecKeyAlgorithmRSASignatureDigestPSSSHA512
__OSX_AVAILABLE(10.13) __IOS_AVAILABLE(11.0) __TVOS_AVAILABLE(11.0) __WATCHOS_AVAILABLE(4.0);
extern const SecKeyAlgorithm kSecKeyAlgorithmRSASignatureMessagePSSSHA1
__OSX_AVAILABLE(10.13) __IOS_AVAILABLE(11.0) __TVOS_AVAILABLE(11.0) __WATCHOS_AVAILABLE(4.0);
extern const SecKeyAlgorithm kSecKeyAlgorithmRSASignatureMessagePSSSHA224
__OSX_AVAILABLE(10.13) __IOS_AVAILABLE(11.0) __TVOS_AVAILABLE(11.0) __WATCHOS_AVAILABLE(4.0);
extern const SecKeyAlgorithm kSecKeyAlgorithmRSASignatureMessagePSSSHA256
__OSX_AVAILABLE(10.13) __IOS_AVAILABLE(11.0) __TVOS_AVAILABLE(11.0) __WATCHOS_AVAILABLE(4.0);
extern const SecKeyAlgorithm kSecKeyAlgorithmRSASignatureMessagePSSSHA384
__OSX_AVAILABLE(10.13) __IOS_AVAILABLE(11.0) __TVOS_AVAILABLE(11.0) __WATCHOS_AVAILABLE(4.0);
extern const SecKeyAlgorithm kSecKeyAlgorithmRSASignatureMessagePSSSHA512
__OSX_AVAILABLE(10.13) __IOS_AVAILABLE(11.0) __TVOS_AVAILABLE(11.0) __WATCHOS_AVAILABLE(4.0);
extern const SecKeyAlgorithm kSecKeyAlgorithmECDSASignatureRFC4754
__OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
extern const SecKeyAlgorithm kSecKeyAlgorithmECDSASignatureDigestX962
__OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
extern const SecKeyAlgorithm kSecKeyAlgorithmECDSASignatureDigestX962SHA1
__OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
extern const SecKeyAlgorithm kSecKeyAlgorithmECDSASignatureDigestX962SHA224
__OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
extern const SecKeyAlgorithm kSecKeyAlgorithmECDSASignatureDigestX962SHA256
__OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
extern const SecKeyAlgorithm kSecKeyAlgorithmECDSASignatureDigestX962SHA384
__OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
extern const SecKeyAlgorithm kSecKeyAlgorithmECDSASignatureDigestX962SHA512
__OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
extern const SecKeyAlgorithm kSecKeyAlgorithmECDSASignatureMessageX962SHA1
__OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
extern const SecKeyAlgorithm kSecKeyAlgorithmECDSASignatureMessageX962SHA224
__OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
extern const SecKeyAlgorithm kSecKeyAlgorithmECDSASignatureMessageX962SHA256
__OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
extern const SecKeyAlgorithm kSecKeyAlgorithmECDSASignatureMessageX962SHA384
__OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
extern const SecKeyAlgorithm kSecKeyAlgorithmECDSASignatureMessageX962SHA512
__OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
extern const SecKeyAlgorithm kSecKeyAlgorithmRSAEncryptionRaw
__OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
extern const SecKeyAlgorithm kSecKeyAlgorithmRSAEncryptionPKCS1
__OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
extern const SecKeyAlgorithm kSecKeyAlgorithmRSAEncryptionOAEPSHA1
__OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
extern const SecKeyAlgorithm kSecKeyAlgorithmRSAEncryptionOAEPSHA224
__OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
extern const SecKeyAlgorithm kSecKeyAlgorithmRSAEncryptionOAEPSHA256
__OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
extern const SecKeyAlgorithm kSecKeyAlgorithmRSAEncryptionOAEPSHA384
__OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
extern const SecKeyAlgorithm kSecKeyAlgorithmRSAEncryptionOAEPSHA512
__OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
extern const SecKeyAlgorithm kSecKeyAlgorithmRSAEncryptionOAEPSHA1AESGCM
__OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
extern const SecKeyAlgorithm kSecKeyAlgorithmRSAEncryptionOAEPSHA224AESGCM
__OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
extern const SecKeyAlgorithm kSecKeyAlgorithmRSAEncryptionOAEPSHA256AESGCM
__OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
extern const SecKeyAlgorithm kSecKeyAlgorithmRSAEncryptionOAEPSHA384AESGCM
__OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
extern const SecKeyAlgorithm kSecKeyAlgorithmRSAEncryptionOAEPSHA512AESGCM
__OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
extern const SecKeyAlgorithm kSecKeyAlgorithmECIESEncryptionStandardX963SHA1AESGCM
__OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
extern const SecKeyAlgorithm kSecKeyAlgorithmECIESEncryptionStandardX963SHA224AESGCM
__OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
extern const SecKeyAlgorithm kSecKeyAlgorithmECIESEncryptionStandardX963SHA256AESGCM
__OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
extern const SecKeyAlgorithm kSecKeyAlgorithmECIESEncryptionStandardX963SHA384AESGCM
__OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
extern const SecKeyAlgorithm kSecKeyAlgorithmECIESEncryptionStandardX963SHA512AESGCM
__OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
extern const SecKeyAlgorithm kSecKeyAlgorithmECIESEncryptionCofactorX963SHA1AESGCM
__OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
extern const SecKeyAlgorithm kSecKeyAlgorithmECIESEncryptionCofactorX963SHA224AESGCM
__OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
extern const SecKeyAlgorithm kSecKeyAlgorithmECIESEncryptionCofactorX963SHA256AESGCM
__OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
extern const SecKeyAlgorithm kSecKeyAlgorithmECIESEncryptionCofactorX963SHA384AESGCM
__OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
extern const SecKeyAlgorithm kSecKeyAlgorithmECIESEncryptionCofactorX963SHA512AESGCM
__OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
extern const SecKeyAlgorithm kSecKeyAlgorithmECIESEncryptionStandardVariableIVX963SHA224AESGCM
__OSX_AVAILABLE(10.13) __IOS_AVAILABLE(11.0) __TVOS_AVAILABLE(11.0) __WATCHOS_AVAILABLE(4.0);
extern const SecKeyAlgorithm kSecKeyAlgorithmECIESEncryptionStandardVariableIVX963SHA256AESGCM
__OSX_AVAILABLE(10.13) __IOS_AVAILABLE(11.0) __TVOS_AVAILABLE(11.0) __WATCHOS_AVAILABLE(4.0);
extern const SecKeyAlgorithm kSecKeyAlgorithmECIESEncryptionStandardVariableIVX963SHA384AESGCM
__OSX_AVAILABLE(10.13) __IOS_AVAILABLE(11.0) __TVOS_AVAILABLE(11.0) __WATCHOS_AVAILABLE(4.0);
extern const SecKeyAlgorithm kSecKeyAlgorithmECIESEncryptionStandardVariableIVX963SHA512AESGCM
__OSX_AVAILABLE(10.13) __IOS_AVAILABLE(11.0) __TVOS_AVAILABLE(11.0) __WATCHOS_AVAILABLE(4.0);
extern const SecKeyAlgorithm kSecKeyAlgorithmECIESEncryptionCofactorVariableIVX963SHA224AESGCM
__OSX_AVAILABLE(10.13) __IOS_AVAILABLE(11.0) __TVOS_AVAILABLE(11.0) __WATCHOS_AVAILABLE(4.0);
extern const SecKeyAlgorithm kSecKeyAlgorithmECIESEncryptionCofactorVariableIVX963SHA256AESGCM
__OSX_AVAILABLE(10.13) __IOS_AVAILABLE(11.0) __TVOS_AVAILABLE(11.0) __WATCHOS_AVAILABLE(4.0);
extern const SecKeyAlgorithm kSecKeyAlgorithmECIESEncryptionCofactorVariableIVX963SHA384AESGCM
__OSX_AVAILABLE(10.13) __IOS_AVAILABLE(11.0) __TVOS_AVAILABLE(11.0) __WATCHOS_AVAILABLE(4.0);
extern const SecKeyAlgorithm kSecKeyAlgorithmECIESEncryptionCofactorVariableIVX963SHA512AESGCM
__OSX_AVAILABLE(10.13) __IOS_AVAILABLE(11.0) __TVOS_AVAILABLE(11.0) __WATCHOS_AVAILABLE(4.0);
extern const SecKeyAlgorithm kSecKeyAlgorithmECDHKeyExchangeStandard
__OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
extern const SecKeyAlgorithm kSecKeyAlgorithmECDHKeyExchangeStandardX963SHA1
__OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
extern const SecKeyAlgorithm kSecKeyAlgorithmECDHKeyExchangeStandardX963SHA224
__OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
extern const SecKeyAlgorithm kSecKeyAlgorithmECDHKeyExchangeStandardX963SHA256
__OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
extern const SecKeyAlgorithm kSecKeyAlgorithmECDHKeyExchangeStandardX963SHA384
__OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
extern const SecKeyAlgorithm kSecKeyAlgorithmECDHKeyExchangeStandardX963SHA512
__OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
extern const SecKeyAlgorithm kSecKeyAlgorithmECDHKeyExchangeCofactor
__OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
extern const SecKeyAlgorithm kSecKeyAlgorithmECDHKeyExchangeCofactorX963SHA1
__OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
extern const SecKeyAlgorithm kSecKeyAlgorithmECDHKeyExchangeCofactorX963SHA224
__OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
extern const SecKeyAlgorithm kSecKeyAlgorithmECDHKeyExchangeCofactorX963SHA256
__OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
extern const SecKeyAlgorithm kSecKeyAlgorithmECDHKeyExchangeCofactorX963SHA384
__OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
extern const SecKeyAlgorithm kSecKeyAlgorithmECDHKeyExchangeCofactorX963SHA512
__OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
/*!
@function SecKeyCreateSignature
@abstract Given a private key and data to sign, generate a digital signature.
@param key Private key with which to sign.
@param algorithm One of SecKeyAlgorithm constants suitable to generate signature with this key.
@param dataToSign The data to be signed, typically the digest of the actual data.
@param error On error, will be populated with an error object describing the failure.
See "Security Error Codes" (SecBase.h).
@result The signature over dataToSign represented as a CFData, or NULL on failure.
@discussion Computes digital signature using specified key over input data. The operation algorithm
further defines the exact format of input data, operation to be performed and output signature.
*/
CFDataRef _Nullable SecKeyCreateSignature(SecKeyRef key, SecKeyAlgorithm algorithm, CFDataRef dataToSign, CFErrorRef *error)
__OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
/*!
@function SecKeyVerifySignature
@abstract Given a public key, data which has been signed, and a signature, verify the signature.
@param key Public key with which to verify the signature.
@param algorithm One of SecKeyAlgorithm constants suitable to verify signature with this key.
@param signedData The data over which sig is being verified, typically the digest of the actual data.
@param signature The signature to verify.
@param error On error, will be populated with an error object describing the failure.
See "Security Error Codes" (SecBase.h).
@result True if the signature was valid, False otherwise.
@discussion Verifies digital signature operation using specified key and signed data. The operation algorithm
further defines the exact format of input data, signature and operation to be performed.
*/
Boolean SecKeyVerifySignature(SecKeyRef key, SecKeyAlgorithm algorithm, CFDataRef signedData, CFDataRef signature, CFErrorRef *error)
__OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
/*!
@function SecKeyCreateEncryptedData
@abstract Encrypt a block of plaintext.
@param key Public key with which to encrypt the data.
@param algorithm One of SecKeyAlgorithm constants suitable to perform encryption with this key.
@param plaintext The data to encrypt. The length and format of the data must conform to chosen algorithm,
typically be less or equal to the value returned by SecKeyGetBlockSize().
@param error On error, will be populated with an error object describing the failure.
See "Security Error Codes" (SecBase.h).
@result The ciphertext represented as a CFData, or NULL on failure.
@discussion Encrypts plaintext data using specified key. The exact type of the operation including the format
of input and output data is specified by encryption algorithm.
*/
CFDataRef _Nullable SecKeyCreateEncryptedData(SecKeyRef key, SecKeyAlgorithm algorithm, CFDataRef plaintext,
CFErrorRef *error)
__OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
/*!
@function SecKeyCreateDecryptedData
@abstract Decrypt a block of ciphertext.
@param key Private key with which to decrypt the data.
@param algorithm One of SecKeyAlgorithm constants suitable to perform decryption with this key.
@param ciphertext The data to decrypt. The length and format of the data must conform to chosen algorithm,
typically be less or equal to the value returned by SecKeyGetBlockSize().
@param error On error, will be populated with an error object describing the failure.
See "Security Error Codes" (SecBase.h).
@result The plaintext represented as a CFData, or NULL on failure.
@discussion Decrypts ciphertext data using specified key. The exact type of the operation including the format
of input and output data is specified by decryption algorithm.
*/
CFDataRef _Nullable SecKeyCreateDecryptedData(SecKeyRef key, SecKeyAlgorithm algorithm, CFDataRef ciphertext,
CFErrorRef *error)
__OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
/*!
@enum SecKeyKeyExchangeParameter SecKey Key Exchange parameters
@constant kSecKeyKeyExchangeParameterRequestedSize Contains CFNumberRef with requested result size in bytes.
@constant kSecKeyKeyExchangeParameterSharedInfo Contains CFDataRef with additional shared info
for KDF (key derivation function).
*/
typedef CFStringRef SecKeyKeyExchangeParameter CF_STRING_ENUM
__OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
extern const SecKeyKeyExchangeParameter kSecKeyKeyExchangeParameterRequestedSize
__OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
extern const SecKeyKeyExchangeParameter kSecKeyKeyExchangeParameterSharedInfo
__OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
/*!
@function SecKeyCopyKeyExchangeResult
@abstract Perform Diffie-Hellman style of key exchange operation, optionally with additional key-derivation steps.
@param algorithm One of SecKeyAlgorithm constants suitable to perform this operation.
@param publicKey Remote party's public key.
@param parameters Dictionary with parameters, see SecKeyKeyExchangeParameter constants. Used algorithm
determines the set of required and optional parameters to be used.
@param error Pointer to an error object on failure.
See "Security Error Codes" (SecBase.h).
@result Result of key exchange operation as a CFDataRef, or NULL on failure.
*/
CFDataRef _Nullable SecKeyCopyKeyExchangeResult(SecKeyRef privateKey, SecKeyAlgorithm algorithm, SecKeyRef publicKey, CFDictionaryRef parameters, CFErrorRef *error)
__OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
/*!
@enum SecKeyOperationType
@abstract Defines types of cryptographic operations available with SecKey instance.
@constant kSecKeyOperationTypeSign
Represents SecKeyCreateSignature()
@constant kSecKeyOperationTypeVerify
Represents SecKeyVerifySignature()
@constant kSecKeyOperationTypeEncrypt
Represents SecKeyCreateEncryptedData()
@constant kSecKeyOperationTypeDecrypt
Represents SecKeyCreateDecryptedData()
@constant kSecKeyOperationTypeKeyExchange
Represents SecKeyCopyKeyExchangeResult()
*/
typedef CF_ENUM(CFIndex, SecKeyOperationType) {
kSecKeyOperationTypeSign = 0,
kSecKeyOperationTypeVerify = 1,
kSecKeyOperationTypeEncrypt = 2,
kSecKeyOperationTypeDecrypt = 3,
kSecKeyOperationTypeKeyExchange = 4,
} __OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
/*!
@function SecKeyIsAlgorithmSupported
@abstract Checks whether key supports specified algorithm for specified operation.
@param key Key to query
@param operation Operation type for which the key is queried
@param algorithm Algorithm which is queried
@return True if key supports specified algorithm for specified operation, False otherwise.
*/
Boolean SecKeyIsAlgorithmSupported(SecKeyRef key, SecKeyOperationType operation, SecKeyAlgorithm algorithm)
__OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
CF_IMPLICIT_BRIDGING_DISABLED
CF_ASSUME_NONNULL_END
__END_DECLS
#endif /* !_SECURITY_SECKEY_H_ */
| 58.917896 | 490 | 0.789468 | [
"object",
"vector"
] |
a905990393f5fb2b23d618131df505d1e9cd592f | 2,984 | h | C | chainerx_cc/chainerx/routines/manipulation.h | mr4msm/chainer | 7942e1cd425b29868ff872a5b9031f90a9bcda53 | [
"MIT"
] | 2 | 2018-10-09T15:37:43.000Z | 2019-04-28T02:45:22.000Z | chainerx_cc/chainerx/routines/manipulation.h | mr4msm/chainer | 7942e1cd425b29868ff872a5b9031f90a9bcda53 | [
"MIT"
] | 1 | 2019-10-17T09:56:18.000Z | 2019-10-17T09:56:18.000Z | chainerx_cc/chainerx/routines/manipulation.h | mr4msm/chainer | 7942e1cd425b29868ff872a5b9031f90a9bcda53 | [
"MIT"
] | null | null | null | #pragma once
#include <cstdint>
#include <vector>
#include <absl/types/optional.h>
#include "chainerx/array.h"
#include "chainerx/axes.h"
#include "chainerx/shape.h"
namespace chainerx {
// Retrieves a scalar from a single-element array.
//
// If the array is not single-element, DimensionError is thrown.
Scalar AsScalar(const Array& a);
Array Ravel(const Array& a);
// Returns a view where the specified axis is moved to start.
Array RollAxis(const Array& a, int8_t axis, int8_t start = 0);
// Returns a transposed view of the array.
Array Transpose(const Array& a, const OptionalAxes& axes = absl::nullopt);
// Returns a reshaped array.
Array Reshape(const Array& a, const Shape& newshape);
// Returns a squeezed array with unit-length axes removed.
//
// If no axes are specified, all axes of unit-lengths are removed.
// If no axes can be removed, an array with aliased data is returned.
Array Squeeze(const Array& a, const OptionalAxes& axis = absl::nullopt);
// Broadcasts the array to the specified shape.
// Returned array is always a view to this array.
Array BroadcastTo(const Array& array, const Shape& shape);
// Returns a concatenated array.
Array Concatenate(const std::vector<Array>& arrays);
Array Concatenate(const std::vector<Array>& arrays, absl::optional<int8_t> axis);
// Returns a joined array along a new axis.
Array Stack(const std::vector<Array>& arrays, int8_t axis = 0);
// Returns a set of arrays resulting from splitting the given array into sections along the specified axis.
// If the dimension is not equally divisible, DimensionError is throws.
std::vector<Array> Split(const Array& ary, int64_t sections, int8_t axis = 0);
// Returns a set of arrays resulting from splitting the given array at the indices along the specified axis.
std::vector<Array> Split(const Array& ary, std::vector<int64_t> indices, int8_t axis = 0);
std::vector<Array> DSplit(const Array& ary, int64_t sections);
std::vector<Array> DSplit(const Array& ary, std::vector<int64_t> indices);
std::vector<Array> VSplit(const Array& ary, int64_t sections);
std::vector<Array> VSplit(const Array& ary, std::vector<int64_t> indices);
Array Swapaxes(const Array& a, int8_t axis1, int8_t axis2);
Array Repeat(const Array& a, int64_t repeats, absl::optional<int8_t> axis);
Array Repeat(const Array& a, const std::vector<int64_t>& repeats, absl::optional<int8_t> axis);
Array ExpandDims(const Array& a, int8_t axis);
Array Flip(const Array& m, const OptionalAxes& axes = absl::nullopt);
Array Fliplr(const Array& m);
Array Flipud(const Array& m);
Array AtLeast2D(const Array& x);
Array AtLeast3D(const Array& x);
// Returns a joined array along horizontal axis.
Array HStack(const std::vector<Array>& arrays);
// Returns a joined array along vertical axis.
Array VStack(const std::vector<Array>& arrays);
Array DStack(const std::vector<Array>& arrays);
Array Moveaxis(const Array& a, const Axes& source, const Axes& destination);
} // namespace chainerx
| 32.791209 | 108 | 0.746984 | [
"shape",
"vector"
] |
a906c7d24327a63120cb65a4fc526b3ffa08075a | 7,150 | h | C | other/bipartite_edge_coloring.h | minhtu1708/ACM_notebook | 3e63bd3ec2ceb6446900e3f99d730154e3d278c3 | [
"MIT"
] | null | null | null | other/bipartite_edge_coloring.h | minhtu1708/ACM_notebook | 3e63bd3ec2ceb6446900e3f99d730154e3d278c3 | [
"MIT"
] | null | null | null | other/bipartite_edge_coloring.h | minhtu1708/ACM_notebook | 3e63bd3ec2ceb6446900e3f99d730154e3d278c3 | [
"MIT"
] | 1 | 2022-02-06T05:30:06.000Z | 2022-02-06T05:30:06.000Z | // Copied from https://judge.yosupo.jp/submission/11755
// Source: Benq
//
// Tested:
// - https://codeforces.com/contest/600/problem/F
// - https://judge.yosupo.jp/problem/bipartite_edge_coloring
// - https://oj.vnoi.info/problem/nkdec
// Credit: Benq
// returns vector of {vertex, id of edge to vertex}
// the second element of the first pair is always -1
template<int N, bool directed> struct Euler {
vector<pair<int, int>> adj[N];
vector<pair<int, int>>::iterator iter[N];
bool in_vertex[N];
vector<int> nodes;
vector<bool> used;
Euler() { for (int i = 0; i < N; i++) in_vertex[i] = 0; }
vector<int> ans;
void clear() {
for (auto &t: nodes) adj[t].clear(), in_vertex[t] = 0;
nodes.clear(); used.clear(); ans.clear();
}
void add(int x) {
if (in_vertex[x]) return;
in_vertex[x] = 1;
nodes.push_back(x);
}
void add_edge(int a, int b) {
int m = used.size();
used.push_back(0);
add(a); add(b);
adj[a].emplace_back(b, m);
if (!directed) adj[b].emplace_back(a, m);
}
void go(int src) {
vector<pair<pair<int, int>,int>> ret, s = {{{src, -1}, -1}};
// {{vertex, prev vertex}, edge label}
while (s.size()) {
int x = s.back().first.first;
auto& it = iter[x], en = end(adj[x]);
while (it != en && used[it->second]) it ++;
if (it == en) { // no more edges out of vertex
if ((int)ret.size() && ret.back().first.second != x) exit(5);
ret.push_back(s.back()), s.pop_back();
} else {
s.push_back({{it->first,x},it->second});
used[it->second] = 1;
}
}
for (int i = 0; i < (int)ret.size() - 1; i++) ans.push_back(ret[i].second);
assert((int)ans.size() % 2 == 0);
}
array<vector<int>, 2> tour() {
for (auto &v: nodes) {
assert(adj[v].size() % 2 == 0);
iter[v] = begin(adj[v]);
}
for (auto &v: nodes) for (auto &e: adj[v]) if (!used[e.second]) go(v);
array<vector<int>, 2> res;
for (int i = 0; i < (int)ans.size(); i++) res[i % 2].push_back(ans[i]);
return res;
}
};
typedef array<int, 2> T;
struct EdgeColoring {
int n; vector<T> ed;
Euler<N * 2, 0> E; // at least 2 * n
array<vector<int>,2> split(vector<int> lab) { // k is even, split into two parts
E.clear();
for (auto &t: lab) E.add_edge(ed[t][0], ed[t][1]);
auto v = E.tour(); // get half edges on each
for (int i = 0; i < 2; i++) for (auto &t: v[i]) t = lab[t];
return v;
}
vector<int> match(vector<int> lab) { // find perfect matching in MlogM
assert((int)lab.size() && (int)lab.size() % n == 0);
int k = (int)lab.size() / n;
int p = 0;
while ((1 << p) < n * k) p ++;
int a = (1 << p) / k;
int b = (1 << p) - k * a;
vector<int> cnt_good((int)lab.size(),a), cnt_bad(n,b); // now each edge is adjacent to 2^t
for (; p; --p) { // divide by two!!
E.clear(); vector<int> tmp;
for (int i = 0; i < n * k; i++) {
if (cnt_good[i] & 1) E.add_edge(ed[lab[i]][0], ed[lab[i]][1]), tmp.push_back(i);
cnt_good[i] /= 2;
}
int num_lab = tmp.size();
for (int i = 0; i < n; i++) {
if (cnt_bad[i] & 1) E.add_edge(i, n + i), tmp.push_back(i);
cnt_bad[i] /= 2;
}
array<vector<int>, 2> x = E.tour();
T cnt = T();
for (int i = 0; i < 2; i++) for (auto &t: x[i]) cnt[i] += t >= num_lab;
if (cnt[0] > cnt[1]) swap(x[0], x[1]);
for (auto &t: x[0]) {
if (t < num_lab) cnt_good[tmp[t]] ++;
else cnt_bad[tmp[t]] ++;
}
}
vector<int> v;
for (int i = 0; i < (int) lab.size(); i++) if (cnt_good[i]) v.push_back(lab[i]);
assert((int)v.size() == n);
return v;
}
vector<bool> used;
vector<vector<int>> edge_color(vector<int> lab) { // regular bipartite graph!
assert((int)lab.size() % n == 0);
int k = (int)lab.size() / n;
if (k == 0) return {};
if (k == 1) return {lab};
if ( __builtin_popcount(k) == 1) {
array<vector<int>,2> p = split(lab);
vector<vector<int>> a = edge_color(p[0]), b = edge_color(p[1]);
a.insert(end(a), b.begin(), b.end());
return a;
}
if (k % 2 == 0) {
array<vector<int>, 2> p = split(lab);
auto a = edge_color(p[0]);
int cur = k/2;
while ( __builtin_popcount(cur) > 1) {
cur ++;
p[1].insert(end(p[1]),a.back().begin(), a.back().end());
a.pop_back();
}
auto b = edge_color(p[1]);
a.insert(end(a),b.begin(), b.end());
return a;
} else {
vector<int> v = match(lab);
for (auto &t: v) used[t] = 1;
vector<int> LAB;
for (auto &t: lab) if (!used[t]) LAB.push_back(t);
for (auto &t: v) used[t] = 0;
auto a = edge_color(LAB);
a.push_back(v);
return a;
}
}
// returns edge chromatic number, ans contains the edge coloring(colors are 1 indexed)
// supports multiple edges
// 0 indexed, O(M log M)
int solve(vector<T> _ed, vector<int> &ans) {
if (_ed.empty()) {
return 0;
}
T side = T();
for (auto &t: _ed) for (int i = 0; i < 2; i++) side[i] = max(side[i], t[i]+1);
vector<int> deg[2], cmp[2], sz[2];
for (int i = 0; i < 2; i++) deg[i].resize(side[i]), cmp[i].resize(side[i]);
for (auto &t: _ed) for (int i = 0; i < 2; i++) deg[i][t[i]] ++;
int k = 0;
for (int i = 0; i < 2; i++) for (auto &t: deg[i]) k = max(k, t);
for (int s = 0; s < 2; s++) {
for (int i = 0; i < side[s]; ) {
sz[s].push_back(0);
while (i < side[s] && sz[s].back() + deg[s][i] <= k) {
cmp[s][i] = (int)sz[s].size() - 1;
sz[s].back() += deg[s][i++];
}
}
}
for (int i = 0; i < 2; i++) while (sz[i].size() < sz[i ^ 1].size()) sz[i].push_back(0);
n = sz[0].size();
for (auto &t: _ed) ed.push_back({cmp[0][t[0]], n + cmp[1][t[1]]});
int ind = 0;
for (int i = 0; i < n; i++) {
while (sz[0][i] < k) {
while (sz[1][ind] == k) ind ++;
sz[0][i] ++, sz[1][ind] ++;
ed.push_back({i, n + ind});
}
}
used.resize(n * k);
vector<int> lab(n * k);
iota(lab.begin(), lab.end(),0);
auto tmp = edge_color(lab);
ans.resize(_ed.size());
for (int i = 0; i < (int) tmp.size(); i++) {
for (auto x: tmp[i]) if (x < (int) _ed.size()) ans[x] = i + 1;
}
return tmp.size();
}
};
| 37.631579 | 98 | 0.445035 | [
"vector"
] |
a90dcfe24509977fea84af7efc715f1e76d6c814 | 1,059 | h | C | src/DOMParserImp.h | esrille/escudo | 1ba68f6930f1ddb97385a5b488644b6dfa132152 | [
"Apache-2.0"
] | 29 | 2015-01-25T15:12:02.000Z | 2021-12-01T17:58:17.000Z | src/DOMParserImp.h | esrille/escudo | 1ba68f6930f1ddb97385a5b488644b6dfa132152 | [
"Apache-2.0"
] | null | null | null | src/DOMParserImp.h | esrille/escudo | 1ba68f6930f1ddb97385a5b488644b6dfa132152 | [
"Apache-2.0"
] | 7 | 2015-04-15T02:05:21.000Z | 2020-06-16T03:53:37.000Z | // Generated by esidl 0.3.0.
// This file is expected to be modified for the Web IDL interface
// implementation. Permission to use, copy, modify and distribute
// this file in any software license is hereby granted.
#ifndef ORG_W3C_DOM_BOOTSTRAP_DOMPARSERIMP_H_INCLUDED
#define ORG_W3C_DOM_BOOTSTRAP_DOMPARSERIMP_H_INCLUDED
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <org/w3c/dom/DOMParser.h>
#include <org/w3c/dom/Document.h>
#include <org/w3c/dom/DOMParser.h>
namespace org
{
namespace w3c
{
namespace dom
{
namespace bootstrap
{
class DOMParserImp : public ObjectMixin<DOMParserImp>
{
public:
// DOMParser
Document parseFromString(const std::u16string& str, const SupportedType& type);
// Object
virtual Any message_(uint32_t selector, const char* id, int argc, Any* argv)
{
return DOMParser::dispatch(this, selector, id, argc, argv);
}
static const char* const getMetaData()
{
return DOMParser::getMetaData();
}
};
}
}
}
}
#endif // ORG_W3C_DOM_BOOTSTRAP_DOMPARSERIMP_H_INCLUDED
| 22.0625 | 83 | 0.734655 | [
"object"
] |
a9123128df4cce442e94e67304fb1a8e8e8bd825 | 32,250 | h | C | src/renderer/atlas/AtlasEngine.h | by-memory/terminal | 62c95b5017e92a780cdc43008e30b4e43d2edc9b | [
"MIT"
] | 1 | 2022-01-15T11:52:28.000Z | 2022-01-15T11:52:28.000Z | src/renderer/atlas/AtlasEngine.h | by-memory/terminal | 62c95b5017e92a780cdc43008e30b4e43d2edc9b | [
"MIT"
] | null | null | null | src/renderer/atlas/AtlasEngine.h | by-memory/terminal | 62c95b5017e92a780cdc43008e30b4e43d2edc9b | [
"MIT"
] | null | null | null | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
#pragma once
#include <d2d1.h>
#include <d3d11_1.h>
#include <dwrite_3.h>
#include "../../renderer/inc/IRenderEngine.hpp"
namespace Microsoft::Console::Render
{
class AtlasEngine final : public IRenderEngine
{
public:
explicit AtlasEngine();
AtlasEngine(const AtlasEngine&) = delete;
AtlasEngine& operator=(const AtlasEngine&) = delete;
// IRenderEngine
[[nodiscard]] HRESULT StartPaint() noexcept override;
[[nodiscard]] HRESULT EndPaint() noexcept override;
[[nodiscard]] bool RequiresContinuousRedraw() noexcept override;
void WaitUntilCanRender() noexcept override;
[[nodiscard]] HRESULT Present() noexcept override;
[[nodiscard]] HRESULT PrepareForTeardown(_Out_ bool* pForcePaint) noexcept override;
[[nodiscard]] HRESULT ScrollFrame() noexcept override;
[[nodiscard]] HRESULT Invalidate(const SMALL_RECT* psrRegion) noexcept override;
[[nodiscard]] HRESULT InvalidateCursor(const SMALL_RECT* psrRegion) noexcept override;
[[nodiscard]] HRESULT InvalidateSystem(const RECT* prcDirtyClient) noexcept override;
[[nodiscard]] HRESULT InvalidateSelection(const std::vector<SMALL_RECT>& rectangles) noexcept override;
[[nodiscard]] HRESULT InvalidateScroll(const COORD* pcoordDelta) noexcept override;
[[nodiscard]] HRESULT InvalidateAll() noexcept override;
[[nodiscard]] HRESULT InvalidateCircling(_Out_ bool* pForcePaint) noexcept override;
[[nodiscard]] HRESULT InvalidateTitle(std::wstring_view proposedTitle) noexcept override;
[[nodiscard]] HRESULT PrepareRenderInfo(const RenderFrameInfo& info) noexcept override;
[[nodiscard]] HRESULT ResetLineTransform() noexcept override;
[[nodiscard]] HRESULT PrepareLineTransform(LineRendition lineRendition, size_t targetRow, size_t viewportLeft) noexcept override;
[[nodiscard]] HRESULT PaintBackground() noexcept override;
[[nodiscard]] HRESULT PaintBufferLine(gsl::span<const Cluster> clusters, COORD coord, bool fTrimLeft, bool lineWrapped) noexcept override;
[[nodiscard]] HRESULT PaintBufferGridLines(GridLineSet lines, COLORREF color, size_t cchLine, COORD coordTarget) noexcept override;
[[nodiscard]] HRESULT PaintSelection(SMALL_RECT rect) noexcept override;
[[nodiscard]] HRESULT PaintCursor(const CursorOptions& options) noexcept override;
[[nodiscard]] HRESULT UpdateDrawingBrushes(const TextAttribute& textAttributes, const RenderSettings& renderSettings, gsl::not_null<IRenderData*> pData, bool usingSoftFont, bool isSettingDefaultBrushes) noexcept override;
[[nodiscard]] HRESULT UpdateFont(const FontInfoDesired& FontInfoDesired, _Out_ FontInfo& FontInfo) noexcept override;
[[nodiscard]] HRESULT UpdateSoftFont(gsl::span<const uint16_t> bitPattern, SIZE cellSize, size_t centeringHint) noexcept override;
[[nodiscard]] HRESULT UpdateDpi(int iDpi) noexcept override;
[[nodiscard]] HRESULT UpdateViewport(SMALL_RECT srNewViewport) noexcept override;
[[nodiscard]] HRESULT GetProposedFont(const FontInfoDesired& FontInfoDesired, _Out_ FontInfo& FontInfo, int iDpi) noexcept override;
[[nodiscard]] HRESULT GetDirtyArea(gsl::span<const til::rect>& area) noexcept override;
[[nodiscard]] HRESULT GetFontSize(_Out_ COORD* pFontSize) noexcept override;
[[nodiscard]] HRESULT IsGlyphWideByFont(std::wstring_view glyph, _Out_ bool* pResult) noexcept override;
[[nodiscard]] HRESULT UpdateTitle(std::wstring_view newTitle) noexcept override;
// DxRenderer - getter
HRESULT Enable() noexcept override;
[[nodiscard]] bool GetRetroTerminalEffect() const noexcept override;
[[nodiscard]] float GetScaling() const noexcept override;
[[nodiscard]] HANDLE GetSwapChainHandle() override;
[[nodiscard]] Types::Viewport GetViewportInCharacters(const Types::Viewport& viewInPixels) const noexcept override;
[[nodiscard]] Types::Viewport GetViewportInPixels(const Types::Viewport& viewInCharacters) const noexcept override;
// DxRenderer - setter
void SetAntialiasingMode(D2D1_TEXT_ANTIALIAS_MODE antialiasingMode) noexcept override;
void SetCallback(std::function<void()> pfn) noexcept override;
void EnableTransparentBackground(const bool isTransparent) noexcept override;
void SetForceFullRepaintRendering(bool enable) noexcept override;
[[nodiscard]] HRESULT SetHwnd(HWND hwnd) noexcept override;
void SetPixelShaderPath(std::wstring_view value) noexcept override;
void SetRetroTerminalEffect(bool enable) noexcept override;
void SetSelectionBackground(COLORREF color, float alpha = 0.5f) noexcept override;
void SetSoftwareRendering(bool enable) noexcept override;
void SetWarningCallback(std::function<void(HRESULT)> pfn) noexcept override;
[[nodiscard]] HRESULT SetWindowSize(SIZE pixels) noexcept override;
void ToggleShaderEffects() noexcept override;
[[nodiscard]] HRESULT UpdateFont(const FontInfoDesired& pfiFontInfoDesired, FontInfo& fiFontInfo, const std::unordered_map<std::wstring_view, uint32_t>& features, const std::unordered_map<std::wstring_view, float>& axes) noexcept override;
void UpdateHyperlinkHoveredId(uint16_t hoveredId) noexcept override;
// Some helper classes for the implementation.
// public because I don't want to sprinkle the code with friends.
public:
#define ATLAS_POD_OPS(type) \
constexpr bool operator==(const type& rhs) const noexcept \
{ \
return __builtin_memcmp(this, &rhs, sizeof(rhs)) == 0; \
} \
\
constexpr bool operator!=(const type& rhs) const noexcept \
{ \
return __builtin_memcmp(this, &rhs, sizeof(rhs)) != 0; \
}
#define ATLAS_FLAG_OPS(type, underlying) \
friend constexpr type operator~(type v) noexcept { return static_cast<type>(~static_cast<underlying>(v)); } \
friend constexpr type operator|(type lhs, type rhs) noexcept { return static_cast<type>(static_cast<underlying>(lhs) | static_cast<underlying>(rhs)); } \
friend constexpr type operator&(type lhs, type rhs) noexcept { return static_cast<type>(static_cast<underlying>(lhs) & static_cast<underlying>(rhs)); } \
friend constexpr void operator|=(type& lhs, type rhs) noexcept { lhs = lhs | rhs; } \
friend constexpr void operator&=(type& lhs, type rhs) noexcept { lhs = lhs & rhs; }
template<typename T>
struct vec2
{
T x{};
T y{};
ATLAS_POD_OPS(vec2)
constexpr vec2 operator/(const vec2& rhs) noexcept
{
assert(rhs.x != 0 && rhs.y != 0);
return { gsl::narrow_cast<T>(x / rhs.x), gsl::narrow_cast<T>(y / rhs.y) };
}
};
template<typename T>
struct vec4
{
T x{};
T y{};
T z{};
T w{};
ATLAS_POD_OPS(vec4)
};
template<typename T>
struct rect
{
T left{};
T top{};
T right{};
T bottom{};
ATLAS_POD_OPS(rect)
constexpr bool non_empty() noexcept
{
return (left < right) & (top < bottom);
}
};
using u8 = uint8_t;
using u16 = uint16_t;
using u16x2 = vec2<u16>;
using u16r = rect<u16>;
using i16 = int16_t;
using u32 = uint32_t;
using u32x2 = vec2<u32>;
using i32 = int32_t;
using f32 = float;
using f32x2 = vec2<f32>;
using f32x4 = vec4<f32>;
struct TextAnalyzerResult
{
u32 textPosition = 0;
u32 textLength = 0;
// These 2 fields represent DWRITE_SCRIPT_ANALYSIS.
// Not using DWRITE_SCRIPT_ANALYSIS drops the struct size from 20 down to 12 bytes.
u16 script = 0;
u8 shapes = 0;
u8 bidiLevel = 0;
};
private:
template<typename T, size_t Alignment = alignof(T)>
struct Buffer
{
constexpr Buffer() noexcept = default;
explicit Buffer(size_t size) :
_data{ allocate(size) },
_size{ size }
{
}
Buffer(const T* data, size_t size) :
_data{ allocate(size) },
_size{ size }
{
static_assert(std::is_trivially_copyable_v<T>);
memcpy(_data, data, size * sizeof(T));
}
~Buffer()
{
deallocate(_data);
}
Buffer(Buffer&& other) noexcept :
_data{ std::exchange(other._data, nullptr) },
_size{ std::exchange(other._size, 0) }
{
}
#pragma warning(suppress : 26432) // If you define or delete any default operation in the type '...', define or delete them all (c.21).
Buffer& operator=(Buffer&& other) noexcept
{
deallocate(_data);
_data = std::exchange(other._data, nullptr);
_size = std::exchange(other._size, 0);
return *this;
}
explicit operator bool() const noexcept
{
return _data != nullptr;
}
T& operator[](size_t index) noexcept
{
assert(index < _size);
return _data[index];
}
const T& operator[](size_t index) const noexcept
{
assert(index < _size);
return _data[index];
}
T* data() noexcept
{
return _data;
}
const T* data() const noexcept
{
return _data;
}
size_t size() const noexcept
{
return _size;
}
private:
// These two functions don't need to use scoped objects or standard allocators,
// since this class is in fact an scoped allocator object itself.
#pragma warning(push)
#pragma warning(disable : 26402) // Return a scoped object instead of a heap-allocated if it has a move constructor (r.3).
#pragma warning(disable : 26409) // Avoid calling new and delete explicitly, use std::make_unique<T> instead (r.11).
static T* allocate(size_t size)
{
if constexpr (Alignment <= __STDCPP_DEFAULT_NEW_ALIGNMENT__)
{
return static_cast<T*>(::operator new(size * sizeof(T)));
}
else
{
return static_cast<T*>(::operator new(size * sizeof(T), static_cast<std::align_val_t>(Alignment)));
}
}
static void deallocate(T* data) noexcept
{
if constexpr (Alignment <= __STDCPP_DEFAULT_NEW_ALIGNMENT__)
{
::operator delete(data);
}
else
{
::operator delete(data, static_cast<std::align_val_t>(Alignment));
}
}
#pragma warning(pop)
T* _data = nullptr;
size_t _size = 0;
};
// This structure works similar to how std::string works:
// You can think of a std::string as a structure consisting of:
// char* data;
// size_t size;
// size_t capacity;
// where data is some backing memory allocated on the heap.
//
// But std::string employs an optimization called "small string optimization" (SSO).
// To simplify things it could be explained as:
// If the string capacity is small, then the characters are stored inside the "data"
// pointer and you make sure to set the lowest bit in the pointer one way or another.
// Heap allocations are always aligned by at least 4-8 bytes on any platform.
// If the address of the "data" pointer is not even you know data is stored inline.
template<typename T>
union SmallObjectOptimizer
{
static_assert(std::is_trivially_copyable_v<T>);
static_assert(std::has_unique_object_representations_v<T>);
T* allocated = nullptr;
T inlined;
constexpr SmallObjectOptimizer() = default;
SmallObjectOptimizer(const SmallObjectOptimizer& other)
{
const auto otherData = other.data();
const auto otherSize = other.size();
const auto data = initialize(otherSize);
memcpy(data, otherData, otherSize);
}
SmallObjectOptimizer& operator=(const SmallObjectOptimizer& other)
{
if (this != &other)
{
delete this;
new (this) SmallObjectOptimizer(other);
}
return &this;
}
SmallObjectOptimizer(SmallObjectOptimizer&& other) noexcept
{
memcpy(this, &other, std::max(sizeof(allocated), sizeof(inlined)));
other.allocated = nullptr;
}
SmallObjectOptimizer& operator=(SmallObjectOptimizer&& other) noexcept
{
return *new (this) SmallObjectOptimizer(other);
}
~SmallObjectOptimizer()
{
if (!is_inline())
{
#pragma warning(suppress : 26408) // Avoid malloc() and free(), prefer the nothrow version of new with delete (r.10).
free(allocated);
}
}
T* initialize(size_t byteSize)
{
if (would_inline(byteSize))
{
return &inlined;
}
#pragma warning(suppress : 26408) // Avoid malloc() and free(), prefer the nothrow version of new with delete (r.10).
allocated = THROW_IF_NULL_ALLOC(static_cast<T*>(malloc(byteSize)));
return allocated;
}
constexpr bool would_inline(size_t byteSize) const noexcept
{
return byteSize <= sizeof(T);
}
bool is_inline() const noexcept
{
// VSO-1430353: __builtin_bitcast crashes the compiler under /permissive-. (BODGY)
#pragma warning(suppress : 26490) // Don't use reinterpret_cast (type.1).
return (reinterpret_cast<uintptr_t>(allocated) & 1) != 0;
}
const T* data() const noexcept
{
return is_inline() ? &inlined : allocated;
}
size_t size() const noexcept
{
return is_inline() ? sizeof(inlined) : _msize(allocated);
}
};
struct FontMetrics
{
wil::unique_process_heap_string fontName;
float baselineInDIP = 0.0f;
float fontSizeInDIP = 0.0f;
u16x2 cellSize;
u16 fontWeight = 0;
u16 underlinePos = 0;
u16 strikethroughPos = 0;
u16 lineThickness = 0;
};
// These flags are shared with shader_ps.hlsl.
// If you change this be sure to copy it over to shader_ps.hlsl.
//
// clang-format off
enum class CellFlags : u32
{
None = 0x00000000,
Inlined = 0x00000001,
ColoredGlyph = 0x00000002,
ThinFont = 0x00000004,
Cursor = 0x00000008,
Selected = 0x00000010,
BorderLeft = 0x00000020,
BorderTop = 0x00000040,
BorderRight = 0x00000080,
BorderBottom = 0x00000100,
Underline = 0x00000200,
UnderlineDotted = 0x00000400,
UnderlineDouble = 0x00000800,
Strikethrough = 0x00001000,
};
// clang-format on
ATLAS_FLAG_OPS(CellFlags, u32)
// This structure is shared with the GPU shader and needs to follow certain alignment rules.
// You can generally assume that only u32 or types of that alignment are allowed.
struct Cell
{
alignas(u32) u16x2 tileIndex;
alignas(u32) CellFlags flags = CellFlags::None;
u32x2 color;
};
struct AtlasKeyAttributes
{
u16 inlined : 1;
u16 bold : 1;
u16 italic : 1;
u16 cellCount : 13;
ATLAS_POD_OPS(AtlasKeyAttributes)
};
struct AtlasKeyData
{
AtlasKeyAttributes attributes;
u16 charCount;
wchar_t chars[14];
};
struct AtlasKey
{
AtlasKey(AtlasKeyAttributes attributes, u16 charCount, const wchar_t* chars)
{
const auto size = dataSize(charCount);
const auto data = _data.initialize(size);
attributes.inlined = _data.would_inline(size);
data->attributes = attributes;
data->charCount = charCount;
memcpy(&data->chars[0], chars, static_cast<size_t>(charCount) * sizeof(AtlasKeyData::chars[0]));
}
const AtlasKeyData* data() const noexcept
{
return _data.data();
}
size_t hash() const noexcept
{
const auto d = data();
#pragma warning(suppress : 26490) // Don't use reinterpret_cast (type.1).
return std::_Fnv1a_append_bytes(std::_FNV_offset_basis, reinterpret_cast<const u8*>(d), dataSize(d->charCount));
}
bool operator==(const AtlasKey& rhs) const noexcept
{
const auto a = data();
const auto b = rhs.data();
return a->charCount == b->charCount && memcmp(a, b, dataSize(a->charCount)) == 0;
}
private:
SmallObjectOptimizer<AtlasKeyData> _data;
static constexpr size_t dataSize(u16 charCount) noexcept
{
// This returns the actual byte size of a AtlasKeyData struct for the given charCount.
// The `wchar_t chars[2]` is only a buffer for the inlined variant after
// all and the actual charCount can be smaller or larger. Due to this we
// remove the size of the `chars` array and add it's true length on top.
return sizeof(AtlasKeyData) - sizeof(AtlasKeyData::chars) + static_cast<size_t>(charCount) * sizeof(AtlasKeyData::chars[0]);
}
};
struct AtlasKeyHasher
{
size_t operator()(const AtlasKey& key) const noexcept
{
return key.hash();
}
};
struct AtlasValueData
{
CellFlags flags = CellFlags::None;
u16x2 coords[7];
};
struct AtlasValue
{
constexpr AtlasValue() = default;
u16x2* initialize(CellFlags flags, u16 cellCount)
{
const auto size = dataSize(cellCount);
const auto data = _data.initialize(size);
WI_SetFlagIf(flags, CellFlags::Inlined, _data.would_inline(size));
data->flags = flags;
return &data->coords[0];
}
const AtlasValueData* data() const noexcept
{
return _data.data();
}
private:
SmallObjectOptimizer<AtlasValueData> _data;
static constexpr size_t dataSize(u16 coordCount) noexcept
{
return sizeof(AtlasValueData) - sizeof(AtlasValueData::coords) + static_cast<size_t>(coordCount) * sizeof(AtlasValueData::coords[0]);
}
};
struct AtlasQueueItem
{
const AtlasKey* key;
const AtlasValue* value;
float scale;
};
struct CachedCursorOptions
{
u32 cursorColor = INVALID_COLOR;
u16 cursorType = gsl::narrow_cast<u16>(CursorType::Legacy);
u8 heightPercentage = 20;
ATLAS_POD_OPS(CachedCursorOptions)
};
struct BufferLineMetadata
{
u32x2 colors;
CellFlags flags = CellFlags::None;
};
// NOTE: D3D constant buffers sizes must be a multiple of 16 bytes.
struct alignas(16) ConstBuffer
{
// WARNING: Modify this carefully after understanding how HLSL struct packing works.
// The gist is:
// * Minimum alignment is 4 bytes (like `#pragma pack 4`)
// * Members cannot straddle 16 byte boundaries
// This means a structure like {u32; u32; u32; u32x2} would require
// padding so that it is {u32; u32; u32; <4 byte padding>; u32x2}.
alignas(sizeof(f32x4)) f32x4 viewport;
alignas(sizeof(f32x4)) f32x4 gammaRatios;
alignas(sizeof(f32)) f32 grayscaleEnhancedContrast = 0;
alignas(sizeof(u32)) u32 cellCountX = 0;
alignas(sizeof(u32x2)) u32x2 cellSize;
alignas(sizeof(u32x2)) u32x2 underlinePos;
alignas(sizeof(u32x2)) u32x2 strikethroughPos;
alignas(sizeof(u32)) u32 backgroundColor = 0;
alignas(sizeof(u32)) u32 cursorColor = 0;
alignas(sizeof(u32)) u32 selectionColor = 0;
#pragma warning(suppress : 4324) // 'ConstBuffer': structure was padded due to alignment specifier
};
// Handled in BeginPaint()
enum class ApiInvalidations : u8
{
None = 0,
Title = 1 << 0,
Device = 1 << 1,
SwapChain = 1 << 2,
Size = 1 << 3,
Font = 1 << 4,
Settings = 1 << 5,
};
ATLAS_FLAG_OPS(ApiInvalidations, u8)
// Handled in Present()
enum class RenderInvalidations : u8
{
None = 0,
Cursor = 1 << 0,
ConstBuffer = 1 << 1,
};
ATLAS_FLAG_OPS(RenderInvalidations, u8)
// MSVC STL (version 22000) implements std::clamp<T>(T, T, T) in terms of the generic
// std::clamp<T, Predicate>(T, T, T, Predicate) with std::less{} as the argument,
// which introduces branching. While not perfect, this is still better than std::clamp.
template<typename T>
static constexpr T clamp(T val, T min, T max)
{
return std::max(min, std::min(max, val));
}
// AtlasEngine.cpp
[[nodiscard]] HRESULT _handleException(const wil::ResultException& exception) noexcept;
__declspec(noinline) void _createResources();
void _releaseSwapChain();
__declspec(noinline) void _createSwapChain();
__declspec(noinline) void _recreateSizeDependentResources();
__declspec(noinline) void _recreateFontDependentResources();
IDWriteTextFormat* _getTextFormat(bool bold, bool italic) const noexcept;
const Buffer<DWRITE_FONT_AXIS_VALUE>& _getTextFormatAxis(bool bold, bool italic) const noexcept;
Cell* _getCell(u16 x, u16 y) noexcept;
void _setCellFlags(SMALL_RECT coords, CellFlags mask, CellFlags bits) noexcept;
u16x2 _allocateAtlasTile() noexcept;
void _flushBufferLine();
void _emplaceGlyph(IDWriteFontFace* fontFace, float scale, size_t bufferPos1, size_t bufferPos2);
// AtlasEngine.api.cpp
void _resolveFontMetrics(const FontInfoDesired& fontInfoDesired, FontInfo& fontInfo, FontMetrics* fontMetrics = nullptr) const;
// AtlasEngine.r.cpp
void _setShaderResources() const;
static f32x4 _getGammaRatios(float gamma) noexcept;
void _updateConstantBuffer() const noexcept;
void _adjustAtlasSize();
void _reserveScratchpadSize(u16 minWidth);
void _processGlyphQueue();
void _drawGlyph(const AtlasQueueItem& item) const;
void _drawCursor();
void _copyScratchpadTile(uint32_t scratchpadIndex, u16x2 target, uint32_t copyFlags = 0) const noexcept;
static constexpr bool debugGlyphGenerationPerformance = false;
static constexpr bool debugGeneralPerformance = false || debugGlyphGenerationPerformance;
static constexpr bool continuousRedraw = false || debugGeneralPerformance;
static constexpr u16 u16min = 0x0000;
static constexpr u16 u16max = 0xffff;
static constexpr i16 i16min = -0x8000;
static constexpr i16 i16max = 0x7fff;
static constexpr u16r invalidatedAreaNone = { u16max, u16max, u16min, u16min };
static constexpr u16x2 invalidatedRowsNone{ u16max, u16min };
static constexpr u16x2 invalidatedRowsAll{ u16min, u16max };
struct StaticResources
{
wil::com_ptr<ID2D1Factory> d2dFactory;
wil::com_ptr<IDWriteFactory1> dwriteFactory;
wil::com_ptr<IDWriteFontFallback> systemFontFallback;
wil::com_ptr<IDWriteTextAnalyzer1> textAnalyzer;
bool isWindows10OrGreater = true;
#ifndef NDEBUG
wil::unique_folder_change_reader_nothrow sourceCodeWatcher;
std::atomic<int64_t> sourceCodeInvalidationTime{ INT64_MAX };
#endif
} _sr;
struct Resources
{
// D3D resources
wil::com_ptr<ID3D11Device> device;
wil::com_ptr<ID3D11DeviceContext1> deviceContext;
wil::com_ptr<IDXGISwapChain1> swapChain;
wil::unique_handle frameLatencyWaitableObject;
wil::com_ptr<ID3D11RenderTargetView> renderTargetView;
wil::com_ptr<ID3D11VertexShader> vertexShader;
wil::com_ptr<ID3D11PixelShader> pixelShader;
wil::com_ptr<ID3D11Buffer> constantBuffer;
wil::com_ptr<ID3D11Buffer> cellBuffer;
wil::com_ptr<ID3D11ShaderResourceView> cellView;
// D2D resources
wil::com_ptr<ID3D11Texture2D> atlasBuffer;
wil::com_ptr<ID3D11ShaderResourceView> atlasView;
wil::com_ptr<ID3D11Texture2D> atlasScratchpad;
wil::com_ptr<ID2D1RenderTarget> d2dRenderTarget;
wil::com_ptr<ID2D1Brush> brush;
wil::com_ptr<IDWriteTextFormat> textFormats[2][2];
Buffer<DWRITE_FONT_AXIS_VALUE> textFormatAxes[2][2];
wil::com_ptr<IDWriteTypography> typography;
Buffer<Cell, 32> cells; // invalidated by ApiInvalidations::Size
f32x2 cellSizeDIP; // invalidated by ApiInvalidations::Font, caches _api.cellSize but in DIP
u16x2 cellSize; // invalidated by ApiInvalidations::Font, caches _api.cellSize
u16x2 cellCount; // invalidated by ApiInvalidations::Font|Size, caches _api.cellCount
u16 underlinePos = 0;
u16 strikethroughPos = 0;
u16 lineThickness = 0;
u16 dpi = USER_DEFAULT_SCREEN_DPI; // invalidated by ApiInvalidations::Font, caches _api.dpi
u16 maxEncounteredCellCount = 0;
u16 scratchpadCellWidth = 0;
u16x2 atlasSizeInPixelLimit; // invalidated by ApiInvalidations::Font
u16x2 atlasSizeInPixel; // invalidated by ApiInvalidations::Font
u16x2 atlasPosition;
std::unordered_map<AtlasKey, AtlasValue, AtlasKeyHasher> glyphs;
std::vector<AtlasQueueItem> glyphQueue;
f32 gamma = 0;
f32 grayscaleEnhancedContrast = 0;
u32 backgroundColor = 0xff000000;
u32 selectionColor = 0x7fffffff;
CachedCursorOptions cursorOptions;
RenderInvalidations invalidations = RenderInvalidations::None;
#ifndef NDEBUG
// See documentation for IDXGISwapChain2::GetFrameLatencyWaitableObject method:
// > For every frame it renders, the app should wait on this handle before starting any rendering operations.
// > Note that this requirement includes the first frame the app renders with the swap chain.
bool frameLatencyWaitableObjectUsed = false;
#endif
} _r;
struct ApiState
{
// This structure is loosely sorted in chunks from "very often accessed together"
// to seldom accessed and/or usually not together.
std::vector<wchar_t> bufferLine;
std::vector<u16> bufferLineColumn;
Buffer<BufferLineMetadata> bufferLineMetadata;
std::vector<TextAnalyzerResult> analysisResults;
Buffer<u16> clusterMap;
Buffer<DWRITE_SHAPING_TEXT_PROPERTIES> textProps;
Buffer<u16> glyphIndices;
Buffer<DWRITE_SHAPING_GLYPH_PROPERTIES> glyphProps;
std::vector<DWRITE_FONT_FEATURE> fontFeatures; // changes are flagged as ApiInvalidations::Font|Size
std::vector<DWRITE_FONT_AXIS_VALUE> fontAxisValues; // changes are flagged as ApiInvalidations::Font|Size
FontMetrics fontMetrics; // changes are flagged as ApiInvalidations::Font|Size
u16x2 cellCount; // caches `sizeInPixel / cellSize`
u16x2 sizeInPixel; // changes are flagged as ApiInvalidations::Size
// UpdateDrawingBrushes()
u32 backgroundOpaqueMixin = 0xff000000; // changes are flagged as ApiInvalidations::Device
u32x2 currentColor;
AtlasKeyAttributes attributes{};
u16 currentRow = 0;
CellFlags flags = CellFlags::None;
// SetSelectionBackground()
u32 selectionColor = 0x7fffffff;
// dirtyRect is a computed value based on invalidatedRows.
til::rect dirtyRect;
// These "invalidation" fields are reset in EndPaint()
u16r invalidatedCursorArea = invalidatedAreaNone;
u16x2 invalidatedRows = invalidatedRowsNone; // x is treated as "top" and y as "bottom"
i16 scrollOffset = 0;
std::function<void(HRESULT)> warningCallback;
std::function<void()> swapChainChangedCallback;
wil::unique_handle swapChainHandle;
HWND hwnd = nullptr;
u16 dpi = USER_DEFAULT_SCREEN_DPI; // changes are flagged as ApiInvalidations::Font|Size
u16 antialiasingMode = D2D1_TEXT_ANTIALIAS_MODE_CLEARTYPE; // changes are flagged as ApiInvalidations::Font
ApiInvalidations invalidations = ApiInvalidations::Device;
} _api;
#undef ATLAS_POD_OPS
#undef ATLAS_FLAG_OPS
};
}
| 42.267366 | 248 | 0.576558 | [
"render",
"object",
"vector"
] |
a9146c8aa58959bdbd6c994ffc2d9a3b08b55099 | 16,019 | h | C | paddle/phi/kernels/primitive/compute_primitives.h | ZibinGuo/Paddle | 6e0892312de5e4ba76d980ff0e4322ac55ca0d07 | [
"Apache-2.0"
] | 1 | 2022-02-22T01:08:00.000Z | 2022-02-22T01:08:00.000Z | paddle/phi/kernels/primitive/compute_primitives.h | ZibinGuo/Paddle | 6e0892312de5e4ba76d980ff0e4322ac55ca0d07 | [
"Apache-2.0"
] | null | null | null | paddle/phi/kernels/primitive/compute_primitives.h | ZibinGuo/Paddle | 6e0892312de5e4ba76d980ff0e4322ac55ca0d07 | [
"Apache-2.0"
] | null | null | null | // Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#ifdef PADDLE_WITH_CUDA
#include <cuda_fp16.h>
#endif
#ifdef PADDLE_WITH_HIP
#include <hip/hip_fp16.h>
#endif
#include "paddle/fluid/platform/device/gpu/gpu_device_function.h"
#include "paddle/phi/common/float16.h"
namespace phi {
namespace kps {
namespace details {
#ifdef __HIPCC__
constexpr int kReduceMaxThread = 256;
constexpr int kWarpSize = 64;
#else
constexpr int kReduceMaxThread = 128;
constexpr int kWarpSize = 32;
#endif
// kGlobalMode: block reduce, each block gets an output;
// kLocalMode: thread reduce, each thread gets an output;
enum ReduceMode { kGlobalMode, kLocalMode };
template <typename T>
class MPTypeTrait {
public:
using Type = T;
};
template <>
class MPTypeTrait<phi::dtype::float16> {
public:
using Type = float;
};
/**
* @brief Will be used in BlockYReduce, get the index of reduce_num in shared
* memory.
*/
__device__ __forceinline__ int SharedMemoryIndex(int index) {
return (threadIdx.y + index) * blockDim.x + threadIdx.x;
}
template <typename T, typename ReduceOp>
__device__ __forceinline__ T WarpReduce(T val, ReduceOp reducer) {
unsigned mask = 0u;
CREATE_SHFL_MASK(mask, true);
for (int stride = details::kWarpSize / 2; stride > 0; stride >>= 1) {
T temp = paddle::platform::CudaShuffleDownSync(mask, val, stride);
val = reducer(val, temp);
}
return val;
}
/* e.g.
* |---------block---------|
* |warp0|warp1|warp2|warp3|
* |0~31|32~63|64~95|96~127| ---->blockDim.x = 128
* \|/ \|/ \|/ \|/ ---->1. First WarpReduce in each warp
* res0 res1 res2 res3 ---->2. Store result of each warp to shared memory
* \ \ / / ---->3. Load the result above from shared memory
* res to warp0 and process the second WarpReduce
*/
/**
* @brief BlockXReduce reduce along blockDim.x.
*/
template <typename T, typename ReduceOp>
__device__ __forceinline__ T BlockXReduce(T val, ReduceOp reducer) {
__syncthreads();
using details::kWarpSize;
__shared__ T shared[2 * kWarpSize];
int block_dim_x = blockDim.x;
if (blockDim.x > kWarpSize) {
block_dim_x = blockDim.x / kWarpSize;
int lane = threadIdx.x % kWarpSize;
int tid = threadIdx.y * blockDim.x + threadIdx.x;
int wid = tid / kWarpSize;
int bid = threadIdx.y;
val = WarpReduce(val, reducer);
if (lane == 0) {
shared[wid] = val;
}
__syncthreads();
val = shared[bid * block_dim_x + lane];
}
unsigned mask = 0u;
CREATE_SHFL_MASK(mask, true);
for (int stride = 1; stride < block_dim_x; stride <<= 1) {
T temp = paddle::platform::CudaShuffleDownSync(mask, val, stride);
val = reducer(val, temp);
}
return val;
}
/**
* @brief BlockYReduce reduce along blockDim.y.
*/
template <typename T, typename ReduceOp>
__device__ __forceinline__ T BlockYReduce(T val, ReduceOp reducer) {
__shared__ T shared_memory[1024];
shared_memory[SharedMemoryIndex(0)] = val;
for (int stride = blockDim.y / 2; stride > 0; stride >>= 1) {
__syncthreads();
if (threadIdx.y < stride && threadIdx.y + stride < blockDim.y) {
T temp = shared_memory[SharedMemoryIndex(stride)];
val = reducer(val, temp);
}
shared_memory[SharedMemoryIndex(0)] = val;
}
__syncthreads();
return shared_memory[threadIdx.x];
}
} // namespace details
/**
* @brief Perform unary calculation according to OpFunc. Shape of input and
* output are the same.
*
* @template paraments
* InT: The data type of in.
* OutT: The data type of out.
* NX: The number of data columns loaded by each thread.
* NY: The number of data rows loaded by each thread.
* BlockSize: Identifies the current device thread index method. For GPU,
* threadIdx.x is used as the thread index. Currently only GPU was supported.
* OpFunc: Compute functor which has an operator() as following:
* template <typename InT, typename OutT>
* struct XxxFunctor {
* HOSTDEVICE OutT operator()(const InT& a) const {
* return ...;
* }
* };
*
* @param:
* out: The register pointer of out, the size is NX * NY.
* in: The register pointer of in, the size is NX * NY.
* compute: Compute function which was declared like OpFunc<InT, OutT>().
*/
template <typename InT,
typename OutT,
int NX,
int NY,
int BlockSize,
class OpFunc>
__device__ __forceinline__ void ElementwiseUnary(OutT* out,
const InT* in,
OpFunc compute) {
#pragma unroll
for (int idx = 0; idx < NX * NY; idx++) {
out[idx] = static_cast<OutT>(compute(in[idx]));
}
}
/**
* @brief Binary calculation according to OpFunc. Shape of The input and output
* are the same.
*
* @template paraments
* InT: The data type of in1 and in2.
* OutT: The data type of out.
* NX: The number of data columns computed by each thread.
* NY: The number of data rows computed by each thread.
* BlockSize: Identifies the current device thread index method. For GPU,
* threadIdx.x is used as the thread index. Currently only GPU was supported.
* OpFunc: Compute functor which has an operator() as following:
* template <typename InT>
* struct XxxFunctor {
* HOSTDEVICE InT operator()(const InT& a, const InT& b) const {
* return ...;
* }
* };
*
* @param:
* out: The register pointer of out, the size is NX * NY.
* in1: The register pointer of fist input, size is NX * NY.
* in2: The register pointer of second input, size is NX * NY.
* compute: Compute function which was declared like OpFunc<InT>().
*/
template <typename InT,
typename OutT,
int NX,
int NY,
int BlockSize,
class OpFunc>
__device__ __forceinline__ void ElementwiseBinary(OutT* out,
const InT* in1,
const InT* in2,
OpFunc compute) {
#pragma unroll
for (int idx = 0; idx < NX * NY; ++idx) {
out[idx] = static_cast<OutT>(compute(in1[idx], in2[idx]));
}
}
/**
* @brief Ternary calculation according to OpFunc. Shape of input and output
* are the same.
*
* @template paraments
* InT: The data type of in1 and in2.
* OutT: The data type of out.
* NX: The number of data columns loaded by each thread.
* NY: The number of data rows loaded by each thread.
* BlockSize: Identifies the current device thread index method. For GPU,
* threadIdx.x is used as the thread index. Currently only GPU was supported.
* OpFunc: Compute functor which has an operator() as following
* template <typename InT>
* struct XxxFunctor {
* HOSTDEVICE InT operator()(const InT& a, const InT& b, const InT& c)
* const {
* return ...;
* }
* };
*
* @param
* out: The register pointer of out, the size is NX * NY.
* in1: The register pointer of fist input, size is NX * NY.
* in2: The register pointer of second input, size is NX * NY.
* in3: The register pointer of third input, size is NX * NY.
* compute: Compute function which was declared like OpFunc<InT>().
*/
template <typename InT,
typename OutT,
int NX,
int NY,
int BlockSize,
class OpFunc>
__device__ __forceinline__ void ElementwiseTernary(
OutT* out, const InT* in1, const InT* in2, const InT* in3, OpFunc compute) {
#pragma unroll
for (int idx = 0; idx < NX * NY; ++idx) {
out[idx] = static_cast<OutT>(compute(in1[idx], in2[idx], in3[idx]));
}
}
/**
* @brief Multivariate calculation according to OpFunc. Shape of inputs and
* output are the same.
*
* @template paraments
* InT: The data type of in1, in2 and in3.
* OutT: The data type of out.
* NX: The number of data columns loaded by each thread.
* NY: The number of data rows loaded by each thread.
* BlockSize: Identifies the current device thread index method. For GPU,
* threadIdx.x is used as the thread index. Currently only GPU was supported.
* Arity: The size of ins.
* OpFunc: Compute functor which has an operator() as following:
* template <typename InT>
* struct XxxFunctor {
* HOSTDEVICE InT operator()(const InT* args) const {
* return ...;
* }
* };
*
* @param
* out: The register pointer of out, the size is NX * NY.
* ins: A pointers of array consisting of multiple inputs.
* compute: Compute function which was declared like OpFunc<InT>().
*/
template <typename InT,
typename OutT,
int NX,
int NY,
int BlockSize,
int Arity,
class OpFunc>
__device__ __forceinline__ void ElementwiseAny(OutT* out,
InT (*ins)[NX * NY],
OpFunc compute) {
InT args[Arity];
#pragma unroll
for (int idx = 0; idx < NX * NY; ++idx) {
#pragma unroll
for (int j = 0; j < Arity; ++j) {
args[j] = ins[j][idx];
}
out[idx] = static_cast<OutT>(compute(args));
}
}
/**
* @brief Binary calculation according to OpFunc. Shape of in1 and in2 are the
* different. Shape of in1 is [1, NX], but in2's shape is [NY, NX], the output
* shape is [NY, NX].
*
* @template paraments
* InT: The data type of in1 and in2.
* OutT: The data type of out.
* NX: The number of data columns loaded by each thread.
* NY: The number of data rows loaded by each thread.
* BlockSize: Identifies the current device thread index method. For GPU,
* threadIdx.x is used as the thread index. Currently only GPU was supported.
* OpFunc: Compute functor which has an operator() as following
* template <typename InT, typename OutT>
* struct XxxFunctor {
* HOSTDEVICE OutT operator()(const InT& a, const InT& b) const {
* return ...;
* }
* };
*
* @param
* out: The register pointer of out, the size is NX * NY.
* in1: The register pointer of fist input, size is NX * 1.
* in2: The register pointer of second input, size is NX * NY.
* compute: Compute function which was declared like OpFunc<InT, OutT>().
*/
template <typename InT,
typename OutT,
int NX,
int NY,
int BlockSize,
class OpFunc>
__device__ __forceinline__ void CycleBinary(OutT* out,
const InT* in1,
const InT* in2,
OpFunc compute) {
#pragma unroll
for (int idx = 0; idx < NX; idx++) {
#pragma unroll
for (int idy = 0; idy < NY; idy++) {
out[idx + idy * NX] =
static_cast<OutT>(compute(in1[idx], in2[idx + idy * NX]));
}
}
}
/**
* @brief The Reduce provides collective methods for computing a parallel
* reduction of items partitioned across a CUDA block and intra thread. When
* ReduceMode == kLocalMode, thread reduce along nx. When ReduceMode ==
* kGlobalMode, use shared memory to reduce between threads.
*
* @template paraments
* T: The type of data.
* NX: The number of data continuously loaded by each thread.
* NY: The number of data rows loaded by each thread, only NY = 1 was supported.
* BlockSize: Identifies the current device thread index method. For GPU,
* threadIdx.x is used as the thread index. Currently only GPU was supported.
* ReduceFunctor: Compute functor which has an operator() as following
* template <typename InT>
* struct ReduceFunctor {
* HOSTDEVICE InT operator()(const InT& a, const InT& b) const {
* return ...;
* }
* };
* ReduceMode: Reduce mode, can be kLocalMode, kGlobalMode.
*
* @param
* out: The register pointer of out, the size is NX * NY.
* in: The register pointer of in, the size is NX * NY.
* reducer: Compute function which was declared like ReduceFunctor<InT>().
* reduce_last_dim: if the last dim gets involved in reduction.
*/
template <typename T,
int NX,
int NY,
int BlockSize,
class ReduceFunctor,
details::ReduceMode Mode>
__device__ __forceinline__ void Reduce(T* out,
const T* in,
ReduceFunctor reducer,
bool reduce_last_dim) {
int block_index = blockDim.y;
if (Mode == details::ReduceMode::kGlobalMode) {
bool block_reduce_y = (!reduce_last_dim) && (block_index > 1);
// when reduce is not required for the last dim, and reduce num has been
// split into multiple threads
if (block_reduce_y) {
#pragma unroll
for (int i = 0; i < NY * NX; i++) { // reduce along blockdim.y
out[i] = details::BlockYReduce<T, ReduceFunctor>(out[i], reducer);
}
}
// when last dimension need to be reduced
if (reduce_last_dim) {
#pragma unroll
for (int i = 0; i < NY * NX; i++) { // reduce along blockDim.x
out[i] = details::BlockXReduce<T, ReduceFunctor>(out[i], reducer);
}
}
} else { // else kLocalMode
#pragma unroll
for (int i = 0; i < NY; ++i) {
#pragma unroll
for (int j = 0; j < NX; ++j) {
out[i] = reducer(out[i], in[i * NX + j]);
}
}
}
}
template <typename InT,
typename OutT,
int NX,
int NY,
int BlockSize,
class OpFunc>
__device__ __forceinline__ void ElementwiseConstant(OutT* out, OpFunc compute) {
#pragma unroll
for (int idx = 0; idx < NX * NY; idx++) {
out[idx] = static_cast<OutT>(compute());
}
}
template <typename StateType,
typename OutT,
int ReturnsCount,
int BlockSize,
class OpFunc>
__device__ __forceinline__ void ElementwiseRandom(OutT* out,
OpFunc compute,
StateType* state) {
auto random_tuple = compute(state);
#pragma unroll
for (int i = 0; i < ReturnsCount; i++) {
out[i] = static_cast<OutT>((&random_tuple.x)[i]);
}
}
// attention please set share_size = blockDim.x;
// data and b are the register pointer
#define shared_size 64
template <typename InT,
typename OutT,
int NX,
int NY,
int BlockSize,
class OpFunc>
__device__ __forceinline__ void Cumsum(OutT* out,
const InT* in,
OpFunc compute) {
__shared__ InT temp[shared_size * 2 + (shared_size * 2) / 32];
int tidx = threadIdx.x;
temp[tidx + tidx / 32] = in[0];
temp[shared_size + tidx + (shared_size + tidx) / 32] = in[1];
for (int stride = 1; stride <= blockDim.x; stride *= 2) {
__syncthreads();
int index = (tidx + 1) * 2 * stride - 1;
if (index < (blockDim.x * 2)) {
temp[index + index / 32] += temp[index - stride + (index - stride) / 32];
}
}
for (int stride = (blockDim.x * 2) / 4; stride > 0; stride /= 2) {
__syncthreads();
int index = (tidx + 1) * 2 * stride - 1;
if ((index + stride) < (blockDim.x * 2)) {
temp[index + stride + (stride + index) / 32] +=
temp[index + (index) / 32];
}
}
__syncthreads();
out[0] = static_cast<OutT>(temp[tidx + tidx / 32]);
out[1] =
static_cast<OutT>(temp[tidx + shared_size + (tidx + shared_size) / 32]);
}
} // namespace kps
} // namespace phi
| 32.960905 | 80 | 0.616081 | [
"shape"
] |
a91d4b00ac27d8e9585278a0bc986c0fc3871954 | 2,839 | c | C | step2.build_gstreamer_project/gst_plugin_tutorial/gst-plugins-bad/ext/dash/gstmpddescriptortypenode.c | zhang-jinyu/Smart-Fruit-Scale-based-on-the-VITIS-AI-and-ZCU104 | 3b389cbaa0a4f472d9dd5bb6b994a904fdc6c832 | [
"Apache-2.0"
] | 1 | 2021-03-05T08:43:24.000Z | 2021-03-05T08:43:24.000Z | step2.build_gstreamer_project/gst_plugin_tutorial/gst-plugins-bad/ext/dash/gstmpddescriptortypenode.c | zhang-jinyu/Smart-Fruit-Scale-based-on-the-VITIS-AI-and-ZCU104 | 3b389cbaa0a4f472d9dd5bb6b994a904fdc6c832 | [
"Apache-2.0"
] | null | null | null | step2.build_gstreamer_project/gst_plugin_tutorial/gst-plugins-bad/ext/dash/gstmpddescriptortypenode.c | zhang-jinyu/Smart-Fruit-Scale-based-on-the-VITIS-AI-and-ZCU104 | 3b389cbaa0a4f472d9dd5bb6b994a904fdc6c832 | [
"Apache-2.0"
] | null | null | null | /* GStreamer
*
* Copyright (C) 2019 Collabora Ltd.
* Author: Stéphane Cerveau <scerveau@collabora.com>
*
* 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.1 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#include "gstmpddescriptortypenode.h"
#include "gstmpdparser.h"
G_DEFINE_TYPE (GstMPDDescriptorTypeNode, gst_mpd_descriptor_type_node,
GST_TYPE_MPD_NODE);
/* GObject VMethods */
static void
gst_mpd_descriptor_type_node_finalize (GObject * object)
{
GstMPDDescriptorTypeNode *self = GST_MPD_DESCRIPTOR_TYPE_NODE (object);
if (self->schemeIdUri)
xmlFree (self->schemeIdUri);
if (self->value)
xmlFree (self->value);
g_free (self->node_name);
G_OBJECT_CLASS (gst_mpd_descriptor_type_node_parent_class)->finalize (object);
}
/* Base class */
static xmlNodePtr
gst_mpd_descriptor_type_get_xml_node (GstMPDNode * node)
{
xmlNodePtr descriptor_type_xml_node = NULL;
GstMPDDescriptorTypeNode *self = GST_MPD_DESCRIPTOR_TYPE_NODE (node);
descriptor_type_xml_node = xmlNewNode (NULL, (xmlChar *) self->node_name);
gst_xml_helper_set_prop_string (descriptor_type_xml_node, "schemeIdUri",
self->schemeIdUri);
gst_xml_helper_set_prop_string (descriptor_type_xml_node, "value",
self->value);
return descriptor_type_xml_node;
}
static void
gst_mpd_descriptor_type_node_class_init (GstMPDDescriptorTypeNodeClass * klass)
{
GObjectClass *object_class;
GstMPDNodeClass *m_klass;
object_class = G_OBJECT_CLASS (klass);
m_klass = GST_MPD_NODE_CLASS (klass);
object_class->finalize = gst_mpd_descriptor_type_node_finalize;
m_klass->get_xml_node = gst_mpd_descriptor_type_get_xml_node;
}
static void
gst_mpd_descriptor_type_node_init (GstMPDDescriptorTypeNode * self)
{
if (self->schemeIdUri)
xmlFree (self->schemeIdUri);
if (self->value)
xmlFree (self->value);
}
GstMPDDescriptorTypeNode *
gst_mpd_descriptor_type_node_new (const gchar * name)
{
GstMPDDescriptorTypeNode *self =
g_object_new (GST_TYPE_MPD_DESCRIPTOR_TYPE_NODE, NULL);
self->node_name = g_strdup (name);
return self;
}
void
gst_mpd_descriptor_type_node_free (GstMPDDescriptorTypeNode * self)
{
if (self)
gst_object_unref (self);
}
| 28.39 | 80 | 0.769285 | [
"object"
] |
a92311365625175e4ab2c1253fa4c231fd2fe01a | 7,790 | c | C | src/unix/sysdep/sysdep_mixer.c | automation-club/pinmame | c44c0503a6516f79259bf5d1dbbfcdeadada1d1a | [
"BSD-3-Clause"
] | 46 | 2016-09-10T15:43:48.000Z | 2022-03-30T13:50:11.000Z | src/unix/sysdep/sysdep_mixer.c | Kissarmynh/pinmame | c552e469d60400602f62f7cdc3c4e93d81c3b720 | [
"BSD-3-Clause"
] | 13 | 2021-01-20T18:36:26.000Z | 2021-12-31T06:49:42.000Z | src/unix/sysdep/sysdep_mixer.c | Kissarmynh/pinmame | c552e469d60400602f62f7cdc3c4e93d81c3b720 | [
"BSD-3-Clause"
] | 25 | 2017-11-13T07:20:39.000Z | 2022-03-30T09:17:23.000Z | /* Sysdep sound mixer object
Copyright 2000 Hans de Goede
This file and the acompanying files in this directory are free software;
you can redistribute them and/or modify them under the terms of the GNU
Library General Public License as published by the Free Software Foundation;
either version 2 of the License, or (at your option) any later version.
These files are distributed in the hope that they will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with these files; see the file COPYING.LIB. If not,
write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
/* Changelog
Version 0.1, February 2000
-initial release (Hans de Goede)
Version 0.2, March 2000
-added a plugin parameter to create, to override the global plugin
configuration (Hans de Goede)
-protected sysdep_mixer_init against being called twice (Hans de Goede)
*/
#include "sysdep_mixer.h"
#include "sysdep_mixer_priv.h"
#include "sysdep_mixer_plugins.h"
/* #define SYSDEP_MIXER_DEBUG */
/* private func prototypes */
static int sysdep_mixer_list_plugins(struct rc_option *option,
const char *arg, int priority);
/* private variables */
static char *sysdep_mixer_plugin = NULL;
static struct rc_struct *sysdep_mixer_rc = NULL;
static struct plugin_manager_struct *sysdep_mixer_plugin_manager = NULL;
static struct rc_option sysdep_mixer_opts[] = {
/* name, shortname, type, dest, deflt, min, max, func, help */
{ "Sound mixer related", NULL, rc_seperator, NULL,
NULL, 0, 0, NULL,
NULL },
{ "sound-mixer-plugin", "smp", rc_string, &sysdep_mixer_plugin,
NULL, 0, 0, NULL,
"Select which plugin to use for the sound mixer" },
{ "list-mixer-plugins", "lmp", rc_use_function_no_arg, NULL,
NULL, 0, 0, sysdep_mixer_list_plugins,
"List available sound-mixer plugins" },
{ NULL, NULL, rc_end, NULL,
NULL, 0, 0, NULL,
NULL }
};
static const struct plugin_struct *sysdep_mixer_plugins[] = {
#ifdef SYSDEP_MIXER_OSS
&sysdep_mixer_oss,
#endif
#ifdef SYSDEP_MIXER_NETBSD
&sysdep_mixer_netbsd,
#endif
#ifdef SYSDEP_MIXER_SOLARIS
&sysdep_mixer_solaris,
#endif
#ifdef SYSDEP_MIXER_NEXT
&sysdep_mixer_next,
#endif
#ifdef DSYSDEP_MIXER_IRIX
&sysdep_mixer_irix,
#endif
#ifdef DSYSDEP_MIXER_AIX
&sysdep_mixer_aix,
#endif
NULL
};
#ifdef SYSDEP_MIXER_DEBUG
const char *sysdep_mixer_names[] = SYSDEP_MIXER_NAMES;
#endif
/* private methods */
static int sysdep_mixer_list_plugins(struct rc_option *option,
const char *arg, int priority)
{
fprintf(stdout, "Sound mixer plugins:\n\n");
plugin_manager_list_plugins(sysdep_mixer_plugin_manager, stdout);
return -1;
}
/* public methods */
int sysdep_mixer_init(struct rc_struct *rc, const char *plugin_path)
{
if(!sysdep_mixer_rc)
{
if(rc && rc_register(rc, sysdep_mixer_opts))
return -1;
sysdep_mixer_rc = rc;
}
if(!sysdep_mixer_plugin_manager)
{
if(!(sysdep_mixer_plugin_manager = plugin_manager_create("sysdep_mixer",
rc)))
{
sysdep_mixer_exit();
return -1;
}
/* no need to fail here, if we don't have any plugins,
sysdep_mixer_create will always fail, but that doesn't have to be
fatal, failing here usually is! */
plugin_manager_register(sysdep_mixer_plugin_manager,
sysdep_mixer_plugins);
plugin_manager_load(sysdep_mixer_plugin_manager, plugin_path, NULL);
if(plugin_manager_init_plugin(sysdep_mixer_plugin_manager, NULL))
{
fprintf(stderr, "warning: no mixer plugins available\n");
}
}
return 0;
}
void sysdep_mixer_exit(void)
{
if(sysdep_mixer_plugin_manager)
{
plugin_manager_destroy(sysdep_mixer_plugin_manager);
sysdep_mixer_plugin_manager = NULL;
}
if(sysdep_mixer_rc)
{
rc_unregister(sysdep_mixer_rc, sysdep_mixer_opts);
sysdep_mixer_rc = NULL;
}
}
struct sysdep_mixer_struct *sysdep_mixer_create(const char *plugin,
const char *device, int flags)
{
int i;
struct sysdep_mixer_struct *mixer = NULL;
struct sysdep_mixer_create_params params;
/* fill the params struct */
params.device = device;
/* create the instance */
if(!(mixer = plugin_manager_create_instance(sysdep_mixer_plugin_manager,
plugin? plugin:sysdep_mixer_plugin, ¶ms)))
return NULL;
/* fill the mixer cache and save the original settings */
for(i = 0; i < SYSDEP_MIXER_CHANNELS; i++)
{
if(mixer->channel_available[i])
{
#ifdef SYSDEP_MIXER_DEBUG
fprintf(stderr, "debug: mixer got channel %s\n",
sysdep_mixer_names[i]);
#endif
if(mixer->get(mixer, i, &mixer->cache_left[i],
&mixer->cache_right[i]))
{
sysdep_mixer_destroy(mixer);
return NULL;
}
mixer->orig_left[i] = mixer->cache_left[i];
mixer->orig_right[i] = mixer->cache_right[i];
}
}
/* save our flags */
mixer->flags = flags;
return mixer;
}
void sysdep_mixer_destroy(struct sysdep_mixer_struct *mixer)
{
int i, left, right;
/* restore orig settings if requested */
for(i = 0; i < SYSDEP_MIXER_CHANNELS; i++)
{
/* check that the channel wasn't modified under our ass */
sysdep_mixer_get(mixer, i, &left, &right);
if(mixer->restore_channel[i])
{
#ifdef SYSDEP_MIXER_DEBUG
fprintf(stderr, "debug: sysdep_mixer: restoring channel %s\n",
sysdep_mixer_names[i]);
#endif
sysdep_mixer_set(mixer, i, mixer->orig_left[i],
mixer->orig_right[i]);
}
}
mixer->destroy(mixer);
}
int sysdep_mixer_channel_available(struct sysdep_mixer_struct *mixer,
int channel)
{
return mixer->channel_available[channel];
}
int sysdep_mixer_set(struct sysdep_mixer_struct *mixer, int channel,
int left, int right)
{
if(!mixer->channel_available[channel])
return -1;
if(mixer->set(mixer, channel, left, right))
return -1;
mixer->cache_left[channel] = left;
mixer->cache_right[channel] = right;
if(mixer->flags & SYSDEP_MIXER_RESTORE_SETTINS_ON_EXIT)
mixer->restore_channel[channel] = 1;
return 0;
}
int sysdep_mixer_get(struct sysdep_mixer_struct *mixer, int channel,
int *left, int *right)
{
if(!mixer->channel_available[channel])
return -1;
if(mixer->get(mixer, channel, left, right))
return -1;
/* if we're close to the cached values use the cache, to avoid repeated
calls to get->set, causing the volume to slide */
if((*left >= (mixer->cache_left[channel] - 5)) &&
(*left <= (mixer->cache_left[channel] + 5)) &&
(*right >= (mixer->cache_right[channel] - 5)) &&
(*right <= (mixer->cache_right[channel] + 5)))
{
#ifdef SYSDEP_MIXER_DEBUG
fprintf(stderr, "debug: sysdep_mixer: cached\n");
#endif
*left = mixer->cache_left[channel];
*right = mixer->cache_right[channel];
}
else
{
#ifdef SYSDEP_MIXER_DEBUG
fprintf(stderr, "debug: sysdep_mixer: modified under our ass\n");
#endif
/* The channel was modified under our ass, no need to restore it anymore.
Save the new values as original values, so that if we change it
later on we restore the new values */
mixer->restore_channel[channel] = 0;
mixer->cache_left[channel] = *left;
mixer->cache_right[channel] = *right;
mixer->orig_left[channel] = *left;
mixer->orig_right[channel] = *right;
}
return 0;
}
| 29.507576 | 79 | 0.681772 | [
"object"
] |
a92d19fc3d02882ce3adf475cff0acb5cc3d49d1 | 16,099 | h | C | include/labeling3D_he_2011_run.h | attltb/YACCLAB | 54daa48bc44331897051b392f30cab760573e913 | [
"BSD-3-Clause"
] | 147 | 2016-05-29T22:10:43.000Z | 2022-03-28T15:39:06.000Z | include/labeling3D_he_2011_run.h | attltb/YACCLAB | 54daa48bc44331897051b392f30cab760573e913 | [
"BSD-3-Clause"
] | 13 | 2016-11-25T15:27:55.000Z | 2021-12-22T09:41:21.000Z | include/labeling3D_he_2011_run.h | attltb/YACCLAB | 54daa48bc44331897051b392f30cab760573e913 | [
"BSD-3-Clause"
] | 38 | 2016-04-13T07:42:31.000Z | 2022-03-31T07:48:27.000Z | // Copyright (c) 2020, the YACCLAB contributors, as
// shown by the AUTHORS file. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
#ifndef YACCLAB_LABELING3D_HE_2011_RUN_H_
#define YACCLAB_LABELING3D_HE_2011_RUN_H_
#include <opencv2/core.hpp>
#include "labeling_algorithms.h"
#include "labels_solver.h"
#include "memory_tester.h"
struct Run
{
uint16_t start = 0;
uint16_t end = 0;
unsigned label = 0;
};
class Table3D
{
public:
size_t d_;
size_t h_;
size_t max_runs_;
Run *data_; // This vector stores run data for each row of each slice
uint16_t *sizes_; // This vector stores the number of runs actually contained in each row of each slice
void Setup(size_t d, size_t h, size_t w)
{
d_ = d;
h_ = h;
max_runs_ = w / 2 + 1;
}
double Alloc(PerformanceEvaluator& perf)
{
perf.start();
data_ = new Run[d_ * h_ * max_runs_];
sizes_ = new uint16_t[d_ * h_];
memset(data_, 0, d_ * h_ * max_runs_ * sizeof(Run));
memset(sizes_, 0, d_ * h_ * sizeof(uint16_t));
perf.stop();
double t = perf.last();
perf.start();
memset(data_, 0, d_ * h_ * max_runs_ * sizeof(Run));
memset(sizes_, 0, d_ * h_ * sizeof(uint16_t));
perf.stop();
return t - perf.last();
}
void Alloc()
{
data_ = new Run[d_ * h_ * max_runs_];
sizes_ = new uint16_t[d_ * h_];
}
void Dealloc()
{
delete[] data_;
delete[] sizes_;
}
};
template <typename LabelsSolver>
class RBTS_3D : public Labeling3D<Connectivity3D::CONN_26>
{
public:
RBTS_3D() {}
Table3D runs;
static inline int ProcessRun(uint16_t row_index, uint16_t row_nruns, Run* row_runs, Run* cur_run, bool *new_label)
{
// Discard previous non connected runs (step "2" of the 2D algorithm)
for (;
row_index < row_nruns &&
row_runs[row_index].end < cur_run->start - 1;
++row_index) {
}
// Get label (step "3A" of the 2D algorithm)
if (row_index < row_nruns &&
row_runs[row_index].start <= cur_run->end + 1) {
if (*new_label) {
cur_run->label = row_runs[row_index].label;
*new_label = false;
}
else {
LabelsSolver::Merge(cur_run->label, row_runs[row_index].label);
}
}
// Merge label (step "3B" of the 2D algorithm)
for (;
row_index < row_nruns &&
row_runs[row_index].end <= cur_run->end;
++row_index) {
LabelsSolver::Merge(cur_run->label, row_runs[row_index].label);
}
// Get label without "removing the run" (step "4" of the 2D algorithm)
// the skip step is not required in this case because this algorithm does not employ
// a circular buffer.
if (row_index < row_nruns &&
row_runs[row_index].start <= cur_run->end + 1) {
LabelsSolver::Merge(cur_run->label, row_runs[row_index].label);
}
return row_index;
}
void PerformLabeling()
{
int d = img_.size.p[0];
int h = img_.size.p[1];
int w = img_.size.p[2];
img_labels_.create(3, img_.size.p, CV_32SC1);
memset(img_labels_.data, 0, img_labels_.dataend - img_labels_.datastart);
runs.Setup(d, h, w);
runs.Alloc();
LabelsSolver::Alloc(UPPER_BOUND_26_CONNECTIVITY); // Memory allocation of the labels solver
LabelsSolver::Setup(); // Labels solver initialization
// First scan
Run* run_slice00_row00 = runs.data_;
uint16_t* nruns_slice00_row00 = runs.sizes_;
for (int s = 0; s < d; s++) {
for (int r = 0; r < h; r++) {
// Row pointers for the input image
const unsigned char* const img_slice00_row00 = img_.ptr<unsigned char>(s, r);
int slice11_row00_index = 0;
int slice11_row11_index = 0;
int slice11_row01_index = 0;
int slice00_row11_index = 0;
int nruns = 0;
Run* run_slice11_row00 = run_slice00_row00 - (runs.max_runs_) * runs.h_;
Run* run_slice11_row11 = run_slice11_row00 - (runs.max_runs_);
Run* run_slice11_row01 = run_slice11_row00 + (runs.max_runs_);
Run* run_slice00_row11 = run_slice00_row00 - (runs.max_runs_);
uint16_t* nruns_slice11_row00 = nruns_slice00_row00 - h;
uint16_t* nruns_slice11_row11 = nruns_slice11_row00 - 1;
uint16_t* nruns_slice11_row01 = nruns_slice11_row00 + 1;
uint16_t* nruns_slice00_row11 = nruns_slice00_row00 - 1;
for (int c = 0; c < w; c++) {
// Is there a new run ?
if (img_slice00_row00[c] == 0) {
continue;
}
// Yes (new run)
bool new_label = true;
run_slice00_row00[nruns].start = c; // We start from 1 because 0 is a "special" run
// to store additional info
for (; c < w && img_slice00_row00[c] > 0; ++c) {}
run_slice00_row00[nruns].end = c - 1;
if (s > 0) {
if (r > 0) {
slice11_row11_index = ProcessRun(slice11_row11_index, // uint16_t row_index
*nruns_slice11_row11, // uint16_t row_nruns
run_slice11_row11, // Run* row_runs
&run_slice00_row00[nruns], // Run* cur_run
&new_label // bool *new_label
);
}
slice11_row00_index = ProcessRun(slice11_row00_index, // uint16_t row_index
*nruns_slice11_row00, // uint16_t row_nruns
run_slice11_row00, // Run* row_runs
&run_slice00_row00[nruns], // Run* cur_run
&new_label // bool *new_label
);
if (r < h - 1) {
slice11_row01_index = ProcessRun(slice11_row01_index, // uint16_t row_index
*nruns_slice11_row01, // uint16_t row_nruns
run_slice11_row01, // Run* row_runs
&run_slice00_row00[nruns], // Run* cur_run
&new_label // bool *new_label
);
}
}
if (r > 0) {
slice00_row11_index = ProcessRun(slice00_row11_index, // uint16_t row_index
*nruns_slice00_row11, // uint16_t row_nruns
run_slice00_row11, // Run* row_runs
&run_slice00_row00[nruns], // Run* cur_run
&new_label // bool *new_label
);
}
if (new_label) {
run_slice00_row00[nruns].label = LabelsSolver::NewLabel();
}
nruns++;
} // Columns cycle end
run_slice00_row00 += (runs.max_runs_);
(*nruns_slice00_row00++) = nruns;
} // Rows cycle end
} // Planes cycle end
// Second scan
LabelsSolver::Flatten();
int* img_row = reinterpret_cast<int*>(img_labels_.data);
Run* run_row = runs.data_;
uint16_t* nruns = runs.sizes_;
for (int s = 0; s < d; s++) {
for (int r = 0; r < h; r++) {
for (int id = 0; id < *nruns; id++) {
for (int c = run_row[id].start; c <= run_row[id].end; ++c) {
img_row[c] = LabelsSolver::GetLabel(run_row[id].label);
}
}
run_row += (runs.max_runs_);
img_row += img_labels_.step[1] / sizeof(int);
nruns++;
}
}
LabelsSolver::Dealloc(); // Memory deallocation of the labels solver
runs.Dealloc(); // Memory deallocation of the Table3D
}
void PerformLabelingWithSteps()
{
double alloc_timing = Alloc();
perf_.start();
FirstScan();
perf_.stop();
perf_.store(Step(StepType::FIRST_SCAN), perf_.last());
perf_.start();
SecondScan();
perf_.stop();
perf_.store(Step(StepType::SECOND_SCAN), perf_.last());
perf_.start();
Dealloc();
perf_.stop();
perf_.store(Step(StepType::ALLOC_DEALLOC), perf_.last() + alloc_timing);
}
private:
double Alloc()
{
// Memory allocation of the labels solver
double ls_t = LabelsSolver::Alloc(UPPER_BOUND_26_CONNECTIVITY, perf_);
// Memory allocation of Table3D
runs.Setup(img_.size.p[0], img_.size.p[1], img_.size.p[2]);
ls_t += runs.Alloc(perf_);
// Memory allocation for the output image
perf_.start();
img_labels_.create(3, img_.size.p, CV_32SC1);
memset(img_labels_.data, 0, img_labels_.dataend - img_labels_.datastart);
perf_.stop();
double t = perf_.last();
perf_.start();
memset(img_labels_.data, 0, img_labels_.dataend - img_labels_.datastart);
perf_.stop();
double ma_t = t - perf_.last();
// Return total time
return ls_t + ma_t;
}
void Dealloc()
{
LabelsSolver::Dealloc();
runs.Dealloc();
// No free for img_labels_ because it is required at the end of the algorithm
}
void FirstScan()
{
int d = img_.size.p[0];
int h = img_.size.p[1];
int w = img_.size.p[2];
memset(img_labels_.data, 0, img_labels_.dataend - img_labels_.datastart);
LabelsSolver::Setup(); // Labels solver initialization
// First scan
Run* run_slice00_row00 = runs.data_;
uint16_t* nruns_slice00_row00 = runs.sizes_;
for (int s = 0; s < d; s++) {
for (int r = 0; r < h; r++) {
// Row pointers for the input image
const unsigned char* const img_slice00_row00 = img_.ptr<unsigned char>(s, r);
int slice11_row00_index = 0;
int slice11_row11_index = 0;
int slice11_row01_index = 0;
int slice00_row11_index = 0;
int nruns = 0;
Run* run_slice11_row00 = run_slice00_row00 - (runs.max_runs_) * runs.h_;
Run* run_slice11_row11 = run_slice11_row00 - (runs.max_runs_);
Run* run_slice11_row01 = run_slice11_row00 + (runs.max_runs_);
Run* run_slice00_row11 = run_slice00_row00 - (runs.max_runs_);
uint16_t* nruns_slice11_row00 = nruns_slice00_row00 - h;
uint16_t* nruns_slice11_row11 = nruns_slice11_row00 - 1;
uint16_t* nruns_slice11_row01 = nruns_slice11_row00 + 1;
uint16_t* nruns_slice00_row11 = nruns_slice00_row00 - 1;
for (int c = 0; c < w; c++) {
// Is there a new run ?
if (img_slice00_row00[c] == 0) {
continue;
}
// Yes (new run)
bool new_label = true;
run_slice00_row00[nruns].start = c; // We start from 1 because 0 is a "special" run
// to store additional info
for (; c < w && img_slice00_row00[c] > 0; ++c) {}
run_slice00_row00[nruns].end = c - 1;
if (s > 0) {
if (r > 0) {
slice11_row11_index = ProcessRun(slice11_row11_index, // uint16_t row_index
*nruns_slice11_row11, // uint16_t row_nruns
run_slice11_row11, // Run* row_runs
&run_slice00_row00[nruns], // Run* cur_run
&new_label // bool *new_label
);
}
slice11_row00_index = ProcessRun(slice11_row00_index, // uint16_t row_index
*nruns_slice11_row00, // uint16_t row_nruns
run_slice11_row00, // Run* row_runs
&run_slice00_row00[nruns], // Run* cur_run
&new_label // bool *new_label
);
if (r < h - 1) {
slice11_row01_index = ProcessRun(slice11_row01_index, // uint16_t row_index
*nruns_slice11_row01, // uint16_t row_nruns
run_slice11_row01, // Run* row_runs
&run_slice00_row00[nruns], // Run* cur_run
&new_label // bool *new_label
);
}
}
if (r > 0) {
slice00_row11_index = ProcessRun(slice00_row11_index, // uint16_t row_index
*nruns_slice00_row11, // uint16_t row_nruns
run_slice00_row11, // Run* row_runs
&run_slice00_row00[nruns], // Run* cur_run
&new_label // bool *new_label
);
}
if (new_label) {
run_slice00_row00[nruns].label = LabelsSolver::NewLabel();
}
nruns++;
} // Columns cycle end
run_slice00_row00 += (runs.max_runs_);
(*nruns_slice00_row00++) = nruns;
} // Rows cycle end
} // Planes cycle end
}
void SecondScan()
{
int d = img_.size.p[0];
int h = img_.size.p[1];
// int w = img_.size.p[2];
// Second scan
LabelsSolver::Flatten();
int* img_row = reinterpret_cast<int*>(img_labels_.data);
Run* run_row = runs.data_;
uint16_t* nruns = runs.sizes_;
for (int s = 0; s < d; s++) {
for (int r = 0; r < h; r++) {
for (int id = 0; id < *nruns; id++) {
for (int c = run_row[id].start; c <= run_row[id].end; ++c) {
img_row[c] = LabelsSolver::GetLabel(run_row[id].label);
}
}
run_row += (runs.max_runs_);
img_row += img_labels_.step[1] / sizeof(int);
nruns++;
}
}
}
};
#endif // YACCLAB_LABELING3D_HE_2011_RUN_H_ | 39.265854 | 118 | 0.468538 | [
"vector"
] |
a930b16794d0fc1c3f36d1d9cbe2c011bfba3260 | 6,311 | h | C | gc/libatomic_ops/src/atomic_ops/sysdeps/ibmc/powerpc.h | eval-apply/Gauche | 446507510afbecf80f522af972010bcfeb2ea0a8 | [
"BSD-3-Clause"
] | 569 | 2015-01-14T07:51:32.000Z | 2022-03-28T02:47:37.000Z | gc/libatomic_ops/src/atomic_ops/sysdeps/ibmc/powerpc.h | eval-apply/Gauche | 446507510afbecf80f522af972010bcfeb2ea0a8 | [
"BSD-3-Clause"
] | 612 | 2015-01-26T02:17:56.000Z | 2022-03-26T10:02:28.000Z | gc/libatomic_ops/src/atomic_ops/sysdeps/ibmc/powerpc.h | eval-apply/Gauche | 446507510afbecf80f522af972010bcfeb2ea0a8 | [
"BSD-3-Clause"
] | 104 | 2015-01-14T09:18:01.000Z | 2022-03-05T02:51:48.000Z |
/* Memory model documented at http://www-106.ibm.com/developerworks/ */
/* eserver/articles/archguide.html and (clearer) */
/* http://www-106.ibm.com/developerworks/eserver/articles/powerpc.html. */
/* There appears to be no implicit ordering between any kind of */
/* independent memory references. */
/* Architecture enforces some ordering based on control dependence. */
/* I don't know if that could help. */
/* Data-dependent loads are always ordered. */
/* Based on the above references, eieio is intended for use on */
/* uncached memory, which we don't support. It does not order loads */
/* from cached memory. */
/* Thanks to Maged Michael, Doug Lea, and Roger Hoover for helping to */
/* track some of this down and correcting my misunderstandings. -HB */
#include "../all_aligned_atomic_load_store.h"
#include "../test_and_set_t_is_ao_t.h"
void AO_sync(void);
#pragma mc_func AO_sync { "7c0004ac" }
#ifdef __NO_LWSYNC__
# define AO_lwsync AO_sync
#else
void AO_lwsync(void);
#pragma mc_func AO_lwsync { "7c2004ac" }
#endif
#define AO_nop_write() AO_lwsync()
#define AO_HAVE_nop_write
#define AO_nop_read() AO_lwsync()
#define AO_HAVE_nop_read
/* We explicitly specify load_acquire and store_release, since these */
/* rely on the fact that lwsync is also a LoadStore barrier. */
AO_INLINE AO_t
AO_load_acquire(const volatile AO_t *addr)
{
AO_t result = *addr;
AO_lwsync();
return result;
}
#define AO_HAVE_load_acquire
AO_INLINE void
AO_store_release(volatile AO_t *addr, AO_t value)
{
AO_lwsync();
*addr = value;
}
#define AO_HAVE_store_release
#ifndef AO_PREFER_GENERALIZED
/* This is similar to the code in the garbage collector. Deleting */
/* this and having it synthesized from compare_and_swap would probably */
/* only cost us a load immediate instruction. */
AO_INLINE AO_TS_VAL_t
AO_test_and_set(volatile AO_TS_t *addr) {
#if defined(__powerpc64__) || defined(__ppc64__) || defined(__64BIT__)
/* Completely untested. And we should be using smaller objects anyway. */
unsigned long oldval;
unsigned long temp = 1; /* locked value */
__asm__ __volatile__(
"1:ldarx %0,0,%1\n" /* load and reserve */
"cmpdi %0, 0\n" /* if load is */
"bne 2f\n" /* non-zero, return already set */
"stdcx. %2,0,%1\n" /* else store conditional */
"bne- 1b\n" /* retry if lost reservation */
"2:\n" /* oldval is zero if we set */
: "=&r"(oldval)
: "r"(addr), "r"(temp)
: "memory", "cr0");
#else
int oldval;
int temp = 1; /* locked value */
__asm__ __volatile__(
"1:lwarx %0,0,%1\n" /* load and reserve */
"cmpwi %0, 0\n" /* if load is */
"bne 2f\n" /* non-zero, return already set */
"stwcx. %2,0,%1\n" /* else store conditional */
"bne- 1b\n" /* retry if lost reservation */
"2:\n" /* oldval is zero if we set */
: "=&r"(oldval)
: "r"(addr), "r"(temp)
: "memory", "cr0");
#endif
return (AO_TS_VAL_t)oldval;
}
#define AO_HAVE_test_and_set
AO_INLINE AO_TS_VAL_t
AO_test_and_set_acquire(volatile AO_TS_t *addr) {
AO_TS_VAL_t result = AO_test_and_set(addr);
AO_lwsync();
return result;
}
#define AO_HAVE_test_and_set_acquire
AO_INLINE AO_TS_VAL_t
AO_test_and_set_release(volatile AO_TS_t *addr) {
AO_lwsync();
return AO_test_and_set(addr);
}
#define AO_HAVE_test_and_set_release
AO_INLINE AO_TS_VAL_t
AO_test_and_set_full(volatile AO_TS_t *addr) {
AO_TS_VAL_t result;
AO_lwsync();
result = AO_test_and_set(addr);
AO_lwsync();
return result;
}
#define AO_HAVE_test_and_set_full
#endif /* !AO_PREFER_GENERALIZED */
AO_INLINE AO_t
AO_fetch_compare_and_swap(volatile AO_t *addr, AO_t old_val, AO_t new_val)
{
AO_t fetched_val;
# if defined(__powerpc64__) || defined(__ppc64__) || defined(__64BIT__)
__asm__ __volatile__(
"1:ldarx %0,0,%1\n" /* load and reserve */
"cmpd %0, %3\n" /* if load is not equal to */
"bne 2f\n" /* old_val, fail */
"stdcx. %2,0,%1\n" /* else store conditional */
"bne- 1b\n" /* retry if lost reservation */
"2:\n"
: "=&r"(fetched_val)
: "r"(addr), "r"(new_val), "r"(old_val)
: "memory", "cr0");
# else
__asm__ __volatile__(
"1:lwarx %0,0,%1\n" /* load and reserve */
"cmpw %0, %3\n" /* if load is not equal to */
"bne 2f\n" /* old_val, fail */
"stwcx. %2,0,%1\n" /* else store conditional */
"bne- 1b\n" /* retry if lost reservation */
"2:\n"
: "=&r"(fetched_val)
: "r"(addr), "r"(new_val), "r"(old_val)
: "memory", "cr0");
# endif
return fetched_val;
}
#define AO_HAVE_fetch_compare_and_swap
AO_INLINE AO_t
AO_fetch_compare_and_swap_acquire(volatile AO_t *addr, AO_t old_val,
AO_t new_val)
{
AO_t result = AO_fetch_compare_and_swap(addr, old_val, new_val);
AO_lwsync();
return result;
}
#define AO_HAVE_fetch_compare_and_swap_acquire
AO_INLINE AO_t
AO_fetch_compare_and_swap_release(volatile AO_t *addr, AO_t old_val,
AO_t new_val)
{
AO_lwsync();
return AO_fetch_compare_and_swap(addr, old_val, new_val);
}
#define AO_HAVE_fetch_compare_and_swap_release
AO_INLINE AO_t
AO_fetch_compare_and_swap_full(volatile AO_t *addr, AO_t old_val,
AO_t new_val)
{
AO_t result;
AO_lwsync();
result = AO_fetch_compare_and_swap(addr, old_val, new_val);
AO_lwsync();
return result;
}
#define AO_HAVE_fetch_compare_and_swap_full
/* TODO: Implement AO_fetch_and_add, AO_and/or/xor directly. */
| 34.298913 | 74 | 0.590081 | [
"model"
] |
a931410985d90df0772999a498f9085495910bb4 | 1,579 | h | C | tests/sources/basic/65-testStatic_c/src/Block.h | mF2C/COMPSsOLD | ba5727e818735fd45fba4e9793cefe40456b2e1e | [
"Apache-2.0"
] | 1 | 2020-11-25T13:01:27.000Z | 2020-11-25T13:01:27.000Z | tests/sources/basic/65-testStatic_c/src/Block.h | mF2C/COMPSsOLD | ba5727e818735fd45fba4e9793cefe40456b2e1e | [
"Apache-2.0"
] | 1 | 2019-11-13T14:30:21.000Z | 2019-11-13T14:30:21.000Z | tests/sources/basic/65-testStatic_c/src/Block.h | mF2C/COMPSsOLD | ba5727e818735fd45fba4e9793cefe40456b2e1e | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2002-2015 Barcelona Supercomputing Center (www.bsc.es)
*
* 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 BLOCK_H
#define BLOCK_H
#include <iostream>
#include <vector>
#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/serialization/serialization.hpp>
#include <boost/serialization/access.hpp>
#include <boost/serialization/vector.hpp>
using namespace std;
using namespace boost;
using namespace serialization;
class Block {
public:
Block(){};
Block(int bSize);
void init(int bSize, double initVal);
static Block create( int bSize, double initVal);
static void generate(Block *b, int bSize, double initVal);
void multiply(Block *block1, Block *block2);
void print();
void result();
std::vector< std::vector< double > > data;
private:
int M;
friend class::serialization::access;
template<class Archive>
void serialize(Archive & ar, const unsigned int version) {
ar & M;
if (Archive::is_loading::value){
data.clear();
}
ar & data;
}
};
#endif
| 23.220588 | 76 | 0.725776 | [
"vector"
] |
a93402317c88cd0e99669a3b81c7f89a234771e1 | 40,492 | h | C | valhalla/baldr/directededge.h | PointzOfficial/valhalla_public_fork | 8313c4b9636b8a3fa6c6920b20012d8da730b24e | [
"MIT"
] | null | null | null | valhalla/baldr/directededge.h | PointzOfficial/valhalla_public_fork | 8313c4b9636b8a3fa6c6920b20012d8da730b24e | [
"MIT"
] | null | null | null | valhalla/baldr/directededge.h | PointzOfficial/valhalla_public_fork | 8313c4b9636b8a3fa6c6920b20012d8da730b24e | [
"MIT"
] | null | null | null | #ifndef VALHALLA_BALDR_DIRECTEDEDGE_H_
#define VALHALLA_BALDR_DIRECTEDEDGE_H_
#include <cstdint>
#include <valhalla/baldr/graphconstants.h>
#include <valhalla/baldr/graphid.h>
#include <valhalla/baldr/json.h>
#include <valhalla/baldr/turn.h>
namespace valhalla {
namespace baldr {
/**
* Directed edge within the graph.
*/
class DirectedEdge {
public:
/**
* Constructor
*/
DirectedEdge();
/**
* Gets the end node of this directed edge.
* @return Returns the end node.
*/
GraphId endnode() const {
return GraphId(endnode_);
}
/**
* Set the end node of this directed edge.
* @param endnode End node of the directed link.
*/
void set_endnode(const GraphId& endnode);
/**
* Gets the free flow speed in KPH.
* @return Returns the free flow speed in KPH.
*/
uint32_t free_flow_speed() const {
return free_flow_speed_;
}
/**
* Sets the free flow speed in KPH.
* @param free flow Speed in KPH.
*/
void set_free_flow_speed(const uint32_t speed);
/**
* Gets the constrained flow speed in KPH.
* @return Returns the constrained flow speed in KPH.
*/
uint32_t constrained_flow_speed() const {
return constrained_flow_speed_;
}
/**
* Sets the constrained flow speed in KPH.
* @param constrained flow Speed in KPH.
*/
void set_constrained_flow_speed(const uint32_t speed);
/**
* Flag indicating the edge has predicted speed records.
* @return Returns true if this edge has predicted speed records.
*/
bool has_predicted_speed() const {
return has_predicted_speed_;
}
/**
* Indicates whether the edge has either predicted, free or constrained flow speeds.
* @return Returns true if this edge has any flow speeds.
*/
bool has_flow_speed() const {
return free_flow_speed_ > 0 || constrained_flow_speed_ > 0 || has_predicted_speed_;
}
/**
* Set the flag indicating the edge has turn lanes at the end of the edge.
* @param lanes True if this edge has turn lane records.
*/
void set_turnlanes(const bool lanes) {
turnlanes_ = lanes;
}
/**
* Flag indicating the edge has turn lanes at the end of the edge.
* @return Returns true if this edge has turn lane records.
*/
bool turnlanes() const {
return turnlanes_;
}
/**
* Set the flag indicating the edge has predicted speed records.
* @param p True if this edge has predicted speed records
*/
void set_has_predicted_speed(const bool p);
/**
* Offset to the common edge data. The offset is from the start
* of the common edge information within a tile.
* @return Returns offset from the start of the edge info within a tile.
*/
uint64_t edgeinfo_offset() const {
return edgeinfo_offset_;
}
/**
* Set the offset to the common edge info. The offset is from the start
* of the common edge info within a tile.
* @param offset Offset from the start of the edge info within a tile.
*/
void set_edgeinfo_offset(const uint32_t offset);
/**
* General restriction or access condition (per mode) for this directed edge.
* @return Returns the restriction for the directed edge.
*/
uint64_t access_restriction() const {
return access_restriction_;
}
/**
* Set the modes which have access restrictions on this edge.
* @param access Modes with access restrictions.
*/
void set_access_restriction(const uint32_t access);
/**
* Does this directed edge have signs?
* @return Returns true if the directed edge has signs,
* false if not.
*/
bool sign() const {
return sign_;
}
/**
* Sets the sign flag.
* @param sign True if this directed edge has signs, false if not.
*/
void set_sign(const bool sign);
/**
* Does this directed edge have the lane connectivity?
* @return Returns true if the directed edge has the lane connectivity,
* false if not.
*/
bool laneconnectivity() const {
return lane_conn_;
}
/**
* Sets the lane connectivity flag.
* @param lc True if this directed edge has lane connectivity.
*/
void set_laneconnectivity(const bool lc);
/**
* Gets the length of the edge in meters.
* @return Returns the length in meters.
*/
uint32_t length() const {
return length_;
}
/**
* Sets the length of the edge in meters.
* @param length Length of the edge in meters.
* @param should_error Bool indicating whether or not to error or warn on length > kMaxEdgeLength
*
*/
void set_length(const uint32_t length, bool should_error = true);
/**
* Get the weighted grade factor
* @return Returns the weighted grade factor (0-15).
* where 0 is a -10% grade and 15 is 15%
*/
uint32_t weighted_grade() const {
return weighted_grade_;
}
/**
* Sets the weighted grade factor (0-15) for the edge.
* @param factor Weighted grade factor.
*/
void set_weighted_grade(const uint32_t factor);
/**
* Gets the maximum upward slope. Uses 1 degree precision for slopes to 16
* degrees and 4 degree precision afterwards (up to a max of 76 degrees).
* @return Returns the maximum upward slope (0 to 76 degrees).
*/
int max_up_slope() const {
return ((max_up_slope_ & 0x10) == 0) ? max_up_slope_ : 16 + ((max_up_slope_ & 0xf) * 4);
}
/**
* Sets the maximum upward slope. If slope is negative, 0 is set.
* @param slope Maximum upward slope (degrees).
*/
void set_max_up_slope(const float slope);
/**
* Gets the maximum downward slope. Uses 1 degree precision for slopes to
* -16 degrees, and 4 degree precision afterwards (up to a max of -76 degs).
* @return Returns the maximum downward slope (0 to -76 degrees).
*/
int max_down_slope() const {
return ((max_down_slope_ & 0x10) == 0) ? -static_cast<int>(max_down_slope_)
: -static_cast<int>(16 + ((max_down_slope_ & 0xf) * 4));
}
/**
* Sets the maximum downward slope. If slope is positive, 0 is set.
* @param slope Maximum downward slope (degrees).
*/
void set_max_down_slope(const float slope);
/**
* Get the road curvature factor.
* @return Returns the curvature factor (0-15).
*/
uint32_t curvature() const {
return curvature_;
}
/**
* Sets the curvature factor (0-16) for the edge.
* @param factor Curvature factor.
*/
void set_curvature(const uint32_t factor);
/**
* Flag indicating the edge is a dead end (no other driveable
* roads at the end node of this edge).
* @return Returns true if this edge is a dead end.
*/
bool deadend() const {
return deadend_;
}
/**
* Set the flag indicating the edge is a dead end (no other driveable
* roads at the end node of this edge).
* @param d True if this edge is a dead end.
*/
void set_deadend(const bool d);
/**
* Does this edge have a toll or is it part of a toll road?
* @return Returns true if this edge is part of a toll road, false if not.
*/
bool toll() const {
return toll_;
}
/**
* Sets the flag indicating this edge has a toll or is it part of
* a toll road.
* @param toll True if this edge is part of a toll road, false if not.
*/
void set_toll(const bool toll);
/**
* Does this edge have a seasonal access (e.g., closed in the winter)?
* @return Returns true if this edge has seasonal access, false if not.
*/
bool seasonal() const {
return seasonal_;
}
/**
* Sets the flag indicating this edge has seasonal access.
* @param seasonal True if this edge has seasonal access, false if not.
*/
void set_seasonal(const bool seasonal);
/**
* Is this edge part of a private or no through road that allows access
* only if required to get to a destination?
* @return Returns true if the edge is destination only / private access.
*/
bool destonly() const {
return dest_only_;
}
/**
* Sets the destination only (private) flag. This indicates the edge should
* allow access only to locations that are destinations and not allow
* "through" traffic
* @param destonly True if the edge is private (allows access to
* destination only), false if not.
*/
void set_dest_only(const bool destonly);
/**
* Is this edge part of a tunnel?
* @return Returns true if this edge is part of a tunnel, false if not.
*/
bool tunnel() const {
return tunnel_;
}
/**
* Sets the flag indicating this edge has is a tunnel of part of a tunnel.
* @param tunnel True if the edge is a tunnel, false if not.
*/
void set_tunnel(const bool tunnel);
/**
* Is this edge part of a bridge?
* @return Returns true if this edge is part of a bridge, false if not.
*/
bool bridge() const {
return bridge_;
}
/**
* Sets the flag indicating this edge has is a bridge of part of a bridge.
* @param bridge True if the edge is a bridge, false if not.
*/
void set_bridge(const bool bridge);
/**
* Is this edge indoor?
* @return Returns true if this edge is indoor, false if not (outdoor).
*/
bool indoor() const {
return indoor_;
}
/**
* Sets the flag indicating this edge is indoor.
* @param indoor True if the edge is indoor, false if not (outdoor).
*/
void set_indoor(const bool indoor);
/**
* Get the HOV type (see graphconstants.h).
*/
HOVEdgeType hov_type() const {
return static_cast<baldr::HOVEdgeType>(hov_type_);
}
/**
* Sets the hov type (see baldr/graphconstants.h)
* @param hov_type HOV type.
*/
void set_hov_type(const HOVEdgeType hov_type);
/**
* Returns t/f if this edge is HOV only.
* @return
*/
bool is_hov_only() const;
/**
* Is this edge part of a roundabout?
* @return Returns true if this edge is part of a roundabout, false if not.
*/
bool roundabout() const {
return roundabout_;
}
/**
* Sets the flag indicating the edge is part of a roundabout.
* @param roundabout True if the edge is part of a roundabout, false if not.
*/
void set_roundabout(const bool roundabout);
/**
* A traffic signal occurs at the end of this edge.
* @return Returns true if a traffic signal is present at the end of the
* directed edge.
*/
bool traffic_signal() const {
return traffic_signal_;
}
/**
* Sets the flag indicating a traffic signal is present at the end of
* this edge.
* @param signal True if a traffic signal exists at the end of this edge,
* false if not.
*/
void set_traffic_signal(const bool signal);
/**
* A stop sign occurs at the end of this edge.
* @return Returns true if a stop sign is present at the end of the
* directed edge.
*/
bool stop_sign() const {
return stop_sign_;
}
/**
* Sets the flag indicating a stop sign is present at the end of
* this edge.
* @param sign True if a stop sign exists at the end of this edge,
* false if not.
*/
void set_stop_sign(const bool sign);
/**
* A yield/give way sign occurs at the end of this edge.
* @return Returns true if a yield/give way sign is present at the end of the
* directed edge.
*/
bool yield_sign() const {
return yield_sign_;
}
/**
* Sets the flag indicating a yield/give way sign is present at the end of
* this edge.
* @param sign True if a yield/give way sign exists at the end of this edge,
* false if not.
*/
void set_yield_sign(const bool sign);
/**
* Is this directed edge stored forward in edgeinfo (true) or
* reverse (false).
* @return Returns true if stored forward, false if reverse.
*/
bool forward() const {
return forward_;
}
/**
* Set the forward flag. Tells if this directed edge is stored forward
* in edgeinfo (true) or reverse (false).
* @param forward Forward flag.
* */
void set_forward(const bool forward);
/**
* Edge leads to a "no thru" region where there are no exits other than
* the incoming edge. This flag is populated by processing the graph to
* identify such edges. This is used to speed pedestrian routing.
* @return Returns true if the edge leads into a no thru region.
*/
bool not_thru() const {
return not_thru_;
}
/**
* Set the not_thru flag. If an edge leads to a "no thru" region where
* there are no exits other than the incoming edge. This flag is populated
* by processing the graph toidentify such edges.
* @param not_thru True if the edge leads into a no thru region.
*/
void set_not_thru(const bool not_thru);
/**
* Get the index of the opposing directed edge at the end node of this
* directed edge. Can be used to find the start node of this directed edge.
* @return Returns the index of the opposing directed edge at the end node
* of this directed edge.
*/
uint32_t opp_index() const {
return opp_index_;
}
/**
* Set the index of the opposing directed edge at the end node of this
* directed edge.
* @param opp_index Opposing directed edge index at the end node.
* */
void set_opp_index(const uint32_t opp_index);
/**
* Get the cycle lane type along this edge. If the edge's use is cycleway, footway or path,
* then cyclelane holds information based on how separated cyclists are from pedestrians
* @returns Returns the type (if any) of bicycle lane along this edge.
*/
CycleLane cyclelane() const {
return static_cast<CycleLane>(cycle_lane_);
}
/**
* Sets the type of cycle lane (if any) present on this edge.
* If edge use is cycleway, footway or path, then cyclelane should represent
* segregation from pedestrians
* @param cyclelane Type of cycle lane.
*/
void set_cyclelane(const CycleLane cyclelane);
/**
* Get the bike network flag for this directed edge.
* @return Returns the bike network flag. This is true if the edge is part of any
* bike network. They type(s) of bike networks are stored in EdgeInfo.
*/
bool bike_network() const {
return bike_network_;
}
/**
* Sets the bike network flag.
* @param bike_network Bicycle network flag. True if edge is part of any bike network.
*/
void set_bike_network(const bool bike_network);
/**
* Get the truck route flag for this directed edge.
* @return Returns true if part of a truck network/route, false otherwise.
*/
bool truck_route() const {
return truck_route_;
}
/**
* Set the truck route flag for this directed edge.
* @param truck_route Truck route flag.
*/
void set_truck_route(const bool truck_route);
/**
* Get the number of lanes for this directed edge.
* @return Returns the number of lanes for this directed edge.
*/
uint32_t lanecount() const {
return lanecount_;
}
/**
* Sets the number of lanes
* @param lanecount Number of lanes
*/
void set_lanecount(const uint32_t lanecount);
/**
* Simple turn restrictions from the end of this directed edge.
* These are turn restrictions from one edge to another that apply to
* all vehicles, at all times.
* @return Returns a bit mask that indicates the local edge indexes
* of outbound directed edges that are restricted.
*/
uint32_t restrictions() const {
return restrictions_;
}
/**
* Set simple turn restrictions from the end of this directed edge.
* These are turn restrictions from one edge to another that apply to
* all vehicles, at all times.
* @param mask A bit mask that indicates the local edge indexes
* of outbound directed edges that are restricted.
*/
void set_restrictions(const uint32_t mask);
/**
* Get the specialized use of this edge.
* @return Returns the use type of this edge.
*/
Use use() const {
return static_cast<Use>(use_);
}
/**
* Sets the specialized use type of this edge.
* @param use Use of this edge.
*/
void set_use(const Use use);
/**
* Is the edge a road (includes generic service roads)
* @return Returns true if the edge is a road use or service road.
*/
bool is_road() const {
return use() == Use::kRoad || use() == Use::kServiceRoad;
}
/**
* Is this edge a transit line (bus or rail)?
* @return Returns true if this edge is a transit line.
*/
bool IsTransitLine() const {
return (use() == Use::kRail || use() == Use::kBus);
}
/**
* Get the speed type (see graphconstants.h)
* @return Returns the speed type.
*/
SpeedType speed_type() const {
return static_cast<SpeedType>(speed_type_);
}
/**
* Set the speed type (see graphconstants.h)
* @param speed_type Speed type.
*/
void set_speed_type(const SpeedType speed_type);
/**
* Get the country crossing flag.
* @return Returns true if the edge crosses into a new country.
*/
bool ctry_crossing() const {
return ctry_crossing_;
}
/**
* Set the country crossing flag.
* @param crossing True if this edge crosses into a new country.
*/
void set_ctry_crossing(const bool crossing);
/**
* Get the access modes in the forward direction (bit field).
* @return Returns the access modes in the forward direction.
*/
uint32_t forwardaccess() const {
return forwardaccess_;
}
/**
* Set the access modes in the forward direction (bit field).
* @param modes Allowed access modes in the forward direction.
*/
void set_forwardaccess(const uint32_t modes);
/**
* Set all forward access modes to true (used for transition edges)
*/
void set_all_forward_access();
/**
* Get the access modes in the reverse direction (bit field).
* @return Returns the access modes in the reverse direction.
*/
uint32_t reverseaccess() const {
return reverseaccess_;
}
/**
* Set the access modes in the reverse direction (bit field).
* @param modes Allowed access modes in the reverse direction.
*/
void set_reverseaccess(const uint32_t modes);
/**
* Gets the average speed in KPH.
* @return Returns the speed in KPH.
*/
uint32_t speed() const {
return speed_;
}
/**
* Sets the average speed in KPH.
* @param speed Speed in KPH.
*/
void set_speed(const uint32_t speed);
/**
* Gets the truck speed in KPH.
* @return Returns the truck speed in KPH.
*/
uint32_t truck_speed() const {
return truck_speed_;
}
/**
* Sets the truck speed in KPH.
* @param speed Speed in KPH.
*/
void set_truck_speed(const uint32_t speed);
/**
* Get the classification (importance) of the road/path.
* @return Returns road classification / importance.
*/
RoadClass classification() const {
return static_cast<RoadClass>(classification_);
}
/**
* Sets the classification (importance) of this edge.
* @param roadclass Road class.
*/
void set_classification(const RoadClass roadclass);
/**
* Gets the sac scale. Shows if edge is meant for hiking, and if so how difficult
* of a hike it is.
* @return sac_scale
*/
SacScale sac_scale() const {
return static_cast<SacScale>(sac_scale_);
}
/**
* Sets the sac scale. Shows if edge is meant for hiking, and if so how difficult
* of a hike it is.
* @param sac_scale SacScale type
*/
void set_sac_scale(const SacScale sac_scale);
/**
* Are names consistent with the from edge (local edge index at the start node).
* @param idx Local edge index at the start.
*/
bool name_consistency(const uint32_t idx) const {
return name_consistency_ & (1 << idx);
}
/**
* Set the name consistency given the other edge's local index. This is limited
* to the first 8 local edge indexes.
* @param from Local index of the from edge.
* @param c Are names consistent between the 2 edges?
*/
void set_name_consistency(const uint32_t from, const bool c);
/**
* Is this edge unpaved or bad surface?
*/
bool unpaved() const {
return (surface() >= Surface::kCompacted);
}
/**
* Get the surface type (see graphconstants.h). This is a general indication
* of smoothness.
*/
Surface surface() const {
return static_cast<Surface>(surface_);
}
/**
* Sets the surface type (see baldr/graphconstants.h). This is a general
* indication of smoothness.
* @param surface Surface type.
*/
void set_surface(const Surface surface);
/**
* Is this edge a link/ramp?
*/
bool link() const {
return link_;
}
/**
* Sets the link flag indicating the edge is part of a link or connection
* (ramp or turn channel).
* @param link True if the edge is part of a link.
*/
void set_link(const bool link);
/**
* Gets the intersection internal flag. This indicates the edge is "internal"
* to an intersection. This is derived from OSM based on geometry of an
* of nearby edges and is used for routing behavior on doubly digitized
* intersections.
* @return Returns true if the edge is internal to an intersection.
*/
bool internal() const {
return internal_;
}
/**
* Sets the intersection internal flag indicating the edge is "internal"
* to an intersection. This is derived from OSM based on geometry of an
* of nearby edges and is used for routing behavior on doubly digitized
* intersections.
* @param internal True if the edge is internal to an intersection.
*/
void set_internal(const bool internal);
/**
* Complex restriction (per mode) for this directed edge at the start.
* @return Returns the starting mode for this complex restriction for the
* directed edge.
*/
uint32_t start_restriction() const {
return start_restriction_;
}
/**
* Set the modes which have a complex restriction starting on this edge.
* @param modes Modes with access restrictions.
*/
void set_start_restriction(const uint32_t modes);
/**
* Complex restriction (per mode) for this directed edge at the end.
* @return Returns the ending mode for this complex restriction for the
* directed edge.
*/
uint32_t end_restriction() const {
return end_restriction_;
}
/**
* Set the modes which have a complex restriction ending on this edge.
* @param modes Modes with access restrictions.
*/
void set_end_restriction(const uint32_t modes);
/**
* Is this edge part of a complex restriction?
* @return Returns true if this edge is part of a complex restriction.
*/
bool part_of_complex_restriction() const {
return complex_restriction_;
}
/**
* Sets the part of complex restriction flag indicating the edge is part
* of a complex restriction or really a via
* @param part_of true if the edge is part of a complex restriction.
*/
void complex_restriction(const bool part_of);
/**
* Get if edge has a shoulder
* @return Returns if edge has a shoulder
*/
bool shoulder() const {
return shoulder_;
}
/**
* Set if edge has a shoulder
* @param shoulder True if edge has shoulder
*/
void set_shoulder(const bool shoulder);
/**
* Get if cyclists should dismount their bikes along this edge
* @return Returns true if edge is a dismount edge, false if it is not.
*/
bool dismount() const {
return dismount_;
}
/**
* Set if cyclists should dismount their bikes along this edge
* @param dismount true if the edge is a dismount edge, false if not.
*/
void set_dismount(const bool dismount);
/**
* Get if a sidepath for bicycling should be preffered instead of this edge
* @return Returns if a sidepath should be preffered for cycling
*/
bool use_sidepath() const {
return use_sidepath_;
}
/**
* Set if a sidepath for bicycling should be preffered instead of this edge
* @param use_sidepath true if sidepath should be preffered for cycling over this edge
*/
void set_use_sidepath(const bool use_sidepath);
/**
* Get the density along the edges.
* @return Returns relative density along the edge.
*/
uint32_t density() const {
return density_;
}
/**
* Set the density along the edges.
* @param density Relative density along the edge.
*/
void set_density(const uint32_t density);
/**
* Is this edge named?
* @return Returns true if the edge is named, false if unnamed.
*/
bool named() const {
return named_;
}
/**
* Sets the named flag.
* @param named true if the edge has names, false if unnamed.
*/
void set_named(const bool named);
/**
* Is there a sidewalk to the left of this directed edge?
* @return Returns true if there is a sidewalk to the left of this edge.
*/
bool sidewalk_left() const {
return sidewalk_left_;
}
/**
* Set the flag for a sidewalk to the left of this directed edge.
* @param sidewalk True if a sidewalk is on the left of this directed edge.
*/
void set_sidewalk_left(const bool sidewalk);
/**
* Is there a sidewalk to the right of this directed edge?
* @return Returns true if there is a sidewalk to the right of this edge.
*/
bool sidewalk_right() const {
return sidewalk_right_;
}
/**
* Set the flag for a sidewalk to the right of this directed edge.
* @param sidewalk True if a sidewalk is on the right of this directed edge.
*/
void set_sidewalk_right(const bool sidewalk);
/**
* Gets the turn type given the prior edge's local index
* (index of the inbound edge).
* @param localidx Local index at the node of the inbound edge.
* @return Returns the turn type (see turn.h)
*/
Turn::Type turntype(const uint32_t localidx) const {
// Turn type is 3 bits per index
uint32_t shift = localidx * 3;
return static_cast<Turn::Type>(((turntype_ & (7 << shift))) >> shift);
}
/**
* Sets the turn type given the prior edge's local index
* (index of the inbound edge).
* @param localidx Local index at the node of the inbound edge.
* @param turntype Turn type
*/
void set_turntype(const uint32_t localidx, const Turn::Type turntype);
/**
* Is there an edge to the left, in between the from edge and this edge.
* @param localidx Local index at the node of the inbound edge.
* @return Returns true if there is an edge to the left, false if not.
*/
bool edge_to_left(const uint32_t localidx) const {
return (edge_to_left_ & (1 << localidx));
}
/**
* Set the flag indicating there is an edge to the left, in between
* the from edge and this edge.
* @param localidx Local index at the node of the inbound edge.
* @param left True if there is an edge to the left, false if not.
*/
void set_edge_to_left(const uint32_t localidx, const bool left);
/**
* Get the stop impact when transitioning from the prior edge (given
* by the local index of the corresponding inbound edge at the node).
* @param localidx Local index at the node of the inbound edge.
* @return Returns the relative stop impact from low (0) to high (7).
*/
uint32_t stopimpact(const uint32_t localidx) const {
// Stop impact is 3 bits per index
uint32_t shift = localidx * 3;
return (stopimpact_.s.stopimpact & (7 << shift)) >> shift;
}
/**
* Set the stop impact when transitioning from the prior edge (given
* by the local index of the corresponding inbound edge at the node).
* @param localidx Local index at the node of the inbound edge.
* @param stopimpact Relative stop impact from low (0) to high (7).
*/
void set_stopimpact(const uint32_t localidx, const uint32_t stopimpact);
/**
* Get the transit line Id (for departure lookups along an edge)
* @return Returns the transit line Id.
*/
uint32_t lineid() const {
return stopimpact_.lineid;
}
/**
* Set the unique transit line Id.
* @param lineid Line Id indicating a unique stop-pair and route.
*/
void set_lineid(const uint32_t lineid);
/**
* Is there an edge to the right, in between the from edge and this edge.
* @param localidx Local index at the node of the inbound edge.
* @return Returns true if there is an edge to the right, false if not.
*/
bool edge_to_right(const uint32_t localidx) const {
return (stopimpact_.s.edge_to_right & (1 << localidx));
}
/**
* Set the flag indicating there is an edge to the right, in between
* the from edge and this edge.
* @param localidx Local index at the node of the inbound edge.
* @param right True if there is an edge to the right, false if not.
*/
void set_edge_to_right(const uint32_t localidx, const bool right);
/**
* Get the index of the directed edge on the local level of the graph
* hierarchy. This is used for turn restrictions so the edges can be
* identified on the different levels.
* @return Returns the index of the edge on the local level.
*/
uint32_t localedgeidx() const {
return localedgeidx_;
}
/** Set the index of the directed edge on the local level of the graph
* hierarchy. This is used for turn restrictions so the edges can be
* identified on the different levels.
* @param idx The index of the edge on the local level.
*/
void set_localedgeidx(const uint32_t idx);
/**
* Get the index of the opposing directed edge on the local hierarchy level
* at the end node of this directed edge. Only stored for the first 8 edges
* so it can be used for edge transition costing.
* @return Returns the index of the opposing directed edge on the local
* hierarchy level at end node of this directed edge.
*/
uint32_t opp_local_idx() const {
return opp_local_idx_;
}
/**
* Set the index of the opposing directed edge on the local hierarchy level
* at the end node of this directed edge. Only stored for the first 8 edges
* so it can be used for edge transition costing.
* @param localidx The index of the opposing directed edge on the local
* hierarchy level at end node of this directed edge.
*/
void set_opp_local_idx(const uint32_t localidx);
/**
* Indicates the mask of the superseded edge bypassed by a shortcut.
* Shortcuts bypass nodes that only connect to lower levels in the hierarchy
* (other than the 1-2 higher level edges that superseded by the shortcut).
* @return Returns the shortcut mask of the matching superseded edge
* outbound from the node. 0 indicates the edge is not a shortcut.
*/
uint32_t shortcut() const {
return shortcut_;
}
/**
* Set the mask for whether this edge represents a shortcut between 2 nodes.
* Shortcuts bypass nodes that only connect to lower levels in the hierarchy
* (other than the 1-2 higher level edges that superseded by the shortcut).
* @param shortcut Mask indicating the edge that is superseded by
* the shortcut. 0 if not a shortcut.
*/
void set_shortcut(const uint32_t shortcut);
/**
* Mask indicating the shortcut that supersedes this directed edge.
* Superseded edges can be skipped unless downward transitions are allowed.
* @return Returns the mask of the matching shortcut edge that supersedes this
* directed edge outbound from the node. 0 indicates the edge is not
* superseded by a shortcut edge.
*/
uint32_t superseded() const {
return superseded_;
}
/**
* Set the mask for whether this edge is superseded by a shortcut edge.
* Superseded edges can be skipped unless downward transitions are allowed.
* @param superseded Mask that matches the shortcut that supersedes this
* directed edge. 0 if not superseded by a shortcut.
*/
void set_superseded(const uint32_t superseded);
/**
* Is this edge a shortcut edge. If there are more than kMaxShortcutsFromNode
* shortcuts no mask is set but this flag is set to true.
* @return Returns true if this edge is a shortcut.
*/
bool is_shortcut() const {
return is_shortcut_;
}
/**
* Does this directed edge end in a different tile.
* @return Returns true if the end node of this directed edge
* is in a different tile.
*/
bool leaves_tile() const {
return leaves_tile_;
}
/**
* Set the flag indicating whether the end node of this directed edge is in
* a different tile
* @param leaves_tile True if the end node of this edge is in a different
* tile than the start node (and the directed edge
* itself).
*/
void set_leaves_tile(const bool leaves_tile);
/**
* Set the flag indicating whether this edge is a bike share station's connection
* @param bss_connection True if the edge is a bike share station's connection
*/
void set_bss_connection(const bool bss_connection);
/**
* If this edge is a bike share station's connection?
* @return Returns true if this edge is a bike share station's connection
*/
bool bss_connection() const {
return bss_connection_;
}
/**
* Create a json object representing this edge
* @return Returns the json object
*/
json::MapPtr json() const;
protected:
// 1st 8-byte word
uint64_t endnode_ : 46; // End node of the directed edge
uint64_t restrictions_ : 8; // Restrictions - mask of local edge indexes at the end node
uint64_t opp_index_ : 7; // Opposing directed edge index
uint64_t forward_ : 1; // Is the edge info forward or reverse
uint64_t leaves_tile_ : 1; // Does directed edge end in a different tile?
uint64_t ctry_crossing_ : 1; // Does the edge cross into new country
// 2nd 8 byte word
uint64_t edgeinfo_offset_ : 25; // Offset to edge data
uint64_t access_restriction_ : 12; // General restriction or access condition (per mode)
uint64_t start_restriction_ : 12; // Complex restriction (per mode) starts on this directed edge
uint64_t end_restriction_ : 12; // Complex restriction (per mode) ends on this directed edge
uint64_t complex_restriction_ : 1; // Edge is part of a complex restriction
uint64_t dest_only_ : 1; // Access allowed to destination only (e.g., private)
uint64_t not_thru_ : 1; // Edge leads to "no-through" region
// 3rd 8-byte word. Note: speed values above 250 for special cases (closures, construction)
uint64_t speed_ : 8; // Speed (kph)
uint64_t free_flow_speed_ : 8; // Speed when there is no traffic(kph)
uint64_t constrained_flow_speed_ : 8; // Speed when there is traffic(kph)
uint64_t truck_speed_ : 8; // Truck speed (kph)
uint64_t name_consistency_ : 8; // Name consistency at start node with other local edges
uint64_t use_ : 6; // Specific use types
uint64_t lanecount_ : 4; // Number of lanes
uint64_t density_ : 4; // Relative road density along the edge
uint64_t classification_ : 3; // Classification/importance of the road/path
uint64_t surface_ : 3; // Representation of smoothness
uint64_t toll_ : 1; // Edge is part of a toll road
uint64_t roundabout_ : 1; // Edge is part of a roundabout
uint64_t truck_route_ : 1; // Edge that is part of a truck route/network
uint64_t has_predicted_speed_ : 1; // Does this edge have a predicted speed records?
// 4th 8-byte word
uint64_t forwardaccess_ : 12; // Access (bit mask) in forward direction (see graphconstants.h)
uint64_t reverseaccess_ : 12; // Access (bit mask) in reverse direction (see graphconstants.h)
uint64_t max_up_slope_ : 5; // Maximum upward slope
uint64_t max_down_slope_ : 5; // Maximum downward slope
uint64_t sac_scale_ : 3; // Is this edge for hiking and if so how difficult is the hike?
uint64_t cycle_lane_ : 2; // Does this edge have bicycle lanes?
uint64_t bike_network_ : 1; // Edge that is part of a bicycle network
uint64_t use_sidepath_ : 1; // Is there a cycling path to the side that should be preferred?
uint64_t dismount_ : 1; // Do you need to dismount when biking on this edge?
uint64_t sidewalk_left_ : 1; // Sidewalk to the left of the edge
uint64_t sidewalk_right_ : 1; // Sidewalk to the right of the edge
uint64_t shoulder_ : 1; // Does the edge have a shoulder?
uint64_t lane_conn_ : 1; // 1 if has lane connectivity, 0 otherwise
uint64_t turnlanes_ : 1; // Does this edge have turn lanes (end of edge)
uint64_t sign_ : 1; // Exit signs exist for this edge
uint64_t internal_ : 1; // Edge that is internal to an intersection
uint64_t tunnel_ : 1; // Is this edge part of a tunnel
uint64_t bridge_ : 1; // Is this edge part of a bridge?
uint64_t traffic_signal_ : 1; // Traffic signal at end of the directed edge
uint64_t seasonal_ : 1; // Seasonal access (ex. no access in winter)
uint64_t deadend_ : 1; // Leads to a dead-end (no other driveable roads) TODO
uint64_t bss_connection_ : 1; // Does this lead to(come out from) a bike share station?
uint64_t stop_sign_ : 1; // Stop sign at end of the directed edge
uint64_t yield_sign_ : 1; // Yield/give way sign at end of the directed edge
uint64_t hov_type_ : 1; // if (is_hov_only()==true), this means (HOV2=0, HOV3=1)
uint64_t indoor_ : 1; // Is this edge indoor
uint64_t spare4_ : 5;
// 5th 8-byte word
uint64_t turntype_ : 24; // Turn type (see graphconstants.h)
uint64_t edge_to_left_ : 8; // Is there an edge to the left (between
// the "from edge" and this edge)
uint64_t length_ : 24; // Length in meters
uint64_t weighted_grade_ : 4; // Weighted estimate of grade
uint64_t curvature_ : 4; // Curvature factor
// Stop impact among edges
struct StopImpact {
uint32_t stopimpact : 24; // Stop impact between edges
uint32_t edge_to_right : 8; // Is there an edge to the right (between
// "from edge" and this edge)
};
// Store either the stop impact or the transit line identifier. Since
// transit lines are schedule based they have no need for edge transition
// logic so we can safely share this field.
union StopOrLine {
StopImpact s;
uint32_t lineid;
};
// 6th 8-byte word (this union plus the next uint32_t bitfield)
StopOrLine stopimpact_;
// Local edge index, opposing local index, shortcut info
uint32_t localedgeidx_ : 7; // Index of the edge on the local level
uint32_t opp_local_idx_ : 7; // Opposing local edge index (for costing and Uturn detection)
uint32_t shortcut_ : 7; // Shortcut edge (mask)
uint32_t superseded_ : 7; // Edge is superseded by a shortcut (mask)
uint32_t is_shortcut_ : 1; // True if this edge is a shortcut
uint32_t speed_type_ : 1; // Speed type (used in setting default speeds)
uint32_t named_ : 1; // 1 if this edge has names, 0 if unnamed
uint32_t link_ : 1; // *link tag - Ramp or turn channel. Used in costing.
};
/**
* Extended directed edge attribution. This structure provides the ability to add extra
* attribution per directed edge without breaking backward compatibility. For now this structure
* is unused.
*/
class DirectedEdgeExt {
/**
* Indicates the Pointz rating of the edge.
* If the edge has a rating, the value is between 1 and 5.
* If the edge has no rating, the value is NULL (0)
* @return Returns the Pointz rating of the edge.
*/
uint64_t rating() const {
return rating_;
}
/**
* Set the Pointz rating of the edge.
* If the edge has a rating, the value should be between 1 and 5.
* If the edge has no rating, the value should be NULL (0)
* @param rating Pointz rating of the edge.
*/
void set_rating(const uint64_t rating);
/**
* Create a json object representing this edge extension
* @return Returns the json object
*/
json::MapPtr json() const;
// Total size must be 64bits (8 bytes)
protected:
uint64_t rating_ : 3; // Rating of the edge (from 1 to 5) fits in 3 bits
uint64_t spare0_ : 61; // Remaining bits
};
} // namespace baldr
} // namespace valhalla
#endif // VALHALLA_BALDR_DIRECTEDEDGE_H_
| 31.758431 | 101 | 0.667317 | [
"geometry",
"object"
] |
a93755eb444b9fc8ed6295d5d6e01ddd15aa7be8 | 2,932 | h | C | src/graph/util/SchemaUtil.h | jackwener/nebula | d83f26db7ecc09cb9d97148dda7cb013a1aff08b | [
"Apache-2.0"
] | 1 | 2022-02-14T12:25:00.000Z | 2022-02-14T12:25:00.000Z | src/graph/util/SchemaUtil.h | jackwener/nebula | d83f26db7ecc09cb9d97148dda7cb013a1aff08b | [
"Apache-2.0"
] | null | null | null | src/graph/util/SchemaUtil.h | jackwener/nebula | d83f26db7ecc09cb9d97148dda7cb013a1aff08b | [
"Apache-2.0"
] | null | null | null | /* Copyright (c) 2020 vesoft inc. All rights reserved.
*
* This source code is licensed under Apache 2.0 License.
*/
#ifndef GRAPH_UTIL_SCHEMAUTIL_H_
#define GRAPH_UTIL_SCHEMAUTIL_H_
#include "common/base/StatusOr.h"
#include "common/datatypes/DataSet.h"
#include "common/expression/Expression.h"
#include "common/meta/NebulaSchemaProvider.h"
#include "interface/gen-cpp2/common_types.h"
#include "interface/gen-cpp2/meta_types.h"
#include "parser/MaintainSentences.h"
namespace nebula {
namespace graph {
class QueryContext;
struct SpaceInfo;
class SchemaUtil final {
public:
using VertexProp = nebula::storage::cpp2::VertexProp;
using EdgeProp = nebula::storage::cpp2::EdgeProp;
SchemaUtil() = delete;
public:
static Status validateProps(const std::vector<SchemaPropItem*>& schemaProps,
meta::cpp2::Schema& schema);
static std::shared_ptr<const meta::NebulaSchemaProvider> generateSchemaProvider(
const SchemaVer ver, const meta::cpp2::Schema& schema);
static Status setTTLDuration(SchemaPropItem* schemaProp, meta::cpp2::Schema& schema);
static Status setTTLCol(SchemaPropItem* schemaProp, meta::cpp2::Schema& schema);
static Status setComment(SchemaPropItem* schemaProp, meta::cpp2::Schema& schema);
static StatusOr<Value> toVertexID(Expression* expr, Value::Type vidType);
static StatusOr<std::vector<Value>> toValueVec(std::vector<Expression*> exprs);
static StatusOr<DataSet> toDescSchema(const meta::cpp2::Schema& schema);
static StatusOr<DataSet> toShowCreateSchema(bool isTag,
const std::string& name,
const meta::cpp2::Schema& schema);
static std::string typeToString(const meta::cpp2::ColumnTypeDef& col);
static std::string typeToString(const meta::cpp2::ColumnDef& col);
static Value::Type propTypeToValueType(nebula::cpp2::PropertyType propType);
static bool isValidVid(const Value& value, const meta::cpp2::ColumnTypeDef& type);
static bool isValidVid(const Value& value, nebula::cpp2::PropertyType type);
static bool isValidVid(const Value& value);
// Fetch all tags in the space and retrieve props from tags
// only take _tag when withProp is false
static StatusOr<std::unique_ptr<std::vector<VertexProp>>> getAllVertexProp(QueryContext* qctx,
GraphSpaceID spaceId,
bool withProp);
// retrieve prop from specific edgetypes
// only take _src _dst _type _rank when withProp is false
static StatusOr<std::unique_ptr<std::vector<EdgeProp>>> getEdgeProps(
QueryContext* qctx,
const SpaceInfo& space,
const std::vector<EdgeType>& edgeTypes,
bool withProp);
};
} // namespace graph
} // namespace nebula
#endif // GRAPH_UTIL_SCHEMAUTIL_H_
| 37.113924 | 98 | 0.688267 | [
"vector"
] |
a9413945aee4566f1ecb84f3e27608cf6061fd72 | 4,291 | h | C | src/gromacs/mdrun/membedholder.h | hejamu/gromacs | 4f4b9e4b197ae78456faada74c9f4cab7d128de6 | [
"BSD-2-Clause"
] | 384 | 2015-01-02T19:44:15.000Z | 2022-03-27T15:13:15.000Z | src/gromacs/mdrun/membedholder.h | hejamu/gromacs | 4f4b9e4b197ae78456faada74c9f4cab7d128de6 | [
"BSD-2-Clause"
] | 168 | 2017-05-27T14:43:32.000Z | 2021-04-12T08:07:11.000Z | src/gromacs/mdrun/membedholder.h | hejamu/gromacs | 4f4b9e4b197ae78456faada74c9f4cab7d128de6 | [
"BSD-2-Clause"
] | 258 | 2015-01-19T11:19:57.000Z | 2022-03-18T08:59:52.000Z | /*
* This file is part of the GROMACS molecular simulation package.
*
* Copyright (c) 2020, by the GROMACS development team, led by
* Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
* and including many others, as listed in the AUTHORS file in the
* top-level source directory and at http://www.gromacs.org.
*
* GROMACS 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.1
* of the License, or (at your option) any later version.
*
* GROMACS 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 GROMACS; if not, see
* http://www.gnu.org/licenses, or write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* If you want to redistribute modifications to GROMACS, please
* consider that scientific software is very special. Version
* control is crucial - bugs must be traceable. We will be happy to
* consider code for inclusion in the official distribution, but
* derived work must not be called official GROMACS. Details are found
* in the README & COPYING files - if they are missing, get the
* official version at http://www.gromacs.org.
*
* To help us fund GROMACS development, we humbly ask that you cite
* the research papers on the package. Check out http://www.gromacs.org.
*/
/*! \internal
* \brief Encapsulates membed methods
*
* \author Joe Jordan <ejjordan@kth.se>
* \ingroup module_mdrun
*/
#ifndef GMX_MDRUN_MEMBEDHOLDER_H
#define GMX_MDRUN_MEMBEDHOLDER_H
#include <cstdio>
#include "gromacs/utility/real.h"
struct gmx_membed_t;
struct gmx_mtop_t;
struct t_commrec;
struct t_filenm;
struct t_inputrec;
class t_state;
namespace gmx
{
/*! \brief Membed SimulatorBuilder parameter type.
*
* Does not (yet) encapsulate ownership semantics of resources. Simulator is
* not (necessarily) granted ownership of resources. Client is responsible for
* maintaining the validity of resources for the life time of the Simulator,
* then for cleaning up those resources.
*/
class MembedHolder
{
public:
//! Build holder from input information.
explicit MembedHolder(int nfile, const t_filenm fnm[]);
//! Move is possible.
MembedHolder(MembedHolder&& holder) noexcept;
//! Move assignment is possible.
MembedHolder& operator=(MembedHolder&& holder) noexcept;
//! Copy is not allowed.
MembedHolder(const MembedHolder&) = delete;
//! Copy assignment is not allowed.
MembedHolder& operator=(const MembedHolder&) = delete;
~MembedHolder();
//! Get information about membed being used.
[[nodiscard]] bool doMembed() const { return doMembed_; }
/*! \brief
* Fully initialize underlying datastructure.
*
* \param[in] fplog Handle to log file.
* \param[in] nfile How many input files are there.
* \param[in] fnm Input file collection datastructure.
* \param[in,out] mtop Handle to mtop, can be modified.
* \param[in,out] inputrec Handle to inputrec, can be modified.
* \param[in,out] state Simulation state information, can be modified.
* \param[in,out] cr Communication information.
* \param[out] cpt Some kind of checkpoint information.
*/
void initializeMembed(FILE* fplog,
int nfile,
const t_filenm fnm[],
gmx_mtop_t* mtop,
t_inputrec* inputrec,
t_state* state,
t_commrec* cr,
real* cpt);
//! Get handle to membed object.
gmx_membed_t* membed();
private:
//! Pointer to membed object. TODO replace with unique_ptr or get rid of this.
gmx_membed_t* membed_ = nullptr;
//! Whether membed is being used.
bool doMembed_ = false;
};
} // namespace gmx
#endif // GMX_MDRUN_MEMBEDHOLDER_H
| 36.364407 | 82 | 0.683291 | [
"object"
] |
a9451c773a4ff1175e857e06ecd985c61a20f4a6 | 12,805 | h | C | Ubpa/UTemplate-0.1/include/UTemplate/Typelist.h | trygas/CGHomework | 2dfff76f407b8a7ba87c5ba9d12a4428708ffbbe | [
"MIT"
] | null | null | null | Ubpa/UTemplate-0.1/include/UTemplate/Typelist.h | trygas/CGHomework | 2dfff76f407b8a7ba87c5ba9d12a4428708ffbbe | [
"MIT"
] | null | null | null | Ubpa/UTemplate-0.1/include/UTemplate/Typelist.h | trygas/CGHomework | 2dfff76f407b8a7ba87c5ba9d12a4428708ffbbe | [
"MIT"
] | null | null | null | #pragma once
#include <iostream>
#include "Basic.h"
namespace Ubpa {
template<typename... Ts>
struct TypeList { };
template<typename List> struct IsTypeList;
template<typename List> constexpr bool IsTypeList_v = IsTypeList<List>::value;
template<typename List> struct Length;
template<typename List> constexpr size_t Length_v = Length<List>::value;
template<typename List> struct IsEmpty;
template<typename List> constexpr bool IsEmpty_v = IsEmpty<List>::value;
template<typename List> struct Front;
template<typename List> using Front_t = typename Front<List>::type;
template<typename List, size_t N> struct At;
template<typename List, size_t N> using At_t = typename At<List, N>::type;
template<typename List, size_t... Indices> struct Select;
template<typename List, size_t... Indices> using Select_t = typename Select<List, Indices...>::type;
template<typename List, typename T> struct Find;
template<typename List, typename T> constexpr size_t Find_v = Find<List, T>::value;
constexpr size_t Find_fail = static_cast<size_t>(-1);
template<typename List, typename T> struct Contain;
template<typename List, typename T> constexpr bool Contain_v = Contain<List, T>::value;
template<typename List, typename... Ts> struct ContainTs;
template<typename List, typename... Ts> constexpr bool ContainTs_v = ContainTs<List, Ts...>::value;
template<typename List0, typename List1> struct ContainList;
template<typename List0, typename List1> constexpr bool ContainList_v = ContainList<List0, List1>::value;
template<typename List, template<typename...> class T> struct CanInstantiate;
template<typename List, template<typename...> class T> constexpr bool CanInstantiate_v = CanInstantiate<List, T>::value;
template<typename List, template<typename...> class T> struct Instantiate;
template<typename List, template<typename...> class T> using Instantiate_t = typename Instantiate<List, T>::type;
template<template<typename...> class T, template<typename...> class U, typename List>
struct IsSameTemplate;
template<template<typename...> class T, template<typename...> class U, typename List>
constexpr bool IsSameTemplate_v = IsSameTemplate<T, U, List>::value;
template<typename List, template<typename...>class T> struct ExistInstance;
template<typename List, template<typename...>class T> constexpr bool ExistInstance_v = ExistInstance<List, T>::value;
// get first template instantiable type
template<typename List, template<typename...>class T> struct SearchInstance;
template<typename List, template<typename...>class T> using SearchInstance_t = typename SearchInstance<List, T>::type;
template<typename List, typename T> struct PushFront;
template<typename List, typename T> using PushFront_t = typename PushFront<List, T>::type;
template<typename List, typename T> struct PushBack;
template<typename List, typename T> using PushBack_t = typename PushBack<List, T>::type;
template<typename List> struct PopFront;
template<typename List> using PopFront_t = typename PopFront<List>::type;
template<typename List> struct Rotate;
template<typename List> using Rotate_t = typename Rotate<List>::type;
template<typename List, template <typename I, typename X> class Op, typename I>
struct Accumulate;
template<typename List, template <typename I, typename X> class Op, typename I>
using Accumulate_t = typename Accumulate<List, Op, I>::type;
template<typename List, template<typename>class Op> struct Filter;
template<typename List, template<typename>class Op> using Filter_t = typename Filter<List, Op>::type;
template<typename List> struct Reverse;
template<typename List> using Reverse_t = typename Reverse<List>::type;
template<typename List0, typename List1> struct Concat;
template<typename List0, typename List1> using Concat_t = typename Concat<List0, List1>::type;
template<typename List, template<typename> class Op> struct Transform;
template<typename List, template<typename> class Op> using Transform_t = typename Transform<List, Op>::type;
template<typename List, template<typename X, typename Y>typename Less>
struct QuickSort;
template<typename List, template<typename X, typename Y>typename Less>
using QuickSort_t = typename QuickSort<List, Less>::type;
template<typename List>
struct IsSet;
template<typename List>
constexpr bool IsSet_v = IsSet<List>::value;
}
namespace Ubpa::detail::TypeList_ {
template<typename List, typename T, size_t N = 0, bool found = false>
struct Find;
template<typename List, template <typename I, typename X> class Op, typename I, bool = IsEmpty_v<List>>
struct Accumulate;
template<typename List, template<typename...>class T, bool found = false, bool = IsEmpty<List>::value>
struct ExistInstance;
template<typename List, typename LastT, template<typename...>class T, bool found = false, bool = IsEmpty<List>::value>
struct SearchInstance;
template<typename List, bool haveSame = false>
struct IsSet;
}
namespace Ubpa {
template<typename... Ts>
struct Name;
template<typename... Ts>
struct Name<TypeList<Ts...>> {
friend std::ostream& operator<<(std::ostream& os, Name<TypeList<Ts...>>) {
os << "[" << Name<Ts...>() << "]";
return os;
}
};
// =================================================
template<typename List>
struct IsTypeList : is_instance_of<List, TypeList> {};
// =================================================
template<typename... Ts>
struct Length<TypeList<Ts...>> : IValue<size_t, sizeof...(Ts)> {};
// =================================================
template<typename List>
struct IsEmpty : IValue<bool, Length_v<List> == 0> {};
// =================================================
template<typename Head, typename... Tail>
struct Front<TypeList<Head, Tail...>> : IType<Head> {};
// =================================================
template<typename List>
struct At<List, 0> : IType<Front_t<List>> {};
template<typename List, size_t N>
struct At : At<PopFront_t<List>, N - 1> {};
// =================================================
template<typename List, size_t... Indices>
struct Select : IType<TypeList<At_t<List, Indices>...>> {};
// =================================================
template<typename List, typename T>
struct Find : detail::TypeList_::Find<List, T> { };
// =================================================
template<typename List, typename T>
struct Contain : IValue<bool, Find_v<List,T> != Find_fail> {};
// =================================================
template<typename List, typename... Ts>
struct ContainTs : IValue<bool, (Contain_v<List, Ts> &&...)> {};
// =================================================
template<typename List, typename... Ts>
struct ContainList<List, TypeList<Ts...>> : IValue<bool, (Contain_v<List, Ts> &&...)> {};
// =================================================
template<template<typename...> class T, typename... Args>
struct CanInstantiate<TypeList<Args...>, T> : is_instantiable<T, Args...> {};
// =================================================
template<template<typename...> class T, typename... Args>
struct Instantiate<TypeList<Args...>, T> : IType<T<Args...>> {};
// =================================================
template<template<typename...> class T, template<typename...> class U, typename... Args>
struct IsSameTemplate<T, U, TypeList<Args...>> : is_same_template<T, U, Args...> {};
// =================================================
template<typename List, template<typename...>class T>
struct ExistInstance : detail::TypeList_::ExistInstance<List, T> {};
// =================================================
template<typename List, template<typename...>class T>
struct SearchInstance : detail::TypeList_::SearchInstance<List, void, T> {};
// =================================================
template<typename T, typename... Ts>
struct PushFront<TypeList<Ts...>, T> : IType<TypeList<T, Ts...>> {};
// =================================================
template<typename T, typename... Ts>
struct PushBack<TypeList<Ts...>, T> : IType<TypeList<Ts..., T>> {};
// =================================================
template<typename Head, typename... Tail>
struct PopFront<TypeList<Head, Tail...>> : IType<TypeList<Tail...>> {};
// =================================================
template<typename Head, typename... Tail>
struct Rotate<TypeList<Head, Tail...>> : IType<TypeList<Tail..., Head>> {};
// =================================================
template<typename List, template <typename I, typename X> class Op, typename I>
struct Accumulate : detail::TypeList_::Accumulate<List, Op, I> {};
// =================================================
template<typename List, template<typename>class Test>
struct Filter : Accumulate<List, AddIf<PushFront, Test>::template Ttype, TypeList<>> {};
// =================================================
template<typename List>
struct Reverse : Accumulate<List, PushFront, TypeList<>> {};
// =================================================
template<typename List, typename T>
struct PushBack : Reverse<PushFront_t<Reverse_t<List>, T>> {};
// =================================================
template<typename List0, typename List1>
struct Concat : Accumulate<List1, PushBack, List0> {};
// =================================================
template<template<typename T> class Op, typename... Ts>
struct Transform<TypeList<Ts...>, Op> : IType<TypeList<typename Op<Ts>::type...>> {};
// =================================================
template<template<typename X, typename Y>typename Less>
struct QuickSort<TypeList<>, Less> : IType<TypeList<>> {};
template<template<typename X, typename Y>typename Less, typename T>
struct QuickSort<TypeList<T>, Less> : IType<TypeList<T>> {};
template<template<typename X, typename Y>typename Less, typename Head, typename... Tail>
struct QuickSort<TypeList<Head, Tail...>, Less> {
private:
template<typename X>
using LessThanHead = Less<X, Head>;
using LessList = Filter_t<TypeList<Tail...>, LessThanHead>;
using GEList = Filter_t<TypeList<Tail...>, Negate<LessThanHead>::template Ttype>;
public:
using type = Concat_t<
typename QuickSort<LessList, Less>::type,
PushFront_t<typename QuickSort<GEList, Less>::type, Head>>;
};
// =================================================
template<typename List>
struct IsSet : detail::TypeList_::IsSet<List> {};
}
namespace Ubpa::detail::TypeList_ {
template<typename List, typename T, size_t N, bool found>
struct Find;
template<typename T, size_t N, typename... Ts>
struct Find<TypeList<Ts...>, T, N, true> : IValue<size_t, N - 1> {};
template<typename T, size_t N>
struct Find<TypeList<>, T, N, false> : IValue<size_t, Find_fail> {};
template<typename T, typename Head, size_t N, typename... Tail>
struct Find<TypeList<Head, Tail...>, T, N, false>
: Find<TypeList<Tail...>, T, N + 1, std::is_same_v<T, Head>> {};
// =================================================
template<typename List, template <typename I, typename X> class Op, typename I>
struct Accumulate<List, Op, I, false> : Accumulate<PopFront_t<List>, Op, typename Op<I, Front_t<List>>::type> { };
template<typename List, template <typename X, typename Y> class Op, typename I>
struct Accumulate<List, Op, I, true> {
using type = I;
};
// =================================================
template<typename List, template<typename...>class T>
struct ExistInstance<List, T, false, true> : std::false_type {};
template<typename List, template<typename...>class T, bool isEmpty>
struct ExistInstance<List, T, true, isEmpty> : std::true_type {};
template<typename List, template<typename...>class T>
struct ExistInstance<List, T, false, false> : ExistInstance<PopFront_t<List>, T, is_instance_of_v<Front_t<List>, T>> {};
// =================================================
template<typename List, typename LastT, template<typename...>class T>
struct SearchInstance<List, LastT, T, false, true> { }; // no 'type'
template<typename List, typename LastT, template<typename...>class T, bool isEmpty>
struct SearchInstance<List, LastT, T, true, isEmpty> {
using type = LastT;
};
template<typename List, typename LastT, template<typename...>class T>
struct SearchInstance<List, LastT, T, false, false> : SearchInstance<PopFront_t<List>, Front_t<List>, T, is_instance_of_v<Front_t<List>, T>> {};
// =================================================
template<typename List>
struct IsSet<List, true> : std::false_type {};
template<>
struct IsSet<TypeList<>, false> : std::true_type {};
template<typename Head, typename... Tail>
struct IsSet<TypeList<Head, Tail...>, false> : IsSet<TypeList<Tail...>, Contain_v<TypeList<Tail...>, Head>> {};
}
| 37.884615 | 145 | 0.62991 | [
"transform"
] |
a94768e7023b3386325e7b9c9734e3a437b15b1c | 11,238 | h | C | include/rtl/tf/TfTree.h | Robotics-BUT/Robotic-Template-Library | a93b31f5a8f5b12fbbd5fa134a714ea0f82c1578 | [
"MIT"
] | 8 | 2020-04-22T09:46:14.000Z | 2022-03-17T00:09:38.000Z | include/rtl/tf/TfTree.h | Robotics-BUT/Robotic-Template-Library | a93b31f5a8f5b12fbbd5fa134a714ea0f82c1578 | [
"MIT"
] | 1 | 2020-08-11T07:24:14.000Z | 2020-10-05T12:47:05.000Z | include/rtl/tf/TfTree.h | Robotics-BUT/Robotic-Template-Library | a93b31f5a8f5b12fbbd5fa134a714ea0f82c1578 | [
"MIT"
] | null | null | null | // This file is part of the Robotic Template Library (RTL), a C++
// template library for usage in robotic research and applications
// under the MIT licence:
//
// Copyright 2020 Brno University 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.
//
// Contact person: Ales Jelinek <Ales.Jelinek@ceitec.vutbr.cz>
#ifndef ROBOTICTEMPLATELIBRARY_TFTREE_H
#define ROBOTICTEMPLATELIBRARY_TFTREE_H
#include <map>
#include <list>
#include "TfTreeNode.h"
#include "GeneralTf.h"
#include "VariantResult.h"
#include "TfChain.h"
namespace rtl
{
/*!
* TfTree is a tree structure for organization of the geometric relationships between different coordinate frames (or poses, we use these as equivalents). Each pose corresponds to a node
* in the tree and is uniquely identified by a key. Transformations between adjacent coordinate frames correspond to the edges of the tree graph. Tree-like structure forbids cycles in the
* resulting graph, therefore between any two nodes, there is exactly one unique chain of transformations, which eliminates potential inconsistencies. The tree cannot be crated without
* the root node.
* @tparam K Key type.
* @tparam T Transformation type.
*/
template<typename K, typename T>
class TfTree
{
public:
typedef K KeyType; //!< Type of the keys.
typedef T TransformationType; //!< Type of the transformations between nodes.
typedef TfTreeNode<KeyType, TransformationType> NodeType; //!< Type of the nodes in the tree.
TfTree() = delete;
//! Base TfTree constructor.
/*!
* TfTree cannot be constructed without root, therefore the implicit constructor is disabled anf the key of the root node has to be passed.
* @param root_key key of the root node.
*/
explicit TfTree(const KeyType root_key)
{
root_node_key = root_key;
nodes.emplace(root_key, NodeType(root_key));
}
//! Copy constructor.
/*!
* Creates a deep copy of the tree.
* @param cp tree to by copied.
*/
TfTree(const TfTree &cp) : nodes(cp.nodes), root_node_key(cp.root_node_key) {}
//! Move constructor.
/*!
* Moves content of \p mv to a new tree. The root node is than copied back to keep \p mv valid.
* @param mv tree to be moved from.
*/
TfTree(TfTree &&mv) noexcept: nodes(mv.nodes), root_node_key(mv.root())
{
mv.insertRoot(root_node_key);
}
//! Destructor.
~TfTree()
{
clear();
}
//! Copy assigment operator.
/*!
* Creates a deep copy of the tree.
* @param eq tree to be copied.
* @return reference to *this.
*/
TfTree &operator=(const TfTree &eq)
{
nodes = eq.nodes;
root_node_key = eq.root_node_key;
return *this;
}
//! Move assigment operator.
/*!
* Moves content of \p mv to a new tree. The root node is than copied back to keep \p mv valid.
* @param mv tree to be moved from.
* @return reference to *this.
*/
TfTree &operator=(TfTree &&mv) noexcept
{
nodes = std::move(mv.nodes);
root_node_key = std::move(mv.root_node_key);
mv.insertRoot(root_node_key);
return *this;
}
//! Checks for an empty tree.
/*!
* Since there always should be the root node, a valid tree should never be empty. Useful for checking if the tree became empty by exception.
* @return False if there are no nodes in the tree, true otherwise.
*/
[[nodiscard]] bool empty() const
{
return nodes.empty();
}
//! Returns number of the nodes in the tree.
/*!
*
* @return number of the nodes in the tree.
*/
[[nodiscard]] size_t size() const
{
return nodes.size();
}
//! Clears the tree leaving only the root unchanged.
void clear()
{
std::vector<KeyType> child_keys;
for (auto c : nodes.at(root_node_key).children())
child_keys.push_back(c->key());
for (auto k : child_keys)
eraseSubtree(k);
}
//! Inserts a new node into the tree.
/*!
*
* @tparam Tf type of the transformation.
* @param key key of the new node.
* @param tf transformation from the parent node to the new node.
* @param parent key of the parent node.
* @return true on success, false otherwise.
*/
template<typename Tf>
bool insert(const KeyType &key, Tf &&tf, const KeyType &parent)
{
auto it_parent = nodes.find(parent);
if (it_parent == nodes.end())
return false;
return nodes.emplace(key, NodeType(key, tf, it_parent->second)).second;
}
//! Erases the node with given key and all its child-nodes recursively.
/*!
* The root node cannot be erased.
* @param key key of the node to be erased.
* @return true on success, false otherwise.
*/
bool erase(const KeyType &key)
{
if (key == root_node_key)
return false;
auto n = nodes.find(key);
if (n == nodes.end())
return false;
return eraseSubtree(key);
}
//! Checks whether a node with given key exists in the tree.
/*!
*
* @param key key of the node to be searched for.
* @return true if found, false otherwise.
*/
bool contains(const KeyType &key) const
{
return nodes.find(key) != nodes.end();
}
//! Returns reference to the root node.
/*!
*
* @return reference to the root node.
*/
[[nodiscard]] const NodeType& root() const
{
return nodes.at(root_node_key);
}
//! Access a node with given \p key.
/*!
* If there is no node with the \p key in the tree, an exception is thrown.
* @param key key of the accessed node.
* @return reference to the accessed node.
*/
NodeType& operator[](const KeyType& key)
{
if (!contains(key))
throw std::out_of_range("The key does not exist in given TfTree.");
return nodes[key];
}
//! Access a node with given \p key.
/*!
* If there is no node with the \p key in the tree, an exception is thrown.
* @param key key of the accessed node.
* @return reference to the accessed node.
*/
NodeType& operator[](KeyType&& key)
{
if (!contains(key))
throw std::out_of_range("The key does not exist in given TfTree.");
return nodes[key];
}
//! Access a node with given \p key.
/*!
* If there is no node with the \p key in the tree, an exception is thrown.
* @param key key of the accessed node.
* @return reference to the accessed node.
*/
NodeType& at(const KeyType& key)
{
return nodes.at(key);
}
//! Access a node with given \p key.
/*!
* If there is no node with the \p key in the tree, an exception is thrown.
* @param key key of the accessed node.
* @return reference to the accessed node.
*/
const NodeType& at(const KeyType& key) const
{
return nodes.at(key);
}
//! Returns a chain of transformations between nodes.
/*!
*
* @param from starting node.
* @param to end node.
* @return chain of transformations between \p from and \p to.
*/
TfChain<TransformationType> tf(const KeyType& from, const KeyType& to) const
{
const NodeType *from_node = &nodes.at(from);
const NodeType *to_node = &nodes.at(to);
std::list<TransformationType> ret;
size_t common_depth = std::min(from_node->depth(), to_node->depth());
if (from_node->depth() > common_depth)
for (;from_node->depth() != common_depth; from_node = from_node->parent())
ret.push_back(from_node->tf().inverted());
auto insert_pos = ret.end();
if (to_node->depth() > common_depth)
for (; to_node->depth() != common_depth; to_node = to_node->parent())
insert_pos = ret.insert(insert_pos, to_node->tf());
while (from_node->key() != to_node->key())
{
insert_pos = ret.insert(insert_pos, to_node->tf());
ret.insert(insert_pos, from_node->tf().inverted());
from_node = from_node->parent();
to_node = to_node->parent();
}
return TfChain<TransformationType>(ret);
}
private:
//! Recursively erases all children of given and and then the node itself.
/*!
*
* @param key key of the node to be erased.
* @return true on success, false otherwise.
*/
bool eraseSubtree(const KeyType &key)
{
std::vector<KeyType> child_keys;
for (auto c : nodes.at(key).children())
child_keys.push_back(c->key());
for (auto k : child_keys)
eraseSubtree(k);
return nodes.erase(key);
}
//! Creates a rood node with given key.
/*!
*
* @param key key of the root node.
*/
void insertRoot(const KeyType &key)
{
root_node_key = key;
nodes.emplace(key, NodeType(key));
}
std::map<KeyType, NodeType> nodes;
K root_node_key;
};
}
#endif //ROBOTICTEMPLATELIBRARY_TFTREE_H
| 35.11875 | 191 | 0.571098 | [
"vector"
] |
a94899389cc6f94b2737127ce8941cbe5f60e9a4 | 1,059 | h | C | TilesetManager.h | Kodeman010/TurnBasedStrategy | 3a9cd195552dd30cd024322b347d529c87c3597d | [
"Zlib"
] | 1 | 2019-11-17T22:31:11.000Z | 2019-11-17T22:31:11.000Z | TilesetManager.h | Kodeman010/TurnBasedStrategy | 3a9cd195552dd30cd024322b347d529c87c3597d | [
"Zlib"
] | null | null | null | TilesetManager.h | Kodeman010/TurnBasedStrategy | 3a9cd195552dd30cd024322b347d529c87c3597d | [
"Zlib"
] | null | null | null | #pragma once
#include <SFML/Graphics.hpp>
#include "Tile.hpp"
/**
Zbior przechowujacy jeden zbior plytek
*/
class Tileset
{
public:
Tileset(){}
Tileset(sf::Texture texture)
{
this->texture = texture;
}
sf::Texture texture;
std::vector <Tile> tiles;
};
/**
Klasa, ktora zarzadza wszystkimi teksturami w grze. laduje wszystkie potrzebne tekstury, po czym dzieli je na pojedyncze kafelki.
*/
class TilesetManager
{
public:
void loadTexture(const std::string name, const std::string filename);
Tile &getTile(const std::string texture, const int ID);
sf::Texture &getTexture(const std::string texture);
int getSize(const std::string texture);
///Funkcja tnie caly zestaw kafelkow na pojedyncze o wielkosci 50x50 pikseli
void SliceTiles(std::string tilesetName);
///Funkcja zwraca nazwe kolejnego zestawu kafelkow, uzywana jest do iterowania po wszystkich teksturach
std::string getNextTileset(const std::string texture);
const int tileSize = 50;
private:
std::map<std::string, Tileset> tilesets;
};
| 24.627907 | 129 | 0.721435 | [
"vector"
] |
a948c9739e82d8e63b629f05434623728a10344c | 11,642 | h | C | xls/ir/package.h | dnmiller/xls | 56402a14c1f900f6c34a9a779684d14b7ebb88ec | [
"Apache-2.0"
] | 687 | 2020-08-20T21:24:09.000Z | 2022-03-24T11:58:16.000Z | xls/ir/package.h | dnmiller/xls | 56402a14c1f900f6c34a9a779684d14b7ebb88ec | [
"Apache-2.0"
] | 472 | 2020-08-20T20:59:38.000Z | 2022-03-31T15:25:47.000Z | xls/ir/package.h | dnmiller/xls | 56402a14c1f900f6c34a9a779684d14b7ebb88ec | [
"Apache-2.0"
] | 92 | 2020-08-24T20:32:46.000Z | 2022-03-27T21:42:17.000Z | // Copyright 2020 The XLS Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef XLS_IR_PACKAGE_H_
#define XLS_IR_PACKAGE_H_
#include <cstdint>
#include <memory>
#include <string>
#include <vector>
#include "absl/container/flat_hash_map.h"
#include "absl/container/flat_hash_set.h"
#include "absl/container/inlined_vector.h"
#include "absl/container/node_hash_map.h"
#include "absl/status/statusor.h"
#include "absl/strings/string_view.h"
#include "xls/ir/channel.h"
#include "xls/ir/channel.pb.h"
#include "xls/ir/channel_ops.h"
#include "xls/ir/fileno.h"
#include "xls/ir/source_location.h"
#include "xls/ir/type.h"
#include "xls/ir/value.h"
namespace xls {
class Block;
class Channel;
class Function;
class FunctionBase;
class Proc;
class SingleValueChannel;
class StreamingChannel;
class Package {
public:
explicit Package(absl::string_view name,
absl::optional<absl::string_view> entry = absl::nullopt);
// Note: functions have parent pointers to their packages, so we don't want
// them to be moved or copied; this makes Package non-moveable non-copyable.
Package(const Package& other) = delete;
Package& operator=(const Package& other) = delete;
virtual ~Package();
// Returns whether the given type is one of the types owned by this package.
bool IsOwnedType(const Type* type) {
return owned_types_.find(type) != owned_types_.end();
}
bool IsOwnedFunctionType(const FunctionType* function_type) {
return owned_function_types_.find(function_type) !=
owned_function_types_.end();
}
BitsType* GetBitsType(int64_t bit_count);
ArrayType* GetArrayType(int64_t size, Type* element_type);
TupleType* GetTupleType(absl::Span<Type* const> element_types);
TokenType* GetTokenType();
FunctionType* GetFunctionType(absl::Span<Type* const> args_types,
Type* return_type);
// Returns a pointer to a type owned by this package that is of the same
// type as 'other_package_type', which may be owned by another package.
absl::StatusOr<Type*> MapTypeFromOtherPackage(Type* other_package_type);
// Creates and returned an owned type constructed from the given proto.
absl::StatusOr<Type*> GetTypeFromProto(const TypeProto& proto);
absl::StatusOr<FunctionType*> GetFunctionTypeFromProto(
const FunctionTypeProto& proto);
Type* GetTypeForValue(const Value& value);
// Add a function, proc, or block to the package. Ownership is tranferred to
// the package.
Function* AddFunction(std::unique_ptr<Function> f);
Proc* AddProc(std::unique_ptr<Proc> proc);
Block* AddBlock(std::unique_ptr<Block> block);
// Get a function, proc, or block by name. Returns an error if no such
// construct of the indicated kind exists with that name.
absl::StatusOr<Function*> GetFunction(absl::string_view func_name) const;
absl::StatusOr<Proc*> GetProc(absl::string_view proc_name) const;
absl::StatusOr<Block*> GetBlock(absl::string_view block_name) const;
// Remove a function, proc, or block. The caller is responsible for ensuring
// no references to the construct remain (e.g., via invoke operations).
absl::Status RemoveFunction(Function* function);
absl::Status RemoveProc(Proc* proc);
absl::Status RemoveBlock(Block* block);
// Returns the entry function of the package.
absl::StatusOr<Function*> EntryFunction();
absl::StatusOr<const Function*> EntryFunction() const;
// Returns a new SourceLocation object containing a Fileno and Lineno pair.
// SourceLocation objects are added to XLS IR nodes and used for debug
// tracing.
//
// An example of how this function might be used from C++ is shown below:
// __FILE__ and __LINE__ macros are passed as arguments to a SourceLocation
// builder and the result is passed to a Node builder method:
//
// SourceLocation loc = package.AddSourceLocation(__FILE__, __LINE__)
// function_builder.SomeNodeType(node_args, loc);
//
// An alternative front-end could instead call AddSourceLocation with the
// appropriate metadata annotated on the front-end AST.
//
// If the file "filename" has been seen before, the Fileno is retrieved from
// an internal lookup table, otherwise a new Fileno id is generated and added
// to the table.
// TODO(dmlockhart): update to use ABSL_LOC and xabsl::SourceLocation.
SourceLocation AddSourceLocation(absl::string_view filename, Lineno lineno,
Colno colno);
// Translates a SourceLocation object into a human readable debug identifier
// of the form: "<source_file_path>:<line_number>".
std::string SourceLocationToString(const SourceLocation loc);
// Retrieves the next node ID to assign to a node in the package and
// increments the next node counter. For use in node construction.
int64_t GetNextNodeId() { return next_node_id_++; }
// Adds a file to the file-number table and returns its corresponding number.
// If it already exists, returns the existing file-number entry.
Fileno GetOrCreateFileno(absl::string_view filename);
// Returns the total number of nodes in the graph. Traverses the functions and
// sums the node counts.
int64_t GetNodeCount() const;
// Returns the functions in this package.
absl::Span<std::unique_ptr<Function>> functions() {
return absl::MakeSpan(functions_);
}
absl::Span<const std::unique_ptr<Function>> functions() const {
return functions_;
}
// Returns the procs in this package.
absl::Span<std::unique_ptr<Proc>> procs() { return absl::MakeSpan(procs_); }
absl::Span<const std::unique_ptr<Proc>> procs() const { return procs_; }
// Returns the blocks in this package.
absl::Span<std::unique_ptr<Block>> blocks() {
return absl::MakeSpan(blocks_);
}
absl::Span<const std::unique_ptr<Block>> blocks() const { return blocks_; }
// Returns the procs, functions, and blocks in this package (all types derived
// from FunctionBase).
// TODO(meheff): Consider holding functions and procs in a common vector.
std::vector<FunctionBase*> GetFunctionBases() const;
const std::string& name() const { return name_; }
// Returns true if analysis indicates that this package always produces the
// same value as 'other' when run with the same arguments. The analysis is
// conservative and false may be returned for some "equivalent" packages.
bool IsDefinitelyEqualTo(const Package* other) const;
// Dumps the IR in a parsable text format.
std::string DumpIr() const;
std::vector<std::string> GetFunctionNames() const;
// Returns whether this package contains a function with the "target" name.
bool HasFunctionWithName(absl::string_view target) const;
int64_t next_node_id() const { return next_node_id_; }
// Intended for use by the parser when node ids are suggested by the IR text.
void set_next_node_id(int64_t value) { next_node_id_ = value; }
// Create a channel. Channels are used with send/receive nodes in communicate
// between procs or between procs and external (to XLS) components. If no
// channel ID is specified, a unique channel ID will be automatically
// allocated.
// TODO(meheff): Consider using a builder for constructing a channel.
absl::StatusOr<StreamingChannel*> CreateStreamingChannel(
absl::string_view name, ChannelOps supported_ops, Type* type,
absl::Span<const Value> initial_values = {},
FlowControl flow_control = FlowControl::kReadyValid,
const ChannelMetadataProto& metadata = ChannelMetadataProto(),
absl::optional<int64_t> id = absl::nullopt);
absl::StatusOr<SingleValueChannel*> CreateSingleValueChannel(
absl::string_view name, ChannelOps supported_ops, Type* type,
const ChannelMetadataProto& metadata = ChannelMetadataProto(),
absl::optional<int64_t> id = absl::nullopt);
// Returns a span of the channels owned by the package. Sorted by channel ID.
absl::Span<Channel* const> channels() const { return channel_vec_; }
// Returns the channel with the given ID or returns an error if no such
// channel exists.
absl::StatusOr<Channel*> GetChannel(int64_t id) const;
absl::StatusOr<Channel*> GetChannel(absl::string_view name) const;
// Returns whether there exists a channel with the given ID.
bool HasChannelWithId(int64_t id) const {
return channels_.find(id) != channels_.end();
}
// Removes the given channel. If the channel has any associated send/receive
// nodes an error is returned.
absl::Status RemoveChannel(Channel* channel);
private:
// Adds the given channel to the package.
absl::Status AddChannel(std::unique_ptr<Channel> channel);
friend class FunctionBuilder;
absl::optional<std::string> entry_;
// Helper that returns a map from the names of functions inside this package
// to the functions themselves.
absl::flat_hash_map<std::string, Function*> GetFunctionByName();
// Name of this package.
std::string name_;
// Ordinal to assign to the next node created in this package.
int64_t next_node_id_ = 1;
std::vector<std::unique_ptr<Function>> functions_;
std::vector<std::unique_ptr<Proc>> procs_;
std::vector<std::unique_ptr<Block>> blocks_;
// Set of owned types in this package.
absl::flat_hash_set<const Type*> owned_types_;
// Set of owned function types in this package.
absl::flat_hash_set<const FunctionType*> owned_function_types_;
// Mapping from bit count to the owned "bits" type with that many bits. Use
// node_hash_map for pointer stability.
absl::node_hash_map<int64_t, BitsType> bit_count_to_type_;
// Mapping from the size and element type of an array type to the owned
// ArrayType. Use node_hash_map for pointer stability.
using ArrayKey = std::pair<int64_t, const Type*>;
absl::node_hash_map<ArrayKey, ArrayType> array_types_;
// Mapping from elements to the owned tuple type.
//
// Uses node_hash_map for pointer stability.
using TypeVec = absl::InlinedVector<const Type*, 4>;
absl::node_hash_map<TypeVec, TupleType> tuple_types_;
// Owned token type.
TokenType token_type_;
// Mapping from Type:ToString to the owned function type. Use
// node_hash_map for pointer stability.
absl::node_hash_map<std::string, FunctionType> function_types_;
// Mapping of Fileno ids to string filenames, and vice-versa for reverse
// lookups. These two data structures must be updated together for consistency
// and should always contain the same number of entries.
absl::flat_hash_map<Fileno, std::string> fileno_to_filename_;
absl::flat_hash_map<std::string, Fileno> filename_to_fileno_;
// Channels owned by this package. Indexed by channel id. Stored as
// unique_ptrs for pointer stability.
absl::flat_hash_map<int64_t, std::unique_ptr<Channel>> channels_;
// Vector of channel pointers. Kept in sync with the channels_ map. Enables
// easy, stable iteration over channels.
std::vector<Channel*> channel_vec_;
// The next channel ID to assign.
int64_t next_channel_id_ = 0;
};
std::ostream& operator<<(std::ostream& os, const Package& package);
} // namespace xls
#endif // XLS_IR_PACKAGE_H_
| 39.464407 | 80 | 0.735784 | [
"object",
"vector"
] |
a94c222ccf90614073a9111ffca900f80cf9928b | 493 | h | C | libs/curl/cpps_curl.h | johnsonyl/cpps | ed91be2c1107e3cfa8e91d159be81931eacfec19 | [
"MIT"
] | 18 | 2017-09-01T04:59:23.000Z | 2021-09-23T06:42:50.000Z | libs/curl/cpps_curl.h | johnsonyl/cpps | ed91be2c1107e3cfa8e91d159be81931eacfec19 | [
"MIT"
] | null | null | null | libs/curl/cpps_curl.h | johnsonyl/cpps | ed91be2c1107e3cfa8e91d159be81931eacfec19 | [
"MIT"
] | 4 | 2017-06-15T08:46:07.000Z | 2021-06-09T15:03:55.000Z | #pragma once
#include <vector>
#include <string>
#include <sstream>
#include <curl/curl.h>
class cpps_curl
{
public:
cpps_curl();
void append_write_data(const char* data, size_t size);
void append_header(const char* data, size_t size);
std::string getdata();
std::string getheader();
void append_get_data(std::string s);
public:
CURL* curl;
std::vector<struct curl_slist* > slists;
std::string data;
std::string header;
std::stringstream strstream;
};
| 18.961538 | 56 | 0.687627 | [
"vector"
] |
a94f54f50ac46520cc62268f519dc52d7a7b4d80 | 13,169 | h | C | llvm/lib/ExecutionEngine/RuntimeDyld/Targets/RuntimeDyldCOFFAArch64.h | medismailben/llvm-project | e334a839032fe500c3bba22bf976ab7af13ce1c1 | [
"Apache-2.0"
] | 1,570 | 2016-06-30T10:40:04.000Z | 2022-03-31T01:47:33.000Z | llvm/lib/ExecutionEngine/RuntimeDyld/Targets/RuntimeDyldCOFFAArch64.h | medismailben/llvm-project | e334a839032fe500c3bba22bf976ab7af13ce1c1 | [
"Apache-2.0"
] | 59 | 2019-02-26T18:57:27.000Z | 2020-08-04T20:49:55.000Z | llvm/lib/ExecutionEngine/RuntimeDyld/Targets/RuntimeDyldCOFFAArch64.h | medismailben/llvm-project | e334a839032fe500c3bba22bf976ab7af13ce1c1 | [
"Apache-2.0"
] | 253 | 2016-06-30T18:57:10.000Z | 2022-03-25T03:57:40.000Z | //===-- RuntimeDyldCOFFAArch64.h --- COFF/AArch64 specific code ---*- C++
//-*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// COFF AArch64 support for MC-JIT runtime dynamic linker.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_LIB_EXECUTIONENGINE_RUNTIMEDYLD_TARGETS_RUNTIMEDYLDCOFFAARCH64_H
#define LLVM_LIB_EXECUTIONENGINE_RUNTIMEDYLD_TARGETS_RUNTIMEDYLDCOFFAARCH64_H
#include "../RuntimeDyldCOFF.h"
#include "llvm/BinaryFormat/COFF.h"
#include "llvm/Object/COFF.h"
#include "llvm/Support/Endian.h"
#define DEBUG_TYPE "dyld"
using namespace llvm::support::endian;
namespace llvm {
// This relocation type is used for handling long branch instruction
// throught the Stub.
enum InternalRelocationType : unsigned {
INTERNAL_REL_ARM64_LONG_BRANCH26 = 0x111,
};
static void add16(uint8_t *p, int16_t v) { write16le(p, read16le(p) + v); }
static void or32le(void *P, int32_t V) { write32le(P, read32le(P) | V); }
static void write32AArch64Imm(uint8_t *T, uint64_t imm, uint32_t rangeLimit) {
uint32_t orig = read32le(T);
orig &= ~(0xFFF << 10);
write32le(T, orig | ((imm & (0xFFF >> rangeLimit)) << 10));
}
static void write32AArch64Ldr(uint8_t *T, uint64_t imm) {
uint32_t orig = read32le(T);
uint32_t size = orig >> 30;
// 0x04000000 indicates SIMD/FP registers
// 0x00800000 indicates 128 bit
if ((orig & 0x04800000) == 0x04800000)
size += 4;
if ((imm & ((1 << size) - 1)) != 0)
assert(0 && "misaligned ldr/str offset");
write32AArch64Imm(T, imm >> size, size);
}
static void write32AArch64Addr(void *T, uint64_t s, uint64_t p, int shift) {
uint64_t Imm = (s >> shift) - (p >> shift);
uint32_t ImmLo = (Imm & 0x3) << 29;
uint32_t ImmHi = (Imm & 0x1FFFFC) << 3;
uint64_t Mask = (0x3 << 29) | (0x1FFFFC << 3);
write32le(T, (read32le(T) & ~Mask) | ImmLo | ImmHi);
}
class RuntimeDyldCOFFAArch64 : public RuntimeDyldCOFF {
private:
// When a module is loaded we save the SectionID of the unwind
// sections in a table until we receive a request to register all
// unregisteredEH frame sections with the memory manager.
SmallVector<SID, 2> UnregisteredEHFrameSections;
SmallVector<SID, 2> RegisteredEHFrameSections;
uint64_t ImageBase;
// Fake an __ImageBase pointer by returning the section with the lowest adress
uint64_t getImageBase() {
if (!ImageBase) {
ImageBase = std::numeric_limits<uint64_t>::max();
for (const SectionEntry &Section : Sections)
// The Sections list may contain sections that weren't loaded for
// whatever reason: they may be debug sections, and ProcessAllSections
// is false, or they may be sections that contain 0 bytes. If the
// section isn't loaded, the load address will be 0, and it should not
// be included in the ImageBase calculation.
if (Section.getLoadAddress() != 0)
ImageBase = std::min(ImageBase, Section.getLoadAddress());
}
return ImageBase;
}
public:
RuntimeDyldCOFFAArch64(RuntimeDyld::MemoryManager &MM,
JITSymbolResolver &Resolver)
: RuntimeDyldCOFF(MM, Resolver), ImageBase(0) {}
unsigned getStubAlignment() override { return 8; }
unsigned getMaxStubSize() const override { return 20; }
std::tuple<uint64_t, uint64_t, uint64_t>
generateRelocationStub(unsigned SectionID, StringRef TargetName,
uint64_t Offset, uint64_t RelType, uint64_t Addend,
StubMap &Stubs) {
uintptr_t StubOffset;
SectionEntry &Section = Sections[SectionID];
RelocationValueRef OriginalRelValueRef;
OriginalRelValueRef.SectionID = SectionID;
OriginalRelValueRef.Offset = Offset;
OriginalRelValueRef.Addend = Addend;
OriginalRelValueRef.SymbolName = TargetName.data();
auto Stub = Stubs.find(OriginalRelValueRef);
if (Stub == Stubs.end()) {
LLVM_DEBUG(dbgs() << " Create a new stub function for "
<< TargetName.data() << "\n");
StubOffset = Section.getStubOffset();
Stubs[OriginalRelValueRef] = StubOffset;
createStubFunction(Section.getAddressWithOffset(StubOffset));
Section.advanceStubOffset(getMaxStubSize());
} else {
LLVM_DEBUG(dbgs() << " Stub function found for " << TargetName.data()
<< "\n");
StubOffset = Stub->second;
}
// Resolve original relocation to stub function.
const RelocationEntry RE(SectionID, Offset, RelType, Addend);
resolveRelocation(RE, Section.getLoadAddressWithOffset(StubOffset));
// adjust relocation info so resolution writes to the stub function
// Here an internal relocation type is used for resolving long branch via
// stub instruction.
Addend = 0;
Offset = StubOffset;
RelType = INTERNAL_REL_ARM64_LONG_BRANCH26;
return std::make_tuple(Offset, RelType, Addend);
}
Expected<object::relocation_iterator>
processRelocationRef(unsigned SectionID, object::relocation_iterator RelI,
const object::ObjectFile &Obj,
ObjSectionToIDMap &ObjSectionToID,
StubMap &Stubs) override {
auto Symbol = RelI->getSymbol();
if (Symbol == Obj.symbol_end())
report_fatal_error("Unknown symbol in relocation");
Expected<StringRef> TargetNameOrErr = Symbol->getName();
if (!TargetNameOrErr)
return TargetNameOrErr.takeError();
StringRef TargetName = *TargetNameOrErr;
auto SectionOrErr = Symbol->getSection();
if (!SectionOrErr)
return SectionOrErr.takeError();
auto Section = *SectionOrErr;
uint64_t RelType = RelI->getType();
uint64_t Offset = RelI->getOffset();
// If there is no section, this must be an external reference.
const bool IsExtern = Section == Obj.section_end();
// Determine the Addend used to adjust the relocation value.
uint64_t Addend = 0;
SectionEntry &AddendSection = Sections[SectionID];
uintptr_t ObjTarget = AddendSection.getObjAddress() + Offset;
uint8_t *Displacement = (uint8_t *)ObjTarget;
switch (RelType) {
case COFF::IMAGE_REL_ARM64_ADDR32:
case COFF::IMAGE_REL_ARM64_ADDR32NB:
case COFF::IMAGE_REL_ARM64_REL32:
case COFF::IMAGE_REL_ARM64_SECREL:
Addend = read32le(Displacement);
break;
case COFF::IMAGE_REL_ARM64_BRANCH26: {
uint32_t orig = read32le(Displacement);
Addend = (orig & 0x03FFFFFF) << 2;
if (IsExtern)
std::tie(Offset, RelType, Addend) = generateRelocationStub(
SectionID, TargetName, Offset, RelType, Addend, Stubs);
break;
}
case COFF::IMAGE_REL_ARM64_BRANCH19: {
uint32_t orig = read32le(Displacement);
Addend = (orig & 0x00FFFFE0) >> 3;
break;
}
case COFF::IMAGE_REL_ARM64_BRANCH14: {
uint32_t orig = read32le(Displacement);
Addend = (orig & 0x000FFFE0) >> 3;
break;
}
case COFF::IMAGE_REL_ARM64_REL21:
case COFF::IMAGE_REL_ARM64_PAGEBASE_REL21: {
uint32_t orig = read32le(Displacement);
Addend = ((orig >> 29) & 0x3) | ((orig >> 3) & 0x1FFFFC);
break;
}
case COFF::IMAGE_REL_ARM64_PAGEOFFSET_12L:
case COFF::IMAGE_REL_ARM64_PAGEOFFSET_12A: {
uint32_t orig = read32le(Displacement);
Addend = ((orig >> 10) & 0xFFF);
break;
}
case COFF::IMAGE_REL_ARM64_ADDR64: {
Addend = read64le(Displacement);
break;
}
default:
break;
}
#if !defined(NDEBUG)
SmallString<32> RelTypeName;
RelI->getTypeName(RelTypeName);
LLVM_DEBUG(dbgs() << "\t\tIn Section " << SectionID << " Offset " << Offset
<< " RelType: " << RelTypeName << " TargetName: "
<< TargetName << " Addend " << Addend << "\n");
#endif
unsigned TargetSectionID = -1;
if (IsExtern) {
RelocationEntry RE(SectionID, Offset, RelType, Addend);
addRelocationForSymbol(RE, TargetName);
} else {
if (auto TargetSectionIDOrErr = findOrEmitSection(
Obj, *Section, Section->isText(), ObjSectionToID)) {
TargetSectionID = *TargetSectionIDOrErr;
} else
return TargetSectionIDOrErr.takeError();
uint64_t TargetOffset = getSymbolOffset(*Symbol);
RelocationEntry RE(SectionID, Offset, RelType, TargetOffset + Addend);
addRelocationForSection(RE, TargetSectionID);
}
return ++RelI;
}
void resolveRelocation(const RelocationEntry &RE, uint64_t Value) override {
const auto Section = Sections[RE.SectionID];
uint8_t *Target = Section.getAddressWithOffset(RE.Offset);
uint64_t FinalAddress = Section.getLoadAddressWithOffset(RE.Offset);
switch (RE.RelType) {
default:
llvm_unreachable("unsupported relocation type");
case COFF::IMAGE_REL_ARM64_ABSOLUTE: {
// This relocation is ignored.
break;
}
case COFF::IMAGE_REL_ARM64_PAGEBASE_REL21: {
// The page base of the target, for ADRP instruction.
Value += RE.Addend;
write32AArch64Addr(Target, Value, FinalAddress, 12);
break;
}
case COFF::IMAGE_REL_ARM64_REL21: {
// The 12-bit relative displacement to the target, for instruction ADR
Value += RE.Addend;
write32AArch64Addr(Target, Value, FinalAddress, 0);
break;
}
case COFF::IMAGE_REL_ARM64_PAGEOFFSET_12A: {
// The 12-bit page offset of the target,
// for instructions ADD/ADDS (immediate) with zero shift.
Value += RE.Addend;
write32AArch64Imm(Target, Value & 0xFFF, 0);
break;
}
case COFF::IMAGE_REL_ARM64_PAGEOFFSET_12L: {
// The 12-bit page offset of the target,
// for instruction LDR (indexed, unsigned immediate).
Value += RE.Addend;
write32AArch64Ldr(Target, Value & 0xFFF);
break;
}
case COFF::IMAGE_REL_ARM64_ADDR32: {
// The 32-bit VA of the target.
uint32_t VA = Value + RE.Addend;
write32le(Target, VA);
break;
}
case COFF::IMAGE_REL_ARM64_ADDR32NB: {
// The target's 32-bit RVA.
uint64_t RVA = Value + RE.Addend - getImageBase();
write32le(Target, RVA);
break;
}
case INTERNAL_REL_ARM64_LONG_BRANCH26: {
// Encode the immadiate value for generated Stub instruction (MOVZ)
or32le(Target + 12, ((Value + RE.Addend) & 0xFFFF) << 5);
or32le(Target + 8, ((Value + RE.Addend) & 0xFFFF0000) >> 11);
or32le(Target + 4, ((Value + RE.Addend) & 0xFFFF00000000) >> 27);
or32le(Target + 0, ((Value + RE.Addend) & 0xFFFF000000000000) >> 43);
break;
}
case COFF::IMAGE_REL_ARM64_BRANCH26: {
// The 26-bit relative displacement to the target, for B and BL
// instructions.
uint64_t PCRelVal = Value + RE.Addend - FinalAddress;
assert(isInt<28>(PCRelVal) && "Branch target is out of range.");
write32le(Target, (read32le(Target) & ~(0x03FFFFFF)) |
(PCRelVal & 0x0FFFFFFC) >> 2);
break;
}
case COFF::IMAGE_REL_ARM64_BRANCH19: {
// The 19-bit offset to the relocation target,
// for conditional B instruction.
uint64_t PCRelVal = Value + RE.Addend - FinalAddress;
assert(isInt<21>(PCRelVal) && "Branch target is out of range.");
write32le(Target, (read32le(Target) & ~(0x00FFFFE0)) |
(PCRelVal & 0x001FFFFC) << 3);
break;
}
case COFF::IMAGE_REL_ARM64_BRANCH14: {
// The 14-bit offset to the relocation target,
// for instructions TBZ and TBNZ.
uint64_t PCRelVal = Value + RE.Addend - FinalAddress;
assert(isInt<16>(PCRelVal) && "Branch target is out of range.");
write32le(Target, (read32le(Target) & ~(0x000FFFE0)) |
(PCRelVal & 0x0000FFFC) << 3);
break;
}
case COFF::IMAGE_REL_ARM64_ADDR64: {
// The 64-bit VA of the relocation target.
write64le(Target, Value + RE.Addend);
break;
}
case COFF::IMAGE_REL_ARM64_SECTION: {
// 16-bit section index of the section that contains the target.
assert(static_cast<uint32_t>(RE.SectionID) <= UINT16_MAX &&
"relocation overflow");
add16(Target, RE.SectionID);
break;
}
case COFF::IMAGE_REL_ARM64_SECREL: {
// 32-bit offset of the target from the beginning of its section.
assert(static_cast<int64_t>(RE.Addend) <= INT32_MAX &&
"Relocation overflow");
assert(static_cast<int64_t>(RE.Addend) >= INT32_MIN &&
"Relocation underflow");
write32le(Target, RE.Addend);
break;
}
case COFF::IMAGE_REL_ARM64_REL32: {
// The 32-bit relative address from the byte following the relocation.
uint64_t Result = Value - FinalAddress - 4;
write32le(Target, Result + RE.Addend);
break;
}
}
}
void registerEHFrames() override {}
};
} // End namespace llvm
#endif
| 35.980874 | 80 | 0.647278 | [
"object"
] |
a95261d2d7d4fcc1165b236e1a2f80c9a604b08d | 1,339 | h | C | Externals/libNeuropix/include/TestConfiguration.h | kampff-lab/bonsai.neuropix | 1c852a18830f2de0a3d4a400052f98b54ba9b6be | [
"MIT"
] | null | null | null | Externals/libNeuropix/include/TestConfiguration.h | kampff-lab/bonsai.neuropix | 1c852a18830f2de0a3d4a400052f98b54ba9b6be | [
"MIT"
] | null | null | null | Externals/libNeuropix/include/TestConfiguration.h | kampff-lab/bonsai.neuropix | 1c852a18830f2de0a3d4a400052f98b54ba9b6be | [
"MIT"
] | null | null | null | /**
* @file Testconfiguration.h
* This file defines the contents of the test configuration shift register.
*/
#ifndef TestConfiguration_h_
#define TestConfiguration_h_
#include "dll_import_export.h"
#include <vector>
class TestConfiguration
{
public:
TestConfiguration();
~TestConfiguration();
/**
* This function sets all members to their default values.
*/
void reset();
/**
* This function combines all members to the chain of bools as needed for the
* shift register.
*
* @param chain : the chain to return
*/
void getChain(std::vector<bool> & chain);
/**
* This function translates the chain from the shift register to the members
* of the test configuration.
*
* @param chain : the chain to translate
*/
void getTestConfigFromChain(std::vector<bool> & chain);
bool digi[2]; // selection of internal test points
bool adcdata; // test of parallel ADC data
bool digi2[2]; // selection of internal test points (b:1, a:0)
bool fclk; // select filter clk source
bool muxAna; // test of mux output selection
bool muxa; // select mux control signal source
bool lfp[4]; // test of lfp channel output selection
bool ap[4]; // test of ap channel output selection
bool pocl[2]; // test of pixel output selection (b:1, a:0)
private:
};
#endif
| 23.491228 | 79 | 0.684093 | [
"vector"
] |
a95e958d5c183f6aaa04d9cb1bac6ce31533ddb9 | 3,114 | h | C | Pods/ABFRealmMapView/ABFRealmMapView/ABFLocationFetchRequest.h | MichaelGuoXY/FindMyGoat | b3d0612065a7d2f0b1f52a85e9479bcb6886c1c7 | [
"MIT"
] | null | null | null | Pods/ABFRealmMapView/ABFRealmMapView/ABFLocationFetchRequest.h | MichaelGuoXY/FindMyGoat | b3d0612065a7d2f0b1f52a85e9479bcb6886c1c7 | [
"MIT"
] | null | null | null | Pods/ABFRealmMapView/ABFRealmMapView/ABFLocationFetchRequest.h | MichaelGuoXY/FindMyGoat | b3d0612065a7d2f0b1f52a85e9479bcb6886c1c7 | [
"MIT"
] | null | null | null | //
// ABFLocationFetchRequest.h
// ABFRealmMapViewControllerExample
//
// Created by Adam Fish on 6/3/15.
// Copyright (c) 2015 Adam Fish. All rights reserved.
//
@import MapKit;
#if __has_include(<RealmMapView/RealmMapView-BridgingHeader.h>)
@import RBQFetchedResultsController;
#else
#import <RBQFetchedResultsController/RBQFetchRequest.h>
#endif
/**
* Converts a MKCoordinate region to an NSPredicate
*
* If the region span cross the -180/180 longitude meridian, the return value is an NSCompoundPredicate containing two NSPredicates that comprise of the region before the meridian and another region of the overflow beyond it.
*
* @param region MKCoordinate region representing the location fetch limits
* @param latitudeKeyPath the latitude key path for the value to test the latitude limits against
* @param longitudeKeyPath the longitude key path for the value to test the longitude limits against
*
* @return instance of NSPredicate (can be NSCompoundPredicate, see description for more info)
*/
NS_ASSUME_NONNULL_BEGIN
extern NSPredicate * NSPredicateForCoordinateRegion(MKCoordinateRegion region,
NSString *latitudeKeyPath,
NSString *longitudeKeyPath);
NS_ASSUME_NONNULL_END
/**
* Location specific subclass of RBQFetchRequest that allows for location fetching on Realm objects that contain latitude and longitude values.
*
* Location fetch is defined by a MKCoordinate region and is converted into a predicate for Realm querying.
*/
@interface ABFLocationFetchRequest : RBQFetchRequest
/**
* Latitude key path on the Realm object for entityName
*/
@property (nonatomic, readonly, nonnull) NSString *latitudeKeyPath;
/**
* Longitude key path on the Realm object for entityName
*/
@property (nonatomic, readonly, nonnull) NSString *longitudeKeyPath;
/**
* Region that defines the fetch boundaries
*/
@property (nonatomic, readonly) MKCoordinateRegion region;
/**
* Creates a ABFLocationFetchRequest instance that defines a fetch based off of a coordinate region boundary.
*
* @param entityName the Realm object name (class name)
* @param realm the RLMRealm in which the entity(s) exist
* @param latitudeKeyPath the latitude key path for the value to test the latitude limits against
* @param longitudeKeyPath the longitude key path for the value to test the longitude limits against
* @param region the region that represents the search boundary
*
* @return an instance of ABFLocationFetchRequest that contains the NSPredicate for the fetch
*/
+ (nonnull instancetype)locationFetchRequestWithEntityName:(nonnull NSString *)entityName
inRealm:(nonnull RLMRealm *)realm
latitudeKeyPath:(nonnull NSString *)latitudeKeyPath
longitudeKeyPath:(nonnull NSString *)longitudeKeyPath
forRegion:(MKCoordinateRegion)region;
@end
| 42.657534 | 226 | 0.707129 | [
"object"
] |
a96171c10412580eebc645820151ba2a30c27a7d | 5,947 | h | C | Source/VelocityCurveEditStrategy.h | hsstraub/TerpstraSysEx.2014 | d032f9d60c1eee6afd381e2825648f74c6b24481 | [
"BSD-3-Clause"
] | 5 | 2015-02-18T21:50:47.000Z | 2022-02-15T00:31:13.000Z | Source/VelocityCurveEditStrategy.h | hsstraub/TerpstraSysEx.2014 | d032f9d60c1eee6afd381e2825648f74c6b24481 | [
"BSD-3-Clause"
] | 3 | 2015-02-16T18:40:34.000Z | 2021-09-08T00:05:15.000Z | Source/VelocityCurveEditStrategy.h | hsstraub/TerpstraSysEx.2014 | d032f9d60c1eee6afd381e2825648f74c6b24481 | [
"BSD-3-Clause"
] | 3 | 2019-03-22T17:49:47.000Z | 2022-02-15T00:30:44.000Z | /*
==============================================================================
VelocityCurveEditStrategy.h
Created: 10 Apr 2019 9:54:14pm
Author: hsstraub
==============================================================================
*/
#pragma once
#include "../JuceLibraryCode/JuceHeader.h"
#include "VelocityCurveComponents.h"
/*
==============================================================================
Base class for velocity curve editing
==============================================================================
*/
class VelocityCurveEditStrategyBase
{
public:
VelocityCurveEditStrategyBase(Path& beamTableFrameRef, std::unique_ptr<VelocityCurveBeam>* velocityBeamTablePtr);
// Set value table (e. g. from LMT file)
virtual bool setEditConfig(int velocityTableValues[]) = 0;
// Export value table (for saving in LMT file)
virtual bool exportEditConfig(int velocityTableValues[]) = 0;
// Takes a given velocity table and tries to extract edit parameters. Returns whether it was successful.
virtual bool setEditConfigFromVelocityTable() { return true; }
// Sets velocity table values from edit parameters
virtual void setVelocityTableValuesFromEditConfig() {}
virtual String getDescriptionText() { return "Click with the mouse in the graphics to draw the velocity curve."; }
virtual void paint(Graphics& g, LookAndFeel& lookAndFeel) { };
// Resize functionality. Assumes that beamTableFrame has already been resized.
virtual void resized() { }
// return: true if a repainting is to be done
virtual bool mouseMove(const MouseEvent &event, juce::Point<float> localPoint) { return false; };
// return: true if some editing was done
virtual bool mouseDown(const MouseEvent &event, juce::Point<float> localPoint) { return false; }
virtual bool mouseDrag(const MouseEvent &event, juce::Point<float> localPoint) { return false; };
virtual void mouseUp(const MouseEvent &event, juce::Point<float> localPoint) { };
protected:
Path& beamTableFrame;
std::unique_ptr<VelocityCurveBeam>* velocityBeamTable;
};
/*
==============================================================================
Velocity curve editing via free drawing
==============================================================================
*/
class VelocityCurveFreeDrawingStrategy : public VelocityCurveEditStrategyBase
{
public:
VelocityCurveFreeDrawingStrategy(Path& beamTableFrameRef, std::unique_ptr<VelocityCurveBeam>* velocityBeamTablePtr);
bool setEditConfig(int velocityTableValues[]) override;
bool exportEditConfig(int velocityTableValues[]) override;
void paint(Graphics& g, LookAndFeel& lookAndFeel) override;
void resized() override;
bool mouseDown(const MouseEvent &event, juce::Point<float> localPoint) override;
bool mouseDrag(const MouseEvent &event, juce::Point<float> localPoint) override;
void mouseUp(const MouseEvent &event, juce::Point<float> localPoint) override;
protected:
Path drawedLine;
};
/*
==============================================================================
Base class for velocity curve editing with segments
==============================================================================
*/
class VelocityCurveSegmentEditStrategyBase : public VelocityCurveEditStrategyBase
{
public:
VelocityCurveSegmentEditStrategyBase(Path& beamTableFrameRef, std::unique_ptr<VelocityCurveBeam>* velocityBeamTablePtr);
bool setEditConfig(int velocityTableValues[]) override;
bool exportEditConfig(int velocityTableValues[]) override;
String getDescriptionText() override { return "Click with the mouse in the graphics to draw the velocity curve. Right-click to delete a segment point."; }
void paint(Graphics& g, LookAndFeel& lookAndFeel) override;
bool mouseMove(const MouseEvent &event, juce::Point<float> localPoint) override;
bool mouseDown(const MouseEvent &event, juce::Point<float> localPoint) override;
bool mouseDrag(const MouseEvent &event, juce::Point<float> localPoint) override;
void mouseUp(const MouseEvent &event, juce::Point<float> localPoint) override;
protected:
bool isDragging() { return draggedOriginalXPosition >= 0; }
Array<juce::Point<float>> getSegmentPoints();
virtual Path createCurveToDraw() = 0;
void drawSegmentPoints(Graphics& g, LookAndFeel& lookAndFeel);
void drawCurve(Graphics& g, LookAndFeel& lookAndFeel);
// y-components of vector line point, -1 if no line points
int fixPointBeamHeights[128];
int mouseXPosition;
int draggedOriginalXPosition;
int minDragXPosition;
int maxDragXPosition;
};
/*
==============================================================================
Velocity curve editing via line segments
==============================================================================
*/
class VelocityCurveLinearDrawingStrategy : public VelocityCurveSegmentEditStrategyBase
{
public:
VelocityCurveLinearDrawingStrategy(Path& beamTableFrameRef, std::unique_ptr<VelocityCurveBeam>* velocityBeamTablePtr);
bool setEditConfigFromVelocityTable() override;
void setVelocityTableValuesFromEditConfig() override;
protected:
Path createCurveToDraw() override;
// Points that are part of a straight line can be removed
void clearSuperfluousPoints();
};
/*
==============================================================================
Velocity curve editing via quadratic curves
==============================================================================
*/
class VelocityCurveQuadraticDrawingStrategy : public VelocityCurveSegmentEditStrategyBase
{
public:
VelocityCurveQuadraticDrawingStrategy(Path& beamTableFrameRef, std::unique_ptr<VelocityCurveBeam>* velocityBeamTablePtr);
bool setEditConfigFromVelocityTable() override;
void setVelocityTableValuesFromEditConfig() override;
protected:
Path createCurveToDraw() override;
};
| 37.878981 | 156 | 0.645199 | [
"vector"
] |
a965a0090e0d0d0324d4264e654db3e9a924c46c | 17,636 | c | C | src/lib/NeuralNetwork.c | Lut99/NeuralNetwork | ea9e72ef55eb76abfd7f82744c301fab4b3f7604 | [
"MIT"
] | null | null | null | src/lib/NeuralNetwork.c | Lut99/NeuralNetwork | ea9e72ef55eb76abfd7f82744c301fab4b3f7604 | [
"MIT"
] | null | null | null | src/lib/NeuralNetwork.c | Lut99/NeuralNetwork | ea9e72ef55eb76abfd7f82744c301fab4b3f7604 | [
"MIT"
] | null | null | null | /* NEURAL NETWORK.c
* by Lut99
*
* Created:
* 6/1/2020, 1:15:46 PM
* Last edited:
* 19/11/2020, 16:44:37
* Auto updated?
* Yes
*
* Description:
* The NeuralNetwork class implements a matrix-based Feedforward Neural
* Network which is hardcoded to use Mean Squared Error for cost function and
* sigmoid as activation function.
*
* This file implements the common functions for the NeuralNetwork. Note that
* the training function and argument parse functions are for specific
* optimisations of the NeuralNetwork, which can be found in the
* 'NeuralNetwork/' directory.
**/
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include "NeuralNetwork.h"
#define WEIGHTS_MIN -3.0
#define WEIGHTS_MAX 3.0
#define BIAS_MIN -3.0
#define BIAS_MAX 3.0
/***** HELPER FUNCTIONS *****/
/* Returns the maximum size_t in a list of size_ts. */
size_t max(size_t size, const size_t* data) {
size_t m = 0;
for (size_t i = 0; i < size; i++) {
if (data[i] > m) {
m = data[i];
}
}
return m;
}
/* Creates and initialises a bias matrix for the number of given nodes. */
double* initialize_biases(size_t n_nodes) {
// Create a new matrix of the proper dimensions
double* to_ret = malloc(sizeof(double) * n_nodes);
// Set each value to a random one in the range BIAS_MIN (inclusive) and BIAS_MAX (exclusive)
for (size_t i = 0; i < n_nodes; i++) {
to_ret[i] = (double)rand()/RAND_MAX * (BIAS_MAX - BIAS_MIN) + BIAS_MIN;
}
// Return
return to_ret;
}
/* Creates and initialises a weights matrix of given proportions. */
double* initialize_weights(size_t input_size, size_t output_size) {
// Create a new matrix of the proper dimensions
double* to_ret = malloc(sizeof(double) * input_size * output_size);
// Set each value to a random one in the range WEIGHTS_MIN (inclusive) and WEIGHTS_MAX (exclusive)
for (size_t i = 0; i < input_size * output_size; i++) {
to_ret[i] = (double)rand()/RAND_MAX * (WEIGHTS_MAX - WEIGHTS_MIN) + WEIGHTS_MIN;
}
// Return
return to_ret;
}
/***** MEMORY MANAGEMENT *****/
neural_net* create_nn(size_t input_nodes, size_t n_hidden_layers, size_t hidden_nodes[n_hidden_layers], size_t output_nodes) {
// Start by seeding the pseudo-random number generator
srand(time(NULL));
// Create a new neural net object
neural_net* to_ret = malloc(sizeof(neural_net));
if (to_ret == NULL) {
fprintf(stderr, "ERROR: create_nn: could not allocate struct (%lu bytes).\n",
sizeof(neural_net));
return NULL;
}
// Fill in the size values
to_ret->n_layers = n_hidden_layers + 2;
to_ret->n_weights = to_ret->n_layers - 1;
// Allocate the required lists for the neural network
to_ret->nodes_per_layer = malloc(sizeof(size_t) * to_ret->n_layers);
to_ret->biases = malloc(sizeof(double*) * to_ret->n_weights);
to_ret->weights = malloc(sizeof(double*) * to_ret->n_weights);
if (to_ret->nodes_per_layer == NULL) {
fprintf(stderr, "ERROR: create_nn: could not allocate nodes list (%lu bytes).\n",
sizeof(size_t) * to_ret->n_layers);
return NULL;
} else if (to_ret->biases == NULL) {
fprintf(stderr, "ERROR: create_nn: could not allocate biases list (%lu bytes).\n",
sizeof(double*) * to_ret->n_weights);
return NULL;
} else if (to_ret->weights == NULL) {
fprintf(stderr, "ERROR: create_nn: could not allocate weights list (%lu bytes).\n",
sizeof(double*) * to_ret->n_weights);
return NULL;
}
// Store the number of nodes per layer
for (size_t i = 0; i < n_hidden_layers; i++) {
to_ret->nodes_per_layer[i + 1] = hidden_nodes[i];
}
// Also add the input and output layers
to_ret->nodes_per_layer[0] = input_nodes;
to_ret->nodes_per_layer[to_ret->n_layers - 1] = output_nodes;
// Initialise the biases and weights of the neural network randomly
for (size_t i = 0; i < to_ret->n_weights; i++) {
to_ret->biases[i] = initialize_biases(to_ret->nodes_per_layer[i + 1]);
if (to_ret->biases[i] == NULL) {
fprintf(stderr, "ERROR: create_nn: could not initialize bias (%lu/%lu).\n",
i + 1, to_ret->n_weights);
return NULL;
}
to_ret->weights[i] = initialize_weights(to_ret->nodes_per_layer[i], to_ret->nodes_per_layer[i + 1]);
if (to_ret->weights[i] == NULL) {
fprintf(stderr, "ERROR: create_nn: could not initialize weight (%lu/%lu).\n",
i + 1, to_ret->n_weights);
return NULL;
}
}
// Done, return
return to_ret;
}
void destroy_nn(neural_net* nn) {
free(nn->nodes_per_layer);
for (size_t i = 0; i < nn->n_weights; i++) {
free(nn->biases[i]);
free(nn->weights[i]);
}
free(nn->biases);
free(nn->weights);
free(nn);
}
/***** NEURAL NETWORK OPERATIONS *****/
void nn_forward(neural_net* nn, size_t n_samples, double* outputs, double** inputs) {
double** biases = nn->biases;
double** weights = nn->weights;
// Declare a temporary inputs and outputs list
size_t max_nodes = max(nn->n_layers, nn->nodes_per_layer);
double* intermediate_inputs = malloc(sizeof(double) * max_nodes);
double* intermediate_outputs = malloc(sizeof(double) * max_nodes);
// Loop through all samples to compute the forward cost
size_t last_nodes = nn->nodes_per_layer[nn->n_layers - 1];
for (size_t s = 0; s < n_samples; s++) {
// Initialize the intermediate inputs to the real inputs for this sample
memcpy(intermediate_inputs, inputs[s], sizeof(double) * nn->nodes_per_layer[0]);
// Iterate over each layer to feedforward through the network
for (size_t l = 1; l < nn->n_layers; l++) {
// Get some references to the bias list and weight matrix
double* bias = biases[l - 1];
double* weight = weights[l - 1];
// Compute the activation for each node on this layer
size_t this_nodes = nn->nodes_per_layer[l];
size_t prev_nodes = nn->nodes_per_layer[l - 1];
for (size_t n = 0; n < this_nodes; n++) {
// Sum the weighted inputs for this node
double z = bias[n];
for (size_t prev_n = 0; prev_n < prev_nodes; prev_n++) {
z += intermediate_inputs[prev_n] * weight[prev_n * this_nodes + n];
}
// Run the activation function over this input and store it in the output
intermediate_outputs[n] = 1 / (1 + exp(-z));
}
// Swap the pointers
double* temp = intermediate_inputs;
intermediate_inputs = intermediate_outputs;
intermediate_outputs = temp;
}
// Copy the intermediate outputs (due to swapping, this is intermediate_inputs) for this sample to the eventual outputs of this sample
memcpy(outputs + s * last_nodes, intermediate_inputs, sizeof(double) * last_nodes);
}
// Destroy the intermediate lists
free(intermediate_inputs);
free(intermediate_outputs);
}
double* nn_train_costs(neural_net* nn, size_t n_samples, double** inputs, double** expected, double learning_rate, size_t n_iterations) {
// Allocate an array for the costs and initialize the scratchpad memory to the correct size
double* costs = malloc(sizeof(double) * n_iterations);
// Set them all to zero
for (size_t i = 0; i < n_iterations; i++) {
costs[i] = 0;
}
// Also obtain links to all biases / matrices
double** biases = nn->biases;
double** weights = nn->weights;
// Initialize the temporary delta memory to the correct size
double* deltas = malloc(sizeof(double) * max(nn->n_layers, nn->nodes_per_layer));
// Create a list that is used to store intermediate outputs. The first input layer (=first column)
// is linked and not copied to the input data
double* layer_outputs[n_samples][nn->n_layers];
for (size_t s = 0; s < n_samples; s++) {
// Link the input layer
layer_outputs[s][0] = inputs[s];
// Allocate arrays for the other layers
for (size_t l = 1; l < nn->n_layers; l++) {
layer_outputs[s][l] = malloc(sizeof(double) * nn->nodes_per_layer[l]);
}
}
// Create the delta_biases and delta_weights arrays / matrices
double* delta_biases[nn->n_weights];
double* delta_weights[nn->n_weights];
for(size_t l = 0; l < nn->n_weights; l++) {
delta_biases[l] = malloc(sizeof(double) * nn->nodes_per_layer[l + 1]);
delta_weights[l] = malloc(sizeof(double) * nn->nodes_per_layer[l] * nn->nodes_per_layer[l + 1]);
// Fill with zeros
for (size_t n = 0; n < nn->nodes_per_layer[l + 1]; n++) {
delta_biases[l][n] = 0;
for (size_t prev_n = 0; prev_n < nn->nodes_per_layer[l]; prev_n++) {
delta_weights[l][prev_n * nn->nodes_per_layer[l + 1] + n] = 0;
}
}
}
// Perform the training for n_iterations (always)
for (size_t i = 0; i < n_iterations; i++) {
/***** FORWARD PASS *****/
// Loop through all samples to compute the forward cost
for (size_t s = 0; s < n_samples; s++) {
// Perform a forward pass through the network to be able to say something about the performance
// sample_outputs is a 2D flattened array for this layer
double** sample_outputs = layer_outputs[s];
// Iterate over each layer to feedforward through the network
for (size_t l = 1; l < nn->n_layers; l++) {
// Get some references to the bias list, weight matrix and outputs of the previous and this layer
double* bias = biases[l - 1];
double* weight = weights[l - 1];
double* prev_output = sample_outputs[l - 1];
double* output = sample_outputs[l];
// Compute the activation for each node on this layer
size_t this_nodes = nn->nodes_per_layer[l];
size_t prev_nodes = nn->nodes_per_layer[l - 1];
for (size_t n = 0; n < this_nodes; n++) {
// Sum the weighted inputs for this node
double z = bias[n];
for (size_t prev_n = 0; prev_n < prev_nodes; prev_n++) {
z += prev_output[prev_n] * weight[prev_n * this_nodes + n];
}
// Run the activation function over this input and store it in the output
output[n] = 1 / (1 + exp(-z));
}
}
// Compute the cost for this sample
double cost = 0;
for (size_t n = 0; n < nn->nodes_per_layer[nn->n_layers - 1]; n++) {
double err = (sample_outputs[nn->n_layers - 1][n] - expected[s][n]);
cost += err * err;
}
costs[i] += cost / nn->nodes_per_layer[nn->n_layers - 1];
}
// Report it once every hundred
if (i % 100 == 0) {
printf(" (Iter %lu) Cost: %.4f\n", i, costs[i]);
}
/***** BACKWARD PASS *****/
// Implementation: https://towardsdatascience.com/simple-neural-network-implementation-in-c-663f51447547
// Loop through all samples to compute the backward cost
for (size_t s = 0; s < n_samples; s++) {
// Backpropagate the error from the last layer to the first.
double** sample_outputs = layer_outputs[s];
double* sample_expected = expected[s];
for (size_t l = nn->n_layers - 1; l > 0; l--) {
// Set shortcuts to some values used both in delta computing and weight / bias updating
size_t this_nodes = nn->nodes_per_layer[l];
double* output = sample_outputs[l];
// Compute the deltas of the correct layer
if (l == nn->n_layers - 1) {
// Deltas for output layer
// Loop through all nodes in this layer to compute their deltas
for (size_t n = 0; n < this_nodes; n++) {
double output_val = output[n];
deltas[n] = (sample_expected[n] - output_val) * output_val * (1 - output_val);
}
} else {
// Deltas for any hidden layer
// Loop through all nodes in this layer to compute their deltas by summing all deltas of the next layer in a weighted fashion
size_t next_nodes = nn->nodes_per_layer[l + 1];
double* weight_next = weights[l];
for (size_t n = 0; n < this_nodes; n++) {
// Take the weighted sum of all connection of that node with this layer
double error = 0;
for (size_t next_n = 0; next_n < next_nodes; next_n++) {
error += deltas[next_n] * weight_next[n * next_nodes + next_n];
}
// Multiply the error with the derivative of the activation function to find the result
double output_val = output[n];
deltas[n] = error * output_val * (1 - output_val);
}
}
// Set some shutcuts for weight updating alone so they don't have to be recomputed each iteration
size_t prev_nodes = nn->nodes_per_layer[l - 1];
double* delta_bias = delta_biases[l - 1];
double* delta_weight = delta_weights[l - 1];
double* prev_output = sample_outputs[l - 1];
// Add all deltas as delta_biases for this layer
for (size_t n = 0; n < this_nodes; n++) {
delta_bias[n] += deltas[n];
}
// Same for all the weights, except we compute the delta_weights first
for (size_t prev_n = 0; prev_n < prev_nodes; prev_n++) {
for (size_t n = 0; n < this_nodes; n++) {
delta_weight[prev_n * this_nodes + n] += prev_output[prev_n] * deltas[n];
}
}
}
}
// Actually update the weights, and reset the delta updates to 0 for next iteration
for (size_t l = 0; l < nn->n_weights; l++) {
double* bias = biases[l];
double* delta_bias = delta_biases[l];
double* weight = weights[l];
double* delta_weight = delta_weights[l];
// Update the biases & reset delta_biases
size_t this_nodes = nn->nodes_per_layer[l + 1];
for (size_t n = 0; n < this_nodes; n++) {
bias[n] += delta_bias[n] * learning_rate;
delta_bias[n] = 0;
}
// Update the weights & reset delta_weights
size_t prev_nodes = nn->nodes_per_layer[l];
for (size_t i = 0; i < this_nodes * prev_nodes; i++) {
weight[i] += delta_weight[i] * learning_rate;
delta_weight[i] = 0;
}
}
}
// Cleanup
// Free the delta biases / weights
for(size_t l = 0; l < nn->n_layers - 1; l++) {
free(delta_biases[l]);
free(delta_weights[l]);
}
// Free the layer_outputs (skip the first, as these merely link the input rather than copy 'em)
for (size_t s = 0; s < n_samples; s++) {
for (size_t l = 1; l < nn->n_layers; l++) {
free(layer_outputs[s][l]);
}
}
// Cleanup the deltas
free(deltas);
return costs;
}
/***** VALIDATION TOOLS *****/
void flatten_output(size_t n_samples, size_t last_nodes, double* outputs) {
for (size_t s = 0; s < n_samples; s++) {
double* output = outputs + s * last_nodes;
// First pass: collect the highest value of this sample
double max_value = -INFINITY;
double max_index = 0;
for (size_t n = 0; n < last_nodes; n++) {
if (output[n] > max_value) {
max_value = output[n];
max_index = n;
}
}
// Second pass: set all to 0, save for the highest value, which will be set to 1
for (size_t n = 0; n < last_nodes; n++) {
output[n] = n == max_index ? 1.0 : 0.0;
}
}
}
void round_output(size_t n_samples, size_t last_nodes, double* outputs) {
for (size_t s = 0; s < n_samples; s++) {
double* output = outputs + s * last_nodes;
// Round each element
for (size_t n = 0; n < last_nodes; n++) {
output[n] = round(output[n]);
}
}
}
double compute_accuracy(size_t n_samples, size_t last_nodes, double* outputs, double** expected) {
double correct = 0;
for (size_t s = 0; s < n_samples; s++) {
double* output = outputs + s * last_nodes;
double* expect = expected[s];
// Compare each element
int equal = 1;
for (size_t n = 0; n < last_nodes; n++) {
equal = equal && fabs(output[n] - expect[n]) < 0.0001;
}
// Update correct based on if they were equal
correct += equal ? 1.0 : 0.0;
}
return correct / n_samples;
}
| 38.17316 | 145 | 0.570254 | [
"object"
] |
a96919b78e85864ff73c0a3183fd1a62fef9f223 | 2,730 | h | C | amd_femfx/src/Simulation/FEMFXSleeping.h | UnifiQ/FEMFX | 95cf656731a2465ae1d400138170af2d6575b5bb | [
"MIT"
] | 418 | 2019-12-16T10:36:42.000Z | 2022-03-27T02:46:08.000Z | amd_femfx/src/Simulation/FEMFXSleeping.h | UnifiQ/FEMFX | 95cf656731a2465ae1d400138170af2d6575b5bb | [
"MIT"
] | 15 | 2019-12-16T15:39:29.000Z | 2021-12-02T15:45:21.000Z | amd_femfx/src/Simulation/FEMFXSleeping.h | UnifiQ/FEMFX | 95cf656731a2465ae1d400138170af2d6575b5bb | [
"MIT"
] | 54 | 2019-12-16T12:33:18.000Z | 2022-02-27T16:33:28.000Z | /*
MIT License
Copyright (c) 2019 Advanced Micro Devices, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
//---------------------------------------------------------------------------------------
// Operations to detect object sleeping and move objects and islands in and out of
// sleeping state
//---------------------------------------------------------------------------------------
#pragma once
#include "FEMFXCommonInternal.h"
#include "FEMFXAsyncThreading.h"
namespace AMD
{
struct FmScene;
class FmAsyncTasksProgress;
struct FmConstraintIsland;
// Sets flag in an object's sleeping island for a later pass waking objects; tests sleeping status
bool FmMarkIslandOfObjectForWaking(FmScene* scene, uint objectId);
// Sets flag in an object's active island for a later pass which will create the sleeping island
void FmMarkIslandForSleeping(FmScene* scene, uint sleepingIslandId);
// Complete waking of marked islands which wakes objects and calls a callback for an external engine to update its objects.
// This does not create new active islands; these are regenerated after new contacts are found.
void FmWakeMarkedIslands(FmScene* scene);
// Create sleeping islands for all marked active islands.
// Clears the original island but leaves its id arrays in place. Active islands are regenerated each frame.
// If FM_ASYNC_THREADING and parentTaskData is non-NULL, this will execute asynchronously and may return before
// tasks are complete.
void FmPutMarkedIslandsToSleep(FmScene* scene, FmAsyncTaskData* parentTaskData);
bool FmPutConstraintIslandToSleep(FmScene* scene, const FmConstraintIsland& srcIsland, bool useCallback, FmAsyncTaskData* parentTaskData);
} | 46.271186 | 142 | 0.733333 | [
"object"
] |
a96b3b695620f429d5a2b887e9472959299af543 | 42,173 | c | C | code/src/anim/orxAnimPointer.c | chrisfont/orx | cbf35f913448729e74f9579eb0417dd9bf6a8627 | [
"Zlib"
] | null | null | null | code/src/anim/orxAnimPointer.c | chrisfont/orx | cbf35f913448729e74f9579eb0417dd9bf6a8627 | [
"Zlib"
] | null | null | null | code/src/anim/orxAnimPointer.c | chrisfont/orx | cbf35f913448729e74f9579eb0417dd9bf6a8627 | [
"Zlib"
] | null | null | null | /* Orx - Portable Game Engine
*
* Copyright (c) 2008-2018 Orx-Project
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
/**
* @file orxAnimPointer.h
* @date 03/03/2004
* @author iarwain@orx-project.org
*
*/
#include "anim/orxAnimPointer.h"
#include "core/orxConfig.h"
#include "core/orxEvent.h"
#include "debug/orxDebug.h"
#include "debug/orxProfiler.h"
#include "math/orxMath.h"
#include "memory/orxMemory.h"
#include "core/orxClock.h"
#include "object/orxObject.h"
#ifdef __orxMSVC__
#pragma warning(disable : 4311 4312)
#endif /* __orxMSVC__ */
/** Module flags
*/
#define orxANIMPOINTER_KU32_STATIC_FLAG_NONE 0x00000000 /**< No flags */
#define orxANIMPOINTER_KU32_STATIC_FLAG_READY 0x00000001 /**< Ready flag */
/** orxANIMPOINTER flags
*/
#define orxANIMPOINTER_KU32_FLAG_NONE 0x00000000 /**< No flags */
#define orxANIMPOINTER_KU32_FLAG_HAS_CURRENT_ANIM 0x00000001 /**< Has current animation flag */
#define orxANIMPOINTER_KU32_FLAG_ANIMSET 0x00000010 /**< Has animset flag */
#define orxANIMPOINTER_KU32_FLAG_LINK_TABLE 0x00000020 /**< Has link table flag */
#define orxANIMPOINTER_KU32_FLAG_PAUSED 0x00000040 /**< Pause flag */
#define orxANIMPOINTER_KU32_FLAG_INIT 0x00000080 /**< Init flag */
#define orxANIMPOINTER_KU32_FLAG_INTERNAL 0x10000000 /**< Internal structure handling flag */
#define orxANIMPOINTER_KU32_MASK_FLAGS 0xFFFFFFFF /**< Flags ID mask */
/** Misc defines
*/
#define orxANIMPOINTER_KZ_CONFIG_FREQUENCY "Frequency"
#define orxANIMPOINTER_KU32_BANK_SIZE 128 /**< Bank size */
#define orxANIMPOINTER_KF_FREQUENCY_DEFAULT 1.0 /**< Default animation frequency */
/***************************************************************************
* Structure declaration *
***************************************************************************/
/** AnimPointer structure
*/
struct __orxANIMPOINTER_t
{
orxSTRUCTURE stStructure; /**< Public structure, first structure member : 32 */
orxANIMSET *pstAnimSet; /**< Referenced AnimationSet : 20 */
orxANIMSET_LINK_TABLE *pstLinkTable; /**< Link table pointer : 24 */
orxU32 u32CurrentAnim; /**< Current animation ID : 28 */
orxU32 u32TargetAnim; /**< Target animation ID : 32 */
orxFLOAT fCurrentAnimTime; /**< Current Time (Relative to current animation) : 26 */
orxFLOAT fTime; /**< Current Time (Absolute) : 40 */
orxFLOAT fFrequency; /**< Current animation frequency : 44 */
orxU32 u32CurrentKey; /**< Current animation key : 48 */
orxU32 u32LoopCount; /**< Current animation loop count : 52 */
};
/** Static structure
*/
typedef struct __orxANIMPOINTER_STATIC_t
{
orxU32 u32Flags; /**< Control flags : 4 */
} orxANIMPOINTER_STATIC;
/***************************************************************************
* Static variables *
***************************************************************************/
/** Static data
*/
static orxANIMPOINTER_STATIC sstAnimPointer;
/***************************************************************************
* Private functions *
***************************************************************************/
/** Deletes all AnimPointers
*/
static orxINLINE void orxAnimPointer_DeleteAll()
{
register orxANIMPOINTER *pstAnimPointer;
/* Gets first anim pointer */
pstAnimPointer = orxANIMPOINTER(orxStructure_GetFirst(orxSTRUCTURE_ID_ANIMPOINTER));
/* Non empty? */
while(pstAnimPointer != orxNULL)
{
/* Deletes AnimPointer */
orxAnimPointer_Delete(pstAnimPointer);
/* Gets first Animation Set */
pstAnimPointer = orxANIMPOINTER(orxStructure_GetFirst(orxSTRUCTURE_ID_ANIMPOINTER));
}
return;
}
/** Sends custom events from an animation between two timestamps
* @param[in] _pstAnim Concerned animation
* @param[in] _pstOwner Event's owner
* @param[in] _fStartTime Start time, excluded
* @param[in] _fEndTime End time, included
* @return orxSTATUS_SUCCESS / orxSTATUS_FAILURE
*/
static orxINLINE void orxAnimPointer_SendCustomEvents(orxANIM *_pstAnim, const orxSTRUCTURE *_pstOwner, orxFLOAT _fStartTime, orxFLOAT _fEndTime)
{
const orxANIM_CUSTOM_EVENT *pstCustomEvent;
orxANIM_EVENT_PAYLOAD stPayload;
/* Checks */
orxSTRUCTURE_ASSERT(_pstAnim);
orxSTRUCTURE_ASSERT(_pstOwner);
orxASSERT(_fEndTime >= _fStartTime);
/* Inits event payload */
orxMemory_Zero(&stPayload, sizeof(orxANIM_EVENT_PAYLOAD));
stPayload.pstAnim = _pstAnim;
stPayload.zAnimName = orxAnim_GetName(_pstAnim);
/* For all events to send */
for(pstCustomEvent = orxAnim_GetNextEvent(_pstAnim, _fStartTime);
(pstCustomEvent != orxNULL) && (pstCustomEvent->fTimeStamp <= _fEndTime);
pstCustomEvent = orxAnim_GetNextEvent(_pstAnim, pstCustomEvent->fTimeStamp))
{
/* Updates event payload */
stPayload.stCustom.zName = pstCustomEvent->zName;
stPayload.stCustom.fValue = pstCustomEvent->fValue;
stPayload.stCustom.fTime = pstCustomEvent->fTimeStamp;
/* Sends event */
orxEVENT_SEND(orxEVENT_TYPE_ANIM, orxANIM_EVENT_CUSTOM_EVENT, _pstOwner, _pstOwner, &stPayload);
}
}
/** Computes current Anim for the given time
* @param[in] _pstAnimPointer Concerned AnimPointer
* @param[in] _fDT Delta time
* @return orxSTATUS_SUCCESS / orxSTATUS_FAILURE
*/
static orxINLINE orxSTATUS orxAnimPointer_Compute(orxANIMPOINTER *_pstAnimPointer, orxFLOAT _fDT)
{
orxSTATUS eResult = orxSTATUS_SUCCESS;
/* Checks */
orxSTRUCTURE_ASSERT(_pstAnimPointer);
orxASSERT(orxStructure_TestFlags(_pstAnimPointer, orxANIMPOINTER_KU32_FLAG_ANIMSET) != orxFALSE);
/* Not already initialized? */
if(!orxStructure_TestFlags(_pstAnimPointer, orxANIMPOINTER_KU32_FLAG_INIT))
{
orxU32 u32BackupTargetAnim;
/* Backups target anim */
u32BackupTargetAnim = _pstAnimPointer->u32TargetAnim;
/* Sets its initial animation */
orxAnimPointer_SetCurrentAnim(_pstAnimPointer, 0);
/* Restores target anim */
_pstAnimPointer->u32TargetAnim = u32BackupTargetAnim;
}
/* Not Paused? */
if(orxStructure_TestFlags(_pstAnimPointer, orxANIMPOINTER_KU32_FLAG_PAUSED) == orxFALSE)
{
/* Has current animation */
if(orxStructure_TestFlags(_pstAnimPointer, orxANIMPOINTER_KU32_FLAG_HAS_CURRENT_ANIM) != orxFALSE)
{
orxFLOAT fEventStartTime;
orxSTRUCTURE *pstOwner;
orxANIM_EVENT_PAYLOAD stPayload;
orxBOOL bRecompute;
/* Gets owner */
pstOwner = orxStructure_GetOwner(_pstAnimPointer);
/* Gets event start time */
fEventStartTime = _pstAnimPointer->fCurrentAnimTime;
/* Updates Times */
_pstAnimPointer->fTime += _fDT * _pstAnimPointer->fFrequency;
_pstAnimPointer->fCurrentAnimTime += _fDT * _pstAnimPointer->fFrequency;
do
{
orxBOOL bCut, bClearTarget;
orxU32 u32NewAnim;
orxFLOAT fTimeBackup, fTimeCompare;
/* Clears recompute status */
bRecompute = orxFALSE;
/* Gets a backup of current time */
fTimeBackup = _pstAnimPointer->fCurrentAnimTime;
/* Computes & updates anim*/
u32NewAnim = orxAnimSet_ComputeAnim(_pstAnimPointer->pstAnimSet, _pstAnimPointer->u32CurrentAnim, _pstAnimPointer->u32TargetAnim, &(_pstAnimPointer->fCurrentAnimTime), _pstAnimPointer->pstLinkTable, &bCut, &bClearTarget);
/* Inits event payload */
orxMemory_Zero(&stPayload, sizeof(orxANIM_EVENT_PAYLOAD));
stPayload.pstAnim = orxAnimSet_GetAnim(_pstAnimPointer->pstAnimSet, _pstAnimPointer->u32CurrentAnim);
stPayload.zAnimName = orxAnim_GetName(stPayload.pstAnim);
/* Keeps current time for comparison */
fTimeCompare = _pstAnimPointer->fCurrentAnimTime;
/* Change happened? */
if(u32NewAnim != _pstAnimPointer->u32CurrentAnim)
{
orxU32 u32TargetAnim;
/* Not cut? */
if(bCut == orxFALSE)
{
orxFLOAT fAnimLength;
/* Gets anim length */
fAnimLength = orxAnim_GetLength(stPayload.pstAnim);
/* In scope? */
if(fEventStartTime < fAnimLength)
{
/* Sends custom events */
orxAnimPointer_SendCustomEvents(stPayload.pstAnim, pstOwner, fEventStartTime, fAnimLength);
}
}
/* Updates current anim ID */
_pstAnimPointer->u32CurrentAnim = u32NewAnim;
/* Clears current key */
_pstAnimPointer->u32CurrentKey = 0;
/* Clears loop count */
_pstAnimPointer->u32LoopCount = 0;
/* Stores target anim */
u32TargetAnim = _pstAnimPointer->u32TargetAnim;
/* Stores cut time */
stPayload.stCut.fTime = (bCut != orxFALSE) ? fTimeBackup : orxFLOAT_0;
/* Sends event */
orxEVENT_SEND(orxEVENT_TYPE_ANIM, (bCut != orxFALSE) ? orxANIM_EVENT_CUT : orxANIM_EVENT_STOP, pstOwner, pstOwner, &stPayload);
/* No new anim? */
if(_pstAnimPointer->u32CurrentAnim == orxU32_UNDEFINED)
{
/* Cleans target anim */
_pstAnimPointer->u32TargetAnim = orxU32_UNDEFINED;
/* Updates flags */
orxStructure_SetFlags(_pstAnimPointer, orxANIMPOINTER_KU32_FLAG_NONE, orxANIMPOINTER_KU32_FLAG_HAS_CURRENT_ANIM);
}
else
{
/* Not yet at target? */
if(_pstAnimPointer->u32CurrentAnim != _pstAnimPointer->u32TargetAnim)
{
/* Asks for recompute */
bRecompute = orxTRUE;
}
/* Not modified during callback? */
if((_pstAnimPointer->u32CurrentAnim == u32NewAnim)
&& (_pstAnimPointer->u32TargetAnim == u32TargetAnim))
{
/* Inits event payload */
stPayload.pstAnim = orxAnimSet_GetAnim(_pstAnimPointer->pstAnimSet, _pstAnimPointer->u32CurrentAnim);
stPayload.zAnimName = orxAnim_GetName(stPayload.pstAnim);
/* Sends event */
orxEVENT_SEND(orxEVENT_TYPE_ANIM, orxANIM_EVENT_START, pstOwner, pstOwner, &stPayload);
/* Should clear target? */
if(bClearTarget != orxFALSE)
{
/* Removes it */
_pstAnimPointer->u32TargetAnim = orxU32_UNDEFINED;
}
}
}
/* Has current time been modified during event? */
if(_pstAnimPointer->fCurrentAnimTime != fTimeCompare)
{
/* Updates event start time */
fEventStartTime = _pstAnimPointer->fCurrentAnimTime;
}
else
{
/* Updates event start time */
fEventStartTime = orx2F(-1.0f);
}
}
else
{
/* Looped? */
if(_pstAnimPointer->fCurrentAnimTime < fTimeBackup)
{
orxFLOAT fAnimLength;
orxU32 u32CurrentAnim, u32TargetAnim;
/* Gets anim length */
fAnimLength = orxAnim_GetLength(stPayload.pstAnim);
/* In scope? */
if(fEventStartTime < fAnimLength)
{
/* Sends custom events */
orxAnimPointer_SendCustomEvents(stPayload.pstAnim, pstOwner, fEventStartTime, fAnimLength);
}
/* Stores current and target anims */
u32CurrentAnim = _pstAnimPointer->u32CurrentAnim;
u32TargetAnim = _pstAnimPointer->u32TargetAnim;
/* Updates loop count */
_pstAnimPointer->u32LoopCount++;
/* Updates payload */
stPayload.stLoop.u32Count = _pstAnimPointer->u32LoopCount;
/* Sends it */
orxEVENT_SEND(orxEVENT_TYPE_ANIM, orxANIM_EVENT_LOOP, pstOwner, pstOwner, &stPayload);
/* Not modified during event? */
if((_pstAnimPointer->u32CurrentAnim == u32CurrentAnim)
&& (_pstAnimPointer->u32TargetAnim == u32TargetAnim))
{
/* Should clear target? */
if(bClearTarget != orxFALSE)
{
/* Removes it */
_pstAnimPointer->u32TargetAnim = orxU32_UNDEFINED;
}
}
/* Has current time been modified during event? */
if(_pstAnimPointer->fCurrentAnimTime != fTimeCompare)
{
/* Updates event start time */
fEventStartTime = _pstAnimPointer->fCurrentAnimTime;
}
else
{
/* Updates event start time */
fEventStartTime = orx2F(-1.0f);
}
}
}
} while((bRecompute != orxFALSE) || (_pstAnimPointer->fCurrentAnimTime > orxAnim_GetLength(stPayload.pstAnim)));
/* Has current anim? */
if(orxStructure_TestFlags(_pstAnimPointer, orxANIMPOINTER_KU32_FLAG_HAS_CURRENT_ANIM) != orxFALSE)
{
orxANIM *pstAnim;
orxFLOAT fTimeCompare;
orxU32 u32CurrentKey;
/* Gets current anim */
pstAnim = orxAnimSet_GetAnim(_pstAnimPointer->pstAnimSet, _pstAnimPointer->u32CurrentAnim);
/* Gets current key */
u32CurrentKey = orxAnim_GetKey(pstAnim, _pstAnimPointer->fCurrentAnimTime);
/* Keeps current time for comparison */
fTimeCompare = _pstAnimPointer->fCurrentAnimTime;
/* New key? */
if(u32CurrentKey != _pstAnimPointer->u32CurrentKey)
{
/* Stores it */
_pstAnimPointer->u32CurrentKey = u32CurrentKey;
/* Inits event payload */
orxMemory_Zero(&stPayload, sizeof(orxANIM_EVENT_PAYLOAD));
stPayload.pstAnim = pstAnim;
stPayload.zAnimName = orxAnim_GetName(pstAnim);
/* Sends it */
orxEVENT_SEND(orxEVENT_TYPE_ANIM, orxANIM_EVENT_UPDATE, pstOwner, pstOwner, &stPayload);
}
/* Has current time not been modified during event? */
if(_pstAnimPointer->fCurrentAnimTime == fTimeCompare)
{
/* Sends custom events */
orxAnimPointer_SendCustomEvents(pstAnim, pstOwner, fEventStartTime, _pstAnimPointer->fCurrentAnimTime);
}
}
}
else
{
/* Can't process */
eResult = orxSTATUS_FAILURE;
}
}
/* Done! */
return eResult;
}
/** Updates the AnimPointer (Callback for generic structure update calling)
* @param[in] _pstStructure Generic Structure or the concerned AnimPointer
* @param[in] _pstCaller Structure of the caller
* @param[in] _pstClockInfo Clock info used for time updates
* @return orxSTATUS_SUCCESS / orxSTATUS_FAILURE
*/
static orxSTATUS orxFASTCALL orxAnimPointer_Update(orxSTRUCTURE *_pstStructure, const orxSTRUCTURE *_pstCaller, const orxCLOCK_INFO *_pstClockInfo)
{
register orxANIMPOINTER *pstAnimPointer;
/* Profiles */
orxPROFILER_PUSH_MARKER("orxAnimPointer_Update");
/* Gets pointer */
pstAnimPointer = orxANIMPOINTER(_pstStructure);
/* Checks */
orxSTRUCTURE_ASSERT(pstAnimPointer);
/* Computes animation pointer */
orxAnimPointer_Compute(pstAnimPointer, _pstClockInfo->fDT);
/* Profiles */
orxPROFILER_POP_MARKER();
/* Done! */
return orxSTATUS_SUCCESS;
}
/***************************************************************************
* Public functions *
***************************************************************************/
/** AnimPointer module setup
*/
void orxFASTCALL orxAnimPointer_Setup()
{
/* Adds module dependencies */
orxModule_AddDependency(orxMODULE_ID_ANIMPOINTER, orxMODULE_ID_MEMORY);
orxModule_AddDependency(orxMODULE_ID_ANIMPOINTER, orxMODULE_ID_CLOCK);
orxModule_AddDependency(orxMODULE_ID_ANIMPOINTER, orxMODULE_ID_CONFIG);
orxModule_AddDependency(orxMODULE_ID_ANIMPOINTER, orxMODULE_ID_PROFILER);
orxModule_AddDependency(orxMODULE_ID_ANIMPOINTER, orxMODULE_ID_EVENT);
orxModule_AddDependency(orxMODULE_ID_ANIMPOINTER, orxMODULE_ID_ANIMSET);
orxModule_AddDependency(orxMODULE_ID_ANIMPOINTER, orxMODULE_ID_ANIM);
return;
}
/** Inits the AnimPointer module
* @return orxSTATUS_SUCCESS / orxSTATUS_FAILURE
*/
orxSTATUS orxFASTCALL orxAnimPointer_Init()
{
orxSTATUS eResult = orxSTATUS_FAILURE;
/* Not already Initialized? */
if(!(sstAnimPointer.u32Flags & orxANIMPOINTER_KU32_STATIC_FLAG_READY))
{
/* Cleans static controller */
orxMemory_Zero(&sstAnimPointer, sizeof(orxANIMPOINTER_STATIC));
/* Registers structure type */
eResult = orxSTRUCTURE_REGISTER(ANIMPOINTER, orxSTRUCTURE_STORAGE_TYPE_LINKLIST, orxMEMORY_TYPE_MAIN, orxANIMPOINTER_KU32_BANK_SIZE, &orxAnimPointer_Update);
}
else
{
/* Logs message */
orxDEBUG_PRINT(orxDEBUG_LEVEL_ANIM, "AnimPointer module already initialized.");
/* Already initialized */
eResult = orxSTATUS_SUCCESS;
}
/* Initialized? */
if(eResult != orxSTATUS_FAILURE)
{
/* Inits Flags */
sstAnimPointer.u32Flags = orxANIMPOINTER_KU32_STATIC_FLAG_READY;
}
else
{
/* Logs message */
orxDEBUG_PRINT(orxDEBUG_LEVEL_ANIM, "Failed to register AnimPointer module.");
}
/* Done! */
return eResult;
}
/** Exits from the AnimPointer module
*/
void orxFASTCALL orxAnimPointer_Exit()
{
/* Initialized? */
if(sstAnimPointer.u32Flags & orxANIMPOINTER_KU32_STATIC_FLAG_READY)
{
/* Deletes animpointer list */
orxAnimPointer_DeleteAll();
/* Unregisters structure type */
orxStructure_Unregister(orxSTRUCTURE_ID_ANIMPOINTER);
/* Updates flags */
sstAnimPointer.u32Flags &= ~orxANIMPOINTER_KU32_STATIC_FLAG_READY;
}
return;
}
/** Creates an empty AnimPointer
* @param[in] _pstAnimSet AnimationSet reference
* @return Created orxANIMPOINTER / orxNULL
*/
orxANIMPOINTER *orxFASTCALL orxAnimPointer_Create(orxANIMSET *_pstAnimSet)
{
orxANIMPOINTER *pstAnimPointer;
/* Checks */
orxASSERT(sstAnimPointer.u32Flags & orxANIMPOINTER_KU32_STATIC_FLAG_READY);
orxSTRUCTURE_ASSERT(_pstAnimSet);
/* Creates animpointer */
pstAnimPointer = orxANIMPOINTER(orxStructure_Create(orxSTRUCTURE_ID_ANIMPOINTER));
/* Was allocated? */
if(pstAnimPointer != orxNULL)
{
/* Stores animset */
pstAnimPointer->pstAnimSet = _pstAnimSet;
/* Adds a reference on the animset */
orxAnimSet_AddReference(_pstAnimSet);
/* Inits flags */
orxStructure_SetFlags(pstAnimPointer, orxANIMPOINTER_KU32_FLAG_ANIMSET | orxANIMPOINTER_KU32_FLAG_HAS_CURRENT_ANIM, orxANIMPOINTER_KU32_MASK_FLAGS);
/* Inits value */
pstAnimPointer->u32CurrentAnim = orxU32_UNDEFINED;
pstAnimPointer->fCurrentAnimTime = orxFLOAT_0;
pstAnimPointer->fFrequency = orxANIMPOINTER_KF_FREQUENCY_DEFAULT;
pstAnimPointer->fTime = orxFLOAT_0;
pstAnimPointer->u32TargetAnim = orxU32_UNDEFINED;
pstAnimPointer->u32CurrentKey = 0;
pstAnimPointer->u32LoopCount = 0;
/* Is animset link table non-static? */
if(orxStructure_TestFlags(_pstAnimSet, orxANIMSET_KU32_FLAG_LINK_STATIC) == orxFALSE)
{
/* Stores link table */
pstAnimPointer->pstLinkTable = orxAnimSet_CloneLinkTable(_pstAnimSet);
/* Updates flags */
orxStructure_SetFlags(pstAnimPointer, orxANIMPOINTER_KU32_FLAG_LINK_TABLE, orxANIMPOINTER_KU32_FLAG_NONE);
}
/* Increases count */
orxStructure_IncreaseCount(pstAnimPointer);
}
else
{
/* Logs message */
orxDEBUG_PRINT(orxDEBUG_LEVEL_ANIM, "Failed creating Anim pointer.");
/* Not created */
pstAnimPointer = orxNULL;
}
/* Done! */
return pstAnimPointer;
}
/** Creates an animation pointer from config
* @param[in] _zConfigID Config ID
* @return orxANIMPOINTER / orxNULL
*/
orxANIMPOINTER *orxFASTCALL orxAnimPointer_CreateFromConfig(const orxSTRING _zConfigID)
{
orxANIMPOINTER *pstResult = orxNULL;
/* Checks */
orxASSERT(sstAnimPointer.u32Flags & orxANIMPOINTER_KU32_STATIC_FLAG_READY);
/* Pushes section */
if((orxConfig_HasSection(_zConfigID) != orxFALSE)
&& (orxConfig_PushSection(_zConfigID) != orxSTATUS_FAILURE))
{
orxANIMSET *pstAnimSet;
/* Creates animset from config */
pstAnimSet = orxAnimSet_CreateFromConfig(_zConfigID);
/* Valid? */
if(pstAnimSet != orxNULL)
{
/* Creates animation pointer from it */
pstResult = orxAnimPointer_Create(pstAnimSet);
/* Valid? */
if(pstResult != orxNULL)
{
/* Has frequency? */
if(orxConfig_HasValue(orxANIMPOINTER_KZ_CONFIG_FREQUENCY) != orxFALSE)
{
/* Updates animation pointer frequency */
pstResult->fFrequency = orxConfig_GetFloat(orxANIMPOINTER_KZ_CONFIG_FREQUENCY);
}
/* Sets AnimSet's owner */
orxStructure_SetOwner(pstAnimSet, pstResult);
/* Updates status flags */
orxStructure_SetFlags(pstResult, orxANIMPOINTER_KU32_FLAG_INTERNAL, orxANIMPOINTER_KU32_FLAG_NONE);
}
else
{
/* Logs message */
orxDEBUG_PRINT(orxDEBUG_LEVEL_ANIM, "Failed creating Anim pointer.");
/* Deletes created anim set */
orxAnimSet_Delete(pstAnimSet);
}
}
/* Pops previous section */
orxConfig_PopSection();
}
else
{
/* Logs message */
orxDEBUG_PRINT(orxDEBUG_LEVEL_ANIM, "\"%s\" does not exist in config.", _zConfigID);
/* Updates result */
pstResult = orxNULL;
}
/* Done! */
return pstResult;
}
/** Deletes an AnimPointer
* @param[in] _pstAnimPointer AnimPointer to delete
* @return orxSTATUS_SUCCESS / orxSTATUS_FAILURE
*/
orxSTATUS orxFASTCALL orxAnimPointer_Delete(orxANIMPOINTER *_pstAnimPointer)
{
orxSTATUS eResult = orxSTATUS_SUCCESS;
/* Checks */
orxASSERT(sstAnimPointer.u32Flags & orxANIMPOINTER_KU32_STATIC_FLAG_READY);
orxSTRUCTURE_ASSERT(_pstAnimPointer);
/* Decreases count */
orxStructure_DecreaseCount(_pstAnimPointer);
/* Not referenced? */
if(orxStructure_GetRefCount(_pstAnimPointer) == 0)
{
/* Has an animset? */
if(orxStructure_TestFlags(_pstAnimPointer, orxANIMPOINTER_KU32_FLAG_ANIMSET) != orxFALSE)
{
/* Removes the reference from the animset */
orxAnimSet_RemoveReference(_pstAnimPointer->pstAnimSet);
/* Was internally allocated? */
if(orxStructure_TestFlags(_pstAnimPointer, orxANIMPOINTER_KU32_FLAG_INTERNAL) != orxFALSE)
{
/* Removes its owner */
orxStructure_SetOwner(_pstAnimPointer->pstAnimSet, orxNULL);
/* Deletes animset */
orxAnimSet_Delete(_pstAnimPointer->pstAnimSet);
}
}
/* Has a link table? */
if(orxStructure_TestFlags(_pstAnimPointer, orxANIMPOINTER_KU32_FLAG_LINK_TABLE) != orxFALSE)
{
/* Deletes it */
orxAnimSet_DeleteLinkTable(_pstAnimPointer->pstLinkTable);
}
/* Deletes structure */
orxStructure_Delete(_pstAnimPointer);
}
else
{
/* Referenced by others */
eResult = orxSTATUS_FAILURE;
}
/* Done! */
return eResult;
}
/** Gets the referenced AnimationSet
* @param[in] _pstAnimPointer Concerned AnimPointer
* @return Referenced orxANIMSET
*/
orxANIMSET *orxFASTCALL orxAnimPointer_GetAnimSet(const orxANIMPOINTER *_pstAnimPointer)
{
orxANIMSET *pstAnimSet = orxNULL;
/* Checks */
orxASSERT(sstAnimPointer.u32Flags & orxANIMPOINTER_KU32_STATIC_FLAG_READY);
orxSTRUCTURE_ASSERT(_pstAnimPointer);
/* Has an animset? */
if(orxStructure_TestFlags(_pstAnimPointer, orxANIMPOINTER_KU32_FLAG_ANIMSET) != orxFALSE)
{
pstAnimSet = _pstAnimPointer->pstAnimSet;
}
else
{
/* Logs message */
orxDEBUG_PRINT(orxDEBUG_LEVEL_ANIM, "Anim pointer does not have Anim set.");
}
/* Done! */
return pstAnimSet;
}
/** AnimPointer current Animation get accessor
* @param[in] _pstAnimPointer Concerned AnimPointer
* @return Current Animation ID
*/
orxU32 orxFASTCALL orxAnimPointer_GetCurrentAnim(const orxANIMPOINTER *_pstAnimPointer)
{
orxU32 u32Anim = orxU32_UNDEFINED;
/* Checks */
orxASSERT(sstAnimPointer.u32Flags & orxANIMPOINTER_KU32_STATIC_FLAG_READY);
orxSTRUCTURE_ASSERT(_pstAnimPointer);
/* Has anim? */
if((orxStructure_TestFlags(_pstAnimPointer, orxANIMPOINTER_KU32_FLAG_ANIMSET) != orxFALSE)
&& (orxStructure_TestFlags(_pstAnimPointer, orxANIMPOINTER_KU32_FLAG_HAS_CURRENT_ANIM) != orxFALSE))
{
/* Not already initialized? */
if(!orxStructure_TestFlags(_pstAnimPointer, orxANIMPOINTER_KU32_FLAG_INIT))
{
/* Sets its initial animation */
orxAnimPointer_SetCurrentAnim((orxANIMPOINTER *)_pstAnimPointer, 0);
}
u32Anim = _pstAnimPointer->u32CurrentAnim;
}
/* Done! */
return u32Anim;
}
/** AnimPointer target Animation get accessor
* @param[in] _pstAnimPointer Concerned AnimPointer
* @return Target Animation ID
*/
orxU32 orxFASTCALL orxAnimPointer_GetTargetAnim(const orxANIMPOINTER *_pstAnimPointer)
{
orxU32 u32Anim = orxU32_UNDEFINED;
/* Checks */
orxASSERT(sstAnimPointer.u32Flags & orxANIMPOINTER_KU32_STATIC_FLAG_READY);
orxSTRUCTURE_ASSERT(_pstAnimPointer);
/* Has anim? */
if((orxStructure_TestFlags(_pstAnimPointer, orxANIMPOINTER_KU32_FLAG_ANIMSET) != orxFALSE)
&& (orxStructure_TestFlags(_pstAnimPointer, orxANIMPOINTER_KU32_FLAG_HAS_CURRENT_ANIM) != orxFALSE))
{
u32Anim = _pstAnimPointer->u32TargetAnim;
}
else
{
/* Logs message */
orxDEBUG_PRINT(orxDEBUG_LEVEL_ANIM, "Anim pointer does not have a current anim.");
}
/* Done! */
return u32Anim;
}
/** AnimPointer current Animation name get accessor
* @param[in] _pstAnimPointer Concerned AnimPointer
* @return Current Animation name
*/
const orxSTRING orxFASTCALL orxAnimPointer_GetCurrentAnimName(const orxANIMPOINTER *_pstAnimPointer)
{
orxU32 u32AnimID;
const orxSTRING zResult = orxSTRING_EMPTY;
/* Checks */
orxASSERT(sstAnimPointer.u32Flags & orxANIMPOINTER_KU32_STATIC_FLAG_READY);
orxSTRUCTURE_ASSERT(_pstAnimPointer);
/* Gets current anim ID */
u32AnimID = orxAnimPointer_GetCurrentAnim(_pstAnimPointer);
/* Valid? */
if(u32AnimID != orxU32_UNDEFINED)
{
orxANIM *pstAnim;
/* Gets it */
pstAnim = orxAnimSet_GetAnim(_pstAnimPointer->pstAnimSet, _pstAnimPointer->u32CurrentAnim);
/* Valid? */
if(pstAnim != orxNULL)
{
/* Updates result */
zResult = orxAnim_GetName(pstAnim);
}
}
/* Done! */
return zResult;
}
/** AnimPointer target Animation name get accessor
* @param[in] _pstAnimPointer Concerned AnimPointer
* @return Target Animation name / orxSTRING_EMPTY
*/
const orxSTRING orxFASTCALL orxAnimPointer_GetTargetAnimName(const orxANIMPOINTER *_pstAnimPointer)
{
orxU32 u32AnimID;
const orxSTRING zResult = orxSTRING_EMPTY;
/* Checks */
orxASSERT(sstAnimPointer.u32Flags & orxANIMPOINTER_KU32_STATIC_FLAG_READY);
orxSTRUCTURE_ASSERT(_pstAnimPointer);
/* Gets current anim ID */
u32AnimID = orxAnimPointer_GetTargetAnim(_pstAnimPointer);
/* Valid? */
if(u32AnimID != orxU32_UNDEFINED)
{
orxANIM *pstAnim;
/* Gets it */
pstAnim = orxAnimSet_GetAnim(_pstAnimPointer->pstAnimSet, _pstAnimPointer->u32TargetAnim);
/* Valid? */
if(pstAnim != orxNULL)
{
/* Updates result */
zResult = orxAnim_GetName(pstAnim);
}
}
/* Done! */
return zResult;
}
/** AnimPointer current anim data get accessor
* @param[in] _pstAnimPointer Concerned AnimPointer
* @return Current anim data / orxNULL
*/
orxSTRUCTURE *orxFASTCALL orxAnimPointer_GetCurrentAnimData(const orxANIMPOINTER *_pstAnimPointer)
{
orxU32 u32AnimID;
orxSTRUCTURE *pstResult = orxNULL;
/* Checks */
orxASSERT(sstAnimPointer.u32Flags & orxANIMPOINTER_KU32_STATIC_FLAG_READY);
orxSTRUCTURE_ASSERT(_pstAnimPointer);
/* Gets current anim ID */
u32AnimID = orxAnimPointer_GetCurrentAnim(_pstAnimPointer);
/* Valid? */
if(u32AnimID != orxU32_UNDEFINED)
{
orxANIM *pstAnim;
/* Gets anim */
pstAnim = orxAnimSet_GetAnim(orxAnimPointer_GetAnimSet(_pstAnimPointer), u32AnimID);
/* Valid? */
if(pstAnim != orxNULL)
{
/* Gets data */
pstResult = orxAnim_GetKeyData(pstAnim, _pstAnimPointer->u32CurrentKey);
}
}
/* Done! */
return pstResult;
}
/** AnimPointer time get accessor
* @param[in] _pstAnimPointer Concerned AnimPointer
* @return Current time
*/
orxFLOAT orxFASTCALL orxAnimPointer_GetTime(const orxANIMPOINTER *_pstAnimPointer)
{
register orxFLOAT fResult = orxFLOAT_0;
/* Checks */
orxASSERT(sstAnimPointer.u32Flags & orxANIMPOINTER_KU32_STATIC_FLAG_READY);
orxSTRUCTURE_ASSERT(_pstAnimPointer);
/* Has anim? */
if(orxStructure_TestFlags(_pstAnimPointer, orxANIMPOINTER_KU32_FLAG_HAS_CURRENT_ANIM) != orxFALSE)
{
/* Gets time */
fResult = _pstAnimPointer->fCurrentAnimTime;
}
else
{
/* Logs message */
orxDEBUG_PRINT(orxDEBUG_LEVEL_ANIM, "Anim pointer does not have a current anim.");
}
/* Done! */
return fResult;
}
/** AnimPointer frequency get accessor
* @param[in] _pstAnimPointer Concerned AnimPointer
* @return AnimPointer frequency
*/
orxFLOAT orxFASTCALL orxAnimPointer_GetFrequency(const orxANIMPOINTER *_pstAnimPointer)
{
/* Checks */
orxASSERT(sstAnimPointer.u32Flags & orxANIMPOINTER_KU32_STATIC_FLAG_READY);
orxSTRUCTURE_ASSERT(_pstAnimPointer);
/* Gets frequency */
return _pstAnimPointer->fFrequency;
}
/** AnimPointer current Animation set accessor
* @param[in] _pstAnimPointer Concerned AnimPointer
* @param[in] _u32AnimID Animation ID to set
* @return orxSTATUS_SUCCESS / orxSTATUS_FAILURE
*/
orxSTATUS orxFASTCALL orxAnimPointer_SetCurrentAnim(orxANIMPOINTER *_pstAnimPointer, orxU32 _u32AnimID)
{
orxSTATUS eResult = orxSTATUS_SUCCESS;
/* Checks */
orxASSERT(sstAnimPointer.u32Flags & orxANIMPOINTER_KU32_STATIC_FLAG_READY);
orxSTRUCTURE_ASSERT(_pstAnimPointer);
/* Has animset? */
if(orxStructure_TestFlags(_pstAnimPointer, orxANIMPOINTER_KU32_FLAG_ANIMSET) != orxFALSE)
{
/* In range? */
if(_u32AnimID < orxAnimSet_GetAnimCount(_pstAnimPointer->pstAnimSet))
{
orxANIM_EVENT_PAYLOAD stPayload;
orxSTRUCTURE *pstOwner;
orxU32 u32CurrentAnim;
orxFLOAT fCurrentAnimTime;
/* Updates its status */
orxStructure_SetFlags(_pstAnimPointer, orxANIMPOINTER_KU32_FLAG_INIT, orxANIMPOINTER_KU32_FLAG_NONE);
/* Clears event payload */
orxMemory_Zero(&stPayload, sizeof(orxANIM_EVENT_PAYLOAD));
/* Gets owner */
pstOwner = orxStructure_GetOwner(_pstAnimPointer);
/* Stores current anim & time */
u32CurrentAnim = _pstAnimPointer->u32CurrentAnim;
fCurrentAnimTime = _pstAnimPointer->fCurrentAnimTime;
/* Stores ID */
_pstAnimPointer->u32CurrentAnim = _u32AnimID;
/* Clears target anim */
_pstAnimPointer->u32TargetAnim = orxU32_UNDEFINED;
/* Clears anim time */
_pstAnimPointer->fCurrentAnimTime = orxFLOAT_0;
/* Clears current key */
_pstAnimPointer->u32CurrentKey = 0;
/* Clears loop count */
_pstAnimPointer->u32LoopCount = 0;
/* Has current anim? */
if(u32CurrentAnim != orxU32_UNDEFINED)
{
/* Inits event payload */
stPayload.pstAnim = orxAnimSet_GetAnim(_pstAnimPointer->pstAnimSet, u32CurrentAnim);
stPayload.zAnimName = orxAnim_GetName(stPayload.pstAnim);
stPayload.stCut.fTime = fCurrentAnimTime;
/* Sends event */
orxEVENT_SEND(orxEVENT_TYPE_ANIM, orxANIM_EVENT_CUT, pstOwner, pstOwner, &stPayload);
}
/* Not modified during cut callback? */
if((_pstAnimPointer->u32CurrentAnim == _u32AnimID)
&& (_pstAnimPointer->u32TargetAnim == orxU32_UNDEFINED))
{
/* Inits event payload */
stPayload.pstAnim = orxAnimSet_GetAnim(_pstAnimPointer->pstAnimSet, _pstAnimPointer->u32CurrentAnim);
stPayload.zAnimName = orxAnim_GetName(stPayload.pstAnim);
stPayload.stCut.fTime = orxFLOAT_0;
/* Sends event */
orxEVENT_SEND(orxEVENT_TYPE_ANIM, orxANIM_EVENT_START, pstOwner, pstOwner, &stPayload);
}
/* Updates flags */
orxStructure_SetFlags(_pstAnimPointer, orxANIMPOINTER_KU32_FLAG_HAS_CURRENT_ANIM, orxANIMPOINTER_KU32_FLAG_NONE);
/* Computes animpointer */
eResult = orxAnimPointer_Compute(_pstAnimPointer, orxFLOAT_0);
}
else
{
/* Logs message */
orxDEBUG_PRINT(orxDEBUG_LEVEL_ANIM, "%d is not a valid ID for the anim pointer.", _u32AnimID);
/* Can't process */
eResult = orxSTATUS_FAILURE;
}
}
else
{
/* Logs message */
orxDEBUG_PRINT(orxDEBUG_LEVEL_ANIM, "Anim pointer does not have a current anim.");
/* Can't process */
eResult = orxSTATUS_FAILURE;
}
/* Done! */
return eResult;
}
/** AnimPointer target Animation set accessor
* @param[in] _pstAnimPointer Concerned AnimPointer
* @param[in] _u32AnimID Animation ID to set / orxU32_UNDEFINED
* @return orxSTATUS_SUCCESS / orxSTATUS_FAILURE
*/
orxSTATUS orxFASTCALL orxAnimPointer_SetTargetAnim(orxANIMPOINTER *_pstAnimPointer, orxU32 _u32AnimID)
{
orxSTATUS eResult = orxSTATUS_SUCCESS;
/* Checks */
orxASSERT(sstAnimPointer.u32Flags & orxANIMPOINTER_KU32_STATIC_FLAG_READY);
orxSTRUCTURE_ASSERT(_pstAnimPointer);
/* Has Animset? */
if(orxStructure_TestAllFlags(_pstAnimPointer, orxANIMPOINTER_KU32_FLAG_ANIMSET | orxANIMPOINTER_KU32_FLAG_HAS_CURRENT_ANIM) != orxFALSE)
{
/* New value? */
if(_pstAnimPointer->u32TargetAnim != _u32AnimID)
{
/* Removes target anim? */
if(_u32AnimID == orxU32_UNDEFINED)
{
/* Removes it */
_pstAnimPointer->u32TargetAnim = orxU32_UNDEFINED;
/* Computes animpointer */
eResult = orxAnimPointer_Compute(_pstAnimPointer, orxFLOAT_0);
}
/* In range? */
else if(_u32AnimID < orxAnimSet_GetAnimCount(_pstAnimPointer->pstAnimSet))
{
/* Stores ID */
_pstAnimPointer->u32TargetAnim = _u32AnimID;
/* Computes animpointer */
eResult = orxAnimPointer_Compute(_pstAnimPointer, orxFLOAT_0);
}
else
{
/* Logs message */
orxDEBUG_PRINT(orxDEBUG_LEVEL_ANIM, "%d is not a valid ID for the anim pointer.", _u32AnimID);
/* Can't process */
eResult = orxSTATUS_FAILURE;
}
}
}
else
{
/* Clears it */
_pstAnimPointer->u32TargetAnim = orxU32_UNDEFINED;
/* Logs message */
orxDEBUG_PRINT(orxDEBUG_LEVEL_ANIM, "Anim pointer does not have a current anim.");
/* Can't process */
eResult = orxSTATUS_FAILURE;
}
/* Done! */
return eResult;
}
/** AnimPointer current Animation set accessor using name
* @param[in] _pstAnimPointer Concerned AnimPointer
* @param[in] _zAnimName Animation name (config's name) to set
* @return orxSTATUS_SUCCESS / orxSTATUS_FAILURE
*/
orxSTATUS orxFASTCALL orxAnimPointer_SetCurrentAnimFromName(orxANIMPOINTER *_pstAnimPointer, const orxSTRING _zAnimName)
{
orxU32 u32AnimID;
orxSTATUS eResult = orxSTATUS_FAILURE;
/* Checks */
orxASSERT(sstAnimPointer.u32Flags & orxANIMPOINTER_KU32_STATIC_FLAG_READY);
orxSTRUCTURE_ASSERT(_pstAnimPointer);
/* Gets corresponding anim ID */
u32AnimID = ((_zAnimName != orxNULL) && (_zAnimName != orxSTRING_EMPTY)) ? orxAnimSet_GetAnimIDFromName(_pstAnimPointer->pstAnimSet, _zAnimName) : orxU32_UNDEFINED;
/* Valid? */
if(u32AnimID != orxU32_UNDEFINED)
{
/* Sets current anim */
eResult = orxAnimPointer_SetCurrentAnim(_pstAnimPointer, u32AnimID);
}
/* Done! */
return eResult;
}
/** AnimPointer target Animation set accessor using name
* @param[in] _pstAnimPointer Concerned AnimPointer
* @param[in] _zAnimName Animation name (config's name) to set / orxNULL
* @return orxSTATUS_SUCCESS / orxSTATUS_FAILURE
*/
orxSTATUS orxFASTCALL orxAnimPointer_SetTargetAnimFromName(orxANIMPOINTER *_pstAnimPointer, const orxSTRING _zAnimName)
{
orxU32 u32AnimID;
orxSTATUS eResult;
/* Checks */
orxASSERT(sstAnimPointer.u32Flags & orxANIMPOINTER_KU32_STATIC_FLAG_READY);
orxSTRUCTURE_ASSERT(_pstAnimPointer);
/* Gets corresponding anim ID */
u32AnimID = ((_zAnimName != orxNULL) && (_zAnimName != orxSTRING_EMPTY)) ? orxAnimSet_GetAnimIDFromName(_pstAnimPointer->pstAnimSet, _zAnimName) : orxU32_UNDEFINED;
/* Sets target anim */
eResult = orxAnimPointer_SetTargetAnim(_pstAnimPointer, u32AnimID);
/* Done! */
return eResult;
}
/** AnimPointer current time set accessor
* @param[in] _pstAnimPointer Concerned AnimPointer
* @param[in] _fTime Time to set
* @return orxSTATUS_SUCCESS / orxSTATUS_FAILURE
*/
orxSTATUS orxFASTCALL orxAnimPointer_SetTime(orxANIMPOINTER *_pstAnimPointer, orxFLOAT _fTime)
{
orxSTATUS eResult;
/* Checks */
orxASSERT(sstAnimPointer.u32Flags & orxANIMPOINTER_KU32_STATIC_FLAG_READY);
orxSTRUCTURE_ASSERT(_pstAnimPointer);
/* Stores relative timestamp */
_pstAnimPointer->fCurrentAnimTime = _fTime - orxMATH_KF_EPSILON;
/* Computes animpointer */
eResult = orxAnimPointer_Compute(_pstAnimPointer, orxMATH_KF_EPSILON);
/* Done! */
return eResult;
}
/** AnimPointer frequency set accessor
* @param[in] _pstAnimPointer Concerned AnimPointer
* @param[in] _fFrequency Frequency to set
* @return orxSTATUS_SUCCESS / orxSTATUS_FAILURE
*/
orxSTATUS orxFASTCALL orxAnimPointer_SetFrequency(orxANIMPOINTER *_pstAnimPointer, orxFLOAT _fFrequency)
{
orxSTATUS eResult;
/* Checks */
orxASSERT(sstAnimPointer.u32Flags & orxANIMPOINTER_KU32_STATIC_FLAG_READY);
orxSTRUCTURE_ASSERT(_pstAnimPointer);
orxASSERT(_fFrequency >= orxFLOAT_0);
/* Stores frequency */
_pstAnimPointer->fFrequency = _fFrequency;
/* Computes animpointer */
eResult = orxAnimPointer_Compute(_pstAnimPointer, orxFLOAT_0);
/* Done! */
return eResult;
}
/** AnimPointer pause accessor
* @param[in] _pstAnimPointer Concerned AnimPointer
* @param[in] _bPause Pause / Unpause
* @return orxSTATUS_SUCCESS / orxSTATUS_FAILURE
*/
orxSTATUS orxFASTCALL orxAnimPointer_Pause(orxANIMPOINTER *_pstAnimPointer, orxBOOL _bPause)
{
orxSTATUS eResult = orxSTATUS_SUCCESS;
/* Checks */
orxASSERT(sstAnimPointer.u32Flags & orxANIMPOINTER_KU32_STATIC_FLAG_READY);
orxSTRUCTURE_ASSERT(_pstAnimPointer);
/* Pause? */
if(_bPause != orxFALSE)
{
/* Updates status flags */
orxStructure_SetFlags(_pstAnimPointer, orxANIMPOINTER_KU32_FLAG_PAUSED, orxANIMPOINTER_KU32_FLAG_NONE);
}
else
{
/* Updates status flags */
orxStructure_SetFlags(_pstAnimPointer, orxANIMPOINTER_KU32_FLAG_NONE, orxANIMPOINTER_KU32_FLAG_PAUSED);
}
/* Done! */
return eResult;
}
#ifdef __orxMSVC__
#pragma warning(default : 4311 4312)
#endif /* __orxMSVC__ */
| 32.793935 | 230 | 0.643706 | [
"object"
] |
a96ed70506906a3807afd2763c10aaafa846d330 | 3,071 | h | C | shaka/include/shaka/media/stream_info.h | Mousmi122767/shaka-player-embedded | 10d9b5e0ec737c714c7d40c62593b9fae8514a36 | [
"Apache-2.0",
"BSD-3-Clause"
] | 185 | 2018-11-06T06:04:44.000Z | 2022-03-02T22:20:39.000Z | shaka/include/shaka/media/stream_info.h | Mousmi122767/shaka-player-embedded | 10d9b5e0ec737c714c7d40c62593b9fae8514a36 | [
"Apache-2.0",
"BSD-3-Clause"
] | 211 | 2018-11-15T22:52:49.000Z | 2022-03-02T18:46:20.000Z | shaka/include/shaka/media/stream_info.h | Mousmi122767/shaka-player-embedded | 10d9b5e0ec737c714c7d40c62593b9fae8514a36 | [
"Apache-2.0",
"BSD-3-Clause"
] | 52 | 2018-12-12T11:00:46.000Z | 2022-02-23T17:35:02.000Z | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://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 SHAKA_EMBEDDED_MEDIA_STREAM_INFO_H_
#define SHAKA_EMBEDDED_MEDIA_STREAM_INFO_H_
#include <memory>
#include <string>
#include <vector>
#include "../macros.h"
#include "../utils.h"
namespace shaka {
namespace media {
/**
* Defines information about a stream; this is used to initialize decoders.
*
* @ingroup media
*/
class SHAKA_EXPORT StreamInfo {
public:
StreamInfo(const std::string& mime, const std::string& codec, bool is_video,
Rational<uint32_t> time_scale,
Rational<uint32_t> sample_aspect_ratio,
const std::vector<uint8_t>& extra_data,
uint32_t width, uint32_t height, uint32_t channel_count,
uint32_t sample_rate);
virtual ~StreamInfo();
SHAKA_NON_COPYABLE_OR_MOVABLE_TYPE(StreamInfo);
/**
* The full MIME type of the input stream. If the input is multiplexed, this
* will contain multiple codecs.
*/
const std::string mime_type;
/**
* The codec string this stream contains. This is the name of the codec as
* seen in @a mime_type. This is a single codec, even for originally
* multiplexed content. If the original MIME type doesn't have a codec, this
* returns an implementation-defined value for the codec.
*/
const std::string codec;
/**
* The time-scale used in frame data. In the encoded frame data, times are in
* this timescale. This doesn't apply to the "double" fields on the frame
* object.
*/
const Rational<uint32_t> time_scale;
/**
* For video frames, the sample aspect ratio. This is the aspect ratio of the
* pixels in the image. (0, 0) is treated as (1, 1).
*/
const Rational<uint32_t> sample_aspect_ratio;
/** Extra data used to initialize the decoder. */
const std::vector<uint8_t> extra_data;
/** True if this represents a video stream; false for audio streams. */
const bool is_video;
/** If this is a video frame, this is the width, in pixels, of the frame. */
const uint32_t width;
/** If this is a video frame, this is the height, in pixels, of the frame. */
const uint32_t height;
/** If this is an audio frame, this is the number of channels. */
const uint32_t channel_count;
/**
* If this is an audio frame, this is the sample rate, in samples per second
* (Hz).
*/
const uint32_t sample_rate;
private:
class Impl;
std::unique_ptr<Impl> impl_;
};
} // namespace media
} // namespace shaka
#endif // SHAKA_EMBEDDED_MEDIA_STREAM_INFO_H_
| 30.107843 | 80 | 0.700749 | [
"object",
"vector"
] |
a970cd157684784768271cf2cd344eea84878bcb | 7,287 | h | C | opencl/test/unit_test/mocks/mock_program.h | lukaszgotszaldintel/compute-runtime | 9b12dc43904806db07616ffb8b1c4495aa7d610f | [
"MIT"
] | null | null | null | opencl/test/unit_test/mocks/mock_program.h | lukaszgotszaldintel/compute-runtime | 9b12dc43904806db07616ffb8b1c4495aa7d610f | [
"MIT"
] | null | null | null | opencl/test/unit_test/mocks/mock_program.h | lukaszgotszaldintel/compute-runtime | 9b12dc43904806db07616ffb8b1c4495aa7d610f | [
"MIT"
] | null | null | null | /*
* Copyright (C) 2017-2021 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#pragma once
#include "shared/source/device/device.h"
#include "shared/source/helpers/hash.h"
#include "shared/source/helpers/string.h"
#include "opencl/source/cl_device/cl_device.h"
#include "opencl/source/kernel/multi_device_kernel.h"
#include "opencl/source/program/kernel_info.h"
#include "opencl/source/program/program.h"
#include "gmock/gmock.h"
#include <string>
namespace NEO {
class GraphicsAllocation;
ClDeviceVector toClDeviceVector(ClDevice &clDevice);
////////////////////////////////////////////////////////////////////////////////
// Program - Core implementation
////////////////////////////////////////////////////////////////////////////////
class MockProgram : public Program {
public:
using Program::createProgramFromBinary;
using Program::deviceBuildInfos;
using Program::internalOptionsToExtract;
using Program::kernelDebugEnabled;
using Program::linkBinary;
using Program::separateBlockKernels;
using Program::setBuildStatus;
using Program::updateNonUniformFlag;
using Program::applyAdditionalOptions;
using Program::areSpecializationConstantsInitialized;
using Program::blockKernelManager;
using Program::buildInfos;
using Program::context;
using Program::createdFrom;
using Program::debugData;
using Program::debugDataSize;
using Program::extractInternalOptions;
using Program::getKernelInfo;
using Program::irBinary;
using Program::irBinarySize;
using Program::isSpirV;
using Program::options;
using Program::packDeviceBinary;
using Program::Program;
using Program::sourceCode;
using Program::specConstantsIds;
using Program::specConstantsSizes;
using Program::specConstantsValues;
MockProgram(const ClDeviceVector &deviceVector) : Program(nullptr, false, deviceVector) {
}
~MockProgram() override {
if (contextSet)
context = nullptr;
}
KernelInfo mockKernelInfo;
void setBuildOptions(const char *buildOptions) {
options = buildOptions != nullptr ? buildOptions : "";
}
std::string getInitInternalOptions() const {
std::string internalOptions;
initInternalOptions(internalOptions);
return internalOptions;
};
void setConstantSurface(GraphicsAllocation *gfxAllocation) {
if (gfxAllocation) {
buildInfos[gfxAllocation->getRootDeviceIndex()].constantSurface = gfxAllocation;
} else {
for (auto &buildInfo : buildInfos) {
buildInfo.constantSurface = nullptr;
}
}
}
void setGlobalSurface(GraphicsAllocation *gfxAllocation) {
if (gfxAllocation) {
buildInfos[gfxAllocation->getRootDeviceIndex()].globalSurface = gfxAllocation;
} else {
for (auto &buildInfo : buildInfos) {
buildInfo.globalSurface = nullptr;
}
}
}
std::vector<KernelInfo *> &getKernelInfoArray(uint32_t rootDeviceIndex) {
return buildInfos[rootDeviceIndex].kernelInfoArray;
}
void addKernelInfo(KernelInfo *inInfo, uint32_t rootDeviceIndex) {
buildInfos[rootDeviceIndex].kernelInfoArray.push_back(inInfo);
}
std::vector<KernelInfo *> &getParentKernelInfoArray(uint32_t rootDeviceIndex) {
return buildInfos[rootDeviceIndex].parentKernelInfoArray;
}
std::vector<KernelInfo *> &getSubgroupKernelInfoArray(uint32_t rootDeviceIndex) {
return buildInfos[rootDeviceIndex].subgroupKernelInfoArray;
}
void setContext(Context *context) {
this->context = context;
contextSet = true;
}
void setSourceCode(const char *ptr) { sourceCode = ptr; }
void clearOptions() { options = ""; }
void setCreatedFromBinary(bool createdFromBin) { isCreatedFromBinary = createdFromBin; }
void clearLog(uint32_t rootDeviceIndex) { buildInfos[rootDeviceIndex].buildLog.clear(); }
void setIrBinary(char *ptr, bool isSpirv) {
irBinary.reset(ptr);
this->isSpirV = isSpirV;
}
void setIrBinarySize(size_t bsz, bool isSpirv) {
irBinarySize = bsz;
this->isSpirV = isSpirV;
}
std::string getCachedFileName() const;
void setAllowNonUniform(bool allow) {
allowNonUniform = allow;
}
bool isFlagOption(ConstStringRef option) override {
if (isFlagOptionOverride != -1) {
return (isFlagOptionOverride > 0);
}
return Program::isFlagOption(option);
}
bool isOptionValueValid(ConstStringRef option, ConstStringRef value) override {
if (isOptionValueValidOverride != -1) {
return (isOptionValueValidOverride > 0);
}
return Program::isOptionValueValid(option, value);
}
cl_int rebuildProgramFromIr() {
this->isCreatedFromBinary = false;
setBuildStatus(CL_BUILD_NONE);
std::unordered_map<std::string, BuiltinDispatchInfoBuilder *> builtins;
return this->build(getDevices(), this->options.c_str(), false, builtins);
}
void replaceDeviceBinary(std::unique_ptr<char[]> newBinary, size_t newBinarySize, uint32_t rootDeviceIndex) override {
if (replaceDeviceBinaryCalledPerRootDevice.find(rootDeviceIndex) == replaceDeviceBinaryCalledPerRootDevice.end()) {
replaceDeviceBinaryCalledPerRootDevice.insert({rootDeviceIndex, 1});
} else {
replaceDeviceBinaryCalledPerRootDevice[rootDeviceIndex]++;
}
Program::replaceDeviceBinary(std::move(newBinary), newBinarySize, rootDeviceIndex);
}
cl_int processGenBinary(const ClDevice &clDevice) override {
auto rootDeviceIndex = clDevice.getRootDeviceIndex();
if (processGenBinaryCalledPerRootDevice.find(rootDeviceIndex) == processGenBinaryCalledPerRootDevice.end()) {
processGenBinaryCalledPerRootDevice.insert({rootDeviceIndex, 1});
} else {
processGenBinaryCalledPerRootDevice[rootDeviceIndex]++;
}
return Program::processGenBinary(clDevice);
}
void initInternalOptions(std::string &internalOptions) const override {
initInternalOptionsCalled++;
Program::initInternalOptions(internalOptions);
};
const KernelInfo &getKernelInfoForKernel(const char *kernelName) const {
return *getKernelInfo(kernelName, getDevices()[0]->getRootDeviceIndex());
}
const KernelInfoContainer getKernelInfosForKernel(const char *kernelName) const {
KernelInfoContainer kernelInfos;
kernelInfos.resize(getMaxRootDeviceIndex() + 1);
for (auto i = 0u; i < kernelInfos.size(); i++) {
kernelInfos[i] = getKernelInfo(kernelName, i);
}
return kernelInfos;
}
std::map<uint32_t, int> processGenBinaryCalledPerRootDevice;
std::map<uint32_t, int> replaceDeviceBinaryCalledPerRootDevice;
static int initInternalOptionsCalled;
bool contextSet = false;
int isFlagOptionOverride = -1;
int isOptionValueValidOverride = -1;
};
class GMockProgram : public Program {
public:
using Program::Program;
MOCK_METHOD(bool, appendKernelDebugOptions, (ClDevice &, std::string &), (override));
};
} // namespace NEO
| 36.074257 | 123 | 0.680115 | [
"vector"
] |
a979017d56b8e5cf23e7672574ed66f83c7b4a79 | 9,591 | c | C | linux-3.0.1/drivers/acpi/acpica/exstoren.c | tonghua209/samsun6410_linux_3_0_0_1_for_aws | 31aa0dc27c4aab51a92309a74fd84ca65e8c6a58 | [
"Apache-2.0"
] | 4 | 2016-07-01T04:50:02.000Z | 2021-11-14T21:29:42.000Z | linux-3.0/drivers/acpi/acpica/exstoren.c | spartan263/vizio_oss | 74270002d874391148119b48882db6816e7deedc | [
"Linux-OpenIB"
] | null | null | null | linux-3.0/drivers/acpi/acpica/exstoren.c | spartan263/vizio_oss | 74270002d874391148119b48882db6816e7deedc | [
"Linux-OpenIB"
] | 1 | 2020-04-03T14:00:39.000Z | 2020-04-03T14:00:39.000Z |
/******************************************************************************
*
* Module Name: exstoren - AML Interpreter object store support,
* Store to Node (namespace object)
*
*****************************************************************************/
/*
* Copyright (C) 2000 - 2011, Intel Corp.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions, and the following disclaimer,
* without modification.
* 2. Redistributions in binary form must reproduce at minimum a disclaimer
* substantially similar to the "NO WARRANTY" disclaimer below
* ("Disclaimer") and any redistribution must be conditioned upon
* including a substantially similar Disclaimer requirement for further
* binary redistribution.
* 3. Neither the names of the above-listed copyright holders nor the names
* of any contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* Alternatively, this software may be distributed under the terms of the
* GNU General Public License ("GPL") version 2 as published by the Free
* Software Foundation.
*
* NO WARRANTY
* 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 MERCHANTIBILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR 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 DAMAGES.
*/
#include <acpi/acpi.h>
#include "accommon.h"
#include "acinterp.h"
#include "amlcode.h"
#define _COMPONENT ACPI_EXECUTER
ACPI_MODULE_NAME("exstoren")
/*******************************************************************************
*
* FUNCTION: acpi_ex_resolve_object
*
* PARAMETERS: source_desc_ptr - Pointer to the source object
* target_type - Current type of the target
* walk_state - Current walk state
*
* RETURN: Status, resolved object in source_desc_ptr.
*
* DESCRIPTION: Resolve an object. If the object is a reference, dereference
* it and return the actual object in the source_desc_ptr.
*
******************************************************************************/
acpi_status
acpi_ex_resolve_object(union acpi_operand_object **source_desc_ptr,
acpi_object_type target_type,
struct acpi_walk_state *walk_state)
{
union acpi_operand_object *source_desc = *source_desc_ptr;
acpi_status status = AE_OK;
ACPI_FUNCTION_TRACE(ex_resolve_object);
/* Ensure we have a Target that can be stored to */
switch (target_type) {
case ACPI_TYPE_BUFFER_FIELD:
case ACPI_TYPE_LOCAL_REGION_FIELD:
case ACPI_TYPE_LOCAL_BANK_FIELD:
case ACPI_TYPE_LOCAL_INDEX_FIELD:
/*
* These cases all require only Integers or values that
* can be converted to Integers (Strings or Buffers)
*/
case ACPI_TYPE_INTEGER:
case ACPI_TYPE_STRING:
case ACPI_TYPE_BUFFER:
/*
* Stores into a Field/Region or into a Integer/Buffer/String
* are all essentially the same. This case handles the
* "interchangeable" types Integer, String, and Buffer.
*/
if (source_desc->common.type == ACPI_TYPE_LOCAL_REFERENCE) {
/* Resolve a reference object first */
status =
acpi_ex_resolve_to_value(source_desc_ptr,
walk_state);
if (ACPI_FAILURE(status)) {
break;
}
}
/* For copy_object, no further validation necessary */
if (walk_state->opcode == AML_COPY_OP) {
break;
}
/* Must have a Integer, Buffer, or String */
if ((source_desc->common.type != ACPI_TYPE_INTEGER) &&
(source_desc->common.type != ACPI_TYPE_BUFFER) &&
(source_desc->common.type != ACPI_TYPE_STRING) &&
!((source_desc->common.type == ACPI_TYPE_LOCAL_REFERENCE) &&
(source_desc->reference.class == ACPI_REFCLASS_TABLE))) {
/* Conversion successful but still not a valid type */
ACPI_ERROR((AE_INFO,
"Cannot assign type %s to %s (must be type Int/Str/Buf)",
acpi_ut_get_object_type_name(source_desc),
acpi_ut_get_type_name(target_type)));
status = AE_AML_OPERAND_TYPE;
}
break;
case ACPI_TYPE_LOCAL_ALIAS:
case ACPI_TYPE_LOCAL_METHOD_ALIAS:
/*
* All aliases should have been resolved earlier, during the
* operand resolution phase.
*/
ACPI_ERROR((AE_INFO, "Store into an unresolved Alias object"));
status = AE_AML_INTERNAL;
break;
case ACPI_TYPE_PACKAGE:
default:
/*
* All other types than Alias and the various Fields come here,
* including the untyped case - ACPI_TYPE_ANY.
*/
break;
}
return_ACPI_STATUS(status);
}
/*******************************************************************************
*
* FUNCTION: acpi_ex_store_object_to_object
*
* PARAMETERS: source_desc - Object to store
* dest_desc - Object to receive a copy of the source
* new_desc - New object if dest_desc is obsoleted
* walk_state - Current walk state
*
* RETURN: Status
*
* DESCRIPTION: "Store" an object to another object. This may include
* converting the source type to the target type (implicit
* conversion), and a copy of the value of the source to
* the target.
*
* The Assignment of an object to another (not named) object
* is handled here.
* The Source passed in will replace the current value (if any)
* with the input value.
*
* When storing into an object the data is converted to the
* target object type then stored in the object. This means
* that the target object type (for an initialized target) will
* not be changed by a store operation.
*
* This module allows destination types of Number, String,
* Buffer, and Package.
*
* Assumes parameters are already validated. NOTE: source_desc
* resolution (from a reference object) must be performed by
* the caller if necessary.
*
******************************************************************************/
acpi_status
acpi_ex_store_object_to_object(union acpi_operand_object *source_desc,
union acpi_operand_object *dest_desc,
union acpi_operand_object **new_desc,
struct acpi_walk_state *walk_state)
{
union acpi_operand_object *actual_src_desc;
acpi_status status = AE_OK;
ACPI_FUNCTION_TRACE_PTR(ex_store_object_to_object, source_desc);
actual_src_desc = source_desc;
if (!dest_desc) {
/*
* There is no destination object (An uninitialized node or
* package element), so we can simply copy the source object
* creating a new destination object
*/
status =
acpi_ut_copy_iobject_to_iobject(actual_src_desc, new_desc,
walk_state);
return_ACPI_STATUS(status);
}
if (source_desc->common.type != dest_desc->common.type) {
/*
* The source type does not match the type of the destination.
* Perform the "implicit conversion" of the source to the current type
* of the target as per the ACPI specification.
*
* If no conversion performed, actual_src_desc = source_desc.
* Otherwise, actual_src_desc is a temporary object to hold the
* converted object.
*/
status = acpi_ex_convert_to_target_type(dest_desc->common.type,
source_desc,
&actual_src_desc,
walk_state);
if (ACPI_FAILURE(status)) {
return_ACPI_STATUS(status);
}
if (source_desc == actual_src_desc) {
/*
* No conversion was performed. Return the source_desc as the
* new object.
*/
*new_desc = source_desc;
return_ACPI_STATUS(AE_OK);
}
}
/*
* We now have two objects of identical types, and we can perform a
* copy of the *value* of the source object.
*/
switch (dest_desc->common.type) {
case ACPI_TYPE_INTEGER:
dest_desc->integer.value = actual_src_desc->integer.value;
/* Truncate value if we are executing from a 32-bit ACPI table */
acpi_ex_truncate_for32bit_table(dest_desc);
break;
case ACPI_TYPE_STRING:
status =
acpi_ex_store_string_to_string(actual_src_desc, dest_desc);
break;
case ACPI_TYPE_BUFFER:
status =
acpi_ex_store_buffer_to_buffer(actual_src_desc, dest_desc);
break;
case ACPI_TYPE_PACKAGE:
status =
acpi_ut_copy_iobject_to_iobject(actual_src_desc, &dest_desc,
walk_state);
break;
default:
/*
* All other types come here.
*/
ACPI_WARNING((AE_INFO, "Store into type %s not implemented",
acpi_ut_get_object_type_name(dest_desc)));
status = AE_NOT_IMPLEMENTED;
break;
}
if (actual_src_desc != source_desc) {
/* Delete the intermediate (temporary) source object */
acpi_ut_remove_reference(actual_src_desc);
}
*new_desc = dest_desc;
return_ACPI_STATUS(status);
}
| 31.97 | 80 | 0.661975 | [
"object"
] |
a97ba2319a222b6ea611b39e8ba3c7c899860b4c | 4,398 | h | C | Code/Framework/AzCore/AzCore/Time/ITime.h | pollend/o3de | 02b6b1dbf4d9889b55d4c11e049aa5b1804c9897 | [
"Apache-2.0",
"MIT"
] | 8 | 2021-08-31T02:14:19.000Z | 2021-12-28T19:20:59.000Z | Code/Framework/AzCore/AzCore/Time/ITime.h | pollend/o3de | 02b6b1dbf4d9889b55d4c11e049aa5b1804c9897 | [
"Apache-2.0",
"MIT"
] | 8 | 2021-07-12T13:55:00.000Z | 2021-10-04T14:53:21.000Z | Code/Framework/AzCore/AzCore/Time/ITime.h | pollend/o3de | 02b6b1dbf4d9889b55d4c11e049aa5b1804c9897 | [
"Apache-2.0",
"MIT"
] | 1 | 2021-09-16T05:06:18.000Z | 2021-09-16T05:06:18.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/Interface/Interface.h>
#include <AzCore/EBus/EBus.h>
#include <AzCore/RTTI/RTTI.h>
#include <AzCore/RTTI/TypeSafeIntegral.h>
#include <AzCore/std/time.h>
#include <AzCore/std/chrono/chrono.h>
namespace AZ
{
//! This is a strong typedef for representing a millisecond value since application start.
AZ_TYPE_SAFE_INTEGRAL(TimeMs, int64_t);
//! This is a strong typedef for representing a microsecond value since application start.
//! Using int64_t as the underlying type, this is good to represent approximately 292,471 years
AZ_TYPE_SAFE_INTEGRAL(TimeUs, int64_t);
//! @class ITime
//! @brief This is an AZ::Interface<> for managing time related operations.
//! AZ::ITime and associated types may not operate in realtime. These abstractions are to allow our application
//! simulation to operate both slower and faster than realtime in a well defined and user controllable manner
//! The rate at which time passes for AZ::ITime is controlled by the cvar t_scale
//! t_scale == 0 means simulation time should halt
//! 0 < t_scale < 1 will cause time to pass slower than realtime, with t_scale 0.1 being roughly 1/10th realtime
//! t_scale == 1 will cause time to pass at roughly realtime
//! t_scale > 1 will cause time to pass faster than normal, with t_scale 10 being roughly 10x realtime
class ITime
{
public:
AZ_RTTI(ITime, "{89D22C98-1450-44F1-952F-41284CC355F9}");
ITime() = default;
virtual ~ITime() = default;
//! Returns the number of milliseconds since application start.
//! @return the number of milliseconds that have elapsed since application start
virtual TimeMs GetElapsedTimeMs() const = 0;
//! Returns the number of microseconds since application start.
//! @return the number of microseconds that have elapsed since application start
virtual TimeUs GetElapsedTimeUs() const = 0;
AZ_DISABLE_COPY_MOVE(ITime);
};
// EBus wrapper for ScriptCanvas
class ITimeRequests
: public AZ::EBusTraits
{
public:
static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single;
static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single;
};
using ITimeRequestBus = AZ::EBus<ITime, ITimeRequests>;
//! This is a simple convenience wrapper
inline TimeMs GetElapsedTimeMs()
{
return AZ::Interface<ITime>::Get()->GetElapsedTimeMs();
}
//! This is a simple convenience wrapper
inline TimeUs GetElapsedTimeUs()
{
return AZ::Interface<ITime>::Get()->GetElapsedTimeUs();
}
//! Converts from milliseconds to microseconds
inline TimeUs TimeMsToUs(TimeMs value)
{
return static_cast<TimeUs>(value * static_cast<TimeMs>(1000));
}
//! Converts from microseconds to milliseconds
inline TimeMs TimeUsToMs(TimeUs value)
{
return static_cast<TimeMs>(value / static_cast<TimeUs>(1000));
}
//! Converts from milliseconds to seconds
inline float TimeMsToSeconds(TimeMs value)
{
return static_cast<float>(value) / 1000.0f;
}
//! Converts from microseconds to seconds
inline float TimeUsToSeconds(TimeUs value)
{
return static_cast<float>(value) / 1000000.0f;
}
//! Converts from milliseconds to AZStd::chrono::time_point
inline auto TimeMsToChrono(TimeMs value)
{
auto epoch = AZStd::chrono::time_point<AZStd::chrono::high_resolution_clock>();
auto chronoValue = AZStd::chrono::milliseconds(aznumeric_cast<int64_t>(value));
return epoch + chronoValue;
}
//! Converts from microseconds to AZStd::chrono::time_point
inline auto TimeUsToChrono(TimeUs value)
{
auto epoch = AZStd::chrono::time_point<AZStd::chrono::high_resolution_clock>();
auto chronoValue = AZStd::chrono::microseconds(aznumeric_cast<int64_t>(value));
return epoch + chronoValue;
}
} // namespace AZ
AZ_TYPE_SAFE_INTEGRAL_SERIALIZEBINDING(AZ::TimeMs);
AZ_TYPE_SAFE_INTEGRAL_SERIALIZEBINDING(AZ::TimeUs);
| 36.65 | 117 | 0.695771 | [
"3d"
] |
a97c652c279aebcb08936b5f245a86940d7031aa | 6,542 | h | C | tensorflow/core/tpu/kernels/compiled_subgraph.h | yage99/tensorflow | c7fa71b32a3635eb25596ae80d007b41007769c4 | [
"Apache-2.0"
] | 4 | 2020-06-28T08:25:36.000Z | 2021-08-12T12:41:34.000Z | tensorflow/core/tpu/kernels/compiled_subgraph.h | yage99/tensorflow | c7fa71b32a3635eb25596ae80d007b41007769c4 | [
"Apache-2.0"
] | 10 | 2021-08-03T08:42:38.000Z | 2022-01-03T03:29:12.000Z | tensorflow/core/tpu/kernels/compiled_subgraph.h | yage99/tensorflow | c7fa71b32a3635eb25596ae80d007b41007769c4 | [
"Apache-2.0"
] | 28 | 2020-02-10T07:03:06.000Z | 2022-01-12T11:19:20.000Z | /* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_CORE_TPU_KERNELS_COMPILED_SUBGRAPH_H_
#define TENSORFLOW_CORE_TPU_KERNELS_COMPILED_SUBGRAPH_H_
#include <memory>
#include <string>
#include "tensorflow/core/platform/refcount.h"
#include "tensorflow/core/platform/status.h"
#include "tensorflow/core/tpu/kernels/tpu_program_group_interface.h"
namespace tensorflow {
namespace tpu {
// Forward declaration to avoid circular dependency.
class TpuCompilationCacheInterface;
// Cache for compiled TPU program.
//
// Each key identifies a unique subgraph, and the value is the vector of
// protos that are emitted by compiling the subgraph.
//
// When a subgraph is considered for compilation, the client calls
//
// auto subgraph_key = <compute key for subgraph>;
// auto compile_function = <lambda to compile subgraph into protos>;
// auto per_step_ref_holder = <container to control lifetime of cached
// results>;
// int64 uid;
// std::vector<string> proto_key;
// CompileIfKeyAbsent(subgraph_key, per_step_ref_holder, &uid, &proto_key,
// compile_function);
//
// where subgraph_key is the key computed for the subgraph. On success,
// proto_key contains a vector of keys, where proto_key[i] can be used to look
// up the ith proto compiled from the subgraph, and uid contains an identifier
// that can be used in place of key for clients that require cheap
// serializable handles. If the compiled protos were not present in the cache,
// compile_function would be called to generate them. per_step_ref_holder
// extends the lifetime of cached results: it is guaranteed that the protos
// indicated in proto_key will be available for lookup for at least as long as
// per_step_ref_holder is not deleted.
//
// If the caller passes nullptr instead of a per_step_ref_holder then the
// caller is responsible for calling Release(subgraph_key) once for every call
// to CompileIfKeyAbsent(subgraph_key, ...) to discard the reference to the
// compilation results, after the caller is sure it will not look up the
// compiled executables again.
//
// Subsequently the client can call
//
// std::unique_ptr<CompilationCacheEntryRef> entry;
// Lookup(proto_key, &entry);
// auto proto = entry->get();
//
// or
//
// std::unique_ptr<CompilationCacheEntryRef> entry;
// Lookup(uid, proto_index, &entry);
// auto proto = entry->get();
//
// to access a cached proto.
// TODO(misard) Switch the existing TPU ops to use uid+proto_index instead of
// string keys for proto lookups.
//
//
// Usage details within the system:
//
// This cache lives in the resource manager of the TPU_SYSTEM device where the
// compiler runs, typically worker 0 of the system. The cache is discarded and
// a new one created whenever the system is reinitialized.
//
// A compiled subgraph is placed into the cache using a key that is a
// combination of the function name, guaranteed_constants, the shapes of the
// dynamic inputs to the subgraph, and the function library in use at the time
// of execution.
//
// Whenever a compile Op is run, it looks to see if there is already an entry
// in the cache corresponding to that Op and the current dynamic shapes, and
// creates one if not. The entry is marked as most recently used in the cache
// by the compile Op. The entry is reference counted. The cache owns one entry
// , and each step that has executed a compile Op referring to the entry owns
// a reference until that step completes.
//
// If the cache exceeds a configured storage limit, entries are marked for
// eviction in order of least recently used. An entry is not evicted until all
// references to it are discarded, so an entry that is marked for eviction can
// still be looked up by the execute Ops in a running step. If another Compile
// Op looks up an entry that is marked for eviction, the entry will be
// unmarked and set to most recently used.
//
struct CompiledSubgraph : public core::RefCounted {
TpuCompilationCacheInterface* parent = nullptr; // Not owned.
bool initialized = false;
// The Status returned by the compilation function when the entry is
// initialized. This status will be returned to any client that requests the
// entry.
Status initialization_status;
// Counter to keep track of LRU entries for the eviction policy.
int64_t last_use = -1;
// The unique key describing this entry.
std::string subgraph_key;
// The uid describing this entry.
int64_t uid;
// Compilation cache proto key to identify the cache entry.
std::vector<std::string> proto_key;
// The number of 'external' client-held references to the entry.
int external_references = 0;
// The sum of the SpaceUsed of each of the elements of programs; an estimate
// of how much RAM the entry consumes, used to determine when entries must
// be marked for eviction.
int64_t total_size = 0;
// Debug info in case we miss.
std::string cache_entry_debug_string;
// Entries representing the associated sharding and unsharding programs,
// which share the same life time of the owning main entry, so we always use
// the main entry's ref count.
std::unique_ptr<CompiledSubgraph> sharding_entry;
std::unique_ptr<CompiledSubgraph> unsharding_entry;
// Only used for the nested sharding/unsharding entries to point to the
// owning main entry.
CompiledSubgraph* main_entry = nullptr;
// Compiled TPU program group.
std::unique_ptr<TpuProgramGroupInterface> tpu_program_group;
// Computes total program size.
size_t ComputeTotalSize() const {
CHECK_EQ(total_size, 0);
int64 size = tpu_program_group->program_size();
if (sharding_entry != nullptr) {
size += sharding_entry->total_size;
}
if (unsharding_entry != nullptr) {
size += unsharding_entry->total_size;
}
return size;
}
};
} // namespace tpu
} // namespace tensorflow
#endif // TENSORFLOW_CORE_TPU_KERNELS_COMPILED_SUBGRAPH_H_
| 38.482353 | 80 | 0.744268 | [
"vector"
] |
a97cfbb5e4c7d18977b306e19231fb2c5011e7de | 5,322 | h | C | Pods/Atlas/Code/Views/ATLMessageInputToolbar.h | jinseokpark6/U-Team | 949a90acda55e0332a205c8f6694f6a6fe880a3f | [
"Apache-2.0"
] | 2 | 2015-11-15T19:47:45.000Z | 2015-11-30T07:43:28.000Z | Pods/Atlas/Code/Views/ATLMessageInputToolbar.h | jinseokpark6/u-team | 949a90acda55e0332a205c8f6694f6a6fe880a3f | [
"Apache-2.0"
] | 1 | 2016-03-12T19:40:47.000Z | 2016-03-12T19:40:47.000Z | Pods/Atlas/Code/Views/ATLMessageInputToolbar.h | jinseokpark6/U-Team | 949a90acda55e0332a205c8f6694f6a6fe880a3f | [
"Apache-2.0"
] | 1 | 2015-11-15T20:02:54.000Z | 2015-11-15T20:02:54.000Z | //
// ATLUIMessageInputToolbar.h
// Atlas
//
// Created by Kevin Coleman on 9/18/14.
// Copyright (c) 2015 Layer. 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 <UIKit/UIKit.h>
#import "ATLMessageComposeTextView.h"
#import "ATLMediaAttachment.h"
@class ATLMessageInputToolbar;
extern NSString *const ATLMessageInputToolbarDidChangeHeightNotification;
extern NSString *const ATLMessageInputToolbarAccessibilityLabel;
//---------------------------------
// Message Input Toolbar Delegate
//---------------------------------
/**
@abstract The `ATLMessageInputToolbarDelegate` notifies its receiver when buttons have been
tapped.
*/
@protocol ATLMessageInputToolbarDelegate <NSObject>
/**
@abstract Notifies the receiver that the right accessory button was tapped.
*/
- (void)messageInputToolbar:(ATLMessageInputToolbar *)messageInputToolbar didTapRightAccessoryButton:(UIButton *)rightAccessoryButton;
/**
@abstract Notifies the receiver that the left accessory button was tapped.
*/
- (void)messageInputToolbar:(ATLMessageInputToolbar *)messageInputToolbar didTapLeftAccessoryButton:(UIButton *)leftAccessoryButton;
@optional
/**
@abstract Notifies the receiver that typing has occurred.
*/
- (void)messageInputToolbarDidType:(ATLMessageInputToolbar *)messageInputToolbar;
/**
@abstract Notifies the receiver that typing has ended.
*/
- (void)messageInputToolbarDidEndTyping:(ATLMessageInputToolbar *)messageInputToolbar;
@end
/**
@abstract The `ATLMessageInputToolbar` provides a lightweight and customizable class
that is similar to the message input toolbar in Messages.
@discussion The class displays two customizable `UIButton` objects separated by a message input text view.
Instances are automatically resized in response to user or system input. The view also
caches any content provided and exposes that content back to a consuming object via the
mediaAttachments property.
*/
@interface ATLMessageInputToolbar : UIToolbar
//------------------------------
// Content Display Methods
//------------------------------
/**
@abstract Inserts the mediaAttachment as an attributed text attachment which is inlined with text.
@param mediaAttachment The `ATLMediaAttachment` instance containing information about the media.
@discussion The view will automatically resize the attachment's thumbnail and itself to comfortably
fit the thumbnail content. The image will also be cached and is accessible via the mediaAttachments
property.
*/
- (void)insertMediaAttachment:(ATLMediaAttachment *)mediaAttachment;
//-----------------------------
// UI Customization
//-----------------------------
/**
@abstract The left accessory button for the view.
@discussion By default, the button displays a camera icon. If set to `nil` the `textInputView` will expand to the left edge of the toolbar.
*/
@property (nonatomic) UIButton *leftAccessoryButton;
/**
@abstract The right accessory button for the view.
@discussion By default, the button displays the text "SEND".
*/
@property (nonatomic) UIButton *rightAccessoryButton;
/**
@abstract The font color for the right accessory button in active state.
*/
@property (nonatomic) UIColor *rightAccessoryButtonActiveColor UI_APPEARANCE_SELECTOR;
/**
@abstract The font color for the right accessory button in disabled state.
*/
@property (nonatomic) UIColor *rightAccessoryButtonDisabledColor UI_APPEARANCE_SELECTOR;
/**
@abstract The image displayed on left accessory button.
@default A `camera` icon.
*/
@property (nonatomic) UIImage *leftAccessoryImage;
/**
@abstract The image displayed on right accessory button.
@default A `location` icon.
*/
@property (nonatomic) UIImage *rightAccessoryImage;
/**
@abstract Determines whether or not the right accessory button displays an icon.
@disucssion If NO, the right accessory button will display the text `SEND` at all times.
@default YES
*/
@property(nonatomic) BOOL displaysRightAccessoryImage;
/**
@abstract An automatically resizing message composition field.
*/
@property (nonatomic) ATLMessageComposeTextView *textInputView;
/**
@abstract The delegate object for the view.
*/
@property (nonatomic, weak) id<ATLMessageInputToolbarDelegate> inputToolBarDelegate;
/**
@abstract The maximum number of lines of next to be displayed.
@default 8
@discussion The text view will stop growing once the maximum number of lines are displayed. It
will scroll its text view to keep the latest content visible.
*/
@property (nonatomic) NSUInteger maxNumberOfLines;
/**
@abstract An array of all media attachments displayed in the text view.
@discussion Any existing media attachments will be removed when the right accessory button is tapped.
*/
@property (nonatomic, readonly) NSArray *mediaAttachments;
@end
| 33.898089 | 140 | 0.753288 | [
"object"
] |
a9816e4f65de539aa7d9224117e6a8d4bac32b1d | 382 | h | C | Day 11 - Dumbo Octopus/Part 1/src/Utils.h | diff-arch/AdventOfCode2021- | a3e48eafed847af8c787dbf6e70e93975c3dc5fa | [
"MIT"
] | 1 | 2021-12-02T19:07:17.000Z | 2021-12-02T19:07:17.000Z | Day 11 - Dumbo Octopus/Part 1/src/Utils.h | diff-arch/AdventOfCode2021- | a3e48eafed847af8c787dbf6e70e93975c3dc5fa | [
"MIT"
] | null | null | null | Day 11 - Dumbo Octopus/Part 1/src/Utils.h | diff-arch/AdventOfCode2021- | a3e48eafed847af8c787dbf6e70e93975c3dc5fa | [
"MIT"
] | null | null | null | //
// Utils.h
// ADVENT OF CODE 2021: Day 11 - Dumbo Octopus (Part 1)
//
// Created by diff-arch on 11/12/2021.
//
#ifndef Utils_h
#define Utils_h
#include <vector>
#include <string>
#include <fstream>
#include <stdexcept>
/// \brief Reads a text file line by line.
/// \returns the vector of individual lines
std::vector<std::string> readData(const char* filepath);
#endif | 17.363636 | 56 | 0.688482 | [
"vector"
] |
a98c8bd5e97891290024f0db85ce8513738a3052 | 8,132 | c | C | server/re/src/data.c | DICE-UNC/iRODS-FUSE-Mod | 8f8e965493a03bcb085df0b6467e7dfcce308d0f | [
"BSD-3-Clause"
] | null | null | null | server/re/src/data.c | DICE-UNC/iRODS-FUSE-Mod | 8f8e965493a03bcb085df0b6467e7dfcce308d0f | [
"BSD-3-Clause"
] | 1 | 2015-09-24T04:20:30.000Z | 2015-09-24T04:20:30.000Z | server/re/src/data.c | DICE-UNC/iRODS-FUSE-Mod | 8f8e965493a03bcb085df0b6467e7dfcce308d0f | [
"BSD-3-Clause"
] | null | null | null | #include <libxslt/xslt.h>
#include <libxslt/xsltInternals.h>
#include <libxslt/transform.h>
#include <libxslt/xsltutils.h>
#include "data.h"
/*
* S ::= struct Id? { F* }
* F ::= Type Id Dim* Annotation* ;
* Annotation ::= Id AnnotationParamList?
* AnnotationParamList ::= ( Id , ... , Id )
* Type ::= BaseType "*"*
* BaseType ::= Id | struct Id
* Dim ::= [ Id ]
*/
PARSER_FUNC_BEGIN(CDefSet)
int rulegen = 1;
int i=0;
LOOP_BEGIN(d)
TRY(t)
TTEXT("typedef");
NT(CStructDef);
i++;
OR(t)
TTYPE(TK_EOS);
printf("defset: eos\n");
DONE(d);
OR(t)
NEXT_TOKEN_BASIC;
printf("defset: token skipped = %s\n", token->text);
END_TRY(t)
LOOP_END(d)
printf("defset : stackTop = %d, counter = %d, diff = %d\n", context->nodeStackTop, i, context->nodeStackTop - i);
BUILD_NODE(C_DEF_SET, "{}", &start, i, i);
PARSER_FUNC_END(CDefSet)
PARSER_FUNC_BEGIN(CIfdefBlock)
int rulegen = 1;
LOOP_BEGIN(loop)
TRY(p)
TTEXT2("#if", "#ifdef");
printf("token = %s\n", token->text);
/* assume that this is a #if 0 block */
/* assume that the macro is not defined */
LOOP_BEGIN(l1)
TRY(e)
TTEXT2("#else", "#endif");
printf("token = %s\n", token->text);
DONE(l1);
OR(e)
NEXT_TOKEN_BASIC;
printf("token skipped = %s\n", token->text);
END_TRY(e)
LOOP_END(l1)
OR(p)
TTEXT("#ifndef");
/* assume that the macro is not defined and it has not #else branch */
NEXT_TOKEN_BASIC;
OR(p)
TTEXT("#endif");
OR(p)
DONE(loop);
END_TRY(p)
LOOP_END(loop)
PARSER_FUNC_END(CIfdefBlock)
PARSER_FUNC_BEGIN(CStructDef)
int rulegen = 1;
char structName[NAME_LEN];
TTEXT("struct");
TRY(n)
TTYPE(TK_TEXT);
rstrcpy(structName, token->text, NAME_LEN);
OR(n)
rstrcpy(structName, "", NAME_LEN);
END_TRY(n)
TTEXT("{");
REPEAT_BEGIN(f)
NT(CIfdefBlock);
NT(CVariableDef);
REPEAT_END(f)
NT(CIfdefBlock);
TTEXT("}");
if(structName[0] == '\0') {
TTYPE(TK_TEXT);
rstrcpy(structName, token->text, NAME_LEN);
structName[strlen(structName)-2] = '\0';
if(isalpha(structName[0])) {
structName[0] = toupper(structName[0]);
}
}
printf("struct : stackTop = %d, counter = %d, diff = %d\n", context->nodeStackTop, COUNTER(f), context->nodeStackTop - COUNTER(f));
BUILD_NODE(C_STRUCT_DEF, structName, &start, COUNTER(f), COUNTER(f));
PARSER_FUNC_END(CStructDef)
PARSER_FUNC_BEGIN(CVariableDef)
int rulegen = 1;
char memberName[NAME_LEN];
NT(CType);
TTYPE(TK_TEXT);
rstrcpy(memberName, token->text, NAME_LEN);
REPEAT_BEGIN(f)
NT(CArrayDim);
BUILD_NODE(C_ARRAY_TYPE, "[]", &start, 2, 2);
REPEAT_END(f)
REPEAT_BEGIN(a)
NT(CGAnnotation);
REPEAT_END(a)
BUILD_NODE(CG_ANNOTATIONS, "annotations", &start, COUNTER(a), COUNTER(a));
TTEXT(";");
BUILD_NODE(C_STRUCT_MEMBER, memberName, &start, 2, 2);
PARSER_FUNC_END(CVariableDef)
PARSER_FUNC_BEGIN(CGAnnotation)
int rulegen = 1;
int n;
char annotationName[NAME_LEN];
TTYPE(TK_TEXT);
rstrcpy(annotationName, token->text, NAME_LEN);
TRY(plt)
LIST_BEGIN(pl)
NT(CGAnnotation)
LIST_DELIM(pl)
TTEXT(",");
LIST_END(pl)
n = COUNTER(pl);
OR(plt)
n = 0;
END_TRY(plt)
BUILD_NODE(CG_ANNOTATION, annotationName, &start, n, n);
PARSER_FUNC_END(CGAnnotation)
PARSER_FUNC_BEGIN(CType)
int rulegen = 1;
NT(CBaseType);
REPEAT_BEGIN(f)
TTEXT("*");
BUILD_NODE(C_POINTER_TYPE, "*", &start, 1, 1);
REPEAT_END(f)
PARSER_FUNC_END(CType)
PARSER_FUNC_BEGIN(CBaseType)
int rulegen = 1;
char type[NAME_LEN];
TRY(bt)
TTEXT("struct");
TTYPE(TK_TEXT);
BUILD_NODE(C_STRUCT_TYPE, token->text, &start, 0, 0);
OR(bt)
TTEXT("unsigned");
TTYPE(TK_TEXT);
snprintf(type, NAME_LEN, "%s %s", "unsigned", token->text);
BUILD_NODE(C_BASE_TYPE, type, &start, 0, 0);
OR(bt)
TTEXT("long");
TTEXT("int");
snprintf(type, NAME_LEN, "%s %s", "long", token->text);
BUILD_NODE(C_BASE_TYPE, type, &start, 0, 0);
OR(bt)
TTYPE(TK_TEXT);
BUILD_NODE(C_BASE_TYPE, token->text, &start, 0, 0);
END_TRY(bt)
PARSER_FUNC_END(CBaseType)
PARSER_FUNC_BEGIN(CArrayDim)
int rulegen = 1;
char dimName[NAME_LEN];
Label l;
TTEXT("[");
l = *FPOS;
TTYPE(TK_TEXT);
rstrcpy(dimName, token->text, NAME_LEN);
TTEXT("]");
BUILD_NODE(C_ARRAY_TYPE_DIM, dimName, &l, 0, 0);
PARSER_FUNC_END(CArrayDim)
codeBuffer_t *newCodeBuffer() {
codeBuffer_t *buf = (codeBuffer_t *) malloc(sizeof(codeBuffer_t));
buf->size = CODE_BUF_SIZE;
buf->pos = 0;
buf->buffer = (char *) malloc(buf->size);
return buf;
}
void deleteCodeBuffer(codeBuffer_t *buf) {
free(buf->buffer);
free(buf);
}
int appendToCodeBuffer(codeBuffer_t *codeBuffer, char *code) {
int n = strnlen(code, MAX_CODE_APPEND_LENGTH);
if(n == MAX_CODE_APPEND_LENGTH) {
// error
return -1;
} else {
while(codeBuffer->size - codeBuffer->pos < n) {
codeBuffer->buffer = (char *)realloc(codeBuffer->buffer, codeBuffer->size * 2);
codeBuffer->size *= 2;
}
memcpy(codeBuffer->buffer+codeBuffer->pos, code, n);
codeBuffer->pos += n;
return 0;
}
}
char *getTag(NodeType nt) {
switch(nt) {
case C_STRUCT_DEF:
return "struct";
case C_STRUCT_MEMBER:
return "struct_member";
case C_ARRAY_TYPE:
return "array_type";
case C_ARRAY_TYPE_DIM:
return "array_dim";
case C_POINTER_TYPE:
return "pointer_type";
case C_STRUCT_TYPE:
return "struct_type";
case C_BASE_TYPE:
return "base_type";
case C_DEF_SET:
return "def_set";
case CG_ANNOTATIONS:
return "annotations";
case CG_ANNOTATION:
return "annotation";
default:
return NULL;
}
}
int toXML(Node *ast, codeBuffer_t *codeBuffer) {
int i;
char *tag = getTag(getNodeType(ast));
if(tag == NULL) {
printf("unsupported node type %d\n", getNodeType(ast));
return RE_UNSUPPORTED_AST_NODE_TYPE;
}
char stag[1024], ftag[1024];
snprintf(stag, 1024, "<%s name='%s'>", tag, ast->text);
snprintf(ftag, 1024, "</%s>", tag);
appendToCodeBuffer(codeBuffer, stag);
for(i = 0; i < ast->degree; i++) {
toXML(ast->subtrees[i], codeBuffer);
}
appendToCodeBuffer(codeBuffer, ftag);
return 0;
}
int testData() {
Region *r = make_region(0, NULL);
rError_t errmsgBuf;
errmsgBuf.errMsg = NULL;
errmsgBuf.len = 0;
ParserContext *pc = newParserContext(&errmsgBuf, r);
Pointer *e = newPointer2("struct abc { int x; long * y; short * * y1; struct abc z; struct abc w [X][Y];int * * w1[X];}");
nextRuleGenCStructDef(e, pc);
Node *n = pc->nodeStack[0];
printTree(n, 0);
codeBuffer_t *cb = newCodeBuffer();
toXML(n, cb);
printf("\n%s\n", cb->buffer);
return 0;
}
#ifdef CODE_GENERATION
int main(int argc, char **args) {
if(argc<4) {
printf("usage:\nRuleEngine <xslt file> <output file> <header file> ...\n");
return 0;
}
char *xsltFileName = args[1];
char *outputFileName = args[2];
char **headerFileName = args+3;
int nHFs = argc - 3;
Region *r = make_region(0, NULL);
rError_t errmsgBuf;
errmsgBuf.errMsg = NULL;
errmsgBuf.len = 0;
int i;
codeBuffer_t *cb = newCodeBuffer();
appendToCodeBuffer(cb, "<root>");
for(i=0;i<nHFs;i++) {
ParserContext *pc = newParserContext(&errmsgBuf, r);
FILE *fp = fopen(headerFileName[i], "r");
if(fp==NULL) {
printf("cannot open header file\n");
return 0;
}
Pointer *e = newPointer(fp, headerFileName[i]);
nextRuleGenCDefSet(e, pc);
if(pc->errmsg->len > 0) {
char buf[1024];
errMsgToString(pc->errmsg, buf, 1024);
printf("error: %s\n", buf);
}
if(pc->nodeStackTop != 1) {
printf("error: nodeStackTop = %d\n", pc->nodeStackTop);
}
Node *n = pc->nodeStack[0];
printTree(n, 0);
toXML(n, cb);
deletePointer(e);
deleteParserContext(pc);
}
appendToCodeBuffer(cb, "</root>");
printf("\n%s\n", cb->buffer);
char *xml = cb->buffer;
xsltStylesheetPtr cur = NULL;
xmlDocPtr doc, res;
xmlSubstituteEntitiesDefault(1);
cur = xsltParseStylesheetFile((const xmlChar *) xsltFileName);
doc = xmlParseDoc((const xmlChar *) xml);
res = xsltApplyStylesheet(cur, doc, NULL);
xsltSaveResultToFilename(outputFileName, res, cur, 0);
xsltFreeStylesheet(cur);
xmlFreeDoc(res);
xmlFreeDoc(doc);
xsltCleanupGlobals();
xmlCleanupParser();
/* if(fp==NULL) {
printf("cannot open header file\n");
return 0;
}
*/
return 0;
}
#endif
| 22.279452 | 132 | 0.666872 | [
"transform"
] |
a98d7166d273d8589730c82a2e5eec9acc46e7e5 | 25,940 | h | C | src/sm/xct.h | caetanosauer/fineline-zero | 74490df94728e513c2dd41f3edb8200698548b78 | [
"Spencer-94"
] | 12 | 2018-12-14T08:57:05.000Z | 2021-12-14T17:37:44.000Z | src/sm/xct.h | caetanosauer/fineline-zero | 74490df94728e513c2dd41f3edb8200698548b78 | [
"Spencer-94"
] | null | null | null | src/sm/xct.h | caetanosauer/fineline-zero | 74490df94728e513c2dd41f3edb8200698548b78 | [
"Spencer-94"
] | 2 | 2019-08-04T21:39:12.000Z | 2019-11-09T03:18:48.000Z | /*
* (c) Copyright 2011-2014, Hewlett-Packard Development Company, LP
*/
/* -*- mode:C++; c-basic-offset:4 -*-
Shore-MT -- Multi-threaded port of the SHORE storage manager
Copyright (c) 2007-2009
Data Intensive Applications and Systems Labaratory (DIAS)
Ecole Polytechnique Federale de Lausanne
All Rights Reserved.
Permission to use, copy, modify and distribute this software and
its documentation is hereby granted, provided that both the
copyright notice and this permission notice appear in all copies of
the software, derivative works or modified versions, and any
portions thereof, and that both notices appear in supporting
documentation.
This code is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. THE AUTHORS
DISCLAIM ANY LIABILITY OF ANY KIND FOR ANY DAMAGES WHATSOEVER
RESULTING FROM THE USE OF THIS SOFTWARE.
*/
/*<std-header orig-src='shore' incl-file-exclusion='XCT_H'>
$Id: xct.h,v 1.161 2010/12/08 17:37:43 nhall Exp $
SHORE -- Scalable Heterogeneous Object REpository
Copyright (c) 1994-99 Computer Sciences Department, University of
Wisconsin -- Madison
All Rights Reserved.
Permission to use, copy, modify and distribute this software and its
documentation is hereby granted, provided that both the copyright
notice and this permission notice appear in all copies of the
software, derivative works or modified versions, and any portions
thereof, and that both notices appear in supporting documentation.
THE AUTHORS AND THE COMPUTER SCIENCES DEPARTMENT OF THE UNIVERSITY
OF WISCONSIN - MADISON ALLOW FREE USE OF THIS SOFTWARE IN ITS
"AS IS" CONDITION, AND THEY DISCLAIM ANY LIABILITY OF ANY KIND
FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
This software was developed with support by the Advanced Research
Project Agency, ARPA order number 018 (formerly 8230), monitored by
the U.S. Army Research Laboratory under contract DAAB07-91-C-Q518.
Further funding for this work was provided by DARPA through
Rome Research Laboratory Contract No. F30602-97-2-0247.
*/
#ifndef XCT_H
#define XCT_H
#include "w_defines.h"
/* -- do not edit anything above this line -- </std-header>*/
#if W_DEBUG_LEVEL > 2
// You can rebuild with this turned on
// if you want comment log records inserted into the log
// to help with deciphering the log when recovery bugs
// are nasty.
#define X_LOG_COMMENT_ON 1
#define ADD_LOG_COMMENT_SIG ,const char *debugmsg
#define ADD_LOG_COMMENT_USE ,debugmsg
#define X_LOG_COMMENT_USE(x) ,x
#else
#define X_LOG_COMMENT_ON 0
#define ADD_LOG_COMMENT_SIG
#define ADD_LOG_COMMENT_USE
#define X_LOG_COMMENT_USE(x)
#endif
#include <chrono>
#include <set>
#include <atomic>
#include <AtomicCounter.hpp>
#include "w_key.h"
#include "lsn.h"
#include "allocator.h"
#include "latches.h"
#include "sm_base.h"
struct okvl_mode;
struct RawXct;
class lockid_t; // forward
class xct_i; // forward
class restart_thread_t; // forward
class lock_m; // forward
class lock_core_m; // forward
class lock_request_t; // forward
class xct_lock_info_t; // forward
class smthread_t; // forward
class lil_private_table;
class logrec_t; // forward
class fixable_page_h; // forward
/**
* Results of in-query (not batch) BTree verification.
* In-query verification is on when xct_t::set_inquery_verify(true).
* Use In-query verification as follows:
* \verbatim
xct()->set_inquery_verify(true); // verification mode on
xct()->set_inquery_verify_keyorder(true); // detailed check for sortedness/uniqueness
xct()->set_inquery_verify_space(true); // detailed check for space overlap
ss_m::create_assoc(...);
ss_m::find_assoc(...);
...
const inquery_verify_context_t &result = xct()->inquery_verify_context();
cout << "checked " << result.pages_checked << "pages"
<< " and found " << result.pids_inconsistent.size() << " inconsistencies.";
if (result.pids_inconsistent.size() > 0) {
// output IDs of inconsistent pages etc..
}
}\endverbatim
*/
class inquery_verify_context_t {
public:
inquery_verify_context_t() : pages_checked(0), next_pid(0), next_level(0) {
}
/** total count of pages checked (includes checks of same page). */
int32_t pages_checked;
/** ID of pages that had some inconsistency. */
std::set<PageID> pids_inconsistent;
/** expected next page id. */
PageID next_pid;
/** expected next page level. -1 means "don't check" (only for root page). */
int16_t next_level;
/** expected next fence-low key. */
w_keystr_t next_low_key;
/** expected next fence-high key. */
w_keystr_t next_high_key;
};
/**\cond skip
* \brief Class used to keep track of stores to be
* freed or changed from tmp to regular at the end of
* a transaction
*/
class stid_list_elem_t {
public:
StoreID stid;
w_link_t _link;
stid_list_elem_t(const StoreID& theStid)
: stid(theStid)
{};
~stid_list_elem_t()
{
if (_link.member_of() != NULL)
_link.detach();
}
static uint32_t link_offset()
{
return W_LIST_ARG(stid_list_elem_t, _link);
}
};
/**\endcond skip */
/**
* \brief A transaction. Internal to the storage manager.
* \ingroup SSMXCT
* This class may be used in a limited way for the handling of
* out-of-log-space conditions. See \ref SSMLOG.
*/
class xct_t : public smlevel_0 {
/**\cond skip */
friend class xct_i;
friend class smthread_t;
friend class lock_m;
friend class lock_core_m;
friend class lock_request_t;
public:
typedef xct_state_t state_t;
/* A nearly-POD struct whose only job is to enable a N:1
relationship between the log streams of a transaction (xct_t)
and its core functionality such as locking and 2PC (xct_core).
Any transaction state which should not eventually be replicated
per-thread goes here. Usually such state is protected by the
1-thread-xct-mutex.
Static data members can stay in xct_t, since they're not even
duplicated per-xct, let alone per-thread.
*/
struct xct_core
{
xct_core(tid_t const &t, state_t s, int timeout);
~xct_core();
//-- from xct.h ----------------------------------------------------
tid_t _tid;
int _timeout; // default timeout value for lock reqs
xct_lock_info_t* _lock_info;
lil_private_table* _lil_lock_info;
/** RAW-style lock manager's shadow transaction object. Garbage collected. */
RawXct* _raw_lock_xct;
state_t _state;
// CS: Using these instead of the old new_xct and destroy_xct methods
void* operator new(size_t s);
void operator delete(void* p, size_t s);
};
protected:
xct_core* _core;
protected:
enum commit_t { t_normal = 0, t_lazy = 1 };
/**\endcond skip */
/**\cond skip */
public:
rc_t commit_free_locks(bool read_lock_only = false, lsn_t commit_lsn = lsn_t::null);
rc_t early_lock_release(lsn_t last_lsn);
bool has_logs();
// CS: Using these instead of the old new_xct and destroy_xct methods
void* operator new(size_t s);
void operator delete(void* p, size_t s);
public:
NORET xct_t(
sm_stats_t* stats = NULL,
int timeout = timeout_t::WAIT_SPECIFIED_BY_THREAD,
const tid_t& tid = 0,
const lsn_t& last_lsn = lsn_t::null,
bool loser_xct = false
);
~xct_t();
public:
friend ostream& operator<<(ostream&, const xct_t&);
state_t state() const;
void set_timeout(int t) ;
int timeout_c() const;
/*
* basic tx commands:
*/
public:
static void dump(ostream &o);
static void cleanup(bool shutdown_clean = true);
bool is_instrumented() {
return (__stats != 0);
}
void give_stats(sm_stats_t* s) {
w_assert1(__stats == 0);
__stats = s;
}
void clear_stats() {
memset(__stats,0, sizeof(*__stats));
}
sm_stats_t* steal_stats() {
sm_stats_t*s = __stats;
__stats = 0;
return s;
}
const sm_stats_t& const_stats_ref() { return *__stats; }
rc_t commit(bool sync_log = true);
rc_t rollback();
rc_t abort(bool save_stats = false);
// used by restart.cpp, some logrecs
protected:
sm_stats_t& stats_ref() { return *__stats; }
rc_t dispose();
void change_state(state_t new_state);
/**\endcond skip */
public:
// used by restart, chkpt among others
static xct_t* look_up(const tid_t& tid);
static tid_t oldest_tid(); // with min tid value
static tid_t youngest_tid(); // with max tid value
/**\cond skip */
static void update_youngest_tid(const tid_t &);
/**\endcond skip */
// used by sm.cpp:
static uint32_t num_active_xcts();
public: // not quite public thing.. but convenient for experiments
xct_lock_info_t* lock_info() const;
lil_private_table* lil_lock_info() const;
RawXct* raw_lock_xct() const;
public:
// XXX this is only for chkpt::take(). This problem needs to
// be fixed correctly. DO NOT USE THIS. Really want a
// friend that is just a friend on some methods, not the entire class.
static w_rc_t acquire_xlist_mutex();
static void release_xlist_mutex();
static void assert_xlist_mutex_not_mine();
static void assert_xlist_mutex_is_mine();
static bool xlist_mutex_is_mine();
/////////////////////////////////////////////////////////////////
// DATA
/////////////////////////////////////////////////////////////////
protected:
// list of all transactions instances
w_link_t _xlink;
static w_descend_list_t<xct_t, queue_based_lock_t, tid_t> _xlist;
void put_in_order();
// CS TODO: TID assignment could be thread-local
static std::atomic<tid_t> _nxt_tid;// only safe for pre-emptive
// threads on 64-bit platforms
static tid_t _oldest_tid;
private:
static queue_based_lock_t _xlist_mutex;
sm_stats_t* __stats; // allocated by user
lockid_t* __saved_lockid_t;
tid_t _tid;
/**
* \brief The count of consecutive SSXs conveyed by this transaction object.
* \details
* SSX can't nest SSX.
* However, as SSX doesn't care what the transaction object is, SSX can \e chain
* an arbitraly number of SSXs as far as they are consecutive SSXs, no multi-log
* system transactions or user-transactions in-between.
* In that case, we simply increment/decrement this counter when we
* start/end SSX. Chaining is useful when SSX operation might cause another SSX
* operation, eg ghost-reservation causes page-split which causes page-evict etc etc.
*/
uint32_t _ssx_chain_len;
static constexpr size_t MaxDepth = 8;
std::array<size_t, MaxDepth> _ssx_positions;
/** concurrency mode of this transaction. */
concurrency_t _query_concurrency;
/** whether to take X lock for lookup/cursor. */
bool _query_exlock_for_select;
// hey, these could be one integer with OR-ed flags
/**
* whether to defer the logging and applying of the change made
* by single-log system transaxction (SSX). Experimental.
*/
bool _deferred_ssx;
/** whether in-query verification is on. */
bool _inquery_verify;
/** whether to additionally check the sortedness and uniqueness of keys. */
bool _inquery_verify_keyorder;
/** whether to check any overlaps of records and integrity of space offset. */
bool _inquery_verify_space;
/** result and context of in-query verification. */
inquery_verify_context_t _inquery_verify_context;
// Latch object mainly for checkpoint to access information in txn object
latch_t _latch;
protected:
void flush_redo_buffer(bool sys_xct = false, bool sync = true);
rc_t _commit_read_only(lsn_t& inherited_read_watermark);
private:
bool one_thread_attached() const; // assertion
public:
bool is_sys_xct () const { return _ssx_chain_len > 0; }
void push_ssx();
void pop_ssx();
void set_inquery_verify(bool enabled) { _inquery_verify = enabled; }
bool is_inquery_verify() const { return _inquery_verify; }
void set_inquery_verify_keyorder(bool enabled) { _inquery_verify_keyorder = enabled; }
bool is_inquery_verify_keyorder() const { return _inquery_verify_keyorder; }
void set_inquery_verify_space(bool enabled) { _inquery_verify_space = enabled; }
bool is_inquery_verify_space() const { return _inquery_verify_space; }
const inquery_verify_context_t& inquery_verify_context() const { return _inquery_verify_context;}
inquery_verify_context_t& inquery_verify_context() { return _inquery_verify_context;}
concurrency_t get_query_concurrency() const { return _query_concurrency; }
void set_query_concurrency(concurrency_t mode) { _query_concurrency = mode; }
bool get_query_exlock_for_select() const {return _query_exlock_for_select;}
void set_query_exlock_for_select(bool mode) {_query_exlock_for_select = mode;}
ostream & dump_locks(ostream &) const;
/////////////////////////////////////////////////////////////////
private:
/////////////////////////////////////////////////////////////////
// non-const because it acquires mutex:
// removed, now that the lock mgrs use the const,INLINE-d form
// int timeout();
static void xct_stats(
u_long& begins,
u_long& commits,
u_long& aborts,
bool reset);
void _teardown();
public:
/**
* Early Lock Release mode.
* This is a totally separated implementation from Quarks.
* @see _read_watermark
*/
enum elr_mode_t {
/** ELR is disabled. */
elr_none,
/** ELR releases only S, U, and intent locks (same as Quarks?). */
elr_s,
/**
* ELR releases all locks. When this mode is on, even read-only transactions
* do an additional check to maintain serializability. So, do NOT forget to
* set this mode to ALL transactions if you are using it for any of
* your transactions.
*/
elr_sx,
/**
* ELR releases no locks but gives permissions for its locks
* to be violated. When this mode is on, even read-only
* transactions do an additional check to maintain
* serializability. So, do NOT forget to set this mode to ALL
* transactions if you are using it for any of your
* transactions.
*/
elr_clv
};
protected: // all data members protected
/**
* Whenever a transaction acquires some lock,
* this value is updated as _read_watermark=max(_read_watermark, lock_bucket.tag)
* so that we maintain a maximum commit LSN of transactions it depends on.
* This value is used to commit a read-only transaction with Safe SX-ELR to block
* until the log manager flushed the log buffer at least to this value.
* Assuming this protocol, we can do ELR for x-locks.
* See jira ticket:99 "ELR for X-lock" (originally trac ticket:101).
*/
lsn_t _read_watermark;
elr_mode_t _elr_mode;
// timestamp for calculating latency
std::chrono::high_resolution_clock::time_point _begin_tstamp;
public:
#if W_DEBUG_LEVEL > 2
private:
bool _had_error;
public:
// Tells if we ever did a partial rollback.
// This state is only needed for certain assertions.
void set_error_encountered() { _had_error = true; }
bool error_encountered() const {
return _had_error; }
#else
void set_error_encountered() {}
bool error_encountered() const { return false; }
#endif
tid_t tid() const {
w_assert1(_core == NULL || _tid == _core->_tid);
return _tid; }
uint32_t& ssx_chain_len() { return _ssx_chain_len;}
const lsn_t& get_read_watermark() const { return _read_watermark; }
void update_read_watermark(const lsn_t &tag) {
if (_read_watermark < tag) {
_read_watermark = tag;
}
}
elr_mode_t get_elr_mode() const { return _elr_mode; }
void set_elr_mode(elr_mode_t mode) { _elr_mode = mode; }
// Latch the xct object in order to access internal data
// it is to prevent data changing while reading them
// Mainly for checkpoint logging purpose
latch_t* latchp() const
{
// If _core is gone (txn is being destroyed), return NULL
// CS TODO: this is incorrect. Threads waiting on the latch after
// core is destructed will encounter a segmentation fault. The real
// problem here is that an object should not be destroyed while some
// thread may still try to access it. We need a different design or
// some higher form of concurrency control.
// if ( NULL == _core)
// return (latch_t *)NULL;
return const_cast<latch_t*>(&(_latch));
}
latch_t &latch()
{
return *latchp();
}
};
/* XXXX This is somewhat hacky becuase I am working on cleaning
up the xct_i xct iterator to provide various levels of consistency.
Until then, the "locking option" provides enough variance so
code need not be duplicated or have deep call graphs. */
/**\brief Iterator over transaction list.
*
* This is exposed for the purpose of coping with out-of-log-space
* conditions. See \ref SSMLOG.
*/
class xct_i {
public:
// NB: still not safe, since this does not
// lock down the list for the entire iteration.
// FRJ: Making it safe -- all non-debug users lock it down
// manually right now anyway; the rest *should* to avoid bugs.
/// True if this thread holds the transaction list mutex.
bool locked_by_me() const {
if(xct_t::xlist_mutex_is_mine()) {
W_IFDEBUG1(if(_may_check) w_assert1(_locked);)
return true;
}
return false;
}
/// Release transaction list mutex if this thread holds it.
void never_mind() {
// Be careful here: must leave in the
// state it was when we constructed this.
if(_locked && locked_by_me()) {
*(const_cast<bool *>(&_locked)) = false; // grot
xct_t::release_xlist_mutex();
}
}
/// Get transaction at cursor.
xct_t* curr() const { return unsafe_iterator.curr(); }
/// Advance cursor.
xct_t* next() { return unsafe_iterator.next(); }
/**\cond skip */
// Note that this is called to INIT the attribute "locked"
static bool init_locked(bool lockit)
{
if(lockit) {
W_COERCE(xct_t::acquire_xlist_mutex());
}
return lockit;
}
/**\endcond skip */
/**\brief Constructor.
*
* @param[in] locked_accesses Set to true if you want this
* iterator to be safe, false if you don't care or if you already
* hold the transaction-list mutex.
*/
NORET xct_i(bool locked_accesses)
: _locked(init_locked(locked_accesses)),
_may_check(locked_accesses),
unsafe_iterator(xct_t::_xlist)
{
w_assert1(_locked == locked_accesses);
_check(_locked);
}
/// Desctructor. Calls never_mind() if necessary.
NORET ~xct_i() {
if(locked_by_me()) {
_check(true);
never_mind();
_check(false);
}
}
private:
void _check(bool b) const {
if(!_may_check) return;
if(b) xct_t::assert_xlist_mutex_is_mine();
else xct_t::assert_xlist_mutex_not_mine();
}
// FRJ: make sure init_locked runs before we actually create the iterator
const bool _locked;
const bool _may_check;
w_list_i<xct_t,queue_based_lock_t> unsafe_iterator;
// disabled
xct_i(const xct_i&);
xct_i& operator=(const xct_i&);
};
/**\cond skip */
inline
xct_t::state_t
xct_t::state() const
{
if (NULL == _core)
return xct_ended;
return _core->_state;
}
// For use in sm functions that don't allow
// active xct when entered. These are functions that
// apply to local volumes only.
class xct_auto_abort_t : public smlevel_0 {
public:
xct_auto_abort_t() : _xct(new xct_t()) {
}
~xct_auto_abort_t() {
switch(_xct->state()) {
case smlevel_0::xct_ended:
// do nothing
break;
case smlevel_0::xct_active:
case smlevel_0::xct_freeing_space: // we got an error in commit
case smlevel_0::xct_committing: // we got an error in commit
W_COERCE(_xct->abort());
break;
default:
cerr << "unexpected xct state: " << _xct->state() << endl;
W_FATAL(eINTERNAL);
}
delete _xct;
}
rc_t commit() {
W_DO(_xct->commit());
return RCOK;
}
rc_t abort() {W_DO(_xct->abort()); return RCOK;}
private:
xct_t* _xct;
};
inline
bool
operator>(const xct_t& x1, const xct_t& x2)
{
return (x1.tid() > x2.tid());
}
/**\endcond skip */
// TODO. this should accept store id/volume id.
// it should say 'does not need' if we have absolute locks in LIL.
// same thing can be manually achieved by user code, though.
inline bool
g_xct_does_need_lock()
{
xct_t* x = xct();
if (x == NULL) return false;
if (x->is_sys_xct()) return false; // system transaction never needs locks
return x->get_query_concurrency() == smlevel_0::t_cc_keyrange;
}
inline bool
g_xct_does_ex_lock_for_select()
{
xct_t* x = xct();
return x && x->get_query_exlock_for_select();
}
/**
* \brief Used to automatically begin/commit/abort a system transaction.
* \details
* Use this class as follows:
* \verbatim
rc_t some_function ()
{
// the function to use system transaction
sys_xct_section_t sxs;
W_DO (sxs.check_error_on_start()); // optional: check the system xct successfully started
rc_t result = do_some_thing();
W_DO (sxs.end_sys_xct (result)); //commit or abort, depending on the result code
// if we exit this function without calling end_sys_xct(), the system transaction
// automatically aborts.
return result;
}\endverbatim
*/
class sys_xct_section_t {
public:
/**
* starts a nested system transaction.
*/
sys_xct_section_t();
/** This destructor makes sure the system transaction ended. */
~sys_xct_section_t();
/** Commits or aborts the system transaction, depending on the given result code.*/
rc_t end_sys_xct (rc_t result);
int _depth;
};
/** Used to tentatively set t_cc_none to _query_concurrency. */
class no_lock_section_t {
public:
no_lock_section_t () {
xct_t *x = xct();
if (x) {
DBGOUT3( << "!!!! no_lock_section_t() - lock has been disabled");
org_cc = x->get_query_concurrency();
x->set_query_concurrency(smlevel_0::t_cc_none);
} else {
DBGOUT3( << "!!!! no_lock_section_t() - set original lock mode to t_cc_none");
org_cc = smlevel_0::t_cc_none;
}
}
~no_lock_section_t () {
xct_t *x = xct();
if (x) {
DBGOUT3( << "!!!! ~no_lock_section_t() - restored original lock mode: " << org_cc);
x->set_query_concurrency(org_cc);
}
}
private:
smlevel_0::concurrency_t org_cc;
};
// microseconds to "give up" watermark waits and flushes its own log in readonly xct
const int ELR_READONLY_WAIT_MAX_COUNT = 10;
const int ELR_READONLY_WAIT_USEC = 2000;
/*<std-footer incl-file-exclusion='XCT_H'> -- do not edit anything below this line -- */
#endif /*</std-footer>*/
| 33.776042 | 113 | 0.603277 | [
"object"
] |
a98d78dfd2785825c0eed87bbea8040f8c63337e | 3,191 | h | C | src/accelerators/kdtreeaccel.h | YuMoZhiChu/pbrt-v3 | 9aea028a4678c418a2a2157235a37438592e5b57 | [
"BSD-2-Clause"
] | null | null | null | src/accelerators/kdtreeaccel.h | YuMoZhiChu/pbrt-v3 | 9aea028a4678c418a2a2157235a37438592e5b57 | [
"BSD-2-Clause"
] | null | null | null | src/accelerators/kdtreeaccel.h | YuMoZhiChu/pbrt-v3 | 9aea028a4678c418a2a2157235a37438592e5b57 | [
"BSD-2-Clause"
] | null | null | null |
/*
pbrt source code is Copyright(c) 1998-2016
Matt Pharr, Greg Humphreys, and Wenzel Jakob.
This file is part of pbrt.
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.
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.
*/
#if defined(_MSC_VER)
#define NOMINMAX
#pragma once
#endif
#ifndef PBRT_ACCELERATORS_KDTREEACCEL_H
#define PBRT_ACCELERATORS_KDTREEACCEL_H
// accelerators/kdtreeaccel.h*
#include "pbrt.h"
#include "primitive.h"
namespace pbrt {
// KdTreeAccel Declarations
struct KdAccelNode;
struct BoundEdge;
class KdTreeAccel : public Aggregate {
public:
// KdTreeAccel Public Methods
KdTreeAccel(std::vector<std::shared_ptr<Primitive>> p,
int isectCost = 80, int traversalCost = 1,
Float emptyBonus = 0.5, int maxPrims = 1, int maxDepth = -1);
Bounds3f WorldBound() const { return bounds; }
~KdTreeAccel();
bool Intersect(const Ray &ray, SurfaceInteraction *isect) const;
bool IntersectP(const Ray &ray) const;
private:
// KdTreeAccel Private Methods
void buildTree(int nodeNum, const Bounds3f &bounds,
const std::vector<Bounds3f> &primBounds, int *primNums,
int nprims, int depth,
const std::unique_ptr<BoundEdge[]> edges[3], int *prims0,
int *prims1, int badRefines = 0);
// KdTreeAccel Private Data
const int isectCost, traversalCost, maxPrims;
const Float emptyBonus;
std::vector<std::shared_ptr<Primitive>> primitives;
std::vector<int> primitiveIndices;
KdAccelNode *nodes;
// nAllocedNodes 节点总数 nodeFreeNode 记录下一个可用的Node
int nAllocedNodes, nextFreeNode;
Bounds3f bounds;
};
struct KdToDo {
const KdAccelNode *node;
Float tMin, tMax;
};
std::shared_ptr<KdTreeAccel> CreateKdTreeAccelerator(
std::vector<std::shared_ptr<Primitive>> prims, const ParamSet &ps);
} // namespace pbrt
#endif // PBRT_ACCELERATORS_KDTREEACCEL_H
| 35.065934 | 77 | 0.715763 | [
"vector"
] |
a98f254cc81a3448858987a2e1fc0eb3b2d45139 | 5,522 | h | C | isis/src/base/apps/spkwriter/SpkSegment.h | ihumphrey-usgs/ISIS3_old | 284cc442b773f8369d44379ee29a9b46961d8108 | [
"Unlicense"
] | null | null | null | isis/src/base/apps/spkwriter/SpkSegment.h | ihumphrey-usgs/ISIS3_old | 284cc442b773f8369d44379ee29a9b46961d8108 | [
"Unlicense"
] | null | null | null | isis/src/base/apps/spkwriter/SpkSegment.h | ihumphrey-usgs/ISIS3_old | 284cc442b773f8369d44379ee29a9b46961d8108 | [
"Unlicense"
] | 1 | 2021-07-12T06:05:03.000Z | 2021-07-12T06:05:03.000Z | #ifndef SpkSegment_h
#define SpkSegment_h
/**
* @file
* $Revision: 6314 $
* $Date: 2015-08-12 15:30:27 -0700 (Wed, 12 Aug 2015) $
*
* Unless noted otherwise, the portions of Isis written by the USGS are
* public domain. See individual third-party library and package descriptions
* for intellectual property information, user agreements, and related
* information.
*
* Although Isis has been used by the USGS, no warranty, expressed or
* implied, is made by the USGS as to the accuracy and functioning of such
* software and related material nor shall the fact of distribution
* constitute any such warranty, and no responsibility is assumed by the
* USGS in connection therewith.
*
* For additional information, launch
* $ISISROOT/doc//documents/Disclaimers/Disclaimers.html
* in a browser or see the Privacy & Disclaimers page on the Isis website,
* http://isis.astrogeology.usgs.gov, and the USGS privacy and disclaimers on
* http://www.usgs.gov/privacy.html.
*
* $Id: SpkSegment.h 6314 2015-08-12 22:30:27Z jwbacker@GS.DOI.NET $
*/
#include <cmath>
#include <string>
#include <vector>
#include <iostream>
#include <sstream>
#include "SpiceSegment.h"
#include "IString.h"
#include "IException.h"
namespace Isis {
class Cube;
class Camera;
class Table;
class PvlObject;
/**
* @brief Maintain a SPK SPICE kernel segment for conversions and export
*
* This class is designed to read SPICE data from ISIS cube blobs and convert
* them to proper formats for export to NAIF formatted SPK SPICE kernel files.
* This particular implementation supports NAIF SPK kernel types 9 and 13.
*
* @author 2011-02-12 Kris Becker
* @internal
* @history 2012-07-06 Debbie A. Cook, Updated Spice members to be more compliant with Isis
* coding standards. References #972.
* @history 2013-12-19 Kris Becker Add SPK kernel type parameter to
* constructors; removed adjustTimes() method; modified
* variable names to conform to coding rules.
* References #1739.
* @history 2014-03-26 Kris Becker Added overlap() method to compare time
* ranges of another SPK segment. References #1739.
* @history 2015-07-21 Kristin Berry - Added NaifStatus::CheckErrors() to see if any NAIF errors
* were signaled. References #2248.
*/
class SpkSegment : public SpiceSegment {
public:
typedef SpiceSegment::SVector SVector;
typedef SpiceSegment::SMatrix SMatrix;
SpkSegment();
SpkSegment(const QString &fname, const int spkType);
SpkSegment(Cube &cube, const int spkType);
virtual ~SpkSegment() { }
void import(Cube &cube);
/** Returns the number of elements in the vectors */
int size() const { return (size(m_states)); }
/** Return kernel type */
int ktype() const { return (m_spkType) ; }
/** Returns SPK segment reference frame */
int BodyCode() const { return (m_body); }
/** NAIF SPICE instrument code */
int CenterCode() const { return (m_center); }
/** Returns CK segment reference frame */
QString ReferenceFrame() const { return (m_refFrame); }
/** Get times of each entry */
SVector Epochs() const { return (m_epochs); }
/** Returns instance of quaternions */
const SMatrix &States() const { return (m_states); }
int Degree() const { return (m_degree); }
bool HasVelocityVectors() const { return (m_hasVV); }
/** Returns a comment summarizing the segment */
QString getComment() const;
bool overlaps(const SpkSegment &other) const;
private:
enum { MinimumStates = 3, MaximumDegree = 7}; // Sensible? NAIF extremes
int m_spkType; // Type 9 or 13 kernel type
int m_body; // NAIF body code of the SPICE segment
QString m_bodyFrame; // NAIF body frame
int m_center; // NAIF center code of the SPICE segment
QString m_centerFrame; // NAIF center frame
QString m_refFrame; // NAIF reference frame
SMatrix m_states; // Position states
SVector m_epochs; // ET times of records
bool m_hasVV; // Has velocity vectors?
int m_degree; // Degree of polynomial to fit in NAIF kernel
// Internal processing methods
void init(const int spkType = 13);
template <class TNTSTORE> int size(const TNTSTORE &t) const { return (t.dim1()); }
SMatrix load(Table &cache);
void getStates(Camera &camera, const SMatrix &spice, SMatrix &states,
SVector &epochs, bool &hasVV) const;
SVector makeState(SpicePosition *position, const double &time0,
const SVector &stateT, const double &timeT) const;
void validateType(const int spktype) const;
};
}; // namespace Isis
#endif
| 41.518797 | 98 | 0.587287 | [
"vector"
] |
a9938801069a0a8ea4a56866be43a9cb1a8f243d | 3,273 | h | C | BRE/ModelManager/Model.h | nicolasbertoa/D3D12Base | cdf36d9a6ef8ab3860a03cb250032a0690f89851 | [
"BSD-3-Clause"
] | 9 | 2016-07-14T05:43:45.000Z | 2016-10-31T15:21:53.000Z | BRE/ModelManager/Model.h | yang-shuohao/BRE12 | cdf36d9a6ef8ab3860a03cb250032a0690f89851 | [
"BSD-3-Clause"
] | null | null | null | BRE/ModelManager/Model.h | yang-shuohao/BRE12 | cdf36d9a6ef8ab3860a03cb250032a0690f89851 | [
"BSD-3-Clause"
] | null | null | null | #pragma once
#include <vector>
#include <GeometryGenerator/GeometryGenerator.h>
#include <ModelManager/Mesh.h>
namespace BRE {
///
/// @brief Represents a model that can be loaded from a file
///
class Model {
public:
~Model() = default;
Model(const Model&) = delete;
const Model& operator=(const Model&) = delete;
Model(Model&&) = delete;
Model& operator=(Model&&) = delete;
///
/// @brief Model constructor
/// @param modelFilename Model filename. Must not be nullptr.
/// @param commandList Command list used to upload buffers content to GPU.
/// It must be executed after this function call to upload buffers content to GPU.
/// It must be in recording state before calling this method.
/// @param uploadVertexBuffer Upload buffer to upload the vertex buffer content.
/// It has to be kept alive after the function call because
/// the command list has not been executed yet that performs the actual copy.
/// The caller can Release the uploadVertexBuffer after it knows the copy has been executed.
/// @param uploadIndexBuffer Upload buffer to upload the index buffer content.
/// It has to be kept alive after the function call because
/// the command list has not been executed yet that performs the actual copy.
/// The caller can Release the uploadIndexBuffer after it knows the copy has been executed.
///
explicit Model(const char* modelFilename,
ID3D12GraphicsCommandList& commandList,
ID3D12Resource* &ploadVertexBuffer,
ID3D12Resource* &uploadIndexBuffer);
///
/// @brief Model constructor
/// @param meshData Mesh data.
/// @param commandList Command list used to upload buffers content to GPU.
/// It must be executed after this function call to upload buffers content to GPU.
/// It must be in recording state before calling this method.
/// @param uploadVertexBuffer Upload buffer to upload the vertex buffer content.
/// It has to be kept alive after the function call because
/// the command list has not been executed yet that performs the actual copy.
/// The caller can Release the uploadVertexBuffer after it knows the copy has been executed.
/// @param uploadIndexBuffer Upload buffer to upload the index buffer content.
/// It has to be kept alive after the function call because
/// the command list has not been executed yet that performs the actual copy.
/// The caller can Release the uploadIndexBuffer after it knows the copy has been executed.
///
explicit Model(const GeometryGenerator::MeshData& meshData,
ID3D12GraphicsCommandList& commandList,
ID3D12Resource* &uploadVertexBuffer,
ID3D12Resource* &uploadIndexBuffer);
///
/// @brief Checks if there are meshes or not
/// @return True if there are meshes. Otherwise, false.
///
__forceinline bool HasMeshes() const noexcept
{
return (mMeshes.size() > 0UL);
}
///
/// @brief Get meshes
/// @return List of meshes
///
__forceinline const std::vector<Mesh>& GetMeshes() const noexcept
{
return mMeshes;
}
private:
std::vector<Mesh> mMeshes;
};
} | 40.407407 | 96 | 0.68011 | [
"mesh",
"vector",
"model"
] |
650e627e7c19b8330e9f67711f2f13c4808f61b8 | 14,747 | h | C | C/include/c4Certificate.h | mhocouchbase/couchbase-lite-core | 8a527a066b703c8865b4e61cbd9e3d41d81ba5ef | [
"Apache-2.0"
] | null | null | null | C/include/c4Certificate.h | mhocouchbase/couchbase-lite-core | 8a527a066b703c8865b4e61cbd9e3d41d81ba5ef | [
"Apache-2.0"
] | null | null | null | C/include/c4Certificate.h | mhocouchbase/couchbase-lite-core | 8a527a066b703c8865b4e61cbd9e3d41d81ba5ef | [
"Apache-2.0"
] | null | null | null | //
// c4Certificate.h
//
// Copyright 2019-Present Couchbase, Inc.
//
// Use of this software is governed by the Business Source License included
// in the file licenses/BSL-Couchbase.txt. As of the Change Date specified
// in that file, in accordance with the Business Source License, use of this
// software will be governed by the Apache License, Version 2.0, included in
// the file licenses/APL2.txt.
//
#pragma once
#include "c4CertificateTypes.h"
#ifdef COUCHBASE_ENTERPRISE
C4_ASSUME_NONNULL_BEGIN
C4API_BEGIN_DECLS
/** \defgroup certificates Certificates
@{ */
/** \name Certificate and CSR Functions
@{ */
/** Instantiates a C4Cert from X.509 certificate data in DER or PEM form.
\note PEM data might consist of a series of certificates. If so, the returned C4Cert
will represent only the first, and you can iterate over the next by calling
\ref c4cert_nextInChain.
\note You are responsible for releasing the returned reference. */
C4Cert* c4cert_fromData(C4Slice certData,
C4Error* C4NULLABLE outError) C4API;
/** Returns the encoded X.509 data in DER (binary) or PEM (ASCII) form.
\warning DER format can only encode a _single_ certificate, so if this C4Cert includes
multiple certificates, use PEM format to preserve them.
\note You are responsible for releasing the returned data. */
C4SliceResult c4cert_copyData(C4Cert*,
bool pemEncoded) C4API;
/** Returns a human-readable, multi-line string describing the certificate in detail.
\note You are responsible for releasing the returned data. */
C4StringResult c4cert_summary(C4Cert*) C4API;
/** Returns the cert's Subject Name, which identifies the cert's owner.
This is an X.509 structured string consisting of "KEY=VALUE" pairs separated by commas,
where the keys are attribute names. (Commas in values are backslash-escaped.)
\note Rather than parsing this yourself, use \ref c4cert_subjectNameComponent.
\note You are responsible for releasing the returned data. */
C4StringResult c4cert_subjectName(C4Cert*) C4API;
/** Returns one component of a cert's subject name, given the attribute ID.
\note If there are multiple names with this ID, only the first is returned.
\note You are responsible for releasing the returned string. */
C4StringResult c4cert_subjectNameComponent(C4Cert*, C4CertNameAttributeID) C4API;
/** Returns one component of a cert's subject name, given a zero-based index into the list.
If the index is out of range, it returns a null slice.
@param cert The certificate to examine.
@param index Zero-based index into the subject name list.
@param outInfo The component's name and value will be written here.
@return True if the index was valid, false if out of range.
\note You are responsible for releasing `outInfo->value`. */
bool c4cert_subjectNameAtIndex(C4Cert* cert,
unsigned index,
C4CertNameInfo *outInfo) C4API;
/** Returns the time range during which a (signed) certificate is valid.
@param cert The signed certificate.
@param outCreated On return, the date/time the cert became valid (was signed).
@param outExpires On return, the date/time at which the certificate expires. */
void c4cert_getValidTimespan(C4Cert* cert,
C4Timestamp* C4NULLABLE outCreated,
C4Timestamp* C4NULLABLE outExpires);
/** Returns the usage flags of a cert. */
C4CertUsage c4cert_usages(C4Cert*) C4API;
/** Returns true if the issuer is the same as the subject.
\note This will be true of root CA certs, as well as self-signed peer certs. */
bool c4cert_isSelfSigned(C4Cert*) C4API;
/** Returns a certificate's public key.
\note You are responsible for releasing the returned key reference. */
C4KeyPair* c4cert_getPublicKey(C4Cert*) C4API;
/** Loads a certificate's matching private key from the OS's persistent store, if it exists,
and returns the key-pair with both private and public key.
\note You are responsible for releasing the returned key reference. */
C4KeyPair* c4cert_loadPersistentPrivateKey(C4Cert*,
C4Error* C4NULLABLE outError) C4API;
/** @} */
/** \name Certificate Requests and Signing
@{ */
/** Creates a Certificate Signing Request, i.e. an unsigned certificate.
\note You are responsible for releasing the returned reference.
@param nameComponents Pointer to an array of one or more \ref C4CertNameComponent structs.
@param nameCount Number of items in the \p nameComponents array.
@param certUsages Flags giving intended usage. (The certificate will be rejected by peers
if you try to use it for something not specified in its certUsages!)
@param subjectKey The owner's private key that this certificate will attest to.
@param outError On failure, the error info will be stored here.
@return The new certificate request, or NULL on failure. */
C4Cert* c4cert_createRequest(const C4CertNameComponent *nameComponents,
size_t nameCount,
C4CertUsage certUsages,
C4KeyPair *subjectKey,
C4Error* C4NULLABLE outError) C4API;
/** Instantiates a C4Cert from an X.509 certificate signing request (CSR) in DER or PEM form.
\note You are responsible for releasing the returned reference. */
C4Cert* c4cert_requestFromData(C4Slice certRequestData,
C4Error* C4NULLABLE outError) C4API;
/** Returns true if this is a signed certificate, false if it's a signing request (CSR). */
bool c4cert_isSigned(C4Cert*) C4API;
/** Completion routine called when an async \ref c4cert_sendSigningRequest finishes.
@param context The same `context` value passed to \ref c4cert_sendSigningRequest.
@param signedCert The signed certificate, if the operation was successful, else NULL.
@param error The error, if the operation failed. */
typedef void (*C4CertSigningCallback)(void *context,
C4Cert *signedCert,
C4Error error);
/** Sends an unsigned certificate (a CSR) to a Certificate Authority (CA) over HTTP
to be signed, and _asynchronously_ returns the signed certificate.
\note There is no standard protocol for sending CSRs; this function uses the protocol
defined by Cloudflare's CFSSL.
@param certRequest The certificate request to be signed.
@param address The URL of the CA server.
@param optionsDictFleece Network options, just like the corresponding field in
\ref C4ReplicatorParameters. Most importantly, this is used to specify
authentication, without which the CA server won't sign anything.
@param callback A function that will be called, on a background thread, after the request
completes.
@param context An arbitrary value that will be passed to the callback function.
@param outError If the parameters are invalid, error info will be written here.
@return True if the parameters are valid and the request will be sent; else false. */
bool c4cert_sendSigningRequest(C4Cert *certRequest,
C4Address address,
C4Slice optionsDictFleece,
C4CertSigningCallback callback,
void* C4NULLABLE context,
C4Error* C4NULLABLE outError) C4API;
/** Signs an unsigned certificate (a CSR) with a private key, and returns the new signed
certificate. This is the primary function of a Certificate Authority; but it can also
be used to create self-signed certificates.
\note You are responsible for releasing the returned reference.
@param certRequest The unsigned certificate to be signed.
@param params Capabilities to store in the cert; if NULL, uses defaults.
@param issuerPrivateKey The Certificate Authority's private key. (If self-signing a
cert, this should be the same as the `subjectKey` it was created with.)
@param issuerCert The Certificate Authority's certificate (which must match
\p issuerPrivateKey), or NULL if self-signing.
@param outError On failure, the error info will be stored here.
@return The signed certificate, or NULL on failure. */
C4Cert* c4cert_signRequest(C4Cert *certRequest,
const C4CertIssuerParameters* C4NULLABLE params,
C4KeyPair *issuerPrivateKey,
C4Cert* C4NULLABLE issuerCert,
C4Error* C4NULLABLE outError) C4API;
/** @} */
/** \name Certificate Chains
@{ */
/** Returns the next certificate in the chain after this one, if any.
\note You are responsible for releasing the returned reference. */
C4Cert* C4NULLABLE c4cert_nextInChain(C4Cert*) C4API;
/** Returns the encoded data of this cert and the following ones in the chain, in PEM form.
\note You are responsible for releasing the returned data.*/
C4SliceResult c4cert_copyChainData(C4Cert*) C4API;
/** @} */
/** \name Certificate Persistence
@{ */
/** Saves a certificate to a persistent storage for easy lookup by name, or deletes a saved cert.
\note The certificate needs to be signed to save into the storage.
@param cert The certificate to store, or NULL to delete any saved cert with that name.
@param entireChain True if the entire cert chain should be saved.
@param name The name to save as.
@param outError On failure, the error info will be stored here.
@return True on success, false on failure. */
bool c4cert_save(C4Cert* C4NULLABLE cert,
bool entireChain,
C4String name,
C4Error* C4NULLABLE outError);
/** Loads a certificate from a persistent storage given the name it was saved under.
\note You are responsible for releasing the returned key reference.
@param name The name the certificate was saved with.
@param outError On failure, the error info will be stored here.
@return The certificate, or NULL if missing or if it failed to parse. */
C4Cert* c4cert_load(C4String name,
C4Error* C4NULLABLE outError);
/** @} */
/** \name Key-Pairs
@{ */
/** Creates a new key-pair.
\note You are responsible for releasing the returned reference.
\warning Key-pairs should usually be persistent. This is more secure because the private
key data is extremely difficult to access. A non-persistent key-pair's private
key data lives in the process's heap, and if you store it yourself it's difficult
to do so securely.
@param algorithm The type of key to create, e.g. RSA.
@param sizeInBits The size (length) of the key in bits. Larger sizes are more secure.
Available key sizes depend on the key type.
@param persistent True if the key should be managed by the OS's persistent store.
@param outError On failure, the error info will be stored here.
@return The new key, or NULL on failure. */
C4KeyPair* c4keypair_generate(C4KeyPairAlgorithm algorithm,
unsigned sizeInBits,
bool persistent,
C4Error* C4NULLABLE outError) C4API;
/** Loads a public key from its data.
The resulting C4KeyPair will not have a private key.
\note You are responsible for releasing the returned reference. */
C4KeyPair* c4keypair_fromPublicKeyData(C4Slice publicKeyData,
C4Error* C4NULLABLE outError) C4API;
/** Loads a private key from its data.
The resulting C4KeyPair will have both a public and private key.
\note You are responsible for releasing the returned reference. */
C4KeyPair* c4keypair_fromPrivateKeyData(C4Slice privateKeyData,
C4Slice passwordOrNull,
C4Error* C4NULLABLE outError) C4API;
/** Returns true if the C4KeyPair has a private as well as a public key. */
bool c4keypair_hasPrivateKey(C4KeyPair*) C4API;
/** Returns a hex digest of the public key.
\note You are responsible for releasing the returned data. */
C4SliceResult c4keypair_publicKeyDigest(C4KeyPair*) C4API;
/** Returns the public key data.
\note You are responsible for releasing the returned data. */
C4SliceResult c4keypair_publicKeyData(C4KeyPair*) C4API;
/** Returns the private key data, if the private key is known and its data is accessible.
\note Persistent private keys generally don't have accessible data.
\note You are responsible for releasing the returned data. */
C4SliceResult c4keypair_privateKeyData(C4KeyPair*) C4API;
/** Returns true if the C4KeyPair is stored int the OS's persistent store. */
bool c4keypair_isPersistent(C4KeyPair*) C4API;
/** Attempts to find & load the persistent key-pair matching this public key.
\note If there is no matching persistent key, returns NULL but sets no error.
\note You are responsible for releasing the returned reference. */
C4KeyPair* c4keypair_persistentWithPublicKey(C4KeyPair*,
C4Error* C4NULLABLE outError) C4API;
/** Removes a private key from persistent storage. */
bool c4keypair_removePersistent(C4KeyPair*,
C4Error* C4NULLABLE outError) C4API;
/** @} */
/** \name Externally-Implemented Key-Pairs
@{ */
/** Creates a C4KeyPair object that wraps an external key-pair managed by client code.
Signatures and decryption will be performed by calling client-defined callbacks.
@param algorithm The type of key (currently only RSA.)
@param keySizeInBits The key size, measured in bits, e.g. 2048.
@param externalKey An abitrary token that will be passed to the callbacks; most likely a
pointer to your own key structure.
@param callbacks A struct containing callback functions to do the work.
@param outError On failure, the error info will be stored here.
@return The key object, or NULL on failure. */
C4KeyPair* c4keypair_fromExternal(C4KeyPairAlgorithm algorithm,
size_t keySizeInBits,
void *externalKey,
struct C4ExternalKeyCallbacks callbacks,
C4Error* C4NULLABLE outError);
/** @} */
/** @} */
C4API_END_DECLS
C4_ASSUME_NONNULL_END
#endif // COUCHBASE_ENTERPRISE
| 47.570968 | 97 | 0.687937 | [
"object"
] |
6518f2639eda17ba334b28c4053e73ef30966b3c | 1,326 | c | C | ext/phalconplus/curl/exception.zep.c | bullsoft/phalconplus | a57a6832d1cba1f7d3aff5ea36a1032aff541570 | [
"BSD-3-Clause"
] | 51 | 2015-05-21T06:09:29.000Z | 2022-03-04T14:29:14.000Z | ext/phalconplus/curl/exception.zep.c | bullsoft/phalconplus | a57a6832d1cba1f7d3aff5ea36a1032aff541570 | [
"BSD-3-Clause"
] | 2 | 2019-04-17T01:43:41.000Z | 2020-05-13T00:45:42.000Z | ext/phalconplus/curl/exception.zep.c | bullsoft/phalconplus | a57a6832d1cba1f7d3aff5ea36a1032aff541570 | [
"BSD-3-Clause"
] | 26 | 2015-05-19T01:43:24.000Z | 2022-03-04T09:54:58.000Z |
#ifdef HAVE_CONFIG_H
#include "../../ext_config.h"
#endif
#include <php.h>
#include "../../php_ext.h"
#include "../../ext.h"
#include <Zend/zend_operators.h>
#include <Zend/zend_exceptions.h>
#include <Zend/zend_interfaces.h>
#include "kernel/main.h"
#include "kernel/array.h"
#include "kernel/object.h"
ZEPHIR_INIT_CLASS(PhalconPlus_Curl_Exception) {
ZEPHIR_REGISTER_CLASS_EX(PhalconPlus\\Curl, Exception, phalconplus, curl_exception, phalconplus_base_exception_ce, phalconplus_curl_exception_method_entry, 0);
return SUCCESS;
}
PHP_METHOD(PhalconPlus_Curl_Exception, getRequest) {
zval _0, _1, _2$$3, _3$$3, _4$$3;
zval *this_ptr = getThis();
ZVAL_UNDEF(&_0);
ZVAL_UNDEF(&_1);
ZVAL_UNDEF(&_2$$3);
ZVAL_UNDEF(&_3$$3);
ZVAL_UNDEF(&_4$$3);
zephir_read_property(&_0, this_ptr, ZEND_STRL("info"), PH_NOISY_CC | PH_READONLY);
zephir_array_fetch_long(&_1, &_0, 1, PH_READONLY, "phalconplus/Curl/Exception.zep", 9);
if (zephir_array_isset_long(&_1, 0)) {
zephir_read_property(&_2$$3, this_ptr, ZEND_STRL("info"), PH_NOISY_CC | PH_READONLY);
zephir_array_fetch_long(&_3$$3, &_2$$3, 1, PH_NOISY | PH_READONLY, "phalconplus/Curl/Exception.zep", 10);
zephir_array_fetch_long(&_4$$3, &_3$$3, 0, PH_NOISY | PH_READONLY, "phalconplus/Curl/Exception.zep", 10);
RETURN_CTORW(&_4$$3);
}
RETURN_NULL();
}
| 26 | 160 | 0.728507 | [
"object"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.